
function check_in_array(haystack,needle) {
	var foundIt = false;
	flatStack = "|:|" + haystack.join("|:|") + "|:|";
	if (flatStack.indexOf("|:|" + needle + "|:|") > -1) foundIt = true;
	return foundIt;
}

function formBtn(elt,btnAction,formName) {
	if (typeof(elt) == "object") {
		theButton = elt;
	} else if (typeof(elt) == "string") {
		theButton = fixElement(elt);	
	}
	if (typeof(theButton) == "object") {
		if (btnAction == "out") {
			removeCssClass(theButton,"buttonHilite");
			removeCssClass(theButton,"buttonClick");
		} else if (btnAction == "over") {
			addCssClass(theButton,"buttonHilite");
		}
	}
	if (btnAction=="click" && formName) {
		validateThenSubmit(formName);	
	}
}
function validateThenSubmit(elt) {
	theForm = fixElement(elt);
	if (typeof(theForm) == "object") {
		if (validateForm(theForm)) theForm.submit();
	} else {
		alert("Cannot validate the form.");	
	}
}

function isValidSSN(ssn) {
	var ssnRE = /^([0-6]\d{2}|7[0-6]\d|77[0-2])([ \-]?)(\d{2})\2(\d{4})$/;
	if(!ssnRE.test(ssn)) { return false; }
	var tempSSN = ssn;
	if(ssn.indexOf("-") != -1) { tempSSN = (ssn.split("-")).join(""); }
	if(ssn.indexOf(" ") != -1) { tempSSN = (ssn.split(" ")).join(""); }
	if(tempSSN.substring(0, 3) == "000") { return false; }
	if(tempSSN.substring(3, 5) == "00") { return false; }
	if(tempSSN.substring(5, 9) == "0000") { return false; }
	if(tempSSN.substring(0, 9) == "111111111") { return false; }
	if(tempSSN.substring(0, 9) == "222222222") { return false; }
	if(tempSSN.substring(0, 9) == "333333333") { return false; }
	if(tempSSN.substring(0, 9) == "444444444") { return false; }
	if(tempSSN.substring(0, 9) == "555555555") { return false; }
	if(tempSSN.substring(0, 9) == "666666666") { return false; }
	if(tempSSN.substring(0, 9) == "123456789") { return false; }
	return true;
}

function validateForm(whichForm) {
	var errorMessage = "The following problems occured with the form:\n";
	var separator = "______________________________________________________________";
	errorMessage += separator + "\n\n";
	var i,j;
	var validContent = 1;//innocent until proven guilty
	
	for (i=0;i<whichForm.elements.length;i++) {//validate each element in the form if property 'validate' is specified
		elt = whichForm.elements[i];
		if ((elt.validate && elt.validate == 1) || elt.getAttribute("validate") == 1) {
			msg = validateElement(elt);
			if (msg.length > 0) {
				validContent = false;
				errorMessage += msg + "\n";
			}
		}
	}
	errorMessage += separator;
	if (!validContent) alert(errorMessage);
	return validContent;
}

