/********************************************************************************************************************
* UNOBTRUSIVE JAVASCRIPT: (PROTOTYPE)                                                                               *
*********************************************************************************************************************
* Note:                                                                                                             *
* name convention for dom ready class name and id                                                                   *
* class name needs to be listened should begin with 'domReady_class_'                                               *
* if class name include _keypress, do function only when key pressed                                                *
* if class name include _click, do function only when button pressed                                                *
* if class name without _keypress || _click, do function when keypress && button press
* other class name used in dom ready should begin with 'dom_'                                                       *
* id needs to be listened should begin with 'domReady_id_'                                                          *
*                                                                                                                   *
* all popups should have class name "dom_popup", it use lightBoxV2 to fade & disable background, close all popups   *
* all popup container's z-index: 100. lightBox will use z-index: 90                                                 *
* domReady_lock_popup is setup to control to close overlay and generalpopup                                         *
*                                                                                                                   *
*********************************************************************************************************************/


/************************************************************************************
* all locks use in dom ready, name convention is domReady_lock_XXX
*************************************************************************************/
var domReady_lock_popup = false; // false: popup and overlay can be closed. true: popup and overlay cannot be closed

/************************************************************************************
* all event functions are put here:
* [do what ever you want, and will not affect other person]
*************************************************************************************/
var domReadyEventFunctionsCollections = {

    // --- BEGIN PERSONALIZATION FUNCTION ---
    doPersonalization: function(e){

        var allSkuSelected = true;
        $$(".skuOptSelect").each(function(skuOpt){
            if(skuOpt.selectedIndex==0){
                allSkuSelected = false;
            }
        })

        qty = $("prodOrderOty").value;
        if(numericCheck.isNumeric(qty)){
            if(!allSkuSelected){
                $("skuOptErrorSection").removeClassName("display_none");
                preventDoubleSubmit=false;

            }else{
                lightBoxV2.doLightBoxV2("domReady_class_popupPersonalizationCancelButton");
                personalization.duplicate('prodOrderOty', 'customizeWidgetContainer', 'beginDuplicateStartLine');
            }
        }else{
            qtyErrorSectionObj = $("qtyErrorSection");
            if (qtyErrorSectionObj) {
                qtyErrorSectionObj.innerHTML="Please enter a valid quantity for the item (valid integer, greater than zero).";
            }
            preventDoubleSubmit = false;
        }

        Event.stop(e);  // stop the event from bubbling
        return false;
    },

    doPersonalizationDisappear: function(e){
        if(!domReady_lock_popup){
            personalization.delAllDuplicate('beginDuplicateStartLine');
            lightBoxV2.cancelLightBoxV2("domReady_class_popupPersonalizationCancelButton");
            //Event.stop(e);
        }
        return false;
    },

    // --- BEGIN GENERAL POPUP ---
    // NOTE: all popup container can use any id [ie. popup1], all element [ie. a link] try to open this popup should has
    //          the id name like 'popup1_domTriggerxxxxx', which means popupId+"_domTrigger"+whatever. In this case, two
    //          elements related each other by their id.
    //       all popup should be used with lightBoxV2 for consistancy.
    //       all popup container should has a class name "dom_popup", which is used in lightBoxV2 for closing the popup.
    //       all popup should contain a element which class name is "dom_focus", which is used to onfocus.
    //       all popup can be closed by apply "domReady_class_popupClose" class name on all close btn & pass this class
    //          to lightBoxV2 as its class name.
    //       all popup should have z-index=100.
    doGeneralPopUpOpen: function(e){
        var currentElementId = e.element().identify();
        var tagetPopupId = currentElementId.substring(0,currentElementId.indexOf('_domTrigger')).strip();
//        alert(":"+tagetPopupId+":");
        if(tagetPopupId.length>0){
            if($(tagetPopupId)){
                lightBoxV2.doLightBoxV2("domReady_class_popupClose");
                $(tagetPopupId).style.left = Event.pointerX(e)+"px";
                $(tagetPopupId).style.top = Event.pointerY(e)+"px";
                $(tagetPopupId).removeClassName("display_none");
                ($(tagetPopupId).select('.dom_focus')).each(function(fo){
                    fo.focus();
                })
            }
        }
    },

    doGeneralPopUpClose: function(e){
        lightBoxV2.cancelLightBoxV2("domReady_class_popupClose");
    },

    // -- BEGIN QTY MODIFICATION SUBMIT (KEY PRESS) ---
    doSubmitQtyModi: function(e){
        var currentElement = e.element();
        var keyunicode=e.charCode || e.keyCode;
        if(keyunicode == 13){
            var domReady_val = currentElement.readAttribute('domReady_value');
            var jsonObj = domReady_val.evalJSON();
//            alert(jsonObj+" | jsonObj's dom_formName: " + jsonObj.dom_formName + " : jsonObj's dom_suffix: " + jsonObj.dom_formSuffix);
            submitForm.submit(jsonObj.dom_formName,jsonObj.dom_formSuffix);
            Event.stop(e);
        }
        return false;
    },

    doSubmitCouponByKey: function(e){
        var keyunicode=e.charCode || e.keyCode;
        if(keyunicode == 13){
            domReadyEventFunctionsCollections.doAjaxJson(e,"domReady_class_submitCoupon_shoppingCartPage");
        }
        return false;

    },

    /*
    * do very general Ajax call to get JSON Obj, the prerequirement is : set 'domReady_value' attri in current element
    * the 'domReady_value' atri includes : dom_ajaxUrl, dom_inputFieldsContainer (all serializable elements within this container should have a class name "domSerializableField"), dom_errorSection
    * */
    doAjaxJson: function(e,c){
        //disable all background action here!
        lightBoxV2.doLightBoxV2("abc", "#ffffff", "0");

        Event.stop(e);
        var currentElement = e.element();
        var domReady_val = currentElement.readAttribute('domReady_value');
        var jsonParam = domReady_val.evalJSON();
//        alert("jsonParam.dom_ajaxUrl: "+jsonParam.dom_ajaxUrl+" | jsonParam.dom_inputFieldsContainer: "+jsonParam.dom_inputFieldsContainer+" | jsonParam.dom_errorSection: "+jsonParam.dom_errorSection);

        generalAjaxAction.processJSON(e, c, jsonParam.dom_ajaxUrl, jsonParam.dom_inputFieldsContainer, jsonParam.dom_errorSection);

//        alert("ajaxRequest.response.responseText: "+ajaxRequest.response.responseText);
    },

    doPopUpPrintVersion: function(e){
        printVersion.popUpWindow();
    },

    doReadPowerReview: function(e){
        alert("power revew");
    },

    doTest: function(e){
        alert("test!!!!");
    }

}

// JS Enhancements
/************************************************************************************
* DOM READY HASH TABLE:
* name convention for dom ready class name and id
* class name needs to be listened should begin with 'domReady_class_'
* if class name include _keypress, do function only when key pressed
* if class name include _click, do function only when button pressed
* if class name without _keypress || _click, do function when keypress && button press
* id needs to be listened should begin with 'domReady_id_'
*
*************************************************************************************/
// list all class names with their functions in hash table
var classNameHashTable = new Hash({
    domReady_class_popupPersonalizationAddToCartButton: domReadyEventFunctionsCollections.doPersonalization,
    domReady_class_popupPersonalizationCancelButton: domReadyEventFunctionsCollections.doPersonalizationDisappear,
    domReady_class_popupOpen: domReadyEventFunctionsCollections.doGeneralPopUpOpen,
    domReady_class_popupClose: domReadyEventFunctionsCollections.doGeneralPopUpClose,
    domReady_class_submitQtyModi_keypress: domReadyEventFunctionsCollections.doSubmitQtyModi,
    domReady_class_submitCoupon_shoppingCartPage_keypress: domReadyEventFunctionsCollections.doSubmitCouponByKey,
    domReady_class_submitCoupon_shoppingCartPage: domReadyEventFunctionsCollections.doAjaxJson,
    domReady_class_popupPrintVersion: domReadyEventFunctionsCollections.doPopUpPrintVersion
});


var classNamesJSONObj = {
    "domReady_class_test":domReadyEventFunctionsCollections.doTest
};


// list all ids with their functions in hash table
var idHashTable = false;/*new Hash({
    domReady_test1Id: domReadyFunctionsCollections.test1,
    domReady_test2Id: domReadyFunctionsCollections.test2
    //main_table is an exception, it don't need to follow name convension
//    main_table: domReadyFunctionsCollections.createLightBox
});*/


// 3. event handler: only if you have some special requirement, one element can add two or more domReady_XXXClass, otherwise, one element can just have one domReady_XXXClass
// PLEASE DON'T MODIFY HERE!!!
var domReadyListener = {
    eventListener1: function(e){
        var currentElement = e.element();
        if(currentElement.classNames().size()>0){
            currentElement.classNames().each(function(c){
                if(c.include("domReady_class_")){
                    if(classNameHashTable.get(c)!=null){
                        if(c.include("_keypress")){// if class name include _keypress, do function only when key pressed
                            if(e.charCode || e.keyCode){
                                classNameHashTable.get(c)(e,c);
                            }
                        }else if(c.include("_click")){// if class name include _click, do function only when button pressed
                            if(e.button){
                                classNameHashTable.get(c)(e,c);
                            }
                        }else{// if class name without _keypress || _click, do function when keypress && button press
                                classNameHashTable.get(c)(e,c);
                                }
                            }
                        }
            })
        }
    },
    eventListener2: function(e){
        var currentElement = e.element();
        if(currentElement.classNames().size()>0){
            currentElement.classNames().each(function(c){

                // DO STH FOR CLASS NAME "domReady_class_test"
                if(c.include("domReady_class_test")){
                    alert("check point 1: classNamesJSONObj.domReady_class_test: "+classNamesJSONObj.domReady_class_test);
                    if(classNamesJSONObj.domReady_class_test){
                        alert("check point 2");
                        classNamesJSONObj.domReady_class_test(e);
                    }
                }
            })
        }
    }
}



/************************************************************************************
* ALL TOOLS LIST BELOW                                                              *
*                                                                                   *
*************************************************************************************/

/************************************************************************************
* textInputDataRemover: this function will remove content of text input box 
*************************************************************************************/
var textInputDataRemover = {
    cleanBaseOnElement:function(element){

        if(element._cleared){
            return;
        }
        element.clear();
        element._cleared = true;
    },
    cleanBaseOnForm:function(form, inputTypeArray){
        var arr = form.getInputs();
        arr.each(function(item){
            inputTypeArray.each(function(type){
                if(item.type==type){
                    item.clear();
                }
            })
        });
    }
}

/************************************************************************************
* lightBoxV2: this function do background fading like lightbox and close all popup
*************************************************************************************/
var lightBoxV2 = {

    createLightBoxV2: function(popupDomClassName){
        var overLay = "<div id='overlay' class='display_none ";
        overLay = overLay + popupDomClassName + "' style='opacity:.40;filter: alpha(opacity=40); -moz-opacity: 0.4; position: absolute; top: 0px; left: 0px; z-index: 90; background-color: #000000; ";
/*
        overLay = overLay + "height: "+pageHeight+"px; ";
        overLay = overLay + "width: "+pageWidth+"px ";
*/
        overLay = overLay + "height: 1px; ";
        overLay = overLay + "width: 1px ";
        overLay = overLay + "'/>";
        $("main_table").insert({bottom:overLay});
    },

    doLightBoxV2: function(popupDomClassName, backgroundColor, opacity){
        var pageHeight = winPageSize.getPageSize().get("pageHeight");
        var pageWidth = winPageSize.getPageSize().get("pageWidth");
        if($("overlay")){
            $("overlay").addClassName(popupDomClassName);
            if(backgroundColor){
                $("overlay").setStyle({backgroundColor:backgroundColor});
            }else{
                $("overlay").setStyle({backgroundColor:"#000000"});
            }
            if(opacity){
                $("overlay").setOpacity(opacity);
            }else{
                $("overlay").setOpacity(0.4);
            }
            $("overlay").setStyle({height:pageHeight+"px", width:pageWidth+"px"});
/*
            $("overlay").style.height = pageHeight;
            $("overlay").style.width = pageWidth;
*/
            $("overlay").removeClassName("display_none");
        }else{
            lightBoxV2.createLightBoxV2(popupDomClassName);
            if(backgroundColor){
                $("overlay").setStyle({backgroundColor:backgroundColor});
            }else{
                $("overlay").setStyle({backgroundColor:"#000000"});
            }
            if(opacity){
                $("overlay").setOpacity(opacity);
            }else{
                $("overlay").setOpacity(0.4);
            }
            $("overlay").setStyle({height:pageHeight+"px", width:pageWidth+"px"});
/*
            $("overlay").style.height = pageHeight;
            $("overlay").style.width = pageWidth;
*/
            $("overlay").removeClassName("display_none");
        }

    },

    cancelLightBoxV2: function(popupDomClassName){
        if(!domReady_lock_popup){
            $$('.dom_popup').each(function(o){
                o.addClassName("display_none");
            })

            if($("overlay")){
                $("overlay").addClassName("display_none");
                $("overlay").removeClassName(popupDomClassName);
            }
        }
    },

    //In some special situation, z-index will re-set to special number for disable all clickable element on popup window, ie. when validation data input on popup ...
    changeLightBoxV2ZIndex: function(zIndexNum){
        if($("overlay")){
            $("overlay").setStyle({zIndex:zIndexNum});
        }
    }
}

