jQuery.fn.fadeToggle = function(speed, easing, callback) {
	return this.animate({ opacity: 'toggle' }, speed, easing, callback);
};
jQuery.fn.leftHeightEqualMainHeight = function() {
	return this.each(function() {
		var leftHeight = jquery("#LeftContent").height();
		var mainHeight = jquery(this).height();
		if (leftHeight < mainHeight)
			jquery("#SkjemaNav").height(mainHeight - 1);
	});
};
jQuery.fn.rightHeightEqualMainHeight = function() {
	return this.each(function() {
		var guidanceHeight = jquery("#Guidance").height();
		var mainHeight = jquery(this).height();
		jquery("#SkjemaLinks").css("min-height", mainHeight - guidanceHeight - 40);
	});
};
/* Input text replacer by Hein Haraldson Berg -- http://haraldson.ch/blog/jquery-input-text-replacer/ */
var InputTextReplacer = function(inputs) {
	if (jquery(inputs).size() > 0) {
		this.init(inputs);
	}
};
InputTextReplacer.prototype = {
	init: function(inputs) {
		var self = this;
		this.inputs = jquery(inputs).filter(':text, textarea');

		jquery(this.inputs).each(function(i, elem) {
			var label = jquery('label[for="' + jquery(this).attr('id') + '"]');
			jquery(label).hide();
			var labelText = jquery(label).text();

			jquery(this).val(labelText)
				.focus(function() {
					if (jquery(this).val() == labelText) {
						jquery(this).val('');
					}
				})
				.blur(function() {
					if (jquery(this).val() != labelText && jquery(this).val() == '') {
						jquery(this).val(labelText);
					}
				});
		});
	}
};

