/**
 * Title: Input Comparison
 * Purpose: Compares the selected values of a ranged input against the parameter array.
 **/
function inputRangeComparison(input, acceptableValues) {
    var selectedValuesArray = Array();
    if (input.length == 0) {
        return;
    }
    var j =0;
    // Get the currently selected value for this input
    if (input.type == "select-one" || input.type == "select-multiple") {
        selectedValuesArray[0] = input.options[input.selectedIndex].value;
    } else if (input[0].type == "checkbox" || input[0].type == "radio") {
        for (var i = 0; i < input.length; i++) {
            if (input[i].checked == true) {
                if (input[i].checked == true) {
                    selectedValuesArray[j] = input[i].value;
                    j++;
                }
            }
        }
    }
    // Cycle through all the acceptable values to check for a match
    for (var i=0; i < acceptableValues.length; i++) {

        for (var k=0; k <selectedValuesArray.length; k++){
            var selectedValue = selectedValuesArray[k];

            if (acceptableValues[i] == selectedValue) {
                return true;
            }
        }
    }
    return false;
}


/**
 * Title: Rfq Form Dynamic Radio/Checkbox Values
 * Purpose: Depending on the value selected in a master select input, we change the visible slave radio/checkboxes.
 * This script is used in conjunction with a set of JavaScript arrays setup in the main code base. See MenuScript.java.
 * @author Paul Deason 06/04/06
 **/
function showRadioCheckboxSlaves(masterInput, slaveInputId, slaveValuesUniqueIdentifier) {
    var slaveArray = document.forms['frmBody'].elements["attr" + slaveInputId];
    var selectedSlaveValues = new Array();
    // Single checkbox
    if (isNaN(slaveArray.length)) {
        selectedSlaveValues[0] = slaveArray.value;
    // Multiple checkboxes
    } else {
        for (var i=0; i < slaveArray.length; i++) {
            if (slaveArray[i].checked) {
                selectedSlaveValues[i] = slaveArray[i].value;
            }
        }
    }
    var masterSelectedIndex = masterInput.selectedIndex;
    if (masterSelectedIndex != 0) {
        var masterSelectedArv = '';
        if (masterSelectedIndex >= 0) {
            masterSelectedArv = masterInput.options[masterSelectedIndex].value;
        }
        var optionIndexes = eval('window.slaveOptionIndexes_' + slaveValuesUniqueIdentifier + '_' + masterSelectedArv);
        if (optionIndexes == null) return;
        // Cycle through the new values and set them to visible
        var optionValues = eval('slaveValues_' + slaveValuesUniqueIdentifier);
        var containerId = "container_chkb" + slaveInputId;
        var tableContainer = document.getElementById(containerId);
        var tableRows = tableContainer.rows.length;
        for (var i=0; i < tableRows; i++) {
            tableContainer.deleteRow(0);
        }
        for (var i = 0; i < optionIndexes.length; i++) {
            var newOption = optionValues[optionIndexes[i]];
            // Check the box if necessary
            var isChecked = "";
            for (var j=0; j < selectedSlaveValues.length; j++) {
                if (selectedSlaveValues[j] == newOption.value) {
                    isChecked = "checked";
                    break;
                }
            }
            var newRow = tableContainer.insertRow(i);
            var inputCell = newRow.insertCell(0);
            inputCell.innerHTML = "<input name=\"attr" + slaveInputId + "\" type=\"checkbox\" value=\"" + newOption.value + "\" " + isChecked + " />";
            var textCell = newRow.insertCell(1);
            textCell.innerHTML = newOption.text;
        }
    }
}


/**
 * Title: Rfq Form Dynamic Select Options
 * Purpose: Depending on the value selected in a master input, we change the option values in a slave input.
 * This script is used in conjunction with a set of JavaScript arrays setup in the main code base. See MenuScript.java.
 * @author Paul Deason 06/03/06
 **/
function populateSlaveOptionValues(masterInput, slaveInput, slaveValuesUniqueIdentifier) {
    var slaveSelectedArv = '';
    if (slaveInput.selectedIndex >= 0) {
        slaveSelectedArv = slaveInput.options[slaveInput.selectedIndex].value;
    }
    var masterSelectedIndex = masterInput.selectedIndex;
    slaveInput.options.length = 0;
    if (masterSelectedIndex == 0) {
        slaveInput.options[0] = new Option('','');
    } else {
        var masterSelectedArv = '';
        if (masterSelectedIndex >= 0) {
            masterSelectedArv = masterInput.options[masterSelectedIndex].value;

            // escape white space characters
            masterSelectedArv= masterSelectedArv.replace('\/','');            
            masterSelectedArv= masterSelectedArv.replace(' ','_');
        }

        var optionIndexes = eval('window.slaveOptionIndexes_' + slaveValuesUniqueIdentifier + '_' + masterSelectedArv);
        if (optionIndexes == null) return;
        // Cycle through the new options and set them in the slave input
        slaveInput.options[0] = new Option('Please select','');
        var optionValues = eval('slaveValues_' + slaveValuesUniqueIdentifier);
        for (var i = 0; i < optionIndexes.length; i++) {
            var newOption = new Option(optionValues[optionIndexes[i]].text, optionValues[optionIndexes[i]].value);
            newOption.title = optionValues[optionIndexes[i]].text;
            slaveInput.options[i + 1] = newOption
            if (slaveSelectedArv == newOption.value) {
                slaveInput.options[i + 1].selected = true;
            }
        }
    }
    if (slaveInput.options.length == 2 && slaveInput.options[1].text == "Not Required") {
        slaveInput.selectedIndex = 1;
        slaveInput.disabled = true;
    }
    else {
        slaveInput.disabled = false;
    }
}

