(function($){"use strict";

$.widget("shiftpress.tooltip", {
    options: {
        keepOnHover: false,
        cls: null,
        container: 'body',
        content: null
    },

    tooltiptpl: '<div class="sp-tooltip-wrapper">' +
        '<div class="sp-tooltip">' +
            '<div class="sp-tooltip-callout"></div>' +
            '<div class="sp-tooltip-content">' +
            '</div>' +
        '</div>' +
    '</div>',

    $target: null,
    $tooltip: null,
    hideTimer: null,
    stopHide: false,

    _create: function() {
        this.$target = this.element;

        var content = this.tooltiptpl.replace(/{{content}}/, this.options.content);

        this.$tooltip = $(content);

        $('.sp-tooltip-content', this.$tooltip).append(this.options.content);

        this.$tooltip
            .addClass(this.options.cls)
            .appendTo(this.options.container)
            .css({
                position: 'absolute',
                zIndex: 99999
            })
            .position({
                of: this.$target,
                my: "left top",
                at: "left bottom"
            })
        ;

        if (this.$tooltip.position().left < this.$target.position().left) {
            $('.sp-tooltip-callout', this.$tooltip).css({ left: (this.$target.position().left - this.$tooltip.position().left) + 10 });
        }

        this.$tooltip.hide();

        this.$target.hover($.proxy(function() {
            if (this.hideTimer) {
                clearTimeout(this.hideTimer);
            }

            this.$tooltip
                .show()
                .position({
                    of: this.$target,
                    my: "left top",
                    at: "left bottom"
                })
            ;
        }, this), $.proxy(function() {
            if (!this.stopHide) {
                this.hideTimer = setTimeout($.proxy(function() {
                    this.$tooltip.hide();
                    this.hideTimer = null;
                }, this), 10);
            }
        }, this));

        if (this.options.keepOnHover) {
            this.$tooltip.hover($.proxy(function() {
                this.stopHide = true;
                if (this.hideTimer) {
                    clearTimeout(this.hideTimer);
                }
            }, this), $.proxy(function() {
                this.stopHide = false;
                this.$target.mouseout();
            }, this));
        }
    },

    content: function() {
        return $('.sp-tooltip-content', this.$tooltip);
    }

});

})(jQuery);

