/****************************************************************
* design and development - christopher aalholm / apt as - 2002 	*
****************************************************************/
var menu = false;
var content = new Array();

function dlfile(myFileID,myUserID,myContentID,myFilename){
	// Checks if user is on Mac and IE, in that case goto a different URL
	isMac = (navigator.appVersion.indexOf("Mac")!=-1) ? true : false;
	IEmac = ((document.all)&&(isMac)) ? true : false;
	if (IEmac) {
		//var myUrl = 'blank.php?'+myFilename+'?k='+myFileID+'&un='+myUserID+'&contentid='+myContentID+'&fn='+myFilename+'&dwl=1';
        var myUrl = 'blank.php?k='+myFileID+'&un='+myUserID+'&contentid='+myContentID+'&fn='+myFilename+'&dwl=1';
	} else {
		var myUrl = 'blank.php?k='+myFileID+'&un='+myUserID+'&contentid='+myContentID+'&fn='+myFilename+'&dwl=1';
	}
	if (parent.frames['blank']) {
		parent.frames['blank'].location.href = myUrl+"&frames=1";
	} else {
		document.location.href = myUrl+"&frames=0";
	}
}

function winpop(myUrl,myWidth,myHeight){	
	
	var macAdd 			= (navigator.platform.indexOf("Mac")!= -1 || navigator.userAgent.indexOf('Opera')!= -1)?0:0;
	var macNetscapeAdd 	= ((navigator.platform.indexOf("Mac")!= -1) && (document.layers))?50:0;
	var winWidth 		= myWidth +macAdd;
	var winHeight 		= myHeight +macNetscapeAdd;
	
	var myX 	= (screen.availWidth/2) - (winWidth/2);
	var myY 	= (screen.availHeight/2) - (winHeight/2);	
	var myWin 	= window.open(myUrl,'winpop','width='+winWidth+',height='+winHeight+',toolbar=0,location=0,directories=0,status=0,scrollbars=0,resizable=0');
	myWin.moveTo(myX,myY);	
	myWin.resizeTo(myWidth,myHeight);
	myWin.focus();
}	

function bestill(skjema) {
	winpop('order.php?type='+skjema, 400,500);
}

function swapImg(name){
	// function: change image
	// returns : nothing
	// note    : syntax for imagename must be: name_number.gif and name_number_over.gif
	
	var img = document.images[name];
	var i;
	var newSrc  = "";
	var newPath = "";
	var newName = "";
	var temp;
	var active;

	if (img) {	
		// get image source
		var image = img.src;
		// extract filename
		var path  = image.split("/");
		var imgname = path[(path.length-1)].split("_");
		// build filepath minus filename
		for(i=0;i<(path.length-1);i++){
			newPath += path[i]+"/";
		}
		// get the image name without '_over' and '.gif'
		active = imgname[0]+"_"+imgname[1];
			
		// if image is in 'over' state change to 'normal' state
		if(imgname.length > 2){
			// build new filename
			newName = imgname[0]+"_"+imgname[1]+".gif";
			// concat filepath and filename
			newSrc = newPath+newName;
			// change image source
			img.src = newSrc;
		}
		// if image is in 'normal' state change to 'over' state
		else{
			// extract image number
			temp = imgname[1].split(".");
			// build new filename
			newName = imgname[0]+"_"+temp[0]+"_over.gif";
			// concat filepath and filename
			newSrc = newPath+newName;
			// change image source
			img.src = newSrc;
		}	
	}
}

function swapMenuImage(name) {
	// Checks if the image to be changed is the same as the active image, in that case no change will happen
	if (name != 'menu'+parent.activePage) swapImg(name);
}

function validate(email){
	
	var exclude=/[^@\-\.\w]|^[_@\.\-]|[\._\-]{2}|[@\.]{2}|(@)[^@]*\1/;
	var check=/@[\w\-]+\./;
	var checkend=/\.[a-zA-Z]{2,3}$/;

	if(((email.search(exclude) != -1)||(email.search(check)) == -1)||(email.search(checkend) == -1)){
		return true;
	} else {
		return false;
	}
}



