///////////////////////////////////////////////////////////////////////////////////////////////////
//												 //
// JavaScript Form Validation									 //
// Copyright © 2001-2007 David E. Haasnoot							 //
// dave@deshave.com										 //
//												 //
// Usage:											 //
// You need to include the validate2_1.js file BEFORE creating					 //
// any array, thusly:										 //
//												 //
// <SCRIPT TYPE="text/javascript" LANGUAGE="JavaScript" SRC="validate2_1.js"></SCRIPT>		 //
//												 //
// Then create an array of required form elements:						 //
//												 //
// <SCRIPT LANGUAGE="JavaScript">								 //
// var requiredFields = new Array();								 //
// requiredFields[0] = new field("<field name>", "<nice name>", "<validation type>"[, <params>]);//
// requiredFields[1] = new field("<field name>", "<nice name>", "regex", /^[0-9]+$/);		 //
// </SCRIPT>											 //
//												 //
// where:											 //
// <field name> = The HTML input name parameter						         //
// <nice name> = Something you want the user to see						 //
// <validation type> = What kind of checking to do on						 //
// 	this variable. Choices are:								 //
//												 //
// card - must have valid credit card number							 //
// date - allows 04/01, 0401, 04-01, etc							 //
// mysqldate - allows only yyyy-mm-dd								 //
// radio - ensures that one of a group is checked                                                //
// depends - ensures that if one has a value, others must be selected                            //
// requires - ensures that if a dropdown has a specific value, another field cannot be blank     //
// oneof - ensures that at least one of the given fields has a value                             //
// regex - applies a given regular expression, uses params					 //
// length - ensures a maximum length (i.e.: for text areas)                                      //
// group - ensures that one of a group of checkboxes has been checked				//
//												 //
// <params> = Additional parameters								 //
//												 //
// NOTE: Multiple validations can be used on the same form input				 //
//												 //
// Be sure to call validate() using the onSubmit() method, like so:				 //
// <FORM ACTION="" METHOD="post" onSubmit="return validate(this, requiredFields)">		 //
//												 //
// Created: 2000-09-13 19:00 EST								 //
// Revised: 2006-08-11 16:37 EST								 //
//												 //
///////////////////////////////////////////////////////////////////////////////////////////////////

// true if you want to lose the "Are you sure?" popups
var bypassConfirm = false;
var useFlashing = true;
var flashTimes = 3;
var flashDelay = 500;

var timer;
var count = 0;
var submittedFormref;
var badFields = new Array();

