$(document).ready(function() {

    $("#ddlRegions0").bind("change", function() {
        ResetFieght($("#ddlRegions0").val());
    })

    var $_OrderOptionSelectId = $("#SubmmitOrder_htmInputOrderOptionSelectId");

    // 如果默认选中了一个收货地址
    $("input[type='radio'][name='SubmmitOrder$radl_Common_ShoppingCart_ConsigneeList']").each(function(i, obj) {
        if (obj.checked) {
            var shippingId = $(this).attr("value");
            ResetAddress(shippingId);
        }
    });
    // 收获地址列表选择触发事件
    $("input[type='radio'][name='SubmmitOrder$radl_Common_ShoppingCart_ConsigneeList']").bind('click', function() {

        var shippingId = $(this).attr("value");
        ResetAddress(shippingId);

    })

    // 配送方式选择触发事件
    $("input[name='shippButton']").bind('click', function() {
        var cartPrice = $("#SubmitOrder_ShopCartPriceLabel_v").val();
        var weight = $("#SubmitOrder_Weight").html();
        var regionId = $("#regionSelectorValue").val();
        var shippmodeId = $(this).attr("value");
        $("#htmShipp").val(shippmodeId);
        $.ajax({
            url: "PaymentHandler.aspx",
            type: 'post', dataType: 'json', timeout: 10000,
            data: { Action: 'CreatePaymentList', ModeId: shippmodeId, Total: cartPrice, Weight: weight, RegionId: regionId }, //CustomMade---------------------------------------------------------------------------------------
            success: function(resultData) {
                if (resultData.Status == "OK") {
                    // 显示配送方式
                    if ($("#SubmitOrder_ShipChargeFeeName").html() == "") {
                        $("#SubmitOrder_ShippingModePrice").html(resultData.Price);
                        $("#SubmitOrder_ShippingModePrice_v").val(resultData.Price_v);
                    }
                    else {
                        $("#SubmitOrder_ShippingModePrice").html("￥0.00");
                        $("#SubmitOrder_ShippingModePrice_v").val("0");
                    }
                    // 清空支付方式
                    $("#SubmitOrder_PaymentPriceLabel").html("￥0.00");
                    $("#SubmitOrder_PaymentPriceLabel_v").val("0");
                    $('#SubmmitOrder_htmInputPaymentId').val("");
                    ResetTatalPrice();
                    CreatePaymentTable(resultData.Payment);
                }
                else {
                    alert("格式化json数据或构造支付表格出错!");
                }
            }
        });

    })

    // 订单选项Radiolist触发事件
    $("input[name^='SubmmitOrder$list_Common_OrderOptions$_$dlstOrderLookupList$'][type='radio']").bind('click', function() {
        var $_this = $(this);
        $.ajax({
            url: "OrderOptionHandle.aspx",
            type: "post",
            dataType: "json",
            data: { lookupItemId: $_this.attr("value"), carTotal: $("#SubmitOrder_ShopCartPriceLabel_v").val() },
            cache: false,
            success: function(data, textStatus) {
                $.each(data, function(i, item) {
                    if (item.IsUserInputRequired != "undefined") {
                        var testID = document.getElementById($_this.attr("id"));
                        var testTable = testID.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.getElementsByTagName('div')[0].getElementsByTagName('table')[0];

                        if (item.IsUserInputRequired == "true") {
                            testTable.style.display = '';
                            testTable.getElementsByTagName('tr')[0].getElementsByTagName('td')[0].getElementsByTagName('input')[0].value = item.UserInputTitle;
                            testTable.getElementsByTagName('tr')[0].getElementsByTagName('td')[1].getElementsByTagName('input')[0].value = item.UserInputContent;
                        }
                        else {
                            testTable.style.display = 'none';
                        }
                        $("#SubmitOrder_OrderOptionName").html(item.Name);
                        if ($("#SubmitOrder_PackingChargeFreeName").html() == "") {
                            testTable.getElementsByTagName('tr')[0].getElementsByTagName('td')[1].getElementsByTagName('input')[1].value = item.AppendMoney_v;
                            ResetOptionPrice();
                        }
                        else {
                            $("#SubmitOrder_OrderOptionPriceLabel").html("￥0.00");
                            $("#SubmitOrder_OrderOptionPriceLabel_v").val("0");
                        }
                        ResetTatalPrice();
                    }
                    else {
                        testTable.style.display = 'none';
                    }
                });
            }
        });
    })

    // 使用优惠券
    $("#btnCoupon").click(function() {
    if (location.href.indexOf("?") > 0) {
            //这里排除快捷登陆过来的优惠券的使用
            if (location.href.split("?")[1].indexOf("shippingId") < 0) {
                alert("团购,限时抢购,积分兑换礼品不能使用优惠券")
                return false;
            }
        }
        var couponCode = $("#txtCouponCode").val();
        //var orderTotal = $("#SubmitOrder_OrderTotalPriceLabel_v").val();
        var orderTotal = $("#SubmitOrder_ShopCartPriceLabel_v").val();
        $.ajax({
            url: "SubmmitOrderHandler.aspx",
            type: 'post', dataType: 'json', timeout: 10000,
            data: { Action: "UseCoupon", OrderTotal: orderTotal, CouponCode: couponCode },
            success: function(resultData) {
                if (resultData.Status == "OK") {
                    $("#SubmitOrder_CouponName").html(resultData.CouponName);
                    $("#SubmitOrder_CouponPriceLabel").html(resultData.DiscountValue);
                    $("#SubmitOrder_CouponPriceLabel_v").val(resultData.DiscountValue_v);
                    $("#SubmmitOrder_htmlCouponCode").val(couponCode);
                    ResetTatalPrice();
                }
            },

            error: function(XMLHttpRequest, textStatus, errorThrown) {
                $("#SubmitOrder_CouponName").html("");
                $("#SubmitOrder_CouponPriceLabel").html("");
                $("#SubmitOrder_CouponPriceLabel_v").val("0");
                ResetTatalPrice();
                alert("您的优惠券编号无效, 或者您的商品金额不够");
            }
        });

    })
    // 创建订单
    $("#SubmmitOrder_btn_Common_ShoppingCart_CreateOrderButton").click(function() {
        // 验证配送地区选择了没有
        var selectedRegionId = GetSelectedRegionId();
        if (selectedRegionId == null || selectedRegionId.length == "" || selectedRegionId == "0") {
            alert("请选择您的收货人地址");
            return false;
        }

        var tel = $("#SubmmitOrder_txt_Common_ShoppingCart_ConsigneeTel").val();
        var handset = $("#SubmmitOrder_txt_Common_ShoppingCart_ConsigneeHandSet").val();
        if (tel == "" && handset == "") {
            alert("电话号码和手机号码要求二者必填其中一个");
            return false;
        }

        if (!PageIsValid()) {
            alert("部分信息没有通过检验，请查看页面提示");
            return false;
        }

        if ($("#htmShipp").val() == "") {
            alert("请选择配送方式");
            return false;
        }
        if ($("#SubmmitOrder_htmInputPaymentId").val() == "") {
            alert("请选择支付方式");
            return false;
        }
        if ($("#SubmmitOrder_txt_Common_ShoppingCart_GuestBook").val().length > 200) {
            alert("备注过长，请输入200字符以内的备注");
            return false;
        }
    })

    jQuery.myfn = {
        // 支付方式选择触发事件
        PaymentSelect: function(paymentId, name, charge, charge_v) {
            if ($("#SubmitOrder_ServiceChargeFreeName").html() == "") {
                $("#SubmitOrder_PaymentPriceLabel").html(charge);
                $("#SubmitOrder_PaymentPriceLabel_v").val(charge_v);
            }
            else {
                $("#SubmitOrder_PaymentPriceLabel").html("￥0.00");
                $("#SubmitOrder_PaymentPriceLabel_v").val("0");
            }
            // 支付方式ID
            $('#SubmmitOrder_htmInputPaymentId').val(paymentId);
            // 这里会最终算支付费用和金额,上面的计算实际没意思，不过安全其间先没删除
            ResetTatalPrice();
        },

        // 订单选项为下拉框选择触发事件
        OrderOptionSelectForDropDownList: function(SelectControl) {
            var testTable = SelectControl.parentNode.parentNode.parentNode.parentNode.parentNode.getElementsByTagName('div')[0].getElementsByTagName('table')[0];
            var index = SelectControl.selectedIndex;
            if (index == 0) {
                testTable.getElementsByTagName('tr')[0].getElementsByTagName('td')[1].getElementsByTagName('input')[1].value = "";
                testTable.style.display = 'none';
                ResetOptionPrice();
                ResetTatalPrice();
            }

            var val = SelectControl.options[index].value;

            $.ajax({
                url: "OrderOptionHandle.aspx",
                type: "post",
                dataType: "json",
                data: { lookupItemId: val, carTotal: $("#SubmitOrder_ShopCartPriceLabel_v").val() },
                cache: false,
                success: function(data, textStatus) {
                    $.each(data, function(i, item) {
                        if (item.IsUserInputRequired != "undefined") {

                            if (item.IsUserInputRequired == "true") {
                                testTable.style.display = '';
                                testTable.getElementsByTagName('tr')[0].getElementsByTagName('td')[0].getElementsByTagName('input')[0].value = item.UserInputTitle;
                                testTable.getElementsByTagName('tr')[0].getElementsByTagName('td')[1].getElementsByTagName('input')[0].value = item.UserInputContent;

                            }
                            else {
                                testTable.style.display = 'none';
                            }
                            $("#SubmitOrder_OrderOptionName").html(item.Name);
                            if ($("#SubmitOrder_PackingChargeFreeName").html() == "") {
                                testTable.getElementsByTagName('tr')[0].getElementsByTagName('td')[1].getElementsByTagName('input')[1].value = item.AppendMoney_v;
                                ResetOptionPrice();
                            }
                            else {
                                $("#SubmitOrder_OrderOptionPriceLabel").html("￥0.00");
                                $("#SubmitOrder_OrderOptionPriceLabel_v").val("0");
                            }
                            ResetTatalPrice();
                        }
                        else {
                            alert("登录失败！");
                        }
                    });
                }
            });
        }

    };

});

