gServerStatus = "http://status.cashs.com.au/";
gColourDefault = "#1F2021";
gColourDefaultBackground = "#ffffff";
gColourError = "#851e00";
gColourErrorBackground = "#ffcebf";

function setFieldStyle(inField, inType) {
	switch(inType) {
		case 0:
			//Error
			inField.style.backgroundColor = gColourErrorBackground;
			inField.style.color = gColourError;
			break;
		default:
			//Default
			inField.style.backgroundColor = gColourDefaultBackground;
			inField.style.color = gColourDefault;
			break;
	}
}

//Open a new browser window
function open_page(pageURL, w, h) {
	var MainPage = ""
	//Close window if it exists
	if (MainPage && MainPage.open) {
		MainPage.close();
	}
	//Open new window
	MainPage = window.open(pageURL,'B2B',"width="+w+",height="+h+",resizable=yes,scrollbars=yes,location=no,menubar=no,status=no,toolbar=yes");
}

function mod(div,base) {
	return Math.round(div - (Math.floor(div/base)*base));
}

//Check all checkboxes under selected box
function cascade_check(inCB) {
	chBool = inCB.checked;
	chVal = inCB.value;
	chName = inCB.name;
	totalFields = document.forms[0].elements.length;

	for (i=0; i<totalFields; ++i) {
		currField = document.forms[0].elements[i];
		currFieldname = currField.name;

		if (currFieldname.indexOf(chName) >=0 ){
			currField.checked = chBool;
		}
	}
}

//Reset a select field to index 0
function reset_select(inField) {
	try {
		outField = eval(inField);
	} catch (e) {
		return false;
	}

	if (outField) {
		outField.selectedIndex = 0;
	}

	return true;
}

//Disable a field
function disable_field(inField) {
	inField.disabled = !inField.disabled;

	return true;
}

//Check all checkboxes belonging to the same group
function check_all(inField, inCheck) {
	if (inField.length != undefined) {
		for (var i = 0; i < inField.length; i++) {
			inField[i].checked = inCheck;
		}
	} else {
		inField.checked = inCheck;
	}
	return true;
}

//Load the Xilo payment page
function LoadXilo() {
	if (document.HiddenForm.HasLoaded.value == '0') {
		document.HiddenForm.HasLoaded.value = '1';
		document.PaymentForm.submit();
	}
}

//Mouseover control for menu buttons
function mo(inStatus, inID, inCls, inCls2, inM, inImg, inName) {
	var lmObj, imgObj, rmObj, rmItem
	var lmItem = inName+inID;
	var imgItem = inName+'_i_'+inID;
	if (inCls2 != '') {rmItem = inName+'_r_'+inID;}

	window.status=inStatus;
	
	//set cross-browser DOM
	if (document.all) {
		lmObj = eval("document.all." + lmItem);
		imgObj = eval("document.all." + imgItem);
		if (inCls2 != '') {rmObj = eval("document.all." + rmItem);}
	} else if (document.getElementById) {
		lmObj = eval("document.getElementById('" + lmItem + "')");
		imgObj = eval("document.getElementById('" + imgItem + "')");
		if (inCls2 != '') {rmObj = eval("document.getElementById('" + rmItem + "')");}
	} else {
		lmObj = eval("document." + lmItem);
		imgObj = eval("document." + imgItem);
		if (inCls2 != '') {rmObj = eval("document." + rmItem);}
	}
	//change class
	lmObj.className = inCls;
	if (inCls2 != '') {rmObj.className = inCls2;}
	
	//Change image
	imgObj.src = inImg;
	
	return true;
}

/* Functions for step 1 */
//Change form values on brand slection
function ChangeBrands(inCategory, inCID) {
	document.brandForm.CatName.value = inCategory;
	document.brandForm.CatID.value = inCID;
	selVal = eval("document.brandForm.selectBrand_"+inCID+".value")
	if (selVal != "") {
		document.brandForm.submit();
	}
}

/* Functions for step 2 */
//Change form values on product selection
function SelectProduct(inProductID, inProduct) {
	document.pTypeForm.ProductName.value = inProduct;
	document.pTypeForm.ProductID.value = inProductID;
	document.pTypeForm.submit();
}

/* Cart functions */
//Store form values and redirect to update freight page
function UpdateFreight(inPage, inForm) {
	inForm.buttonsubmit.disabled = true;
	qsPay = escape(inForm.PayType.value);
	qsEmail = escape(inForm.ConEmail.value);
	qsName = escape(inForm.ConName.value);
	qsComments = escape(inForm.Comments.value);
	qsAddress = escape(inForm.AddressID.value);
	qsPriority = escape(inForm.PriorityID.value);
	qsBill = "";
	qsComments2 = escape(inForm.Comments2.value);
	qsPONum = escape(inForm.PurchaseOrderNum.value);
	qsSplitStockType = escape(inForm.SplitStockType.value);

	if (inForm.BillTo) {
		qsBill = escape(inForm.BillTo.value);
	}
	
	//Hard coded message for Own Freight priority
	if (qsPriority == 6) {
		alert('You have selected Own Freight.\nPlease enter your freight details in the\nDelivery Documentation Notes area provided.');
	}

	location.href=inPage+'?aid='+qsAddress+'&prid='+qsPriority+'&p='+qsPay+'&em='+qsEmail+'&n='+qsName+'&b='+qsBill+'&c='+qsComments+'&c2='+qsComments2+'&po='+qsPONum+'&sst='+qsSplitStockType;
}

