﻿var delay=200;
var animationTime = 200;
var timerShow;
var activeLevel = -1;

$(document).ready(function() {

	AddExpandableStyles();

	AddClasses($(".flyout"), 1);

	// Set hover function for all menu items to show/hide flyouts
	$(".flyout li > a").hover(function() {
			var li = $(this).parent();
			activeLevel = LevelOfLi(li);
			clearTimeout(timerShow);
			timerShow = setTimeout(function(){LiHover(li)},delay);
	  }, function() {
			activeLevel = -1;
			var li = $(this).parent();
			setTimeout(function(){LiOut(li)},delay);
		});
});

// Add a style to each expandable menu item to show that there is a sub-menu
function AddExpandableStyles()
{
	$(".flyout li > ul").each( function() {
			$(this).parent().children("a").addClass("expandable");
			//AddExpandableSpan($(this).parent());
		});
}
/*
function AddExpandableSpan(li)
{
	var a = jQuery(li).children('a')[0];
	jQuery(a).html(jQuery(a).html() + '<span class="menuTriangle"/>');
}
*/

// Add level-n class to the children of the ul, where n = level + 1
function AddClasses(uls, level)
{
	var childUls = jQuery(uls).children("li").children("ul");
	if(childUls.length > 0)
	{
		jQuery(childUls).addClass("level"+(level+1));
		AddClasses(childUls, level+1);
	}
}

function LiHover(li) {
	li.children("ul").show(animationTime);
}

function LiOut(li) {
	if(activeLevel == -1 ||
		 activeLevel <= LevelOfLi(li))
	{
		//alert("hiding\nactiveLevel = "+activeLevel +"\nli level "+LevelOfLi(li));
		li.find("ul").hide(animationTime);
		HideParent(jQuery(li).parent());
	}
	else
	{
		//alert("not hiding\nactiveLevel = "+activeLevel +"\nli level "+LevelOfLi(li));
	}
}

function HideParent(ul) {
	var lv = LevelOfUl(ul);
	if((lv > 1) && 
		 (activeLevel < lv))
	{
		//alert("hiding\nactiveLevel = "+activeLevel +"\nul level "+lv);
		jQuery(ul).hide(animationTime);
		HideParent(ul.parent().parent("ul"));
	}
}

// To find out the level in the menu (First level is level 1, not 0)
function LevelOfLi(li)
{
	var ul = jQuery(li).parent();
	return LevelOfUl(ul);
}
function LevelOfUl(ul)
{
	if(ul.hasClass("flyout"))
		return 1;
	else if(ul.hasClass("level2"))
		return 2;
	else if(ul.hasClass("level3"))
		return 3;
	else if(ul.hasClass("level4"))
		return 4;
	else if(ul.hasClass("level5"))
		return 5;
	else
		return -1;
}