// 重置收货地址
function ResetAddress(shippingId)
{
    var ConsigneeName = $("#SubmmitOrder_txt_Common_ShoppingCart_ConsigneeName");
        var ConsigneeAddress = $("#SubmmitOrder_txt_Common_ShoppingCart_ConsigneeAddress");
        var ConsigneePostCode = $("#SubmmitOrder_txt_Common_ShoppingCart_ConsigneePostCode");
        var ConsigneeEmail = $("#SubmmitOrder_txt_Common_ShoppingCart_ConsigneeEmail");
        var ConsigneeTel = $("#SubmmitOrder_txt_Common_ShoppingCart_ConsigneeTel");
        var ConsigneeHandSet = $("#SubmmitOrder_txt_Common_ShoppingCart_ConsigneeHandSet");

        $.ajax({
            url: "SubmmitOrderHandler.aspx",
            type: 'post', dataType: 'json', timeout: 10000,
            data: { Action: "UserShippingAddressesGet", ShippingId: shippingId },
            success: function(resultData) {

                if (resultData.Status == "OK") {

                    $(ConsigneeName).val(resultData.ShipTo);
                    ConsigneeName.focus();

                    $(ConsigneeAddress).val(resultData.Address);
                    ConsigneeAddress.focus();

                    $(ConsigneePostCode).val(resultData.Zipcode);
                    ConsigneePostCode.focus();

                    $(ConsigneeEmail).val(resultData.EmailAddress);
                    ConsigneeEmail.focus();

                    $(ConsigneeTel).val(resultData.TelPhone);
                    ConsigneeTel.focus();

                    $(ConsigneeHandSet).val(resultData.CellPhone);
                    ConsigneeHandSet.focus();

                    ResetSelectedRegion(resultData.RegionId);
                    ConsigneeName.focus();
                    ResetFieght(resultData.RegionId);
                }
                else {
                    alert("收获地址选择出错，请重试!");
                }
            }
        });
}
// 订单选项金额总和
function ResetOptionPrice() {
    var x = document.getElementsByName("submmitorder_optionPrice");
    var price = eval(0.00);
    for (var i = 0; i < x.length; i++) {
        if (x[i].value != "")
            price = price + eval(x[i].value);
    }
    $("#SubmitOrder_OrderOptionPriceLabel_v").val(price);
    $.ajax({
        url: "SubmmitOrderHandler.aspx?action=FormatMoney&value=" + price + "&timestamp=" + new Date().getTime(),
        type: 'GET', dataType: 'json', timeout: 10000,
        success: function(resultData) {
            $("#SubmitOrder_OrderOptionPriceLabel").html(resultData.Money); 
            
        }
    });
}
// 总金额
function ResetTatalPrice() {
    var cartPrice = $("#SubmitOrder_ShopCartPriceLabel_v").val();
    var paymodePrice = $("#SubmitOrder_PaymentPriceLabel_v").val();
    var shippmodePrice = $("#SubmitOrder_ShippingModePrice_v").val();
    var orderOptionPrice = $("#SubmitOrder_OrderOptionPriceLabel_v").val();    
    var couponPrice = $("#SubmitOrder_CouponPriceLabel_v").val();    
    var paymentId =$('#SubmmitOrder_htmInputPaymentId').val();
    var total = eval(cartPrice) - couponPrice;

    if ($("#SubmitOrder_ShipChargeFeeName").html() == "")
        total = total + eval(shippmodePrice);
    if ($("#SubmitOrder_PackingChargeFreeName").html() == "")
        total = total + eval(orderOptionPrice);
    
    // 计算未有支付方式费用的总金额
    $.ajax({
        url: "SubmmitOrderHandler.aspx?action=FormatMoney&value=" + total + "&timestamp=" + new Date().getTime(),
        type: 'GET', dataType: 'json', timeout: 10000,
        success: function(resultData) {
            $("#SubmitOrder_OrderTotalPriceLabel").html(resultData.Money);
            $("#SubmitOrder_OrderTotalPriceLabel_v").val(resultData.Money_v);
            $("#SubmitOrder_PointTotal").html(resultData.Point);

            // 如果不免支付手续费 -- 不放在这个里面会不能得到最新的订单总金额
            if ($("#SubmitOrder_ServiceChargeFreeName").html() == "")
            {
                // 如果选择了支付方式
                if ($('#SubmmitOrder_htmInputPaymentId').val()!="")
                {
                    // 计算支付方式费用
                    $.ajax({
                        url: "PaymentHandler.aspx",
                        type: 'post', dataType: 'json', timeout: 10000,
                        data: {Action:'GetPaymentPrice', PaymentId: paymentId, Total: resultData.Money_v  },
                        success: function(resultDataPay) {
                            if (resultDataPay.Status == "OK") {
                                // 显示支付费用
                                $("#SubmitOrder_PaymentPriceLabel").html(resultDataPay.Price);
                                $("#SubmitOrder_PaymentPriceLabel_v").val(resultDataPay.Price_v);
                                total+=eval(resultDataPay.Price_v);
                                // 重新计算订单总金额
                                $.ajax({
                                    url: "SubmmitOrderHandler.aspx?action=FormatMoney&value=" + total + "&timestamp=" + new Date().getTime(),
                                    type: 'GET', dataType: 'json', timeout: 10000,
                                    success: function(resultData1) {
                                        $("#SubmitOrder_OrderTotalPriceLabel").html(resultData1.Money);
                                        $("#SubmitOrder_OrderTotalPriceLabel_v").val(resultData1.Money_v);
                                        $("#SubmitOrder_PointTotal").html(resultData1.Point);
                                    }
                                });
                            }
                        }
                    });
                }        
            }
    
        
        }
    });
}

