var origLeaf = null;
var origLeaf = null;
var origLeaf = null;
var itemInFocus = null;       // checkbox var (checkQuantity() and checkItemSelected())
var ITEM_DELIMITER = ",";
var ITEM_QTY_DELIMITER = ":";
var INITIAL_PAGE = "";

// navigation
var SEARCH = 0 ;
var TOC = 1 ;
var INDEX =2;
var CART =3;
var ADVANCED_SEARCH =4;
var CAT_SEARCH = 5;
var UNSPSC =6;
var ECLASS = 7;
var FAVORITES = 8;
var OTHER =10;

var USING_JSP = false;
//var USING_MATRIX = false;
var FROM_ITEMDETAIL = false;
var FROM_ITEMCOMPARE = false;
var FROM_ITEMVIEW = false;


var NETSCAPE_DELAY = 1000;

var previousFormValues = new Array();

// called by onMouseover="roll(this)"
// works in IE4 only
// changes color of button text
function roll(hrefRoll) {
   if (document.all) hrefRoll.style.color = "#C2AA8E";
   } // end roll

// called by onMouseout="unRoll(this)"
// works in IE4 only
// changes color of button text
function unRoll(hrefRoll) {
   if (document.all) hrefRoll.style.color = "white";
   } // end unRoll

function browseUNSPSCAdd() {
    setOriginalCategory();
    document.items.target = "";
    document.items.leaf.value = "0";
    document.items.cmd.value = "unspscadd";
    //browseCatWin = window.open("", "browseCatWin", "resizable=1,scrollbars=1,height=500,width=650,menubar=1,statusbar=1,location=0");
    //document.items.target = "browseCatWin";
    document.items.submit();
    //focusWin(browseCatWin);
}
function browseSupplierTOCAdd() {
    setOriginalCategory();
    document.items.target = "";
    document.items.leaf.value = "0";
    document.items.cmd.value = "suppliertocadd";
    //browseCatWin = window.open("", "browseCatWin", "resizable=1,scrollbars=1,height=500,width=650,menubar=1,statusbar=1,location=0");
    //document.items.target = "browseCatWin";
    document.items.submit();
    //focusWin(browseCatWin);
}

function ECMbrowseByAttribute( attrname ) {
    setActiveTab(OTHER);
    setAttrName(attrname);
    setOriginalCategory();
    document.items.target = "";
    document.items.leaf.value = "0";
    document.items.cmd.value = "ecmbrowseattr";
    document.items.indexbyattrname.value = attrname ;
    document.items, new Array("indexbyattrname")
    document.items.submit()
}

function ECMbrowseUNSPSC() {
    setOriginalCategory();
    document.items.target = "";
    document.items.leaf.value = "0";
    document.items.cmd.value = "ecmunspsc";
    document.items.submit();
}
function ECMbrowseECLASS() {
    setOriginalCategory();
    document.items.target = "";
    document.items.leaf.value = "0";
    document.items.cmd.value = "ecmeclass";
    document.items.submit();
}

function ECMBrowseCats() {
    setOriginalCategory();
    document.items.target = "";
    document.items.leaf.value = "0";
    document.items.cmd.value = "ecmbrowsecats";
    document.items, new Array("cmd")
    document.items.submit();
}
function browseCats() {
    setActiveTab(INDEX);
    setOriginalCategory();
    document.items.target = "";
    clearSearchSettings();
    document.items.cmd.value = "browsecats";
    document.items, new Array("cmd", "basecmd")
    document.items.submit();
}
function browseByAttribute( attrname ) {
    setActiveTab(OTHER);
    setAttrName(attrname);
    setOriginalCategory();
    document.items.target = "";
    clearSearchSettings();
    document.items.cmd.value = "browseattr";
    document.items.indexbyattrname.value = attrname ;
    //browseCatWin = window.open("", "browseCatWin", "resizable=1,scrollbars=1,height=500,width=650,menubar=1,statusbar=1,location=0");
    //document.items.target = "browseCatWin";
    document.items.submit();
    //focusWin(browseCatWin);
}
function browseTOC() {
    setActiveTab(TOC);
    document.items.target = "";
    var origLeaf = document.items.leaf.value;
    clearSearchSettings();
    document.items.cmd.value = "toc";
    document.items.itemcmd.value = "toc";
    //browseCatWin = window.open("", "browseCatWin", "resizable=1,scrollbars=1,height=500,width=650,menubar=1,statusbar=1,location=0");
    //document.items.target = "browseCatWin";
    document.items.submit();
    //focusWin(browseCatWin);
    //document.items.leaf.value = origLeaf;
}
function browseUNSPSC() {
    document.items.target = "";
    var origLeaf = document.items.leaf.value;
    clearSearchSettings();
    document.items.cmd.value = "unspsc";
    document.items.itemcmd.value = "unspsc";
    document.items.submit();
}
function browseSupplierTOC() {
    document.items.target = "";
    var origLeaf = document.items.leaf.value;
    clearSearchSettings();
    document.items.cmd.value = "suppliertoc";
    document.items.itemcmd.value = "suppliertoc";
    document.items.submit();
}
function browseRosettaNet() {
    document.items.target = "";
    var origLeaf = document.items.leaf.value;
    clearSearchSettings();
    document.items.cmd.value = "RosettaNet";
    document.items.itemcmd.value = "RosettaNet";
    document.items.submit();
}
function ECMbrowseRosettaNet() {
    setOriginalCategory();
    document.items.target = "";
    document.items.leaf.value = "0";
    document.items.cmd.value = "ecmRosettanet";
    document.items.submit();
}
function browseECLASS() {
    document.items.target = "";
    var origLeaf = document.items.leaf.value;
    clearSearchSettings();
    document.items.cmd.value = "eclass";
    document.items.itemcmd.value = "eclass";
    document.items.submit();
}
function ECMBrowseTOC() {
    document.items.target = "";
    var origLeaf = document.items.leaf.value;
    document.items.leaf.value = "0";
    document.items.cmd.value = "ecmtoc";
    document.items.itemcmd.value = "toc";
    document.items.submit();
}
function displayAdvancedSearch() {
    setActiveTab(ADVANCED_SEARCH);
    document.items.target = "";
    setQuickSearch();
    var origLeaf = document.items.leaf.value;
    //document.items.leaf.value = "0";
    document.items.cmd.value = "advancedsearch";
    //document.items.itemcmd.value = "toc";
    //browseCatWin = window.open("", "browseCatWin", "resizable=1,scrollbars=1,height=500,width=650,menubar=1,statusbar=1,location=0");
    //document.items.target = "browseCatWin";
    document.items, new Array("cmd")
    document.items.submit();

    //focusWin(browseCatWin);
    //document.items.leaf.value = origLeaf;
}
function displayECMAdvancedSearch() {
    document.items.target = "";
    var origLeaf = document.items.leaf.value;
    document.items.cmd.value = "ecmadvancedsearch";
    document.items.submit();
}

function setUnits( aValue ) {
    alert("setUnits");
    document.items.query.value = 'RefineSearch' ;
    //document.items.cmd.value = document.items.basecmd.value;
    document.items.itemcmd.value = "";
    //document.items.units.value = aValue;
    document.items.target = "";
    document.items.submit() ;
}

window.onerror=null;
browserName = navigator.appName;
browserVer = parseInt(navigator.appVersion);
if(browserName=="Netscape" && browserVer >= 4)
    supp = "yes";
else
    supp = "no";

function focusWin( aWin ) {
    if(supp == "yes") {
        aWin.focus();
    }
}

function changeSearchString( textString ) {
    document.items.quicksearch.value = textString;
    doQuery("Search");
}

function clearAllSelected()
{
    if( document.items.cachedSelectedItemIds.value.length == 0 || document.items.ItemCount.value == "0") {
        return;
    }

    document.items.cachedSelectedItemIds.value = "";
    document.items.cachedSelectedItemCategorys.value = "";
    displayNumItemsSelectedText();

    if( document.items.item.length == null ) {
        document.items.item.checked = false;
    }
    else {
        for( i = 0; i < document.items.item.length; i++ ) {
            document.items.item[i].checked = false;

            if ( document.items.cmd.value != 'favorites' && eval("document.items.qty_" + document.items.item[i].value)) {
                eval("document.items.qty_" + document.items.item[i].value + ".value=''");
            }
        }
    }
}

function clearAll(myForm) {
    var val;

    if(myForm.item.length == null) {
        myForm.item.checked = false;

        var itemCatStr = ':' + myForm.item + ':' + myForm.itemcategory;
        myForm.cachedSelectedItemCategorys.value = myForm.cachedSelectedItemCategorys.value.replace('|' + itemCatStr, '');
        myForm.cachedSelectedItemIds.value = myForm.cachedSelectedItemIds.value.replace('|' + myForm.item, '');
    } else {
        for(i=0; i < myForm.item.length; i++) {
            myForm.item[i].checked = false;
            val = myForm.item[i].value;
            myForm.cachedSelectedItemIds.value = myForm.cachedSelectedItemIds.value.replace('|' + val, '');

            var itemCatStr = ':' + myForm.item[i].value + ':' + myForm.itemcategory[i].value;
            myForm.cachedSelectedItemCategorys.value = myForm.cachedSelectedItemCategorys.value.replace('|' + itemCatStr, '');

            if (document.items.cmd.value != 'favorites' && eval("myForm.qty_" + val)) {
                eval("myForm.qty_" + val + ".value=''");
            }
        }
    }
    displayNumItemsSelectedText();

}
function resetForm() {
    document.items.itemcmd.value = "";
    document.items.target = "";
}
function quickSearch( queryVal ) {
   setActiveTab(SEARCH);
   document.items.cmd.value = document.items.basecmd.value;
   // Vinaya : added check the line below makes no sense!!
   // document.items, createQuickSearchFields()
   if (!alreadySubmitted( document.items, createQuickSearchFields()) ) {
        doQuery( queryVal );
    }
}