jquery(function() {
	jquery(".accordion.help-box > h4").click(function() {
		jquery(this).next(".acc-content").slideToggle();
	});

	if (typeof registerCancelEvent === "function") {
		registerCancelEvent();
	}

	// LeftContent and RightContent should be same height as MainContent
	jquery("#MainContent").leftHeightEqualMainHeight().rightHeightEqualMainHeight();

	// bugfix, jquery ajax calls
	// http://stackoverflow.com/questions/5364422/jquery-autocomplete-invalid-label-firebug-uncaught-syntaxerror-chrome
	jquery.ajaxSetup({
		jsonp: null,
		jsonpCallback: null
	});

	// remove no-js class from html
	jquery("html").removeClass("no-js");

	// workaround for ie8 og buttons som blir satt inn dynamisk
	jquery("html.ie8 #colorbox input").live("keypress", function(e) {
		if (e.which == 13) {
			e.preventDefault();
			jquery(this).closest("form").find("button.submit").trigger("click");
		}
	});

	// a.disabled skal aldri gjøre noe
	jquery("a.disabled").live("click", function() {
		return false;
	});

	/* Accordion */
	jquery("div.login-box").accordion({
		active: false,
		collapsible: true
	});
	/* Lagre url-hash ved klikk på overskrift i accordion */
	if (window.location.hash == "#newuser") {
		jquery("div.login-box").accordion("option", "active", 1);
	}

	if(window.location.hash == "#login") {
		jquery("div.login-box").accordion("option", "active", 0);
	}

	if (jquery('h3#login').length) {
		jquery('div#UserFunctions li.login a').click(function() {
			jquery("div.login-box").accordion("option", "active", 0);
		});
		jquery('div#UserFunctions li.newuser a').click(function() {
			jquery("div.login-box").accordion("option", "active", 1);
		});
	}

	//if only one choice is availible, expand it
	if(jquery('h3.ui-accordion-header').length == 1)
	{
		jquery("div.login-box").accordion("option", "active", 0);
	}

	jquery("div.accordion h3 a").click(function(event) {
		window.location.hash = this.hash;
	});

	/* Glemt passord */
	jquery('a.forgot-pwd').live("click", function() {
		jquery("#ForgotPwd").css({ height: "auto" });
		jquery("div.login-box div.acc-content").css({ height: "auto" });
		jquery('#ForgotPwd').toggle();
		return false;
	});

	/* hvis #forgotpwd finnes i url, vis Glemt passord */
	if (window.location.hash == "#forgotpwd") {
		jquery("#ForgotPwd").css({ height: "auto" });
		jquery("div.login-box div.acc-content").css({ height: "auto" });
		jquery("#ForgotPwd").show();
	}

	/* Input replacer */
	var K247TextReplacer = new InputTextReplacer('.ireplace');

	/* Login side, disable felt ved klikk på "MinID" */
	jquery('input.login-choice').live("click", function() {
		var parent = jquery(this).parents('div.form-wrap:eq(0)');
		var ul = parent.find('ul.form-table.disablable');
		if (jquery('#login-minid').is(':checked')) {
			ul.find('input').attr('disabled', 'disabled');
			parent.find('button').addClass('disabled').attr('disabled', 'disabled');
			;
			parent.addClass('disabled');
			ul.find(".acceptPrivacy input").removeAttr("disabled");
		} else {
			ul.find('input').removeAttr('disabled');
			parent.find('button').removeClass('disabled').removeAttr("disabled");
			;
			parent.removeClass('disabled');
		}
	});
	if (jquery("#login-minid").is(":checked"))
		jquery('#login-minid').trigger("click");

	/* Validering av felter */
	/* -------------------- */
	/* Valider at privacy checkbox er checked på MinID-lenke */

	/* Logg-inn side */
	jquery('#frmLogIn').validate({
		errorContainer: jquery('#frmLogIn div.error-msgs'),
		errorLabelContainer: jquery('ol', jquery('#frmLogIn div.error-msgs')),
		wrapper: 'li',
		onfocusout: false,
		onkeyup: false,
		invalidHandler: function() {
			jquery("#frmLogIn").css({ height: "auto" });
			jquery("div.login-box div.acc-content").css({ height: "auto" });
		},
		submitHandler: function() {
			LogIn(consts.consumerUsername, consts.requestQuerystring);
			jquery("#frmLogIn").css({ height: "auto" });
			jquery("div.login-box div.acc-content").css({ height: "auto" });
		}
	});

	jquery('#frmForgotten').validate({
		errorContainer: jquery('#frmForgotten div.error-msgs'),
		errorLabelContainer: jquery('ol', jquery('#frmForgotten div.error-msgs')),
		wrapper: 'li',
		onfocusout: false,
		onkeyup: false,
		invalidHandler: function() {
			jquery("#frmForgotten").css({ height: "auto" });
			jquery("div.login-box div.acc-content").css({ height: "auto" });
		},
		submitHandler: function() {
			ForgottenPassword(consts.consumerUsername, consts.requestQuerystring);
			jquery("#frmForgotten").css({ height: "auto" });
			jquery("div.login-box div.acc-content").css({ height: "auto" });
		}
	});

	jquery('#frmNewUser').validate({
		errorContainer: jquery('#frmNewUser div.error-msgs'),
		errorLabelContainer: jquery('ol', jquery('#frmNewUser div.error-msgs')),
		wrapper: 'li',
		onfocusout: false,
		onkeyup: false,
		rules: {
			newUser_RepeatPassword: {
				equalTo: "#newUser_Password"
			}
		},
		invalidHandler: function() {
			jquery("#frmNewUser").css({ height: "auto" });
			jquery("div.login-box div.acc-content").css({ height: "auto" });
		},
		submitHandler: function() {
			NewUser();
			jquery("#frmNewUser").css({ height: "auto" });
			jquery("div.login-box div.acc-content").css({ height: "auto" });
			return false;
		}
	});

	jquery('#frmGoTo').validate({
		errorContainer: jquery('#frmGoTo div.error-msgs'),
		errorLabelContainer: jquery('ol', jquery('#frmGoTo div.error-msgs')),
		wrapper: 'li',
		onfocusout: false,
		onkeyup: false,
		invalidHandler: function() {
			jquery("#frmGoTo").css({ height: "auto" });
			jquery("div.login-box div.acc-content").css({ height: "auto" });
		}
	});

	

	/* Change email validation */
	jquery('#frmEditProfile').validate({
		errorContainer: jquery('#frmEditProfile div.error-msgs'),
		errorLabelContainer: jquery('ol', jquery('#frmEditProfile div.error-msgs')),
		wrapper: 'li',
		onfocusout: false,
		onkeyup: false
	});

	// used to prevent caching 
	var randomNumber = Math.random();
	
	jquery("a#help").colorbox({
		href: function() {
			var url = jquery(this).attr("href") + "?number=" + randomNumber;
			return url + " div.container";
		},
		width: "600px",
		maxWidth: "90%",
		scrolling: true,
		onComplete: function () {
            jquery("div.help-box").accordion({
                heightStyle: "content",
                animate: 300,
                active: false,
                collapsible: true,
                header: "h4",
                activate: function (event, ui) {
                    var heightStyle = jquery("div.help-box").accordion("option", "heightStyle");
                }
            });
		}
	});

	jquery("a#emailReceipt").colorbox({
		href: function()
		{
			var url = jquery(this).attr("href");
			return url;
		},
		width: '500px',
		maxWidth: "90%",
		height: '250px',
		onComplete: function()
		{
			jquery('#frmEmailReceipt').validate({
				errorContainer: jquery('#frmEmailReceipt div.error-msgs'),
				errorLabelContainer: jquery('ol', jquery('#frmEmailReceipt div.error-msgs')),
				wrapper: 'li',
				onfocusout: false,
				onkeyup: false,
				submitHandler: function()
				{
					SendEmailReceipt(jquery("#refId").val());
				}
			});
		}
	});

	jquery('a.privacyLink').colorbox({
		href: function() {
			var url = jquery(this).attr("href") + "?number=" + randomNumber;
			return url + " div.container";
		},
		width: '700px',
		maxWidth: "90%",
		height: '650px',
		onComplete: function() {
			jquery("div.help-box").accordion({
				active: false,
				collapsible: true,
				header: "h4"
			});
		}
	});

	jquery('a.SubmittedByConsumerName').colorbox({
		href: function() {
			var url = jquery(this).attr("href");
			return url + " div.container";
		},
		width: '400px',
		maxWidth: "90%",
		height: '300px',
		onComplete: function() {
			jquery("div.help-box").accordion({
				active: false,
				collapsible: true,
				header: "h4"
			});
		}
	});

	if (typeof registerSaveEvent === "function") {
		registerSaveEvent();
	}
	
	jquery('a.new-window').live("click", function() {
		window.open(this.href);
		return false;
	});

	/* Skjul bunn-border på kategori liste på elementet før aktiv element */
	//jquery('ul.cat_list').find('li.active').prev().eq(0).css({ 'border': '0 none' });

	/* Vis/skjul informasjon om utfylling av skjema */
	jquery('div#InfoContainer .InfoTrigger').click(function() {
		jquery('div#InfoContainer h3.InfoTrigger').toggleClass('active');
		jquery('div#InfoContainer div.InfoContent').slideToggle(function()
		{
			//update iframe height after slide complete
			var parameterFromUrl = getParameterFromUrl('iframeurl', '', true);
			if(parameterFromUrl != false)
				iframeResizePipe(parameterFromUrl);
	    });

		return false;
	});

	/* tabs, mine saker */
	jquery('#cases-tabs').tabs();

	/* Delete user */
	jquery("#frmDeleteUser").addDeleteConfirmButton();

	/* vis/skjul hjelpetabs */
	jquery('#CtrlSkjema span.help').hide();
	jquery('#CtrlSkjema .guidance a').click(function()
	{
		jquery('#CtrlSkjema span.help').fadeOut("fast");
		jquery("#CtrlSkjema > table tbody tr").last().addClass("imlast");
		jquery("#CtrlSkjema > table tbody tr").last().prev().addClass("imlast");
		if(jquery("#CtrlSkjema > table tbody tr").length > 4) {
			if(jquery(this).parents("tr").hasClass("imlast"))
			{
				jquery(this).siblings("span.help").css({ top: "auto", bottom: 25 });
				jquery(this).siblings("span.help").children(".nud").addClass("nuddown");
				jquery(this).siblings("span.help").children(".nud").removeClass("nud");
			}
		}
		var helpContainer = jquery(this).siblings("span.help");
		if(helpContainer.is(":hidden"))
		{
			var myinternalElm = jquery(this).siblings("span.help");

			myinternalElm.fadeIn("fast");
			myinternalElm.css({ "padding-right": 30 });
			var myCloseButton = jquery("<a>");
			myCloseButton.attr("href", "#test");
			myCloseButton.html("&times;");
			myCloseButton.click(function(e)
			{
				e.preventDefault();
				myinternalElm.fadeOut("fast");
			});
			myCloseButton.css({
				float: "right",
				"text-decoration": "none",
				"font-size": "16px",
				"position": "absolute",
				"top": "8px",
				"right": "8px",
				"background": "#EEEEEE",
				width: 14,
				height: 18,
				"padding-left": 4,
				"box-shadow": "0px 0px 5px -3px #000"
			});
			myinternalElm.append(myCloseButton);
			jquery(document).click(function()
			{

				myinternalElm.fadeOut("fast");
				myinternalElm.click(function(e)
				{
					e.stopPropagation();
				});
			});
		}
		else
		{
			jquery(this).siblings("span.help").fadeOut("fast");
		}
		return false;
	});
	
	jquery("#leavedraftyes").unbind("click").click(function()
	{
		jquery.ajax({
			url: consts.siteroot + "/" + consts.consumerUsername + "/leavedraftyes?" + consts.requestQuerystring,
			type: "POST",
			dataType: "json",
			cache: false,
			success: function(data)
			{
				window.location.href = data.retururl;
			}
		});
	});
	
	jquery("#backtodraft").unbind("click").click(function()
	{
		var url = jquery('#PendingForm').val();
		window.location.href = url;
	});
	
	var iFrame = getParameterFromUrl("iframe", "", false);
	if(iFrame == 1)
	{
		jquery("body").css('background-color', 'transparent');
		jquery("body").css('overflow-y', 'no-display');
	}
	
	var delayedSaveUrlParameter = getParameterFromUrl("delayedsave", "", false);
	if(delayedSaveUrlParameter == 1)
	{
		jquery(".save > input").click();
	}
});