/*
* all serializable elements should have a class name "domSerializableField"
* all serializable elements can set domReady_value for mandatory:true/false
*
* */
var generalAjaxAction = {
    processJSON: function(e, c, url, serializableFieldsContainerId, errorDisplayAreaId){
        var validated = true;
        var errorSectionObj;

        if(errorDisplayAreaId!=null){
            if(errorDisplayAreaId.strip().length>0){
                if($(errorDisplayAreaId)){
                    errorSectionObj = $(errorDisplayAreaId);
                }
            }
        }


        if($(serializableFieldsContainerId)){
            var arr = $(serializableFieldsContainerId).select('.domSerializableField');

/* DON'T NEED, ERROR MSG IN JSON OBJ

            arr.each(function(o){
                var jsonParam = o.readAttribute('domReady_value').evalJSON();
                if(jsonParam.mandatory=='true'){
                    //simple validation for input tag
                    if(o.tagName=="INPUT"){
                        if(o.type=="text"){
                            if(o.value.strip() == ""){
                                errorSectionObj.innerHTML="Please enter a valid value.";
                            }else{
                                errorSectionObj.innerHTML="";
                            }
                        }
                    }
                    //simple validation for select

                }
            })
*/


            if(arr.length>0 && validated){
                var params = Form.serializeElements(arr);

                if (window.location.toString().substring(0, 5) == "http:") {
                    url = url.replace("https", "http"); // remove the secure link for AJAX calls if we are loaded insecurely
                }

                new Ajax.Request(
                    url,
                    {
                        method: 'post',
                        parameters: params,
                        onSuccess: function(response){
                            var json = response.responseText.evalJSON();
//                            alert(response.responseText);
                            lightBoxV2.cancelLightBoxV2("abc");
                            generalAjaxAction.processing(e, c,json,errorSectionObj);
                        },
                        onFailure: function () {
                            errorSectionObj.innerHTML="Ajax call failed!";
                        }
                    });

            }else{
                alert("NO CLASS NAME 'domSerializableField' CAN BE FOUND IN "+serializableFieldsContainerId+" CONTAINER!")
            }
        }else{
            alert("NO ID "+serializableFieldsContainerId+"CAN BE FOUND!");
        }

    },

    // do diff process base on diff dom class name
    processing: function(e, c,jsonObj,errorSectionObj){

        errorSectionObj.innerHTML = "";
        // for domReady_class_submitCoupon_shoppingCartPage
        if(c=="domReady_class_submitCoupon_shoppingCartPage"){

            if (jsonObj.confirmOverride) {
                lightBoxV2.doLightBoxV2("domReady_class_popupClose");
                $("shopCartCodeInputContainer").removeClassName("display_none");
                $("shopCartCodeInputContainer").select(".dom_focus").each(function(fo){
                    fo.focus();
                })
            } else if(jsonObj.submitFormWithoutConfirm) {
                submitForm.submit("applyCoupon");
            } else {
                errorSectionObj.innerHTML = jsonObj.errorMessage;
            }

        }
    }
}

var printVersion= {
    hideElementIdsInPage: [
        {"pageClassName":"productDetailPG","hideElementId":["globalHeader","globalFooter"], "url":""},
        {"pageClassName":"checkoutConfirmationPG","hideElementId":["checkouthead","checkoutfooter","printButtonImg"], "url":"/checkoutConfirmation.jsp.vr"}
    ],


    getCurrentPageURL: function(){
//        return {"pageName":$("main_table").classNames().toArray()[0].strip(), "pageURL":window.location.href};
        return window.location.href;
    },

    popUpWindow: function(){
        var url="";
        printVersion.hideElementIdsInPage.each(function(j){
            if(j.pageClassName==$("main_table").classNames().toArray()[0].strip()){
                if(j.url!=null){
                    if(j.url.strip().length>0){
                        url = j.url.strip();
                    }
                }
            }
        })
        if(url.length<1){
            url = printVersion.getCurrentPageURL();
        }
//        window.open(printVersion.getCurrentPageUrl(),'printWindow','width=1000')
        var printWindow = window.open(url,'printWindow', 'scrollbars=yes,toolbar=no,copyhistory=no,location=no,directories=no,status=no,menubar=yes,width=1100px');

    },

    hideMe: function(){

//        lightBoxV2.doLightBoxV2("abc", "transparent", "0");
        printVersion.hideElementIdsInPage.each(function(j){
            if(j.pageClassName==$("main_table").classNames().toArray()[0].strip()){

                j.hideElementId.each(function(id){
                    if($(id)){
                        $(id).addClassName("display_none");
                    }
                })
            }
        })
        if($("printButtonID")){
            $("printButtonID").addClassName("display_none");
        }
        if($("printMeID")){
            $("printMeID").removeClassName("display_none");
        }

/*
        document.body.setStyle({
            background: "transparent url('/imageservlet?webImageName=background_gradiant_print.gif&languageId=EN') top center repeat-y"
        });
*/

//        document.body.style.background = "transparent url('/imageservlet?webImageName=background_gradiant_print.gif&languageId=EN') top center repeat-y";
    }
}

var powerReview = {
    showReviews: function(){
        switchTabs.doSwitch('tabSet_reviews', 'tabsID', 'tabContents_Container_id');

    }
}

/************************************************************************************
* winPageSize: this functions return back window width, height, page width, height
*************************************************************************************/
var winPageSize = {

    getPageSize: function(){
        var xScroll, yScroll;
        var pageHeight, pageWidth;

        if (window.innerHeight && window.scrollMaxY) {
            xScroll = document.body.scrollWidth;
            yScroll = window.innerHeight + window.scrollMaxY;
        } else if (document.body.scrollHeight > document.body.offsetHeight){
            xScroll = document.body.scrollWidth;
            yScroll = document.body.scrollHeight;
        } else {
            xScroll = document.body.offsetWidth;
            yScroll = document.body.offsetHeight;
        }

        var windowWidth, windowHeight;
        if (typeof(window.innerWidth)=='number') {
            windowWidth = window.innerWidth;
            windowHeight = window.innerHeight;
        } else if (document.documentElement && document.documentElement.clientHeight) {
            windowWidth = document.documentElement.clientWidth;
            windowHeight = document.documentElement.clientHeight;
        } else if (document.body) {
            windowWidth = document.body.clientWidth;
            windowHeight = document.body.clientHeight;
        }

        if(yScroll < windowHeight){
            pageHeight = windowHeight;
        } else {
            pageHeight = yScroll;
        }

        if(xScroll < windowWidth){
            pageWidth = windowWidth;
        } else {
            pageWidth = xScroll;
        }

        var winPageSizeHash = new Hash({
            windowWidth: windowWidth,
            windowHeight: windowHeight,
            pageWidth: pageWidth,
            pageHeight: pageHeight
        })
        return winPageSizeHash;
    }

}


/*
 * this is the general class for switch tabs and it's related content
 *
 */

var switchTabs = {
    doSwitch: function(currentObjID, tabsParentID, tabcContentsParentID){
        if(!$(currentObjID).className.indexOf('selected') >= 0){
            for(var i=0; i<$(tabsParentID).childElements().size(); i++){
                $(tabsParentID).childElements()[i].removeClassName('selected');
            }
            $(currentObjID).addClassName('selected');

            for(var j=0; j<$(tabcContentsParentID).childElements().size(); j++){
                $(tabcContentsParentID).childElements()[j].addClassName('display_none');
            }
            $(currentObjID+"_content").removeClassName('display_none')
            //$(currentObjID.replace("TabID", "P0")).click();
            if ( currentObjID.indexOf("billMeLater") < 0) { // don't preselect BML
                var testEL = $(currentObjID.replace("TabID", "P0"));
                if (testEL) {
                    testEL.click();
                }
            }
        }

    }
}

var numericCheck = {
    isNumeric: function(num){
        var test_result = /^\d+$/.test(num);
        return test_result;
    }
}

var skuOption = {
    skuOptionsAjaxCall: function(url, objId){

        var optionValue = $(objId).options[$(objId).selectedIndex].value;
        if(optionValue!=null && optionValue>0){
            skuOption.availabelColorChange(optionValue);
        }

        var nextSelectId = "skuOpt"+(parseInt(objId.substring(objId.length-1, objId.length))+1);

//        if($(objId).value!=null && $(objId).value!=""){
        if($(objId).selectedIndex!=0){
            var param = $(objId).serialize();
            lightBoxV2.doLightBoxV2("abc", "#FFFFFF", "0");
            $("ajaxSkuInfoSection").removeClassName("display_none");

            if (window.location.toString().substring(0, 5) == "http:") {
                url = url.replace("https", "http"); // remove the secure link for AJAX calls if we are loaded insecurely
            }

            new Ajax.Request(
                url,
                {
                    method: 'post',
                    parameters: param,
                    onSuccess: function(response){
                        var json = response.responseText.evalJSON();

                        $(nextSelectId).writeAttribute("domReady_value", response.responseText);

                        if(json.errorMessage==""){
                            if($(nextSelectId)){
                                var allNodes = $(nextSelectId).childElements();
                                for(var i=0; i<allNodes.length; i++) {
                                    allNodes[i].remove();
                                }
                            }
                            //                    alert(json.nextSkuOption.prettyName);

                            json.nextSkuOption.optionList.each(function(jsonOption){
//                                var optionHtml = "<option value='"+jsonOption.value+"'>"+jsonOption.prettyName+"</option>";
                                $(nextSelectId).insert("<option value='"+jsonOption.value+"'>"+jsonOption.prettyName+"</option>");
        //                        alert(jsonOptionList.value+" : "+jsonOptionList.prettyName+" : "+jsonOptionList.selected);
                            })

                            $(nextSelectId).selectedIndex = 0;
                            $("ajaxSkuInfoSection").addClassName("display_none");
                            lightBoxV2.cancelLightBoxV2("abc");

                            $(nextSelectId).disabled = false;
                        }

                    },
                    onFailure: function () {
                        $("ajaxSkuInfoSection").addClassName("display_none");
                        lightBoxV2.cancelLightBoxV2("abc");
                        alert("Ajax call failed!");
                    }
                });
        }else{

            // all assumptions are based on MAX SKU OPTIONS NUMBER IS 3. ugly!!!
            $(nextSelectId).selectedIndex = 0;
            $(nextSelectId).disabled = true;
//            $("prodOrderOty").disabled = true;

            var nextNextSelectId = "skuOpt"+(parseInt(nextSelectId.substring(nextSelectId.length-1, nextSelectId.length))+1);
            if($(nextNextSelectId)){
                $(nextNextSelectId).selectedIndex = 0;
                $(nextNextSelectId).disabled = true;
            }
        }
    },



    shippingInfoAjaxCall: function(url, objId){
//$("globalHeader_C1R5").innerHTML = "<p><span style='color:red'>url:</span> "+url+" <span style='color:red'>| url:</span> "+objId+"</p>";
//        var optionValue = $(objId).options[$(objId).selectedIndex].value;
        var param = $(objId).serialize();

        if (window.location.toString().substring(0, 5) == "http:") {
            url = url.replace("https", "http"); // remove the secure link for AJAX calls if we are loaded insecurely
        }

        new Ajax.Request(
            url,
            {
                method: 'post',
                parameters: param,
                onSuccess: function(response){
                    var jsonObj = response.responseText.evalJSON();

                    if(jsonObj.errorMessage==null || jsonObj.errorMessage==""){
                        // replace CustomShippingInfo & replace shipping fee
                        var allInfoList='';

                        if(jsonObj.nextSkuOption.optionList!=null && jsonObj.nextSkuOption.optionList.size()>0){
                            allInfoList='';
                            jsonObj.nextSkuOption.optionList.each(function(list){
                                allInfoList = allInfoList+"<li><p class='shippingProcessingFeeclass'>"+list.shippingInfo.shippingProcessingFee+"</p><p class='shippingRecyclingFeeclass'>"+list.shippingInfo.shippingRecyclingFee+"</p><p class='shippingLeadTimeclass'>"+list.shippingInfo.leadTime+"</p><p class='CustomShippingInfoclass'>"+list.shippingInfo.customShippingInfo+"</p><p class='shippingDate'>"+list.shippingInfo.shippingDate+"</p></li>";
                            })

                            allInfoList="<ul>"+allInfoList+"</ul>";

                            if($("allInfoList")){
                                $("allInfoList").innerHTML=allInfoList;
                            }

                        }else{
                            if($("allInfoList")){
                                $("allInfoList").innerHTML="";
                            }
                        }

                    }else{
                        // not deal with error msg yet...
                    }

                },
                onFailure: function () {
                    alert("Ajax call failed!");
                }
            });
    },

    replaceInfo: function(objId){

        $("skuOptErrorSection").addClassName("display_none");

        var optionValue = $(objId).options[$(objId).selectedIndex].value;
        if(optionValue!=null && optionValue>0){
            skuOption.availabelColorChange(optionValue);
        }

        var domReady_val = $(objId).readAttribute("domReady_value");

        var jsonObj = domReady_val.evalJSON()

        for(var i=0; i<jsonObj.nextSkuOption.optionList.length; i++){
            if(i==$(objId).selectedIndex){

                //replace from prefix
                if(jsonObj.nextSkuOption.optionList[i].multiplePrices==true){
                    if($("priceTitle_wasfrom")){
                        $("priceTitle_wasfrom").innerHTML = "From";
                    }
                    if($("priceTitle_nowfrom")){
                        $("priceTitle_nowfrom").innerHTML = "From";
                    }
                }else{
                    if($("priceTitle_wasfrom")){
                        $("priceTitle_wasfrom").innerHTML = "";
                    }
                    if($("priceTitle_nowfrom")){
                        $("priceTitle_nowfrom").innerHTML = "";
                    }
                }

                // replace current price
                if($("currentPriceValue") && jsonObj.nextSkuOption.optionList[i].price!=null){
//                    $("priceCurrentId").replace("<p id='priceCurrentId' class='priceCurrent font_150'>"+jsonObj.nextSkuOption.optionList[i].price+"</p>");
                    $("currentPriceValue").innerHTML = jsonObj.nextSkuOption.optionList[i].price;
                }

                // replace originalRetailPrice
                if($("pricePreviousValue") && jsonObj.nextSkuOption.optionList[i].originalRetailPrice!="" && jsonObj.nextSkuOption.optionList[i].originalRetailPrice!=null){
                    $("pricePreviousValue").innerHTML = jsonObj.nextSkuOption.optionList[i].originalRetailPrice;
                    $("originalPriceID").removeClassName("display_none");
                }else if($("pricePreviousValue")){
                    $("originalPriceID").addClassName("display_none");

                }

                // inventory check
                if(jsonObj.nextSkuOption.optionList[i].available==true){

                    // enable qty input box if has inventory
                    if($("prodOrderOty")){
                        $("prodOrderOty").disabled = false;
                        $$(".skuOptSelect").each(function(o){
                            if(o.selectedIndex==0){
                                $("prodOrderOty").disabled = true;
                                throw $break;
                            }
                        })
                        
                    }
                    // don't show 'out of stock' if has inventory
                    if($("qtyErrorSection")){
                        $("qtyErrorSection").innerHTML="";
                    }

                    if($("popupPersonalizationButtonImg")){
                        $("popupPersonalizationButtonImg").src = "/imageservlet?webImageName=addToCart.gif&languageId=EN";
                        $("popupPersonalizationButton").addClassName("domReady_class_popupPersonalizationAddToCartButton");
                        $("popupPersonalizationButtonImg").addClassName("domReady_class_popupPersonalizationAddToCartButton");
                    }else if($("addToCartButton")){
                        $("addToCartButton").replace("<input type='image' class='image addToCartBtnIeFix' alt='add To Cart button' src='/imageservlet?webImageName=addToCart.gif&amp;languageId=EN' id='addToCartButton'/>");
                    }

                }else if(jsonObj.nextSkuOption.optionList[i].available==false){

                    // disable qty input box if has no inventory
                    if($("prodOrderOty")){
                        $("prodOrderOty").disabled = true;
                    }
                    // show 'out of stock' if has inventory
                    if($("qtyErrorSection")){
                        $("qtyErrorSection").innerHTML="Out of Stock";
                    }

                    if($("popupPersonalizationButtonImg")){
                        $("popupPersonalizationButtonImg").src = "/imageservlet?webImageName=disabledAddToCart.gif&languageId=EN";
                        $("popupPersonalizationButton").removeClassName("domReady_class_popupPersonalizationAddToCartButton");
                        $("popupPersonalizationButtonImg").removeClassName("domReady_class_popupPersonalizationAddToCartButton");
                    }else if($("addToCartButton")){
                        $("addToCartButton").replace("<img id='addToCartButton' src='/imageservlet?webImageName=disabledAddToCart.gif&amp;languageId=EN' alt='add To Cart button' />")
                    }

                }

                break;
            }
        }


        // replace protection plan
        var protectionPlanLineInnerHtml = "";
        var protectionPlanTabListInnerHtml = "";
        var protectionPlanContainerObj = $("protectionPlanContainer_id");
        if(protectionPlanContainerObj){
            protectionPlanContainerObj.addClassName("display_none");
            protectionPlanContainerObj.innerHTML = "";
        }

        for(var i=0; i<jsonObj.nextSkuOption.optionList.length; i++){
            if(i==$(objId).selectedIndex){
                if(jsonObj.nextSkuOption.optionList[i].protectionPlanList.length>0){
                   jsonObj.nextSkuOption.optionList[i].protectionPlanList.each(function(proPlanObj){
                       protectionPlanLineInnerHtml = protectionPlanLineInnerHtml+"<div class='protectionPlanLine'>";
                       protectionPlanLineInnerHtml = protectionPlanLineInnerHtml+"<div class='protectionTitle'><label for='protectionPlan_"+proPlanObj.suffix+"'>"+proPlanObj.prettyName+"</label></div>";
                       protectionPlanLineInnerHtml = protectionPlanLineInnerHtml+"<div class='protectionValue'><label for='protectionPlan_"+proPlanObj.suffix+"'>"+proPlanObj.price+"</label></div>";
                       protectionPlanLineInnerHtml = protectionPlanLineInnerHtml+"<div class='protectionCheckbox'>";
                       protectionPlanLineInnerHtml = protectionPlanLineInnerHtml+"<input type='checkbox' class='checkbox protectionPlan' name='protectionPlan_"+proPlanObj.suffix+"' id='protectionPlan_"+proPlanObj.suffix+"'/>";
                       protectionPlanLineInnerHtml = protectionPlanLineInnerHtml+"</div></div>";

                       protectionPlanTabListInnerHtml = protectionPlanTabListInnerHtml+"<li>"+proPlanObj.prettyName+" "+proPlanObj.price+"</li>";
                   })

/*
                   if($("protectionPlanLines_container")){
                       $("protectionPlanLines_container").innerHTML = protectionPlanLineInnerHtml;
                   }
*/
                }
                break;
            }
        }

        if(protectionPlanContainerObj && protectionPlanLineInnerHtml.length>0){
            protectionPlanContainerObj.innerHTML = "<h2 class='font_100'>Add Protection Plus</h2><div id='protectionPlanLines_container'>"+protectionPlanLineInnerHtml+"</div>";
            protectionPlanContainerObj.removeClassName("display_none");
        }

        // change protection plan list in protection plan tab
        var protectionPlanTab_planContainer = $("protectionPlanTab_protList");

        if(protectionPlanTab_planContainer && protectionPlanTabListInnerHtml.length>0){
            protectionPlanTab_planContainer.innerHTML = "<ul class='pdTab_protectionPlanInfo'>"+protectionPlanTabListInnerHtml+"</ul>"
        }

    },

    availabelColorChange: function(productID){
/*
        var availableColorBtns = $("availableColorsID").select(".availableColorBtn");
        availableColorBtns.each(function(o){
            o.removeClassName("border_style_3");
        })

*/
        var availableColorBoxID = "colorBtn_"+productID;
        var availableColorBox = $(availableColorBoxID);
        if(availableColorBox){
//            availableColorBox.addClassName("border_style_3");
            availableColorBox.click();
        }

    }

}

