/* variables used in the validation functions to set the fields to their proper classes */
var goodClass = "basicText";
var fixClass = "fixField";
var goodoldClass = "boldText";
var fixoldClass = "fixoldField";

var defaultForm = "editForm";
/* validateForm is the function that validates the form and either submits it, or returns a list of 
items to be fixed before re-trying the submit*/
	function validateForm(formName_IN)
	{
		var errMessage = "The form was not properly completed:" //error message to be built with any new errors
		var errCount = 0;										//count of errors found
		var strResult = '';										//result string from the validation check on each field
		var strFieldName;										//the field name that is composed of the record ID/field Name
		var recNum = '';
		
		// list of fields that are contained in the form 
		var strFields = document.getElementById(formName_IN).fieldList.value;
		var arrFields = strFields.split(",");

		// list of the records that are being displayed on the current form 
		// Note: if this is a single record input form, then editKeys should exist but just be blank 
		var strRecords = document.getElementById(formName_IN).editKeys.value;
		var arrRecords = strRecords.split(",");
		//cycle through all of the fields in the form and validate them 
		for (var x=0; x<arrRecords.length; x++)
		{
			recNum = arrRecords[x];
			if(recNum == "*")
				recNum = "";
			//flags are used to see if the record has been edited at all 
			//if the flag is on (1), then check its fields, otherwise it hasn't changed so there's no reason to check it
			if(document.getElementById('Flag'+recNum).value == "1")
				for (var i = 0; i<arrFields.length; i++) 
				{
					strFieldName = arrFields[i] + recNum;
					strResult = validateField(formName_IN,strFieldName);
					if(strResult != "")
					{
						swapStyles(strFieldName,true);
						errCount += 1;
						errMessage += " \n " + errCount + ". " + strResult;
					}else
						swapStyles(strFieldName,false);
				}
		}
		//if there were any errors, throw the user an error messege, else, submit the form
		if(errCount > 0)

			alert(errMessage)
		else
			document.getElementById(formName_IN).submit();
	}
	
	function checkForm(formName_IN)
	{
		var errMessage = "The form was not properly completed:" //error message to be built with any new errors
		var errCount = 0;										//count of errors found
		var strResult = '';										//result string from the validation check on each field
		var strFieldName;										//the field name that is composed of the record ID/field Name
		var recNum = '';
		
		// list of fields that are contained in the form 
		var strFields = document.getElementById(formName_IN).fieldList.value;
		var arrFields = strFields.split(",");

		// list of the records that are being displayed on the current form 
		// Note: if this is a single record input form, then editKeys should exist but just be blank 
		var strRecords = document.getElementById(formName_IN).editKeys.value;
		var arrRecords = strRecords.split(",");
		//cycle through all of the fields in the form and validate them 
		for (var x=0; x<arrRecords.length; x++)
		{
			recNum = arrRecords[x];
			if(recNum == "*")
				recNum = "";
			//flags are used to see if the record has been edited at all 
			//if the flag is on (1), then check its fields, otherwise it hasn't changed so there's no reason to check it
			if(document.getElementById('Flag'+recNum).value == "1")
				for (var i = 0; i<arrFields.length; i++) 
				{
					strFieldName = arrFields[i] + recNum;
					strResult = validateField(formName_IN,strFieldName);
					if(strResult != "")
					{
						swapStyles(strFieldName,true);
						errCount += 1;
						errMessage += " \n " + errCount + ". " + strResult;
					}else
						swapStyles(strFieldName,false);
				}
		}
		//if there were any errors, throw the user an error messege, else, submit the form
		if(errCount > 0)
			return(errMessage)
		else
			return('');
	}
	
	//checkField is a "mini-validation" that runs just after the user enters a value into the field
	function checkField()
	{
		var args = checkField.arguments;
		if(args.length == 1)
			var formName_IN = defaultForm;
		else
			var formName_IN = args[1];
		var fieldName_IN = args[0];
	
		//calls the validateField function on the field - this is the same function at the base of the form validation function
		var strResult = validateField(formName_IN,fieldName_IN);

		//validateField will return an error string if there was one
		//if there was an error, change the classes to highlight the proper fields, and give the user the error message 
		//else, set all the classes back to the original classes
		if(strResult != "")
		{
			swapStyles(fieldName_IN,true);
			alert(strResult);					
		}else
			swapStyles(fieldName_IN,false);
		//after the field has been changed, the flag for that record needs to be set
		var idNumber ="Flag" +  textTrim(getIDNumber(fieldName_IN));
		if(document.getElementById(idNumber))
			document.getElementById(idNumber).value = 1;
			
	}
	
	//the true guts of the validation - this function verifies each field's value with the proper criteria that is found 
	//   in the field's 'validity' attribute 
	function validateField(formName_IN,fieldName_IN)
	{
		// grab the necessary information needed to validate the field - validity text, title and value 
		var arrField = eval("document." + formName_IN + "." + fieldName_IN + ".getAttribute('validity');")
		var fldDesc = eval("document." + formName_IN + "." + fieldName_IN + ".title;")
		var fldValue = eval("document." + formName_IN + "." + fieldName_IN + ".value;")

		//verify that the field has the necessary validity text to be verified against 
		if(arrField != "")
		{
			arrField = arrField.split("|")
			//arrField[0] is true or false for required or optional, everything after that is a validation sequence
			for(i=1;i<arrField.length;i++)
				switch(arrField[i])
				{
				//arrField[i] is going to contain the field type for the validation - numbers, date, string
				case "numbers":
					if(isNaN(fldValue))
						return fldDesc + " is not numeric.  Please supply a number value";
					else
					{
						fldValue = parseInt(fldValue);
						//arrField[i+1] is going to contain either a sub type for the validation or nothing 
						//nothing means that the field just has to be of the field type and nothing else in particular
						switch(arrField[i+1])
						{
							case "interval":
								//number interval - has two values X|Y;  used to make sure the field value is in between
								//X and Y; if Y is 0 then X acts as a lower bound
								var strEnd = arrField[i+3] += '';
								var strStart = arrField[i+2] += '';

								if(arrField[i+3] == 0)
								{
									if(fldValue < arrField[i+2])
										return fldDesc + " must be greater than " + arrField[i+2];
								}
								else
								{
									if(fldValue < arrField[i+2] || fldValue > arrField[i+3])
										return fldDesc + " must be between " + strStart + " and " + strEnd;
								}
								break;
							//automatically rounds a number down/up to become divisible by X
							case "divisible":
								if(fldValue % arrField[i+2] > 0)
								{
									if((fldValue % arrField[i+2]) > arrField[i+2]/2)
									{
										eval("document." + formName_IN + "." + fieldName_IN + ".value = parseInt(fldValue) + parseInt(arrField[i+2] - (fldValue % arrField[i+2]));")
									}else{
										eval("document." + formName_IN + "." + fieldName_IN + ".value = parseInt(fldValue) - parseInt(fldValue % arrField[i+2]);")
									}
								}
								break;
							case "length":
								if(document.getElementById(fieldName_IN).value.length < arrField[i+2])
									return fldDesc + " must be at least " + arrField[i+2] + " digits long"
								break;
							default:
								break;
								
						}
					}
					break;
				case "dates":
					var dteResult = isDate(fldValue,fieldName_IN);
					if(dteResult != "")
						if(arrField[0] == "true")
							return dteResult;
						else
							if(fldValue != "")
								return dteResult;
					else
						switch(arrField[i+1])
						{
							//same as numbers|interval, except with dates
							//if X is 0 then dates must be prior to Y, if Y is 0 then dates must be after X
							case "interval":
								var dteValue = createDate(fldValue);
								if(arrField[i+2] != "0"){
									if(arrField[i+3] != "0")
										var intervalA = createDate(arrField[i+2]);
										var intervalB = createDate(arrField[i+3]);
								
										if(dteValue < intervalA || dteValue > intervalB)
											return fldDesc + " must be between " + arrField[i+2] + " and " + arrField[i+3];
									else
										var intervalA = createDate(arrField[i+2]);
										
										if(dteValue < intervalA)
											return fldDesc + " must be on or past " + arrField[i+2]
								}else{
									var intervalB = createDate(arrField[i+3]);
										
									if(dteValue > intervalB)
										return fldDesc + " must be on or before " + arrField[i+3]
								}	
								break;
							default:
								break;
						}
					break;
				case "string":
					alert('here');
					if(fldValue != "")
					{
						switch(arrField[i+1])
						{
							//maxlength attributes can control the maximum length of a string, this validation can control the minimum
							case "length":
								if(fldValue.length < parseInt(arrField[i+2]))
									return fldDesc + " must be at least " + arrField[i+2] + " characters long";
								break;
								
							case "maxlength":
								alert('here');
								if(fldValue.length > parseInt(arrField[i+2]))
									return fldDesc + " must be no larger than " + arrField[i+2] + " characters long";
								break;
							//justtext requires that there be no numbers or punctuation in the value of the text box, just letters
							case "justtext":
								if(getNonText(fldValue).length > 0)
									return fldDesc + " cannot contain anything but letters";
								break;
							//justgrammar will not allow any numbers to be entered into a field, just letters and punctuation
							case "justgrammar":
								if(getNumbers(fldValue).length > 0)
									return fldDesc + " cannot contain any numbers";
								break;
							//alphanumeric will not allow any punctuation to be entered into a field, just letters and numbers
							case "alphanumeric":
								if(getPunctuation(fldValue).length >0)
									return fldDesc + " cannot contain any punctuation";
								break;
							case "phone":
								if(formatPhone(fldValue).length > 0)
									 eval("document." + formName_IN + "." + fieldName_IN + ".value = '" + formatPhone(fldValue) + "';")
								else
									return fldDesc + " must be a valid phone number";
								break;
							case "zipcode":
								return formatZip(fieldName_IN);
								break;
							case "ssn":
								if(dashSSN(fldValue)=="")
									return fldDesc + " must be a valid Social Security Number";
								else
									eval("document." + formName_IN + "." + fieldName_IN + ".value = '" + dashSSN(fldValue)+ "';")
						}
					}else if(arrField[0] == "true")
						return fldDesc + " cannot be empty";
					else
						return "";
			}
		}
		//if the validation has cleared up to here, then it needs to check if the value is required or not
		//if it is, then it will not be able to be blank
		if(arrField[0] == "true")
		{
			if(textTrim(document.getElementById(fieldName_IN).value) == "" || textTrim(document.getElementById(fieldName_IN).value) == "*") 
				return fldDesc + " cannot be empty ";
			else
				return "";
		}else
			return "";
	}

// retrieves the current record's ID # from the front of the field name
	function getIDNumber(strInput)
	{
		var strResult = '';
		var blnFound = false;

		for (var i=strInput.length-1;i>=0; i--)
		{
			if(!isNaN(strInput.charAt(i)))
				strResult = strInput.charAt(i) + '' + strResult;
			else
				return strResult;
		}
	}
	
	function swapStyles(fieldName_IN,blnFix)
	{
		// variables used in the validation functions to set the fields to their proper classes
		var goodClass = "field";
		var fixClass = "fixField";
		var goodoldClass = "oldfield";
		var fixoldClass = "fixoldField";
		
		switch (document.getElementById(fieldName_IN).className)
		{
			case fixClass:
			case goodClass:
				if(blnFix)
					document.getElementById(fieldName_IN).className = fixClass;
				else
					document.getElementById(fieldName_IN).className = goodClass;
				break
			case fixoldClass:
			case goodoldClass:
				if(blnFix)
					document.getElementById(fieldName_IN).className = fixoldClass;
				else
					document.getElementById(fieldName_IN).className = goodoldClass;
				break
			default:
				break
		}
	}
