var FieldChanged = false;

var StrAllYellowFields = '\nAlle gule felter skal benyttes.';
var FieldArray = ':';

var strMaxLenLegend1 = 'Du kan maximal indtaste ';
var strMaxLenLegend2 = ' tegn i dette felt';
var strMustBeANumber = 'Feltet skal indeholde et tal.';
var strNoBetweenLegend1 = 'Feltet skal indeholde et tal som er mellem ';
var strNoBetweenLegend2 = ' og ';
var strMustBeAnEmail = 'Feltet skal indeholde en korrekt e-mail adresse.';
var strDateText1 = 'Feltet skal indeholde en dato\ni formatet:\ndd-mm-yyyy\neller\nddmmyy\neller\nddmmyyyy';
var strDateText2 = 'Feltet skal indeholde en dato og tid\ni formatet:\ndd-mm-yyyy hh:nn\neller\nddmmyy hhnn\neller\nddmmyyhhnn';
var strDateText3 = 'Feltet skal indeholde en dato og tid\ni formatet:\ndd-mm-yyyy hh:nn\neller\nddmmyy hhnn\neller\nddmmyyhhnn\neller\nvære tomt.';
var strTimeText  = 'Feltet skal indeholde en tid\ni formatet:\nhh:nn\neller\nhhnn';

var checkOldDateTime = false;

function trim (value) {
    var str = value.replace(/^\s\s*/, ''), ws = /\s/, i = str.length;
    while (ws.test(str.charAt(--i))){}
    return str.slice(0, i + 1);
}

function selectNone(object) {
    for (var i=0, l=object.options.length;i<l;i++) {
        object.options[i].selected = false;
    }
}

function deleteOption(object,index) {
    object.options[index] = null;
}

function addOption(object,text,value) {

  selectNone(object);

	var defaultSelected = true;
  var selected = true;

	var tekstLen = text.lastIndexOf(' (Nicam)');
	if (tekstLen>0) {
		text = text.substring(0,tekstLen)+'*';
		var valueLen = value.lastIndexOf(':N');
		value = value.substring(0,valueLen);
	}

	var optionName = new Option(text, value, defaultSelected, selected);

  object.options[object.length] = optionName;
}

function selectAll(object) {
    for (var i=0, l=object.options.length;i<l;i++) {
        object.options[i].selected = true;
    }
}

function copySelected(fromObject,toObject) {
	var i;
    for (i=0, l=fromObject.options.length;i<l;i++) {
        if (fromObject.options[i].selected) {
            addOption(toObject,fromObject.options[i].text,fromObject.options[i].value);
		}
    }
    for (i=fromObject.options.length-1;i>-1;i--) {
        if (fromObject.options[i].selected) {
            deleteOption(fromObject,i);
		}
    }
}

function copySelected2(fromObject,toObject) {
	var i;
	alert(fromObject.name);
    for (i=0, l=fromObject.options.length;i<l;i++) {
        if (fromObject.options[i].selected) {
            addOption(toObject,fromObject.options[i].text,fromObject.options[i].value);
		}
    }
    for (i=fromObject.options.length-1;i>-1;i--) {
        if (fromObject.options[i].selected) {
            deleteOption(fromObject,i);
		}
    }
}

function copyAllFastEdition(fromObject,toObject) {
	$(toObject).html($(fromObject).html());
	$(fromObject).empty();
}

function copyAll(fromObject,toObject) {
	var i;
    for (i=0, l=fromObject.options.length;i<l;i++) {
        addOption(toObject,fromObject.options[i].text,fromObject.options[i].value);
    }
    for (i=fromObject.options.length-1;i>-1;i--) {
        deleteOption(fromObject,i);
    }
}

function flytop(object) {
    if (object.options.selectedIndex != -1) {
        index = object.options.selectedIndex;
        if ( index === 0 ) {
        } else {
        byttekst = object.options[object.options.selectedIndex - 1].text;
        object.options[object.options.selectedIndex - 1].text = object.options[object.options.selectedIndex].text;
        object.options[object.options.selectedIndex].text = byttekst;
        object.options.selectedIndex = index-1;
        }
    }
}



function replace(string,text,by) {
// Replaces text with by in string
    var strLength = string.length, txtLength = text.length;
    if ((strLength === 0) || (txtLength === 0)) { return string; }

    var i = string.indexOf(text);
    if ((!i) && (text != string.substring(0,txtLength))) { return string; }
    if (i === -1) { return string; }

    var newstr = string.substring(0,i) + by;

    if (i+txtLength < strLength) {
        newstr += replace(string.substring(i+txtLength,strLength),text,by);
	}

    return newstr;
}

function maxLength(object,maxLen){

	if (object.value.length>maxLen)
	{
		alert(strMaxLenLegend1 + maxLen + strMaxLenLegend2);
		object.value = object.value.substring(0,maxLen);
		object.focus();
		return true;
	}
	return true;
}


function setValidate(field){
FieldArray += field+':';
}

function validateFields(Object) {

	var valid = true;
	var myType;
	var ObjectName;
	var sDummy='';


	var checkBoxes = false;
	var checkboxChecked = false;
	var radioButtons = false;
	var radioChecked = false;

    for (var i=0, j=Object.elements.length; i<j; i++) {
		myType = Object.elements[i].type;
		ObjectName = Object.elements[i].name;


		if (FieldArray.indexOf(':'+ObjectName+':')!=-1){

			if (myType === 'select-multiple') {

				if (-1 == Object.elements[i].selectedIndex){
						valid = false;
						sDummy += '\''+ObjectName+'\' skal vælges.\n';
						Object.elements[i].style.backgroundColor="#FFFF99";
					}
			} else
			if (myType==='select-one') {

				if (-1 == Object.elements[i].options[Object.elements[i].selectedIndex].value){
						valid = false;
						sDummy += '\''+ObjectName+'\' skal vælges.\n';
						Object.elements[i].style.backgroundColor="#FFFF99";
					}
			} else
			if (myType==='text' || myType === 'password' || myType === 'textarea') {
				if (''===trim(Object.elements[i].value)){
						valid = false;
						sDummy += '\''+ObjectName+'\' skal udfyldes.\n';
						Object.elements[i].style.backgroundColor="#FFFF99";
				}
			} else
			{
				if (myType === 'radio') {
					radioButtons = true;
					if (Object.elements[i].checked) { radioChecked = true; }
				}

				if (myType === 'checkbox') {
					checkBoxes = true;
					if (Object.elements[i].checked) {checkboxChecked = true;} else { Object.elements[i].style.backgroundColor="#FFFF99";}
				}
			}
		}
    }

    if ((checkBoxes && !checkboxChecked) || (radioButtons && !radioChecked)){ valid = false;sDummy+=ObjectName+'\n'; }

    if (!valid){
        alert(StrAllYellowFields);
	}

    return valid;
}