var highLightTool = {
    hightLight: function(parentID, highLightClassName, hightLightStyle, highLightObjID){
        var hightLightObj = $(parentID).select("."+highLightClassName);
        hightLightObj.each(function(o){
            o.removeClassName(hightLightStyle);
        })
        if(highLightObjID!=null){
            if($(highLightObjID)){
                $(highLightObjID).addClassName(hightLightStyle);
            }
        }
    }
}

var personalization = {
    duplicate: function(qtyId, duplicatedObjId, duplicateStartLineId){
        qty = $(qtyId).value;
        if(numericCheck.isNumeric(qty)){
            $("qtyErrorSection").innerHTML="";

            var duplicatedObj = $(duplicatedObjId);
//            $("popupPersonalizationButton").disabled = true; // temp. to put this here, will be removed after implement background fading.
//            $("popupPersonalizationButtonImg").disabled = true;

    //        alert(duplicatedObjId+" : "+$$("#customizeWidgetContainer .multipleObj").length);

            var duplicateStartLine = $(duplicateStartLineId);
            if(qty>1){
                $("personalizeAll").removeClassName("display_none");
            }else{
                $("personalizeAll").addClassName("display_none");
            }
            for(var i=0; i<qty-1; i++){
                duplicateStartLine.insert(duplicatedObj.innerHTML);
            }

            //to do list: will change the hardcode id and class name later.
    //        alert($$("#productCustomization .multipleObj").length);
            var suffix=0;
            var multiObjs;
            var labelObjs = null;
            var inputObjs = null;
            var selectObjs = null;
            var errorObjs = null;
            for(var j=0; j<$$("#productCustomization .widgetRight_container").length; j++){

                multiObjs = $$("#productCustomization .widgetRight_container")[j];

                labelObjs = multiObjs.getElementsByTagName("label");
                inputObjs = multiObjs.getElementsByTagName("input");
                selectObjs = multiObjs.getElementsByTagName("select");
                errorObjs = multiObjs.select(".personalizeErrorSection");


                if(labelObjs.length>0){
                    for(var k=0; k<labelObjs.length; k++){
                        labelObjs[k].htmlFor = labelObjs[k].htmlFor + "_"+suffix;
                        labelObjs[k].id = labelObjs[k].id + "_"+suffix;
                    }
                }
                if(inputObjs.length>0){
                    for(var k=0; k<inputObjs.length; k++){
                        inputObjs[k].id = inputObjs[k].id + "_"+suffix;
                        inputObjs[k].name = inputObjs[k].name + "_"+suffix;
                    }
                }
                if(selectObjs.length>0){
                    for(var k=0; k<selectObjs.length; k++){
                        selectObjs[k].id = selectObjs[k].id + "_"+suffix;
                        selectObjs[k].name = selectObjs[k].name + "_"+suffix;
                    }
                }
                if(errorObjs.length>0){
                    for(var k=0; k<errorObjs.length; k++){
                        errorObjs[k].id = errorObjs[k].id + "_"+suffix;
                    }
                }
                suffix = suffix + 1;

            }

            $('productCustomization').removeClassName('display_none');

            $("addToCartButtonInPersonalization").focus();

        }else{
            $("qtyErrorSection").innerHTML="Please enter a valid quantity for the item (valid integer, greater than zero).";
        }
    },
    delAllDuplicate: function(duplicateStartLineId){
        var personalizationGeneralErrorSection = $("errorMsgPersonalization");
        var duplicateStartLine = $(duplicateStartLineId);
        if(personalizationGeneralErrorSection){
            personalizationGeneralErrorSection.addClassName("display_none");
        }
        if(duplicateStartLine){
            duplicateStartLine.innerHTML = "";
    //        $("popupPersonalizationButton").disabled = false;
    //        $("popupPersonalizationButtonImg").disabled = false;

            //remove suffix number
            var multiObjs = null;
            var labelObjs = null;
            var inputObjs = null;
            var selectObjs = null;
            var errorObjs = null;
            var idName;
            for(var j=0; j<$$("#customizeWidgetContainer .widgetRight_container").length; j++){

                multiObjs = $$("#customizeWidgetContainer .widgetRight_container")[j];

                labelObjs = multiObjs.getElementsByTagName("label");
                inputObjs = multiObjs.getElementsByTagName("input");
                selectObjs = multiObjs.getElementsByTagName("select");
                errorObjs = multiObjs.select(".personalizeErrorSection");

                if(labelObjs.length>0){
                    for(var k=0; k<labelObjs.length; k++){
                        idName = labelObjs[k].htmlFor;
                        id = labelObjs[k].id;
                        labelObjs[k].htmlFor = idName.substring(0, idName.length-2) ;
                        labelObjs[k].id = id.substring(0, id.length-2) ;
                        if($(labelObjs[k].id).className.indexOf("color_site_3") >= 0){
                            $(labelObjs[k].id).removeClassName("color_site_3");
                        }
                    }
                }

                if(inputObjs.length>0){
                    for(var k=0; k<inputObjs.length; k++){
                        idName = inputObjs[k].id;
                        inputObjs[k].id = idName.substring(0, idName.length-2);
                        inputObjs[k].name = idName.substring(0, idName.length-2);
    //                    inputObjs[k].value = "";
                    }
                }

                if(selectObjs.length>0){
                    for(var k=0; k<selectObjs.length; k++){
                        idName = selectObjs[k].id;
                        selectObjs[k].id = idName.substring(0, idName.length-2);
                        selectObjs[k].name = idName.substring(0, idName.length-2);
                        selectObjs[k].selectedIndex = 0;
                    }
                }

                if(errorObjs.length>0){
                    for(var k=0; k<errorObjs.length; k++){
                        idName = errorObjs[k].id;
                        errorObjs[k].id = idName.substring(0, idName.length-2);
                        errorObjs[k].innerHTML = "";
                    }
                }
            }
        }
    },
    replaceAll: function(idList, qty){
        var idListValue = [];
        for(var i=0; i<idList.length; i++){
            idListValue[i] = $(idList[i]+"_0").value;
        }

        for(var i=1; i<qty; i++){
            for(var j=0; j<idList.length; j++){
                $(idList[j]+"_"+i).value = idListValue[j];
            }
        }

    },
    personalizationAjaxCall: function(url, containerId, serializeObjClassName, replaceBlockId){
        var arr = $(containerId).select('.'+serializeObjClassName);
        var params = Form.serializeElements(arr);
//        alert("Serialized String : " + params.inspect());

        if (window.location.toString().substring(0, 5) == "http:") {
            url = url.replace("https", "http"); // remove the secure link for AJAX calls if we are loaded insecurely
        }

        new Ajax.Request(
            url,
            {
                method: 'post',
                parameters: params,
                onSuccess: function(response){
                    var json = response.responseText.evalJSON();
                    var errorFieldList = json.json_errorFieldNameList;
                    var innerHtmlContent = "";

                    if(!json.json_hasError){
//                        alert("no error: close "+containerId);
                        $(containerId).addClassName("display_none");
                        lightBoxV2.cancelLightBoxV2("domReady_class_popupClose");
                        for(var j=0; j<arr.length; j++){
                            $(arr[j].name+"_label").removeClassName("color_site_3");
                            $(arr[j].name+"_errorSection").innerHTML = "";
                            labelInnterHtml = $(arr[j].name+"_label").innerHTML;
                            labelInnterHtml = labelInnterHtml.replace("*","");
                            innerHtmlContent = innerHtmlContent + "<p class='personalizationLine'><span class='personalizationTitle'>"+labelInnterHtml+"</span><span class='personalizationContent'>"+$(arr[j]).value+"</span></p>"
                        }

                        $(replaceBlockId).innerHTML = innerHtmlContent;

                    }else{
//                        alert("input has error, errorFieldList length: "+errorFieldList.length);
                        for(var i=0; i<errorFieldList.length; i++){
                            for(var j=0; j<arr.length; j++){
                                if(arr[j].name.indexOf(errorFieldList[i])>=0){
                                    $(arr[j].name+"_label").addClassName("color_site_3");
                                    $(arr[j].name+"_errorSection").innerHTML = json.json_errorMessageList[i];
                                }
                            }
                        }

                    }
                },
                onFailure: function () {
                        alert("Ajax call failed!");
                }
            });

    },
    popupClose: function(popupContainerId, serializableObjClassName){
        $(popupContainerId).addClassName("display_none");
    }


}

