//	Name:		validation.js
//	Author: 	Nate Blanchard
//	Date:		06/09/03
//	Description: 	This javascript is used to validate form data

	var	familyArray = null;
	var fieldid = ""; 			// default when no id is available
	var valmsg = "";				// error message variable when exception found
	// ***********************************************************************
	// NOTE: Will need to add to this list of keys as new validators are added
	// ***********************************************************************
	// These strings need to get added to the form element 'id' attribute
	// example: <input name=" ViewKey.KEY_NAME " id="Freindly Name_req" type="text" size="15" value="">
	var required = "_req"		// to make a any form element required
	var number = "_num"			// to validate a form element of types text, textarea, password with the isNumber() function
	var notNumber = "_!num"		// to validate a form element of types text, textarea, password with the isNotNumber() function
	var decimal = "_dec"		// to validate a form element of types text, textarea, password with the isDecimal() function
	var notDecimal = "_!dec"	// to validate a form element of types text, textarea, password with the isNotDecimal() function
	var email = "_email"		// to validate a form element of types text, textarea, or password with the validateEmailAddress() function
	var maxval = "_max-"		// to validate a form element of types text, textarea, or password with the maxValue() function
	var maxend = "-max"			// to end the value for maxValue() function
	var minval = "_min-"		// to validate a form element of types text, textarea, or password with the minValue() function
	var minend = "-min"			// to end the value for minValue() function
	var mixed = "_mix"			// to set the field text to mixed case

	
