// GraybarCommon.js

TEXT_NODE = 3;

// This function automatically checks the check box given the form name and the check box ID
function checkTheBox(formName, boxID) {
	eval("document." + formName + "." + boxID).checked = true;
}

function isArray(testObject) {       
	return testObject && 
		!(testObject.propertyIsEnumerable('length')) && 
		typeof testObject === 'object' && 
		typeof testObject.length === 'number';
}

function notDefined(aParam) {
	if (aParam == null) return true;
	if (aParam == undefined) return true;
	return false;
}

function notEmpty(aParam) {
	if (notDefined(aParam)) return false;
	if (aParam == "") return false;
//	if (aParam.length != null && aParam.length != undefined && aParam.length ==0) return false;
	if (aParam.length == 0) return false;

	return true;
}

function empty(aParam) {
	return !notEmpty(aParam);
}

function show(anElementID) {
	//alert ("show called on "+anElementID);
	if (notEmpty(anElementID)) {
		anElement = document.getElementById(anElementID);
		if (notEmpty(anElement)) {
			anElement.style.display="block";
		}
	}
}

function hide(anElementID) {
	//alert ("hide called on "+anElementID);
	if (notEmpty(anElementID)) {
		anElement = document.getElementById(anElementID);
		if (notEmpty(anElement)) {
			anElement.style.display="none";
		}
	}
}

function addErrorStyle(anElement, aStyle) {
	//alert ("adding error style");
	if (empty(anElement)) return;
	if (empty(aStyle)) return;
	// only add the style if it's not already there
	if (anElement.className.indexOf(aStyle) < 0) {
		anElement.className += " " + aStyle;
	}
}

function removeErrorStyle(anElement, aStyle) {
	//alert ("removing error style");
	if (empty(anElement)) return;
	if (empty(aStyle)) return;
	replaceString = '/' + aStyle + '/';
	anElement.className = anElement.className.replace(aStyle, '');
//	alert("anElement.className="+anElement.className);
}

function updateCellStyle(aCell, anErrorMsg) { // pass error msg rather than boolean in case we want to do something with it later
	if (notEmpty(aCell)) {
		if (notEmpty(anErrorMsg)) {
			addErrorStyle(aCell, 'formError');
		}
		else {
			removeErrorStyle(aCell, 'formError');
		}
	}
	else {
	//	alert("selectAndQtyCell is empty");
	}
}


function isNum(numericString) {
  var str = numericString;
  var digit = '';
  for (var index = 0; index < str.length; index++) {
    digit = str.substring(index, index + 1)
    if (digit < "0" || "9" < digit)
      return false;
  }
  return true;
}


function isValidCatEntryId(aCatEntryId) {
	return notEmpty(aCatEntryId);
}

// this value is used as a placeholder comparison value for cat entries that have a quantity but are
// not checked for comparison purposes
var	NO_COMPARE_VALUE = " ";

function isValidComparisonValue(aCompareId) {
	return notEmpty(aCompareId)	&& aCompareId != NO_COMPARE_VALUE;
}

function isValidQtyValue(aQty) {
	return notEmpty(aQty) && isNum(aQty);
}


function getFieldValue(aFieldId) {
	
	if (empty(aFieldId)) {
		alert("getFieldValue called with an empty fieldId");
		return;
	}
	
	field = document.getElementById(aFieldId);
	value = "";
	
	if (empty(field)) {
		alert("unable to find element with id: "+aFieldId);
	}
	else {
		value = field.value;
	}
	return value;	
}

var errorRows = new Array();
function addErrorRow(anErrorRowId) {
	if (notEmpty(anErrorRowId)) {
		errorRows[errorRows.length] = anErrorRowId;
	}
}

function showErrorRows() {
	for (var i = 0; i < errorRows.length; ++i) {
		show(errorRows[i]);
	}
}

function hideErrorRows() {
	for (var i = 0; i < errorRows.length; ++i) {
		hide(errorRows[i]);
	}
}



function updateManager(aManager) {	

	var manager = aManager;
	
//	this.setManager(aManager) {
//		manager = aManager;
//	}

	this.update = function() {
	//	alert("update manager called by element with ID:"+this.id+", name:"+this.name+", value:"+this.value);
		manager.updateListeners(this);
	}
}

/* appendHiddenField() 
   - sets the pageType accordingly so that ODE redirects it back after P&A check
 */
function appendHiddenField(form, name, value) {
	var inputName = document.createElement('input');
	inputName.setAttribute('type','hidden');
	inputName.setAttribute('name',name);
	inputName.setAttribute('id','name');
	inputName.setAttribute('value',value);

	formObj = document.getElementById(form);
	formObj.appendChild(inputName);
}