function stateFilter(countryEL, stateEL, preselectedDataObj) {
        // countryRegionDataObj is now the required dataObject that is globally generated
        if (countryEL && stateEL && countryRegionDataObj) {
            preselectedState = {'index': stateEL.selectedIndex || 0, 'value': ((preselectedDataObj)?preselectedDataObj[7]:stateEL.options[stateEL.selectedIndex].value)  };
            selectedIndx = 0;                                                                       // Select the first entry by default until told otherwise
            countrySelectedIndx = ((preselectedDataObj)?((preselectedDataObj[8] == "")?0:countryEL.selectedIndex):countryEL.selectedIndex);//countryEL.selectedIndex || 0;
            countryCode = countryEL.options[countrySelectedIndx].value;                         // found out which country we're talking about
            stateEL.childElements().each(  function(removableNode){ removableNode.remove(); }  );   // remove all option list items in stateEL
            try {   // Check if the country is in our dataMap
                if (!countryRegionDataObj[countryCode]) {   // this check will error in IE browsers
                    countryCode = "FN";     // if the country code doesn't exist in our data object, then default to Other ("FN")
                }
               } catch(errorEvent) {        // if the country code doesn't exist in our data object, then default to Other ("FN") *IE's error case*
                countryCode = "FN";
            }
            if (countryCode == "US" || countryCode == "CA") {
                stateEL.insert("<option value=''>Please Select</option>");
            }
            countryRegionDataObj[countryCode].regions.each(  function(newOptionNode, optionCount){
                                                                    if ( newOptionNode.value == preselectedState.value ) {                     //newOptionNode.selected) {   // should this option be selected?
                                                                        selectedIndx = (optionCount + 1);     // since it does, indicate it's indexcount
                                                                    }
                                                                    stateEL.insert("<option value='"+newOptionNode.value+"'>"+newOptionNode.name+"</option>");
                                                                }
                                                          );
            //for ie only
            //stateEL.selectedIndex = (stateEL.selectedIndex == selectedIndx)?(( ((selectedIndx - 1) <= 0) )?0:(selectedIndx -1)):((selectedIndx >= stateEL.selectedIndex)?(stateEL.selectedIndex - 1):selectedIndx);
            var tempNum = ( (stateEL.options.length == selectedIndx)?(( ((selectedIndx - 1) <= 0) )?0:(selectedIndx -1)):((selectedIndx >= stateEL.selectedIndex)?(stateEL.selectedIndex - 1):selectedIndx) );
            stateEL.selectedIndex =  (tempNum>=0)?tempNum:0; // when the ugly code rains, it pours :(
            countryEL.selectedIndex = countrySelectedIndx;
        }
}

var replaceInputFieldValues = {
    //ie: replaceInputFieldValues.replaceAll([['replaceID1/replaceString1','be replacedID1','1:replace/0: not replace'],['replaceID2/replaceString2','be replacedID2','1:replace/0: not replace'],...])
    replaceAll: function(arrayList){
        for(var i=0; i<arrayList.length; i++){
            if(document.getElementById(arrayList[i][1])!=null){
                if(document.getElementById(arrayList[i][0])!=null){
                    if(arrayList[i][2]==1){
                        document.getElementById(arrayList[i][1]).value = document.getElementById(arrayList[i][0]).value;
                    }else{
                        if(document.getElementById(arrayList[i][1]).value==null || document.getElementById(arrayList[i][1]).value.length==0){
                            document.getElementById(arrayList[i][1]).value = document.getElementById(arrayList[i][0]).value;
                        }
                    }
                }else{
                    if(arrayList[i][2]==1){
                        document.getElementById(arrayList[i][1]).value = arrayList[i][0];
                    }else{
                        if(document.getElementById(arrayList[i][1]).value==null || document.getElementById(arrayList[i][1]).value.length==0){
                            document.getElementById(arrayList[i][1]).value = arrayList[i][0];
                        }
                    }
                }
            }
        }
    },

    replaceAllByChoose:function(curSelection, arrayList){
        //alert(curSelection.selectedIndex);

        for(var i=0; i<arrayList[0].length; i++){
            if(document.getElementById(arrayList[0][i])!=null && curSelection.selectedIndex>0){
                document.getElementById(arrayList[0][i]).value = cleanOutput(arrayList[curSelection.selectedIndex][i]);
            }
        }
    }
}
/*
 * The following dims the site with whatever opacity is set and also
 */
var inlineCart = {
	getFocus: function(e) {
		var firstDiv = $("main_table");
		//new Effect.Opacity('main_table', { from: 1, to: 0.2, duration:0.1 });
/*		innerModal({	'url': "",
			 	'className': "",
			 	'target': "",
			 	'content': ""	//"<div id=\"popUpContent\" style=\"position: absolute; width: 200px; line-height: 200px; vertical-align: middle; border: 2px solid orange; background-color: yellow; opacity: 1; \" >Say WORD!</div>"
			});*/
		//alert("this.id = " + this.id);
		var inlineCart = $("dynCart");
		var containerDiv = $("main_table");
		var parentDiv = document.childNodes[1].childNodes[1];
		parentDiv.insertBefore(inlineCart, containerDiv);
	},
	returnFocus: function() {
		innerModal();
		//var firstDiv = $("main_table");
		//new Effect.Opacity('main_table', { from: 0.2, to: 1, duration:0.1 });
	},
	proceedToCheckout: function(url) {
		document.location = "/shoppingCart.jsp.vr";
		return false;
	}
}

var page_focus = {

	getFocus: function(e) {
	        /*var newDiv = document.createElement("div");
	        var containerDiv = $("main_table");
	        var bodyNode = document.childNodes[1].childNodes[1];

	        bodyNode.insertBefore(newDiv,containerDiv);
	        / * IE 6 bug : setAttribute doesn't work, workaround used * /
	        document.getElementsByTagName("DIV")[0].innerHTML = "<div id='mask_div' onclick='page_focus.returnFocus();'></div>";

	        $('mask_div').style.display="block";
	        $('mask_div').style.backgroundColor="#fff";
	        $('mask_div').style.height=$('main_table').offsetHeight+"px";
	        $('mask_div').style.width="100%";
	        $('mask_div').style.position="absolute";
	        $('mask_div').style.borderStyle="solid";
	        $('mask_div').style.borderWidth="1px";

	        var tagTotal = document.getElementsByTagName("select");
	        for(i=0;i<tagTotal.length;i++){
	            document.getElementsByTagName("select")[i].visibility = "hidden"; //.disabled="true";
	        }
	        new Effect.Opacity('mask_div', { to: 0.8, duration:0});*/
	},

    returnFocus: function() {
	    innerModal();
        /*document.childNodes[1].childNodes[1].removeChild(document.getElementsByTagName("DIV")[0]);
			var tagTotal = document.getElementsByTagName("select");
			for(i=0;i<tagTotal.length;i++){
				document.getElementsByTagName("select")[i].visibility = ""; //disabled="";
			}*/
	}

}

var ajaxLoading = {
    JObj : null,

    $: function (id){
        return document.getElementById(id);
    },

    loading: function(url, divID){
        var XMLHttpRequestObject = false;
        if (window.XMLHttpRequest) {
            XMLHttpRequestObject = new XMLHttpRequest();
        } else if (window.ActiveXObject) {
            XMLHttpRequestObject = new ActiveXObject("Microsoft.XMLHTTP");
        }

        if(XMLHttpRequestObject) {

            var obj = ajaxLoading.$(divID);
            var url = url;

            if (window.location.toString().substring(0, 5) == "http:") {
                url = url.replace("https", "http"); // remove the secure link for AJAX calls if we are loaded insecurely
            }

            XMLHttpRequestObject.open("POST", url, true);  //changed to "post" in hope to avoid squid issue

            XMLHttpRequestObject.onreadystatechange = function()
            {
                if (XMLHttpRequestObject.readyState == 4 &&
                XMLHttpRequestObject.status == 200) {
                    obj.innerHTML = XMLHttpRequestObject.responseText;
                }
            }

            XMLHttpRequestObject.send(null); //Downloading the data
        } else{
            obj = ajaxLoading.$(divID);
            obj.innerHTML = "Sorry, your browser doesn't support Ajax.";
        }
    },

    JSONObj: function(url, divID, popupDivID, formname, buttonObj){
        var XMLHttpRequestObject = false;
        if (window.XMLHttpRequest) {
            XMLHttpRequestObject = new XMLHttpRequest();
        } else if (window.ActiveXObject) {
            XMLHttpRequestObject = new ActiveXObject("Microsoft.XMLHTTP");
        }

        if(XMLHttpRequestObject) {
		var url = url;
		var obj = ajaxLoading.$(divID);
		var jsonObj;
		XMLHttpRequestObject.open("POST", url, true);  //changed to "post" in hope to avoid squid issue
		XMLHttpRequestObject.onreadystatechange = function() {
			if (XMLHttpRequestObject.readyState == 4 && XMLHttpRequestObject.status == 200) {
				jsonObj = eval('('+XMLHttpRequestObject.responseText+')');
                if (jsonObj.confirmOverride) {
					$(popupDivID).style.display = 'block';
				   } else if(jsonObj.submitFormWithoutConfirm) {
					buttonObj.disabled = true;
					submitForm.submit(formname);
				   } else {
					$(divID).innerHTML = jsonObj.errorMessage;
				}
			}
		}
            XMLHttpRequestObject.send(null); //Downloading the data
            preventDoubleSubmit = false;
            //console.log("preventDoubleSubmit set to \"" + preventDoubleSubmit + "\" @ " + Date());
            return ajaxLoading.JObj;

        } else{
            obj = ajaxLoading.$(divID);
            obj.innerHTML = "Sorry, your browser doesn't support Ajax.";
        }

    }
}

var verifyJSON = {
    verifyCoupon: function(url, div, popupDivID, formname){
        var jsonObj = ajaxLoading.JSONObj(url, div);
        if(jsonObj.confirmOverride){
            $(popupDivID).style.display = 'block';
        }else if(jsonObj.submitFormWithoutConfirm){
            submitForm.submit(formname);
        }else{
            $(div).innerHTML = jsonObj.errorMessage;
        }



//        $(div).innerHTML = jsonObj.errorMessage;
    }

}

var submitForm = {
    submit: function(formName, suffix){
        if(suffix!=null && suffix.length>0){
            document.forms[formName].action = suffix;
        }
        document.forms[formName].submit();
    }
}

var submitFormWithEnter = {
    submit: function(formName, suffix, e){
        //alert("formName: "+formName + " : suffix: "+suffix);
        submitForm.submit(formName,suffix);
        return true;

    }
}

// if we need to take care of %3C|%3E ...
var stripHTML = {
    strippingU: function(value){
        var re = /(<([^>]+)>)/gi;
        var re1 = /(&lt;|&gt;|%3C|%3E)/g;
        return value.replace(re1, function (strMatch, p1){return ((p1 == "&lt;") || (p1 == "%3C"))? "<" : ">";}).replace(re, "");
    }
}

var cookieUtil = {

    createCookie: function(name,value,days, path, domain, secure) {
        var expires = "";
        if (days) {
            var date = new Date();
            date.setTime(date.getTime()+(days*24*60*60*1000));
            expires = "; expires="+date.toGMTString();
        }
        document.cookie = name+"="+value
                + expires
                + (path ? "path=" + path : "")
                + (domain ? "; domain=" + domain : "")
                + (secure ? "; secure" : "");
    },

    getCookie: function(name){
        var beginIndex = document.cookie.lastIndexOf(name+'=');
        if(beginIndex == -1) { return null; }
        var value = document.cookie.substring(beginIndex+name.length+1);
        var endIndex = value.indexOf(';');
        if(endIndex == -1) { endIndex = value.length; }
        value = value.substring(0, endIndex);
        value = value.unescapeHTML().stripTags();

        return value;
    },

    eraseCookie: function(name) {
	    cookieUtil.createCookie(name,"",-1);
    }
}

//
///*
// * Inline cart ajax call and
// */
//var url = "http://brookstone.dev.novator.com/inline_cart.jsp";
//new Ajax.Request(url,{
//	onSuccess: function(transport){},
//	onComplete: function(transport){
//		$('inline_cart_container').innerHTML=transport.responseText;
//	}
//});

function inline_cart(){
    Effect.toggle('dynCart', 'blind',{duration: 0.4});
    return false;
}

var couponConfirmation = {
    applyCoupon: function(value){
        /* to be determined from business rules */
    }

}

var showEmailToFriend = {
    showForm: function(){
        document.getElementById('emailToFriend_container').show();
    }

}

function closeBox(){
	document.getElementById('emailToFriend_container').hide();
}


