/*
Functions:

======================================================================================================================================
=	isMoney( obj, msg, cstate, integer )						Checks that it's a number and rounds to nearest
=																			penny. If 'integer' is true (boolean) then it
=																			converts amount to an integer, else converts it
=																			to 2 decimal places.
=
=	requiredField( obj, msg, cstate )							Checks that anything has been entered in the
=																			specified fileds.
=
=	requiredRadio( obj, msg, cstate )							Checks that one radio button has been selected.
=
=	isaNum( obj, msg, cstate )										Checks that it's a positive integer.
=
=	minLength( obj, msg, minlen, cstate )						Ensures the selected field is longer than or equal
=																			to the minimum length.
=
=	maxLength( obj, msg, maxlen, cstate )						Ensures the selected field is no longer than the
=																			maximum length.
=
=	validSame( obj1, obj2, msg, cstate )						Ensures 2 fileds are equal (good for confirming
=																			passwords).
=
=	validEmail( obj, msg, cstate )								Ensures that the selected field contains an '@' and#
=																			a '.'.
=
=	validDate( objDay, objMonth, objYear, msg, cstate )	Checks that three fields make up a valid date.
=
=  requiredTextarea( obj, msg, initialValue, cstate )		Checks that a textarea contains text.  Set
=																			'initialValue' to blank ('') if there is none.
=
=  requiredSelect( obj, msg, cstate )							Checks that a select box's value is not 0.
=
======================================================================================================================================
*/


// this flags keeps track of the first error and so sets the focus on that input type first
errorFlag = 0;

function errorMsg( str )
	{
	messageStr += str + "\n"
	return false;
}

function PostcodeUK( obj, msg, cstate )
{
		pcode = "" + (obj.value);
		pcode = pcode.substring(0,2);
		pcode = pcode.toUpperCase();
		if ((pcode.indexOf('GY') > -1) || (pcode.indexOf('JE') > -1 ))
		{
			if (errorFlag == 0)
			{
			obj.focus();
			errorFlag = 1
			}
			return errorMsg(msg);
		}


	return cstate;
}


function isMoney( obj, msg, cstate, integer ) {
	// check to see if numeric
	if (isNaN(obj.value)) {
		if (errorFlag == 0) {
			obj.focus();
			errorFlag = 1
		}
		return errorMsg(msg);
	}
	// check to see if decimal entered
	var s = obj.value;
	var decimal = s.search(/\./i);
	if (decimal == -1){
		if (errorFlag == 0) {
			obj.focus();
			errorFlag = 1
		}
	return errorMsg(msg);
	}
	// check to see if pence entered to two decimals
	if (s.length != decimal + 3){
		if (errorFlag == 0) {
			obj.focus();
			errorFlag = 1
		}
	return errorMsg(msg);
	}
	return cstate;
}

function requiredField( obj, msg, cstate ) {
	if( obj.value.length == 0 ) {
		if (errorFlag == 0) {
			obj.focus();
			errorFlag = 1
		}
		return errorMsg(msg);
	}
	return cstate;
}


function requiredCheck( obj, msg, cstate ) {
	if( obj.checked == false ) {
		if (errorFlag == 0) {
			obj.focus();
			errorFlag = 1
		}
		return errorMsg(msg);
	}
	return cstate;
}


function requiredRadio( obj, msg, cstate ) {
	var IsChecked = 0
	for (var x=0; x < obj.length; x++)
		{
		if (obj[x].checked == true)
			{IsChecked = 1}
		}
	 if( IsChecked == 0 ) {
		if (errorFlag == 0) {
			obj[0].focus();
			errorFlag = 1
		}
		return errorMsg(msg);
	}
	return cstate;
}



function requiredTextarea( obj, msg, initialValue, cstate ) {
	if( obj.value.length <= 1 || obj.value == initialValue ) {
		if (errorFlag == 0) {
			obj.focus();
			errorFlag = 1
		}
		return errorMsg(msg);
	}
	return cstate;
}

function requiredSelect( obj, msg, cstate ) {
	selectedPosition = obj.selectedIndex;
	if( obj.options[selectedPosition].value == 0 || selectedPosition == 0 ) {
		if (errorFlag == 0) {
			obj.focus();
			errorFlag = 1
		}
		return errorMsg(msg);
	}
	return cstate;
}



function requiredMultiSelect( obj, msg, cstate ) {
	selectedPosition = obj.selectedIndex;
	if( selectedPosition == -1 ) {
		if (errorFlag == 0) {
			obj.focus();
			errorFlag = 1
		}
		return errorMsg(msg);
	}
	return cstate;
}



function requiredSelectOrField(obj1, obj2, msg, cstate) {
	selectedPosition = obj1.selectedIndex;
	if( (obj1.options[selectedPosition].value == 0 || selectedPosition == 0) && obj2.value.length == 0 ) {
		if (errorFlag == 0) {
			obj1.focus();
			errorFlag = 1
		}
		return errorMsg(msg);
	}
	return cstate;


}


