// vim: et:ts=4:sw=4:sts=4:ft=javascript

'use strict';

/*@
Ox.Tooltip <f:Ox.Element> Tooltip Object
    () ->              <f> Tooltip Object
    (options) ->       <f> Tooltip Object
    (options, self) -> <f> Tooltip Object
    options <o> Options object
    self    <o> shared private variable
@*/

Ox.Tooltip = function(options, self) {

    self = self || {};
    var that = Ox.Element({}, self)
            .defaults({
                animate: true, // fixme: shouldn't booleans be false by default?
                title: ''
            })
            .options(options || {})
            .addClass('OxTooltip')
            .html(self.options.title);

    self.options.animate && that.css({
        opacity: 0
    });

    self.setOption = function(key, value) {
        if (key == 'title') {
            that.html(value);
            value === '' && that.detach();
        }
    };

    that.hide = function() {
        if (self.options.title) {
            if (self.options.animate) {
                that.animate({
                    opacity: 0
                }, 250, function() {
                    that.detach();
                });
            } else {
                that.detach();
            }
        }
        return that;
    };

    // can pass event instead of x/y
    // fixme: use this in widgets
    that.show = function(x, y) {
        var left, top, width, height;
        if (self.options.title) {
            if (arguments.length == 1) {
                self.x = arguments[0].clientX;
                self.y = arguments[0].clientY;
            } else if (arguments.length == 2) {
                self.x = x;
                self.y = y
            }
            $('.OxTooltip').detach(); // fixme: don't use DOM
            that.appendTo(Ox.UI.$body);
            width = that.width();
            height = that.height();
            left = Ox.limit(
                self.x - width / 2, 0, window.innerWidth - width - 8
            );
            top = self.y > window.innerHeight - height - 16
                ? self.y - 16 - height
                : self.y + 16;
            that.css({
                left: left + 'px',
                top: top + 'px'
            });
            self.options.animate && that.animate({
                opacity: 1
            }, 250);
        }
        return that;
    };

    return that;

};