function isLeapYear(day,month,year)
{
    if(day == 29 && month == 2  && (year % 4) == 0 && ((year % 100) != 0 || (year % 400 == 0)) )
        return true;

    return false;
}


function isNumericStr(str)
{
        var digits="0123456789";
        var temp;

        for (var i=0;i<str.length;i++)
        {
                temp=str.substring(i,i+1)

                if (digits.indexOf(temp)==-1)
                {
                        return false;
                }
        }

        return true;
}

function isNumericField(field)
{
    return isNumericStr(field.value);
}

function validateDate(day,month,year)
{

    // Check for om der er indtastet data
    if(day.value.length == 0)
    {
        alert("Fejl: Dag i m\u00E5ned skal angives");
        day.focus();
        return false;
    }
    else if(day.value.length == 1)
    {
        day.value = "0" + day.value;
    }

    if(month.value.length == 0)
    {
        alert("Fejl: Måned i \u00E5r skal angives");
        month.focus();
        return false;
    }
        else if(month.value.length == 1)
    {
        month.value = "0" + month.value;
    }

    if(year.value.length == 0)
    {
        alert("Fejl: \u00C5r skal angives");
        year.focus();
        return false;
    }

    // Check om den dato der er indtastet kun betår af tal
    if(isNumericField(day) == false)
    {
        alert("Fejl: Dato ikke gyldig");
        day.focus();
        return false;
    }

    if(isNumericField(month) == false)
    {
        alert("Fejl: Dato ikke gyldig");
        month.focus();
        return false;
    }

    if(isNumericField(year) == false)
    {
        alert("Fejl: Dato ikke gyldig");
        year.focus();
        return false;
    }

    // Hent tekst fra felterne
    var iday = parseInt(((day.value.indexOf("0") == 0) ? day.value.substr(1) : day.value));
    var imonth = parseInt(((month.value.indexOf("0") == 0) ? month.value.substr(1) : month.value));
    var iyear = parseInt(year.value);

    // Check år
    if(iyear < 1800)
    {
        alert("Fejl: Dato ikke gyldig");
        year.focus();
        return false;
    }

    // Check måned
    if(imonth < 1 || imonth > 12)
    {
        alert("Fejl: Dato ikke gyldig");
        month.focus();
        return false;
    }

    // Check dag i måned
    days = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];

    if(iday < 1 || ( iday > days[imonth] && isLeapYear(iday,imonth,iyear) == false ) )
    {
        alert("Fejl: Dato ikke gyldig");
        day.focus();
        return false;
    }

    return true;
}

//Function to make all checkboxes in the form 'theForm' checked or unchecked 
function selectAll(theForm) {
	if(areAllCheckBoxesSelected(theForm)){
		setAll(theForm, false);
	}
	else{
		setAll(theForm, true);
	}
	return;	
}

function setAll(theForm, value){
	var z = 0;	
	var count = theForm.elements.length;
	if(count > 0){
		for (z=0; z< count;z++){
			theElement = theForm.elements[z];
			if(theElement.type == 'checkbox') {	 
				theElement.checked = value;				
			}
		}
	}
	return;
}

function enableManager(enable, managerNumber, createOrEnd) {
	theElement = document.getElementById("manager" + managerNumber);
	if (theElement) {
		var enableElement = (createOrEnd == 'end') ? enable : false;
		theElement.disabled = !enableElement;

		if (enableElement) {
			setEnabledTxtInputBGColor(theElement);				
		} else {
			setDisabledTxtInputBGColor(theElement);
		}
	}
	
	return;
}
	
function setAllManagerFields(theForm, createOrEnd, setDisabled){	
	var count = theForm.elements.length;
	var z = 0;
	if(count > 0){
		for (z=0; z<count; z++){
			theElement = theForm.elements[z];
			index = theElement.id.indexOf('manager');
			if(index > -1){
				toIndex = theElement.id.length;				
				managerNo = theElement.id.substring(index+7, toIndex);
				if(theForm.elements['selected'+ managerNo]){
					checked=theForm.elements['selected'+ managerNo].checked;
					manElement = document.getElementById("manager" + managerNo);
					if(checked == true){
						enableManager(true, managerNo, createOrEnd, setDisabled);
													
					}
					else{
						enableManager(false, managerNo, createOrEnd, setDisabled);
					}
				}				
			}
		}
	}
	return;
}