function isaNum( obj, msg, cstate ) {
	if (isNaN(obj.value) || (obj.value == '')){
		if (errorFlag == 0) {
			obj.focus();
			errorFlag = 1
		}
		return errorMsg(msg);

	} else {
    }
	if( obj.value < 0 ) {

		if (errorFlag == 0) {
			obj.focus();
			errorFlag = 1
		}
		return errorMsg(msg);
	} else {
    }
	return cstate;
}


function isaNumOrBlank( obj, msg, cstate ) {
	if (isNaN(obj.value)){
		if (errorFlag == 0) {
			obj.focus();
			errorFlag = 1
		}
		return errorMsg(msg);

	} else {
    }
	if( obj.value < 0 ) {

		if (errorFlag == 0) {
			obj.focus();
			errorFlag = 1
		}
		return errorMsg(msg);
	} else {
    }
	return cstate;
}




function minLength( obj, msg, minlen, cstate ) {
	if( obj.value.length < minlen ) {
		if (errorFlag == 0) {
			obj.value = "";
			obj.focus();
			errorFlag = 1
		}
		return errorMsg(msg);
	}
	return cstate;
}

function maxLength( obj, msg, maxlen, cstate ) {
	if( obj.value.length > maxlen ) {
		if (errorFlag == 0) {
			obj.value = "";
			obj.focus();
			errorFlag = 1
		}
		return errorMsg(msg);
	}
	return cstate;
}
function validText (obj, msg, cstate) {
	var valid="abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789,.?!-£$%^&*()+#'@/\"\\_=;:'\n\r";
	len = obj.value.length;
	if (len > 0) {
		for (i=0;i<len;i++) {
			if (valid.indexOf(obj.value.charAt(i)) == -1) {
				if (errorFlag == 0) {
					obj.value = "";
					obj.focus();
					errorFlag = 1
				}
				return errorMsg(msg);
			}
		}
	}
	return cstate;
}

function validSame( obj1, obj2, msg, cstate ) {
	if( obj1.value != obj2.value ) {
		obj2.value = "";
		if (errorFlag == 0) {
			obj2.focus();
			errorFlag = 1
		}
		return errorMsg(msg);
	}
	return cstate;
}

var emailRegxp = /^([\w-_]+)(.[\w-_]+)*@([\w-_]+)(.[\w-_]{2,3}){1,2}$/;

function validEmail( obj, msg, cstate ) {
	if( obj.value.length == 0 ) {
		if (errorFlag == 0) {
			obj.focus();
			errorFlag = 1
		}
		return errorMsg(msg);
	}
	else {
		tempmail = "" + (obj.value);

		if (emailRegxp.test(tempmail) != true) {
	//	if((tempmail.indexOf("@") == -1) || (tempmail.indexOf(".") == -1) || (tempmail.indexOf('/') > -1) || (tempmail.indexOf('\\') > -1)|| (tempmail.indexOf('\&') > -1) )  {
			if (errorFlag == 0) {
				obj.focus();
				errorFlag = 1
			}
			return errorMsg(msg);
		}
	}
	return cstate;
}

function validTelephone (obj, msg, cstate) {
//	var phoneRE = /^\(\d\d\d\) \d\d\d-\d\d\d\d$/;
//	var phoneRE = /^(\+)[\s]*(.*)\(\d{1,3}\) \d{5,15}$/;
	var phoneRE = /^((\+\d{1,3}(-| )?\(?\d\)?(-| )?\d{1,5})|(\(?\d{1,6}\)?))(-| )?(\d{1,6})(-| )?(\d{1,6})(( x| ext)\d{1,5}){0,1}$/
	if (!obj.value.match(phoneRE)) {
		if (errorFlag == 0) {
			obj.focus();
			errorFlag = 1
		}
		return errorMsg(msg);
	}
	return cstate;
}

function validURL(obj, msg, cstate) {
	if (obj.value.length == 0) {
		if (errorFlag ==0) {
			obj.focus();
			errorFlag = 1;
		}
		return errorMsg(msg);
	}

    var v = new RegExp();
    v.compile("^[A-Za-z]+://[A-Za-z0-9-_]+\\.[A-Za-z0-9-_%&\?\/.=]+$");
    if (!v.test(obj.value)) {
        msg = "You must supply a valid URL.";
        return errorMsg(msg);
    }
	return cstate;
}
function validMonth( obj, msg, cstate ) {
	if( obj.value < 1 || obj.value > 12 ) {
		if (errorFlag == 0) {
			obj.focus();
			errorFlag = 1
		}
		return errorMsg(msg);
		}
	return cstate;
}

function validYear( obj, msg, cstate ) {
	if( obj.value < 2002 || obj.value > 2011 ) {
		if (errorFlag == 0) {
			obj.focus();
			errorFlag = 1
		}
		return errorMsg(msg);
		}
	return cstate;
}

