function navigate(location) {
	var form = document.forms.viewer;
	form.location.value = location;
	form.submit();
	return false;
}

function setFlowrule(flowrule) {
	var form = document.forms.viewer;
	form.flowrule.value = flowrule;
	return false;
}

//submits the DIBS pay-form
function pay_dibs() {
	var form = document.forms.dibs_pay;
	form.submit();
	return false;
}

function refresh(doneFunction) {
	jquery("#overlay").show();
	
	saveModel();

	var buttonHtml;
	var documentMapHtml;

	jquery
		.when(
			jquery.ajax({
				type: 'POST',
				url: location.pathname + "/NavigatorButtons",
				success: function(data) {
					if(jquery(data).is("div") && jquery(data).hasClass("message"))
					{
						SetMessageInMainContentArea(data);
						return;
					}
					buttonHtml = data;
				},
				async: true,
			}),
			jquery.ajax({
				type: 'POST',
				url: location.pathname + "/DocumentMap",
				success: function (data) {
					if(jquery(data).is("div") && jquery(data).hasClass("message"))
					{
						SetMessageInMainContentArea(data);
						return;
					}
					documentMapHtml = data;
				},
				async: true,
			}))
		.then(function () {
			if(buttonHtml != null) {
				jquery('.SkjemaBottomNav').replaceWith(buttonHtml);
				if (typeof registerCancelEvent === "function") {
					registerCancelEvent();
				}
				if (typeof registerSaveEvent === "function") {
					registerSaveEvent();
				}
			}
			if(documentMapHtml != null)
				jquery('#SkjemaNav').html(documentMapHtml);
			
			jquery("#overlay").hide();
		})
        .done(function () {
            // Added to support functions for mobileview
            if(doneFunction != null){
                doneFunction();
            }
        });
	
	jQuery("#SkjemaNav").height('auto');
}

function saveModel() {
	jquery.ajax({
		type: 'POST',
		url: location.pathname + "/SaveModel",
		data: jquery("#viewer").serialize(),
		success: function(response)
		{
			if(jquery(response).is("div") && jquery(response).hasClass("message"))
			{
				jquery("li.cancel").addClass("cancelClickEvent");
				SetMessageInMainContentArea(response);
				return false;
			}
		},
		error: function (request, status, error) {
			alert(request.responseText);
		},
		async: false
	});
}

