$(document).ready(function () {
    $("#login-username").focus();

    $(document).keyup(function (e) {
        if (e.key === "Enter") {
            var focused = $(':focus').attr('data-id');

            if (focused == 'login-data') {
                $("#login-btn").click();
            } else if (focused == 'reg-data') {
                $("#reg-btn").click();
            } else {
                return false;
            }
        }
    });

    $('.toggle-div').click(function () {
        $('.form-div').slideToggle();

        let parent = $(this).parent('p').parent().attr('id');

        if (parent == 'login_form') {
            $("#jform_firstname").focus()
        } else {
            $("#login-username").focus()
        }
    });

    $('#continue-btn').click(function () {
        $('.form-div').slideToggle();
        $('#reg_form').show();
        $('.success_container').hide();
        $('#alert-div').hide();
    });

    $("#reg_form").submit(function (e) {
        e.preventDefault();

        let username = $('#jform_username').val();
        let firstname = $('#jform_firstname').val();
        let lastname = $('#jform_lastname').val();
        let email = $('#jform_email').val();
        let password = $('#jform_password').val();
        let password2 = $('#jform_password2').val();
        let ctrID = $('#ctrID').val();
        let name = firstname + ' ' + lastname;
        let phone = $('#jform_phone').val();

        $.ajax({
            type: "POST",
            url: "/index.php?option=com_users&Itemid=124&lang=hu&task=registration.registerWithARCHLine",
            data: {
                name: name,
                username: username,
                firstname: firstname,
                lastname: lastname,
                email: email,
                password: password,
                password2: password2,
                country: ctrID,
                phone: phone,
                captcha: grecaptcha.getResponse()
            },
            success: function (data) {
                let msg = '';
                let alertClass = '';
                let response = JSON.parse(data);

                $('#alert-div').removeClass('alert-danger');
                $('#alert-div').removeClass('alert-success');

                if (response.error) {
                    alertClass = 'alert-danger';
                } else {
                    alertClass = 'alert-success';

                    $('#reg_form').slideToggle();
                    $('.success_container').slideToggle();
                }

                msg = response.msg;

                $('#alert-div').addClass(alertClass);
                $('#alert-div').html(msg);
                $('#alert-div').show();
            }
        });
    });
});