var hasSkus, minQuantity, maxQuantity;
$(document).ready(function() {
    $("#productSkuSelector select").bind("change", function() { SelectSkus($(this).attr("id")); });
    $("#productAccessoriesSelector input[type=checkbox]").bind("click", function() { SelectAccessory($(this).attr("id"), $(this).attr("checked")); });
    $("#buyButton").bind("mouseover", function() { CheckSelector(); });
    $("#buyButton").bind("click", function() { AddCurrentProductToCart(); });
    $("#buyAmount").bind("keyup", function() { ChangeBuyAmount(); });
    hasSkus = ($("#productSkuSelector").length > 0);
    minQuantity = eval($("#minQuantity").val());
    maxQuantity = eval($("#maxQuantity").val());
});

function SelectAccessory(selectorId, accessoryChecked) {
    var valueHidden = $("#" + selectorId.replace("productAccessoriesSelector_chk_", "productAccessoriesSelector_v_"));
    var accessryPrice = eval($(valueHidden).val());

    if (accessoryChecked) {
        // 选择了配件 商品总价=当前金额+选择的配件金额
        UpdateTotalPrice(GetProductTotal() + accessryPrice * eval($("#buyAmount").val()));
    }
    else {
        // 取消选择了配件 商品总价=当前金额-选择的配件金额
        UpdateTotalPrice(GetProductTotal() - accessryPrice * eval($("#buyAmount").val()));
    }
}

function SelectSkus(currentSelector) {
    
    var selectedValue = $("#" + currentSelector).val();
    var selectedOptions = "";
    var allSelected = (selectedValue.length > 0);

    if (allSelected) {
        $.each($("#productSkuSelector select"), function(i, item) {
            if ($(item).val().length == 0) {
                allSelected = false;
                return;
            }
            else {
                selectedOptions += $(item).val() + ",";
            }
        });
    }
    else {
        ResetCurrentSku("", "", "0", "");
    }

    if (allSelected) {
        selectedOptions = selectedOptions.substring(0, selectedOptions.length - 1);
        var skuSelectorData = GetSelectorData();
        
        $.ajax({
            url: "ShoppingHandler.aspx",
            type: 'post', dataType: 'json', timeout: 10000,
            data: { action: "GetSkuByOptions", productId: skuSelectorData.CurrentProductId, options: selectedOptions },
            success: function(resultData) {
                if (resultData.Status == "OK") {
                    ResetCurrentSku(resultData.SKU, resultData.Stock, resultData.SKUPrice, selectedOptions,resultData.Status);
                }
                else {
                    ResetCurrentSku("", "", "0", "",resultData.Status); //带服务端返回的结果，函数里可以根据这个结果来显示不同的信息
                }
            }
        });
    }
}

function ResetCurrentSku(sku, stock, price, options,result) {
    // 页面显示的项目
    // 当前货号
    var productDetailSku = $("#productDetails_sku");
    var productDetailSku_v = $("#productDetails_sku_v");
    // 当前库存数量
    var productDetailStock = $("#productDetails_Stock");

    // 客户选择的内容
    // 当前规格的价格
    var currentSkuPrice = $("#productSkuSelector_Price");
    // 当前规格的货号
    var currentSku = $("#productSkuSelector_Sku");

    var skuPrice = eval($(currentSkuPrice).val());
    
    if (result!="OK") {
        
        if (skuPrice > 0) {
            UpdateTotalPrice(GetProductTotal() - skuPrice * eval($("#buyAmount").val()));
        }

        // 没有匹配的规格
        $(productDetailSku).html("");
        $(productDetailSku_v).val("");
        $(productDetailStock).html("");
        $(currentSkuPrice).val("0");
        $(currentSku).val("");

        SetToWarnStatus(result);
    }
    else {
        $(productDetailSku).html(sku);
        $(productDetailSku_v).val(sku);
        $(productDetailStock).html(stock);
        $(currentSkuPrice).val(price);
        $(currentSku).val(sku);
        UpdateTotalPrice(GetProductTotal() - skuPrice * eval($("#buyAmount").val()) + eval(price) * eval($("#buyAmount").val()));
        SetToOkStatus(options, price);
    }
}

