﻿//2008/11/26 by Marble Wu (Marble.M.Wu@newegg.com)
function reBuildDiscountMessage(total, totalFinal) {
    $("#discountMessage").html("");
    var messageFormat = infos.M0006;
    var message = "";
    if (total > totalFinal) {
        var discount = total - totalFinal;
        var totalText = total.toFixed(2);
        var discountText = discount.toFixed(2);
        message = messageFormat.replace(/\$\$\$Price\$\$\$/g, totalText).replace(/\$\$\$Discount\$\$\$/g, discountText);
    }
    $("#discountMessage").html(message);
};
//2008/11/26 by Marble Wu (Marble.M.Wu@newegg.com)
function doDeleteMulitItems(indexList) {
    if (indexList && indexList.length > 0) {
        var index = indexList.pop();
        if (index != undefined && index != null) {
            var itemCode = $("#itemCode" + index).val();
            $.getJSON(
            Env.ProductAjaxUrl
            , { op: Configs.Operation.RemoveToCart, itemcode: itemCode }
            , function(data) {
                if (data && data.SuccessApply) {
                    deleteAllPresent(index);
                    $("#tab" + index).remove();
                    if (data.ContinerIdList) {
                        for (var i = 0; i < data.ContinerIdList.length; i++) {
                            $("#tab" + data.ContinerIdList[i]).remove();
                        }
                    }
                    doDeleteMulitItems(indexList);
                    reBuildHeaderCartItemsCount(data);
                }
            });
        }
    }
    dealPrice();
};

function deleteAllPresent(i) {
    var mianItemCode = $("#itemCode" + i).attr("value");
    var presentItem = $("input[name='presentMainItem" + mianItemCode + "']");
    if (presentItem.length > 0) {
        presentItem.each(function() {
            if ($(this).val().toString() != "NaN") {
                $("#present" + $(this).val()).remove();
            }
        });
    }
    removePresentTable();
}
function removePresentTable() {
    var chk = $("input[name='cartGiftSingleCheckBox']");
    if (chk.length == 0) {
        $("#persentTip").hide();
        $("#persentTableTitle").hide();
        $("#tbPresent").hide();
    }
}
//2008/12/02 by Marble Wu (Marble.M.Wu@newegg.com)
function reBuildHeaderCartItemsCount(data) {
    var count = data.ItemCount;
    var hyperLink = $("#header_cart_count");
    var textFormat = infos.CM0001;
    var text = textFormat.replace(/\$\$\$Count\$\$\$/g, count + '');
    hyperLink.html(text);

    var header_cart_count_2 = $("#header_cart_count_2");
    if (header_cart_count_2) {
        header_cart_count_2.html(count);
    }

    var dlCartList = $("#dlCartList");
    if (dlCartList) {
        var count = $("#dlCartList > dd").length;
        for (i = 0; i < count; i++) {
            if ($("#header_cart_itemCode_" + i).val() == data.ItemCode) {

                $("#headPriceFinal_" + i).html(getString(data.CustomerPrice));
                $("#headQuantity_" + i).html(data.Qty);
                $("#header_cart_price_" + i).val(data.CustomerPrice);
                $("#header_cart_qty_" + i).val(data.Qty);
                $("#header_cart_item_sum_" + i).val(data.Qty * data.CustomerPrice);
            }
        }
    }

    window.HeaderCartItemsCount = count;
    reBuildHeaderCartPriceTotal();
    if (count <= 0) {
        $(".cartNoitemsWarningNormal").show();
        $("#checkOut").hide();
        $("div[rel='whenNoItemsHidden']").hide();
        $("#tbPresent").hide();
        $("td[rel='whenNoItemsHidden']").hide();
        $("ul[rel='whenNoItemsHidden']").hide();
    }
};

function reBuildHeaderCartPriceTotal() {

    //set price
    var price = 0, qty = 0, sumPrice = 0, totalPrice = 0;
    var itemCount = window.HeaderCartItemsCount - 0;
    var header_cart_item_sum_elements = $("input[rel='header_cart_item_sum']");
    if (header_cart_item_sum_elements.length > 0) {
        for (i = 0; i < header_cart_item_sum_elements.length; i++) {
            var sum = getPrice($(header_cart_item_sum_elements[i]).val());
            totalPrice += sum;
        }
    }
    if ($("#header_cart_price_total")) {
        $("#header_cart_price_total").text('￥' + totalPrice);
    }
}

