/*******************************************************************
 * Copyright (c) 2002-2004 More Optimized Registration Elements AS *
 *******************************************************************/

var calculatetarget;
var zipcodetarget;
var orgnametarget;
var orgadrtarget;
var orgziptarget;
var orgcitytarget;
var orgemailtarget;

var hidestr = "hidden";
var showstr = "visible";

var QUESTION_HELP_HELPBUTTON = 1;
var QUESTION_HELP_ERRORMSG = 2;

var currentQuestionField = null;
var currentQuestionHelp = null;
var currentQuestionFieldOverride = null;
var stopMessageFieldOverride = null;
var cancelHideQuestionHelp = false;
function getAbsolutePosX(field) {
	var curleft = 0;
	if (field.offsetParent) {
		while (field.offsetParent) {
			curleft += field.offsetLeft;
			field = field.offsetParent;
		}
	} else if (field.x) {
		curleft += field.x;
	}
	return curleft;
}

function getAbsolutePosY(field) {
	var curtop = 0;
	if (field.offsetParent) {
		while (field.offsetParent) {
			curtop += field.offsetTop;
			field = field.offsetParent;
		}
	} else if (field.y) {
		curtop += field.y;
	}
	return curtop;
}

function closeWindow() {
	if (confirm("Vil du avbryte dokumentveiviseren?")) {
		window.close();
	}
}

function getRadioValue(radioGrp, useAnswervalue) {
	if (radioGrp) {
		for (var i = 0; i < radioGrp.length; i++) {
			if (radioGrp[i].checked) {
				if (useAnswervalue == true) {
					return radioGrp[i].answervalue;
				} else {
					return radioGrp[i].value;
				}
			}
		}
	}
}

function getChkboxValue(chkboxField) {
	if (chkboxField.checked) {
		return "Y";
	} else {
		return "N";
	}
}

function openWizardHelp(wizardId, versionId, languageId) {
	win = window.open("wizardhelp.jsp?wizardid=" + wizardId + "&versionid=" + versionId + "&languageid=" + languageId, "wizardHelp", "height=600,width=700,scrollbars=yes");
	win.focus();
}

