

var baseUrl = "http://192.168.3.20/api/";

function get(api, data, callback) {
    http.ajax({
        type: "GET",
        data: data,
        url: baseUrl + api,
        success: function(result) {
            callback(result);
        },
        error: function () {
            callback();
        }
    });
}


function post(api, data, callback) {
    http.ajax({
        type: "POST",
        data: JSON.stringify(data),
        url: baseUrl + api,
        success: function(result) {
            callback(result);
        },
        error: function () {
            callback();
        }
    });
}

function getQueryVariable (variable) {
    var query = window.location.search.substring(1);
    var vars = query.split("&");
    for (var i=0;i<vars.length;i++) {
        var pair = vars[i].split("=");
        if(pair[0] == variable){return pair[1];}
    }
    return(false);
}

function getKey (callback) {
    get("verify_code", {}, function (result) {
        if(result.status === 200) {
            callback(result.data);
        }
    });
}

function show (text) {
    var dialog = document.getElementById('dialog');
    dialog.style.display = "block";
    document.getElementById("tips").innerHTML = text;

    setTimeout(function(){
        dialog.style.display = "none";
    }, 1500);
}

function verify (phone) {
    getKey(function (result) {
        var data = {
            code: "",
            key: result.key,
            phone: phone,
            type: "register"
        };
        post("register/verify", data, function (result) {
            if(result.status !== 200) {
                show(result.msg);
            }else{
                show("短信发送成功!");
            }
        });
    });
}

function register (phone, passwd, code) {
    console.log(phone, passwd, code);
    if(phone.trim() === ""){
        console.log('phone is null !');
        return;
    }
    var sp = getQueryVariable("sp");
    sp = sp === false ? null : sp;
    console.log(sp);

    var data = {
        account: phone,
        captcha: code,
        password: passwd,
        spread: sp
    };

    post("register", data, function (result) {
        console.log(result);
        if(result.status === 200) {
            show("注册成功!");
            document.location.href = "http://baidu.com";
        } else {
            show(result.msg);
        }
    });
}