var rootId = "root";
var linkPrefix = "link_";
var activeUl = "active";
var activeElement = "is_active";

var selectedRoot;
var isDisplayingItems = false;

$(document).ready(function() {
	$("#menuRoot").children().each(function(){addClickForUlMenu($(this), true);});
	$("#menuItems").children().each(function(){addClickForUlMenu($(this), false);});
 });

function addClickForUlMenu(ulElement, isRoot) {
	ulElement.children().each(function (){

		if (isRoot) {
			/* Add click to li */
			$(this).click(function () {
				clickedMenuItem($(this), isRoot);
			});
		} else {
			/* Add click to the content of the li because we don't
			 want the full li to be clickable */
			var menuItem = $(this);

			$(this).children().each(function () {
				$(this).hover(function () {
					clickedMenuItem(menuItem, isRoot);
				})
			});
		}
	});
}

function clickedMenuItem(menuItem, isRoot) {
	markMenuItemAsActive(menuItem);

	var menuItemId = menuItem.attr('id');
	if (menuItemId != "") {
		var idToShow = menuItemId.substr(linkPrefix.length, menuItemId.length - linkPrefix.length);
		showUlMenu(idToShow);

		if (isRoot) {
			checkToggleMenuItems(menuItem);
		}
	}
}

function markMenuItemAsActive(menuItem) {
	var parent = menuItem.parent();

	parent.children().each(function (){
		$(this).removeClass(activeElement);
	});

	menuItem.addClass(activeElement);
}

function showUlMenu(ulId) {
	//Remove class
	$("#menuItems").children().each(function (){
		var childId = $(this).attr('id');
		
		if (childId != undefined) {
			var isActive = $(this).hasClass(activeUl);
			var belowCurrent = childId.length >= ulId.length;

			if (childId != undefined) {
				var isActive = $(this).hasClass(activeUl);
				var belowCurrent = childId.length >= ulId.length;

				if (belowCurrent && isActive) {
					removeMenuClasses($(this));
				}
			}
		}
	});

	//Add class
	$("#" + ulId).addClass(activeUl);
}

function removeMenuClasses(ulElement) {
	ulElement.removeClass(activeUl);

	ulElement.children().each(function (){
		$(this).removeClass(activeElement);
	});
}

function checkToggleMenuItems(rootMenuItem) {
	rootId = rootMenuItem.attr('id');
	var toggle = rootId == selectedRoot;

	if (toggle || !isDisplayingItems) {
		toggleMenuItems();
	}

	selectedRoot = rootId;
}

function toggleMenuItems() {
	if (isDisplayingItems) {
		$("#menuItems").slideUp('fast', function() {
			$("#" + selectedRoot).removeClass(activeElement);
        	// Animation complete
    	});
	} else {
		$("#menuItems").slideDown('fast', function() {
        	// Animation complete
    	});
	}

	isDisplayingItems = !isDisplayingItems;
}
