﻿function round(n, dec) {
    n = parseFloat(n);
    if (!isNaN(n)) {
        if (!dec) var dec = 0;
        var factor = Math.pow(10, dec);
        return Math.floor(n * factor + ((n * factor * 10) % 10 >= 5 ? 1 : 0)) / factor;
    } else {
        return n;
    }
}

function roundHalf(val) {
    var converted = parseFloat(val);
    var decimal = (converted - parseInt(converted, 10));
    var v = (decimal * 10);
    if (v >= 5) {
        return parseInt(converted, 10) + 1;
    } else {
        return parseInt(converted, 10);
    }
}

function MoneyConvert(value) {
    var val = round(value, 2);

    valStr = val.toString();
    if (valStr.indexOf(".") == -1) {
        valStr += ".00";
    }
    else {
        var arr = valStr.split(".");
        var numVal = arr[0];
        var decVal = arr[1];
        if (decVal.length < 2) { decVal += "0"; }
        valStr = numVal + "." + decVal;
    }

    return valStr;
}

function showBasketPopup() {
    if (location.href.toLowerCase().indexOf("cart.aspx") > 0) {
        window.location = location.href;
    }
    else {
        var screenH = $(document).height();
        var screenW = $(window).width();
        var winH = $(window).height();
        var winW = $(window).width();
        newtop = 0;
        newleft = 0;
        newtop = winH / 2 - $('#BasketDisplay').height() / 2;
        newleft = winW / 2 - $('#BasketDisplay').width() / 2;

        $('#BasketDisplay').css("top", newtop);
        $('#BasketDisplay').css("left", newleft);
        $('#BasketDisplay').fadeIn('fast');
        $('#bkgPopup').show();
    }
}

function closeCSPopup() {
    $('#CSDisplay').hide();
    $('#BasketDisplay').hide();
    $('#bkgPopup').hide();
}

function saveVariantToBasket(productCode) {
    //alert(productCode);
    var img = document.getElementById("saveToCart_" + productCode);
    img.src = greenCheckMark.src;

    var variantTextBox = document.getElementById("ctl00_MainContent_ProductDetails_addVariant_TextBox");
    var submitButtonURL = document.getElementById("ctl00_MainContent_ProductDetails_addVariantToBasket_LinkButton");
    variantTextBox.value = "SAV_" + productCode;
    location.href = submitButtonURL;
}

function addVariantToBasket(productCode) {
    //alert(productCode);
    var variantTextBox = document.getElementById("ctl00_MainContent_ProductDetails_addVariant_TextBox");
    var submitButtonURL = document.getElementById("ctl00_MainContent_ProductDetails_addVariantToBasket_LinkButton");
    variantTextBox.value = "ADD_" + productCode;
    // NOTE: NO NEED TO TRIGGER THE SUBMIT BUTTON, IF THE TEXTBOX HAS AN AUTOPOSTBACK EVENT ON CHANGE
    location.href = submitButtonURL;
}
var greenCheckMark = new Image(25, 25);
greenCheckMark.src = "/images/greenCheckmark.jpg";

$(function() {$("#Div1").hide();});

function updatePrice(callingDropDown) {
    var price = callingDropDown[callingDropDown.selectedIndex].getAttribute("price");
    var productId = callingDropDown.getAttribute("productId");

    //FIREFOX
    document.getElementById(productId + "_price").textContent = price;
    //IE
    document.getElementById(productId + "_price").innerText = price;

    //alert(price + "\n" + productId);
}
function showMoreDescription() {
    var sd = document.getElementById("shortDescription");
    sd.style.height = sd.scrollHeight + "px";
    var moreLink = document.getElementById("moreDescriptionLink");
    moreLink.style.display = "none";
}