function eventTrafficController(e) {
    actionEL = fakedEvent = false;
    try  {
        actionEL = Event.element(e);
     } catch(errorEvent){
        if (e.fake) {
            actionEL = e.targetElement;
            fakedEvent = e.fake;
        }
    }
	switch(e.type.toLowerCase()) {
        case "click":
            if (e.button == 0) { // Left Click
                // Detects if a link is using the "Store Locator" node, and tags the omniture code for it
                // if we're a link, or an img or span inside of a link, pretend we're a link
                if (actionEL.tagName.toLowerCase() == "a" || actionEL.parentNode.tagName.toLowerCase() == "a") {
                    if ( (actionEL.tagName.toLowerCase() == "img") || (actionEL.tagName.toLowerCase() == "span") ) {
                        actionEL = actionEL.parentNode;
                    }
                    // Grabs the anchor href set, and strips domain and extension
                    nodeLinkFromURL = actionEL.href.substring(actionEL.href.indexOf("/",8)+1,actionEL.href.indexOf(".",actionEL.href.indexOf("/",8)));
                   try {
                        // if the entity's action exists in the omniture dataObject, then register the click event with omniture
                        if(omnitureURLHashmap[nodeLinkFromURL] != undefined){
                            var s=s_gi(OMNITURE_VALUE);
                            s.linkTrackVars='events';
                            s.linkTrackEvents='event12';
                            s.events='event12';
                            s.tl(true,'o',omnitureURLHashmap[nodeLinkFromURL]);
                        }
                      } catch(errorEvent) {   // explicitly catch and indicate any issue to the developer if the appropriate data object doesn't exist
                        //alert("omnitureDataObj['" + nodeLinkFromURL.name + "'] does not exist. Please check the dataobject you are building, and ensure the appropriate name or ID exists.");
                    }

                }

                if ( actionEL.className.indexOf("ShipSameAsBill") >= 0 ) {
                    if ( (actionEL.tagName.toLowerCase() == "input") && (actionEL.type.toLowerCase() == "checkbox") ) {
                        synchBillingAndShipping(actionEL.checked);
                    }
                    // and then allow the event to bubble up appropriately
                  } else if ( actionEL.className.indexOf("printPage") >= 0 ) {
                    Effect.ScrollTo( 'main_table' );  //'globalHeader_C3R1' );
                    bodyEL = $$("body");
                    Event.stop(e);
                    if (bodyEL.length > 0) {
                        bodyEL[0].addClassName("print");
                        var printResults = window.print();
                        bodyEL[0].removeClassName("print");
                    }
                  } else if ( actionEL.className.indexOf("billMeLaterLabel") >= 0 ) {
                    if ( (document.selection) && (actionEL.tagName.toLowerCase() == "label") ) {
                        //alert("IE needs an explicit click event sent to " + actionEL.htmlFor);
                        tempClickEL = $(actionEL.htmlFor);
                        if (tempClickEL){
                            tempClickEL.click();
                        }
                    }
                  } else if ( actionEL.className.indexOf("protectionPlan") >= 0 ) {
                    if ( (actionEL.tagName.toLowerCase() == "input") && (actionEL.type.toLowerCase() == "checkbox") ) {
                        if (activeProtectionPlanCheckboxID != "") { // if we currently don't have a selected protection plan checkbox
                            if (actionEL.checked) {                    // and the element that triggered the event isn't already checked
                                if (activeProtectionPlanCheckboxID != actionEL.id) {    // or already identified as active
                                    tempEL = $(activeProtectionPlanCheckboxID);         // reference that element
                                    if (tempEL && tempEL.tagName.toLowerCase() == "input" && tempEL.type.toLowerCase() == "checkbox") { // and if it exists, and is an input checkbox, then uncheck it
                                        tempEL.checked = false;
                                    }
                                    tempEL = false;
                                }
                                activeProtectionPlanCheckboxID = actionEL.id;   // set myself as the active checkbox id
                             } else {
                                activeProtectionPlanCheckboxID = "";   // remove my name from the active registry
                            }
                         } else {
                            activeProtectionPlanCheckboxID = actionEL.id;   // set myself as the active checkbox id
                        }
                    }   //  note that we don't need to explicitly set the element to checked because we're allowing the event bubbling to take care of that
                  } else if ( actionEL.className.indexOf("shipToMethodMatrix") >= 0 ) {
                        try {
                            if (shipToMethodActiveMatrix[actionEL.name] != "") {
                                if ((shipToMethodActiveMatrix[actionEL.name] != actionEL.id)&&(shipToMethodActiveMatrix[actionEL.name] != "")) {
                                    tempEL = $(shipToMethodActiveMatrix[actionEL.name] + "_Options");
                                    if (tempEL){
                                        tempEL.addClassName("display_none");
                                    }
                                    tempEL = false;
                                }
                            }
                          } catch(e) {
                            /*shipToMethodActiveMatrix[actionEL.name] = actionEL.id;
                            tempEL = $(shipToMethodActiveMatrix[actionEL.name] + "_Options");
                            if (tempEL){
                                tempEL.addClassName("display_none");
                            }*/
                        }
                        shipToMethodActiveMatrix[actionEL.name] = actionEL.id;
                        tempEL = $(shipToMethodActiveMatrix[actionEL.name] + "_Options");
                        if (tempEL){
                            tempEL.removeClassName("display_none");
                            inputCollectionArray = tempEL.getElementsByTagName("input");
                            if (inputCollectionArray.length > 0) {
                                preSelectInput = 0; // Preselect the first shipping option (when sorted, it is the cheapest method)
                                inputCollectionArray[preSelectInput].checked = "checked";
                            }
                        }
                } else if ( actionEL.className.indexOf("editGiftMessaging") >= 0 ) { // Enhance anchor based on a specific id
                    Event.stop(e);
                    patternMask = "#";
                    maskCount = (actionEL.href.length - actionEL.href.replace(RegExp(patternMask, "gi"), "").length) / patternMask.length;
                    patternMaskID = actionEL.href.substring((actionEL.href.indexOf(patternMask) + 1), actionEL.href.length);
                    if ( patternMaskID.length > 1 ) {
                        actionEL.blur();
                        giftMessageInputEL = $(patternMaskID);
                        if (giftMessageInputEL) {
                            giftMessageInputEL.toggleClassName("notEditing");
                            giftMessageInputEL.readOnly = (giftMessageInputEL.className.match("notEditing"))?true:false;
                            giftMessageInputEL.focus();
                        }
                    }
                } else if ( (actionEL.className.indexOf("closePopUp") >= 0 )||(actionEL.className.indexOf("closeModal") >= 0 ) ) {
                    innerModal();
                    Event.stop(e);
                    preventDoubleSubmit = false;
                } else if (actionEL.className.indexOf("innerModal") >= 0 ) {
                    patternMask = "#";
                    maskCount = (actionEL.href.length - actionEL.href.replace(RegExp(patternMask, "gi"), "").length) / patternMask.length;
                    patternMaskID = actionEL.href.substring((actionEL.href.indexOf(patternMask) + 1), actionEL.href.lastIndexOf(patternMask));
                    if ( (maskCount > 1)&&(patternMaskID.length > 1) ) {
                        actionEL.blur();
                      } else {
                        patternMaskID = ((actionEL.id != "")?actionEL.id:((actionEL.name != "")?actionEL.name:""));
                    }
                    targetInnerModalContainerEL = $(patternMaskID + '_detail');
                    if (targetInnerModalContainerEL) {
                        Event.stop(e);
                        actionEL.blur();
                        if (patternMaskID == "editAddressContainerID") {
                            $$("#" + targetInnerModalContainerEL.id + " .color_site_red").each(function(erroredEL){ // if the popup has errors, grab all of the entities affected
                                if (erroredEL.tagName.toLowerCase() == "label") {   // then check element is a label
                                    erroredEL.removeClassName("color_site_red");        // if it is remove the error indicating class name
                                  } else {                                          // otherwise
                                    erroredEL.remove();                                 // assume it is the error messsage div and remove it completely
                                }
                            });
                            arrayOfDataKeys = ["City", "Company", "Country", "DayPhone", "Email", "FirstName", "LastName", "State", "StreetAddress1", "StreetAddress2", "ZipCode", "", "", "", "", "", "", "", "", "", "", ""];//.toArray();
                            popUpFormPrefix = "ship";
                            prePopulatedDataObj = actionEL.href.toQueryParams();
                            editingAddress = (prePopulatedDataObj["popUpId"] != "addAddressContainerID");

                            modalTitleEL = $("editAddressContainerID_indicator");
                            if (modalTitleEL) {
                                modalTitleEL.innerHTML = (editingAddress)?("Editing \" " + prePopulatedDataObj["shipAddressName"] + "\" "):("Add a ");
                            }

                            addressNameEL = $("shipAddressName");
                            if (addressNameEL) {
                                //addressNameEL.readOnly = editingAddress;
                                addressNameEL.style.borderWidth = ((editingAddress)?"0":"1") + "px";
                                addressNameEL.value = (editingAddress)?prePopulatedDataObj["shipAddressName"]:"";
                                if (editingAddress) {
                                    if (prePopulatedDataObj["shipAddressName"].toLowerCase().replace(/^\s+|\s+$/g,"") == 'my billing address') {
                                        shipEmailEL = $("shipEmail");
                                        shipEmailContainerEL = $("shipEmailContainer");
                                        if (shipEmailEL && shipEmailContainerEL) {
                                            shipEmailContainerEL.removeClassName("display_none");
                                        } else {
                                            shipEmailContainerEL.addClassName("display_none");
                                        }
                                      } else {
                                            shipEmailContainerEL = $("shipEmailContainer");
                                            if (shipEmailContainerEL) {
                                                shipEmailContainerEL.addClassName("display_none");
                                            }
                                    }
                                }
                            }

                            for (x = 0; x < arrayOfDataKeys.toArray().length; x++) {
                                if ( typeof(arrayOfDataKeys[x]) != "function" ) {
                                    tempEL = $(popUpFormPrefix + arrayOfDataKeys[x]);
                                    if (tempEL) {
                                        try {
                                            switch( tempEL.type.toLowerCase() ) {
                                                case "select-one":
                                                case "select-multiple":
                                                    for (i = 0; i < tempEL.options.length; i++) {
                                                        tempEL.options[i].selected = (editingAddress)?( tempEL.options[i].value.toLowerCase() == prePopulatedDataObj[popUpFormPrefix + arrayOfDataKeys[x]].toLowerCase() ):0;
                                                    }
                                                    break;
                                                case "radio":
                                                case "checkbox":
                                                    tempEL.checked = (editingAddress)?(tempEL.value == prePopulatedDataObj[popUpFormPrefix + arrayOfDataKeys[x]]):false;
                                                    break;
                                                default:
                                                    tempEL.value = cleanOutput((editingAddress)?prePopulatedDataObj[popUpFormPrefix + arrayOfDataKeys[x]]:"");
                                            }
                                          } catch(e) {
                                            // catch any stumbles, and humbly keep it moving...
                                        }
                                    }
                                    tempEL = null;
                                }
                            }
                        }
                        innerModal({	'url': "",
                                        'className': "",
                                        'target': "",
                                        'toolTipCoOrds': {'x': e.clientX, 'y': e.clientY},
                                        'container': targetInnerModalContainerEL.id,
                                        'content': ""		//"<div id=\"popUpContent\" style=\"position: absolute; width: 200px; line-height: 200px; vertical-align: middle; border: 2px solid orange; background-color: yellow; \" >Say WORD!</div>"
                            });
                        advancedToolTip_containerEL = $('advancedToolTip_container');
                        if (advancedToolTip_containerEL) {
                            advancedToolTip.inittip(this, 'you can put any title info here', actualObj.id, 'left', 550, 'x');
                            advancedToolTip_containerEL.style.display='block';
                        } else {
                            targetInnerModalContainerEL.removeClassName("display_none");
                        }
                    }
                 } else if ( actionEL.className.indexOf("tabOption") >= 0 ) {
                    Event.stop(e);
                    switchTabs.doSwitch(actionEL.parentNode.id, 'tabsID', 'tabContents_Container_id');
                 } else if (actionEL.className.indexOf("externalPopUp") >= 0 ) {
                    Event.stop(e);
                    myRef = window.open(actionEL.href, 'BrookstoneStoreLocator', 'width=550, height=400, toolbar=0, resizable=0, scrollbars=1');
                }else {
                    //if input[image|submit]:click
                    if (actionEL.tagName.toLowerCase() == "input") {
//                        $("debugArea").insert({bottom:"t-1) actionEL is: "+actionEL.tagName+" | "+actionEL.className+"<br/>"});

                        if(!submitEventBound){
                            if(actionEL.className.indexOf("addToCartBtnIeFix") >= 0){

                                formEL2=$("addToCart");
                                if(formEL2){

                                    var allSkuSelected = true;
                                    $$(".skuOptSelect").each(function(skuOpt){
                                        if(skuOpt.selectedIndex==0){
                                            allSkuSelected = false;
                                        }
                                    });
                                    skuOptErrorSectionObj = $("skuOptErrorSection");
                                    if(!allSkuSelected){
                                        if (skuOptErrorSectionObj) {
                                            skuOptErrorSectionObj.removeClassName("display_none");
                                        }
                                        preventDoubleSubmit=false;
                                        if (!fakedEvent) {
                                            Event.stop(e);
                                        }
                                        return false;
                                    }else{
                                        if (skuOptErrorSectionObj) {
                                            skuOptErrorSectionObj.addClassName("display_none");
                                            lightBoxV2.changeLightBoxV2ZIndex(110);
                                            domReady_lock_popup = true;
                                        }
                                        if (!fakedEvent) {
                                            Event.stop(e);
                                        }

                                        // Validate the quantity field since we don't by checking for specific epp element, and degrading to the generic pattern
                                        var prodOrderOtyObj = $("prodOrderOty");

                                        if (prodOrderOtyObj) {
                                            var qtyErrorSectionObj = $("qtyErrorSection");
                                            if (!numericCheck.isNumeric(prodOrderOtyObj.value) && qtyErrorSectionObj) {
                                                qtyErrorSectionObj.innerHTML = "Please enter a valid quantity for the item (valid integer, greater than zero).";
                                                Event.stop(e);
                                                preventDoubleSubmit = false;
                                                return preventDoubleSubmit ;
                                            } else if (qtyErrorSectionObj) {
                                                qtyErrorSectionObj.innerHTML = "";
                                            }
                                        }

                                        ajaxForm(formEL2);
                                    }

                                }

                            }
                            
                        }

                    } else if (actionEL.parentNode.tagName.toLowerCase() == "a") {
                 //alert(e.type + "'d " + actionEL.tagName + " -> " + actionEL.className);
                        if ( actionEL.parentNode.href.charAt(actionEL.parentNode.href.length - 1) == "#") { // Once we have an appropriate ADA compliant solution for the popUps, this code will need to change
                            Event.stop(e);
                        }
                    }
                }
            }
            break;
        case "submit":  // form:submit
            if (!preventDoubleSubmit) {
                preventDoubleSubmit = true;
                actionEL.blur();
                switch( actionEL.name ) {
                    case "billShip":
                            billingCheckEL = $("ShipSameAsBill");
                            if (billingCheckEL) {
                                if (billingCheckEL.checked) {
                                    synchBillingAndShipping(billingCheckEL.checked);
                                }
                            }
                        break;
                    case "addToCart":
                    case "addToCartAjax":           // changed to accommodate the shopping cart quick sells
                        var allSkuSelected = true;
                        $$(".skuOptSelect").each(function(skuOpt){
                            if(skuOpt.selectedIndex==0){
                                allSkuSelected = false;
                            }
                        });
                        skuOptErrorSectionObj = $("skuOptErrorSection");
                        if(!allSkuSelected){
                            if (skuOptErrorSectionObj) {
                                skuOptErrorSectionObj.removeClassName("display_none");
                            }
                            preventDoubleSubmit=false;
                            if (!fakedEvent) {
                                Event.stop(e);
                            }
                            return false;
                        } else {
                            if (skuOptErrorSectionObj) {
                                skuOptErrorSectionObj.addClassName("display_none");
                                lightBoxV2.changeLightBoxV2ZIndex(110);
                                domReady_lock_popup = true;
                            }
                            if (!fakedEvent) {
                                Event.stop(e);
                            }

                            // Validate the quantity field since we don't by checking for specific epp element, and degrading to the generic pattern
                            var prodOrderOtyObj = $("prodOrderOty") || $$("#" + actionEL.id + " input.text")[0];
                            if (prodOrderOtyObj) {
                                var qtyErrorSectionObj = $("qtyErrorSection") || $$("#" + actionEL.id + " span.qty")[0];
                                if (!numericCheck.isNumeric(prodOrderOtyObj.value) && qtyErrorSectionObj) {
                                    qtyErrorSectionObj.innerHTML = "Please enter a valid quantity for the item (valid integer, greater than zero).";
                                    Event.stop(e);
                                    preventDoubleSubmit = false;
                                    return preventDoubleSubmit ;
                                } else if (qtyErrorSectionObj) {
                                    qtyErrorSectionObj.innerHTML = "";
                                }
                            }
                            //actionEL.blur();
//                            $("debugArea").insert({bottom:"actionEL.name: "+actionEL.name+"<br/>"});
                            ajaxForm(actionEL);
                        }
                        break;
                }
               } else {
                Event.stop(e);
            }
            break;
    }
}

