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

function clickOtherCheckboxes (thisCheckbox, checkboxArray) {
	var t = fixElement(thisCheckbox);
	var o = null;
	var c = false;
	if (t != null && t.checked) c = true;

	if ((checkboxArray instanceof Array) && (checkboxArray.length > 0)) for (i in checkboxArray) { 
		fixElement(checkboxArray[i]).checked = c;
	};
}

function checkCheckbox (checkboxname) {
	if (getElement(checkboxname)) getElement(checkboxname).checked = 1;
}

function setRadioSelect (radioset, value) {
	for (var i = 0; i < radioset.length; i++) {
		if (value == radioset[i].value) radioset[i].checked = true;
	}
	return;
}
function getSelectedRadioValue (radioset) {
	//document.orderform.music
	//var radios = fixElement(radioset);
	var rad_val = '';
	for (var i = 0; i < radioset.length; i++) {
		if (radioset[i].checked) {
			rad_val = radioset[i].value;
		}
	}
	return rad_val;
}
function clearRadioSelect (radioset) {
	for (var i = 0; i < radioset.length; i++) {
		radioset[i].checked = false;
	}
	return;
}

function numbersOnly (evt) {
	var allowDash = (arguments[1] ? arguments[1] : false);
	var allowPeriod = (arguments[2] ? arguments[2] : false);

	var charCode = (evt.which) ? evt.which : evt.keyCode
	
	//alert(charCode);

	//let arrowkeys through (188 is control-v on Mac; need the code for Windows)
	if (IndexOf(charCode, [37,38,39,40,118]) >= 0) return true;

	//alert(charCode);
	if ((allowPeriod) && (charCode == 190 || charCode == 110 || charCode == 46)) return true;
	if ((allowDash) && (charCode == 109 || charCode == 189 || charCode == 45)) return true;

	//now check everything else
	if (charCode > 31 && (charCode < 48 || charCode > 57)) return false;

	return true;
}

function clickBox (box_clicked, state, boxes_to_act) {
	//what is this buggery?
	var yes_box, no_box;
	
	yes_box = fixElement(box_clicked + '_yes');	
	no_box = fixElement(box_clicked + '_no');	
	if (state == 'yes') {
		yes_box.checked = 1;
		no_box.checked = 0;
		for (var b in boxes_to_act) showDiv(boxes_to_act[b]);
	}
	else if (state == 'no') {
		yes_box.checked = 0;
		no_box.checked = 1;
		for (var b in boxes_to_act) hideDiv(boxes_to_act[b]);
	}
}

function swapFill (e, match_to_clear) {
	e.className = 'onfill';
	if (e.value == match_to_clear) e.value = '';
}

function swapBack (e, match_to_fill) {
	if (e.value == match_to_fill || e.value == '') {
		e.className = 'prefill';
		e.value = match_to_fill;
	}
}

/* resize a ckeditor instance */
function editorResize (editorInstance, width, height) {
	editorInstance.resize(width, height, true);
}

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 disableFormElement (eid) {
	var e = fixElement(eid);
	if (e) e.disabled = true;
}

function enableFormElement (eid) {
	var e = fixElement(eid);
	if (e) e.disabled = false;
}

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 displayFormErrorMessage (message) {
	var reportDiv = arguments[1];
	var reportDivElement = getElement(reportDiv);
	if (reportDivElement) {
		reportDivElement.innerHTML = message;
		showDiv(reportDiv);
	}
	else alert(message);
}

function validateForm (whichForm) {
    var reportDiv = arguments[1];
    
//    console.log("form: " + whichForm.name + "");

	var errorMessage = "The following problems occured with the form:\n";
	var separator = "______________________________________________________________";
	
	errorMessage += separator + "\n\n";
	
	var htmlErrorMessage = "";

	var i, j;
	var validContent = 1; //innocent until proven guilty
	var errorCount = 0;
	
	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";
				htmlErrorMessage += "&mdash; " + msg + "<br />";
				++errorCount;
			}
		}
	}
	errorMessage += separator;
	if (!validContent) {
		if (!reportDiv) alert(errorMessage);
		else {
			displayFormErrorMessage("<b>Error.</b> <i>Please correct the following:</i><br />" + htmlErrorMessage, reportDiv);
		}
	}
	else {
		if (reportDiv) {
			hideDiv(reportDiv);
		}
	}
	
	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 != "") {
//				console.log("value: " + 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).";
			}
		}
	}
	
	if (errorMessage != "") {
		addCssClass(elt, "forminputerror");
	}
	
	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();
	}
}

//2011-07
function updateStateSelection (countrySelectId, stateSelectId) {
	var countryField = fixElement(countrySelectId);
	var stateField = fixElement(stateSelectId);
	
	var stateInputFreeFormId = arguments[2];

	var selectedCountryId = 0;
	if (countryField) selectedCountryId = countryField.options[countryField.selectedIndex].value;
	if (selectedCountryId) {
		var statesListToCopy = [];
		statesListToCopy = document.statesByCountryId[selectedCountryId];
		
		if (statesListToCopy && statesListToCopy.length > 0) {
		//there are states to select from
			if (stateInputFreeFormId != null) {
			//reset this, in case it was changed
				showDiv(stateSelectId);
				hideDiv(stateInputFreeFormId);
			}

			//stateField.options = [];
			stateField.options.length = statesListToCopy.length;
			
			for (i = 0; i < statesListToCopy.length; i++) {
				stateField.options[i].value = statesListToCopy[i][0];
				stateField.options[i].text = statesListToCopy[i][1];
			}
		}
		else {
		//there are no states; show the free form entry
			if (stateInputFreeFormId != null) {
				hideDiv(stateSelectId);
				showDiv(stateInputFreeFormId);
			}
		}
	}
}

function switchStates(whichCountryField) {
	//determine the name of the node id we're using
	var i;
	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, whichSubmit) {
	if (!whichSubmit) whichSubmit = 'mySubmit';
	var theSendingDiv = fixElement('sendingDiv');
	var theForm = eval(whichForm);
	if (theForm) var theSubmitBtn = eval("whichForm."+whichSubmit); //using pre getElementById spec... may want to update this but this currently allows for multiple forms to use 'mySubmit' as a name
	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 = "Please wait...";
	}
	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) {
	var respectdisabled = arguments[1] ? arguments[1] : false;
	f = document.getElementById(e);
	if (!f) {
		f = document.getElementsByName(e);
		if (f[0]) f = f[0];
	}
	
	if (f) isdisabled = f.disabled;

	if (f && (!isdisabled || !respectdisabled)) {
		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;
}

function resetSelect (selectField) {
	var i = (arguments[1] ? arguments[1] : 0);
	var field = getElement(selectField);
	//alert('x');
	if (field) {
		//alert("z!");
		field.selectedIndex = i;
	}
	//else alert("don't know what to change");
}

function clearValue (field) {
	var f = getElement(field);
	if (f) f.value = '';
}