/****************************************
* functions that operate the menu		*
****************************************/

function returnImagePath(strPath){
	
	var retPath  = '';
	var arrPath  = strPath.split("/");	
	for(var i=0;i<(arrPath.length-1);i++){
		retPath += arrPath[i]+"/";
	}
	return retPath;
}

function showMenu(item){
	// function: show menu
	// returns : false if menu isn't loaded
	// calls   : hideMenu()
	
	
		
	// check if menu is loaded	
	if((content)&& (menu)){ 
		
		hideMenu();
		
		if(document.getElementById){ // ie 5.0, nn6
		
			document.getElementById('menubg'+item).style.visibility = 'visible';
						
			// opera-fix
			for(var j=0;j<content[item].length;j++){
				document.getElementById('menu'+item+'_'+j).style.visibility = 'visible';
			}
			
			document.getElementById('bg').style.visibility = 'visible';
			document.getElementById('bgtop').style.visibility = 'visible';			
			document.getElementById('bgleft').style.visibility = 'visible';
			document.getElementById('bgright').style.visibility = 'visible';			
		}
	}
	return false;
}

function showSub(x,y,z){
	
	hideSub();	
	
	if(content){ 
		if(document.getElementById){ // ie 5.0, nn6
			if(content[x][y].length>1){
				document.getElementById('menubg'+x+'_'+y).style.visibility = 'visible';
												
				for(var j=1;j<content[x][y].length;j++){
					document.getElementById('menu'+x+'_'+y+'_'+j).style.visibility = 'visible';
				}
				
				if((z)&&(content[x][y][z].length>1)){
					document.getElementById('menubg'+x+'_'+y+'_'+z).style.visibility = 'visible';
												
					for(var j=1;j<content[x][y][z].length;j++){
						document.getElementById('menu'+x+'_'+y+'_'+z+'_'+j).style.visibility = 'visible';
					}
				
				}
				document.getElementById('bg').style.visibility = 'visible';
				document.getElementById('bgtop').style.visibility = 'visible';
				document.getElementById('bgleft').style.visibility = 'visible';
				document.getElementById('bgright').style.visibility = 'visible';			
			}	
		}
	}
	return false;
}

function hideSub(){
	var i;
	var j;
	var p;
	var k;
		
	for(i=0;i<content.length;i++){
		if(document.getElementById){ // ie 5.x.nn6
			for(j=0;j<content[i].length;j++){
				if(content[i][j].length > 1){
				
					document.getElementById('menubg'+i+'_'+j).style.visibility = 'hidden';
					
					for(p=1;p<content[i][j].length;p++){
						document.getElementById('menu'+i+'_'+j+'_'+p).style.visibility = 'hidden';
						if(content[i][j][p].length > 1){
							document.getElementById('menubg'+i+'_'+j+'_'+p).style.visibility = 'hidden';
							for(k=1;k<content[i][j][p].length;k++){
								document.getElementById('menu'+i+'_'+j+'_'+p+'_'+k).style.visibility = 'hidden';								
							}						
						}
					}															
				}
			}
		}
	}
}

function hideMenu(){
	// function: hide menu
	// returns : nothing
	// calls   : hideBg()
	
	var i;
	if(menu){
		for(i=0;i<content.length;i++){
			if(document.getElementById){ // ie 5.x.nn6
				document.getElementById('menubg'+i).style.visibility = 'hidden';
				// opera-fix
				for(var j=0;j<content[i].length;j++){
					document.getElementById('menu'+i+'_'+j).style.visibility = 'hidden';
				}			
			}
		}
		hideSub();
		hideBg();
		resetImagesExcept('');
	}
}

function hideBg(){
	// function: hide the closing backgroundlayers
	// returns : nothing
	
	if(document.getElementById){ // ie 5.x,nn6
		document.getElementById('bg').style.visibility = 'hidden';
		document.getElementById('bgtop').style.visibility = 'hidden';		
		document.getElementById('bgleft').style.visibility = 'hidden';
		document.getElementById('bgright').style.visibility = 'hidden';		
	}
}