function ajaxForm(actionEL) {
    //alert("the party is starting in ajaxForm with " + actionEL.name + " as our guest of honor!");
    ajaxInfoSectionEL = $("ajaxInfoSection");
    var personalizationGeneralErrorSection = $("errorMsgPersonalization");
    if(ajaxInfoSectionEL){
        ajaxInfoSectionEL.removeClassName("display_none");
    } else {
        needleEL = getElementWithFocus();
        if (needleEL) {
            needleEL.blur();
        }
        needleEL = false;
        innerModal({	'url': "",
                        'className': "",
                        'target': "",
                        'container': "",
                        'toolTipCoOrds': {'x': 0, 'y': 0},
                        'content': ""
            });
        Effect.ScrollTo( 'main_table' );        //'globalHeader_C3R1' );
        // [for whatever reason, prototype doesn't fix IE's wonky element JS object so natively extending an object won't work - actionEL.request({ ]
        $("dynCart").style.display = "block";
        $("miniShoppingCartLoader").style.display = "block";
    }
    var dataObj;
    if (window.location.toString().substring(0, 5) == "http:") {		// Since AJAX transactions need to be sent using the same protocol as the page was loaded
		actionEL.action = actionEL.action.replace("https", "http");	// remove the secure link for AJAX calls if we are loaded insecurely
	}
	formParams = actionEL.serialize();
    ajaxRequestInProgress = true;
    new Ajax.Request(actionEL.action, {
		method: actionEL.method,
		parameters: formParams,
		onComplete: function(initialTransaction){
			var usableResponse = "Sorry but the AJAX transaction didn't complete.";
            var newProductShortName = "";
            totalCartQuantity = -1;
            if (parseInt(initialTransaction.status) == 200) {
                    itemsShowing = totalCartQuantity = 0;
	                newProductShortName = "";
                    if (initialTransaction.responseJSON) {
	                    dataObj = initialTransaction.responseJSON;
                        if(!dataObj.json_hasError || dataObj.json_hasError==null){
                            if(personalizationGeneralErrorSection){
                                personalizationGeneralErrorSection.addClassName("display_none");
                            }
                            if(ajaxInfoSectionEL){
                                ajaxInfoSectionEL.addClassName("display_none");
                            }
                            domReady_lock_popup = false;
                            lightBoxV2.changeLightBoxV2ZIndex(90);
                            domReadyEventFunctionsCollections.doPersonalizationDisappear();
                            if(ajaxInfoSectionEL){
                                innerModal({	'url': "",
                                                'className': "",
                                                'target': "",
                                                'container': "",
                                                'toolTipCoOrds': {'x': 0, 'y': 0},
                                                'content': ""
                                    });
                            }
                            Effect.ScrollTo( 'main_table' );    //'globalHeader_C3R1' );
                            // [for whatever reason, prototype doesn't fix IE's wonky element JS object so natively extending an object won't work - actionEL.request({ ]
                            $("dynCart").style.display = "block";
                            $("miniShoppingCartLoader").style.display = "block";
                        }else{
                            if(personalizationGeneralErrorSection){
                                personalizationGeneralErrorSection.removeClassName("display_none");
                            }

                            if(ajaxInfoSectionEL) {
                                ajaxInfoSectionEL.addClassName("display_none");
                            }
                            lightBoxV2.changeLightBoxV2ZIndex(90);
                            domReady_lock_popup = false;
                            $("productCustomization").select(".title").each(function(obj){
                                for(var i=0; i<dataObj.json_errorFieldNameList.length; i++){
                                    if(obj.id.indexOf(dataObj.json_errorFieldNameList[i])>-1){
                                        obj.addClassName('color_site_3');
                                        errorSectionId = obj.id.replace(/label/i, "errorSection");
                                        $(errorSectionId).innerHTML = dataObj.json_errorMessageList[i];
                                        break;
                                    }else{
                                        obj.removeClassName('color_site_3');
                                        errorSectionId = obj.id.replace(/label/i, "errorSection");
                                        $(errorSectionId).innerHTML = "";
                                    }
                                }
                            });
                            preventDoubleSubmit = false;
                            return preventDoubleSubmit; // make sure that since the response contains errors, we don't finish the rest of the script
                        }
                    switch( dataObj['status'].toLowerCase() ) {
                        case "results":
                                var responseEL;
                                var cartObj;
                                cartObj = dataObj['cart'].lineList;
                                var itemCount;
                                itemCount = itemsShowing = 0;
                                responseEL = $('shoppingCartTBODY');
                                if (responseEL) {
                                    if(responseEL.hasChildNodes()) {
                                        while(responseEL.childNodes.length >= 1 ) {
                                            responseEL.removeChild(responseEL.firstChild);
                                        }
                                    }
                                  for (listItem in cartObj) {
                                        switch( typeof(cartObj[listItem]) ) {
                                            case "object":
                                                try {
                                                    if (itemCount < 10) {
                                                        lineListItemObj = cartObj[listItem];
                                                            trEL = document.createElement('tr');
                                                                    trEL.setAttribute('id', "miniCartLineItem" + itemsShowing);
                                                                    trEL.setAttribute(cssDomAttribute, "data_row_" + ((itemCount % 2)?"odd":"even"));
                                                                    tdEL = document.createElement('td');
                                                                        tdEL.setAttribute(cssDomAttribute, "inline_product");
                                                                            imgEL = document.createElement('img');
                                                                                imgEL.setAttribute('src', lineListItemObj["inlineCartImage"]);
                                                                                imgEL.setAttribute('alt', lineListItemObj["inlineCartAltImage"]);
                                                                                imgEL.setAttribute('width', "86");
                                                                                imgEL.setAttribute('height', "65");
                                                                        tdEL.appendChild( imgEL );
                                                                            divEL = document.createElement('div');
                                                                                divEL.setAttribute(cssDomAttribute, "inline_productDetail");
                                                                                bEL = document.createElement('b');
                                                                                    bEL.appendChild( document.createTextNode( cleanOutput(lineListItemObj["prettyName"]) ) );
                                                                            divEL.appendChild( bEL );
                                                                            bEL = null;
                                                                            try {
                                                                                if (lineListItemObj['upSells'].length > 0) {
                                                                                    upSellDataObj = lineListItemObj['upSells'];
                                                                                    ulEL = document.createElement('ul');
                                                                                        ulEL.setAttribute(cssDomAttribute, "upSells");
                                                                                    for (upSellIndice = 0; upSellIndice < upSellDataObj.length; upSellIndice++ ) {
                                                                                        liEL = document.createElement('li');
                                                                                            if (upSellDataObj[upSellIndice]['personalizationAttributeList'].length > 0) {
                                                                                                personalizationObj = upSellDataObj[upSellIndice]['personalizationAttributeList'];
                                                                                                for (personalizationIndice = 0; personalizationIndice < personalizationObj.length; personalizationIndice++) {
                                                                                                    liEL.appendChild( document.createTextNode(personalizationObj[personalizationIndice]) );
                                                                                                    liEL.appendChild( document.createElement('br') );
                                                                                                }
                                                                                            } else {
                                                                                                liEL.appendChild( document.createTextNode(upSellDataObj[upSellIndice].prettyName + ((upSellDataObj[upSellIndice].price != "")?(" - " + upSellDataObj[upSellIndice].price):"") /*upSellDataObj[upSellIndice]*/) );
                                                                                            }
                                                                                        ulEL.appendChild(liEL);
                                                                                        liEL = null;
                                                                                    }
                                                                                    divEL.appendChild (ulEL);
                                                                                    ulEL=null;
                                                                                }
                                                                              } catch(oopSies){
                                                                                // catch your fall with a summersault and keep it moving!
                                                                            }
                                                                        tdEL.appendChild( divEL );
                                                                        divEL = null;
                                                                trEL.appendChild(tdEL);
                                                                    tdEL = document.createElement('td');
                                                                        tdEL.setAttribute(cssDomAttribute, "inline_price");
                                                                            divEL = document.createElement('div');
                                                                                divEL.setAttribute(cssDomAttribute, "clear_both");
                                                                                priceArray = ["originalRetailPrice", "price"];
                                                                                for (price in priceArray) {
                                                                                    if ((typeof(priceArray[price]) == "string") && (lineListItemObj[priceArray[price]] != "") ) {
                                                                                        pEL = document.createElement('p');
                                                                                            if (priceArray[price] == "price") { // now
                                                                                                pEL.setAttribute(cssDomAttribute, ("price" + ((lineListItemObj[ priceArray[price - 1] ]!="")?"Current":"")) );
                                                                                                pEL.appendChild( document.createTextNode( ((lineListItemObj[ priceArray[price - 1] ]!="")?"Now":" ") + " " + lineListItemObj[ priceArray[price] ] )  );
                                                                                             } else {                           // was
                                                                                                pEL.appendChild( document.createTextNode("Was ") );
                                                                                                spanEL = document.createElement('span');
                                                                                                    spanEL.setAttribute(cssDomAttribute, "pricePrevious");
                                                                                                    spanEL.appendChild( document.createTextNode(lineListItemObj[priceArray[price]]) );
                                                                                                pEL.appendChild( spanEL );
                                                                                            }
                                                                                        divEL.appendChild(pEL);
                                                                                    }
                                                                                }
                                                                        tdEL.appendChild( divEL );
                                                                trEL.appendChild(tdEL);
                                                                    tdEL = document.createElement('td');
                                                                        tdEL.setAttribute(cssDomAttribute, "inline_qty");
                                                                        tdEL.appendChild( document.createTextNode(lineListItemObj['quantity']) );
                                                                trEL.appendChild(tdEL);
                                                                    tdEL = document.createElement('td');
                                                                        tdEL.setAttribute(cssDomAttribute, "inline_subtotal");
                                                                        tdEL.appendChild( document.createTextNode(lineListItemObj['subtotal']) );
                                                        trEL.appendChild(tdEL);
                                                        responseEL.appendChild( trEL );
                                                        trEL = tdEL = imgEL = divEL = pEL = null;
                                                       itemsShowing++;
                                                    }
                                                } catch(funk){
                                                    //alert("numba 1 chief rocka!" + funk.message + "\n" + funk.lineNumber);
                                            }
                                            itemCount++;
                                        }
                                    }
                                    if (itemCount > 9) {
                                        displayText = ("Displaying " + itemsShowing + " of the " + itemCount + " items in your cart.");
                                        miniCartDisplayCountEL = $('miniCartDisplayCount');
                                        if (miniCartDisplayCountEL) {
                                            miniCartDisplayCountEL.innerHTML = displayText;
                                        }
                                        miniCartDisplayCountEL = null;
                                    }
                                }
                                try {
                                responseEL = cartObj = null;
                                newProductShortName = dataObj['cart'].currentProductShortName;
                                totalCartQuantity = dataObj['cart'].totalQty;
                                $("miniShoppingCartAddedQuantity").innerHTML = initialTransaction.responseJSON['addedQuantity'];
                                $("miniShoppingCartAddedProductName").innerHTML = newProductShortName;
                                $("inlineCartTotalValue").innerHTML = initialTransaction.responseJSON["cart"].subtotal;
                                var omnitureObj = dataObj['omniture'];
                                var omniture = s_gi(OMNITURE_VALUE);
                                omniture.linkTrackVars = 'products,events';
                                omniture.linkTrackEvents = 'scAdd,scOpen';
                                for (var key in omnitureObj) {
                                    if (omnitureObj.hasOwnProperty(key)) {
                                        omniture[key] = omnitureObj[key];
                                    }
                                }
                                omniture.tl(true,'o','add to cart');

                                // Will change once JSON response is available
                                cartItems = 0;
                                cartListContainerObj = $('cartList_container');
                                if (cartListContainerObj) {
                                    $$('#cartList_container td.inline_qty').each(function(chosenElement) {
                                        if (chosenElement) {
                                                cartItems += parseInt(chosenElement.innerHTML);
                                            }
                                    });
                                    if (totalCartQuantity != "") {
                                        $("inlineCartTotalQty").innerHTML = totalCartQuantity;
                                    }
                                }
                                if (cartItems >= 0) {
                                    $("totalInShoppingCartID").innerHTML = (" " + totalCartQuantity + " Item" + (((totalCartQuantity==0)||(totalCartQuantity>1))?"s":"") );
                                }
                                } catch(asd){
                                    //alert("numba 1 chief rocka!" + asd.message + "\n" + asd.lineNumber);
                                }
                            break;
                        case "outofstock":
                            $$('#addToCart input, #addToCart select').each(function(chosenElement) {
                                if (chosenElement) {
                                        chosenElement.disabled = "disabled";
                                    }
                            });
                            addToCartButtonEL = $('addToCartButton');
                            if (addToCartButtonEL) {
                                addToCartButtonEL.src="/imageservlet?webImageName=disabledAddToCart.gif&languageId=EN";
                            }
                        case "inputerror":
                        case "quantityerror":
                        default:
                                responseEL = $('inline_cart');
                                if (responseEL) {
                                    responseEL.innerHTML = "";
                                    pEL = document.createElement('p');
                                        pEL.appendChild( document.createTextNode( cleanOutput(dataObj['message']) ) );
                                    responseEL.appendChild(pEL);
                                }
                    }
			   } else {
                    if (initialTransaction.responseText == "error in ajax action") {
                        $('inline_cart').innerHTML = "We were unable to complete your request. (Error: \"" + initialTransaction.responseText + "\", " + initialTransaction.statusText + ", " + initialTransaction.status + ")";
                     } else {
                        new Ajax.Request('/inline_cart.jsp',
                            {
                                method:'post',  //changed to "post" in hope to avoid squid issue
                                onSuccess: function(transport) {
                                                inlineCartValue = transport.responseText.replace('Product Name', newProductShortName);
                                                $('inline_cart').innerHTML = cleanOutput(inlineCartValue) || "no response text";
                                            },
                                onFailure: function(){ inlineCartValue = 'Something went wrong...'; }
                            }
                        );
                    }
            }
		}
            $('miniShoppingCartLoader').style.display = "none";
            if (itemsShowing > 3) {
                $('miniShoppingCartScroller').style.height = "280px";
                $('miniShoppingCartScroller').style.overflow = "auto";
            }
            Effect.toggle('inline_cart', 'blind', {duration: 0.4});
            ajaxRequestInProgress = false;
        },
        onFailure: function(errorInstance){
            $('inline_cart').innerHTML = "We were unable to complete your request due to a request error.";
            $('miniShoppingCartLoader').style.display = "none";
            Effect.toggle('inline_cart', 'blind', {duration: 0.4});
            ajaxRequestInProgress = false;
        }
   });
    preventDoubleSubmit = false;
}
var viewport;
try {
viewport = {'width': ((typeof window.innerWidth != 'undefined')?window.innerWidth:((typeof document.documentElement != 'undefined' && typeof document.documentElement.clientWidth != 'undefined' && document.documentElement.clientWidth != 0)?document.documentElement.clientWidth:document.getElementsByTagName('body')[0].clientWidth)), 'height': ((typeof window.innerHeight != 'undefined')?window.innerHeight:((typeof document.documentElement != 'undefined' && typeof document.documentElement.clientHeight != 'undefined' && document.documentElement.clientHeight != 0)?document.documentElement.clientHeight:document.getElementsByTagName('body')[0].clientHeight)) /*, 'scrollTop': ((document.body.scrollTop == 0)?((window.pageYOffset)?window.pageYOffset:((document.body.parentElement)?document.body.parentElement.scrollTop:0)):document.body.scrollTop)*/ };
} catch(zut) {
    // what say you sitedesigner?
}
function reCalculateViewport() {
    containerEL = $("main_table");      //document.getElementsByTagName('body')[0]; // because document.body was triggering an error
    viewport.height = (viewport.height == 0)?$("main_table").offsetHeight:viewport.height;
    viewport.width = (viewport.width == 0)?(document.viewport.getWidth() + ((document.selection)?0:17) ):viewport.width;
	viewport.scrollTop = (containerEL.scrollTop == 0)?((window.pageYOffset)?window.pageYOffset:((containerEL.parentElement)?containerEL.parentElement.scrollTop:0)):containerEL.scrollTop;
    if (activeModalDetailID != "") {
        var activeModalEL = $(activeModalDetailID);
        if (activeModalEL) {
			activeModalEL.style.top = viewport.scrollTop + ( viewport.height/8 ) + "px";
            activeModalEL.style.left = ( (viewport.width/2) - 250 ) + "px";
        }
        activeModalEL = false;
    }
    var tempPopUpEL = $('popUp');
    if (tempPopUpEL) {
        tempPopUpEL.style.width = (viewport.width - ((document.selection)?0:17) ) + "px";   //viewport.width + "px";
        tempPopUpEL.style.height = winPageSize.getPageSize().get("pageHeight") + "px";      // viewport.height + "px";
        tempPopUpEL = false;
    }
}

