// Validation File

var submitted = false;

function CheckEmailAddress (emailStr) {

	/* The following pattern is used to check if the entered e-mail address
	   fits the user@domain format.  It also is used to separate the username
	   from the domain. */
	var emailPat=/^(.+)@(.+)$/
	/* The following string represents the pattern for matching all special
	   characters.  We don't want to allow special characters in the address.
	   These characters include ( ) < > @ , ; : \ " . [ ]    */
	var specialChars="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]"
	/* The following string represents the range of characters allowed in a
	   username or domainname.  It really states which chars aren't allowed. */
	var validChars="\[^\\s" + specialChars + "\]"
	/* The following pattern applies if the "user" is a quoted string (in
	   which case, there are no rules about which characters are allowed
	   and which aren't; anything goes).  E.g. "jiminy cricket"@disney.com
	   is a legal e-mail address. */
	var quotedUser="(\"[^\"]*\")"
	/* The following pattern applies for domains that are IP addresses,
	   rather than symbolic names.  E.g. joe@[123.124.233.4] is a legal
	   e-mail address. NOTE: The square brackets are required. */
	var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/
	/* The following string represents an atom (basically a series of
	   non-special characters.) */
	var atom=validChars + '+'
	/* The following string represents one word in the typical username.
	   For example, in john.doe@somewhere.com, john and doe are words.
	   Basically, a word is either an atom or quoted string. */
	var word="(" + atom + "|" + quotedUser + ")"
	// The following pattern describes the structure of the user
	var userPat=new RegExp("^" + word + "(\\." + word + ")*$")
	/* The following pattern describes the structure of a normal symbolic
	   domain, as opposed to ipDomainPat, shown above. */
	var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$")


	/* Finally, let's start trying to figure out if the supplied address is
	   valid. */

	/* Begin with the coarse pattern to simply break up user@domain into
	   different pieces that are easy to analyze. */
	var matchArray=emailStr.match(emailPat)
	if (matchArray==null) {
	  /* Too many/few @'s or something; basically, this address doesn't
		 even fit the general mould of a valid e-mail address. */
		return false
	}
	var user=matchArray[1]
	var domain=matchArray[2]

	// See if "user" is valid
	if (user.match(userPat)==null) {
		// user is not valid
		return false
	}

	/* if the e-mail address is at an IP address (as opposed to a symbolic
	   host name) make sure the IP address is valid. */
	var IPArray=domain.match(ipDomainPat)
	if (IPArray!=null) {
		// this is an IP address
		  for (var i=1;i<=4;i++) {
			if (IPArray[i]>255) {
			return false
			}
		}
		return true
	}

	// Domain is symbolic name
	var domainArray=domain.match(domainPat)
	if (domainArray==null) {
		return false
	}

	/* domain name seems valid, but now make sure that it ends in a
	   three-letter word (like com, edu, gov) or a two-letter word,
	   representing country (uk, nl), and that there's a hostname preceding
	   the domain or country. */

	/* Now we need to break up the domain to get a count of how many atoms
	   it consists of. */
	var atomPat=new RegExp(atom,"g")
	var domArr=domain.match(atomPat)
	var len=domArr.length
	if (domArr[domArr.length-1].length<2 ||
		domArr[domArr.length-1].length>3) {
	   // the address must end in a two letter or three letter word.
	   return false
	}

	// Make sure there's a host name preceding the domain.
	if (len<2) {
	   return false
	}

	// If we've gotten this far, everything's valid!
	return true;
}

function CheckInputValidation( inputType, inputObj, boolCanBeEmpty, lngMinLength, lngMaxLength, boolStripChars )
{
	// Assume a negative
	var isValid = false;
	var inputValue = inputObj.value;

	// Is it a select
	if ( inputType == 'select' )
		isValid = CheckSelect( inputValue, boolCanBeEmpty )	
	else if ( inputType == 'email' )
		isValid = CheckEmailAddress( inputValue, boolCanBeEmpty, lngMinLength, lngMaxLength, boolStripChars )	
	else if ( inputType == 'phonenumber' )
		isValid = CheckPhoneNumber( inputValue, boolCanBeEmpty, lngMinLength, lngMaxLength, boolStripChars )
	else if ( inputType == 'freetext' )
		isValid = CheckFreeText( inputValue, boolCanBeEmpty, lngMinLength, lngMaxLength, boolStripChars )
	else if ( inputType == 'radio' )
		isValid = CheckRadio( inputObj, boolCanBeEmpty );
	
	// Set the colour ...
	if ( isValid ) 
		if ( inputType == 'radio' ) {
			for (i = 0; i < inputObj.length; i++) {
				inputObj[i].style.background = '';
			}
		} else
			inputObj.style.background = 'white';
	else 
		if ( inputType == 'radio' ) {
			for (i = 0; i < inputObj.length; i++) {
				inputObj[i].style.background = 'red';
			}
		} else
			inputObj.style.background = 'red';
	
	if (submitted && !isValid){

		errMsg = "";
		if (inputObj.id){
			errMsg = inputObj.id;
		}
		else{
			errMsg = "Elements in Red";
		}
		alert(errMsg + " must be completed\n");
		submitted = false;
	}
	// ... and return boolean indication
	return isValid;
}

