/****************************************************************
There are several key things that must be done to this document:
1) Remove from the elts array any form elements that you do not want 
   to be validated.
2) If you choose to add elements to the array, make sure you first 
   declare a new object for each element (i.e., var firstname = new validation . . .
3) Search throughout the document for references to the templateform and 
   replace the text "templateform" with the name of your form.  This should 
   only need to be done in the clearField() function at the end of the file.
****************************************************************/

/***************************************************************
Set the variable formIsLive to true if the page is active.  If you are using 
is as a test page, and do not want the form to submit, set it to false.
If you are using the form as a test/preview page, formNotLiveMsg 
will be displayed in an alert box upon succesful completion of the form.
***************************************************************/
var formIsLive = true;
var formNotLiveMsg = "  Congratulations!!  You have completed  \n  the workcamps registration preview form  \n  successfully.  Please return on  \n  December 1, 2002, when the form will  \n  become active and you can begin the  \n  registration process.";

/***************************************************************
** define and instantiate validation objects
** the validation object accepts the following parameters:
**
**   realName: name used in the alerts (same as label on the page)
**
**   formEltName: this must be the name of the corresponding
**       HTML form element; make it the same as the object name
**
**   uptoSnuff: function call that's evaluated during validation check
**     isText(str)
**     isSelect(formObj)
**     isRadio(formObj)
**     isCheck(formObj, form, [index of first checkbox in group],
**         [number of checkboxes])
**     isEmail(str)
**     isEmailMatch(str1, str2)
**     isState(str)
**     isZipCode(str)
**     isPhoneNum(str)
**     isDate(str)
**
**   responseType: type of response for alerts;
**     deposit: for monetary (minimum/maximum) alerts
**     emailmatch: for matching the e-mail and duplicate e-mail fields
**     include: ask user to include an item (default)
**     select: ask user to select an item
**
**   format: text representation of required format;
**     pass 'null' if no required format;
**     used in alert as an aid to user
**
**   conditionMet: conditional validation;
**	   pass true if no conditions must be met to run validation;
**	   if conditions exist, pass an expression that when the 
**	   conditions are correct it is evaluated as true
***************************************************************/

// object definition
function validation(realNamePrefix, realName, formEltName, upToSnuff, responseType, format, conditionMet) {
	this.realNamePrefix = realNamePrefix;
	this.realName = realName;
	this.formEltName = formEltName;
	this.responseType = responseType;
	this.upToSnuff = upToSnuff;
	this.format = format;
	this.conditionMet = conditionMet;
}

// create a new object for each form element you need to validate
var district = new validation('the', 'district', 'district', 'isSelect(formObj)', 'include', null, true);
var age_grp = new validation('your', 'age group', 'age_grp', 'isSelect(formObj)', 'include', null, true);
var Worship = new validation('your', 'worship rating', 'Worship', 'isRadio(formObj)', 'include', null, true);
var Business = new validation('your', 'business rating', 'Business', 'isRadio(formObj)', 'include', null, true);
var Exhibits = new validation('your', 'exhibits rating', 'Exhibits', 'isRadio(formObj)', 'include', null, true);
var Fellowship = new validation('your', 'fellowship rating', 'Fellowship', 'isRadio(formObj)', 'include', null, true);
var meal_events = new validation('your', 'ticketed meal events rating', 'meal_events','isRadio(formObj)', 'include', null, true);
var cash_buffet = new validation('your', 'cash buffet rating', 'cash_buffet', 'isRadio(formObj)', 'include', null, true);
var insight_sessions = new validation('your', 'insight sessions rating', 'insight_sessions', 'isRadio(formObj)', 'include', null, true);
var bible_studies = new validation('your', 'bible study rating', 'bible_studies', 'isRadio(formObj)', 'include', null, true);
var evening_arts = new validation('your', 'evening arts rating', 'evening_arts', 'isRadio(formObj)', 'include', null, true);
var age_programs = new validation('your', 'age group rating', 'age_programs', 'isRadio(formObj)', 'include', null, true);
var overall_conf = new validation('your', 'overall conf rating', 'overall_conf', 'isRadio(formObj)', 'include', null, true);