function toggleQuestionHelp(helpText,yOffset,title,qfieldname,noHide, isHelpButton, overrideQfieldname) {
	// overrideQfieldname overrides qfieldname and uses qfieldname only for positioning
//	confirm("toggleQuestionHelp, event=" + event + " helpText=" + helpText + " yOffset=" + yOffset + " title=" + title + " qfieldname=" + qfieldname);
	if (!noHide) {
		noHide = false;
	}
	if (!isHelpButton) {
		isHelpButton = false;
	}
	if (!qfieldname) {
		alert("no qfieldname, helpText=" + helpText + " yOffset=" + yOffset + " title=" + title);
		return;
	}
	if (!helpText || helpText.length == 0) {
		return;
	}
	var helpTextCell = document.getElementById ? document.getElementById('helptext') : document.all.helptext;
	var helpTextDiv = document.getElementById ? document.getElementById('helptextDiv') : document.all.helptextDiv;
	var isFieldgroupButton = false;
	//var isTableButton = false;
	if (helpTextCell) { // Position the helpTextDiv
		var field = document.qform[qfieldname];
		if (qfieldname.indexOf('qgroup') > -1) {
			isFieldgroupButton = true;
			var is_webkit = navigator.userAgent.toLowerCase().indexOf('webkit') > -1;
			if (is_webkit) {
				field = document.getElementById(qfieldname);
			}
		}
		if (qfieldname.indexOf('tbl_') > -1) {
			field = document.getElementById(qfieldname);
		}
		if (!field || (field.type != undefined && field.type === 'hidden')) {
			field = document.qform[qfieldname + '_1']; //FIXME: Is test for table in use?
			if (field) { // table
			//	isTableButton = true;
			}
			if (!field) { // Check info question
				var spanName = 'q' + qfieldname.replace('A_', '');
				field = document.getElementById(spanName);
			}
			if (!field) { // Multichoice/radiobutton helpbutton
				field = document.getElementById('tdHelpButton' + qfieldname);
			}
			if (!field) { // Upload 
				field = document.getElementById('tdUpload' + qfieldname);
			}
		} else if (isRadio(field)) {
			if (field.type!="radio") { 
				field = field[0];
			}
		}
		
		if (!field) {
			//alert("ERROR: Could not get field, qfieldname=" + qfieldname + " helpText=" + helpText);
			return;
		}
		var helpwidth = helpTextCell.offsetWidth;
		var helpheight = helpTextCell.offsetHeight;
		var helpleft = getAbsolutePosX(helpTextCell);
		var helptop = getAbsolutePosY(helpTextCell);
		var eventleft = getAbsolutePosX(field);
		var eventtop = getAbsolutePosY(field);
		//confirm("helpwidth=" + helpwidth + " helpheight=" + helpheight + " helpleft=" + helpleft + " helptop=" + helptop + " eventleft=" + eventleft + " eventtop=" + eventtop);
		if (helpleft >= eventleft) {
			helpTextDiv.style.left = helpleft + 4;
		} else {
			if (eventleft >= (helpleft + helpwidth)) {
				helpTextDiv.style.left = helpleft + 4;
			} else {
				helpTextDiv.style.left = eventleft;
			}
		}

		if (helptop >= eventtop) {
			helpTextDiv.style.top = helptop + 4;
		} else {
			if (eventtop >= (helptop + helpheight)) {
				helpTextDiv.style.top = helptop + 4;
				//helpTextDiv.style.top = eventtop;
			} else {
				helpTextDiv.style.top = eventtop;
			}
		}
		//alert("helpTextDiv top=" + helpTextDiv.style.top + " left=" + helpTextDiv.style.left);
	} else { 
		// Qpage help is turned off
		return;
	}
	
	helpTextDiv.style.visibility = "visible";
	
	var isIE = document.all && !window.opera && !(typeof document.body.style.maxHeight != "undefined");

	if (helpTextDiv) {
		
		if (currentQuestionField && !noHide) { // Hide current help button highlighting
			hideIconHighlighting();
		}
		// The type of help to display
		var questionHelp = isHelpButton ? QUESTION_HELP_HELPBUTTON : QUESTION_HELP_ERRORMSG;
		var sameQfieldname = currentQuestionField == qfieldname || (overrideQfieldname && (currentQuestionFieldOverride == overrideQfieldname));
		if (sameQfieldname && currentQuestionHelp == questionHelp && !noHide) {  // Hide help
			hideQuestionHelp();
			currentQuestionField = null;
			currentQuestionHelp = null;
			currentQuestionFieldOverride = null;
		} else {  // Show help
			var nudge = noHide && sameQfieldname;
			currentQuestionField = qfieldname;
			currentQuestionHelp = questionHelp;
			currentQuestionFieldOverride = overrideQfieldname ? overrideQfieldname : null;
			var currentErrorIcon;

			if (!isFieldgroupButton) {
				if (!isHelpButton) { // Get the error/warning icon
					currentErrorIcon = document.getElementById('errorImg' + currentQuestionField);
					if (currentErrorIcon) currentErrorIcon = currentErrorIcon.childNodes[0];
					//confirm("showhelp erroricon=error/warning");
				} else { // Get the helpbutton icon 
					currentErrorIcon = document.getElementById('tdHelpButton' + currentQuestionField);
					if (currentErrorIcon) currentErrorIcon = getElementsByTagNames('a', currentErrorIcon).pop();
					if (currentErrorIcon) currentErrorIcon = currentErrorIcon.childNodes[0];
					//confirm("showhelp erroricon=help, " + currentQuestionField + " icon=" + currentErrorIcon);
				}
			} else {
				currentErrorIcon = document.getElementById(currentQuestionField); // fieldgroup
				if (currentErrorIcon) currentErrorIcon = getElementsByTagNames('legend', currentErrorIcon).pop(); // legend
				if (currentErrorIcon) currentErrorIcon = getElementsByTagNames('a', currentErrorIcon).pop(); // a
				if (currentErrorIcon) currentErrorIcon = currentErrorIcon.childNodes[0]; // span / img
			}
			var newImgFile = "";
			if (currentErrorIcon && !overrideQfieldname) { // Highlight icon if the qfieldname is not overriden
				if (isIE) { // Apply PNG filter
					var filter = currentErrorIcon.style.filter;
					var imgPos1 = filter.indexOf("'");
					var imgPos2 = filter.indexOf("'", imgPos1 + 1);
					var imgFile = filter.substring(imgPos1 + 1, imgPos2);
					var dPos = imgFile.indexOf(".");
					newImgFile = imgFile.substring(0, dPos) + "_active" + imgFile.substring(dPos);
					var newFilter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + newImgFile + "', sizingMethod='scale')";
					if ((navigator.userAgent.toLowerCase().indexOf('windows nt 5.0') == -1) && (navigator.userAgent.toLowerCase().indexOf('windows nt 6.0') == -1))  { // Don't mess with w2k, crashes
						currentErrorIcon.style.filter = newFilter;
					}
				} else { // Not IE <= 6.0
					if (currentErrorIcon) {
						var imgFile = currentErrorIcon.src;
						if (imgFile && imgFile.length > 0) {
							imgFile = imgFile.replace('.png', '_active.png');
							currentErrorIcon.src = imgFile;
							newImgFile = imgFile;
						}
					} else {
						alert("no imgFile, currentQuestionField=" + currentQuestionField);
					}
				}
			}

			showQuestionHelp(helpTextDiv,helpText,yOffset,title,newImgFile);
			if (overrideQfieldname) {
				currentQuestionField = null;
			}
			// Nudge
			if (nudge) {
				if (orgNudgeLeft == null) nudgeQuestionHelp();
			}
		}
	}
}

var orgNudgeLeft = null;
var orgNudgeTop = null;
var numNudge = 0;
var leftNudge = true; // Current direction to nudge

