// $Id: general.js 65983 2011-07-21 13:25:43Z tore $


var winOpenTempURL = "html/winOpenTemp.html";
if(typeof commonFolder !== 'undefined') winOpenTempURL = commonFolder+winOpenTempURL;
else if(typeof staticFileLocation !== 'undefined') winOpenTempURL = staticFileLocation+winOpenTempURL;
else winOpenTempURL = "/"+winOpenTempURL;
//alert("winOpenTempURL "+winOpenTempURL);


//string used to keep track of doSetTimeout calls etc., can be shown in user error messages if something fails
if(typeof globalCallLogString != 'undefined') alert('general.js is being included more than once!: '+globalCallLogString);
var globalCallLogString = "";
var setTimeoutCount = 0;

//"logging" in a global var (can also be shown user in error messages etc.), easily replaceable 
//with firebug console.log or something even more fancy for local testing
function writeToCallLog(s){
	globalCallLogString += "[ " + new Date().getTime()	+ ": " + s + " ]\n";
}

//simple wrapper function for doSetTimeout to enable simpler debugging using firebug breakpoints etc. - until getting rid of the calls completely
function doSetTimeout(expressionStringOrFunction,waitMS){
	writeToCallLog("setTimeout(" + expressionStringOrFunction + "," + waitMS + ")");	
	setTimeoutCount++;
	setTimeout(expressionStringOrFunction,waitMS);
}

//resets the global call log string
function resetCallLog(){
	globalCallLogString = "";
	setTimeoutCount = 0;
}

//alerts the current call log, using a simple alert box or the at any point political correct modal window if a js UI framework is used
function alertCallLog(){
	//alert("number ofdoSetTimeout calls since reset: " +doSetTimeoutCount + " \n\nTrace:\n------------------\n" + globalCallLogString);
	w = window.open("","logconsoleWindow");
	w.document.writeln(
	  "<html><head><title>Javascript Call Log</title></head>"
	   + "<body bgcolor='white' onLoad='self.focus()'><pre>"
	   + "number ofdoSetTimeout calls since reset: " + setTimeoutCount + " \n\nTrace:\n------------------\n" + globalCallLogString
	   + "</pre></body></html>"
 	);
 	w.document.close()
}

function logCallLog(){
	if (console != 'undefined' && console.log) {
		console.log("number ofdoSetTimeout calls since reset: " +  setTimeoutCount + " \n\nTrace:\n------------------\n" + globalCallLogString);	
	}else{
		alert('console log not active, activate or just use "javascript: alertCallLog()" in your browser address field.');
	}
}


function handleMultipleItems2(actionURL,formName){
	newwin = window.open(winOpenTempURL,"popupForm","scrollbars=yes,toolbar=no,location=no,directories=no,menubar=no,resizable=yes,status=no,height=600,width=650");
	document.forms[formName].target = "popupForm";
	document.forms[formName].action= actionURL;
	//var URL = document.forms['"+formName+"'].submit();
	setTimeout("document.forms['"+formName+"'].submit();",500);
}

function test(){
	alert("2klous2c");
}

function toggleDIV(id, flagit){
	if (flagit == "1"){
		if (document.layers) document.layers[''+id+''].visibility = "show";
		else if (document.all) document.all[''+id+''].style.visibility = "visible";
		else if (document.getElementById) document.getElementById(''+id+'').style.visibility = "visible";
	}else if (flagit = "0"){
		if (document.layers) document.layers[''+id+''].visibility = "hide";
		else if (document.all) document.all[''+id+''].style.visibility = "hidden";
		else if (document.getElementById) document.getElementById(''+id+'').style.visibility = "hidden";
	}
	
}


function checkForm(theform){
//if IE 4+ or NS 6+
	var isFilled = true;
	if (document.all||document.getElementById){
		//screen thru every element in the form
		for (i=0;theform.length>i;i++){
			var tempobj=theform.elements[i];
			if (tempobj.type.toLowerCase()=="text"){
				if (tempobj.value=="" && tempobj.alt != "notMandatory"){
					//alert("Alle obligatorisk felter skal fylles!");
					tempobj.focus();
					return false;
				}
			}
		}
		return true;
	}
}



function submitonce(theform){
	//if IE 4+ or NS 6+
	if (document.all||document.getElementById){
		//screen thru every element in the form, and hunt down "submit" and "reset"
		for (i=0;i<theform.length;i++){
			var tempobj=theform.elements[i]
			if(tempobj.type.toLowerCase()=="submit"||tempobj.type.toLowerCase()=="reset")
				tempobj.disabled=true
		}
	}
}



