/**************************************************************************
This function will validate a field given the field type, if validation
	fails, set the focus to the field and return out of the function so the 
	form doesn't get submitted
	FieldValue --> the value in the HTML form element
	FieldType --> an integer representing the type of input field it is
	ErrorMessage --> javascript alert text
					
// ************************************************************************/
function ValidateField(FieldValue, DefaultValue, FieldType, ErrorMessage, IsRequired) {

	/* these variables will be used as constants for the field types
		they match the ID's of field type in the Fields table */
	var TEXTBOX = 1;
	var TEXTAREA = 2;
	var SELECT_LIST = 3;
	var EMAIL = 6;
	var PHONE = 7;
	var CREDITCARD = 8;
	var MONEY = 9;
	var NUMBER = 10;
	var DATE_FIELD = 11;
	var TIME_FIELD = 12;
	var URL = 13;		
	
		/*Check if the field is blank, if it is return false
			this will take care of checking for TEXTBOX and TEXTAREA fields */
		if (IsRequired == 'True' || IsRequired == 'true') {
			if (HasValue(FieldValue, ErrorMessage) == false) {
				return false;
			}
		}
		
		/* This switch statement will call the various valudation finctions based on
				the FieldType parameter, individual functions will return TRUE/FALSE if the 
				field passes validation */	
	
		switch (FieldType) {
			case 3: //make sure the default value wasn't selected for select lists
				return ValidateSelection(FieldValue, DefaultValue, ErrorMessage, IsRequired);
				
			case 6: //make sure it is a valid e-mail
				return ValidateEmail(FieldValue, ErrorMessage, IsRequired);

			case 7: //make sure it is a valid phone number
				return ValidatePhoneNumber(FieldValue, ErrorMessage, IsRequired);

			case 8: //make sure it is a valid credit card number
				return ValidateCreditCard(FieldValue, ErrorMessage, IsRequired);

			case 9: //make sure it is a valid currency value
				return ValidateCurrency(FieldValue, ErrorMessage);
				
			case 10:	//make sure it is a valid number
				return ValidateNumber(FieldValue, ErrorMessage);
				
			case 11:	//make sure it is a valid date value
				return ValidateDate(FieldValue, ErrorMessage, IsRequired);
				
			case 12:	//make sure it is a valid time value
				return ValidateTime(FieldValue, ErrorMessage, IsRequired);
				
			case 13:	//make sure it is a valid URL, we send the Isrequired bit so we can process around the "http://"
				return ValidateURL(FieldValue, ErrorMessage, IsRequired);
				
		}			
						
	return true;
}


/**************************************************
 this function Checks for the following valid date format:
 MM/DD/YYYY
 *************************************************/ 
function ValidateDate(FieldValue, ErrorMessage, IsRequired) {

	if (FieldValue != '') {
		var months = new Array(12);
	
		months[4] = "April";
		months[6] = "June";
		months[9] = "September";
		months[11] = "November";
	
		var dateStr = FieldValue;
			
		var datePat = /^(\d{1,2})(\/)(\d{1,2})\2(\d{4})$/;

		var matchArray = dateStr.match(datePat); // is the format ok?

		if (matchArray == null) {
			alert(ErrorMessage + " Date is not in a valid format.");
			return false;
		}
	
		var month = matchArray[1];	// parse date into variables
		if (month.length == 2 && (month == 4 || month == 6 || month == 9)) {	// trim the leading zeros for array processing
			month = month.charAt(1);
		}
	
		var day = matchArray[3];
		var year = matchArray[4];

		if (year > 2100)
		{
			alert(ErrorMessage + " Year must be less than 2100.");
			return false;
		}
	
		if (month < 1 || month > 12) { // check month range
			alert(ErrorMessage + " Month must be between 1 and 12.");
			return false;
		}
	
		if (day < 1 || day > 31) {
			alert(ErrorMessage + " Day must be between 1 and 31.");
			return false;
		}

		if ((month==4 || month==6 || month==9 || month==11) && day==31) {
			alert(ErrorMessage + " The month of " + months[month] + " doesn't have 31 days.");
			return false;
		}
	
		if (month == 2) { // check for february 29th
			var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
	
			if (day>29 || (day==29 && !isleap)) {
				alert(ErrorMessage + " February " + year + " doesn't have " + day + " days.");
				return false;
			}
		}			
	}
	
	// date is valid
	return true;
}


