//新版模板JS集合

var $sel_country = jQuery("#sel_country");
var $sel_province = jQuery("#DropProvince");
var $sel_city = jQuery("#DropCity");
var $sel_area = jQuery("#DropArea");
//更新地址
function GetRegion(action, value) {
    if (value != "default") {
        var elementID = "";
        var countrySelected = "中华人民共和国";
        var provinceSelected = $sel_province.val();
        var citySelected = $sel_city.val();
        var areaSelected = $sel_area.val() == "-" ? "" : $sel_area.val();

        if (areaSelected == "-") {
            action = "getZipCode";
        }
        switch (action) {
            case 'getCountry':
                elementID = 'sel_country';
                break;
            case 'getProvince':
                elementID = 'DropProvince';
                break;
            case 'getCity':
                elementID = 'DropCity';
                break;
            case 'getArea':
                elementID = 'DropArea';
                break;
            default: break;
        }


        jQuery.pe.ajax('addresspicker', { params: {
            action: action,
            country: countrySelected,
            province: provinceSelected,
            city: citySelected,
            area: areaSelected
        },
            success: function (data) {
                var status = jQuery("status", data).text();
                if (status == "err") {
                }
                else if (status == "ok") {
                    var result = jQuery("result", data).text();
                    if (action == 'getZipCode') {
                        jQuery("#TxtZipCode").val(result);
                    }
                    else {
                        jQuery("#" + elementID).empty();
                        if (result != "empty") {
                            result = eval('(' + result + ')');
                            jQuery.each(result, function (entryIndex, entry) {
                                var newOption = new Option(entryIndex, result[entryIndex]);
                                document.getElementById(elementID).options.add(newOption);
                            });
                            if (value != '') {
                                jQuery("#" + elementID).val(value);
                            }
                            if (jQuery(document).queue("RegionUpdateQueue").length > 0) {
                                jQuery(document).dequeue("RegionUpdateQueue");
                            }
                            else {
                                jQuery("#" + elementID).trigger("change");
                            }
                        }
                        else {
                            var newOption = new Option("-", "-");
                            document.getElementById(elementID).options.add(newOption);
                            if (action == 'getArea') {
                                jQuery("#" + elementID).trigger("change");
                            }
                        }
                        jQuery("#TxtZipCode").val("");
                    }
                    var address = "";
                    if ($sel_country.val() != 'default') {
                        address += $sel_country.val();
                    }
                    if ($sel_province.val() != 'default') {
                        address += "," + $sel_province.val();
                    }
                    if ($sel_city.val() != 'default') {
                        address += "," + $sel_city.val();
                    }
                    if ($sel_area.val() != null && $sel_area.val() != 'default' && $sel_area.val() != '-') {
                        address += "," + $sel_area.val();
                    }
                    jQuery("#selectedAddress").html(address);
                }
            }
        }
                );
    }
}

function JsInit() {
    //初始化地址
    GetRegion('getProvince', "中华人民共和国");

    //如果没有默认地址列表，则选中其他地址
    var $addressList = jQuery("input[name='address']");
    $addressList.click(function () {
        var addressId = parseInt(jQuery(this).attr("addressId"));
        if (addressId == 0) {
            jQuery("#ULAddressEdit").show();
        }
        else {
            jQuery("#ULAddressEdit").hide();
        }
    });

    if ($addressList.length == 1) {
        $addressList.eq(0).click();
    }
    jQuery("#TxtEmail").val(jQuery("#HdnEmail").val());
}

JsInit();

//表单验证
jQuery("#customerInfoAddress").find(".editBox li .text").each(function () {
    var $this = jQuery(this);
    var focusClass = "current"; //控件选中时的样式
    var arrCustomValParam = jQuery.pe.stringToJSON($this.attr("CustomValParam"));

    if (arrCustomValParam != null) {
        //是否必填
        for (var i = 0; i < arrCustomValParam.length; i++) {
            if (arrCustomValParam[i].Type == "require") {
                $this.after('<span class="require">*</span>');
            }
        }
    }

    //选中
    $this.focus(function () {
        $this.addClass(focusClass);
    });

    //验证
    $this.blur(function () {
        $this.removeClass(focusClass);
        ValidateCtrl($this, false);

        //当本控件验证通过的时候，验证关联控件
        var relctrlParam = GetParamByType($this, "relctrl");
        if (relctrlParam != null) {
            ValidateCtrl(jQuery("#" + relctrlParam.RelCtrl), false);
        }
    });
});