function wordcount(string) {
  var a = string.split(/\s+/g); // split the sentence into an array of words
  return a.length;
}

function countInstances(string, word) {
  var substrings = string.split(word);
  return substrings.length - 1;
}


function cfinit(){ FieldChanged = false; }
function cf(){ FieldChanged = true; }
function cfi(object,min,max){
	cf();
	if(object.value===''){
		return true;
	}
	var str=parseInt(object.value,10)+0;
	if(isNaN(str)){
		window.alert(strMustBeANumber);
		object.focus();
		return false;
	} else
	{
		if (str<min|str>max){
			window.alert(strNoBetweenLegend1 + min + strNoBetweenLegend2 + max +'.');
			object.focus();
			return false;
		}
		else{
			object.value=str;
			return true;
			}
		}
	}

function cent(amount) {
// returns the amount in the .99 format
    amount -= 0;
    var str = (amount == Math.floor(amount)) ? amount + '.00' : (  (amount*10 == Math.floor(amount*10)) ? amount + '0' : amount);
//	alert( Math.floor(amount) );
	return str;
}

function roundNumber(num, dec) {
	var result = Math.round( Math.round( num * Math.pow( 10, dec + 1 ) ) / Math.pow( 10, 1 ) ) / Math.pow(10,dec);
	return result;
}

function cff(object,min,max,dec){
	cf();
	var value=replace(object.value,',','.');

	var str=parseFloat(value)+0.0;
	if(isNaN(str)){
		window.alert(strMustBeANumber);
		object.focus();
		return false;
	}
	else{
		if (str<min|str>max){
			window.alert(strNoBetweenLegend1 + min + strNoBetweenLegend2 + max+'.');
			object.focus();
			return false;
		}
		else{
			str=roundNumber(str, dec);
			object.value=replace(str+'','.',',');
			return true;
		}
	}
}


function isEmail(emailStr){
var knownDomsPat=/^(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum)$/;
var emailPat=/^(.+)@(.+)$/;
var specialChars="\\(\\)><@,;:\\\\\\\"\\.\\[\\]";
var validChars="\[^\\s" + specialChars + "\]";
var quotedUser="(\"[^\"]*\")";
var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/;
var atom=validChars + '+';
var word="(" + atom + "|" + quotedUser + ")";
var userPat=new RegExp("^" + word + "(\\." + word + ")*$");
var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$");
var matchArray=emailStr.match(emailPat);
var i;

if(matchArray===null){
return false;
}
var user=matchArray[1];
var domain=matchArray[2];
for(i=0; i<user.length; i++){
if(user.charCodeAt(i)>127){
return false;
}
}
for(i=0;i<domain.length;i++){
if(domain.charCodeAt(i)>127){
return false;
}
}
if(user.match(userPat)===null){
return false;
}
var IPArray=domain.match(ipDomainPat);
if(IPArray!==null){
for(i=1;i<=4;i++){
if(IPArray[i]>255){
return false;
}
}
return true;
}
var atomPat=new RegExp("^" + atom + "$");
var domArr=domain.split(".");
var len=domArr.length;
for(i=0;i<len;i++){
if(domArr[i].search(atomPat)==-1){
return false;
}
}
if(domArr[domArr.length-1].length!=2 && domArr[domArr.length-1].search(knownDomsPat)==-1){
return false;
}
if(len<2){
return false;
}
return true;
}

function cfe(object){
	cf();
	if (object.value===''){return true;}
	else{
	if (!isEmail(object.value)){
		window.alert(strMustBeAnEmail);
		object.focus();
		return false;
	}else{return true;}
	}
}

function y2k(year) { return (year < 100) ? parseInt(year,10) + 2000 : (year < 200) ? parseInt(year,10) + 1900 : year;}
function n2(value) { return (parseInt(value,10) < 10) ? '0' + parseInt(value,10) : '' + value;}

function date(){
	var d = new Date();
	return n2(d.getDate())+'-'+n2(d.getMonth()+1)+'-'+d.getFullYear();
}
function datetime(){
	var d = new Date();
	return n2(d.getDate())+'-'+n2(d.getMonth()+1)+'-'+d.getFullYear()+' '+n2(d.getHours())+':'+n2(d.getMinutes());
}

function formatDate(d){
	return n2(d.getDate())+'-'+n2(d.getMonth()+1)+'-'+d.getFullYear();
}




function isDateOK(xday,xmonth,xyear){
	var d = new Date();
	xmonth=((!xmonth)?d.getMonth()+1:xmonth);
	xyear=((!xyear)?d.getFullYear():y2k(xyear));
	var test = new Date();
	test.setFullYear(xyear,xmonth-1,xday);
	if((test.getFullYear() == xyear) &&
		(xmonth == test.getMonth()+1) &&
		(xday == test.getDate())){
			return n2(xday)+'-'+n2(xmonth)+'-'+xyear;
		}
	else
		{
			return '';
		}
}


function isDateTimeOK(day,month,year,hour,min) {
	var d = new Date();
	month=((!month)?d.getMonth()+1:month);
	year=((!year)?y2k(d.getYear()):y2k(year));
	hour=((!hour)?'00':hour);
	min=((!min)?'00':min);
    var test = new Date(year,month-1,day,hour,min);

	if ( (y2k(test.getYear()) == y2k(year)) &&
         (month == test.getMonth()+1) &&
         (day == test.getDate()) &&
         (hour == test.getHours()) &&
         (min == test.getMinutes()) ) {
			if ((checkOldDateTime) && ( test<datetime()))
			{alert(day+'-'+month+'-'+y2k(year)+' '+hour+':'+min);return '';}
			else{
		        return day+'-'+month+'-'+y2k(year)+' '+hour+':'+min;
			}
	}
    else
	{
//		alert(y2k(test.getYear())+'='+y2k(year)+' '+month+'='+test.getMonth+' '+day+'='+test.getDate+' '+hour+'='+test.getHours+' '+min+'='+test.getMinutes);
        return '';
	}
}