function doClearCartConfirm() {
    window.showConfirm("您真的要清空购物车中吗？", "doClearCart()");
    return false;
}

function doClearCart() {
    $("#hidCommand").val('ClearCart');
    $("#aspnetForm").submit();
}

$().ready(function() {
    $("#checkOut").click(function() {

        $("#hidCommand").val('CheckOut');
        var btn = $(this)[0];
        if (btn) {
            AjaxLoading.showReplaceCheckOut(btn);
        }
        $('#aspnetForm').submit();
        return true;
        
    });

    $("#btnClearCar").click(function() {
        return doClearCartConfirm();
    });

    //2008/12/02 by Marble Wu (Marble.M.Wu@newegg.com)
    $("#checkAllCartItems").click(function() {
        checkAllItemsOrUnCheckAllItems();
    });

    $("#checkAllCartGift").click(function() {
        checkAllGiftOrUnCheckAllGift();
    });

    $("input[name='cartGiftSingleCheckBox']").click(function() {
        checkGiftItem();
        changePresentStatus($(this).val(), $(this).attr("checked"));
    });

    //2008/12/02 by Marble Wu (Marble.M.Wu@newegg.com)
    $("input[name='cartItemSingleCheckBox']").click(
    function() {
        var isCheckAll = true;
        $("input[name='cartItemSingleCheckBox']").each(function() {
            if ($(this).attr("checked") != true) {
                isCheckAll = false;
            }
            $("#checkAllCartItems").attr("checked", isCheckAll);
        });
    });

    checkGiftItem();
});

function checkGiftItem() {
    var isCheckAll = true;
    $("input[name='cartGiftSingleCheckBox']").each(function() {
        if ($(this).attr("checked") != true) {
            isCheckAll = false;
        }
        $("#checkAllCartGift").attr("checked", isCheckAll);
    });
}

function checkAllItemsOrUnCheckAllItems() {
    if ($("#checkAllCartItems").attr("checked") == true) {
        $("input[name='cartItemSingleCheckBox']").each(function() {
            $(this).attr("checked", true);
            $("#checkAllCartItems").attr("checked", true);
        });
    }
    else {
        $("input[name='cartItemSingleCheckBox']").each(function() {
            $(this).attr("checked", false);
            $("#checkAllCartItems").attr("checked", false);
        });
    }
};

function checkAllGiftOrUnCheckAllGift() {
    if ($("#checkAllCartGift").attr("checked") == true) {
        $("input[name='cartGiftSingleCheckBox']").each(function() {
            $(this).attr("checked", true);
            $("#checkAllCartGift").attr("checked", true);
        });
    }
    else {
        $("input[name='cartGiftSingleCheckBox']").each(function() {
            $(this).attr("checked", false);
            $("#checkAllCartGift").attr("checked", false);
        });
    }
    $.getJSON(
        Env.ProductAjaxUrl
        , { op: Configs.Operation.ChangeAllPresent, spic: $("#checkAllCartGift").attr("checked") }
        , function(data) {
            if (data && data.SuccessApply) {
                reBuildHeaderCartItemsCount(data);
            }
        }
    );
};

var Configs = {
    Operation: {
        AddToCart: 2,
        RemoveToCart: 3,
        ChangeQtyToCart: 4,
        ChangePresent: 5,
        AddPresent: 6,
        ChangeAllPresent: 7,
        GetOrderGift: 8
    }
};
function selectAll() {
    var checklist = $("input[name='cartItemSingleCheckBox']");
    for (var i = 0; i < checklist.length; i++) {
        checklist[i].checked = true;
    }
};
function deleteSelectItem() {
    var hasSelected = false;
    var checklist = $("input[name='cartItemSingleCheckBox']");
    for (var i = 0; i < checklist.length; i++) {
        if (checklist[i].checked) {
            hasSelected = true;
            break;
        }
    }
    if (hasSelected) {
        window.showConfirm(infos.M0004, "deleteSelect()");
    }
    else {
        window.alert(infos.M0005);
    }
};
function deleteSelect() {
    var checklist = $("input[name='cartItemSingleCheckBox']");
    var itemPreDeleteIndexList = new Array();
    for (var i = 0; i < checklist.length; i++) {
        if (checklist[i].checked) {
            itemPreDeleteIndexList.push(i);
        }
    }
    doDeleteMulitItems(itemPreDeleteIndexList);
    dealPrice();
};
function deleteItem(i) {
    var itemCode = $("#itemCode" + i).attr("value");
    window.showConfirm(infos.M0003, "confirmDelete(" + itemCode + "," + i + ")");
};