function ValidateCtrl(obj, isCallBySelf) {
    var isPassed = true;
    var arrCustomValParam = jQuery.pe.stringToJSON(obj.attr("CustomValParam"));
    if (arrCustomValParam != null) {
        for (var i = 0; i < arrCustomValParam.length; i++) {
            //当当前验证内容为空时，检查是否有关联验证控件              
            if (obj.val() == "" && arrCustomValParam[i].Type == "relctrl" && !isCallBySelf) {
                var $objRelCtrl = jQuery("#" + arrCustomValParam[i].RelCtrl);
                if ($objRelCtrl.length > 0) {
                    if (ValidateCtrl($objRelCtrl, true)) {//关联的控件验证通过，则通过
                        SetMsg(obj, "", "");
                        return true;
                    }
                    else {
                        continue;
                    }
                }
            }

            var regx = GetRegex(arrCustomValParam[i].Type);
            if (!isCallBySelf) {
                if (!regx.test(obj.val())) {
                    SetMsg(obj, "error", arrCustomValParam[i].ErrMsg);
                    isPassed = false;
                    return isPassed;
                }
                else {
                    SetMsg(obj, "success", "");
                }
            }
            else {
                if (!regx.test(obj.val())) {
                    return false;
                }
            }
        }
    }

    return isPassed;
}

function GetRegex(type) {
    var regx;
    switch (type) {
        case "mobile":
        case "phone":
            regx = /0?1[358][0-9]{9}|(\(\d{3,4}\)|\d{3,4}-?)?\d{7,8}(-\d{1,5})?/;
            break;
        case "zipcode":
            regx = /\d{6}/;
            break;
        case "email":
            regx = /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/;
            break;
        case "relctrl": //关联的必填一个即可
        case "require":
            regx = /.+/;
            break;
    }
    return regx;
}

function SetMsg(obj, className, msg) {
    obj.nextAll().remove();
    var html = "";
    var isRequire = false; //是否必填
    var requireParam = GetParamByType(obj, "require");
    if (requireParam != null) {
        isRequire = true;
    }

    if (isRequire) {
        html += '<span class="require">*</span>';
    }
    html += '<span class="' + className + '">' + msg + '</span>';
    obj.after(html);
}

function GetParamByType(obj, typeName) {
    var param = null;
    var arrCustomValParam = jQuery.pe.stringToJSON(obj.attr("CustomValParam"));
    if (arrCustomValParam != null) {
        //是否必填
        for (var i = 0; i < arrCustomValParam.length; i++) {
            if (arrCustomValParam[i].Type == typeName) {
                param = arrCustomValParam[i];
                break;
            }
        }
    }
    return param;
}

//验证组控件
function ValidateGroup(groupName) {
    var $groupObjList = jQuery("input[groupname='" + groupName + "']");
    var passedCount = 0;
    $groupObjList.each(function () {
        if (ValidateCtrl(jQuery(this), false)) {
            passedCount++;
        }
    });

    if ($groupObjList.length == passedCount) {
        return true;
    }
    else {
        return false;
    }
}

//收货信息保存
function SaveAddressInfo() {
    return SaveAddressInfoType(true);
}

