﻿//jQuery Intellisense Document Reference for External js Files
///<reference path="jquery-1.2.6.min-vsdoc.js" />

//********************************************************
//*****  Add To Cart Functions ***************************
//********************************************************

    //jQuery Ajax GET to add item(s) to database shopping cart
    function jQueryAddItem(itemDataString, hasWarranty) {
        //make jQuery ajax call to minibag.aspx
        $.ajax({
            type: "GET",
            datatype: "html",
            url: "_minibag.aspx?action=add",
            data: itemDataString,
            cache: false,
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                //alert('Sorry, an error has occured. Can not add item at this time, jQueryAddItem call failed. Please contact customer service.');
            },
            success: function(itemHtmlData, textStatus) {
                //check if product has a warranty available for it
                if (hasWarranty == 'True') {
                    //if warranty available, call function to check if warranty was selected.
                    //don't load returned html for item yet, just pass html to checkForWarranty fuction. 
                    //if warranty exists, we want to load both items to bag at same time.
                    checkForWarranty(itemHtmlData);

                } else {
                    //warranty not available for item, reload calculator with updated contents
                    loadCalculatorContent(itemHtmlData);
                    
                    //update cart item count in header
                    updateCartItemCount();
                    
                    //update totals
                    calculateTotals($("#shoppingtotalprice").text().replace("$", ""));
                }
                
                //check for errors/info messages that occurred during add of item and/or warranty
                jQueryCheckError();
            }
        });   // end item ajax call
    }
    
    //reload calculator with updated cart contents
    function loadCalculatorContent(htmlData) {
        $("#calculatorcontent").html(htmlData);

        //re-insert Understand These Totals Link
        //$("#calc_understand_totals").insertAfter('<div class="calc_understand_totals"><a href="IshouldunderstandTotals.aspx?height=350&width=739" class="thickbox"><span class="thegreen"><u>Understand These Totals</u></span></a></div>');
    }
    
    //process warranty control and return string of data
    function checkForWarranty(itemHtmlData) {
        //declare variables
        var arrWarrantyControlValues, productOfferCode, productOrderItemXID, warrantyControlId, result;
        var warrantyOfferCode, warrantyOfferXID, warrantyGroupXID, warrantyOfferOptionXID;
        var warrantyDataString = '';
        
        //get needed values from hidden fields in warrantyDetails user control
        productOfferCode = document.getElementById('hdnProductOfferCode').value;
        productOrderItemXID = document.getElementById('hdnProductOrderItemXID').value;
        
        //get warranty radiobuttonlist table control id
        warrantyControlId = document.getElementById('hdnWarrantyClientId').value;

        //call function to parse the radiobuttonlist table rows and return checked radio button control
        arrWarrantyControlValues = getSelectedWarranty(warrantyControlId).split(',');

        //Check if offerXID (array index 1) has a value, if not, don't build query string or make ajax call cause no warranty selected by customer
        if (arrWarrantyControlValues[1] != null && arrWarrantyControlValues[1] != '') {
        
            //Need to get OrderItemXID from returned html data string for multiple warranties on same product
            var searchFor, startPosition, endPosition, newString, value;
            searchFor1 = 'id="hdnOrderItemXID"';
            searchFor2 = 'name="hdnOrderItemXID"';

            startPosition = itemHtmlData.search(searchFor1);
            endPosition = itemHtmlData.search(searchFor2);

            if (startPosition > -1) {
                newString = itemHtmlData.substring((startPosition + searchFor1.length), endPosition);
                newString = newString.replace(/value=/i, "");       //remove value= from string
                newString = newString.replace(/"/g, "");            //remove double quotes from string
                newString = newString.replace(/^\s+|\s+$/g, "");    //remove any white spaces from string

                //verify final value is numeric
                if (isNumeric(newString)) {
                    productOrderItemXID = newString;
                } else {
                    alert('Product OrderItemXID was not detected. Please call customer service if issue persists.');
                    productOrderItemXID = '0';
                }
            } else {
                productOrderItemXID = '0';
            }
            // end of getting OrderItemXID for multi warranties
            
            //customer selected warranty, set values for adding to cart
            warrantyOfferCode = arrWarrantyControlValues[0];
            warrantyOfferXID = arrWarrantyControlValues[1];
            warrantyOfferOptionXID = arrWarrantyControlValues[2];
            warrantyGroupXID = arrWarrantyControlValues[3];

            //build warranty query string
            warrantyDataString = "_offerXID=" + warrantyOfferXID;
            warrantyDataString = warrantyDataString + "&_groupXID=" + warrantyGroupXID;
            warrantyDataString = warrantyDataString + "&_offerOptionXID=" + warrantyOfferOptionXID;
            warrantyDataString = warrantyDataString + "&_warrantyoffercode=" + warrantyOfferCode;
            warrantyDataString = warrantyDataString + "&_productoffercode=" + productOfferCode;
            warrantyDataString = warrantyDataString + "&_productorderitemxid=" + productOrderItemXID;
            warrantyDataString = warrantyDataString + "&_warrantyflag=Y";
            warrantyDataString = warrantyDataString + "&_quantity=1";

            //jQuery ajax call to add warranty
            jQueryAddWarranty(warrantyDataString);

        } else {
            //warranty not selected for item, reload calculator with updated contents
            loadCalculatorContent(itemHtmlData);

            //update cart item count in header
            updateCartItemCount();
            
            //update totals
            calculateTotals($("#shoppingtotalprice").text().replace("$", ""));
        }
    }

    function isNumeric(value) {
      if (value != null && !value.toString().match(/^[-]?\d*\.?\d*$/)) return false;
      return true;
    }

    //parses the RadioButtonList Table rows and returns the checked radio button control      
    function getSelectedWarranty(warrantyOfferControlId) {
        var rbl = document.getElementById(warrantyOfferControlId).rows;
        var listControl = null;
        var result;
        var ctrlName;

        for (var i = 0; i < rbl.length; i++) {
            ctrlName = warrantyOfferControlId + '_' + i;
            listControl = document.getElementById(ctrlName);

            if (listControl.checked == true)
            { result = listControl.value; }
        }
        return result;
    }

    //jQuery ajax Get to add warranty to cart
    function jQueryAddWarranty(warrantyDataString) {
    
        $.ajax({
            type: "GET",
            datatype: "html",
            url: "_minibag.aspx?action=add",
            data: warrantyDataString,
            cache: false,
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                //alert('Sorry, an error has occured. Can not add item at this time, checkForWarranty call failed. Please contact customer service.');
            },
            success: function(warrantyHtmlData, textStatus) {
                //warranty added, reload calculator with updated contents
                loadCalculatorContent(warrantyHtmlData);

                //warranty added, update cart item count in header
                updateCartItemCount();
                
                //update totals
                calculateTotals($("#shoppingtotalprice").text().replace("$", ""));
            }
        }); // end warranty ajax call
    }

    //update the cart item count in upper right corner of header
    function updateCartItemCount() {
        //jQuery ajax call to get updated html
        $("#shoppingBag").load(
            "_cartItemCount.aspx",
            {},
            function(responseText, textStatus, XMLHttpRequest) {
                //check xmlhttpRequest status
                switch (XMLHttpRequest.status) {
                    case 200:
                        //success
                        break;        
                    default:
                        //alert('Sorry, a ' + XMLHttpRequest.status + 'Error occured. Could not update item count in header.');
                        break;
               }    
            }
        );
    }

    //remove item from the cart
    function removeFromCart(offerXID) {
        $.ajax({
            type: "GET",
            datatype: "html",
            url: "_minibag.aspx?action=remove",
            data: "_offerXID=" + offerXID,
            success: function(htmlData) {
                //reload calculator with updated contents
                loadCalculatorContent(htmlData);

                //update cart item count in header
                updateCartItemCount();

                //refresh error div
                jQueryCheckError()
                
                //update totals
                calculateTotals($("#shoppingtotalprice").text().replace("$", ""));
            }
        });
    }

    //check session for custom error messages that need displaying
    function jQueryCheckError() {
        $.ajax({
            type: "GET",
            datatype: "html",
            url: "_errormessage.aspx",
            data: {},
            cache: false,
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                //alert('Sorry, an error has occured. Can not check for errors at this time, jQueryCheckError call failed. Please contact customer service.');
            },
            success: function(htmlData, textStatus) {
                //load erorr message div with returned html data
                $("#divErrorMessage").html(htmlData);
                
                // [February Release] RM 1347: Special Messages on Product Pages  
                if( htmlData.indexOf('<div id="rptErrMsg">')> -1 && document.documentElement.scrollTop > 0 )
                {
                    var targetOffset = $("#divErrorMessage").offset().top - 5;
                    $('html,body').animate({scrollTop: targetOffset}, 1000);
                }
               
            }
        });  // end ajax call
    }
    
    function calculateTotals(totalPrice) {
        if (totalPrice != "") {
            //jQuery Ajax GET to get totals
            //make jQuery ajax call to _calcdata.aspx
            $.ajax({
                type: "GET",
                datatype: "html",
                url: "_calcdata.aspx?",
                data: "price="+totalPrice,
                cache: false,
                error: function(XMLHttpRequest, textStatus, errorThrown) {
                    //alert('Sorry, an error has occured. Can not add item at this time, jQueryAddItem call failed. Please contact customer service.');
                },
                success: function(itemHtmlData, textStatus) {
                    displayCalcTotals(itemHtmlData);
                }
            });   // end item ajax call
        }
    }

    
    function displayCalcTotals(priceString) {
        //make an array from the comma delimited options string
        var OptionsArray = priceString.split("|");

        //for each array element, add it as an option to the
        //input select object and set it's innerText
        if ((priceString == 0) || (priceString == null)) {
            $("#cYourCardTotal").text("$0.00");
            $("#cYourCardPayments").text("0");
            $("#cYourCardFinalTotal").text("$0.00");
            $("#cFastOptionTotal").text("$0.00");
            $("#cFastOptionPayments").text("0");
            $("#cFastOptionFinalTotal").text("$0.00");
            $("#cFastOptionPayment").text("$0.00");
            $("#cEasyOptionTotal").text("$0.00");
            $("#cEasyOptionPayments").text("0");
            $("#cEasyOptionFinalTotal").text("$0.00");
            $("#cEasyOptionPayment").text("$0.00");
            $("#cTypicalVisaTotal").text("$0.00");
            $("#cTypicalVisaPayments").text("0");
            $("#cTypicalVisaFinalTotal").text("$0.00");
            $("#cTypicalVisaPayment").text("$0.00");
        } else {
            $("#cYourCardTotal").text(OptionsArray[0]);
            $("#cYourCardPayments").text(OptionsArray[1]);
            $("#cYourCardFinalTotal").text(OptionsArray[2]);
            $("#cFastOptionTotal").text(OptionsArray[3]);
            $("#cFastOptionPayments").text(OptionsArray[4]);
            $("#cFastOptionFinalTotal").text(OptionsArray[5]);
            $("#cFastOptionPayment").text(OptionsArray[6]);
            $("#cEasyOptionTotal").text(OptionsArray[7]);
            $("#cEasyOptionPayments").text(OptionsArray[8]);
            $("#cEasyOptionFinalTotal").text(OptionsArray[9]);
            $("#cEasyOptionPayment").text(OptionsArray[10]);
            $("#cTypicalVisaTotal").text(OptionsArray[11]);
            $("#cTypicalVisaPayments").text(OptionsArray[12]);
            $("#cTypicalVisaFinalTotal").text(OptionsArray[13]);
            $("#cTypicalVisaPayment").text(OptionsArray[14]);
        }
    }
    
    function currencyFormatted(amount) {
        var i = parseFloat(amount);
        if (isNaN(i)) { i = 0.00; }
        var minus = '';
        if (i < 0) { minus = '-'; }
        i = Math.abs(i);
        i = parseInt((i + .005) * 100);
        i = i / 100;
        s = new String(i);
        if (s.indexOf('.') < 0) { s += '.00'; }
        if (s.indexOf('.') == (s.length - 2)) { s += '0'; }
        s = minus + s;
        return s;
    }

    
    function personalizationWarrantyCheck() {
        //declare variables
        var arrWarrantyControlValues, productOfferCode, productOrderItemXID, warrantyControlId, result;
        var warrantyOfferCode, warrantyOfferXID, warrantyGroupXID, warrantyOfferOptionXID;
        var warrantyDataString = '';

        //get needed values from hidden fields in warrantyDetails user control
        productOfferCode = document.getElementById('hdnProductOfferCode').value;
        productOrderitemXID = document.getElementById('hdnProductOrderItemXID').value;

        //get warranty radiobuttonlist table control id
        warrantyControlId = document.getElementById('hdnWarrantyClientId').value;

        //call function to parse the radiobuttonlist table rows and return checked radio button control
        arrWarrantyControlValues = getSelectedWarranty(warrantyControlId).split(',');

        //Check if offerXID (array index 1) has a value, if not, don't build query string or make ajax call cause no warranty selected by customer
        if (arrWarrantyControlValues[1] != null && arrWarrantyControlValues[1] != '') {
            //customer selected warranty, set values for adding to cart
            warrantyOfferCode = arrWarrantyControlValues[0];
            warrantyOfferXID = arrWarrantyControlValues[1];
            warrantyOfferOptionXID = arrWarrantyControlValues[2];
            warrantyGroupXID = arrWarrantyControlValues[3];

            //build warranty query string
            warrantyDataString = "&WarrantyOfferXID=" + warrantyOfferXID;
            warrantyDataString = warrantyDataString + "&WarrantyGroupXID=" + warrantyGroupXID;
            warrantyDataString = warrantyDataString + "&WarrantyOfferOptionXID=" + warrantyOfferOptionXID;
            warrantyDataString = warrantyDataString + "&Warrantyoffercode=" + warrantyOfferCode;
            warrantyDataString = warrantyDataString + "&Productoffercode=" + productOfferCode;
            warrantyDataString = warrantyDataString + "&Productorderitemxid=" + productOrderitemXID;
            warrantyDataString = warrantyDataString + "&Warrantyflag=Y";
            warrantyDataString = warrantyDataString + "&WarrantyQuantity=1";
        } else {
            warrantyDataString = '';
        }
  
        return warrantyDataString;
    }

    //faq, function for initial display of an FAQ
    function showFAQ(faqLevel, faqId) {
        var sectionId, qaSectionId, questionId, anchorId;
        
        //check faqLevel ("q" = Question section block and "a" = Answer block)
        if (faqLevel == "q") {
            //faqId is the Id for question/answer block
            //get the main section div id and anchor id
            sectionId = getSectionId(faqId);
            anchorId = getAnchorId(sectionId);

            //click anchor link to move to correct part of page
            $('#' + anchorId).click();
            //display questions/answer div
            $('#' + faqId).show("slow");
            //change css class for main section div
            $('#' + sectionId).addClass("faq_section2");
            
        } else if (faqLevel == "a") {
            //faqId is the Id for lowest level - answer div
            //get the 3 other levels of div IDs, used for adding/removing classes and displaying divs
            //and the anchorId for moving to correct part of page
            questionId = getQuestionId(faqId);
            sectionId = getSectionId(faqId);
            qaSectionId = getQASectionId(sectionId);
            anchorId = getAnchorId(sectionId);

            //click anchor link to move to correct part of page
            $('#' + anchorId).click();
            //display answer div
            $('#' + faqId).show("slow");
            //change css class for question div
            $('#' + questionId).addClass("faq_question2");
            //display questions/answer div
            $('#' + qaSectionId).show("slow");
            //change css class for main section div
            $('#' + sectionId).addClass("faq_section2");
        }
    }
    function getQuestionId(faqId) {
        var tempStr;
        tempStr = faqId.substring(0, faqId.length - 1);
        return tempStr + 'q';
    }
    function getQASectionId(faqId) {
        return faqId + '--qa';
    }
    function getSectionId(faqId) {
        return faqId.substring(0, faqId.indexOf("--", 0));
    }
    function getAnchorId(faqId) {
        return faqId + '--anchor';
    }
                