//If Datagrid, the executable is placed in the grid (containerId = rowId). Not always?
//If Panel, the executable is placed on panel or on section, input/output fields are in panel or on section.
//executableId: The id of the prefill executable.
//inputIds: The id(s) (outer guid) of the input fields.
//containerId: The container of the prefill executable.
function prefill(executableId, inputIds, containerId) {
    jquery(document).ready(function () {
		jquery.each(inputIds, function(i, inputId) {
			var input;
			if (containerId != "")
				input = containerId + "_" + inputId;
			else
				input = inputId;

			jquery("#" + input).live("change", function(event) {
				var inputValue = jquery(this).val();
				if (jquery(this).attr('type') == 'checkbox')
					if (!this.checked)
						inputValue = "";

				//If input is table, this is a value transfer from summary row in grid
				//Get id and value in last input in footerRow
				if (jquery("#" + input).is('table')) {
					jquery("#" + input + " > tfoot > tr > td > div > input").each(function() {
						inputId = this.id;
						inputValue = jquery("#" + this.id).val();
					});
				}

				inputValue = encodeURI(inputValue);

				jquery.ajax(
					{
						url: location.pathname + "/UpdateDependentField?id=" + executableId + "&containerId=" + containerId + "&" + inputId + "=" + inputValue,
						dataType: 'json',
						async: false,
						success: function(data) {
							if (data != null) {
								jquery.each(data, function(key) {
									//Empty dropdownlist
									if (key.indexOf("|") != -1)
										jquery("#" + key.substring(0, key.indexOf("|"))).empty();
								});
								jquery.each(data, function(key, value) {
									//Update dropdownlist with new items
									if (key.indexOf("|") != -1) {
										jquery("#" + key.substring(0, key.indexOf("|")))
											.append(jquery('<option>', { value: key.substring(key.indexOf("|") + 1) })
												.text(value));
									}
								});
							}
						},
						error: function(request) {
							if(jquery(request.responseText).is("div") && jquery(request.responseText).hasClass("message"))
								SetMessageInMainContentArea(request.responseText);
							return;
						}
					});

				function clearErrorAndSetOutput(data) {
					jquery.each(data.Inputs, function() {
						var innerId = this.Outer;
						var outerId = this.Inner;

						if (this.Container != null) {
							innerId = this.Container + "_" + innerId;
							outerId = this.Container + "_" + outerId;
						}

						//fjern feilmelding i fullversjon
						jquery("label[for='" + innerId + "']").closest('li').remove(); //fjern tidligere feilmelding
						//fjern feilmelding i mobilversjon
						var idToRemove = "#" + innerId + "-error";
						jquery(idToRemove).remove(); //fjern tidligere feilmelding
						jquery('#' + outerId).removeClass("error"); //fjern tidligere satt error class på input
					});

					if(typeof data.Values !== 'undefined')
					{
						jquery.each(data.Values, function (key, value)
						{
							if(jquery("#" + key).is("span"))
							{
								//Datalabel
								jquery('#' + key).text(value);
							}
							//Update choice with new items
							else if(key.indexOf("_options") != -1)
							{
								var fieldId = key.substring(0, key.indexOf("_options"));

								if(fieldId.indexOf("_") != -1)
								{
									//ta høyde for at option ligger i panel
									fieldId = fieldId.substring(fieldId.indexOf("_") + 1);
								}

								renderField(fieldId, "");
							}
							else
							{
								jquery('#' + key).val(value);
								var lockField = false;

								jquery.each(data.Locks, function (lockKey, lockValue)
								{
									if(lockValue === key)
									{
										lockField = true;
										return false;
									}
								});

								if(lockField === true)
								{
									jquery('#' + key).attr('disabled', 'disabled');
									jquery('#' + key).attr('readonly', 'readonly');
								}
								else
								{
									jquery('#' + key).removeAttr('disabled');
									jquery('#' + key).removeAttr('readonly');
								}
							}

							jquery("#" + key).parent().trigger("onchange");
						});
					}

					if(data.Message != null && data.Message == "HasPageCondition")
					{
                        refresh();
					};
				}

				jquery.ajax(
					{
						url: location.pathname + "/values?id=" + executableId + "&containerId=" + containerId + "&" + inputId + "=" + inputValue,
						dataType: 'json',
						async: true,
						success: function(data, status, request) {
							//alert(request.responseText);

							jquery("li[id='" + executableId + "']").remove(); //fjern tidligere exception melding

							if (data != null) {
								clearErrorAndSetOutput(data);
							}
						},
						error: function(request, status, error) {
							//alert(request.responseText);

							data = jquery.parseJSON(request.responseText);

							jquery("li[id='" + executableId + "']").remove(); //fjern tidligere exception melding

							if (data != null) {
								if (data.Exception != null) {
									var listItem = '<li id="' + executableId + '" class="error"><label class="error-link">' + data.Exception + '</label></li>';
									jquery('#guidanceList').append(listItem); //legg til ny feilmelding

									return;
								}

								clearErrorAndSetOutput(data);

								jquery.each(data.Errors, function() {
									var innerId = this.Outer;
									var outerId = this.Inner;

									if (this.Container != null) {
										innerId = this.Container + "_" + innerId;
										outerId = this.Container + "_" + outerId;
									}

									jquery('#' + outerId).addClass("error"); //error class
									//jquery('#' + innerId).focus(); //sett focus i feil feltet

									var listItem = '<li class="error"><label for="' + innerId + '" class="error-link">' + this.Message + '</label></li>'; //opprett feilmelding

									jquery('#guidanceList').append(listItem); //legg til ny feilmelding

									//legg til feilmelding for mobil visning
									var mobileError = "<div id='" + executableId + "-error' class='felt-feilmelding'>" + data.Errors[0].Message + "</div>";
									var selector = "#" + executableId;
									jquery(selector).parent().append(mobileError);
								});
							}
						}
					});
			});
		});
	});
}

