/*
   This script validates form fields for proper values.
   Here's how to use it:

	  Call it from OnSubmit in the form tag with the following: OnSubmit="return checkForm(this.name);"
	  To validate a field include a hidden tag with the same name but append "_validate"
	   	to it then put the type of field it is as the value (see lit of types below).
		You may also add a custom error message for the field by appending
		the error message with a "-" then the message.
		
		Examples:
		With a custom message: 		<input type="hidden" name="FIRST_NAME_validate" value="text-Custom error message goes here.">
		Without a custome message 	<input type="hidden" name="FIRST_NAME_validate" value="text">
				
		The current field types are as follows:
		
		text - regular text field, check for the existance of a value- nothing else
		month - checks for an integer between 1 and 12 (no decimals)
		year - checks for integer (no decimals)
		longYear - checks for integer (no decimals)
	  	dropdown - checks that the first item is not selected
		checkbox - checks for at least one choice (note: all fields must be named the same)
		radio - checks for a selection
		email - checks for proper email syntax
		email_null - checks for proper email syntax, but allows null value
		numeric[(a)|(a,b)] - checks that the value is an integer number
				- (a): checks that the value is lesser than 'a'
				- (a,b): checks that the value is between 'a' and 'b'
		zipcode - checks that the value is a valid US zip code
		file[(ext1[, ext2[, ...]][:size]) - checks the field is not null
				- (ext1[, ext2[, ...]]) - checks the extension of the file is one of 'ext1', 'ext2', etc...
				- (:size) - checks the file is smaller than 'size' bytes
	
	For testing purposes, include a hidden field in your form named "sitesys_test" and
	it will stop the form from submitting.
	
	Modifications History
	**********************
	06/07/2001 - Created 
	06/11/2001 - Added new function to focus on first field that needs fixing
	06/12/2001 - Dash no longer needed when no custom error message is specified
	06/18/2001 - Added email_null type to check for proper email syntax only if a value is provided
	11/05/2001 - Fix Month and Year routine
	09/25/2002 - Add longYear validation
	11/11/2004 - Fix Year to use this year not a hard coded value
	02/11/2007 - Added numeric and zipcode validation
	04/18/2007 - Added file validation
*/

