﻿/* Menu Desplegable Version 1.1 */

var MenuDesplegable = Class.create()
    
MenuDesplegable.prototype = { 
    initialize : function() {
        $$("a.menuDesplegable").each(function(item){
        	Event.observe(item, 'click', this.desplegar.bind(this))
        }.bind(this));
        
        $$("a.finMenu").each(function(item){
        	Event.observe(item, 'click', function(evt) {this.marcar(Event.element(evt))}.bind(this))
        }.bind(this));
    },
    
    desplegar : function(evt){
        var elemento = Event.findElement(evt, 'LI');
        var itemMenu = Event.element(evt);
        
        $(elemento).siblings().each(function(item){
            this.plegar(item);
        }.bind(this));
                
        itemMenu.ancestors();
        
        elementoMostrar = itemMenu.next();      
        if(elementoMostrar != null){
			if(elementoMostrar.visible()) elementoMostrar.hide();
			else elementoMostrar.show();
		}
        
        this.marcar(itemMenu);
    },
    
    plegar : function(item){
		item.ancestors();
        item.immediateDescendants().each(function(item) {
            this.plegar(item);
            if (item.hasClassName('optMenuDesplegable')){
            	item.hide();
            }
        }.bind(this));                
    },
    
    recojerRaiz : function(raiz){
		raiz.ancestors();
		
    	while (raiz.up('ul.optMenuDesplegable')){
    		raiz = raiz.up('ul.optMenuDesplegable');
    	}
    	
    	return raiz;
    },
    
    desmarcar : function(item){
    	item.immediateDescendants().each(function(item){
    		window.desmarcar(item);
   			if(item.getAttribute("classSel")){
   				item.removeClassName(item.getAttribute("classSel"));
   			}
    	});
    	
    },

    marcar : function(item){
    	desmarcar(recojerRaiz(item));
    	marcarAux(item);
    },
    
    marcarAux : function(item){
		if($(item).getAttribute("classSel")){
    		$(item).addClassName($(item).getAttribute("classSel"))
    	}
    	    	
    	padre = $(item).up("ul.optMenuDesplegable");
    	if(padre){
    		padre.siblings().each(function(itemInt){
    			if(item.hasClassName("menuDesplegable") || item.hasClassName("finMenu")){
    				marcarAux(itemInt);
    			}
    		})	
    	}
    }
    
};
		
Event.observe(window,"load", function(){ 
	Object.extend(window, new MenuDesplegable());
});