// override onclick for Add-to-Cart.
$(function () {
    // cycle through the add buttons and remove default onclick
    $("TABLE[id$='gvVariants'] A[id$='addToCart']").each(function () {
        $(this)[0].onclick = null;
        $(this).click(AddToCartClickedProductPg);
    });


    // completely remove the default onclick behavior for bkgPopup
    $("DIV#bkgPopup").each(function () { $(this)[0].onclick = null; });

    // prevent the background from closing when the ajax loader is on
    $("DIV#bkgPopup").click(function (ev) {
        ev.stopPropagation();
        ev.preventDefault();
        var isLoading = $("DIV#cartProgressBar:visible").length > 0;
        if (!isLoading) {
            pfd.display.HidePopupBySelector("DIV.ModalPopupBox");
        }
        return false;
    });

    // for the order confirmation popup, "Continue shopping"/"Close" buttons will close popup
    $("DIV.ModalPopupBox DIV.btn-close-pop-up, DIV.ModalPopupBox DIV.close-pu, DIV.ListViewConfirmationBox A.popupContinueShopping").click(function () {
        pfd.display.HidePopupBySelector("DIV.ModalPopupBox");
    });

    // handler for modal confirmation's "proceed to cart" button
    $("DIV.ListViewConfirmationBox A.popupProceedToCart").click(function () {
        pfd.display.HidePopupBySelector("DIV.ModalPopupBox");
        window.location.href = "/cart.aspx";
        return false;
    });

});

