// Set up <essages
var msgGenericInvalidStart		= "Please enter a valid ";
var	msgGenericInvalidEnd		= "";

//== Field name variables:
var fieldForeName = 'foreName';
var fieldSurName = 'surName';
var fieldEmail = 'email';
var fieldStartDate = 'startDate';
var fieldEndDate = 'endDate';
var fieldTelephone = 'telephone';

//== Constants
var constMaxFieldLength			= 100;	

//==	object glbGetElementById (string strName)
//
//==		returns the element object contained in the document where the name is equal 
//==		to string strName. designed to be cross-browser compatible.

function glbGetElementById (strName) {
	var objRetVal;
	var blnUseForm = false;
	if (document.getElementById) {					//==	Check for getElementById method
		objRetVal = document.getElementById(strName);
	} else {
		if (document.all) {							//==	Check for the document.all collection
			objRetVal = document.all[strName];
		} else {									//==	Search document forms for element
			blnUseForm = true;
		}
	}
	
	if (objRetVal) {
		if (objRetVal.type) {								//==	If object is a radio button we need to access it using
			if (objRetVal.type.toLowerCase() == "radio") {	//==	the document.formname.elementname notation to retrive the radioset array
				eval ("objRetVal = document." + objRetVal.form.name + "." + strName);
			}
		}
	}

	if (blnUseForm) {
		for (var lngFormCounter=0; !objRetVal && lngFormCounter < document.forms.length; lngFormCounter++) {
			for (var lngElementCounter=0; !objRetVal && lngElementCounter < document.forms[lngFormCounter].elements.length; lngElementCounter++) {
				var objElement = document.forms[lngFormCounter].elements[lngElementCounter];
				if (objElement.name == strName) {			//==	Found element 
					objRetVal = document.forms[lngFormCounter].elements[strName];
				}
			}
		}			
	}
	return objRetVal;
}



//==	string getFieldValue (object objField) 
//
//==		returns the value of the select element object passed in to
//==		the function. returns an empty string if the object is null, 
//==		not a select or	does not have a value selected.

function getFieldValue(objField) {
	if (objField) {
		if (objField.type) {
			if (objField.type.toLowerCase() == "select-one") {			//==	Field is a select drop-down. Get the selected option value
				if (objField.selectedIndex > -1) {
					return objField.options[objField.options.selectedIndex].value;
				}
			}
			if (objField.type.toLowerCase() == "radio") {				//==	Field is a radio box, but not checked so don't return a value
				if (!objField.checked) {
					return "";
				}
			}
		}
		if (objField.length && objField[0]) {							//==	Field is an radioset array. Find radio button that is checked
			for (var intOption = 0; intOption < objField.length; intOption++) {	
				if (objField[intOption].checked) {
					return objField[intOption];
				}
			}
		}
		if (objField.value) {											//==	Standard field. Use the value property
			return objField.value;
		}
	}
	return "";
}



//==	string formatCurrency (decimal decCurrency) 
//
//==		returns a string formating the decimal decCurrency to two decimal
//==		places.

function formatCurrency(decCurrency) {
	var strCurrency = decCurrency.toString();
	var intDecPosn = strCurrency.indexOf(".");
	if (intDecPosn == -1) {								//==	No decimal point in number. Add the two decimal places.
		strCurrency = strCurrency + ".00";	
	} else {
		if ((strCurrency.length - intDecPosn) < 3) {	//==	Decimal point exists, but not to two decimal places. Pad to correct length
			strCurrency = rightPad(strCurrency, intDecPosn + 3, "0");
		}
	}
	return strCurrency;
}



//==	string leftPad (string str, integer len, string chr)
//
//==		returns the string str left-padded to length len with 
//==		the character chr.

function leftPad(str, len, chr) {
	while (str.length < len) str = chr + str;
	return str;
}



//==	string rightPad (string str, integer len, string chr)
//
//==		returns the string str right-padded to length len with 
//==		the character chr.

function rightPad(str, len, chr) {
	while (str.length < len) str = str + chr;
	return str;
}



//==	string getDateValue(object objDay, object objMonthYear)
// 
//==		if either of objDay, or objMonthYear are set to the "no, just one way" value, 
//== 		it returns a blank string and sets both fields to the "no, just one way" value.
//==		otherwise, it returns the date value provided by the fields in the following 
//==		format: 
//==			dd mmm yyyy
//==		use isValidDate to validate the date value.

function getDateValue(objDay, objMonthYear) {
	var strDayValue = "";
	var strMonthYearValue = "";
	
	strDayValue = getFieldValue(objDay);
	strMonthYearValue = getFieldValue(objMonthYear);

	if (strDayValue == -1 || strMonthYearValue == -1) {	//==	Day field set to "no" or
														//==	Month Year field set to "just one way"

		objDay.selectedIndex		= 0;				//==	Set to "no"
		objMonthYear.selectedIndex	= 0;				//==	Set to "just one way"
		return "";
	}
	return leftPad(strDayValue, 2, "0") + " " + strMonthYearValue.substr(0,3) + " " + strMonthYearValue.substr(3,4);
}



//==	bool isValidDate (string strDate)
// 
//==		strDate should be the following format: dd mmm yyyy
//==		if strDate is empty, or contains a valid date value, returns true.
//== 		otherwise returns false.