function validateElement(elt) {
	var errorMessage = "";
	
	validateType = (elt.validatetype) ? elt.validatetype : elt.getAttribute("validatetype");
	required = (elt.isrequired) ? elt.isrequired : elt.getAttribute("isrequired");
	displayName = (elt.displayname) ? elt.displayname : elt.getAttribute("displayname");
		if (!displayName) displayName = (elt.id) ? elt.id : elt.name;
	minLength = (elt.minlength) ? elt.minlength : elt.getAttribute("minlength");
	maxLength = (elt.maxlength) ? elt.maxlength : elt.getAttribute("maxlength");
	compareTo = (elt.compareto) ? elt.compareto : elt.getAttribute("compareto");
	compareElt = 0;
	if (compareTo && fixElement(compareTo)) compareElt = fixElement(compareTo);
	typeinfo = (elt.typeinfo) ? elt.typeinfo : elt.getAttribute("typeinfo");
	typeinfoElt = 0;
	if (typeinfo && fixElement(typeinfo)) typeinfoElt = fixElement(typeinfo);
	if (typeinfoElt) {
		validateType = typeinfoElt.value.toLowerCase();
	}
	
	var ccre = /cc\-\(.*\)/;
	if (ccre.test(validateType)) {
		ccTypes = validateType.substring(4,validateType.length-1);
		validateType = "cc";
	}
	
	var regExp = new Array();
	regExp['snumber'] = /^S\d{8}$/;
	regExp['integer'] = /^-?\d+$/;
	regExp['decimal'] = /^[\d\.]+$/;
	regExp['money'] = /^\$?\-?(\d|,)+(\.\d{2})?$/;
	regExp['string'] = /.*/;
	regExp['binary'] = /^[true,false,0,1]$/;
	regExp['hex'] = /^#[A-Fa-f0-9]{6}$/;
	regExp['email'] = /(^email$)|(^([a-zA-Z0-9_\-])([a-zA-Z0-9_\-\.]*)@(\[((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}|((([a-zA-Z0-9\-]+)\.)+))([a-zA-Z]{2,}|(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\])$)/;
	regExp['username'] = /^[a-zA-Z0-9_\-]+$/;
	regExp['userid'] = /^([0-9]+|ID)+$/;
	regExp['password'] = /.*/;
	regExp['emailalias'] = /^([A-Za-z])([a-zA-Z0-9_\-]){2}([a-zA-Z0-9_\-]+)?$/;
	regExp['phone'] = /^1?\s*[-\.]?\s*(\d{3}|\(\s*\d{3}\s*\))\s*[-\.]?\s*\d{3}\s*[-\.]?\s*\d{4}$/;
	regExp['areacode'] = /^\d+$/;
	//regExp['phonenumber'] = /^\d{3}\s*[-\.]?\s*\d{4}$/;
	regExp['phonenumber'] = /^[0-9 -\.]+$/;
	//regExp['zip'] = /(^[A-Z]{1,2}[0-9]{1,2}[A-Z]? ?[0-9][ABDEFGHJLNPQRSTUWXYZ]{2}$)|(^postal$)|(^postal code$)|(^\d{5}(-\d{4})?$)|(^[A-Za-z]\d[A-Za-z][ -]?\d[A-Za-z]\d$)|(^\d{4}$)(^([A-Z0-9]{3}[A-Z0-9]?( )?)+$)/;
	regExp['zip'] = /.*/;
	regExp['date'] = /^\d{1,2}\/|-\d{1,2}\/|-\d{4}$/;
	regExp['mysqlDate'] = /^\d{4}-\d{2}|-\d{2}$/;
	regExp['file'] = /.*/;
	regExp['ssn'] = /^([0-6]\d{2}|7[0-6]\d|77[0-2])([ \-]?)(\d{2})\2(\d{4})$/;
	regExp['ein'] = /^\d{2}[\-\. ]?\d{7}$/;
	regExp['ssnein'] = /^(\d{3}[\-\. ]?\d{2}[\-\. ]?\d{4})|(\d{2}[\-\. ]?\d{7})$/;
	regExp['ip'] = /^\d\d?\d?\.\d\d?\d?\.\d\d?\d?\.\d\d?\d?$/;
	regExp['dropdown'] = /^..*$/;
	regExp['cc'] = /^(\*{12}\d{4})|(4\d{3}-?\d{4}-?\d{4}-?\d{4})|(5[1-5]\d{2}-?\d{4}-?\d{4}-?\d{4})|(6011-?\d{4}-?\d{4}-?\d{4})|(3[4,7]\d{13})|(3[4,7]\d{13})$/;
	regExp['ccMasked'] = /^\*{12}\d{4}$/;
	regExp['visa'] = /^4\d{3}-?\d{4}-?\d{4}-?\d{4}$/;
	regExp['mc'] = /^5[1-5]\d{2}-?\d{4}-?\d{4}-?\d{4}$/;
	regExp['discover'] = /^6011-?\d{4}-?\d{4}-?\d{4}$/;
	regExp['amex'] = /^3[4,7]\d{13}$/;
	regExp['diners'] = /^3[0,6,8]\d{12}$/;
	
	var noRegExp = new Array();
	noRegExp['snumber'] = "\"" + displayName + "\" must be a properly formatted s-number (S12345678).";
	noRegExp['integer'] = "\"" + displayName + "\" must contain only digits.";
	noRegExp['decimal'] = "\"" + displayName + "\" must contain only digits or a period.";
	noRegExp['money'] = "\"" + displayName + "\" must be a valid dollar amount ($123.45).";
	noRegExp['string'] = "\"" + displayName + "\" must be a valid string.";
	noRegExp['binary'] = "\"" + displayName + "\" must be either true or false.";
	noRegExp['hex'] = "\"" + displayName + "\" must be a hexidecimail color code (#AF614C).";
	noRegExp['email'] = "\"" + displayName + "\" must be a properly formatted email address (you@yourserver.com).";
	noRegExp['username'] = "\"" + displayName + "\" may only contain letters, numbers, underscores, or dashes.";
	noRegExp['userid'] = "\"" + displayName + "\" must be a valid user id (1234).";
	noRegExp['password'] = "\"" + displayName + "\" must be a valid password.";
	noRegExp['emailalias'] = "\"" + displayName + "\" must start with a letter and should not contain any blank spaces or special characters including: . , ? ; : \" ' ! @ # $ % ^ & * ( ), etc.";
	noRegExp['phone'] = "\"" + displayName + "\" must be a properly formatted phone number (123) 456-7890.";
	noRegExp['areacode'] = "\"" + displayName + "\" must be a properly formatted area code 123.";
	noRegExp['phonenumber'] = "\"" + displayName + "\" must be a properly formatted phone number 456-7890.";
	noRegExp['zip'] = "\"" + displayName + "\" must be a properly formatted postal code (12345-6789), (A1B 2C3), etc.";
	noRegExp['date'] = "\"" + displayName + "\" must be in date format (MM/DD/YYYY).";
	noRegExp['mysqlDate'] = "\"" + displayName + "\" must be in date format (YYYY-MM-DD).";
	noRegExp['file'] = "\"" + displayName + "\" must contain the name of a file on your drive.";
	noRegExp['ssn'] = "\"" + displayName + "\" must be a valid social security number (123-45-6789).";
	noRegExp['ein'] = "\"" + displayName + "\" must be a valid federal employer identification number (12-3456789).";
	noRegExp['ssnein'] = "\"" + displayName + "\" must be a valid social security number (123-45-6789) or federal employer identification number (12-3456789).";
	noRegExp['ip'] = "\"" + displayName + "\" must be a valid IP address (123.456.789.012).";
	noRegExp['dropdown'] = "You must select a value for \"" + displayName + "\".";
	noRegExp['cc'] = "\"" + elt.value + "\" is not a valid card number.";
	noRegExp['visa'] =  "\"" + elt.value + "\" is not a valid Visa card number.";
	noRegExp['mc'] =  "\"" + elt.value + "\" is not a valid MasterCard number.";
	noRegExp['discover'] =  "\"" + elt.value + "\" is not a valid discover card number.";
	noRegExp['amex'] =  "\"" + elt.value + "\" is not a valid AmEx card number.";
	noRegExp['diners'] =  "\"" + elt.value + "\" is not a valid diners card number.";
	
	var digits = new Array('integer','decimal','money');
	var alternateTypes = new Array('radio','checkbox');
	
	var units = "character";
	var i;
	for (i=0;i<digits.length;i++) {
		if (validateType == digits[i]) {
			units = "digit";
			break;
		}
	}
	
	if (typeof(regExp[validateType]) != "undefined" || (check_in_array(alternateTypes,validateType))) {
		if (validateType == "checkbox") {
			if (required==1 && (elt.checked==false)) errorMessage += "\"" + displayName + "\" must be checked.";
		} else if (validateType == "radio") {
			var i;
			var isChecked = false;
			for (i=0;i<elt.length;i++) {
				alert(elt[i]);
				if (elt[i].checked) isChecked = true;
			}
			if (!isChecked) errorMessage += "Please select a/an " + displayName + ".";
		} else if (validateType == "cc") {
			var validCC = false;
			var types = ccTypes.split("|");
			re = regExp[validateType];
			for (i=0;i<ccTypes.length;i++) if (re.test(elt.value)) validCC = true;
			re = regExp['ccMasked'];
			if (validCC && !re.test(elt.value)) {
				// Checksum ("Mod 10")
				// Add even digits in even length strings or odd digits in odd length strings.
				var checksum = 0;
				var currCcNum = elt.value.replace(/\-/g,"");
				
				for (j=(2-(currCcNum.length % 2)); j<=currCcNum.length; j+=2) {
					checksum += parseInt(currCcNum.charAt(j-1));
				}
				// Analyze odd digits in even length strings or even digits in odd length strings.
				for (j=(currCcNum.length % 2) + 1; j<currCcNum.length; j+=2) {
					var digit = parseInt(currCcNum.charAt(j-1)) * 2;
					if (digit < 10) { 
						checksum += digit; 
					} else { 
						checksum += (digit-9);
					}
				}
				if ((checksum % 10) != 0) {
					validCC = false;
				}			
			}
			
			if (!validCC) errorMessage += noRegExp[validateType];
		} else {
			if (required == 1 || (!required || required == 0) && elt.value != "") {
				re = regExp[validateType];
				if (!re.test(elt.value)) errorMessage += noRegExp[validateType];
				if (compareElt && elt.value != compareElt.value) errorMessage += "\"" + displayName + "s\" do not match.";
				if (minLength && elt.value.length < minLength) errorMessage += "\"" + displayName + "\" must contain " + minLength + " or more "+units+"(s).";
				else if (maxLength && elt.value.length > maxLength) errorMessage += "\"" + displayName + "\" must contain " + maxLength + " or less "+units+"(s).";
			}
		}
	}
	
	return errorMessage;
}

function setFormFieldValue(whichField,whichValue,isParent) {
	var theField = (isParent) ? fixParentElement(whichField) : fixElement(whichField);
	if (theField) {
		theField.value = whichValue;
	}
}

function specialFormSubmit(whichForm,formAction,formTarget,validate) {
	theForm = fixElement(whichForm);
	theForm.action = (formAction) ? formAction : theForm.action;
	theForm.target = (formTarget) ? formTarget : "_self";
	if ((!validate) || (validate && validateForm(theForm))) {
		theForm.submit();
	}
}

function switchStates(whichCountryField) {
	//determine the name of the node id we're using
	var whichNodeId = "countryId";
	if (whichCountryField.id.indexOf(whichNodeId) == -1) whichNodeId = 'CountryId';
	whichNodeParts = whichCountryField.id.split(whichNodeId); 
	if (whichNodeParts.length > 1) { //get the name of the current node id
		prefix = whichNodeParts[0];
		nodeId = whichNodeParts[1];
	}
	//now determine the name of the state field
	if (prefix != '') whichStateField = fixElement(prefix + 'StateId' + nodeId);
	else whichStateField = fixElement('stateId' + nodeId);

	if (typeof(whichStateField) == "object") {
		whichStateField.options.selectedIndex = 0;
		if (!in_array(hasStates,whichCountryField.value)) {
			whichArray = states0;
		} else {
			whichArray = eval("states" + whichCountryField.value);
		}
		whichStateField.options.length = whichArray.length;
		for (i=0;i<whichArray.length;i++) {
			whichStateField.options[i].value = whichArray[i][0];
			whichStateField.options[i].text = whichArray[i][2];
		}
	}
}
var submittingForm;
function sendForm(whichForm) {
	var theSendingDiv = fixElement('sendingDiv');
	var theForm = eval(whichForm);
	if (theForm) var theSubmitBtn = eval("whichForm.mySubmit");
	if (theForm) var theSubmitImg = eval(fixElement('mySubmitImg'));
	var theSendingImg = fixElement('sendingImg');
	if (theSendingDiv) {
		setDisplay(theSendingDiv,'inline');
		setVisibility(theSendingDiv,'visible');
	}
	if (theSendingImg) {
		setDisplay(theSendingImg,'inline');
		setVisibility(theSendingImg,'visible');
		setTimeout('var theSendingImg = fixElement("sendingImg"); theSendingImg.src = "/img/sending.gif"', 200);
	}
	if (theSubmitBtn) {
		theSubmitBtn.disabled=true;
		addCssClass(theSubmitBtn,"buttonDisabled");
		if (theSubmitBtn.value) theSubmitBtn.value="sending...";
	}
	if (theSubmitImg) {
		theSubmitImg.disabled=true;
	}
	submittingForm = 1;
	return true;
}
	
var hasStates = new Array();
var states0 = new Array();
states0[0] = new Array('','No States/Provinces','No States/Provinces');


function checkToggle (e) {
	f = document.getElementById(e);
	if (!f) {
		f = document.getElementsByName(e);
		if (f[0]) f = f[0];
	}

	if (f) {
		if (f.checked) f.checked = false;
		else f.checked = true;
	}
}

function checkOn (e) {
	f = document.getElementById(e);
	if (!f) {
		f = document.getElementsByName(e);
		if (f[0]) f = f[0];
	}

	if (f) f.checked = true;
}

function checkOff (e) {
	f = document.getElementById(e);
	if (!f) {
		f = document.getElementsByName(e);
		if (f[0]) f = f[0];
	}

	if (f) f.checked = false;
}

function insertAtCursor (areaId, text) {
	var txtarea = document.getElementById(areaId);
	var scrollPos = txtarea.scrollTop;
	var strPos = 0;
	var br = ((txtarea.selectionStart || txtarea.selectionStart == '0') ? "ff" : (document.selection ? "ie" : false ) );
	
	if (br == "ie") {
		txtarea.focus();
		var range = document.selection.createRange();
		range.moveStart ('character', -txtarea.value.length);
		strPos = range.text.length;
	}
	else if (br == "ff") strPos = txtarea.selectionStart; 
	
	var front = (txtarea.value).substring(0,strPos);
	var back = (txtarea.value).substring(strPos,txtarea.value.length);
	txtarea.value = front+text+back;
	strPos = strPos + text.length;

	if (br == "ie") {
		txtarea.focus();
		var range = document.selection.createRange();
		range.moveStart ('character', -txtarea.value.length);
		range.moveStart ('character', strPos);
		range.moveEnd ('character', 0); range.select();
	}
	else if (br == "ff") {
		txtarea.selectionStart = strPos;
		txtarea.selectionEnd = strPos;
		txtarea.focus();
	}
	txtarea.scrollTop = scrollPos;
}