// Function to make all checkboxes in the form 'theForm' checked or unchecked depending on the boolean parameter 'check'
// Also changes between the to texts supplied 'text1' and 'text2'
var lastCheckedVal = false;
function selectDeselectAll(theForm, theButton, text1, text2) {		 
    var z = 0;	
	var count = theForm.elements.length;
	if(count > 0){
		for (z=0; z< count;z++){
			theElement = theForm.elements[z];			
			if(theElement.type == 'checkbox') {	 
				if(lastCheckedVal == false){
					theElement.checked = true;										
				}
				else{
					theElement.checked = false;
				}
			}
		}
		if(lastCheckedVal == false){
			lastCheckedVal = true;
		}
		else{
			lastCheckedVal = false;
		}
		if(theButton.value == text1){
			theButton.value = text2;
			lastButtonText = text2;
		}
		else{
			theButton.value = text1;
			lastButtonText = text1;
		}
		
	}
}



// Function to check that at least ONE checkbox is selected
function oneOrMoreCheckBoxSelected(theForm){
	var z = 0;	
	var count = theForm.elements.length;
	if(count > 0){
		for (z=0; z< count;z++){
			theElement = theForm.elements[z];
			if(theElement.type == 'checkbox'){	
				if(theElement.checked == true){
					return true;
				}
			}
		}
	}
	return false;	
}

// Function to check that at all elements of type checkbox is selected
function areAllCheckBoxesSelected(theForm){
	var z = 0;	
	var count = theForm.elements.length;
	if(count > 0){
		for (z=0; z< count;z++){
			theElement = theForm.elements[z];
			if(theElement.type == 'checkbox'){	
				if(theElement.checked == false){
					return false;
				}
			}
		}
	}
	return true;	
}

/**
   * function isValidEmail(theForm, emailFields, requiredEmailFields):
   * if the email addresses in "requiredEmailFields" are not empty,
   * we validate the fields contained in "emailFields" for validity. 
   */
function isValidEmail(theForm, emailFields, requiredEmailFields)
{	
	if(!checkRequiredFields(requiredEmailFields)){
		return false;
	}	
	else{
		for(y=0;y <emailFields.length;y++){
			var theEmailField = emailFields[y];			
			var fieldValue = trim(theEmailField.value);
			if (fieldValue.length > 0){
				if(/^[+\-.0-9A-Z_a-z]+@([^\s()><@,;:".\[\]]+(\.[^\s()><@,;:".\[\]]{2,})+|\[\d{1,3}(\.\d{1,3}){3}\])$/.test(fieldValue) == false){
					var label = getLabel(theEmailField.id);								
					fieldName = theEmailField.name;
					theForm.elements[fieldName].focus();
					if(label.length > 0){
						alert("E-mail adressen i feltet med teksten \"" + label + "\" er ikke valid.");
					}
					else{
						alert("Emailadressen er ikke valid!");
					}
					return false;
				}
			}
		}
		return true;
	}
	
}

/**
   * function getLabel(pID):
   *  Gets the label for the element with the id "pID" .. if no label exists a zero length string is returned.
   */
function getLabel(pID) {
	Labels = document.getElementsByTagName("label");
    
	for(var i=0;i<Labels.length;i++) {
		elemAtt = Labels[i].htmlFor;
		if (elemAtt == pID){
			return Labels[i].innerHTML;
		}
	}
 	return '';
}

/**
   * function checkRequiredFields(fields):
   *  Checks that the fields passed in as parameter are not empty... sets the focus to the first (if any) empty required field.
   */
function checkRequiredFields(fields){
	var alertText = "F\u00F8lgende felter skal v\u00E6re udfyldt: \n";
	var error = "false";
	var firstFieldWithError = "";
	if(fields != null){
		for(x=0;x <fields.length;x++){
			var theField = fields[x];
			var fieldValue = theField.value;
			var fieldName = theField.name;
			if (fieldValue.length <= 0){
				if(error == "false"){
					error = "true";
				}
				if(firstFieldWithError == ""){
					firstFieldWithError = theField;
				}
				alertText = alertText + " - " + getLabel(theField.id) + "\n";
			}
		}
		if(error == "true"){
			alert(alertText);
			firstFieldWithError.focus();
			return false;
		}
	}
	return true;
}

/**
   * function trim(s):
   * Trims of leading and trailing whitespace
   */	
function trim(s) {
	while (s.substring(0,1) == ' ') {
		s = s.substring(1,s.length);
	}
	while (s.substring(s.length-1,s.length) == ' ') {
		s = s.substring(0,s.length-1);
	}  
	return s;
}


function printWindow(){
	bV = parseInt(navigator.appVersion)
	if (bV >= 4){
		window.print()
	}
}

function setButtonStatus(buttonId, enabled) {
	var button = document.getElementById(buttonId);
	if (button){
		if (enabled) {
			button.disabled = false;
			button.className="btn";
		} else {
			button.disabled = true;
			button.className="btn disabled";
		}
	}
}

