
function addLoadEvent(func) {
  	var oldonload = window.onload;
  	if (typeof window.onload != 'function') {
		window.onload = func;
  	} else {
		window.onload = function() {
	  		oldonload();
	  		func();
		}
  	}
}

function addUnloadEvent(func) {
  	var oldonunload = window.onunload;
  	if (typeof window.onunload != 'function') {
		window.onunload = func;
  	} else {
		window.onunload = function() {
	  		oldonunload();
	  		func();
		}
  	}
}

function prepareForms() {
	for (var i=0; i<document.forms.length; i++) {
		var thisform = document.forms[i];
		
		if(thisform.name != "subscribe"){
			thisform.onsubmit = function() {
				return validateForm(this);
			}
		}
  	}
}

function isFilled(field) {
  	var ret = false;
  
  	if (field.type == 'checkbox') {
	  	if (field.checked) ret = true;
  	} else if (field.value != '') ret = true;

  	return ret;
}

function isUkPostcode(pc) {
	ret = false;
	var re = /^[A-Za-z]{1,2}[\d]{1,2}([A-Za-z])?\s?[\d][A-Za-z]{2}$/;				
	
	if (re.test(pc)) {
		ret = true;
	}
	return ret;
}

function checkIllegalChars(string){
	
	flag = 0;
	var illegal_chars = "*|,\":<>[]{}`\';()@&$#%";
	
	for (var i = 0; i < string.length; i++) {
		if (illegal_chars.indexOf(string.charAt(i)) != -1){
			flag=1;
		}
	}
	if(flag)
		return false;
	else
		return true;
}

function isDOB(dob) {
	ret = false;
	
	if (isDate(dob)){
		ret = true;
	}
    return ret
}

var dtCh= "/";
var minYear=1900;
var maxYear=2100;

function isInteger(s){
	var i;
    for (i = 0; i < s.length; i++){   
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    // All characters are numbers.
    return true;
}

function stripCharsInBag(s, bag){
	var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++){   
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

function daysInFebruary (year){
	// February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}
function DaysArray(n) {
	for (var i = 1; i <= n; i++) {
		this[i] = 31
		if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
		if (i==2) {this[i] = 29}
   } 
   return this
}

function isDate(dtStr){
	var daysInMonth = DaysArray(12)
	var pos1=dtStr.indexOf(dtCh)
	var pos2=dtStr.indexOf(dtCh,pos1+1)
	var strDay=dtStr.substring(0,pos1)
	var strMonth=dtStr.substring(pos1+1,pos2)
	var strYear=dtStr.substring(pos2+1)
	strYr=strYear
	if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1)
	if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1)
	for (var i = 1; i <= 3; i++) {
		if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1)
	}
	day=parseInt(strDay)
	month=parseInt(strMonth)
	year=parseInt(strYr)
	if (pos1==-1 || pos2==-1){
		alert("The date format should be : dd/mm/yyyy")
		return false
	}
	if (strMonth.length<1 || month<1 || month>12){
		alert("Please enter a valid month")
		return false
	}
	if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
		alert("Please enter a valid day")
		return false
	}
	if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
		alert("Please enter a valid 4 digit year between "+minYear+" and "+maxYear)
		return false
	}
	if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
		alert("Please enter a valid date")
		return false
	}
return true
}

function isEmail(str) {
	ret = false;
	var re = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})/;
	
	if (re.test(str) || str == '') {
		ret = true;
	}
	return ret;
}

