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(); });
    $("#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);
    }
    else {
        // 取消选择了配件 商品总价=当前金额-选择的配件金额
        UpdateTotalPrice(GetProductTotal() - accessryPrice);
    }
}

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);
                }
                else {
                    ResetCurrentSku("", "", "0", "");
                }
            }
        });
    }
}

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

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

    var skuPrice = eval($(currentSkuPrice).val());

    if (sku.length == 0) {
        if (skuPrice > 0) {
            UpdateTotalPrice(GetProductTotal() - skuPrice);
        }

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

        SetToWarnStatus();
    }
    else {
        $(productDetailSku).html(sku);
        $(productDetailStock).html(stock);
        $(currentSkuPrice).val(price);
        $(currentSku).val(sku);

        UpdateTotalPrice(GetProductTotal() - skuPrice + eval(price));
        SetToOkStatus(options, price);
    }
}

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

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() {
    var skuSelectorData = GetSelectorData();
    var selectorMsg = $("#productSkuSelector_Msg");

    RemoveMsgClass();

    $(selectorMsg).addClass(skuSelectorData.WarnTextCssClass);
    $(selectorMsg).html(skuSelectorData.WarnText);
}

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");
    $(buyButton).unbind("click");

    if (hasSkus) {
        var currentSku = $("#productSkuSelector_Sku");
        if ($(currentSku).val().length == 0) {
            $(buyButton).css("cursor", "auto");
            SetToWarnStatus();
        }
        else {
            $(buyButton).bind("click", function() { AddCurrentProductToCart(); });
            $(buyButton).css("cursor", "pointer");
        }
    }
    else {
        $(buyButton).bind("click", function() { AddCurrentProductToCart(); });
        $(buyButton).css("cursor", "pointer");
    }
}

// 购买按钮单击事件
function AddCurrentProductToCart() {
    if (!ValidateBuyAmount()) {
        return;
    }
    
    var quantity = parseInt($("#buyAmount").val());
    var stock = eval($("#productDetails_Stock").val());

    if (quantity > stock) {
        alert("商品库存不足 " + quantity + " 件，请修改购买数量!");
        return;
    }

    var accessories = GetSelectedAccessories();

    $.ajax({
        url: "ShoppingHandler.aspx",
        type: 'post', dataType: 'json', timeout: 10000,
        data: { action: "AddToCartBySkus", quantity: quantity, productSku: $("#productDetails_sku").html(), accessorySkus: accessories },
        success: function(resultData) {
            if (resultData.Status == "OK") {
                var cartForm = window.open(applicationPath + "/ShoppingCart.aspx", "ShoppingCart");
                if (cartForm != null && !cartForm.closed) cartForm.focus();
            }
            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);
            }
        }
    });
}

// 获取当前选择的所有配件的货号，用半角逗号分割多个货号
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 ChangeBuyAmount() {
    if (ValidateBuyAmount()) {
        var quantity = parseInt($("#buyAmount").val());
        RefreshTotalPriceDisplay(GetProductTotal() * quantity);
    }
}

// 检测用户输入的购买数量
function ValidateBuyAmount() {
    // 检查当前购买数量是否满足最小/最大购买数量
    // 库存数量在点击购买按钮提交时检测
    var buyAmount = $("#buyAmount");
    if ($(buyAmount).val().length == 0) {
        alert("请先填写购买数量!");
        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;
}