﻿/// <reference path="jQuery.IntelliSense.js" />

var pageLinkUrl = "";
var ajaxUrl = "ajaxServer/ForOrderInfo.aspx";
var isConOpen = false;
var isPayTypeAndShipTypeOpen = false;
var isInvoiceOpen = false;
var isRemarkOpen = false;

var ffAlertTxt = '您的输入含有非法字符，请检查！';
function checkSubmitError(bakValue, obj) {
    if (bakValue != null) {
        if (bakValue.indexOf('error_') == 0) {
            var newd = document.createElement("span");
            newd.name = 'errorInfo';
            newd.style.cssText = 'color:red;';
            if (bakValue.length > 6)
            { bakValue = bakValue.substr(6); }
            else { bakValue = '程序发生了未知错误，请再次尝试！'; }
            newd.innerHTML = bakValue;
            obj.appendChild(newd);
            return false;
        }
        return true;
    }
    return true;
}
function clearSubmitError(obj) {
    if (obj.parentNode.childNodes.length > 0) {
        if (obj.parentNode.lastChild.name == 'errorInfo') {
            obj.parentNode.removeChild(obj.parentNode.lastChild);
        }
    }
}

//----------------------------收货人信息-------------------------------------

//当前获取到的地址对象
var address;
function ShowAddLable() {
    if ($("#otxtAddress").val().length <= 1 || $("#otxtReceiver").val().length <= 1) {
        OpenAddrEdit();
    } else {
        $("#lbAddress").text($("#otxtAddress").val());
        $("#lbReceiver").text($("#otxtReceiver").val());
        $("#lbPostCode").text($("#otxtPostCode").val());
        $("#lbPhone").text($("#otxtPhone").val());
        $("#lbMobile").text($("#otxtMobile").val());

    }
}
//根据id获取地址信息
function GetAddress(addid) {
    $.ajax({
        url: '/Ashx/address.ashx?action=getaddress',
        type: 'Post',
        timeout: 8000,
        async: false,
        cache: false,
        data: { 'addid': addid },
        error: function () {
            alert('获取默认送货地址失败！');
            //提示无默认地址
            return 0;
        },
        success: function (result) {
            if (result.Result) {
                address = $.parseJSON(result.Data);
            }
            else {
                alert(result.Message);
                return 0;
            }
        }
    }
    );
}
//当前默认addid
var selAddressId = $("#addid").val();
var maxAddressShowCount = 5;
var isAddressMoreOpen = false;
//客户完整地址列表
var AddressList;
function GetAddressList() {
    $.ajax({
        url: '/Ashx/address.ashx?action=getaddresslist',
        type: 'Post',
        timeout: 8000,
        async: false,
        cache: false,
        data: {},
        error: function () {
            alert('获取默认送货地址失败！');
            //提示无默认地址
            return 0;
        },
        success: function (result) {
            if (result.Result) {
                var addlist = $.parseJSON(result.Data);
                AddressList = addlist;
                var html = '';
                if (addlist.length > 0) {
                    // html += "<div class='cydz'>";
                    //  html += "<b>常用地址</b>";
                    html += "<ul>";
                    var isHaveMore = false;
                    for (var i = 0; i < addlist.length; i++) {
                        if (i + 1 > maxAddressShowCount && !isHaveMore) {
                            isHaveMore = false;
                            html += "</ul>";
                            html += "<div style='text-align:center'><a href='#none' class='remark' onclick=\"var dobj=g('cydz_more');if(isAddressMoreOpen){isAddressMoreOpen=false;dobj.style.display='none'}else{isAddressMoreOpen=true;dobj.style.display=''}\">更多常用地址</a></div>";
                            html += "<ul id='cydz_more' " + (isAddressMoreOpen ? "" : "style='display:none'") + ">";
                        }
                        html += "<li id='addrIi" + addlist[i].UniqueID + "'" + ((addlist[i].UniqueID == selAddressId) ? " class='xz'" : "") + ">";
                        // html += "<table cellspacing='0' cellpadding='0' border='0' style='width:98%'><tr>";
                        html += "<input class='addrlist' value='" + addlist[i].UniqueID + "' id='addr_" + addlist[i].UniqueID + "' type='radio' name='rbtnAddr' onclick=\"selectAddress('" + addlist[i].UniqueID + "');\" " + ((addlist[i].UniqueID == selAddressId) ? " checked" : "") + " />";
                        html += "<label for='addr_" + addlist[i].UniqueID + "'><strong>" + addlist[i].Address + "</strong>&nbsp;</label>";
                        html += "<a href='javascript:void(0)' class='remark' onclick=\"DeleteAddress('" + addlist[i].UniqueID + "');\">[删除]</a>"
                        //  html += "</tr></table>";
                        html += "</li>";
                    }
                    html += "</ul>";
                    //   html += "</div>";
                }
                $("#addlist").html(html);
            }
            else {
                alert(result.Message);
                return 0;
            }
        }
    }
    );

}

function SaveToAddressList() {
    if (check_con()) {
        var address = $("#txtAddress").val();
        var receiver = $("#txtReceiver").val();
        var postcode = $("#txtPostCode").val();
        var phone = $("#txtPhone").val();
        var mobile = $("#txtMobile").val();
        var uniqueid = $("#addid").val();
        var provinceid = $("#Select1").val();
        var cityid = $("#Select2").val();
        var areaid = $("#Select3").val();
        for (var i = 0; i < AddressList.length; i++) {
            if (receiver == AddressList[i].Receiver && address == AddressList[i].Address) {
                if (confirm("已存在相同收件人的名称和地址确认保存?")) {
                    SaveAddrToServer();
                    return;
                } else { return; }
            }
        }
        SaveAddrToServer();
    } else { return false; }
}
var provincename, cityname, areaname;
function GetSelectedAddress() {
    provincename = $("select[name='Select1'] option[selected]").text();
    cityname = $("select[name='Select2'] option[selected]").text();
    areaname = $("select[name='Select3'] option[selected]").text();
}
//把编辑页面的信息保存到当前页面表单中以便提交
function SaveAddress() {
    if (check_con()) {
        GetSelectedAddress();
        $("#otxtAddress").val(provincename + cityname + areaname + $("#txtAddress").val());
        $("#otxtReceiver").val($("#txtReceiver").val());
        $("#otxtPostCode").val($("#txtPostCode").val());
        $("#otxtPhone").val($("#txtPhone").val());
        $("#otxtMobile").val($("#txtMobile").val());
        $("#addid").val($("#litAddressID").val());
        $("#otxtProvinceID").val($("#Select1").val());
        $("#otxtCityID").val($("#Select2").val());
        $("#otxtAreaID").val($("#Select3").val());
        ShowAddLable();
        CloseAddrEdit();
    } else { return false; }
}