function hiLite(obj,theClass,theMenuClass){
	// function: change background-color in a layer
	// returns : nothing
	if((document.getElementById)||(document.all)){		
		var childObj;
		if(obj.firstChild.nextSibling){
			childObj = obj.firstChild.nextSibling;
			obj.firstChild.src = returnImagePath(obj.firstChild.src) + 'pil_h.gif';
		}else{
			childObj = obj.firstChild;
		}
		childObj.className = theMenuClass;		
		obj.className = theClass;
	}
}

function loLite(obj,theClass,theMenuClass){
	// function: change background-color in a layer
	// returns : nothing
	if((document.getElementById)||(document.all)){
		var childObj;
		if(obj.firstChild.nextSibling){
			childObj = obj.firstChild.nextSibling;
			obj.firstChild.src = returnImagePath(obj.firstChild.src) + 'pil.gif';
		}else{
			childObj = obj.firstChild;
		}
		childObj.className = theMenuClass;
		obj.className = theClass;
	}
}

function checkOrderForm(myForm){
	var isError = false;
	var alertMsg= "Du må rette følgende:\n\n";
	var strType 	= myForm.elements['type'].value;
	var strRegion 	= selectBox(myForm.elements['region']);
	if (strType == 'brevark') {

		var strAntall	= (myForm.elements['antall'].value * 1);
		if (strAntall <= 0) {
			isError = true;
			alertMsg += '- du må angi ett antall brevark';
		}

	} else if (strType == 'konvolutter') {

		var strAntallC4	= (myForm.elements['antallc4'].value * 1);
		var strAntallC5	= (myForm.elements['antallc5'].value * 1);

		if ((strAntallC4 <= 0) && (strAntallC5 <= 0)) {
			isError = true;
			alertMsg += '- du må angi ett antall konvolutter';
		}

	} else if (strType == 'visittkort') {

		var strNavn		= myForm.elements['vnavn'].value;
		var strStilling	= myForm.elements['vstilling'].value;
		var strDirekte	= myForm.elements['vdirekte'].value;
		var strMobil	= myForm.elements['vmobil'].value;
		var strEpost	= myForm.elements['vepost'].value;
		var strAntall	= (myForm.elements['vantall'].value * 1);

		if(notValidPhonenumber(strDirekte,'phone')){
			isError = true;
			alertMsg += '- du må skrive inn et gyldig telefonnummer\n';
		}	
		if(notValidPhonenumber(strMobil,'mobile')){
			isError = true;
			alertMsg += '- du må skrive inn et gyldig mobiltelefonnummer\n';
		}	
		if(strNavn.length < 1){
			isError = true;
			alertMsg += '- du må skrive inn navnet til den som skal ha visittkortet\n';
		}
		if(strStilling.length < 1){
			isError = true;
			alertMsg += '- du må skrive inn stillingen til den som skal ha visittkortet\n';
		}
		if(notValidMailFormat(strEpost)){
			isError = true;
			alertMsg += '- du må skrive inn en gyldig epostadresse\n';
		}
		if (strAntall <= 0) {
			isError = true;
			alertMsg += '- du må angi ett antall visittkort';
		}
	}
	if(isError){
		alert(alertMsg);
		return false;
	}	
	return true;	
}

function notValidMailFormat(email){
	// function: validates an email to format: x@x.xx
	// returns : boolean
	var exclude=/[^@\-\.\w]|^[_@\.\-]|[\._\-]{2}|[@\.]{2}|(@)[^@]*\1/;
	var check=/@[\w\-]+\./;
	var checkend=/\.[a-zA-Z]{2,3}$/;
	if(((email.search(exclude) != -1)||(email.search(check)) == -1)||(email.search(checkend) == -1)){
		return true;
	} else {
		return false;
	}
}

function notValidPhonenumber(intNO,strType){
	var re = (strType == 'mobile') ? /^[489]/ : /^[23567]/;
//	var re = /^[23456789]/;
	var intNumber = removeSpaces(intNO);
	if(intNumber.length != 8){		
		return true;
	}
	if(!isNumber(intNumber)){		
		return true;
	}
	if(intNumber.search(re) == -1){
		return true;
	}	
	return false;
}

