/* Copyright 2002, Prelude Systems, Inc.  All Rights Reserved. www.prelude.com  Duplication,Retransmission or Reproduction in part or whole is forbidden without Written Consent of Prelude Systems Inc. */
//var changeflag = false;
var multiMode=0;
var goToCheckout = false;
function DocumentSubmit()
{
    document.forms[0].submit();
}
function CursorWait()
{
    this.window.status="Retrieving Data Please Wait";
    if (navigator.appName == "Microsoft Internet Explorer")
    {
        document.body.style.cursor="wait";
    }
}
function change()
{
    var fieldName=getObj("changeflag");
    fieldName.value="true";
    // changeflag="true";
}
function changeMultiCart()
{

    var fieldName=getObj("changeflag");
    fieldName.value="true";
    var AC=getObj("ActiveCartId");
    if (AC != null && typeof AC != "undefined")
    {
        AC.disabled=true;
    }
    multiMode=1;
}
function changeMultiFavorite()
{
    var fieldName=getObj("changeflag");
    fieldName.value="true";
    var AF=getObj("ActiveFavoriteId");
    if (AF != null && typeof AF != "undefined")
    {
        AF.disabled=true;
    }
    multiMode=2;
}
function changeMultiCartAndFavorite()
{

    var fieldName=getObj("changeflag");
    fieldName.value="true";
    var AC=getObj("ActiveCartId");
    var AF=getObj("ActiveFavoriteId");
    try
    {
        if (AC != null &&  AF != null && typeof AC != "undefined" && typeof AF != "undefined")
        {
            AC.disabled=true;
            document.forms[0].ActiveCartId.disabled=true;
            AF.disabled=true;
        }
    } catch (err)
    {
        // absorb err;
    }
    multiMode=3;
}
function checkChange(m9,autoPost,changedPrompt)
{
    var fieldName=getObj("changeflag");
    if (typeof fieldName != "undefined")
    {
        if (fieldName.value==null)
        {
            fieldName.value="false";
        }
        if (fieldName.value=="true")
        {
            // have to ask user to save changes 
            if (changedPrompt)
            {
                if (confirm(m9))
                {
                    if (goToCheckout)
                    {
                        document.forms[0].action="viaUpdateCart.jsp?callerID=viaCheckout.jsp";
                        document.forms[0].submit();
                    } else
                    {
                        document.forms[0].submit();
                    }
                }
            } else
            {
                // data changed but not supposed to ask
                if (autoPost)
                {
                    document.forms[0].submit();
                }
            }
        }
    }
}
function clearCart(m11)
{
    if (confirm(m11))
    {
        document.forms[0].action="viaListProducts.jsp?param=DELETE.CART&searchText=VIEWCART&modifier=VIEWCART&reqTitle=TITLE_VIAVIEWCART";
        document.forms[0].submit();
    }
}
function convertText(qtyFieldName)
{
    var pattern = /\s+/ig;

    var txtFld=getObj(qtyFieldName);
    var newVal=txtFld.value.replace(pattern,"^");
    txtFld.value=newVal;
}
function replaceSpaces(conversionString)
{
    var pattern = /\s+/ig;
    var pattern2 = /\"+/ig;
    var conversionString2 = conversionString.replace(pattern,"^");
    var  conversionString3 = conversionString2.replace(pattern2,"{");
    return conversionString3;
}
function replaceVariable(conversionString,from,to)
{
    var conversionString1 = conversionString.replace(from,to);
    return conversionString1;
}
function specialReset()
{
//????   var activeFavorite=document.forms[0].ActiveFavoriteId.selectedIndex;
    //alert("acttive favorite is "+activeFavorite);
    document.forms[0].reset();
    var activeFavoriteField=getObj("ActiveFavoriteId");
    activeFavoriteId.setSelectedIndex=1;
}
function postIt()
{

    //var fieldName=document.getElementById('changeflag');
    var fieldName=getObj("changeflag");
    var activeCartId=getObj("ActiveCartId");
    var activeFavoriteId=getObj("ActiveFavoriteId");
    if (fieldName != null)
    {
        if (typeof fieldName != "undefined")
        {
            if (fieldName.type == "string" || fieldName.type =="hidden")
            {
                fieldName.value="false";
            } else
            {
                fieldName.checked=true;

            }
            document.body.onunload="";
        }
    }
    CursorWait();
    if ((multiMode==1 || multiMode==3) && activeCartId !=null)
    {
        activeCartId.disabled=false;
        //document.forms[0].ActiveCartId.disabled=false;
    }
    if ((multiMode==2 || multiMode==3) && activeFavoriteId !=null)
    {
        //document.forms[0].ActiveFavoriteId.disabled=false;
        activeFavoriteId.disabled=false;
    }
    document.forms[0].submit();
}
function postIt2()
{
    //var fieldName=document.getElementById('changeflag');
    var fieldName=getObj("changeflag");
    var activeCartId=getObj("ActiveCartId");
    var activeFavoriteId=getObj("ActiveFavoriteId");
    fieldName.value="true";
    displayBlock("UpdateDiv10");
    displayBlock("UpdateDiv11");
    CursorWait();
    if ((multiMode==1 || multiMode==3) && activeCartId !=null)
    {
        ativeCartId.disabled=false;
    }
    if ((multiMode==2 || multiMode==3) && activeFavoriteId !=null)
    {
        activeFavoriteId.disabled=false;
    }
    document.forms[0].submit();
}
function postItnClose()
{
    CursorWait();
    document.forms[0].submit();
    parent.close();

}

