﻿jQuery.fn.positionAncestor = function (selector) {
	var left = 0;
	var top = 0;
	this.each(function (index, element) {
		// check if current element has an ancestor matching a selector
		// and that ancestor is positioned
		var $ancestor = $(this).closest(selector);
		if ($ancestor.length && $ancestor.css("position") !== "static") {
			var $child = $(this);
			var childMarginEdgeLeft = $child.offset().left - parseInt($child.css("marginLeft"), 10);
			var childMarginEdgeTop = $child.offset().top - parseInt($child.css("marginTop"), 10);
			var ancestorPaddingEdgeLeft = $ancestor.offset().left + parseInt($ancestor.css("borderLeftWidth"), 10);
			var ancestorPaddingEdgeTop = $ancestor.offset().top + parseInt($ancestor.css("borderTopWidth"), 10);
			left = childMarginEdgeLeft - ancestorPaddingEdgeLeft;
			top = childMarginEdgeTop - ancestorPaddingEdgeTop;
			// we have found the ancestor and computed the position
			// stop iterating
			return false;
		}
	});
	return {
		left: left,
		top: top
	}
};

var currentMenu;

function setPanelWidth() {
	var maxw = 100;
	currentMenu.find(".menu-l2").each(function () {
		var w = 0;
		$(this).find("li").each(function () {
			w += parseFloat($(this).outerWidth(true));
		});
		if (w > maxw)
			maxw = (10 + w);
	});

	var allowedWidth = parseFloat($("#container").width()) - currentMenu.positionAncestor("#container").left;

	while (maxw > allowedWidth) {
		maxw -= (maxw / 3);
	}
	
	currentMenu.width(maxw);
}

function hideCurrentMenu() {
	if (currentMenu != null) {
		currentMenu.fadeTo('fast', 0, function () { $(this).hide(); });
		currentMenu.parent(".selected").removeClass("selected");
	}
}

$(document).ready(function () {
	$("ul.topnav li .sub").css({ 'opacity': '0' });

	$("ul.topnav a.cosami").click(function () {
		hideCurrentMenu();
		currentMenu = $(this).parent("li").find(".sub");

		if (currentMenu.html() != null) {
			currentMenu.stop().fadeTo('fast', 1).show(); //Find sub and fade it in
			$(this).parent("li").addClass("selected");
			setPanelWidth();
			return false; //stop click bubbling
		}
	});

	$(".sub a").click(function () {
		document.location = $(this).attr("href");
	});

	$(".sub").click(function () {
		return false;
	});

	$("body").click(hideCurrentMenu);

});