// handle the "Add to Cart" button
function AddToCartClickedProductPg() {

    // show a progress/loading bar while we do this transaction
    pfd.display.ShowPopupBySelector("#cartProgressBar");

    // get the product id and quantity to be added to the basket
    var detailWrapper = $(this).closest("TR");
    var productId = $.trim(detailWrapper.find("SPAN[id$='lblSku']").text().replace("(", "").replace(")", ""));
    var brandName = $.trim($("span[id$='lblProductName']").html());
    
    var quantity = detailWrapper.find("SELECT[id$='_ddlQuantity']").val();
    var prodImg = $("IMG[id$='_ProductImage']");
    var prodTitle = $.trim($("span[id$='lblProductName']").html());
    var prodVariantTitle = $.trim(detailWrapper.find("SPAN[id$='lblDisplayAttributesLine1']").html()); //$.trim(checkedItem.closest("DIV.variant-row").find("SPAN.opt-cont").html());
    var prodVariantPrice = $.trim(detailWrapper.find("SPAN[id$='lblSalePrice']").html()); //$.trim(checkedItem.closest("DIV.variant-row").find("SPAN.sale-cont").html());
    
    var isAutoshipEligible = false;
    var hasAutoshipDiscount = false;
    var hasAutoshipBeenChosen = false;
    var frequency = null;
    
    
    var autoshipText = detailWrapper.find("DIV.title-as-box").text();
    var hasDiscountSavings = false;

    // get autoship percent
    var autoshipPercent = null;
    var useFireClick = (typeof (fc_click) != "undefined" && fc_click != null);
    var useOmniture = (typeof (s_gi) != "undefined" && s_gi != null);
    var omnitureObj = (useOmniture) ? s_gi("s_account") : null;

    
    var salePrice = parseFloat($.trim($("SPAN[id$='lblSalePrice']").text()).replace("$",""));
    var retailPrice = salePrice;

    var oRetailPrice = detailWrapper.find("SPAN[id$='lblRetailPrice']");
    if (oRetailPrice.length > 0) {
        retailPrice = parseFloat($.trim($("SPAN[id$='lblRetailPrice']").text()).replace("$", ""));
    }
    
    var newListPrice = salePrice;


    // get the savings amount percentage
    savingsAmount = round((1 - parseFloat(newListPrice) / parseFloat(retailPrice)) * 100, 2);

    var onComplete = function (success) {
        // if we successfully can add to cart, keep the background up while we show the next modal
        if (success) {
            // this will remove the modal, but keep the dark background
            pfd.display.HidePopupBySelector("#cartProgressBar", false);
        }
        // if we failed to add to cart, hide modal and background.
        else {
            // this will remove the entire modal/background
            pfd.display.HidePopupBySelector("#cartProgressBar", true);
        }
    };

    var onSuccess = function () {

        // fill in the modal popup
        var jImg = $("DIV.ListViewConfirmationBox IMG.popupProductImg");
        var jTitle = $("DIV.ListViewConfirmationBox DIV.popupTitle");
        var jVariantTitle = $("DIV.ListViewConfirmationBox DIV.popupVariantTitle");
        var jQuantity = $("DIV.ListViewConfirmationBox SPAN.popupQuantity");
        var endeca = $("DIV.ListViewConfirmationBox DIV.popupEndeca");

        // autoship is not available (yet) on the product screen
        var jAutoshipContainer = $("DIV.ListViewConfirmationBox DIV.you-will-save");
        var jAutoshipSavings = jAutoshipContainer.find("SPAN.popupAutoshipSavings");
        var jAutoshipBrand = jAutoshipContainer.find("SPAN.popupAutoshipDiscountBrand");
        var jAutoshipPrices = $("DIV.ListViewConfirmationBox DIV.popupAutoshipPrices");

        // random/aux DOM elements
        var cartBasketContainer = $("DIV.basket-text");
        var cartCount = parseInt($.trim(cartBasketContainer.find("SPAN#cartCount").html()), 10);

        // reset autoship objects
        jAutoshipSavings.hide();
        jAutoshipBrand.hide();
        jAutoshipContainer.hide();
        jAutoshipPrices.hide();

        // increment the cart counter
        if (cartCount == 0) {
            cartBasketContainer.html(cartBasketContainer.html().replace("items ", "item "));
        }else{
            cartBasketContainer.html(cartBasketContainer.html().replace("item ", "items "));
        }
        cartBasketContainer.find("SPAN#cartCount").html(cartCount + 1);


        // (Again, the autoship feature is not available on this page, but when it is...) we will switch these to active
        if (hasAutoshipBeenChosen && hasAutoshipDiscount) {

            if (hasDiscountSavings) {
                jAutoshipBrand.html(brandName);
                jAutoshipBrand.show();
            }

            $("SPAN.popupRetailPrice").html("$" + MoneyConvert(retailPrice));
            $("SPAN.popupSalePrice").html("$" + MoneyConvert(salePrice));
            $("SPAN.popupPromoPrice").html("$" + MoneyConvert(newListPrice));

            jAutoshipContainer.show();
            jAutoshipPrices.show();
        }


        // config the image
        jImg.attr("src", prodImg.attr("src"));
        jImg.attr("height", 150); //prodImg.height());
        jImg.attr("width", 150); //prodImg.width());
        jImg.attr("title", prodVariantTitle);

        // config the title, variant title, and quantity
        jTitle.html(prodTitle);
        jVariantTitle.html(prodVariantTitle);
        jQuantity.html(quantity);

        // show the popup
        pfd.display.ShowPopupBySelector("DIV.ListViewConfirmationBox");
    };


    // we'll attempt to add to the cart... 
    // If success, hide the modal, keep the bg; if failure, hide modal/bg and show alert of msg.

    $.ajax({
        type: "POST",
        url: "/ClientSideOperations.asmx/AddItemWithAutoshipFrequency",
        data: "{\"variantId\":\"" + productId + "\", \"quantity\": " + quantity + ", \"frequency\": \"" + frequency + "\"}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        complete: function (jqXHR, textStatus) {
            onComplete(textStatus == "notmodified" || textStatus == "success");
        },
        success: function (msg) {

            var d = $("<div></div>");
            d.html(msg.d);
            var f = d.find("form");
            f.find("DIV:has(INPUT[name='__VIEWSTATE'])").remove();
            $("DIV.popupEndeca").html(f.html());

            onSuccess();
        }
    });

    // this prevents the browser from hopping to the top of the screen
    return false;
}
