if (!document.getElementById) {
	document.getElementById = function() {
		return null;
	};
}
// =========================================================================
// Cookie functions
// =========================================================================
/* This function is used to set cookies */
function setCookie(name, value, expires, path, domain, secure) {
	document.cookie = name + "=" + escape(value)
			+ ((expires) ? "; expires=" + expires.toGMTString() : "")
			+ ((path) ? "; path=" + path : "")
			+ ((domain) ? "; domain=" + domain : "")
			+ ((secure) ? "; secure" : "");
}

/* This function is used to get cookies */
function getCookie(name) {
	var prefix = name + "=";
	var start = document.cookie.indexOf(prefix);

	if (start == -1) {
		return null;
	}

	var end = document.cookie.indexOf(";", start + prefix.length);
	if (end == -1) {
		end = document.cookie.length;
	}

	var value = document.cookie.substring(start + prefix.length, end);
	return unescape(value);
}

/* This function is used to delete cookies */
function deleteCookie(name, path, domain) {
	if (getCookie(name)) {
		document.cookie = name + "=" + ((path) ? "; path=" + path : "")
				+ ((domain) ? "; domain=" + domain : "")
				+ "; expires=Thu, 01-Jan-70 00:00:01 GMT";
	}
}

function initMenu() {
	$(".menuList").children("li").each(function(index) {
		initMenuPath($(this), "", 1, index);
	});
}

function initMenuPath(menu, parentPath, level, subMenuItemIndex) {
	var menuSelected = getCookie("menuSelected");
	// decorate menu item
	var menuPath = parentPath + "/" + subMenuItemIndex;
	$(menu).data("myPath", menuPath);
	$(menu).click(function(event) {
		event.stopPropagation();
		setCookie("menuSelected", menuPath, null, "/", null, null);

		$(".selected.level1").children("ul").fadeOut("slow");
		$(".selected").removeClass("selected");
		if (level == 1) {
			$("#menuBottom").fadeOut("slow");
		}

		$(menu).children("ul").each(function(index) {
			$("#menuBottom").fadeIn("slow");
			return false;
		});
		$(menu).children("ul").fadeIn("slow");
		$(menu).addClass("selected");
	});

	if (menuSelected && menuSelected.match("^" + menuPath) == menuPath) {
		$(menu).children("ul").show();
		$(menu).addClass("selected");
		$(menu).children("ul").each(function(index) {
			$("#menuBottom").show();
			return false;
		});
	}

	// decorate sub-menu items
	$(menu).children("ul").each(function(subMenuIndex) {
		$(this).children("li").each(function(subMenuItemIndex) {
			initMenuPath(this, menuPath, level + 1, subMenuItemIndex);
		});
	});
}

// Select the menu that matches the URL when the page loads
$(document).ready(function() {
	initMenu();
});

