var _dropDownOpen = false;

window.addEvent('domready', function() {

	var navHolder = $(document.body).getElement('div#navigation .holder');
	var topLevelMenu = $$('a.toplevel');
	
	var dropDownPanels = $$('li.toplevel div.dropdownarea').fade('hide').removeClass('none');
	
	topLevelMenu.each(function(menuItem, n){
		menuItem._openpanel = false;
		menuItem.addEvents({
			click: function(el){
				var e = el.stop();
				//Remove the selected state from previous selected section
				topLevelMenu.removeClass('selected');
				//Highlight the newly selected section
				this.addClass('selected');
				//Open the Drop Down Panel
				navHolder.addClass('selected');
				//Hiding already open Drop Down Panels
				dropDownPanels.fade('hide');
				//Finding the state of the Drop Downs.
				//If one is already open then pop it in, if not fade it in.
				var fadeState = (_dropDownOpen == true) ? 'show' : 'in';				
				dropDownPanels[n].fade(fadeState);
				//Let the page know that there is a drop down panel open.
				_dropDownOpen = true;
			},
			mouseenter: function(){
				_dropDownOpen = true;
			},
			mouseleave: function(){
				this.fireEvent('closePanel', this.className, 1000);	
				_dropDownOpen = false;
			},
			closePanel: function(){
				if(!_dropDownOpen) {
					dropDownPanels[n].fade('out');				
					navHolder.removeClass('selected');
					topLevelMenu.removeClass('selected');
				}				
			}
		});
	});
	
	dropDownPanels.each(function(dropDown, n) {
		dropDown.addEvents({
			mouseleave: function(attribute){
				this.fireEvent('closePanel', this.className, 1000);	
				_dropDownOpen = false;			
			},
			mouseenter: function(attribute){
				if(!_dropDownOpen){
					this.fade('in');
					navHolder.addClass('selected');
					topLevelMenu[n].addClass('selected');
					_dropDownOpen = true;
				}
			},
			closePanel: function(){
				if(!_dropDownOpen) {
					this.fade('out');				
					navHolder.removeClass('selected');
					topLevelMenu.removeClass('selected');
				
				}
			}
		});
	});
});