function checkBoxManager(){
	var managedCheckBoxes = new Array();
//	var checkBoxActiveFlags = new Array();
	var containerElement;
	
	var listeners = new Array();
	
	var varsToSave = new Array();
	
	var managerId = "";
	var valueDelim = ",";	
	
	var updater = new updateManager(this);
	
	this.addListener = function(aListener) {
		if (notEmpty(aListener)) {
			listeners[listeners.length] = aListener;
		}
	}
	
	this.updateListeners = function(checkbox) {	
		//alert ("updating "+	listeners.length + " listeners");
		for (i=0; i < listeners.length; ++i) {
			listeners[i].onClicked(managerId, checkbox);
		}
	}
	
	this.init = function(aManagerId, anElement) {
	
		if (notEmpty(aManagerId)) {
			managerId = aManagerId;
		}
	
		//alert("init called");
		if (empty(anElement)) {
			containerElement = document;
		}
		else {
			containerElement = anElement;
		}
		
		inputElements = containerElement.getElementsByTagName("input");
		for (i = 0; i < inputElements.length; ++i) {
			//	alert("inputElement["+i+"].type = "+inputElements[i].type);

			if (notEmpty(inputElements[i].type) && inputElements[i].type == "checkbox") {
			//	alert("input "+i+" is  a checkbox; its id is: {"+inputElements[i].id+"}");
				if (notEmpty(inputElements[i].id)) {
					managedCheckBoxes[inputElements[i].id] = inputElements[i];
					managedCheckBoxes[inputElements[i].id].onclick = updater.update;
				}
				else {
					// alert ("input "+i+" does not have an id");
				}
			}
		}
	}
	
	this.getCheckedBoxes = function() {
		var checkedBoxes = new Array();
		
	//	for (i = 0; i < checkBoxActiveFlags.length; ++i) {
	//		if (checkBoxActiveFlags[i] == true) {
	//			checkedBoxes[checkedBoxes.length] = managedCheckBoxes
	//		}
	
		//if (notEmpty(managedCheckBoxes)) {
		for (i in managedCheckBoxes) {
			if (managedCheckBoxes[i].checked) {
				checkedBoxes[checkedBoxes.length] = managedCheckBoxes[i];
			}			
		}
	//	}
		return checkedBoxes;
	}
	
	this.getCheckBoxById = function(aCheckBoxId) {
		if (empty(aCheckBoxId)) return;
		
		return managedCheckBoxes[aCheckBoxId];
	}
	
	
	this.selectAll = function() {
	//	for (i = 0; i < managedCheckBoxes.length; ++i) {
		for (i in managedCheckBoxes) {
			// exclude the will call checkbox.
			if (managedCheckBoxes[i].name != 'willCallCheckbox') {
				managedCheckBoxes[i].checked = true;
			}
		}
	}

	this.deselectAll = function() {
		for (i in managedCheckBoxes) {
			if (managedCheckBoxes[i].name != 'willCallCheckbox') {
				managedCheckBoxes[i].checked = false;
			}
		}
	}
	
	
	this.addVarToSave = function(aVarName, aFormElementId) {
		if (notEmpty(aVarName) && notEmpty(aFormElementId)) {
			varsToSave[aVarName] = aFormElementId;
			//alert("updated mgr object; will now also save variable named: {"+aVarName+"} in form input named: {"+aFormElementId+"}; varsToSave["+aVarName+"]={"+varsToSave[aVarName]+"}");
		}
	}
	
	this.saveSelectedData = function() {
	//	alert("saveSelectedData called!");
		
	//	if (notEmpty(varsToSave)) {
			selectedIndices = this.getCheckedBoxes();		
			if (notEmpty(selectedIndices) ) {
			
				for (varName in varsToSave) {
					varValues = "";
					for (index in selectedIndices) {
						varIndex = selectedIndices[index].value;
			//			if (notEmpty(varIndex)) {

						elementToSave = document.getElementById(varName + varIndex)								

						if (notEmpty(elementToSave) && notEmpty(elementToSave.value)) {
							if (notEmpty(varValues)) varValues += valueDelim;
							
							varValues += elementToSave.value;
							
						}
		//			}
					}
					
					formElement = document.getElementsByName(varsToSave[varName]);
					if (notEmpty(formElement)) {
						formElement = formElement[0];
					} else {
						formElement = document.getElementById(varsToSave[varName]);
					}
					
					formElement.value = varValues;
					// alert("set "+formElement.name+" to store: {"+varValues+"}");
				}
			}
			else {
		//		alert("no checkboxes selected");
			}
	//	}

	}
	

	this.getSelectedData = function() {
		selectedValues = new Array();
		
	//	if (notEmpty(varsToSave)) {
			selectedIndices = this.getCheckedBoxes();		
			if (notEmpty(selectedIndices) ) {			
				for (varName in varsToSave) {
					selectedValues[varName] = this.getSelectedDataFor(varName);					
				}
			}
			else {
			//	alert("no checkboxes selected");
			}
	//	}
	
		return selectedValues;
	}

	this.getSelectedDataFor = function (aVarName) {
		varValues = new Array();
		
		if (notEmpty(aVarName)) {
			selectedIndices = this.getCheckedBoxes();
			for (index in selectedIndices) {
				varIndex = selectedIndices[index].value;
//				if (notEmpty(varIndex)) {

				elementToSave = document.getElementById(aVarName + varIndex)								

				if (notEmpty(elementToSave) && notEmpty(elementToSave.value)) {
					varValues[varValues.length] = elementToSave.value;
				}
//				}
			}
		}
		return varValues;
	}
	
}




	function f_formManager() {
		var id = "";
		var suffix = "";
		var maxIndex = 0;
				
		var formVars = new Array();
		
		this.init = function(anId, aSuffix, aMaxIndex) {
			id = anId;
			suffix = aSuffix;
			maxIndex = aMaxIndex;
		}
		
		this.addFormVar = function(aFormVar) {
			if (empty(aFormVar)) return;
			
			i = 0;
			for (; i < formVars.length; ++i) {
				if (formVars[i] == aFormVar) {
					break;
				}
			}
			// if aFormVar is not in the array then i==formVars.length, which is the index where we want to 
			// insert the new var
			formVars[i] = aFormVar;
		}
		
		
/*		this.getFormVarValue(aFormVar) {
			if (empty(aFormVar)) return new Array();
			
			i = 0;
			for (; i < formVars.length; ++i) {
				if (formVars[i] == aFormVar) {
					break;
				}				
			}
			
			if (i >= formVars.length) return new Array(); // aFormVar is not found in the form vars array
			
			
		}*/
		

/*		this.getFieldValue = function(aFieldId) {
			
			if (empty(aFieldId)) {
				alert("getFieldValue called with an empty fieldId");
				return;
			}
			
			field = document.getElementById(aFieldId);
			value = "";
			
			if (empty(field)) {
				alert("unable to find element with id: "+aFieldId);
			}
			else {
				value = field.value;
			}
			return value;	
		}*/

		this.getEnteredFormData = function() {
//			alert("this.getEnteredFormData called for form with id="+id);

			index = 1;
			formValues = new Array();
			formValues['catEntryId'] = new Array();
			formValues['quantity'] = new Array();
			formValues['compareId'] = new Array();			
			
			valueIter = 0;
			// alert("maxIndex="+maxIndex);
			while (index <= maxIndex) {
				//alert("index = "+index);
				compareValue = NO_COMPARE_VALUE;
			
				checkboxId = "checkbox_" + index + suffix;
				checkboxField = document.getElementById(checkboxId);
				
				quantityFieldId = "quantity_" + index + suffix;
//				quantityValue = this.getFieldValue(quantityFieldId);
				quantityValue = getFieldValue(quantityFieldId);
				
				if (empty(quantityValue)) quantityValue = 0;
				
				if (checkboxField.checked) {
					compareFieldId = "compareId_" + index + suffix;
//					compareValue = this.getFieldValue(compareFieldId);					
					compareValue = getFieldValue(compareFieldId);					
				}
				
				if (checkboxField.checked || quantityValue > 0) {
					catEntryFieldId = "catEntryId_" + index + suffix;
//					catEntryValue = this.getFieldValue(catEntryFieldId);	
					catEntryValue = getFieldValue(catEntryFieldId);	
					
					formValues['catEntryId'][valueIter] = catEntryValue;
					formValues['quantity'][valueIter] = quantityValue;
					formValues['compareId'][valueIter] = compareValue;					

					++valueIter;
				}
				else {
					//alert("checkbox not checked and no quantity is entered");
				}
				
				++index;
			}
			return formValues;
		}
		
		this.getAllFormData = function() {
//			alert("this.getAllFormData called for form with id="+id);

			index = 1;
			formValues = new Array();
			formValues['catEntryId'] = new Array();
			formValues['quantity'] = new Array();
			formValues['compareId'] = new Array();
			formValues['qtyMultiple'] = new Array();
			
			valueIter = 0;
			// alert("maxIndex="+maxIndex);
			while (index <= maxIndex) {
				//alert("index = "+index);
				compareValue = NO_COMPARE_VALUE;
			
				checkboxId = "checkbox_" + index + suffix;
				checkboxField = document.getElementById(checkboxId);
				
				quantityFieldId = "quantity_" + index + suffix;
//				quantityValue = this.getFieldValue(quantityFieldId);
				quantityValue = getFieldValue(quantityFieldId);
				//if (empty(quantityValue)) quantityValue = 0;
				
				qtyMultipleFieldId = "qtyMultiple_" + index + suffix;
				qtyMultipleValue = getFieldValue(qtyMultipleFieldId);
				
				if (checkboxField.checked) {
					compareFieldId = "compareId_" + index + suffix;
//					compareValue = this.getFieldValue(compareFieldId);					
					compareValue = getFieldValue(compareFieldId);					
				}
								
		/*		if (checkboxField.checked || notEmpty(quantityValue)) { */
		
					catEntryFieldId = "catEntryId_" + index + suffix;
//					catEntryValue = this.getFieldValue(catEntryFieldId);	
					catEntryValue = getFieldValue(catEntryFieldId);	
					
					formValues['catEntryId'][valueIter] = catEntryValue;
					formValues['quantity'][valueIter] = quantityValue;
					formValues['compareId'][valueIter] = compareValue;
					formValues['qtyMultiple'][valueIter] = qtyMultipleValue;
	
					++valueIter;
					
		/*		}
				else {
					//alert("checkbox not checked and no quantity is entered");
				}*/
				
				++index;
			}
			return formValues;
		}		
	}


