$(document).ready(function () {
var baseURL = "http://pay.wanlou.com/";
    var teststart = getParam("test");
    $("#wl_divProduct").html("<form class='wl-product-form' id='form_order' target='_blank' name='form_order'  method='post'  action='" + baseURL + "order.aspx?test=" + teststart + "'> <div class='wl-field radio-wrap'> <label  class='label'>产品名称：</label> <div class='inputbox' id='divProductGroup'>  &nbsp;</div> </div> <div class='wl-field'> <label  class='label'>订购数量：</label> <div class='inputbox'> <input class='text'  type='text' name='txtOrderNum' id='txtOrderNum' maxlength='3' /></div> </div>  <div class='wl-field'> <label class='label'>您的姓名：</label> <div  class='inputbox'> <input class='text' type='text' name='txtBuyerName'  id='txtBuyerName' maxlength='30' /></div> </div> <div class='wl-field'> <label  class='label'>手机号码：</label> <div class='inputbox'> <input class='text'  type='text' name='txtBuyerPhone' id='txtBuyerPhone' maxlength='11' /></div>  </div> <div class='wl-field'> <label class='label'>联系邮箱：</label> <div  class='inputbox'> <input class='text' type='text' name='txtBuyerEmail'  id='txtBuyerEmail' maxlength='50' /></div> </div> <div class='wl-field'> <label  class='label'>区域选择：<input type='hidden' id='hidAreaID' /></label> <div class='inputbox'> <select class='select'  name='selProvince' id='selProvince'> <option value='999'>--请选择--</option>  </select> <select class='select' name='selCity' id='selCity'> <option  value='999'></option> </select> <select class='select' name='selArea'  id='selArea'> <option value='999'></option> </select> </div> </div> <div  class='wl-field'> <label class='label'>详细地址：</label> <div class='inputbox'>  <input class='text address' type='text' name='txtBuyerAddress'  id='txtBuyerAddress' maxlength='100' /></div> </div> <div class='wl-field'>  <label class='label'>支付方式：</label> <div class='inputbox' id='divPayMethod'>  &nbsp;</div> </div> <div class='wl-field'> <label  class='label'>送货时间：</label> <div class='inputbox' id='divAssignedTime'>  &nbsp;</div> </div> <div class='wl-field'> <label  class='label'>您的留言：</label> <div class='inputbox'> <textarea  class='messagebox' name='txtRemark' id='txtRemark'></textarea></div> </div> <div  class='wl-field'> <div class='inputbox'> <input type='hidden' id='hdUcode'  name='hdUcode' value='' /><input type='hidden' id='hdDcode'  name='hdDcode' value='' /><input type='hidden' id='hdSpecial'  name='hdSpecial' value='0' /> <input class='wl-btn-order' type='submit'  value='提交' /></div> </div> </form>");
    //取ucode
    var ucode = getParam("ucode");
    var ducode = form_product_param.ucode;
    var special = form_product_param.sid;
    $("#hdDcode").val(ducode);
    $("#hdSpecial").val(special);

    if (ucode != null && ucode != "null" && ucode != "") {
        $("#hdUcode").val(ucode);
        $("#ShowuCode").text(ucode);
        SetCookies("ucode", ucode, 15);
    }
    else if (GetCookies("ucode") != null) {
        $("#hdUcode").val(GetCookies("ucode"));
        $("#ShowuCode").text(GetCookies("ucode"));
    }
    else {
        $("#hdUcode").val(ducode);
        $("#ShowuCode").text(ducode);
    }

    //表单数据
    $.getJSON(baseURL + "ajax/ProductFormHandler.ashx?callback=?", { pid: form_product_param.pid }, function (data) {
        if (data.Status.Success) {
            BindProductGroup(data.ProductGroup);
            BindPayMethod(data.PayMethod);
            BindAssignedTime(data.AssignedTime);
        }
        else {
            alert(data.Status.Message);
        }
    });

    //初始化地区
    $.getJSON(baseURL + "ajax/AreaHandler.ashx?callback=?", { method: 1, ts: Math.round(5) }, function (data) {
        if (data.Status.Success) {
            FillArea("selProvince", data.Province);
            FillArea("selCity", data.City);
            FillArea("selArea", data.Area);
        }
        else {
            alert(data.Status.Message);
        }
    });

    //省份切换
    $("#selProvince").change(function () {
        var selID = $(this).val();
        $.getJSON(baseURL + "ajax/AreaHandler.ashx?callback=?", { pid: selID, ts: Math.round(5) }, function (data) {
            if (data.Status.Success) {
                FillArea("selCity", data.Area);
                $("#selArea").get(0).options.length = 0;
            }
            else {
                alert(data.Status.Message);
            }
        });
    });
    //地市切换
    $("#selCity").change(function () {
        var selID = $(this).val();
        $.getJSON(baseURL + "ajax/AreaHandler.ashx?callback=?", { pid: selID, ts: Math.round(5) }, function (data) {
            if (data.Status.Success) {
                FillArea("selArea", data.Area);
            }
            else {
                alert(data.Status.Message);
            }
        });
    });
    //地市切换
    $("#selArea").change(function () {
        var sValue = $("#selArea").val();
        $.getJSON(baseURL + "ajax/AreaIsLocalePay.ashx?callback=?", { aid: sValue }, function (data) {
            $("#hidAreaID").val(data.IsLocalePay);
        });
    });

    //表单验证
    $("#form_order").validate({
        rules: {
            txtOrderNum: {
                number: true,
                required: true
            },
            txtBuyerName: {
                required: true
            },
            txtBuyerPhone: {
                required: true,
                checkmobile: true
            },
            txtBuyerEmail: {
                required: true,
                email: true
            },
            selArea: {
                checkarea: true,
                areaislocalepay: true
            },
            txtBuyerAddress: {
                required: true
            }
        },
        messages: {
            txtOrderNum: {
                number: "请输入数字！",
                required: "请输入订购数量！"
            },
            txtBuyerName: {
                required: "请输入你的姓名！"
            },
            txtBuyerPhone: {
                required: "请输入手机号码！"
            },
            txtBuyerEmail: {
                required: "请输入你的邮箱！",
                email: "邮箱格式不正确，请重新输入！"
            },
            txtBuyerAddress: {
                required: "请输入详细地址！"
            }
        },
        errorElement: "em",
        success: function (label) {
            label.text("OK！").addClass("success");
        }
    });

});