function disableSubmit(theform){
	//if IE 4+ or NS 6+
	if (document.all||document.getElementById){
		//screen thru every element in the form, and hunt down "submit" and "reset"
		for (i=0;i<theform.length;i++){
			var tempobj=theform.elements[i]
			if(tempobj.type.toLowerCase()=="submit"||tempobj.type.toLowerCase()=="reset"||tempobj.name=="submitButton")
				tempobj.disabled=true
		}
	}
}



function enableSubmit(theform){
	//if IE 4+ or NS 6+
	if (document.all||document.getElementById){
		//screen thru every element in the form, and hunt down "submit" and "reset"
		for (i=0;i<theform.length;i++){
			var tempobj=theform.elements[i]
			if(tempobj.type.toLowerCase()=="submit"||tempobj.type.toLowerCase()=="reset"||tempobj.name=="submitButton")
				tempobj.disabled=false
		}
	}
}



function createWindow(url, externalResources) {
	mywindow = window.open('about:blank','sprettopp','width=793,height=547,toolbar=no,location=no,status=no,menubar=no,scrollbars=yes,resizable=yes');
	createFrameset(url, externalResources);
}



function createFrameset(url, externalResources) {
	var output =
				'<html><head><title>nettopp.biz</title></head>' +
				'<frameset border="0" rows="*,40">' +
				'<frameset border="0" cols="*,147">' +
				'<frame border="0" scrolling="auto" name="mainFrame" src="' +url+ '"/>' +
				'<frame border="0" scrolling="no" name="rightFrame" src="' +externalResources+ '"/>' +
				'</frameset>'+
				'<frame border="0" scrolling="no" name="bottomFrame" src="' +externalResources+ '&amp;pageName=contentBottomMenu"/>' +
				'</frameset></html>';
	mywindow.document.write(output);
}



function createWindowTwoFrames(url, externalResources) {
	mywindow = window.open('about:blank','sprettopp','width=793,height=547,toolbar=no,location=no,status=no,menubar=no,scrollbars=yes,resizable=yes');
	createFramesetTwoFrames(url, externalResources);
}



function createFramesetTwoFrames(url, externalResources) {
	var output =
				'<html><head><title>nettopp.biz</title></head>' +
				'<frameset border="0" rows="*,50">' +
				'<frame border="0" scrolling="auto" name="mainFrame" src="' +url+ '"/>' +
				'<frame border="0" scrolling="no" name="bottomFrame" src="' +externalResources+ '&amp;pageName=contentBottomMenu"/>' +
				'</frameset></html>';
	mywindow.document.write(output);
}



function createBOLDescriptionFrameset(Url1,Url2) {
	var output=
	'<frame border="0" scrolling="auto" name="mainFrame">'+
	'<frameset border="0" rows="*,74">' +
		'<frame border="0" scrolling="auto" name="top"  src="'+Url1+'"/>' +
		'<frame border="0" scrolling="auto" name="rightBottomFrame" src="'+Url2+'"/>' +
	'</frameset>'+
	'</frame>';
	parent.mainFrame.document.write(output);
}



