//--Copyright © 1999-2005,A Plus Consultants,LLC,All Rights Reserved.(040523)
//  No part of this script may be used for any purpose without prior
//  written permission. Contact richard@aplusconsultants.com.
/*
	Common JavaScript functions.
	Created: 05/23/2004

	Functions:
	CalcMultiply(sForm, sTgt, iDec, sField1, sField2, sField3)
							- used to multiply a series of numbers.
	ClearFields(oForm)		- used to absolutely clear fields in a search form.
	CopyBillToShip(oForm)	- copy billing address to shipping address.
	IsNumber(sValue)		- determine whether a value is numeric.
	SetProduct				- fill form fields with product information.
	Validate(oForm)			- validates common form rules.
*/

function CalcMultiply(sForm, sTgt, iDec, sField1, sField2, sField3) {
/*
Created:	06/02/2005
Purpose:	
	Multiply a series of numbers and return the result.
Description:
	At least two fields must be supplied to perform a multiplication.
Arguments:
	sForm		- name of form on which to find values.
	sTgt		- name of form field to receive the result.
	iDec		- number of decimal places for the return value.
	sFieldn		- name of form field to multiply.
*/
	var ii = 0;
	var num = 0;
	var nResult = 0;
	var oForm = document.forms[sForm];
	

	if (arguments.length < 5) {
		alert("Not enough values were supplied to perform a calculation.");
	}
	//	Check that all the numeric arguments are valid.
	for (ii = 3; ii < arguments.length; ii++) {
		num = oForm[arguments[ii]].value;
		if (! IsNumber(num)) {
			return;
		}
		if (ii == 3) {
			nResult = num;
		}
		else {
			nResult = nResult * num;
		}
	}

	nResult = Round(nResult, iDec);
	oForm[sTgt].value = nResult;
}

function Round(iValue, iDecimals) {
	var ar = new Array();

	var reRound = /[0-9]+([.][0-9]{1,2})?/gi;
	var sValue = "";
//alert(iValue);
//	iValue = parseInt(iValue * (10 * 10), 10) / (10 * 10);
	iValue = (iValue * (10 * 10)) / (10 * 10);
//alert(parseInt(iValue * (10 * 10), 10));
	sValue = "" + iValue;
	if (sValue.indexOf(".") == -1) {
		sValue = sValue + ".";
	}
	sValue = sValue + "000000";
//	alert(sValue);
//	alert(sValue.match(reRound));
	ar = sValue.match(reRound);
	if (ar == null) {
		alert("Rounding error.");
		iValue = ar;
	}
	else {
		iValue = ar[0];
	}
	return iValue;
}

function ClearFields(oForm) {
/*
	Set all fields to blank, regardless of the default value.
*/
	for (ii = 0; ii < oForm.elements.length; ii++) {
		var oEl = oForm.elements[ii];
		if (oEl.type == "password" || oEl.type == "text" || oEl.type == "textarea") {
			oEl.value = "";
		}
		if (oEl.type == "checkbox" || oEl.type == "radio") {
			oEl.checked = false;
		}
		if (oEl.type == "select-one" || oEl.type == "select-multiple") {
			oEl.selectedIndex = 0;
		}
		//	Set the value for this element to the default.
		if (oEl.name == "MaxRows") {
			oEl.value = oEl.defaultValue;
		}
	}
}

function CopyBillToShip(oForm, sFrom, sTo) {
/*
	Copy the values from the set of bill-to elements to the corresponding
	ship-to elements.
	This is used to make it easy to fill in both billing and shipping
	information on a form.
	Called:	vendororderedit.cfm
*/
	var arAddress = new Array();
	arAddress[0] = "NameBusiness";
	arAddress[1] = "AddressStreet1";
	arAddress[2] = "AddressStreet2";
	arAddress[3] = "AddressCity";
	arAddress[4] = "AddressState";
	arAddress[5] = "AddressPostal";
	arAddress[6] = "AddressCountry";
	arAddress[7] = "Email";
	arAddress[8] = "PhoneVoice";
	for (ii = 0; ii < arAddress.length; ii++) {
		oForm[sTo + arAddress[ii]].value = oForm[sFrom + arAddress[ii]].value;
	}
}

function IsNumber(sValue) {
/*
Created:	06/02/2005
Purpose:	
	Determine whether a value matches the pattern for a valid number.
Description:
	A pattern is used rather than mathematical functions, because
	parseInt and parseFloat examine only the beginning portion of a
	value and, if that portion is numeric, it goes no further, even
	though the balance of the value may not be numeric.
Arguments:
	sValue		- string of characters to examime.
*/
	var reNum = /^[+-]?[0-9]+([.][0-9]+)?$/gi;
	if (sValue.search(reNum) == -1) {
		if (sValue == "") {
			sValue = "blank";
		}
		alert("[" + sValue + "] is not a valid number."); 
		return false;
	}
	return true;
}

function SetProduct(oSelect) {
/*
	Fill in values in a form based on the selection of a select item.
	Called:	vendororderdetail.cfm
*/
	var oForm = oSelect.form;
	var sValue = oSelect.options[oSelect.selectedIndex].value;
	var arVal = sValue.split("|");
	//	The select option value is formatted like this.
	//	Product_id|Cost_at|VendorStock_cd|OrderMinimum_nb
	oForm["Product"].value = arVal[0];
	oForm["Cost"].value = arVal[1];
	oForm["VendorStock"].value = arVal[2];
	oForm["OrderedQty"].value = arVal[3];
	oForm["ExtendedCost"].value = arVal[1] * arVal[3];
}