function addRow(gridId, maxRows, position)
{
	jquery("#" + gridId + " > tfoot a").addClass("disabled");

	var strPosition = "";
	if(position === 0)
		strPosition = "&position=" + position;

	jquery.ajax({
		type: 'POST',
		url: location.pathname + "/addrow?gridId=" + gridId + strPosition,
		async: false,
		success: function(row) {
			//result is not a row, but a message (probably session timeout)
			if(jquery(row).is("div") && jquery(row).hasClass("message"))
			{
				SetMessageInMainContentArea(row);
				return;
			}

			var focusFieldId = "";
			var numberOfTabIndexInNewRow = 0;

			//Get highest tabindex in new row
			jquery(row).find("input,select,textarea").each(function()
			{
				if(jquery(this).attr("tabindex"))
				{
					//Get focus field: id of the first input control in new row
					if(focusFieldId.length == 0)
						focusFieldId = jquery(this).attr("id");
				
					numberOfTabIndexInNewRow++;
				}
			});

			var highestTabIndexInOrigGrid = 0;

			//Get highest tabindex in orig grid (before row is added)
			jquery("#" + gridId).find("input,select,textarea").each(function() {
				if (parseInt(jquery(this).attr("tabindex")) > highestTabIndexInOrigGrid)
					highestTabIndexInOrigGrid = parseInt(jquery(this).attr("tabindex"));
			});

			var lowestTabIndexInOrigGrid = highestTabIndexInOrigGrid;

			//Get lowest tabindex in orig grid (before row is added)
			jquery("#" + gridId).find("input,select,textarea").each(function()
			{
				if(jquery(this).attr("tabindex") && parseInt(jquery(this).attr("tabindex")) > 0 && parseInt(jquery(this).attr("tabindex")) < lowestTabIndexInOrigGrid)
					lowestTabIndexInOrigGrid = parseInt(jquery(this).attr("tabindex"));
			});

			//Update tabindex on controls with higher tabindex than controls in orig datagrid
			jquery('input,select,textarea').each(function()
			{
				var jqueryinput = jquery(this);
				var tabIndex = parseInt(jqueryinput.attr("tabindex"));
				if(tabIndex > highestTabIndexInOrigGrid)
					jqueryinput.attr("tabindex", tabIndex + numberOfTabIndexInNewRow);
			});

			//Add the row to datagrid
			if(position === 0)
			{
				jquery("#" + gridId + " > tbody").prepend(row);

				var rowCounter = 1;

				//Update row number on all rows
				jquery("#" + gridId + " > tbody > tr > td[id^='RowNumber_']").each(function()
				{
					jquery(this).text(rowCounter);
					rowCounter++;
				});
			}
			else
				jquery("#" + gridId + " > tbody").append(row);

			var rowId = jquery(row).attr("id");
			var newRow = jquery("tr[id='" + rowId + "']");
			
			//Enable/disable move up/down arrows
			if(position === 0)
			{
				var nextRow = newRow.next();
				nextRow.find("a[id^='moveUpRow']").attr('class', 'moveUpRow');
			}
			else
			{
				var previousRow = newRow.prev();
				previousRow.find("a[id^='moveDownRow']").attr('class', 'moveDownRow');
			}

			//Update tabindex on controls in datagrid
			var i = 0;
			jquery("#" + gridId).find("input,select,textarea").each(function()
			{
				var input = jquery(this);
				if(input.attr("tabindex"))
					input.attr("tabindex", parseInt(lowestTabIndexInOrigGrid) + i++);
			});
			
			var rowCount = jquery("#" + gridId + " > tbody > tr").length;
        
			//the add button is active, should we disable it?
			if (rowCount >= maxRows)
				jquery("#" + gridId + " > tfoot a").addClass("disabled");
			else
				jquery("#" + gridId + " > tfoot a").removeClass("disabled");

			//after a row is added, we can always delete it, check if it is disabled first
			jquery("#" + gridId + " > tbody a").removeClass("disabled");

			//invoke so that focus event is registered for the newly added row
			setFocusMessages();

			//Set focus
			jquery('#' + focusFieldId).focus();
		}
	});

	jquery.post(location.pathname + "/AddCalculationScriptForFooterRow?gridId=" + gridId, function(updatedCalculationScript) {
		if (updatedCalculationScript.length > 0) {
			//Remove old calculation script
			jquery("#" + gridId + " > tfoot > tr > script").remove();

			//Add updated calculation script
			jquery("#" + gridId + " > tfoot > tr").append(updatedCalculationScript);
		}
	});

	setSkjemaContainerHeight();

	var parameterFromUrl = getParameterFromUrl('iframeurl', '', true);
	if (parameterFromUrl != false)
		iframeResizePipe(parameterFromUrl);

	return false;
}

/* _clears_ values from the row */
function clearRow(gridId, rowId) {
	var rowToDelete = jquery("#" + rowId);

	jquery.ajax({
		type: 'POST',
		url: location.pathname + "/clearrow?gridId=" + gridId + "&rowId=" + rowId,
		async: false,
		success: function(row) {
			rowToDelete.replaceWith(row);
		}
	});
}

