$(function() {

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

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

        if (canSure(mobile, password)) {
            var postData = {
                mobile: mobile,
                password: hex_md5(password),
                returnurl: $("#return_url").val(),
                app_type: $("#app_type").val(),
            }

            setCookie("login_mobile", mobile);

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

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

        } 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 (!checkPhone(phone)) {
        return false;
    }

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

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

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