// set global params
var focusfield = '';
var bletSubmitGo = true
var today = new Date();
//
function checkForm(formname) {
//to avoid the ENTER without ckick;	
if (bletSubmitGo==false){return false}


	// create some default parameters for the error message if one is needed
	var final_msg = ""; 
	var intro = "There was a problem with your response.         \n\n"; // create intro 
	var ending = "\nPlease, make the necessary changes and try again.     " // create ending
	
	// define default messages 
	var err_text = "     - Incomplete Form"
	var err_month = "     - Invalid Month"
	var err_day = "     - Invalid Day"
	var err_year = "     - Invalid Year"
	var err_longYear = "     - Invalid Year"
	var err_dropdown = "     - Incomplete Form"
	var err_checkbox = "     - No checkbox selected"
	var err_email = "     - Invalid Email"
	var err_numeric = "     - Invalid number"
	var err_zipcode = "     - Invalid zipcode"
	
	var f = eval("document." + formname + ".elements"); // define the scope to save time
	var vArray = new Array(); // Create an Array to hold fields to be validated
		
	//Check for fields that need to be validated
	for (i=0; i<f.length; i++) {
		if(f[i].name.indexOf('_validate') != -1) {
			if (vArray.length == 0) {
				vCurrent = 0;
			} else {
				vCurrent = vCurrent + 1;
			}
			vArray[vCurrent]  = f[i].name;
		}
		// check for a hidden test to stop form from submitting
		if(f[i].name == 'sitesys_test') {
			var testing = true;
		}
	}

	// Now that we have the validated fields, start checking values
	for (i=0; i<vArray.length; i++) {
		var fposition = vArray[i].indexOf('_validate'); // find the position of "_validate"
		var fname = vArray[i].substring(0, fposition); // extract field name
		var validate = eval("document." + formname + "." + vArray[i] + ".value"); // define scope
		var dash = validate.indexOf('-'); // find the position of the "-"

		if(dash == -1) {
			var type = validate; // if there is no dash set error_msg to blank/default
			var err_msg = '';
		} else {
			var type = validate.substring(0,dash); // get field type

			//Only for numeric check
			var tmp = "numeric";
			if(type.substring(0, tmp.length) == tmp) {
				var n_beg = -65535;
				var n_end = 65535;

				var tmp_1 = type.indexOf('(');
				var tmp_2 = type.indexOf(')');

				if(tmp_1 != -1 && tmp_2 != -1 && tmp_1 < tmp_2)
				{
					var aux_1 = type.substring(tmp_1 + 1, tmp_2);
					var aux_2 = aux_1.split(',');

					type = "numeric";

					if(aux_2.length == 1)
					{
						if(isNumeric(aux_2[0]))
							n_end = aux_2[0];
					}
					else if(aux_2.length == 2)
					{
						if(isNumeric(aux_2[0]) && isNumeric(aux_2[1]))
						{
							n_beg = aux_2[0];
							n_end = aux_2[1];
						}
					}
					
				}
			}
			//End Only for numeric check

			//Only for file check
			tmp = "file";
			var f_size = -1;
			var f_extensions = new Array();

			if(type.substring(0, tmp.length) == tmp)
			{
				var tmp_1 = type.indexOf('(');
				var tmp_2 = type.indexOf(')');

				if(tmp_1 != -1 && tmp_2 != -1 && tmp_1 < tmp_2)
				{

					var aux_1 = type.substring(tmp_1 + 1, tmp_2);
					var aux_2 = aux_1.split(':');

					type = "file";

					if(aux_2.length >= 1 && aux_2.length <= 2)
					{
						var aux_3 = aux_2[0].split(',');

						for(var k = 0; k < aux_3.length; k++)
							if(trim(aux_3[k]).length > 0)
								f_extensions.push(trim(aux_3[k].toLowerCase()));

						if(aux_2.length == 2)
						{
							if(isNumeric(aux_2[1]))
								f_size = aux_2[1];
						}
					}
				}
			}
			//End Only for file check

			var err_msg = validate.substring(dash + 1, validate.length); // get custom error message if any
			var aTempLength = err_msg.split('<br>')
			for (iTempLength=0;iTempLength<aTempLength.length;iTempLength++){
				err_msg = err_msg.replace('<br>','\n')
			}
			aTempLength = err_msg.split('<b>')
			for (iTempLength=0;iTempLength<aTempLength.length;iTempLength++){
				err_msg = err_msg.replace('<b>','')
			}
			aTempLength = err_msg.split('</b>')
			for (iTempLength=0;iTempLength<aTempLength.length;iTempLength++){
				err_msg = err_msg.replace('</b>','')
			}
			
		}	

		var field = eval("document." + formname + "." + fname); // define field scope
		 
		// validate text fields
		if(type == 'text') {
			if(!field.value) {
				if (err_msg == "") {
					final_msg = final_msg + err_text + "\n";
				} else {
					final_msg = final_msg + err_msg + "\n";
				}	
			setCKFocus(field); // run focus function
			}	
		}
		// end text validation
		
		// validate month 
		if(type == 'month') {
			if ((!field.value) || (!isFinite(field.value)) || (field.value.indexOf('.') != -1) || (field.value > 12) || (field.value < 1) || (field.value == '  ') || (field.value == ' ')) {
				if (err_msg == "") {
					final_msg = final_msg + err_month + "\n";
					} else {
						final_msg = final_msg + err_msg + "\n";
				}				
			setCKFocus(field); // run focus function
			}
		}		
		// end month validation
		
		// validate day 
		if(type == 'day') {
			if ((!field.value) || (!isFinite(field.value)) || (field.value.indexOf('.') != -1) || (field.value > 31) || (field.value < 1) || (field.value == '  ') || (field.value == ' ')) {
				if (err_msg == "") {
					final_msg = final_msg + err_day + "\n";
					} else {
						final_msg = final_msg + err_msg + "\n";
				}				
			setCKFocus(field); // run focus function
			}
		}		
		// end month validation

		// validate year
		if(type == 'year') {
			if ((!field.value) || (!isFinite(field.value)) || (field.value.indexOf('.') != -1) || (field.value == '  ') || (field.value == ' ')) {
				if (err_msg == "") {
						final_msg = final_msg + err_year + "\n";
					} else {
						final_msg = final_msg + err_msg + "\n";
				}				
			setCKFocus(field); // run focus function	
			}
		}		
		// end year validation

		// validate longYear
		if(type == 'longYear') {
			//alert(field.value.length)
			iTemp = Val(field.value)
			sTemp = iTemp  + "A"
			//alert(sTemp.length)
			if ((sTemp.length != 5) || (!isFinite(iTemp)) || (sTemp.indexOf('.') != -1) || (iTemp < 1900) || (iTemp > today.getFullYear()) ){
				if (err_msg == "") {
						final_msg = final_msg + err_longYear + "\n";
					} else {
						final_msg = final_msg + err_msg + "\n";
				}				
			setCKFocus(field); // run focus function	
			}
		}		
		// end longYear validation
		
		
		// validate dropdown
		if(type == 'dropdown') {
			if(field[0].selected) {
				if (err_msg == "") {
						final_msg = final_msg + err_dropdown + "\n";
					} else {
						final_msg = final_msg + err_msg + "\n";
				}
			setCKFocus('nofocus'); // run focus function								
			}
		}
		// end dropdown validation
		
		// validate checkbox 
		if(type == 'checkbox'){
			var cempty = true;
			if(!field.length)
			{
				if(field.checked)
					cempty = false;
			}
			else for (c=0;c<field.length;c++) {
				if(field[c].checked) {
					cempty = false;
				}
			}
			if(cempty) {
				if (err_msg == "") {
					final_msg = final_msg + err_checkbox + "\n";
					} else {
						final_msg = final_msg + err_msg + "\n";
				}
			setCKFocus('nofocus'); // run focus function											
			}
		}
		// end checkbox validation
		
		// validate radio
		if(type == 'radio'){
			var rempty = true;
			for (r=0;r<field.length;r++) {
				if(field[r].checked) {
					rempty = false;
				}
			}
			if(rempty) {
				if (err_msg == "") {
					final_msg = final_msg + err_radio + "\n";
					} else {
						final_msg = final_msg + err_msg + "\n";
				}
			setCKFocus('nofocus'); // run focus function											
			}
		}
		// end radio validation
		
		// validate email
		if (type == 'email') {
			var bademail = false
	
			if (!field.value) { 
				bademail = true; 
				} else {
			
				var emailStr = field.value;
				var emailPat=/^(.+)@(.+)$/;
				var specialChars="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]";
				var validChars="\[^\\s" + specialChars + "\]";
				var quotedUser="(\"[^\"]*\")";
				var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/;
				var atom=validChars + '+';
				var word="(" + atom + "|" + quotedUser + ")";
				var userPat=new RegExp("^" + word + "(\\." + word + ")*$");
				var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$");
				var matchArray=emailStr.match(emailPat);
				
				if (matchArray==null) { 
					bademail = true; 
				} else {
				
						var user=matchArray[1];
						var domain=matchArray[2];
						
						if (user.match(userPat)==null)  { bademail = true; }
						
						var IPArray=domain.match(ipDomainPat);
						if (IPArray!=null) {
						    // this is an IP address
							  for (var i=1;i<=4;i++) {
							    if (IPArray[i]>255) {
									 bademail = true;
							    }
						    }
						}
				
				
						var domainArray=domain.match(domainPat);
						if (domainArray==null)  { bademail = true; }
						
						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) {
							bademail = true;
						}
						
						if (len<2) {
							bademail = true;
						}
				}	
			}
				
			if(bademail) {
				if (err_msg == "") {
					final_msg = final_msg + err_email + "\n";
					} else {
						final_msg = final_msg + err_msg + "\n";
				}
			setCKFocus(field); // run focus function											
			}
		}
		//end email validation

		// validate email
		if (type == 'email_null') {
			var bademail = false
	
			if (!field.value) { 
				bademail = false; 
				} else {
			
				var emailStr = field.value;
				var emailPat=/^(.+)@(.+)$/;
				var specialChars="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]";
				var validChars="\[^\\s" + specialChars + "\]";
				var quotedUser="(\"[^\"]*\")";
				var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/;
				var atom=validChars + '+';
				var word="(" + atom + "|" + quotedUser + ")";
				var userPat=new RegExp("^" + word + "(\\." + word + ")*$");
				var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$");
				var matchArray=emailStr.match(emailPat);
				
				if (matchArray==null) { 
					bademail = true; 
				} else {
				
						var user=matchArray[1];
						var domain=matchArray[2];
						
						if (user.match(userPat)==null)  { bademail = true; }
						
						var IPArray=domain.match(ipDomainPat);
						if (IPArray!=null) {
						    // this is an IP address
							  for (var i=1;i<=4;i++) {
							    if (IPArray[i]>255) {
									 bademail = true;
							    }
						    }
						}
				
				
						var domainArray=domain.match(domainPat);
						if (domainArray==null)  { bademail = true; }
						
						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) {
							bademail = true;
						}
						
						if (len<2) {
							bademail = true;
						}
				}	
			}
				
			if(bademail) {
				if (err_msg == "") {
					final_msg = final_msg + err_email + "\n";
					} else {
						final_msg = final_msg + err_msg + "\n";
				}
			setCKFocus(field); // run focus function											
			}
		}
		//end email validation
				
		//validate number
		if(type == 'numeric') {
			if(	!isNumeric(field.value)	||
				(isNumeric(field.value) && 
				 (parseInt(field.value) < n_beg || parseInt(field.value) > n_end)))
			{
				if (err_msg == "") {
						final_msg = final_msg + err_numeric + "\n";
					} else {
						final_msg = final_msg + err_msg + "\n";
				}
			setCKFocus(field); // run focus function	
			}
		}
		//end validate number

		//validate zipcode
		if(type == 'zipcode') {
			if(!(isNumeric(field.value)	&& trim(field.value).length == 5))
			{
				if (err_msg == "") {
						final_msg = final_msg + err_zipcode + "\n";
					} else {
						final_msg = final_msg + err_msg + "\n";
				}
			setCKFocus(field); // run focus function	
			}
		}
		//end validate zipcode

		//validate file
		if(type == 'file') {
			var b_error = false;

			if(!field.value)
				b_error = true;
			else
			{
				if(f_extensions.length)
				{
					b_error = true;

					for(var k = 0; k < f_extensions.length; k++)
						if(filterFileType(field.value, f_extensions[k]))
						{
							b_error = false;
							break;
						}
				}

				if(f_size != -1)
				{
					if(getFileSize(field.value) > f_size)
						b_error = true;
				}
			}

			if(b_error)
			{
				if (err_msg == "") {
					final_msg = final_msg + err_text + "\n";
				} else {
					final_msg = final_msg + err_msg + "\n";
				}	

				setCKFocus(field); // run focus function
			}
		}
		//end validate file

		// add new	
		// end new

	}

	// stop the submission if there are errors and notify the user
	if (final_msg != "") {
		alert(intro + final_msg + ending); // give the user the error
		if(focusfield != "false") {
			var focus_on = eval("document." + formname + "." + focusfield); // define scope
			focus_on.focus(); // focus on first field that needs to be fixed
		 }

		focusfield = ''; // clear out the focus field for next run
		return false; 

	}
	

	
	// check and see if we are testing, if so, then stop the form from submitting
	if(testing) { return false; }
		
	
}