function addToFavoritesListOld(){
	var favFormObject = document.AddtoFavList;
	var orderItemFormObject = document.ItemPageOrderItemAddForm; //USE APPROPRIATE FORM
	var requisitionListName = favFormObject.newFavsList.value;
	var newList = false;
	if (requisitionListName.length !=0){
		newList = true;
	}
	var requisitionListId = "";
	if(favFormObject.addToExistingFav.length >0){
		requisitionListId=favFormObject.addToExistingFav[favFormObject.addToExistingFav.selectedIndex].value;
	}else{
		newList = true; //no existing list
	}


	if(newList){
		if(requisitionListName.length ==0){
			alert('Please enter new list name');
			return false;
		}
		favFormObject.appendChild(addInputElement("name",requisitionListName));
		favFormObject.appendChild(addInputElement("status","Y"));
	}else{
		favFormObject.appendChild(addInputElement("requisitionListId",requisitionListId));
	}

	//quantity check
	var hasErr=false;

	for (var j = 0; j < orderItemFormObject.quantity.value.length; j++) {
		ch =orderItemFormObject.quantity.value.substring(j,j + 1)        
		if (ch < "0"  ||  ch >"9")
		{	
		hasErr=true;
		break;
		}
	 }

	if(hasErr || orderItemFormObject.quantity.value.length==0){
		favFormObject.appendChild(addInputElement("quantity",1)); //invalid quantity - default to 1
	}else{
		favFormObject.appendChild(addInputElement("quantity",orderItemFormObject.quantity.value)); //obtain valid input quantity
	}
		favFormObject.submit();
}		

