// source --> https://www.vaud.ch/app/themes/child/assets/scripts/main.js 
(function ($) {
    //Header sticky
    function headerSticky() {
        if ($(this).scrollTop() > 50) {
            $("#website-menu").addClass("sticky");
            $(".mobile-iam-btn").addClass("sticky-btn");
        } else {
            $("#website-menu").removeClass("sticky");
            $(".mobile-iam-btn").removeClass("sticky-btn");
        }

        $(window).on("scroll", function () {
            if ($(this).scrollTop() > 50) {
                $("#website-menu").addClass("sticky");
                $(".mobile-iam-btn").addClass("sticky-btn");
            } else {
                $("#website-menu").removeClass("sticky");
                $(".mobile-iam-btn").removeClass("sticky-btn");
            }
        });

        $(".main-menu-inner > li.menu-item-has-children").hover(
            function () {
                $("body").addClass("menu-open");
            },
            function () {
                $("body").removeClass("menu-open");
            }
        );
    }

    //Back to top
    function backToTop() {
        $(".back-to-top").on("click", function (e) {
            e.preventDefault();
            $("html, body").animate({ scrollTop: 0 }, "300");
        });
    }

    //Slider
    function slider() {

        const hasSpecialClass = $(".slider-load").parent().hasClass('header-season');

        $(".slider-load").slick({
            infinite: true,
            slidesToShow: 1,
            slidesToScroll: 1,
            autoplay: true,
            autoplaySpeed: 5000,
            arrows: hasSpecialClass,
            pauseOnFocus: false,
            pauseOnHover: false,
            fade: true,
            responsive: [
                {
                    breakpoint: 767,
                    settings: {
                        dots: true,
                    },
                },
            ],
        });


        if ($(".first-slide video").length || $(".first-slide iframe").length) {
            $(".slider-load").slick("slickPause");
        }

        var initialDelay = 3000;

        if ($(".loader").length) {
            $(".slider-load").slick("slickPause");
            setTimeout(function () {
                $(".slider-load").slick("slickPlay");
            }, initialDelay);
        }

        $(".slider-nav li[data-slide]").on("click", function (e) {
            e.preventDefault();
            var slideno = $(this).attr("data-slide");
            $(".slider-load").slick("slickGoTo", slideno - 1);
            $(".slider-nav li[data-slide]").removeClass("active");
            $(this).addClass("active");
        });

        $(".slider-load").on("beforeChange", function (event, slick, currentSlide, nextSlide) {
            // then let's do this before changing slides
            $(".slider-load video").each(function () {
                $(this).get(0).pause();
                //$(this).get(0).currentTime = 0;
            });

            $(".slider-load iframe").each(function () {
                var player, command;
                player = $(this).get(0);
                command = {
                    event: "command",
                    func: "pauseVideo",
                };

                if (player != undefined) {
                    //post our command to the iframe.
                    player.contentWindow.postMessage(JSON.stringify(command), "*");
                }
            });

            var vid = $(slick.$slides[nextSlide]).find("video");
            var youtube = $(slick.$slides[nextSlide]).find("iframe");
            var player, command;
            if (vid.length > 0) {
                $(".slider-load").slick("slickPause");
                $(vid).get(0).play();
            } else if (youtube.length > 0) {
                $(".slider-load").slick("slickPause");
                player = youtube.get(0);
                //console.log(player);
                command = {
                    event: "command",
                    func: "playVideo",
                };

                if (player != undefined) {
                    //post our command to the iframe.
                    player.contentWindow.postMessage(JSON.stringify(command), "*");
                }
            } else {
                $(".slider-load").slick("slickPlay");
            }
        });

        $(".slider-load").on("afterChange", function (event, slick, currentSlide, nextSlide) {
            var currentSlide = currentSlide + 1;

            $(".slider-nav li[data-slide]").removeClass("active");
            $(".slider-nav li[data-slide='" + currentSlide + "']").addClass("active");
        });
    }

    //Post slider
    function postSlider() {
        if ($(".posts-slider").length) {
            $(".posts-slider").each(function () {
                $(this).slick({
                    slidesToShow: 2,
                    slidesToScroll: 1,
                    nextArrow: $(this).siblings(".post-list-arrows").find(".next-arrow"),
                    prevArrow: $(this).siblings(".post-list-arrows").find(".prev-arrow"),
                    infinite: false,
                    lazyLoad: "anticipated",
                    // responsive: [
                    //     {
                    //         breakpoint: 576,
                    //         settings: {
                    //             slidesToShow: 1,
                    //         },
                    //     },
                    // ],
                });
            });
        }

        if ($(".events-slider").length) {
            $(".events-slider").each(function () {
                $slick_slider = $(this);
                settings = {
                    slidesToShow: 1,
                    slidesToScroll: 1,
                    rows: 2,
                    infinite: false,
                    nextArrow: $(this).siblings(".post-list-arrows").find(".next-arrow"),
                    prevArrow: $(this).siblings(".post-list-arrows").find(".prev-arrow"),
                    lazyLoad: "anticipated",
                    responsive: [
                        {
                            breakpoint: 991,
                            settings: {
                                slidesToShow: 2,
                                slidesToScroll: 1,
                            },
                        },
                    ],
                };
                $slick_slider.slick(settings);

                // reslick only if it's not slick()
                $(window).on("resize", function () {
                    if (window.innerWidth < 768) {
                        if ($slick_slider.hasClass("slick-initialized")) {
                            $slick_slider.slick("unslick");
                        }
                        return;
                    }

                    if (!$slick_slider.hasClass("slick-initialized")) {
                        return $slick_slider.slick(settings);
                    }
                });

                if (window.innerWidth < 768) {
                    if ($slick_slider.hasClass("slick-initialized")) {
                        $slick_slider.slick("unslick");
                    }
                    return;
                }

                if (!$slick_slider.hasClass("slick-initialized")) {
                    return $slick_slider.slick(settings);
                }
            });

            if (window.innerWidth > 768 && window.innerWidth < 991) {
                var maxHeight = 0;
                $(".events-slider .slick-slide > div:first-child").each(function () {
                    var height = $(this).height();
                    if (height > maxHeight) {
                        maxHeight = height;
                    }
                });
                $(".events-slider .slick-slide > div:first-child").height(maxHeight);
            }

            $(window).on("resize", function () {
                if (window.innerWidth > 768 && window.innerWidth < 991) {
                    var maxHeight = 0;
                    $(".events-slider .slick-slide > div:first-child").each(function () {
                        var height = $(this).height();
                        if (height > maxHeight) {
                            maxHeight = height;
                        }
                    });

                    $(".events-slider .slick-slide > div:first-child").height(maxHeight);
                }
            });
        }
    }

    //Call to action slider
    function ctaSlider() {
        if ($(".call-to-action").length) {
            $(".call-to-action").each(function () {

                let slidesToShow;
                let slidesToShowSmallDesktop;
                if($(this).hasClass("v2")) {
                    slidesToShow = 4;
                    slidesToShowSmallDesktop = 4;
                } else {
                    slidesToShow = 3;
                    slidesToShowSmallDesktop = 2;
                }

                var item_length = $(this).find(" > *").length - 1;
                $(this).slick({
                    slidesToShow: slidesToShow,
                    slidesToScroll: 1,
                    nextArrow: $(this).siblings(".post-list-arrows").find(".next-arrow"),
                    prevArrow: $(this).siblings(".post-list-arrows").find(".prev-arrow"),
                    infinite: false,
                    lazyLoad: "anticipated",
                    responsive: [
                        {
                            breakpoint: 1300,
                            settings: {
                                slidesToShow: slidesToShowSmallDesktop,
                            },
                        },
                        {
                            breakpoint: 767,
                            settings: {
                                slidesToShow: 2,
                            },
                        },
                    ],
                });

                $(this).on("afterChange", function (event, slick, currentSlide) {
                    if (slick.currentSlide >= slick.slideCount - slick.options.slidesToShow) {
                        $(this).addClass("finished");
                    } else {
                        $(this).removeClass("finished");
                    }
                });
            });
        }
    }

    //Gallery
    function lightgallery() {
        if ($(".lightgallery").length) {
            $(".lightgallery").not(".itinerary-block .lightgallery").lightGallery({
                selector: ".grid-item",
                hash: false,
                videojs: true
            });
        }

        if ($(".gallery-slider").length) {
            $(".gallery-slider").slick({
                infinite: true,
                slidesToShow: 1,
                slidesToScroll: 1,
                arrows: true,
                dots: true,
                adaptiveHeight: true,
                lazyLoad: "progressive",
                prevArrow: "<button type='button' class='slick-prev'><lord-icon src='https://cdn.lordicon.com/zmkotitn.json' trigger='hover' colors='primary:#ffffff' style='width:60px;height:60px'></lord-icon></button>",
                nextArrow: "<button type='button' class='slick-next'><lord-icon src='https://cdn.lordicon.com/zmkotitn.json' trigger='hover' colors='primary:#ffffff' style='width:60px;height:60px'></lord-icon></button>",
            });

            $(".gallery-slider").on("beforeChange", function (event, slick, currentSlide, nextSlide) {
                const currentVideo = $(slick.$slides[nextSlide]).find("video").get(0);
                if (currentVideo) {
                    // Forcer le recalcul des contrôles avant le changement
                    currentVideo.controls = false; // Désactive temporairement les contrôles
                    setTimeout(() => {
                        currentVideo.controls = true; // Réactive les contrôles pour forcer leur recalcul
                    }, 0);
                }
            });
        }
    }

    //Accordion
    function accordion() {
        $(".accordion-item .accordion-header").on("click", function () {
            var parentSelector = $(this).parent(".accordion-item");
            parentSelector.siblings().removeClass("active");
            parentSelector.stop().toggleClass("active");
            parentSelector.siblings().find(".accordion-header").removeClass("active");
            $(this).stop().toggleClass("active");
            parentSelector.siblings().find(".accordion-content").slideUp();
            $(this).siblings(".accordion-content").stop().slideToggle();
        });
    }

    //Tabs
    function tabs() {
        $(".tabs-nav li").on("click", function () {
            var related_tab = $(this).attr("data-tab-nav");
            $(this).siblings().removeClass("active");
            $(this).stop().toggleClass("active");
            $(this).parents(".tabs-nav").siblings(".tabs-content").find(".tab").hide();
            $(this).parents(".tabs-nav").siblings(".tabs-content").find(".tab").removeClass("active");
            $('[data-tab-content="' + related_tab + '"]')
                .stop()
                .fadeIn();

            $(".gallery-slider").slick("refresh");
        });

        $(".tourism-office-tabs .wp-block-heading a").on("click", function (e) {
            e.preventDefault();
            var target = $(this).attr("href");
            var target = target.split("#")[1];
            $(this).addClass("active");
            $(this).siblings().removeClass("active");

            $(this).parents(".tourism-office-tabs").find(".contact-information-wrapper").removeClass("active");
            $(this).parents(".tourism-office-tabs").find(".contact-information-wrapper[id='" + target + "']").addClass("active");
        });
    }

    //SELECT
    function create_custom_dropdowns() {
        $("select").each(function (i, select) {
            if (!$(this).next().hasClass("dropdown")) {
                $(this).after('<div class="dropdown ' + ($(this).attr("class") || "") + '" tabindex="0"><span class="current"></span><div class="list"><ul></ul></div></div>');
                var dropdown = $(this).next();
                var selected = $(this).find("option:selected");
                dropdown.find(".current").html(selected.data("display-text") || selected.text());

                if ($(this).hasClass("with-search")) {
                    var placeholder = $(this).attr("data-placeholder");
                    dropdown.find(".list").prepend('<input type="text" placeholder="' + placeholder + '" class="dropdown-search">');
                }

                if ($(this).hasClass("hierarchical-select")) {
                    dropdown.addClass("dropdown-group");
                    dropdown.removeClass("dropdown");
                    var all_label = $(this).attr("data-all-label");
                    var options = $(select).find(" > *");
                    options.each(function (j, o) {
                        var display = $(o).text();
                        //var options = $(o).find("option");
                        var level = $(o).attr("data-level");
                        if (typeof $(this).data("id") !== "undefined") {
                            var id = $(o).attr("data-id");
                        }
                        if ($(this).hasClass("has-children")) {
                            if (!$(this).attr("data-parent-id")) {
                                dropdown.find(".list > ul").append('<li class="option parent level-' + level + '" data-label="' + display + '" data-id="' + id + '"><span>' + display + "</span><ul></ul></li>");
                            } else {
                                var parent_id = $(this).attr("data-parent-id");
                                dropdown.find("li[data-id='" + parent_id + "'] > ul").append('<li class="option parent level-' + level + '" data-label="' + display + '" data-id="' + id + '">' + "<span>" + display + "</span>" + "<ul></ul>" + "</li>");
                            }
                        } else if ($(this).attr("data-parent-id")) {
                            var parent_id = $(this).attr("data-parent-id");
                            dropdown.find("li[data-id='" + parent_id + "'] > ul").append('<li class="option level-' + level + '" data-label="' + display + '" data-value="' + id + '"><span>' + display + "</span></li>");
                        } else {
                            var display = $(o).data("display-text") || "";
                            dropdown.find(".list > ul").append('<li class="option ' + ($(o).is(":selected") ? "selected" : "") + '" data-value="' + $(o).val() + '" data-display-text="' + display + '"><span>' + $(o).text() + "</span></li>");
                        }
                    });
                } else {
                    var options = $(select).find("option");
                    options.each(function (j, o) {
                        var display = $(o).data("display-text") || "";
                        dropdown.find("ul").append('<li class="option ' + ($(o).is(":selected") ? "selected" : "") + '" data-value="' + $(o).val() + '" data-display-text="' + display + '">' + $(o).text() + "</li>");
                    });
                }
            }
        });
    }

    $(document).on("keyup", ".dropdown-search", function () {
        var value = this.value.toLowerCase().trim();
        $(this)
            .siblings("ul")
            .find("li")
            .show()
            .filter(function () {
                return $(this).text().toLowerCase().trim().indexOf(value) == -1;
            })
            .hide();
    });

    // Event listeners
    // Open/close
    $(document).on("click", ".dropdown", function (event) {
        if ($(event.target).closest(".dropdown-search").length === 0) {
            $(".dropdown").not($(this)).removeClass("open");
            $(this).toggleClass("open");
            $(".ginput_container_select").parent(".gfield").not($(this)).removeClass("open");
            $(".ginput_container_select").parent(".gfield").toggleClass("open");
            $(".ginput_container_select").parent(".form_field").not($(this)).removeClass("open");
            $(".ginput_container_select").parent(".form_field").toggleClass("open");
            if ($(this).hasClass("open")) {
                $(this).find(".option").attr("tabindex", 0);
                $(this).find(".selected").focus();
            } else {
                $(this).find(".option").removeAttr("tabindex");
                $(this).focus();
            }
        }
    });

    // Close when clicking outside
    $(document).on({
        touchstart: function (event) {
            if ($(event.target).closest(".dropdown, .dropdown-group, .dropdown-search").length === 0) {
                $(".dropdown, .dropdown-group").removeClass("open");
                $(".dropdown .option").removeAttr("tabindex");
            }
            event.stopPropagation();
        },
    });

    $(document).on("click", function (event) {
        if ($(event.target).closest(".dropdown, .dropdown-group, .dropdown-search").length === 0) {
            $(".dropdown, .dropdown-group").removeClass("open");
            $(".dropdown .option").removeAttr("tabindex");
        }
        event.stopPropagation();
    });

    // Option click
    $(document).on("click", ".dropdown .option", function (event) {
        $(this).closest(".list").find(".selected").removeClass("selected");
        $(this).addClass("selected");
        var text = $(this).data("display-text") || $(this).text();
        $(this).closest(".dropdown").find(".current").text(text);
        $(this).closest(".dropdown").prev("select").val($(this).data("value")).trigger("change");
    });

    // Keyboard events
    $(document).on("keydown", ".dropdown", function (event) {
        var focused_option = $($(this).find(".list .option:focus")[0] || $(this).find(".list .option.selected")[0]);
        // Space or Enter
        if (event.keyCode == 13) {
            if ($(this).hasClass("open")) {
                focused_option.trigger("click");
            } else {
                $(this).trigger("click");
            }
            return false;
            // Down
        } else if (event.keyCode == 40) {
            if (!$(this).hasClass("open")) {
                $(this).trigger("click");
            } else {
                focused_option.next().focus();
            }
            return false;
            // Up
        } else if (event.keyCode == 38) {
            if (!$(this).hasClass("open")) {
                $(this).trigger("click");
            } else {
                focused_option = $($(this).find(".list .option:focus")[0] || $(this).find(".list .option.selected")[0]);
                focused_option.prev().focus();
            }
            return false;
            // Esc
        } else if (event.keyCode == 27) {
            if ($(this).hasClass("open")) {
                $(this).trigger("click");
            }
            return false;
        }
    });

    // Menu mobile
    function menuMobile() {
        $(".menuburger").on("click", function () {
            if ($(this).hasClass("active")) {
                $(".menu-mobile").fadeOut();
                $(this).removeClass("active");
                $("#website-menu").removeClass("menu-open");

                $(".menu-mobile .menu-mobile-header *").remove();
                $(".menu-mobile .menu-mobile-footer .calendar-btn").remove();
                $(".menu-mobile .menu-mobile-footer .slider-socials").hide();

                $("body, html").removeClass("no-scroll");
            } else {
                $(this).addClass("active");
                $("#main-menu-inner").clone().appendTo($(".menu-mobile .menu-mobile-header"));
                $(".calendar-btn:not(.mobile-calendar-btn)").clone().prependTo($(".menu-mobile .menu-mobile-footer"));
                $(".main-search").clone().prependTo($(".menu-mobile .menu-mobile-header"));
                $(".menu-mobile .menu-mobile-footer .slider-socials").show();
                searchInput();
                //$(".menu-mobile").css("display", "flex").hide().fadeIn();

                $(".menu-mobile").css("display", "flex").hide().fadeIn(function() {
                    // Forcer le chargement des images lazy load dans le menu mobile
                    $(".menu-mobile .lazyload").each(function() {
                        var $img = $(this);
                        var dataSrc = $img.attr("data-src");
                        var currentSrc = $img.attr("src") || "";
                        if (dataSrc && (currentSrc === "" || currentSrc.indexOf("loading-pixel") !== -1)) {
                            $img.attr("src", dataSrc).removeClass("lazyload").addClass("lazyloaded");
                            // Déclencher l'événement pour a3 Lazy Load si disponible
                            if (typeof window.a3_lazy_load !== 'undefined' && window.a3_lazy_load.load) {
                                window.a3_lazy_load.load($img[0]);
                            }
                        }
                    });
                });
                $("#website-menu").addClass("menu-open");

                $("body, html").addClass("no-scroll");
            }
        });

        $(document).on("click", ".menu-mobile .main-menu-inner .menu-item-has-children > a", function (e) {
            e.preventDefault();
            //$(this).siblings(".sub-menu").slideToggle();
            $(this).parent().toggleClass("sub-open");
            if (!$(this).siblings(".sub-menu").find(".submenu-header").length) {
                var item_title = $(this).text();
                $(this)
                    .siblings(".sub-menu")
                    .prepend('<div class="submenu-header">' + item_title + "</div>");
            }
        });

        // $(document).on("click", ".main-menu-inner > li > .sub-menu > ul > li.menu-item-has-children > a", function (e) {
        //     e.preventDefault();
        //     $(this).siblings(".sub-menu").slideToggle();
        //     $(this).parent().toggleClass("sub-open");
        // });

        $(document).on("click", ".submenu-header", function (e) {
            e.preventDefault();
            $(this).closest(".menu-item-has-children").removeClass("sub-open");
        });

        if (window.innerWidth > 767) {
            $("body").removeClass("mobile");
        } else {
            $("body").addClass("mobile");
        }

        $(window).on("resize", function () {
            if (window.innerWidth > 767) {
                $(".menu-mobile").removeAttr("style");
                $(".menu-mobile .menu-mobile-header *").remove();
                $(".menu-mobile .menu-mobile-footer .calendar-btn").remove();
                $("body").removeClass("mobile");
                $(".accordion-mobile .wp-block-group").removeAttr("style");
                $(".menuburger").removeClass("active");
            } else {
                $("body").addClass("mobile");
            }

            if (window.innerWidth > 991) {
                $(".mobile-filters-btn").removeClass("open");
                $(".filter-inner").removeAttr("style");
            }
        });
    }

    function ajaxPostFilter() {
        $(".posts-by-category").each(function () {
            var elem = $(this);
            /********* CAT FILTER ***********/
            $(this)
                .find(".category-filter li")
                .on("click", function () {
                    const cat_values = [];
                    if ($(this).hasClass("all")) {
                        $(this).siblings("li").removeClass("active");
                        $(this).toggleClass("active");
                    } else {
                        $(this).toggleClass("active");
                        $(".category-filter li.all").removeClass("active");
                    }

                    $(this)
                        .parents(".category-filter")
                        .find("li.active")
                        .each(function () {
                            var cat = $(this).attr("data-value");
                            if (cat != "") {
                                cat_values.push(cat);
                            }
                        });

                    const max_post = elem.attr("data-max-post");
                    //console.log(cat_values);
                    //console.log(max_post);

                    $("body").addClass("loading");
                    ajax_filter_posts(cat_values, max_post);
                });

            $(this)
                .find(".load-more-btn")
                .on("click", function (e) {
                    // prevent action
                    e.preventDefault();

                    if ($(this).parents(".posts-by-category").hasClass("with-filters")) {
                        var cat_values = [];
                        elem.find(".category-filter li.active").each(function () {
                            var cat = $(this).attr("data-value");
                            if (cat != "") {
                                cat_values.push(cat);
                            }
                        });
                    } else {
                        var categories = $(this).attr("data-categories");
                        if (categories != "") {
                            var cat_values = categories.split("-");
                        } else {
                            var cat_values = [];
                        }
                    }

                    var offset = $(this).attr("data-count-post");
                    var max_post = $(this).attr("data-post-per-page");
                    var btn = $(this);

                    $("body").addClass("loading");
                    //console.log(cat_values);
                    //console.log(max_post);

                    load_more(cat_values, max_post, offset, btn);
                });

            function ajax_filter_posts(cat_values, max_post) {
                const currentUrl = window.location.href.split("?")[0];
                window.history.replaceState({}, "", currentUrl);
                $.ajax({
                    url: ajax.ajaxurl,
                    method: "POST",
                    data: {
                        action: "filter_posts",
                        cat_values: cat_values,
                        max_post: max_post,
                    },
                    success: function (response) {
                        elem.find(".posts-by-category-list").html(response.content);
                        elem.find(".load-more-btn").attr("data-count-post", response.count);

                        if (response.delete_btn == true) {
                            elem.find(".load-more-btn").hide();
                        } else {
                            elem.find(".load-more-btn").fadeIn().css("display", "inline-block");
                        }
                    },
                    error: function (xhr, textStatus) {},
                    complete: function () {
                        $("body").removeClass("loading");
                    },
                });
            }

            function load_more(cat_values, max_post, offset, btn) {
                $.ajax({
                    url: ajax.ajaxurl,
                    method: "POST",
                    data: {
                        action: "load_more",
                        offset: offset,
                        max_post: max_post,
                        cat_values: cat_values,
                    },
                    success: function (response) {
                        btn.fadeOut();

                        elem.find(".posts-by-category-list").append(response.content);
                        elem.find(".load-more-btn").attr("data-count-post", response.new_offset);

                        if (response.delete_btn == true) {
                            elem.find(".load-more-btn").fadeOut();
                        } else {
                            elem.find(".load-more-btn").fadeIn().css("display", "inline-block");
                        }
                    },
                    error: function (xhr, textStatus) {},
                    complete: function () {
                        $("body").removeClass("loading");
                    },
                });
            }

            $(document).on("click", ".posts-by-category-list .card", function () {
                // Nettoyer l'URL en supprimant les paramètres existants
                const currentUrl = window.location.href.split("?")[0];
                window.history.replaceState({}, "", currentUrl);
                // Récupérer les paramètres de filtrage actuels
                var category = elem.find(".category-filter .active").attr("data-value");

                // Récupérer les informations sur le nombre d'éléments affichés
                var totalItems = elem.find(".load-more-btn").attr("data-count-post");

                // Créer un objet avec les paramètres
                var filterParams = {
                    category: category,
                    totalItems: totalItems,
                };

                // Stocker dans le localStorage
                localStorage.setItem("newsFilters", JSON.stringify(filterParams));
            });
        });
    }

    function searchBtn() {
        $(".search-btn").on("click", function (e) {
            e.preventDefault();
            e.stopPropagation();
            $(this).toggleClass("active");
            $(".search-form").toggleClass("open");
            $("body").toggleClass("menu-open");
            $("body").toggleClass("search-open");
            if ($(this).hasClass("active")) {
                $(this).html('<lord-icon src="https://cdn.lordicon.com/nhfyhmlt.json" trigger="hover" colors="primary:#0A4069" style="width:27px;height:27px"></lord-icon>');
            } else {
                $(this).html('<lord-icon src="https://cdn.lordicon.com/xfftupfv.json" trigger="hover" colors="primary:#0A4069" style="width:27px;height:27px"></lord-icon>');
            }
        });

        $(document).on("click", function () {
            $(".search-btn").removeClass("active");
            $(".search-btn").html('<lord-icon src="https://cdn.lordicon.com/xfftupfv.json" trigger="hover" colors="primary:#0A4069" style="width:27px;height:27px"></lord-icon>');
            $(".search-form").removeClass("open");
            $("body").removeClass("menu-open");
            $("body").removeClass("search-open");
        });

        $(".search-form").on("click", function (e) {
            e.stopPropagation();
        });
    }

    function menuIam() {
        $(document).on("click", ".iam-btn", function (e) {
            e.preventDefault();
            $(".iam-menu").addClass("open");
            $("body,html").addClass("no-scroll");
        });

        $(".iam-menu lord-icon.close").on("click", function () {
            $(".iam-menu").removeClass("open");
            $("body,html").removeClass("no-scroll");
        });

        $(document).on("click", ".iam-menu", function (event) {
            if (!$(event.target).closest("#iam-menu, .iam-menu .iam-back-btn, .iam-menu .role").length) {
                $(".iam-menu").removeClass("open");
                $("body,html").removeClass("no-scroll");
            }
        });

        $(document).on("click", ".iam-menu.second-level .iam-back-btn", function () {
            $(".menu-iam").removeClass("hidden");
            $(".iam-menu-inner > .sub-menu").remove();
            $(".iam-menu h3 .role").text("...");
            $(".iam-menu").removeClass("second-level");
        });

        $(document).on("click", ".menu-iam .menu-item.menu-item-has-children a", function (e) {
            e.preventDefault();
            if ($(this).find("> .title").length) {
                var title = $(this).find("> .title").text();
            } else {
                var title = $(this).text();
            }

            $(".iam-menu h3 .role").html(" <span class='green'>" + title + "</span>");
            $(this).siblings(".sub-menu").clone().appendTo($(".iam-menu-inner"));
            $(".iam-menu-inner .sub-menu").addClass("open");
            $(".menu-iam").addClass("hidden");
            $(".iam-menu").addClass("second-level");
        });

        $(".iam-menu-inner .menu-iam .menu-item .sub-menu").each(function () {
            var related_item = $(this).parent(".menu-item").attr("id");
            $(this).attr("data-related", related_item);
        });

        var count_item = $("#iam-menu > li").length;

        if (count_item > 4) {
            $(".menu-iam").slick({
                slidesToShow: 4,
                slidesToScroll: 4,
                rows: 2,
                dots: true,
                arrows: false,
                infinite: false,
                responsive: [
                    {
                        breakpoint: 991,
                        settings: {
                            slidesToShow: 3,
                            rows: 2,
                            slidesToScroll: 3,
                        },
                    },
                    {
                        breakpoint: 768,
                        settings: {
                            slidesToShow: 1,
                            rows: 7,
                            slidesToScroll: 1,
                        },
                    },
                ],
            });
        }
    }

    // Parallax effect
    function parallax() {
        var speed = 0.3;

        var scroll_position = $(window).scrollTop();
        var windowHeight = $(window).height();

        $(".parallax").each(function () {
            if (scroll_position + windowHeight > $(this).offset().top) {
                var scroll_position_in_section_parallax = scroll_position;
                $(this).css({
                    "background-position": "50% calc(50% + " + scroll_position_in_section_parallax * speed + "px)",
                });
            }
        });

        $(window).scroll(function () {
            var scroll_position = $(window).scrollTop();
            var windowHeight = $(window).height();

            $(".parallax").each(function () {
                if (scroll_position + windowHeight > $(this).offset().top) {
                    var scroll_position_in_section_parallax = scroll_position;
                    $(this).css({
                        "background-position": "50% calc(50% + " + scroll_position_in_section_parallax * speed + "px)",
                    });
                }
            });
        });
    }

    function equalizeSubmenuHeights() {
        var submenus = $("#website-menu:not(.menu-mobile) .main-menu-inner > li.menu-item-has-children > .sub-menu > ul > li > .sub-menu");

        if (submenus.length === 0) return;

        // Grouper les sous-menus par leur parent commun (niveau 2)
        var parentGroups = {};

        submenus.each(function () {
            var $submenu = $(this);
            var $level2Parent = $submenu.closest(".main-menu-inner > li.menu-item-has-children > .sub-menu");

            if ($level2Parent.length) {
                var parentId = $level2Parent.closest("li").attr("id") || "default";

                if (!parentGroups[parentId]) {
                    parentGroups[parentId] = {
                        submenus: [],
                        parentSubmenu: $level2Parent,
                    };
                }

                parentGroups[parentId].submenus.push($submenu);
            }
        });

        // Pour chaque groupe, trouver la hauteur maximale et l'appliquer
        $.each(parentGroups, function (parentId, group) {
            var maxHeight = 0;

            // Réinitialiser d'abord la min-height du parent et les hauteurs des sous-menus
            group.parentSubmenu.css("min-height", "");
            $.each(group.submenus, function (index, $submenu) {
                $submenu.css("height", "auto");
            });

            // Attendre un court délai pour s'assurer que le DOM est re-rendu
            setTimeout(function () {
                // Trouver la hauteur maximale
                $.each(group.submenus, function (index, $submenu) {
                    if ($submenu.is(":visible")) {
                        var height = $submenu.outerHeight();
                        if (height > maxHeight) {
                            maxHeight = height;
                        }
                    }
                });

                // Appliquer la hauteur maximale au parent de niveau 2
                if (maxHeight > 0) {
                    group.parentSubmenu.css("min-height", maxHeight + "px");
                }
            }, 10);
        });
    }

    function masonry() {
        if ($(".lightgallery").length) {
            var $grid = $(".lightgallery").not(".itinerary-block .lightgallery").masonry({
                percentPosition: true,
                itemSelector: ".grid-item",
                columnWidth: ".grid-item",
            });

            $(".lightgallery").not(".itinerary-block .lightgallery").find(".lazyload").on('load', function() {
                $(".lightgallery").not(".itinerary-block .lightgallery").masonry('layout');
            });
        }
    }

    function calendarMasonry() {
        if ($(".calendar").length) {
            //Initialisation de isotope
            var $grid = $(".calendar").isotope({
                percentPosition: true,
                itemSelector: ".grid-item",
                columnWidth: ".grid-sizer",
                layoutMode: "fitRows",
            });

            //Action au click de chaque case si elles sont actives
            $grid.on("click", ".grid-item.active", function () {
                //Agrandit la case
                $(this).toggleClass("big-item");
                if ($(this).hasClass("opening") && $(this).hasClass("opened")) {
                    //Affiche le contenu du produit si la case a déjà été vue
                    $(this).removeClass("opened");
                } else if ($(this).hasClass("opening")) {
                    //Referme la case et active la case comme vue
                    $(this).addClass("opened");
                } else {
                    //Affiche le contenu du produit
                    $(this).addClass("opening");
                }
                //Réarrange le masonry après l'agrandissement
                $grid.isotope("layout");
            });

            //Affiche le message d'attente si les cases sont désactivées
            $(".calendar .grid-item.disabled").on("click", function () {
                $(this).stop().toggleClass("waiting");
            });

            //Affiche le contenu du produit du jour mis en avant
            $(".calendar-page .product-detail .calendar-box").on("click", function () {
                $(".calendar-page").addClass("calendar-open");
            });
        }
    }

    function searchInput() {
        $.fn.textWidth = function (text, font) {
            if (!$.fn.textWidth.fakeEl) $.fn.textWidth.fakeEl = $("<span>").hide().appendTo(document.body);

            $.fn.textWidth.fakeEl.text(text || this.val() || this.text() || this.attr("placeholder")).css("font", font || this.css("font"));

            return $.fn.textWidth.fakeEl.width();
        };

        $(".width-dynamic")
            .on("input", function () {
                var inputWidth = $(this).textWidth();
                $(this).css({
                    width: inputWidth,
                });
            })
            .trigger("input");

        function inputWidth(elem, minW, maxW) {
            elem = $(this);
            //console.log(elem);
        }
        var targetElem = $(".width-dynamic");
        inputWidth(targetElem);

        $(".main-search input").keypress(function () {
            $(this).parents(".main-search").addClass("writing");
        });
        $(".main-search input").blur(function () {
            var searchwrite = $(this).val();
            if (searchwrite == "") {
                $(this).parents(".main-search").removeClass("writing");
            }
        });
        $(".main-search input").keyup(function () {
            if (!this.value) {
                $(this).parents(".main-search").removeClass("writing");
            }
        });
    }

    function mobileFilters() {
        $(".mobile-filters-btn").on("click", function () {
            $(this).siblings(".filter-inner").slideToggle();
            if ($(this).hasClass("open")) {
                $(this).find(".icon").html('<lord-icon src="https://cdn.lordicon.com/qhybrhfg.json" target=".mobile-filters-btn" trigger="hover" colors="primary:#0A4069" style="width:26px;height:26px"></lord-icon>');
            } else {
                $(this).find(".icon").html('<lord-icon src="https://cdn.lordicon.com/nhfyhmlt.json" target=".mobile-filters-btn" trigger="hover" colors="primary:#0A4069" style="width:26px;height:26px"></lord-icon>');
            }
            $(this).toggleClass("open");
        });
    }

    function menuFooter() {
        $(document).on("click", "body.mobile .more-page-mobile", function () {
            $(".menu-footer").slideToggle();
            $(this).toggleClass("open");
        });

        $(document).on("click", "body.mobile .accordion-mobile > .wp-block-heading", function () {
            $(this).siblings(".wp-block-group").slideToggle();
            $(this).toggleClass("open");
        });
    }

    function producersAjax() {
        $(".producers-list-outer").each(function () {
            var elem = $(this);
            $(this)
                .find(".load-more-btn")
                .on("click", function (e) {
                    e.preventDefault();
                    var search_value = elem.find(".filters .search-field input").val();
                    var city = elem.find(".filters .cities").val();
                    var sector = elem.find(".filters .sectors").val();
                    var capacity = elem.find(".filters .capacity").val();

                    var posts_limit = $(this).attr("data-post-per-page");
                    var current_page = $(this).attr("data-page");
                    var btn = $(this);

                    $("body").addClass("loading");

                    load_more_producers(posts_limit, current_page, search_value, city, sector, capacity, btn);
                });

            function load_more_producers(posts_limit, current_page, search_value, city, sector, capacity, btn) {
                $.ajax({
                    url: ajax.ajaxurl,
                    method: "POST",
                    data: {
                        action: "load_more_producers",
                        posts_limit: posts_limit,
                        current_page: current_page,
                        search_value: search_value,
                        city: city,
                        sector: sector,
                        capacity: capacity,
                    },
                    success: function (response) {
                        btn.fadeOut();

                        elem.find(".producers-list").append(response.content);
                        elem.find(".load-more-btn").attr("data-page", response.new_page);

                        if (response.delete_btn == true) {
                            elem.find(".load-more-btn").fadeOut();
                        } else {
                            elem.find(".load-more-btn").fadeIn().css("display", "inline-block");
                        }
                    },
                    error: function (xhr, textStatus) {},
                    complete: function () {
                        $("body").removeClass("loading");
                    },
                });
            }

            let timeoutID = null;
            $(this)
                .find(".search-field input")
                .keyup(function (e) {
                    clearTimeout(timeoutID);
                    const value = e.target.value;
                    timeoutID = setTimeout(() => searchProducers(value), 500);
                });

            $(this)
                .find("select")
                .on("change", function () {
                    var search_value = elem.find(".filters .search-field input").val();
                    searchProducers(search_value);
                });

            function searchProducers(value) {
                $("body").addClass("loading");

                const currentUrl = window.location.href.split("?")[0];
                window.history.replaceState({}, "", currentUrl);

                elem.find(".load-more-btn").hide();
                var city = elem.find(".filters .cities").val();
                var sector = elem.find(".filters .sectors").val();
                var capacity = elem.find(".filters .capacity").val();
                var posts_limit = elem.attr("data-max-post");

                $.ajax({
                    url: ajax.ajaxurl,
                    method: "POST",
                    data: {
                        action: "search_producers",
                        value: value,
                        city: city,
                        sector: sector,
                        capacity: capacity,
                        posts_limit: posts_limit,
                    },
                    success: function (response) {
                        elem.find(".load-more-btn").fadeOut();
                        elem.find(".producers-list").html(response.content);
                        elem.find(".load-more-btn").attr("data-page", response.new_page);

                        elem.find(".total .number").html(response.total);

                        if (elem.find(".filters .cities").val() != "" || elem.find(".filters .sectors").val() != "" || elem.find(".filters .capacity").val() != "" || elem.find(".filters .search").val() != "") {
                            elem.find(".filters-tools").slideDown({
                                start: function () {
                                    $(this).css({
                                        display: "flex",
                                    });
                                },
                            });
                        } else {
                            elem.find(".filters-tools").slideUp();
                        }

                        if (response.delete_btn == true) {
                            elem.find(".load-more-btn").fadeOut();
                        } else {
                            elem.find(".load-more-btn").fadeIn().css("display", "inline-block");
                        }
                    },
                    error: function (xhr, textStatus) {},
                    complete: function () {
                        $("body").removeClass("loading");
                    },
                });
            }

            $(this)
                .find(".reset-filters")
                .on("click", function (e) {
                    e.preventDefault();
                    $(this)
                        .parents(".filter-inner")
                        .find("select")
                        .each(function () {
                            $(this).next().find(".selected").removeClass("selected");
                            $(this).next().find(".option[data-value='']").addClass("selected");
                            var text = $(this).next().find(".option[data-value='']").data("display-text") || $(this).next().find(".option[data-value='']").text();
                            $(this).next().find(".current").text(text);
                            $(this).val("");
                        });
                    $(this).parents(".filter-inner").find(".search").val("");
                    searchProducers("");
                });

            $(document).on("click", ".producers-list .producer-item", function () {
                // Nettoyer l'URL en supprimant les paramètres existants
                const currentUrl = window.location.href.split("?")[0];
                window.history.replaceState({}, "", currentUrl);
                // Récupérer les paramètres de filtrage actuels
                var search_value = elem.find(".filters .search-field input").val();
                var city = elem.find(".filters .cities").val();
                var sector = elem.find(".filters .sectors").val();
                var capacity = elem.find(".filters .capacity").val();

                // Récupérer les informations sur le nombre d'éléments affichés
                var postsPerPage = elem.find(".load-more-btn").attr("data-post-per-page");
                var currentPage = elem.find(".load-more-btn").attr("data-page");
                var totalItems = postsPerPage * currentPage;

                // Créer un objet avec les paramètres
                var filterParams = {
                    search: search_value,
                    city: city,
                    sector: sector,
                    capacity: capacity,
                    totalItems: totalItems,
                };

                // Stocker dans le localStorage
                localStorage.setItem("producerFilters", JSON.stringify(filterParams));
            });
        });
    }

    function productsAjax() {
        $(".products-list-outer").each(function () {
            var elem = $(this);
            $(this)
                .find(".load-more-btn")
                .on("click", function (e) {
                    e.preventDefault();
                    var search_value = elem.find(".filters .search-field input").val();
                    var category = elem.find(".filters .categories").val();

                    var posts_limit = $(this).attr("data-post-per-page");
                    var current_page = $(this).attr("data-page");
                    var btn = $(this);

                    $("body").addClass("loading");

                    load_more_products(posts_limit, current_page, search_value, category, btn);
                });

            function load_more_products(posts_limit, current_page, search_value, category, btn) {
                $.ajax({
                    url: ajax.ajaxurl,
                    method: "POST",
                    data: {
                        action: "load_more_products",
                        posts_limit: posts_limit,
                        current_page: current_page,
                        search_value: search_value,
                        category: category,
                    },
                    success: function (response) {
                        btn.fadeOut();

                        elem.find(".products-list").append(response.content);
                        elem.find(".load-more-btn").attr("data-page", response.new_page);

                        if (response.delete_btn == true) {
                            elem.find(".load-more-btn").fadeOut();
                        } else {
                            elem.find(".load-more-btn").fadeIn().css("display", "inline-block");
                        }
                    },
                    error: function (xhr, textStatus) {},
                    complete: function () {
                        $("body").removeClass("loading");
                    },
                });
            }

            let timeoutID = null;
            $(this)
                .find(".search-field input")
                .keyup(function (e) {
                    clearTimeout(timeoutID);
                    const value = e.target.value;
                    timeoutID = setTimeout(() => searchProducts(value), 500);
                });

            $(this)
                .find("select")
                .on("change", function () {
                    var search_value = elem.find(".filters .search-field input").val();
                    searchProducts(search_value);
                });

            function searchProducts(value) {
                $("body").addClass("loading");

                const currentUrl = window.location.href.split("?")[0];
                window.history.replaceState({}, "", currentUrl);

                elem.find(".load-more-btn").hide();
                var category = elem.find(".filters .categories").val();
                // console.log(category);
                var posts_limit = elem.attr("data-max-post");

                $.ajax({
                    url: ajax.ajaxurl,
                    method: "POST",
                    data: {
                        action: "search_products",
                        value: value,
                        category: category,
                        posts_limit: posts_limit,
                    },
                    success: function (response) {
                        elem.find(".load-more-btn").fadeOut();
                        elem.find(".products-list").html(response.content);
                        elem.find(".load-more-btn").attr("data-page", response.new_page);

                        elem.find(".total .number").html(response.total);

                        if (elem.find(".filters .categories").val() != "" || elem.find(".filters .search").val() != "") {
                            elem.find(".filters-tools").slideDown({
                                start: function () {
                                    $(this).css({
                                        display: "flex",
                                    });
                                },
                            });
                        } else {
                            elem.find(".filters-tools").slideUp();
                        }

                        if (response.delete_btn == true) {
                            elem.find(".load-more-btn").fadeOut();
                        } else {
                            elem.find(".load-more-btn").fadeIn().css("display", "inline-block");
                        }
                    },
                    error: function (xhr, textStatus) {},
                    complete: function () {
                        $("body").removeClass("loading");
                    },
                });
            }

            $(this)
                .find(".reset-filters")
                .on("click", function (e) {
                    e.preventDefault();
                    $(this)
                        .parents(".filter-inner")
                        .find("select")
                        .each(function () {
                            $(this).next().find(".selected").removeClass("selected");
                            $(this).next().find(".option[data-value='']").addClass("selected");
                            var text = $(this).next().find(".option[data-value='']").data("display-text") || $(this).next().find(".option[data-value='']").text();
                            $(this).next().find(".current").text(text);
                            $(this).val("");
                        });
                    $(this).parents(".filter-inner").find(".search").val("");
                    searchProducts("");
                });

            $(document).on("click", ".products-list .producer-item", function () {
                // Nettoyer l'URL en supprimant les paramètres existants
                const currentUrl = window.location.href.split("?")[0];
                window.history.replaceState({}, "", currentUrl);
                // Récupérer les paramètres de filtrage actuels
                var search_value = elem.find(".filters .search-field input").val();
                var category = elem.find(".filters .categories").val();

                // Récupérer les informations sur le nombre d'éléments affichés
                var postsPerPage = elem.find(".load-more-btn").attr("data-post-per-page");
                var currentPage = elem.find(".load-more-btn").attr("data-page");
                var totalItems = postsPerPage * currentPage;

                // Créer un objet avec les paramètres
                var filterParams = {
                    search: search_value,
                    category: category,
                    totalItems: totalItems,
                };

                // Stocker dans le localStorage
                localStorage.setItem("productFilters", JSON.stringify(filterParams));
            });
        });
    }

    function partnersAjax() {
        $(".partners-list-outer").each(function () {
            var elem = $(this);

            let timeoutID = null;
            $(this)
                .find(".search-field input")
                .keyup(function (e) {
                    clearTimeout(timeoutID);
                    const value = e.target.value;
                    timeoutID = setTimeout(() => searchPartners(value), 500);
                });

            $(this)
                .find("select")
                .on("change", function () {
                    var search_value = elem.find(".filters .search-field input").val();
                    searchPartners(search_value);
                });

            function showFilterTools(elem) {
                if (elem.hasClass("partners-map-list")) {
                    // Pour la vue carte, on vérifie uniquement groups et search
                    return elem.find(".filters .groups").val() != "" || elem.find(".filters .search").val() != "";
                } else {
                    // Pour la vue liste, on vérifie groups, locations et search
                    return elem.find(".filters .groups").val() != "" || elem.find(".filters .locations").val() != "" || elem.find(".filters .search").val() != "";
                }
            }

            function toggleFilterTools(elem) {
                if (showFilterTools(elem)) {
                    elem.find(".filters-tools").slideDown({
                        start: function () {
                            $(this).css({
                                display: "flex",
                            });
                        },
                    });
                } else {
                    elem.find(".filters-tools").slideUp();
                }
            }

            function searchPartners(value) {
                $("body").addClass("loading");
                var group = elem.find(".filters .groups").val();
                var location = elem.find(".filters .locations").val();

                $.ajax({
                    url: ajax.ajaxurl,
                    method: "POST",
                    data: {
                        action: "search_partners",
                        value: value,
                        group: group,
                        location: location,
                    },
                    success: function (response) {
                        elem.find(".partners-list").html(response.content);
                        elem.find(".total .number").html(response.total);

                        toggleFilterTools(elem);
                    },
                    error: function (xhr, textStatus) {},
                    complete: function () {
                        $("body").removeClass("loading");
                    },
                });
            }

            $(this)
                .find(".reset-filters")
                .on("click", function (e) {
                    e.preventDefault();
                    $(this)
                        .parents(".filter-inner")
                        .find("select")
                        .each(function () {
                            $(this).next().find(".selected").removeClass("selected");
                            $(this).next().find(".option[data-value='']").addClass("selected");
                            var text = $(this).next().find(".option[data-value='']").data("display-text") || $(this).next().find(".option[data-value='']").text();
                            $(this).next().find(".current").text(text);
                            $(this).val("");
                        });
                    $(this).parents(".filter-inner").find(".search").val("");
                    searchPartners("");
                });

            $(document).on("click", ".partners-list .partner-item", function () {
                // Nettoyer l'URL en supprimant les paramètres existants
                const currentUrl = window.location.href.split("?")[0];
                window.history.replaceState({}, "", currentUrl);
                // Récupérer les paramètres de filtrage actuels
                var search_value = elem.find(".filters .search-field input").val();
                var group = elem.find(".filters .groups").val();
                var location = elem.find(".filters .locations").val();

                // Créer un objet avec les paramètres
                var filterParams = {
                    search: search_value,
                    group: group,
                    location: location,
                };

                // Stocker dans le localStorage
                localStorage.setItem("partnerFilters", JSON.stringify(filterParams));
            });
        });
    }

    function dropdownGroup() {
        $(document).on("click", ".dropdown-group", function (event) {
            $(".dropdown, .dropdown-group").not($(this)).removeClass("open");

            if (!$(event.target).closest(".list").length) {
                $(this).toggleClass("open");
            }

            if ($(this).hasClass("open")) {
                $(this).find(".selected").focus();
            } else {
                $(this).focus();
            }
        });

        $(document).on("click", ".dropdown-group .option.parent > span", function (event) {
            var subHeader = $(this).html();

            if (!$(this).siblings("ul").find(".parent-header").length) {
                $("<li class='parent-header'>" + subHeader + "</li>").prependTo($(this).siblings("ul"));
            }

            $(this).siblings("ul").addClass("active");

            $(this).parents(".list").find("> ul").addClass("active");

            $(this).parents("ul").addClass("subactive");
            $(this).parents("ul").scrollTop(0);
        });

        $(document).on("click", ".parent-header", function (event) {
            $(this).parent("ul").removeClass("active");
            $(this).closest(".parent").parent("ul").removeClass("subactive");
        });

        $(document).on("click", ".dropdown-group .option:not(.parent)", function (event) {
            $(this).parents(".list").find(".selected").removeClass("selected");
            $(this).parents(".list").find(".option.parent").removeClass("active");

            $(this).addClass("selected");
            $(this).parents(".parent").addClass("active");
            var text = $(this).text();
            $(this).parents(".dropdown-group").find(".current").text(text);

            $(this).parents(".dropdown-group").toggleClass("open");
            $(this).parents("ul").removeClass("active");
            $(this).parents("ul").removeClass("subactive");
            $(this).closest(".dropdown-group").prev("select").val($(this).data("value")).trigger("change");
        });
    }

    function preventProducerClick() {
        $(".producer-item").on("click", function (event) {
            if ($(event.target).closest(".link").length) {
                event.preventDefault();
            }
        });
    }

    function imageAnimate() {
        $(".is-style-left-img-text, .is-style-right-img-text").each(function () {
            var scroll_position = $(window).scrollTop();
            var windowHeight = $(window).height();
            if (window.innerWidth < 767) {
                var offset = 100;
            } else {
                var offset = 200;
            }
            if (scroll_position + windowHeight > $(this).offset().top + offset) {
                $(this).addClass("reveal");
            } else if (scroll_position + windowHeight < $(this).offset().top) {
                $(this).removeClass("reveal");
            }
        });

        $(window).on("resize scroll", function () {
            if (window.innerWidth < 767) {
                var offset = 100;
            } else {
                var offset = 200;
            }

            $(".is-style-left-img-text, .is-style-right-img-text").each(function () {
                var scroll_position = $(window).scrollTop();
                var windowHeight = $(window).height();
                if (scroll_position + windowHeight > $(this).offset().top + offset) {
                    $(this).addClass("reveal");
                } else if (scroll_position + windowHeight < $(this).offset().top) {
                    $(this).removeClass("reveal");
                }
            });
        });
    }

    function eventsAjax() {
        $(".events-list-outer").each(function () {
            var elem = $(this);
            var data_type = elem.attr("data-type");
            var lang = $(elem).attr("data-lang");
            $(this)
                .find(".load-more-btn")
                .on("click", function (e) {
                    e.preventDefault();

                    var posts_limit = $(this).attr("data-post-per-page");
                    var current_page = $(this).attr("data-page");
                    var btn = $(this);

                    if (elem.hasClass("posts-list-map")) {
                        var version_2 = true;
                    } else {
                        var version_2 = false;
                    }

                    if(data_type == "events_old"){
                        if (elem.find(".filters #datepicker").length > 0 && elem.find(".filters #datepicker").val() != "") {
                            var date_from = elem.find(".filters #datepicker").data("daterangepicker").startDate.format("YYYY-MM-DD");
                            var date_to = elem.find(".filters #datepicker").data("daterangepicker").endDate.format("YYYY-MM-DD");
                        } else {
                            var date_from = "";
                            var date_to = "";
                        }

                        // console.log(date_from);
                        // console.log(date_to);

                        var category = elem.find(".filters .categories").val();
                        var location = elem.find(".filters .locations").val();
                        var data = {
                            action: "load_more_events",
                            posts_limit: posts_limit,
                            current_page: current_page,
                            date_from: date_from,
                            date_to: date_to,
                            category: category,
                            location: location,
                            version_2: version_2,
                            data_type: data_type,
                        }
                    }else if(data_type == "events"){
                        var types = elem.find(".filters .types").val();
                        var destinations = elem.find(".filters .destinations").val();
                        var event_AT194 = elem.find(".filters #event_AT194").is(":checked") ? 1 : 0;
                        var event_AT290 = elem.find(".filters #event_AT290").val();
                        var search = elem.find(".filters .search").val();
                        if (elem.find(".filters #datepicker").val() != "") {
                            var start = elem.find(".filters #datepicker").data("daterangepicker").startDate.format("YYYY-MM-DD");
                            var end = elem.find(".filters #datepicker").data("daterangepicker").endDate.format("YYYY-MM-DD");
                        } else {
                            var start = "";
                            var end = "";
                        }
                        var data = {
                            action: "load_more_events",
                            posts_limit: posts_limit,
                            current_page: current_page,
                            types: types,
                            tenants: destinations,
                            event_AT194: event_AT194,
                            event_AT290: event_AT290,
                            version_2: version_2,
                            data_type: data_type,
                            search: search,
                            start: start,
                            end: end
                        }
                    }else if(data_type == "venues"){
                        var search = elem.find(".filters .search").val();
                        var types = elem.find(".filters .types").val();
                        var destinations = elem.find(".filters .destinations").val();
                        var locations = elem.find(".filters .locations").val();
                        var capacity_min = elem.find(".filters .capacity-min").val();
                        var data = {
                            action: "load_more_events",
                            posts_limit: posts_limit,
                            current_page: current_page,
                            search: search,
                            types: types,
                            destinations: destinations,
                            locations: locations,
                            capacity_min: capacity_min,
                            version_2: version_2,
                            data_type: data_type,
                        }
                    }else if(data_type == "pois"){
                        var types = elem.find(".filters .types").val();
                        var destinations = elem.find(".filters .destinations").val();
                        var landmark_AT194 = elem.find(".filters #landmark_AT194").is(":checked") ? 1 : 0;
                        var search = elem.find(".filters .search").val();
                        var landmark_AT290 = elem.find(".filters #landmark_AT290").val();
                        var data = {
                            action: "load_more_events",
                            posts_limit: posts_limit,
                            current_page: current_page,
                            types: types,
                            tenants: destinations,
                            landmark_AT194: landmark_AT194,
                            landmark_AT290: landmark_AT290,
                            version_2: version_2,
                            data_type: data_type,
                            search: search
                        }
                    }else if(data_type == "tours"){
                        var types = elem.find(".filters .types").val();
                        var destinations = elem.find(".filters .destinations").val();
                        var tour_AT194 = elem.find(".filters #tour_AT194").is(":checked") ? 1 : 0;
                        var search = elem.find(".filters .search").val();
                        var tour_AT290 = elem.find(".filters #tour_AT290").val();
                        var length = elem.find(".filters .length:checked").val();
                        var duration = elem.find(".filters .duration:checked").val();
                        var data = {
                            action: "load_more_events",
                            posts_limit: posts_limit,
                            current_page: current_page,
                            types: types,
                            tenants: destinations,
                            tour_AT194: tour_AT194, // Accessibility
                            tour_AT290: tour_AT290, // Seasons
                            length: length,
                            duration: duration,
                            version_2: version_2,
                            data_type: data_type,
                            search: search
                        }
                    }

                    $("body").addClass("loading");

                    data['lang'] = lang;

                    load_more_events(data, btn);
                });

            function load_more_events(data, btn) {
                //console.log(data);
                $.ajax({
                    url: ajax.ajaxurl,
                    method: "POST",
                    data: data,
                    success: function (response) {
                        btn.fadeOut();

                        elem.find(".events-list").append(response.content);
                        elem.find(".load-more-btn").attr("data-page", response.new_page);

                        if (response.delete_btn == true) {
                            elem.find(".load-more-btn").fadeOut();
                        } else {
                            elem.find(".load-more-btn").fadeIn().css("display", "inline-block");
                        }
                    },
                    error: function (xhr, textStatus) {},
                    complete: function () {
                        $("body").removeClass("loading");
                    },
                });
            }

            $(this)
                .find("#datepicker")
                .on("apply.daterangepicker", function (ev, picker) {
                    search_events();
                })
                .on("cancel.daterangepicker", function () {
                    $(this).val("");
                    search_events();
                })
                .on("change", function () {
                    // Si la valeur est vidée manuellement (reset), lancer la recherche
                    if (!$(this).val()) {
                        search_events();
                    }
                });

            
            let timeoutID = null;
            $(this)
                .find(".search-input .search, input.capacity-min")
                .keyup(function (e) {
                    clearTimeout(timeoutID);
                    const value = (e.target.value || "").trim();
                    // Ne rien lancer si moins de 3 caractères ou seulement des espaces
                    if (value.length < 3) {
                        return;
                    }
                    timeoutID = setTimeout(() => search_events(), 1000);
                });

                $(this)
                .find("input.capacity-min")
                .on("change", function (e) {
                    clearTimeout(timeoutID);
                    const value = e.target.value;
                    timeoutID = setTimeout(() => search_events(), 1000);
                });

            $(this)
                .find("input.checkbox, .radio-group input")
                .on("change", function () {
                    search_events();
                });

            $(this)
                .find("select")
                .on("change", function () {
                    search_events();
                });

            function search_events() {
                $("body").addClass("loading");

                if (elem.hasClass("posts-list-map") && typeof window.mapFunctions !== 'undefined' && data_type != "tours") {
                    window.mapFunctions.loadEventsPins(elem, data_type);
                }

                // Nettoyer l'URL en supprimant les paramètres existants
                const currentUrl = window.location.href.split("?")[0];
                window.history.replaceState({}, "", currentUrl);

                elem.find(".load-more-btn").hide();

                //console.log(category);
                var posts_limit = elem.attr("data-max-post");

                if (elem.hasClass("posts-list-map")) {
                    var version_2 = true;
                } else {
                    var version_2 = false;
                }

                if(data_type == "events_old"){
                    var category = elem.find(".filters .categories").val();
                    var location = elem.find(".filters .locations").val();
                    if (elem.find(".filters #datepicker").val() != "") {
                        var start = elem.find(".filters #datepicker").data("daterangepicker").startDate.format("YYYY-MM-DD");
                        var end = elem.find(".filters #datepicker").data("daterangepicker").endDate.format("YYYY-MM-DD");
                    } else {
                        var start = "";
                        var end = "";
                    }
                    var data = {
                        action: "search_events",
                        date_from: start,
                        date_to: end,
                        category: category,
                        location: location,
                        posts_limit: posts_limit,
                        version_2: version_2,
                        data_type: data_type,
                    }
                }else if(data_type == "events"){
                    var types = elem.find(".filters .types").val();
                    var destinations = elem.find(".filters .destinations").val();
                    var event_AT194 = elem.find(".filters #event_AT194").is(":checked") ? 1 : 0;
                    var event_AT290 = elem.find(".filters #event_AT290").val();
                    var search = elem.find(".filters .search").val();
                    if (elem.find(".filters #datepicker").val() != "") {
                        var start = elem.find(".filters #datepicker").data("daterangepicker").startDate.format("YYYY-MM-DD");
                        var end = elem.find(".filters #datepicker").data("daterangepicker").endDate.format("YYYY-MM-DD");
                    } else {
                        var start = "";
                        var end = "";
                    }
                    var data = {
                        action: "search_events",
                        start: start,
                        end: end,
                        tenants: destinations,
                        types: types,
                        event_AT194: event_AT194, // Accessibility
                        event_AT290: event_AT290, // Seasons
                        posts_limit: posts_limit,
                        version_2: version_2,
                        data_type: data_type,
                        search: search,
                    }
                }else if(data_type == "venues"){
                    var search = elem.find(".filters .search").val();
                    var types = elem.find(".filters .types").val();
                    var destinations = elem.find(".filters .destinations").val();
                    var locations = elem.find(".filters .locations").val();
                    var capacity_min = elem.find(".filters .capacity-min").val();
                    var data = {
                        action: "search_events",
                        search: search,
                        types: types,
                        destinations: destinations,
                        locations: locations,
                        capacity_min: capacity_min,
                        posts_limit: posts_limit,
                        version_2: version_2,
                        data_type: data_type,
                    }
                }else if(data_type == "pois"){
                    var types = elem.find(".filters .types").val();
                    var destinations = elem.find(".filters .destinations").val();
                    var landmark_AT194 = elem.find(".filters #landmark_AT194").is(":checked") ? 1 : 0;
                    var search = elem.find(".filters .search").val();
                    var landmark_AT290 = elem.find(".filters #landmark_AT290").val();

                    var data = {
                        action: "search_events",
                        tenants: destinations,
                        types: types,
                        landmark_AT194: landmark_AT194, // Accessibility
                        landmark_AT290: landmark_AT290, // Seasons
                        posts_limit: posts_limit,
                        version_2: version_2,
                        data_type: data_type,
                        search: search,
                    }
                }else if(data_type == "tours"){
                    var types = elem.find(".filters .types").val();
                    var destinations = elem.find(".filters .destinations").val();
                    var tour_AT194 = elem.find(".filters #tour_AT194").is(":checked") ? 1 : 0;
                    var search = elem.find(".filters .search").val();
                    var tour_AT290 = elem.find(".filters #tour_AT290").val();
                    var length = elem.find(".filters .length:checked").val();
                    var duration = elem.find(".filters .duration:checked").val();
                    var data = {
                        action: "search_events",
                        tenants: destinations,
                        types: types,
                        tour_AT194: tour_AT194, // Accessibility
                        tour_AT290: tour_AT290, // Seasons
                        length: length, // Length filter
                        duration: duration, // Duration filter
                        posts_limit: posts_limit,
                        version_2: version_2,
                        data_type: data_type,
                        search: search,
                    }
                }

                data['lang'] = lang;

                $.ajax({
                    url: ajax.ajaxurl,
                    method: "POST",
                    data: data,
                    success: function (response) {
                        elem.find(".load-more-btn").fadeOut();
                        elem.find(".events-list").html(response.content);
                        elem.find(".load-more-btn").attr("data-page", response.new_page);

                        elem.find(".total .number").html(response.total);

                        // Vérifier si n'importe quel select ou input dans les filtres n'est pas vide
                        var hasActiveFilters = false;
                        elem.find(".filters #datepicker, .filters select, .filters input").each(function() {
                            var $el = $(this);
                            var val = $el.val();
                            var isChecked = $el.is(":checked");
                            var isRadio = $el.attr("type") === "radio";
                            var isCheckbox = $el.attr("type") === "checkbox";
                            
                            // Pour les boutons radio : ignorer ceux qui ne sont pas cochés
                            if (isRadio) {
                                // Si le bouton radio est coché et que sa valeur n'est pas vide, c'est un filtre actif
                                if (isChecked && val != "" && val != null && val !== undefined) {
                                    hasActiveFilters = true;
                                    return false; // Sortir de la boucle
                                }
                                // Sinon, ignorer ce bouton radio (non coché ou "All" sélectionné)
                                return; // Continuer avec le suivant
                            }
                            
                            // Pour les checkboxes : vérifier si elles sont cochées
                            if (isCheckbox) {
                                if (isChecked) {
                                    hasActiveFilters = true;
                                    return false; // Sortir de la boucle
                                }
                                return; // Continuer avec le suivant
                            }
                            
                            // Pour les autres (text, select, datepicker) : vérifier si la valeur n'est pas vide
                            // Convertir en string et vérifier que ce n'est pas une chaîne vide
                            var valStr = String(val || "");
                            if (valStr.trim() !== "") {
                                hasActiveFilters = true;
                                return false; // Sortir de la boucle
                            }
                        });
                        
                        if (hasActiveFilters) {
                            elem.find(".filters-tools:not(.v2)").slideDown({
                                start: function () {
                                    $(this).css({
                                        display: "flex",
                                    });
                                },
                            });
                            elem.find(".filters-tools .reset-filters").removeClass("d-none");
                        } else {
                            elem.find(".filters-tools:not(.v2)").slideUp();
                            elem.find(".filters-tools .reset-filters").addClass("d-none");
                        }

                        if (response.delete_btn == true) {
                            elem.find(".load-more-btn").fadeOut();
                        } else {
                            elem.find(".load-more-btn").fadeIn().css("display", "inline-block");
                        }
                    },
                    error: function (xhr, textStatus) {},
                    complete: function () {
                        $("body").removeClass("loading");
                    },
                });
            }

            $(this)
                .find(".reset-filters")
                .on("click", function (e) {
                    e.preventDefault();
                    elem.find(".filter-inner select").each(function () {
                        $(this).next().find(".selected").removeClass("selected");
                        $(this).next().find(".option[data-value='']").addClass("selected");
                        var text = $(this).next().find(".option[data-value='']").data("display-text") || $(this).next().find(".option[data-value='']").text();
                        $(this).next().find(".current").text(text);
                        $(this).val("");
                    });
                    // Réinitialiser les inputs (text, checkbox, etc.)
                    elem.find(".filter-inner input").each(function () {
                        var $input = $(this);
                        // Si c'est un bouton radio, ne pas le décocher ici (on le gère après)
                        if ($input.attr("type") === "radio") {
                            return; // Passer au suivant
                        }
                        $input.val("");
                        $input.prop("checked", false);
                    });
                    // Réinitialiser les boutons radio en activant "All" (valeur vide)
                    elem.find(".filter-inner input.length[type='radio'][value='']").prop("checked", true);
                    elem.find(".filter-inner input.duration[type='radio'][value='']").prop("checked", true);
                    $(this).parents(".filter-outer").find("#datepicker").val("");
                    $(this).parents(".filter-outer").find(".datepicker-reset").hide();
                    var $el = $(this).parents(".filter-outer").find("#datepicker");
                    var drp = $el.data('daterangepicker');
                    if (drp && typeof drp.clickCancel === 'function') {
                        drp.clickCancel();
                    } else {
                        // Fallback: émettre l'événement cancel
                        $el.trigger('cancel.daterangepicker', [drp]);
                    }
                    var date_from = "";
                    var date_to = "";
                    search_events(date_from, date_to);
                    // Mettre à jour la carte si elle existe
                    if (elem.hasClass("posts-list-map") && typeof window.mapFunctions !== 'undefined') {
                        window.mapFunctions.loadEventsPins(elem, data_type);
                    }
                });

            $(document).on("click", ".events-list .event-card", function () {
                // Nettoyer l'URL en supprimant les paramètres existants
                const currentUrl = window.location.href.split("?")[0];
                window.history.replaceState({}, "", currentUrl);
                // Récupérer les paramètres de filtrage actuels
                // Récupérer les informations sur le nombre d'éléments affichés
                var postsPerPage = elem.find(".load-more-btn").attr("data-post-per-page");
                var currentPage = elem.find(".load-more-btn").attr("data-page");
                var totalItems = postsPerPage * currentPage;

                if(data_type == "events_old"){
                    var dates = elem.find(".filters #datepicker").val();
                    var category = elem.find(".filters .categories").val();
                    var location = elem.find(".filters .locations").val();
                    // Créer un objet avec les paramètres
                    var filterParams = {
                        dates: dates,
                        category: category,
                        location: location,
                        totalItems: totalItems,
                    };
                }else if(data_type == "events"){
                    var dates = elem.find(".filters #datepicker").val();
                    var search = elem.find(".filters .search").val();
                    var types = elem.find(".filters .types").val();
                    var destinations = elem.find(".filters .destinations").val();
                    var event_AT194 = elem.find(".filters #event_AT194").is(":checked") ? 1 : 0;
                    var event_AT290 = elem.find(".filters #event_AT290").val();
                    var filterParams = {
                        dates: dates,
                        search: search,
                        categories: types,
                        tenants: destinations,
                        event_AT194: event_AT194, // Accessibility
                        event_AT290: event_AT290, // Seasons
                        totalItems: totalItems,
                    };
                }else if(data_type == "venues"){
                    var search = elem.find(".filters .search").val();
                    var types = elem.find(".filters .types").val();
                    var destinations = elem.find(".filters .destinations").val();
                    var locations = elem.find(".filters .locations").val();
                    var capacity_min = elem.find(".filters .capacity-min").val();
                    // Créer un objet avec les paramètres
                    var filterParams = {
                        search: search,
                        types: types,
                        destinations: destinations,
                        locations: locations,
                        capacity_min: capacity_min,
                        totalItems: totalItems,
                    };
                }else if(data_type == "pois"){
                    var dates = elem.find(".filters #datepicker").val();
                    var search = elem.find(".filters .search").val();
                    var types = elem.find(".filters .types").val();
                    var destinations = elem.find(".filters .destinations").val();
                    var landmark_AT194 = elem.find(".filters #landmark_AT194").is(":checked") ? 1 : 0;
                    var landmark_AT290 = elem.find(".filters #landmark_AT290").val();
                    var filterParams = {
                        dates: dates,
                        search: search,
                        categories: types,
                        tenants: destinations,
                        landmark_AT194: landmark_AT194, // Accessibility
                        landmark_AT290: landmark_AT290, // Seasons
                        totalItems: totalItems,
                    };
                }else if(data_type == "tours"){
                    var types = elem.find(".filters .types").val();
                    var destinations = elem.find(".filters .destinations").val();
                    var tour_AT194 = elem.find(".filters #tour_AT194").is(":checked") ? 1 : 0;
                    var search = elem.find(".filters .search").val();
                    var tour_AT290 = elem.find(".filters #tour_AT290").val();
                    var length = elem.find(".filters .length:checked").val();
                    var duration = elem.find(".filters .duration:checked").val();
                    var filterParams = {
                        categories: types,
                        tenants: destinations,
                        tour_AT194: tour_AT194, // Accessibility
                        tour_AT290: tour_AT290, // Seasons
                        length: length, // Length filter
                        duration: duration, // Duration filter
                        totalItems: totalItems,
                        search: search
                    };
                }
                // Stocker dans le localStorage
                localStorage.setItem("postsListFilters", JSON.stringify(filterParams));
            });
        });
    }

    function loadMorePartners() {
        $(".partners-list-outer").each(function () {
            var elem = $(this);
            $(this)
                .find(".load-more-btn")
                .on("click", function (e) {
                    // prevent action
                    e.preventDefault();

                    var offset = $(this).attr("data-count-post");
                    var max_post = $(this).attr("data-post-per-page");
                    var category = $(this).attr("data-category");
                    var btn = $(this);

                    $("body").addClass("loading");
                    //console.log(max_post);

                    load_more_partners(category, max_post, offset, btn);
                });

            function load_more_partners(category, max_post, offset, btn) {
                $.ajax({
                    url: ajax.ajaxurl,
                    method: "POST",
                    data: {
                        action: "load_more_partners",
                        offset: offset,
                        max_post: max_post,
                        category: category,
                    },
                    success: function (response) {
                        btn.fadeOut();

                        elem.find(".partners-list").append(response.content);
                        elem.find(".load-more-btn").attr("data-count-post", response.new_offset);

                        if (response.delete_btn == true) {
                            elem.find(".load-more-btn").fadeOut();
                        } else {
                            elem.find(".load-more-btn").fadeIn().css("display", "inline-block");
                        }
                    },
                    error: function (xhr, textStatus) {},
                    complete: function () {
                        $("body").removeClass("loading");
                    },
                });
            }
        });
    }
    function jslink() {
        $(document).on("click", ".js-link", function (e) {
            e.preventDefault();
            e.stopPropagation();
            const url = $(this).data("url");
            const target = $(this).data("target");

            if (target === "_blank") {
                window.open(url, "_blank");
            } else {
                window.location = url;
            }
        });
    }

    function popup() {
        $(".popup .close-btn").on("click", function (e) {
            e.preventDefault();
            e.stopPropagation();
            $(".popup-container").removeClass("active");
        });

        $(".popup .popup-inner a").on("click", function (e) {
            e.stopPropagation();
        });

        $(".popup-container").on("click", function (e) {
            e.preventDefault();
            if ($(e.target).closest(".popup").length > 0) {
                return;
            }
            $(".popup-container").removeClass("active");
        });

        if ($(".popup img").length > 0 || $(".popup video").length > 0) {
            // Correction pour le cas où il y a soit une seule image, soit une seule vidéo

            if ($(".popup img").length > 0) {
                var img = $(".popup img")[0];
                if (img.complete) {
                    $(".popup-container").addClass("active");
                } else {
                    $(img).on("load", function () {
                        $(".popup-container").addClass("active");
                    });
                }
            } else if ($(".popup video").length > 0) {
                var video = $(".popup video")[0];
                // On utilise 'loadeddata' pour s'assurer que la vidéo est prête à être affichée
                $(video).on("loadeddata", function () {
                    $(".popup-container").addClass("active");
                });
            }else{
                $(".popup-container").addClass("active");
            }
        }else{
            $(".popup-container").addClass("active");
        }
    }

    function destinationAjax() {
        $(document).on("click", ".our-destinations .destinations-list a", function (e) {
            if(!$(this).hasClass("anchor")) {
                e.preventDefault();
                e.stopPropagation();

                const page_id = $(this).attr("data-id");
                const $destinationDetail = $(this).parents(".our-destinations").find(".destination-detail");
                const $destinationsLoading = $(this).parents(".our-destinations").find(".destinations-loading");
                const $destinationInner = $(this).parents(".our-destination-inner");
                $destinationsLoading.addClass("active");

                $.ajax({
                    url: ajax.ajaxurl,
                    method: "POST",
                    data: {
                        action: "get_destination_detail",
                        page_id: page_id,
                    },
                    success: function (response) {
                        if (response.success) {
                            $destinationDetail.html(response.data.destination_detail);
                            $destinationDetail.addClass("active");
                            $destinationsLoading.removeClass("active");
                            $destinationInner.addClass("invisible");
                        }
                    },
                    error: function (xhr, textStatus) {
                        console.log(xhr);
                        console.log(textStatus);
                    },
                });
            }else{
                var target = $(this).attr("href");
                // Animation de scroll jusqu'à la target
                if (target) {
                    var $target = $(target);
                    if ($target.length) {
                        e.preventDefault();
                        $("html, body").animate(
                            { scrollTop: $target.offset().top - 80 },
                            700
                        );
                    }
                }
            }
        });

        $(document).on("click", ".back-to-destination-list", function (e) {
            $(this).parents(".our-destinations").find(".our-destination-inner").removeClass("invisible");
            $(this).parents(".destination-detail").removeClass("active");
            $(this).parents(".destination-detail").html("");
        });

        $(document).on("click", ".our-destinations-map svg g[id]", function (e) {
            e.preventDefault();
            e.stopPropagation();
            const id = $(this).attr("id");
            $(this)
                .parents(".our-destinations")
                .find(".destinations-list a[data-slug=" + id + "]")
                .trigger("click");
        });

        $(".our-destinations-map svg g[id]").hover(
            function () {
                const id = $(this).attr("id");
                const $correspondingLink = $(this)
                    .parents(".our-destinations")
                    .find('.destinations-list a[data-slug="' + id + '"]');
                const $correspondingLogo = $(this)
                    .parents(".our-destinations")
                    .find('.our-destinations-map svg [id="logo-' + id + '"]');
                if ($correspondingLink.length) {
                    $correspondingLink.addClass("active");
                }
                if ($correspondingLogo.length) {
                    $correspondingLogo.addClass("active");
                }
            },
            function () {
                const id = $(this).attr("id");
                const $correspondingLink = $(this)
                    .parents(".our-destinations")
                    .find('.destinations-list a[data-slug="' + id + '"]');
                const $correspondingLogo = $(this)
                    .parents(".our-destinations")
                    .find('.our-destinations-map svg [id="logo-' + id + '"]');
                if ($correspondingLink.length) {
                    $correspondingLink.removeClass("active");
                }
                if ($correspondingLogo.length) {
                    $correspondingLogo.removeClass("active");
                }
            }
        );

        $(".our-destinations .destinations-list a").hover(
            function () {
                const slug = $(this).attr("data-slug");
                const $correspondingPath = $(this)
                    .parents(".our-destinations")
                    .find(".our-destinations-map svg g#" + slug);
                const $correspondingLogo = $(this)
                    .parents(".our-destinations")
                    .find('.our-destinations-map svg [id="logo-' + slug + '"]');
                if ($correspondingPath.length) {
                    $correspondingPath.addClass("active");
                }
                if ($correspondingLogo.length) {
                    $correspondingLogo.addClass("active");
                }
                
                const $map_path = $(this).parents(".our-destinations").find(".our-destinations-map svg #map-path");
                $map_path.append($correspondingPath);
            },
            function () {
                const slug = $(this).attr("data-slug");
                const $correspondingPath = $(this)
                    .parents(".our-destinations")
                    .find(".our-destinations-map svg g#" + slug);
                const $correspondingLogo = $(this)
                    .parents(".our-destinations")
                    .find('.our-destinations-map svg [id="logo-' + slug + '"]');
                if ($correspondingPath.length) {
                    $correspondingPath.removeClass("active");
                }
                if ($correspondingLogo.length) {
                    $correspondingLogo.removeClass("active");
                }
            }
        );
    }

    function stickyNav() {
        if ($(".sticky-nav-outer").length) {
            var stickyElements = [];
            var websiteMenu = $("#website-menu");

            function initStickyElements() {
                stickyElements = [];
                $(".sticky-nav-outer").each(function () {
                    var $outer = $(this);
                    var $nav = $outer.find(".sticky-nav");
                    var offset = $outer.offset().top;

                    stickyElements.push({
                        outer: $outer,
                        nav: $nav,
                        offset: offset,
                        isSticky: false,
                    });
                });
            }

            function recalculateOffsets() {
                stickyElements.forEach(function (element) {
                    element.offset = element.outer.offset().top;
                });
            }

            function checkStickyStates() {
                var scrollTop = $(window).scrollTop();
                var activeElement = null;
                var hasAnySticky = false;

                // Trouver l'élément qui devrait être sticky (le plus bas dans la page atteint)
                stickyElements.forEach(function (element) {
                    if (scrollTop >= element.offset) {
                        activeElement = element;
                    }
                });

                // Appliquer les états : désactiver tous, activer seulement l'élément actif
                stickyElements.forEach(function (element) {
                    if (element === activeElement) {
                        // Activer cet élément
                        if (!element.isSticky) {
                            element.outer.css("height", element.nav.outerHeight());
                            element.nav.addClass("sticky");
                            element.isSticky = true;
                        }
                        hasAnySticky = true;
                    } else {
                        // Désactiver tous les autres éléments
                        if (element.isSticky) {
                            element.nav.removeClass("sticky");
                            element.outer.css("height", "auto");
                            element.isSticky = false;

                            // Remettre le scroll-left à 0 seulement si on est remonté au-dessus
                            if (scrollTop < element.offset) {
                                element.nav[0].scrollTo({
                                    left: 0,
                                    behavior: "smooth",
                                });
                            }
                        }
                    }
                });

                if (hasAnySticky) {
                    websiteMenu.addClass("has-sticky-menu");
                } else {
                    websiteMenu.removeClass("has-sticky-menu");
                }
            }

            // Initialisation
            initStickyElements();
            checkStickyStates();

            // Recalculer après le chargement des images
            $(window).on("load", function () {
                setTimeout(function () {
                    recalculateOffsets();
                    checkStickyStates();
                }, 100);
            });

            // Recalculer lors du redimensionnement
            var resizeTimeout;
            $(window).on("resize", function () {
                clearTimeout(resizeTimeout);
                resizeTimeout = setTimeout(function () {
                    recalculateOffsets();
                    checkStickyStates();
                }, 250);
            });

            // Écouter le chargement des images lazy load
            $(document).on("load", 'img[loading="lazy"], img[data-src]', function () {
                recalculateOffsets();
            });

            // Observer pour les changements de layout (solution moderne)
            if (window.ResizeObserver) {
                var resizeObserver = new ResizeObserver(function (entries) {
                    recalculateOffsets();
                });

                // Observer le body pour détecter les changements de layout
                resizeObserver.observe(document.body);
            }

            // Scroll listener principal
            $(window).on("scroll", checkStickyStates);

            // Fonction publique pour recalcul manuel
            window.recalculateStickyNav = function () {
                recalculateOffsets();
                checkStickyStates();
            };

            // Gestion du smooth scroll et des liens actifs
            initStickyNavLinks();
        }

        function initStickyNavLinks() {
            // Smooth scroll pour les liens d'ancre
            $(document).on("click", '.sticky-nav a[href^="#"]', function (e) {
                e.preventDefault();
                var target = $(this.getAttribute("href"));

                if (target.length) {
                    var offset = getStickyOffset();
                    var targetPosition = target.offset().top - offset;

                    $("html, body").animate(
                        {
                            scrollTop: targetPosition,
                        },
                        800,
                        "swing"
                    );
                }
            });

            // Activation des liens selon la section visible
            $(window).on("scroll", function () {
                updateActiveNavLinks();
            });

            // Initialiser les liens actifs
            updateActiveNavLinks();
        }

        function getStickyOffset() {
            var offset = 50; // Marge de base

            // Ajouter la hauteur du menu principal s'il est sticky
            if ($("#website-menu").hasClass("sticky")) {
                offset += $("#website-menu").outerHeight();
            }

            return offset;
        }

        function updateActiveNavLinks() {
            var scrollTop = $(window).scrollTop();
            var offset = getStickyOffset();

            $(".sticky-nav").each(function () {
                var $stickyNav = $(this);
                var $links = $stickyNav.find('a[href^="#"]');
                var activeLink = null;

                // Parcourir tous les liens pour trouver la section active
                $links.each(function () {
                    var $link = $(this);
                    var targetId = $link.attr("href");
                    var $target = $(targetId);

                    if ($target.length) {
                        var targetTop = $target.offset().top - offset - 20;
                        var targetBottom = targetTop + $target.outerHeight() + $("#website-menu").outerHeight();

                        // Vérifier si nous sommes dans cette section
                        if (scrollTop >= targetTop && scrollTop < targetBottom) {
                            activeLink = $link;
                        }

                        // Ou si c'est la dernière section et nous sommes en bas de page
                        if (scrollTop + $(window).height() >= $(document).height() - 10) {
                            var $lastTarget = $($links.last().attr("href"));
                            if ($target.is($lastTarget)) {
                                activeLink = $link;
                            }
                        }
                    }
                });

                // Appliquer la classe active
                $links.removeClass("active");
                if (activeLink) {
                    activeLink.addClass("active");
                    // Scroll simple vers l'item actif
                    $stickyNav[0].scrollTo({
                        left: activeLink[0].offsetLeft - 15,
                        behavior: "smooth",
                    });
                }
            });
        }
    }

    function addToFavorites() {
        $(document).on("click", ".favorite-button", function (e) {
            e.preventDefault();

            // Récupérer l'ID de l'événement depuis l'attribut data ou le paramètre
            const itemId = $(this).attr("data-item-id");
            // Récupérer le nom de l'événement depuis l'attribut data ou le paramètre
            const itemName = $(this).attr("data-item-title");

            const itemType = $(this).attr("data-item-type");

            if (itemId) {
                // Récupérer les favoris existants depuis le cookie
                let favorites = [];
                const favoriteCookie = getCookie("vp_user_favorites_" + itemType);
                if (favoriteCookie) {
                    try {
                        favorites = JSON.parse(favoriteCookie);
                    } catch (e) {
                        favorites = [];
                    }
                }

                if ($(this).hasClass("is-favorite")) {
                    // Retirer des favoris
                    $(this).removeClass("is-favorite");
                    favorites = favorites.filter((id) => id !== itemId);
                    _paq.push(["trackEvent", "Favoris " + itemType, "Retiré des favoris", itemName, 1]);

                    // Récupérer le nombre de favoris
                    const favoritesCounter = $("#favorites-btn").find(".favorites-counter");
                    const count = parseInt(favoritesCounter.text());
                    favoritesCounter.text(count - 1);
                    if (count - 1 === 0) {
                        favoritesCounter.removeClass("show");
                    }

                    if ($(this).parents(".favorites-list").length) {
                        $(this).parents(".favorites-card").remove();
                        $('.favorites-group').each(function() {
                            if($(this).find(".favorites-card").length === 0) {
                                $(this).remove();
                            }
                        });
                        if($(".favorites-list").find(".favorites-group").length === 0) {
                            $(".favorites-list").find(".alert").removeClass("hide");
                        }
                    }
                } else {
                    // Ajouter aux favoris
                    $(this).addClass("is-favorite");
                    if (!favorites.includes(itemId)) {
                        favorites.push(itemId);
                    }
                    _paq.push(["trackEvent", "Favoris " + itemType, "Ajouté aux favoris", itemName, 1]);

                    // Récupérer le nombre de favoris
                    const favoritesCounter = $("#favorites-btn").find(".favorites-counter");
                    const count = parseInt(favoritesCounter.text());
                    favoritesCounter.text(count + 1);
                    favoritesCounter.addClass("show");
                }

                // Sauvegarder dans le cookie (expire dans ~10 ans)
                setCookie("vp_user_favorites_" + itemType, JSON.stringify(favorites), 3650);
            }
        });
    }

    // Fonction utilitaire pour définir un cookie
    function setCookie(name, value, days) {
        let expires = "";
        if (days) {
            const date = new Date();
            date.setTime(date.getTime() + days * 24 * 60 * 60 * 1000);
            expires = "; expires=" + date.toUTCString();
        }
        document.cookie = name + "=" + (value || "") + expires + "; path=/";
    }

    // Fonction utilitaire pour récupérer un cookie
    function getCookie(name) {
        const nameEQ = name + "=";
        const ca = document.cookie.split(";");
        for (let i = 0; i < ca.length; i++) {
            let c = ca[i];
            while (c.charAt(0) === " ") c = c.substring(1, c.length);
            if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length, c.length);
        }
        return null;
    }

    //CALL FUNCTIONS ON READY
    $(document).ready(function () {
        slider();
        headerSticky();
        lightgallery();
        accordion();
        tabs();
        create_custom_dropdowns();
        $(document).bind("gform_post_render", function () {
            create_custom_dropdowns();
        });
        menuMobile();
        ajaxPostFilter();
        setTimeout(function () {
            $(".loader").fadeOut(500);
        }, 3000);
        postSlider();
        backToTop();
        searchBtn();
        menuIam();
        ctaSlider();
        parallax();
        equalizeSubmenuHeights();
        mobileFilters();
        searchInput();
        menuFooter();
        producersAjax();
        productsAjax();
        partnersAjax();
        dropdownGroup();
        preventProducerClick();
        eventsAjax();
        loadMorePartners();
        calendarMasonry();
        jslink();
        destinationAjax();
        stickyNav();
        if ($(".popup").length > 0) {
            popup();
        }
        addToFavorites();
        //imageAnimate();
    });

    //CALL FUNCTIONS ON RESIZE
    // Exécuter lors du redimensionnement de la fenêtre avec debounce
    var resizeTimeout;
    $(window).on("resize", function () {
        clearTimeout(resizeTimeout);
        resizeTimeout = setTimeout(function () {
            equalizeSubmenuHeights();
        }, 250);
    });

    //CALL FUNCTIONS ON LOAD
    $(window).on("load", function () {
        masonry();
    });

    $.fn.isInViewport = function () {
        var elementTop = $(this).offset().top;
        var elementBottom = elementTop + $(this).outerHeight();

        var viewportTop = $(window).scrollTop();
        var viewportBottom = viewportTop + $(window).height();

        return elementBottom > viewportTop && elementTop < viewportBottom;
    };
})(jQuery);