function doTip(evt,txt)
{
// depricated 
}
function hideTip() 
{
    // Depricated
}

/** Code to place a checkmark for all products in the Mark For Favorites column.
    This code needs to have a hidden field somewhere in the calling .jsp page to 
    work correctly which must be named tableLength and have VALUE equal to the 
    number of dataTable rows
    Ex:  <INPUT TYPE="HIDDEN" NAME="tableLength" VALUE="<%=liRows%>">   
*/
function markAll()
{
    var fieldName;
    var formName=document.forms[0].name;
    var length = eval("document." + formName + ".tableLength.value");
    for (x=0; x < length; x++)
    {
        fieldName=getObj("ptcFlg_" + x);
        if (typeof fieldName != "undefined")
        {
            if (fieldName.type == "string" || fieldName.type =="hidden")
            {
                fieldName.value="true";
            } else
            {
                fieldName.checked=true;
            }
            change();
        }
    }
}
function markAll1(lineNum)
{
    var fieldName;
    var formName=document.forms[0].name;
    fieldName=getObj("ptcFlg_" + lineNum);
    if (typeof fieldName != "undefined")
    {
        if (fieldName.type == "string" || fieldName.type =="hidden")
        {
            fieldName.value="true";
        } else
        {
            fieldName.checked=true;

        }
        change();
    }
}
/**
   This function will close the current browser window that calls this function
*/
function closeWindow()
{
    parent.close();
}
/**
 * This method checks to see if the user hit 'enter'.  If they did, we either execute the form's POST method
 * or the field's 'ONBLUR' event depending on what was passed in the 'mode' variable.  
 */
function detectEnter(e,mode)
{
   // The 3 lines below fix fire fox error with "e" not being the event
   // FF  uses e to have the object that triggered the event where is ie uses the "EVENT" model or object
    var evt = e || event;
    //var myObject = evt.target || evt.srcElement;
    e=evt;
    var nav4 = window.Event ? true : false;
    if (nav4)
    {
        var whichCode = e.which

    } else
    {
        if (e.type=="keypress")
        {
            var whichCode=e.keyCode
        }
    }
    if (e.type == "keypress" && whichCode=="13")
    {
        if (mode == "post")
        {
            postIt();
        } else
        {
            e.srcElement.blur();
        }
    }
}
/**
   This function displays/hides a section of HTML code.  Typically the block of code is 
   within tags that have an ID associated with them.  You pass that tag id to this function.  
*/
function displayBlock(elementId)
{
    var styleObject = document.getElementById(elementId);
    if (styleObject.style.display == "none" )
    {
        styleObject.style.display = "";
        styleObject.style.visibility="visible";
    } else
    {
        styleObject.style.display = "none";
        styleObject.style.visibility="hidden";
    }
}
function displayMenuBlock(elementId,menuGroup)
{
    for (x=0;x<10;x++)
    {
        // reset all menu options to closed or none
        var xstyleObject = getObj("menu_"+x);
        if (xstyleObject != null && elementID != "menu_"+x)
        {
            xstyleObject.style.display = "none";
            xstyleObject.style.visibility="hidden";
        }
    }
    var styleObject = new getObj(elementId);
    if (styleObject.style.display == "none")
    {
        styleObject.style.display = "block";
        styleObject.style.visibility="visible";
    } else
    {
        styleObject.style.display = "none";
        styleObject.style.visibility="hidden";
    }
}
function displayMenuBlockImage(elementId,menuGroup)
{
    for (x=0;x<10;x++)
    {
        
        // reset all menu options to closed or none
        var xstyleObject = getObj("menu_"+x);
        if (xstyleObject != null)
        {
            xstyleObject.style.display = "none";
        }
        var xob= new getObj("menuGroup"+x);
        // reset all menu groups to standard colors
        var styleObject = new getObj(elementId);
    }
    if (styleObject.style.display == "none")
    {
        styleObject.style.display = "";
        // set menu group to different color so know its selected
        var ob = new getObj(menuGroup);
        ob.style.display="";
    } else
    {
        styleObject.style.display = "none";
    }
}

