// JavaScript Document
var menu = new Class({
	Implements: [Options],
	options: {
		navWrapper: 'nav',
		mainNav: '#mainNav li',
		subNavs: '#hiddenSubNav ul',
		replaceMain: 'main',
		replaceSub: 'sub'
	},
	initialize: function(options){
		//Set the id's defined in the options
		this.setOptions(options);
		this.activeMainId = '';
		this.activeSubId = '';
		//Get the elements
		this.navWrapper = $(this.options.navWrapper);
		this.mainNav = $$(this.options.mainNav);
		this.subNavs = $$(this.options.subNavs);
		this.subNavId = this.options.subNavs.replace('#','');
		this.subNavId = this.subNavId.replace(' ul','');
		//Hide the menus when leaving the navigation
		this.navWrapper.addEvent('mouseleave', function() {
			this.hideMenus(true);
		}.bind(this));
		//When entering a main-navigation item, show the corresponding subMenu
		this.mainNav.each(function(item, index) {
			if(item.hasClass('active') == true) {
				this.activeMainId = item.id;	
			}
			item.addEvent('mouseenter',function(id) {
				var subId = this.options.replaceSub + id.replace(this.options.replaceMain,'');
				if($(subId)) {
					this.hideMenus(false);
					$(id).addClass('active');
					$(id).addClass('hasSub');
					$(subId).setStyle('display','');
					$(this.subNavId).tween('height',$(subId).getStyle('height').toInt() + $(subId).getStyle('padding-top').toInt());
				}
			}.bind(this, item.id));
		}.bind(this));
		//Add a mouseleave event to hide all submenus 
		//and show the menu that was originally active
		this.subNavs.each(function(item,index) {
			if(item.hasClass('active') == true) {
				this.activeSubId = item.id;	
			}
			item.addEvent('mouseleave',function() {
				this.hideMenus(true);
			}.bind(this));
		}.bind(this));
		
	},
	hideMenus: function(showActive) {
		//Function to hide all menus
		this.mainNav.each(function(item,index) {
			if(item.id != this.activeMainId) {
				item.removeClass('active');
			}
		}.bind(this));
		if($(this.activeMainId)) {
			$(this.activeMainId).removeClass('hasSub');	
		}
		if($(this.subNavId)) {
			$(this.subNavId).tween('height',0);
			this.subNavs.each(function(item,index) {
				item.setStyle('display','none');				
			});
		}
		if(showActive == true) {
			this.showActiveMenu();	
		}
	},
	showActiveMenu: function() {
		//Function to show the active menu (defined in initialize)
		if(this.activeMainId != '') {
			$(this.activeMainId).addClass('active');
			this.activeSubId = this.options.replaceSub + this.activeMainId.replace(this.options.replaceMain,'');				
			if($(this.activeSubId)) {
				if($(this.activeSubId).hasClass('active')) {
					$(this.activeMainId).addClass('hasSub');
					$(this.activeSubId).setStyle('display','');
					$(this.subNavId).tween('height',$(this.activeSubId).getStyle('height').toInt() + $(this.activeSubId).getStyle('padding-top').toInt());
				}
			}
		}	
	}
});
