document.addEventListener('keydown', (event) => {
    var modals = document.getElementsByClassName('modal');
    if (event.key === 'Escape') {
        for (let i = 0; i < modals.length; i++) {
            closeForm(modals[i].id);
        }
    }
})

function openForm(id) {
    var modal = document.getElementById(id);
    modal.classList.add('is-active')
    document.getElementById('html').classList.add('is-clipped')
}

function closeForm(id) {
    $('.btn_reset').click();
    var modal = document.getElementById(id);
    modal.classList.remove('is-active');
    $('.erreur').html('');
    $('label.error').html('');
    document.getElementById('html').classList.remove('is-clipped')

}

function editForm() {
    var lesInputs = document.querySelectorAll('.formedit');
    document.getElementById('saveChanges').removeAttribute('disabled');

    lesInputs.forEach(e => {
        e.removeAttribute('disabled');
    });
}

function closeFormDetail() {
    document.getElementById('saveChanges').setAttribute('disabled', '');
    var lesInputs = document.querySelectorAll('.formedit');
    lesInputs.forEach(e => {
        e.setAttribute('disabled', '');
    });
    var modal = document.getElementById(id);
    modal.classList.remove('is-active')
}

// navbar js
document.addEventListener('DOMContentLoaded', () => {
    if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|BB|PlayBook|IEMobile|Windows Phone|Kindle|Silk|Opera Mini/i.test(navigator.userAgent)) {
        $('#barreRecherche').prependTo('#barreRechercheCopie');
    }
    // Get all "navbar-burger" elements
    const $navbarBurgers = Array.prototype.slice.call(document.querySelectorAll('.navbar-burger'), 0);

    // Check if there are any navbar burgers
    if ($navbarBurgers.length > 0) {

        // Add a click event on each of them
        $navbarBurgers.forEach(el => {
            el.addEventListener('click', () => {

                // Get the target from the "data-target" attribute
                const target = el.dataset.target;
                const $target = document.getElementById(target);

                // Toggle the "is-active" class on both the "navbar-burger" and the "navbar-menu"
                el.classList.toggle('is-active');
                $target.classList.toggle('is-active');

            });
        });
    }

});

//JS pour la recherche depuis le navbar
$('#rechercheNavigation').on('input', () => {
    $('#rechercheNavigation').focusout(() => {
        setTimeout(() => {
            $('#trouves').addClass('is-hidden');
            $('#rechercheNavigation').val('');
            $('#trouves').html('')
        }, 500);
    });
    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });
    $.ajax({
        url: "/rechercheEleveNavBar",
        type: "POST",
        dataType: 'json',
        beforeSend: function() {
            $('#loader').removeClass('hidden')
        },
        complete: function () { // Set our complete callback, adding the .hidden class and hiding the spinner.
            $('#loader').addClass('hidden')
        },
        data: {
            recherche: $('#rechercheNavigation').val(),
        },
        success: function (response) {
            if (response.length > 0) {
                $('#trouves').removeClass('is-hidden');
                if ($('#rechercheNavigation').val().length == 0) {
                    $('#trouves').addClass('is-hidden');
                }
                $('#trouves').empty();
                for (var i = 0; i < response.length; i++) {
                    $('#trouves').append("<div class='mb-2'><a href='/rechercheEleveNavBar/eleve/" + response[i].slug + "'>" + response[i].prenom + " " + response[i].nom + "</a></div>")
                }
            } else {
                $('#trouves').addClass('is-hidden');
                $('#trouves').append('');
            }
        },
        error: function (response) {
            console.log(response);
        }
    });
})

// Service Worker
if ('serviceWorker' in navigator) {
    navigator.serviceWorker.register('/sw.js')
        .then((registration) => {
            console.log('Service Worker enregistré avec succès:', registration);
        })
        .catch((error) => {
            console.log('Échec de l\'enregistrement du Service Worker:', error);
        });
}