// returns dd-mm-yyyy
function date2Str( value )
{
	var dt = new Date(value + new Date().getTimezoneOffset()*60000 );
	return n2(dt.getDate())+'-'+n2(dt.getMonth()+1)+'-'+dt.getFullYear()
		// +' ' + n2(dt.getHours())+':'+n2(dt.getMinutes());
}

function date2StrWithMins( value )
{
	if (""+value==""){
		return ""
	} else {
	value = new Date(value);
	return n2(value.getDate())+'-'+n2(value.getMonth()+1)+'-'+value.getFullYear()+" "+n2(value.getHours())+":"+n2(value.getMinutes());
	}
}

/*
function date2StrMod( value, direction, mod)
{
	var month=new Array(12);
	month[0]="Januar";
	month[1]="Februar";
	month[2]="Marts";
	month[3]="April";
	month[4]="Maj";
	month[5]="Juni";
	month[6]="Juli";
	month[7]="August";
	month[8]="September";
	month[9]="Oktober";
	month[10]="November";
	month[11]="December";
	var newdate
	if (direction == "down") {
		newdate = new Date(value.getFullYear(), value.getMonth(), (value.getDate()-mod));
		return "<div id='"+mod+"DayBack' class='timeline' style='width:"+ (windowWidth / 6) +"px;'>"+n2(newdate.getDate())+'<br>'+month[newdate.getMonth()] + "</div>";
	} else if (direction == "up") {
		newdate = new Date(value.getFullYear(), value.getMonth(), (value.getDate()+mod));
		return "<div id='"+mod+"DayAhead' class='timeline' style='width:"+ (windowWidth / 6) +"px;'>"+ n2(newdate.getDate())+'<br>'+month[newdate.getMonth()] + "</div>";
	} else {
		return alert("direction is invalid");
	}
}*/

function cfd(object){
	cf();
	var str=object.value;
	if(str==''){return true;}
	else
	{
		str=isDate(str);
		if (str=='') {window.alert('Feltet skal indeholde en dato\ni formatet:\ndd-mm-yyyy\neller\nddmmyy\neller\nddmmyyyy');object.focus();return false;}else{object.value=str;cf();return true;}
		}
}

function isDate(str){
	var d='';
	var r1 = new RegExp('^[0-9]{2}-[0-9]{2}-[0-9]{4}$');
	var r2 = new RegExp('^[0-9]{8}$');
	var r3 = new RegExp('^[0-9]{1}|[0-9]{2}|[0-9]{4}|[0-9]{6}$');
	if (r1.test(str)){d = isDateOK(str.substring(0,2),str.substring(3,5),str.substring(6,10));}
	else if (r2.test(str)){d = isDateOK(str.substring(0,2),str.substring(2,4),str.substring(4,8));}
	else if (r3.test(str)){d = isDateOK(str.substring(0,2),str.substring(2,4),str.substring(4,6));}
	return d;
}

function cfd(object){
	cf();
	var str=trim(''+object.value);
	if(str===''){return true;}
	else
	{
		if (str.toLowerCase()==='dd'){str=date();}
		str=isDate(str);
		if (str==='') {window.alert(strDateText1);object.focus();return false;}else{object.value=str;cf();return true;}
		}
}

function isDateTime(str){
	var d='';
	var r1 = new RegExp('^[0-9]{2}-[0-9]{2}-20[0-9]{2} [0-9]{2}:[0-9]{2}$');	// 01-01-2006 11:22
	var r4 = new RegExp('^[0-9]{2}-[0-9]{2}-20[0-9]{2} [0-9]{4}$');				// 01-01-2006 1122
	var r5 = new RegExp('^[0-9]{2}-[0-9]{2}-20[0-9]{2} [0-9]{2}$');				// 01-01-2006 11
	var r2 = new RegExp('^[0-9]{6} [0-9]{4}$');									// 01012006 1122
	var r3 = new RegExp('^[0-9]{6}[0-9]{4}$');									// 010120061122
	var r6 = new RegExp('^[0-9]{6} [0-9]{2}$');									// 010106 11
	var r7 = new RegExp('^[0-9]{8}$');											// 01010611
	var r8 = new RegExp('^[0-9]{6}$');											// 010106
	if (r1.test(str)){
		d=isDateTimeOK(str.substring(0,2),str.substring(3,5),str.substring(6,10),str.substring(11,13),str.substring(14,16));
		}
	else if (r4.test(str)){
		d=isDateTimeOK(str.substring(0,2),str.substring(3,5),str.substring(6,10),str.substring(11,13),str.substring(13,15));
		}
	else if (r5.test(str)){
		d=isDateTimeOK(str.substring(0,2),str.substring(3,5),str.substring(6,10),str.substring(11,13),0);
		}
	else if (r2.test(str)){
		d=isDateTimeOK(str.substring(0,2),str.substring(2,4),str.substring(4,6),str.substring(7,9),str.substring(9,11));
		}
	else if (r3.test(str)){
		d=isDateTimeOK(str.substring(0,2),str.substring(2,4),str.substring(4,6),str.substring(6,8),str.substring(8,10));
		}
	else if (r6.test(str)){
		d=isDateTimeOK(str.substring(0,2),str.substring(2,4),str.substring(4,6),str.substring(7,9),0);
		}
	else if (r7.test(str)){
		d=isDateTimeOK(str.substring(0,2),str.substring(2,4),str.substring(4,8),'',0);
		}
	else if (r8.test(str)){
		d=isDateTimeOK(str.substring(0,2),str.substring(2,4),str.substring(4,6),'',0);
		}

	return d;
}

function cfdt(object){
	cf();
	var str=trim(''+object.value);
	if (str==="") {return true;}
	if (str.toLowerCase()==='dd'){str=datetime();}
	str=isDateTime(str);
	if (str===''){window.alert(strDateText2);object.focus();return false;}else{object.value=str;return true;}
}


function cfdtEmpty(object){
	cf();
	var str=isDateTime(object.value);
	var ok=2;
	if((object.value>'') && (str==='')){ok=0;}
	if((object.value==='') && (str==='')){ok=1;}
	if(str!==''){ok=1;}
	if (ok===0){window.alert(strDateText3);object.focus();return false;}else{object.value=str;return true;}
}