function printWindow()
{
    if (window.print)
    {
        window.print() ;  
    } else
    {
        var WebBrowser = '<OBJECT ID="WebBrowser1" WIDTH=0 HEIGHT=0 CLASSID="CLSID:8856F961-340A-11D0-A96B-00C04FD705A2"></OBJECT>';
        document.body.insertAdjacentHTML('beforeEnd', WebBrowser);
        WebBrowser1.ExecWB(6, 2);//Use a 1 vs. a 2 for a prompting dialog box    WebBrowser1.outerHTML = "";  
    }
}
function validatePhone(field,msg,country)
{
    var formName=document.forms[0].name;
    var areaCodePat = /(\d{3})-(\d{3})-(\d{4})/;
    var fld = eval("document."+formName+"."+field);
    var phone=fld.value;
    var phoneMatch = phone.match(areaCodePat);
    var countryCheck = eval("document."+formName+"."+country+".value");
    if (phone != "" && phoneMatch == null && countryCheck == "US")
    {
        alert(msg);
        fld.focus();
    }
}
function validateZip(field,msg,country)
{
    var formName=document.forms[0].name;
    var zipCodePat = /(\d{5})-(\d{4})/;
    var fld = eval("document."+formName+"."+field);
    var zip = fld.value;
    var zipMatch = zip.match(zipCodePat);
    var countryCheck = eval("document."+formName+"."+country+".value");
    if (zip.length > "5" && zip != "")
    {
        if (zipMatch == null && countryCheck == "US")
        {
            alert(msg);
            fld.focus();
        }
    } else
    {
        if (zip != "" && zip.length < "5" && countryCheck == "US")
        {
            alert(msg);
            fld.focus();
        }
    }
}
/**
   This function validates the cart quantity that the user entered.  
   If the Enforce Min Sell Qty flag is "Y", then this function will verify that the quantity
   entered is greater than the minimum sell qty AND is a multiple of the minimum selling quantity.
   Currently the selling package quantity is only used to initially default the quantity but not
   used for any kind of validation.  
   @param fld_name   name of qty field as a string
   @param lineNum The line number of the product the user changed quantities on
   @param minSellQty The minimum quantity is used is allowed to buy of this product.  Also used
                     to see if the entered quantity is a multiple of this quantity
   @param increment The quantity that will be added when the user hits the up arrow
   @param defQty The quantity that defaults in the quantity box, comes from Selling Package Qty in ADS
   @param inCartQty The current cart quantity that the user entered
   @param enforceFlag Y/N flag to determine if we are enforcing the minimum sell quantities
   @param minOrderQty is the limit the web user can purchase this products
   @param maxOrderQty is the limit the web user can purchase for this product
   @param M1 Resource DIALOG_NEUMERIC_ONLY
   @param M2 Resource DIALOG_QTY_BELOW_MIN
   @param M3 Resource DIALOG_QTY_NOT_MULTIPLE_PKG
   @param M4 Resource DIALOG_QTY_BELOW_MIN_ORDER
   @param M5 DIALOG_QTY_MAX_ORDER
   @param boolean ShowMarkForcartField if false then must do autocheck else user must click it
   @param boolean showChanged flag
 * 
 * 
 * 
 */
