// the timeout for the menu
var timeout = 100;
var timer;
var itemColor = "#E2E9F0";


// not very clean but simple
// the function can be run in the HTML for faster display
// window.onload=initMenu;


// this fonction apply the CSS style and the event
function initMenu(){
	
	// get some element
	var menu = document.getElementById('nav'); // the root element
	var lis = menu.getElementsByTagName('li'); // all the li

	// change the class name of the menu,
	// it's usefull for compatibility with old browser
	menu.className='nav';
	
	$$('#nav li').each(function(item, i){
		item.addEvent('mouseover',show);
		item.addEvent('focus',show);
		item.addEvent('mouseout',timeoutHide);
		item.addEvent('blur',timeoutHide);
		item.setAttribute( 'id', "li"+i);
		eval("timeoutli" + i + " = false;");
	
	});
}


// hide the first ul element of the current element
function timeoutHide() {
	// start the timeout
	eval( "timeout" + this.id + " = window.setTimeout('hideUlUnder( \"" + this.id + "\" )', " + timeout + " );");
}

// hide the ul elements under the element identified by id
function hideUlUnder( id ){
	
	var li = document.getElementById(id);
	
	with (li){
		
		// Setting to inactive
		className = "";
	
		if (getElementsByTagName('ul')[0])
			getElementsByTagName('ul')[0].style['left'] = ' -999em';
	}
}

// show the first ul element found under this element
function show() {

	// show the sub menu
	if ( this.getElementsByTagName('ul').length > 0 ){
		this.getElementsByTagName('ul')[0].style['left'] = 'auto';
	}
	
	// clear the timeout
	eval ( "clearTimeout( timeout"+ this.id +");" );
	hideAllOthersUls( this );

	// Change some styles ... Highlights Active Status
	this.className 	= "active";

}

// hide all ul on the same level of  this list item
function hideAllOthersUls( currentLi ){

	var ul = currentLi.parentNode;

	for ( var i=0; i<ul.childNodes.length; i++ ) {
		if ( ul.childNodes[i].id && ul.childNodes[i].id != currentLi.id ) {
			hideUlUnderLi( ul.childNodes[i] );
		}
	}

}

// hide all the ul wich are in the li element
function hideUlUnderLi( li ){
	
	// Change some styles ... Deactivates Highlight Status
	li.className = "";
	
	// get UL Childs
	var uls = li.getElementsByTagName('ul');

	for ( var i=0; i<uls.length; i++ ) {
		uls.item(i).style['left'] = ' -999em';
	}
}

window.addEvent('domready', function(){	
	initMenu();
});