function validDate( objDay, objMonth, objYear, msg, cstate ) {

	_day   = 0 + objDay.options[objDay.selectedIndex].value;
	_month = objMonth.options[objMonth.selectedIndex].value;
	_year  = 0 + objYear.options[objYear.selectedIndex].value;

	// Validate the date
	if( _day == 0 || _month == 0 || _year == 0)
		{
		return errorMsg(msg + "You must enter a valid date.");
		}

	if( _month == "9" || _month == "4" || _month == "6" || _month == "11" ) {
		if( _day > 30 ) {
			if (errorFlag == 0) {
				objDay.focus();
				errorFlag = 1
			}
			return errorMsg(msg + "There are only 30 days in the selected month!");
		}
	}
	if( _month == "2" ) {
	//Is it a leap year (modulus 4)
		if( (_year % 4) == 0 ) {
			if(_day > 29 ) {
				if (errorFlag == 0) {
					objDay.focus();
					errorFlag = 1
				}
				return errorMsg(msg + "There are 29 days in February of that year.");
			}
		}
		else {
			if( _day > 28 ) {
				if (errorFlag == 0) {
					objDay.focus();
					errorFlag = 1
				}
				return errorMsg(msg + "There are 28 days in February of that year.");
			}
		}
	}
	return cstate;
}

function validCard (obj, msg, cLength, cstate)
    {
    	var white_space = " +";
		var number_string = "0123456789";
    	var creditcard_string="";
		var temp_string="";
    	var check_char;

    	// remove white space

re = / /gi;
str = obj.value;
creditcard_string=str.replace(re, "");

//    	for (var i = 0; i < obj.value.length; i++)
//    	{
//    		check_char = white_space.indexOf(obj.value.charAt(i))
//    		if (check_char < 0)
//    			creditcard_string += obj.value.substring(i, (i + 1));
//    	}
    	if (creditcard_string.length == 0) {
			if (errorFlag == 0) {
				obj.focus();
				errorFlag = 1
			}
	   		return errorMsg(msg + " card number not entered.");
        }
    	if (creditcard_string.length < cLength) {
			if (errorFlag == 0) {
				obj.focus();
				errorFlag = 1
			}
	    	return errorMsg(msg + " card number too short.");
        }

		// check for numerics only
		for (var i = 0; i < creditcard_string.length; i++)
    	{
			check_char = creditcard_string.substring(i, (i + 1))
    		if (isNaN(check_char)) {
				if (errorFlag == 0) {
					obj.focus();
					errorFlag = 1
				}
				return errorMsg(msg + " alphanumeric number entered.");
            }

    	}

    	// make sure number is a valid integer
    	if (creditcard_string.charAt(0) == "+") {
	    	return errorMsg(msg + " non numeric number entered.");
        }
    	// now check mod10
    	var doubledigit = creditcard_string.length % 2 == 1 ? false : true;
    	var checkdigit = 0;
    	var tempdigit;
    	for (var i = 0; i < creditcard_string.length; i++)
    	{
    		tempdigit = eval(creditcard_string.charAt(i))
    		if (doubledigit)
    		{
    			tempdigit *= 2;
    			checkdigit += (tempdigit % 10);
    			if ((tempdigit / 10) >= 1.0)
    			{
    				checkdigit++;

    			}
    			doubledigit = false;
    		}
    		else
    		{
    			checkdigit += tempdigit;
    			doubledigit = true;
    		}
    	}
		if ((checkdigit % 10) != 0)
			{
				return errorMsg(msg + " invalid number entered.");
			}

		return cstate;
    }

function doRed(obj) {
    	obj.style.background='#12B206';
        obj.style.color='#ffffff';
}

function undoRed(obj) {
        obj.style.background='#ffffff';
        obj.style.color='#000000';
}


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, msg, cstate){
		var daysInMonth = DaysArray(12)
		var pos1=dtStr.value.indexOf(dtCh)
		var pos2=dtStr.value.indexOf(dtCh,pos1+1)
		var strDay=dtStr.value.substring(0,pos1)
		var strMonth=dtStr.value.substring(pos1+1,pos2)
		var strYear=dtStr.value.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){
			dtStr.focus();
			return errorMsg(msg + ": The date format should be : dd/mm/yyyy");
		}


		if (strMonth.length<1 || month<1 || month>12){
			dtStr.focus();
			return errorMsg(msg + ": Please enter a valid month");
		}

		if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
			dtStr.focus();
			return errorMsg(msg + ": Please enter a valid day");
		}

		if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
			dtStr.focus();
			return errorMsg(msg + ": Please enter a valid 4 digit year between "+minYear+" and "+maxYear);
		}

		if (dtStr.value.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr.value, dtCh))==false){
			dtStr.focus();
			return errorMsg(msg + ": Please enter a valid date");
		}

		return cstate;
	}