function innerModal(objective) {
	// objective = { 'url': "url", 'className': "url", 'target': "target" 'content': "html content?"}
    popUpEL = $('popUp');
	containerEL = document.body;
	justCreatedInIE = false;
	if ( !popUpEL ) {
		popUpEL = document.createElement("div");
		popUpEL.id = "popUp";
		popUpEL.style.position = "absolute";
		popUpEL.style.top = "0";
		popUpEL.style.left = "0";
		popUpEL.style.zIndex = "50";
		popUpEL.style.backgroundColor = "#000";
		popUpEL.style.textAlign = "center";
		popUpEL.style.width = (viewport.width - ((document.selection)?0:17) ) + "px";
		popUpEL.style.height = winPageSize.getPageSize().get("pageHeight") + "px";
		popUpEL.onclick = function() { if (!ajaxRequestInProgress) {
                                            affirmativeAnchorEL = $("affirmativeShoppingCartLink");
                                            if (refreshShoppingCart && affirmativeAnchorEL) {
                                                window.location = affirmativeAnchorEL.href;
                                              } else {
                                                innerModal();
                                            }
                                        }
                                };
		document.body.appendChild(popUpEL);
		popUpEL = $('popUp');
		if (document.selection) {
		        new Effect.Opacity('popUp', { from: 0, to: 0.4, duration: 0, beforeStart: function() { 	$('popUp').style.display = "block"; }  });
		} else {
		    popUpEL.setOpacity(0.4);
        }
    }

	if (document.selection) {						// IE select box z-index fix
        var tagTotal = document.getElementsByTagName("select");
        for (var i=0; i<tagTotal.length; i++) {
            tagTotal[i].style.visibility  = ((objective)?"hidden":"");
        }
        if (objective) {
            try {
                $$("#" + objective.container + " select").each(function(unHideThisSelectEL){
                    unHideThisSelectEL.style.visibility  = "";
                });
            } catch(incidentReport) {
                // objective.container probably doesn't exist, but we pretend that it doesn't matter and keep it moving
            }
        }
    }

	if (document.selection) {
		containerEL.style.overflow = ((objective)?"hidden":"");
	   } else {
		containerEL.style.overflowY = ((objective)?"hidden":"scroll");
	}

	toolTipObj = $("advancedToolTip_container");
    if (objective) {					// if we have an objective, open the overlay
        reCalculateViewport();
		if (objective.content != "") {
			popUpEL.innerHTML = objective.content;		// Yeah it's dirty, but I am just trying to make a point
		}

		if (objective.container != "") {
			activeModalDetailID = objective.container;
            toolTipObj = $(activeModalDetailID);
        }

        popUpEL.style.display = "block";
		//popUpEL.setOpacity(0.6);
		if (toolTipObj) {
			toolTipObj.style.top = viewport.scrollTop + ( viewport.height/8 ) + "px";
            toolTipObj.style.left = ( (viewport.width/2) - 250 ) + "px";
            toolTipObj.removeClassName("display_none");
            var firstElement = Form.getElements(toolTipObj).find(function(element) {        // Find the first form element if it exists
                return element.type != 'hidden' && !element.disabled && ['input', 'select', 'textarea'].include(element.tagName.toLowerCase());
            });
            if(firstElement != null) {                                                          // and either select that element
                firstElement.activate();
             } else {                                                                           // or focus on the container
                toolTipObj.focus();
            }
        }
       } else {						// otherwise close the popup
            if (!ajaxRequestInProgress) {
                popUpEL.style.display = "none";
                if (toolTipObj) {
                    if (toolTipObj.style.display != "none") {
                        toolTipObj.style.display = "none";
                    }
                }
                if (activeModalDetailID != "") {
                    containerIDEL = $(activeModalDetailID);
                    if (containerIDEL) {
                        if (containerIDEL.style.display != "none") {
                            containerIDEL.addClassName("display_none");
                        }
                    }
                    activeModalDetailID = "";
                }
                dynCartObj = $('dynCart');
                if (dynCartObj) {
                    if (dynCartObj.style.display == "block") {
                        if (dynCartObj) {
                            if (dynCartObj.style.display != "none") {
                                    Effect.toggle('dynCart', 'blind', {duration: 0.4 });
                                }
                            }

                        inlineCartObj = $('miniShoppingCartScroller');
                        if (inlineCartObj) {
                            if (inlineCartObj.style.display != "none") {
                                //inlineCartObj.style.display = "none";
                                    Effect.toggle('inline_cart', 'blind', {duration: 0.4 });
                                    $('miniShoppingCartScroller').style.height = "auto";
                                    $('miniShoppingCartScroller').style.overflow = "";
                                }
                        }
                    }
                }
            }
           preventDoubleSubmit = false;
        qtyErrorSectionObj = $("qtyErrorSection");
        if (qtyErrorSectionObj) {
            qtyErrorSectionObj.innerHTML = "";
        }
	}
}

function getElementWithFocus() {
    var hf;     // initialize function global reference to document, and find the element that currently h(as)f(ocus)
    // IE uses activeElement
    if ( document.activeElement ) hf = document.activeElement;
    // Firefox uses focusNode
    else hf = document.focusNode;
    return hf;
}
window.onresize = function() {
	reCalculateViewport();
}

function synchBillingAndShipping(synchValues) {
    //arrayOfDataKeys = ["City", "Company", "Country", "DayPhone", "Email", "FirstName", "LastName", "State", "StreetAddress1", "StreetAddress2", "ZipCode", "", "", "", "", "", "", "", "", "", "", ""];
    sourcePrefix = "bill";
    targetPrefix = "ship";
    sourceFormElementsArray = $$("#billingAddress_container input, #billingAddress_container select, #billingAddress_container textarea");//.length;
/*  filter.stateFilter('billCountry', 'billState', [['', '', 'Please select',  'selected'],['AB', 'CA', 'Alberta', ''],['BC', 'CA', 'British Columbia', ''],['MB', 'CA', 'Manitoba', ''],['NB', 'CA', 'New Brunswick', ''],['NL', 'CA', 'Newfoundland', ''],['NS', 'CA', 'Nova Scotia', ''],['NU', 'CA', 'Nunavut', ''],['ON', 'CA', 'Ontario', ''],['PE', 'CA', 'Prince Edward Island', ''],['QC', 'CA', 'Quebec', ''],['SK', 'CA', 'Saskatchewan', ''],['NT', 'CA', 'Northwest Territories', ''],['YT', 'CA', 'Yukon Territory', ''],['AA', 'US', 'Armed Forces Americas', ''],['AE', 'US', 'Armed Forces Europe, Middle East, & Canada', ''],['AK', 'US', 'Alaska', ''],['AL', 'US', 'Alabama', ''],['AP', 'US', 'Armed Forces Pacific', ''],['AR', 'US', 'Arkansas', ''],['AS', 'US', 'American Samoa', ''],['AZ', 'US', 'Arizona', ''],['CA', 'US', 'California', ''],['CO', 'US', 'Colorado', ''],['CT', 'US', 'Connecticut', ''],['DC', 'US', 'District of Columbia', ''],['DE', 'US', 'Delaware', ''],['FL', 'US', 'Florida', ''],['FM', 'US', 'Federated States of Micronesia', ''],['GA', 'US', 'Georgia', ''],['GU', 'US', 'Guam', ''],['HI', 'US', 'Hawaii', ''],['IA', 'US', 'Iowa', ''],['ID', 'US', 'Idaho', ''],['IL', 'US', 'Illinois', ''],['IN', 'US', 'Indiana', ''],['KS', 'US', 'Kansas', ''],['KY', 'US', 'Kentucky', ''],['LA', 'US', 'Louisiana', ''],['MA', 'US', 'Massachusetts', ''],['MD', 'US', 'Maryland', ''],['ME', 'US', 'Maine', ''],['MH', 'US', 'Marshall Islands', ''],['MI', 'US', 'Michigan', ''],['MN', 'US', 'Minnesota', ''],['MO', 'US', 'Missouri', ''],['MP', 'US', 'Northern Mariana Islands', ''],['MS', 'US', 'Mississippi', ''],['MT', 'US', 'Montana', ''],['NC', 'US', 'North Carolina', ''],['ND', 'US', 'North Dakota', ''],['NE', 'US', 'Nebraska', ''],['NH', 'US', 'New Hampshire', ''],['NJ', 'US', 'New Jersey', ''],['NM', 'US', 'New Mexico', ''],['NV', 'US', 'Nevada', ''],['NY', 'US', 'New York', ''],['OH', 'US', 'Ohio', ''],['OK', 'US', 'Oklahoma', ''],['OR', 'US', 'Oregon', ''],['PA', 'US', 'Pennsylvania', ''],['PR', 'US', 'Puerto Rico', ''],['PW', 'US', 'Palau', ''],['RI', 'US', 'Rhode Island', ''],['SC', 'US', 'South Carolina', ''],['SD', 'US', 'South Dakota', ''],['TN', 'US', 'Tennessee', ''],['TX', 'US', 'Texas', ''],['UT', 'US', 'Utah', ''],['VA', 'US', 'Virginia', ''],['VI', 'US', 'Virgin Islands', ''],['VT', 'US', 'Vermont', ''],['WA', 'US', 'Washington', ''],['WV', 'US', 'West Virginia', ''],['WI', 'US', 'Wisconsin', ''],['WY', 'US', 'Wyoming', '']])  */
    for (x = 0; x < sourceFormElementsArray.length; x++) {  // for all the source objects
        if ( typeof(sourceFormElementsArray[x]) != "function" ) {
            // find your targetPrefix sibling
            tempEL = $(sourceFormElementsArray[x].id.replace(sourcePrefix, targetPrefix));
            if (tempEL) {
                try {
                    switch( tempEL.type.toLowerCase() ) {
                        case "select-one":
                        case "select-multiple":
                            if (synchValues) {
                                if (sourceFormElementsArray[x].id == "billCountry") {
                                    tempEL.selectedIndex = sourceFormElementsArray[x].selectedIndex;
                                    if (countryRegionDataObj) {
                                        tempTargetString = sourceFormElementsArray[x].id.replace("bill", "ship");
                                        stateFilter($(tempTargetString), $(tempTargetString.replace("Country", "State")));
                                    }
                                    billStateEL = $('billState');
                                    shipStateEL = $('shipState');
                                    if (billStateEL && shipStateEL) {
                                        if (billStateEL.options.length == shipStateEL.options.length) {
                                            shipStateEL.selectedIndex = (synchValues)?billStateEL.selectedIndex:0;
                                        } else {
                                            newSelectedIndex = -1;
                                            do {
                                                newSelectedIndex++;
                                            } while ( (billStateEL.options[billStateEL.selectedIndex].value != shipStateEL.options[newSelectedIndex].value)&&(newSelectedIndex < shipStateEL.options.length) );
                                            shipStateEL.selectedIndex = (synchValues)?newSelectedIndex:0;
                                        }
                                    }
                                }
                             } else {
                                tempEL.selectedIndex = 0;
                                if (tempEL.id.indexOf("Country")>=0) {
                                    stateFilter(tempEL, $(tempEL.id.replace("Country", "State")));
                                }
                            }
                            break;
                        case "radio":
                        case "checkbox":
                            tempEL.checked = (synchValues)?sourceFormElementsArray[x].checked:false;
                            break;
                        default:
                            tempEL.value = (synchValues)?sourceFormElementsArray[x].value:"";//prePopulatedDataObj[popUpFormPrefix + arrayOfDataKeys[x]];
                    }
                  } catch(e) {
                    // catch any stumbles, and humbly keep it moving...(ToDo: make sure this is commented out when site goes live)
                    alert("The following error occurred:\n" + e.message + " on line " + e.line);
                }
            }
            tempEL = null;
        }
    }
    myBillingAddressIndex = 0;

    shipAddressNameEL = $('shipAddressName');
    if (shipAddressNameEL) {
        shipAddressNameEL.value = (synchValues)?useBillingAddressText:"";
    }

    shipAddressBookEL = $('shipaddressBook');
    if (shipAddressBookEL) {
        if (synchValues) {
            for (i = 0; i < shipAddressBookEL.options.length; i++) {
                if (shipAddressBookEL.options[i].text == useBillingAddressText) {
                    myBillingAddressIndex = i;
                }
            }
        }
        shipAddressBookEL.selectedIndex = myBillingAddressIndex;
    }
}

