$(function(){
	$("#menu").hover(function() { update_hover(0, true); },  function() { update_hover(0, false); } );
	$("#menu li.multiple").hover(function() { update_hover(1, true, $(this).attr('id')); }, function() { update_hover(1, false, $(this).attr('id')); } );
});

var menu_wait_max = 500;
var sub_wait_max = 250;
var timer_update = 100;
		
var show_menu = false;
var menu_wait = 0;

var sub_item = Array();

function remove_sub_item(id, bRemove) {
	var index = -1;
	for(var i=0; i<sub_item.length; i++) {
		var data = sub_item[i];
		if (data[0] == id) {
			index = i;
			break;
		}
	}
	
	if (bRemove && index == -1) {
		//we will remove this item, so it needs to be on the list
		if (index == -1) {
			//add the item
			sub_item.push(new Array(id, 0));
		}
	} else if (!bRemove && index > -1) {
		//we will no longer remove this item, so remove it
		sub_item.splice(index,1);
	}
}

function update_hover(level, bShow, id) {
	if (level == 0) {
		show_menu = bShow;
	} else {
		if (bShow) {
			$("#" + id).children("a.multiple").attr('class','multiple selected');
			$("#" + id).children("ul").fadeIn();
			remove_sub_item(id, false);
		} else {
			remove_sub_item(id, true);
			//$("#" + id).children("a.multiple").attr('class','multiple');
			//$("#" + id).children("ul").fadeOut();
		}
	}			
}

function menu_update() {
	if (show_menu) {
		$("#menu").children("ul.level1").fadeIn();
		menu_wait = 0;
	} else {
		menu_wait+=timer_update;
		if (menu_wait > menu_wait_max) {
			$("#menu").children("ul.level1").fadeOut();
		}
	}
	
	for(var i=0; i<sub_item.length; i++) {
		var data = sub_item[i];
		data[1] += timer_update;
		if (data[1] > sub_wait_max) {
			var id = data[0];
			$("#" + id).children("a.multiple").attr('class','multiple');
			$("#" + id).children("ul").fadeOut();
		}
	}
}

var menu_timer = setInterval("menu_update()", timer_update);
