PasswordCheckMessage = "Both passwords must match.\n"

// Vars below include placeholder text that will be replaced to make the alert specific to the field/error (ie "FieldDescription is required.\n" becomes "First Name is required.\n" )
RequiredFieldsMessage = "FieldDescription is required.\n"; // FieldDescription
NumericFieldsMessage = "FieldDescription should be numeric.\n"; // FieldDescription
MinFieldsMessage = "FieldDescription should be greater than MinValue.\n";  // FieldDescription, MinValue
MaxFieldsMessage = "FieldDescription should be greater than MaxValue.\n";  // FieldDescription,  MaxValue
DateFormatMessage = "FieldDescription should be DatePattern.\n"; // FieldDescription, DatePattern
PhoneFormatMessage = "FieldDescription should be PhonePattern.\n"; // FieldDescription, PhonePattern
EmailFormatMessage = "The FieldDescription you have entered is not a properly formatted email address.\n"; //  FieldDescription

// see ColourRequired() in NavFunctions.js for implementation of this
RequiredFieldsBackgroundColor = "D1DAFF";
RequiredFieldsTextColor = "000000";

ResetFieldsBackgroundColor = "ffffff";
ResetFieldsTextColor = "7E7E7E";

ShowMeErrors = true; // Triggers alerts when error trapping finds something, otherwise system skips broken item

ChangeRadioButtonColor = true;

AutoFillChecked = false;
FireFoxErrorFound = false;

// Not Used
// Code below overrides changes made by autofill toolbars - see FixAutoFillChange() for details
//if (window.attachEvent) {
//    window.attachEvent("onload",PrepForAutoFillChange);
//  }
  
  
function PrepForAutoFillChange(){ // Code below overrides changes made by autofill toolbars - see FixAutoFillChange() for details
    AllInputs = document.getElementsByTagName("INPUT");
    for(LoopCount=0;LoopCount<AllInputs.length;LoopCount++){
      AllInputs[LoopCount].attachEvent("onpropertychange",FixAutoFillChange);
      AllInputs[LoopCount].style.backgroundColor = "";
    }
    AllSelects = document.getElementsByTagName("SELECT");
    for(LoopCount=0;LoopCount<AllSelects.length;LoopCount++){
      AllSelects[LoopCount].attachEvent("onpropertychange",FixAutoFillChange);
      AllSelects[LoopCount].style.backgroundColor = "";
    }
	
 }

function FixAutoFillChange(){
// Tools that pre-fill frequently used fields (ie Google toolbar populating your email address, ...)
// replace our colour scheme with their own colours to mark these fields. We over-ride their changes
// with this function, so we can have required fields a colour of our choosing. 
// See PrepForAutoFillChange() which is launched earlier in this file, 
// and attaches this function to onpropertychange of all form fields. This is IE specific.

// AutoFillChecked is set to true after page load, so this function will only run through after
// any prefill tools have made their changes but NOT if we change colours after page load.
if (!AutoFillChecked) { 

  if (typeof(RequiredFields) != "undefined") { // Error trap if required fields not set properly
  	  
	  // Color hex values have been declared at top
  	  TargetbackgroundColor = ResetFieldsBackgroundColor; 
	  Targetcolor = ResetFieldsTextColor; 
	  
	  // RequiredFields is a comma seperated list declared on relevant pages
	  AutoFillCheckRequiredFields = RequiredFields.split(",");
	  
	  // We check to see if the field that had been changed is in the list of required fields
	  for(LoopCount2=0;LoopCount2<AutoFillCheckRequiredFields.length;LoopCount2++){

	  	ThisField = AutoFillCheckRequiredFields[LoopCount2]
		
	  	if (event.srcElement.name == ThisField) { 
		// If match, change the colour value to our required colour 
		// (Else it will remain the default targets which were set above)
			TargetbackgroundColor = RequiredFieldsBackgroundColor;
			Targetcolor = RequiredFieldsTextColor;
		}
	  }
	  
	  // Change the style attributes based on above
	  event.srcElement.style.backgroundColor = TargetbackgroundColor;
	  event.srcElement.style.color = Targetcolor;
	  
  } else {
  
  	// If the RequiredFields list is not available, we just set it to our default colour
  	event.srcElement.style.backgroundColor = ResetFieldsBackgroundColor;
	event.srcElement.style.color = ResetFieldsTextColor;
  }	 

 }
 
}

  

