var xmlHttp;
$(document).ready(function() {

    // 配送方式选择触发事件
    $("input[name='shippButton']").bind('click', function() {
        var cartPrice = $("#SubmitOrder_ShopCartPriceLabel_v").val();
        var weight = $("#SubmitOrder_Weight").html();
        var regionId = $("#SubmmitOrder_drop_Common_Userinfo_Location_dropRegions_1 option:selected").val();
        var shippmodeId = $(this).attr("value");
        $.ajax({
            url: "PaymentHandler.aspx",
            type: 'post', dataType: 'json', timeout: 10000,
            data: { ModeId: shippmodeId, Total: cartPrice, Weight: weight, RegionId: regionId },
            success: function(resultData) {
                if (resultData.Status == "OK") {
                    // 显示配送方式
                    $("#SubmitOrder_ShippingModeName").html(resultData.ShippingName);
                    $("#SubmitOrder_ShippingModePrice").html(resultData.Price);
                    $("#SubmitOrder_ShippingModePrice_v").val(resultData.Price_v);

                    if ($("#SubmitOrder_ShipChargeFeeName").html() != "") {
                        $("#SubmitOrder_ShipChargeFeePriceLabel").html(resultData.Price);
                        $("#SubmitOrder_ShipChargeFeePriceLabel_v").val(resultData.Price_v);
                    }
                    // 清空支付方式
                    $("#SubmitOrder_PaymentName").html("");
                    $("#SubmitOrder_PaymentPriceLabel").html("");
                    $("#SubmitOrder_PaymentPriceLabel_v").val("0");
                    $('#SubmmitOrder_htmInputPaymentId').attr({ 'value': "" });
                    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") },
            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.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);
                        $("#SubmitOrder_OrderOptionPriceLabel").html(item.AppendMoney);
                        $("#SubmitOrder_OrderOptionPriceLabel_v").val(item.AppendMoney_v);

                        if ($("#SubmitOrder_PackingChargeFreeName").html() != "") {
                            $("#SubmitOrder_PackingChargeFreePriceLabel").html(item.AppendMoney);
                            $("#SubmitOrder_PackingChargeFreePriceLabel_v").val(item.AppendMoney_v);
                        }

                        ResetTatalPrice()
                    }
                    else {
                        testTable.style.display = 'none';
                    }
                });
            }
        });
    })

    // 使用优惠券
    $("#btnCoupon").click(function() {
        var couponCode = $("#txtCouponCode").val();
        var orderTotal = $("#SubmitOrder_OrderTotalPriceLabel_v").val();
        $("#SubmmitOrder_htmlCouponCode").val(couponCode);
        $.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);
                    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() {
        if (!PageIsValid())
            return false;

        if ($("input[@name='shippButton'][@checked]").val() == undefined) {
            alert("请选择配送方式");
            return false;
        }
        if ($("#SubmitOrder_PaymentName").html() == "") {
            alert("请选择支付方式");
            return false;
        }


    })

    jQuery.myfn = {
        // 支付方式选择触发事件
        PaymentSelect: function(gaeway, name, charge, charge_v) {
            $("#SubmitOrder_PaymentName").html(name);
            $("#SubmitOrder_PaymentPriceLabel").html(charge);
            $("#SubmitOrder_PaymentPriceLabel_v").val(charge_v);
            $('#SubmmitOrder_htmInputPaymentId').attr({ 'value': gaeway });

            if ($("#SubmitOrder_ServiceChargeFreeName").html() != "") {
                $("#SubmitOrder_ServiceChargeFreePriceLabel").html(charge);
                $("#SubmitOrder_ServiceChargeFreePriceLabel_v").val(charge_v);
            }
            ResetTatalPrice();
        },

        // 订单选项为下拉框选择触发事件
        OrderOptionSelectForDropDownList: function(SelectControl) {

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

            var testTable = SelectControl.parentNode.parentNode.parentNode.parentNode.parentNode.getElementsByTagName('div')[0].getElementsByTagName('table')[0];

            $.ajax({
                url: "OrderOptionHandle.aspx",
                type: "post",
                dataType: "json",
                data: { lookupItemId: 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);
                            $("#SubmitOrder_OrderOptionPriceLabel").html(item.AppendMoney);
                            $("#SubmitOrder_OrderOptionPriceLabel_v").val(item.AppendMoney_v);

                            if ($("#SubmitOrder_PackingChargeFreeName").html() != "") {
                                $("#SubmitOrder_PackingChargeFreePriceLabel").html(item.AppendMoney);
                                $("#SubmitOrder_PackingChargeFreePriceLabel_v").val(item.AppendMoney_v);
                            }

                            ResetTatalPrice()
                        }
                        else {
                            alert("登陆失败！");
                        }
                    });
                },
                error: function(XMLHttpRequest, textStatus, errorThrown) {
                    testTable.style.display = 'none';
                    $("#SubmitOrder_OrderOptionName").html("");
                    $("#SubmitOrder_OrderOptionPriceLabel").html("");
                }
            });
        }

    };

});

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 total = eval(cartPrice) - couponPrice;

    if ($("#SubmitOrder_ShipChargeFeeName").html() == "")
        total = total + eval(shippmodePrice);
    if ($("#SubmitOrder_ServiceChargeFreeName").html() == "")
        total = total + eval(paymodePrice);
    if ($("#SubmitOrder_PackingChargeFreeName").html() == "")
        total = total + eval(orderOptionPrice);         

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

//构造支付方式表格类;
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("td");
        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_Row0.appendChild(PayTableCurrent_hCell);
    }
    PaymentTableBody.appendChild(PayTableCurrent_Row0);

    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].Gateway + "','" + 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;
            }
            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;
}

//function xmlhttpRequest(e) {
//    var url = "PaymentHandler.aspx?ModeId=" + escape(e.toString()); //要请求的服务端地址
//    if (window.XMLHttpRequest) {
//        xmlHttp = new XMLHttpRequest();
//    }
//    else if (window.ActiveXObject) {
//        xmlHttp = new ActiveXObject("Microsoft.XMLHttp");
//    }
//    if (xmlHttp) {
//        try {
//            xmlHttp.open("Post", url, true);
//            xmlHttp.onreadystatechange = Update_Payment;
//            xmlHttp.send(null);
//        } catch (exception) {
//            alert("请求的服务器文件不存在或请求超时!");
//        }
//    }
//}
//function Update_Payment() {
//    if (xmlHttp.readyState == 4) {
//        if (xmlHttp.status == 200 || xmlHttp.status == 0) {
//            var resp = xmlHttp.responseText;
//            if (resp.length == 4) {
//                alert("当前配送方式下无匹配的支付方式!");
//                document.getElementById("PaymentList").innerHTML = "";
//                return false;
//            }
//            else {
//                try {
//                    var json = eval('(' + resp + ')');
//                    var PaymentTable = new CreatePaymentTable(json);
//                    document.getElementById("PaymentList").appendChild(PaymentTable);
//                } catch (exception) {
//                    alert("格式化json数据或构造支付表格出错!");
//                }
//            }
//        }
//        else {
//            alert("请求超时!");
//        }
//    }
//}