/**
 * @requires util_h.js
 * @requires util_cc.js
 */
// HELLO
function changeTagStyle(tagID, tag, style, resetValues) {
   if (!(document.all || document.getElementById)) {
      return;
   }
   if (tagID == null) {
      return;
   }


   var tagArray = null;
   if (document.all) {
      tagArray = document.all.tags(tag);
   } else if (document.getElementsByTagName(tag)) {
      tagArray = document.getElementsByTagName(tag);
   } else {
      return;
   }
   for (var i = 0; i < tagArray.length; i++) {
      var elRow = tagArray[i];
      if (elRow != null) {
         if ((elRow.id != null) && (elRow.id.indexOf(tagID) >= 0)) {
            elRow.style.display = style;
            if (style == "none") {
               // deactivate any form elements
               if ( resetValues ){
                   if (document.getElementsByTagName) {
                      var inputElements = elRow.getElementsByTagName("input");
                      for (var j = 0; j < inputElements.length; j++) {
                         var tmpInputElement = inputElements[j];
                         if (tmpInputElement.type == "checkbox" || tmpInputElement.type == "radio") {
                             tmpInputElement.checked = false;
                         } else if (tmpInputElement.type == "text") {
                            tmpInputElement.value = '';
                         }
                      }
                      var selectElements = elRow.getElementsByTagName("select");
                      for (var j = 0; j < selectElements.length; j++) {
                         var tmpSelectElement = selectElements[j];
                         tmpSelectElement.selectedIndex = 0;
                      }
                   }
                }
            }

         }
      }
   }
}

function hideTag(tagID, tag, resetValues) {
    changeTagStyle(tagID, tag, "none", resetValues);
}

function displayTag(tagID, tag, resetValues) {
	changeTagStyle(tagID, tag, "", resetValues);
}

function setAllRadioButtons(_form, _value) {
	return setAllRadioButtons(_form, _value, false, new Array(0));
}
function setAllRadioButtons(_form, _value, _submit) {
	return setAllRadioButtons(_form, _value, _submit, new Array(0));
}
function setAllRadioButtons(_form, _value, _submit, _exceptions) {

	if (_form == null || _value == null) return false;
	if (_exceptions == null) _exceptions = new Array(0);
	for (var i = 0; i < _form.elements.length; i++) {

		if (_form.elements[i] != null && _form.elements[i].value != null && _form.elements[i].value == _value) {
			var checkButton = true;
			for (var j = 0; j < _exceptions.length; j++) {
				if (_form.elements[i].name == _exceptions[j]) {
					checkButton = false;
				}
			}
			document.frmBody.elements[i].checked = checkButton;
			if (document.frmBody.elements[i].onclick != null) document.frmBody.elements[i].onclick();
		}
	}
	if (_submit) _form.submit();

}

function enableRadioButton(_name, _caller) {
	if (document.frmBody == null || _name == null || _caller == null || _caller.value != 'aarv9990010') return;
	for (var i = 0; i < document.frmBody.elements.length; i++) {
		if (document.frmBody.elements[i] != null && document.frmBody.elements[i].name == _name) {
			document.frmBody.elements[i].disabled = false;
		}
	}
}

function disableRadioButtonAND(_name, _dependencies) {
	return disableRadioButtonAND(_name, _dependencies, 'aarv9990020');
}

function elementHasValue(_elementName, _value) {
    if (document.frmBody[_elementName] == null || document.frmBody[_elementName] == undefined) return false;
    var element = document.frmBody[_elementName];

    if (element.type = 'radio') {
        for (i=0; i<element.length; i++) {
            if (element[i].checked) {
                return (element[i].value == _value);
            }
        }
    } else {
        if (element.value == undefined || element.value == null) return false;
        return (element.value == _value);
    }

	return false;
}

function setElementOnConditionAND(_elementName, _elementValue, _dependencies, _dependencyValues) {

	if (document.frmBody == null || _elementName == null) return;
	if (_dependencies.length != _dependencyValues.length) return;
	if (_dependencies == null || _dependencyValues == null) return;

	var setElement = true;
	for (var i = 0; i < _dependencies.length; i++) {
		setElement = setElement && elementHasValue(_dependencies[i], _dependencyValues[i]);
		if (!setElement) break;
	}
	if (setElement) {
		for (var i = 0; i < document.frmBody.elements.length; i++) {

			if (document.frmBody.elements[i] != null && document.frmBody.elements[i].name == _elementName) {
				if (document.frmBody.elements[i].type == 'input') {
					document.frmBody.elements[i].value = _elementValue;
				} else if (document.frmBody.elements[i].type == 'radio' && document.frmBody.elements[i].value == _elementValue) {
					document.frmBody.elements[i].checked = true;
				}
			}
		}
	}
}
function setElementOnConditionOR(_elementName, _elementValue, _dependencies, _dependencyValues) {

	if (document.frmBody == null || _elementName == null) return;
	if (_dependencies.length != _dependencyValues.length) return;
	if (_dependencies == null || _dependencyValues == null) return;

	var setElement = false;
	for (var i = 0; i < _dependencies.length; i++) {
		setElement = setElement || elementHasValue(_dependencies[i], _dependencyValues[i]);
		if (setElement) break;
	}
	if (setElement) {
		for (var i = 0; i < document.frmBody.elements.length; i++) {
			if (document.frmBody.elements[i] != null && document.frmBody.elements[i].name == _elementName) {
				if (document.frmBody.elements[i].type == 'input') {
					document.frmBody.elements[i].value = _elementValue;
				} else if (document.frmBody.elements[i].type == 'radio' && document.frmBody.elements[i].value == _elementValue) {
					document.frmBody.elements[i].checked = true;
				}
			}
		}
	}
}


