/*

*/

var debug = true;
var ieDebug = false;
var sitemapDistributionFactor = 0.60;

var debugString = "";

var jqie6 = false;

$.validator.addMethod("allowedFile", function(value) {
	var allowedFiles = ",.pdf,.doc,docx,";
	return (value.length == 0 || allowedFiles.indexOf(',' + value.substr(value.length - 4).toLowerCase() + ',') > -1);
}, 'Filen skal være i pdf eller word format.');

var mouseX = 0;


$().ready(function()
{
	log("js.js start");

	$().mousemove(function(e){
		mouseX = e.pageX;
	});
	$("#rightColumn").append($("#content .jsMoveRight").removeClass("hidden"));
	$("#content .jsMoveRight").remove();
	
	$("#rightColumn > img").addClass("right");
	$("#rightColumn > a > img").addClass("right");

	if (!(window.isIE6 === undefined))
	{
		jqie6 = (window.isIE6 == true);
	}

	$("input:hidden").addClass("hidden");

	$(".column").each(function() {
		if ($(this).children().length == 0) $(this).css("visibility", "hidden");
	})

	$("div#icons a.jsshow").wrapInner("<span></span>");

	$("a.jsshow").removeClass("jsshow");

	$("div#topNavigation > ul > li > ul").append('<li class="last"></li>');

	$("div#leftNavigation ul.nav > li:last").addClass("last");

	$("div.frontpageBox div.buttons:has(a)").each(function() {
		var maxHeight = 0;
		var links = $(this).find("a");
		for (var i = 0; i < links.length; i++)
		{
			if ($(links[i]).height() > maxHeight) maxHeight = $(links[i]).height();
		}
		for (var i = 0; i < links.length; i++)
		{
			$(links[i]).height(maxHeight);
		}
		if (links.length > 0 && links.length < 3)
		{
			for (var i = 0; i < links.length; i++)
			{
				$(links[i]).css("border-bottom", "none")
			}
			$(this).css("border-bottom", "1px solid #4a6878");
		}
		if (links.length > 3 && links.length < 6)
		{
			for (var i = 3; i < links.length; i++)
			{
				$(links[i]).css("border-bottom", "none")
			}
			$(this).css("border-bottom", "1px solid #4a6878");
		}
	});

	$("#applicationForm").validate({
		success: "valid",
		errorContainer: "#errors",
		showErrors: function(errorMap, errorList) {
			this.defaultShowErrors();
			$("#applicationForm input").each(function() {
				if ($(this).hasClass("error"))
					$(this).prev().addClass("errorL");
				else
					$(this).prev().removeClass("errorL");

				if ($(this).next().hasClass("valid"))
					$(this).addClass("valid").prev().addClass("valid");
				else
					$(this).removeClass("valid").prev().removeClass("valid");
			
			});
			log("error");
		},
		submitHandler: function(form) {
			$(form).ajaxSubmit({
				dataType: "xml",
				success: documentCommentResponse
			});
			$(form).find("input:submit").attr("disabled", "disabled");
		}
	});

	setupSitemap();
	activateMenu();
	
	log("js.js end");
	if (debug && ieDebug && !self.console) alert(debugString);
});

function log(s)
{
	var now = new Date();
	s = (now.getTime() + '').substr(9) + ": " + s;
	if (self.console)
		console.log(s);
	else
		if (debug) debugString += s + '\n';
}

function activateMenu()
{
	if (jqie6)
	{
		var sfEls = document.getElementById("topNavigation").getElementsByTagName("LI");
		for (var i=0; i<sfEls.length; i++) {
			sfEls[i].onmouseover=function() {
				this.className+=" sfhover";
			}
			sfEls[i].onmouseout=function() {
				this.className=this.className.replace(new RegExp(" sfhover\\b"), "");
			}
		}
	}
	else
	{
		$('div#topNavigation > ul.nav').superfish({
			delay:       500,
			animation:   {opacity:'show',height:'show'},
			speed:       'fast',
			autoArrows:  false,
			dropShadows: true
		});
	}
}