/* This is the function that is called for adding item(s) to an existing or a new favorites list */
function addToFavoritesList(favFormObject, catEntryIds, qtys){

	missingData = false;
		
	if (notDefined(catEntryIds) || catEntryIds.length < 1) {
		alert(errorMsgs['Graybar_catalog_ERROR_NO_ITEMS_FOR_FAVS']);
		missingData = true;
	}
		
	if (missingData) {
		return false;
	}

	var requisitionListName = favFormObject.newFavsList.value;
	var newList = false;
	if (requisitionListName.length !=0){
		newList = true;
	}
	var requisitionListId = "";
	if(favFormObject.addToExistingFav.length >0){
		requisitionListId=favFormObject.addToExistingFav[favFormObject.addToExistingFav.selectedIndex].value;
	}else{
		newList = true; //no existing list
	}


	if(newList){
		if(requisitionListName.length ==0){
			alert('Please enter new list name');
			return false;
		}
		favFormObject.appendChild(addInputElement("name",requisitionListName));
		favFormObject.appendChild(addInputElement("status","Z"));
	}else{
		favFormObject.appendChild(addInputElement("requisitionListId",requisitionListId));
	}


	for (i = 0; i < catEntryIds.length; ++i) {
		quantity = qtys[i];
	
		// if quantity not entered, set it to 1
		// TODO: verify that this is the desired behaviour
		// quantity 0 is interpreted as a value selected from another page, so in order to support add2favs
		// from multiple product pages, need to convert quantity==0 to quantity==1
		if (empty(quantity) || !isNum(quantity) || quantity == 0) quantity = 1;

		if (isValidCatEntryId(catEntryIds[i])) {
			favFormObject.appendChild(addInputElement("quantity_"+(i+1), quantity));
			favFormObject.appendChild(addInputElement("catEntryId_"+(i+1), catEntryIds[i]));		
		}
	}

	// add parameters to support redirection back to the current page
	favFormObject = addRedirectionParams(favFormObject);

	favFormObject.submit();

}