function validateForm(frm) {

	var ret = true;
	var msg = '';
	
	for (var i=0; i<frm.elements.length; i++) {
		var element = frm.elements[i];
		
		var arrClassRules = element.className.split(' ');

		for (var j=0; j<arrClassRules.length; j++) {
			var rule = arrClassRules[j];
			
			if (rule.indexOf('required') != -1 && ret) {    // IF FIELD IS REQUIRED
				if (element.parentNode.style.display != 'none') {	// AND PARENT DIV IS VISIBLE
					if (element.style.display != 'none') { // AND IT IS VISIBLE
						if (!isFilled(element)) { // AND ITS NOT FILLED IN
							msg = getMsg(element);
							ret = false;
						}
					}
				}
				
			} else if ((rule.indexOf('tied') != -1) && ret) {    // IF FIELD IS REQUIRED AND TIED TO ANOTHER FIELD
				var arrParms = rule.split('_');
				var tiedElement = document.getElementById(arrParms[1]);
					
				if (arrParms.length == 2) {
					if (!isFilled(element) && !isFilled(tiedElement)) {
						msg = getMsg(element);
						ret = false;
					}	
						
				} else if (arrParms.length == 3) {
					var selectedFlag = false;
		
					if (tiedElement.tagName == 'SELECT') {
						selectedFlag = (arrParms[2] == tiedElement.selectedIndex);
					} else if ((tiedElement.tagName == 'INPUT') && (tiedElement.type == 'radio')) {
						selectedFlag = eval("tiedElement.form." + tiedElement.name + "[" + arrParms[2] + "].checked")
					}
						
					if (!isFilled(element) && selectedFlag) {
						msg = getMsg(element);
						ret = false;
					}					
				} 
			} else if ((rule.indexOf('number') != -1) && ret) {    // IF FIELD MUST BE A NUMBER
				if (isNaN(element.value)) {
					msg = getMsg(element);
					ret = false;
				}
			} else if ((rule.indexOf('ukpostcode') != -1) && ret) {    // IF FIELD MUST BE A UK POSTCODE
				if (!isUkPostcode(element.value)) {
					msg = getMsg(element);	
										ret = false;
				}
			}
			else if ((rule.indexOf('friend_name') != -1) && ret) {    
				
				// check checkbox
				var friend = document.getElementById("friendYes").checked;
				var friend_name= document.getElementById("friendName").value;


				if(friend){
					// check both username and postcode are entered
					if(friend_name == ''){
						msg = getMsg(element);		
						ret = false;
					}
					
				}
				
			}
			else if ((rule.indexOf('friend_postcode') != -1) && ret) {    
				
				// check checkbox
				var friend = document.getElementById("friendYes").checked;
				var friend_postcode= document.getElementById("friendPO").value;
				
					
				if(friend){
					// check both username and postcode are entered
					if(friend_postcode == ''){
						
						msg = getMsg(element);		
						ret = false;
					}
					
				}
				
			}
			
			// Postcode ********
			else if ((rule.indexOf('postcode') != -1) && ret) {    // IF FIELD MUST BE A UK POSTCODE
				if (element.parentNode.style.display != 'none') {	// AND PARENT DIV IS VISIBLE
					if (element.style.display != 'none') { // AND IT IS VISIBLE

							var selected = "";
							var myform = frm.getAttribute('name');
							var el_id = element.getAttribute('id');
							
							// Messages
							var default_msg = getMsg(element);
							var uk_msg = getCustomMsg(el_id);
							//alert(uk_msg);
							
							// Country Selected
							if(el_id == "postcode_new"){
								// New Country - Change Details Form
								if(eval('document.' + myform + '.country_new.value')) selected = eval('document.' + myform + '.country_new.value');
								var illegal_msg = 'Your new postcode contains illegal characters';
							}
							else{
								if(eval('document.' + myform + '.country.value')) selected = eval('document.' + myform + '.country.value');
								var illegal_msg = 'Your postcode contains illegal characters';
							}
							
							//alert(default_msg);
							// If not value supplied 
							if(element.value == ''){
								
								if(selected == "United Kingdom" || (selected == "" && frm.typeAddress.value != 'International')){
									msg = uk_msg;
									ret = false;
								}
								else{
									// disabled mandatory international postcodes - TR JUN2007
									//  msg  = default_msg;
								}
							}
							// if value enter validate
							else{
								
								if(selected == "United Kingdom" || (selected == "" && frm.typeAddress.value != 'International')){
									if (!isUkPostcode(element.value)) {
										msg = uk_msg;					
										ret = false;
									}
								}
								else{
									if (!checkIllegalChars(element.value)) {
										msg = illegal_msg;					
										ret = false;
									}
								}
							}
					}
				}
			}
			else if ((rule.indexOf('email') != -1) && ret) {    // IF FIELD MUST BE AN EMAIL
				if (!isEmail(element.value)) {
					msg = getCustomMsg('emailValid');						
					ret = false;
				}
				
                        } else if ((rule.indexOf('telephone') != -1) && ret) {    // IF FIELD MUST BE A TELEPHONE NUMBER
				if(document.getElementById('telephone'))
				{
					if(!document.getElementById('telephone').value || isInteger(document.getElementById('telephone').value)==false){
						msg = getCustomMsg('telephone');						
						ret = false;
					}
				}
				
			} else if ((rule.indexOf('msword') != -1) && ret) {    // IF FIELD MUST INCLUDE .doc
				if (element.value.indexOf('.doc') == -1 && (element.value != '')) {
					msg = getCustomMsg('msword');						
					ret = false;
				}				
			} else if ((rule.indexOf('dob') != -1) && ret) {    // IF FIELD MUST BE A DATE FORMAT
				if ((element.value != '') && (element.value != null)) {
				
					if (!isDOB(element.value)) {
						//msg = getMsg(element);
						ret = false;
					}
				}
                        } else if ((rule.indexOf('over18') == false) && ret) { 
                                if (!document.dataCapture.over18.checked) {
					alert('You must be over 18');	
                                        ret = false;
				}
			} else if ((rule.indexOf('gt') != -1) && ret) {    // IF FIELD MUST BE GREATER THAN A NUMBER
				if ((element.value != '') && (element.value != null)) {		
					var arrParms = rule.split('_');

					if (parseInt(element.value) <= parseInt(arrParms[1])) {
						msg = getMsg(element);
						ret = false;
					}	
				}
			} else if ((rule.indexOf('participants') != -1) && ret) {    // Check number of participants					
				if ((element.value != '') && (element.value != null)) {		
					if (document.famine.participants.value < 3 || document.famine.participants.value > 9999) {
						alert('Please enter a value between 3 - 9999');	
						ret = false;
					}
				}
			}else if ((rule.indexOf('accountMin') != -1) && ret) {    // Check account number is no less than 8	
				if ((element.value != '') && (element.value != null)) {		
					if (document.sponsorPayment.acount_code.value.length < 8 ) {
						alert('Your account number should be 8 digits long');	
						ret = false;
					}
				}
			}
		}
	}
	if (msg.length > 0) alert(msg)
	return ret;
}

