/*
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

$('#username').on("keyup", function () {
    $('#username').val($('#username').val().toLowerCase());
});

function checkAndSave(username, password) {
    app.preloader.show();

    callAPIRawResponse("ping", {
        username: username,
        password: password
    }, function (data) {
        localStorage.setItem("username", username);
        localStorage.setItem("password", password);
        localStorage.setItem("configured", true);
        callAPI("playerexists", {
            username: username,
            password: password
        }, function (resp) {
            app.preloader.hide();
            if (resp.exists == true) {
                router.navigate("/home");
            } else {
                router.navigate("/chooseteam");
            }
        }, function (msg) {
            app.preloader.hide();
            app.dialog.alert(msg, "Error");
        });
    }, function (msg, xhr) {
        app.preloader.hide();
        if (xhr.status == 401) {
            app.dialog.alert("Login incorrect.", "Error");
        } else {
            app.dialog.alert(msg, "Error");
        }
    });
}

function setupAccount() {
    var username = $("#username").val();
    var password = $("#password").val();

    checkAndSave(username, password);
}

$("#password").on("keyup", function (evt) {
    if (evt.keyCode == 13) {
        setupAccount();
    }
})