function qtyValidate(fld_name,lineNum,minSellQty,increment,defQty,inCartQty,enforceFlag,minOrderQty,maxOrderQty,M1,M2,M3,M4,M5)
{
    var currentQtyField = getObj(fld_name);
    //var currentQtyField = getObj("icQty_" + lineNum);
    var currentQty = currentQtyField.value;
    //eval("document.forms[0].icQty_" + lineNum + ".value");
    //var ptcflagField = eval("document.forms[0].ptcFlg_"+lineNum);    
    var newCurrentQty=currentQty;
    //if (showMarkForCart="false")
    //{
    //   autoCheck=true;
    //} else
    //{
    //   autoCheck=false;
    //}
    if (isNaN(currentQty))
    {
        alert( M1);
        currentQtyField.focus();
        return 1;
    }
    var msg="";
    if (currentQty.indexOf("+") > -1)
    {
        newCurrentQty = inCartQty + parseInt(currentQty);
    } else if (currentQty.indexOf("-") > -1)
    {
        newCurrentQty = inCartQty + parseInt(currentQty);
    }

    if (enforceFlag && newCurrentQty!="0" && minSellQty!="0")
    {
        var remainder = newCurrentQty % increment;
        if (newCurrentQty < minSellQty)
        {
            msg=M2;
            msg=replaceVariable(msg,"$1",minSellQty);
            currentQtyField.value = minSellQty;
            currentQtyField.focus();
        } else if (remainder > 0)
        {
            if (enforceFlag)
            {
                msg=M3;
                msg=replaceVariable(msg,"$1",minSellQty);
                currentQtyField.value = (newCurrentQty - remainder) + increment;
                currentQtyField.focus();
            }
        }
    }
    if (minOrderQty!="0" && maxOrderQty!="0" && newCurrentQty!="0")
    {
        if (newCurrentQty < minOrderQty)
        {
            msg=M4;
            msg=replaceVariable(msg,"$1",minSellQty);
            currentQtyField.value = minOrderQty;
            currentQtyField.focus();
        } else
        {
            if (newCurrentQty > maxOrderQty)
            {
                msg=M5;
                msg=replaceVariable(msg,"$1",maxOrderQty);
                currentQtyField.value = maxOrderQty;
                currentQtyField.focus();
            }
        }
    }
    if (msg != "")
    {
        alert(msg);
        return 1;
    } else
    {
        currentQtyField.value = newCurrentQty;
        return 0;
    }
}
/*
Date Check functions
*/
function checkdate(objName,leadTime,m1,m2) 
{
    var datefield = objName;
    if (objName.value.length == 0)
    {
        return;
    }
    if (objName.value.length <6)
    {
        alert(m1);
        datefield.select();
        datefield.focus();
        return false;
    }
    if (chkdate(objName) == false)
    {
        datefield.select();
        alert(m1);
        datefield.focus();
        return false;
    } else
    {
        if (checkLeadTime(objName,leadDate) == false)
        {
            var leadDate=calcLeadTimeDate(objName,leadTime);
            alert(m2);
            datefield.select();
            datefield.focus();
            return false;
        } else
        {
            return true;
        }
    }
}
function chkdate(objName)
{
    var strDatestyle = "US"; //United States date style
    //var strDatestyle = "EU";  //European date style
    var strDate;
    var strDateArray;
    var strDay;
    var strMonth;
    var strYear;
    var intday;
    var intMonth;
    var intYear;
    var booFound = false;
    var datefield = objName;
    var strSeparatorArray = new Array("-"," ","/",".");
    var intElementNr;
    var err = 0;
    var strMonthArray = new Array(12);
    strMonthArray[0] = "Jan";
    strMonthArray[1] = "Feb";
    strMonthArray[2] = "Mar";
    strMonthArray[3] = "Apr";
    strMonthArray[4] = "May";
    strMonthArray[5] = "Jun";
    strMonthArray[6] = "Jul";
    strMonthArray[7] = "Aug";
    strMonthArray[8] = "Sep";
    strMonthArray[9] = "Oct";
    strMonthArray[10] = "Nov";
    strMonthArray[11] = "Dec";
    strDate = datefield.value;
    if (strDate.length < 1)
    {
        return true;
    }
    for (intElementNr = 0; intElementNr < strSeparatorArray.length; intElementNr++)
    {
        if (strDate.indexOf(strSeparatorArray[intElementNr]) != -1)
        {
            strDateArray = strDate.split(strSeparatorArray[intElementNr]);
            if (strDateArray.length != 3)
            {
                err = 1;
                return false;
            } else
            {
                strDay = strDateArray[0];
                strMonth = strDateArray[1];
                strYear = strDateArray[2];
            }
            booFound = true;
        }
    }
    if (booFound == false)
    {
        if (strDate.length>5)
        {
            strDay = strDate.substr(0, 2);
            strMonth = strDate.substr(2, 2);
            strYear = strDate.substr(4);
        }
    }
    if (strYear.length < 2)
    {
        strYear=fmt00(strYear);
    }
    if (strYear.length == 2)
    {
        strYear = '20' + strYear;
    }
    // US style
    if (strDatestyle == "US")
    {
        strTemp = strDay;
        strDay = strMonth;
        strMonth = strTemp;
    }
    intday = parseInt(strDay, 10);
    if (isNaN(intday))
    {
        err = 2;
        return false;
    }
    intday=fmt00(intday);
    intMonth = parseInt(strMonth, 10);
    if (isNaN(intMonth))
    {
        for (i = 0;i<12;i++)
        {
            if (strMonth.toUpperCase() == strMonthArray[i].toUpperCase())
            {
                intMonth = i+1;
                strMonth = strMonthArray[i];
                i = 12;
            }
        }
        if (isNaN(intMonth))
        {
            err = 3;
            return false;
        }
    }
    intMonth=fmt00(intMonth);
    intYear = parseInt(strYear, 10);
    if (isNaN(intYear))
    {
        err = 4;
        return false;
    }
    if (intMonth>12 || intMonth<1)
    {
        err = 5;
        return false;
    }
    if ((intMonth == 1 || intMonth == 3 || intMonth == 5 || intMonth == 7 || intMonth == 8 || intMonth == 10 || intMonth == 12) && (intday > 31 || intday < 1))
    {
        err = 6;
        return false;
    }
    if ((intMonth == 4 || intMonth == 6 || intMonth == 9 || intMonth == 11) && (intday > 30 || intday < 1))
    {
        err = 7;
        return false;
    }
    if (intMonth == 2)
    {
        if (intday < 1)
        {
            err = 8;
            return false;
        }
        if (LeapYear(intYear) == true)
        {
            if (intday > 29)
            {
                err = 9;
                return false;
            }
        } else
        {
            if (intday > 28)
            {
                err = 10;
                return false;
            }
        }
    }
    intYear=fmt00(intYear);
    if (strDatestyle == "US")
    {
        datefield.value = fmt00(intMonth) + "/" + fmt00(intday)+"/" + fmt00(strYear);
    } else
    {
        datefield.value = fmt00(intday) + " " + strMonthArray[intMonth-1] + " " + fmt00(strYear);
    }
    return true;
}
function LeapYear(intYear)
{
    if (intYear % 100 == 0)
    {
        if (intYear % 400 == 0)
        {
            return true;
        }
    } else
    {
        if ((intYear % 4) == 0)
        {
            return true;
        }
    }
    return false;
}
function doDateCheck(from, to)
{
    if (Date.parse(from.value) <= Date.parse(to.value))
    {
        return true;
        //   alert("The dates are valid.");
    } else
    {
        if (from.value == "" || to.value == "")
            alert("Both dates must be entered.");
        else
            alert("To date must occur after the from date.");
    }
}
function calcLeadTimeDate(dte,leadDays)
{
    var sysDate=new Date();
    var dys=sysDate.getDate()+leadDays;
    var dateplusLead = new Date(sysDate.getYear(),sysDate.getMonth(),dys);
    return dateplusLead;
}
function checkLeadTime(dte,leadDate)
{
    var testDate     = new Date(dte.value);
    if ( testDate <= leadDate)
    {
        return false;
    } else
    {
        return true;
    }
}
function fmt00(b)
{
    var d = b.value;
    // fmt00: Tags leading zero onto numbers 0 - 9.
    // Particularly useful for displaying results from Date methods.
    //
    if (parseInt(b) < 0) var neg = true;
    if (Math.abs(parseInt(b)) < 10)
    {
        b = "0"+ Math.abs(b);
    }
    if (neg) b = "-"+b;
    return b;
}
/**
 * 1/16/04 (SRG) - made changes to clearField(), c(), SearchDetectEnter() and convertSearch() to make
 * the retrieval of fields more generic.  Before we were relying on 'document.forms[0]....', but if we move the
 * search function to somewhere like the menu bar, then the fields are not in a 'form' and must be retrieved some
 * other way such as 'getElementsByName'.
 * 
 * @param fld    Field to Clear Text from may/may not be same field on so you now must specifiy the field id String
 * @param txt    Text that is the default for this field to remove otherwise no clear is done.
 */
