var menu = new Class({
	initialize: function() {		
		if (menu.hasCreated) {
			return;
		}
		this.timeShow = 400;
		this.timeHide = 150;
		this.overClass = 'current';
		menu.hasCreated = true;		
		this.initMenu();
	},
	
	initMenu: function() {		
		var that = this;
		var menus = $$('a.menuBtn');
		if(!menus.length) return;
		menus.each(function(btn, i){											
			btn.addEvent('mouseover', function(evt){
				new Event(evt).stop();
				this.isMouseOver = true;
				
				if (!this.subMenu) {
					this.subMenu = this.getNext().clone().inject($$("body")[0]);								
					this.subMenu.orgH = this.subMenu.getCoordinates().height;
					this.subMenu.fx = new Fx.Styles(this.subMenu, {
						duration: that.timeShow
					}).set({'height': 0});
					this.subMenu.fx2 = new Fx.Styles(this.subMenu, {
						duration: that.timeHide
					});
					this.subMenu.subUL = this.subMenu.getElements("ul");
				}			
				
				this.subMenu.setStyles({
					left: this.getPosition().x + 8
				});
				
				clearInterval(this.menuInterval);				
				this.subMenu.fx.start({'height': this.subMenu.orgH});
				
				this.subMenu.getElements("a").addEvents({
					"mouseover": function(evt){
						new Event(evt).stop();
					
						btn.isMouseOver = true;
						btn.getParent().addClass(that.overClass);	
						
						try { 
							clearInterval(btn.menuInterval);
						} catch(e) {}						
					},
					
					"mouseout": function(evt){
						new Event(evt).stop();
						
						try {
							clearInterval(btn.menuInterval);
							btn.menuInterval = setInterval(function() {
								btn.isMouseOver = false;
								that.hideMenu(btn);
							}, 100);
						} catch(e) {}
					}
				});				
			});
			
			btn.addEvent("mouseout", function(evt){
				new Event(evt).stop();
								
				clearInterval(this.menuInterval);
				this.menuInterval = setInterval(function() {				
					btn.isMouseOver = false;
					that.hideMenu(btn);
				}, 100);					
			});		
		});
		
		var nav = $('nav');
		if(!nav) return;
		var currentLi = nav.getElements('li');		
		if(currentLi){
			currentLi.each(function(li, index){
				if(li.hasClass('current')){
					that.currentLi = li;					
				}
			});
		}
	},
	
	hideMenu: function(menu) {	
		var that = this;	
		if (!menu.isMouseOver && menu.subMenu) {			
			menu.getParent().removeClass(this.overClass);
			//clearInterval(menu.menuInterval);							
			var subOpenedMenu = menu.subMenu;
			subOpenedMenu.fx.stop();
			subOpenedMenu.fx2.start({'height': 0});
				
			subOpenedMenu.fx2.addEvent('complete', function() {
				menu.subMenu.destroy();
				menu.subMenu = null;
			});
			if(that.currentLi){
				that.currentLi.addClass('current');
			}
		}
	}
});	

window.addEvent("domready", function(){
	new menu();
});