function PasswordCheck(MatchThis,MatchThat) { // Simple this v that
			if (MatchThis != MatchThat) {
				return PasswordCheckMessage;
			} else {
				return "";
			}
		}
		
function Required(TargetFields) { // Checks for required fields of any type (ie text, radio, ...)
	
	Result = "";
	ReqCheck = "";	
	ReqCheckStart = "";
	
	// RequiredFields is a comma seperated list declared on relevant pages
	TargetFields = TargetFields.split(","); 
	
	// We loop through all the required fields
	for (LoopCount=0;LoopCount<TargetFields.length;LoopCount++){
	
		// assume for now no radio, select have been found
		RadioFound = false;
		SelectFound = false;
		
		ThisField = TargetFields[LoopCount];
				
		// Trap errors caused by including fields in RequiredFelds variable that don't exist
		if (typeof(document.getElementById(ThisField)) == "undefined" || FireFoxErrorFound) {
			if (ShowMeErrors) {
				alert("ERROR - The field listed in the RequiredFields list as " + ThisField + " does not exist. Please remove or adjust accordingly.") 
			}
		} else {
		
		ThisLength = document.getElementById(ThisField).length
		
		if (ThisLength > 0) { // If the field is a radio, checkbox, select list, ...
		
			// Assume nothing found yet
			ThisFieldCheck = ""; // This will be populated IF a value is found, otherwise it remains blank
			EmptySelectCheck = "";
		
			// Loop through items in field (ie radio, checkbox, select options)
			for (LoopCount2=0;LoopCount2<ThisLength;LoopCount2++){	
				
				// Some fields refer to type at different levels
				if (typeof(document.getElementById(ThisField).type) != "undefined") {
					ThisType = document.getElementById(ThisField).type;
				} else {
					ThisType = document.getElementById(ThisField)[LoopCount2].type;
				}
				
				//alert(ThisType);
				if (ThisType == "radio") { // Radio
				
					RadioFound = true; // Yay!! We found a radio box !!
					ThisSelect = document.getElementById(ThisField)[LoopCount2].checked; //
					
				} else if (ThisType == "select-one" || ThisType == "select-multiple") { // Select - drop down or list

					SelectFound = true; // Yay!! We found a select list !!
					
					// We build this variable as we go, and then after we check if we
					// have forgotten to give the select field a value
					EmptySelectCheck = EmptySelectCheck + document.getElementById(ThisField)[LoopCount2].value;

					if (document.getElementById(ThisField).value == "") {
						ThisSelect = false; // Not selected
					} else {
						ThisSelect = true; // Yay!! Item selected
					}				
				} else { // Check box
					ThisSelect = document.getElementById(ThisField).selected 
				}
				
				if (ThisSelect) { // did we find anything?
					ThisFieldCheck = "selected";
				}
			}
			
			// Error trap
			if (SelectFound && ShowMeErrors && EmptySelectCheck == "") {
				alert("ERROR - The select box/drop down in the RequiredFields list as " + ThisField + " does not have values attached. (ie <option value=...)") 
			}
			
		} else { // else if the field is a text field (with 0 length)
			ThisFieldCheck = document.getElementById(ThisField).value
		}
		
		if (RadioFound) { // the alt tag is referred to differently for radio
			ThisDesc = document.getElementById(ThisField)[0].alt;
		} else {
			ThisDesc = document.getElementById(ThisField).alt;
		}
		
		
		if (typeof(ThisDesc) == "undefined" || ThisDesc == "") { // If the alt has no value
			if (ShowMeErrors && !SelectFound) {
				alert("ERROR - The field listed in the RequiredFields list as " + ThisField + " has no alt value. Please add a field description as an alt value for this field (ie <input alt='User First Name' ...).")
			}
			ThisDesc = ThisField // Just use the field name if we can't find an alt tag
		}
	
		if (ThisFieldCheck == "" || ThisFieldCheck == " ") {
			// If, after all the checks above, ThisFieldCheck hasn't been populated ...
			Result = Result + RequiredFieldsMessage.replace("FieldDescription",ThisDesc);
		}
		
				
		//alert(ThisField + " - ends")
		
		}
	}
	
	return Result;
}

