﻿var Top10Tooltip = new Class({
    Implements: Options,
    options: {
        delay: 100
    },
    
    initialize: function(els) {
        els.each(function(el) {
            el.addEvents({
                'mouseenter': function() { this.show(el); }.bind(this),
                'mouseleave': function() { this.hide(); }.bind(this)
            });
        }.bind(this));
    },
    
    show: function(el) {
        if (this.element == el)
            this.keepAlive();
        else {
            this.doHide();
            var text = el.getProperty('rel');
            if (text) {
                var position = el.getPosition();
                var size = el.getSize();
                this.tip = new Element('div', { 'class': 'tooltip', 'styles': { 'left': (position.x + (size.x / 4 * 3)) + 'px', 'top': (position.y + (size.y / 2) - 16) + 'px' }, 'events': {
                    'mouseenter': function() { this.keepAlive(); }.bind(this),
                    'mouseleave': function() { this.hide(); }.bind(this),
                    'click': function() { el.fireEvent('click'); }
                }}).set('text', text).inject($(document.body));
            }
        }
    },
    
    keepAlive: function() {
        $clear(this.timer);
    },
    
    hide: function(el) {
        if (this.tip) {
            this.timer = setTimeout(function() { this.doHide(); }.bind(this), this.options.delay);
        }
    },
    
    doHide: function() {
        $clear(this.timer);
        if (this.tip) this.tip.destroy();
    }
});