function queryRange( startAt ) {
    document.items.currentitem.value =  startAt;
    document.items.query.value = "Next";
    document.items.submit();
}

function doQuery( queryVal ) {
    if (document.items.cmd.value == 'favorites') {
        document.items.basecmd.value = 'favorites';
    }
    else {
        document.items.cmd.value = document.items.basecmd.value;
    }
    reallyDoQuery( queryVal ) ;
}



function setupDoQuery( queryVal ) {
  //alert("cmd="+    document.items.cmd.value + ", basecmd=" + document.items.basecmd.value ) ;
    document.items.itemcmd.value = "";
    document.items.target = "";
    document.items.query.value = queryVal;
    setQuickSearch();
    if(queryVal == "Next") {
        resetCategory();
        document.items.currentitem.value = document.items.nextitem.value;
    } else {
       //if(document.items.usingtextsearch != null) {
       if(document.items.quicksearch != null && document.items.quicksearch.value != "") {
          document.items.usingtextsearch.value = "T";
       }
       else if ((document.items.parametrictoset != null && document.items.parametrictoset.value!= null &&  document.items.parametrictoset.value!= "") || (document.items.parametrics != null && document.items.parametrics.value!= null &&  document.items.parametrics.value!= ""))
       {
          document.items.usingtextsearch.value = "F";
       }
        if(document.items.currentitem != null) {
            document.items.currentitem.value = 1;
        }
    }
    if(queryVal == "Search") {
       clearSearchSettings();
    }
}

function reallyDoQuery( queryVal ) {
    setupDoQuery( queryVal );
    document.items.submit();
}

function setQuickSearch(){
   if(document.entersubmit != null){
      document.items.quicksearch.value=document.entersubmit.searchtext.value;
   }
}

function compare( leaf, newWin) {
/*
    This is a check to stop compare from executeing when there are no items
    if((document.items.item.length == null && document.items.item.value == null) ||
       (document.items.item.length != null && document.items.item[0].value == null)){
        alert("No items to compare.");
        return;
    }
*/
    var numitems = 1;
    if(numItemsSelected() == 0) {
        numitems = setAll(document.items);
    }
    if (numitems > 0) {
        setOriginalCategory();
        //If the leaf id is 0 then we are not in a leaf search so check and see if the select items are all
        //in the same category.  If they are then set the leaf so compare will show the leaf attributes.
        compareCatResult = compareCategories();
        if( leaf == "0" && compareCatResult ) {
            var itemCatArray = document.items.cachedSelectedItemCategorys.value.split('|');
            var currentItemArray = itemCatArray[1].split(':');
            document.items.leaf.value = currentItemArray[2];

        }
        //Make sure leaf form parameter is set to zero if the item categories are not all the same
        else if( leaf == "0" || !compareCatResult ) {
            document.items.leaf.value = "0";
        }
        document.items.itemid.value = '';
        document.items.cmd.value = "compare";

        stashQtyAndChecks();

        if(newWin) {
            editWin= window.open( "","editWin", "resizable=1,scrollbars=1,height=500,width=650,menubar=1,statusbar=1,location=0");
            document.items.target = "editWin";
            document.items.submit();
            focusWin(editWin);
        } else {
            document.items.target= "";
            document.items.submit();
        }
    }
    else {
        alert(noItemsSelected);
    }
}

function displayStatus(msg) {
    window.status= msg;
}

function displayUrl( theUrl ) {
    urlWin= window.open( theUrl,"urlWin","resizable=1,scrollbars=1,height=550,width=750,menubar=1,location=0");
    focusWin(urlWin);
}

function displayHelp ( url ) {
   helpWin= window.open( url,"urlWin","resizable=1,scrollbars=1,height=550,width=550,menubar=1,location=0");
   focusWin(helpWin);
}

function displayConfigHelp ( helpRoot ) {
      var fileName = "";

      if(document.properties.selectedTab.value != ""){

          var tabName =  document.properties.selectedTab.value.toLowerCase();

          //replace periods

          tabName = replace(tabName, ".", "_");

          //replace spaces

          tabName = replace(tabName, " ", "_");

          fileName = document.properties.cmd.value + "_" + tabName + ".html";

      }

      var url = helpRoot + fileName;

      //alert("Help url: " + url);

      helpWin= window.open( url,"urlWin","resizable=1,scrollbars=1,height=550,width=550,menubar=1,location=0");

      focusWin(helpWin);

      }


function replace(str, oldStr, newStr){

    var start = 0;

    var end = str.length;

    var index = str.indexOf(oldStr);

    var finalString = "";

    while(index > -1 && index < end){

        finalString += str.substring(start, index) + newStr;

        start = index + newStr.length;

        index = str.indexOf(oldStr, start);

    }

    finalString += str.substring(start, end);

    return(finalString);

}



function displayGlossary ( url ) {
   glossaryWin= window.open( url,"urlWin","resizable=1,scrollbars=1,height=550,width=750,menubar=1,location=0");
   focusWin(glossaryWin);
}

function doNext(){
    window.history.forward();
}

/*
 This function is for the previous button only
 */
function doPrev() {

   // iterate over selected item
   for( i = 0; i < document.items.item.length; i++ ) {
       if( document.items.item[i].checked ) {
            var itemId = document.items.item[i].value;

            if( (qty = eval("document.items.qty_" + itemId)) ) {
                if( qty.value == '' ) {
                    qty.value = '1';
                }
                document.returnform.cartItemQuantities.value += '|' + itemId + ':' + qty.value;
            }
       }
   }

   document.returnform.cachedSelectedItemIds.value= document.items.cachedSelectedItemIds.value;
   document.returnform.cachedSelectedItemCategorys.value = document.items.cachedSelectedItemCategorys.value;
   document.returnform.currentitem.value= document.items.previtem.value;
   document.returnform.submit() ;
}
/*
 This function is to be used in place of history back
 */
function doBack() {
   document.returnform.submit() ;
}

function stashQtyAndChecks() {
    // add all selected items on the page to the returnurl
    var itemsChecked = "";
    var itemQuantities = "";
    for (i = 0; i < document.items.elements.length; i++) {
      var element = document.items.elements[i];
      if (element.name == "item" && element.checked == true) {
        if (itemsChecked.length < 1) {
          itemsChecked += element.value;
        }
        else {
          itemsChecked += ITEM_DELIMITER + element.value;
        }

        //Also grab the quantity fields which are specified
        if (eval("document.items.qty_" + element.value)) {
          var checkBox = eval("document.items.qty_" + element.value);
          if (checkBox.value != '') {
               itemQuantities += element.value +  ITEM_QTY_DELIMITER + checkBox.value + ITEM_DELIMITER;
          }
        }
      }
    }
    document.items.returnurl.value += "&selectedItems=" + itemsChecked + "&itemQuantities=" + itemQuantities;
    if( document.items.selecteditems != null)
      document.items.selecteditems.value= itemsChecked;

}

function itemDetail( item, leaf, newWin, templateurl,supskunum) {
    var basecmdorig = document.items.basecmd.value;
    var cmdorigval =  document.items.cmd.value;
    var itemorig =  document.items.itemid.value;
    var targetorig = document.items.target;

    document.items.basecmd.value = document.items.cmd.value;
    document.items.cmd.value = "itemdetail";
    document.items.itemid.value = item;

    //this should be defined in itemview.html
    if(document.items.supskunum != null)
       document.items.supskunum.value= supskunum;

    setOriginalCategory();
    document.items.leaf.value = leaf;
    stashQtyAndChecks();
    if(templateurl != null){
       document.items.templateurl.value = templateurl;
    }
    else{
       document.items.templateurl.value= "";
    }
    if(newWin) {
        itemDetailWin= window.open("","itemDetailWin", "resizable=1,scrollbars=1,height=500,width=650,menubar=1,statusbar=1,location=0");
        document.items.target = "itemDetailWin";
        document.items.submit();
        focusWin(itemDetailWin);
        if (navigator.appName == 'Netscape') {
             sleepseconds(1);
        }
    } else {
        document.items.target = "";
        document.items.submit();
        if (navigator.appName == 'Netscape') {
             sleepseconds(1);
        }
    }
	document.items.basecmd.value = basecmdorig;
	document.items.cmd.value = cmdorigval;
	document.items.itemid.value = itemorig;
	document.items.target = targetorig;
}

function numItemsSelected(){
    var numItems = 0;

    var array = document.items.cachedSelectedItemIds.value.split('|');
    return array.length-1;
}