function numbersonly(element, objEvent)
{
	objEvent = (objEvent != null) ? objEvent : window.event; //need this check since IE7 won't accept objEvent as just event. It needs to be window.event. LOK-1588
	var iKeyCode;
	//iKeyCode = objEvent.keyCode;
	if (objEvent.keyCode) iKeyCode = objEvent.keyCode;
	if (objEvent.which) iKeyCode = objEvent.which;
	//alert('iKeyCode '+iKeyCode+' value='+element.value);
	var foundDot = 0;
	if (element.value.indexOf('.') > -1 || element.value.indexOf(',') > -1){
		foundDot = 1;
	}
	var selected = '';
	if (document.selection && document.selection.createRange) {
		
		selected = document.selection.createRange();
		selected = selected.text;
	}
		
	//alert('selected='+selected);
	if (selected.indexOf('.') > -1 || selected.indexOf(',') > -1){
		foundDot = 0;
	}
	
	 if( (iKeyCode>=48 && iKeyCode<=57) || (iKeyCode==44 && foundDot==0) ) {
		return true;
	}
	 if(iKeyCode==46 && foundDot==0) {
//	 	try {
//	        objEvent.keyCode = 44; //Gjør punktum om til komma  // 2009-05-11 lbg : PGS-882 kommentert ut, forskjellig oppførsel i ie7/ff
//	} catch (e) {}
		return true;
	}
	if(iKeyCode==45 && (element.value.lastIndexOf('-') < 0 && selected.length == 0) ) {
		//alert('minus: ingen fra før, ikke noe er valgt');
		element.value = '-' + element.value;
		return false;
	}
	if(iKeyCode==45 && (element.value.lastIndexOf('-') > -1 && selected.length == 0) ) {
		//alert('minus, det er en fra før, ikke noe er valgt - gjør ingenting');
		return false;
	}
	if(iKeyCode==45 && (element.value.lastIndexOf('-') == -1 && selected.length > 0) ) {
		//alert('minus: noe er valgt, ingen minus fra før');
		document.selection.createRange().text=""; //Fjerner første det som er valgt
		self.focus();
		element.focus(); //sikrer at jeg står først i formen (ikke så elegant kanskje...)
		document.selection.createRange().text="-" //setter inn minusen
		return false;
	}
	if(iKeyCode==45 && element.value.lastIndexOf('-') > -1 && selected.length > 0 && selected.lastIndexOf('-') == -1) {
		//alert('minus. noe er valgt, minus eksisterer fra før, men ikke i selected - gjør ingenting');
		return false;
	}
	if(iKeyCode==45 && element.value.lastIndexOf('-') > -1 && selected.length > 0 && selected.lastIndexOf('-') > -1) {
		//alert('minus: noe er valgt, minus eksisterer fra før OG er i selected - sletter og legger inn');
		return true;
	}
	if(iKeyCode==37 || iKeyCode==39) {
		//i FF blir % og <- det samme og ' og -> det samme. Lagt inn så % og ' stoppes, mens pil høyre og venstre er ok
		if (typeof(objEvent.which) == "undefined" || objEvent.which == 37 || objEvent.which == 39)  {			
			return false;
		}
		else { 
			return true;
		}
		return true;
	}
	if(iKeyCode==8 || iKeyCode==9){
		return true;
	}	
	return false;
}


function openWindow(url) {
	var availheight=((screen.availHeight-500)/2);
	var availwidth=((screen.availWidth-700)/2);
	winStats='toolbar=no,location=no,directories=no,menubar=no,resizable=yes,';
	winStats+='scrollbars=yes,status=no,width=700,height=500';
	if (navigator.appName.indexOf("Microsoft")>=0) {
		winStats+=',left='+availwidth+',top='+availheight;
	}else{
		winStats+=',screenX='+availwidth+',screenY='+availheight;
	}
	//JE@2006-09-20 - Assumes that we never use more than two popups
	//floater=window.open(url,"sprettopp",winStats)
	floater=window.open(url,'',winStats)
}

function openWindow(url,width,height) {
	var availheight=((screen.availHeight-height)/2);
	var availwidth=((screen.availWidth-width)/2);
	var windowName = 'sprettopp';
	if (parent.name == 'sprettopp') {
		windowName = 'sprettopp2';
	}
	//Scrollbars is set to yes because AUTO doesn't work in the structurebuilder
	winStats='resizable=yes,toolbar=no,status=no,location=no,directories=no,menubar=no,scrollbars=yes,width='+width+',height='+height;
	if (navigator.appName.indexOf("Microsoft")>=0) {
		winStats+=',left='+availwidth+',top='+availheight;
	}else{
		winStats+=',screenX='+availwidth+',screenY='+availheight;
	}
	//JE@2006-09-20 - Assumes that we never use more than two popups
	//floater=window.open(url,windowName,winStats)
	floater=window.open(url,'',winStats);
}

function openWindowFull(url) {
    var windowName = 'sprettopp';
    try {
        if (parent && parent.name == 'sprettopp') {
            windowName = 'sprettopp2';
        }
    } catch(ex) {
        window.status='Ex:'+ex.message;
        windowName = 'sprettopp2';
    }
    //Scrollbars is set to yes because AUTO doesn't work in the structurebuilder
    winStats='resizable=yes,fullscreen=yes,toolbar=no,status=no,location=no,directories=no,menubar=no,scrollbars=yes';

    floater=window.open(url,'',winStats);
}