function PhoneFormatCheck(TargetFields,Pattern) {
	
	Result = "";
	TargetFields = TargetFields.split(",");
	for (LoopCount=0;LoopCount<TargetFields.length;LoopCount++){
	
		PhoneFormatFail = false;
		
		ThisTargetFieldValue = document.getElementById(ThisField).value;
		ThisTargetFieldDesc =document.getElementById(ThisField).alt;	
	
		if (ThisTargetFieldValue != "") {
		
			switch(Pattern) { // We're using a switch so we can add if needed
				case '(###) ###-####':
				
					// Strip and rebuild without common formatting
					ThisTargetFieldValue = searchAndReplace(ThisTargetFieldValue,"(","");
					ThisTargetFieldValue = searchAndReplace(ThisTargetFieldValue,")","");
					ThisTargetFieldValue = searchAndReplace(ThisTargetFieldValue," ","");
					ThisTargetFieldValue = searchAndReplace(ThisTargetFieldValue,"-","");
					
					if (ThisTargetFieldValue.length != 10) {
						PhoneFormatFail = true; // too many or too few characters
					}
					
					for (var i = 1; i <= ThisTargetFieldValue.length; i++) { // check each char
						var j = i - 1;
						if ((ThisTargetFieldValue.substring(j,i) < "0") || (ThisTargetFieldValue.substring(j,i) > "9")) {
								PhoneFormatFail = true; // alpha character has been entered
						}
					}	
					
					// rebuild the phone number the way we want it
					document.getElementById(ThisField).value = "(" + ThisTargetFieldValue.substring(0,3) + ") " + ThisTargetFieldValue.substring(3,6) + "-" + ThisTargetFieldValue.substring(6,10);
					
					break;
				default:
					//Code goes here
			}
		
			if (PhoneFormatFail) {
			
				Result = Result + PhoneFormatMessage.replace("FieldDescription",ThisTargetFieldDesc);
				Result = Result.replace("PhonePattern",Pattern);
			
			}	
		
		}

	}
	
	return Result;
}

function DateFormatCheck(TargetFields,Pattern) {

	Result = "";
	
	// We have the option of checking more than one field at a time
	TargetFields = TargetFields.split(",");
	
	for (LoopCount=0;LoopCount<TargetFields.length;LoopCount++){
	
		DateFormatFail = false; // we assume we pass ...

		ThisField = TargetFields[LoopCount]
		
		ThisTargetFieldValue = document.getElementById(ThisField).value;
		ThisTargetFieldDesc = document.getElementById(ThisField).alt;
		
		if (ThisTargetFieldValue != "") {
		
			switch(Pattern) {
				case 'YYYY/MM/DD':
					ThisTargetFieldValueUngrouped = ThisTargetFieldValue.split("/");	
					for (var i = 1; i <= ThisTargetFieldValue.length; i++) {
						var j = i - 1;
						if ((ThisTargetFieldValue.substring(j,i) < "0") || (ThisTargetFieldValue.substring(j,i) > "9")) {
							if (ThisTargetFieldValue.substring(j,i) != "/") {
								DateFormatFail = true; // alpha character has been entered
							}
						}
					}	
					
					//alert(DateFormatFail + " - alpha or not")
					
					if (ThisTargetFieldValueUngrouped.length < 3) {
						DateFormatFail = true; // didn't have two /
						//alert(DateFormatFail + " - not two slashes")
					} else {
						if (ThisTargetFieldValueUngrouped[0].length != 4) {
							DateFormatFail = true; // year not 4 character digit
							//alert(DateFormatFail + " - not 4 char year")
						}
						if (ThisTargetFieldValueUngrouped[1].length > 2) {
							DateFormatFail = true; // day not 1 or 2 character digit
							//alert(DateFormatFail + " - not one or two char day")
						}
						if (ThisTargetFieldValueUngrouped[2].length > 2) {
							DateFormatFail = true; // month not 1 or 2 character digit
							//alert(DateFormatFail + " - not one or two char month")
						}
						if (ThisTargetFieldValueUngrouped[1] > 12 || ThisTargetFieldValueUngrouped[2] < 1) {
							DateFormatFail = true; // month greater than 12, less than 1
							//alert(DateFormatFail + " - ")
						}
						if (ThisTargetFieldValueUngrouped[2] > 31 || ThisTargetFieldValueUngrouped[1] < 1) {
							DateFormatFail = true; // day greater than 31, less than 1
							//alert(DateFormatFail + " - day not proper")
						}
					}
				
					break;
				default:
					//Code goes here
			}
		
			if (DateFormatFail) {
			
				Result = Result + DateFormatMessage.replace("FieldDescription",ThisTargetFieldDesc);
				Result = Result.replace("DatePattern",Pattern);
			
			}	
		
		}

	}
	
	return Result;
}