function clearField(fld,txt)
{
    var dataFld = getObj(fld);
    if (dataFld.value == txt)
    {
        dataFld.value="";
    }
}
function clearDataField(fld)
{
       var dataFld = getObj(fld);
       dataFld.value="";
}
/**
 * Takes the contents of one variable 'searchString', converts spaces within it, checks for single character keywords
 * and then passes the converted keyword to 'hfield'.  
 */
function convertSearch(searchString,hfield,msg)
{
    var pattern = /\s+/ig; // spaces
    var pattern2 = /\"+/ig;  // " marks
    var pattern3 = /\'+/ig;  // ' marks
    var sfld=getObj(searchString);
    /* this removes duplicate spaces */
    var _regExp=/\s\s/gi;
    var _foundStr="";
    var newVal=sfld.value;
    while (newVal.match(_regExp)!=null)
    {
        _foundStr=newVal.match(_regExp)[0];
        newVal=newVal.replace(new RegExp(_foundStr,"gmi")," ");
    }
    var error=false;
    var nstring=newVal.split(" ");
    for (var i=nstring.length;i>=0;i--)
    {
        if ((nstring[i]!=null ))
        {
            if (nstring[i].length<=1)
            {
                alert(msg);
                error=true;
            }
        }
    }
    /*convert spaces into ^ for transmission */
    newVal=newVal.replace(pattern,"^");
    newVal=newVal.replace(pattern2,"{");
    newVal=newVal.replace(pattern3,"}");
    var tfld=getObj(hfield);
    tfld.value=newVal;
    if (error)
    {
        return false;
    } else
    {
        return true;
    }
}
/**
 * Checks if the user hit the enter key.  If we do find the enter key then we run the performSearch() routine.  
 * This method is only used from the search field in advertiseFrame.jsp.  
 */
function SearchDetectEnter(e,msg)
{
    var nav4 = window.Event ? true : false;
    
    if (nav4)
    {
        var whichCode = e.which
    } else
    {
        if (e.type=="keypress")
        {
            var whichCode=e.keyCode
        }
    }
    if (e.type == "keypress" && whichCode=="13")
    {
        window.status= "Retrieving Data Please Wait";
        performSearch(msg);
    }
}
function performSearch(msg)
{
    if (convertSearch('dsearchText','searchText',msg))
    {
        var keywords="";
        var dataFld = getObj("searchText");
        var refineFld = getObj("refineButton");
        var group1ans=getObj("inpProductGrouping1");
        var group2ans=getObj("inpProductGrouping2");
        var group3ans=getObj("inpProductGrouping3");
        var group4ans=getObj("inpProductGrouping4");
        var group5ans=getObj("inpProductGrouping5");
        var xmsg=replaceSpaces(msg);
        if (refineFld != null)
        {
            if (refineFld.checked == true)
            {
                keywords = dataFld.value + "$REFINE$";
            } else
            {
                if (dataFld.value!=xmsg)
                {
                    keywords = dataFld.value;
                }
            }
        } else
        {
                if (dataFld.value!=xmsg)
                {
                    keywords = dataFld.value;
                }
        }
        if (group1ans !=null && group1ans.value!="")
        {
            keywords+="^"+group1ans.value;
        }
        if (group2ans !=null && group2ans.value!="")
        {
            keywords+="^"+group2ans.value;
        }
        if (group3ans !=null && group3ans.value!="")
        {
            keywords+="^"+group3ans.value;
        }
        if (group4ans !=null && group4ans.value!="")
        {
            keywords+="^"+group4ans.value;
        }
        if (group5ans !=null && group5ans.value!="")
                    {
            keywords+="^"+group5ans.value;
        }
        if (keywords!="")
        {
        
            var reqx=getObj("req");
            if (reqx != null)
            {
                reqx.value="viaListProducts.jsp?searchText="+keywords+"&modifier=SEARCH&reqTitle=TITLE_VIASEARCHRESULT";
            }
            document.forms[0].action="viaListProducts.jsp?searchText="+keywords+"&modifier=SEARCH&reqTitle=TITLE_VIASEARCHRESULT";
            DocumentSubmit();
        }
    }
}