/***************************************************************
** Define the elts array:
** Add a new item to the array for each object you create above
** Make sure the value of the array element is the same as
** the name of the object, and that the array elements are listed
** in the same order the corresponding objects appear in the form
** (it's more clear to the user that way)
***************************************************************/

var elts = new Array(
		district,
		age_grp,
		Worship,
		Business,
		Exhibits,
		Fellowship,
		meal_events,
		cash_buffet,
		insight_sessions,
		bible_studies,
		evening_arts,
		age_programs,
		overall_conf
		);

               
/***************************************************************
** The main function keeps track of which fields the user missed
** or filled in incorrectly, and alerts the user so they can go
** back and fix what's wrong.
** Set allAtOnce to true if you want this "validation help" to
** alert the user to all mistakes at once; set it to false if
** you want it to show one mistake at a time
***************************************************************/
var allAtOnce = true;


/***************************************************************
** These three variables pass information to special functions.
** duplicateEmailField specifies which field contains the 
** re-entry of the e-mail address (used to validate that the 
** user intended to enter the first address as it is).  minCost
** specifies the minimum cost for deposit calculations, and
** maxCost specifies the maximum cost for deposit calculations.
***************************************************************/
var duplicateEmailField = 'emaildup'
var minCost = 125
var maxCost = 225


/***************************************************************
** these functions validate the string or form object passed in,
** and return true or false based on whether the test succeeds or fails
**
** validate existence of input
**   isText(str): verifies text input or textarea is not empty
**   isSelect(formObj): verifies item from a select menu is chosen
**   isRadio(formObj): verifies one of a group of radio buttons is chosen
**
** validate text in text input or textarea matches pattern
**   isChurchCode: verifies church code in the form xx-xxx
**   isEmail(str): verifies email address (contains "@" and ".")
**   isEmailMatch(str): verifies that the two e-mail addresses match each other; pulls location of matching address from duplicateEmailField
**   isZipCode(str): verifies zip code of form xxxxx or xxxxx-xxxx
**   isPhoneNum(str): verifies phone number of form xxx-xxx-xxxx
**   isDate(str): verifies date of form mm/dd/yyyy
**   isDeposit(str): verifies the deposit falls within the boundaries established by minCost and maxCost
***************************************************************/

function isText(str) { return (str != "") }


function isSelect(formObj) { return (formObj.selectedIndex != 0) }


function isRadio(formObj) {
	for (j=0; j<formObj.length; j++) { if (formObj[j].checked) { return true } }
	return false;
}


function isChurchCode(str) {
	var l = str.length;
	if (l != 6) { return false }
	for (j=0; j<l; j++) {
		if (j == 2) {
			if (str.charAt(j) != "-") { return false }
		} else {
			if ((str.charAt(j) < "0") || (str.charAt(j) > "9")) { return false }
		}
	}
	return true;
}


function isEmail(str) { return ((str != "") && (str.indexOf("@") != -1) && (str.indexOf(".") != -1)) }


function isEmailMatch(str1, str2) { return (str1 == str2) }


function isZipCode(str) {
	var l = str.length;
	if ((l != 5) && (l != 10)) { return false }
	for (j=0; j<l; j++) {
		if ((l == 10) && (j == 5)) {
			if (str.charAt(j) != "-") { return false }
		} else {
			if ((str.charAt(j) < "0") || (str.charAt(j) > "9")) { return false }
		}
	}
	return true;
}


function isPhoneNum(str) {
	if (str.length != 12) { return false }
	for (j=0; j<str.length; j++) {
		if ((j == 3) || (j == 7)) {
			if (str.charAt(j) != "-") { return false }
		} else {
			if ((str.charAt(j) < "0") || (str.charAt(j) > "9")) { return false }
		}
	}
	return true;
}