function removeSpaces(str){
    var re   = /[\s]/g;
    return str.replace(re,'');
}

function isNumber(input){
	var item = parseInt(input, 10);
	if(isNaN(item)){
		return false;  
	}
	item = parseFloat(input);
	if(isNaN(input)) {
		return false;
	}
	return true;
}

function checkFormSave(myForm){
	// function: 
	// returns :

	var i;
	var j;
	var k;
	var send = true;	
	var found_first = false;
	var group_val = "";
	var komma = "";
	if(arguments.length == 3){
		myForm.elements[arguments[1]].value = arguments[2];
	}
	for(i=0;i<myForm.elements.length;i++){
	// find the fieldname for the first dynamic field
		if((!found_first)&&(myForm.elements[i].name.indexOf('field_')!=-1)){
			found_first = myForm.elements[i].name;
		}
	
	// check fieldtype
		switch(myForm.elements[i].type){
			case"checkbox":
			// check if it's in a group..
				if(myForm.elements[myForm.elements[i].name].length){
				
					group_val = "";
					komma = "";
					k = i;
					
				// loop through the collection of checkboxes
					for(j=0;j<myForm.elements[myForm.elements[k].name].length;j++){
						group_val += komma + checkBox(myForm.elements[i]);
						komma = ",";
						// increment the counter..
						i++;
					}
					
				// return the compiled value to the last element in the group
					myForm.elements[i-1].value = group_val;
					
				// decrement the counter
					i--;					
				
				}else{
				// it's not..
					myForm.elements[i].value = checkBox(myForm.elements[i]);
				}
				break;
				
			case"radio":
			// check if it's in a group
				if(myForm.elements[myForm.elements[i].name].length){
					group_val = "";
					komma = "";
					k = i;
				// loop through the collection of radiobuttons
					
					for(j=0;j<myForm.elements[myForm.elements[k].name].length;j++){						
						group_val += komma + radioBox(myForm.elements[i]);
						komma = ",";
												
					// increment the counter
						i++;
					}
				// return the compiled value to the last element in the group
					myForm.elements[i-1].value = group_val;
					myForm.elements[i-1].checked = true;
					
				// decrement the counter
					i--;
					//alert(myForm.elements[k].name + ' ' + myForm.elements[k].value);
				
				}else{
				
				// it's not..
					myForm.elements[i].value = radioBox(myForm.elements[i]);
				}
				
				break;
				
			case"select-one":				
				myForm.elements[i].value = selectBox(myForm.elements[i]);	
				break;
				
			default:
				myForm.elements[i].value = textBox(myForm.elements[i]);
				break;			
		}
	}
	
// check the dateinput..

	if(myForm.elements['Startdate']){
		if(nonValidDate(myForm.elements['Startdate'].value)){
			// not valid date
			alert('Feil datoformat! (dd.mm.yyyy)');
			send = false;
			return;
		}else{		
		// valid, format it..
			myForm.elements['Startdate'].value = formatDate(myForm.elements['Startdate'].value);
			
		}
		
		if(nonValidDate(myForm.elements['Stopdate'].value)){
		// not valid date
			alert('Feil datoformat! (dd.mm.yyyy)');
			send = false;
			return;
		}else{
		// valid, format it..
			myForm.elements['Stopdate'].value = formatDate(myForm.elements['Stopdate'].value);
		}
	}
	
// copy value from first dynamic field to instname
	if(myForm.elements['instname']){
		myForm.elements['instname'].value = myForm.elements[found_first].value;
	}
	
	if(send){
		myForm.submit();
	}
}

function checkBox(myObj){
	// function: check if a checkbox/radio is checked or not
	// returns : string, will also check the box
		
	if(myObj.checked){
		return myObj.value;
	}else{
		myObj.checked = true;
		if(myObj.name == 'Active'){
			return 'n'
		}else{
			return '0';
		}
	}
}

function radioBox(myObj){
	// function: check if a radio is checked or not
	// returns : string, checks the last box
		
	if(myObj.checked == true){		
		return myObj.value;
	}else{
		//myObj.checked=true;
		return '0';
	}
}