function openLoadingWindow(url,width,height) {
	var availheight=((screen.availHeight-height)/2);
	var availwidth=((screen.availWidth-width)/2);
	var windowName = 'sprettopp';
	if (parent.name == 'sprettopp') {
		windowName = 'sprettopp2';
	}
	//Scrollbars is set to yes because AUTO doesn't work in the structurebuilder
	winStats='resizable=yes,toolbar=no,status=no,location=no,directories=no,menubar=no,scrollbars=yes,width='+width+',height='+height;
	if (navigator.appName.indexOf("Microsoft")>=0) {
		winStats+=',left='+availwidth+',top='+availheight;
	}else{
		winStats+=',screenX='+availwidth+',screenY='+availheight;
	}
	//JE@2006-09-20 - Assumes that we never use more than two popups
	//floater=window.open(url,windowName,winStats)
	floater=window.open(winOpenTempURL,'',winStats);
    floater.location=url
}

function openMediaWindow(url,width,height) {
	var availheight=((screen.availHeight-height)/2);
	var availwidth=((screen.availWidth-width)/2);
	winStats='resizable=no,toolbar=no,status=no,location=no,directories=no,menubar=no,';
	winStats+='scrollbars=no,width='+width+',height='+height;
	if (navigator.appName.indexOf("Microsoft")>=0) {
		winStats+=',left='+availwidth+',top='+availheight;
	}else{
		winStats+=',screenX='+availwidth+',screenY='+availheight;
	}
	floater=window.open(url,"",winStats)
}

function submitToPopup(termSearchForm) {
	newwin = window.open('about:blank','Ordliste','scrollbars=yes,toolbar=no,location=no,directories=no,menubar=no,resizable=yes,status=no,height=500,width=700');
	newwin.focus();
}

var ie=(document.all)?1:0;



function flashy_DoFSCommand(command, args) {
	if (ie) {
		document.flashy.SetVariable("finished", "true");
	} else {
		self.document.questionform.flashy.SetVariable("finished", "true");
	}
}



function assessmentRestart() {
	var obj = eval(parent.window.location);
	var org = obj.href;
	parent.window.location.reload();
}
var icons=new Array(4);
	icons["information"]=64;
	icons["question"]=32;
	icons["critical"]=16;
	icons["exclamation"]=48;
var buttons=new Array(6);
	buttons["okCancel"]=1;
	buttons["abortRetryIgnore"]=2;
	buttons["yesNoCancel"]=3;
	buttons["yesNo"]=4;
	buttons["retryCancel"]=6;
var defButton=new Array(2);
	defButton[2]=256;
	defButton[3]=512;
var systemModal=4096;
var returnValues=new Array(7);
	returnValues["ok"]=1;
	returnValues["cancel"]=2;
	returnValues["abort"]=3;
	returnValues["retry"]=4;
	returnValues["ignore"]=5;
	returnValues["yes"]=6;
	returnValues["no"]=7;



function generatePrompt(text,title,defaultText){
	text=(text==null)?'no text value supplied':text;
	title=(title==null)?'no title value supplied':title;
	defaultText=(defaultText==null)?'no default text value supplied':defaultText;
	if (!ie) {
		return prompt(text,defaultText);
	} else {
		return generateInput(text,title,defaultText);
	}
}



function generateBox(message,title,icon,buttons,modal,defaultButton){
	message=(message==null)?'no message supplied':message;
	title=(title==null)?'no title supplied':title;
	icon=(icon==null)?48:icon;
	buttons=(buttons==null)?0:buttons;
	modal=(modal==null)?0:modal;
	defaultButton=(defaultButton==null)?0:defaultButton;
	if (!ie){
		if (icon==icons["exclamation"] || icon==icons["critical"] || icon==icons["information"] || icon==0) {
			alert(message);
			return 1;
		} else return confirm(message);
	} else {
		return generateVBBox(message,title,icon+buttons+modal+defaultButton);
	}
}



function wannaQuit(spm, title, icon, butt) {
	reallyQuit = generateBox(spm, title, icon, butt, systemModal, 0);
	if ((reallyQuit == 6)||(reallyQuit == 1)) {
		parent.window.close();
	}
}



function RBCheck(r,message) {
	var isChecked = 0;
	var x = r.length;
	var i = 0;
	x--;
	while (i != x) {
		i++;
		if (r[i].checked == true) {
			isChecked = 1;
		}
	}
	if (isChecked == 0) {
		alert(message);
		return false;
	} else {
		r.submit();
	}
}



function numericCheck(r,message) {
	var isChecked = 0;
	var x = r.length;
	var i = 0;
	x--;
	while (i != x) {
		i++;
		if (r[i].value == "") {
			isChecked = 1;
		}
	}
	if (isChecked == 1) {
		alert(message);
		return false;
		} else {
			r.submit();
	}
}



