// (C) Copyright 2020 Hewlett-Packard Enterprise Company, L.P.

define(['jquery'], function() {
    (function($) {
        // jQuery plugin definition
        /**
         * Scrolls to ensure that some elements are visible.
         * Looks for first parent that is scrollable and isn't showing everything.
         * Handles thin windows to make sure we never scroll elements off the top.
         * Used by components with drop menus to make them visible.
         * Usage:
         *    $('#my-element').hpScrollParent('#my-menu');
         */ 
        $.fn.hpScrollParent = function(additional) {
                
            function scrollParent(elem) {
                // Walk up the parents to see if the menu is being clipped and we
                // can scroll.
                var parentTop, parentBottom, top, bottom;
                var parent = elem.parent();
                while (parent && parent.length > 0) {
                    if ((parent.outerHeight() + 10) < parent[0].scrollHeight) {
                        // scrolling element, check position
                        parentTop = parent.offset().top;
                        parentBottom = parentTop + parent.outerHeight();
                        top = elem.offset().top;
                        bottom = top + $(elem).outerHeight();
                        if (additional) {
                            bottom += $(additional).outerHeight();
                        }
                        if (bottom > parentBottom) {
                            // need to scroll, don't clip top, give some padding
                            var delta = Math.min(((bottom + 10) - parentBottom), ((top - 10) - parentTop));
                            var targetScrollTop = parent.scrollTop() + delta;
                            parent.animate({scrollTop: targetScrollTop}, 100);
                        }
                        break;
                    }
                    parent = parent.parent();
                }
            }
            
            // pluginify
            var ret;
            this.each(function() {
                var $elem = $(this);
                
                scrollParent($elem);
                
                ret = ret ? ret.add($elem) : $elem;
            });
            return ret;
        };
    }(jQuery));
});
