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

define(['jquery'], function() {
    (function($) {
        // jQuery plugin definition
        
        $.fn.hpEllipsis = function(options) {

            function hpEllipsis(elem) {
              
                var container;
                var tip;
                
                function onMove(ev) {
                    if (tip && ((ev.pageX < tip.offset().left ||
                        (ev.pageX > (tip.offset().left + tip.outerWidth()))) ||
                        (ev.pageY < tip.offset().top ||
                        (ev.pageY > (tip.offset().top + tip.outerHeight()))))) {
                        $('body').unbind('mousemove', onMove);
                        $('body').unbind('click', onMove);
                        tip.remove();
                        tip = null;
                    }
                }
                
                function onOver(ev) {
                    var offset;
                    if (! tip &&
                        container[0].offsetWidth < container[0].scrollWidth) {
                        tip = $('<div class="hp-text-tip">' +
                          container.html() + '</div>');
                        if (container.parents('.hp-global').length > 0) {
                            tip.addClass('hp-global');
                        }
                        
                        offset = container.offset();
                        tip.css({top: offset.top, left: offset.left, 
                          'word-break': 'break-all', 
                          'font-size': container.css('font-size'),
                          'line-height': container.css('line-height')});
                        
                        $('body').append(tip);
                        $('body').bind('mousemove', onMove);
                        $('body').bind('click', onMove);
                    }
                }

                function initialize() {
                    container = $(elem);
                    if (! container.hasClass('hp-ellipsised')) {
                        container.addClass('hp-ellipsised');
                        container.mouseenter(onOver);
                    }
                }
                
                initialize();
            }
            
            // pluginify
            var ret;
            var instance = null;
            this.each(function() {
                var $elem = $(this);
                instance = new hpEllipsis($elem[0]);
                ret = ret ? ret.add($elem) : $elem;
            });
            return ret;
        };
    }(jQuery));
});