function deleteRow(gridId, rowId, minRows) {
	var inputValues = new Array();
	var rowToDelete = jquery("#" + rowId);
	var previousRow = rowToDelete.prev();
	var nextRow = rowToDelete.next();
	var isLastRow = nextRow.length == 0;
	var isFirstRow = previousRow.length == 0;

	//For each input in row
	jquery("#" + rowId + " > td > div > input[id*=" + rowId + "]:visible").each(function()
	{
		//Get the column index
		var inputColumnIndex = jquery(this).parent().parent().index();

		//Insert value from input field into array 
		inputValues[inputColumnIndex] = jquery(this).val();
	});

	jquery.post(location.pathname + "/deleterow?gridId=" + gridId + "&rowId=" + rowId, function()
	{
		rowToDelete.remove();
		
		//Get row to set focus to
		var focusRow;

		if(nextRow.length > 0)
			focusRow = nextRow;
		else
			focusRow = previousRow;

		//Set focus to first input in focus row
		focusRow.find("input,select,textarea").first().focus();

		if(isFirstRow)
			nextRow.find("a[id^='moveUpRow']").attr('class', 'moveUpRowDisabled');
		else if(isLastRow)
			previousRow.find("a[id^='moveDownRow']").attr('class', 'moveDownRowDisabled');

		//if the add button is disabled, enable it (after deleting a row we can always add a new one)
		jquery("#" + gridId + " > tfoot a").removeClass("disabled");

		//remove button is enabled, disable it if rowcount == minrows
		var rowCount = jquery("#" + gridId + " > tbody > tr").length;

		if (rowCount == minRows) jquery("#" + gridId + " > tbody a").not(".clearRow").addClass("disabled");

		var rowCounter = 1;
		
		//Update row number on each row
		jquery("#" + gridId + " > tbody > tr > td[id^='RowNumber_']").each(function()
		{
			jquery(this).text(rowCounter);
			rowCounter++;
		});

		//Update footer calculations
		jquery("#" + gridId + " > tfoot > tr > td > div > input").each(function()
		{
			var outputIndex = jquery(this).parent().parent().index();
			var footerFieldId = jquery(this).attr("id");
			var footerFieldValue = jquery('#' + footerFieldId).val();
			var deletedValue = inputValues[outputIndex];

			jquery('#' + footerFieldId).val(footerFieldValue - deletedValue);
		});
	});
	return false;
}

function moveUpRow(gridId, rowId)
{
	var currentRow = jquery("tr[id='" + rowId + "']");
	var previousRow = currentRow.prev();
	var nextRow = currentRow.next();
	var rowIndex = currentRow.index();
	var isLastRow = nextRow.length == 0;

	jquery.post(location.pathname + "/MoveUpRow?gridId=" + gridId + "&rowIndex=" + rowIndex, function()
	{
		previousRow.insertAfter(currentRow);
		
		var rowCounter = 1;

		//Update row number on each row
		jquery("#" + gridId + " > tbody > tr > td[id^='RowNumber_']").each(function()
		{
			jquery(this).text(rowCounter);
			rowCounter++;
		});
		
		//Swap classes
		if(rowIndex == 1)
		{
			previousRow.find("a[id^='moveUpRow']").attr('class', 'moveUpRow');
			currentRow.find("a[id^='moveUpRow']").attr('class', 'moveUpRowDisabled');
		}

		if(isLastRow)
		{
			previousRow.find("a[id^='moveDownRow']").attr('class', 'moveDownRowDisabled');
			currentRow.find("a[id^='moveDownRow']").attr('class', 'moveDownRow');
		}

		//set focus to the first input in the row moving up
		currentRow.find("input,select,textarea").first().focus();
	});
	return false;
}

function moveDownRow(gridId, rowId)
{
	var currentRow = jquery("tr[id='" + rowId + "']");
	var nextRow = currentRow.next();
	var rowIndex = currentRow.index();
	var isNextRowLastRow = nextRow.next().length == 0;

	jquery.post(location.pathname + "/MoveDownRow?gridId=" + gridId + "&rowIndex=" + rowIndex, function()
	{
		currentRow.insertAfter(nextRow);

		var rowCounter = 1;

		//Update row number on each row
		jquery("#" + gridId + " > tbody > tr > td[id^='RowNumber_']").each(function()
		{
			jquery(this).text(rowCounter);
			rowCounter++;
		});

		//Swap classes
		if(rowIndex == 0)
		{
			nextRow.find("a[id^='moveUpRow']").attr('class', 'moveUpRowDisabled');
			currentRow.find("a[id^='moveUpRow']").attr('class', 'moveUpRow');
		}

		if(isNextRowLastRow)
		{
			nextRow.find("a[id^='moveDownRow']").attr('class', 'moveDownRow');
			currentRow.find("a[id^='moveDownRow']").attr('class', 'moveDownRowDisabled');
		}

		//set focus to the first input in the row moving down
		currentRow.find("input,select,textarea").first().focus();
	});
	return false;
}