function nudgeQuestionHelp() {
	var helptextDiv = document.getElementById('helptextDiv');
	if (helptextDiv) {
		if (orgNudgeLeft == null) {
			orgNudgeLeft = helptextDiv.style.left;
			orgNudgeTop = helptextDiv.style.top;
			if (orgNudgeLeft.indexOf('px') > -1) orgNudgeLeft = orgNudgeLeft.replace('px', '');
			if (orgNudgeTop.indexOf('px') > -1) orgNudgeTop = orgNudgeTop.replace('px', '');
			orgNudgeLeft = parseInt(orgNudgeLeft);
			orgNudgeTop = parseInt(orgNudgeTop);
			//alert("orgnudgeleft=" + orgNudgeLeft);
		}
		leftNudge = !leftNudge;
		
		if (numNudge < 10) {
			var nudgeAmountX = (leftNudge == true ? -1 : 1);
			var nudgeAmountY = (leftNudge == true ? 1 : -1);
			helptextDiv.style.left = (orgNudgeLeft + nudgeAmountX) + 'px';
			helptextDiv.style.top = (orgNudgeTop + nudgeAmountY) + 'px';
			numNudge ++;
			setTimeout("nudgeQuestionHelp()", 50);
		} else {
			helptextDiv.style.left = orgNudgeLeft;
			helptextDiv.style.top = orgNudgeTop;
			orgNudgeLeft = null;
			orgNudgeTop = null;
			leftNudge = true;
			numNudge = 0;
		}
	}
}
function resizeQuestionHelp() {
	if (currentQuestionField || currentQuestionFieldOverride) {
		var helptextCell = document.getElementById('helptext');
		var helptextDiv = document.getElementById('helptextDiv');
		if (helptextCell) { // Check to prevent crash
			var posX = getAbsolutePosX(helptextCell);
			helptextDiv.style.left = posX + 4;
		}
	}
}
window.onresize = resizeQuestionHelp;

