$(document).ready(function(){

    // ******* Navbars & dropdowns *******
    // add the 'dropdown' class on menus with children
    $('.first-level-menu, .second-level-menu').each((i, menu) => {
        if ($(menu).find('.subMenu')) {
            $(menu).addClass('dropdown');
        }
    })

    // delay in ms before dropdown collapse after the cursor leave
    var collapsingDelay = 400;

    // hide the dropdown element and its children
    var hideDropdownsFor = function(elt, delay=0) {
        if (delay === 0) {
            elt.children('ul.dropdown-menu').removeClass('dropdown-displayed');
            elt.removeClass('dropdown-displayed');
            elt.children('ul.dropdown-menu').hide();
        } else {
            elt.delay(delay).queue(function(next) {
                elt.children('ul.dropdown-menu').removeClass('dropdown-displayed');
                elt.removeClass('dropdown-displayed');
                next();
            });
            elt.children('ul.dropdown-menu').delay(delay).hide(1);
        }
    }

    // stop any delayed commands on elt and its children
    var stopDelayedHidingFor = function(elt) {
        elt.stop(true);
        elt.children('ul.dropdown-menu').stop(true);
    }

    $('.dropdown').on('mouseenter tap', function(e) {

        // Special: block this event on mobile and tablet versions
        if ($('#menu-container .toggle-menu:visible').length > 0) {
            return;
        }

        e.preventDefault();

        // stop any delayed hiding on this since the cursor went back on it
        stopDelayedHidingFor($(this));

        // hide every other dropdown in the page
        $('.dropdown.dropdown-displayed').not($(this).parents()).each(function() {
            hideDropdownsFor($(this));
        });

        // display the dropdown
        dropdown = $(this).find('ul.dropdown-menu:first');

        if (dropdown.length !== 0) {
            $(this).addClass('dropdown-displayed');
            dropdown.addClass('dropdown-displayed');
            dropdown.show();

            // if this is a second level dropdown
            if ($(this).parents('.dropdown').length !== 0) {

                // move it on the right or left according to its current position
                dropdown.removeClass('dropdown-left').removeClass('dropdown-right');
                if (($(this).offset().left + $(this).width() + dropdown.width()) > $(window).width()) {
                    dropdown.addClass('dropdown-left');
                } else {
                    dropdown.addClass('dropdown-right');
                }
            }
        }

    }).on('mouseleave', function(e) {
        // Special: block this event on mobile and tablet versions
        if ($('#menu-container .toggle-menu:visible').length > 0) {
            return;
        }

        if ($(this).hasClass('delayed-collapsing')) {
            hideDropdownsFor($(this), collapsingDelay);
        } else {
            hideDropdownsFor($(this));
        }
    });

    // * Sticky menu
    if ($('#menu').length) {
        var menuTop = $('#menu').offset().top;
        var menuHeight = $('#menu').height();
    }

    $(function(){
        $(window).scroll(function() {

            // Not for little screens
            if ($('#menu-container .toggle-menu').is(":visible")) {
                return;
            }

            if ($(this).scrollTop() >= menuTop) {
                $('#menu-container').addClass('sticky');
            }
            else if (($(this).scrollTop() < (menuTop - menuHeight)) || ($(this).scrollTop() === 0)) {
                $('#menu-container').removeClass('sticky');
            }
        });
    });

    // * Responsive menu

    $('#menu-container .toggle-menu').on('click', function() {
        $('#menu').toggleClass('show-flex');
    });

    $('.toggle-dropdown').on('click', function(e) {
        var dropdown = $(this).closest('.dropdown');
        var dropdown_menu = dropdown.find('.dropdown-menu').first();
        dropdown_menu.toggleClass('show-flex');
        $(this).toggleClass('fa-plus');
        $(this).toggleClass('fa-minus');
    });



    // **** Login Pop-Up and Auth
    $('#login-btn').on('click', function(e) {
        e.preventDefault();
        $('#login-popup .popup-form').toggleClass("show");
    });

    if ($('#login-popup').find('.alert').length) {
        $('#login-popup .popup-form').toggleClass("show");
    }

    // **** Forms ****
    $('.search-submit').on('click', function(e) {
        $(this).parent('form').submit();
    })

    $('.datepicker').datepicker({
        minDate: new Date(),
        maxDate: "+2y",
        dayNames: [ "Dimanche", "Lundi", "Mardi", "Mercredi", "Jeudi", "Vendredi", "Samedi" ],
        dayNamesMin: [ "Di", "Lu", "Ma", "Me", "Je", "Ve", "Sa" ],
        dayNamesShort: [ "Dim", "Lun", "Mar", "Mer", "Jeu", "Ven", "Sam" ],
        monthNames: [ "Janvier", "Février", "Mars", "Avril", "Mai", "Juin", "Juillet", "Août", "Septembre", "Octobre", "Novembre", "Décembre" ],
        monthNamesShort: [ "Jan", "Fev", "Mar", "Avr", "Mai", "Jui", "Juil", "Aou", "Sep", "Oct", "Nov", "Dec" ],
        dateFormat: "dd/mm/yy"
    });

    // **** Carousels *****

    // uses the slick lib, see https://kenwheeler.github.io/slick/
    $('header .carousel').slick({
        arrows: false,
        dots: false,
        autoplay: true,
        autoplaySpeed: 3600,
        draggable: false,
        speed: 700,
        adaptiveHeight: false
    });

    $('.content .carousel').slick({
        arrows: true,
        dots: true,
        autoplay: true,
        autoplaySpeed: 5000,
        draggable: false,
        speed: 700
    });

    $('.ot-donors .carousel').slick({
        arrows: false,
        dots: false,
        autoplay: true,
        autoplaySpeed: 4800,
        draggable: false,
        speed: 700
    });

    // **** Leaflet: maps *****
    var map;

    function showMap(mapDiv, zoomToItems=true) {

        let mapId = $(mapDiv).attr("id");
        if (!mapId) {
            console.error('missing id attribute for map');
            return;
        }

        // Collect the data from th map children <i>
        let items = [];
        mapDiv.children('.item-geodata').each(function () {
            let item = {
                id: $(this).data('id'),
                long: $(this).data('long'),
                lat: $(this).data('lat'),
                label: $(this).data('label')
            };
            items.push(item);
        });

        // Instanciate the map object  @see https://leafletjs.com/reference-1.6.0.html#map-factory
        const mapOptions = {scrollWheelZoom: false, zoomSnap: 0.25};
        map = L.map(mapId, mapOptions);
        if (zoomToItems && items.length > 0) {
            map.setView([items[0].lat, items[0].long], 13);
        } else {
            map.setView([46.71, 2.14], 6);
        }

        // Add the tile layer
        L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
            attribution: '&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
        }).addTo(map);

        // Collect the event geodata to create the markers
        let markers = [];

        items.forEach(function (item) {
            let marker = L.marker([item.lat, item.long]).addTo(map);
            marker.bindPopup(item.label);
            markers.push(marker);
        });

        // Set the view
        let bounds = null;
        if (zoomToItems && items.length > 0) {
            const markersGroup = new L.featureGroup(markers);
            bounds = markersGroup.getBounds()
        } else {
            bounds = L.latLngBounds(
                    L.latLng(51.03, -5.78),
                    L.latLng(41.2, 9.70)
                );
        }
        if (bounds !== null) {
            map.fitBounds(bounds);
            // map.zoomOut();
        }
    }

    // Display map on events index page
    if ($('.ot-all-events #event-map').length) {
        showMap($('#event-map').first());
    }

    // Display map on event's details page
    if ($('.ot-show-event #event-map').length) {
        showMap($('#event-map').first());
    }

    // Display map on (non-framed) network structures page
    if ($('.ot-structures #structure-map').length) {
        showMap($('#structure-map').first());
    }

});