function RedirectWindowTop(url)
{
	window.top.location.href = url;
}

// Pipes the data to the parent frame through the helpframe
function iframeResizePipe(iframeurl)
{
    var mainRegionHeight = jQuery("#MainRegion").height() + 15;
    var pipe = document.getElementById('helpframe');
	//when src is set, IframeResizer.html on parent page is loaded, and the onload="parentIframeResize()" is triggered
	pipe.src = iframeurl + '?height=' + mainRegionHeight; //+'&cacheb='+Math.random();
}

// Pipes the data to the parent frame through the helpframe
// Used to open a read more link (documentUrl) in new browser windowwhen iframe viewer
function openDocumentPipe(iframeurl, documentUrl)
{
	var mainRegionHeight = jQuery("#MainRegion").height() + 15;
	var pipe = document.getElementById('helpframe');
	//Yes, iframeurl is IframeResizer.html... 
	pipe.src = iframeurl + '?height=' + mainRegionHeight + '&documentUrl=' + documentUrl;
}

// Get the value of a parameters either from current URL or static URL
function getParameterFromUrl(parameterName, staticUrl, decode)
{
	var currLocation = (staticUrl.length)? staticUrl : window.location.search;
	var parameterArray = "";
	if(currLocation)
		parameterArray = currLocation.split("?")[1].split("&");
	
	if(parameterArray.length > 0)
	{
		for(var i = 0; i < parameterArray.length; i++)
		{
			var parameter = parameterArray[i].split("=");
			if(parameter[0] == parameterName)
				return (decode) ? decodeURIComponent(parameter[1]) : parameter[1];
		}
	}

	return false;
}