function openGuideWin(side,navn,bredde, hoejde){
	var w=window.open(side, navn, 'width='+bredde+',height='+hoejde+',left=0,top=0,locationbar=no;toolbar=no,scrollbars=yes,resizable=yes,status=yes,directories=no,menubar=no,location=no,'); 
	if(w){
		w.focus();		
	}
}
	 
function showPrintable(side,navn,bredde, hoejde){
	var w = window.open(side, navn, 'width='+bredde+',height='+hoejde+',left=0,top=0,locationbar=no;toolbar=no,scrollbars=yes,resizable=yes,status=yes,directories=no,menubar=no,location=no,'); 
	if(w){
		w.focus();		
	}		 
}

	  
function setDisabledTxtInputBGColor(theElement){	
		theElement.style.backgroundColor = "#EBEBE4";
}

function setEnabledTxtInputBGColor(theElement){	
		theElement.style.backgroundColor = "#FFFFFF";
}

function setEducationsDisabled(disable){	
		document.forms[2].elements['qualificationForm.education'].disabled = disable;
		
		document.forms[2].elements['qualificationForm.placeOfEducation'].disabled = disable;
		document.forms[2].elements['qualificationForm.examYear'].disabled = disable;
		document.forms[2].elements['continue'].disabled = disable;	
		bgcolor = "#FFFFFF";
		if (disable) {	
			bgcolor = "#EBEBE4";	
			changeCSSClass('continue', 'btn disabled');		
		} else {			
			changeCSSClass('continue', 'btn');	
		}
		document.forms[2].elements['qualificationForm.education'].style.backgroundColor = bgcolor;
		document.forms[2].elements['qualificationForm.placeOfEducation'].style.backgroundColor = bgcolor;
		document.forms[2].elements['qualificationForm.examYear'].style.backgroundColor = bgcolor;
}


  // This function takes care of checking whether or not it is legal to send the form
        var submitExecuted = 0;

        function haveNotSubmittedBefore()
        {
            // Have the user already submited the form?
            if(submitExecuted == 0)
            {
                submitExecuted = 1;
                return true;
            }
            else
            {
                // Ths user has already submittet a form and is not allowed to do it twice
                alert("Du har allerede klikket på en knap på denne side!\nVent venligst på et svar.")
                return false;
            }
        }



// Changes the CSS class used by element with id "elemId" to "newClass"
function changeCSSClass(elemId, newClass) {
	identity=document.getElementById(elemId);
	identity.className=newClass;
}


//Jumps to the field defined by ID 'nextId' in the form when max. length of elmnt has been reached.
// EXECPT if the key pressed was TAB (keycode=9), ENTER(keycode=13), SHIFT (keycode=16), ARROW-LEFT (keycode=37) or ARROW-RIGHT(keycode=39)
function toNextField(elmnt,nextId, evt)
{	
	var evnt = (window.event) ? window.event : evt;
	var content = elmnt.value;
	if(evnt.keyCode != 9 && evnt.keyCode != 13 && evnt.keyCode != 16 && evnt.keyCode != 37 && evnt.keyCode != 39){
		if (content.length==elmnt.maxLength){
			next=document.getElementById(nextId);			
			next.focus();			
			Highlight(next);
		}		
	}
}


// Selects the content of the element passed in as parameter
function Highlight(theElement){
	if(theElement){
		theElement.select();
	}
}

function setPrintRecipientEnabled(value, elm){	
		elm.disabled = !value;	
		if(!value){
			setDisabledTxtInputBGColor(elm);
		}
		else{
			setEnabledTxtInputBGColor(elm);
		}
}

function toggleBox(divID, visible) 
{
    if(document.layers){ 
       //NN4+
       document.layers[divID].visibility = visible ? "show" : "hide";       
    }
    else if(document.getElementById){	  
    	//gecko(NN6) and IE5+
        var obj = document.getElementById(divID);
        obj.style.visibility = visible ? "visible" : "hidden";        
    }
    else if(document.all){
    	// IE 4
        document.all[divID].style.visibility = visible ? "visible" : "hidden";               
    }
    if(visible){
       	setFocus('printRecipient');
    } 
}

function setFocus(elementId){
	 if(document.layers){ 
       //NN4+
       document.layers[elementId].focus();       
    }
    else if(document.getElementById){	  
	    //gecko(NN6) and IE5+
    	document.getElementById(elementId).focus();        
    }
    else if(document.all){
    	// IE 4
        document.all[elementId].focus();
              
    }
}