/* This is the function that is called for adding item(s) to an existing or a new RFQ */
function addToRFQList(rfqFormObject, catEntryIds){

	missingData = false;
		
	if (notDefined(catEntryIds) || catEntryIds.length < 1) {
		alert(errorMsgs['Graybar_catalog_ERROR_NO_ITEMS_FOR_RFQ']);
		missingData = true;
	}
		
	if (missingData) {
		return false;
	}

	var rfqListName = rfqFormObject.newRFQList.value;
	var newList = false;
	if (rfqListName.length !=0){
		newList = true;
	}
	var rfqListId = "";
	if(rfqFormObject.addToExistingRFQ.length >0){
		rfqListId = rfqFormObject.addToExistingRFQ[rfqFormObject.addToExistingRFQ.selectedIndex].value;
	}else{
		newList = true; //no existing list
	}

	if(newList){
		if(rfqListName.length ==0){
			alert('Please enter new rfq name');
			return false;
		}
		// add required shortdesc new rfq name and set action the "add to new rfq" command
		rfqFormObject.appendChild(addInputElement("shortdesc",rfqListName));
		rfqFormObject.action='GraybarRFQCreateItemAddCmd';
		
	}else{
		// add required offering id for existing rfq and set action the "add to existing rfq" command
		rfqFormObject.appendChild(addInputElement("offering_id",rfqListId));
		rfqFormObject.action='RFQItemAdd';
	}

	for (i = 0; i < catEntryIds.length; ++i) {
		if (isValidCatEntryId(catEntryIds[i])) {
			rfqFormObject.appendChild(addInputElement("catentryid", catEntryIds[i]));		
		}
	}

	// add parameters to support redirection back to the current page
	rfqFormObject = addRedirectionParams(rfqFormObject);
	
	rfqFormObject.submit();

}


/* This is the function that is called for adding item(s) to an existing or a new RFQ */
function addToRFQList(rfqFormObject, catEntryIds, qtys){

	missingData = false;
		
	if (notDefined(catEntryIds) || catEntryIds.length < 1) {
		alert(errorMsgs['Graybar_catalog_ERROR_NO_ITEMS_FOR_RFQ']);
		missingData = true;
	}
		
	if (missingData) {
		return false;
	}

	var rfqListName = rfqFormObject.newRFQList.value;
	var newList = false;
	if (rfqListName.length !=0){
		newList = true;
	}
	var rfqListId = "";
	if(rfqFormObject.addToExistingRFQ.length >0){
		rfqListId = rfqFormObject.addToExistingRFQ[rfqFormObject.addToExistingRFQ.selectedIndex].value;
	}else{
		newList = true; //no existing list
	}

	if(newList){
		if(rfqListName.length ==0){
			alert('Please enter new rfq name');
			return false;
		}
		// add required shortdesc new rfq name and set action the "add to new rfq" command
		rfqFormObject.appendChild(addInputElement("shortdesc",rfqListName));
		rfqFormObject.action='GraybarRFQCreateItemAddCmd';
		
	}else{
		// add required offering id for existing rfq and set action the "add to existing rfq" command
		rfqFormObject.appendChild(addInputElement("offering_id",rfqListId));
		rfqFormObject.action='RFQItemAdd';
	}

	for (i = 0; i < catEntryIds.length; ++i) {
		quantity = qtys[i];
		if (empty(quantity) || !isNum(quantity) || quantity == 0) quantity = 1;
		if (isValidCatEntryId(catEntryIds[i])) {
			rfqFormObject.appendChild(addInputElement("catentryid", catEntryIds[i]));
			rfqFormObject.appendChild(addInputElement("quantity", quantity));		
		}
	}

	// add parameters to support redirection back to the current page
	rfqFormObject = addRedirectionParams(rfqFormObject);

	rfqFormObject.submit();

}