function isDate(str) {
	if (str.length != 10) { return false }

	for (j=0; j<str.length; j++) {
		if ((j == 2) || (j == 5)) {
			if (str.charAt(j) != "/") { return false }
		} else {
			if ((str.charAt(j) < "0") || (str.charAt(j) > "9")) { return false }
		}
	}

	var month = str.charAt(0) == "0" ? parseInt(str.substring(1,2)) : parseInt(str.substring(0,2));
	var day = str.charAt(3) == "0" ? parseInt(str.substring(4,5)) : parseInt(str.substring(3,5));
	var begin = str.charAt(6) == "0" ? (str.charAt(7) == "0" ? (str.charAt(8) == "0" ? 9 : 8) : 7) : 6;
	var year = parseInt(str.substring(begin, 10));

	if (day == 0) { return false }
	if (month == 0 || month > 12) { return false }
	if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) {
		if (day > 31) { return false }
	} else {
		if (month == 4 || month == 6 || month == 9 || month == 11) {
			if (day > 30) { return false }
	} else {
		if (year%4 != 0) {
				if (day > 28) { return false }
			} else {
				if (day > 29) { return false }
			}
		}
	}
	return true;
}


function isDeposit(str) {
	var l = str.length;
	if (isNaN(str)) { return false };

	if (str < minCost) { return false }
	if (str > maxCost) { return false }

	return true;
}


/***************************************************************
** Text for alerts (FYI: "at" stands for "alert text"
***************************************************************/
var atBeginInclude = "Please include ";
var atBeginSelect = "Please specify ";
var atEnd = ".";
var atBeginInvalid = " is an invalid ";
var atEndInvalid = ".";
var atBeginFormat = "  Please use this format: ";


/***************************************************************
** The validateForm() function validates the form elements
** previously defined as validation objects and as members of
** the elts array. We loop through the elts array, testing each
** element in turn, and alerting the user when they've missed
** a required field
***************************************************************/