function isTimeOK(hour,min){
	var test = new Date(2005,2,1,hour,min);
	if((hour == test.getHours()) && (min == test.getMinutes())){
		return hour+':'+min;
	}else { return ''; }
}

function isTime(str){
	var t='';
	var r1 = new RegExp('^[0-9]{2}:[0-9]{2}$');
	var r2 = new RegExp('^[0-9]{4}$');
	var r3 = new RegExp('^[0-9]{2}$');
	var r4 = new RegExp('^[0-9]{1}$');
	if (r1.test(str)){
		t = isTimeOK(str.substring(0,2),str.substring(3,5));
	}else if (r2.test(str)){
		t = isTimeOK(str.substring(0,2),str.substring(2,4));
	}else if (r3.test(str)){
		t = isTimeOK(str.substring(0,2),'00');
	}else if (r4.test(str)){
		t = isTimeOK('0'+str.substring(0,1),'00');
	}
	return t;
}
function cft(object){
	cf();

	var str=object.value;
	if(str===''){return true;}else{
	str=isTime(str);
	if (str==='') {
		window.alert(strTimeText);
		object.focus();
		return false;
	}else{
		object.value=str;
		return true;
	}}
}


function isCPR(object){

	var cpr = object.value, match = false, c = document.getElementById(object.name + '_OK'), result = '';

	if (cpr!='')
	{
		if(cpr.match(/[0-9]{10}/)){object.value = '' + cpr.substring(0,6) +'-'+cpr.substring(6,10) ; cpr = object.value;}
		if(cpr.match(/[0-9]{6}\-?[0-9]{4}/)){
			cpr = cpr.replace(/\-/g,"");
			var chk = 0;
			for(i=9;i>-1;i--){
				chk += (+cpr.charAt(i))*((i>2)?(10-i):(4-i));
			}
			if(chk%11==0){match = true;}
			var dag = new Date(+cpr.substring(4,2),+cpr.substring(2,2),+cpr.substring(0,2));
			if(dag.getTime() > new Date().getTime() || !match){
				result = 'cprerror';
			}else{
				result = "cpr" + ((cpr.match(/[13579]$/))?"man":"woman");
			}
		}else{
			result = 'cprerror';
		}
		if (c) {
			c.innerHTML = '<img src="/cms/images/' + result + '.png" width="16" height="16" border="0" alt="">'
		} else {
			if (result == 'cprerror'){ alert( 'CPR nummer er ikke gyldigt.');}
		}
	}
	return  (result != 'cprerror')
}

function cfcpr(object){
	cf();
	return isCPR(object)

}





var newImgNo = 0;
var newImgText = '';

function uploadImage(selectObj,ImageFolder,selectObj2){
	if (isNaN(ImageFolder)){ImageFolder=0;}

	newImgNo = 0;
	window.showModalDialog("/cms/upload.asp?IF="+ImageFolder,window,"dialogHeight:210px;dialogWidth:480px;edge:Raised;center:1;help:1;resizable:1;scroll:0;status:1;");
	if (newImgNo>0){
		if (newImgText==='') {newImgText='Uploaded billede';}

		if (!selectObj2)
		{
			selectObj.selectedIndex = 0;
			selectObj.options.length = 0; // clear all
			selectObj.options[0] = new Option(newImgText,newImgNo,true,true);
		}else
		{
			selectObj.value = newImgNo;
			selectObj2.value = newImgText;
		}
	}
}


function uploadImage2(selectObj,ImageFolder, SubOwner, Name){
	if (isNaN(ImageFolder))
	{ImageFolder=0;
	}
	newImgNo = 0;
	window.showModalDialog("/cms/upload.asp?IF="+ImageFolder+"&SO="+SubOwner+"&N="+Name,window,"dialogHeight:210px;dialogWidth:480px;edge:Raised;center:1;help:1;resizable:1;scroll:0;status:1;");
	if (newImgNo>0){
		if (newImgText==='')	{newImgText='Uploaded billede';}
		selectObj.selectedIndex = 0;
		selectObj.options.length = 0; // clear all
	    selectObj.options[0] = new Option(newImgText,newImgNo,true,true);
	}
}


function uploadList(selectObj,ListNo,Parm1){
	newImgNo = 0;
	var CurValue= selectObj.options[selectObj.selectedIndex].value;
	if (CurValue== -1){CurValue=0;}

	window.showModalDialog("/cms/list_update.asp?ListIDno="+CurValue+"&ListNo="+ListNo+"&Parm1="+Parm1,window,"dialogHeight:190px;dialogWidth:510px;edge:Raised;center:1;help:1;resizable:1;scroll:0;status:1;");

	if (newImgNo>0){
		selectObj.selectedIndex = 0;
		selectObj.options.length = 0; // clear all
	    selectObj.options[0] = new Option(newImgText,newImgNo,true,true);
	} else {
		if (newImgNo==-1){selectObj.selectedIndex = 0; }
	}
}

function uploadList2(selectObj,ListNo,Parm1, Parms){
	newImgNo = 0;
	var CurValue= selectObj.options[selectObj.selectedIndex].value;
	if (CurValue== -1){CurValue=0;}

	var arrayParms=Parms.split("#");
	var url="";
	url = url + '&N1=' + escape( (arrayParms[0]?arrayParms[0]:'') );
	url = url + '&N2=' + escape( (arrayParms[1]?arrayParms[1]:'') );
	url = url + '&N3=' + escape( (arrayParms[2]?arrayParms[2]:'') );
	url = url + '&N4=' + escape( (arrayParms[3]?arrayParms[3]:'') );
	url = url + '&P1=' + escape( (arrayParms[4]?arrayParms[4]:'') );
	url = url + '&P2=' + escape( (arrayParms[5]?arrayParms[5]:'') );


	window.showModalDialog("/cms/list_update.asp?ListIDno="+CurValue+"&ListNo="+ListNo+"&Parm1="+Parm1+url,window,"dialogHeight:190px;dialogWidth:510px;edge:Raised;center:1;help:1;resizable:1;scroll:0;status:1;");
	if (newImgNo>0){
		addOption(selectObj,newImgText,newImgText)
		selectObj.selectedIndex = selectObj.options.length-1;
	} else {
		if (newImgNo==-1){
			var i
			for (i=selectObj.options.length-1;i>0;i--) {
				if (selectObj.options[i].selected) {
					deleteOption(selectObj,i);
				}
			}
			selectObj.selectedIndex = 0;
		}
	}
}