function disableElement(_name, _dependency, _disableValue) {

	if (document.frmBody == null || _name == null) return;

	var doDisable = elementHasValue(_dependency, _disableValue);

//	alert("do disable is " + doDisable);
	if (doDisable) {
		for (var i = 0; i < document.frmBody.elements.length; i++) {
			if (document.frmBody.elements[i] != null && document.frmBody.elements[i].name == _name) {
				document.frmBody.elements[i].disabled = true;
			}
		}
	}
}

function disableElementOR(_name, _dependencies, _disableValues) {

	if (document.frmBody == null || _name == null) return;

	if (_dependencies.length != _disableValues.length) return;

	if (_dependencies == null) _dependencies = new Array(0);
	var doDisable = false;
	for (var i = 0; i < _dependencies.length; i++) {
		doDisable = doDisable || elementHasValue(_dependencies[i], _disableValues[i]);
		if (doDisable) break;
	}

//	alert("do disable is " + doDisable);
	if (doDisable) {
		for (var i = 0; i < document.frmBody.elements.length; i++) {
			if (document.frmBody.elements[i] != null && document.frmBody.elements[i].name == _name) {
				document.frmBody.elements[i].disabled = true;
			}
		}
	}
}

function disableElementAND(_elementName, _dependencies, _disableValues) {

	if (document.frmBody == null || _elementName == null) return;

	if (_dependencies.length != _disableValues.length) return;

	if (_dependencies == null) _dependencies = new Array(0);
	var doDisable = true;
	for (var i = 0; i < _dependencies.length; i++) {
		doDisable = doDisable && elementHasValue(_dependencies[i], _disableValues[i]);
		if (!doDisable) break;
	}

	for (var i = 0; i < document.frmBody.elements.length; i++) {

		if (document.frmBody.elements[i] != null && document.frmBody.elements[i].name == _elementName) {
			document.frmBody.elements[i].disabled = doDisable;
		}
	}
}


function disableRadioButtonAND(_name, _dependencies, _disableValue) {
	if (document.frmBody == null || _name == null) return;

	if (_disableValue == null) _disableValue = 'aarv9990020';

	var doDisable = true;
	if (_dependencies == null) _dependencies = new Array(0);
	for (var i = 0; i < _dependencies.length; i++) {
		for (var j = 0; j < document.frmBody.elements.length; j++) {
			if (document.frmBody.elements[j] != null && document.frmBody.elements[j].name == _dependencies[i] && document.frmBody.elements[j].value == _disableValue) {
				doDisable = doDisable && document.frmBody.elements[j].checked == true;
			}
		}
	}
	//alert("do disable is " + doDisable);
	if (doDisable) {
		for (var i = 0; i < document.frmBody.elements.length; i++) {
			if (document.frmBody.elements[i] != null && document.frmBody.elements[i].name == _name) {
				document.frmBody.elements[i].disabled = true;
			}
		}
	}
}



//window opener

/**
 * open a window and manager all the focusing behaviour
 * if the flat is set to 0 then it is taken that
 * @param url the page to open
 * @param name the name of the window
 * @param flag an int specifying the window characteristics
 * @param height the explicit height in pixels
 * @param width the explicit width in pixels
 * @return nothing, but to get the newly opened window use:
 *   > openWin(url, 'winName', 1);
 *   > var newWin = document.customObjects.get("openWin_"+winName);
 */
