clickedLink = null;	// if you click on a menu item, the a-element will be saved here because the page loading is delayed

animOptions = {shots:{interval:null, nextLeftLi:0, nextRightLi:0}, shakes:{}};	// see $.ready also

// configure these
animOptions["shots"]["intervalTime"] = 700;		// time between each shot
animOptions["shots"]["nextIsLeftOrRight"] = 'left';	// which direction to start with
animOptions["shots"]["speed"] = 200; 			// px per second
animOptions["shots"]["margin"] = 120;			// space between the menu items in px, is only used if no "finalLeft"-attribute is specified per li

animOptions["shakes"]["minTime"] = 2000;	// duration is random, enter the limits here in msec
animOptions["shakes"]["maxTime"] = 3000;
animOptions["shakes"]["distance"] = 15;	// how far should they shake

function initialHideMenu()
{
	$(".menuItem a:not(.noResponseInIntro)").click(function(){	// if you change this, also change the unbind()-call below
		clickedLink = $(this);
		linkWasClicked();
		return false;
	});

	// put menu items to left/right borders of logo, only show their bars on top of them
	$("#leftUl > div, #rightUl > div").css({position:'absolute', height:'0px', overflow:'hidden'});
	// DEBUG: initially roll the menus out
	//$("#leftUl > div, #rightUl div").css("height", "auto");
	var logoLeft = $("#logo").offset().left - $("#logo").offsetParent().offset().left;
	$("#leftUl > div").css("left", logoLeft).data("posBehindLogo", logoLeft);
	$("#rightUl > div").each(function(index, obj){
		var cssLeft = logoLeft + $("#logo").width() - $(obj).width();
		$(obj).css("left", cssLeft).data("posBehindLogo", cssLeft);
	});
}

function shootNext()
{
	var li = null;
	var liIndex = 0;
	// only select lis of the top uls. lis may be wrapped in divs by $.effect
	var leftUlLis = $("#leftUl .menuItem").eq(animOptions["shots"]["nextLeftLi"]);
	var rightUlLis = $("#rightUl .menuItem").eq(animOptions["shots"]["nextRightLi"]);	// warning: jQuery's eq-selector accepts negative indices and returns actual objects! => test for positivity necessary, see below

	if( animOptions["shots"]["nextIsLeftOrRight"] == "left" && leftUlLis.size())
	{
		li = leftUlLis;
		liIndex = animOptions["shots"]["nextLeftLi"];
		animOptions["shots"]["nextLeftLi"]++;
	}
	else if(rightUlLis.size() && animOptions["shots"]["nextRightLi"] >= 0)
	{
		li = rightUlLis;
		liIndex = animOptions["shots"]["nextRightLi"];
		animOptions["shots"]["nextRightLi"]--;
	}
	if(!li)
	{
		clearInterval(animOptions["shots"]["interval"]);
		return;
	}
	
	if(li.has("[finalLeft]"))
	{
		var targetPosition = li.attr("finalLeft");
		var distance = Math.abs(targetPosition - parseInt(li.css("left")));
	}
	else
	{
		// if you change this, also change code in linkWasClicked()
		var distance = animOptions["shots"]["margin"]*(liIndex+1);
		var targetPosition = parseInt(li.css("left"));
		if(animOptions["shots"]["nextIsLeftOrRight"] == "left")
			targetPosition -= distance;
		else
			targetPosition += distance;
	}

	var timeFromSpeed = distance / animOptions["shots"]["speed"] * 1000;
	li.data("finalLeft", targetPosition);
	// shoot it out
	li.animate({left:targetPosition}, timeFromSpeed, 'easeInOutQuad', 
		function()
		{
			$(this).addClass("hasBeenShot");
			initRandomShakes($(this));
			$(this).hover(
				// mousein
				function()
				{
					$(this).stop(true).animate({height:$(this).data("initialHeight")}, 200);
				},
				// mouseout
				function()
				{
					$(this).stop(true).animate({height:'0'}, 500, function() {
						// after menu rolled in, go back to initial position and start shaking from there again
						$(this).animate({left:0}, 1000, function(){ initRandomShakes($(this)); });
					});
				}
			);
		}
	);

	if(animOptions["shots"]["nextIsLeftOrRight"] == "left")
		animOptions["shots"]["nextIsLeftOrRight"] = "right";
	else
		animOptions["shots"]["nextIsLeftOrRight"] = "left";
}