// 运费
function ResetFieght(regionId) {
    var cartPrice = $("#SubmitOrder_ShopCartPriceLabel_v").val();
    var weight = $("#SubmitOrder_Weight").html();
    var shippmodeId = $("#htmShipp").val();
    $.ajax({
        url: "PaymentHandler.aspx",
        type: 'post', dataType: 'json', timeout: 10000,
        data: {Action:'CreatePaymentList', ModeId: shippmodeId, Total: cartPrice, Weight: weight, RegionId: regionId },
        success: function(resultData) {
            if (resultData.Status == "OK") {
                // 显示配送方式
                if ($("#SubmitOrder_ShipChargeFeeName").html() == "") {
                    $("#SubmitOrder_ShippingModePrice").html(resultData.Price);
                    $("#SubmitOrder_ShippingModePrice_v").val(resultData.Price_v);
                }
                else {
                    $("#SubmitOrder_ShippingModePrice").html("￥0.00");
                    $("#SubmitOrder_ShippingModePrice_v").val("0");
                }

                ResetTatalPrice();
            }
            else {
                alert("格式化json数据或构造支付表格出错!");
            }
        }
    });
}


//构造支付方式表格类;
var CreatePaymentTable = function(PaymentData) {
    var PaymentBody = document.getElementById("PaymentList");
    PaymentBody.innerHTML = "";
    PaymentTable = document.createElement("table");
    PaymentTableBody = document.createElement("tbody");

    PayTableCurrent_Row0 = document.createElement("tr");
    for (var hCell = 0; hCell <= 2; hCell++) {
        PayTableCurrent_hCell = document.createElement("th");
        if (hCell == 0) {
            PayTableCurrent_hCell.innerHTML = "选择";
            PayTableCurrent_hCell.setAttribute("width", "5%");
            //PayTableCurrent_hCell.setAttribute("align", "center");
        }
        if (hCell == 1) {
            PayTableCurrent_hCell.innerHTML = "支付方式";
            PayTableCurrent_hCell.setAttribute("width", "20%");
            //PayTableCurrent_hCell.setAttribute("align", "center");
        }
        if (hCell == 2) {
            PayTableCurrent_hCell.innerHTML = "详细介绍";
            PayTableCurrent_hCell.setAttribute("width", "65%");
        }
        PayTableCurrent_Row0.appendChild(PayTableCurrent_hCell);
    }
    PaymentTableBody.appendChild(PayTableCurrent_Row0);
    if (PaymentData != undefined)
    {
        for (var nRows = 0; nRows < PaymentData.length; nRows++) {
            PayTableCurrent_Row = document.createElement("tr");

            for (var nCells = 0; nCells <= 2; nCells++) {
                PayTableCurrent_Cell = document.createElement("td");
                if (nCells == 0) {
                    PayTableCurrent_Cell.innerHTML = "<input id=SubmmitOrder_grd_Common_ShoppingCart_PaymentTable___grdPayment_"
                        + PaymentData[nRows].ModeId + " type=radio value=" + PaymentData[nRows].ModeId
                        + " name=payButton onclick=\"$.myfn.PaymentSelect('" + PaymentData[nRows].ModeId + "','" + PaymentData[nRows].Name + "','" + PaymentData[nRows].Charge + "','" + PaymentData[nRows].Charge_v + "');\">";
                    PayTableCurrent_Cell.setAttribute("width", "5%");
                    //PayTableCurrent_Cell.setAttribute("align", "center");
                }
                if (nCells == 1) {
                    PayTableCurrent_Cell.innerHTML = PaymentData[nRows].Name;
                    PayTableCurrent_Cell.setAttribute("width", "20%");
                    //PayTableCurrent_Cell.setAttribute("align", "center");
                }
                if (nCells == 2) {
                    PayTableCurrent_Cell.innerHTML = PaymentData[nRows].Description.replace(/&amp;/g, '&').replace(/&quot;/g, '\"').replace(/&lt;/g, '<').replace(/&gt;/g, '>');
                }
                PayTableCurrent_Row.appendChild(PayTableCurrent_Cell);
            }
            PaymentTableBody.appendChild(PayTableCurrent_Row);
        }
    }
    PaymentTable.appendChild(PaymentTableBody);
    PaymentBody.appendChild(PaymentTable);
    PaymentTable.setAttribute("cellSpacing", "0");
    PaymentTable.setAttribute("class", "PaymentListStyle");
    if (document.all) { PaymentTable.setAttribute("className", "PaymentListStyle"); }
    return PaymentTable;
}