//Hide column header if there is no visible field in column (conditions evaluated to false).
//Show column header if one or more fields are visible in column.
function hideTableColumnHeader(outputField)
{
	var tdCell = jquery(outputField).closest('td');
	var cellIndex = tdCell[0].cellIndex;
	var th = jquery(tdCell).closest('table').find('th').eq(cellIndex);
	var antallSynligeInputIKolonne = 0;

	jquery(tdCell).closest('table').find('tbody > tr').each(function ()
	{
		var cell = this.cells[cellIndex];
		var antallSynligeInputICelle = jquery(cell).find('input:visible').length;
		if (antallSynligeInputICelle > 0)
			antallSynligeInputIKolonne = antallSynligeInputIKolonne + antallSynligeInputICelle;
	});

	if(antallSynligeInputIKolonne > 0)
		jquery(th).find(">:first-child").css('display', 'inline');
	else
		jquery(th).find(">:first-child").css('display', 'none');

	return;
}

function addPanelRow(panelId, maxRows) {
	var jqueryCurrentTable = jquery("table[data-id = '" + panelId + "']");
	jquery("a.addPanelRow", jqueryCurrentTable).addClass("disabled");
	jquery.post(location.pathname + "/addpanelrow?panelId=" + panelId, function(panelRow) {
		var highestTabIndexInRow = 0;
		var focusFieldId = "";

		//Get highest tabindex in new row
		jquery(panelRow).find("input,select,textarea").each(function() {
			if (parseInt(jquery(this).attr("tabindex")) > highestTabIndexInRow) {
				highestTabIndexInRow = parseInt(jquery(this).attr("tabindex"));

				//Get focus field: id of the first input control in new row
				if (focusFieldId.length == 0)
					focusFieldId = jquery(this).attr("id");
			}
		});

		var highestTabIndexInOrigPanel = 0;

		//Get highest tabindex in orig panel (before row is added)
		jqueryCurrentTable.find("input,select,textarea").each(function() {
			if (parseInt(jquery(this).attr("tabindex")) > highestTabIndexInOrigPanel)
				highestTabIndexInOrigPanel = parseInt(jquery(this).attr("tabindex"));
		});

		//Update tabindex on controls with higher tabindex than controls in orig panel
		var added = 1;
		jquery('input,select,textarea').each(function() {
			var jqueryinput = jquery(this);
			if (parseInt(jqueryinput.attr("tabindex")) > highestTabIndexInOrigPanel) {
				jqueryinput.attr("tabindex", parseInt(highestTabIndexInRow) + added);
				added++;
			}
		});
		
		jquery(jqueryCurrentTable).append(panelRow);

		setSkjemaContainerHeight();

		var rowCount = jquery("table[data-id = '" + panelId + "']" + '> tbody > tr').length;
		
		//the add button is active, should we disable it?
		if(rowCount >= maxRows)
			jquery("a.addPanelRow", jqueryCurrentTable).addClass("disabled");
		else
			jquery("a.addPanelRow", jqueryCurrentTable).removeClass("disabled");
		
		//after a row is added, we can always delete it, check if it is disabled first..
		jquery("tbody a", jqueryCurrentTable).removeClass("disabled");

		//invoke so that focus event is registered for the newly added row
		setFocusMessages();
		
		//invoke so that help click event is registered for the newly added row
		setClickMessages();
		
		//Set focus
		jquery('#' + focusFieldId).focus();
	});
	return false;
}

function deletePanelRow(panelId, panelRowId, minRows) {
	jquery.post(location.pathname + "/deletepanelrow?panelId=" + panelId + "&panelRowId=" + panelRowId, function() {
		//Remember that panelId = panelRowId for first panel row
		var jqueryCurrentTable = jquery("table[data-id='" + panelId + "']");
		var panelRowNumber = jquery("> tbody > tr > td > div > label[id='PanelRowNumber_" + panelRowId + "']", jqueryCurrentTable).text();

		jquery("tr[id='" + panelRowId + "']").remove();
		//if the add button is disabled, enable it (after deleting a row we can always add a new one)
		jquery("> tfoot a", jqueryCurrentTable).removeClass("disabled");
		//remove button is enabled, disable it if rowcount == minrows
		var rowCount = jquery("> tbody > tr", jqueryCurrentTable).length;

		if (rowCount == minRows) jquery("> tbody a", jqueryCurrentTable).addClass("disabled");
		//Update row number
		jquery("> tbody > tr > td > div > label[id^='PanelRowNumber_']", jqueryCurrentTable).each(function() {
			var rowNumber = jquery(this).text();
			if (rowNumber > panelRowNumber) {
				jquery(this).text(rowNumber - 1);
			}
		});
	});
	return false;
}

function removeFile(divId, fileBoxId, containerId, gridId, panelId) {
	jquery.post(location.pathname + "/removefile?fileBoxId=" + fileBoxId + "&containerId=" + containerId + "&gridId=" + gridId + "&panelId=" + panelId,
		function(data) {
			if (gridId.length > 0)
				jquery("#" + gridId).parent().replaceWith(data);
			else if (panelId.length > 0)
				jquery("#" + panelId).parent().replaceWith(data);
			else
				jquery("#" + divId).replaceWith(data);
		}
	);
	return false;
}