/* Order History Functions */
//Submit form values for order history sort
function SubmitHistSort() {
	document.FormFilter.submit();
}

/* Step 3 Functions (plus field check functions */
//Refresh form to account for master control fields
function refresh_form(inForm, in_status_string) {
	if (!gAutoBlur) {
		step3_submit_disable(in_status_string);
		inForm.PageRefresh.value = 1;
		inForm.submit();
	}
}

//Test field value for a valid APN
function chk_apn(inField) {
	var fVal = inField.value;
	var fChk = true;
	var fLen = fVal.length;
	var fChkLen = 13;
	var chkA, chkB, chkC
	
	var chkfDig = parseInt(fVal.charAt(fLen-1))

	//Initialise check values
	chkA = 0;
	chkB = 0;
	chkC = 0;
	
	//check APN
	if (fVal != '') {
		//Check APN length
		if (fLen != fChkLen) {
			fChk = false;
		}
		
		//Calculate first check field
		for (i=fChkLen-2; i>=0; i=i-2) {
			chkA = chkA+parseInt(fVal.charAt(i));
		}
		chkA = chkA*3;
		
		//Calculate second check field
		chkB = 0;
		for (i=fChkLen-3; i>=0; i=i-2) {
			chkB = chkB+parseInt(fVal.charAt(i));
		}

		chkC = chkA+chkB+chkfDig
		if (mod(chkC, 10) != 0) {
			fChk = false;
		}
	}

	if (!fChk) {
		setFieldStyle(inField, 0);
		gAutoBlur = false;
		alert('You have entered an invalid APN.\nPlease correct this, or clear the entry to continue.');
		setTimeout(function() {
			inField.focus();inField.select();
		}, 10);
	} else {
		setFieldStyle(inField);
	}
	
	return fChk;
}

//Test field value for a valid keycode
function chk_keycode(inField) {
	var fVal = inField.value;
	var fChk = true;
	var fLen = fVal.length;
	var fChkLen = 3;
	var chkA, chkB, chkC
	
	var chkfDig = parseInt(fVal.charAt(fLen-1))

	//Initialise check values
	chkA = 0;
	chkB = 0;
	chkC = 0;
	
	//check KeyCode
	if (fVal != '') {
		//Check KeyCode length
		if (fLen < fChkLen) {
			fChk = false;
		}
		
		//Calculate first check field
		for (i=fLen-2; i>=0; i=i-2) {
			chkA = chkA+parseInt(fVal.charAt(i));
		}
		chkA = chkA*3;
		
		//Calculate second check field
		chkB = 0;
		for (i=fLen-3; i>=0; i=i-2) {
			chkB = chkB+parseInt(fVal.charAt(i));
		}

		chkC = chkA+chkB+chkfDig
		if (mod(chkC, 10) != 0) {
			fChk = false;
		}
	}

	if (!fChk) {
		setFieldStyle(inField, 0);
		gAutoBlur = false;
		alert('You have entered an invalid keycode.\nPlease correct this, or clear the entry to continue.')
		setTimeout(function() {
			inField.focus();inField.select();
		}, 10);
	} else {
		setFieldStyle(inField);
	}
}

//Test field value for a valid UPC
//inLen = length of UPC input
//inType = whether to check the check digit or create it (0 to check, 1 to create)
function chk_upc_main(inVal, inLen, inType) {
	var outChk = true;
	var fLen = inVal.length;
	var outChkLen = inLen;
	var chkA, chkB, chkC

	if (inType == 1) {
		fLen = fLen+1;
	}
	var chkfDig = parseInt(inVal.charAt(fLen-1))

	//Initialise check values
	chkA = 0;
	chkB = 0;
	chkC = 0;

	//check UPC
	if (inVal != '') {
		//Check UPC length
		if (fLen != outChkLen) {
			outChk = false;
		}

		//Calculate first check field
		for (i=outChkLen-2; i>=0; i=i-2) {
			chkA = chkA+parseInt(inVal.charAt(i));
		}
		chkA = chkA*3;

		//Calculate second check field
		chkB = 0;
		for (i=outChkLen-3; i>=0; i=i-2) {
			chkB = chkB+parseInt(inVal.charAt(i));
		}

		if (inType == 1) {
			outChk = 10-mod(chkA+chkB, 10);
			if (outChk == 10) { outChk = 0; }
		} else {
			chkC = chkA+chkB+chkfDig
			if (mod(chkC, 10) != 0) {
				outChk = false;
			}
		}
	}

	return outChk;
}