//检查手机格式是否正确
$.validator.addMethod(
                "checkmobile",
                function (value, element) {
                    var reg = /^(\+86)?(1[0-9]{10})$/;
                    return reg.test(value);
                },
                '手机号码格式不正确，请重新输入！'
            );

//检查地址是否选中
$.validator.addMethod(
                "checkarea",
                function (value, element) {
                    if (value == 999 || value == "") { return false; } else { return true; }
                },
                '请选择你所在的地区！'
            );
//查询所选地区是否支持货到付款
                $.validator.addMethod(
                "areaislocalepay",
                function (value, element) {
                    var meid = '';
                    var New = document.getElementsByName("rblPayMethod");
                    for (var i = 0; i < New.length; i++) {
                        if (New.item(i).checked) {
                            meid = New.item(i).getAttribute("value");
                        }
                    }
                    if (meid == '99') {
                        var sValue = $("#hidAreaID").val();
                        if (sValue == '0') {
                            return false;
                        }
                        else {
                            return true;
                        }
                    }
                    else {
                        return true;
                    }
                },
                '<br/>你所选择的地区不支持货到付款'
            );

//绑定产品
function BindProductGroup(data) {
    var str = "";
    var stri = 0;
    $.each(data, function(idx, item) {
        str += "<p><input name='rblProductGroup' id='rblProductGroup_" + idx + "' type='radio' value='" + item.GroupID + "'  /><label for='rblProductGroup_" + idx + "'>" + item.GroupName + "</label></p>";
        stri++;
    })
    $("#divProductGroup").html(str);
    if (stri == 1) {
        $("input[name=rblProductGroup]:eq(0)").attr("checked", 'checked');
    } else {
        $("input[name=rblProductGroup]:eq(1)").attr("checked", 'checked');
    }
}
//绑定支付方式
function BindPayMethod(data) {
    var str = "<p>";
    $.each(data, function (idx, item) {
        str += "<input name='rblPayMethod' id='rblPayMethod_" + idx + "' type='radio' value='" + item.MethodID + "'  /><label for='rblPayMethod_" + idx + "'>" + item.MethodName + "</label>";
    })
    str += "</p>";
    $("#divPayMethod").html(str);
    $("input[name=rblPayMethod]:eq(0)").attr("checked", 'checked');
}

//绑定客户送货时间
function BindAssignedTime(data) {
    var str = "";
    $.each(data, function (idx, item) {
        str += "<p><input name='rblAssignedTime' id='rblAssignedTime_" + idx + "' type='radio' value='" + item.AssignedTimeID + "'  /><label for='rblAssignedTime_" + idx + "'>" + item.AssignedTimeName + "</label></P>";
    })
    $("#divAssignedTime").html(str);
    $("input[name=rblAssignedTime]:eq(0)").attr("checked", 'checked');
}

//绑定地区
function FillArea(selectid, data) {
    $("#" + selectid).get(0).options.length = 0;
    if (data.length > 0) {
        $("#" + selectid).prepend("<option value='999'>--请选择--</option>");   //为Select插入一个Option(第一个位置) 
    }
    else {
        $("#" + selectid).prepend("<option value='999'></option>");   //为Select插入一个Option(第一个位置) 
    }
    $.each(data, function (idx, item) {
        var selected = "";
        if (item.IsSel == 1) {
            selected = "selected=\"selected\"";
        }
        $("#" + selectid).append("<option value='" + item.AreaID + "' " + selected + ">" + item.AreaName + "</option>");
    });
}

//取参数值
function getParam(a) {
    var c = location.href;
    c = c.substring(c.indexOf("?") + 1, c.length).split("&");
    b = {};
    for (i = 0; j = c[i]; i++) b[j.substring(0, j.indexOf("=")).toLowerCase()] = j.substring(j.indexOf("=") + 1, j.length);
    a = b[a.toLowerCase()];
    return typeof a == "undefined" ? "null" : a.split("#")[0]
}

function GetCookies(name) {
    var search = name + "=";
    if (document.cookie.length > 0) {
        offset = document.cookie.indexOf(search);
        if (offset != -1) {
            offset += search.length;
            end = document.cookie.indexOf(";", offset);
            if (end == -1) end = document.cookie.length;
            return document.cookie.substring(offset, end);
        }
        else
            return null;
    }
}
function SetCookies(name, value, days) {
    var expires = "";
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        expires = "; expires=" + date.toGMTString();
    }
    document.cookie = name + "=" + escape(value) + expires + "; path=/" + ";domain=" + window.location.host;
}
function eraseCookie(name) {
    createCookie(name, "", -1);
}