/* This function adds ODE specific parameters to the form object to support redirection back to the current ODE page */
/* The hidden form logic is moved from GraybarAdd2FavBox.jsp and GraybarAdd2RFQBox.jsp to here */
function addRedirectionParams(formObj){
	var ip_state = getParamValue("ip_state");
	var isFromSearch = getParamValue("isFromSearch");
	var ip_text_header = getParamValue("ip_text_header");
	var ip_text_adv1 = getParamValue("ip_text_adv1");
	var ip_text_adv2 = getParamValue("ip_text_adv2");
	var ip_constraint_val = getParamValue("ip_constraint_val");
	var ip_constraint_val_adv = getParamValue("ip_constraint_val_adv");
	var ip_constrain = getParamValue("ip_constrain");
	var ip_wcsCompareItems = getParamValue("ip_wcsCompareItems");
	var ip_page = getParamValue("ip_page");
	var ip_perPage = getParamValue("ip_perPage");
	var ip_page = getParamValue("ip_page");
	var gb_tempCompareId = getParamValue("gb_tempCompareId");
	var gb_tempCatEntryId = getParamValue("gb_tempCatEntryId");
	var gb_tempQty = getParamValue("gb_tempQty");
	
	// need to always append ip_state even when empty to allow proper redirections from add2fav and add2rfq commands
	formObj.appendChild(addInputElement("ip_state", ip_state));

	if (isFromSearch != '') {formObj.appendChild(addInputElement("isFromSearch", isFromSearch));}
	if (ip_text_header != '') {formObj.appendChild(addInputElement("ip_text_header", ip_text_header));}
	if (ip_text_adv1 != '') {formObj.appendChild(addInputElement("ip_text_adv1", ip_text_adv1));}
	if (ip_text_adv2 != '') {formObj.appendChild(addInputElement("ip_text_adv2", ip_text_adv2));}
	if (ip_constraint_val != '') {formObj.appendChild(addInputElement("ip_constraint_val", ip_constraint_val));}
	if (ip_constraint_val_adv != '') {formObj.appendChild(addInputElement("ip_constraint_val_adv", ip_constraint_val_adv));}
	if (ip_constrain != '') {formObj.appendChild(addInputElement("ip_constrain", ip_constrain));}
	if (ip_wcsCompareItems != '') {formObj.appendChild(addInputElement("ip_wcsCompareItems", ip_wcsCompareItems));}
	if (ip_page != '') {formObj.appendChild(addInputElement("ip_page", ip_page));}
	if (ip_perPage != '') {formObj.appendChild(addInputElement("ip_perPage", ip_perPage));}
	if (gb_tempCompareId != '') {formObj.appendChild(addInputElement("gb_tempCompareId", gb_tempCompareId));}
	if (gb_tempCatEntryId != '') {formObj.appendChild(addInputElement("gb_tempCatEntryId", gb_tempCatEntryId));}
	if (gb_tempQty != '') {formObj.appendChild(addInputElement("gb_tempQty", gb_tempQty));}
	
	return formObj;
}

function addInputElement(astrName,astrValue){
	var element  = document.createElement("input");
	element.setAttribute("name",astrName);
	element.setAttribute("type","hidden");
	element.setAttribute("value",astrValue);
	return element;
}

/* This is the validation function that is called before the P&A check */
function isPreparedForPA(aFormToSubmit, aCatEntryIdsArray, aQtysArray) {

	var missingData = false;
	var zeroQty = true;
	/* This check is for IE, to flag as error if all qty are 0 */
	for (i=0; i<aQtysArray.length; i++) {
		if (aQtysArray[i] != 0) {
			zeroQty = false;
		}
	}
	if (zeroQty || notDefined(aQtysArray) || aQtysArray.length < 1) {
		alert(errorMsgs['Graybar_catalog_ERROR_NO_QTYS_FOR_PA']);
		missingData = true;
	}

	if (!missingData) {
		if (notDefined(aCatEntryIdsArray) || aCatEntryIdsArray.length < 1) {
			alert(errorMsgs['Graybar_catalog_ERROR_NO_ITEMS_FOR_PA']);
			missingData = true;
		}
	}
		
	if (missingData) {
		return false;
	}
	
	var copyIndex = 1;
	
	for (i = 0; i < aCatEntryIdsArray.length; i++) {
		if (aQtysArray[i] > 0) {
			aFormToSubmit.appendChild(addInputElement("catEntryId_"+copyIndex, aCatEntryIdsArray[i]));
			aFormToSubmit.appendChild(addInputElement("quantity_"+copyIndex, aQtysArray[i]));
			++copyIndex;
		}
	}
	
	if (!aFormToSubmit.URL) {
		aFormToSubmit.appendChild(addInputElement("URL", ""));				
	}

	if (!aFormToSubmit.orderId) {
		aFormToSubmit.appendChild(addInputElement("orderId", "."));
	}

	return true;
}

