//--------------------------------------------------------------------------
//	Filename:		form_validation.js
// 	Name:				form_validation (javascript)
//	Purpose(s):	contains javascript methods used by tracker to validate form
//	Author:			Brian Vaughn (bvaughn@vitalassets.com)
//	Date:				2005.02.16
//	Notes:			N/A
//
//	Copyright 2005 Brian Vaughn
//
//	Licensed under the Apache License, Version 2.0 (the "License"); 
//	you may not use this file except in compliance with the License. 
//	You may obtain a copy of the License at
//	
//	http://www.apache.org/licenses/LICENSE-2.0
//	
//	Unless required by applicable law or agreed to in writing, software 
//	distributed under the License is distributed on an "AS IS" BASIS, 
//	WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 
//	implied. See the License for the specific language governing 
//	permissions and limitations under the License.
//--------------------------------------------------------------------------

//--------------------------------------------------------------------------
// 	Name:				validate_integer
//	Purpose(s):	validates that value for specified form field is an integer
//	Author:			Brian Vaughn (bvaughn@vitalassets.com)
//	Date:				2005.02.16
//	Input:			form_field		- form field containing value in question
//							alert_message	- alert message to display (if not standard)
//	Output:			N/A
//	Notes:			function calls validate_number() for validation
//--------------------------------------------------------------------------
function validate_integer( form_field, alert_message ) {

	// if no alert message was specified, construct default
	if ( alert_message == '' || alert_message == null )
		alert_message	= 'You must enter an integer value!';
		
	// call out to helper function
	return validate_number( form_field, alert_message, "int" );
	
} // END validate_integer()

//--------------------------------------------------------------------------
// 	Name:				validate_float
//	Purpose(s):	validates that value for specified form field is an float
//	Author:			Brian Vaughn (bvaughn@vitalassets.com)
//	Date:				2005.02.16
//	Input:			form_field		- form field containing value in question
//							alert_message	- alert message to display (if not standard)
//	Output:			N/A
//	Notes:			function calls validate_number() for validation
//--------------------------------------------------------------------------
function validate_float( form_field, alert_message ) {

	// if no alert message was specified, construct default
	if ( alert_message == '' || alert_message == null )
		alert_message	= 'You must enter a decimal value!';
		
	// call out to helper function
	return validate_number( form_field, alert_message, "float" );
	
} // END validate_float()

//--------------------------------------------------------------------------
// 	Name:				validate_number
//	Purpose(s):	validates that value for form field is of type data_type
//	Author:			Brian Vaughn (bvaughn@vitalassets.com)
//	Date:				2005.02.16
//	Input:			form_field		- form field containing value in question
//							alert_message	- alert message to display (if not standard)
//							data_type			- type of data to check
//	Output:			N/A
//	Notes:			N/A
//--------------------------------------------------------------------------
function validate_number( form_field, alert_message, data_type ) {

	// using form field passed...
	with ( form_field ) {

		// remove leading zeros from value (to prevent breaking a valid ZEROFILL number)
		mod_value	= value;
		
		// walk through mod_value and discard any leading zeros
		for( var i = 0; i < mod_value.length; i++ ) {
			// once a non-zero integer has been reached, 
			if ( string[ i ] != '0' ) {
				mod_value	= mod_value.substring( i );
				break;
			}
		}
			
		// if an integer value is required, further parse float for int
		if ( data_type == "int" ) {
			form_field_parsed_value = parseInt( mod_value );
		
		// if float value, (or no value) parse string entered for float value
		} else {
			form_field_parsed_value = parseFloat( mod_value );
		
		} // end if int or float
		
		// if original value is not the same as parsed value, an error has occured
		if ( value != form_field_parsed_value && value != "" ) {
			
			// alert user of error
			window.alert( alert_message );
			
			// return false to indicate failure
			return false;
			
		// if original value is the same...
		} else {
			
			// return true to indicate success
			return true;
			
		} // END if failure check
		
	} // END with form_field
	
} // END validate_number()

//--------------------------------------------------------------------------
// 	Name:				validate_required
//	Purpose(s):	validates that required form fields have values entered
//	Author:			Brian Vaughn (bvaughn@vitalassets.com)
//	Date:				2005.03.02
//	Input:			form_field		- form field containing value in question
//							alert_message	- alert message to display (if not standard)
//	Output:			N/A
//	Notes:			N/A
//--------------------------------------------------------------------------
function validate_required( form_field, alert_message ) {

	// if no alert message was specified, construct default
	if ( alert_message == '' || alert_message == null )
		alert_message	= 'You are required to enter a value to proceed!';

	// using form field passed...
	with ( form_field ) {
		
		// if no value has been set, return an error message
		if ( value == "" ) {
			
			// alert user of error
			window.alert( alert_message );
			
			// return false to indicate failure
			return false;
			
		// if a value has been set...
		} else {
			
			// return true to indicate success
			return true;
			
		} // END if value given check
		
	} // END with form_field
	
} // END validate_required()