function orgTreeWin(orgURL) {
	var remote = open(orgURL, "OrgTreeWin", 'scrollbars=yes,menubar=no,status=no,toolbar=no,height=400,width=250,resizable=yes');
	if (remote.opener == null) // if something went wrong
		remote.opener = window;
}



function selectSubjectNode(formName, val1,val2){
	//alert("hey");
	window.opener.document.forms[formName].subject.value = val1;
	window.opener.document.forms[formName].subjectId.value = val2;
	window.opener.document.forms[formName].subject.focus();
	this.close();
}

function initialCheckBox2(formName, elementName){
	var theForm = document.forms[formName];
	for (var i=0;i< theForm.elements.length;i++)	{
		var e = theForm.elements[i];
		if ((e.name == elementName) && (e.type=='checkbox'))
		{
		e.checked = theForm.selectAllBox.checked;
		}
	}
}

function initialCheckBox(){
	for (var i=0;i< document.showContentItems.elements.length;i++)	{
		var e = document.showContentItems.elements[i];
		if ((e.name != 'selectAllBox') && (e.type=='checkbox'))
		{
		e.checked = document.showContentItems.selectAllBox.checked;
		}
	}
}

function handleMultipleItems(additionalParameters,formName){
	newwin = window.open(winOpenTempURL,"popupForm","scrollbars=yes,resizable=yes,status=no,height=600,width=722");
	//"scrollbars=yes,toolbar=no,location=no,directories=no,menubar=no,resizable=yes,status=no,height=600,width=650");
	document.forms[formName].target = "popupForm";
	document.forms[formName].action= servlet+"&"+additionalParameters;
	document.forms[formName].submit();
}

function handleMultipleItems2(actionURL,formName){
	newwin = window.open(winOpenTempURL,"popupForm","scrollbars=yes,toolbar=no,location=no,directories=no,menubar=no,resizable=yes,status=no,height=600,width=650");
	document.forms[formName].target = "popupForm";
	document.forms[formName].action= actionURL;
	//var URL = document.forms['"+formName+"'].submit();
	setTimeout("document.forms['"+formName+"'].submit();",500);
}


function calendarWinWithPosition(URL,left, top) {
	var remote = open(URL, "calendarWin", 'scrollbars=yes,menubar=no,status=no,toolbar=no,height=182,width=273,resizable=yes,left='+left+',top='+top);
	if (remote.opener == null) // if something went wrong
		remote.opener = window;
}

function calendarWin(URL) {
	var remote = open(URL, "calendarWin", 'scrollbars=no,menubar=no,status=no,toolbar=no,height=182,width=273,resizable=yes');
	if (remote.opener == null) // if something went wrong
		remote.opener = window;
}



function openWind(url) {
	var availheight=((screen.availHeight-650)/2);
	var availwidth=((screen.availWidth-700)/2);
	winStats='toolbar=no,location=no,directories=no,menubar=no,resizable=yes,';
	winStats+='scrollbars=yes,width=700,height=685';
	if (navigator.appName.indexOf("Microsoft")>=0) {
		winStats+=',left='+availwidth+',top='+availheight;
	}else{
		winStats+=',screenX='+availwidth+',screenY='+availheight;
	}
	floater=window.open(url,"sprettopp",winStats)
}



function openCustomWindow(url,width,height) {
	var availheight=((screen.availHeight-height)/2);
	var availwidth=((screen.availWidth-width)/2);
	winStats='toolbar=no,location=no,directories=no,menubar=no,resizable=yes,';
	winStats+='scrollbars=yes,width='+width+',height='+height;
	if (navigator.appName.indexOf("Microsoft")>=0) {
		winStats+=',left='+availwidth+',top='+availheight;
	}else{
		winStats+=',screenX='+availwidth+',screenY='+availheight;
	}
	floater=window.open(url,"sprettopp",winStats)
}


function openCourseBuildingWindow(url,width,height) {
	var availheight=((screen.availHeight-height)/2);
	var availwidth=((screen.availWidth-width)/2);
	winStats='toolbar=no,location=no,directories=no,menubar=no,resizable=yes,status=yes,';
	winStats+='scrollbars=yes,width='+width+',height='+height;
	if (navigator.appName.indexOf("Microsoft")>=0) {
		winStats+=',left='+availwidth+',top='+availheight;
	}else{
		winStats+=',screenX='+availwidth+',screenY='+availheight;
	}
	floater=window.open(url,"sprettopp",winStats)
}