function openWin(url, name, flag, explicitHeight, explicitWidth) {
	var sOptions = "";
	if (flag == 1) {
		//450(default)x282, non-resizable, scrollbars, no status bar
		var height = 450;
		//only let NS4 + IE4 + higher do this test
		if (document.all || document.layers) {
			if (window.screen.availHeight < 450) height = window.screen.availHeight;
		}
		sOptions = "height=" + height + ",width=282,top=0,resizable=1,scrollbars=1,status=0,location=0,menubar=0,toolbar=0";
	} else if (flag == 2) {
		//320x355, resizable, scrollbars, no status bar, positioned in the center of the parent window
		var newWinHeight = 320;
		var newWinWidth = 355;
		var left = 0;
		var top = 0;
		if (document.all) {
			//IE
			left = window.screenLeft;
			left+=(window.document.body.clientWidth/2);
			left-=(newWinWidth/2);
			top = window.screenTop;
			top+=(window.document.body.clientHeight/2);
			top-=(newWinHeight/2);
		} else {
			//ns
			left = window.screenX;
			left+=(window.outerWidth/2);
			left-=(newWinWidth/2);
			top = window.screenY;
			top+=(window.outerHeight/2);
			top-=(newWinHeight/2);
		}
		sOptions = "height="+newWinHeight+",width="+newWinWidth+",resizable=1,scrollbars=1,status=0,location=0,menubar=0,toolbar=0";
		if (left>0 && top>0) {
			sOptions+=",left="+left+",top="+top;
		}
	} else if (flag == 3) {
		//350x620, resizable, scrollbars, no status bar
		sOptions = "height=350,width=620,resizable=1,scrollbars=1,status=0,location=0,menubar=0,toolbar=1";
	} else if (flag == 4) {
		//375x450, non-resizable, scrollbars, no status bar
		sOptions = "height=375,width=505,resizable=0,scrollbars=1,status=0,location=0,menubar=0,toolbar=0";
	} else if (flag == 8) {
		//450x500, resizable, scrollbars, no status bar, toolbar
		sOptions = "height=450,width=500,resizable=1,scrollbars=1,status=0,location=0,menubar=0,toolbar=1";
	} else if (flag == 9) {
		//350x280, resizable, scrollbars, no status bar
		sOptions = "height=350,width=280,resizable=1,scrollbars=1,status=0,location=0,menubar=0,toolbar=0";
	} else if (flag == 10) {
		//282x450, resizable, scrollbars, no status bar
		sOptions = "height=300,width=450,resizable=1,scrollbars=1,status=0,location=0,menubar=0,toolbar=0";
	} else if (flag == 11) {
		//max 550h, 790w, resizeable, scrollable, no status, no location bar, no menu bar, no toolbar
		var dimension = 550;
		if (document.all || document.layers) { //only let NS4 + IE4 + higher do this test
			if (window.screen.availHeight < dimension) dimension = window.screen.availHeight;
		}
		sOptions += "height="+dimension;
		dimension = 790;
		if (document.all || document.layers) { //only let NS4 + IE4 + higher do this test
			if (window.screen.availWidth < dimension) dimension = window.screen.availWidth;
		}
		sOptions += ",width="+dimension;
		sOptions = ",top=1,left=1,resizable=1,scrollbars=1,status=0,location=0,menubar=1,toolbar=0";
	} else if (flag == 0) {
		// use defaults if not set
		if ((explicitHeight == null) || (explicitWidth == null)) {
			explicitHeight = "450";
			explicitWidth = "500";
		}
		sOptions = "height=" + explicitHeight +",width=" + explicitWidth + ",resizable=1,scrollbars=1,status=0,location=0,menubar=0,toolbar=0";
	}
	var newWin = window.open(url, name, sOptions);
	newWin.focus();
	document.customObjects.put("openWin_"+name, newWin);
}

//close window
function closeWin(sParentGoto) {
	//get parent and redirect to 'sParentGoto'
	var oOpener = window.opener;
	if (!oOpener.closed)
		oOpener.location.href = sParentGoto;
	window.close();
}

//going back
function goBack(backIfNoBack) {
	if (window.history.length>0) {
		window.history.back();
	} else {
		window.location.href = backIfNoBack;
	}
}

//various form submitting methods
function doFormSubmit(frmName) {
	var frm = document.forms[frmName];
	if (frm==null) return;

	if (frm.onsubmit==null) {
		frm.submit();
	} else {
		if (frm.onsubmit()) {
			frm.submit();
		}
	}
}

function goPrev(strForm,strElement,strValue) {
	var objForm = document.forms[strForm];
	//check valid form
	if (objForm == null) return;

	var objEl = objForm.elements[strElement];
	//check valid element
	if (objEl == null) return;

	//set element
	objEl.value = strValue;

   if (objForm.elements['__doBranches'] != null) {
      objForm.elements['__doBranches'].value = 'false';
   }

	//submit form
	doFormSubmit(strForm);
}
function goPrevNewUrl(strForm,strContext,strVertical,strElement,strValue) {
	var objForm = document.forms[strForm];
	//check valid form
	if (objForm == null) return;

	var objEl = objForm.elements[strElement];
	//check valid element
	if (objEl == null) return;

	//set element
	objEl.value = strValue;

   if (objForm.elements['__doBranches'] != null) {
      objForm.elements['__doBranches'].value = 'false';
   }

   if (strElement == 'formNav'){
       document.forms[strForm].action = strContext+'/dorfq/'+strVertical+"/"+strValue+".htm"
   }
   //submit form
	doFormSubmit(strForm);
}

function doCheckMsgSubmit(strForm, iMin) {
	var oForm = document.forms[strForm]; if (oForm == null) return;

	//use form check count to get the number of checked elements
	if(formCheckCount(strForm, "")>=iMin)
		doFormSubmit(strForm);
	else
		window.alert("Please select at least " + iMin + " recipient" + ((iMin != 1)?"s":"") + " for this message.");
	return;
}

function doCheckSubmit(strForm, iMin) {
	var oForm = document.forms[strForm]; if (oForm == null) return;

	//get number of checked elements
	if(formCheckCount(strForm, "")>=iMin)
		doFormSubmit(strForm);
	else
		window.alert("You must select at least " + iMin + " item(s).");
	return;
}

function doCompare(strForm, strPrefix, iMin, iMax) {
	var oForm = document.forms[strForm]; if (oForm == null) return;

	//get the number of checked elements
	var checkCount = formCheckCount(strForm, strPrefix);
	if(checkCount>=iMin && checkCount<=iMax)
		doFormSubmit(strForm);
	else {
		//display an appropriate method
		var msg = "You must select either " + iMin + " or " + iMax + " quotes to compare.";
		if (iMax - iMin > 1)
			msg = "You must select between " + iMin + " and " + iMax + " quotes to compare.";
		window.alert(msg);
	}
	return;
}