/* This is the validation function that is called before updating ship-to and will-call location */
function isPreparedForUpdate(aFormToSubmit, aCatEntryIdsArray, aQtysArray) {
	var missingData = false;
	var zeroQty = true;
	/* This check is for IE, to flag as error if all qty are 0 */
	for (i=0; i<aQtysArray.length; i++) {
		if (aQtysArray[i] != 0) {
			zeroQty = false;
		}
	}

	// if there is any qty entered for any of the items on the page, need to check for new P&A hence perform additional validation
	// o/w, skip this validation and with just updating ship-to and will-call location
	if (!zeroQty && !notDefined(aQtysArray) && aQtysArray.length > 0) {
		if (zeroQty || notDefined(aQtysArray) || aQtysArray.length < 1) {
			alert(errorMsgs['Graybar_catalog_ERROR_NO_QTYS_FOR_PA']);
			missingData = true;
		}
	
		if (!missingData) {
			if (notDefined(aCatEntryIdsArray) || aCatEntryIdsArray.length < 1) {
				alert(errorMsgs['Graybar_catalog_ERROR_NO_ITEMS_FOR_PA']);
				missingData = true;
			}
		}
			
		if (missingData) {
			return false;
		}
		
		var copyIndex = 1;
		
		for (i = 0; i < aCatEntryIdsArray.length; i++) {
			if (aQtysArray[i] > 0) {
				aFormToSubmit.appendChild(addInputElement("catEntryId_"+copyIndex, aCatEntryIdsArray[i]));
				aFormToSubmit.appendChild(addInputElement("quantity_"+copyIndex, aQtysArray[i]));
				++copyIndex;
			}
		}
	}
	
	if (!aFormToSubmit.URL) {
		aFormToSubmit.appendChild(addInputElement("URL", ""));				
	}
	
	if (!aFormToSubmit.orderId) {
		aFormToSubmit.appendChild(addInputElement("orderId", "."));
	}
	return true;
}

function validateShipping(aForm) {
	if (aForm.shipToLocation[document.PnASnippetForm.shipToLocation.selectedIndex].value == 'x') {
		alert ("Please select a valid shipto address");
		return false;
	}
	if (aForm.willCallCheckbox.checked && 
		aForm.willCallLocation[aForm.willCallLocation.selectedIndex].value == 'x') {
		alert ("Please select a valid willCall location");
		return false;
	}	
	return true;
}

/*
function add2favs(favsURL, catEntryIdArray, isNewFavsList) { 
	
	missingData = false;
		
	if (notDefined(catEntryIdArray) || catEntryIdArray.length < 1) {
		alert(errorMsgs['Graybar_catalog_ERROR_NO_ITEMS_FOR_FAVS']);
		missingData = true;
	}
		
	if (missingData) {
		return false;
	}

	//alert("before adding catentries, favsURL="+favsURL);
	for (i = 0; i < catEntryIdArray.length; i++) {
		if (isValidCatEntryId(catEntryIdArray[i])) {
			if (isNewFavsList) {
				favsURL += "&catEntryId_"+(i+1)+"=" + catEntryIdArray[i];
				// for now, quantity is hardcoded to 1 since UI does not accept a quantity input
				favsURL += "&quantity_"+(i+1)+"=1";
			}
			else {
				favsURL += "&catEntryId=" + catEntryIdArray[i];
				// for now, quantity is hardcoded to 1 since UI does not accept a quantity input
				favsURL += "&quantity=1";
			}
		}
	}
	//alert("after adding catentries, favsURL="+favsURL);
	
	location.href = favsURL;	
}*/

/*
function add2rfq(rfqURL, catEntryIdArray) { 
	
	missingData = false;
		
	if (notDefined(catEntryIdArray) || catEntryIdArray.length < 1) {
		alert(errorMsgs['Graybar_catalog_ERROR_NO_ITEMS_FOR_RFQ']);
		missingData = true;
	}
		
	if (missingData) {
		return false;
	}

	//alert("before adding catentries, rfqURL="+rfqURL);
	for (i = 0; i < catEntryIdArray.length; i++) {
		if (isValidCatEntryId(catEntryIdArray[i])) {
			rfqURL += "&catentryid=" + catEntryIdArray[i];
		}
	}
	//alert("after adding catentries, rfqURL="+rfqURL);
	
	location.href = rfqURL;	
}*/