//Loads the supplied url in the current window if the message is confirmed
function confirmMessage(url, msg){
	if (confirm(msg)){
		document.location.href=url;
	}
}

//This function checkes/unchecks all the checkboxes which starts with
//the name supplied in the String parameter 'checkBoxName'. The checkBoxes
//are given the value of the checkBox with name equal to the String parameter
//checkAllBoxName. This method is useful in pages where a lot of CheckBoxes
//are listed and where one want's a quick way to check/uncheck all.
//
//Notice that the method only tests if the checkboxes starts with the supplied
//name. This makes the method useful in different request parameter sending contexts.
//
//Parameter:
//formName is the name of the form which the Check All box is
//checkAllBoxName is the name of the checkbox which decides
//CheckBoxName is the name of the checkboxes which should get
//the same value as the box with name checkAllBoxName
function selectAllCheckBox(formName, checkAllBoxName, checkBoxName){
	for (var i=0; i < document.forms[formName].elements.length; i++)	{
		var e = document.forms[formName].elements[i];
		var n = e.name;
		var index = n.indexOf(checkBoxName);
		if ((index > -1 ) && (e.type=='checkbox')){
			e.checked = document.forms[formName].elements[checkAllBoxName].checked;
		}
	}
}


/***********************************************
* Auto Maximize Window Script- © Dynamic Drive (www.dynamicdrive.com)
* This notice must stay intact for use
* Visit http://www.dynamicdrive.com/ for this script and 100's more.
***********************************************/

function maximize(win){
	win.moveTo(0,0);
	if (document.all) {
		win.resizeTo(screen.availWidth,screen.availHeight);
	}
	else if (document.layers||document.getElementById) {
		if (win.outerHeight<screen.availHeight||win.outerWidth<screen.availWidth){
			win.outerHeight = screen.availHeight;
			win.outerWidth = screen.availWidth;
		}
	}
}

function mergeDates(formName) {
	if (document.forms[formName].startDay.value != '' && document.forms[formName].endDay.value != '') {
		document.forms[formName].startDate.value = document.forms[formName].startDay.value+' '+document.forms[formName].startHour.value+':'+document.forms[formName].startMinute.value+':00';
		if((document.forms[formName].endHour.value == document.forms[formName].startHour.value) && (document.forms[formName].endMinute.value == document.forms[formName].startMinute.value) ) {
			document.forms[formName].endDate.value = document.forms[formName].endDay.value+' 23:59:00';
		}
		else
			document.forms[formName].endDate.value = document.forms[formName].endDay.value+' '+document.forms[formName].endHour.value+':'+document.forms[formName].endMinute.value+':00';

		if (document.forms[formName].assignmentDeadline && document.forms[formName].assignmentDay.value != '') {
			document.forms[formName].assignmentDeadline.value = document.forms[formName].assignmentDay.value+' '+document.forms[formName].assignmentHour.value+':'+document.forms[formName].assignmentMinute.value+':00';
		}
	}
}

function checkDates(formName) {
	if (document.forms[formName].startDate.value=='' || document.forms[formName].endDate.value=='' || document.forms[formName].startDate.value==null || document.forms[formName].endDate.value==null) {
		alert('Dato må settes');
		return(false);
	}else if (document.forms[formName].endDate.value < document.forms[formName].startDate.value) {
		alert('Sluttdato må være større enn startdato');
		return(false);
	}else{
		document.forms[formName].submit();
	}
}

/**
* Show/hide a div.
* whichLayer is id of the div
*/
function toggleLayer(whichLayer)
{
	//alert('whichLayer '+whichLayer);
var style2; 	
if (document.getElementById)
{
// this is the way the standards work
style2 = document.getElementById(whichLayer).style;
//style2.display = style2.display? "":"block";
}
else if (document.all)
{
// this is the way old msie versions work
style2 = document.all[whichLayer].style;
//style2.display = style2.display? "":"block";
}
else if (document.layers)
{
// this is the way nn4 works
style2 = document.layers[whichLayer].style;
//style2.display = style2.display? "":"block";
}
//alert('disp='+style2.display);
if(style2.display == ""){
	style2.display = "none";
}else if(style2.display == "block"){
	style2.display = "none";
}else if (style2.display == "none"){
	style2.display = "block";
}

}