function setAll(myForm) {
   var numItems = 0;

    if(myForm.item && myForm.item.length == null) {
        myForm.item.checked = true;

        addItemSelectedEntry(myForm.item.value, myForm.itemcategory.value);
        numItems++;
    }
    else {
        if (myForm.item) {
            for(i=0; i < myForm.item.length; i++) {
               if (eval("myForm.item[i]")) {
                   myForm.item[i].checked = true;
                   addItemSelectedEntry(myForm.item[i].value, myForm.itemcategory[i].value);
                   numItems++;
               }
            }
        }
    }
    displayNumItemsSelectedText();
    return numItems;
}

function setAllFromButton(myForm) {
   setAll(myForm);
}


function setCategory( catid ) {
    document.items.quicksearch.value = document.items.origquicksearch.value ;
    document.items.leaf.value = catid;
    doQuery("RefineSearch");
}

function setCategoryLB(){
    resetCategory();
    ind = document.items.categorynamelb.options.selectedIndex;
    document.items.categoryname.value = document.items.categorynamelb.options[ind].value;
    doQuery("RefineSearch");
}

function setParametrics( aValue ) {
    document.items.query.value = 'RefineSearch' ;
    if (aValue == null || aValue == "") {
       if (document.items.parametricsCount.value > 0)
            document.items.usingtextsearch.value= 'true';
       document.items.query.value = 'Search' ;
    }
    if (document.items.cmd.value != 'favorites') {
        document.items.cmd.value = document.items.basecmd.value;
    }
    //document.items.cmd.value = document.items.basecmd.value;
    document.items.itemcmd.value = "";
    document.items.parametrics.value = aValue;
    if (aValue == "" && document.items.quicksearch.value== "" && document.items.leaf.value != "") {
        document.items.leafsearch.value= 'T';
    }
    document.items.target = "";
    document.items.submit() ;
}

function searchByParametrics( aValue ) {
    document.items.query.value = 'RefineSearch' ;
    document.items.cmd.value = document.items.basecmd.value;
    //alert("cmd="+    document.items.cmd.value + ", basecmd=" + document.items.basecmd.value ) ;

    document.items.itemcmd.value = "";
    document.items.quicksearch.value = "";
    document.items.categories.value = "";
    document.items.categoriescounts.value = "";
    document.items.parametrics.value = aValue;
    document.items.usingtextsearch.value = 'F';
    document.items.target = "";
    if ( !alreadySubmitted( document.items, new Array("cmd","parametrics" ) ) ) {
        document.items.submit() ;
    }
}

function resetCategory(){
    if(origLeaf != null) {
        document.items.leaf.value = origLeaf;
    }
}

function setOriginalCategory(){
    if(origLeaf == null) {
        origLeaf = document.items.leaf.value;
    }
}

function setSort( sort ) {
    resetCategory();
    document.items.sortparams.value = sort;
    doQuery("RefineSearch");
}

function setViewMode( modeString ) {
    resetCategory();
    document.items.tableview.value = modeString;
    doQuery("RefineSearch");
}
function showWindow( desc, isRoot ) {
    showWindowItemCmd( desc, isRoot, "dispsetdesc" );
}

function showWindowItemCmd( desc, isRoot, itemcmd ){

    var descOrig = document.items.desc.value;
    var itemCmdOrig =  document.items.itemcmd.value;
    var cmdOrig =  document.items.cmd.value;
    var baseCmdOrig =  document.items.basecmd.value;
    var targetOrig = document.items.target;
    var isRootOrig = document.items.isroot.value;

    setQuickSearch();
    if (self.name == "") {
    self.name = "itemWindow";
    }

    if (document.items.cmd.value != 'favorites') {
        document.items.cmd.value = document.items.basecmd.value;
    }
    else {
        document.items.basecmd.value = 'favorites';
    }

    document.items.itemcmd.value = itemcmd;
    document.items.isroot.value = isRoot;
    document.items.desc.value = desc;
    if ( !alreadySubmitted( document.items, new Array("itemcmd", "isroot", "desc" ) ) ) {
        var manWin= window.open( "","manWin", "resizable=1,height=550,width=450,menubar=0,location=0,scrollbars=1");
        document.items.target = "manWin";
        document.items.submit();
        focusWin(manWin);
    }
    document.items.desc.value = descOrig;
    document.items.itemcmd.value = itemCmdOrig;
    document.items.cmd.value = cmdOrig;
    document.items.basecmd.value = baseCmdOrig;
    document.items.target = targetOrig;
    document.items.isroot.value = isRootOrig;
}

function clearParamsAndSubmit(){
    document.items.cmd.value = document.items.basecmd.value;
    document.items.categories.value = "";
    document.items.parametrics.value = "";
    document.items.sortparams.value = "";
    //document.items.target = window.opener.name;
    document.items.submit();
    //self.close();
}


function viewQuery(queryVal) {
    document.items.quicksearch.value = queryVal;
    document.items.query.value = 'Search';
    document.items.leafsearch.value = 'F';
    document.items.leaf.value = '0';
    clearParamsAndSubmit();
}
function update() {
    resetCategory();
    document.items.cmd.value = document.items.basecmd.value;
    document.items.itemcmd.value = '';
    document.items.query.value = 'RefineSearch';
    document.items.target = '';
    document.items.submit();
}
function editItem( item, leaf ) {
    document.items.cmd.value = 'edititem';
    document.items.itemid.value = item;
    setOriginalCategory();
    document.items.leaf.value = leaf;
    editWin= window.open( "","editWin","resizable=1,scrollbars=1,height=500,width=650,menubar=1,statusbar=1,location=0");
    document.items.target = 'editWin';
    document.items.submit();
    focusWin(editWin);
}

function displayPriceHistory( leaf, setAllItems ) {

    if ((numItemsSelected() == 0) && (setAllItems == false)) {
       alert("No Items are selected");
       return;
    }
    document.items.cmd.value = 'pricehistory';
    setOriginalCategory();
    document.items.leaf.value = leaf;
    editWin= window.open( "","editWin", "resizable=1,scrollbars=1,height=500,width=850,menubar=1,statusbar=1,location=0");
    document.items.target = "editWin";
    document.items.submit();
    focusWin(editWin);
}

function editMultItemForPCM( leaf, setAllItems, itemcmd ) {
    editMultItemBase( leaf, setAllItems, itemcmd, 'pcmedititem' );
}

function deleteMultItemForPCM( leaf, setAllItems, itemcmd ) {
    if(setAllItems == true) {
       var numItems = setAll(document.items);
       if (numItems == 0) {
          alert(noItemsSelected);
          return;
       }
    } else if ((numItemsSelected() == 0) && (setAllItems == false)) {
       alert(noItemsSelected);
       return;
    }
    if (!confirm(thisWillDelete + " " + numItemsSelected() + " " + numItemsString))
      return;
    document.items.cmd.value = 'pcmedititem';
    document.items.itemcmd.value = itemcmd;
    setOriginalCategory();
    document.items.leaf.value = leaf;
    editWin= window.open( "","editWin", "resizable=1,scrollbars=1,height=500,width=650,menubar=1,statusbar=1,location=0");
    document.items.target = "editWin";
    document.items.submit();
    focusWin(editWin);
}

function editMultItem( leaf, setAllItems, itemcmd ) {
    editMultItemBase( leaf, setAllItems, itemcmd, 'edititem' );
}

function editMultItemBase( leaf, setAllItems, itemcmd, cmd ) {
    if( setAllItems == true ) {
        var numItems = setAll(document.items);
        if (numItems == 0) {
           alert(noItemsSelected);
           return;
        }
    } else if ((numItemsSelected() == 0) && (setAllItems == false)) {
       alert(noItemsSelected);
       return;
    }

    document.items.cmd.value = cmd;
    document.items.itemcmd.value = itemcmd;
    setOriginalCategory();
    document.items.leaf.value = leaf;
    editWin= window.open( "","editWin", "resizable=1,scrollbars=1,height=500,width=800,menubar=1,statusbar=1,location=0");
    document.items.target = "editWin";
    document.items.submit();
    focusWin(editWin);
}

function deleteMultItem( leaf, setAllItems, itemcmd ) {
    if(setAllItems == true) {
       var numItems = setAll(document.items);
       if (numItems == 0) {
          alert(noItemsSelected);
          return;
       }
    } else if ((numItemsSelected() == 0) && (setAllItems == false)) {
       alert(noItemsSelected);
       return;
    }
    if (!confirm(thisWillDelete + " " + numItemsSelected() + " " + numItemsString))
      return;

    // reset te current item if the deletion will cause the current page to be invalid
    if( document.items.currentitem.value > document.items.ItemCount.value-numItemsSelected() ) {
       document.items.currentitem.value= document.items.previtem.value;
    }

    document.items.cmd.value = 'edititem';
    document.items.itemcmd.value = itemcmd;
    setOriginalCategory();
    document.items.leaf.value = leaf;
    editWin= window.open( "","editWin", "resizable=1,scrollbars=1,height=500,width=650,menubar=1,statusbar=1,location=0");
    document.items.target = "editWin";
    document.items.submit();
    document.items.cachedSelectedItemIds.value = "";
    document.items.cachedSelectedItemCategorys.value = "";
    focusWin(editWin);
}

