/**
 * Menu
 */
var Menu = Class.create({
	/**
	 * Init Menu
	 */
	initialize: function(mainmenu, menus) {	  
		this.menus = menus;
		this.activeMenu = null;

		this.bLock = false;
		
		//init menus
		this.menus.each(function(item, index) {
			var link = item.previous();
      var mainItem;
			var mainLink;
			
			// hide all menus but the active one
			if (item.hasClassName('open')) {
	      mainItem = item.up('.main');
	      mainLink = mainItem.down('a');
	      this.activeMainMenu = mainLink.next();
	  
				this.activeMenu = item;				
			}
			else {
				item.hide();
			}
			// attach click listener to the "parent" link
			if (link.id != "lock") {
			  // if id is lock then we don't want to expand
			  link.observe('click', this.toggle.bind(this));
			}
		}.bind(this));		
		// show
		mainmenu.style.display = "block";
	},
	
	toggle: function(evt) {
		var link = evt.findElement('a');
		var menu = link.next();		
	  var mainItem = link.up('.main');
	  var mainLink = mainItem.down('a');
	  mainMenu = mainLink.next();
		
	  // abort if already in transition
	  if (this.bLock) {
	    return false;
	  }
	  
		// try closing the current active one
		if (this.activeMainMenu) {	
		  if (this.activeMainMenu == mainMenu) {
		    if (this.activeMenu == menu) {
		      this.close(this.activeMenu);
		      this.activeMenu = null;		      
		      this.activeMainMenu = null;
		    }
		    else {
		      // only close if the menu is not a main menu!
		      if (this.activeMenu != this.activeMainMenu) {
		        this.close(this.activeMenu);
		      }

		      if (menu == this.activeMainMenu) {		      
		        // close if an open main menu
            if (menu.className == "submenu open") {
              this.close(this.activeMainMenu);
		        }
		        else {
		          this.activeMenu = menu;
		          this.open(this.activeMenu);
		        }
		      }
		      else {
		        this.activeMenu = menu;
		        this.open(this.activeMenu);
		      }
		    }
		  }
		  else {
		    this.close(this.activeMainMenu);
		    
				this.close(this.activeMenu);
				this.activeMainMenu = mainMenu;
				
				this.activeMenu = menu;
				this.open(this.activeMenu);
		  }
	  }
		else {
			this.activeMainMenu = mainMenu;
				
			this.activeMenu = menu;			
			this.open(this.activeMenu);
		}	  
		evt.stop();
	},
	
	open: function(item) {
	  this.bLock = true;
	  
		item.addClassName('open');
    new Effect.BlindDown(item, { duration: 0.3, afterFinish: this.effectComplete.bind(this) });
	},
	
	close: function(item) {
	  this.bLock = true;
	  
		item.removeClassName('open');
    new Effect.BlindUp(item, { duration: 0.3, afterFinish: this.effectComplete.bind(this) });
	},
	
	effectComplete: function(evt) {
	  this.bLock = false;
	}	
	
});