// some common regexs
var alpha = /^[A-Za-z]+$/;
var digit = /^[0-9]+$/;
var notnull = /.+/;
var name = /^[A-Za-z0-9 '-]{3,}$/;
var zipcode = /^[0-9A-Za-z ]{5,10}$/;
var phone = /^\(?[0-9]{3}\)?[\s\.-]?[0-9]{3}[ \.-]?[0-9]{4}|[0-9 ]{10,14}$/;
var ssn = /^[0-9]{3}[ -]?[0-9]{2}[ -]?[0-9]{4}$/;
var email = /^[A-Za-z0-9_\.-]+@[A-Za-z0-9\.-]+\.[A-Za-z]{2,4}$/;
var money = /^[0-9,]+(\.[0-9]{2})?$/;
var date = /[0-9]{1,2}[\/-]+[0-9]{2,4}/;
var mysqldate = /[0-9]{4}-[0-9]{2}-[0-9]{2}/;

function check_me(fref) {
	this.formref = fref;
	submittedFormref = fref;
	this.ref = fref.elements[this.name];
	if (eval('this.check_' + this.type)) {
		return eval('this.check_' + this.type + '()');
	} else {
		return "System Error: Invalid validation request (" + this.type + ")";
	}
}

function checkme_length() {
	if (this.params) {
		if (this.ref.value.length > this.params) {
			return this.niceName + " is more than the limit of " + this.params + " characters.";
		}
		return "";
	} else {
		return "System Error: Please contact the Webmaster";
	}
}

function checkme_regex() {
	if (this.params) {
		if (!this.ref.value.match(this.params)) {
			if (this.ref.value=="") {
				return this.niceName + " was left blank";
			} else {
				return this.niceName + " contains \"" + this.ref.value + "\", which is invalid";
			}
		}
		return "";
	} else {
		return "System Error: Please contact the Webmaster";
	}
}


function checkme_date() {
	if (this.ref.value.length < 4) {
		return this.niceName + " contains \"" + this.ref.value + "\", which is not a valid Expiration Date";
	}
	month = parseInt(this.ref.value.substring(0,2));
	year = parseInt(this.ref.value.substring((this.ref.value.length-2),this.ref.value.length));
	if (month > 0 && month < 13) {
		year = "" + year;
		if (parseInt(year.charAt(0)) < 0 || parseInt(year.charAt(0)) > 9 || parseInt(year.charAt(1)) < 0 || parseInt(year.charAt(1)) > 9)  {
			return this.niceName + " contains \"" + this.ref.value + "\", which is not a valid Expiration Date";
		}
	} else {
		return this.niceName + " contains \"" + this.ref.value + "\", which is not a valid Expiration Date";
	}
	return "";
}

function checkme_mysqldate() {
	if (this.ref.value.length != 10) {
		return this.niceName + " contains \"" + this.ref.value + "\", which is not a valid MySQL Date";
	}
	month = parseInt(this.ref.value.substring(5,7));
	if (month < 1 || month > 13) {
		return this.niceName + " contains \"" + this.ref.value + "\", which is not a valid MySQL Date";
	}
	year = parseInt(this.ref.value.substring(0,4));
	if (year < 2000 || year > 2050)  {
		return this.niceName + " contains \"" + this.ref.value + "\", which is not a valid MySQL Date";
	}
	day = parseInt(this.ref.value.substring(8,10));
	if (day < 1 || day > 31) {
		return this.niceName + " contains \"" + this.ref.value + "\", which is not a valid MySQL Date";
	}
	return "";
}

function checkme_card() {
	if (this.ref.value.length > 0) {
		cardNum = this.ref.value;
		cardNum = replace(cardNum,"-","");
		cardNum = replace(cardNum," ", "");
		cardNum_digit = new Array();
		k = cardNum.length - 1;
		for (j = 1; j < cardNum.length + 1; j++) {
			cardNum_digit[j] = cardNum.charAt(k);
			k--;
		}
		for (digit_position = 2; digit_position < cardNum.length + 1; digit_position += 2){
			digit_times_two = (cardNum_digit[digit_position] * 2);
			if (digit_times_two > 9) {
				cardNum_digit[digit_position] = (digit_times_two - 9);
			} else {
				cardNum_digit[digit_position] = digit_times_two;
			}
		}
		validation_number = 0;
		for (j = 1; j < cardNum_digit.length; j++) {
			validation_number += parseInt(cardNum_digit[j]);
		}
		invalid = validation_number % 10 != 0;
		if (invalid) {
			return this.niceName + " contains \"" + this.ref.value + "\", which is not a valid Credit Card Number";
		}
		return "";
	} else {
		return this.niceName + " was left blank";
	}
}

function checkme_radio() {
	for(j=0;j<this.ref.length;j++) {
		if (this.ref[j].checked) {
			return "";
		}
	}
	return this.niceName + " was not selected";
}

function checkme_depends() {
	if (this.formref[this.params].checked) {
		if (this.check_radio()!="") {
			return this.niceName + " was left blank";
		}
	}
	return "";
}

function checkme_requires() {
	fields = this.params.split("|")
	if (this.formref[fields[0]].value==fields[1]) {
		if (this.ref.value=="") {
			return this.niceName + " cannot be blank when " + this.formref[fields[0]].options[this.formref[fields[0]].selectedIndex].text + " is selected";
		}
	}
	return "";
}

function checkme_oneof() {
	flag = false;
	fields = this.params.split("|");
	for(j = 0; j < fields.length; j++) {
		if (this.formref[fields[j]].value!="") {
			if (!this.formref[fields[j]].value.match(this.params2)) {
				return this.niceName + " contains \"" + this.formref[fields[j]].value + "\", which is not a valid entry";
			} else {
				flag = true;
			}
		}
	}
	if (!flag) {
		return this.niceName + " must have at least one value";
	} else {
		return "";
	}
}

function checkme_group() {
	fields = this.params.split("|");
	for (k = 0; k < fields.length; k++) {
		if (this.formref[fields[k]].checked == true) {
			return "";
		}
	}
	return this.niceName + " must have at least one item checked";
}

function replace(origText,findText,replaceText) {
	var pos = 0;
	var len = findText.length;
	pos = origText.indexOf(findText);
	while (pos > 0){
		preString = origText.substring(0,pos);
		postString = origText.substring(pos + len,origText.length);
		origText = preString + replaceText + postString;
		pos = origText.indexOf(findText);
	}
	return origText;
}

function field(name, niceName, type, params, params2) {
	// initialize member variables
	this.name = name;
	this.niceName = niceName;
	this.type = type;
	this.params = params;
	this.params2 = params2;
	this.ref = null; // cannot initialize until page loads
	
	// member functions
	this.check = check_me;
	this.check_date = checkme_date;
	this.check_card = checkme_card;
	this.check_regex = checkme_regex;
	this.check_radio = checkme_radio;
	this.check_depends = checkme_depends;
	this.check_requires = checkme_requires;
	this.check_oneof = checkme_oneof;
	this.check_length = checkme_length;
	this.check_group = checkme_group;
}

function validate(reference, required) {
	badFields = new Array();
	ready = true;
	errorMessage = "";
	for(i = 0; i < required.length; i++) {
		answer = required[i].check(reference);
		if(answer != "") {
			errorMessage += answer + "\n";
			badFields.push(required[i].name);
			ready = false;
		}
	}
	if (ready) {
		if (bypassConfirm) {
			var button = document.getElementById("subButton");
			if (button) {
				button.disabled = true;
			}
			return true;
		} else {
			if (confirm("Submitting this form will alter the live Web site. Are you sure you want to do this now?")) {
				if (reference.subButton) {
					reference.subButton.disabled = true;
				}
				return true;
			} else {
				return false;
			}
		}
	} else {
		// Compensate for that $&%$*ing Safari browser....
//		if (useFlashing && navigator.userAgent.indexOf('Safari') == -1) {
			flashBackground(flashDelay);
//		}
		alert("I'm sorry, but there were errors in the form:\r\n\r\n" + errorMessage + "\r\nPlease correct the form and submit again.");
		return false;
	}
}

function flashBackground(delay) {
	timer = setInterval("toggleBg()", delay);
}

function toggleBg() {
	if (count <= (flashTimes * 2)) {
		for (i = 0; i < badFields.length; i++) {
			field = document.getElementById(badFields[i]);
//			field = submittedFormref.elements[badFields[i]];
			if (count % 2 == 0) {
//				submittedFormref.elements[badFields[i]].style.backgroundColor = "#fefefe";
				field.style.backgroundColor = "#fefefe";
			} else {
//				submittedFormref.elements[badFields[i]].style.backgroundColor = "#ffff00";
				field.style.backgroundColor = "#ffff00";
			}
		}
		count++;
	} else {
		for (i = 0; i < badFields.length; i++) {
			submittedFormref.elements[badFields[i]].style.backgroundColor = "";
		}
		clearInterval(timer);
		count = 0;
	}
}

function hilite(field, value) {
	ref = document.forms[0][field];
	for(i=0;i<ref.options.length;i++) {
		if (ref.options[i].value == value) {
			ref.selectedIndex = i;
			return;
		}
	}
}