function uploadImageFolder(selectObj){
	newImgNo = 0;
	var CurValue= selectObj.options[selectObj.selectedIndex].value;
	if (CurValue== -1){CurValue=0;}

	window.showModalDialog("/cms/imagefolder_update.asp?SelectIDno="+CurValue,window,"dialogHeight:190px;dialogWidth:510px;edge:Raised;center:1;help:1;resizable:1;scroll:0;status:1;");
	if (newImgNo>0){

		if (CurValue===0)
		{
		    var defaultSelected = true;
			var selected = true;
			var optionName = new Option(newImgText, newImgNo, defaultSelected, selected);
			var length = selectObj.length;
			selectObj.options[length] = optionName;
		}else
		{
			selectObj.options[selectObj.selectedIndex].text = newImgText;
		}
	}
}


function o(M,L,ID){location.href='?mode='+M+'&I='+ID+'&L='+L;return false;}
function o2(M,L,ID,L1,L2,L3,L4,LT,CP){location.href='?mode='+M+'&I='+ID+'&L='+L+'&L1='+L1+'&L2='+L2+'&L3='+L3+'&L4='+L4+'&D='+LT+'&CP='+CP;return false;}
function o3(url){location.href=url;return false;}
function o4(M,L,ID,L1,L2,L3,L4,LT,CP,RT,RTI){location.href='?mode='+M+'&I='+ID+'&L='+L+'&L1='+L1+'&L2='+L2+'&L3='+L3+'&L4='+L4+'&D='+LT+'&CP='+CP+'&RT='+RT+'&RTI='+RTI;return false;}
function o5(M,L,ID,L1,L2,L3,L4,LT,CP,RT,RTI,RTCFP){location.href='?mode='+M+'&I='+ID+'&L='+L+'&L1='+L1+'&L2='+L2+'&L3='+L3+'&L4='+L4+'&D='+LT+'&CP='+CP+'&RT='+RT+'&RTI='+RTI+'&RTCFP='+RTCFP;return false;}
function o6(M,L,ID,L1,L2,L3,L4,LT,CP,LA,P,CS){if(CS==1){location.href='/'+LA+'/'+P+'/?mode='+M+'&I='+ID+'&L='+L+'&L1='+L1+'&L2='+L2+'&L3='+L3+'&L4='+L4+'&D='+LT+'&CP='+CP;}else{location.href='?mode='+M+'&I='+ID+'&L='+L+'&L1='+L1+'&L2='+L2+'&L3='+L3+'&L4='+L4+'&D='+LT+'&CP='+CP;} return false;}
function o7(M,L,ID,L1,L2,L3,L4,LT,CP,LA,P,CS,LSO){if(CS==1){location.href='/'+LA+'/'+P+'/?mode='+M+'&I='+ID+'&L='+L+'&L1='+L1+'&L2='+L2+'&L3='+L3+'&L4='+L4+'&D='+LT+'&CP='+CP+'&LSO='+LSO;}else{location.href='?mode='+M+'&I='+ID+'&L='+L+'&L1='+L1+'&L2='+L2+'&L3='+L3+'&L4='+L4+'&D='+LT+'&CP='+CP+'&LSO='+LSO;} return false;}
function nRandId(){ return Math.random(); }
function nRandNumber(){ return Math.round( Math.random() * 10000000); }

function dhtmlLoadScript(url)
{
	//alert(url);
	var e = document.createElement("script");
	e.src = url;
	e.type="text/javascript";
	document.getElementsByTagName("head")[0].appendChild(e);
}

function iZupChange0(Object,TheType){

	var s='rand='+nRandId+'&iZupType='+TheType+'&FieldChanged='+FieldChanged;
    for (var i=0, j=Object.elements.length; i<j; i++) {
		s += '&'+Object.elements[i].name + '=' +escape(Object.elements[i].value);
	}



	dhtmlLoadScript("/loadscript.asp?" + s);
}

function iZupChange(Object,TheType, FileName ){
	var el; var found;
	var s='rand='+nRandId()+'&iZupType='+TheType+'&callingName='+Object.name+'&FieldChanged='+FieldChanged;
    for (var i=0, j=Object.elements.length; i<j; i++) {
		el = Object.elements[i];
		found = (el.type != 'radio');
		if (!found){ if(el.checked) { found = true; }}
		if (found){s += '&'+el.name + '=' +escape(el.value); }
	}
	FileName=((!FileName)?"/loadscript.asp":FileName);
//window.open(FileName + "?" + s,'_blank');
	dhtmlLoadScript(FileName + "?" + s);
}

function iZupChangeCMS(Object,TheType, FileName ){
	var el; var found;
	var s='rand='+nRandId()+'&iZupType='+TheType+'&callingName='+Object.name+'&FieldChanged='+FieldChanged;
    for (var i=0, j=Object.elements.length; i<j; i++) {
		el = Object.elements[i];
		found = (el.type != 'radio');
		if (!found){ if(el.checked) { found = true; }}
		if (found){s += '&'+el.name + '=' +escape(el.value);}
	}
	FileName=((!FileName)?"/cms/loadscript.asp":FileName);
//window.open(FileName + "?" + s,'_blank');
	dhtmlLoadScript(FileName + "?" + s);
}

function iZupChange1(Object,TheType, FileName ){
	var el; var found;
	var s='rand='+nRandId()+'&iZupType='+TheType+'&FieldChanged='+FieldChanged;
    for (var i=0, j=Object.elements.length; i<j; i++) {
		el = Object.elements[i];
		found = (el.type != 'radio');
		if (!found){ if(el.checked) { found = true; }}
		if (found){s += '&'+el.name + '=' +escape(el.value);}
	}

	FileName=((!FileName)?"/loadscript.asp":FileName);
//window.open(FileName + "?" + s,'_blank');
	dhtmlLoadScript(FileName + "?" + s);
}