function doLoginOrReg(frmName, frmElement, elValue, frmEmail, emailName, lnk) {
	var oFrm = document.forms[frmName];
	if (oFrm==null) return;
	var oElCheck = oFrm.elements[frmElement];
	if (oElCheck==null) return;
	var oElEmail = oFrm.elements[frmEmail];

	if (oElCheck[0].checked) {
		//registering
		window.location.href = lnk + "&" + emailName + "=" + oElEmail.value;
	} else {
		doFormSubmit(frmName);
	}
}

function confirmLogout() {
	confirmLogoutMsg("You are currently logged on as a vendor.  If you continue, you will be logged out and " +
			"be asked to log in as a buyer.\n\nAre you sure you want to continue?");
}
function confirmLogoutMsg(msg) {
	if (window.confirm(msg)) {
		doFormSubmit('frmBody');
	}
}

function confirmPursue() {
	if (
		window.confirm("In order to pursue this quote, we will need to pass your company name,\n" +
			"contact, telephone number and email address to the provider.")
	)
		return true;
	else
		return false;
}

function confirmPursueSubmit(frm, msg) {
	var m = msg;
	if (m==null)
		m = "In order to pursue this quote, we will need to pass your company name,\n" +
			"contact, telephone number and email address to the provider."
	if (
		window.confirm(m)
	) {
		var oForm = document.forms[frm]; if (oForm==null) return;
		document._DOSAVE = 0;
		doFormSubmit(frm);
	}
}

function confirmOnClick(msg) {
	if (window.confirm(msg)) { return true; }
	else { return false; }
}

//form saving
function addNameValue(str, name, val) {
	var newStr = str + "&" + name + "=" + escape(val);
	return newStr;
}

function getFormAsQueryString(strForm, prefix) {
	var oForm = document.forms[strForm];  if (oForm==null) return "";

	var qs = "";
	if (prefix != null) {
		qs += prefix;
	}
	for (var i=0;i<oForm.elements.length;i++) {
		var oEl = oForm.elements[i];
		var doDefault = true;
		if (oEl.type == "radio") {
			if (oEl.checked)
				qs = addNameValue(qs, oEl.name, oEl.value);
			doDefault = false;
		}

		if (oEl.type == "checkbox") {
			if (oEl.checked)
				qs = addNameValue(qs, oEl.name, oEl.value);
			doDefault = false;
		}

		if (oEl.type == "select-one" || oEl.type == "select-multiple") {
			//select box
			for (var j=0;j<oEl.options.length;j++) {
				//if selected add to query string (possibly many selected)
				if (oEl.options[j].selected)
					qs = addNameValue(qs, oEl.name, oEl.options[j].value);
			}
			doDefault = false;
		}

		if (doDefault) {
			qs = addNameValue(qs, oEl.name, oEl.value);
		}
	}

	return qs;
}

function simpleSaveForm() {
	document.frmBody.__action.name = "__old_action";
	window.open("/main?" + getFormAsQueryString('frmBody', '__action=saveform') + "&__DO_SAVE_CONFIRM=1", "tmpWin", "top=0,left=0,height=50,width=120,resizable=0,scrollbars=0,status=0,location=0,menubar=0,toolbar=0");
	document.frmBody.__action.name = "__action";
}

function saveForm() {
	//disallow NS4 - works OK in NS3 but don't bother
	if (!document.all) {
		//window.releaseEvents(Event.UNLOAD);
		//return window.confirm("Exiting this page will remove all the data!");
		return true;
	}

	if (document._DOSAVE != 1) return true;

	document.frmBody.__action.name = "__old_action";

	window.open("/main?" + getFormAsQueryString('frmBody', '__action=saveform'), "tmpWin", "top=" + window.screenTop + ",left=" + window.screenLeft + ",height=50,width=120,resizable=0,scrollbars=0,status=0,location=0,menubar=0,toolbar=0");

	this.focus();

	return true;
}

//form checking (field values)
function checkValid(strElement,strCheckFor) {
	var objEl = eval(strElement);
	//check valid
	if (objEl == null) return;

	if (objEl.options[objEl.selectedIndex].value == strCheckFor) {
		if (objEl._prevSelected == null) objEl._prevSelected = -1;

		if (objEl._prevSelected > objEl.selectedIndex) {
			//MOVING UP
			objEl.selectedIndex--;
			if (objEl.selectedIndex < 1)
				objEl.selectedIndex = 1;
		}
		else {
			//MOVING DOWN
			objEl.selectedIndex++;
		}

		objEl._prevSelected = objEl.selectedIndex;
	}
}

function checkIdentity(strEl1, strEl2) {
	//get objects and return if not found
	var obj1 = eval(strEl1);  if (obj1 == null) return;
	var obj2 = eval(strEl2);  if (obj2 == null) return;

	if (obj1.value != "" && obj2.value != "" && obj1.value != obj2.value) {
		alert("The passwords entered are not the same.\n\nPlease try again.");
		obj1.value = "";
		obj2.value = "";
		obj1.focus();
	}
}