//on document ready.....
    $(document).ready(function() {

        calculateTotals($("#shoppingtotalprice").text().replace("$", ""));

        if ($("#calculatorcontent").length > 0) {
            $("#calculatorcontent").load(
            "_minibag.aspx?action=load",
            {},
            function() {
                calculateTotals($("#shoppingtotalprice").text().replace("$", ""));
            }
        )
        };

        $(".tab_off").click(
            function() {
                $("#tab1, #tab2").toggle();
            }
        );

        $("#total_cost_link").click(
            function() {
                if ($("#total_cost_display").is(":hidden")) {
                    $("#total_cost_display").slideDown("slow", function() {
                        $("#total_cost").removeClass("total_cost_showit");
                        $("#total_cost").addClass("total_cost_hideit");
                        $("#openCloseIdentifier").show();
                    });
                } else {
                    $("#total_cost_display").slideUp("slow", function() {
                        $("#total_cost").removeClass("total_cost_hideit");
                        $("#total_cost").addClass("total_cost_showit");
                        $("#openCloseIdentifier").hide();
                    });
                }
            }
        );

        $("#home_calc_dropdown").change(
            function() {
                if ($(this).val() == "$------") {
                    calculateTotals(0);
                } else {
                    calculateTotals($(this).val().replace("$", ""));
                }
            }
        );

        //black friday promo - image replacement for mouse hover
        $("div.blackfriday img").hover(
            function() {
                this.src = this.src.replace("_off", "_hover");
            },
            function() {
                this.src = this.src.replace("_hover", "_off");

            }
        )

        //black friday promo - image replacement for mouse click
        $("div.blackfriday img").click(
            function() {
                if (this.src.indexOf("_on") == -1) {
                    this.src = this.src.replace("_hover", "_on");

                    if (this.id.indexOf("A") == -1) {
                        var altImgId = document.getElementById(this.id.replace("B", "A"))
                        altImgId.src = altImgId.src.replace("_on", "_off");
                    } else {
                        var altImgId = document.getElementById(this.id.replace("A", "B"))
                        altImgId.src = altImgId.src.replace("_on", "_off");
                    }
                } else {
                    this.src = this.src.replace("_on", "_hover");
                }
            }
        )

        //insert Understand These Totals Link
        $("#calc_understand_totals").replaceWith('<div class="calc_understand_totals"><a href="understandTotals.aspx?height=350&width=739" class="thickbox"><span class="thegreen"><u>Understand These Totals</u></span></a></div>');

        //faq, hide/show main section content
        $("div.faq_section").toggle(
            function() {
                $(this).next("div.faq_section_content").slideDown("fast");
                $(this).addClass("faq_section2");
            },
            function() {
                $(this).next("div.faq_section_content").slideUp("fast");
                $(this).removeClass("faq_section2");
            });

        //faq, hide/show answer for a specific question
        $("div.faq_question").toggle(
            function() {
                $(this).next("div.faq_answer").slideDown("fast");
                $(this).addClass("faq_question2");
            },
            function() {
                $(this).next("div.faq_answer").slideUp("fast");
                $(this).removeClass("faq_question2");
            });
    });