function DeleteSavedInstanceConfirm(refid, consumer)
{
	var jqColorConfirm = jquery("#color-confirm-saved");

	jquery.colorbox({
		inline: true,
		href: "#color-confirm-saved"
	});
	
	jquery("button.yep", jqColorConfirm).unbind("click").click(function()
	{
		DeleteSavedInstance(refid, consumer);
		jquery('#cboxClose').click();
	});
	jquery("button.nope", jqColorConfirm).unbind("click").click(function()
	{
		jquery('#cboxClose').click();
	});
	
	return false;
}

function DeleteSavedInstance(refid, consumer)
{
	var url = consts.siteroot + "/" + consumer + "/saker/deleteSaved/";

	jquery.post(url,
	{
		refid: refid
	},
	function(data)
	{
		jquery('#SavedDrafts').html(data);
	});

	return false;
}

function DeleteSubmittedInstanceConfirm(refid, consumer)
{
	var jqColorConfirm = jquery("#color-confirm-submitted");

	jquery.colorbox({
		inline: true,
		href: "#color-confirm-submitted"
	});

	jquery("button.yep", jqColorConfirm).unbind("click").click(function()
	{
		DeleteSubmittedInstance(refid, consumer);
		jquery('#cboxClose').click();
	});
	jquery("button.nope", jqColorConfirm).unbind("click").click(function()
	{
		jquery('#cboxClose').click();
	});

	return false;
}