/** Code to place a checkmark for all products in the Delete Item column.
 This code needs to have a hidden field somewhere in the calling .jsp page to 
 work correctly which must be named tableLength and have VALUE equal to the 
 number of dataTable rows
 Ex:  <INPUT TYPE="HIDDEN" NAME="tableLength" VALUE="<%=liRows%>">   
*/
function DeleteAll()
{
    var fieldName;
    var formName=document.forms[0].name;
    var qtyField;
    var length = eval("document." + formName + ".tableLength.value");
    for (x=0; x < length; x++)
    {
        qtyField=eval(getElementById("icQty_" + x));
        qtyField.value = 0;
        fieldName=getElementById(".ptcFlg_" + x);
        if (typeof fieldName != "undefined")
        {
            if (fieldName.type == "string" || fieldName.type =="hidden")
            {
                fieldName.value="true";
            } else
            {
                fieldName.checked=true;

            }
        }
    }
    change();
    postIt();
}
function textCounter(field, maxlimit,m1 ) 
{
    if ( field.value.length > maxlimit )
    {
        m1=replaceVariable(m1,"$1",maxlimit);
        field.value = field.value.substring( 0, maxlimit );
        alert(m1);
        return false;
    }
}
function changeField(FieldName,vlu)
{
    var txtFld=getObj(FieldName);
    txtFld.value=vlu;
}
/**
 * Code to display Changed Icon if Values of A product have been changed
 *
 * @param currentField  Field which this function was called from, required as some should not trigger a Mark for cart call
 * @param active    results from Method called ot see if Show changed is enabled
 * @param ShowMark  results from method call to see if mark for cart is displayed
 * @param prodLineNumber internal line number that you wish to set the changed icon for.
 * @param soldonWebflag  sold on web for the specific product you are dealing with
 * */
function setChangedIcon(currentField,active,showMark,prodLineNumber,soldOnWeb)
{
    if (active)
    {
        var ptcflagField = getObj("ptcFlg_"+prodLineNumber);    
        var chgfld=getObj("Changed_"+prodLineNumber);
        chgfld.src=chgfld.src.replace(/Un/g,"");
    }
    if (showMark && soldOnWeb=="Y" && currentField!="lsFlg_")
    {
        markForCart(prodLineNumber)
    }
}
function UP(qtyFieldName,increment,lineNum,minSellQty,defQty,inCartQty,enforceFlag,minOrderQty,maxOrderQty,showChanged,showMark,soldOnWeb,autoPost,M1,M2,M3,M4,M5)
{
    if (increment > 0)
    {
        // var formName=document.forms[0].name;
        // var qtyField=eval("document." + formName + "." + qtyFieldName);
        var qtyField=getObj(qtyFieldName);
        var curQty=qtyField.value;
        if (curQty!="")
        {
            qtyField.value=parseInt(curQty)+increment;
        } else
        {
            qtyField.value=1;
        }
        qtyValidate(qtyFieldName,lineNum,minSellQty,increment,defQty,inCartQty,enforceFlag,minOrderQty,maxOrderQty,M1,M2,M3,M4,M5);
        setChangedIcon(qtyFieldName,showChanged,showMark,lineNum,soldOnWeb,autoPost);
    }
}
function DOWN(qtyFieldName,increment,lineNum,minSellQty,defQty,inCartQty,enforceFlag,minOrderQty,maxOrderQty,showChanged,showMark,soldOnWeb,autoPost,M1,M2,M3,M4,M5)
{
    if (increment > 0)
    {
        // var formName=document.forms[0].name;
        // var qtyField=eval("document." + formName + "." + qtyFieldName);
        var qtyField=getObj(qtyFieldName);
        var origQty = qtyField.value;
        var curQty=qtyField.value;
        if ((curQty!="") && (parseInt(curQty) > 0))
        {
            qtyField.value=parseInt(curQty)-increment;
        }
        qtyValidate(qtyFieldName,lineNum,minSellQty,increment,defQty,inCartQty,enforceFlag,minOrderQty,maxOrderQty,M1,M2,M3,M4,M5);
        setChangedIcon(qtyFieldName,showChanged,showMark,lineNum,soldOnWeb,autoPost);
    }
}
/**
 * Code to Change String contents from a Field in Page ***NOTE*** Only to Be used for value Contents
 * 
 * @param inField   Field Name to change contents of
 * @param oldString old string this can be space or multi character
 * @param newString newString - new String this can be space or multi character
 */