function SaveAddrToServer() {

    var address = $("#txtAddress").val();
    var receiver = $("#txtReceiver").val();
    var postcode = $("#txtPostCode").val();
    var phone = $("#txtPhone").val();
    var mobile = $("#txtMobile").val();
    var uniqueid = $("#addid").val();
    var provinceid = $("#Select1").val();
    var cityid = $("#Select2").val();
    var areaid = $("#Select3").val();
    var html = '{"UniqueID":"' + uniqueid + '","CityID":"' + cityid + '","Address":"' + address + '","PostCode":"' + postcode + '","AreaID":"' + areaid + '","ProvinceID":"' + provinceid + '","AddressID":"","Receiver":"' + receiver + '","Tel":"' + phone + '","Mobile":"' + mobile + '","Ext1":""}';
    $.ajax({
        url: '/Ashx/address.ashx?action=add',
        type: 'Post',
        timeout: 8000,
        async: false,
        cache: false,
        data: { 'addinfo': html },
        error: function () {
            alert('保存常用送货地址失败！');
            //提示无默认地址
            return false;
        },
        success: function (result) {
            if (result.Result) {
                //绑定前端显示
                GetAddressList();
                return false;
            }
            else {
                alert(result.Message);
                return 0;
            }
        }
    }
    );
}
//选择常用地址填充地址编辑页面
function selectAddress(addID) {
    //从服务器获取add
    GetAddress(addID);
    setaddress(address.ProvinceID, address.CityID, address.AreaID);

    $("#txtAddress").val(address.Address);
    $("#txtReceiver").val(address.Receiver);
    $("#txtPostCode").val(address.PostCode);
    $("#txtPhone").val(address.Phone);
    $("#txtMobile").val(address.Mobile);
    $('#litAddressID').val(address.AddressID);
}
//删除常用地址
function DeleteAddress(addID) {
    if (confirm("确定删除常用地址!")) {
        $.ajax({
            url: '/Ashx/address.ashx?action=delete',
            type: 'Post',
            timeout: 8000,
            async: false,
            cache: false,
            data: { 'addid': addID },
            error: function () {
                alert('删除送货地址失败！');
                //提示无默认地址
                return false;
            },
            success: function (result) {
                if (result.Result) {
                    $("#addrIi" + addID).remove();
                    for (var i = 0; i < AddressList.length; i++) {
                        if (AddressList[i].Uniqueid == addID) {
                            AddressList.remove(i);
                        }
                    }

                    if ($('#addid').val() == addID) {

                        $("#otxtAddress").val("");
                        $("#otxtReceiver").val("");
                        $("#otxtPostCode").val("");
                        $("#otxtPhone").val("");
                        $("#otxtMobile").val("");
                        $("#addid").val("");
                        $("#otxtProvinceID").val("");
                        $("#otxtCityID").val("");
                        $("#otxtAreaID").val("");
                    }
                    return false;
                }
                else {
                    alert(result.Message);
                    return 0;
                }
            }
        }
    );
    }
}
//关闭编辑页面
function CloseAddrEdit() {
    $("#addedit").hide();
    $("#addLable").show();
}
//打开编辑页面
function OpenAddrEdit() {
    $("#addedit").show();
    $("#addLable").hide();

}


//保存收货人信息时的检查
function check_con() {
    $(".msg").remove();
    var res = true;
    if (isEmpty('txtReceiver')) { res = false; }
    if (isEmpty('txtAddress')) { res = false; }
    if (!check_con_area()) { res = false; }
    if (!check_phone()) { res = false; }
    if (!check_message()) { res = false; }
    if (!check_phoneAndMob()) { res = false; }
    return res;
}
function isEmpty(ctrlID) {
    if ($('#' + ctrlID).val().length <= 0) {
        $('#' + ctrlID).after('<span class="msg">不可为空!</span>');
        return true;
    }
    return false;
}
function Msg(ctrlID) {

}

//检查省市区
function check_con_area() {

    if ($('#Select1').val() == 0 || $('#Select2').val() == 0 || $('#Select3').val() == 0) {
        $('#Select3').after('<span class="msg">必须选择完整!</span>');
        return false;
    }

    CaulateOrderAmount()
    return true;
}
//检查邮政编码
function check_postcode() {

    if ($('#txtPostCode').val() != '') {

        var myReg = /(^\s*)\d{6}(\s*$)/;
        if (!myReg.test($('#txtPostCode').val())) { $('#txtPostCode').after('<span class="msg">邮编格式不正确</span>'); return false; }
    }
    return true;
}
//检查联系电话
function check_phone() {
    // removeAlert('');

    // var pNode = $('#txtPhone').parentNode;
    //var myReg=/((\d+)|^((\d+)|(\d+)-(\d+)|(\d+)-(\d+)-(\d+)-(\d+))$)/;
    //if(!isEmpty('consignee_phone') && !myReg.test(g('consignee_phone').value)){showAlert('固定电话格式不正确',pNode,'phone_ff');return false;}
    //if(!isEmpty('consignee_phone') && !myReg.test(g('consignee_phone').value)){showAlert('固定电话格式不正确',pNode,'phone_ff');return false;}
    return true;
}
//检查手机号
function check_message() {

    if ($('#txtMobile').val() != '') {

        var myReg = /(^\s*)(((\(\d{3}\))|(\d{3}\-))?13\d{9}|1\d{10})(\s*$)/;
        if (!myReg.test($('#txtMobile').val())) { $('#txtMobile').after('<span class="msg">手机号格式不正确</span>'); return false; }
    }
    return true;
}
//检查电话和手机是否都填写了
function check_phoneAndMob() {


    //    if ($('#txtPhone').val() == '' && $('#txtMobile').val() == '') { $('#txtMobile').after('<span class="msg">固定电话和手机号码请至少填写一项！</span>'); return false; }
    return true;
}