function UpdateTotalPrice(totalPrice) {
    $("#productDetails_Total_v").val(totalPrice);
    RefreshTotalPriceDisplay(totalPrice);
}

function RefreshTotalPriceDisplay(totalPrice) {
    $.ajax({
        url: "ShoppingHandler.aspx?action=FormatMoney&value=" + totalPrice + "&timestamp=" + new Date().getTime(),
        type: 'GET', dataType: 'json', timeout: 10000,
        success: function(resultData) {
            $("#productDetails_Total").html(resultData);
        }
    });
}

function SetToWarnStatus(result) {
    var skuSelectorData = GetSelectorData();
    var selectorMsg = $("#productSkuSelector_Msg");

    RemoveMsgClass();

    selectorMsg.addClass(skuSelectorData.WarnTextCssClass);

    if (result == "1") {
        // 没有匹配的规格
       selectorMsg.text("此商品没有您选择的规格!");
    }
    else if (result == "2") {
        // 商品已经下架
        selectorMsg.text("此商品已经下架，暂时不能购买!");
    }
    else if (result == "3") {
        // 商品库存不足
        selectorMsg.text("您选择的规格库存不足!");
    }
    else if (result == ""){
        // 如果没有选择
        selectorMsg.text("请选择商品规格!");
    }
    else    {
        selectorMsg.text("");
    }
    
}

function SetToOkStatus(options, price) {
    var skuSelectorData = GetSelectorData();
    var selectorMsg = $("#productSkuSelector_Msg");
    var displayText = "您当前选择的是:";

    RemoveMsgClass();
    $(selectorMsg).addClass(skuSelectorData.ContainerOkCssClass);

    if (price > 0) {
        $.ajax({
            url: "ShoppingHandler.aspx?action=FormatMoney&value=" + price + "&timestamp=" + new Date().getTime(),
            type: 'GET', dataType: 'json', timeout: 10000,
            success: function(resultData) {
                $(selectorMsg).html(displayText + options + "&nbsp;+" + resultData);
            }
        });
    }
    else {
        $(selectorMsg).html(displayText + options);
    }
}

function GetProductTotal() {
    return eval($("#productDetails_Total_v").val());
}

function RemoveMsgClass() {
    var selectorMsg = $("#productSkuSelector_Msg");
    var c = $(selectorMsg).attr("class");

    if (c) {
        $(selectorMsg).removeClass(c);
    }
}

function GetSelectorData() {
    return eval("(" + $("#productSkuSelector_SkuSelectorData").val() + ")");
}

// 当鼠标移动到购买按钮以后根据规格当前的选择状态更改购买按钮的样式和单击事件
function CheckSelector() {
    var buyButton = $("#buyButton");

    if (hasSkus) {
        var currentSku = $("#productSkuSelector_Sku");

        if (currentSku.val().length == 0) {
            $(buyButton).css("cursor", "auto");
            if ($("#productSkuSelector_Msg").text() == "")
                SetToWarnStatus("");
        }
        else {
            $(buyButton).css("cursor", "pointer");
        }
    }
    else {
        $(buyButton).css("cursor", "pointer");
    }
}