function add2cart(orderForm, catEntryIdArray, qtyArray) { 
	
	missingData = false;
		
	if (notDefined(catEntryIdArray) || catEntryIdArray.length < 1) {
		alert(errorMsgs['Graybar_catalog_ERROR_NO_ITEMS_FOR_CART']);
		missingData = true;
	}	
	else if (notDefined(qtyArray) || qtyArray.length < 1) {
		alert(errorMsgs['Graybar_catalog_ERROR_NO_QTYS_FOR_CART']);
		missingData = true;
	}
		
	if (missingData) {
		// indicate that operation failed
		return false;
	}
		
	if (catEntryIdArray.length != qtyArray.length) {
		// this should only be caused by developer error, not user error
		alert("The number of items does not match the number of quantities.");
		// indicate that operation failed
		return false;
	}

	for (i = 0; i < catEntryIdArray.length; i++) {
		newElement = document.createElement("input");
		newElement.type = "hidden";
		newElement.name = "catEntryId_"+(i+1);
		newElement.value = catEntryIdArray[i];
		orderForm.appendChild(newElement);
	              
		newElement = document.createElement("input");
		newElement.type = "hidden";
		newElement.name = "quantity_"+(i+1);
		newElement.value = qtyArray[i];
		orderForm.appendChild(newElement);
	}
	
	orderForm.action='OrderItemAdd';
	orderForm.errorViewName.value = "CatalogItemAddErrorView";
	orderForm.URL.value='OrderItemDisplay?orderItemId=&quantity_*=&catEntryId_*=';
	//orderForm.URL.value='SetPendingOrder?URL=OrderCalculate?URL=OrderItemDisplay?orderId=.&updatePrices=1&calculationUsageId=-1';    
	//orderForm.URL.value='OrderCalculate?updatePrices=1&calculationUsageId=-1&calculationUsageId=-2&URL=OrderItemDisplay&orderId=&quantity*=';
	orderForm.submit();	
	return true;
}


var busy=false;



function validateFormData(catEntryIds, qtys, qtyMultiples) {

	// todo: add validation of inputs

	var cellErrorMsgsArray = new Array();
	// store number of cells with error msgs in first element of array for easy access
	cellErrorMsgsArray[0] = 0;

	// note: intentionally starting at i==1 since array at i==0 stores number of error cells
    for (var i = 1; i <= catEntryIds.length; i++) {		
		if (notEmpty(qtys[i-1])) {		
			if (isValidQtyValue(qtys[i-1])) {
				if (qtys[i-1] > 0 ) {
					// valid number, now check this qty is a multiple of the quantity multiple
					if ((parseInt(qtys[i-1]) % parseFloat(qtyMultiples[i-1]) )!= 0)
					{
						// error: qty not a multiple of the quantity multiple
						cellErrorMsgsArray[i] = errorMsgs['Graybar_catalog_ERROR_NOT_OF_QTY_MULTIPLE1'] + " " + qtyMultiples[i-1] + errorMsgs['Graybar_catalog_ERROR_NOT_OF_QTY_MULTIPLE2'];
					}
				}
				else {
					// error: qty is zero or negative
					
					// alert(errorMsgs['Graybar_catalog_ERROR_VALIDATION_QTY_LT_0']+(i+1));
					//invalidCellsArray[invalidCellsArray.length] = i;
					cellErrorMsgsArray[i] = errorMsgs['Graybar_catalog_ERROR_VALIDATION_QTY_LT_0'];
				}
			}			
			else {
				// error: qty is not valid but is specified
				
				//alert(errorMsgs['Graybar_catalog_ERROR_VALIDATION_QTY_NOT_NUM']+(i+1));
				//invalidCellsArray[invalidCellsArray.length] = i;				
				cellErrorMsgsArray[i] = errorMsgs['Graybar_catalog_ERROR_VALIDATION_QTY_NOT_NUM'];
			}
		}
		
		// if an error msg was added for this cell, increment number of error cells, otherwise set the
		// error msg for the current cell to empty string
		if (notEmpty(cellErrorMsgsArray[i])) {
			++cellErrorMsgsArray[0];
		}
		else {
			cellErrorMsgsArray[i] = "";
		}
	}
    return cellErrorMsgsArray;
}

// this method will return the URL parameter value given a parameter name
function getParamValue(paramName){
  //alert ("paramName="+paramName);
  var paramValue = "";
  var strURL = window.location.href;
  //alert ("strURL="+strURL);
  if ( strURL.indexOf("&") > -1 ){
    var initialQueryString = strURL.substr(strURL.indexOf("?"));
    var queryString = initialQueryString.split("&");
    for (var i=0; i<queryString.length; i++) {
      if (queryString[i].indexOf(paramName + "=") > -1) {
        var paramArray = queryString[i].split("=");
        paramValue = paramArray[1];

		// unescape the parameters on the URL and replace encoded space "+", before submitting to the form
		if (paramValue != '') {
			paramValue=unescape(paramValue).replace(/\+/g," ");
		}

        // remove occasional # sign substring at the end of parameter
        var poundIndex = paramValue.indexOf("#");
        if (poundIndex > -1) {
        	paramValue = paramValue.substring(0,poundIndex);
        }
        break;
      }
    }
  }
  return paramValue;
}