function documentCommentResponse(responseText, statusText)  {
    // for normal html responses, the first argument to the success callback
    // is the XMLHttpRequest object's responseText property

    // if the ajaxSubmit method was passed an Options Object with the dataType
    // property set to 'xml' then the first argument to the success callback
    // is the XMLHttpRequest object's responseXML property

    // if the ajaxSubmit method was passed an Options Object with the dataType
    // property set to 'json' then the first argument to the success callback
    // is the json data object returned by the server

	if ($(responseText).find("StatusCode").text() == "1")
	{
		log(responseText);
/*
		$("#commentForm input.button").attr("disabled", "");
		$("#commentForm input:not(.button,.hidden)").val("");
		$("#commentForm textarea").val("");
		$("#comments").html($j("#comments").html() + "<h2>" + $j(responseText).find("Headline").text() + "</h2><p>" + $j(responseText).find("Text").text() + "</p><hr />");
		var heading = $j("#commentsHeading").text();
		var start = heading.search(/\d+/);
		var end = start + heading.substr(start).search(/\D/);
		var amount = heading.substring(start, end);
		heading = commentsPlural;
		if (amount == 0) heading = commentsSingular;
		heading = heading.replace(/(.)(\d+)(.)/, "$1" + (1.0 * amount + 1) + "$3");
		log(heading);
		$("#commentsHeading").text(heading);
*/
	}
	else
	{
		document.location = document.location;
	}

//    alert('status: ' + statusText + '\n\nresponseText: \n' + responseText + '\n\nThe output div should have already been updated with the responseText.');
}









function pollVote(formId)
{
	createCookie("voted" + formId, "1", 10 * 365);
	$("form#f" + formId).submit();
}

function pollInit()
{
	$("div.poll").each(function() {
		var formId = $(this).find("div.radios h1").html();

		var voted = (readCookie("voted" + formId) == "1");
		if (document.location.href.indexOf(formId) > 0) voted = true;

		var id = 1;

		var voteHtml = $(this).find("div.intro").html();
		$(this).find("div.radios p").each(function() {
			voteHtml += '<input id="Radio_' + id + '" name="Radio" class="RadioButton" type="radio" value="' + id + '" /><label for="Radio_' + id + '" class="RadioButton">' + $(this).find("span:first").text() + '</label><br />';
			id++;
		});
		voteHtml += '<input type="hidden" class="hidden" name="formId" value="' + formId + '" />';
		voteHtml += '<input type="button" onclick="pollVote(\'' + formId + '\')" disabled="disabled" class="Button" value="' + $(this).find('a:first').text() + '" />';

		var linkText = $(this).find("div.radios a:last").text();
		if (linkText != '') voteHtml += '<a href="?showPollId=' + formId + '">' + linkText + '</a>';

		if (!voted) $(this).find("div.shown").append(voteHtml);

		var resultsHtml = $(this).find("div.resultsIntro").html();
		var resultsTotal = 0;

		$(this).find("div.radios p").each(function() {
			resultsTotal += 1.0 * $(this).find("span:last").text();
		});

		$(this).find("div.radios p").each(function() {
			var votes = $(this).find("span:last").text() * 1.0;
			var percent = 0;
			if (resultsTotal > 0) percent = Math.round((100.0 * votes) / resultsTotal);
			resultsHtml += '<p><strong>' + $(this).find("span:first").text() + ':</strong><br class="br" /><span class="pollPercent">' + percent + '%</span> <a class="bar" title="' + votes + '" style="width: ' + Math.round(1.4 * percent) + 'px"></a></p>';
		});

		resultsHtml += "<p>" + $(this).find("div.radios h3").text() + resultsTotal + "</p>";
		
		resultsHtml += $(this).find("div.resultsOutro").html();

		if (voted) $(this).find("div.shown").append(resultsHtml);

		$(this).find("div.shown").wrap('<form class="rwform poll" id="f' + formId + '" action="" method="post">' + '</form>');
		$(this).find("div.shown input[type='radio']").click(function() {
			$(this).parent().find("input.Button").removeAttr("disabled");
		});

	});
}


function checkToggleUrl()
{
	var href = document.location.href.toLowerCase();
	var toggleIndex = href.indexOf("toggleurl=");
	var endIndex = href.indexOf("&", toggleIndex);
	if (toggleIndex > -1)
	{
		if (endIndex > -1)
			var url = href.substring(toggleIndex + 10, endIndex)
		else
			var url = href.substr(toggleIndex + 10)
	}
	$("#leftNavigation ul.nav li.collapsed > a").each(function() {
		if ($(this).attr("href").indexOf(url) > -1)
			$(this).parent().toggleClass("collapsableOpen");
	});
}

function activateCollapsables()
{
	$("#leftNavigation ul.nav li.collapsed > a").click(function() {
		$(this).parent().toggleClass("collapsableOpen");
		this.blur();
		return false;
	});
}