function iZupChange2(Object,TheType, FileName ){
	var el; var found;
	var s='rand='+nRandId()+'&iZupType='+TheType+'&callingName='+Object.name+'&FieldChanged='+FieldChanged;
    for (var i=0, j=Object.elements.length; i<j; i++) {
		el = Object.elements[i];
		found = (el.type != 'radio');
		if (!found){ if(el.checked) { found = true; }}
		if (found){s += '&'+el.name + '=' +escape(el.value);}
	}
	FileName=((!FileName)?"/loadscript.asp":FileName);
window.open(FileName + "?" + s,'_blank');
//	dhtmlLoadScript(FileName + "?" + s);
}

function changeImage(name,src) {
    if (document.images) {
        document.images[name].src = src;
	}
}

function changeImage2(name,src) {

    if (document.images)
	{
		var FileName = document.images[name].src;
		var splitArray = FileName.split('/');
		FileName = '';
		for (var i=0; i<splitArray.length-1; i++) {
			FileName = FileName + splitArray[i] + '/';
		}

		splitArray = src.split('/');
		FileName = FileName + splitArray[splitArray.length-1];

		document.images[name].src = FileName;
	}
}

function help(id){
	var url = '/cms/help.asp?id=' + id;
	var l = screen.width - 350;
	var t = 50;
	window.open(url,'_help','scrollbars=yes,width=300,height=400,left='+l+',top='+t);
}

function randomPassword(Object,length,passwordType)
{
  var pass = "";
  var max = 58;
  var chars = "1234567890abcdefghijkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ";
  if (passwordType==1){max = 34;}
  if (passwordType==2){max = 10;}
  for(x=0;x<length;x++)
  {
    i = Math.floor(Math.random() * max);
    pass += chars.charAt(i);
  }
  Object.value = pass;
  return true;
}

function styleIn(obj){obj.style.color = '#FF0000';obj.style.backgroundColor = '#6C6C76';return false;}
function styleInW(obj){obj.className = obj.className + '_s';return false;}
function styleOut(obj){obj.className = String(obj.className).substring(0,4);return false;}
function styleOutS(obj){obj.style.color = '';obj.style.backgroundColor = '';return false;}
function styleOutRC(obj,addClass){obj.className = String(obj.className).substring(0,4)+' '+addClass;return false;}


function dosearch(url){url=url+document.getElementById("w").value+"/";window.open(url,'_self');}

function setSelected( obj, value ){for(var i=0; i < obj.length ;i++) { if(obj.options[i].value==value){obj.options[i].selected=true;}}}

function recommend(){ window.open('/cms/recommend.asp?URL='+escape(location.href),'recommend','width=480,height=340,screenX=200,screenY=200,top=200,left=200,resizable=1'); }
function popImage(FileName, Width, Height, Name){return '<IMG SRC="/custom/' + FileName + '" WIDTH="' + Width + '" HEIGHT="'+ Height +'" BORDER="0" ALT="' + Name + '">'; }

function getFlashMovieObject(movieName)
{
  if (window.document[movieName])
  {
      return window.document[movieName];
  }
  if (navigator.appName.indexOf("Microsoft Internet")==-1)
  {
    if (document.embeds && document.embeds[movieName]) {
      return document.embeds[movieName];
	}
  }
  else // if (navigator.appName.indexOf("Microsoft Internet")!=-1)
  {
    return document.getElementById(movieName);
  }
}


function StopFlashMovie(movieName)
{
	var flashMovie=getFlashMovieObject(movieName);
	flashMovie.StopPlay();
}

function PlayFlashMovie(movieName)
{
	var flashMovie=getFlashMovieObject(movieName);
	flashMovie.Play();
}


function wordOpen(filename, defaultFilename, orderNo, companyName){
	var wordCreated = 0;

	var fso = new ActiveXObject("Scripting.FileSystemObject");

	if (!fso.FileExists(filename))

		{if (confirm('Opret ny fra template?')) {
			fso.CopyFile( defaultFilename, filename );
			wordCreated=1;
			}}

	if (fso.FileExists(filename))
	{
		var word = new ActiveXObject("Word.Application"); // creates the word object
		word.Visible=true; // doesn't display Word window
		doc = word.Documents.Open(filename); // specify path to document

		if (wordCreated==1)
		{
			var docRange = doc.Range();
			docRange.Find.Execute( "@OrderNo@", false, false, false, false, false, true, 1, false, orderNo, 2);
			docRange.Find.Execute( "@CompanyName@", false, false, false, false, false, true, 1, false, companyName, 2);
		}
	}
}

function showFolder( CurID, AllIDs )
{

	var Elem, elems, e, i, max;

	for (var x=0;x<=AllIDs;x++)
	{

		Elem = document.getElementById("izup-fbl-" + x );
		if (x==CurID)
		{
			Elem.style.backgroundImage = "url(/cms/images/fbl2.gif)";
		}else{
			Elem.style.backgroundImage = "url(/cms/images/fbl.gif)";
		}

		Elem = document.getElementById("izup-fbm-" + x );
		if (x==CurID)
		{
			Elem.style.backgroundImage = "url(/cms/images/fbm2.gif)";
		}else{
			Elem.style.backgroundImage = "url(/cms/images/fbm.gif)";
		}

		Elem = document.getElementById("izup-fbr-" + x );
		if (x==CurID)
		{
			Elem.style.backgroundImage = "url(/cms/images/fbr2.gif)";
		}else{
			Elem.style.backgroundImage = "url(/cms/images/fbr.gif)";
		}


		Elem = document.getElementById("izupFolder-" + x );
		if (x==CurID)
		{
			Elem.style.visibility = "visible";
		}else{
			Elem.style.visibility = "hidden";
		}

		elems = Elem.getElementsByTagName("img");
		if(elems){

			for(i = 0, max = elems.length; i < max; ++i) {
				e = elems[i];
				if (e)
				{
					if (e.className=='selfbutton'){
						if (x==CurID)
						{
							e.style.visibility = "visible";
						}else{
							e.style.visibility = "hidden";
						}
					}
				}
			}
		}
	}
}