function compareCategories(){

    if( document.items.cachedSelectedItemCategorys.value.lastIndexOf('|') == 0 ) {
        return true;
    }
    else {
        firstval = "";

        var itemCatArray = document.items.cachedSelectedItemCategorys.value.split('|');
        for( i = 1; i < itemCatArray.length; i++) {
            var currentItemArray = itemCatArray[i].split(':');
            if( firstval == "" ) {
                firstval = currentItemArray[2];
            }
            else if( firstval != currentItemArray[2]) {
                return false;
            }
        }
    }
    return true;
}

function editCategory( leaf ) {
    if( compareCategories()) {
        if(numItemsSelected() == 0) {
            alert(classifyItemError);
            return;
        }
        document.items.cmd.value = 'classify';
        setOriginalCategory();
        document.items.leaf.value = leaf;
        editWin = window.open( "","editWin","resizable=1,scrollbars=1,height=500,width=650,menubar=1,statusbar=1,location=0");
        document.items.target = "editWin";
        document.items.submit();
        focusWin(editWin);
    } else {
        alert(itemMoveMessage);
    }
}

function configureItem(itemid, leaf, configUrl, newWin){
    document.items.cmd.value = 'itemconfigurator';
    document.items.configuratorurl.value = configUrl;
    setOriginalCategory();
    document.items.leaf.value = leaf;
    document.items.itemid.value= itemid;
    if(newWin == 'T' || newWin=='t') {
        configuratorWin = window.open("","configuratorWin","resizable=1,scrollbars=1,height=500,width=650,menubar=1,statusbar=1,location=0");
        document.items.target = "configuratorWin";
        document.items.submit();
        focusWin(configuratorWin);
    } else {
        document.items.target = "";
        document.items.submit();
    }
}

function addToCartWithAddDesc( item, pricenum, adddesc){


    var cartcmd = "cartcmd=addanddisplay&item=";
    cartcmd += item;
    if(pricenum != "")
        cartcmd += "&secondKey=" + pricenum;
    if(adddesc != "")
        cartcmd += "&adddesc=" + adddesc;
    displayCartCmd( cartcmd );
}

function addToCart( item, pricenum){

   //request is from itemdetail view with matrix data
  if(FROM_ITEMDETAIL == true) {
      //alert("++ request is from itemdetail");
      if(allSelected() == 0)  {
         /* For localisation purpose "selectMatrixAttrib" can be used as a variable name and
            can be initialised to a property value in the template.
            eg.in template where addToCart() is called add the line
            var selectMatrixAttrib = "%BUGSEYE_PROPERTY_selectMatrixAttrib%";
         */
         //alert(selectMatrixAttrib)
         alert("Please select all matrix attributes.")
         return
      }
    }

    //request is from item compare
    else if(FROM_ITEMCOMPARE == true || FROM_ITEMVIEW == true) {
        if(hasMatrix(item) == true)  {
        //alert("++ this request is from item compare")

            for(var k = 0; k < matrixCount; k++) {
               if(matrixData[k].itemid == item) {
                  itemDetail(matrixData[k].itemid, matrixData[k].catid, false, "");
                  return;
               }
            }
        }

      }

    document.items.itemid.value= item;
    if(pricenum != "")
        document.items.secondKey = pricenum;

    displayCartCmd("addanddisplay");
}


function addToCartUsingPopup( item, pricenum, message ) {
    document.items.itemid.value= item;
    if(pricenum != "") {
      document.items.secondKey = pricenum;
    }
    document.items.cartcmd.value = 'addanddisplay';
    document.items.cmd.value = 'cart';
    document.items.target = "cartWin";

    document.items.submit();
}
//EMS-755
function removeFromNoProcurableItemIDs(itemId){
	if(ifIncludeNoProcurableItemIDs!=null&&ifIncludeNoProcurableItemIDs!='')
	{
		if( ifIncludeNoProcurableItemIDs.indexOf(itemId) != -1 )
		 {
        ifIncludeNoProcurableItemIDs = ifIncludeNoProcurableItemIDs.replace('|' + itemId, '');
		}
	}
}

function isProcurable() {
	//EMS-755
	if(ifIncludeNoProcurableItemIDs!=null&&ifIncludeNoProcurableItemIDs!=''){
		alert(nonProcurableMsg);
		return false;
	}

	var allProcurable = true;

	//If no items are selected return true so the standard message will be displayed
	if(numItemsSelected() == 0)
		return true;

	//If there is only one item then it is the selected item
	if(document.items.item.length == null) {

		//Get the items procurable status
		if(procurableFlags.length == 1) {
			allProcurable = procurableFlags[0];
		}

	//If there are multiple items find the ones that are selected
	} else {
		for (i=0; i < document.items.item.length; i++) {
			//If the item is selected check its procurable status
        	if (document.items.item[i].checked) {
        		if(i < procurableFlags.length) {
        			if(!procurableFlags[i]) {
        				allProcurable = false;
        				break;
        			}
        		}
        	}
        }
	}

	//Display the message to the user if some items are not procurable
	if(!allProcurable)
		alert(nonProcurableMsg);

	//Return the procurable status of the items
	return allProcurable;
}
function addToDirectToExternalCart( item, pricenum, message ) {
   document.items.itemid.value= item;
   if(pricenum != "")
       document.items.secondKey = pricenum;
   displayCartCmd("addAndDirectPost");
}

function addToDirectToExternalCartToggle () {
    document.items.itemid.value="";
    if(numItemsSelected() == 0) {
        //noItemsSelectedCart is a global variable dynamically set in the template
        alert(noItemsSelectedCart);
        return;
    }

    displayCartCmd("addAndDirectPost");
}

//need to display itemdetail for this item, safe ?
var hasMatrixDisplay = false;

function addToCartUsingToggle() {

   document.items.itemid.value="";
   //ems747
   document.items.cmd.value = "cart";
   
    if(numItemsSelected() == 0) {
        //noItemsSelectedCart is a global variable dynamically set in the template
        alert(noItemsSelectedCart);
        return;
    }

    var matrixlist = new Array();
    var mlistcounter = 0;
    var checkednonmatrixitemcount = 0;

    //only one item in the view
//    if(document.items.item.length == null) {
//      if(document.items.item.checked) {
//         if(hasMatrix(document.items.item.value) == true) {
//       document.items.item.checked = false;
//            matrixlist[0] = document.items.item.value;
//         }
//       }
//    }
//    else {
//        mlistcounter = 0;
//        checkednonmatrixitemcount = 0;
//      for(var i = 0; i < document.items.item.length; i++) {
//          if (eval("document.items.item[i]")) {
//              if(document.items.item[i].checked) {
//                   if(hasMatrix(document.items.item[i].value) == true) {
//                      document.items.item[i].checked = false;
//                      matrixlist[mlistcounter] = document.items.item[i].value;
//                      mlistcounter++;
//                   }
//                   else
//                      checkednonmatrixitemcount++;
//               }
//            }
//        }
//    }

    //EMS-785
    if(document.items.cachedSelectedItemIds.value.length > 0){  
       var cachedSelectedItems = document.items.cachedSelectedItemIds.value.split('|');       
       for(var i = 0; i < cachedSelectedItems.length; i++) {
         if(cachedSelectedItems[i] != ""){
           if(hasMatrix(cachedSelectedItems[i]) == true) {
                  matrixlist[mlistcounter] = cachedSelectedItems[i];
                  mlistcounter++;                           
           }else
              checkednonmatrixitemcount++;   
          }                        
       }
    }    


    if(matrixlist.length == 1)
       hasMatrixDisplay = true;
    else
       hasMatrixDisplay = false;

    //if only one selected item and it has matrix
    if(matrixlist.length == 1 && checkednonmatrixitemcount == 0) {
        displayListForMatrix(matrixlist);

    }
    else {

       //contral the sequence of function calls so that windows can displayed correctly
       if(matrixlist.length == 1) {
          displayCartCmd('addanddisplay');
          //ems-764 call  displayListForMatrix(matrixlist) first.
          displayListForMatrix(matrixlist);
          clearAllSelected();

       }else {
          displayListForMatrix(matrixlist);
          displayCartCmd('addanddisplay');
          clearAllSelected();
       }
    }
}