function deleteHeaderCartItem(index) {
    var itemCode = $("#header_cart_itemCode_" + index).val() + '';
    confirmDelete(itemCode, index);
};

function confirmDelete(itemCode, i) {
    $.getJSON(
    Env.ProductAjaxUrl
    , { op: Configs.Operation.RemoveToCart, itemcode: itemCode }
    , function(data) {
        if (data && data.SuccessApply) {
            $("#header_cart_row_" + i).remove();
            reBuildHeaderCartItemsCount(data);
            window.HeaderCartItemsCount = data.ItemCount;
            reBuildHeaderCartPriceTotal();
            $("#tab" + i).remove();
            if (data.ContinerIdList) {
                for (var t = 0; t < data.ContinerIdList.length; t++) {
                    $("#tab" + data.ContinerIdList[t]).remove();
                }
            }
            dealPrice();
        }
    });
};

function setQty(i, q, b, minAdd, minLimit) {
    var input = $("#qty" + i).get(0);
    ///不做每单最大购买量限制,但限制最大输入数
    var limitedQty = 999999;
    var orgQty = input.value;
    var qty = getString(input.value) - 0 + q;

    if (!checkQty(qty, minLimit, minAdd)) {
        $("#checkOut").hide();
        return;
    }
    $("#checkOut").show();
    setQtyBoxReadOnly(true);
    var priceFinal = $("#priceFinal" + i).get(0);
    var sppriceFinal = $("#spPriceFinal" + i).get(0);
    if (!b) {
        b = false;
    } else {
        b = true;
    }
    if (qty.toString() != "NaN") {
        //qty = Math.floor(qty);
        if (qty > limitedQty) {
            input.value = limitedQty;
            qty = limitedQty;
            if (limitedQty >= 0) {
                alert(infos.M0001.replace('{0}', limitedQty));
            }
        }
        else if (qty <= 0) {
            if (limitedQty <= 0) {
                alert(infos.M0008);
                return;
            }
            alert(infos.M0002);
            input.value = 1;
            qty = 1;
        }
        else {
            input.value = qty;
        }
    }
    else {
        alert(infos.M0002);
        input.value = 1;
        qty = 1;
    }

    var itemCode = $("#itemCode" + i).attr("value");
    $.getJSON(
        Env.ProductAjaxUrl
        , { op: Configs.Operation.ChangeQtyToCart, itemcode: itemCode, qty: qty, delGift: b }
        , function(data) {
            var input = $("#qty" + i).get(0);
            var flag = b;
            if (data) {
                if (data.ContinerIdList) {
                    input.value = orgQty;
                    dealPrice();
                    var textFormat = infos.M0009;
                    var itemName = "";
                    for (var t = 0; t < data.ContinerIdList.length; t++) {
                        itemName += "(" + $("#itemName" + data.ContinerIdList[t]).val() + ") ";
                    }
                    var text = textFormat.replace(/\$\$\$Name\$\$\$/g, itemName + '');
                    text = text.replace(/\$\$\$Count\$\$\$/g, orgQty + '');
                    window.showConfirm(text, "deleteAllGift(" + data.ContinerIdList + "," + i + "," + q + ")");
                }
            }
            priceFinal.value = data.CustomerPrice;
            $(sppriceFinal).html(getString(data.CustomerPrice));
            reBuildHeaderCartItemsCount(data);
            dealPrice();
            setQtyBoxReadOnly(false);
        }
    );
};

function setQtyBoxReadOnly(status) {
    var tabCount = $("#tabCount").attr("value") - 0;
    for (i = 0; i < tabCount; i++) {
        var input = $("#qty" + i).attr("disabled", status);
    }
}