function renderField(fieldId, containerId) {
	//se removeFile ovenfor - grid/panel-støtte.
	jquery.post(location.pathname + "/renderfield?fieldId=" + fieldId + "&containerId=" + containerId,
		function (data)	{
		    var outerGuid = data.split('id="')[1].split('"')[0];
            console.log("outerGuid = " + outerGuid);
            jquery("#" + outerGuid).replaceWith(data);
		}
	);
	return false;
}

function registerFocusHelp(messages) {
	jquery('#skjema :input:enabled').focus(function() {
		var jQMessageBox = jquery('#Guidance li.help');
		var name = this.name;
		if (name.indexOf("-") != -1)
			name = name.substring(0, name.indexOf("-"));
		var split = name.split("_");
		if (split.length > 1) name = split[split.length - 1];
		var message = messages[name];
		if (!message)
			message = "";
		if(message != jQMessageBox.html())
		    jQMessageBox.html(message).effect("highlight", { color: "#ffd" }, 1000);

		if (consts["responsiveSupport"])
		{
			var width = (window.innerWidth > 0) ? window.innerWidth : screen.width;
			if (width < 950) {
			    jquery(".help-message").remove();
			    var parentDom = this.parentNode;
			    var grandParentDom = parentDom.parentNode;
			    if (parentDom.tagName !== "DIV" || grandParentDom.tagName == "TD") {
			        parentDom = parentsUntilElement(parentDom, "TABLE");
			        parentDom = parentDom.parentNode;
			    }
				jQuery(parentDom).prepend("<p class='help-message'>" + message + "</p>");
				iframeResizePipeFix();
				jQuery(".help-message").effect("highlight", {}, 2000);
			}
		}
	});
}

function parentsUntilElement(domElement, tagName) {
    console.log("tagName:", domElement.tagName);
    if (domElement.tagName !== tagName) {
        domElement = parentsUntilElement(domElement.parentNode, tagName);
    }
    return domElement;
}

function registerClickHelp(messages) {
    jquery('.toggleGuidance, .guidance').click(function () {
        toggleGuidanceEvent(this, messages);
    });

    jquery('.toggleGuidance, .guidance').on('keydown', function (event) {
        console.log("keypress on help");
        var keycode = (event.keyCode ? event.keyCode : event.which);
        if (keycode == '13') {
            toggleGuidanceEvent(this, messages);
        }
    });
}