function initRandomShakes(li)
{
	var ran = Math.random();	// ran \in [0..1)
	ran = parseInt(ran*(animOptions["shakes"]["maxTime"] - animOptions["shakes"]["minTime"]) + animOptions["shakes"]["minTime"]);	// ran \in minTime..maxTime
	performInfiniteShakes(li, animOptions["shakes"]["distance"], ran);
}

function performInfiniteShakes(li, distance, time)
{
	$(li).effect("shake", {easing:'easeInOutSine', times:100, distance:distance}, time, function(){ performInfiniteShakes(li, distance, time) });
}

function linkWasClicked()
{
	if(animOptions["shots"]["interval"])
	{
		clearInterval(animOptions["shots"]["interval"]);
		// maybe there are menu items that have not been shaken => do not have a wrapper div
		$("#leftUl, #rightUl")
			.find("> .menuItem")
			.css("position", "relative")
			.wrap("<div style='position:absolute;'>")
			.each(function(index, obj){
					var currentLeft = $(obj).css("left");
					$(obj).css("left", "0px").parent().css("left", currentLeft);	// move obj's left to wrapper's left
				}
			);
		//console.log( $("#leftUl, #rightUl").find("> .menuItem") );
	}
	$(".menuItem").unbind().stop(true).animate({height:0});
	$(".hasBeenShot").animate({left:0});
	// shoot everything that has not been shot
	var animateMenuUpTime = 700;
	//console.log("left");
	$("#leftUl .menuItem:not(.hasBeenShot)").parent().each(function(index, obj){
			var posBehindLogo = $(obj).find("> div:first").data("posBehindLogo");
			var el;
			if(el = $(obj).find("> .menuItem[finalLeft]"))
			{
				var distance = Math.abs(el.attr("finalLeft") - posBehindLogo);
			}
			else
			{
				var distance = animOptions["shots"]["margin"]*($(obj).prevAll().size()+1);
			}
			$(obj).animate({left:posBehindLogo - distance}, animateMenuUpTime);
			/*
			console.log($(obj));
			console.log($(obj).css("left"));
			console.log(posBehindLogo - distance);
			console.log("------");
			*/
		});
	//console.log("right");
	$("#rightUl .menuItem:not(.hasBeenShot)").parent().each(function(index, obj){
			var posBehindLogo = $(obj).find("> div:first").data("posBehindLogo");
			var el;
			if(el = $(obj).find("> .menuItem[finalLeft]"))
			{
				var distance = Math.abs(el.attr("finalLeft") - posBehindLogo);
			}
			else
			{
				var distance = animOptions["shots"]["margin"]*($(obj).prevAll().size()+1);
			}
			$(obj).animate({left:posBehindLogo + distance}, animateMenuUpTime);
			/*
			console.log($(obj));
			console.log($(obj).css("left"));
			console.log(posBehindLogo + distance);
			console.log("------");
			*/
		});
	
	//$("#menu").animate({"top":20}, animateMenuUpTime, function(){
	$("#menu").animateToClass("menuFinalState", animateMenuUpTime, function(){
		$(".menuItem").each(
			function(index, obj)
			{
				$(obj).animate({height:$(this).data("initialHeight")}, 500);
			}
		).find("a").unbind("click");
		afterMenuIsAtTop();
	});
}

// stuff after the menu has slided all the way up
function afterMenuIsAtTop()
{
	$("#contentWrapper").css("width", $("#contentWrapper").closest(":visible").width()+"px").show("scale", {}, 700, function() { $(this).addClass("contentSpinner"); executeLink(); });
}

function executeLink()
{
	if(clickedLink == null || $(clickedLink).attr("href") == "")
	{
		return;
	}
	document.location.href = $(clickedLink).attr("href");
}

function convertMenuToDivs()
{
	// convert uls to divs because $.effect wraps lis with divs, which causes errors
	var uls = ["leftUl", "rightUl"];
	for(var ulId in uls)
	{
		var ulId = uls[ulId];
		$("#"+ulId).removeAttr("id").wrap("<div id='"+ulId+"'>").find("> li").each(function(index, obj){
			var menuItem = $("<div>")
							.addClass("menuItem").css("float", "left")
							.html($(obj).html())
							.find("ul > li")
							.addClass("subMenuItem")
							.end();	// important!
			if($(obj).has("[finalLeft]"))
				menuItem.attr("finalLeft", $(obj).attr("finalLeft"));
			// #leftUl is now the wrapping div
			$("#"+ulId).append(menuItem);
			menuItem.data("initialHeight", menuItem.height());	// save the li's height for the menu's slideDown. this has to be the last statement somehow
		});
		$("#"+ulId+" > ul").remove();
	}
}