function displayListForMatrix(matrixlist)
{

   var  tmp = "";
   var  foundmatrix = false;

   //no item with matrix is selected
   if(matrixlist.length < 1) {
      return;
   }
   //only one selected item with matrix
   else if(matrixlist.length == 1){
       for(var k = 0; k < matrixCount; k++) {
          if(matrixData[k].itemid == matrixlist[0]) {
          //ems-764
          var qtyComp = document.getElementsByName("qty_"+matrixData[k].itemid)[0];
          if(qtyComp){
             var qty = qtyComp.value;
          	 	if(qty!=null){
          	 			qty = qty.replace(/(^\s*)|(\s*$)/g, "");
          	 	}
          	 	if(qty.length==0){
          	 	  	qtyComp.value=1;
          	 		}
          }     	 		        
             itemDetail(matrixData[k].itemid, matrixData[k].catid, false, "");
             return;
          }
       }
   }

   awin=window.open("","mywindow","resizable=1,scrollbars=1,height=250,width=350,location=0");
   awin.moveTo(50,50);
   awin.focus()

   awin.document.write("<strong>The following items are not added to shopping cart since they have matrix data. Please go back to prevous page and click on detail icon for the items shown on this list then add this item from the item detail view. This window is informative window only. \n");
   awin.document.write("<TABLE width=100% align='center' cellspacing='1' cellpadding='1' border='1'>");

   awin.document.write("<TR bgcolor=7f7f7f align='center' size='1'><TH>Category</TH><TH>Mfg Name</TH><TH>Mfg Part Num</TH><TH>Sup Name</TH><TH>Sup Part Num</TH></TR>");

   for(var i = 0; i < matrixCount; i++)
   {
      foundmatrix = false;

      for(var j = 0; j < matrixlist.length; j++)
          if(matrixlist[j] == matrixData[i].itemid)
              foundmatrix = true;

      if(foundmatrix == false)
         continue;

      awin.document.write("<TR>");

      tmp = matrixData[i].category;
      if(tmp == null || tmp.length == 0)
         tmp= "&nbsp";
      awin.document.write("<TD valign='top' align='center'>" + tmp + "</TD>");

      tmp = matrixData[i].mfgname;
      if(tmp == null || tmp.length == 0)
         tmp= "&nbsp";
      awin.document.write("<TD valign='top' align='center'>" + tmp + "</TD>");

      tmp = matrixData[i].mfgpartnum;
      if(tmp == null || tmp.length == 0)
         tmp= "&nbsp";
      awin.document.write("<TD valign='top' align='center'>" + tmp + "</TD>");

      tmp = matrixData[i].supname;
      if(tmp == null || tmp.length == 0)
         tmp= "&nbsp";
      awin.document.write("<TD valign='top' align='center'>" + tmp + "</TD>");

      tmp = matrixData[i].suppartnum;
      if(tmp == null || tmp.length == 0)
         tmp= "&nbsp";
      awin.document.write("<TD valign='top' align='center'>" + tmp + "</TD></TR>");
   }

   awin.document.write("</TABLE>");

   awin.document.write("<FORM><INPUT TYPE='BUTTON' align='center' VALUE='Close' onClick='javascript:window.close()'></FORM>");

}

function hasMatrix( itemID )
{
   var id;
   var i = 0;
   for(i = 0; i < matrixCount; i++)
   {
      if(matrixData[i].itemid == itemID)
          return true;
   }
   return false;
}

function addToCartUsingToggleWithAddURL( addUrl ) {
    document.items.itemid.value="";
    var cartcmd = "cartcmd=addanddisplay";
    itemString = getSelectedItems();
    if(itemString != "") {
        cartcmd += itemString;
        cartcmd += "&" + addUrl;
        displayCartCmd( cartcmd );
        clearAllSelected();
    }
}

function addToCartUsingToggleValidate() {
    document.items.itemid.value="";
    var cartcmd = "addanddisplay";
    itemString = getSelectedItemsValidate( document.items.itemstatus);
    if(itemString != "") {
        cartcmd += itemString;
        displayCartCmd( cartcmd );
        clearAllSelected();
    }
}

function displayCart() {
    setActiveTab(CART);
    displayCartCmd('display');
}

// ----------------------------------------------------------
// ADDED FOR GEXPRO

function getSkuForSelectedItems(){
       var itemString = document.items.cachedSelectedSkuNums.value;
       var checked=0;
       if ( document.items.item.length == null) {
          if (document.items.item.checked) {
             checked=1;
             iValue = document.items.item.value;
             itemString += "|" + eval("document.items.supskunum_"+iValue+".value");
             //alert("added "+itemString);
          }
       } else {
          for (i=0; i < document.items.item.length; i++) {
             if (document.items.item[i].checked) {
                checked=1;
                iValue = document.items.item[i].value;
                itemString += "|" + eval("document.items.supskunum_"+iValue+".value");
                        //alert("added "+itemString);
             }
          }
       }
       if (checked==0) {
          alert("No Items are selected");
       }
       document.items.cachedSelectedSkuNums.value=itemString;
  }


function displayCartCmd(cartCmd){

    if(cartCmd=="addanddisplay") {
	if(FROM_ITEMVIEW) {getSkuForSelectedItems();}
        var itemString = document.items.cachedSelectedSkuNums.value;
        document.items.cachedSelectedSkuNums.value="";
        if(FROM_ITEMVIEW) { clearAllSelected();}
    	parent.addToCart(itemString);
    }

/* ----------------------------------------------------------

    document.items.target = "";
    document.items.cartcmd.value = cartCmd;
    document.items.cmd.value = 'cart';
    //document.items.basecmd.value = 'item';
    //displayCartInSameWindow is a global variable set in the template
    if(!hasMatrixDisplay && displayCartInSameWindow) {

       document.items.target = "";
       document.items.submit();

    } else {
        cartWin = window.open( "","cartWin","resizable=1,scrollbars=1,height=400,width=650,menubar=1,statusbar=1,location=0");
        document.items.target = "cartWin";
        document.items.submit();
        cartWin.focus();

        if(hasMatrixDisplay) {

            sleepseconds(3);
            cartWin.close();
        }
    }
--------------------------------------------------------------- */   
}

function displayFavorites() {
    //clearSearchSettings();
    document.items.usingtextsearch.value = "";
    document.items.quicksearch.value = "";
    document.items.leaf.value = 0;
    document.items.sortparams.value = "";
    document.items.parametrics.value = "";
    document.items.categories.value = "";
    document.items.categoriescounts.value = "";
    if(document.items.leafsearch != null) {
       document.items.leafsearch.value = "";
    }
    setActiveTab(FAVORITES);
    displayFavoritesCmd ('');
}

function displayFavoritesCmd(cmd){

    document.items.target = "";
    document.items.itemcmd.value = cmd;
    document.items.cmd.value = 'favorites';
    document.items.basecmd.value = 'item';
    //displayCartInSameWindow is a global variable set in the template

    //favoritesWin = window.open( "","favoritesWin","resizable=1,scrollbars=1,height=400,width=650,menubar=1,statusbar=1,location=0");
    //document.items.target = "favoritesWin";
    document.items.submit();
    //favoritesWin.focus();

}

function addToFavorites (){

    getSkuForSelectedItems();
    var itemString = document.items.cachedSelectedSkuNums.value;
    document.items.cachedSelectedSkuNums.value="";
    clearAllSelected();
    
    if (itemString !="") {
    	parent.addToCatalog(itemString);
    }
        
    /* --------------------------------------------------    

    document.items.itemid.value="";
    if(numItemsSelected() == 0) {
        //noItemsSelectedCart is a global variable dynamically set in the template
        alert(noItemsSelectedCart);
        return;
    }

    //clearSearchSettings();
    document.items.usingtextsearch.value = "";
    document.items.leaf.value = 0;
    document.items.sortparams.value = "";
    document.items.parametrics.value = "";
    //document.items.categories.value = "";
    //document.items.categoriescounts.value = "";
    // Not sure what this is, but it breaks everything
    if(document.items.leafsearch != null) {
       document.items.leafsearch.value = "";
    }


    if (document.items.hasMultiLists.value == 'true') {
        showListSelectWindow ()  ;
    }
    else {
        //clearSearchSettings();
        document.items.target = "";
        document.items.itemcmd.value = 'addToFavorites';
        document.items.cmd.value = 'favorites';
        document.items.basecmd.value = 'item';

        //document.items.target = "";
        document.items.submit();
        clearAllSelected();
    }
  -------------------------------------------------------- */
}

function showListSelectWindow() {
  listWin= window.open("","listWin", "resizable=1,height=400,width=400,menubar=yes,statusbar,location=0");
  document.items.target = "listWin";
  document.items.cmd.value = 'selectFavoriteList';
  document.items.submit();
  focusWin(listWin);
}

function sleepseconds(s)
{
    var tdy = new Date();
    var seconds = tdy.getSeconds() + s;
    while(tdy.getSeconds() < seconds)
    {
         tdy = new Date();
    }
}


function updateUnit( basecmd,unitName,unitFormVal ) {
    var cmd = basecmd + "&unitName|" + unitFormVal.options[unitFormVal.selectedIndex].value;
    self.location = cmd;
}

// JavaScript functions cannot be overloaded (and don't need to be)
//function doDynURL(name, newWin, requireItems, type, formParams, itemid, leafid) {
//   doDynURL(name, newWin, requireItems, type, formParams, itemid, leafid, true, null);
//}