function replaceString(inField,oldString,newString)
{
    var chgFld=getObj(inField);
    var pattern="/"+oldstring+"/g";
    var pattern2 = /\s+/ig;  
    if (oldString==" " || newString==" ")
    {
        if (oldString==" ")
        {
            chgFld = chgFld.replace(pattern2,newString);
        }
        if (newString==" ")
        {
            chgFld=chgFld.replace(oldString,pattern2);
        }
    } else
    {
        chgfld=chgfld.replace(pattern,newString);
    }
}
function markForCart(lineNum)
{
    var fieldName=getObj("ptcFlg_"+lineNum);
    var fieldType=getObj("ptcFlg_"+lineNum).type.toLowerCase();
    if (fieldType != "undefined")
    {
        if (fieldType == "checkbox")
        {
            fieldName.checked=true;
        } else
        {
            fieldName.value="true";
        }
    }
    change();
}
function highlightMenuOption(ImageName,imageUrl) 
{
    setBackgroundImage(ImageName,imageUrl);
}

function setBackgroundImage (id, imageURL) 
{
    if (document.layers)
        document[id].background.src = imageURL == 'none' ? null : imageURL;
    else if (document.all)
        document.all[id].style.backgroundImage = imageURL == 'none' ? 'none' : 'url(' + imageURL + ')';
    else if (document.getElementById)
        document.getElementById(id).style.backgroundImage = imageURL == 'none' ? 'none' : 'url(' + imageURL + ')';
}

function blankprice(field,M10)
{

    var fieldName;
    fieldName=document.getElementById(field);
    if (typeof fieldName != "undefined")
    {
        fieldName.innerHTML=M10;
    }
    return 0;
}
function getObj(name)
{
    var obj;
    if (document.all)
    {
        // Microsoft DOM code old ie 4
        obj = document.all[name];
    }
    if (document.layers)
    {
// Netscape DOM code ns 4
        obj = document.layers[name];
    }
    if (document.getElementById)
    {
// W3C DOM code newer browsers Gecko, Internet Explorer 5+, Opera 5+
        obj = document.getElementById(name);
    }
    return obj;
}
function setListFlag(lineNum)
{
    var dataField=getObj("listChanged_"+lineNum);
    dataField.value="1";
}
function reSortList(field,url)
{
    var stn=getObj(field).value;
    url=url+"&inpSortProductsBy="+stn;
    go(url,"DATAPANEL",0);
}
function updateCheckoutFlag()
{
    goToCheckout=true;
}
function setFocus(fldID)
{
    var fld=getObj(fldID);
    fld.focus();
}
function validateCCNumber(ccnumberFieldName,cardTypeFieldName,error0,error1,error2,error3,error4)
{
    var cardnumber=getObj(ccnumberFieldName).value;
    var cardname=getObj(cardTypeFieldName).value;
    var error=checkCreditCard(cardnumber,cardname);
    if (error>=0)
    {
        if (error==0)
        {
            alert(error0);
        }
        if (error==1)
        {
            alert(error1);
        }
        if (error==2)
        {
            alert(error2);
        }
        if (error==3)
        {
            alert(error3);
        }
        if (error==4)
        {
            alert(error4);
        }
    return 1;
   } else
   {
     return 0;
   }
}

/*============================================================================*/

/*
 
This routine checks the credit card number. The following checks are made:
 
1. A number has been provided
2. The number is a right length for the card
3. The number has an appropriate prefix for the card
4. The number has a valid modulus 10 number check digit if required
 
If the validation fails an error is reported.
 
The structure of credit card formats was gleaned from a variety of sources on 
the web, although the best is probably on Wikepedia ("Credit card number"):
 
  http://en.wikipedia.org/wiki/Credit_card_number
 
Parameters:
            cardnumber           number on the card
            cardname             name of card as defined in the card list below
 
Author:     John Gardner
Date:       1st November 2003
Updated:    26th Feb. 2005      Additional cards added by request
Updated:    27th Nov. 2006      Additional cards added from Wikipedia
Updated:    18th Jan. 2008      Additional cards added from Wikipedia
 
*/

/*
   If a credit card number is invalid, an error reason is loaded into the 
   global ccErrorNo variable. This can be be used to index into the global error  
   string array to report the reason to the user if required:
   
   e.g. if (!checkCreditCard (number, name) alert (ccErrors(ccErrorNo);
*/

