//reference: http://www.i-marco.nl/weblog/jquery-accordion-menu-redux2/

function initMenus() {
	$('ul.menu ul').hide();
	$.each($('ul.menu'), function(){
		var cookie = $.cookie(this.id); //menu1
		var cookie1 = $.cookie("clickedMenu"); //menu
		var cookie2 = $.cookie("clickedItem"); //item
		//alert("cookie1="+cookie1+", cookie2="+cookie2);
		
		if(cookie === null || String(cookie).length < 1) {
			$('#' + this.id + '.expandfirst ul:first').show();
		}
		
		else {
			
			$('#' + this.id + ' .' + cookie).next().show();
		}
		
		if (cookie1 !=null) {
			$('#' + cookie1).children().css({"background" : "#106db2", "background-repeat" : "no-repeat"});
		}
 
  		if (cookie2 !=null) {
			$('#' + cookie2).children().css({"background" : "#97ccf3", "border-left" : "5px #f6b524 solid", "padding-left" : "15px"});
		}
	});
	

	$('ul.menu li a').click(
		function() {
			var checkElement = $(this).next();
			var parent = this.parentNode.parentNode.id;
			var thisItem = this.parentNode.id;
			var getURL = $(this).attr('href');
			
			$.cookie("thisItem", thisItem);
			
			
			if($(this).hasClass('clickedItem')){
				$.cookie("clickedItem", thisItem); //set the 'submenu' cookie
			}
			else{ // menu clicked
				setTimeout(function(){location.href=getURL;}, 800); //wait for animation of menu
				$.cookie("clickedMenu", thisItem);
				$.cookie("clickedItem", null);
			}	
						
			if($('#' + parent).hasClass('noaccordion')) {
				if((String(parent).length > 0) && (String(this.className).length > 0)) {
					if($(this).next().is(':visible')) {
						$.cookie(parent, null);
					}
					else {
						$.cookie(parent, this.className);
					}
					$(this).next().slideToggle('slow');
				}
			} //endif no accordion
			
			if((checkElement.is('ul')) && (checkElement.is(':visible'))) {
				
				if($('#' + parent).hasClass('collapsible')) {
					//$('#' + parent + ' ul:visible').slideUp('slow');
				}
				return false;
			} //endif collapsible
			
			if((checkElement.is('ul')) && (!checkElement.is(':visible'))) {
			
				$('#' + parent + ' ul:visible').slideUp('slow');
				if((String(parent).length > 0) && (String(this.className).length > 0)) {
					$.cookie(parent, this.className);
				}
				checkElement.slideDown('slow');
				return false;
			}
			
		} //end function
	
	); //end click
}
$(document).ready(function() {initMenus();});