/**************************************************
 this function Checks for the following valid time format:
 Checks if time is in HH:MM:SS AM/PM format
 The seconds and AM/PM are optional
 *************************************************/ 
function ValidateTime(FieldValue, ErrorMessage, IsRequired) {
	
	if (FieldValue != '') { 	
		var timeStr = FieldValue;
		var timePat = /^(\d{1,2}):(\d{2})(:(\d{2}))?(\s?(AM|am|PM|pm))?$/;
		var milPat = /^(0)(\d{1})$/;
		var military = false;

		var matchArray = timeStr.match(timePat);
		if (matchArray == null) {
			alert(ErrorMessage + " Time is not in a valid format.");
			return false;
		}

		var hour = matchArray[1];
		var minute = matchArray[2];
		var second = matchArray[4];
		var ampm = matchArray[6];

		var MilHour = hour.match(milPat);
		if (MilHour != null) {military = true;}

		if (second=="") { second = null; }
		if (ampm=="") { ampm = null; }

		if (hour < 0  || hour > 23) {
			alert(ErrorMessage + " Hour must be between 1 and 12. (or 0 and 23 for military time)");
			return false;
		}

		if (hour <= 12 && ampm == null && hour != 0 && military == false)
		{
			if (confirm("Please indicate which time format you are using.  OK = Standard Time, CANCEL = Military Time")) {
				alert(ErrorMessage + " You must specify AM or PM.");
				return false;
		   }
		}
	
		if  ((military == true || hour > 12) && ampm != null) {
			alert(ErrorMessage + " You can't specify AM or PM for military time.");
			return false;
		}

		if (minute<0 || minute > 59) {
			alert (ErrorMessage + " Minute must be between 0 and 59.");
			return false;
		}
		if (second != null && (second < 0 || second > 59)) {
			alert (ErrorMessage + " Second must be between 0 and 59.");
			return false;
		}
	}

	//time is valid
	return true;
}

/**************************************************
 this function makes sure the default selection wasn't selected
 *************************************************/
function ValidateSelection(FieldValue, DefaultValue, ErrorMessage, IsRequired) {
	
	if ((FieldValue == DefaultValue) && (IsRequired == 'True' || IsRequired == 'true')) {
		alert(ErrorMessage);
		return false;
	}
		
	// everything is valid
	return true;
}


/**************************************************
 this function makes sure the text box is not empty, if empty pop an alert and return false
 *************************************************/
function HasValue(FieldValue, ErrorMessage) {
	
	var tempString = FieldValue;
	
	while ('' + tempString.charAt(0) == ' ') tempString = tempString.substring(1, tempString.length);
	
	if (tempString == "") {
		alert(ErrorMessage);
		return false;
	} 
		
	// everything is valid
	return true;
}


/**************************************************
 this function checks for a valid email entry
 *************************************************/ 
function ValidateEmail(FieldValue, ErrorMessage, IsRequired) {

	if (FieldValue != '') { 
		/* 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 ( ) < > @ , ; : \ " . [ ]	 */
		   /* bug fix by shawn 2/5/03: added ' to bad list cu screwd up our javascript */
		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 +")*$");


		/* see if the supplied address is valid. */
	
		/* break up user@domain into different pieces that are easy to analyze. */
		var matchArray=FieldValue.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. */
			alert(ErrorMessage + " Email address seems incorrect (check @ and .'s)");
			return false;
		}
	
		var user=matchArray[1];
		var domain=matchArray[2];

		// See if "user" is valid 
		if (user.match(userPat)==null) {
		    // user is not valid
		    alert(ErrorMessage + " The username doesn't seem to be 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) {
				alert(ErrorMessage + " Destination IP address is invalid.");
					return false;
			    }
		    }
		    return true;
		}

		// Domain is symbolic name
		var domainArray=domain.match(domainPat);
		if (domainArray==null) {
			alert(ErrorMessage + " The domain name doesn't seem to be valid.");
		    return false;
		}

		/* domain name seems valid, but now make sure that it ends in a
		   four-letter word (like firm, name, info),
		   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>4) {
		   // the address must end in a two letter or three letter word.
		   alert(ErrorMessage + " The address must end in a three or four letter domain, or two letter country.");
		   return false;
		}

		// Make sure there's a host name preceding the domain.
		if (len<2) {
		   alert(ErrorMessage + " This address is missing a hostname.");
		   return false;
		}
	}

	// everything is valid
	return true;
}


/**************************************************
 this function checks for a valid phone number entry
 *************************************************/ 