function setCKFocus(field) {
	if(focusfield == '') {
		if (field == 'nofocus') {
			focusfield = "false";
		} else {
			focusfield = field.name;
		} 
	}	
}

		function Val(sString){
			bFlag = true;
			sResult = "";
			for (i=0; i<=sString.length-1; i++){
				if (bFlag){
					sTemp = sString.substring(i,i+1);
					if (sTemp >= "0" && sTemp <= "9"){
						sResult = sResult + sTemp;
					}
					else {
						bFlag = false;
					}
				}
			}
			return sResult*1
		}

function isNumeric(sString)
{
	bFlag = false;
	var iTmp;

	sString = trim(sString);

	for (i=0; i<=sString.length-1; i++) {
		iTmp = parseInt(sString.substring(i,i+1));
		if(!(iTmp >= 0 && iTmp <= 9)) {
			break;
		}

		if(i == sString.length - 1)
			bFlag = true;
	}
	return bFlag;
}

function trim(sThisValue) {
		sThis = rtrim(sThisValue)
		sThis = ltrim(sThis)
      return sThis
}

function ltrim(sThisL) {
      return sThisL.replace(/^\s*/,'')
}
function rtrim(sThisR) {
      return sThisR.replace(/\s*$/,'')
}

function filterFileType(file, ext)
{
	if(file.toLowerCase().indexOf('.' + ext) == -1)
	{
		return false;
	}

	return true;
}

function getFileSize(file)
{
	var oas = new ActiveXObject("Scripting.FileSystemObject");

	var e = oas.getFile(file);

	var f = e.size;

	return f;
}