function showQuestionHelp(helpTextDiv,helpText,yOffset,title,imgfile) {
	//confirm("showQuestionHelp - helpTextDiv=" + helpTextDiv + " helpText=" + helpText + " yOffset=" + yOffset + " title=" + title + " imgfile=" + imgfile);
	if (helpText.length > 0) {
		var helptitle;
		if (document.getElementById) { // Level 1 DOM
			helptitle = document.getElementById('helptitle');
		} else if (document.all) { // Old IE
			helptitle = document.all.helptitle;
		}
		
		if (!title) title = '';
		helptitle.innerHTML  = "<b>" + title + "</b><br/>";
		
		var helpicon;
		if (document.getElementById) { // Level 1 DOM
			helpicon = document.getElementById('helpicon');
		} else if (document.all) { // Old IE
			helpicon = document.all.helpicon;
		}
		if (helpicon) {	
			if (imgfile && (imgfile.length > 0)) {
				var isIE = document.all && !window.opera && !(typeof document.body.style.maxHeight != "undefined");
				if (isIE) {
					imgfile = imgfile.replace('_active.','.');
					var newFilter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + imgfile + "', sizingMethod='scale')";
					if ((navigator.userAgent.toLowerCase().indexOf('windows nt 5.0') == -1) && (navigator.userAgent.toLowerCase().indexOf('windows nt 6.0') == -1)) { // Don't mess with w2k, crashes
						helpicon.style.filter = newFilter;
						helpicon.style.height = 20;
						helpicon.style.width = 21;
						//correct use of helpicon.style.display causes heading to start on new line
						//helpicon.display = 'block';
						//helpicon.style.display = 'block';
					}
				} else {
					imgfile = imgfile.replace('_active.','.');
					helpicon.src = imgfile;
					helpicon.style.height = 20;
					helpicon.style.width = 21;
					//helpicon.display = 'block';
					//helpicon.style.display = 'block';
				}
			} else {
				helpicon.style.height = 0;
				helpicon.style.width = 0;
				helpicon.style.filter = '';
				//helpicon.display = 'none';
				//helpicon.style.display = 'none';
			}
		} else {
			alert("no helpicon");
		}
		var helptext;
		if (document.getElementById) { // Level 1 DOM
			helptext = document.getElementById('helptextspan');
		} else if (document.all) { // Old IE
			helptext = document.all.helptextspan;
		}		
		if (helptext) {
			helptext.innerHTML = helpText;
		}
		helpTextDiv.style.visibility = 'visible';		
	} else {
		helpTextDiv.style.visibility = 'hidden';
	}
}
// Hide error/warning icons
function hideQuestionIcons(qfieldname) {
	if (!qfieldname) {
		qfieldname = currentQuestionField;
	}
	var validateDiv = document.getElementById('validateDiv' + qfieldname);
	if (validateDiv) {
		validateDiv.innerHTML = "";
	}
}
function showQuestionIcons(qfieldname, qtext, message, iserror) {
	// Default values for qtext, message and iserror
	if (!qtext) qtext = "notext";
	if (!message) message = "nomessage";
	if (!iserror) iserror = true;
	var validateDiv = document.getElementById('validateDiv' + qfieldname);
	if (validateDiv) {
		//alert('qtext = ' + qtext);
		var html = "";
		var isIE = document.all && !window.opera && !(typeof document.body.style.maxHeight != "undefined");
		if (isIE) {
			if (iserror) {
				html += "<a href=\"javascript:void(0)\" onClick=\"toggleQuestionHelp('" + message + "',0,'" + qtext +"','" + qfieldname + "');\"><span id=\"errorImg" + qfieldname + "\"><span style=\"height:20; width:21; filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='images/questioncheck_error.png', sizingMethod='scale');\"></span></span></a>";
			} else {
				html += "<a href=\"javascript:void(0)\" onClick=\"toggleQuestionHelp('" + message + "',0,'" + qtext +"','" + qfieldname + "');\"><span id=\"errorImg" + qfieldname + "\"><span style=\"height:20; width:21; filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='images/questioncheck_warning.png', sizingMethod='scale');\"></span></span></a>";
			}
		} else {
			if (iserror) {
				html += "<a href=\"javascript:void(0)\" onClick=\"toggleQuestionHelp('" + message + "',0,'" + qtext +"','" + qfieldname + "');\"><span id=\"errorImg" + qfieldname + "\"><img src=\"images/questioncheck_error.png\" border=\"0\" /></span></a>";
			} else {
				html += "<a href=\"javascript:void(0)\" onClick=\"toggleQuestionHelp('" + message + "',0,'" + qtext +"','" + qfieldname + "');\"><span id=\"errorImg" + qfieldname + "\"><img src=\"images/questioncheck_warning.png\" border=\"0\" /></span></a>";
			}
		}
		validateDiv.innerHTML = html;
	} else {
		alert('Could not find validatediv = ' + qfieldname);
	}
}
function hideQuestionHelp(qfieldname) {
	if (window.opera) {
		// Problem with correct resetting of cancelHideQuestionHelp in opera and IE,firefox
		if (cancelHideQuestionHelp) {
			if ((currentQuestionField != null) && qfieldname && (currentQuestionField != qfieldname)) {
				//alert("hideQuestionhelp=" + qfieldname + " Setting cancelQuestionHelp to false; CurrentQuestionField : " + currentQuestionField);
				cancelHideQuestionHelp = false;
			}
			return;
		}
	} else if (cancelHideQuestionHelp || (currentQuestionField != null && currentQuestionField == qfieldname)) {
			cancelHideQuestionHelp = false;
			return;
	}
	//alert("hideQuestionhelp=" + qfieldname);
	var helpTextDiv;
	if (document.getElementById) { // Level 1 DOM
		helpTextDiv = document.getElementById('helptextDiv');
	} else if (document.all) { // Old IE
		helpTextDiv = document.all.helptextDiv;
	}
	if (helpTextDiv) {
		var helpicon = document.getElementById('helpicon');
		if (helpicon.src) {
			// Setting src to empty string will call qpage.jsp ?!?!
			//helpicon.src = "";
		} else {
			if (helpicon.style.filter) {
				helpicon.style.filter = '';
			}
		}
		var helptext = document.getElementById('helptext');
		if (helptext) {
			helptext.innerText = '';
		}
		helpTextDiv.style.visibility = "hidden";
		currentQuestionField = null;
		currentQuestionHelp = null;
		currentQuestionFieldOverride = null;
	}
	// Remove current highlighting
	hideIconHighlighting();
}
// Removes icon highlighting from currentQuestionField (if not null)
function hideIconHighlighting() {
	if (currentQuestionField) {
		var isIE = document.all && !window.opera && !(typeof document.body.style.maxHeight != "undefined");
		
		var currentErrorIcon = document.getElementById('errorImg' + currentQuestionField);
		if (currentErrorIcon) currentErrorIcon = currentErrorIcon.childNodes[0];
		if (currentErrorIcon) {
			if (isIE) { // Apply PNG filter
				var filter = currentErrorIcon.style.filter;
				var imgPos1 = filter.indexOf("'");
				var imgPos2 = filter.indexOf("'", imgPos1 + 1);
				var imgFile = filter.substring(imgPos1 + 1, imgPos2);
				var dPos = imgFile.indexOf("_active.png");
				if (dPos > -1) {
					var newImgFile = imgFile.substring(0, dPos) + imgFile.substring(dPos + 7);
					var newFilter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + newImgFile + "', sizingMethod='scale')";
					if ((navigator.userAgent.toLowerCase().indexOf('windows nt 5.0') == -1) && (navigator.userAgent.toLowerCase().indexOf('windows nt 6.0') == -1)) { // Don't mess with w2k, crashes
						currentErrorIcon.style.filter = newFilter;
					}
				}
			} else { // Not IE <= 6.0
				var imgFile = currentErrorIcon.src;
				if (imgFile && imgFile.length > 0 && imgFile.indexOf("_active.png") > -1) {
					imgFile = imgFile.replace('_active.png', '.png');
					currentErrorIcon.src = imgFile;
				}
			}
		}
		
		var currentHelpIcon = document.getElementById('tdHelpButton' + currentQuestionField);
		if (currentHelpIcon) currentHelpIcon = getElementsByTagNames('a', currentHelpIcon).pop();
		if (currentHelpIcon) currentHelpIcon = currentHelpIcon.childNodes[0];
		if (currentHelpIcon) {
			if (isIE) { // Apply PNG filter
				var filter = currentHelpIcon.style.filter;
				var imgPos1 = filter.indexOf("'");
				var imgPos2 = filter.indexOf("'", imgPos1 + 1);
				var imgFile = filter.substring(imgPos1 + 1, imgPos2);
				var dPos = imgFile.indexOf("_active.png");
				if (dPos > -1) {
					var newImgFile = imgFile.substring(0, dPos) + imgFile.substring(dPos + 7);
					var newFilter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + newImgFile + "', sizingMethod='scale')";
					if ((navigator.userAgent.toLowerCase().indexOf('windows nt 5.0') == -1) && (navigator.userAgent.toLowerCase().indexOf('windows nt 6.0') == -1)) { // Don't mess with w2k, crashes
						currentHelpIcon.style.filter = newFilter;
					}
				}
			} else { // Not IE <= 6.0
				var imgFile = currentHelpIcon.src;
				if (imgFile && imgFile.length > 0 && imgFile.indexOf("_active.png") > -1) {
					imgFile = imgFile.replace('_active.png', '.png');
					currentHelpIcon.src = imgFile;
				}
			}
		}
		
		var currentFieldgroupIcon = document.getElementById(currentQuestionField); // fieldgroup
		if (currentFieldgroupIcon) currentFieldgroupIcon = getElementsByTagNames('legend', currentFieldgroupIcon).pop(); // legend
		if (currentFieldgroupIcon) currentFieldgroupIcon = getElementsByTagNames('a', currentFieldgroupIcon).pop(); // a
		if (currentFieldgroupIcon) currentFieldgroupIcon = currentFieldgroupIcon.childNodes[0]; // span / img
		if (currentFieldgroupIcon) {
			if (isIE) { // Apply PNG filter
				var filter = currentFieldgroupIcon.style.filter;
				var imgPos1 = filter.indexOf("'");
				var imgPos2 = filter.indexOf("'", imgPos1 + 1);
				var imgFile = filter.substring(imgPos1 + 1, imgPos2);
				var dPos = imgFile.indexOf("_active.png");
				if (dPos > -1) {
					var newImgFile = imgFile.substring(0, dPos) + imgFile.substring(dPos + 7);
					var newFilter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + newImgFile + "', sizingMethod='scale')";
					if ((navigator.userAgent.toLowerCase().indexOf('windows nt 5.0') == -1) && (navigator.userAgent.toLowerCase().indexOf('windows nt 6.0') == -1)) { // Don't mess with w2k, crashes
						currentFieldgroupIcon.style.filter = newFilter;
					}
				}
			} else { // Not IE <= 6.0
				var imgFile = currentFieldgroupIcon.src;
				if (imgFile && imgFile.length > 0 && imgFile.indexOf("_active.png") > -1) {
					imgFile = imgFile.replace('_active.png', '.png');
					currentFieldgroupIcon.src = imgFile;
				}
			}
		}
	}
}
function goToPage(pageId, preview, rsid, temprsid) {
	if (validateRequired()) {
		if (pageId == "upload") {
			document.qform.cmd.value = "upload";
		} else if (pageId == "summary") {
			document.qform.cmd.value = "summary";
		} else if (pageId == "check") {
			document.qform.cmd.value = "check";
		} else {
			document.qform.cmd.value = "jump";
			document.qform.qpageid.value = pageId;
		}
		if (preview == true) {
			if (document.qform.preview) {
				document.qform.preview.value = "yes";
				//alert('Setting preview to yes');
			} else {
				alert('Could not find qform.preview parameter');
			}
		}
		if (document.qform.onsubmit()) {
			document.qform.submit();
		}
	}
}