function doDynURL(name, newWin, requireItems, type, formParams, itemid, leafid, extQuery) {
    if(requireItems && numItemsSelected() == 0) {
       /* For localisation purpose "selectItemsofInterest" can be used as a variable name and
            can be initialised to a property value in the template.
            eg.in template where doDynURL() is called add the line
            var selectItemsofInterest = "%BUGSEYE_PROPERTY_selectItemsofInterest%";
         */

        //alert(selectItemsofInterest);
       alert("Please select the items of interest.");
        return;
    }
    //A BugsEye dyn url means we want to make a call back into BugsEye
    if(type == "BugsEye") {
        setFormParams(document.items, formParams);
    } else {
        if (document.items.exturlname) {
            document.items.exturlname.value = name;
        }
        document.items.cmd.value = "builddynurl";
    }
    if(itemid != null){
       document.items.itemid.value= itemid;
    }
    else{
       document.items.itemid.value = '';
    }
    if(leafid != null){
       document.items.leaf.value = leafid;
    }
    else{
       document.items.leaf.value = '';
    }

    // test for existence of form object before setting property
    // (extquery doesn't exist on the shopping cart page)
    if (document.items.extquery) {
        if(extQuery != null) {
           document.items.extquery.value = extQuery;
        } else {
           document.items.extquery.value= '';
        }
    }

    if(newWin) {
        dynUrlWin = window.open( "","dynUrlWin", "resizable=1,scrollbars=1,height=500,width=650,menubar=1,statusbar=1,location=0");
        document.items.target = "dynUrlWin";
        document.items.submit();
        focusWin(dynUrlWin);
    } else {
        document.items.target = "";
        document.items.submit();
    }
}

//Parse a string of form name/value pairs and set the form value appropriately
function setFormParams(theForm, formParams){
    if(formParams == null || formParams.length < 1) {
        return;
    }
    var nameValue = new Array(2);
    var nameValueStr = "";
    while(formParams.length > 0) {
        endIndex = formParams.indexOf("|");
        if(endIndex == -1) {
            nameValueStr = formParams;
            formParams = "";
        } else {
            nameValueStr = formParams.substring(0, endIndex);
            formParams = formParams.substring(endIndex + 1, formParams.length);
        }
        setNameValue(nameValueStr, nameValue);
        for(i=0; i < theForm.elements.length; i++) {
            if(theForm.elements[i].name == nameValue[0]) {
                theForm.elements[i].value = nameValue[1];
            }
        }
    }
}

function setNameValue(nameValueStr, nameValue){
    equalIndex = nameValueStr.indexOf("=");
    if(equalIndex != -1) {
        nameValue[0] = nameValueStr.substring(0, equalIndex);
        nameValue[1] = nameValueStr.substring(equalIndex + 1, nameValueStr.length);
    } else {
        nameValue[0] = "";
        nameValue[1] = "";
        alert("Invalid name value string: \"" + nameValueStr + "\" missing equals sign.");
        /* For localisation purpose "invalidNameValue" & "missingEquals"
           can be used as a variable name and can be initialised to a
           property value in the template.
           eg.in template where setNameValue() is called add the line
           var invalidNameValue = "%BUGSEYE_PROPERTY_invalidNameValue%";
        */


        //alert(invalidNameValue + nameValueStr + missingEquals);
    }
}

// Table of Contents functions
function setMajorID( leafID ) {
   document.items.majorid.value = leafID;
   document.items.leaf.value = leafID;
   document.items.submit() ;
}

function setNavID( majorID, leafID, hier) {
   document.items.majorid.value = majorID;
   document.items.leaf.value = leafID;
   document.items.hier.value = hier;
   document.items.submit() ;
}

function setSupplierTOCNode( supplierName, nodeID,command) {
    document.items.cmd.value = command;
    document.items.itemcmd.value = command;
    document.items.supplierName.value = supplierName;
    document.items.nodeID.value = nodeID;
    document.items.submit();

}

function setHierCode(itemCode,mappedCode,desc,currLevel, command){

    //document.items.query.value = "";
   // document.items.quicksearch.value = "";
  if (command == null || command == "") {
     command = "unspsc";
  }
   document.items.cmd.value = command;
  document.items.itemcmd.value = command;

  document.items.leaf.value = "0";
  //document.items.cmd.value = "unspsc";
  // clearSearchSettings();
  document.items.itemcode.value = itemCode;
  document.items.mappedCode.value = mappedCode;
  document.items.itemdescription.value = desc;
  document.items.currentLevel.value = currLevel;
  //alert(document.items.title.value);
  document.items.submit() ;
}

function setItemCode(itemCode,desc){
 // document.items.cmd.value = "unspsc";
  document.items.itemcode.value = itemCode;
  document.items.itemdescription.value = desc;
  //alert(document.items.title.value);
  document.items.submit() ;
}

function setSelectedIndexForAllListsOfName(theForm, selectListName, selectListIndex){
   for(elementIndex = 0; elementIndex < theForm.elements.length; elementIndex++){
      if(theForm.elements[elementIndex].name == selectListName){
         theForm.elements[elementIndex].selectedIndex = selectListIndex;
      }
   }
}

function doExport(leaf) {
   doExport(leaf, null);
}

function doExport(leaf, formatType)
{
    document.items.cmd.value='job_backgrounder';
    document.items.query.value='Redisplay';
    if (formatType != null && formatType != "") {
       document.items.exportformat.value = formatType;
    } else {
       if (document.items.exportformat.value== null || document.items.exportformat.value=="") {
          document.items.exportformat.value = "txt";
       }
    }
    //set the exportLocals flag to the right value
    document.items.exportlocals.value=document.items.tmp_exportlocals.value;
    document.items.submit();
}

function getRadioValue( radioGroup )
{
   for ( var idx = 0; idx < radioGroup.length; idx++ )
   {
      if ( radioGroup[idx].checked )
         return radioGroup[idx].value;
   }

   return null;
}

// return a valid float
function getFloatVal(val)
{
    var finalVal = "";  // outgoing value
    var ch  = "";

    val = "" + val;     // make val a string

    for (i=0; i < val.length; i++) {
        ch = val.substring(i,i+1);

        if ((ch >= "0" && ch <= "9") ||
            ch == "." ||
            ch == ",") {
            finalVal += ch;
        }
    }
    return finalVal;
}

function processItemCheckbox( checkBoxField, itemID, catItemID )
{
    var selectedItemIds;
    var itemCatStr = ':' + itemID + ':' + catItemID;
    var quantityField = eval("document.items.qty_" + itemID);

    if( itemInFocus != null && itemInFocus == itemID ) {
        if( checkBoxField.checked ) {
            return false;
        }
        else {
            checkBoxField.checked = true;
        }
    }
    if( !checkBoxField.checked && document.items.cachedSelectedItemIds.value.indexOf(itemID) > -1 ) {
        removeItemSelectedEntry(itemID, catItemID);
        //EMS-784
        // clear quantity field when box is unchecked
        //if( quantityField != null ) {
        //    quantityField.value = "";
        //}
    }
    else if ( checkBoxField.checked ) {
        addItemSelectedEntry(itemID, catItemID);
        if( quantityField != null ) {
            quantityField.focus();
        }
    }
    // set global flag
    itemInFocus = null;
}

function selectCachedSelectedItems(itemList, cachedSelectedItemIds)
{
    // if in favorites return
    if( eval("document.items.favoriteLists") || document.items.ItemCount.value == "0" ) {
        return;
    }

    if( document.items.cachedSelectedItemIds.value.length == 0) {
        return;
    }

    if( itemList.length == null ) {
        if( document.items.cachedSelectedItemIds.value.indexOf(itemList.value) > -1 ) {
            itemList.checked = true;
        }
    }
    else {

        for( i = 0; i < itemList.length; i++ ) {
            if( document.items.cachedSelectedItemIds.value.indexOf(itemList[i].value) > -1 ) {
                itemList[i].checked = true;
            }
        }
    }
}

// if quantity > 0, checkbox should be checked
function checkItemSelected( quantityField, itemID, itemCatID )
{
    var value   = getFloatVal(quantityField.value);
    var element = getItemReference(itemID);

    if (quantityField && quantityField.value.length > 0) {
        // if quantity field value wasn't changed by getFloatVal(), check the box automatically
        if (value == quantityField.value) {
            addItemSelectedEntry(itemID, itemCatID);
            if( element != null ) {
                element.checked = true;
            }
            // set global flag
            itemInFocus = itemID;
        }
        else {
            // inform user that quantity is invalid
            alert(quantityInvalidMsg1 + " (" + quantityField.value + ")\n" + quantityInvalidMsg2);
            if (element != null) {
                removeItemSelectedEntry(itemID, itemCatID);
                element.checked = false;
            }
            quantityField.value = "";
        }
    }
    return true;
}

function getItemReference( itemID ) {
  for (i = 0; i < document.items.elements.length; i++) {
    var element = document.items.elements[i];
    if (element.name == "item" && element.value == itemID) {
      return element;
    }
  }
  return null;
}

function reselectItems( itemList , quantitiesList) {

  // reselect all previously selected items
  for (i = 0; i < document.items.elements.length; i++) {
    var element = document.items.elements[i];
    if (element.name == "item") {
      if (itemList.indexOf(element.value) != -1) {
        // item is in itemList, so check the checkbox
        element.checked = true;
      }
    }
  }
  //set quantity fields.
  if (quantitiesList != null && quantitiesList.length > 0) {
     for (i = 0; i < document.items.elements.length; i++) {
       var element = document.items.elements[i];
       if (element.name == "item") {
         //work from the back of the string, since this is where we get the
         //most current value  (if it was updated on item details.)
         var elementIndex = quantitiesList.lastIndexOf( element.value + ITEM_QTY_DELIMITER );
         if ( elementIndex != -1) {
            elementIndex += element.value.length + 1;
            var endIndex = quantitiesList.substring(elementIndex).indexOf(ITEM_DELIMITER);
            if (endIndex != -1) {
               var quantityString = quantitiesList.substring(elementIndex, elementIndex + endIndex);
               var checkBox = eval("document.items.qty_" + element.value);
               checkBox.value= quantityString;
            }
            element.checked = true;
         }
       }
     }
  }
}