function getMsg(el) {
	var msg = el.getAttribute('alt');
	
	if ((msg == null) || (msg == '')) {
		msg = getCustomMsg(el.name);
	}
	
	return msg;
}

function getCustomMsg(elName) {
	var msg;
	//alert(elName);
	/* messages for various pages */	
	
	if(elName == 'postCode'){
		
		msg = 'Please enter a valid uk postcode.';
		
	} else if(elName == 'postcode_new'){
		
		msg = 'Please enter a valid uk new postcode.';
		
	} else if (elName == 'ukAccount') {
		msg = 'Please confirm that you have a UK bank account.';
		
	} else if (elName == 'tellUsWhere' || elName == 'motivation') {
		//msg = 'Please tell us where you heard about World Vision Child Sponsorship.';
		msg = 'Please tell us where you heard about World Vision UK.';	
		
	} else if (elName == 'tellUsWhere2') {
		msg = 'Please tell us where you heard about World Vision.';	
		
	} else if (elName == 'emailValid') {
		msg = 'Please enter a valid email address.';				
	
	/* messages for dataCapture */		
		
	} else if (elName == 'title') {
		msg = 'Please select a title.';
		
	} else if (elName == 'title') {
		msg = 'Please select a title.';
		
	} else if (elName == 'membership') {
		msg = 'Please enter your World Vision Membership Number.';
		
	} else if (elName == 'surname') {
		msg = 'Please enter your second name.';		
		
	} else if (elName == 'forename') {
		msg = 'Please enter your first name.';		
		
	} else if (elName == 'organisation') {
		msg = 'Please enter your organisation\'s name.';		
		
	} else if (elName == 'contact') {
		msg = 'Please enter your organisation\'s contact name.';		
		
	} else if (elName == 'postCode') {
		msg = 'Please enter your postcode.';		
		
	} else if (elName == 'address1') {
		msg = 'Please enter your address.';	
		
	} else if (elName == 'country') {
		msg = 'Please enter your country.';
                
	} else if (elName == 'telephone') {
		msg = 'Please enter your home telephone number.';
                
	} else if (elName == 'postcode_new') {
		msg = 'Please enter your new postcode.';		
		
	} else if (elName == 'address_new1') {
		msg = 'Please enter your new address.';		
		
	}
	else if (elName == 'country_new') {
		msg = 'Please enter your new country.';		
		
	}
	else if (elName == 'dobUnder') {
		msg = 'Please enter your date of birth if you\'re under 18.';		
		
	/* messages for regularGiving */	
	
	} else if (elName == 'largerAmount') {
		msg = 'Please specify a valid amount.';		
	
	} else if (elName == 'larger') {
		msg = 'Please enter a larger amount than £8.';		
			
	/* messages for singleDonation */	
	
	} else if (elName == 'singleAmount') {
		msg = 'Please specify a valid amount.';				
	
	} else if (elName == 'appeal') {
		msg = 'Please select the appeal you would like to donate to.';			
	
	/* messages for sponsorPayment */	
	
	} else if (elName == 'sortCode') {
		msg = 'Please specify a sort code.';				
	
	} else if (elName == 'accountNum') {
		msg = 'Please specify an account number.';				
	
	} else if (elName == 'accountHolder') {
		msg = 'Please specify an account holder.';						
		
	/* messages for send_to_friend.php */	
	
	} else if (elName == 'sourceName') {
		msg = 'Please enter your name.';
	
	} else if (elName == 'sourceEmail') {
		msg = 'Please enter your email.';
	
	} else if (elName == 'targetName') {
		msg = 'Please enter the recipient\'s name.';
	
	} else if (elName == 'targetEmail') {
		msg = 'Please enter the recipient\'s email address.';
		
	/* messages for ADPlocator block */	
	
	} else if (elName == 'show') {
		msg = 'Please select a country.';		
		
	/* messages for application form */
	} else if (elName == 'email') {
		msg = 'Please enter your email.';
	} else if (elName == 'notice') {
		msg = 'Please enter the period of notice.';
	} else if (elName == 'position') {
		msg = 'Please enter the position applied for.';
	} else if (elName == 'dataProtection') {
		msg = 'Please consent to World Vision UK holding your details.';
	
	} else if (elName == 'declaration') {
		msg = 'Please confirm that all your details are knowingly correct.';
		
	} else if (elName == 'homeTel') {
		msg = 'Please enter your home telephone number.';
	
	} else if (elName == 'address3') {
		msg = 'Please enter the city of your home address.';
	
	} else if (elName == 'schoolName1') {
		msg = 'Please enter the name of your school or college.';

	} else if (elName == 'attendedStartMonth1') {
		msg = 'Please enter the month you started your school or college.';
	
	} else if (elName == 'attendedStartYear1') {
		msg = 'Please enter the year you started your school or college.';

	} else if (elName == 'attendedFinishMonth1') {
		msg = 'Please enter the month you finished your school or college.';
	
	} else if (elName == 'attendedFinishYear1') {
		msg = 'Please enter the year you finished your school or college.';
	
	} else if (elName == 'postCodeSchool1') {
		msg = 'Please enter the postcode of your school or college.';
	
	} else if (elName == 'schoolAddress11') {
		msg = 'Please enter the first line of the address for your school or college.';
	
	} else if (elName == 'schoolAddress1') {
		msg = 'Please enter the first line of the address for your school or college.';
	
	} else if (elName == 'schoolAddress1_2') {
		msg = 'Please enter the second line of the address for your school or college.';
		
	} else if (elName == 'qualifications1') {
		msg = 'Please enter the qualifications you gained at your school or college.';

	} else if (elName == 'namePastoral') {
		msg = 'Please enter a name for your pastoral reference.';
	
	} else if (elName == 'postCodePastoral') {
		msg = 'Please enter a postcode for your pastoral reference.';

	} else if (elName == 'address1Pastoral') {
		msg = 'Please enter the first line of the address for your pastoral reference.';

	} else if (elName == 'address2Pastoral') {
		msg = 'Please enter the second line of the address for your pastoral reference.';

	} else if (elName == 'pastoralYears' || elName == 'personalYears2') {
		msg = 'Please enter a valid number of years you have known your referee.';

	} else if (elName == 'namePersonal') {
		msg = 'Please enter a name for your personal reference.';

	} else if (elName == 'namePersonal2') {
		msg = 'Please enter a name for your personal reference.';

	} else if (elName == 'postCodePersonal') {
		msg = 'Please enter a postcode for your personal reference.';

	} else if (elName == 'address1Personal') {
		msg = 'Please enter the first line of the address for your personal referee.';

	} else if (elName == 'address2Personal') {
		msg = 'Please enter the second line of the address for your personal referee.';
		
	} else if (elName == 'jobTitle1') {
		msg = 'Please enter your job title.';

	} else if (elName == 'organisation1') {
		msg = 'Please enter your organisation.';
	
	} else if (elName == 'employStartMonth1') {
		msg = 'Please enter the month you started your job.';
	
	} else if (elName == 'employStartYear1') {
		msg = 'Please enter the year you started your job.';
	
	} else if (elName == 'employFinishMonth1') {
		msg = 'Please enter the month you finished your job.';

	} else if (elName == 'employStartYear1') {
		msg = 'Please enter the year you started your job.';

	} else if (elName == 'salaryStart1') {
		msg = 'Please enter your salary at the start of your job.';
		
	} else if (elName == 'salaryFinish1') {
		msg = 'Please enter your salary at the end of your job.';
	
	} else if (elName == 'responsibilities1') {
		msg = 'Please enter your responsibilities at this job.';
	
	} else if (elName == 'reason1') {
		msg = 'Please enter your reasons for leaving this job.';
	
	} else if (elName == 'nameEmploy1') {
		msg = 'Please enter the name of your employer.';
	
	} else if (elName == 'postCodeEmploy') {
		msg = 'Please enter the postcode for the address of your job.';

	} else if (elName == 'address1Employ1') {
		msg = 'Please enter the first line of the address for this job.';
	
	} else if (elName == 'address2Employ1') {
		msg = 'Please enter the second line of the address for this job.';
		
	} else if (elName == 'supEmploy1') {
		msg = 'Please enter your supervisor\'s name.';
		
	} else if (elName == 'supJobTitle1') {
		msg = 'Please enter your supervisor\'s job title.';

	} else if (elName == 'church') {

		msg = 'Please eneter a church name for your pastoral reference.';
	
	} else if (elName == 'describeInvolvement') {
	
		msg = 'Please describe your involvement in a Church or a Christian community.';

	} else if (elName == 'describeFaith') {
		
		msg = 'Please describe your faith.';

	} else if (elName == 'difference') {
		
		msg = 'Please describe what difference your faith has made to your life.';
	
	} else if (elName == 'msword') {
		
		msg = 'CV must be in word format.';	
	} else if (elName == 'org_group') {
		
		msg = 'Please select the type of group';		

	/* default message for anything else */		
		
	} 
	return msg;
}

