/*
 * Clear Default Text: functions for clearing and replacing default text in
 * <input> elements.
 */
addEvent(window, 'load', init, false);

function init() {
    var formInputs = document.getElementsByTagName('input');
    for (var i = 0; i < formInputs.length; i++) {
        var theInput = formInputs[i];
        
        if (theInput.type == 'text' && theInput.className.match(/\bdateInput\b/)) {  
            /* Add event handlers */          
            addEvent(theInput, 'focus', clearDefaultText, false);
            addEvent(theInput, 'blur', replaceDefaultText, false);
            
            /* Save the current value */
            if (theInput.value != '') {
                theInput.defaultText = theInput.value;
            }
        }
    }
}
/* 
 * Cross-browser event handling
 */
function addEvent(element, eventType, lamdaFunction, useCapture) {
    if (element.addEventListener) {
        element.addEventListener(eventType, lamdaFunction, useCapture);
        return true;
    } else if (element.attachEvent) {
        var r = element.attachEvent('on' + eventType, lamdaFunction);
        return r;
    } else {
        return false;
    }
}
//search field default text
function clearDefaultText(e) {
    var target = window.event ? window.event.srcElement : e ? e.target : null;
    if (!target) return;
    
    if (target.value == target.defaultText) {
        target.value = '';
    }
}

function replaceDefaultText(e) {
    var target = window.event ? window.event.srcElement : e ? e.target : null;
    if (!target) return;
    
    if (target.value == '' && target.defaultText) {
        target.value = target.defaultText;
    }
}

//check date formats
function validateDate(fld) {
	var date = fld;
    var RegExPattern = /^((((0?[1-9]|[12]\d|3[01])[\/](0?[13578]|1[02])[\/]((1[6-9]|[2-9]\d)?\d{2}))|((0?[1-9]|[12]\d|30)[\/](0?[13456789]|1[012])[\/]((1[6-9]|[2-9]\d)?\d{2}))|((0?[1-9]|1\d|2[0-8])[\/]0?2[\/]((1[6-9]|[2-9]\d)?\d{2}))|(29[\/]0?2[\/]((1[6-9]|[2-9]\d)?(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00)|00)))|(((0[1-9]|[12]\d|3[01])(0[13578]|1[02])((1[6-9]|[2-9]\d)?\d{2}))|((0[1-9]|[12]\d|30)(0[13456789]|1[012])((1[6-9]|[2-9]\d)?\d{2}))|((0[1-9]|1\d|2[0-8])02((1[6-9]|[2-9]\d)?\d{2}))|(2902((1[6-9]|[2-9]\d)?(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00)|00))))$/;
    var errorMessage = 'Please enter valid date in the format dd/mm/yyyy';
    if ((date.match(RegExPattern)) && (date!='')) {
        //alert('Date is OK'); 
    } else {
        alert(errorMessage);
        date.focus;
    } 
}

function trim(s)
{
  return s.replace(/^\s+|\s+$/, '');
}

