$(function() {
    var cachedMobile = getCookie("login_mobile");
    if (cachedMobile != null) {
        $("#phone").val(cachedMobile);
    }

    //获取验证码
    $("#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", false);
        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();

            if (checkPhone(mobile)) {

                var postData = {
                    mobile: mobile,
                    code: code,
                    returnurl: $("#return_url").val(),
                    app_type: $("#app_type").val(),
                }

                setCookie("login_mobile", mobile);

                postRequest("/login/code/submit", postData, doSuccess, doFail);

                function doSuccess(res) {
                    if (res.state == 0) {
                        serverErrorMsg(res);
                        return;
                    }
                    var url = res.data.url;
                    window.location.href = url;
                }
            }
        }
    });

    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 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);
}

function setCookie(name,value){
    document.cookie = name + "="+ escape (value) + ";expires=" + 0;
}

function getCookie(name){
    var arr = document.cookie.match(new RegExp("(^| )" + name + "=([^;]*)(;|$)"));
    if (arr != null)
        return unescape(arr[2]);
    return null;
}