//----------------------------支付方式及配送方式--------------------

var canSubmitCard = true;
var canAdd = false;
var cantAddDesc = "输入卡验证未通过，请输入您的卡号和密码";


function validVoucher() {
    var vid = $("#voucherNo").val();
    var url = '/Ashx/Card.ashx?action=vvouch&vid=' + vid + '&pid=' + $("#ctl00_ContentMain_hidVPid").val();
    $.ajax({
        url: url,
        type: 'GET',
        timeout: 18000,
        cache: false,
        error: function () {
            alert("请求超时！");
        },
        success: function (html) {
            var arr = html.split("~");
            var amount = arr[2] > 0 ? ("  可抵金额:" + arr[2] + "元") : "";
            document.getElementById("divVoucherTips").innerHTML = arr[1] + amount;
            $('#voucherAmount').text(arr[2]);
            CaulateOrderAmount();
            if (arr[0] == "F") {
                $('#voucherNo').val('');
            }
        }
    })
    return false;
}
function validPayPoints() {
    var ppid = $("#payPoints").val();
    var url = '/Ashx/Card.ashx?action=vpaypoints&ppid=' + ppid + '&webuseid=' + $("#ctl00_ContentMain_hidUseId").val();
    $.ajax({
        url: url,
        type: 'GET',
        timeout: 8000,
        cache: false,
        error: function () {
            alert("请求超时！");
        },
        success: function (html) {
            var arr = html.split("~");
            document.getElementById("divPayPointsTips").innerHTML = arr[1];
        }
    })
    return false;
}
function validCard(index) {
    var cid = $("#cardNo" + index).val();
    var pwd = $("#cardPwd" + index).val();
    var url = '/Ashx/Card.ashx?action=vcard&cid=' + cid + '&cpwd=' + pwd + '&cost=' + $("#ctl00_ContentMain_hidCost").val();
    $.ajax({
        url: url,
        type: 'GET',
        timeout: 8000,
        cache: false,
        error: function () {
            alert("请求超时！");
        },
        success: function (html) {
            var arr = html.split("~");
            if (arr[0] == "T") {
                canSubmitCard = canAdd = true;

                $("#hidCost" + index).val(arr[2]);
            }
            else {
                canSubmitCard = canAdd = false;
                $("#hidCost" + index).val(0);
            }
            var hidCosts = $('input[name=hidCost]');
            var totalCost = 0.00;
            for (var i = 0; i < hidCosts.length; i++) {
                totalCost += parseFloat(hidCosts[i].value);
            }

            var orderCost = parseFloat($("#ctl00_ContentMain_hidCost").val());
            //alert(totalCost);
            //alert(orderCost);
            if (totalCost >= orderCost) {
                cantAddDesc = "当前储值卡可以足额支付，不需要再添加储值卡";
                canAdd = false;
            }
            document.getElementById("divCardTips" + index).innerHTML = arr[1];
        }
    });
    return false;
}
function addCard() {
    var index = ($('input[name=cardNo]').length);
    index = index + 1;
    if (canAdd) {
        var newOne = '<br>卡号：<input type="text" id="cardNo' + index + '" name="cardNo"  />&nbsp;密码：<input type="password" id="cardPwd' + index + '" name="cardPwd"   onkeypress="if(event.keyCode==13) return validCard(' + index + ');" onblur="return validCard(' + index + ')" />&nbsp;&nbsp;<a style="cursor:pointer" onclick="return validCard(' + index + ')">确认</a>&nbsp;&nbsp;<span style="color:red;" id="divCardTips' + index + '"></span><input type="hidden" value="0" name="hidCost" id="hidCost' + index + '"/>';
        $("#divCard").append(newOne);
        canSubmitCard = canAdd = false;
    }
    else
        alert(cantAddDesc);


}

