var hasSkus, minQuantity, maxQuantity;
var islogin = "true";
$(document).ready(function() {
    $("#productSkuSelector select").bind("change", function() { SelectSkus($(this).attr("id")); });
    $("#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());
    $.ajax({
        url: "ShoppingHandler.aspx?action=IsLogin&timestamp=" + new Date().getTime(),
        type: 'GET', dataType: 'json', timeout: 10000,
        success: function(resultData) {
            if (resultData.Status == "False") {
                islogin = "false";
            }
        }
    });
});


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;
    }
    if (islogin == "false") {
        alert("只有会员并且登录后才能进行限时抢购！");
        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 allOerderCount = parseInt($("#ProductDetails_lit_Common_ViewProduct_OrderCount").html()) + parseInt($("#buyAmount").val());
//    var maxCount = parseInt($("#ProductDetails_lit_Common_ViewProduct_Count").html());

//    if (allOerderCount > maxCount) {
//        alert("订购数量超过了此次团购活动的订购总数，请修改订购数量");
//        return;
//    }

    var attributeFill = GetAttributeFill();

    var added = false;

    var cartForm = window.open(applicationPath + "/SubmmitOrder.aspx?buyAmount=" + quantity + "&productSku=" + $("#productDetails_sku_v").val() + "&AttributeFill=" + attributeFill + "&from=countDown", "SubmmitOrder");
    if (cartForm != null && !cartForm.closed) cartForm.focus();
}


// 获取当前填写的属性值
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;
}