function addReturnUrlQuantity(textField) {
   //get rid of the qty_ in the input name.
   document.returnform.itemQuantities.value += textField.name.substring(4) + ITEM_QTY_DELIMITER + textField.value + ITEM_DELIMITER;
}

function clearSearchSettings(){
   document.items.usingtextsearch.value = "";
   document.items.leaf.value = 0;
   document.items.sortparams.value = "";
   document.items.parametrics.value = "";
   document.items.categories.value = "";
   document.items.categoriescounts.value = "";
   // Not sure what this is, but it breaks everything
   if(document.items.leafsearch != null) {
       document.items.leafsearch.value = "";
   }
}

function getNextStep(form) {

   var current = form.supplier_current_step.value;
   if (current == null || current == '' ) {
      return;
   }
   var wizard_steps = form.supplier_steps.value;

   if (wizard_steps == null  || wizard_steps == '') {
      return;
   }
   var commandDelim = '|';
   var stepDelim = '=';
   var step;
   var gotStep = false;

   while (wizard_steps!= null && wizard_steps.length > 0) {
      var index = wizard_steps.indexOf(commandDelim);

      if (index == -1) {
         step = wizard_steps;
         wizard_steps = null;
      } else {
         step  = wizard_steps.substring(0, index);
         wizard_steps = wizard_steps.substring(index + commandDelim.length, wizard_steps.length);
      }

      stepIndex = step.indexOf(stepDelim);
      var stepNumber = step.substring(0, stepIndex);
      var val = step.substring(stepIndex + stepDelim.length, step.length);
      var nextStep;
      var command;
      if (stepNumber > current && !gotStep) {
         command = val;
         nextStep = stepNumber;
         gotStep = true;
      }

   }

   if (command != null) {
      form.cmd.value= command;
      form.supplier_current_step.value = nextStep;
      form.submit();
   }
}

// generic function to open a popup window
function popup(URL, windowName, windowSettings) {

   // default bugseye settings for a popup window (used if windowSettings is null)
   var defaultWindowSettings = "dependent=yes,directories=no,height=500," +
                               "hotkeys=no,width=750,location=no,menubar=no," +
                               "resizable=yes,screenX=120,screenY=75,scrollbars=yes," +
                               "status=no,titlebar=yes,toolbar=no";

   // ensure all window settings have a valid value
   if (URL == null || URL == "") {
      URL = INITIAL_PAGE;
   }
   if (windowName == null || windowName == "") {
      windowName = "BugsEyeWindow";
   }
   if (windowSettings == null || windowSettings == "") {
      windowSettings = defaultWindowSettings;
   }
   newwin = window.open(URL, windowName, windowSettings)
   newwin.focus();
   return newwin;
//   return (window.open(URL, windowName, windowSettings));
}


// for BugsEye navigation in JSPs
function setActiveTab(val) {
   if (document.items.activeNavigationTab) {
      document.items.activeNavigationTab.value = val;
   }
}
// for BugsEye navigation in JSPs (attributed indexes)
function setAttrName(val) {
   if (document.items.activeNavigationText) {
      document.items.activeNavigationText.value = val;
   }
}

var JDWMinNS4   = (navigator.appName.indexOf("Netscape") >= 0 &&
   parseFloat(navigator.appVersion) >= 4) ? 1 : 0;
var JDWMinNS6   = (navigator.appName.indexOf("Netscape") >= 0 &&
   parseFloat(navigator.appVersion) == 6) ? 1 : 0;
var JDWMinIE4   = (document.all) ? 1 : 0;
var JDWMinIE5   = (JDWMinIE4 && navigator.appVersion.indexOf("5.")  >= 0) ?
   1 : 0;
var JDWMinIE55  = (JDWMinIE5 && navigator.appVersion.indexOf("5.5") >= 0) ?
   1 : 0;

function getPageScrollX() {
   if (JDWMinNS4)
      return window.pageXOffset;
   if (JDWMinIE4)
      return document.body.scrollLeft;
   return -1;
}

function getPageScrollY() {
   if (JDWMinNS4)
      return window.pageYOffset;
   if (JDWMinIE4)
      return document.body.scrollTop;
   return -1;
}

function setScrollPosition(x,y){
   if (x!= null && x!= '' && y != null && y != ''){
      if(JDWMinNS4)
         window.scroll(x,y);
      if(JDWMinIE4)
         setTimeout('window.scroll(' + x + ','+ y + ')' , '200');
   }
}

//If you want to do something to the shopping cart window after
//the cart posts a list of items to order, fill in this function
//with your custom javascript. Otherwise, we will just leave the
//old cart as is.
function doCartWindowCleanup() {
//   if (navigator.appName == 'Netscape') {
//          setTimeout('self.close()', 1000);
//   }
//   else {
//          self.close();
//   }
}


// ADD AN OPTION TO A SELECT LIST
// selectObj: reference to select list (document.formName.selectListName)
// text: text value of the option to add (<option value="value">text</option>)
// value: value of the option to add
// addDuplicates: true - add duplicate options
function addToSelectList(selectObj, text, value, addDuplicates) {
    if (selectObj && text) {
        var option;
        var addOption = true;
        if (value) {
            option = new Option(text, value);
        }
        else {
            option = new Option(text, text);
        }
        // check for duplicates
        if (!addDuplicates) {
            for (i=0; i<selectObj.length; i++) {
                if (selectObj.options[i].text == text) {
                    addOption = false;
                }
            }
        }
        if (addOption) {
            selectObj.options[selectObj.length] = option;
        }
    }
}

// DELETE AN OPTION FROM A SELECT LIST
function deleteFromSelectList(selectObj, text) {
    for (i=0; i<selectObj.length; i++) {
        if (selectObj.options[i].text == text) {
            selectObj.options[i] = null;
        }
    }
}

// RETURNS AN ARRAY OF JAVASCRIPT OPTION OBJECTS (properties: text, value)
function getSelectedOptions(selectObj) {
    var options = new Array();
    var count   = 0;
    if (selectObj) {
        if (selectObj.type == "select-multiple") {
            for (i=0; i<selectObj.length; i++) {
                if (selectObj.options[i].selected) {
                    options[count] = selectObj.options[i]
                    count++;
                }
            }
        }
        else {
            options[count] = selectObj.options[selectObj.selectedIndex];
        }
    }
    return options;
}
//Expects 3 integers for the month, day, & year and validates that if it is a valid date or not
//Returns true if it is valid, false if it is not
//NOTE: Gregorian calendar only!!
function isValidDate(month, day, year) {
	//Make sure it is a valid month and day
	if(month <1 || month > 12 || day < 1 || day > 31)
		return false;

	//Handle 30 day months
	if(month == 4 || month == 6 || month == 9 || month == 11) {
		if(day > 30)
			return false;

	//Handle February
	} else if (month == 2) {
		if((year % 4) == 0) {
			if(day > 29)
				return false;
		} else {
			if(day > 28)
				return false;
		}
	}

	return true;
}

// DELETE AN OPTION FROM A SELECT LIST
function deleteSelectListOption(selectObj, index) {
    selectObj.options[index] = null;
}

// create an initial option in a blank select list (for sizing select lists in Navigator)
// 1.  First line in select list:  <script>document.write(setSelectWidth(30));</script>
// delete the option after the page loads (so that select list is properly sized, but contains no extraneous values)
// 2.  Add this to "<body onload" method:  deleteSelectListOption(document.<formName>.<selectListName>,0);
function setSelectWidth(width) {
    var widthString = "<option>";
    for (i=0; i<width; i++) {
        widthString += "&nbsp;";
    }
    widthString += "</option>";
    return widthString;
}

function submitToJsp(jspCmd){
   if (document.items != null) {
      document.items.cmd.value = jspCmd;
      document.items.submit();
   }
}

function clearStatus(){
     window.status = "";
}

function alreadySubmitted( form, fieldNames ) {
    var newValues = extractFormObjectsIntoArray( form, fieldNames )
    if ( sameArrays( newValues, previousFormValues ) ) {
        return true;
    }
    else {
       previousFormValues = newValues;
       return false;
    }
}

function sameArrays( arr1, arr2 ) {
    if ( arr1.length != arr2.length ) {
        return false
    }
    else {
        var len1 = arr1.length;
        for( var i = 0; i < len1; i++ ) {
            if ( arr1[i] != arr2[i] ) {
                return false;
            }
        }
        return true;
    }
}