function setCaptionWidths()
{
	$("#content .captioned").each(function()
	{
		$(this).width($(this).find("img:first").width());
		if ($(this).width() >= ($(this).parent().width() - 32))
			$(this).removeClass("left").removeClass("right").css("marginLeft", "0px").css("marginRight", "0px").css("clear", "both");
	});
}

function fixOldViaForms()
{
	$("#content form.viaform1 label.CheckBoxLabel").each(function()
	{
		$(this).removeClass("CheckBoxLabel")
		$(this).after($(this).find("input"));
		$(this).next("input").after("<br />");
	});
	$("#content form.viaform1 input.Button:first").before("<label></label>");
}


function cleanNavigation()
{
	if ($("div#extraNavigation > ul > li > a:first").attr("href").indexOf(umbracoUrl) != 0)
	{
		$("#extraNavigation a").each(function()
		{
			$(this).attr("href", umbracoUrl + $(this).attr("href"));
		});
	}
}

function markTopNavigation()
{
	if ($("#leftNavigation ul.nav > li.open").length != 0)
	{
		$("#topNavigation ul.nav a[@href='" + $("#leftNavigation ul.nav > li.open > a").attr("href") + "']").addClass("open").parent().addClass("open").parent().parent().addClass("open").find("> a").addClass("open");
	}
	else if ($("#leftNavigation ul.nav > li.selected").length != 0)
	{
		$("#topNavigation ul.nav a[@href='" + $("#leftNavigation ul.nav > li.selected > a").attr("href") + "']").addClass("selected").parent().addClass("selected").parent().parent().addClass("open").find("> a").addClass("open");
	}
}

function drawPath()
{
	if (umbraco)
	{
		$("#path ul.nav").remove();

		var selectedNode = $("#leftNavigation ul.nav a.selected");
		var path = "<ul><li class=\"selected\"><a class=\"selected\" href=\"" + $(selectedNode).attr("href") + "\">" + $(selectedNode).html() + "</a></li><ul>";
		var leftNavigationParentNode = $(selectedNode).parent().parent();

		while ($(leftNavigationParentNode).length != 0 && !$(leftNavigationParentNode).hasClass("nav"))
		{
			leftNavigationParentNode = $(leftNavigationParentNode).parent().parent();
			var link = $(leftNavigationParentNode).find("> li > a.open");
			path = "<ul><li class=\"open\"><a class=\"open\" href=\"" + $(link).attr("href") + "\">" + $(link).html() + "</a>" + path + "</li></ul>";
		}
		var link = $("#topNavigation > ul.nav > li > a.open");
		if ($(link).length > 0)
		{
			path = "<ul><li class=\"open\"><a class=\"open\" href=\"" + $(link).attr("href") + "\">" + $(link).html() + "</a>" + path + "</li></ul>";
		}

		$("#path").prepend(path);
	}
}

function stitchTopNavigation()
{
	for (var i = 0; i < navigationStitching.length - 1; i += 2)
	{
		if (umbraco)
			var url = viaUrl + navigationStitching[i];
		else
			var url = navigationStitching[i];
		var node = $("#topNavigation > ul > li > a[@href='" + url + "']");
		if ($(node).length > 0)
		{
			$(node).parent().prepend($("#extraNavigation a[@href='" + umbracoUrl + navigationStitching[i+1] + "']").parent().children("ul").clone());
		}
	}
	$("#topNavigation > ul > li > ul > li > ul").remove();
	$("#topNavigation > ul > li").each(function() {
		if ($(this).find("ul").length > 1)
		{
			$(this).find("ul:last").append($(this).find("ul:first > li"));
			$(this).find("ul:first").remove();
		}
	})
	
}