function chk_upc(inField) {
	var upcLength = 12;
	var fVal = inField.value;

	if (chk_upc_main(fVal, upcLength, 0) != true) {
		setFieldStyle(inField, 0);
		gAutoBlur = false;
		alert('You have entered an invalid UPC.\nPlease correct this, or clear the entry to continue.')
		setTimeout(function() {
			inField.focus();inField.select();
		}, 10);
	} else {
		setFieldStyle(inField);
	}
}

//Check for a valid DPCI field
function chk_dpci(inField) {
	var upcLength = 14;
	var fPrefix = '7049';
	var fChkLen = 9;
	
	var fVal = inField.value;
	var fChk = true;
	var fLen = fVal.length;
	var fLineNum = inField.name.substring(0, inField.name.indexOf('_'));
	var chkA;

	//Initialise check values
	chkA = 0;

	//check APN
	if (fVal != '') {
		//Check DPCI length
		if (fLen != fChkLen) {
			fChk = false;
		}
		if (!parseInt(fVal)) {
			fChk = false;
		}
	}

	if (!fChk) {
		setFieldStyle(inField, 0);
		gAutoBlur = false;
		alert('You have entered an invalid DPCI.\nPlease correct this, or clear the entry to continue.')
		setTimeout(function() {
			inField.focus();inField.select();
		}, 10);
	} else {
		setFieldStyle(inField);
	}

	var currName = "";
	var currField = "";
	
	//Cycle through all fields, matching line number and DPCI hidden field
	for (var i = 0; i<document.addToCartForm.elements.length; i++) {
		currField = document.addToCartForm.elements[i];
		currName = currField.name;
		currLineNum = currName.substring(0, inField.name.indexOf('_'));
		//If found same line/DPCI field, enter generated number
		if (currLineNum == fLineNum && currName.indexOf('DPCI_H_') > 0) {
			upcCheck = chk_upc_main(fPrefix+fVal, upcLength, 1);
			if (!fChk || fVal == '') {
				currField.value = '';
			} else {
				currField.value = fPrefix+fVal+upcCheck;
			}
		}
	}
}

//Check for a valid UPC Shipping label field
function chk_upcship(inField) {
	var upcLength = 14;
	var fPrefix = '10';
	var fChkLen = 12;
	
	var fVal = inField.value;
	var fChk = true;
	var fLen = fVal.length;
	var fLineNum = inField.name.substring(0, inField.name.indexOf('_'));
	var chkA;

	//Initialise check values
	chkA = 0;

	//check APN
	if (fVal != '') {
		//Check DPCI length
		if (fLen != fChkLen) {
			fChk = false;
		}
		if (!parseInt(fVal)) {
			fChk = false;
		}
	}

	if (!fChk) {
		setFieldStyle(inField, 0);
		gAutoBlur = false;
		alert('You have entered an invalid UPC Shipping Label.\nPlease correct this, or clear the entry to continue.')
		setTimeout(function() {
			inField.focus();inField.select();
		}, 10);
	} else {
		setFieldStyle(inField);
	}

	var currName = "";
	var currField = "";
	
	//Cycle through all fields, matching line number and UPC hidden field
	for (var i = 0; i<document.addToCartForm.elements.length; i++) {
		currField = document.addToCartForm.elements[i];
		currName = currField.name;
		currLineNum = currName.substring(0, inField.name.indexOf('_'));
		//If found same line/UPC field, enter generated number
		if (currLineNum == fLineNum && currName.indexOf('UPC_H_') > 0) {
			upcCheck = chk_upc_main(fPrefix+fVal.substring(0, fLen-1), upcLength, 1);
			if (!fChk || fVal == '') {
				currField.value = '';
			} else {
				currField.value = fPrefix+fVal.substring(0, fLen-1)+upcCheck;
//				alert(currField.value);
			}
		}
	}
}

//Converts value of infield to Uppercase lettering
function chk_allcaps(inField) {
	inField.value = inField.value.toUpperCase();
}

//Check if a string is valid monetary
function chk_monetary(inField, inStatusZero) {
	var outRegExp = /^\d*\.?\d+$/;
	outstatus = true;
	
	if (inField.value != "" && !inField.value.toString().match(outRegExp)) {
		setFieldStyle(inField, 0);
		gAutoBlur = false;
		alert("An invalid input was detected in the highlighted field below.\n\nNote the monetary field accepts only:\nNumeric 0 to 9\n. (Full stop)\n\nPlease delete and re-enter the value.");
		outstatus = false;
		setTimeout(function() {
			inField.focus();inField.select();
		}, 10);
	} else {
		setFieldStyle(inField);
		//Remove trailing zeroes
		if (inStatusZero) {
			var outRegExp = new RegExp(/.00$/);
			inField.value = inField.value.replace(outRegExp, "");
		}
	}
	
	return outstatus;
}