function NumericCheck(TargetFields) {
	
	
	Result = "";
	ReqCheck = "";	
	ReqCheckStart = "";
	TargetFields = TargetFields.split(",");
	
	for (LoopCount=0;LoopCount<TargetFields.length;LoopCount++){
		
		ThisField = TargetFields[LoopCount];
		
		NumberFail = false;
		
		// Trap errors caused by including fields in RequiredFelds variable that don't exist
		if (typeof(document.getElementById(ThisField)) == "undefined") {
		 	 alert("ERROR - The field listed in the NumericCheck function as " + document.getElementById(ThisField) + " does not exist. Please remove or adjust accordingly.") 
		} else {
			ThisFieldString = document.getElementById(ThisField).value
			for (var i = 1; i <= ThisFieldString.length; i++) {
				var j = i - 1;
				if ((ThisFieldString.substring(j,i) < "0") || (ThisFieldString.substring(j,i) > "9")) {
					if (ThisFieldString.substring(j,i) != ".") {
						NumberFail = true;
					}
				}
			}
		
			if (NumberFail) {
			
				Result = Result + NumericFieldsMessage.replace("FieldDescription",document.getElementById(ThisField).alt);
			}
			
		}
	}
	
	return Result;
	
	
}

function EmailCheck(TargetFields) {
	
	
	Result = "";
	TargetFields = TargetFields.split(",");
	RestrictedEmailChars = "~@`@#@$@%@^@&@*@(@)!@+@+@{@}@[@]@|@\\@;@:@\"@'@,@<@>@?@/"
	RestrictedEmailChars = RestrictedEmailChars.split("@");
	
	for (LoopCount=0;LoopCount<TargetFields.length;LoopCount++){
		
		ThisField = TargetFields[LoopCount];
		
		EmailFail = false;
		
		// Trap errors caused by including fields in RequiredFelds variable that don't exist
		if (typeof(document.getElementById(ThisField)) == "undefined") {
		 	 alert("ERROR - The field listed in the EmailCheck function as " + ThisField + " does not exist. Please remove or adjust accordingly.") 
		} else if (document.getElementById(ThisField).value != "" && document.getElementById(ThisField).value != " ") {
			ThisFieldString = document.getElementById(ThisField).value;			
			ThisFieldString = ThisFieldString.split("@");
			
			if (ThisFieldString.length != 2) {
				EmailFail = true;
			} else if (ThisFieldString[1].indexOf(".") == -1) {
				EmailFail = true;
			} else {
			
				for (LoopCount=0;LoopCount<RestrictedEmailChars.length;LoopCount++){
					
					if (ThisFieldString[1].indexOf(RestrictedEmailChars[LoopCount]) != -1) {
						EmailFail = true;
					}
					
				}
			}
			
			if (EmailFail) {
				Result = Result + EmailFormatMessage.replace("FieldDescription",document.getElementById(ThisField).alt);
			}
			
		}
		
		
	}
	
	return Result;
	
	
}

function MinMax(TargetFields,Min,Max) {
	
	
	Result = "";
	ReqCheck = "";	
	ReqCheckStart = "";
	TargetFields = TargetFields.split(",");
	for (LoopCount=0;LoopCount<TargetFields.length;LoopCount++){
		NumberFail = false;
		ThisField = document.getElementById(TargetFields[LoopCount]).value
		ThisDesc = document.getElementById(TargetFields[LoopCount]).alt;
		if (Min != "" && parseInt(ThisField) < Min) {
			Result = Result + MinFieldsMessage.replace("FieldDescription",ThisDesc);
			Result = Result.replace("MinValue",(Min-1));
		}
		if (Max != "" && parseInt(ThisField) > Max) {
			Result = Result + MaxFieldsMessage.replace("FieldDescription",ThisDesc);
			Result = Result.replace("MaxValue",(Max+1));
		}
		
	}
	
	return Result;
	
	
}

