$(function() {
    //获取验证码
    $("#get_code").click(function() {
        
        var phone = $("#phone").val();
        var aespass = $('#aespass').val();

        if (!checkPhone(phone)) {
            return;
        }

        var postData = {
            phone: phone,
            aespass: aespass,
        }
        $("#get_code").attr("disabled", true);
        changeNum(60);

        postRequest("/getcode", postData, doSuccess, doFail);

        function doSuccess(res) {
            
            if (res.state == 0) {
                serverErrorMsg(res);
                return;
            }
            layer.msg(res.data.msg);
        }
    });

    //确定
    $("#submit").click(function() {
        var code = $("#code").val();

        if (code != null && code != undefined && code != "") {
            var mobile = $("#phone").val();
            var password = $("#password").val();

            if (canSure(phone, password)) {
                var postData = {
                    mobile: mobile,
                    password: hex_md5(password),
                    code: code,
                }

                postRequest("/password/modify", postData, doSuccess, doFail);

                function doSuccess(res) {
                    if (res.state == 0) {
                        serverErrorMsg(res);
                        return;
                    }
                    // $(".layerBg").show();
                    // $(".layerSuccess").show();
                    window.location.href = "/login"
                }

            } else {
                return;
            }
        }
    });

    document.onkeydown = function(event) {
        var e = event || window.event || arguments.callee.caller.arguments[0];
        if (e && e.keyCode == 13) { // enter 键
            $("#submit").click();
        }
    };
});

function doFail(res) {
    serverErrorMsg(res);
}

function checkPhone(phone) {
    if (!phone || phone == "") {
        layer.msg("手机号码不能为空");
        return false;
    }

    if (!(/^1\d{10}$/.test(phone))) {
        layer.msg("手机号码有误，请重填");
        return false;
    }
    return true;
}

function canSure(phone, password) {
    if (!phone || phone == "") {
        layer.msg("手机号码不能为空");
        return false;
    }

    if (!password) {
        layer.msg('密码为空');
        return false;
    }

    if (password.length < 6) {
        layer.msg('密码至少要6位数');
        return false;
    }
    return true;
}

function changeNum(num) {
    setTimeout(function() {
        if (num > 1) {
            $('#get_code').html(num + "s");
            --num;
            changeNum(num);
        } else {
            $('#get_code').html("发送验证码");
            $("#get_code").attr("disabled", false);
        }
    }, 1000);
}