var TR_MENU = {
    'init' : function() {
        var dims;
        if ( !$('menu') ) return;
        $('menu').style.overflow = 'visible';
        // Busquem l'ul que engloba tot el menu
        var ul = TR_MENU.getElementsByTagNameLevel1( $('menu'), 'ul' )[0];
        // Ara busquem els lis de primer nivell
        var lis = TR_MENU.getElementsByTagNameLevel1( ul, 'li' );
        for ( var x = 0; x < lis.length; x++ ) {
            lis[x].menu = TR_MENU.getElementsByTagNameLevel1( lis[x], 'ul' )[0];
            if (lis[x].menu) {
                lis[x].menu.parent = lis[x];
                Element.hide( lis[x].menu );
                lis[x].menu.plegar = function() {
                    this.parent.className = '';
                    this.timer = null;
                    if ( this.working ) return;
                    new Effect.BlindUp(this, {duration:0.5,afterFinish : function(obj) {obj.element.working=false;obj.element.desplegat = false;} });
                    this.working = true;
                }
                lis[x].menu.desplegar = function() {
                    this.parent.className = 'hover';
                    if ( this.working ) return;
                    new Effect.BlindDown(this, {duration:0.5,afterFinish : function(obj) {obj.element.working=false;obj.element.desplegat = true;} });
                    this.working = true;
                }
                lis[x].menu.timer = null;
                lis[x].menu.working = false;
                lis[x].onmouseover = function() {                
                    //$('prova').innerHTML += '<br />over!';
                    if ( this.menu.timer != null ) {
                        clearTimeout( this.menu.timer );
                        this.menu.timer = null;
                      //  $('prova').innerHTML += '<br />plegada cancelada!';
                    } else {
                        if ( !this.menu.desplegat ) {
                            this.menu.desplegar();
                            //$('prova').innerHTML += '<br />Go!';
                        }
                    }
                }
                lis[x].onmouseout = function() {
                    //$('prova').innerHTML += '<br />out!';
                    if ( this.menu.desplegat )
                        this.menu.timer = setTimeout( this.menu.plegar.bind(this.menu) , 100 );
                }
            }
        }
    },
    
    'getElementsByTagNameLevel1' : function(node,tag) {
        var els = new Array();
        var i = 0;
        for ( var x=0; node.childNodes[x]; x++ ) {
            if ( node.childNodes[x].nodeName.toLowerCase() == tag )
                els[i++] = node.childNodes[x];
        }
        return els;
    }

};

Event.observe( window, 'load', TR_MENU.init );