function addCommas(nStr) {
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	return x1 + x2;
}

function cleanOutput(dirtyText) { // Since prototype can't even do .unescapeHTML() consistently between browsers, I'll write a hideous hack myself
    try {
    dirtyText = dirtyText.unescapeHTML();
    }catch(monDieu){
        // quietly catch the error if IE doesn't like it
    }
    dirtyText = dirtyText.replace(/&#34;/g,'"'); // replace for double quotes
    dirtyText = dirtyText.replace(/&#39;/g,"'"); // replace for single quotes
    dirtyText = dirtyText.replace(/&#28;/g,"'"); // replace left parenthetical
    dirtyText = dirtyText.replace(/&#29;/g,"'"); // replace left parenthetical
    return dirtyText;
}

/************************************************************************************
* DOM READY MAIN BODY:
* 1. Listen dom:loaded -> do domReadyPageInit
* 2. Registers an event handler on a DOM element: main_table
* 3. Listen -> check class name hash table -> do related function (s)
*
*************************************************************************************/
// 1. listen dom ready using prototype

// 2. register a event handler to dom element
function domReadyPageInit(e){
    // Event Observe
    mainTableEL = $('main_table');
    if (mainTableEL) {
        // Stone, if possible, could you use one function for your onclick event handling
        Event.observe( mainTableEL, 'click', domReadyListener.eventListener1);
        Event.observe( mainTableEL, 'keypress', domReadyListener.eventListener1);
        Event.observe( mainTableEL, 'click', domReadyListener.eventListener2);

        Event.observe( mainTableEL, 'click', eventTrafficController.bindAsEventListener() );
        Event.observe( mainTableEL, 'submit', eventTrafficController.bindAsEventListener() );
    }
    // function need to run after dom loaded
    if (document.selection) {    // If we're being loaded in IE, compensate for it's wonky rendering engine by staggering the DomReady function calls
        badIE = setTimeout("domReadyFunctionsCollections.go()", 50);
     } else {
        domReadyFunctionsCollections.go();
    }
}

/************************************************************************************
* all functions need to be run after dom loaded put here:
* should be very careful to use it, since dom ready is fired far more early than it should be in ie7
* 'go' function is the entrance function, PLEASE DON'T MODIFY IT!!!
*************************************************************************************/
var domReadyFunctionsCollections = {
    // 3. go is the entrance function : don't modify it !!!
    go: function(){
        //alert("go!");
        if (document.selection) {
            clearTimeout(badIE);    // clear out our timeout
        }

/*
        //top header without shadow in index.jsp.vr : it's danger to use wrap for all the pages.
        if($("main_table").hasClassName("homePagePG")){
            $("main_table").setStyle({
                width:"1028px",
                background:"transparent url('/imageservlet?webImageName=background_gradiant_top.gif&languageId=EN') top center no-repeat",
                backgroundRepeat:"no-repeat"
            });
            $("main_table").wrap('div', { 'id':'noShadow', 'style':'width:1028px' });
        }else{
            $("main_table").setStyle({
                width:"1028px"
            });
        }
*/

        //change width to apply shadow for all pages. We can't apply background in body becasue 'marin:0 auto' doesn't do god job when we resize window.
/*
        if(window.name != "printWindow"){
            $("main_table").setStyle({
                width:"1028px"
            });
        }
*/

        if (idHashTable) {
            idHashTable.each(function(pair){
                var id=pair.key
                var o = $(id);
                if(o){
                    document.observe("o:loaded", idHashTable.get(pair.key)(o));
                }
            });
        }

        if(window.name == "printWindow"){
            $("main_table").setStyle({
//                margin:"1px 0 0 1px",
                float:"left"
            });
            document.body.style.background = "transparent url('/imageservlet?webImageName=trans.gif&languageId=EN') top center repeat-y";
            printVersion.hideMe();
        }

        //display all hidden element to visible
        mainTableEL.addClassName("showEventHandledElements");

        // Yeah I'm sorry how ugly this solution is, but it's only until I have time to do it properly

        // Capture the onfocus and onblur's
        for (elementIndice in onClickClearArray) {
            if ( typeof(onClickClearArray[elementIndice]) != "function" ) {
                        onClickClearEL = $(elementIndice);
                        if (onClickClearEL) {
                            onClickClearEL.onfocus = function() {
                                if (this.value == onClickClearArray[this.id]) this.value = '';
                            };
                            onClickClearEL.onblur = function() {
                                if (this.value == '') this.value = (this.defaultValue ? this.defaultValue : '');
                            };
                        }
            }
        }
        // Capture select's onchange
        $$("select.jumpMenu").each( function(targetElement) {
                                        targetElement.onchange = function() {
                                                newLocation = this.options[this.selectedIndex].value;
                                                if (newLocation != ""){
                                                    location=newLocation;
                                                }
                                        }
                                    }
                );
        onChangeSelectArray = ["billCountry", "shipCountry", "shipaddressBook", "CountryId", "selectCountry"];
        for (i = 0; i < onChangeSelectArray.length; i++) {
            onChangeSelectEL = $(onChangeSelectArray[i]);
            if ( onChangeSelectEL ) {
                onChangeSelectEL.onchange = ((onChangeSelectArray[i] == "shipaddressBook")?
                                                (function() {
                                                    ShipSameAsBillEL = $('ShipSameAsBill');
                                                    if (ShipSameAsBillEL) {
                                                        ShipSameAsBillEL.checked = false;
                                                        //}

                                                        resetFieldValues = (this.selectedIndex == 0);
                                                        if (resetFieldValues) {
                                                            synchBillingAndShipping(false);
                                                          } else {
                                                            //stateFilter
                                                            replaceInputFieldValues.replaceAllByChoose(this, addressBookDataObject);
                                                            stateFilter($('shipCountry'), $('shipState'), addressBookDataObject[this.selectedIndex]);
                                                        }
                                                        /* // [Make the address book's field like plainText ]
                                                        shipAddressNameEL = $('shipAddressName');
                                                        if (shipAddressNameEL) {
                                                            //shipAddressNameEL.style.borderWidth = ((ShipSameAsBillEL.checked)?"1":"0") + "px";
                                                            shipAddressNameEL.readOnly = (resetFieldValues)?false:true;
                                                        }*/
                                                    }
                                                }):(   function() {
                                                            stateFilter(this, $(this.id.replace("Country", "State")));
                                                    }
                                                )
                                            );
//                if ( (onChangeSelectEL.id != "shipaddressBook")&&(onChangeSelectEL.selectedIndex == 0) ) {  // If we are a Country dropdown, that isn't preselected, preselect the good old United States of America
                if (onChangeSelectEL.id != "shipaddressBook") {
                    stateFilter(onChangeSelectEL, $(onChangeSelectEL.id.replace("Country", "State")));
                }

                // do filter when preselected for shipping and billing address page only
//                if((onChangeSelectEL.id == "billCountry")||(onChangeSelectEL.id == "shipCountry")&&(onChangeSelectEL.selectedIndex > 0)){
//                    stateFilter(onChangeSelectEL, $(onChangeSelectEL.id.replace("Country", "State")));
//                }
            }
        }

        // Read the amount of shopping cart items cookie and write into the shopping cart link
        cookieValue = cookieUtil.getCookie('cart_items_2');
        cartItems = parseInt((cookieValue)?cookieValue:cartItems);
        totalInShoppingCartEL = $("totalInShoppingCartID");
        if (totalInShoppingCartEL && (cartItems > 0) ) {
            totalInShoppingCartEL.innerHTML = (addCommas(cartItems) + " Item" + (((cartItems==0)||(cartItems>1))?"s":"") );
        }

        /* IEFormBind - Since IE refuses to play nice, we unfortunately have to save it from itself when doubleSubmitting forms */
        if (document.selection) {
        	var formCounted = 0;
//            formELs = $$("#EPPOrderArea_C1R1 form, #PGBody1_C1R3 form, #PGBody1_C2R3 form");
            if($("EPP_container_id")){
                formEL=$("addToCart");
            }else{
                formELs = $$("form");
            }

            if (formELs) {
                formELs.each( function(formForIE, formCount) {
	                                        if (formForIE) {
		                                        //alert(formForIE + " is a " + formForIE.tagName + " with the following clases: " + formForIE.className);
                                                Event.observe(formForIE, 'submit', eventTrafficController );
//                                                Event.observe(formForIE, 'submit', eventTrafficController.bindAsEventListener(formForIE) );
                                            }
	                });
	        } else if(formEL){
                Event.observe(formEL, 'submit', eventTrafficController );
            }else{
                submitEventBound = false;
//                location.reload(true);
            }
        }else{
            if($("EPP_container_id")){
                formEL=$("addToCart");
                if(formEL){
                    Event.observe(formEL, 'submit', eventTrafficController );
                }else{
                    submitEventBound = false;
//                    location.reload(true);
                }
            }
        }

/* [Ticket #139714]
        #C5ProductDetailEppFDT.jsp <%-- fix for ticket #139714 --%><script type="text/javascript">var onProductDetailPage = true;</script><noscript></noscript>
         if (onProductDetailPage) {
            alert("firing new omniture linktracker vars");
            // Since I can't alter the core version of omniture.jsp, I pitch and catch the solution for ticket #139714
            s.linkTrackVars='eVar18,eVar19',s.eVar18='N/A';
            s.eVar19='N/A';
            setTimeout("s.tl(this,'o','N/A');",500);
        }*/

        // Check if a modal should be reactivated based on an error
        makeAModalEL = $('makeAModal');
        if (makeAModalEL) {      // if the popUp element actually exists when the page loads, a modal failed when it attempted to submit itself
            testEL = $(makeAModalEL.innerHTML);
            if (testEL) {
                if (testEL.id == "customerCouponPrompt") {
                    ajaxRequestInProgress = true;
                }
                innerModal({	'url': "",
                                'className': "",
                                'target': "",
                                'container': makeAModalEL.innerHTML,
                                'toolTipCoOrds': {'x': 0, 'y': 0},
                                'content': ""
                    });
            }
        }
        reCalculateViewport();

        //remove saved form value form gift card lookup page only.
        var giftCardLookupForm = $("giftCardLookup");
        if(giftCardLookupForm){
            textInputDataRemover.cleanBaseOnForm(giftCardLookupForm,["text","password"]);
        }
    },

    //------------------- put all customized function below -------------------//

    // --- BEGIN TESTING FUNCTION ---
    test1: function(o){
        alert("test1");
    },

    test2: function(o){
        alert("test2");
    },
    // --- END TESTING FUNCTION ---

    createLightBox: function(){
        lightBoxV2.createLightBoxV2("dom_overlay");
    }

}
/************************************************************************************
* DOM READY MAIN BODY ---- END
*
*************************************************************************************/

/*
window.onerror = function(issue, scriptname, linenumber){
    alert("[window.onerror]\n" + issue + "\n occured on line " + linenumber + " of script " + scriptname);
    return true;
}
*/

/* <Global Scoped Javascript Variables> */
    cssDomAttribute = (document.selection)?"className":"class";
    onClickClearArray = { 'frmTextSimpleSearch': "Enter Keyword or Item #", 'searchString': "Enter Keyword or Item #", 'frmTextEmail': "Enter Email Address", 'searchAgainField': "Enter Keyword or Item #" };
    omnitureURLHashmap = {'customerServiceStoreLocatorPage': "Store Locator Link"};
    cartItems = 0;
    preventDoubleSubmit = false;
    ajaxRequestInProgress = false;
    ShipSameAsBillArray = false;
    countryRegionDataObj = false;   // N
    activeModalDetailID = "";
    protectionPlanCheckboxObj = ({'activeID': "", 'collection': []});
    omnitureS_OBJ = false; //s_gi(OMNITURE_VALUE); // should the omnitureJS Object always be initialized? is so, remove the namespace reservation and invoke the s_gi() object initialization | OMNITURE_VALUE is set in CXOmnitureFDT.jsp
    activeProtectionPlanCheckboxID = "";
    badIE = false;
    var formEL = null;
    var formELs = null;
    refreshShoppingCart = false;
    onProductDetailPage = false;
    submitEventBound = true;
/* </Global Scope Javascript Variables> */


document.observe('dom:loaded', domReadyPageInit);