function stitchNavigation()
{
	if (umbraco)
	{
		for (var i = 0; i < navigationStitching.length - 1; i += 2)
		{
			$("#viaExtraNavigation a[@href='" + navigationStitching[i] + "']").parent().append($("#extraNavigation a[@href='" + umbracoUrl + navigationStitching[i+1] + "']").parent().children("ul"));
		}

		$("#viaExtraNavigation *").removeClass("open").removeClass("selected");

		$("#leftNavigation ul.nav").remove();
		$("<ul class=\"nav\"></ul>").prependTo("#leftNavigation");

		log("c3");
		var leftNavigationParentNode = $("#viaExtraNavigation  a[@href='" + umbracoLocation + "']").parent().parent();

		while ($(leftNavigationParentNode).length != 0 && !$(leftNavigationParentNode).parent().parent().hasClass("nav"))
		{
			leftNavigationParentNode = $(leftNavigationParentNode).parent().parent();
		}

		$(leftNavigationParentNode).children().each(function() {
			$(this).appendTo($("#leftNavigation ul.nav"));
		});

		cleanNavigationLevel($("#leftNavigation > ul.nav"), umbracoLocation);
		
		$("#leftNavigation ul.nav a").each(function() {
			if ($(this).attr("href").indexOf(umbracoUrl) < 0)
				$(this).attr("href", viaUrl + $(this).attr("href"));
		});
	}
	else
	{
		for (var i = 0; i < navigationStitching.length - 1; i += 2)
		{
			var node = $("#leftNavigation a.selected[@href='" + navigationStitching[i] + "']");
			if ($(node).length > 0) $(node).parent().append($("#extraNavigation a[@href='" + umbracoUrl + navigationStitching[i+1] + "']").parent().children("ul"));

			if ($("#topNavigation > ul.nav > li > a.selected[@href='" + navigationStitching[i] + "']").length != 0)
			{
				$("#leftNavigation ul.nav").remove();
				$("#leftNavigation").prepend(("<ul class=\"nav\"></ul>"));
				$("#topNavigation a.selected").parent().find("li").each(function() {
					$("#leftNavigation ul.nav").append($(this).clone());
				});
			}
			if ($("#topNavigation > ul.nav > li > a.open[@href='" + navigationStitching[i] + "']").length != 0)
			{
				$("#leftNavigation > ul.nav").append($("#extraNavigation a[@href='" + umbracoUrl + navigationStitching[i+1] + "']").parent().find("> ul > li > a"));
				$("#leftNavigation > ul.nav > a").wrap("<li></li>");
			}

		}
		cleanLeftNavigation($("#leftNavigation > ul.nav"), viaLocation);
	}
}
function cleanLeftNavigation(ul, selectedHref)
{
	$(ul).find("a[@href='" + selectedHref + "']").parent().find("ul > li:not(.collapsed) > ul").remove();
}

function cleanNavigationLevel(ul, selectedHref)
{
	$(ul).find("> li:not(.collapsed)").each(function() {
		if ($(this).find("a[@href='" + selectedHref + "']").length == 0)
		{
			$(this).find("ul").remove();
		}
		else
		{
			if ($(this).find("> a").attr("href") == selectedHref)
			{
				$(this).addClass("selected");
				$(this).find("> a").addClass("selected");
			}
			else
			{
				$(this).addClass("open");
				$(this).find("> a").addClass("open");
				$(this).find("> ul").each(function() {
					cleanNavigationLevel(this, selectedHref);
				});
			}
		}
	});
}

function stitchSitemap()
{
	if ($("#topContent ul.nav").length > 0)
	{
		for (var i = 0; i < navigationStitching.length - 1; i += 2)
		{
			$("#topContent ul.nav a[@href='" + navigationStitching[i] + "']").parent().append($("#extraNavigation a[@href='" + umbracoUrl + navigationStitching[i+1] + "']").parent().children("ul").clone());
		}
	}
}


function printurl(section)
{
	var u = document.location.href;
	if(u.indexOf('#') > 0)
	{
	u = u.split('#');
	u = u[0];
	}
	u += (u.indexOf('?') >0)? '&':'?';
	u +='print=1';
	if(typeof(section)!="undefined") u +='&section='+ section;
	return u;
}

function printing(section)
{
	var u = printurl(section);
	w = window.open(u,'print','width=650,height=680,toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,copyhistory=no');
	w.focus();
}

function setLinkIcons()
{
	$('#content a').each(
		function() {
			setIconIfAllowed(this);
		}
	);
	$('#rightColumn a').each(
		function() {
			setIconIfAllowed(this);
		}
	);
	$('#leftNavigation .box a').each(
		function() {
			setIconIfAllowed(this);
		}
	);
}

function setIconIfAllowed(e)
{
	var icons = ",.pdf,.doc,.dwg,.txt,.xls,.wmv,.exe,.ppt,";
	if (icons.indexOf(',' + e.href.substr(e.href.length - 4).toLowerCase() + ',') > -1)
	{
		if ($(e).children("img").length > 0)
		{
		}
		else if ($(e).parent().is("p") && ($(e).parent().html().substr(0,2).toLowerCase() == "<a"))
		{
			$(e).addClass(e.href.substr(e.href.length - 3).toLowerCase());
		}
		else if ($(e).parent().is("p") && !($(e).parent().html().substr(0,2).toLowerCase() == "<a"))
		{
		}
		else
		{
			$(e).addClass(e.href.substr(e.href.length - 3).toLowerCase());
		}
	}
}