function checkCreditCard (cardnumber, cardname) 
{

    // Array to hold the permitted card characteristics
    var cards = new Array();
    var ccErrorNo="";
    
    // Define the cards we support. You may add addtional card types.
    
    //  Name:      As in the selection box of the form - must be same as user's
    //  Length:    List of possible valid lengths of the card number for the card
    //  prefixes:  List of possible prefixes for the card
    //  checkdigit Boolean to say whether there is a check digit
        //Visa  
     cards [0] = {name: "Visa", 
        length: "13,16", 
        prefixes: "4",
        checkdigit: true};
        // Master card
     cards [1] = {name: "M/C", 
        length: "16", 
        prefixes: "51,52,53,54,55",
        checkdigit: true};
        // diners Club
     cards [2] = {name: "D/C", 
        length: "14,16", 
        prefixes: "300,301,302,303,304,305,36,38,55",
        checkdigit: true};
    cards [3] = {name: "CarteBlanche", 
        length: "14", 
        prefixes: "300,301,302,303,304,305,36,38",
        checkdigit: true};
        //  amex and Optima
    cards [4] = {name: "AMEX", 
        length: "15", 
        prefixes: "34,37",
        checkdigit: true};
        //  Discover
    cards [5] = {name: "Disc", 
        length: "16", 
        prefixes: "6011,650",
        checkdigit: true};
/*
        Future cards that may be needed
    cards [6] = {name: "JCB", 
        length: "15,16", 
        prefixes: "3,1800,2131",
        checkdigit: true};
    cards [7] = {name: "enRoute", 
        length: "15", 
        prefixes: "2014,2149",
        checkdigit: true};
    cards [8] = {name: "Solo", 
        length: "16,18,19", 
        prefixes: "6334, 6767",
        checkdigit: true};
    cards [9] = {name: "Switch", 
        length: "16,18,19", 
        prefixes: "4903,4905,4911,4936,564182,633110,6333,6759",
        checkdigit: true};
    cards [10] = {name: "Maestro", 
        length: "16,18", 
        prefixes: "5020,6",
        checkdigit: true};
    cards [11] = {name: "VisaElectron", 
        length: "16", 
        prefixes: "417500,4917,4913",
        checkdigit: true};
  */  
    // Establish card type
    var cardType = -1;
    for (var i=0; i<cards.length; i++)
    {
        
        // See if it is this card (ignoring the case of the string)
        if (cardname.toLowerCase () == cards[i].name.toLowerCase())
        {
            cardType = i;
            break;
        }
    }
    
    // If card type not found, report an error
    if (cardType == -1)
    {
        //ccErrorNo = 0;
        return 0; 
    }

    // Ensure that the user has provided a credit card number
    if (cardnumber.length == 0)
    {
        // ccErrorNo = 1;
        return 1;
    }

    // Now remove any spaces from the credit card number
    cardnumber = cardnumber.replace (/\s/g, "");
    
    // Check that the number is numeric
    var cardNo = cardnumber
    var cardexp = /^[0-9]{13,19}$/;
    if (!cardexp.exec(cardNo))
    {
        //ccErrorNo = 2;
        return 2; 
    }

    // Now check the modulus 10 check digit - if required
    if (cards[cardType].checkdigit)
    {
        var checksum = 0;                                  // running checksum total
        var mychar = "";                                   // next char to process
        var j = 1;                                         // takes value of 1 or 2
        
        // Process each digit one by one starting at the right
        var calc;
        for (i = cardNo.length - 1; i >= 0; i--)
        {
            
            // Extract the next digit and multiply by 1 or 2 on alternative digits.
            calc = Number(cardNo.charAt(i)) * j;
            
            // If the result is in two digits add 1 to the checksum total
            if (calc > 9)
            {
                checksum = checksum + 1;
                calc = calc - 10;
            }

            // Add the units element to the checksum total
            checksum = checksum + calc;
            
            // Switch the value of j
            if (j ==1)
            {
                j = 2
            } else
            {
                j = 1
            };
        } 
        
        // All done - if checksum is divisible by 10, it is a valid modulus 10.
        // If not, report an error.
        if (checksum % 10 != 0)
        {
            //ccErrorNo = 3;
            return 3; 
        }
    }

    // The following are the card-specific checks we undertake.
    var LengthValid = false;
    var PrefixValid = false; 
    var undefined; 
    
    // We use these for holding the valid lengths and prefixes of a card type
    var prefix = new Array ();
    var lengths = new Array ();
    
    // Load an array with the valid prefixes for this card
    prefix = cards[cardType].prefixes.split(",");
    
    // Now see if any of them match what we have in the card number
    for (i=0; i<prefix.length; i++)
    {
        var exp = new RegExp ("^" + prefix[i]);
        if (exp.test (cardNo)) PrefixValid = true;
    }
    
    // If it isn't a valid prefix there's no point at looking at the length
    if (!PrefixValid)
    {
        //ccErrorNo = 3;
        return 3; 
    }

    // See if the length is valid for this card
    lengths = cards[cardType].length.split(",");
    for (j=0; j<lengths.length; j++)
    {
        if (cardNo.length == lengths[j]) LengthValid = true;
    }
    
    // See if all is OK by seeing if the length was valid. We only check the 
    // length if all else was hunky dory.
    if (!LengthValid)
    {
        //ccErrorNo = 4;
        return 4; 
    };   
    
    // The credit card is in the required format.
    return -1;
}

function validateCCExpmon(expmon,expyear,cm,cy,error0)
{
   var icm=getObj(expmon).value;
   var icy=getObj(expyear).value;
    if (icm<cm && cy==icy)
    {
        alert(error0);
        return 1;
    }
}

function addToManditory(thefield,fieldTag)
{
 manditoryFields.push(thefield);
 manditoryFieldTags.push(fieldTag);
}
function validateManditory()
{
    var fieldMsg="";
    for (var i =0;i<manditoryFields.length;i++)
    {
        if (manditoryFields[i].length>0)
        {
           var fld = getObj(manditoryFields[i]);
           if (fld==null || fld.value.length<=0)
           {
               fieldMsg+="\n"+manditoryFieldTags[i];
           }
        }
    }
    if (fieldMsg.length>1)
    {
        alert("The following Fields are Required Data\n"+fieldMsg);
    } else
    {
        alert(" all is good");
    }
}
function resetManditory()
{
    manditoryFields= [];
    manditoryFieldTags= [];
}
/*============================================================================*/