/**
* Show/hide a div.
* whichLayer is id of the div
* displayMe boolean	
*/
function setLayerDisplay(whichLayer, displayMe)
{

var newStyle = "none";
if(displayMe){
	newStyle = "block";
}		
//alert("setLayerDisplay newStyle="+newStyle+" whichLayer="+whichLayer);	
if (document.getElementById)
{
// this is the way the standards work
var style2 = document.getElementById(whichLayer).style;
style2.display = newStyle;
}
else if (document.all)
{
// this is the way old msie versions work
var style2 = document.all[whichLayer].style;
style2.display = newStyle;
}
else if (document.layers)
{
// this is the way nn4 works
var style2 = document.layers[whichLayer].style;
style2.display = newStyle;
}
}

function setLayerDisplay2(whichLayer, displayMe)
{

var newStyle = "2000px";
if(displayMe){
	newStyle = "0px";
}		

//alert("setLayerDisplay newStyle="+newStyle+" whichLayer="+whichLayer);
if (document.getElementById)
{
// this is the way the standards work
var style2 = document.getElementById(whichLayer).style;
style2.left = newStyle;
}
else if (document.all)
{
// this is the way old msie versions work
var style2 = document.all[whichLayer].style;
style2.left = newStyle;
}
else if (document.layers)
{
// this is the way nn4 works
var style2 = document.layers[whichLayer].style;
style2.left = newStyle;
}
}

function reloadWithNewLanguage(langVar, languageId){ 
	var tempurl = document.location.href;
	//alert("Actual URL is: " + tempurl);
	var i = tempurl.indexOf(langVar + '=',0);
	if (i > 0){
		//alert("Found '" + langVar + "' at index: " + i);
		var amp = tempurl.indexOf('&',i);
		tempurl = tempurl.substring(0, i-1);
		if (amp > 0){
			//alert("Found '&' at index: " + amp);
			var temp = document.location.href;
			tempurl = tempurl + temp.substring(amp, temp.length);
		}
	}else{
		var j = tempurl.indexOf('?',0);
		if (j < 1){
			tempurl = tempurl + '?'  
		}
	}
	//alert("URL now: " + tempurl);
	tempurl = tempurl + '&amp;' + langVar + '='+languageId;
	//alert("URL now: " + tempurl);
	document.location.href=tempurl;
}

function fillTitle(form) {
	var filename=form.filename.value.split("\\");
	var shortFilename = filename[filename.length-1].split(".");
	if (form.title.value == '') {
		form.title.value = shortFilename[0]
	}
}

function openNewWindow(URLtoOpen, windowName, windowFeatures) { 
  newWindow=window.open(URLtoOpen, windowName, windowFeatures);
}



function checkBGClass(tbl, strOddCell, strEvenCell){
    if(!strOddCell){
        strOddCell = 'oddCell';
    }
    if(!strEvenCell){
        strEvenCell = 'evenCell';
    }
    //alert('strOddCell='+strOddCell+' strEvenCell='+strEvenCell);
    var bgclass = strEvenCell;
	for(var i=0;i<tbl.rows.length;i++){
		if(i % 2 == 1){
			bgclass = strOddCell;
		}else{
			bgclass = strEvenCell;
		}
        //alert('bgclass='+bgclass);
        var row = tbl.rows[i];
        row.className = bgclass;

        //for(var j=0;j<row.cells.length;j++){
        	//alert('dd ' +j);
            //row.cells[j].className = bgclass;
        //}
	}
}


function integersOnly(myfield, e, formen) {
	var Key;
	var keychar;

	if (window.event)
   		Key = window.event.keyCode;
	else if (e)
   		Key = e.which;
	else
	   	return true;

	keychar = String.fromCharCode(Key);
	var digit = /\d/;
	var punktum = /\./;
	var komma = /,/;
	var digitMatch = keychar.match(digit);
	var punktumMatch = keychar.match(punktum);
	var kommaMatch = keychar.match(komma);
	var update = 0;
	var oldInput = myfield.value;
	var inputArray = new Array();
	var i;
	for (i = 0; i < oldInput.length; i++)
		inputArray[i] = oldInput.charAt(i);

	if  (punktumMatch != null) {
		return false;
	}
	if (update == 0)
		if (kommaMatch != null) {
			return false;
		}
	if (update == 0)
		if (digitMatch != null) {
			update++;
			if (oldInput.length != 0)
				inputArray[oldInput.length] = keychar;
			else
				inputArray[0] = keychar;
		}
	if (update == 1) {
		var i;
		var newString = "";
		if (oldInput.length != 0)
			for (i = 0; i < inputArray.length; i++)
				newString += inputArray[i];
		else
			newString = inputArray[0];
		myfield.value = newString;
		return false;
	} else {
		return false;
	}
}