function validateForm(form) {
	var formEltName = "";
	var formObj = "";
	var eltType = "";
	var str = "";
	var realName = "";
	var realNamePrefix = "";
	var conditionMet = false;
	var origAlertText = "________________________________________________________  \n\nYour form was not completed correctly.\nPlease correct the following error(s) and resubmit the form.\n________________________________________________________  \n\n";
	var alertText = origAlertText
	var firstMissingElt = null;
	var hardReturn = "\r\n";

	for (i=0; i<elts.length; i++) {
		formEltName = elts[i].formEltName;
		formObj = eval("form." + formEltName);
		realName = elts[i].realName;
		realNamePrefix = elts[i].realNamePrefix;
		responseType = elts[i].responseType;
		conditionMet = eval(elts[i].conditionMet);
		
		// alert("Form object: " + formObj)
		
		if (conditionMet) {
			switch (responseType) {
				default :
					// This default case handles everything not covered by another case, including the "include" case
					str = formObj.value;
					if (eval(elts[i].upToSnuff)) continue;
					if (str == "") {
						if (allAtOnce) {
							alertText += atBeginInclude + realNamePrefix + " " + realName + atEnd + hardReturn;
							if (firstMissingElt == null) {firstMissingElt = formObj};
						} else {
							alertText = atBeginInclude + realNamePrefix + " " + realName + atEnd + hardReturn;
							alert(alertText);
						}
					} else {
						if (allAtOnce) {
							alertText += str + atBeginInvalid + realName + atEndInvalid + hardReturn;
						} else {
							alertText = str + atBeginInvalid + realName + atEndInvalid + hardReturn;
						}
						if (elts[i].format != null) { alertText += atBeginFormat + elts[i].format + hardReturn; }
						if (allAtOnce) { 
							if (firstMissingElt == null) {firstMissingElt = formObj};
						} else {
							alert(alertText);
						}
					}
					break;
					
				case "select" :
					// The select cases is designed to handle form elements where the user can choose from several options
					str = formObj.value;
					if (eval(elts[i].upToSnuff)) continue;
					if (allAtOnce) {
						alertText += atBeginSelect + realNamePrefix + " " + realName + atEnd + hardReturn;
						if (firstMissingElt == null) {firstMissingElt = formObj};
					} else {
						alertText = atBeginSelect + realNamePrefix + " " + realName + atEnd + hardReturn;
						alert(alertText);
					}
					
					break;
				case "deposit" :
					// prepare field value for evaluation
					str = formObj.value;
					var l = str.length;
					if(str.charAt(0) == "$") {
						var newStr = ""
						for (j=1; j<l; j++) { newStr += str.charAt(j) }
						str = parseFloat(newStr);
						formObj.value = str;
					}
					// evaluate validity of deposit value and if invalid process user alert
					if (eval(elts[i].upToSnuff)) continue;
					if (str == "") {
						if(allAtOnce) {
							alertText += "You did not enter a deposit amount.\n    Please enter a deposit amount between $" + minCost + " and $" + maxCost + "." + hardReturn;
							if (firstMissingElt == null) {firstMissingElt = formObj};
						} else {
							alertText = "You did not enter a deposit amount.\n    Please enter a deposit amount between $" + minCost + " and $" + maxCost + "." + hardReturn;
							alert(alertText);
						}
					} else {
						if(allAtOnce) {
							alertText += "$" + str + " is an invalid deposit amount.\n    Please enter a deposit amount between $" + minCost + " and $" + maxCost + "." + hardReturn;
							if (firstMissingElt == null) {firstMissingElt = formObj};
						} else {
							alertText = "$" + str + " is an invalid deposit amount.\n    Please enter a deposit amount between $" + minCost + " and $" + maxCost + "." + hardReturn;
							alert(alertText);
						}
					}
					break;
					
				case "emailmatch" :
					// The emailmatch case creates the user alert when both addresses that were entered do not match
					str1 = formObj.value;
					if (formEltName == "nominee_email") { str2 = form.nominee_email_dup.value; }
						else { str2 = form.nominator_email_dup.value; }
					if (eval(elts[i].upToSnuff)) continue;
					if (str2 == "") {
						if(allAtOnce) {
							alertText += "You must re-enter " + realNamePrefix + " " + realName + " to verify." + hardReturn;
							if (firstMissingElt == null) {firstMissingElt = formObj}
						} else {
							alertText = "You must re-enter " + realNamePrefix + " " + realName + " to verify." + hardReturn;
							alert(alertText);
						}
					} else {
						if(allAtOnce) {
							alertText += "The e-mail addresses you entered do not match.\n    Please verify " + realNamePrefix + " " + realName + "." + hardReturn;
							if (firstMissingElt == null) {firstMissingElt = formObj}
						} else {
							alertText = "The e-mail addresses you entered do not match.\n    Please verify " + realNamePrefix + " " + realName + "." + hardReturn;
							alert(alertText);
						}
					}
					break;
			
			}

			var goToObj = (allAtOnce) ? firstMissingElt : formObj;
			if (goToObj.select) goToObj.select();
			if (goToObj.focus) goToObj.focus();
			
			if (!allAtOnce) {return false};
		}
	}
	
	if (allAtOnce) {
		if (alertText != origAlertText) {
			alert(alertText);
			return false;
		}
	}
	
	if (formIsLive) {
		return true;
	} else {
		alert(formNotLiveMsg);
		return false;
	}
}

// This is the end of scipt for validation



// Code to open a popup window
function openAnyWindow(url, name) {
	var l = openAnyWindow.arguments.length;
	var w = "";
	var h = "";
	var features = "";

	for (i=2; i<l; i++) {
		var param = openAnyWindow.arguments[i];
		if ( (parseInt(param) == 0) || (isNaN(parseInt(param))) ) {
			features += param + ',';
		} else {
			(w == "") ? w = "width=" + param + "," :
				h = "height=" + param;
		}
	}

	features += w + h;
	var code = "popupWin = window.open(url, name";
	if (l > 2) code += ", '" + features;
	code += "')";
	eval(code);
}


// Clear the congregation field (which has a readonly status)
function clearField() {
	window.document.NYACreg.congregation.value = "";
	window.document.NYACreg.congregationname.value = "church code was entered manually";
	window.document.getElementById("textDisplayCongName").childNodes[0].nodeValue = " ";
	window.document.getElementById("textDisplayCongInstructions").childNodes[0].nodeValue = "Every Church of the Brethren congregation has a five-digit code that uniquely identifies it.  Please click ";
	}