function setAllGiftLimitCount(mainItemCode, mainItemQuantity) {
    var giftItem = $("input[name='mainCode" + mainItemCode + "']");
    if (giftItem.length > 0) {
        giftItem.each(function() {
            if ($(this).val().toString() != "NaN") {
                var index = $(this).val();
                var giftCount = $("#giftCount" + index).val();
                var mainCount = $("#mainBuyCount" + index).val();
                if (mainItemQuantity.toString() != "NaN" && mainCount.toString() != "NaN" && giftCount.toString() != "NaN") {
                    var realLimt = $("#realLimited" + index).val();
                    var rsLimit = (mainItemQuantity - (mainItemQuantity % mainCount)) / mainCount * giftCount;
                    if (realLimt.toString() != "NaN" && rsLimit > realLimt) {
                        rsLimit = realLimt;
                    }
                    $("#limited" + index).val(rsLimit);
                }
            }
        });
    }
}

function deleteOrAddPresent(i) {
    var qty = $("#qty" + i).val();
    var mianItemCode = $("#itemCode" + i).attr("value");
    var presentItem = $("input[name='presentMainItem" + mianItemCode + "']");

    if (presentItem.length > 0) {
        presentItem.each(function() {
            if ($(this).val().toString() != "NaN") {
                var index = $(this).val();
                var mainCount = $("#mainItemCount" + index).val();
                if (mainCount.toString() != "NaN" && qty.toString() != "NaN") {
                    if (mainCount > qty) {
                        $("#present" + index).remove();
                    } else {
                        UpdatePresentQuantity(index, i);
                    }
                }
            }
        });
    }
    $.getJSON(Env.ProductAjaxUrl
            , { op: Configs.Operation.AddPresent, qty: qty, mainCode: mianItemCode }
            , function(data) {
                if (data) {
                    reBuildHeaderCartItemsCount(data);
                    if (data.PresentItem) {
                        CreatePresentHtml(data.PresentItem, mianItemCode);
                    }
                    if ($("tr[rel='presentTr']").length > 0) {
                        $("#persentTip").show();
                        $("#persentTableTitle").show();
                        $("#tbPresent").show();
                    } else {
                        $("#persentTip").hide();
                        $("#persentTableTitle").hide();
                        $("#tbPresent").hide();
                    }
                    checkGiftItem();
                }
            });
}

function UpdatePresentQuantity(o, i) {
    var mainCount = $("#mainItemCount" + o).val();
    var mainItemQuantity = $("#qty" + i).val();
    var perentCount = $.trim($("#presentQuantity" + o).val());
    if (mainCount.toString() != "NaN" &&
        mainItemQuantity.toString() != "NaN" &&
        perentCount.toString() != "NaN") {
        $("#persentQty" + o).empty();
        $("#persentQty" + o).append((mainItemQuantity - (mainItemQuantity % mainCount)) / mainCount * perentCount);
    }
}

function CreatePresentHtml(o, m) {
    var index = -1;
    var indexArr = $("input[name='presentMainItem" + m + "']");
    for (var i = 0; i < indexArr.length; i++) {
        if (indexArr[i].value != "NaN") {
            if (indexArr[i].value > index) {
                index = indexArr[i].value;
            }
        }
    }
    index++;
    var arr = [];
    if (!o.length) {
        arr.join(arr);
    } else {
        arr = o;
    }
    for (var i = 0; i < arr.length; i++) {
        index += i;
        var html = "<tr rel='presentTr' id='present" + index + "'>" +
                "<td class='c_select'>" +
                    "<input type='checkbox' checked='checked' value='" + index + "' name='cartGiftSingleCheckBox' />" +
                "</td>" +
                "<td class='c_info'>" +
                    "<a href='" + arr[i].Url + "' class='pic' title='" + arr[i].Name + "'>" +
                        "<img src='" + arr[i].ImagePath + "' title='" + arr[i].Name + "' alt='" + arr[i].Name + "' /></a>" +
                    "<ul>" +
                        "<li> " +
                            "<a href='" + arr[i].Url + "' title='" + arr[i].Name + "'>" + arr[i].Name + "</a>" + "</li>" +
                        "<li>" + arr[i].Modal + "</li>" +
                        "<li>" + arr[i].PrintSize + "</li>" +
                    "</ul>" +
                    "<input type='hidden' name='presentMainItem" + m + "' value='" + index + "' />" +
                    "<input type='hidden' id='mainItemCount" + index + "' value='" + arr[i].MainItemCount + "' />" +
                    "<input type='hidden' id='presentMainItemCode" + index + "' value='" + m + "' />" +
                    "<input type='hidden' id='presentItemCode" + index + "' value='" + arr[i].ItemCode + "' />" +
                    "<input type='hidden' id='presentQuantity" + index + "' value='" + arr[i].Quantity + "' />" +
                "</td>" +
                "<td class='c_num' id='persentQty" + index + "'>" + arr[i].Quantity + "</td>" +
            "</tr>";
        $(html).insertBefore($("#trPresentLine"));
    }
}