function TellAFriend()
{
	var path = document.location.href;
	if (path.indexOf('?lastPagePath=') > 0) path = path.substring(0, path.indexOf('?lastPagePath='));
	var title = document.title;
	document.location.href='/Tell+a+friend?lastPagePath=' + escape(path) + '&lastPageTitle=' + escape(title);
}

function showJSIcons()
{
	$(".jsshow").removeClass("jsshow");
}

function setTopHeight()
{
	var imgHeight = $("#top img:first").height();
	$("#top").css("height", imgHeight);
	$("#topNavigation").css("top", imgHeight + 10);
	$("#pathNavigation").css("top", imgHeight + 54);
	$("#siteContainer").css("padding-top", imgHeight + 85);
	$("#siteContainerFront").css("padding-top", imgHeight + 53);
}

function lineTables()
{
	$("table.linedTable").each(function() {
		$(this).find("tr:odd").addClass("e");
	});
	$("table.linedTable tr").mouseover(function() {
		$(this).addClass("o");
	});
	$("table.linedTable tr").mouseout(function() {
		$(this).removeClass("o");
	});
}

function lineNavigation(ul, level)
{
	var subUL = $(ul).find("> li > ul");
	if (subUL.length > 0)
	{
		var subSubUL = $(subUL).find("> li > ul");
		if (subSubUL.length > 0)
			lineNavigation(subUL, level + 1);
		else
			if (level > 1) subUL.parent().addClass("lined");
	}
	$(ul).find("li.collapsed").removeClass("lined");
}

function setupSitemap()
{
	var avg = $("#topContent > ul.nav li").length / 4.0;
	if (avg > 0)
	{
		$("#topContent > ul.nav").before('<div id="sitemap"></div>');
		$("#sitemap").before('<ul class="navjs"></ul>');
		var ul = $("#topContent > ul.navjs");
		var cnt = 0;
		var ulCnt = 1;
		while ($("#topContent > ul.nav > li").length > 0)
		{
			ul.append($("#topContent > ul.nav > li:first-child"));
			cnt = $("#topContent > ul.navjs li").length;
			if (cnt > (avg * sitemapDistributionFactor) && ulCnt < 4)
			{
				ulCnt++;
				$("#sitemap").append(ul);
				if (ulCnt > 3)
					$("#sitemap").before('<ul class="navjs navjslast"></ul>');
				else
					$("#sitemap").before('<ul class="navjs"></ul>');
				ul = $("#topContent > ul.navjs");
			}
		}
		$("#sitemap").append(ul);
		$("#topContent > ul.nav").remove();
		$("#topContent ul.navjs").addClass("nav");
	}
}

function addNavigation()
{
	var extra = $("#extraNavigation > ul > li");
	$("#topNavigation ul.nav").prepend(extra.clone());
	$("#topContent ul.nav").prepend(extra);

	$("#topNavigation > ul.nav > li > ul > li > ul").remove();
}

function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}



// flash functions

function updatePopup(args)
{
	log("updatepopup called with: " + args);

	document["flashy2"].setPopup(args);
	
	var left = args[0] - 60;
	if (left < 0) left = 0;
	if (left > 642) left = 642;

/*
	var minX = 0;
	var top = $("#flashy1").offset().top - 192 - 44;
	var maxX = minX + 934 - 292;
	var left = minX;
	var myMouseX = mouseX - $("#flashy1").offset().left;

	if (args[1] > 3)
		left = maxX;
	else if (args[1] > 2)
		left += 38 + (172 * 3) - 60;
	else if (args[1] > 1)
		left += 38 + (172 * 2) - 60;
	else if (args[0] > 0)
		left += 38 + (172 * 1) - 60;
		log(3);
*/

// alert(top + " , " + mouseX);
/*
	if (myMouseX > left + 38 + (172 * 4))
		left = maxX;
	else if (myMouseX > left + 38 + (172 * 3))
		left += 38 + (172 * 3) - 60;
	else if (myMouseX > left + 38 + (172 * 2))
		left += 38 + (172 * 2) - 60;
	else if (myMouseX > left + 38 + (172 * 1))
		left += 38 + (172 * 1) - 60;
*/
	log("left: " + left);
	$("#flashPopup").css({top: '-192px'});
	$("#flashPopup").css({left: left});

}

function hidePopup(id)
{
	document["flashy2"].hidePopup(id);
	$("#flashPopup").css({ left: -5000});
}