//KBE19022009: returns current date/time in MySQL DATETIME format (YYYY-MM-DD HH:mm:SS)
function mysqlNow() {

	var d = new Date();
	var dDate = d.getDate();
	var dMonth = d.getMonth() + 1;
	var dYear = d.getFullYear();
	var dHours = d.getHours();
	var dMinutes = d.getMinutes();
	var dSeconds = d.getSeconds();

	if( dDate < 10 ) { dDate = "0" + dDate; }
	if( dMonth < 10 ) { dMonth = "0" + dMonth; }
	if( dHours < 10 ) { dHours = "0" + dHours; }
	if( dMinutes < 10 ) { dMinutes = "0" + dMinutes; }
	if( dSeconds < 10 ) { dSeconds = "0" + dSeconds; }

	/* return dDate + "-" + dMonth + "-" + dYear + " " + dHours + ":" + dMinutes + ":" + dSeconds; */
	return dYear + "-" + dMonth + "-" + dDate + " " + dHours + ":" + dMinutes + ":" + dSeconds;

	}

//KBE20012009: converts text with decimal comma to floating number with decimal point (which javascript can calculate on)
function text2float( t ) {

	s = String( t );
	s = s.replace( '.', '' );
	s = s.replace( ',', '.' );

	return parseFloat( s );

	}

//Adds commas to a number and returns a string
//By Keith Jenci, http://www.mredkj.com/javascript/numberFormat.html
function addCommas( nStr ) {
	nStr += '';
	x = nStr.split( '.' );
	x1 = x[ 0 ];
	x2 = x.length > 1 ? '.' + x[ 1 ] : '';
	var rgx = /(\d+)(\d{3})/;
	while ( rgx.test( x1 ) ) {
		x1 = x1.replace( rgx, '$1' + ',' + '$2' );
		}
	return x1 + x2;
	}

//KBE20012009: converts floating number to string with decimal comma (which is used in techCMS)
function float2string( f ) {

	s = addCommas( f );
	s = s.replace( '.', '|' );
	s = s.replace( ',', '.' );
	s = s.replace( '|', ',' );

	return s;

	}

function ajaxObject(url, callbackFunction) {
	var that=this;
	this.updating = false;
	this.update = function(passData,postMethod) {
		if (that.updating===true) { return false; }
		that.updating=true;
		var AJAX = null;
		if (window.XMLHttpRequest) {
			AJAX=new XMLHttpRequest();
		} else {
			AJAX=new ActiveXObject("Microsoft.XMLHTTP");
		}
		if (AJAX===null) {
			return false;
		} else {
			AJAX.onreadystatechange = function() {
				if (AJAX.readyState==4) {
					that.updating=false;
					that.callback(AJAX.responseText,AJAX.status,AJAX.responseXML);
					delete AJAX;
				}
			};
			var timestamp = new Date();
			var uri;
			if (postMethod=='POST') {
				uri=urlCall+'?'+timestamp.getTime();
				AJAX.open("POST", uri, true);
				AJAX.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
				AJAX.send(passData);
			} else {
				uri=urlCall+'?'+passData+'×tamp='+(timestamp*1);
				AJAX.open("GET", uri, true);
				AJAX.send(null);
			}
			return true;
		}
	};
	var urlCall = url;
	this.callback = callbackFunction || function () { };
}

function attachScript(responseText, responseStatus) {
// This function is called by the ajaxObject when the server has finished
// sending us the requested script.
	if (responseStatus==200) {
		eval(responseText);
	}
}

// ajaxObject is an object constructor, pass it the server url you want it to call
// and the function name you want it to call when it gets the data back from the server.
// Use the .update() method to actually start the communication with the server.
// The first optional argument for update is the data you want to send to the server.
// ajaxvar.update('id=1234&greed=good&finish=true');
// The second optional argument for update is 'POST' if you want to send the data
// as a POST instead of the default GET (post can handle larger amounts of data and
// the data doesn't show up in your server logs).
// ajaxvar.update('id=1234&greed=good&finish=true','POST');
// var getScriptViaAjax=new ajaxObject('http://mydomain.com/somescript.js',attachScript);
// getScriptViaAjax.update();
// var anotherScript = new ajaxObject('http://mydomain.com/anotherScript.php',attachScript);
// anotherScript.update('userId=4323','POST');

function iZupChangeAjax(Object,TheType, FileName ){
	var el; var found;
	var s='rand='+nRandId()+'&iZupType='+TheType+'&callingName='+Object.name+'&FieldChanged='+FieldChanged;
    for (var i=0, j=Object.elements.length; i<j; i++) {
		el = Object.elements[i];
		found = (el.type != 'radio');
		if (!found){ if(el.checked) { found = true; }}
		if (found){s += '&'+el.name + '=' +escape(el.value);}
	}
	FileName = ((!FileName)?"/loadscript.asp":FileName);

// window.open(FileName + "?" + s,'_blank');
	//	dhtmlLoadScript(FileName + "?" + s);

	var ajax = new ajaxObject(FileName,attachScript);
	ajax.update(s,'POST');

}


function getSelectedRadio(buttonGroup) {
   // returns the array number of the selected radio button or -1 if no button is selected
   if (buttonGroup[0]) { // if the button group is an array (one button is not an array)
      for (var i=0; i<buttonGroup.length; i++) {
         if (buttonGroup[i].checked) {
            return i
         }
      }
   } else {
      if (buttonGroup.checked) { return 0; } // if the one button is checked, return zero
   }
   // if we get to this point, no radio button is selected
   return -1;
} // Ends the "getSelectedRadio" function

function getSelectedRadioValue(buttonGroup) {
   // returns the value of the selected radio button or "" if no button is selected
   var i = getSelectedRadio(buttonGroup);
   if (i == -1) {
      return "";
   } else {
      if (buttonGroup[i]) { // Make sure the button group is an array (not just one button)
         return buttonGroup[i].value;
      } else { // The button group is just the one button, and it is checked
         return buttonGroup.value;
      }
   }
} // Ends the "getSelectedRadioValue" function



function getCheckedValue(radioObj) {
	if(!radioObj) { return ""; }
	var radioLength = radioObj.length;
	if(radioLength === undefined) {
		if(radioObj.checked){
			return radioObj.value;
		}
	}
		else { return ""; }
	for(var i = 0; i < radioLength; i++) {
		if(radioObj[i].checked) { return radioObj[i].value; }
	}
	return "";
}