// Sets all fields in a function to "", or the first select box item
function ResetForm(FormTarget) {

	for (LoopCount=0;LoopCount<FormTarget.length;LoopCount++){
		if (FormTarget[LoopCount].length >= 0) {
			FormTarget[LoopCount][0].selected = true;
		} else {
			FormTarget[LoopCount].value = "";
		}
	}

}


// Functions below toggle field colours for required fields
// ********************************************************
function ColourRequired() {
	
		
		RequiredFieldsBroken = RequiredFields.split(",");

		for (LoopCount=0;LoopCount<RequiredFieldsBroken.length;LoopCount++){

			ThisField = RequiredFieldsBroken[LoopCount]
		
		  // Trap errors caused by including fields in RequiredFelds variable that don't exist
		 // alert(this[ThisFieldByPart[0]]);
		  if (typeof(document.getElementById(ThisField)) == "undefined") {
		 	 alert("ERROR - The field listed in RequiredFields as " + ThisField + " does not exist. Please remove or adjust accordingly.") 
		  } else {
			if (document.getElementById(ThisField).length > 0) {
				
				for (LoopCount2=0;LoopCount2<document.getElementById(ThisField).length;LoopCount2++){

				  if (document.getElementById(ThisField)[LoopCount2].type != "radio" || (ChangeRadioButtonColor)) {
					document.getElementById(ThisField)[LoopCount2].style.backgroundColor = RequiredFieldsBackgroundColor;
					document.getElementById(ThisField)[LoopCount2].style.color = RequiredFieldsTextColor;
				  }
				} // end second for loop
			} else {
				document.getElementById(ThisField).style.backgroundColor = RequiredFieldsBackgroundColor;
				document.getElementById(ThisField).style.color = RequiredFieldsTextColor;
			} // end if statement
	
	
		  } // end if statement
		  
		} // end first for loop

	
  
}

function ConditionalColourChange(TargetFields,ChangeType) {

	AutoFillChecked = true;
	if (ChangeType == "required") {
		ChangeBackgroundColor = RequiredFieldsBackgroundColor;
		ChangeTextColor = RequiredFieldsTextColor
	} else {		
		ChangeBackgroundColor = ResetFieldsBackgroundColor;
		ChangeTextColor = ResetFieldsTextColor
	}
	
	TargetFieldsBroken = TargetFields.split(",");
	for (LoopCount=0;LoopCount<TargetFieldsBroken.length;LoopCount++){
	
		ThisField = TargetFieldsBroken[LoopCount]
		
		if (typeof(document.getElementById(ThisField)) == "undefined") {
			alert("ERROR - The field listed in the ConditionalColourChangefunction as " + ThisField + " does not exist. Please remove or adjust accordingly.") 
		} else {
		 
			if (document.getElementById(ThisField).length > 0) {
			
				for (LoopCount2=0;LoopCount2<document.getElementById(ThisField).length;LoopCount2++){
				  if (document.getElementById(ThisField)[LoopCount2].type != "radio" || (ChangeRadioButtonColor)) {
					document.getElementById(ThisField)[LoopCount2].style.backgroundColor = ChangeBackgroundColor;
					document.getElementById(ThisField)[LoopCount2].style.color = ChangeTextColor;
				  }
				}
				
			} else {
				document.getElementById(ThisField).style.backgroundColor = ChangeBackgroundColor;
				document.getElementById(ThisField).style.color = ChangeTextColor;
			}
			
		}
	}
	
	
}

function ConditionalColourRequired(TargetFields) {

	ConditionalColourChange(TargetFields,"required")
	
}

function ConditionalColourReset(TargetFields) {

	ConditionalColourChange(TargetFields,"reset")
	
}

function SelectConditionalColourChange(CheckThis,AgainstThis,TargetFields) {

	AutoFillChecked = true;
	ChangeNow = false;
	
	AgainstThisBroken = AgainstThis.split(",");
	for (LoopCount=0;LoopCount<AgainstThisBroken.length;LoopCount++){
		if (AgainstThisBroken[LoopCount] == CheckThis) {
			ChangeNow = true;
		}
	}
	
	if (ChangeNow) {
		ConditionalColourChange(TargetFields,"required")
	} else {
		ConditionalColourChange(TargetFields,"reset")
	}
	
	
	
}