function ValidatePhoneNumber(FieldValue, ErrorMessage, IsRequired)
{
	
	var TheNumber = FieldValue;
	var GoodChars = "0123456789()-+ext ";
	var i = 0;

	if ((IsRequired == "true" || IsRequired == "True") && TheNumber.length < 10)
	{
		alert(ErrorMessage + " Phone Numbers must be at least 10 digits long.");
		return false;
	}

	for (i =0; i <= TheNumber.length -1; i++)
	{
		if (GoodChars.indexOf(TheNumber.charAt(i)) == -1)
		{
			alert(ErrorMessage);
			return false;
		}
	}

	// everything is valid
	return true;
}


/**************************************************
 this function checks for a valid credit card number entry
 *************************************************/
function ValidateCreditCard(FieldValue, ErrorMessage, IsRequired)
{
	/* for now we are just checking that it has no letters or special characters
		and that it has sixteen numbers, later we can put in the code to check,
		it can be found at: http://javascript.internet.com/forms/val-credit-card.html */

	var TheNumber = FieldValue;
	var GoodChars = "0123456789";
	var i = 0;

	if ((IsRequired == "true" || IsRequired == "True") && TheNumber.length != 16)
	{
		alert(ErrorMessage + " Number must be sixteen digits long.");
		return false;
	}

	for (i =0; i <= TheNumber.length -1; i++)
	{
		if (GoodChars.indexOf(TheNumber.charAt(i)) == -1)
		{
			alert(ErrorMessage + " Number must not have any letters or special characters.");
			return false;
		}
	}

	return true;
}
 
 
/**************************************************
 this function checks for a valid currency entry,
	first we will strip any currency characters (,$)
	then we check that the value is numeric
 *************************************************/  
function ValidateCurrency(FieldValue, ErrorMessage) {

	var Money = FieldValue;
	
	//Money = Money.replace(/\$|\,/g,'');	//remove commas and $
	Money = Money.replace(/\,/g,'');	//remove commas and $
	
	if (isNaN(Money)) {	//check if the leftover is numeric
		alert(ErrorMessage);
		return false;
	}
	
	return true;
}


/**************************************************
 this function checks for a valid numeric entry
 *************************************************/ 
function ValidateNumber(FieldValue, ErrorMessage) {

	var Number = FieldValue;
	
	if (isNaN(Number)) {
		alert(ErrorMessage);
		return false;
	}
	
	return true;
}  


/**************************************************
 this function checks for a valid URL entry
 *************************************************/ 
function ValidateURL(FieldValue, ErrorMessage, IsRequired) {
	
	var URL = FieldValue;
	
	var tempString = URL.substring(0, 7);
	
	if (IsRequired == 'true' || IsRequired == 'True') //do these checks if it is required
	{
		//if they left the default value (http://), it's not valid
		if (URL == "http://") {
			alert(ErrorMessage);
			return false;
		}
		
		//if the URL doesn't start with http://, it's not valid
		if (tempString != "http://") {
			alert(ErrorMessage);
			return false;
		}
	} else {
		if ((URL != '') && (URL != 'http://')) {	//if they filled anything in we should check it
			//if the URL doesn't start with http://, it's not valid
			if (tempString != 'http://') {
				alert(ErrorMessage);
				return false;
			}
		}
	}
	return true;
}