function DeleteSubmittedInstance(refid, consumer)
{
	var url = consts.siteroot + "/" + consumer + "/saker/deleteSubmitted/";
	
	jquery.post(url,
	{
		refid: refid
	},
	function(data)
	{
		jquery('#SentForms').html(data);
	});
	
	return false;
}

function ChangeListViewSaved()
{
	var url = consts.siteroot + "/" + consts.consumerUsername + "/saker/ChangeListViewSaved/";
	
	jquery.post(url,
		function(data)
		{
			jquery('#SavedDrafts').html(data);
		});
	return false;
}

function ChangeListViewSubmitted()
{
	var url = consts.siteroot + "/" + consts.consumerUsername + "/saker/ChangeListViewSubmitted/";

	jquery.post(url,
		function(data)
		{
			jquery('#SentForms').html(data);
		});
	return false;
}

function LogIn(consumerUsername, qrystring)
{
	var url;
	if (jquery("#login-minid").is(":checked")) {
		location = consts.siteroot + "/" + consumerUsername + "/bruker/logginnminid?" + qrystring;
		return;
	}
	if (qrystring)
		url = consts.siteroot + "/" + consumerUsername + "/bruker/logginn?" + qrystring;
	else
		url = consts.siteroot + "/" + consumerUsername + "/bruker/logginn?";

	jquery.post(
		url,
		{ userEmail: jquery("#user_Email").val(), userPassword: jquery("#user_Password").val(), acceptPrivacy: jquery('#acceptPrivacy').attr('checked') },
		function(data)
		{
			if(data == null)
			{
				alert("En feil har oppstått. Data er null.");
			}
			else
			{
				if(data.url)
				{
					window.location.href = data.url;
				}
				else if(data.errorMessage)
				{
					var errorLi = jquery("#DivLogin div.error-msgs ol li.xhr-error");
					if(errorLi.length)
					{
						jquery("#DivLogin div.error-msgs ol").show().parent().show();
						errorLi.html(data.errorMessage);
					}
					else
					{
						jquery("#DivLogin div.error-msgs ol").show().append("<li class=\"xhr-error\">" + data.errorMessage + "</li>").parent().show();
					}
				}
				else
				{
					alert("En feil har oppstått. Både data.url og data.html er null.");
				}
			}
		},
		"json"
	);
}

function NewUser()
{
	var url = consts.siteroot + "/" + consts.consumerUsername + "/bruker/ny?" + consts.requestQuerystring;
	jquery.post(
		url,
		{ userEmail: jquery("#newUser_Email").val(), userPassword: jquery("#newUser_Password").val(), userRepeatPassword: jquery("#newUser_RepeatPassword").val(), acceptPrivacy: jquery('#newUser_acceptPrivacy').attr('checked')},
		function(data)
		{
			if(data == null)
			{
				alert("En feil har oppstått. Data er null.");
			}
			else
			{
				if(data.url)
				{
					window.location.href = data.url;
				}
				else if(data.errorMessage)
				{
					var errorLi = jquery("#DivNewUser div.error-msgs ol li.xhr-error");
					if(errorLi.length)
					{
						jquery("#DivNewUser div.error-msgs ol").show().parent().show();
						errorLi.html(data.errorMessage);
					}
					else
					{
						jquery("#DivNewUser div.error-msgs ol").show().append("<li class=\"xhr-error\">" + data.errorMessage + "</li>").parent().show();
					}
				}
				else
				{
					alert("En feil har oppstått. Både data.url og data.html er null.");
				}
			}
		},
		"json"
	);
}

function ForgottenPassword(consumerUsername, qrystring) {
	var url = consts.siteroot + "/" + consumerUsername + "/bruker/glemtpassord?" + qrystring;

	jquery.post(
		url,
		{ email: jquery("#Email_EmailAddress").val() },
		function(data)
		{
			if(data == null)
			{
				alert("En feil har oppstått. Data er null.");
			}
			else
			{
				if(data.ForgottenEmailAddress)
				{
					var infoLi = jquery("#ForgotPwd div.info-msgs ol li.xhr-error");
					if(infoLi.length)
					{
						jquery("#ForgotPwd div.info-msgs ol").show().parent().show();
						infoLi.html(data.ForgottenEmailAddress);
					}
					else
					{
						jquery("#ForgotPwd div.info-msgs ol").show().append("<li class=\"xhr-error\">" + data.ForgottenEmailAddress + "</li>").parent().show();
					}
				}
				else if(data.errorMessage)
				{
					var errorLi = jquery("#ForgotPwd div.error-msgs ol li.xhr-error");
					if(errorLi.length)
					{
						jquery("#ForgotPwd div.error-msgs ol").show().parent().show();
						errorLi.html(data.errorMessage);
					}
					else
					{
						jquery("#ForgotPwd div.error-msgs ol").show().append("<li class=\"xhr-error\">" + data.errorMessage + "</li>").parent().show();
					}
				}
				else
				{
					alert("En feil har oppstått. data.ForgottenEmailAddress er null.");
				}
			}
		},
		"json"
	);
}