function checkForm(form) {

	// intended to deny the double entry from a double click
//	try {
//		this.submitButton.disabled = "true"
//	} catch (e) {
		// this exception will be caught when the customPreValidation function is not overloaded
//	} // ends try	
		
	// NOTE: In the future we should create ways to validate dates, text field families, no zero
	var mnv;					// variable to hold the actual min value of a field				
	var mxv;					// variable to hold the actual max value of a field				
	var selectDefault = "NONE";	// to set the default select option default (selectDefault)
	var family; 				// global family group place holder if needed
	
	/** To implement specific pre validation scripts for any page just create a function 
		 called "customPreValidation(form)" on the page that requires the validation 
		 and implement your specific validating code */
	try {
		if (!customPreValidation(form)) {
			// make sure all usages of customPreValidation return either true or false
			// alert messages must be in the overloaded customPreValidation function specific to task validated
			return false;
		} // ends if
	} catch (e) {
		// this exception will be caught when the customPreValidation function is not overloaded
	} // ends try	
	
	// loop through all the form elements
	for (var i=0; i < form.length; i++) {
		var field = form.elements[i];
		field.value = field.value.replace(/'/g, "");
		field.value = field.value.replace(/;/g, "");
		field.value = field.value.replace(/:/g, "");		
		// ***************************************************************
		// NOTE: Will need to add to this list as new validators are added
		// ***************************************************************
		// Only checks fields that are not disabled
		if (field.disabled == false) {
		// strip out all bad characters

			// check if the id has an entry in the id
			if (field.id != null && field.id != "") {
				// check if the id has the "required" key in the id
				if (field.id.indexOf(required, 0)!=-1) {
					// find out what type of element it is
					if (field.type == "text" || field.type == "textarea" || field.type == "password" || field.type == "file" ) {
						// validate each type for empty of null
						if (isEmpty(field.value)) {
							parseFieldIDKeys(field);
							valmsg = "No '" + fieldid + "' has been entered.\r\nPlease submit a valid " + field.type + " entry.";
							return exception(form,field,valmsg);
						} // ends if
					} // ends if
					if (field.type == "select-one") {
						// validate each type for a selection ohter than the default - "NONE"
						if (field.options[field.selectedIndex].value == selectDefault) {
							parseFieldIDKeys(field);
							valmsg = "No option for '" + fieldid + "' has been selected.\r\nPlease select one of the options.";
							return exception(form,field,valmsg);
						} // ends if
					} // ends if
					if (field.type == "select-multiple") {
						// loop through all options in the select list
						var selection = false;
						for (var j=0; j < field.length; j++) {
							// validate each type for a selection ohter than the default - "NONE"
							if (field.options[j].value == selectDefault) {
								field.options[j].selected = false;
							} else if (field.options[j].value != selectDefault && field.options[j].selected) {
								selection = true;
							} // ends if
						} // ends for
						if (!selection) {
							parseFieldIDKeys(field);
							valmsg = "No options for '" + fieldid + "' has been selected.\r\nPlease select at least one of the options.\r\nYou may select multiple options.";
							return exception(form,field,valmsg);
						}
					} // ends if
					if (field.type == "checkbox" || field.type == "radio") {
						// establishes the first time it recognizes a new family
						if (familyArray != null) {
							var needToAddAFamily = true;
							// loop through all family array names
							for (var j=0; j < familyArray.length; j++) {
								// check to see if this family button is the same as one of the many possible stored ones
								if ( familyArray[j] != null && familyArray[j].name != null && familyArray[j].name == field.name) {
									needToAddAFamily = false;
									break;
								} // ends if
							} // ends for
							if (needToAddAFamily) {
								family = new Family(field.name, field.type);
								addFamily(family);
							} // ends if
						} else {
							familyArray = new Array;
							family = new Family(field.name, field.type);
							addFamily(family);
						} // ends if
						
						// is current family checked, otherwise no need to compare
						if (field.checked) {
							// loop through all family buttons with the same name
							for (var j=i; j < form.length; j++) {
								for (var k=0; k < familyArray.length; k++) {
									// check to see if the comparable element is a family element
									if (form.elements[j].type != field.type) {
										break; // check next form element
									} // ends if
									// check to see if this family element is in the same family 
									// and that the family checked status is still invalid
									if (!familyArray[k].checked && form.elements[j].name == field.name && familyArray[k].name == field.name) {
										// update the right family element in the array
										familyArray[k].checked = true;
									} // ends if
								} // ends for k
							} // ends for j
						} // ends if
					} // ends if
				} // ends if
				
				// ***************************************************************
				// NOTE: Will need to add to this list as new validators are added
				// ***************************************************************
				// only checks form element of type 'text, 'textarea' or 'password'
				if (field.type == "text" || field.type == "textarea" || field.type == "password") {
					// check if the id has the "isNumber" key in the id
					if (field.id.indexOf(number, 0)!=-1) {
						if (! isPositiveNumber(form, field)) {
							return false;
						} // ends if
					} // ends if
					// check if the id has the "notNumber" key in the id
					if (field.id.indexOf(notNumber, 0)!=-1) {
						if (! isNotPositiveNumber(form, field)) {
							return false;
						} // ends if
					} // ends if
					// check if the id has the "email" key in the id
					if (field.id.indexOf(email, 0)!=-1) {
							if (! validateEmailAddress(form, field)) {
								return false;
							} // ends if						
					} // ends if
					// check if the id has the "isDecimal" key in the id
					if (field.id.indexOf(decimal, 0)!=-1) {
						if (! isDecimal(form, field)) {
							return false;
						} // ends if
					} // ends if
					// check if the id has the "notDecimal" key in the id
					if (field.id.indexOf(notDecimal, 0)!=-1) {
						if (! isNotDecimal(form, field)) {
							return false;
						} // ends if
					} // ends if
					if (field.id.indexOf(minval, 0)!=-1) {
						mnv = extractValue(field.id, minval, minend)
						if (! minValue(form, field, mnv)) {
							return false;
						} // ends if
					} // ends if
					if (field.id.indexOf(maxval, 0)!=-1) {
						mxv = extractValue(field.id, maxval, maxend);
						if (! maxValue(form, field, mxv)) {
							return false;
						} // ends if
					} // ends if
					if (field.id.indexOf(mixed, 0)!=-1) {
						toMixedCase(field);
					} // ends if
				} // ends if
			} // ends if
			// changes field value to uppercase prior to submit, except login, as that process is case senstitive.
			//if ((field.type == "text" || field.type == "textarea") && field.name != "j_username") {
			//	toMixedCase(field)
			//} // ends if
		} // ends if
	} // ends for
		
	// send family alerts
	// loop through all family array names
	if (familyArray != null && familyArray.length > 0) {
		for (var i=0; i < familyArray.length; i++) {
			if (!familyArray[i].checked) {
				valmsg = "No " + familyArray[i].type + " for '" + familyArray[i].name + "' has been selected.\r\nPlease select at least one of the available options.";
				return exception(form,field,valmsg);
			} // ends if
		} // ends for
	} // ends if
	
	/** To implement specific validation for any page just create a function 
		 called "customPostValidation(form)" on the page that requires the validation 
		 and implement your specific validating code */
	try {
		if (!customPostValidation(form)) {
			// make sure all usages of customValidation return either true or false
			// alert messages must be in the overloaded customValidation function specific to task validated
			return false;
		} // ends if
	} catch (e) {
		// alert("caught exception: " + e);
	} // ends try	
	// next two lines are for testing only
	// alert("Submit successful!");
	// return false;
} // ends function checkForm()

function Family(name, type) {
	this.name = name;
	this.type = type;
	this.checked = false;
} // ends function newFamily()

function addFamily(family) {
	familyArray[familyArray.length] = family;
} // ends function addFamily()

function myReset() {
	if (familyArray != null) {
		familyArray.length = 0;
	} // ends if
} // ends function addFamily()

// ***************************************
// 			validator functions
// ***************************************

function isEmpty(strIn) {
	// to see if an input is empty
	if (strIn == null || strIn == "") {
		return true;
	} // ends if
	return false;
} // ends function isEmpty()

function isNotEmpty(strIn) {
	// to see if an input is not empty
	if (strIn != null && strIn != "") {
		return true;
	} // ends if
	return false;
} // ends function isNotEmpty()

function isPositiveNumber(form, field) {
	// to see if a numeric input is a positive integer
	var inputStr = field.value.toString();
	for (var i=0; i < inputStr.length; i++) {
		var oneChar = inputStr.charAt(i);
		if (oneChar < "0" || oneChar > "9") {
			parseFieldIDKeys(field);
			valmsg = "The value '" + field.value + "' is not a valid entry for '" + fieldid + "'.\r\nYou must enter a positive, numeric value.\r\nYou may not enter any letters or punctuaction characters.";
			return exception(form,field,valmsg);			
		} // ends if
	} // ends for
	return true;
} // ends function isPositiveNumber()

function isNotPositiveNumber(form, field) {
	// to see if a numeric input is not a positive integer
	var inputStr = field.value.toString();
	for (var i=0; i < inputStr.length; i++) {
		var oneChar = inputStr.charAt(i);
		if (!(oneChar < "0" || oneChar > "9")) {
			parseFieldIDKeys(field);
			valmsg = "The value '" + field.value + "' is not a valid entry for '" + fieldid + "'.\r\nYou cannot enter a numeric value.";
			return exception(form,field,valmsg);
		} // ends if
	} // ends for
	return true;
} // ends function isNotPositiveNumber()

function validateEmailAddress(form, field){
	//This checks to see if a email address has an "@" symbol and if its followed by a period and at least on char.
	if (field.value.indexOf('@',0)==-1 || field.value.indexOf('@',0)== 0 || field.value.indexOf('.',0)==-1) {
		parseFieldIDKeys(field);
		valmsg = "The value '" + field.value + "' is not a valid entry for '" + fieldid + "'.\r\nPlease enter a valid email address.";
		return exception(form,field,valmsg);	
    } // ends if
	return true;
} // ends function validateEmailAddress()

function isDecimal(form, field) {
	// to see if a numeric input is a decimal
	var dec = false;
	var inputStr = field.value.toString();
	for (var i=0; i < inputStr.length; i++) {
		var oneChar = inputStr.charAt(i);
		if (oneChar == ".") {
			dec = true;
		} // ends if
		if (oneChar != "." && (oneChar < "0" || oneChar > "9") ) {
			parseFieldIDKeys(field);
			valmsg = "The value '" + field.value + "' is not a valid entry for '" + fieldid + "'.\r\nYou must enter a decimal value.\r\nYou may not enter any letters or punctuaction characters other than the decimal point.";
			return exception(form,field,valmsg);
		} // ends if
	} // ends for
	if (!dec) {
		parseFieldIDKeys(field);
		valmsg = "The value '" + field.value + "' is not a valid entry for '" + fieldid + "'.\r\nYou must enter a decimal value.";
		return exception(form,field,valmsg);		
	} // ends if
	return true;
} // ends function isDecimal()

function isNotDecimal(form, field) {
	// to see if a numeric input is not a decimal
	var inputStr = field.value.toString();
	for (var i=0; i < inputStr.length; i++) {
		var oneChar = inputStr.charAt(i);
		if (oneChar != "." && (oneChar < "0" || oneChar > "9") ) {
			parseFieldIDKeys(field);
			valmsg = "The value '" + field.value + "' is not a valid entry for '" + fieldid + "'.\r\nYou cannot enter a decimal value.\r\nYou may not enter any letters or punctuaction characters.";
			return exception(form,field,valmsg);
		} else if (oneChar == ".") {
			parseFieldIDKeys(field);
			valmsg = "The value '" + field.value + "' is not a valid entry for '" + fieldid + "'.\r\nYou cannot enter a decimal value.";
			return exception(form,field,valmsg);
		} // ends if
	} // ends for
	return true;
} // ends function isNotDecimal()

function passMinCharCheck(form, field, m) {
	if (field.value.length < m) {
		parseFieldIDKeys(field);
		valmsg = "Invalid search criteria has been entered.\r\nSearch must have at least " + m + " characters.";
		return exception(form,field,valmsg);		
	} // ends if
	return true;
} // ends function passMinCharCheck()

function minValue(form, field, minval) {
	if (parseInt(field.value) < parseInt(minval)) {
		parseFieldIDKeys(field);
		valmsg = "The value '" + field.value + "' is not a valid entry for '" + fieldid + "'.\r\nThe minimum allowed value is '" + minval + "'.";
		return exception(form,field,valmsg);		
	} // ends if
	return true;
} // ends function minValue()

function maxValue(form, field, maxval) {
	if (parseInt(field.value) > parseInt(maxval)) {
		parseFieldIDKeys(field);
		valmsg = "The value '" + field.value + "' is not a valid entry for '" + fieldid + "'.\r\nThe maximum allowed value is '" + maxval + "'.";
		return exception(form,field,valmsg);		
	} // ends if
	return true;
} // ends function maxValue()

function passMaxCharCheck(form, field, m) {
	if (field.value.length > m) {
		parseFieldIDKeys(field);
		valmsg = "Invalid search criteria has been entered.\r\nSearch cannot exceed " + m + " characters.";
		return exception(form,field,valmsg);		
	} // ends if
	return true;
} // ends function passMaxCharCheck()

 //This function confirms if a user wants to delete some record 
function confirmDelete(inStr){
	if (! confirm("Are you sure the you want to delete this " + inStr + "?")) {
		return false;
	} // ends if
} // ends function confirmDelete()

 //This function changes all filed values to uppercase 
function toUpper(field){
	field.value = field.value.toUpperCase();
} // ends function toUpper()

 //This function changes all filed values to uppercase 
function toMixedCase(field){
	var inputStr = field.value.toString();
	var newString = "";
	for (var i=0; i < inputStr.length; i++) {
		var oneChar = inputStr.charAt(i);
		if (i == 0 || inputStr.charAt(i-1) == " ") {
			newString = newString + oneChar.toUpperCase();
		} else {
			newString = newString + oneChar.toLowerCase();
		} // ends if
	} // ends for
	field.value = newString
	return true;
} // ends function toUpper()

//This parses the min or max values from the field id
function extractValue(val, start, end){
	val = val.toString();
	start = val.indexOf(start, 0)+start.length;
	end = val.indexOf(end, 0);
	var out = val.substring(start,end);
	return out;
}//ends function parseValue()

//function used to check if the selected month and year are valid(not greater than the current month and yr)
function checkYrMonth(form, month, yr) {
	todayDate=new Date();
	var mm=todayDate.getMonth();
	var yy = todayDate.getYear();	
		
	if(month.substring(0,1)=="0") {
		month=parseInt(month.substring(1));
	} else {
		month=parseInt(month);
	} // ends if
	
	if(yr.substring(0,1)=="0") {
		yr=parseInt(yr.substring(1));
	} else {
		yr=parseInt(yr);
	} // ends if
	
	yy=parseInt(yy);
	mm=parseInt(mm);
	mm=mm+1;	
		
	if(yr==yy && mm<month) {
		valmsg = "This is not valid selection.\r\nYou must select a date prior to today.";
		return exception(form,field,valmsg);			
	} // ends if
	// form.submit();
	return true;		
} // ends function

function exception(form, field, valmsg) {
	try { 
		customPreAlert(form);
	} catch (e) {
		// no customPreAlert() function overloaded
	} // ends try
	alert(valmsg);
	try { 
		if (field != null) {
			field.focus();
			field.select();
		}	

	} catch (e) {
		// no field was passed in
	} // ends try
		
	// intended to deny the double entry from a double click
//	try {
//		this.submitButton.disabled = "false"
//	} catch (e) {
//		// this exception will be caught when the customPreValidation function is not overloaded
//	} // ends try
	return false;
} // ends function exceptionHandler()

function parseFieldIDKeys(field) {
	// removes any form of the js keys from the id
	if (isNotEmpty(field.id)) {
		fieldid = field.id; // default to the id if available
		// remove the variable 'required' value from the human readable elements id
		if (field.id.indexOf(required, 0)!=-1) {
			fieldid = fieldid.replace(required, "");
		} // ends if
		// remove the variable 'isNumber' value from the human readable elements id
		if (field.id.indexOf(number, 0)!=-1) {
			fieldid = fieldid.replace(number, "");
		} // ends if
		// remove the variable 'notNumber' value from the human readable elements id
		if (field.id.indexOf(notNumber, 0)!=-1) {
			fieldid = fieldid.replace(notNumber, "");
		} // ends if
		// remove the variable 'email' value from the human readable elements id
		if (field.id.indexOf(email, 0)!=-1) {
			fieldid = fieldid.replace(email, "");
		} // ends if
		// remove the variable 'isDecimal' value from the human readable elements id
		if (field.id.indexOf(decimal, 0)!=-1) {
			fieldid = fieldid.replace(decimal, "");
		} // ends if
		// remove the variable 'notDecimal' value from the human readable elements id
		if (field.id.indexOf(notDecimal, 0)!=-1) {
			fieldid = fieldid.replace(notDecimal, "");
		} // ends if
		// remove the variable 'maxval' value from the human readable elements id
		if (field.id.indexOf(minval, 0)!=-1) {
			mnv = extractValue(field.id, minval, minend)
			fieldid = fieldid.replace(minval, "");
			fieldid = fieldid.replace(minend, "");
			fieldid = fieldid.replace(mnv, "");
		} // ends if
		if (field.id.indexOf(maxval, 0)!=-1) {
			mxv = extractValue(field.id, maxval, maxend)
			fieldid = fieldid.replace(maxval, "");
			fieldid = fieldid.replace(maxend, "");
			fieldid = fieldid.replace(mxv, "");
		} // ends if
		// remove the variable 'minval' value from the human readable elements id
	} // ends if
} // ends function parseFiledIDKeys()
