/* Propery of Site Systems, Copyright 2001. All rights Reserved.
   Developers:  Rodolfo Suarez, Matthew Edwards

   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)
	  	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
	
	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 by Rodolfo Suarez and Matthew Edwards
	06/11/2001 - Added new function to focus on first field that needs fixing - Matthew Edwards
	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: Rodolfo Suarez
	09/25/2002 - Add longYear validation
*/

// set global params
var focusfield = '';

function checkForm(formname) {

	// create some default parameters for the error message if one is needed
	var final_msg = ""; 
	var intro = "There was a problem with your submission.          \n\n"; // create intro 
	var ending = "\nPlease make the appropriate changes and resubmit the form.     " // 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 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
			var err_msg = validate.substring(dash + 1, validate.length); // get custom error message if any
		}	

		
		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";
				}	
			setFocus(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";
				}				
			setFocus(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";
				}				
			setFocus(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";
				}				
			setFocus(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 > 2010) ){
				if (err_msg == "") {
						final_msg = final_msg + err_longYear + "\n";
					} else {
						final_msg = final_msg + err_msg + "\n";
				}				
			setFocus(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";
				}
			setFocus('nofocus'); // run focus function								
			}
		}
		// end dropdown validation
		
		// validate checkbox 
		if(type == 'checkbox'){
			var cempty = true;
			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";
				}
			setFocus('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";
				}
			setFocus('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";
				}
			setFocus(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";
				}
			setFocus(field); // run focus function											
			}
		}
		//end email validation
				
		// 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 setFocus(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 submitform(formname){
	var isOK = checkForm(formname);
	if(isOK != false){
		var f = eval("document." + formname);
		f.submit();
	} else {
		return false;
	}
}