function isValidDate(strDate) {
	if (strDate == "") return true;
	var strDay = strDate.substr(0,2);					//==	Take the first two characters from the date
	if (strDay.substr(0,1) == "0")						//==	Remove padded zero	
		strDay = strDay.substr(1,1);
	var intDay = parseInt(strDay);
	var dteDate = new Date(strDate);
	
	if (dteDate.getDate() != intDay) {					//==	The day value of the date has changed,
														//==	the date must be invalid
		return false;
	}
	
	return true;
}



//==	bool isValidNumber (string strNumber)
// 
//==		returns true if is string strNumber is a valid number 
//== 		(contains 0-9 . + - ( or )). otherwise returns false.

function isValidNumber(strNumber) {
	var numInput = "+-0123456789(). ";					//==	String containing valid characters
	
	if (strNumber == "") return false;
	
	for(var k = 0; k < strNumber.length; k++) {
		if(numInput.indexOf(strNumber.charAt(k)) == -1)	{
			return false;
		}
	}
	return true;
}



//==	bool isValidPostcode (string strPostcode)
// 
//==		returns true if is string strPostcode is a valid postcode.
//== 		otherwise returns false.

function isValidPostcode(strPostcode) {
	var regExPC = /^[a-zA-Z]{1,2}[0-9]{1,2}[a-zA-Z]? ?[0-9][a-zA-Z]{2}$/
	return regExPC.test(strPostcode);
}



//==	bool isValidEmail (string strEmail)
// 
//==		returns true if is string strEmail is a valid email address.
//== 		otherwise returns false.

function isValidEmail(strEmail) {
	var regExEmail = /^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/
	return regExEmail.test(strEmail);
}



//==	string monthName (integer intMonth)
// 
//==		returns the abbreviated name of the month corresponding to the integer intMonth supplied.


function monthName (intMonth) {
	var aryMonths = new Array ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
	
	if ((intMonth > 0) && (intMonth < 13)) {
		return aryMonths[intMonth - 1];
	}
	
	return "";
}



//==	integer daysInMonth (integer intMonth, integer intYear)
// 
//==		returns the numbers of days in the month for the month and year supplied

function daysInMonth (intMonth, intYear) {
	if (intMonth < 1 || intMonth > 12) {
		return 0;
	}
	if (intMonth == 12) return 31;
	
	var dteDate = new Date ("1 " + monthName (intMonth + 1) + " " + intYear)
	
	if (dteDate) {
		dteDate.setDate(0);
		return dteDate.getDate();
	}
	
	return 0;
}


//==	bool checkRequiredField (object objField, string strTitle, bool blnRequired, optional string strType)
//
//==		returns true if the field value passes the validation tests based on whether it is required, 
//==		the type of the field. if it fails validation, a generic message is displayed using the 
//==		the supplied title. focus is given to the object, and false is returned.

function checkRequiredField (objField, strTitle, blnRequired, strType) {
	var strValue = getFieldValue(objField);

	if (objField) {
		if (objField.length && objField[0]) {		//==	Field is an array - likely radioset
			objField = objField[0];					//==	Set field to first item so we can apply focus
		}
	}
	
	if (blnRequired || strValue != "") {			//==	Field is required, or value has been entered so check format
		if (strType == "postcode" && blnRequired) {	//==	Apply postcode validation only if required
			if (!isValidPostcode(strValue)) {
				alert (msgGenericInvalidStart + strTitle + msgGenericInvalidEnd);
				objField.focus();
				return false;
			}
		}
		if (strType == "number") {
			if (!isValidNumber(strValue)) {			//==	Apply number validation
				alert (msgGenericInvalidStart + strTitle + msgGenericInvalidEnd);
				objField.focus();
				return false;
			}
		}
		if (strType == "email") {
			if (!isValidEmail(strValue)) {			//==	Apply email validation 
				alert (msgGenericInvalidStart + strTitle + msgGenericInvalidEnd);
				objField.focus();
				return false;
			}
		}
		if (strType == "date") {
			if (!isDate(strValue,strTitle)) {			//==	Apply date validation 
				objField.focus();
				return false;
			}
		}
		if (strValue == "" || strValue == -1) {		//==	Value is required but no value present
			alert (msgGenericInvalidStart + strTitle + msgGenericInvalidEnd);
			objField.focus();
			return false;
		}
	}
	
	if (strValue.length > constMaxFieldLength) {	//==	Length of field is greater than max length
		alert (msgGenericLongStart + strTitle + msgGenericLongEnd);
		objField.focus();
		return false;
	}
	
	return true;									//==	Check successful
}




function checkPage() {

	var objForeName	  	= glbGetElementById(fieldForeName);
	var objSurName			= glbGetElementById(fieldSurName);
	var objEmail  			= glbGetElementById(fieldEmail);
	var objTelephone  	= glbGetElementById(fieldTelephone);
	var objStartDate    = glbGetElementById(fieldStartDate);
	var objEndDate     	= glbGetElementById(fieldEndDate);
	
	if (!checkRequiredField(objForeName, "First Name", true, "")) return false;
	if (!checkRequiredField(objSurName, "Surname", true, "")) return false;
	if (!checkRequiredField(objEmail, "Email address", true, "email")) return false;
	if (!checkRequiredField(objTelephone, "Telephone", true, "")) return false;
	if (!checkRequiredField(objStartDate, "Start Date", true, "date")) return false;
	if (!checkRequiredField(objEndDate, "End Date", true, "date")) return false;

	return true;
} 








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