function compare3(strForm,prefix,strElClicked) {
	var oForm = document.forms[strForm];
	if (oForm == null) return;

	var iChecked = 0;
	for (var i=0;i<oForm.elements.length;i++) {
		var oEl = oForm.elements[i];

		if (oEl.name.substring(0,prefix.length) == prefix) {
			//we have a match
			if (oEl.checked) iChecked++;
		}
	}

	if (iChecked > 3) {
		window.alert("You can only select 3 items to compare.");
		var oElClick = oForm.elements[strElClicked];
		if (oElClick == null) return;

		oElClick.checked = false;
	}
}

function formCheckCount(strForm, strPrefix) {
	var oForm = document.forms[strForm]; if (oForm == null) return 0;
	if (strPrefix==null) strPrefix="";

	var iSelected = 0;
	//get the number of checked boxes in a form
	for (var i=0;i<oForm.elements.length;i++) {
		var oEl = oForm.elements[i];
		if (oEl.name.substring(0, strPrefix.length) == strPrefix && oEl.type == "checkbox")
			if (oEl.checked) iSelected++;
	}

	return iSelected;
}

function updateElement(frm, elPrefix, elHidden) {
	var oForm = document.forms[frm]; if (oForm==null) return;

	var valArray = new Array(10);
	var valsAdded = 0;

	for (var i=0;i<oForm.elements.length;i++) {
		var oEl = oForm.elements[i];
		if (oEl.name.substring(0,elPrefix.length)==elPrefix) {
			if (oEl.value!="") {
				//get value and store in array
				if (valsAdded - 1 == valArray.length)
					valArray.length = valArray.length + valArray.length; //double size of array
				valArray[valsAdded] = oEl.value + "_" + getAARVValue(oEl.name);
				valsAdded++;
			}
		}
	}

	//now order the array and add to the hidden elements
	valArray.sort();
	var pos = 0;
	for (var i=0;i<oForm.elements.length;i++) {
		var oEl = oForm.elements[i];
		if (oEl.name == elHidden) {
			if (pos>=valsAdded)
				oEl.value = "";
			else
				oEl.value = getAARVValue(valArray[pos]);
			pos++;
		}
	}
}

function getAARVValue(name) {
	var idx = name.indexOf("aarv");
	if (idx > 0)
		return name.substring(idx, name.length);
	else
		return "";
}

function clearBox(frmName, elName) {
	var oForm = document.forms[frmName]; if (oForm==null) return;
	var oEl = oForm.elements[elName]; if (oEl==null) return;

	oEl.checked = false;
}

function clearFieldsOnSelect(frmName, frmChk, elPrefix) {
	var oForm = document.forms[frmName]; if (oForm==null) return;
	var oChk = oForm.elements[frmChk]; if (oChk==null) return;

	if (!oChk.checked) return;

	for (var i=0;i<oForm.elements.length;i++) {
		var oEl = oForm.elements[i];
		if (oEl.name.substring(0,elPrefix.length)==elPrefix) {
			oEl.value="";
		}
	}
}

function autoSelectIfZero(el) {
	var oFrm = document.forms["frmBody"]; if (oFrm==null) return;
	var oEl = oFrm.elements[el]; if(oEl==null) return;
	if (oEl.value=="0") {
		oEl.select();
	}
}

//VALIDATION METHODS
function chkCompletedSelect(frm, el) {
	var oFrm = document.forms[frm]; if (oFrm==null) return true;
	var oEl = oFrm.elements[el]; if(oEl==null) return true;
	var val = oEl.options[oEl.selectedIndex].value;
	if(val.length < 1 ) {
		window.alert("Please complete the form.");
		oEl.focus();
		return false;
	} else {
		return true;
	}
}

function chkCompleted(frm, el) {
	var oFrm = document.forms[frm]; if (oFrm==null) return true;
	var oEl = oFrm.elements[el]; if(oEl==null) return true;
	var val = oEl.value;
	if(val.length < 1 ) {
		window.alert("Please complete the form.");
		oEl.focus();
		return false;
	} else {
		return true;
	}
}
function chkEmail(frm, el) {
	var oFrm = document.forms[frm]; if (oFrm==null) return true;
	var oEl = oFrm.elements[el]; if(oEl==null) return true;
	var val = oEl.value;
	//allow empty field
	if (val.length<1) return true;

	var showAlert = true;

	//check there's an '@' and at least one '.'

	var seenAt = false;
	for (var i=0;i<val.length;i++) {
		var c = val.charAt(i);
		if (seenAt) {
			if (c=='.') {
				showAlert=false;
				i=val.length;
			}
		} else {
			if (c=='@')
				seenAt = true;
		}
	}

	if (showAlert) {
		window.alert("The value entered \"" + val + "\" is not a valid email address. \n\nFor example: name@website.com is valid.");
		oEl.select();
		oEl.focus();
		return false;
	}
	else
		return true;
}

function chkAlphaNumeric(frm, el) {
	var oFrm = document.forms[frm]; if (oFrm==null) return true;
	var oEl = oFrm.elements[el]; if(oEl==null) return true;
	var val = oEl.value;
	//allow empty field
	if (val.length<1) return true;

	var showAlert = false;

	//check there are no non-alphanumerics characters
	for (var i=0;i<val.length;i++) {
		var c = val.charAt(i);
		if (
			(c>='a' && c<='z') ||
			(c>='A' && c<='Z') ||
			(c>='0' && c<='9')
		) {
			//ok
		} else {
			//invalid character
			showAlert=true;
			i=val.length;
		}
	}

	if (showAlert) {
		window.alert("The value entered \"" + val + "\" is not a valid username.\n\nNo special chracters can be used, only alphabetic or numerics allowed.");
		oEl.select();
		oEl.focus();
		return false;
	}
	else
		return true;
}