function toggleGuidanceEvent(that, messages) {
    var message = messages[that.id];
    // remove active class from other icons
    jquery('.toggleGuidance, .guidance').removeClass("active");
    // add class active
    jquery(that).addClass("active");
    if (!message) message = "";
    jquery('#Guidance li.help').html(message).parent().effect("highlight", {}, 1000);

    if (consts["responsiveSupport"]) {
        var width = (window.innerWidth > 0) ? window.innerWidth : screen.width;
        if (width < 950) {
            jquery(".help-message").remove();
            jquery(".toggleGuidance").colorbox({
                html: "<p class='help-message'>" + message + "</p>",
                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(this).parent().append("<p class='help-message'>" + message + "</p>");
        }
    }

    var parameterFromUrl = getParameterFromUrl('iframeurl', '', true);
    if (parameterFromUrl != false)
        iframeResizePipe(parameterFromUrl);
}

function maskDateBox(id, format) {
	jquery(document).ready(function() {
		if (format == "d")
			jquery("#" + id).mask("?99.99.9999");
		else if (format == "t")
			jquery("#" + id).mask("?99:99");
	});
}

function limitTextAreaInput(textAreaId, limit, of)
{
    var text = textAreaId.value;
    var newLines = text.match(/(\r\n|\n|\r)/g);
    var addition = 0;
    if(newLines != null)
        addition = newLines.length;
    
    //newlines count as 2 chars
    var totalLength = text.length + addition;

    if(totalLength > limit)
        jquery("#" + textAreaId.id).val(text.substring(0, limit - addition));
    else
    {
        var message = '&nbsp;({0} {1} {2})'.replace('{0}', totalLength).replace('{1}', of).replace('{2}', limit);
        jquery("#" + textAreaId.id + "_charCount").html(message);
    }
}

jquery(function()
{
	jquery("#skjema").keydown(function(event)
	{
		if(event.keyCode == 13)
		{
			//allow click on enter in textarea
			if(document.activeElement.tagName != "TEXTAREA")
			{
				event.preventDefault();
				return false;
			}
		}
	});

	jquery("a.addRow, a.addRowOnTop, a.deleteRow, a.moveUpRow, a.moveDownRow, a.clearRow").live("click", function(e)
	{
		e.preventDefault();
		jqThis = jquery(this);
		if(!jqThis.hasClass("disabled"))
		{
			var gridId = jqThis.closest("table").attr("id");

			if(jqThis.hasClass("addRow"))
				addRow(gridId, consts[gridId + ".maxRows"], "");
			else if(jqThis.hasClass("addRowOnTop"))
				addRow(gridId, consts[gridId + ".maxRows"], 0);
			else if(jqThis.hasClass("deleteRow"))
				deleteRow(gridId, jqThis.parent().parent().attr("id"), consts[gridId + ".minRows"]);
			else if (jqThis.hasClass("clearRow"))
				clearRow(gridId, jqThis.parent().parent().attr("id"));
			else if(jqThis.hasClass("moveUpRow"))
				moveUpRow(gridId, jqThis.parent().parent().attr("id"));
			else if(jqThis.hasClass("moveDownRow"))
				moveDownRow(gridId, jqThis.parent().parent().attr("id"));
		}
	});

	jquery("a.addPanelRow, a.deletePanelRow").live("click", function(e)
	{
		e.preventDefault();
		jqThis = jquery(this);
		if(!jqThis.hasClass("disabled"))
		{
			var panelId = jqThis.closest("table").data("id");

			if(jqThis.hasClass("addPanelRow"))
				addPanelRow(panelId, consts[panelId + ".maxRows"]);
			else if(jqThis.hasClass("deletePanelRow"))
				deletePanelRow(panelId, jqThis.parent().parent().attr("id"), consts[panelId + ".minRows"]);
		}
	});
    
	jquery('form.submit-once').submit(function (e)
	{
		if(jquery(this).hasClass('form-submitted'))
		{
			e.preventDefault();
			return;
		}
		jquery(this).addClass('form-submitted');
	});

	setSkjemaContainerHeight();
});

function setSkjemaContainerHeight()
{
	//KOM-2464 (fant ikke noe bedre sted å legge dette, det skal altså skje når betingelse for felt har kjørt)
	jquery('.relativeTableTD:has(:input:visible)').css('padding-top', '6px');
	jquery('.relativeTableTD:has(div.labelfield)').css('padding-top', '6px').css('padding-bottom', '2px');

	var heights = [];

    jQuery("#skjema > div").each(function () {
        if(jQuery(this).css("position", "absolute")) {
            var top = jQuery(this).position().top;
            var height = jQuery(this).outerHeight();
            var add = 15;

            heights.push(height + top + add);
        }
    });

    var newHeight = Math.max.apply(Math, heights);

    jQuery("#skjema").height(newHeight);

    return newHeight;
};

function isNumeric(number) {
	var num = new String(number).replace(/\s+/g, '');
	var regex = /^(\-\d{1,},\d{1,}|\-\d{1,}|\d{1,},\d{1,}|\d{1,},\d{1,}|\d{1,})$/;
	var isNumeric = regex.test(num);
	return isNumeric;
}

function isDate(date) {
	return Date.parse(date) != null;
}

function SetMessageInMainContentArea(message) {
	jquery("#" + 'MainContentArea').empty().append(message);
	return;
}

function fileSelected(e) {
	if (window.File && window.FileReader) //sjekk etter nødvendig støtte
	{
		var files = e.target.files || e.dataTransfer.files;
		var id_inner = e.target.dataset.id_inner;
		var id_outer = e.target.dataset.id_outer;
		var id_container = e.target.dataset.id_container != null ? e.target.dataset.id_container : null;
		var id_grid = e.target.dataset.id_grid != null ? e.target.dataset.id_grid : null;
		var id_full = e.target.id;
		
		

		for (var i = 0, f; f = files[i]; i++) {
			if (!validateFile(f, e.target)) {
				e.target.value = '';
				return;
			}

			uploadFile(f, id_inner, id_outer, id_container, id_full, id_grid);
		}
	}
}

function validateFile(file, field) {
	var field_caption = field.dataset.caption;
	var acceptedextensions = field.dataset.acceptedextensions;
	var maxfilesizemb = field.dataset.maxfilesizemb;
	var message_max = field.dataset.message_max;
	var message_notfound = field.dataset.message_notfound;
	var message_noextension = field.dataset.message_noextension;
	var message_illegalextension = field.dataset.message_illegalextension;

	if (maxfilesizemb == null)
		maxfilesizemb = 5; //TODO: hent default fra web.config?? 
		
	if (file.size == 0) {
		var message = null;

		if (message_notfound != null && message_notfound != "")
			message = message_notfound;
		else
			message = FileBox_FileNotFound;

		alert(message);

		return false;
	}

	var sizeKb = Math.round(file.size / 1024);
	var sizeMb = (sizeKb / 1024).toFixed(1)
	var maxSizeKb = maxfilesizemb * 1024;

	if (sizeKb > maxSizeKb) {
		var message = null;
		if (message_max != null && message_max != "")
			message = message_max;
		else
			message = FileBox_MaxFileSizeReached;
		
		alert(message.replace("{caption}", "'" + field_caption + "'").replace("{maxSizeMb}", maxfilesizemb));
		
		return false;
	}
	
	var fileExtension = getFileExtension(file.name);
	
	if (fileExtension === "") {
		if (message_noextension != null && message_noextension != "")
			message = message_noextension;
		else
			message = FileBox_NoExtension;
		
		alert(message.replace("{caption}", "'" + field_caption + "'"));

		return false;
	}
	
	if (acceptedextensions != null && acceptedextensions != "" && jquery.inArray(fileExtension, acceptedextensions.split(";")) === -1) {
		if (message_illegalextension != null && message_illegalextension != "")
			message = message_illegalextension;
		else
			message = FileBox_IllegalExtension;

		alert(message.replace("{caption}", "'" + field_caption + "'").replace("{acceptedExtensions}", acceptedextensions));
		
		return false;
	}
	
	return true;
}

function getFileExtension(filename) {
	var a = filename.split(".");
	if (a.length === 1 || (a[0] === "" && a.length === 2)) {
		return "";
	}
	return a.pop().toLowerCase();
}

function uploadFile(file, id_inner, id_outer, id_container, id_full, id_grid) {
	var xhr = new XMLHttpRequest();
	if (xhr.upload) { //TODO: sjekk etter gyldig bilde og størrelse. -  && file.type == "image/jpeg" && file.size <= 1024
		xhr.upload.addEventListener("progress", function (e) {
			if (e.lengthComputable) {
				var percentComplete = Math.round(e.loaded * 100 / e.total);
				//alert(pc);
				var progress = jquery("#" + id_full); 
				progress.css("background-size", percentComplete + "% 100%");
			}
		}, false);
		xhr.addEventListener("load", function(evt) {
			var div = jquery("#" + id_outer);

			if (id_container != null) {
				var row = div.parent().parent();
				var a = row.find("td").last().find("a");
				a.removeClass().addClass("clearRow"); //remove deleteRow disabled
			}

			div.replaceWith(evt.target.responseText);
		}, false);
		xhr.addEventListener("error", uploadFailed, false);
		xhr.addEventListener("abort", function (evt) {
			//jquery("#" + id_full).attr("value", "Avbryter..."); //TODO: correct language
			jquery("#" + id_full).addClass("cancel");
			removeFile(id_outer, id_inner, id_container != null ? id_container : '', id_grid != null ? id_grid : '', '');
		}, false);

		var uploadFileUrl = location.pathname + "/UploadFile?fileName=" + file.name + "&fileId=" + id_inner;
		
		if (id_container != null)
			uploadFileUrl += "&containerId=" + id_container;
		
		xhr.open("POST", uploadFileUrl, true);
		
		var url = location.pathname + "/BeginUpload?fileId=" + id_inner + "&containerId=" + (id_container != null && id_container != '' ? id_container : "") + "&filename=" + file.name;

		//alert(url);

		jquery.ajax({
			type: 'GET',
			url: url,
			success: function (response) {
				//alert(response);
				jquery("#" + id_full).replaceWith(response); //show progress
			},
			error: function (request, status, error) {
				alert(request.responseText);
			},
			async: false
		});

		if (id_container != null) {
			var div = jquery("#" + id_outer);
			var row = div.parent().parent();
			var a = row.find("td").last().find("a");
			a.removeClass(); //remove deleteRow disabled
			a.click(function () {
				xhr.abort();
			});
		}
		else {
			var abortLink = jquery("#" + id_outer + " a");
			abortLink.click(function() {
				xhr.abort();
			});
		}

		xhr.send(file);
	}
}

function uploadFailed(evt) {
	alert("There was an error attempting to upload the file.");
	//TODO: vis tomt vedleggs-felt igjen.
}

function getResource(resource, resourcePath) {

    var langResource = resource[language];

    if (typeof langResource == "undefined") {
        langResource = resource["root"];
    }
    var languageString = langResource[resourcePath];
    if (typeof languageString == "undefined") {
        langResource = resource["root"];
    }
    languageString = langResource[resourcePath];
    if (typeof languageString == "undefined") {
        return "resource for '" + resourcePath + "' is missing";
    }
    return languageString;
}

//var width = jquery(window).width() - 100;
//console.log(width);
//if (width < 980) {
//    console.log("tester igjen")
//    jquery("a#help").colorbox({ width: width });
//}