function SendEmailReceipt(referencenumber)
{
	var url = consts.siteroot + "/" + consts.consumerUsername + "/kvittering/" + referencenumber + "/sendemail";

	jquery.post(url,
		{ emailAddress: jquery("#email").val() },
		function(data)
		{
			jquery("#color-confirm-emailreceipt div.info-msgs ol").empty();
			jquery("#color-confirm-emailreceipt div.error-msgs ol").empty();
			if(data.errorMessage)
			{
				jquery("#color-confirm-emailreceipt div.info-msgs").hide();
				jquery("#color-confirm-emailreceipt div.error-msgs ol").show().append("<li class=\"xhr-error\">" + data.errorMessage + "</li>").parent().show();
			}
			else if(data.EmailSentOk)
			{
				jquery("#btnEmailReceiptSend").removeClass("success");

				jquery("#email").focus(
					function()
					{
						jquery("#btnEmailReceiptSend").addClass("success");
					});

				jquery("#color-confirm-emailreceipt div.info-msgs ol").show().append("<li class=\"xhr-error\">" + data.EmailSentOk + "</li>").parent().show();
			}
		});
	
	return false;
}

jQuery.fn.addDeleteConfirmButton = function() {
	jQThis = jquery(this);
	jQSubmitButton = jquery("button[type='submit']", jQThis);
	return this.each(function() {
		jQSubmitButton.click(function() {
			jquery("#DeleteUserFieldset").toggle();
			jquery("#ConfirmUserDelete").toggle();
			return false;
		});

		jquery("#ConfirmUserDelete a.decline").click(function() {
			jquery("#DeleteUserFieldset").toggle();
			jquery("#ConfirmUserDelete").toggle();
			return false;
		});

		jquery("#ConfirmUserDelete a.confirm-delete").click(function(e) {
			e.preventDefault();
			jQThis.submit();
		});
	});
};
jquery(document).ready(function() {
    if (navigator.userAgent.match(/msie/i)) {
        jquery("#SkjemaSection #MainContent").css("min-width", "518px");
        jquery("#SkjemaSection").css("widht", "100%");
        jquery("#SkjemaSection #LeftContent").css("width", "186px");
        jquery("#SkjemaSection #RightContent").css("with", "186px");
        jquery("#PageHeader #Header .container_12 .grid_12").css("width", "100%");
    }
    else {
        if (jquery.browser.msie) {
            jquery("#SkjemaSection #MainContent").css("min-width", "518px");
            jquery("#SkjemaSection").css("widht", "100%");
            jquery("#SkjemaSection #LeftContent").css("width", "186px");
            jquery("#SkjemaSection #RightContent").css("with", "186px");
            jquery("#PageHeader #Header .container_12 .grid_12").css("width", "100%");
        }
    }
});

function registerCancelEvent()
{
    jquery("li.cancel input").click(function (e) {
        //cancel event
        if(jquery("li.cancel").hasClass("cancelClickEvent"))
            return false;
        // if cancel button is pressed
        e.preventDefault();
        // cache confirm box (hidden in footer.vm)
        jqColorConfirm = jquery("#color-confirm");
        // create colorbox
        jquery.colorbox({
            inline: true,
            href: "#color-confirm",
            onComplete: function () {
                jquery('#cboxLoadedContent').addClass("cboxLoadedContent_Confirm");
            }
        });
        // if save yes click, trigger save button
        jquery("button.yep", jqColorConfirm).unbind("click").click(function () {
            jquery("li.save input").click();
            //if a message is shown, close the colorbox
            if(jquery('div').hasClass('message'))
                jquery('#cboxClose').click();
        });

        var aborturl = "";
        var aborturlParameter = getParameterFromUrl("aborturl", "", true);
        if(aborturlParameter != false)
            aborturl = "&aborturl=" + aborturlParameter;

        // else, submit form
        jquery("button.nope", jqColorConfirm).unbind("click").click(function () {
            jquery.ajax({
                url: location.pathname + "/cancel/?action=cancel&shortname=" + consts["formId"] + "&version=" + consts["version"] + aborturl,
                dataType: "json",
                type: "POST",
                success: function (data) {
                    if(data.returnUrl) {
                        if(data.windowTopLocation)
                            window.top.location.href = data.returnUrl;
                        else
                            window.location.href = data.returnUrl;
                    }
                },
                error: function (data) {
                    if(jquery(data.responseText).is("div") && jquery(data.responseText).hasClass("message")) {
                        SetMessageInMainContentArea(data.responseText);
                        jquery('#cboxClose').click();
                    }
                }
            });
        });
    });
}