function showErrorText(fieldname) {
	// 'click' the error img if it exists
	var valDiv = document.getElementById('validateDiv' + fieldname);

	if (valDiv) {
		var anchor = getElementsByTagNames('a', valDiv);
		valDiv = anchor.pop();
	}
	var isIE = document.all && !window.opera && !(typeof document.body.style.maxHeight != "undefined");
	if (valDiv) {
		if (isIE) {
			valDiv.click();
		} else {
			valDiv.onclick();
		}
	} else {
		if (window["onBlur" + fieldname] !== undefined) {
			window["onBlur" + fieldname]();
		} else if (window["onChange" + fieldname] !== undefined) {
			window["onChange" + fieldname]();
		}
	}
}

var oldTextsArray = [];
function checkTextareaChars(fieldname) {
	var isIE = document.all && !window.opera && !(typeof document.body.style.maxHeight != "undefined");
	
	var textarea = document.getElementById(fieldname);
	var counter = document.getElementById(fieldname + '_counter');
	var textareaValue = textarea.value;
	var currentCount = textarea.value.length;
	
	if (counter) {
		var maxCountObj = document.getElementById(fieldname + '_maxcount');
		var maxCount = parseInt(maxCountObj ? maxCountObj.value : "-1");
		
		if (currentCount > maxCount) {
			textarea.value = (oldTextsArray[fieldname] ? oldTextsArray[fieldname] : '');
			window.alert(trans_TEXTAREA_MAX_CHARS_TEXT1 + currentCount + trans_TEXTAREA_MAX_CHARS_TEXT2 + maxCount);
			counter.value = maxCount;
			textarea.focus();
			return;
		}
		counter.value = maxCount - currentCount;
	}
	
	var maxLinesObj = document.getElementById(fieldname + '_maxlines');
	if (maxLinesObj) {
		var maxLines = maxLinesObj.value;
		var charOnLine = 0;
		var lines = (currentCount > 0 ? 1 : 0);
		for (var i = 0; i<currentCount; i++) {
			var v = textareaValue.charAt(i);
			if (charOnLine > 0 && ((isIE && v === "\r") || (!isIE && v === "\n"))) {
				charOnLine = 0;
				lines++;
			} else if (charOnLine == 0 && ((isIE && v == "\r") || (!isIE && v === "\n"))) {
				lines++;
			} else {
				charOnLine++;
				if (charOnLine == 80) {
					lines++;
					charOnLine = 0;
				}
			}
		}
		
		var linesObj = document.getElementById(fieldname + '_lines');
		if ((lines - maxLines) > 2) {
			textarea.value = (oldTextsArray[fieldname] ? oldTextsArray[fieldname] : '');
			window.alert(trans_TEXTAREA_MAX_LINES_TEXT1 + lines + trans_TEXTAREA_MAX_LINES_TEXT2 + maxLines);
			linesObj.value = maxLines;
			counter.value = maxCount;
			textarea.focus();
			return;
		}
		
		var availLines = maxLines - lines
		linesObj.value = (availLines < 0 ? 0 : availLines);
	}
	
	oldTextsArray[fieldname] = textareaValue;
}