// 购买按钮单击事件
function AddCurrentProductToCart() {
    if (!ValidateBuyAmount()) {
        return;
    }
    var currentSku = $("#productSkuSelector_Sku");
    if (currentSku.val() != undefined && currentSku.val().length == 0) {
        alert("请选择商品规格");
        return;
    }
    var quantity = parseInt($("#buyAmount").val());
    var stock = parseInt($("#productDetails_Stock").html());
    if (quantity > stock) {
        alert("商品库存不足 " + quantity + " 件，请修改购买数量!");
        return;
    }
     
    var accessories = GetSelectedAccessories();
    var attributeFill = GetAttributeFill();
    
    var added = false;
    
    $.ajax({
        url: "ShoppingHandler.aspx",
        type: 'post', dataType: 'json', timeout: 10000,
        data: { action: "AddToCartBySkus", quantity: quantity, productSku: $("#productDetails_sku_v").val(), accessorySkus: accessories, AttributeFill : attributeFill },
        async: false,
        success: function(resultData) {
        
            
            
            if (resultData.Status == "OK") { 
                var cartForm = window.open(applicationPath + "/ShoppingCart.aspx", "ShoppingCart");
                if (cartForm != null && !cartForm.closed) cartForm.focus();
                added = true;
            }
            else if (resultData.Status == "0") {
                // 商品已经下架
                alert("此商品已经下架，暂时不能购买");
            }
            else if (resultData.Status == "1") {
                // 商品库存不足
                alert("商品库存不足 " + quantity + " 件，请修改购买数量!");
            }
            else if (resultData.Status == "2") {
                var msg = "以下配件已经下架或库存不足，不能加入购物车：\r\n\r\n";
                $.each(resultData.Items, function(i, item) {
                    msg += item.DisplayName + "\r\n";
                });
                alert(msg);
            }
            else {
                // 抛出异常消息
                alert(resultData.Status);
            }
        }
    });

    if (added) {
        var cartForm = window.open(applicationPath + "/ShoppingCart.aspx", "ShoppingCart");
        if (cartForm != null && !cartForm.closed) cartForm.focus();
    }
}

// 获取当前选择的所有配件的货号，用半角逗号分割多个货号
function GetSelectedAccessories() {
    var accessories = "";
    var skuHidden;
    
    $.each($("#productAccessoriesSelector input[type=checkbox]"), function(i, item) {
        if ($(item).attr("checked")) {
            skuHidden = $("#" + $(item).attr("id").replace("productAccessoriesSelector_chk_", "productAccessoriesSelector_sku_"));
            accessories += $(skuHidden).val() + ",";
        }
    });

    if (accessories.length > 0) {
        accessories = accessories.substring(0, accessories.length - 1);
    }

    return accessories;
}
// 获取当前填写的属性值
function GetAttributeFill() {
    var attributes = "";
    var attName;
    $.each($("#productAttributesFill input[type=text]"), function(index, item) {
        var itemval = $(item).val();
        if (itemval != "") {
            attName = $("#" + $(item).attr("id").replace("AttributesFill_Value", "AttributesFill_Name"));
            if (itemval.length > 20)
                itemval = itemval.substring(0, 20);
            attributes += $(attName).html() + itemval + ",";
        }
    })
    if (attributes.length > 0)
        attributes = attributes.substring(0, attributes.length - 1);
    return attributes;
    
}

// 购买数量变化以后的处理
function ChangeBuyAmount() {
    if (ValidateBuyAmount()) {
        var quantity = parseInt($("#buyAmount").val());
        var oldQuantiy=parseInt($("#oldBuyNumHidden").val());
        UpdateTotalPrice(GetProductTotal() / oldQuantiy * quantity);
        $("#oldBuyNumHidden").attr("value",quantity);
    }
}

// 检测用户输入的购买数量
function ValidateBuyAmount() {
    // 检查当前购买数量是否满足最小/最大购买数量
    // 库存数量在点击购买按钮提交时检测
    var buyAmount = $("#buyAmount");
    if ($(buyAmount).val().length == 0) {
        alert("请先填写购买数量!");
        return false;
    }
    if ($(buyAmount).val().length > 5) {
        alert("填写的购买数量不能超过99999!");
        var str = $(buyAmount).val();
        $(buyAmount).val(str.substring(0, 5));
        return false;
    }
    var amountReg = /^[1-9]d*|0$/;
    if (!amountReg.test($(buyAmount).val())) {
        alert("请填写正确的购买数量!");
        return false;
    }

    var quantity = parseInt($(buyAmount).val());
    if (quantity < minQuantity) {
        alert("此商品一次最少必须要购买" + minQuantity + "件!");
        $("#minQuantity").val(minQuantity);
        
        return false;
    }

    if (maxQuantity > 0 && quantity > maxQuantity) {
        alert("此商品一次最多只能购买" + maxQuantity + "件!");
        $("#maxQuantity").val(maxQuantity);
        
        return false;
    }

    return true;
}