function deleteAllGift(idList, i, q) {
    if (!idList) {
        return;
    }
    var list = [];
    if (!idList.length) {
        list.push(idList);
    } else {
        list = idList;
    }
    doDeleteMulitItems(list);
    setQty(i, q, true);
}

function dealPrice() {
    //set price
    var tab, price = 0, qty = 0, totalPrice = 0, priceFinal = 0, totalPriceFinal = 0;
    var tabCount = $("#tabCount").attr("value") - 0;
    for (i = 0; i < tabCount; i++) {
        tab = $("#tab" + i);
        if (tab.length > 0) {
            if ($("#qty" + i).length > 0) {
                var sumPrice, sumPriceFinal;
                price = $("#price" + i).val() - 0;
                priceFinal = $("#priceFinal" + i).val() - 0;
                qty = $("#qty" + i).val() - 0;

                sumPrice = price * qty - 0;
                sumPriceFinal = priceFinal * qty - 0;
                totalPrice += sumPrice - 0;
                totalPriceFinal += sumPriceFinal - 0;

                $("#sumPrice" + i).html(Env.MoneySymbol + getString(sumPriceFinal));
            }
        }
    }
    //set total
    $("#totalPriceFinal").html(Env.MoneySymbol + getString(totalPriceFinal));
    $("#totalPrice").html(Env.MoneySymbol + getString(totalPrice));
    setOrderGift(totalPriceFinal);
    reBuildDiscountMessage(totalPrice, totalPriceFinal);
};

function setOrderGift(p) {
    if (p.toString() == "NaN") { return; }
    if (p <= 0) {
        $("#orderGiftTip").hide();
        $("#tbOrderGift").hide();
    } else {
        $.getJSON(Env.ProductAjaxUrl
        , { op: Configs.Operation.GetOrderGift, price: p }
        , function(data) {
            if (data) {
                if (data.PresentItem && data.PresentItem.length > 0) {
                    $("#sltOrderGift > option").each(function() {
                        if ($.trim($(this).val()) != "") {
                            $(this).remove();
                        }
                    });
                    for (var i = 0; i < data.PresentItem.length; i++) {
                        $("<option value='" + data.PresentItem[i].ItemCode + "'>" + data.PresentItem[i].Name + "</option>").appendTo("#sltOrderGift");
                    }
                }
                if ($("#sltOrderGift > option").length <= 1) {
                    $("#orderGiftTip").hide();
                    $("#tbOrderGift").hide();
                } else {
                    $("#orderGiftTip").show();
                    $("#tbOrderGift").show();
                }
            }
        });
    }
}

function changePresentStatus(i, b) {
    if (!i || i.toString() == "NaN") {
        return;
    }
    var m = $("#presentMainItemCode" + i).val();
    var c = $("#presentItemCode" + i).val();
    $.getJSON(
        Env.ProductAjaxUrl
        , { op: Configs.Operation.ChangePresent, itemcode: c, mainCode: m, spic: b }
        , function(data) {
            if (data && data.SuccessApply) {
                reBuildHeaderCartItemsCount(data);
            }
        }
    );
}

function getPrice(o) {
    o = o + '';
    var priceValue = $.trim(o.replace(Env.MoneySymbol, ""));
    var dbltemp = parseFloat(priceValue, 10);
    if (isNaN(dbltemp)) {
        dbltemp = 0;
    }
    dbltemp = dbltemp * 100;

    dbltemp = Math.floor(dbltemp);
    dbltemp = dbltemp;
    dbltemp = dbltemp / 100;

    return dbltemp;
};
function getString(v) {
    var num = 2;
    var a, b, c, i;
    a = v.toString();
    b = a.indexOf('.');
    c = a.length;
    if (num == 0) {
        if (b != -1)
            a = a.substring(0, b);
    }
    else {
        if (b == -1) {
            a = a + ".";
            for (i = 1; i <= num; i++)
                a = a + "0";
        }
        else {
            a = a.substring(0, b + num + 1);
            for (i = c; i <= b + num; i++)
                a = a + "0";
        }
    }

    return a;
};

