$(document).ready(function () {
    scrollMenu();
    menuToggle();
    closeMenu();
    manageFormContact();
    manageFormSearch();
    manageFormIndiv();
    initialisePopovers();
});

function initialisePopovers() {
    $('[data-toggle="popover"]').popover({
        html: true,
        container: '.map',
        placement: 'top',
        trigger: 'focus',
    });

    $('[data-toggle="popover-bulle"]').popover({
        html: true,
        container: '.popup-bulle',
        trigger: 'click',
    });
}

function manageFormIndiv() {
    document
        .querySelectorAll('.add_item_link')
        .forEach(btn => btn.addEventListener("click", addFormToCollection));
}

const addFormToCollection = (e) => {
    const collectionHolder = document.querySelector('.' + e.currentTarget.dataset.collectionHolderClass);
    const item = document.createElement('li');
    item.innerHTML = collectionHolder
        .dataset
        .prototype
        .replace(
            /__name__/g,
            collectionHolder.dataset.index
        );

    collectionHolder.appendChild(item);

    collectionHolder.dataset.index++;

    if (collectionHolder.dataset.index >= 6) {
        e.currentTarget.style.visibility = 'hidden';
    }
    // add a delete link to the new form
    addFormDeleteLink(item, e.currentTarget);
};

const addFormDeleteLink = (formLi, currentTarget) => {
    const collectionHolder = document.querySelector('.' + currentTarget.dataset.collectionHolderClass);
    const removeFormButton = document.createElement('button')
    removeFormButton.classList.add('button-green', 'button-remove')
    removeFormButton.innerText = 'Supprimer'

    formLi.append(removeFormButton);

    removeFormButton.addEventListener('click', (e) => {
        collectionHolder.dataset.index--;
        if (collectionHolder.dataset.index <= 6) {
            currentTarget.style.visibility = 'visible';
        }
        e.preventDefault()
        formLi.remove();
    });
}

function menuToggle() {
    var box = $('.menu-content');
    var button = $('.toggle');
    button.on('click', function () {
        box.toggle('slow');
    });
}

function closeMenu() {
    var box = $('.menu-content');
    $('.row-menu a').on('click', function () {
        box.toggle('slow');
    })
}

function scrollMenu() {
    $('a[href*="#"]:not([href="#"])').click(function () {
        var target = $(this.hash);
        $('html,body').stop().animate({
            scrollTop: target.offset().top - 122
        }, 'linear');
    });
    if (location.hash) {
        var id = $(location.hash);
        $('html,body').animate({scrollTop: id.offset().top - 122}, 'linear')
    }
}

function manageFormSearch() {
    $(".dropdown-search").on("change", "input[type='checkbox']", function () {
        $(this).closest("li").toggleClass("active", this.checked);
    });

    $(document).on('click', '.allow-focus', function (e) {
        e.stopPropagation();
    });

    $('.pagination a').click(function (e) {
        console.log(this.href.split('page=')[1]);
        $('.hidden-page').val(this.href.split('page=')[1]);
        $('.search-button').click();
        return false;
    });
}

function manageFormContact() {
    $('.lccap').val('blop');
    $('#contact-form-btn').on('click', function () {
        if (checkFormValidity('#contact-form')) {
            $('#contact-form').fadeOut(200);
            $form = $('#contact-form');
            $.ajax({
                url: $form.prop('action'),
                method: $form.prop('method'),
                data: $form.serialize(),
                dataType: "json",
                success: function (response) {
                    $('#contact-form').html('<p class="success-post">Merci pour votre message, nous vous r&eacute;pondrons dans les plus brefs d&eacute;lais.</p>');
                    $('#contact-form').fadeIn(500);
                }
            });
        }
    });
}

function checkFormValidity(formId) {
    if (!document.getElementById(formId.substr(1)).checkValidity()) {
        document.getElementById(formId.substr(1)).reportValidity()
        return false;
    } else {
        return true;
    }
}