function chkInteger(frm, el) {
	var oFrm = document.forms[frm]; if (oFrm==null) return true;
	var oEl = oFrm.elements[el]; if(oEl==null) return true;
	var val = oEl.value;
	//allow empty field
	if (val.length<1) return true;

	var showAlert = false;

	//check there are no alphabetic characters - could be more sophisticated here
	for (var i=0;i<val.length;i++) {
		var c = val.charAt(i);
		if ( c<'0' || c>'9' ) {
			showAlert=true;
			i=val.length;
		}
	}

	//check there's an '@' and at least one '.'
	if (showAlert) {
		window.alert("The value entered \"" + val + "\" is not a valid number. \n\nFor example: 2000 is valid.");
		oEl.select();
		oEl.focus();
		return false;
	}
	else
		return true;
}

function chkPhone(frm, el) {
	var oFrm = document.forms[frm]; if (oFrm==null) return true;
	var oEl = oFrm.elements[el]; if(oEl==null) return true;
	var val = oEl.value;
	//allow empty field
	if (val.length<1) return true;

	var showAlert = false;

	//check there are no alphabetic characters - could be more sophisticated here
	for (var i=0;i<val.length;i++) {
		var c = val.charAt(i);
		if ( (c>='a' && c<='z') || (c>='A' && c<='Z') ) {
			showAlert=true;
			i=val.length;
		}
	}

	//check there's an '@' and at least one '.'
	if (showAlert) {
		window.alert("The value entered \"" + val + "\" is not a valid number. \n\nFor example: (020) 7378 9800 is valid.");
		oEl.select();
		oEl.focus();
		return false;
	}
	else
		return true;
}

function chkDouble(frm, el) {
	var oFrm = document.forms[frm]; if (oFrm==null) return true;
	var oEl = oFrm.elements[el]; if(oEl==null) return true;
	var val = oEl.value;

	//essentially, parse the value into strOut and check strOut is a float
	var showAlert = false;

	var strOut = new String();
	for (var i=0;i<val.length;i++) {
		var c = val.charAt(i);
		if (c<'0' || c>'9') {
			//check if char should be removed
			// - must be followed by 3 numerics
			if (i+3 < val.length) {
				var bAllNums = true;
				for (var j=1;j<4;j++) {
					if (val.charAt(i+j) < '0' || val.charAt(i+j) > '9')
						bAllNums = false;
				}
				//if all numerics, ignore the character, otherwise add it
				if (!bAllNums)
					strOut += c;
			} else {
				strOut += c;
			}
		} else {
			strOut += c;
		}
	}

	//test if strOut is a valid float
	if (val.length>0) {
		var fVal = parseFloat(strOut);
		//for the following check, need to strip leading and trailing 0's
		//i.e. if strOut == 002 or 2.10, then fVal will be 2 or 2.1
		strOut = stripZeros(strOut);
		if (isNaN(fVal) || String(fVal)!=strOut)
			showAlert=true;
	}

	if (showAlert) {
		window.alert("The value entered \"" + val + "\" is not a valid number. \n\nFor example: 2,000.01 is valid.");
		oEl.select();
		oEl.focus();
		return false;
	}
	else
		return true;
}

//help function for above
function stripZeros(str) {
	var startIdx = 0;
	var endIdx = str.length;

	//strip leading 0's
	for (var i=0;i<str.length;i++) {
		//check char
		if (str.charAt(i)!='0') {
			startIdx = i;
			i = str.length;
		}
	}
	if (str.charAt(startIdx)==".") {
		//check there's a leading zero if directly followed by a "."
		//i.e. "0.25" will get stripped to ".25" - restore to "0.25"
		// also, if ".25" is entered, put to "0.25"
		startIdx--;
		if (startIdx<0) {
			startIdx=0;
			str = "0" + str;
		}
	}

	if (str.indexOf(".")>=0) {
		//strip trailing 0's (if there's a fractional part)
		for (var i=str.length-1;i>startIdx;i--) {
			//check char
			if (str.charAt(i)!='0') {
				endIdx = i+1;
				i = startIdx;
			}
		}
	}

	//check the last index is not a "dot" , i.e. "10.0" will be stripped to "10." - should be just 10
	if (str.charAt(endIdx-1)==".")
		endIdx--;

	//next check the indexes for a valid substring
	if (endIdx-startIdx < 1)
		return "0"; //must have been something like 0.0
	else
		return str.substring(startIdx, endIdx);
}

