$(function()
{
	// Navigation dropdowns
	var $activedropdown = null;
	var $activedropparent = null;
	var activebox = null;
	var activeradius = 50;
	
	var watchdropdown = function(evt)
	{
		if (!activebox)
		{
			activebox = $activedropdown.offset();
			activebox.right = activebox.left + $activedropdown.width();
			activebox.bottom = activebox.top + $activedropdown.height();
		}
		
		if (evt.pageX < activebox.left-activeradius || evt.pageX > activebox.right+activeradius ||
		    evt.pageY < activebox.top-activeradius || evt.pageY > activebox.bottom+activeradius)
		{
			hidedropdown();
		}
	};
	
	var hidedropdown = function ()
	{
		if (!$activedropdown) return;
		$activedropdown.hide();
		$activedropparent.removeClass("dropdown_active");
		$activedropdown = null;
		$activedropparent = null;
		activebox = null;
		$(document).unbind('mousemove', watchdropdown);
	};
	
	$("UL#navigation > LI:has(UL.navigation_dropdown)").each(function()
	{
		var timer = null;
		var $dp = $(this);
		var $dd = $("UL.navigation_dropdown", this);
		
		// Measure the size of the dropdown and assign it
		$dd.css("left", "-10000px").css("top", "-10000px").show().css("zoom", 1);
		window.setTimeout(function()
		{
			var iw = $dd.innerWidth();
			if (iw > 200) iw = 200;
			$dd.css("width", iw);
			$dd.hide().css("top", "").css("left", "");
		}, 0);
		
		// Normal processing
		$dd.append('<div class="navigation_dropdown_bg navigation_dropdown_w"></div><div class="navigation_dropdown_bg navigation_dropdown_s"></div><div class="navigation_dropdown_bg navigation_dropdown_e"></div><div class="navigation_dropdown_bg navigation_dropdown_se"></div><div class="navigation_dropdown_bg navigation_dropdown_sw"></div>');
		$(this).mouseenter(function()
		{
			if (timer)
				window.clearTimeout(timer);
			
			timer = window.setTimeout(function()
			{
				hidedropdown();
				
				$dd.show();
				$dp.addClass("dropdown_active");
				$activedropdown = $dd;
				$activedropparent = $dp;
				timer = null;

				$(document).bind('mousemove', watchdropdown);
			}, 300);
		}).mouseleave(function()
		{
			if (timer)
			{
				window.clearTimeout(timer);
				timer = null;
			}
		});
	});
	
	// Search box magic
	$("#searchquery").each(function()
	{
		if ($(this).val() == "Suchbegriff")
		{
			$(this).addClass("fresh").focus(function()
			{
				$(this).removeClass("fresh").val("");
			});
		}
	});
	
	// Magic popup boxes
	var showpopup = function(name)
	{
		var options =
		{
			width: 600,
			height: 500,
			contentisurl: true,
			shadow: true
		};
		dFrame.showModal("/kontakt/kontakt-"+name, options);
	};
	$("#contact_pem").click(function()
	{
		showpopup("pem");
		return false;
	});
	$("#contact_sam").click(function()
	{
		showpopup("sam");
		return false;
	});
});