﻿/// <reference path="http://ajax.microsoft.com/ajax/jQuery/jquery-1.4.1.min.js"/>
jQuery.fn.exists = function () { return jQuery(this).length > 0; }

$(document).ready(function ()
{
	var animatingDown = false;
	var background = document.createElement("div");
	background = $(background);

	init();

	function init()
	{
		background.attr("id", "Background");
		background.attr("class", "navigation");
		$("#Navigation").after(background);
		background.append("<span></span>");
		background.hover(function ()
		{
			$(this).addClass("hover");
		}, function ()
		{
			$(this).removeClass("hover");
		});

		$("#Navigation ul li").find("li").css("display", "none");
		$("#Navigation ul li").find("span").remove();

		$("#Navigation ul li").has("ul").hover(show, function ()
		{
			$(this).removeClass("hover");
			setTimeout(hide, 100, false);
		});
		$("#Background").hover(animateDown, function () { hide(false); });

		$(window).resize(function ()
		{
			hide(true);
		});
	}



	function show()
	{
		$(this).addClass("hover");

		$(background).find("ul").remove();

		var items = $(this).find("ul").clone();
		items.attr("display", "block");
		items.appendTo(background);
		items.css("left", $("#Navigation ul").position().left);

		$(background).find("li").css("display", "list-item");

		$(this).parent().addClass("active");
		$(this).addClass("active").siblings().removeClass("active");

		animateDown();
	}
	function hide(resize)
	{
		if (resize || !($("#Navigation ul li.hover ul").exists() || $("#Background.hover").exists()))
		{
			$("#Navigation ul").removeClass("active");
			animatingDown = false;

			background.stop(true, false);
			background.animate(
					{ height: 0 },
					{ duration: 300 },
					{ easing: "linear" },
					function () { }
				);
		}
	}
	function animateDown()
	{
		$("#Navigation ul").addClass("active");
		if (!animatingDown)
		{
			animatingDown = true;
			background.stop(true, false);
			background.animate(
						{ height: 273 },
						{ duration: 300 },
						function () { animatingDown = false; }
					);
		}
	}
});