function chk100pc(frm, els, type) {
	//frm - string: name of form
	//els - string: comma seperated list of elements (specified by type)
	//type - int: 0=text 1=select IMPORTANT: only text and select supported

	//get the form
	var oForm = document.forms[frm]; if (oForm==null) return true;

	//get the elements (as an array)
	var aEls = new Array();
	var idxPrev = 0;
	var idxNext = els.indexOf(",");
	while (idxNext >= 0) {
		//get the element
		var sEl = els.substring(idxPrev, idxNext);
		//append to array
		aEls[aEls.length] = sEl;

		//get next indexes
		idxPrev = idxNext + 1;
		idxNext = els.indexOf(",", idxPrev);
	}
	//get the last string
	var sEl = els.substring(idxPrev, els.length);
	aEls[aEls.length] = sEl;

	var oReturnTo = null;

	//now test that each element exists
	//and get the selected values (what is displayed in the drop down - must be "xx%" no spaces)
	for (var i=0;i<aEls.length;i++) {
		var oEl = oForm.elements[aEls[i]]; if (oEl==null) return true;

		//initialise number value
		aEls[i] = '0';

		//check if this element is a collection (multiple elements with the same name)
		if (oEl.type == "text" || oEl.type == "select-one") {
			if (type==0)
				aEls[i] = oEl.value;
			if (type==1)
				aEls[i] = oEl.options[oEl.selectedIndex].text.substring(0,oEl.options[oEl.selectedIndex].text.length - 1);

			//if there is an error, return to the first element
			if (i==0) oReturnTo = oEl;
		} else {
			for (var j=0;j<oEl.length;j++) {
				var oSubEl = oEl[j];
				var iNum = 0;
				if (type==0)
					iNum = parseInt(oSubEl.value);
				if (type==1)
					iNum = parseInt(oSubEl.options[oSubEl.selectedIndex].text.substring(0,oSubEl.options[oSubEl.selectedIndex].text.length - 1));

				//if valid add it
				if (!isNaN(iNum))
					aEls[i] = iNum + parseInt(aEls[i]);
			}

			//if there is an error, return to the first element
			if (i==0) oReturnTo = oEl[0];
			//if (i==0) oReturnTo = oEl;
		}
	}

	//now test the values add up to 100%
	var iTotal = 0;
	for (var i=0;i<aEls.length;i++) {
		var iNum = parseInt(aEls[i]);
		if (!isNaN(iNum))
			iTotal += iNum;
	}

	if (iTotal == 100 || iTotal == 0)
		return true;

	//must not add up to 100
	window.alert("The total must add up to 100%.\n\nPlease check the values and try again.");

	//set element as focused
	if (oReturnTo!=null) {
		if (type==0)
			oReturnTo.select();
		oReturnTo.focus();
	}
	return false;
}
/**
 * returns boolean depending on whether form.el has
 */
function hasValue(frm, el) {
	var oFrm = document.forms[frm];
	if (oFrm==null) return false;

	var oEl = oFrm.elements[el];
	if(oEl==null) return false;

	var val = oEl.value;
	if(val == null) {
		return false;
	} else if(val.length < 1) {
		return false;
	} else {
		return true;
	}
}
/**
 * Check that the given postcode and telephone number are UK.  If both are not, an alert is displayed
 */
function checkUkRequest(frmName, postcodeElementName, telephoneElementName) {
	var retVal = true;

	var frm = document.forms[frmName];
	if (frm != null) {
		var pCode = trimElementValue(document.forms[frmName].elements[postcodeElementName]);
		var tel = trimElementValue(document.forms[frmName].elements[telephoneElementName]);

		var pCodeError = false;
		var telError = false;

		if (pCode.length > 0) {
			var charCheck = pCode.charAt(0);
			if ((charCheck >= 'a' && charCheck <= 'z') || (charCheck >= 'A' && charCheck <= 'Z')) {
				//ok, check phone
			} else {
				pCodeError = true;
			}
		}
		if (tel.length > 1) {
			var firstChar = tel.charAt(0);
			var firstPair = tel.substring(0, 1);
			if (firstChar == '0' || firstChar == '4' || firstPair == "+4") {
				//ok
			} else {
				telError = true;
			}
		}

		if (pCodeError && telError) {
			window.alert("From the information supplied, it appears you are a non-UK resident or business.  We can only provide quotes for UK requests.");
			retVal = false;
		}
	}

	return retVal;
}
function trimElementValue(element) {
	var retVal = "";

	if (element == null || element.value == null || element.value.length < 1) {
		retVal = "";
	} else {
		retVal = trimString(element.value);
	}

	return retVal;
}
function trimString(stringToTrim) {
	var retVal = "";

	if (stringToTrim == null || stringToTrim.length < 1) {
		retVal = "";
	} else {
		retVal = stringToTrim;
		//left trim
		while (retVal.charAt(0) == ' ') {
			retVal = trimString(retVal.substring(1, retVal.length));
		}
		//right trim
		while (retVal.charAt(retVal.length - 1) == ' ') {
			retVal = trimString(retVal.substring(0, retVal.length - 1));
		}
	}

	return retVal;
}



function replaceAll(oldStr,findStr,repStr) {
  var srchNdx = 0;  // srchNdx will keep track of where in the whole line of oldStr are we searching.
  var newStr = "";  // newStr will hold the altered version of oldStr.
  while (oldStr.indexOf(findStr,srchNdx) != -1){   // As long as there are strings to replace, this loop will run.
    // Put it all the unaltered text from one findStr to the next findStr into newStr.
    newStr += oldStr.substring(srchNdx,oldStr.indexOf(findStr,srchNdx));
    // Instead of putting the old string, put in the new string instead.
    newStr += repStr;
    // Now jump to the next chunk of text till the next findStr.
    srchNdx = (oldStr.indexOf(findStr,srchNdx) + findStr.length);
  }
  // Put whatever's left into newStr.
  newStr += oldStr.substring(srchNdx,oldStr.length);
  return newStr;
}