function ShowHTML(oForm, sCtrl) {
//	alert(sCtrl);
	var W = 500;
	var H = 300;
	var L = 100;
	var T = 100;
	var w = window.open("", "_x", "width=" + W + ",height=" + H + ",left=" + L + ",top=" + T + ",scrollbars=yes,status=no");
	w.document.open();
	w.document.writeln('<html><head><title>Test Display</title><link href="fc_style.css" rel="stylesheet" type="text/css" /></head><body onload="window.focus()">');
	w.document.write(oForm[sCtrl].value);
	w.document.writeln("</body></html>");
	w.document.close();
}

function Validate(oForm) {
/*
Created:	05/28/2004
Purpose:	
	Perform a light-weight client side form validation.
Description:
	This function piggy-backs on ColdFusion's form field validation
	by looking for the hidden ColdFusion input objects and
	performing a similar validation using JavaScript.
Arguments:
	oForm		- form object whose elements are to be validated.

Change History:
06/09/2005: Corrected ii to jj in array loop.
			Added handling for arrays of text boxes.
*/
	var arList = new Array();
	var ii = new Number;
	var jj = new Number;
	var sField = new String;
	var sMsg = new String;	//	Text contained in the hidden CF input object.
	var sName = new String;	//	Name of the form control object.
	for (ii = 0; ii < oForm.elements.length; ii++) {
		sName = oForm[ii].name;
		sMsg = oForm[sName].value;
		//	Process the ColdFusion required value validation input.
		if (sName.indexOf("_required") > 0) {
			sField = sName.substring(0, sName.indexOf("_required"));
			if (oForm[sField].type == "password" || oForm[sField].type == "text" || oForm[sField].type == "textarea") {
				if (oForm[sField].value == "") {
					alert(sMsg);
					return false;
				}
			}
			if (oForm[sField].type == "select-one" || oForm[sField].type == "select-multiple") {
				iPicked = oForm[sField].selectedIndex;
				if (oForm[sField].options[iPicked].value == "") {
					alert(sMsg);
					return false;
				}
			}
			if (oForm[sField].type == "checkbox" || oForm[sField].type == "radio") {
				if (! oForm[sField].checked) {
					alert(sMsg);
					return false;
				}
			}

			//	Handle check boxes, radio buttons, and text boxes in an array.
			if (! oForm[sField].options) {
				if (oForm[sField].length) {
					var bOk = false;
					//	06/09/2005: Corrected ii to jj in following loop.
					for (jj = 0; jj < oForm[sField].length; jj++) {
						if (oForm[sField][jj].checked) {
							bOk = true;
						}
						//	06/09/2005: Added handling for text boxes.
						else {
							if (oForm[sField][jj].type == "text") {
								if (oForm[sField][jj].value == "") {
									//	03/26/2007 Changed handling in connection with Captcha.
									if (sMsg == "") {
										sMsg = "All " + sField + " entries must have a value.";
									}
									break;
								}
								bOk = true;
							}
						}
					}
					if (! bOk) {
						alert(sMsg);
						return false;
					}
				}
			}
		}
		//	Process the ColdFusion date value validation input.
		if (sName.indexOf("_date") > 0) {
			sField = sName.substring(0, sName.indexOf("_date"));
			var sValue = oForm[sField].value;
			var reDate = new RegExp("[0-1][0-9][/][0-3][0-9][/](18|19|20)[0-9]{2}", "gi");
			if (sValue.search(reDate) == -1) {
				alert(sMsg);
				return false;
			}
		}
		//	Process the ColdFusion integer value validation input.
		if (sName.indexOf("_integer") > 0) {
			sField = sName.substring(0, sName.indexOf("_integer"));
			var sValue = oForm[sField].value;
			if (isNaN(sValue)) {
				alert(sMsg);
				return false;
			}
		}
		//	If the form has has a list, make sure it has the right number of elements.
		if (sName.indexOf("_List") > 0) {
			sValue = oForm.elements[ii].value;
			arList[arList.length] = sValue;
			if (sValue == "") {
				alert("All " + sName + " entries must have a value.");
				return false;
			}
			if (isNaN(sValue)) {
				alert("All " + sName + " entries must be numeric.");
				return false;
			}
		//	alert(arList);
		}
	}
	//	If the form has the fields, compare it.
	if (oForm["NamePasswordRepeat"]) {
		if (oForm["NamePassword"].value != oForm["NamePasswordRepeat"].value) {
			alert("Your password and re-entered password don't match. Please retype them.");
			return false;
		}
	}
	return true;
}

/*
Change History:
05/23/2004:	Added ClearFields function.
05/28/2004:	Added Validate function.
05/29/2004:	Added CopyBillToShip and SetProduct function.
06/02/2005:	Added CalcMultiply and IsNumber functions.
06/20/2005:	Corrected Validate function which was returning immediately
			on a validation of a checkbox array.
08/09/2005:	Added ShowHTML function.
03/26/2007:	Changed Validate function in conjunction with captcha. 
*/