//--------------------------------------------------------------------------
// 	Name:				validate_email
//	Purpose(s):	validates given string to ensure valid email format
//	Author:			Sandeep V. Tamhankar (stamhankar@hotmail.com)
//	Date:				2005.03.04
//	Input:			form_field		- form field containing value in question
//	Output:			N/A
//	Notes:			This script and many more are available free online at
//							The JavaScript Source!! (http://javascript.internet.com)
//--------------------------------------------------------------------------
function validate_email( form_field ) {

	// retrieve text entered from given form field
	var emailStr = form_field.value;
	
	// proceed only if field not empty
	if (	emailStr != '' &&	emailStr != null ) {
	
		/* The following variable tells the rest of the function whether or not
		to verify that the address ends in a two-letter country or well-known
		TLD.  1 means check it, 0 means don't. */	
		var checkTLD=1;
		
		/* The following is the list of known TLDs that an e-mail address must end with. */	
		var knownDomsPat=/^(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum)$/;
		
		/* 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);
		
		/* Too many/few @'s or something; basically, this address doesn't
		even fit the general mould of a valid e-mail address. */
		if (matchArray==null) {	
			alert( "Invalid email format!" );
			return false;
		}
		
		var user=matchArray[1];
		var domain=matchArray[2];
		
		// Start by checking that only basic ASCII characters are in the strings (0-127).	
		for (i=0; i<user.length; i++) {
			if (user.charCodeAt(i)>127) {
				alert( "This username contains invalid characters." );
				return false;
			}
		}
		for (i=0; i<domain.length; i++) {
			if (domain.charCodeAt(i)>127) {
				alert( "This domain name contains invalid characters." );
				return false;
			}
		}
		
		// See if "user" is valid 
		if (user.match(userPat)==null) {
			alert( "This 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( "Destination IP address is invalid!" );
					return false;
				}
			}
			return true;
		}
		
		// Domain is symbolic name.  Check if it's valid.
		var atomPat=new RegExp("^" + atom + "$");
		var domArr=domain.split(".");
		var len=domArr.length;
		for (i=0;i<len;i++) {
			if (domArr[i].search(atomPat)==-1) {
				alert( "The domain name does not seem to be valid." );
				return false;
			}
		}
		
		/* domain name seems valid, but now make sure that it ends in a
		known top-level domain (like com, edu, gov) or a two-letter word,
		representing country (uk, nl), and that there's a hostname preceding 
		the domain or country. */
		if (checkTLD && domArr[domArr.length-1].length!=2 && 
		domArr[domArr.length-1].search(knownDomsPat)==-1) {
			alert( "The address must end in a well-known domain or two letter country." );
			return false;
		}
		
		// Make sure there's a host name preceding the domain.
		if (len<2) {
			alert( "This address is missing a hostname!" );
			return false;
		}
	
	} // end if string not empty
	
	// If we've gotten this far, everything's valid!
	return true;
} // END validate_email()

//--------------------------------------------------------------------------
// 	Name:				validate_phone
//	Purpose(s):	validates a user-entered phone number
//	Author:			Brian Vaughn (bvaughn@vitalassets.com)
//	Date:				2005.03.04
//	Input:			form_field		- form field containing value in question
//							alert_message	- alert message to display (if not standard)
//	Output:			N/A
//	Notes:			N/A
//--------------------------------------------------------------------------
function validate_phone( form_field, alert_message ) {

	// if no alert message was specified, construct default
	if ( alert_message == '' || alert_message == null )
		alert_message	= 'You did not enter a valid phone number!';

	// setup regular expressions values for later use
	allowed_digits			= '0-9';
	allowed_seperators	= '-,., ,(,)';
	allowed_extensions	= 'e,x,t';
	
	// check to make sure field is not empty before proceeding
	if ( form_field.value != '' && form_field.value != null ) {
		form_value	= form_field.value;
		
		// remove seperators from field value
		strip_seperators_exp = new RegExp( '[' + allowed_seperators + ']' );
		while( form_value.match(	strip_seperators_exp ) )
			form_value	= form_value.replace(	strip_seperators_exp, "" );
		
		// remove extension label from field value
		strip_extensions_exp = new RegExp( '[' + allowed_extensions + ']' );
		while( form_value.match(	strip_extensions_exp ) )
			form_value	= form_value.replace(	strip_extensions_exp, "" );
		
		// check now to make sure that only numerical data remains
		strip_digits_exp = new RegExp( '[^' + allowed_digits + ']' );
		if ( form_value.match(	strip_digits_exp ) ) {
			window.alert( alert_message );
			return false;
		} // end if non-numerical data present
	
	} // end if form empty
	
	// return true if script has made it this far
	return true;
	
} // END validate_phone()