function validateEmail(fld) {
    var error="";
    var tfld = trim(fld.value);                        // value of field with whitespace trimmed off
    var emailFilter = /^[^@]+@[^@.]+\.[^@]*\w\w$/ ;
    var illegalChars= /[\(\)\<\>\,\;\:\\\"\[\]]/ ;
   
    if (fld.value == "" || !emailFilter.test(tfld)) {
        fld.style.background = '#F6C580';
        error = "\n- Please enter a valid email address";
    } else if (fld.value.match(illegalChars)) {
        fld.style.background = '#F6C580';
        error = "\n- The email address contains illegal characters";
    } else {
        fld.style.background = '#ffffff';
    }
    return error;
}

function validateEmpty(fld, errmsg) {
    var error = "";
 
    if (fld.value.length == 0) {
        fld.style.background = '#F6C580'; 
        error = errmsg;
    } else {
        fld.style.background = '#ffffff';
    }
    return error;  
}

function validateArrDepDate(fld) {
    var error = true;
 
    if (fld.value.length == 0 || fld.value == "dd/mm/yyyy") {
        fld.style.background = '#F6C580'; 
        error = false;
    } else {
        fld.style.background = '#ffffff';
    }
    return error;  
}

function validateArrDepDates(fld1, fld2, errmsg) {
    var error = "";
 
    if (validateArrDepDate(fld1) == false)
        error = errmsg;
	if (validateArrDepDate(fld2) == false) 
        error = errmsg;
    if (error == "")
	{
		// process dates
		var dfrom = fld1.value;
		var dto = fld2.value;
		var date_from = new Date(dfrom.substring(6,10),dfrom.substring(3,5)-1,dfrom.substring(0,2));
		var date_to = new Date(dto.substring(6,10),dto.substring(3,5)-1,dto.substring(0,2));
	    if (date_from > date_to)
		{
	        fld1.style.background = '#F6C580'; 
			fld2.style.background = '#F6C580'; 
	        error = "\n- Your arrival date comes after your departure date";
		}
		else
		{
	        fld1.style.background = '#ffffff'; 
			fld2.style.background = '#ffffff'; 
		}
    }
    return error;  
}

function validateEmptyCombo(fld, errmsg) {
    var error = "";
 
    if (fld.selectedIndex == 0) {
        fld.style.background = '#F6C580'; 
        error = errmsg;
    } else {
        fld.style.background = '#ffffff';
    }
    return error;  
}

function validateCheckbox(fld, errmsg) {
    var error = "";
	if (fld.checked != true) {
		fld.style.background = '#F6C580'; 
		error = errmsg;
	} else {
		fld.style.background = '#ffffff';
    }
	return error;
}

function validateValue(fld, value, errmsg) {
    var error = "";
 
    if (fld.value != value) {
        fld.style.background = '#F6C580'; 
        error = errmsg;
    } else {
        fld.style.background = '#ffffff';
    }
    return error;  
}

//form validation
function validateDirectory() {
	var errorText = "";
	var regform = document.forms['pg_form'];
	var yF = regform['yearfrom'].value;
	var yT = regform['yearto'].value;
	errorText += validateEmpty(regform['fname'], "\n- Please enter your first name");
	errorText += validateEmpty(regform['lname'], "\n- Please enter your last name");
	errorText += validateEmail(regform['email']);
	errorText += validateEmptyCombo(regform['country'], "\n- Please select a country");
	errorText += validateEmptyCombo(regform['yearfrom'], "\n- Please select the year you arrived in Brockwood Park School");
	errorText += validateEmptyCombo(regform['yearto'], "\n- Please select the year you left Brockwood Park School");
	if ( yF > 0 &&  yT > 0 )
	{
		if ( yF > yT )
		{
			regform['yearfrom'].style.background = '#F6C580'; 
			regform['yearto'].style.background = '#F6C580'; 
			errorText += "\n- Your arrival year at Brockwood comes after your departure year";
		}
		else
		{
			regform['yearfrom'].style.background = '#ffffff'; 
			regform['yearto'].style.background = '#ffffff'; 
		}
	}	
	errorText += validateEmpty(regform['occupation'], "\n- Please enter your occupation");
	errorText += validateCheckbox(regform['agreement'], "\n- To submit the form you have to agree that the information provided be listed in the Alumni Directory");
	if (errorText != "") {
		alert("Please correct the following entries on the registration form:\n" + errorText);
		return false;
	}
	else return true;
}

function validateGuestbook() {
	var errorText = "";
	var regform = document.forms['pg_form'];
	errorText += validateEmpty(regform['fname'], "\n- Please enter your first name");
	errorText += validateEmpty(regform['lname'], "\n- Please enter your last name");
	errorText += validateEmpty(regform['address'], "\n- Please enter a contact address");
	errorText += validateEmpty(regform['city'], "\n- Please enter your city");
	errorText += validateEmpty(regform['postcode'], "\n- Please enter your postcode");	
	errorText += validateEmptyCombo(regform['country'], "\n- Please select a country");
	errorText += validateEmail(regform['email']);
	if ( regform['heardAbout'].value.indexOf('*') != -1 ) {
		errorText += validateEmpty(regform['heardFrom'], "\n- Please tell us how you heard about the school");
	}
	errorText += validateValue(regform['safe'], 5, "\n- Please validate the security code");
	if (errorText != "") {
		alert("Please correct the following mistakes on the guest book form:\n" + errorText);
		return false;
	}
	else return true;
}

function validateProspectus() {
	var errorText = "";
	var regform = document.forms['pg_form'];
	errorText += validateEmpty(regform['fname'], "\n- Please enter your first name");
	errorText += validateEmpty(regform['lname'], "\n- Please enter your last name");
	errorText += validateEmpty(regform['address'], "\n- Please enter a contact address");
	errorText += validateEmpty(regform['city'], "\n- Please enter your city");
	errorText += validateEmpty(regform['postcode'], "\n- Please enter your postcode");	
	errorText += validateEmptyCombo(regform['country'], "\n- Please select a country");
	errorText += validateEmail(regform['email']);
	if ( regform['heardAbout'].value.indexOf('*') != -1 ) {
		errorText += validateEmpty(regform['heardFrom'], "\n- Please tell us how you heard about the school");
	}
	if (errorText != "") {
		alert("Please correct the following mistakes on the prospectus form:\n" + errorText);
		return false;
	}
	else return true;
}

function validateContact() {
	var errorText = "";
	var regform = document.forms['pg_form'];
	errorText += validateEmpty(regform['name'], "\n- Please enter your name");
	errorText += validateEmail(regform['email']);
	errorText += validateEmpty(regform['text'], "\n- Please enter your message");
	if (errorText != "") {
		alert("Please correct the following mistakes on the contact form:\n" + errorText);
		return false;
	}
	else return true;
}