//----------------------------发票---------------------------
var label_invoice;
function showForm_invoice(obj) {
    selInvoiceId = 0;
    label_invoice = g("part_invoice").innerHTML;
    showWaitInfo('正在读取发票信息，请等待！', obj);
    var radioList = "setRadioDefaultItem('invoince_type','invoice_InvoiceType')";
    radioList += ";setRadioDefaultItem('invoince_pttt','invoice_InvoiceTitle')";
    radioList += ";setRadioDefaultItem('invoince_content','invoice_Invoice_Content')";
    radioList += ";invoice_setInvDetailTipShow();";

    setAjax_getResAndRunCode("action=showForm_invoice", "part_invoice", "GetInvoiceList();isInvoiceOpen=true;" + radioList);

}
function close_invoice(obj) {
    g("part_invoice").innerHTML = label_invoice;
    isInvoiceOpen = false;
}
//选择发票类型
function invoince_setType(selValue) {
    g('invoice_InvoiceType').value = selValue;
    if (selValue == 1) {
        setDisplay('invoice_ivc_Tr', 'none');
        setDisplay('invoice_titleTr', '');
    }
    if (selValue == 2) {
        setDisplay('invoice_ivc_Tr', '');
        setDisplay('invoice_titleTr', 'none');
    }
    invoince_setContentShow(selValue);
}
//显示发票内容区域
function invoince_setContentShow(invType) {
    setAjax_getResAndRunCode('action=invoince_setContentShow&typeId=' + invType, 'invoince_contentPanel', "setRadioDefaultItem('invoince_content','invoice_Invoice_Content');invoice_setInvDetailTipShow();");
}
//选择发票抬头
function invoince_setPttt(selValue) {
    g('invoice_InvoiceTitle').value = selValue;
    if (selValue == InvHeader_personal) {
        setDisplay('invoice_unitNameTr', 'none');
    }
    if (selValue == InvHeader_company) {
        setDisplay('invoice_unitNameTr', '');
    }
}
//选择发票内容
function invoince_setContent(selValue) {
    g('invoice_Invoice_Content').value = selValue;
    invoice_setInvDetailTipShow();
}
//设置发票内容提示的显示颜色
function invoice_setInvDetailTipShow() {
    try {
        var invd = g('invDetailTip');
        if (invd != null) {
            var selV = g('invoice_Invoice_Content').value;
            if (selV == '1')
                invd.className = 'gray';
            else
                invd.className = 'red';
        }
    } catch (e) { }
}
//保存发票时的检查
function check_invoice() {
    if (g('invoice_InvoicePutType').value != '0') return true; //即时开取验证
    if (g('invoice_InvoiceType').value == InvType_general) {
        //普通发票
        if (g('invoice_InvoiceTitle').value == InvHeader_company) {
            //选择了单位
            return check_invoice_unit();
        }
        else {
            return true;
        }

    }
    if (g('invoice_InvoiceType').value == InvType_vat) {
        var res = true;
        if (!check_Ivc_TitName()) { res = false; }
        if (!check_NsrCode()) { res = false; }
        if (!check_InvoiceAddress()) { res = false; }
        if (!check_InvoicePhone()) { res = false; }
        if (!check_InvoiceBank()) { res = false; }
        if (!check_InvoiceBankCode()) { res = false; }
        return res;
    }
}
//普票时的单位名称
function check_invoice_unit() {
    removeAlert('Invoice_UnitEmpty');
    removeAlert('Invoice_UnitFf');
    var pNode = g('invoice_Unit_TitName').parentNode;
    if (isEmpty('invoice_Unit_TitName')) { showAlert('单位名称不能为空！', pNode, 'Invoice_UnitEmpty'); return false; }
    if (!is_forbid(g('invoice_Unit_TitName').value)) { showAlert(ffAlertTxt, pNode, 'Invoice_UnitFf'); return false; }
    return true;
}
//增票的单位名称
function check_Ivc_TitName() {
    removeAlert('Invoice_TitNameEmpty');
    removeAlert('Invoice_TitNameFf');
    var pNode = g('invoice_Ivc_TitName').parentNode;
    if (isEmpty('invoice_Ivc_TitName')) { showAlert('单位名称不能为空！', pNode, 'Invoice_TitNameEmpty'); return false; }
    if (!is_forbid(g('invoice_Ivc_TitName').value)) { showAlert(ffAlertTxt, pNode, 'Invoice_TitNameFf'); return false; }
    return true;
}
//增票的纳税人标识
function check_NsrCode() {
    removeAlert('Invoice_NsrCodeEmpty');
    removeAlert('Invoice_NsrCodeFf');
    var pNode = g('invoice_Ivc_NsrCode').parentNode;
    if (isEmpty('invoice_Ivc_NsrCode')) { showAlert('纳税人识别号不能为空！', pNode, 'Invoice_NsrCodeEmpty'); return false; }
    if (!is_forbid(g('invoice_Ivc_NsrCode').value)) { showAlert(ffAlertTxt, pNode, 'Invoice_NsrCodeFf'); return false; }
    return true;
}
//增票的注册地址
function check_InvoiceAddress() {
    removeAlert('Invoice_addressEmpty');
    removeAlert('Invoice_addressFf');
    var pNode = g('invoice_Ivc_Address').parentNode;
    if (isEmpty('invoice_Ivc_Address')) { showAlert('注册地址不能为空！', pNode, 'Invoice_addressEmpty'); return false; }
    if (!is_forbid(g('invoice_Ivc_Address').value)) { showAlert(ffAlertTxt, pNode, 'Invoice_addressFf'); return false; }
    return true;
}
//增票的注册电话
function check_InvoicePhone() {
    removeAlert('Invoice_PhoneEmpty');
    removeAlert('Invoice_PhoneFf');
    var pNode = g('invoice_Ivc_Phone').parentNode;
    if (isEmpty('invoice_Ivc_Phone')) { showAlert('注册电话不能为空！', pNode, 'Invoice_PhoneEmpty'); return false; }
    if (!is_forbid(g('invoice_Ivc_Phone').value)) { showAlert(ffAlertTxt, pNode, 'Invoice_PhoneFf'); return false; }
    return true;
}
//增票的开户银行
function check_InvoiceBank() {
    removeAlert('Invoice_bankEmpty');
    removeAlert('Invoice_bankFf');
    var pNode = g('invoice__Ivc_Bank').parentNode;
    if (isEmpty('invoice__Ivc_Bank')) { showAlert('开户银行不能为空！', pNode, 'Invoice_bankEmpty'); return false; }
    if (!is_forbid(g('invoice__Ivc_Bank').value)) { showAlert(ffAlertTxt, pNode, 'Invoice_bankFf'); return false; }
    return true;
}
//增票的银行帐户
function check_InvoiceBankCode() {
    removeAlert('Invoice_bankCodeEmpty');
    removeAlert('Invoice_bankCodeFf');
    var pNode = g('invoice_Ivc_BankCode').parentNode;
    if (isEmpty('invoice_Ivc_BankCode')) { showAlert('银行帐户不能为空！', pNode, 'Invoice_bankCodeEmpty'); return false; }
    if (!is_forbid(g('invoice_Ivc_BankCode').value)) { showAlert(ffAlertTxt, pNode, 'Invoice_bankCodeFf'); return false; }
    return true;
}
//保存发票
function savePart_invoice(obj) {
    clearSubmitError(obj);
    if (check_invoice()) {
        var x = getFormXmlBySign('invoice_');
        showWaitInfo('正在提交发票信息，请等待。。。', obj);
        setAjax("POST", "action=savePart_invoice", '<table>' + x + '</table>', true, obj, 'part_invoice', 'if(checkSubmitError(xmlHttp.responseText,curBtn.parentNode)){isInvoiceOpen=false;}');
    }
}