function selectBox(myObj){
	// function: return the value of a select
	// returns : string, value of selectedIndex
	
	return myObj[myObj.selectedIndex].value;
}

function textBox(myObj){
	// function: return the value from a text-input or text-area
	// returns : string
	return myObj.value;
}

function formatDate(str){
	// function: to format a date to valid input into the database
	// returns : string, formatted as yyyy.mm.dd
	
	var output = str;
	var day, month, year, tall;
	var dato = new Date();
	
	if(str.length == 10){
		day   = str.substring(0,2);
		month = str.substring(3,5);
		year  = str.substring(6,10);
		output = year + "." + month + "." +day;
	}else{
		day   = str.substring(0,2);
		month = str.substring(2,4);
		year  = str.substring(4,8);
		output = year + "." + month + "." +day;
	}	
		
	return output;
}

function isEmpty(str){
	// function: check if a string is empty
	// returns : boolean
	
	if(str == "" || str == null || str.length == 0){
		return true;
	}else{
		return false;
	}
}

function nonValidDate(str){
	// function: check if a date is valid (dd.mm.yyyy,dd-mm-yyyy,dd/mm/yyyy or ddmmyyyy)
	// returns : boolean
	
	var svar, day, month, year;
	svar = true;
	
	if(!isEmpty(str)){
		if(str.length == 10){
			if(str.charAt(2) == '/' || str.charAt(2) == '.' || str.charAt(2) == '-'){
				if(str.charAt(5) == '/' || str.charAt(2) == '.' || str.charAt(2) == '-'){
					if(str.substring(0,1) == "0"){
						day = str.substring(1,2);
					}else {
						day = str.substring(0,2);
					}
					month = str.substring(3,5);
					year = str.substring(6,10);
				}
			}
		}else if(str.length == 8){
			if(str.substring(0,1) == "0"){
				day = str.substring(1,2);
			} else {
				day = str.substring(0,2);
			}
			month = str.substring(2,4);
			year = str.substring(4,8);
		}
		
		day = parseInt(day);
		month = parseInt(month);
		year = parseInt(year);
		
		if(!isNaN(day) || !isNaN(month) || !isNaN(year)){
			if(month <= 12 && year < 3000){
				if(validateDay(day,month,year)){
					svar = false;
				}
			}
		}
	}
	
	return svar;
}

function validateDay(day,month,year){
	// function: validate that a day exists within a given month/year
	// returns : boolean
	
	day = parseInt(day);
	month = parseInt(month);
	var monthMAX = new Array(31,31,28,31,30,31,30,31,31,30,31,30,31);
	
	if(year%4 == 0){
		monthMAX[2] = 29;
	}
	
	var topp = monthMAX[month];
	
	if(day >= 1 && day <= topp ){
		return true;
	}else{
		return false;
	}
}

function sitemap(){
	// function: alter menu to reflect which page that is viewed
	// calls   : swapImg
	// returns : nothing
	var myMenuID = parent.activePage;
	if(myMenuID != -1){
		myMenuItem = 'menu'+myMenuID;
		swapImg(myMenuItem);
	}
}

function setpage(myPage){
	parent.activePage = myPage;
}

function resetPage() {
	parent.activePage = -1;
}

function resetImagesExcept(ig) {
	// Resets all images, except the one specified in i and the activePage image.
	var newSrc  = "";
	var newPath = "";
	var newName = "";
	var temp;
	for (j=1; j<=4; j++) {
		s = '0'+j;
		if (s != parent.activePage) {
			if (((ig != '') && (s != ig)) || (ig == '')) {
				var img = document.images['menu'+s];
				// get image source
				var image = img.src;
				// extract filename
				var path  = image.split("/");
				var imgname = path[(path.length-1)].split("_");
				if (imgname.length > 2) {
					// build filepath minus filename
					for(i=0;i<(path.length-1);i++) newPath += path[i]+"/";
					// build new filename
					newName = imgname[0]+"_"+imgname[1]+".gif";
					// concat filepath and filename
					newSrc = newPath+newName;
					// change image source
					img.src = newSrc;
				}
			}
		}
	}
}