function stopNewcharsInTextarea(event, fieldname) { 
	var textarea = document.getElementById(fieldname);
	var maxCountObj = document.getElementById(fieldname + '_maxcount');
	var maxCount = parseInt(maxCountObj ? maxCountObj.value : "-1");

	var linesObj = document.getElementById(fieldname + '_lines');
	var lines = parseInt(linesObj ? linesObj.value : "-1", 10);
	var maxLinesObj = document.getElementById(fieldname + '_maxlines');
	var maxLines = parseInt(maxLinesObj ? maxLinesObj.value : "-1", 10);
	
	var keyId = (window.event ? window.event.keyCode : event.keyCode);
	
	var currentCount = textarea.value.length;
	if (maxCount != -1 && currentCount >= maxCount) {
		if (keyId == 46 || keyId == 8 // delete and backspace
			|| keyId == 33 || keyId == 34 || keyId == 35 || keyId == 36 // page up, page down, home and end
			|| keyId == 37 || keyId == 38 || keyId == 39 || keyId == 40 // the arrows
				) return true;
		else return false;
	}
	if (maxLines != -1 && lines == 0 && keyId == 13) return false;
	if (maxLines != -1 && lines < 0) {
		if (keyId == 46 || keyId == 8 // delete and backspace
			|| keyId == 36 || keyId == 35
			|| keyId == 37 || keyId == 38 || keyId == 39 || keyId == 40 // the arrows
				) return true;
		else return false;
	}
	
	return true;
}

function fixOnFocus(e) {
	if (!e) var e = window.event;
	// handle event
	var elem = e.target || e.srcElement;
	elem.className+=" infocus";
	//e.cancelBubble = true;
	//if (e.stopPropagation) e.stopPropagation();	
}
function fixOnBlur(e) {
	if (!e) var e = window.event;
	// handle event
	var elem = e.target || e.srcElement;
	elem.className = elem.className.replace(new RegExp(" infocus\\b"), "");
	//e.cancelBubble = true;
	//if (e.stopPropagation) e.stopPropagation();	
}
// Attach :focus to IE since it doesnt like :focus via CSS
inFocus = function() {
	var inEls = getElementsByTagNames('input,textarea', document.qform);
	for (var i=0; i<inEls.length; i++) {
		if (! isRadio(inEls[i])) {
			if (inEls[i].attachEvent) {
				inEls[i].attachEvent("onfocus", fixOnFocus);
				inEls[i].attachEvent("onblur", fixOnBlur);
			}
		}
	}
}
if (window.attachEvent) window.attachEvent("onload", inFocus);