//Check if a string contains invalid characters
function chk_characters(inField, inCharacters) {
	//Fix reg exp characters
	var outCharacters = inCharacters;
	outCharacters = outCharacters.replace("\[", "\\[");
	outCharacters = outCharacters.replace("\]", "\\]");

	var outRegExp = new RegExp("["+outCharacters+"]");
	outstatus = true;

	if (outRegExp.test(inField.value.toString())) {
		setFieldStyle(inField, 0);
		gAutoBlur = false;
		alert("An invalid character was detected in the highlighted field below.\n\nNote this field does not accept the following characters:\n"+inCharacters+"\n\nPlease remove the offending characters before proceding.");
		outstatus = false;
		setTimeout(function() {
			inField.focus();inField.select();
		}, 10);
	} else {
		setFieldStyle(inField);
	}

	return outstatus;
}

//Check if a string contains invalid characters
function chk_characters_base(inField) {
	var out_characters = /[^a-zA-Z0-9 +-.,:;'\"`\/(){}~!@#$%\^&=_<>?\*\[\]\\]/g;
	//Can get open square brackets - but not close
	var outRegExp = new RegExp(out_characters);	
	outstatus = true;

	if (inField.value.match(outRegExp)) {
		setFieldStyle(inField, 0);
		inField.value = inField.value.replace(outRegExp, "");
		gAutoBlur = false;
		alert("An invalid character was detected and removed in the highlighted field below.\n\nNote this field only accepts following characters:\na-z A-Z 0-9 + - . , : ; ' \" ` / ( ) { } ~ ! @ # $ % \ ^ & = _ < > ? * [ ] \\\n\nPlease check the updated value before continuing.");
		outstatus = false;
		setTimeout(function() {
			inField.focus();inField.select();
		}, 10);
	} else {
		setFieldStyle(inField);
	}

	return outstatus;
}

//Disable the step 3 submit buttons
function step3_submit_disable(in_status_string) {
	step3_submit_toggle(true, in_status_string);
}

//Enable the step 3 submit buttons
function step3_submit_enable() {
	step3_submit_toggle(false);
}

function step3_submit_toggle(in_status, in_status_string) {
	if (document.addToCartForm.UpdateCartButton) {
		document.addToCartForm.UpdateCartButton.disabled = in_status;
		if (in_status_string) {
			document.addToCartForm.UpdateCartButton.value = in_status_string;
		}
	}
	if(document.addToCartForm.AddToCartButton) {
		document.addToCartForm.AddToCartButton.disabled = in_status;
		if (in_status_string) {
			document.addToCartForm.AddToCartButton.value = in_status_string;
		}
	}
	if (document.addToCartForm.ButtonSubmit) {
		document.addToCartForm.ButtonSubmit.disabled = in_status;
		if (in_status_string) {
			document.addToCartForm.ButtonSubmit.value = in_status_string;
		}
	}
	if (document.addToCartForm.AddFieldButton) {
		document.addToCartForm.AddFieldButton.disabled = in_status;
		if (in_status_string) {
			document.addToCartForm.AddFieldButton.value = in_status_string;
		}
	}
}

//Converts value of infield to Uppercase lettering
function chk_boxquantity(inField) {
	step3_submit_disable();
	
	var fVal = inField.value;
	var fBoxQuantity = document.addToCartForm.ProdBoxQuantity.value;

	if (mod(fVal, fBoxQuantity) != 0) {
		alert('This product is only available in multiples of '+fBoxQuantity);
		inField.value = Math.ceil(fVal/fBoxQuantity)*fBoxQuantity;
		setTimeout(function() {
			inField.focus();inField.select();gAutoBlur = false;
		}, 10);
	}
	
	step3_submit_enable();
}

//Checks field value, makes sure it is not less than the input value
function chk_minval(inField, inVal) {
	step3_submit_disable();
	
	var fVal = inField.value;
	if (fVal < inVal && inVal != '' && fVal != '') {
		alert('This product has a minimum quantity of '+inVal);
		inField.value = inVal;
		setTimeout(function() {
			inField.focus();inField.select();gAutoBlur = false;
		}, 10);
	} else if (fVal < 0) {
		alert('Negative quantities are not permitted.');
		inField.value = inVal;
		setTimeout(function() {
			inField.focus();inField.select();gAutoBlur = false;
		}, 10);
	}
	
	step3_submit_enable();
}

function toggleHideFilter(inTarget, inStatus) {
	instatus = 'hide';
	
	if (document.getElementById && document.getElementById[0]) {
		//For Netscape Browsers
		obj = document.getElementById;

		for (i=0; i<obj.length; i++) {
			if (obj.item(i).id.indexOf(inTarget) > -1) {
	 			toggleHide(obj.item(i).id, inStatus);
			}
		}
	} else if(document.all) {
		//For IE browsers
		obj = document.all;
	
		for (var j=0; j<obj.length; j++) {
			if (obj.item(j).id.indexOf(inTarget) > -1) {
				if ((obj.item(j).style.display == 'none' && inStatus != 'hide') || inStatus == 'show') {
					obj.item(j).style.display = ''
				} else {
					obj.item(j).style.display = 'none'
				}
			}
		}
	} else if (document.getElementsByTagName) {
		elementList = new Array('div', 'tr', 'td');
		
		for (var i=0; i<elementList.length; i++) {
			obj = document.getElementsByTagName(elementList[i]);

			for (var j=0; j<obj.length; j++) {
				if (obj.item(j).id.indexOf(inTarget) > -1) {
					if ((obj.item(j).style.display == 'none' && inStatus != 'hide') || inStatus == 'show') {
						obj.item(j).style.display = ''
					} else {
						obj.item(j).style.display = 'none'
					}
				}
			}
		}
	}
}

//Used to hide table cells
function toggleHide(inTarget, inStatus) {
	if (document.getElementById && document.getElementById[0]) {
		//For Netscape Browsers
		obj = document.getElementById;
		alert(obj);

		for (i=0; i<obj.length; i++) {
			if (obj.id) {
				if ((obj.style.display == 'none' && inStatus != 'hide') || inStatus == 'show') {
					obj.style.display = 'block'
				} else {
					obj.style.display = 'none'
				}
			}
		}
	} else if(document.all && document.all(inTarget)) {
		//For IE browsers
		obj = document.all(inTarget);

		if (obj.length == undefined) {
			if ((obj.style.display == 'none' && inStatus != 'hide') || inStatus == 'show') {
				obj.style.display = 'block'
			} else {
				obj.style.display = 'none'
			}
		} else {
			//Fixes problem where only a single object is found
			for (var i=0; i<obj.length; i++) {
				if ((obj(i).style.display == 'none' && inStatus != 'hide') || inStatus == 'show') {
					obj(i).style.display = 'block';
				} else {
					obj(i).style.display = 'none';
				}
			}
		}
	} else if (document.getElementsByTagName) {
		elementList = new Array('div', 'tr', 'td');
		
		for (var i=0; i<elementList.length; i++) {
			obj = document.getElementsByTagName(elementList[i]);

			for (var j=0; j<obj.length; j++) {
				if (obj.item(j).id == inTarget) {
					if ((obj.item(j).style.display == 'none' && inStatus != 'hide') || inStatus == 'show') {
						obj.item(j).style.display = ''
					} else {
						obj.item(j).style.display = 'none'
					}
				}
			}
			
		}
	}
}

//Disable enter key in form submission
function handleEnter(field, event) {
	var keyCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
	if (keyCode == 13) {
		field.blur();
		return false;
	} else {
		return true;
	}
}      

//UI Label Functions
/* Functions for step 2 */
//Change form values on product selection
function setField(inField, inValue) {
	inField.value = inValue;
}

function submitbutton(inFormName, inTask) {
	if (document[inFormName].FormTask != undefined) {
		eval("document."+inFormName+".FormTask.value='"+inTask+"';");
	} else {
		eval("document."+inFormName+".task.value='"+inTask+"';");
	}
	
	eval("document."+inFormName+".submit();");
}

//Executes the submitbutton function when the user hits Enter
function submitbuttondisable_enter(inEvent, inFormName, inTask, inButton, inTextReplace) {
	var keycode;
	
	if (window.event) {
		keycode = window.event.keyCode;
	} else if (inEvent) {
		keycode = inEvent.which;
	} else {
		return true;
	}

	if (keycode == 13) {
	   submitbuttondisable(inFormName, inTask, inButton, inTextReplace);
	   return false;
	} else {
	   return true;
	}
}

function submitbuttondisable(inFormName, inTask, inButton, inTextReplace) {	
	disablebutton(inFormName, inButton, inTextReplace);
	submitbutton(inFormName, inTask);
}

function disablebutton(inFormName, inButton, inTextReplace) {
	if (inTextReplace) {
		eval("document."+inFormName+"['"+inButton+"'].value = '"+inTextReplace+"';");
	}
	eval("document."+inFormName+"['"+inButton+"'].disabled = true;");
}

function buttonstatus(inIDButton, inTextReplace, inStatus) {
	$(inIDButton).disabled = !inStatus;
	$(inIDButton).value = inTextReplace;
}

function enablebutton(inFormName, inButton, inTextReplace) {
	if (inTextReplace) {
		eval("document."+inFormName+"."+inButton+".value = '"+inTextReplace+"';");
	}
	eval("document."+inFormName+"."+inButton+".disabled = false;");
}

function submitFilterForm(inPvs) {
	document.filterForm.pvs.value = inPvs;
	
	//Turn order into an array
	inField = document.newOrderForm.order;
	if (inField) {
		oidField = document.filterForm.oid;
		oidRemField = document.filterForm.oidRem;


		for (i = 0; i < inField.length; i++) {
			currVal = inField[i].value;
			if (inField[i].checked) {
				oidField.value = currVal+','+oidField.value;
			} else {
				oidRemField.value = currVal+','+oidRemField.value;
			}
		}
	}
	document.filterForm.submit();
}

//String Functions
//Test if a string is alpha-numeric
function is_alphanumeric(inString) {
	var outStatus = false;
	var outString = inString.toUpperCase();

	var outChars = "AZ09";
	var outCharCode_A = outChars.charCodeAt(0);
	var outCharCode_Z = outChars.charCodeAt(1);
	var outCharCode_0 = outChars.charCodeAt(2);
	var outCharCode_9 = outChars.charCodeAt(3);
	
	for (var i=0; i<outString.length; i++) {
		outCharCode = outString.charCodeAt(i);

		if ((outCharCode >= outCharCode_0 && outCharCode <= outCharCode_9) ||
			(outCharCode >= outCharCode_A && outCharCode <= outCharCode_Z)) {
			outStatus = true;
		} else {
			outStatus = false;
		}
	}

	return outStatus;
}

//Test if a string is alphabetic
function is_alpha(inString) {
	var outStatus = true;
	var outString = inString.toUpperCase();

	var outChars = "AZ";
	var outCharCode_A = outChars.charCodeAt(0);
	var outCharCode_Z = outChars.charCodeAt(1);
	
	for (var i=0; i<outString.length; i++) {
		outCharCode = outString.charCodeAt(i);

		if (outCharCode < outCharCode_A || outCharCode > outCharCode_Z) {
			//That's bad
			outStatus = false;
		}
	}

	return outStatus;
}

//Test if a string is numeric
function is_numeric(inString) {
	var outStatus = true;
	var outString = inString;

	var outChars = "09";
	var outCharCode_0 = outChars.charCodeAt(0);
	var outCharCode_9 = outChars.charCodeAt(1);
	
	for (var i=0; i<outString.length; i++) {
		outCharCode = outString.charCodeAt(i);

		if (outCharCode < outCharCode_0 || outCharCode > outCharCode_9) {
			//That's bad
			outStatus = false;
		}
	}

	return outStatus;
}

//Copy the value of one field to another
function copy_field(inSourceField, inTargetField, inReplace) {
	if ((inTargetField.value == "" || inReplace)) {
		inTargetField.value = inSourceField.value;
	}
}

function submitFormSearch(inRecordStart) {
	if (document.FormSearch.pageViewStart != undefined) {
		document.FormSearch.pageViewStart.value = inRecordStart;
	} else {
		document.FormSearch.RecordStart.value = inRecordStart;
	}

	//Turn persistent ID's into an array
	inField = document.FormSearch.IDPersistToAdd;
	if (inField) {
		outFieldIDPersistToAdd = document.FormSearch.IDPersistToAdd;
		outFieldIDPersistToRemove = document.FormSearch.IDPersistToRemove;

		for (i = 0; i < inField.length; i++) {
			currVal = inField[i].value;
			if (inField[i].checked) {
				outFieldIDPersistToAdd.value = currVal+','+outFieldIDPersistToAdd.value;
			} else {
				outFieldIDPersistToRemove.value = currVal+','+outFieldIDPersistToRemove.value;
			}
		}
	}
	document.FormSearch.submit();
}

function submitFormFilter(inPageViewStart) {
	document.FormFilter.pageViewStart.value = inPageViewStart;

	document.FormFilter.submit();
}

function toggleHideSection(inTarget) {
		Effect.toggle(inTarget, "blind", {duration: 0.5});
}

function toggleHidePopup(inTarget) {
		Effect.toggle(inTarget, "appear", {duration: 0.5});
}

function toggleHideMulti(inIDElement) {
	//Get all elements
	var outElements = $$('[id^="'+inIDElement+'"]');
	outElements.invoke('toggle');
}

function submitbuttonsearch(inFormName, inFieldName, inRecordStart) {
	eval("document."+inFormName+"."+inFieldName+".value='"+inRecordStart+"';");
	eval("document."+inFormName+".submit();");
}

var gAutoBlur = false;
function blurAllFields(inForm) {
	gAutoBlur = true;
	outStatus = true;
	
	//Blur all fields to activate validity checks
	for (var i = 0; i < inForm.elements.length; i++) {
		if (gAutoBlur && inForm.elements[i].onblur) {
			inForm.elements[i].onblur();
		}
	}
	
	//If a function turned it off, means there was an error
	if (gAutoBlur == false) {
		outStatus = false;
	} else {
		gAutoBlur = false;
	}
	
	
	return true;
}

function getObject(inType, inID) {
	var outObject;

	if (document.all) {
		//for IE browsers
		outObject = document.all(inID);
	} else if (document.getElementById(inID).length != undefined) {
		//For opera & netscape browsers
		outObject = document.getElementById(inID);
	} else {
		//For firefox browser
		outObject = document.getElementsByTagName(inType);
		var outObjectLength = outObject.length;
		
		for (var i=0; i<outObjectLength; i++) {
			if (outObject[i] && outObject[i].id == inID) {
				outObject = outObject.item(i);
			}
		}
	}
	
	return outObject;
}

function openMenuTopContent(in_id) {
	Effect.BlindRight(in_id, {duration: 0.5});
}

function closeMenuTopContent(in_id) {
	Effect.BlindLeft(in_id, {duration: 0.5});
}

function isenter(inEvent) {
	var keycode;

	if (window.event) {
		keycode = window.event.keyCode;
	} else if (inEvent) {
		keycode = inEvent.which;
	} else {
		return true;
	}

	if (keycode == 13) {
	   return true;
	} else {
	   return false;
	}
}

function parseBool(inValue) {
	outStatus = false;

	if (inValue.toLowerCase() == "true" || inValue == true || parseInt(inValue) == 1) {
		outStatus = true;
	}
	
	return outStatus;
}

function check_group(inIDElement, inStatus) {
	//Get all elements
	var outElements = $$('input[id^="'+inIDElement+'"]');
	outElements.invoke('writeAttribute', 'checked', inStatus);
}

function get_group_value(inIDElement) {
	//Get all elements
	var outElements = $$('input:checked[id^="'+inIDElement+'"]');
	return outElements.pluck('value');
}

function get_group_value_name(inNameElement) {
	//Get all elements
	var outElements = $$('input:checked[name^="'+inNameElement+'"]');
	return outElements.pluck('value');
}

function get_group_element(inTypeElement, inIDElement) {
	//Get all elements of a particular type
	var outElements = $$(inTypeElement+'[id^="'+inIDElement+'"]');
	return outElements;
}

//Strip HTML from a string
String.prototype.stripHTML = function() {
	outString = this;
	
	//Replace html spaces
//	outString = outString.replace("&nbsp;", " ");
	
	//Match all HTML tags
	var outRegularExpression = /<(?:.|\s)*?>/g;
	
	//Remove the tags
	outString = outString.replace(outRegularExpression, "");
	
	return outString;
};

//http://github.com/kvz/phpjs/raw/master/functions/strings/get_html_translation_table.js
function get_html_translation_table (table, quote_style) {
    // http://kevin.vanzonneveld.net
    // +   see website for revitions
    // +      input by: Ratheous
    // %          note: It has been decided that we're not going to add global
    // %          note: dependencies to php.js, meaning the constants are not
    // %          note: real constants, but strings instead. Integers are also supported if someone
    // %          note: chooses to create the constants themselves.
    // *     example 1: get_html_translation_table('HTML_SPECIALCHARS');
    // *     returns 1: {'"': '&quot;', '&': '&amp;', '<': '&lt;', '>': '&gt;'}
    
    var entities = {}, hash_map = {}, decimal = 0, symbol = '';
    var constMappingTable = {}, constMappingQuoteStyle = {};
    var useTable = {}, useQuoteStyle = {};
    
    // Translate arguments
    constMappingTable[0]      = 'HTML_SPECIALCHARS';
    constMappingTable[1]      = 'HTML_ENTITIES';
    constMappingQuoteStyle[0] = 'ENT_NOQUOTES';
    constMappingQuoteStyle[2] = 'ENT_COMPAT';
    constMappingQuoteStyle[3] = 'ENT_QUOTES';

    useTable       = !isNaN(table) ? constMappingTable[table] : table ? table.toUpperCase() : 'HTML_SPECIALCHARS';
    useQuoteStyle = !isNaN(quote_style) ? constMappingQuoteStyle[quote_style] : quote_style ? quote_style.toUpperCase() : 'ENT_COMPAT';

    if (useTable !== 'HTML_SPECIALCHARS' && useTable !== 'HTML_ENTITIES') {
        throw new Error("Table: "+useTable+' not supported');
        // return false;
    }

    entities['38'] = '&amp;';
    if (useTable === 'HTML_ENTITIES') {
        entities['160'] = '&nbsp;';
        entities['161'] = '&iexcl;';
        entities['162'] = '&cent;';
        entities['163'] = '&pound;';
        entities['164'] = '&curren;';
        entities['165'] = '&yen;';
        entities['166'] = '&brvbar;';
        entities['167'] = '&sect;';
        entities['168'] = '&uml;';
        entities['169'] = '&copy;';
        entities['170'] = '&ordf;';
        entities['171'] = '&laquo;';
        entities['172'] = '&not;';
        entities['173'] = '&shy;';
        entities['174'] = '&reg;';
        entities['175'] = '&macr;';
        entities['176'] = '&deg;';
        entities['177'] = '&plusmn;';
        entities['178'] = '&sup2;';
        entities['179'] = '&sup3;';
        entities['180'] = '&acute;';
        entities['181'] = '&micro;';
        entities['182'] = '&para;';
        entities['183'] = '&middot;';
        entities['184'] = '&cedil;';
        entities['185'] = '&sup1;';
        entities['186'] = '&ordm;';
        entities['187'] = '&raquo;';
        entities['188'] = '&frac14;';
        entities['189'] = '&frac12;';
        entities['190'] = '&frac34;';
        entities['191'] = '&iquest;';
        entities['192'] = '&Agrave;';
        entities['193'] = '&Aacute;';
        entities['194'] = '&Acirc;';
        entities['195'] = '&Atilde;';
        entities['196'] = '&Auml;';
        entities['197'] = '&Aring;';
        entities['198'] = '&AElig;';
        entities['199'] = '&Ccedil;';
        entities['200'] = '&Egrave;';
        entities['201'] = '&Eacute;';
        entities['202'] = '&Ecirc;';
        entities['203'] = '&Euml;';
        entities['204'] = '&Igrave;';
        entities['205'] = '&Iacute;';
        entities['206'] = '&Icirc;';
        entities['207'] = '&Iuml;';
        entities['208'] = '&ETH;';
        entities['209'] = '&Ntilde;';
        entities['210'] = '&Ograve;';
        entities['211'] = '&Oacute;';
        entities['212'] = '&Ocirc;';
        entities['213'] = '&Otilde;';
        entities['214'] = '&Ouml;';
        entities['215'] = '&times;';
        entities['216'] = '&Oslash;';
        entities['217'] = '&Ugrave;';
        entities['218'] = '&Uacute;';
        entities['219'] = '&Ucirc;';
        entities['220'] = '&Uuml;';
        entities['221'] = '&Yacute;';
        entities['222'] = '&THORN;';
        entities['223'] = '&szlig;';
        entities['224'] = '&agrave;';
        entities['225'] = '&aacute;';
        entities['226'] = '&acirc;';
        entities['227'] = '&atilde;';
        entities['228'] = '&auml;';
        entities['229'] = '&aring;';
        entities['230'] = '&aelig;';
        entities['231'] = '&ccedil;';
        entities['232'] = '&egrave;';
        entities['233'] = '&eacute;';
        entities['234'] = '&ecirc;';
        entities['235'] = '&euml;';
        entities['236'] = '&igrave;';
        entities['237'] = '&iacute;';
        entities['238'] = '&icirc;';
        entities['239'] = '&iuml;';
        entities['240'] = '&eth;';
        entities['241'] = '&ntilde;';
        entities['242'] = '&ograve;';
        entities['243'] = '&oacute;';
        entities['244'] = '&ocirc;';
        entities['245'] = '&otilde;';
        entities['246'] = '&ouml;';
        entities['247'] = '&divide;';
        entities['248'] = '&oslash;';
        entities['249'] = '&ugrave;';
        entities['250'] = '&uacute;';
        entities['251'] = '&ucirc;';
        entities['252'] = '&uuml;';
        entities['253'] = '&yacute;';
        entities['254'] = '&thorn;';
        entities['255'] = '&yuml;';
    }

    if (useQuoteStyle !== 'ENT_NOQUOTES') {
        entities['34'] = '&quot;';
    }
    if (useQuoteStyle === 'ENT_QUOTES') {
        entities['39'] = '&#39;';
    }
    entities['60'] = '&lt;';
    entities['62'] = '&gt;';


    // ascii decimals to real symbols
    for (decimal in entities) {
        symbol = String.fromCharCode(decimal);
        hash_map[symbol] = entities[decimal];
    }
    
    return hash_map;
}

//http://github.com/kvz/phpjs/raw/master/functions/strings/html_entity_decode.js
function html_entity_decode (string, quote_style) {
    // http://kevin.vanzonneveld.net
    // +   original by: john (http://www.jd-tech.net)
    // +   see website for revisions
    // -    depends on: get_html_translation_table
    // *     example 1: html_entity_decode('Kevin &amp; van Zonneveld');
    // *     returns 1: 'Kevin & van Zonneveld'
    // *     example 2: html_entity_decode('&amp;lt;');
    // *     returns 2: '&lt;'

    var hash_map = {}, symbol = '', tmp_str = '', entity = '';
    tmp_str = string.toString();
    
    if (false === (hash_map = this.get_html_translation_table('HTML_ENTITIES', quote_style))) {
        return false;
    }

    // fix &amp; problem
    // http://phpjs.org/functions/get_html_translation_table:416#comment_97660
    delete(hash_map['&']);
    hash_map['&'] = '&amp;';

    for (symbol in hash_map) {
        entity = hash_map[symbol];
        tmp_str = tmp_str.split(entity).join(symbol);
    }
    tmp_str = tmp_str.split('&#039;').join("'");
    
    return tmp_str;
}
