// ----------------------------------
//    Tooltips
// ----------------------------------

window.addEvent('domready', function() {
    new TipsFormHelp();
});

// ----------------------------------
//    Tips d'aide à un formulaire
// ----------------------------------
var TipsFormHelp = new Class({
    // Paramètres par défaut
    options: {
        items: '.help',
        className: 'tooltip',
        offsets: {'x': 16, 'y': 16},

        onShow: function(tip){
            tip.setStyle('visibility', 'visible');
        },
        onHide: function(tip){
            tip.setStyle('visibility', 'hidden');
        }
    },

    // Init de l'Objet
    initialize: function(options) {
        this.setOptions(options);

        this.timer = null;

        this.tooltip, this.wrapper;
        this.buildDOM();

        $$(this.options.items).each(this.build, this);
    },

    buildDOM: function() {
        this.tooltip = new Element('div', {
            'class': this.options.className,
            'styles': {
                'position': 'absolute',
                'visibility': 'hidden',
                'top': 0,
                'left': 0
            }
        }).inject(document.body);

        this.wrapper = new Element('div').inject(this.tooltip);
    },

    build: function(elm) {
        // On check si le parent est un lien et si il possède l'attribut 'rel'
        if(elm.getParent().getTag() != 'a' || !elm.getParent().getProperty('rel')) return false;

        elm.$tmp.text = elm.getParent().getProperty('rel');
        elm.addEvent('mouseenter', function(e) {
            this.start(elm);
            this.position(elm);
        }.bind(this));
        elm.addEvent('mouseleave', function(e) {
            this.end(elm);
        }.bind(this));
    },

    start: function(elm) {
        this.wrapper.empty();
        if(elm.$tmp.text) this.wrapper.setHTML(elm.$tmp.text);
        $clear(this.timer);
        this.timer = this.show.delay(100, this);
    },

    end: function(elm) {
        $clear(this.timer);
        this.timer = this.hide.delay(100, this);
    },

    show: function() {
        this.fireEvent('onShow', [this.tooltip]);
    },

    hide: function() {
        this.fireEvent('onHide', [this.tooltip]);
    },

    position: function(elm) {
        var pos = elm.getPosition();
        this.tooltip.setStyles({
            'left': pos.x + this.options.offsets.x,
            'top': pos.y + this.options.offsets.y
        });
    }
});
TipsFormHelp.implement(new Events, new Options);