function extractFormObjectsIntoArray( form, fieldNames ) {
    var formValues = new Array()
    var fieldLen = fieldNames.length
    var allOptionsValues = new Array()

    for ( var i = 0; i < fieldLen; i++ ) {
        var element = eval( "form.elements." + fieldNames[i] )
        if ( element != null ) {
            var elementType = element.type
            if ( elementType == "text" ||
                 elementType == "hidden" ||
                 elementType == "button" ||
                 elementType == "checkbox" ||
                 elementType == "file" ||
                 elementType == "passord" ||
                 elementType == "radio" ||
                 elementType == "textarea" ) {
                formValues[i] = element.value;
            }
            else if ( elementType == "select-one" ||
                      elementType == "select-multiple" ) {
                var options = getSelectedOptions( element )
                for ( var j = 0; j < options.length; j++ ) {
                    allOptionsValues[ allOptionsValues.length ] = options[j].value
                }
            }
        }
    }
    for ( var k = 0; k < allOptionsValues.length; k++ ) {
        formValues[ formValues.length ] = allOptionsValues[k]
    }

    return formValues
}

function resetPreviousFormValues() {
    previousFormValues = new Array();
}

function createQuickSearchFields() {
    var fields = new Array()
    fields[0] = "quicksearch"
    fields[1] = "searchconfig"
    return fields
}

function doQuickSearch( queryVal ) {

    var fields = createQuickSearchFields()
    if (!alreadySubmitted( document.items, fields) ) {
        doQuery( queryVal );
    }
}

function showWindowOnce( desc, isRoot ) {
    showWindowItemCmd( desc, isRoot, "dispsetdesc" )
}

function viewLeaf(leafID) {
    document.items.leaf.value = leafID;
    document.items.leafsearch.value = 'T';
    document.items.query.value = 'RefineSearch';
    document.items.quicksearch.value = "";
    if (!alreadySubmitted( document.items, new Array("leaf") ) ) {
        clearParamsAndSubmit()
    }
}

function clearIt( attrID ) {
   document.items.parametrictoset.value = attrID ;
   if (!alreadySubmitted( document.items, new Array("parametrictoset") ) ) {
       document.items.submit();
   }
}

function childIsLoaded() {
    previousFormValues = new Array();
}

function advSetCategoryId(val)
{
    document.items.leaf.value = val ;
    if ( !alreadySubmitted( document.items, new Array("leaf" ) ) ) {
        document.items.submit();
    }
}

function advClearCategory()
{
    document.items.leaf.value = '' ;
    document.items.parametrics.value ='';
    document.items.desc.value ='';
    if ( !alreadySubmitted( document.items, new Array("leaf", "parametrics", "desc" ) ) ) {
        document.items.submit();
    }
}

function advQuickSearch(searchValue) {
   document.items.cmd.value='ecmadvancedsearch';
   setupDoQuery( searchValue );
   if ( !alreadySubmitted( document.items, createQuickSearchFields() ) ) {
        reallyDoQuery(searchValue) ;
   }
}

function advShowWindow( name, root ) {
   var tempCmd = document.items.cmd.value;
   var origCmd = document.items.orig_basecmd.value;
   var baseCmd = document.items.basecmd.value;
   var itemCmd = document.items.itemcmd.value;

   if(origCmd == 'data_export')
        document.items.cmd.value = 'data_export';
   else
        document.items.cmd.value = 'itemview';

   document.items.orig_basecmd.value= document.items.basecmd.value;
   document.items.basecmd.value= 'ecmadvancedsearch' ;
   document.items.itemcmd.value = "dispsetdesc" ;
   document.items.isroot.value = root;
   document.items.desc.value = name;
   if (!alreadySubmitted( document.items, new Array("isroot", "desc" ) ) ) {
        var manWin= window.open( "","manWin", "scrollbars=1,resizable=1,height=500,width=450,menubar=0,location=0");
        document.items.target = "manWin";
        document.items.submit();
        focusWin(manWin);
        // fixes a LAME NETSCAPE BUG.
        if (navigator.appName == 'Netscape') {
            //sleep(1000);
        }
    }
   //set out values back.
    document.items.target = "";
   document.items.cmd.value = tempCmd;
   document.items.orig_basecmd.value = origCmd;
   document.items.basecmd.value = baseCmd;
   document.items.itemcmd.value = itemCmd;
}

function advSetAttribute( attrID, theFormElement, attrName, isRoot ) {
   var index = theFormElement.selectedIndex ;
   document.items.parametrictoset.value = attrID ;
   var val = theFormElement.options[ index ].value ;
   var formElements = new Array();
   formElements[0] = "parametrictoset"
   formElements[1] = attrID
   if ( !alreadySubmitted( document.items, formElements ) ) {
        if (val == "-1") {
          advShowWindow( attrName, isRoot ) ;
        } else {
            document.items.submit() ;
        }
   }
}

function browseCatsAdd() {
    setOriginalCategory();
    document.items.target = "";
    document.items.leaf.value = "0";
    document.items.cmd.value = "browsecatsadd";
    if (eval(document.matrix)) {
       document.items.productType.value = getRadioValue(document.matrix.productSelect);
    } else {
       document.items.productType.value = "normalProduct";
    }
    if ( !alreadySubmitted( document.items, new Array("productType","cmd","leaf") ) ) {
        document.items.submit();
    }
}

function submitTOCLetter(letter) {
    document.items.start.value = letter;

    if (eval(document.matrix)) {
       document.items.productType.value = getRadioValue(document.matrix.productSelect);
    } else if ( eval(document.items.productType) ) {
       document.items.productType.value = "normalProduct";
    }

    if (!alreadySubmitted( document.items, new Array("start","cmd") ) ) {
        document.items.submit()
    }
}

function showHideVolumePricing(itemid,showOrHide) {
//showOrHide should be zero to hide volumn pricing - and one to show it.
    vpDivID = "vp_"+itemid; //volume pricing div id
    vpIDivID = "vpIcon_"+itemid; //volume pricing icon div id
    npDivID = "np_"+itemid; //normal pricing div id
    npIDivID = "npIcon_"+itemid; //normal pricing icon div id
if(document.layers)	   //NN4+
    {
       document.layers[vpDivID].display = showOrHide ? "inline" : "none";
       document.layers[vpIDivID].display = showOrHide ? "inline" : "none";
       document.layers[npDivID].display = showOrHide ? "none" : "inline";
       document.layers[npIDivID].display = showOrHide ? "none" : "inline";
    }
    else if(document.getElementById)	  //gecko(NN6) + IE 5+
    {
        var vpObj = document.getElementById(vpDivID);
        var vpIconObj = document.getElementById(vpIDivID);
        var npObj = document.getElementById(npDivID);
        var npIconObj = document.getElementById(npIDivID);
        vpIconObj.style.display = showOrHide ? "inline" : "none";
        vpObj.style.display = showOrHide ? "inline" : "none";
        npIconObj.style.display = showOrHide ? "none" : "inline";
        npObj.style.display = showOrHide ? "none" : "inline";
    }
    else if(document.all)	// IE 4
    {
        document.all[vpDivID].style.display = showOrHide ? "inline" : "none";
        document.all[vpIDivID].style.display = showOrHide ? "inline" : "none";
        document.all[npDivID].style.display = showOrHide ? "none" : "inline";
        document.all[npIDivID].style.display = showOrHide ? "none" : "inline";
    }

}


function addToCartUsingVolumePricingLink(itemid,quantityField,quantity) {
    eval(quantityField).value=quantity;
    document.items.itemid.value=itemid;
    document.items.cachedSelectedItemIds.value += '|' + itemid;
    displayCartCmd("addanddisplay");
}

function removeItemSelectedEntry(itemId, itemCatId)
{
    var itemCatStr = ':' + itemId + ':' + itemCatId;

    if( document.items.cachedSelectedItemIds.value.indexOf(itemId) != -1 ) {
        document.items.cachedSelectedItemIds.value = document.items.cachedSelectedItemIds.value.replace('|' + itemId, '');
        document.items.cachedSelectedItemCategorys.value = document.items.cachedSelectedItemCategorys.value.replace('|' + itemCatStr, '');
        displayNumItemsSelectedText();
    }
        //EMS-755
    if(ifIncludeNoProcurableItemIDs!=null&&ifIncludeNoProcurableItemIDs!='')
    removeFromNoProcurableItemIDs(itemId);
}

function addItemSelectedEntry(itemId, itemCatId)
{
    var itemCatStr = ':' + itemId + ':' + itemCatId;
    if( document.items.cachedSelectedItemIds.value.indexOf(itemId) == -1 ) {
        document.items.cachedSelectedItemIds.value += '|' + itemId;
        document.items.cachedSelectedItemCategorys.value += '|' + itemCatStr;
        displayNumItemsSelectedText();
    }
}

function displayNumItemsSelectedText()
{
    if( document.all['itemsSelectedCount'] != null ) {
        document.all['itemsSelectedCount'].innerHTML = numItemsSelected();
    }
}

// EMS-394 this function will be called when the dropdown value for #of items to be displayed is changed
function itemDisplayedChoiceSubmit(){
   if(document.items.cmd.value == 'edititem'){  // set the cmd to base cmd only for edititem. EMS 402 & 394
     document.items.target="_self";
      document.items.itemcmd.value="";
      document.items.cmd.value=document.items.basecmd.value;
   }
   document.items.submit();
}