function InvoicePutTypeOnChange(obj) {
    var putValue = obj.value;
    g('invoice_InvoicePutType').value = putValue;
    if (putValue == '0') g('tb_invoice').style.display = '';
    else { g('tb_invoice').style.display = 'none'; }
}
//选择常用地址
function changeInv(obj, index) {
    var radioList = "setRadioDefaultItem('invoince_type','invoice_InvoiceType');";
    radioList += "setRadioDefaultItem('invoince_pttt','invoice_InvoiceTitle');";
    radioList += "setRadioDefaultItem('invoince_content','invoice_Invoice_Content')";
    if (g('invIi' + selInvoiceId) != null)
        g('invIi' + selInvoiceId).className = '';
    selInvoiceId = index;
    g('invIi' + selInvoiceId).className = 'xz';
    setAjax_getResAndRunCode("action=changeInv&index=" + index, "part_invoice_form", radioList);
}
function AddInvoice(obj) {
    clearSubmitError(obj);
    if (check_invoice()) {
        var x = getFormXmlBySign('invoice_');
        showWaitInfo('正在提交发票信息，请等待。。。', obj);
        setAjax("POST", "action=AddInvoice", '<table>' + x + '</table>', true, obj, null, 'isInvoiceMoreOpen=true;GetInvoiceList();');
    }
}
function DelInv(obj, id) {
    setAjax("Get", "action=DelInv&id=" + id, null, false, obj, null, 'GetInvoiceList()');
}
var selInvoiceId = 0;
var maxInvoiceShowCount = 5;
var isInvoiceMoreOpen = false;
function GetInvoiceList() {
    setAjax_runCode("action=GetInvoiceList", "BuildInvoiceListHtml(backValue);");
}
function BuildInvoiceListHtml(objstr) {
    var obj = eval(objstr);
    var html = '';
    if (obj.length > 0) {
        html += "<div class='cydz'>";
        html += "<b>常用发票</b>";
        html += "<ul>";
        var isHaveMore = false;
        for (var i = 0; i < obj.length; i++) {
            if (i + 1 > maxInvoiceShowCount && !isHaveMore) {
                isHaveMore = true;
                html += "</ul>";
                html += "<div style='text-align:center'><a href='#none' class='remark' onclick=\"var dobj=g('cyfp_more');if(isInvoiceMoreOpen){isInvoiceMoreOpen=false;dobj.style.display='none'}else{isInvoiceMoreOpen=true;dobj.style.display=''}\">更多常用发票</a></div>";
                html += "<ul id='cyfp_more' " + (isInvoiceMoreOpen ? "" : "style='display:none'") + ">";
            }
            html += "<li id='invIi" + obj[i].Id + "'" + ((obj[i].Id == selInvoiceId) ? " class='xz'" : "") + ">";
            html += "<table cellspacing='0' cellpadding='0' border='0' style='width:98%'><tr>";
            html += "<td style='width:20px;'><input id='inv_" + obj[i].Id + "' type='radio' name='rbtnInv' onclick=\"changeInv(this,'" + obj[i].Id + "');\" " + ((obj[i].Id == selInvoiceId) ? " checked" : "") + " /></td>";
            html += "<td><label for='inv_" + obj[i].Id + "'><strong>" + obj[i].InvoiceHeader + "</strong>&nbsp;" + obj[i].NameInvoiceType + "&nbsp;内容:" + obj[i].NameInvoiceContentType + "</label></td>";
            html += "<td style='width:40px'><a href='#none' class='remark' onclick=\"DelInv(this,'" + obj[i].Id + "');\">[删除]</a></td>"
            html += "</tr></table>";
            html += "</li>";
        }
        html += "</ul>";
        html += "</div>";
    }
    g('invoiceListPanel').innerHTML = html;
}

//----------------------------备注---------------------------
var label_remark;
function showForm_remark(obj) {
    label_remark = g('part_remark').innerHTML;
    showWaitInfo('正在读取订单备注信息，请等待！', obj);
    setAjax_getResAndRunCode("action=showForm_remark", "part_remark", "isRemarkOpen=true");
}
function close_remark(obj) {
    g('part_remark').innerHTML = label_remark;
    isRemarkOpen = false;
}
//保存备注
function savePart_remark(obj) {
    clearSubmitError(obj);
    if (check_remark()) {
        var x = getFormXmlBySign('remark_');
        showWaitInfo('正在提交订单备注信息，请等待。。。', obj);
        setAjax("POST", "action=savePart_remark", '<table>' + x + '</table>', true, obj, 'part_remark', "isRemarkOpen=false");
    }
}
function check_remark() {
    removeAlert('remark_Ff');
    var pNode = g('remark_remark').parentNode;
    if (!is_forbid(g('remark_remark').value)) { showAlert(ffAlertTxt, pNode, 'remark_Ff'); return false; }
    return true;
}