// Sets focus to a form control with given tabindex
function setFocusToTabindex(element, tabindex) {
	if (!element) return;
	var formFieldList = getElementsByTagNames('input,select,textarea',element);
	for (var i=0;i<formFieldList.length;i++) {
		if (parseInt(formFieldList[i].tabIndex) == tabindex) {
			try {
				formFieldList[i].focus();
				return;
			} catch (e) { // Form field is probably hidden
				break; // Go for a bigger tabindex
			}
		}
	}
	for (var i=0;i<formFieldList.length;i++) {
		if (formFieldList[i].tabIndex > tabindex) {
			try {
				formFieldList[i].focus();
				return;
			} catch (e) { // Form field is probably hidden
				// Continue
			}
		}
	}
	// FF, Opera has problems with qforms childnodes, however this hack works!
	return setFocusToTabindex(document, tabindex);
}
// Gets a form field with a tabindex larger than specified tabindex
function getNextTabindex(tabindex) {
	var formFieldList = getElementsByTagNames('input,select,textarea', document.qform, true, true);
	for (var i=0;i<formFieldList.length;i++) {
		if (parseInt(formFieldList[i].tabIndex) > tabindex) {
			return formFieldList[i];
		}
	}
	return null;
}
// Gets all elements with tagname in the string (tags separated by comma), list, that is children of the object, obj.
// They are returned in the order they appear in the source code.
function getElementsByTagNames(list,obj,uniqueNames,omitHidden) {
        if (!obj) var obj = document;
        if (!uniqueNames) uniqueNames = false; // Used when we dont want elements with same name, eg. radio buttons
        if (!omitHidden) omitHidden = uniqueNames; // Omit hidden inputs?
        var tagNames = list.split(',');
        var resultArray = new Array();
        var resultNames = new Array();
        for (var i=0;i<tagNames.length;i++)
        {
                var tags = obj.getElementsByTagName(tagNames[i]);
                for (var j=0;j<tags.length;j++)
                {
                	if (omitHidden && isHidden(tags[j])) continue;
	                if (uniqueNames) {
                        	var tagName = tags[j].name;
                        	var numUnderscore = numChars(tagName,'_');
                        	if (numUnderscore == 2) {
                        		tagName = tagName.substring(0, tagName.lastIndexOf('_'));
                        		
                        	}
                        	if (! hasArray(resultNames, tagName)) {
 		                    //   	confirm("ADD tagname=" + tagName + " type=" + tags[j].type);
                        		resultNames.push(tagName);
		                        resultArray.push(tags[j]);
                        	} else {
                        	//	confirm("EXIST tagname=" + tagName + " type=" + tags[j].type);
                        	}
                        } else {
	                        resultArray.push(tags[j]);
                        }
                }
        }
        var testNode = resultArray[0];
        if (!testNode) return resultArray; // Return empty array
        if (testNode.sourceIndex)
        {
                resultArray.sort(function (a,b) {
                                return a.sourceIndex - b.sourceIndex;
                });
        }
        else if (testNode.compareDocumentPosition)
        {
                resultArray.sort(function (a,b) {
                                return 3 - (a.compareDocumentPosition(b) & 6);
                });
        }
        return resultArray;
}
function hasArray(array, name) {
	for (var i=0;i<array.length;i++) {
		if (array[i] == name) return true;
	}
	return false;
}
// Count occurences of char in src string
function numChars(src, singlechar) {
	var num=0;
	var index=src.indexOf(singlechar);
	while (index!=-1) {
		num++;
		index = src.indexOf(singlechar, index+1);
	}
	return num;
}
function setField(fieldname, calcFunc) {
	var el = getField(fieldname);
	if (el) {
		var newValue = calcFunc;
		var oldValue = el.value;
		el.value = newValue;
		if (getField(fieldname + '_display')) {
			getField(fieldname + '_display').value = newValue;
		}
		if (newValue != oldValue) {
			if (window["onChange" + fieldname] !== undefined) {
				window["onChange" + fieldname]();
			}
		}
	}
}
function getField(id) {
	var el = document.qform[id];
	if (el) return el;
	return null;
}
function multiFields() {
	var params = ['multi'];
	for (var i=0;i<arguments.length;i++) params[i+1] = arguments[i];
	return calcFields.apply(null,params);
}
function subFields() {
	var params = ['sub'];
	for (var i=0;i<arguments.length;i++) params[i+1] = arguments[i];
	return calcFields.apply(null,params);
}
function addFields() {
	var params = ['add'];
	for (var i=0;i<arguments.length;i++) params[i+1] = arguments[i];
	return calcFields.apply(null,params);
}
// Calc form fields, accepts arbitrary length of params (element refs and/or qform names(strings))
function calcFields(operator) {
	var total = 0;
	for (var i=1;i<arguments.length;i++) {
		var arg = arguments[i];
		var el;
		if (! arg) return;
		if (! arg.nodeType) {
			if (typeof arg == 'string') {
				el = document.qform[arg];
				if (!el) continue;
			} else {
				continue;
			}
		} else {
			el = arg;
		}
		var value = getFormValue(el);
		if (operator == 'add')  {
			if ((value && value.length > 0 && !isNaN(value))) {
				value = parseInt(value);
				total += value;
			}
		} else if (operator == 'sub') {
			if (value && value.length > 0 && !isNaN(value)) {
				value = parseInt(value);
				if (i==1) total = value;
				else total -= value;
			}
		} else if (operator == 'multi') {
			if (!(value && value.length > 0 && !isNaN(value))) {
				total = 0;
			} else {
				value = parseInt(value);
				if (i==1) total = value;
				else total *= value;
			}
		} else {
			alert("Cannot calculate fields, unknown operator: '" + operator + "'");
		}
	}
	if (total == 0) return '';
	return total;
}
// Gets form value for any form element
function getFormValue(frmElem) {
	if (!frmElem) return null;
	if (isRadio(frmElem)) {
		var radios = frmElem.length ? frmElem : document.qform[frmElem.name];
		for (var i=0;i<radios.length;i++) {
			if (radios[i].checked) return radios[i].value;
		}
	} else if (isSelect(frmElem)) {
		if (frmElem.selectedIndex == 0) return;
		return frmElem.options[frmElem.selectedIndex].value;
	} else if (isCheckbox(frmElem)) {
		if (frmElem.checked) {
			return 1;
		} else {
			return 2;
		}
	} else {
		if (frmElem.value === undefined) alert("Element is no formelement, " + frmElem + " name=" + frmElem.name + " id=" + frmElem.id);
		return frmElem.value;
	}
}
function isRadio(el) { 
	return (el.length&&(el[0].type=="radio"))||(el.type=="radio");
}
function isSelect(el) {
	return el.options;
}
function isCheckbox(el) {
	return el.type == 'checkbox';
}
function isHidden(el) {
	return el.type == 'hidden';
}
function isAnswered(el) {
	if (!el) return false;
	if (isRadio(el)) {
		var radios = document.qform[el.name];
		for (var i=0;i<radios.length;i++) {
			if (radios[i].checked) return true;
		}
	} else if (isSelect(el)) {
		var value = getFormValue(el);
		//confirm("select value=" + value);
		if (!value) {
			return isSelectChkboxAnswered(el);
		}
		return value.length > 0;
	} else if (isCheckbox(el)) {
		if (numChars(el.name,'_') == 2) { // SELECT CHKBOX TYPE
			return isSelectChkboxAnswered(el.name.substring(0, el.name.lastIndexOf('_')));
		}
//		confirm("checkbox, " + el.name + "=" + el.checked + " type=" + el.type);
		return el.checked;
	} else if (isHidden(el)) {
		/*if (el.type == 'hidden') {
			if (document.getElementById('CHK' + el.name)) {
				return document.getElementById('CHK' + el.name).checked;
			}
		}*/
	} else {
		return el.value.length > 0;
	}
	return false;
}
function isSelectChkboxAnswered(el) {
	var i = 1;
	var maxAnswerid = 5000;
	var foundElement = false;
	while (i < maxAnswerid) {
		var formEl = document.qform[el + '_' + i];
		if (formEl) {
			foundElement = true;
			// Increase maxAnswerid, if we've got an element close to the boundary, extend the boundary so we're not skipping elements!
			if (i > (maxAnswerid - 100)) {
				maxAnswerid += 200;
			}
			if (getFormValue(formEl) == '1') { 
				return true;
			}
		}
		i ++;
	}
	if (!foundElement) { // Answerid is probably out of range
		alert("Could not find checkbox element for element, " + el + " Tried, 1-" + maxAnswerid);
	} else {
		var formEl = document.qform[el + '_OTHERCHK'];
		if (formEl) {
			if (getFormValue(formEl) == '1') { 
				return true;
			}
		}
	}
	return false;
}
function hasSelectChkboxValue(el, value) {
	//alert('el = ' + el);
	var i = 1;
	var maxAnswerid = 100;
	var foundElement = false;
	while (i < maxAnswerid) {
		var formEl = document.qform[el + '_' + i];
		var formElChk = document.qform['CHK' + el + '_' + i];
		//alert('document.qform[CHK + el + + i] = ' + document.qform['CHK' + el + '_' + i].name);
		if (formEl && formElChk) {
			foundElement = true;
			// Increase maxAnswerid, if we've got an element close to the boundary, extend the boundary so we're not skipping elements!
			//if (i > (maxAnswerid - 100)) {
				//maxAnswerid += 200;
			//}
			if ((formElChk.checked == true) && (formEl.answervalue == value)) { 
				return true;
			}
		}
		i ++;
	}
	if (!foundElement) { // Answerid is probably out of range
		alert("Could not find checkbox element for element, " + el + " Tried, 1-" + maxAnswerid);
	} else {
		//var formEl = document.qform[el + '_OTHERCHK'];
		//if (formEl) {
			//if (getFormValue(formEl) == '1') { 
				//return true;
			//}
		//}
	}
	return false;
}
function debug(message) {
	logMessage(message, '', 'debug');
}
function logMessage(message, username, type) {
	if (!username) username = '';
	if (!type) type = "msg";
	var logger = document.getElementById('logger');
	if (logger) {
		logger.src = 'lookup/logger.jsp?msg=' + message + '&type=' + type + '&username=' + username;
	}
}
function printInfoText(infoText) {
	var helpTextCell;
	var helpTextDiv;
	if (document.getElementById) { // Level 1 DOM
		helpTextCell = document.getElementById('helptext');
		helpTextDiv = document.getElementById('helptextDiv');
	} else if (document.all) { // Old IE
		helpTextCell = document.all.helptext;
		helpTextDiv = document.all.helptextDiv;
	}
	
	if (helpTextCell) {
		var helpwidth = helpTextCell.offsetWidth;
		var helpheight = helpTextCell.offsetHeight;
		var helpleft = getAbsolutePosX(helpTextCell);
		var helptop = getAbsolutePosY(helpTextCell);

		helpTextDiv.style.left = helpleft + 4;
		helpTextDiv.style.top = helptop + 4;
		//alert('helptextdiv left = ' + helpTextDiv.style.left + ' top = ' + helpTextDiv.style.top);
	}
	//alert('printing infotekst : ' + infoText);

	showQuestionHelp(helpTextDiv,infoText,0,'Utfylling og bruk','');
}
function addAttachFile() {
	if (document.attachform) {
		document.attachform.submit();
	}
}
function stopMessage(stopfield) {
	if (stopMessageFieldOverride && stopfield && (stopfield == stopMessageFieldOverride)) { 
		//alert('stopMessageFieldOverride = ' + stopMessageFieldOverride + ' stopfield = ' + stopfield);
		stopMessageFieldOverride = null;
		return true;
	}
	//alert('stopMessageFieldOverride = ' + stopMessageFieldOverride + ' stopfield = ' + stopfield);
	stopMessageFieldOverride = stopfield;
	return false;
}

function isEnterPressed(event) {
	return (event.keyCode == 13);
}