function SaveAddressInfoType(isPost) {
	var result = ValidateGroup("ConsigneeEmail");
    var addressId = parseInt(jQuery("input[name='address']:checked").attr("addressId"));
    if (addressId == 0) {//使用其他地址的
        result = ValidateGroup("ConsigneeAddress") && ValidateGroup("ConsigneeEmail");
        if (result) {
            var jsonAddressInfo = { "UserName": "", "ConsigneeName": "", "Area": "", "AddressId": 0, "HomePhone": "", "Mobile": "", "Country": "", "Province": "", "City": "", "Address": "", "ZipCode": "", "IsDefault": true, "IsNull": false };
            jsonAddressInfo.Province = jQuery("#DropProvince").val();
            jsonAddressInfo.City = jQuery("#DropCity").val();
            jsonAddressInfo.Area = jQuery("#DropArea").val();
            jsonAddressInfo.Address = jQuery("#TxtAddress").val();
            jsonAddressInfo.ZipCode = jQuery("#TxtZipCode").val();
            jsonAddressInfo.ConsigneeName = jQuery("#TxtConsigneeName").val();
            jsonAddressInfo.Mobile = jQuery("#TxtMobile").val();
            jsonAddressInfo.HomePhone = jQuery("#TxtHomePhone").val();
            jQuery("#HdnAddressInfo").val(jQuery.pe.jsonToString(jsonAddressInfo));
            //邮件
            jQuery("#HdnEmail").val(jQuery("#TxtEmail").val());

            //显示选中信息
            var selectedAddress = jsonAddressInfo.ConsigneeName + "，" + jsonAddressInfo.Province + "，" + jsonAddressInfo.City + "，" + jsonAddressInfo.Area + "，" + jsonAddressInfo.Address + "，" + jsonAddressInfo.ZipCode + "，" + jsonAddressInfo.Mobile + "，" + jsonAddressInfo.HomePhone + "，" + jQuery("#TxtEmail").val();
            jQuery("#LtrAddress").text(selectedAddress);
        }
    }
    else {//使用已有地址
        result = ValidateGroup("ConsigneeEmail");

        if (result) {
            jQuery("#HdnAddressInfo").val(addressId);

            //邮件
            jQuery("#HdnEmail").val(jQuery("#TxtEmail").val());

            //显示选中信息
            var selectedAddress = jQuery("#address-" + addressId).next().html() + "，" + jQuery("#TxtEmail").val();
            jQuery("#LtrAddress").text(selectedAddress);
        }
    }

	//更新购物车
	if(isPost){
		UpdateShoppingCart();
	}

    return result;
}

//送货方式保存
function SaveDeliverType() {
   return SaveDeliverTypeDetail(true);
}

function SaveDeliverTypeDetail(isPost) {
    var typeId = jQuery("input[name='delivertype']:checked").attr("typeId");
    jQuery("#HdnDeliverType").val(typeId);
    //更新购物车
    if (isPost) {
        UpdateShoppingCart();
    }
    //显示选中信息
    var selectedDeliverType = jQuery("#RadDeliverType_" + typeId).next().text();
    jQuery("#LtrDeliverType").text(selectedDeliverType);
    return true;
}

//送货方式取消
function CancelDeliverType() {
    var typeId = jQuery("#HdnDeliverType").val();
    jQuery("input[name='delivertype'][typeId='" + typeId + "']").attr("checked", true);
    return true;
}

//支付方式保存
function SavePaymentType() {
    var typeId = jQuery("input[name='paymenttype']:checked").attr("typeId");
    jQuery("#HdnPaymentType").val(typeId);
    //显示选中信息
    var selectedPaymentType = jQuery("#RadPaymentType_" + typeId).next().text();
    jQuery("#LtrPaymentType").text(selectedPaymentType);
    return true;
}

//支付方式取消
function CancelPaymentType() {
    var typeId = jQuery("#HdnPaymentType").val();
    jQuery("input[name='paymenttype'][typeId='" + typeId + "']").attr("checked", true);
    return true;
}

//备注保存
function SaveRemark() {
    var remark = jQuery("#TxtRemark").val();
    jQuery("#HdnRemark").val(remark);
    jQuery("#LtrRemark").text(remark);
    return true;
}

//备注取消
function CancelRemark() {
    jQuery("#TxtRemark").val(jQuery("#HdnRemark").val());
    return true;
}

function SaveInvoiceInfo() {
    return SaveInvoice(true);
}