/**
 * Simpler integersonly function, allows integers and backspace
 * @param evt
 */
function positiveIntegersOnly(evt) {
    evt = (evt) ? evt : window.event
    var charCode = (evt.which) ? evt.which : evt.keyCode
//    alert(charCode);
    
    if (charCode > 31 && (charCode < 48 || charCode > 57) ) {
        return false;
    }

    return true;
}


function replaceAllStr(original, toReplace, replacement){
    if(original != null && toReplace != null && replacement != null){
        while(original.indexOf(toReplace, 0) > -1){
            original = original.replace(toReplace, replacement);
        }
    }
    return original;
}

/*sjekker om det er noen checkbox'er som er krysset av. Dersom det er det
  enabler den dropdownmenyen*/
function checkContent(formName,selector){
	for (var i=0; i < document.forms[formName].elements.length; i++)	{

		var e = document.forms[formName].elements[i];
		if ( e.type == 'checkbox' && e.checked == true )
		{
		document.getElementById(''+selector+'').disabled = false;
		return;
		}
	}
	document.getElementById(''+selector+'').disabled = true;
}

function getStyleSheet(StyleSheetURL) {
	//<![CDATA[
    StyleSheetURL = checkURLProtocol(StyleSheetURL);
	if(document.createStyleSheet) {

	document.createStyleSheet(StyleSheetURL);

	}

	else {

	var styles = "@import url("+StyleSheetURL+");";

	var newSS=document.createElement('link');

	newSS.rel='stylesheet';

	newSS.href='data:text/css,'+escape(styles);

	document.getElementsByTagName("head")[0].appendChild(newSS);

	}

	//]]>
}

logObject_str = function(obj){
    //var outp = $('debug');
    var retval = '';
    for(var x in obj){
        retval += '\n'+x+' : '+obj[x];
    }
    return retval;
}

/**
 * document.getElementsByClassName is deprecated in Prototype 1.6, and seems buggy in ff3
 * This method should do the same job. Needs Prototype.js
 * @param _desiredClass
 * @param ancestorElement
 * @returns Array of descendants with desired class
 */
getDescendantsByClassName = function(_desiredClass, ancestorElement ){
    var _descendants = [];

    if(ancestorElement)
    try {
        var desc_ = $(ancestorElement.id).descendants();
        for (var i = 0; i < desc_.length; i++) {
            var descy = desc_[i];
            if (descy.hasClassName(_desiredClass)) {
                //alert('getDescendantsByClassName '+descy.className+'_'+descy.id);
                _descendants[_descendants.length] = descy;
            }
        }
    } catch(ex) {
        //alert('exception getting descendants for '+ancestorElement);
    }
    return _descendants;
}

/**
 * IE8 gives a warning if this stylesheets are fetched with http: from a https: page.
 * Created as a quick fix to PGSCF-166
 * @param s_url
 */
checkURLProtocol = function(s_url){
    try{
        if(s_url.indexOf(location.protocol)== 0){
            return s_url;
        }else if (s_url.indexOf("://") > -1){
            var pos = s_url.indexOf("://");
            return location.protocol+s_url.substring(pos+1);
        }
    }catch(err){

    }
    return s_url;
};

var setBtnLoader = function(btnId) {
    var btn = $(btnId);
    var loader = $('btnLoader');
    if (loader == null) {
            // should do this in prototype, but how do i find body
            var body = document.getElementsByTagName('body').item(0);
            var img = document.createElement('img');
            img.setAttribute('id', 'btnLoader');
            img.setAttribute('src', staticFileLocation + 'gfx/admin/btn-loader.gif');
            img.setAttribute('style', 'position: absolute');
            body.appendChild(img);
            loader = $('btnLoader');
        }
        loader.clonePosition(btn, {
        setWidth: false,
        setHeight: false,
        offsetLeft: (btn.getWidth() / 2 - loader.getWidth() / 2),
        offsetTop: (btn.getHeight() / 2 - loader.getHeight() / 2)
    });
    loader.show();
};

var clearBtnLoader = function() {
    var loader = $('btnLoader');
    if (loader != null) {
        loader.hide();
    }
};

//alert('1' +escape('æøå'));
//alert('2' +encodeURIComponent('æøå'));
if(escape('æøå')!='%E6%F8%E5'){
//    alert('override utf-8');
    // assuming UTF-8, related to PGS-418
    escape = function(param){
        return encodeURIComponent(param);
     }
}