//----------------------------优惠券--------------------------
function showTicket() {
    if (g('part_ticket').style.display == 'none') {
        g('part_ticket').style.display = '';
    } else {
        g('part_ticket').style.display = 'none';
    }
    setCouponStateShow();
}
function setCouponStateShow() {
    if (g('part_ticket').style.display == '') {
        g('couponStateShow').innerHTML = '-';
    } else { g('couponStateShow').innerHTML = '+'; }
}
//在操作券成功后执行的方法
function runInCouponOk() {
    showLiPinKa();
}
//添加实体券
function addShiTiCoupon(obj) {
    var couponKey = g('txtInputKey').value;
    if (couponKey == "") { alert('请输入实体券密码！'); return; }
    showWaitInfo('正在提交信息，请等待！', obj);
    setAjax_getResAndRunCode("action=addShiTiCoupon&key=" + couponKey, "shitiList", "runInCouponOk();g('txtInputKey').value='';showOrderInfo();if(selectedDong!=null){selectedDong.checked=false;selectedDong=null;setDianZiStyle();}");
}
//清空实体券
function clearShiTiCoupon(obj) {
    showWaitInfo('正在清空实体券信息，请等待。。。', obj);
    setAjax_getResAndRunCode("action=clearShiTiCoupon", "shitiList", "runInCouponOk();showOrderInfo()");
}
//删除实体券
function removeShiTi(id, obj) {
    showWaitInfo('正在删除实体券信息，请等待。。。', obj);
    setAjax_getResAndRunCode("action=removeShiTi&id=" + id, "shitiList", "runInCouponOk();showOrderInfo()");
}
//添加电子京券
function selectJing(obj, couponKey) {
    var runCode = "runInCouponOk();if(backValue=='ok'){";
    runCode += "showOrderInfo();";
    runCode += "}else{";
    runCode += "alert(backValue.substr(7));";
    runCode += "curBtn.checked=!curBtn.checked;";
    runCode += "}";
    runCode += "setDianZiStyle();";
    var actionStr = (!obj.checked) ? "removeDianZiCoupon" : "addDianZiCoupon";
    setAjax_runCodeAndBtn("action=" + actionStr + "&key=" + couponKey + "&cType=jing", obj, runCode);
}

var selectedDong;
//选择东券
function selectDong(obj, couponKey) {
    var runCode = "runInCouponOk();if(backValue=='ok'){";
    runCode += "showOrderInfo();";
    //清空实体券
    runCode += "g('shitiList').innerHTML='';";
    //清空电子京券
    runCode += "var sList=document.getElementsByName('jingCheckBox');";
    runCode += "for(var i=0;i<sList.length;i++)";
    runCode += "{sList[i].checked=false;}";

    runCode += "if(selectedDong==curBtn){curBtn.checked=false;selectedDong=null;}else{selectedDong=curBtn;}";
    runCode += "}else{";
    runCode += "alert(backValue.substr(7));";
    runCode += "if(selectedDong!=null){selectedDong.checked=true;}else{curBtn.checked=false;}";
    runCode += "}";
    runCode += "setDianZiStyle();";
    var actionStr = (selectedDong == obj) ? "removeDianZiCoupon" : "addDianZiCoupon";
    setAjax_runCodeAndBtn("action=" + actionStr + "&key=" + couponKey + "&cType=dong", obj, runCode);
}
function setDianZiStyle() {
    var sList = document.getElementsByName('jingCheckBox');
    for (var i = 0; i < sList.length; i++) {
        if (sList[i].checked) { sList[i].parentNode.className = 'couponSelect'; }
        else { sList[i].parentNode.className = 'couponNoSelect'; }
    }
    sList = document.getElementsByName('rbtnlDong');
    for (var i = 0; i < sList.length; i++) {
        var idStr = "CouponCancel_" + sList[i].id.substr(5);

        if (sList[i].checked) {
            sList[i].parentNode.className = 'couponSelect';
            g(idStr).style.display = '';
        }
        else {
            sList[i].parentNode.className = 'couponNoSelect';
            g(idStr).style.display = 'none';
        }
    }
}
//显示电子券信息
function showCouponInfo() {
    if (g('coupon_discount') == null || g('price_coupon') == null) return;
    g('coupon_discount').innerHTML = g('price_coupon').innerHTML;
    var cList = document.getElementsByName('rbtnlDong');
    for (var i = 0; i < cList.length; i++) {
        if (cList[i].checked) {
            g('coupon_count').innerHTML = '1';
            return;
        }
    }
    var cCount = 0;
    cList = document.getElementsByName('jingCheckBox');
    for (var i = 0; i < cList.length; i++) {
        if (cList[i].checked) {
            cCount++;
        }
    }
    cList = document.getElementsByName('shitiCoupon');
    cCount += cList.length;
    g('coupon_count').innerHTML = cCount;

}
//初始化东券选择
function setDongSelected() {
    var dongList = document.getElementsByName('rbtnlDong');
    for (var i = 0; i < dongList.length; i++) {
        if (dongList[i].checked) { selectedDong = dongList[i]; return; }
    }
}

//-------------------订单信息-------------------