addLoadEvent(prepareForms);


// QAS support for forms

function goToFindAddress(pc, buildingNumber, buildingName, addr, county, country, type) {
	
	// parameters (all optional, except pc)
	
	// pc is the specified postcode.
	// buildingNumber is the name of the building number field. (Added TR - 23Jul07)
	// buildingName is the name of the building name field. (Added TR - 23Jul07)
	// addr is the name of the field we'll populate with the address.
	// county is the name of the field we'll populate with the county.
	// country is the name of the field we'll populate with 'United Kingdom' - since QAS is UK only.
		
	if(!isUkPostcode(pc)){
		if(type==''){
		alert("Please enter a valid uk postcode");
		}
		else{
			document.getElementById("error").innerHTML = "Please enter a valid uk postcode.<br />";
			
		}
	} else {
		// add pc to url
		//qasUrl = 'https://www.worldvision.org.uk/php/qas.php?pc=' + pc + "&addr=" + addr + "&county=" + county;
		qasUrl = './qas.php?pc=' + pc + "&buildingName=" + buildingName + "&buildingNumber=" + buildingNumber + "&addr=" + addr + "&county=" + county;
		// open window
		newwin = window.open(qasUrl, 'qas' , 'width=500,height=300,toolbar=0,scrollbars=1,resizable=1');
		if (newwin.opener==null) newwin.opener = self;
		
		if(country==null) country = 'country';
		if (document.getElementById(country)) document.getElementById(country).options[0] = new Option ('United Kingdom', 'United Kingdom', true, true);
	}
	
}

