var playerName = undefined;
var errorShown = false;


$(document).ready(_ => {
    mp.trigger("CEF:Login_RequestPlayerName");

    $('.form').find('input, textarea').on('keyup blur focus', function (e) {

        var $this = $(this),
            label = $this.prev('label');

        if (e.type === 'keyup') {
            if ($this.val() === '') {
                label.removeClass('active highlight');
            } else {
                label.addClass('active highlight');
            }
        } else if (e.type === 'blur') {
            if ($this.val() === '') {
                label.removeClass('active highlight');
            } else {
                label.removeClass('highlight');
            }
        } else if (e.type === 'focus') {

            if ($this.val() === '') {
                label.removeClass('highlight');
            }
            else if ($this.val() !== '') {
                label.addClass('highlight');
            }
        }

    });

    $('.tab a').on('click', function (e) {

        e.preventDefault();

        $(this).parent().addClass('active');
        $(this).parent().siblings().removeClass('active');

        target = $(this).attr('href');

        $('.tab-content > div').not(target).hide();
        $(target).fadeIn(600);

    });

    $('#form-login').on('submit', e => {

        e.preventDefault();

        var username = $("#login-username").val();
        var password = $("#login-password").val();

        if (password.trim().length === 0 || username.trim().length === 0) {
            showError("Alle Felder müssen <b>ausgefüllt</b< werden");
            return;
        }
        
        mp.trigger('CEF:Login_LoginRequest', username, password);
    });

    $('#form-register').on('submit', e => {

        e.preventDefault();

        var username = $("#register-username").val();
        var password = $("#register-password-first").val();
        var passwordRepeat = $("#register-password-second").val();

        if (password.trim().length === 0 || username.trim().length === 0 || passwordRepeat.trim().length === 0) {
            showError("Alle Felder müssen <b>ausgefüllt</b< werden");
            return;
        }

        if (password !== passwordRepeat) {
            showError("Beide <b>Passwörter</b> müssen <b>übereinstimmen</b>");
            return;
        }

        mp.trigger('CEF:Login_RegisterRequest', username, password, passwordRepeat);
    });
});

function setPlayerName(name) {
    playerName = name;
    $(".input-username").val(playerName);
    $(".input-username").prev("label").addClass("active");
}

function showError(error) {
    $("#error-field p").html(error);
    if (errorShown) {
        $("#error-field").effect("shake", null, 500);
    } else {
        $("#error-field").slideDown();
    }

    errorShown = true;
}