function showOrderInfo() {
    setAjax_getResAndRunCode("action=showOrderInfo", "part_info", "setCouponStateShow();showCouponInfo();");
}
function useBalance(obj) {
    setAjax_getResAndRunCode("action=useBalance&isUsed=" + ((obj.checked) ? "1" : "0"), "part_info", "setCouponStateShow();");
}
//-------------------------提交订单信息-----------------
function check_submit() {
    var res = true;
    if (!check_submit_isClose()) {
        res = false;
    }
    return res;
}
function check_submit_isClose() {
    var errInfo = "";
    //检查是否都关闭
    if (isConOpen) { errInfo += "“收货人信息”"; }
    if (isPayTypeAndShipTypeOpen) { if (errInfo != '') { errInfo += ","; } errInfo += "“支付方式及配送方式”"; }
    if (isInvoiceOpen) { if (errInfo != '') { errInfo += ","; } errInfo += "“发票信息”"; }
    if (isRemarkOpen) { if (errInfo != '') { errInfo += ","; } errInfo += "“订单备注”"; }
    if (errInfo != "") {
        showAlert("请先保存" + errInfo, g("submit_error"), "")
        return false;
    }
    return true;
}
var isReSubmit = 0;
var passWord = '';
function submitOrder(obj) {

    g("submit_error").innerHTML = '';
    if (check_submit()) {
        showWaitInfo("正在提交订单，请等待！", g("submitWaitInfo"));
        g('submit_btn').style.display = 'none';
        var checkcode = "";
        var a = g('checkcodeTxt');
        if (a != null)
            checkcode = a.value;
        setAjax("GET", "action=submitOrder&isReSubmit=" + isReSubmit + "&passWord=" + escape(passWord) + "&ck=" + checkcode, null, false, obj, null, 'setOrderSubmitRes(backValue);');
        passWord = '';
    }
}
function closeSubmitTip() {
    g('MessageW').parentNode.removeChild(g('MessageW'));
    g('backW').parentNode.removeChild(g('backW'));
}
function setOrderSubmitRes(bakValue) {
    clearWaitInfo();
    g('submit_btn').style.display = '';
    if (bakValue.indexOf('submitError_') == 0) {
        var errStr = bakValue.substr(12);
        if (errStr == 'djd') {
            var a = new SubmitAlert();
            a.title = '尊敬的客户，您购买的商品中包含大家电产品';
            a.content = "&nbsp;&nbsp;&nbsp;&nbsp;对于此类产品京东为您提供销售服务，我们保证产品型号的正确和包装完整；安装、调试、保修等行为则由厂家直接负责。收到货物后您可以直接拨打厂家售后服务电话预约安装、调试服务，不建议自行开箱安装。京东大家电包含具体品类及其他注意事项，请详见：<a href='http://www.360buy.com/help/helectronic.aspx' target='_blank'>购物指南-大家电。</a>";
            a.bottom = "<a href='#none' id='Tip_apply' onclick=\"closeSubmitTip();isReSubmit=1;g('submit').click();\"><span>知道了，提交订单</span></a>";
            a.sender = g('submit');
            a.show();
            return;
        } else if (errStr == 'noPassWord') {
            var a = new SubmitAlert();
            a.title = '请输入登录密码';
            a.content = "<div style='padding-bottom:8px;'>尊敬的客户，为了您帐号的安全着想，请再次输入您的登录密码！</div>&nbsp;&nbsp;&nbsp;&nbsp;请输入登录密码:<input type='password' id='submit_pass' onkeypress=\"var key=window.event?event.keyCode:event.which;if(key==13){SubmitOnPassword();}\" /></a>&nbsp;<span id='submitAlert_mess' style='color:red;'></span>";
            a.bottom = "<a href='#none' id='Tip_apply' onclick=\"SubmitOnPassword();\"><span>提交订单</span></a>";
            a.sender = g('submit');
            a.show();
            g('submit_pass').focus();
            return;

        } else if (errStr == 'passWordError') {
            var a = new SubmitAlert();
            a.title = '请输入登录密码:';
            a.content = "<div style='text-align:center;color:red;padding-bottom:8px;'>您输入的密码有误，请重新输入！</div>&nbsp;&nbsp;&nbsp;&nbsp;请输入登录密码:<input type='password' id='submit_pass' onkeypress=\"var key=window.event?event.keyCode:event.which;if(key==13){SubmitOnPassword();}\" /></a>&nbsp;<span id='submitAlert_mess' style='color:red;'></span>";
            a.bottom = "<a href='#none' id='Tip_apply' onclick=\"SubmitOnPassword();\"><span>提交订单</span></a>";
            a.sender = g('submit');
            a.show();
            g('submit_pass').focus();
            return;
        }

        if (errStr == "priceChange") { showForm_cart(); showOrderInfo(); errStr = "尊敬的用户，您订单中的商品促销时限已过，价格已恢复为原价，您将按原价购买该商品，请您确认并再次提交订单。"; }
        showAlert(errStr, g("submit_error"), "");
    }
    if (bakValue.indexOf('url_') == 0) {
        var urlStr = bakValue.substr(4);
        urlStr = urlStr.split('@@');
        g('submit_btn').innerHTML = "<span class='submitSuccess'>" + urlStr[0] + "</span>";
        window.location = urlStr[1];
    }
    else if (bakValue.indexOf('fun_') == 0) {

        var funStr = bakValue.substr(4);
        eval(funStr);
    }
    else if (bakValue.indexOf('alert_') == 0) {

        var funStr = bakValue.substr(6);
        alert(funStr);
    }
}
function SubmitOnPassword() {
    if (g('submit_pass').value == '') { g('submitAlert_mess').innerHTML = '请输入密码！'; return; }
    passWord = g('submit_pass').value;
    closeSubmitTip();
    g('submit').click();
}
function SubmitAlert() {
    this.title = '';
    this.content = '';
    this.bottom = '';
    this.sender = null;
    this.show = function () {
        //背景
        var bWidth = parseInt(document.body.offsetWidth);
        var bHeight = parseInt(document.body.offsetHeight);
        var back = document.createElement("div");
        back.id = "backW";
        var styleStr = "top:0px;left:0px;background:#666;position:absolute;width:" + bWidth + "px;height:" + bHeight + "px;";
        styleStr += (isIe) ? "filter:alpha(opacity=40);" : "opacity:0.4;";
        back.style.cssText = styleStr;
        document.body.appendChild(back);
        //提示
        var mesW = document.createElement("div");
        mesW.id = "MessageW";
        mesW.innerHTML += "<div class='Tip_Title'><em><img src='skin/images/tip_close.jpg' class='Tip_Close' onclick=\"closeSubmitTip();\"/></em>" + this.title + "</div>";
        mesW.innerHTML += "<div class='Tip_Content'>" + this.content + "</div>";
        mesW.innerHTML += "<div class='Tip_Submit'>" + this.bottom + "</div>";
        var pos = new getPos(this.sender);
        var styleStr = 'position:absolute;width:400px;background:#fff;';
        styleStr += "top:" + (pos.Top - 100) + "px;left:" + (pos.Left - 220) + "px;";
        mesW.style.cssText = styleStr;
        document.body.appendChild(mesW);
    }

}