function setCheckedValue(radioObj, newValue) {
	if(!radioObj) {	return; }
	var radioLength = radioObj.length;
	if(radioLength === undefined) {
		radioObj.checked = (radioObj.value == newValue.toString());
		return;
	}
	for(var i = 0; i < radioLength; i++) {
		radioObj[i].checked = false;
		if(radioObj[i].value == newValue.toString()) {
			radioObj[i].checked = true;
		}
	}
}

function doRepeatBox(IDno){
	window.showModalDialog("/cms/doZupRepeat.asp?I="+IDno,window,"dialogHeight:210px;dialogWidth:480px;edge:Raised;center:1;help:1;resizable:1;scroll:0;status:1;");
}

function popThisImage(thisImg) {
	window.open('/cms/popImage.asp?F='+thisImg.src,'image','width=100,height=100,screenX=50,screenY=50,top=50,left=50,resizable=1');
}

function debugAddBorder() {
	var arrayOfDivs = document.getElementsByTagName('div');
	for (var i=0; i < arrayOfDivs.length - 1; i++) {
		arrayOfDivs[i].style.border = '1px red solid';
	}
}

function isInteger( sText ) {
	var validChars = "0123456789-";
	var result = true;
	var Char;
	for( i = 0; i < sText.length && result === true; i++ ) {
		Char = sText.charAt( i );
		if( validChars.indexOf( Char ) == -1 ) { result = false; }
		}
		return result;
   }

function isFloat( sText ) {
	var validChars = "0123456789.-";
	var result = true;
	var Char;
	for( i = 0; i < sText.length && result === true; i++ ) {
		Char = sText.charAt( i );
		if( validChars.indexOf( Char ) == -1 ) { result = false; }
		}
		return result;
   }

function findPosLeft(obj)
  {
    var curleft = 0;
    if(obj.offsetParent)
        while(1)
        {
          curleft += obj.offsetLeft;
          if(!obj.offsetParent)
            break;
          obj = obj.offsetParent;
        }
    else if(obj.x)
        curleft += obj.x;
    return curleft;
  }

  function findPosTop(obj)
  {
    var curtop = 0;
    if(obj.offsetParent)
        while(1)
        {
          curtop += obj.offsetTop;
          if(!obj.offsetParent)
            break;
          obj = obj.offsetParent;
        }
    else if(obj.y)
        curtop += obj.y;
    return curtop;
  }


function findWidth(obj)
{
    // Get an object left position from the upper left viewport corner
    // Tested with relative and nested objects
	var oParent
    var oWidth = obj.offsetWidth            // Get Width from the parent object
    while(obj.offsetParent!=null) {   // Parse the parent hierarchy up to the document element
        oParent = obj.offsetParent    // Get parent object reference
        oWidth += oParent.offsetWidth // Add parent Width
        obj = oParent
    }
    return oWidth
}

var calendar_obj = null;

// show calendar
function calendar_show(el, lang, showTime) {

	if (calendar_obj) return;

	calendar_obj = new RichCalendar();
	calendar_obj.value_el = el;
	calendar_obj.format = '%d-%m-%Y';
	if (showTime) { calendar_obj.format += ' %H:%i';}
	calendar_obj.show_time = showTime;
	calendar_obj.language = lang;
	calendar_obj.user_onchange_handler = calendar_on_change;
	calendar_obj.user_onclose_handler = calendar_on_close;
	calendar_obj.user_onautoclose_handler = calendar_on_autoclose;

	calendar_obj.parse_date(calendar_obj.value_el.value, calendar_obj.format);

	calendar_obj.show_at_element(calendar_obj.value_el, "right-bottom");
}

// user defined onchange handler
function calendar_on_change(cal, object_code) {
	if (object_code == 'day') {
		cal.value_el.value = cal.get_formatted_date(cal.format);
		cal.hide();
		calendar_obj = null;
	}
}

// user defined onclose handler (used in pop-up mode - when auto_close is true)
function calendar_on_close(cal) {
//	if (window.confirm('Are you sure to close the calendar?')) {
		cal.hide();
		calendar_obj = null;
//	}
}

// user defined onautoclose handler
function calendar_on_autoclose(cal) {
	calendar_obj = null;
}

function stripHTML( value )
{
	var matchTag = /<(?:.|\s)*?>/g;
	return value.replace(matchTag, "");
}


function showOverlay( source ) {
	source=((source)?source:'<DIV style="position: relative;left: 50%; top: 50%;width:18px; height:18px;"><img src="/cms/images/loading2.gif" width="18" height="18" border="0" alt=""></DIV>');
	var ni = document.body;
	var newdiv
	newdiv = document.getElementById('overlay')
	if (!newdiv)
	{
		newdiv = document.createElement('div');
		newdiv.setAttribute('id','overlay');
		newdiv.style.position = 'absolute';
		newdiv.style.top = '0px';
		newdiv.style.left = '0px';
		newdiv.style.width = '100%';
		newdiv.style.width = '100%';
		newdiv.style.height = '100%';
		newdiv.style.overflow = 'hidden';
		newdiv.style.padding = '0';
		newdiv.style.margin = '0';
		newdiv.style.zIndex = '10100';
		newdiv.style.background = 'URL(/cms/images/loadingbg.png) repeat';
		newdiv.innerHTML = source;
		ni.appendChild(newdiv);
	}
	else
	{
		newdiv.style.display = 'block';
	}
}

function consoleLog(string) {
	if (this.console && typeof console.log != "undefined") {
		console.log(string);
	}
}

function getYoutubeVideo(videoString) {
	if ((typeof jQuery !== "undefined")) {
		var closeButton = "<img src='/cms/images/close32.png' alt='Close window' onclick='closeYoutube()'>";
		var youtubeVid = videoString.replace("http://www.youtube.com/watch?v=", "");
		youtubeVid = "<iframe title='YouTube video player' width='480' height='390' src='http://www.youtube.com/embed/"+ youtubeVid +"?rel=0&autoplay=1&hd=1' frameborder='0' allowfullscreen></iframe>";
/*
		var overlay = $("div#overlay");
		overlay.show();
		overlayShown = true;
*/
		var youtubeDiv = $("div#youtube");
		youtubeDiv.html(closeButton + youtubeVid);
		youtubeDiv.show();
	} else {
		consoleLog("Please include jQuery");
	}
}

function closeYoutube() {
	var overlay = $("div#overlay");
	var youtubeDiv = $("div#youtube");

	overlay.hide();
	youtubeDiv.hide();
}