function registerSaveEvent() {
    //If url parameter loginurl is set AND user not logged in
    //handle login by EpiServer, else open modal login window
    var loginurl = getParameterFromUrl("loginurl", "", true);

    if(loginurl != false && jquery('li.save').hasClass('UserNotLoggedIn')) {
        jquery('li.save').live("click", function () {
            RedirectWindowTop(loginurl);
            return false;
        });
    }
    else {
        // if not logged in while editing form, and tries to save, open modal below
        jquery('li.UserNotLoggedIn input, #UserFunctions li.UserNotLoggedIn a').colorbox({
            href: "bruker?retur=" + consts.siteroot + "/" + consts.consumerUsername + "/" + consts.formId + "/savedocument&popup=true&shortname=" + consts.formId + " div.container",
            width: '600px',
            maxWidth: "90%",
            height: '400px',
            overlayClose: false,
            onComplete: function () {
                var activeAccordion = 0;
                if(jquery.colorbox.element().parent().hasClass("newuser"))
                    activeAccordion = 1;
                jquery("div.login-box").accordion({
                    heightStyle: "content",
                    active: activeAccordion,
                    collapsible: true,
                    activate: function (event, ui) {
                        jquery.colorbox.resize();
                    }
                });
                jquery('#frmLogIn').validate({
                    errorContainer: jquery('#frmLogIn div.error-msgs'),
                    errorLabelContainer: jquery('ol', jquery('#frmLogIn div.error-msgs')),
                    wrapper: 'li',
                    onfocusout: false,
                    onkeyup: false,
                    invalidHandler: function () {
                        jquery("#frmLogIn").css({ height: "auto" });
                        jquery("div.login-box div.acc-content").css({ height: "auto" });
                    },
                    submitHandler: function () {
                        LogIn(consts.consumerUsername, consts.requestQuerystring);
                        jquery("#frmLogIn").css({ height: "auto" });
                        jquery("div.login-box div.acc-content").css({ height: "auto" });
                    }
                });
                jquery('#frmForgotten').validate({
                    errorContainer: jquery('#frmForgotten div.error-msgs'),
                    errorLabelContainer: jquery('ol', jquery('#frmForgotten div.error-msgs')),
                    wrapper: 'li',
                    onfocusout: false,
                    onkeyup: false,
                    invalidHandler: function () {
                        jquery("#frmForgotten").css({ height: "auto" });
                        jquery("div.login-box div.acc-content").css({ height: "auto" });
                    },
                    submitHandler: function () {
                        ForgottenPassword(consts.consumerUsername, consts.requestQuerystring);
                        jquery("#frmForgotten").css({ height: "auto" });
                        jquery("div.login-box div.acc-content").css({ height: "auto" });
                    }
                });
                jquery('#frmNewUser').validate({
                    errorContainer: jquery('#frmNewUser div.error-msgs'),
                    errorLabelContainer: jquery('ol', jquery('#frmNewUser div.error-msgs')),
                    wrapper: 'li',
                    onfocusout: false,
                    onkeyup: false,
                    rules: {
                        newUser_RepeatPassword: {
                            equalTo: "#newUser_Password"
                        }
                    },
                    invalidHandler: function () {
                        jquery("#frmNewUser").css({ height: "auto" });
                        jquery("div.login-box div.acc-content").css({ height: "auto" });
                    },
                    submitHandler: function () {
                        NewUser();
                        jquery("#frmNewUser").css({ height: "auto" });
                        jquery("div.login-box div.acc-content").css({ height: "auto" });
                        return false;
                    }
                });
                jquery('#colorbox a.privacyLink').bind("click", function () {
                    window.open(this.href);
                    return false;
                });
            }
        });
    }
}