function showForm_cart() {
    if (g('part_cart') == null) return;
    setAjax_getRes("action=showForm_cart", 'part_cart');
}

var openSuitList = "";
//控制套装显示
function setSuitShow(suitId) {
    if (g('suit_' + suitId) == null) { return; }
    if (g('suit_' + suitId).style.display == 'none') {
        if (openSuitList.indexOf('{' + suitId + '}') < 0) {
            openSuitList += '{' + suitId + '}';
        }
        g('suit_' + suitId).style.display = '';
        g('suitA_' + suitId).innerHTML = '[收起套装商品]';
        g('suitImg_' + suitId).src = 'skin/images/bag_close.gif';
    } else {
        openSuitList = openSuitList.replace('{' + suitId + '}', '');
        g('suit_' + suitId).style.display = 'none';
        g('suitA_' + suitId).innerHTML = '[查看套装商品]';
        g('suitImg_' + suitId).src = 'skin/images/bag_open.gif';
    }
}



//促销
var promObj = null;
var promTime = null;
function runTime() {
    if (promObj == null) {
        clearTimeout(promTime); alert(promObj.length); return;
    }
    if (promObj.json != null) { promObj = promObj.json; }
    for (var i = 0; i < promObj.length; i++) {
        var tmpInt = parseInt(promObj[i].LeaveTime);
        if (tmpInt == 0) { g('PromSec_' + promObj[i].Id).innerHTML = "[抢购结束]"; continue; }
        promObj[i].LeaveTime = tmpInt - 1;
        var ts = new TimeSpan(tmpInt);
        g('PromSec_' + promObj[i].Id).innerHTML = ts.hour + "小时" + ts.minute + "分" + ts.second + "秒";
    }

    promTime = setTimeout(runTime, 1000);
}
function ShowPromoInfo() {
    setAjax_runCode("action=ShowPromoInfo", "ShowPromoInfo_callback(backValue)");
}
function ShowPromoInfo_callback(resHtml) {
    clearTimeout(promTime);
    if (g('Promo_panel') != null) {
        var pHtml = resHtml.split('@-@');
        if (pHtml.length == 2) {
            g('Promo_panel').innerHTML = pHtml[0];
            promObj = eval(pHtml[1]);

            runTime();
        } else {
            g('Promo_panel').innerHTML = '';
        }
    }
}


//----------------------礼品卡--------------------------
function showLipinka() {
    if (g('part_lipinka').style.display == 'none') {
        g('part_lipinka').style.display = '';
    } else {
        g('part_lipinka').style.display = 'none';
    }
    setLiPinKaStateShow();
}
function setLiPinKaStateShow() {
    if (g('part_lipinka').style.display == '') {
        g('lipinkaStateShow').innerHTML = '-';
    } else { g('lipinkaStateShow').innerHTML = '+'; }
}
//添加礼品卡
function addShiTiLiPinKa(obj, cType) {
    var couponKey = g('txtInputLPKey').value;
    if (couponKey == "") { alert('请输入礼品卡密码！'); return; }
    showWaitInfo('正在提交信息，请等待！', obj);
    setAjax_runCode("action=addLiPinKa&key=" + couponKey + "&cType=" + cType + "&isBind=0", "selectLiPinKa_callback(backValue);");

}
var curLiPinka = null;
function selectLiPinKa(obj, cType, id) {
    curLiPinka = obj;
    if (obj.checked) {
        setAjax_runCode("action=addLiPinKa&key=" + obj.value + "&cType=" + cType + "&isBind=1", "selectLiPinKa_callback(backValue)");

    } else {
        setAjax_runCode("action=delLiPinKa&cType=" + cType + "&id=" + id, "selectLiPinKa_callback(backValue)");
    }

}
function selectLiPinKa_callback(backValue) {
    if (backValue == 'ok') { showLiPinKa(); showOrderInfo(); }
    else {
        if (backValue.indexOf('lerror_') == 0) {
            var errInfo = backValue.substr(7);
            alert(errInfo);
            if (curLiPinka != null) curLiPinka.checked = !curLiPinka.checked;
        }
    }
    curLiPinka = null;
}
function showLiPinKa() {
    setAjax_getRes("action=showLiPinKa", "part_lipinka");
}



function showSplitInfo() {
    if (g('Split_panel') == null) return;
    setAjax_getRes("action=showSplitInfo", "Split_panel");
}

//---------------------贺卡--------------------
function Card_show(skuId, message, fun) {
    if (message != '') alert(message);
    var cardTest = new Card();
    cardTest.Fun = "ReBuildCard()";
    cardTest.Url = null;
    cardTest.Show();

}
function ReBuildCard(type) {
    setAjax_runCode("action=ReBuildCard", "showOrderInfo();showForm_cart();");
}

//---------------------以旧换新--------------------
function TradeIn_Apply(skuId) {
    if (confirm('确认要申请以旧换新吗？'))
        setAjax_runCode("action=TradeIn_Apply&SkuId=" + skuId, "TradeIn_Apply_Callback(backValue);");
}
function TradeIn_Apply_Callback(result) {
    if (result == 'NoLogin') {
        //登录
        if (confirm('此业务需登录后才能申请，现在去登录？')) {
            ToLogin();
        }
    }
    else if (result == 'NoConfig') {
        alert('抱歉,此商品目前无法申请‘以旧换新’业务！');
    }
    else if (result == 'ok') {
        alert('申请成功！您将享受到‘以旧换新’的优惠！');
        showOrderInfo();
        showForm_cart();
    }
}