function isPhoneNumber(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 isMoney(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" ) && c !="," && c!=".") 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++)
    {   
        // Check that current character isn't whitespace.
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

function CheckRadio( inputObj, boolCanBeEmpty )
{
	var isValid = false;
	
	if ( boolCanBeEmpty == false ) {
		for (i = 0; i < inputObj.length; i++) {
			thisValid = inputObj[i].checked; 	 // had to do this cos of javascript 
			if ( thisValid == true ) isValid = true; // bombing out cos of some bug
		}
	}
	
	return isValid;
}

function CheckAttributes ( inputValue, boolCanBeEmpty, lngMinLength, lngMaxLength, strStripChars )
{
	var isValid = true;
	
	// Do we need to count spaces in the length check?
	if ( strStripChars != "" ) inputValue = stripCharsInBag( inputValue, strStripChars );
	
	// Is it empty? And can it be?
	if ( !boolCanBeEmpty && inputValue.length == 0 ) 
		isValid = false;
	// Check if its too short ...
	if ( inputValue.length < lngMinLength ) 
		isValid = false;	
	// Or too long?
	else if ( inputValue.length > lngMaxLength ) 
		isValid = false;
		
	return isValid;
}	

function CheckFreeText(inputValue, boolCanBeEmpty, lngMinLength, lngMaxLength, strStripChars )
{
	var isValid = CheckAttributes( inputValue, boolCanBeEmpty, lngMinLength, lngMaxLength, strStripChars );
	
	return isValid;
}

function CheckSelect( inputValue, boolCanBeEmpty )
{

	var isValid 	= false;
		
	// Can this field be empty? And is it? Don't check then
	// Is it a select?
	if ( 	( boolCanBeEmpty == true )  ||
		( ( boolCanBeEmpty == false ) && !( ( inputValue == "" ) || ( inputValue == 0 ) ) ) 
	)
		isValid = true;

	return isValid;	
	
	// Ignore this  .... deals with mutiple selects, maybe useful one day?
	var inputObj;
	
	if ( boolCanBeEmpty == false ) {
		var lngSelectCount = 0;
		for (i = 0; i < inputObj.length; i++) {
			thisValid = inputObj[i].selected;
			if ( thisValid ) lngSelectCount++;
		}	
	}	
}

function CheckPhoneNumber(inputValue, boolCanBeEmpty, lngMinLength, lngMaxLength, boolStripChars )
{

	// Declaring required variables
	var digits = "0123456789";

	// non-digit characters which are allowed in phone numbers
	var phoneNumberDelimiters = "()- ";

	// characters which are allowed in international phone numbers (a leading + is OK)
	var validWorldPhoneChars = phoneNumberDelimiters + "+";

	// Minimum no of digits in an international phone no.
	var minDigitsInIPhoneNumber = 10;

	var isValid = CheckAttributes( inputValue, boolCanBeEmpty, lngMinLength, lngMaxLength, boolStripChars );

	if ( isValid ) { 
		s=stripCharsInBag(inputValue,validWorldPhoneChars);
		isValid = (isPhoneNumber(s) && s.length >= minDigitsInIPhoneNumber);	
	}
	
	return isValid;
}



function GetKeyCode(e) { // event object is being passed from function call.

	//Cross Browser functionality :-)
	

	//Call as follows: <textarea name="text" rows="4" cols="25" onKeypress="var x=GetKeyCode(event);alert(x);"></textarea>


	if(e){ // if the event object is present (NN only)
		e = e // var e = event
	}
	else {
		e = window.event // else e = winddow.event for IE
	}

	if(e.which){ // if there is syntax support for the property 'which' (NN only)
		var keycode = e.which // e.which is stored in variable "keycode"
	}
	else {
		var keycode = e.keyCode // otherwise for IE, var keycode stores e.keyCode syntax
	}


	return keycode;

	//These can be used to trap things from other functions (not that e must be passed)
	    //e.returnValue=false;
	//return false;


}


function DateEntryAutoHandler(objControl,e,strFormat) {


	//Written By Chris Barnes 2006-07-25

	var lngSeparatorCode;
	var lngTextLength;
	var boolReject;
	var objDate=new Date();
	var datLocaleNow;
	var lngKeyCodeWhiteSpace=32;
	var lngKeyCodeColon=58;
	var y;
	

	boolReject=true; //By Default



	if (isEmpty(strFormat)) {
		strFormat='dd/MM/yyyy hh:mm';
		lngSeparatorCode=47;
		strSeparatorChar="/";
		datLocaleNow= formatDate(objDate,strFormat);
	} else {
		if (strFormat !="dd/mm/yyyy hh:mm") {
			alert("This function currently only handles format dd/mm/yyyy hh:mm");
			e.returnValue=false;
			return false;
		}

	}

	//Parse the text already in the control

	var strText=objControl.value; //Note this is the value prior to update
	strText=strText.toString();
	lngTextLength=strText.length;
	var strSplitArray=strText.split(strSeparatorChar);

	if (lngTextLength > 0) {
		lngSepCount=strSplitArray.length -1;
	} else {
		lngSepCount=0;
	}


	//Look at what would happen if the key press was allowed
	var keycode=GetKeyCode(e);
	var strEntered=String.fromCharCode(keycode);
	strEntered=strEntered.toString();
	var strTestString=(strText + strEntered);

	var boolNumberEntered=false;
	y=parseInt(strEntered);

	// Changed this line from if(y > 0)

	if (y >= 0) {
		boolNumberEntered=true;
	}


	//Allow Back Space ! (Strangely, I had 46 in here, which IE thinks is a period symbol	
	if (keycode==8 || keycode==9) {
		//alert('hello');
		boolReject=false;
	}


	//If we have double zeros as the first string, forget it !
	if (strTestString=="00") {
		boolReject=true;	
		e.returnValue=false;
		return false;

	}
	
	

	if (keycode == 110 || keycode==78){
		if (strText != "") {
			
			if (confirm("Insert Todays Date ?") !=true) {
				boolReject=true;
				e.returnValue=false;
				return false;
			}
		}
		objControl.value=datLocaleNow;
		return false;	
	}


	if ((keycode >=48 && keycode <=58)||  keycode==lngKeyCodeWhiteSpace || keycode==lngSeparatorCode) {



		switch(lngSepCount){

			//Check for separators in existing string

			case 0:


				if (strSplitArray[0].length <=2 && keycode !=lngKeyCodeWhiteSpace && keycode !=lngKeyCodeColon ) {

					if (strSplitArray[0].length==0) {
						//Disallow Slash or space at begining
						if (keycode == lngSeparatorCode) {
							boolReject=true;
						} else {
							boolReject=false;
						}
					} else {

						//Check for out of range numbers
						y=parseInt(strSplitArray[0] + strEntered);

						//We dont know about leap years at this stage
						if (y > 31) {
							boolReject=true;
						} else {
							boolReject=false;
						}

					}

				} else {
					boolReject=true;

				}


				break;


			case 1:

				if (strSplitArray[1].length <=2 && keycode !=lngKeyCodeWhiteSpace && keycode !=lngKeyCodeColon) {

					if (strSplitArray[1].length==0) {
						//Disallow Slash at begining
						if (keycode == lngSeparatorCode) {
							boolReject=true;
						} else {
							boolReject=false;
						}
					} else {

						//Check for out of range numbers
						y=parseInt(strSplitArray[1] + strEntered);

						if (y > 12) {
							boolReject=true;
						} else {
							boolReject=false;
						}

					}

				} else {
					boolReject=true;

				}



				break;

			case 2: //Handle Year & Time

				if (keycode != lngSeparatorCode   && keycode !=lngKeyCodeWhiteSpace && keycode !=lngKeyCodeColon && strSplitArray[2].length < 4) {
					if (strSplitArray[2].length==0) {
						//Prevent non Y2K compliant dates
						if (strEntered == "0") {
							boolReject=true;
						} else {
							boolReject=false;
						}
					} else {
					boolReject=false;
					}
				}


				//Getting towards handling time - the white space
				if (strSplitArray[2].length == 4 && keycode==lngKeyCodeWhiteSpace) {
					//Can only be a single white space
					boolReject=false;
				}

				//Handle time

				if (strSplitArray[2].length > 4) {


					var strTime=strSplitArray[2].toString();
					strTime=strTime.substring(5,strTime.length);
					var strTimeArray=strTime.split(":");


					y=parseInt(strTimeArray[0] + strEntered);				
					if (y <= 23 && boolNumberEntered==true){
						boolReject=false;
					}
					
					y=parseInt(strTimeArray[0]);
					if (isUndefined(strTimeArray[1]) && y <=23 && y >=0 && keycode==lngKeyCodeColon) {
						boolReject=false;
					}
	
	
					if (!isUndefined(strTimeArray[1])){
						y=parseInt(strTimeArray[1] + strEntered);				
						if (y <= 59 && boolNumberEntered==true){
								boolReject=false;
						}

					}
					
				}




				break;

		}





	} // End Processing



	if (boolReject==true) {
		e.returnValue=false;
		return false;
	}


}