//发票保存
function SaveInvoice(isPost) {
    var result = true;
    var needInvoice = jQuery("#ChkNeedInvoice").attr("checked") == "checked";
    if (needInvoice == true) {
        if (ValidateGroup("Invoice")) {
            jQuery("#HdnNeedInvoice").val(needInvoice);
            var jsonInvoiceInfo = { "InvoiceType": "0", "InvoiceTitleType": "0", "InvoiceName": "", "InvoiceContent": ""};
            var $selectedInvoiceType = jQuery("input[name='invoicetype']:checked");
            jsonInvoiceInfo.InvoiceType = $selectedInvoiceType.attr("value");
            var selectedInvoiceTypeText = $selectedInvoiceType.next().text();

            var $selectedInvoiceTitleType = jQuery("input[name='invoicetitletype']:checked");
            jsonInvoiceInfo.InvoiceTitleType = $selectedInvoiceTitleType.attr("value");
            var selectedInvoiceTitleTypeText = $selectedInvoiceTitleType.next().text();
            var selectedTxtInvoiceAmountText = jQuery("#TxtInvoiceAmount").val();

            jsonInvoiceInfo.InvoiceName = jQuery("#TxtInvoiceName").val();
            jsonInvoiceInfo.InvoiceContent = jQuery("#TxtInvoiceContent").val();

            jQuery("#HdnInvoiceOldValue").val(jQuery.pe.jsonToString(jsonInvoiceInfo));

            var content = "发票抬头：" + selectedInvoiceTypeText + " " + selectedInvoiceTitleTypeText + " " + jsonInvoiceInfo.InvoiceName + 
            "\r\n 商品名称：" + jsonInvoiceInfo.InvoiceContent + "\r\n发票金额："+ selectedTxtInvoiceAmountText +"元";
            jQuery("#HdnInvoiceContent").val(content);
            jQuery("#LtrInvoiceInfo").text(content);

            //更新购物车
            if (isPost) {
                UpdateShoppingCart();
            }
        }
        else {
            result = false;
        }
    }
    else {
        //更新购物车
        jQuery("#HdnNeedInvoice").val(needInvoice);
        if (isPost) {
            UpdateShoppingCart();
        }
    }
    return result;
}

//发票取消
function CancelInvoiceInfo() {
    var oldValue = jQuery("#HdnInvoiceOldValue").val();
    if (oldValue != "") {
        var jsonInvoiceInfo = jQuery.pe.stringToJSON(oldValue);
        jQuery("#invoicetype_" + jsonInvoiceInfo.InvoiceType).attr("checked", true);
        jQuery("#invoicetitletype_" + jsonInvoiceInfo.InvoiceTitleType).attr("checked", true);
        jQuery("#TxtInvoiceName").val(jsonInvoiceInfo.InvoiceName);
        jQuery("#TxtInvoiceContent").val(jsonInvoiceInfo.InvoiceContent);
    }
    return true;
}

//优惠券保存
function SaveCoupon() {
    return true;
}

//优惠券取消
function CancelCoupon() {
    return true;
}

//提交订单前验证
function SubmitValidator() {
    var errMsg = "";
    if (jQuery("#customerInfoAddress").hasClass("editInfo")) {
        errMsg += "请确认收货信息<br />";
    }
    else if (!SaveAddressInfoType(false)) {
        errMsg += "请填写正确的收货信息<br />";
    }

    if (jQuery("#LtrDeliverType").text().trim()=="") {
        errMsg += "请确认送货方式<br />";
    }
    else {
        SaveDeliverTypeDetail(false);
    }

    if (jQuery("#LtrPaymentType").text().trim()=="") {
        errMsg += "请确认支付方式<br />";
    }
    else {
        SavePaymentType();
    }
    if (!SaveInvoice(false)) {
        errMsg += "请填写正确的发票信息<br />";
    }

    if (errMsg != "") {
        errMsg = errMsg.replace(/\<br \/\>/g, "\r\n");
        alert(errMsg);
        return false;
    }
    return true;
}

//设置项信息的修改显示状态
function SetItemInfoState(obj, type, beforeSetFuntionName) {
    var result = true;

    GetRegion("getZipCode", jQuery("#DropProvince").val());
    GetRegion("getZipCode", jQuery("#DropCity").val());
    GetRegion("getZipCode", jQuery("#DropArea").val());

    if (beforeSetFuntionName != null && beforeSetFuntionName != "") {
        result = eval('(' + beforeSetFuntionName + '())');
    }

    if (result) {
        var $this = jQuery(obj);
        var $RootParent = $this.parents(".customerInfoItem");
        switch (type) {
            case "edit":
                $RootParent.addClass("editInfo");
                break;
            case "close":
            case "save":
                $RootParent.removeClass("editInfo");
                break;
        }
    }
}

//更新购物车
function UpdateShoppingCart() {
    jQuery("#BtnUpdateShoppingCart").click();
}