;(function ($, window, document, undefined) {
    var $win = $(window);
    var $doc = $(document);
    var isMobile = $win.width() > 1024 ? false : true;
    var ajaxLoading = false;
    var observer;
    var $grid;
    var $container, $parent;

    $doc.ready(function () {

        // Set Isotope container
        $grid = $('.isotope-container');

        // fixes pagination on EI Quiz (it should NOT be clickable!)
        $('.article-quiz-emotional .paging-quaternary').on('click', 'a', function () {event.preventDefault();});

        // Clone widget for mobile
        if ($('.widget-happiness').length && $('.section-topics').length) {
            $('.widget-happiness')
                .clone()
                .insertAfter($('.section-topics .section-title'))
                .addClass('cloned');
        }

        // fixes submit buttons for quizzes
        $('.eequiz_submit_all_button').addClass('btn btn-primary btn-orange');
        $('.submit_answer_button').addClass('btn btn-primary btn-orange');

        // Get image src and puts in to background
        $('.fullsize-bg').each(function () {
            var $img = $(this);

            // check if the image is already hidden, if so, the background has been assigned in code
            if (!$img.hasClass("hidden")) {
                $img.addClass('hidden');
                $(this)
                    .parent()
                    .addClass('container-fullsize')
                    .css('background-image', 'url(' + $img.attr('src') + ')');
            }
        });

        // Mobile internal ad
        var mobileAdStr = Cookies.get('gg_content_ad') || '{"ads": []}';
        var mobileAds = JSON.parse(mobileAdStr);
        if (mobileAds && mobileAds.ads && mobileAds.ads.length > 0) {
            // If some ads have been closed (saved in the cookie)
            //  Check if the current ones in the HTML needs to be hidden or not
            var mobileAdsArray = mobileAds.ads;
            $('.article-body .article-mobile-ad').each(function (idx, adElement) {
                var adId = $(adElement).data('id');
                if (adId) {
                    jQuery.each(mobileAdsArray, function (idxAd, mobileAd) {
                        if (mobileAd.id == adId) {
                            if (Date.now() < (mobileAd.timestamp)) {
                                // The hide period is ok, remove ad from content
                                $(adElement).remove();
                            }
                        }
                    });
                }
            });
            // Clean the array of expired ads
            var adsToRemove = [];
            // Note: we can't modify an array that we're currently looping through
            jQuery.each(mobileAdsArray, function (idxAd, mobileAd) {
                if (Date.now() > (mobileAd.timestamp)) {adsToRemove.push(idxAd);}
            });
            jQuery.each(adsToRemove, function (idxAd, adToRemove) {
                mobileAdsArray.splice(adToRemove, 1);
            });
            mobileAds.ads = mobileAdsArray;

            // Save our ads preferences in a cookie
            Cookies.set('gg_content_ad', JSON.stringify(mobileAds), { expires: 100 });
        } else {

        }

        $('.article-body .article-mobile-ad .ad-close').on('click', function (e) {
            var mobileAdStr = Cookies.get('gg_content_ad') || '{"ads": []}';
            var mobileAds = JSON.parse(mobileAdStr);
            var hidePeriod = 604800000; // 1 week in ms
            var ad = {
                timestamp: (Date.now() + hidePeriod),
                id: $(this).parent().parent().data('id')
            };
            if (mobileAds && mobileAds.ads && mobileAds.ads.length > 0) {

            } else {
                mobileAds = {};
                mobileAds.ads = [];
            }
            mobileAds.ads.push(ad);
            // Save our ads preferences in a cookie
            Cookies.set('gg_content_ad', JSON.stringify(mobileAds), { expires: 100 });

            // Remove ad from content
            $(this).parent().parent().remove();
        });

        $('*').on('focusin', function (event) {
            event.stopPropagation();

            //console.log($(this));
        });

        $('.nav-primary li').each(function () {
            var $this = $(this);
            if ($this.find('ul').length) {$this.addClass('has-dd');}
        });

        // Focus on tab press
        $('.nav-primary a').on('focusin', function (event) {
            event.preventDefault();

            var $this = $(this);

            $('.nav-primary .has-dd').removeClass('focused'); // Close other dropdowns
            $this.closest('.has-dd').addClass('focused');
        });

        // Ensure .last is only applied to the last .has-dd item
        $('.nav-primary li.has-dd:last').addClass('last');

        // Adjust focusout behavior to prevent premature closing of the dropdown
        $('.nav-primary .last a').on('focusout', function (event) {
            var $dropdown = $(this).closest('.has-dd.focused');

            setTimeout(function () {
                if (!$dropdown.find(':focus').length) {$dropdown.removeClass('focused');}
            }, 50);
        });

        // Nav Primary trigger on tablet
        $('.nav-primary .has-dd > a').one('click', function (event) {
            if ($win.width() < 992) {
                event.preventDefault();

                $('.nav-primary .has-dd').removeClass('focused'); // Close other dropdowns
                $(this).closest('li').addClass('focused');
            }
        });

        /**
         * Initialize tab navigation on page load
         * Handles hash-based tab selection for URLs like #panel-authors, #what-is-happiness, etc.
         * Falls back to first tab if hash doesn't match any tab or no hash is present
         */
        function initializeTabNavigation() {
            var activeTabClass = 'current';
            var hash = window.location.hash.toLowerCase();

            if (hash) {
                // Find the tab button that matches the hash (e.g., #panel-authors -> button[data-target="#panel-authors"])
                var $targetTabButton = $('.tabs-nav button[data-target="' + hash + '"]');

                if ($targetTabButton.length > 0) {
                    // Activate the matching tab
                    activateTab($targetTabButton, activeTabClass);
                } else {
                    // If no matching tab found, activate the first tab as fallback
                    var $firstTabButton = $('.tabs-nav button').first();
                    if ($firstTabButton.length > 0) {
                        activateTab($firstTabButton, activeTabClass);
                    }
                }
            } else {
                // No hash present, activate the first tab by default
                var $firstTabButton = $('.tabs-nav button').first();
                if ($firstTabButton.length > 0) {
                    activateTab($firstTabButton, activeTabClass);
                }
            }
        }

        /**
         * Activate a specific tab and update all related UI elements
         * @param {jQuery} $tabButton - The tab button to activate
         * @param {string} activeTabClass - CSS class for active state (usually 'current')
         */
        function activateTab($tabButton, activeTabClass) {
            var targetTabSelector = $tabButton.data('target');
            var $targetTab = $(targetTabSelector);
            var $parentLi = $tabButton.parent();

            // Safety check: ensure we have valid elements
            if (!$targetTab.length || !$parentLi.length) {
                console.warn('activateTab: Invalid tab button or target element');
                return;
            }

            // Update tab button states and ARIA attributes
            $('.tabs-nav li').removeClass(activeTabClass);
            $parentLi.addClass(activeTabClass);
            $('.tabs-nav button').attr('aria-selected', 'false');
            $tabButton.attr('aria-selected', 'true');

            // Show/hide tab content panels
            $('.tabs-body .tab').attr('hidden', 'true').attr('aria-hidden', 'true').removeClass(activeTabClass);
            $targetTab.removeAttr('hidden').attr('aria-hidden', 'false').addClass(activeTabClass);

            // Initialize Isotope layout for the new active tab (if present)
            var $container = $targetTab.find('.isotope-container');
            if ($container.length > 0) {
                var isoCheck = $container.data('isotope');
                if (isoCheck) {$container.isotope('destroy');}
                initIsotope($container);

                // Handle pagination for first load
                var showMoreLink = $targetTab.find('.show-more-container a');
                if (showMoreLink.attr('data-first-load') === 'yes') {
                    var href = showMoreLink.attr('href') + '/P0';
                    $container.isotope('layout');
                    isotopeMagic(href);
                } else {isotopeMagic();}
            }

            // Update filter states and initialize audio players
            $('.isotope-filter li:first').addClass(activeTabClass);
            initAudioPlayers();
        }

        // Initialize tab navigation on page load (handles hash-based tab selection)
        initializeTabNavigation();

        //Tabs behaviour on the Education page
        $('.eduTab').click(function (e) {
            e.preventDefault();
            var contentId = $(this).attr('href').substring(1); // Remove the '#' from the href
            var contentElement = $('#' + contentId);
            var parentDiv = $('#educationNav');
            var parentDivTop = parentDiv.offset().top;
            var contentTop = parentDivTop - contentElement.offset().top;

            $('html, body').animate({
                scrollTop: contentTop
            }, 1000);

            // Update the URL with the # identifier
            var fragment = '#' + contentId;
            history.pushState(null, null, fragment);
        });

        // Owl Carousels
        const initializedCarousels = new Set(); // Tracks initialized instances to prevent duplicate initialization

        // Clean up existing carousel elements before re-initializing
        function cleanCarousel($carousel) {
            if ($carousel.hasClass('owl-loaded')) {
                $carousel.trigger('destroy.owl.carousel') // Destroy OwlCarousel instance
                    .removeClass('owl-loaded owl-drag') // Remove OwlCarousel-specific classes
                    .find('.owl-stage-outer').children().unwrap(); // Unwrap slide elements from OwlCarousel structure

                // Clean up OwlCarousel-generated elements to ensure no duplication
                $carousel.find('.owl-item, .owl-cloned, .owl-stage-outer, .owl-nav, .owl-dots').remove();
            }
        }

        // Initialize OwlCarousel if not already initialized
        function initCarousel($carousel) {
            const carouselIndex = $carousel.index('.slider-primary .owl-carousel');

            // Prevent re-initialization of carousels already initialized
            if (initializedCarousels.has(carouselIndex)) return;

            cleanCarousel($carousel); // Ensure carousel is cleaned before initialization

            // Initialize only if there are actual slides in the carousel
            if ($carousel.children('.slide').length > 0) {
                initializedCarousels.add(carouselIndex);

                $carousel.owlCarousel({
                    loop: false, // Prevent looping for better keyboard accessibility
                    margin: 55,
                    nav: true,
                    mouseDrag: false, // Mouse drag disabled to ensure better keyboard navigation
                    responsive: {
                        0: { items: 1 },
                        768: { items: 2 },
                        992: { items: 3 }
                    }
                });

                enableArrowKeyNavigation($carousel); // Enable keyboard navigation
            }
        }

        // Wait for AJAX-loaded content, ensuring carousels initialize once slides are available
        function waitForSlidesAndInitAllCarousels() {
            $('.slider-primary .owl-carousel').each(function () {
                const $carousel = $(this);

                const interval = setInterval(() => {
                    if ($carousel.children('.slide').length > 0) {
                        clearInterval(interval);
                        initCarousel($carousel); // Initialize once slides are present
                    }
                }, 300);

                // Failsafe in case content takes longer to load
                setTimeout(() => {
                    if (!initializedCarousels.has($carousel.index('.slider-primary .owl-carousel'))) {initCarousel($carousel);}
                }, 5000);
            });
        }

        // Enable keyboard navigation using Arrow keys and Tab
        function enableArrowKeyNavigation($carousel) {
            $carousel.attr('tabindex', '-1'); // Ensure carousel is focusable via keyboard

            const $allSlides = $carousel.find('.owl-item');

            // Add .focus-slide to the FIRST visible slide for initial focus
            $allSlides.first().addClass('focus-slide');

            // Arrow Key Navigation Logic
            $carousel.on('keydown', function (e) {
                const keyCode = e.keyCode || e.which;
                const $focusedSlide = $allSlides.filter('.focus-slide');

                // Arrow Left (Previous Slide)
                if (keyCode === 37) {
                    const $prevSlide = $focusedSlide.prev('.owl-item');

                    if ($prevSlide.length) {
                        $focusedSlide.removeClass('focus-slide');
                        $prevSlide.addClass('focus-slide').find('a, button, input').first().focus();
                    }
                    e.preventDefault();
                }

                // Arrow Right (Next Slide)
                if (keyCode === 39) {
                    const $nextSlide = $focusedSlide.next('.owl-item');

                    if ($nextSlide.length) {
                        $focusedSlide.removeClass('focus-slide');
                        $nextSlide.addClass('focus-slide').find('a, button, input').first().focus();
                    } else {
                        // Exit carousel focus by jumping to next valid focusable element
                        const $nextFocusable = $carousel
                            .closest('.slider')
                            .nextAll(':visible')
                            .find('a, button, input, select, textarea')
                            .first();

                        if ($nextFocusable.length) {
                            $focusedSlide.removeClass('focus-slide');
                            $nextFocusable.focus();
                        }
                    }

                    e.preventDefault();
                }
            });

            // Ensure links inside slides are focusable via Tab
            $carousel.find('.slide a').attr('tabindex', '0');

            // Highlight the focused slide for visibility
            $carousel.find('.slide a').on('focus', function () {
                $allSlides.removeClass('focus-slide');
                $(this).closest('.owl-item').addClass('focus-slide');
            }).on('blur', function () {$(this).closest('.owl-item').removeClass('focus-slide');});

            // Global Esc Key Event - Exits the carousel and moves focus to the next element
            $(document).on('keydown', function (e) {
                if (e.key === 'Escape') {
                    const $focusedElement = $(':focus');
                    const $currentCarousel = $focusedElement.closest('.owl-carousel');

                    if ($currentCarousel.length) {
                        const $carouselContainer = $currentCarousel.closest('.slider');

                        // Insert temporary focus anchor OUTSIDE the carousel container
                        const $focusAnchor = $('<div tabindex="-1"></div>').insertAfter($carouselContainer);

                        const $nextFocusable = $focusAnchor
                            .nextAll()
                            .find('a, button, input, select, textarea')
                            .filter(':visible')
                            .first();

                        console.log('➡️ Next Focusable Element:', $nextFocusable[0]);

                        $focusedElement.blur();

                        setTimeout(() => {
                            $focusAnchor.focus(); // Step 1: Force focus OUT of the carousel
                            setTimeout(() => {
                                $nextFocusable.trigger('focus').get(0).scrollIntoView({ behavior: 'smooth' });
                                $focusAnchor.remove(); // Clean up the temporary anchor
                            }, 100);
                        }, 100);

                        e.preventDefault();
                    } else {
                        console.warn('❗ Still no valid next focusable element found. Defaulting to body.');
                        $('body').focus();
                    }
                }
            });
        }

        // Initialize carousels once content is ready
        waitForSlidesAndInitAllCarousels();

        // Monitor AJAX-loaded content for dynamically added carousels
        const observer = new MutationObserver(() => {waitForSlidesAndInitAllCarousels();});

        const targetNodes = document.querySelectorAll('[data-ajax-target-id]');
        targetNodes.forEach(node => {
            observer.observe(node, { childList: true, subtree: true });
        });




        // Show Nav dropdown
        // This variable is needed as the next two actions compete to toggle the nav
        $navIsChanging = false;
        // This opens the nav dropdown normally
        $('.nav-trigger').on('click', function (event) {
            $navIsOpen = $('.nav-trigger').hasClass('active');
            if (!$navIsOpen && !$navIsChanging) {
                $navIsChanging = true;
                toggleNav(event);
            }
        });
        // This will close the nav if clicked outside of nav-container
        $(document).on('click', function (event) {
            // is the element outside the nav?
            $navElement = $('#nav-container')[0];

            if (typeof $navElement !== 'undefined') {
                $isClickInside = $navElement.contains(event.target);

                // is this a special menu item that closes the nav?
                $isClosingElement = false;
                $closingElement = $('.nav-trigger-nostyle');
                $closingElement.each(function () {
                    // return false ends the each loop
                    if ($(this)[0].contains(event.target)) {
                        $isClosingElement = true;
                        return false;
                    }
                });

                $navIsOpen = $('.nav-trigger').hasClass('active');

                // close if these are true
                if (
                    (!$isClickInside || $isClosingElement) &&
                    $navIsOpen &&
                    !$navIsChanging
                ) {
                    $navIsChanging = true;
                    toggleNav(event);
                }
                $navIsChanging = false;
            }
        });

        function toggleNav(event) {
            $navTrigger = $('.nav-trigger');
            event.preventDefault();

            $navTrigger.toggleClass('active');

            //$('.nav, .wrapper').toggleClass('active');
            if ($('.wrapper').hasClass('active')) {
                setTimeout(function () {$('.wrapper').toggleClass('active');}, 300);
            } else {$('.wrapper').toggleClass('active');}

            $('.nav-dropdown, .nav-dropdown .nav-bg').slideToggle(300);

            if (!$navTrigger.hasClass('active')) {
                $('#skip').attr('tabindex', '1');
                $('#skip a').removeAttr('tabindex');
            } else {
                $('a, input, button, select, textarea, radio, #skip').attr(
                    'tabindex',
                    '-1'
                );
                $('.nav-dropdown a').removeAttr('tabindex');
            }

            if ($win.width() > 768) {
                setTimeout(function () {
                    $('.nav-dropdown .nav-aside').css(
                        'min-height',
                        $('.nav-dropdown .nav-content').outerHeight()
                    );
                }, 300);
            }

            if ($win.width() < 768) {
                if ($('.nav-dropdown').find('.current')) {
                    $('.nav-dropdown').find('.current').parent().show();
                    $('.nav-dropdown')
                        .find('.current')
                        .parent()
                        .prev()
                        .addClass('active');
                }
            }
        }

        $('#skip').on('focusin', function () {$(this).addClass('focused');});

        $('#skip a').last().on('focusout', function () {$('#skip').removeClass('focused');});

        $('.nav-dropdown a:last, .nav-dropdown a:first').on('focusin', function (
            event
        ) {
            $('a, input, button, select, textarea, radio').removeAttr(
                'tabindex'
            );
        });

        $('.nav-dropdown a:last').last().on('focusout', function (event) {
            $('.wrapper, .nav-trigger').removeClass('active');
            $('.nav-dropdown, .nav-dropdown .nav-bg').slideUp(300);

            $('#skip').attr('tabindex', '1');
            $('#skip a').removeAttr('tabindex');
        });

        // Responsive nav toggle
        $('.nav-dropdown h2').on('click', function (event) {
            event.preventDefault();
            // This checks if out menunav is in mobile width
            if ($(window).width() < 768) {
                $(this).toggleClass('active');
                $(this).next('ul').slideToggle();
            }
        });

        // Show search on click
        $('.search label').on('click', function () {
            $(this).closest('.search').addClass('active');
            $('.wrapper, body').addClass('active');
            $('.header').addClass('darken');
            $('.nav-dropdown').slideUp(300);

            $('.nav, .nav-trigger').removeClass('active');
            $('.search-inner input').focus();
        });
        $('.search a').on('click', function () {
            $(this).closest('.search').addClass('active');
            $('.wrapper, body').addClass('active');
            $('.header').addClass('darken');
            $('.nav-dropdown').slideUp(300);

            $('.nav, .nav-trigger').removeClass('active');
            $('.search-inner input').focus();
        });
        // Show search on 'enter' if focused
        $('.search a').keypress(function (e) {
            if (e.keyCode == 13 && $(this).is(':focus')) {
                $(this).closest('.search').addClass('active');
                $('.wrapper, body').addClass('active');
                $('.header').addClass('darken');
                $('.nav-dropdown').slideUp(300);

                $('.nav, .nav-trigger').removeClass('active');
                $('.search-inner input').focus();
            }
        });

        // Print Articles
        $('body').on('click', '.fa-print', function () {
            event.preventDefault();
            window.print();
        });

        // Tabs
        (function () {
            var activeTabClass = 'current';

            // Ensure the first tab is active if none are marked
            if ($('.tabs-nav').find('.current').length === 0) {
                var firstTabNav = $('.tabs-nav').find('li').first();
                var targetTab = firstTabNav.find('button').data('target');
                firstTabNav.addClass(activeTabClass);
                firstTabNav.find('button').attr('aria-selected', 'true');
                $(targetTab).removeAttr('hidden').attr('aria-hidden', 'false');
            }

            $('.tabs-nav button').on('click', function (event) {
                var $tabButton = $(this);
                var targetTabSelector = $tabButton.data('target');

                // Use the shared activateTab function
                activateTab($tabButton, activeTabClass);

                event.preventDefault();
                $tabButton.focus(); // Keep focus on the tab
                // update url to add hash
                history.pushState(null, null, targetTabSelector);
            });

            // Handle arrow key navigation for tabs
            $('.tabs-nav button').on('keydown', function (event) {
                var $currentTab = $(this);
                var $allTabs = $('.tabs-nav button');
                var index = $allTabs.index($currentTab);
                var newIndex;
                var isVertical = $('.tabs-head').attr('aria-orientation') === 'vertical';

                switch (event.key) {
                    case 'ArrowRight':
                        if (!isVertical) {
                            newIndex = (index + 1) % $allTabs.length;
                            var $newTab = $allTabs.eq(newIndex);
                            $newTab.focus();
                            activateTab($newTab, activeTabClass);
                            event.preventDefault();
                        }
                        break;
                    case 'ArrowLeft':
                        if (!isVertical) {
                            newIndex = (index - 1 + $allTabs.length) % $allTabs.length;
                            var $newTab = $allTabs.eq(newIndex);
                            $newTab.focus();
                            activateTab($newTab, activeTabClass);
                            event.preventDefault();
                        }
                        break;
                    case 'ArrowDown':
                        if (isVertical) {
                            newIndex = (index + 1) % $allTabs.length;
                            var $newTab = $allTabs.eq(newIndex);
                            $newTab.focus();
                            activateTab($newTab, activeTabClass);
                            event.preventDefault();
                        }
                        break;
                    case 'ArrowUp':
                        if (isVertical) {
                            newIndex = (index - 1 + $allTabs.length) % $allTabs.length;
                            var $newTab = $allTabs.eq(newIndex);
                            $newTab.focus();
                            activateTab($newTab, activeTabClass);
                            event.preventDefault();
                        }
                        break;
                    case 'Home':
                        var $firstTab = $allTabs.eq(0);
                        $firstTab.focus();
                        activateTab($firstTab, activeTabClass);
                        event.preventDefault();
                        break;
                    case 'End':
                        var $lastTab = $allTabs.eq($allTabs.length - 1);
                        $lastTab.focus();
                        activateTab($lastTab, activeTabClass);
                        event.preventDefault();
                        break;
                    case 'Tab':
                        if (!event.shiftKey) {
                            // **Ensure tab selection before focus shift**
                            if (!$currentTab.parent().hasClass('current')) {
                                $currentTab.trigger('click');  // Select tab if it isn't active
                            }

                            var targetPanel = $('#' + $currentTab.attr('aria-controls'));
                            var focusableElements = targetPanel.find('a, button, input, textarea, select, [tabindex]:not([tabindex="-1"])');

                            if (focusableElements.length) {
                                focusableElements.first().focus(); // Move focus into the panel
                                event.preventDefault();
                            } else {
                                targetPanel.attr('tabindex', '-1').focus(); // Ensure the panel itself can receive focus
                                event.preventDefault();
                            }
                        }
                        break;
                }
            });


            // Handle Shift+Tab inside the panel to move focus back to the active tab
            $('.tabs-body .tab').on('keydown', function (event) {
                if (event.key === 'Tab' && event.shiftKey) {
                    var tabId = $(this).attr('aria-labelledby');
                    $('#' + tabId).focus();
                    event.preventDefault();
                }
            });

            // Dynamically update aria-orientation if needed for vertical layouts
            function updateTabOrientation() {
                var isVertical = window.matchMedia('(max-width: 768px)').matches; // Adjust as needed
                $('.tabs-head').attr('aria-orientation', isVertical ? 'vertical' : 'horizontal');
            }

            $(window).on('resize', updateTabOrientation);
            updateTabOrientation(); // Run on page load

        })();


        // Check if studies section exists
        // Updated for fixing resources/studies page
        // @TODO needs refactor.. for now this works but not elegant.

        var specialSections = ['#studies-section', '#books-section'];
        var hasSpecialSection = false;
        specialSections.forEach(function (sectionId) {
            if ($(sectionId).length > 0) {
                hasSpecialSection = true;

                // used on resources/studies page & possibly other pages
                $(sectionId + ' .isotope-filter a').on('click', function (event) {
                    event.preventDefault();

                    var $this = $(this);
                    var filter = $this.data('filter');
                    $parent = $this.closest('li');
                    var $tab = $('.tab.current');
                    var $list = $('.isotope-filter');
                    var $isotopeInstance = $('.isotope-container');

                    if ($parent.hasClass('inactive')) {return;}

                    $list.each(function () {$(this).find('li').removeClass('current');});

                    $parent.addClass('current');

                    $newEls = $isotopeInstance.find('.isotope-item');

                    // $isotopeInstance.isotope('insert', $newEls);
                    $isotopeInstance.isotope({ filter: filter });
                    $win.trigger('scroll');

                    // prevent tabbing for hidden video items
                    $('.isotope-item a').attr('tabindex', '-1');
                    $(filter).find('a').removeAttr('tabindex');
                });
            }
        });

        // legacy behaviour
        if (!hasSpecialSection) {
            $('.isotope-filter a').on('click', function (event) {
                event.preventDefault();

                var $this = $(this);
                var filter = $this.data('filter');
                $parent = $this.closest('li');
                var $tab = $('.tab.current');
                var $list = $('.isotope-filter');
                var $isotopeInstance = $tab.find('.isotope-container');

                if ($parent.hasClass('inactive')) {return;}

                $list.each(function () {$(this).find('li').removeClass('current');});

                $parent.addClass('current');

                $newEls = $tab.find('.isotope-container .isotope-item');


                $isotopeInstance.isotope({ filter: filter });
                $isotopeInstance.isotope('layout');
                $win.trigger('scroll');

                // prevent tabbing for hidden video items
                $('.isotope-item a').attr('tabindex', '-1');
                $(filter).find('a').removeAttr('tabindex');
            });
        }

        var $lazyLoadImgs = $('img.lazyload');
        $lazyLoadImgs.lazyload({
            effect: 'fadeIn',
            failure_limit: Math.max($lazyLoadImgs.length - 1, 0)
        });


        // Bookmark button
        // This makes the bookmark buttons use AJAX instead of reloading the page every time
        $('.section-body').on('submit', '[id*=bookmark_form]', function (e) {
            const $this = $(this);

            // Check if it's already changing
            const buttonClicked = $this.data('clicked');
            if (buttonClicked) {
                return false;
            } else {
                $this.data('clicked', true);
            }

            // Get the data for the URL
            const url = $this.data('url');
            const buttonURL = $this.data('button-url');
            const entryId = $this.data('entry-id');
            const collection = $this.find('[name*=collection]').val();
            const entryButtonUrl = url + buttonURL + '/' + entryId + '/' + collection;

            // Change the button color, so that the user knows not to click until finished adding
            const buttonIcon = $(this).find('i');
            if (buttonIcon.hasClass("far")) {
                // Adding
                buttonIcon.addClass("fas").removeClass("far");
                buttonIcon.css("color", '#000');
            } else {
                // Removing
                buttonIcon.addClass("far").removeClass("fas");
                buttonIcon.css("color", '#000');
            }

            // submit the form here
            $(this).ajaxSubmit({
                success: function (data) {
                    // Succesfully submitted now switch the button

                    $this.load(entryButtonUrl, function () {
                        $this.data('clicked', false);
                    });

                }
            });

            return false;
        });

        $doc.keyup(function (e) {
            if (e.keyCode == 27) {
                // escape key maps to keycode `27`
                $('.wrapper, body, .search').removeClass('active');
                $('.header').removeClass('darken');
            }
        });

        $doc.on('click touchend', function (event) {
            var $target = $(event.target);

            if ($('.search').hasClass('active')) {
                if (!$target.is('.search, .search *')) {
                    $('.search, .wrapper, body').removeClass('active');
                    $('.header').removeClass('darken');
                }
            }
        });

        $('.btn-load-more').on('click', function (event) {
            event.preventDefault();

            if (ajaxLoading) {
                return false;
            }
            const $this = $(this);

            const loadingIndicator = $this.closest('.section-actions').find('.loading-indicator');
            const ajaxContainer = $this.parents('.tab').find('.ajax-container');
            const item = $this.data('item');
            ajaxLoading = true;

            loadingIndicator.fadeIn(300);

            loadMoreContent($this, ajaxContainer, item, loadingIndicator);
            setTimeout(function () { }, 500);
        });

        function loadMoreContent($button, $container, item, loadingIndicator) {
            // ADRIENNE AND CLAIR MODIFIED THIS FUNCTION FROM THE HTMLBOUTIQUE ORIGINAL ON 2016-12-01

            var items_initial_offset = $button.data('initial-offset');
            var items_offset = $button.data('offset');
            if (typeof items_initial_offset !== 'undefined') {
                items_offset += items_initial_offset;
                $button.removeAttr('data-initial-offset');
                $button.removeData("initial-offset");
            }
            $.ajax({
                url: $button.attr('href') + '/' + items_offset,
                success: function (newHTML) {
                    var $html = $(newHTML);
                    var $items = $(item, $html);

                    $items.hide();
                    $container.append($items);

                    $items.fadeIn();

                    if ($items.length === 0) {$button.remove();} else {
                        $button.data('offset', items_offset + 8);
                    }

                    ajaxLoading = false;
                    loadingIndicator.fadeOut(300);
                    showAdminOnlyMeta();
                }
            });
        }

        function sectAside() {
            $('.section-topics .section-aside').css(
                'min-height',
                $('.section-topics .widget-support').outerHeight() +
                30 +
                $('.section-topics .widget-books').outerHeight()
            );
        }

        // Scroll to top
        $('.link-top').on('click', function (event) {
            event.preventDefault();

            $('html, body').animate(
                {
                    scrollTop: 0
                },
                'slow'
            );
        });

        // Toggle Share dropdown

        $('.share-toggle').on('click', function (event) {
            event.preventDefault();

            $('.share').removeClass('active');
            $(this).closest('.share').toggleClass('active');
        });

        $('.link-close').on('click', function (event) {
            event.preventDefault();

            $(this).closest('.share').toggleClass('active');
        });

        // Auto-fill the email field in Subscribe popup with the email entered
        // This has to live BEFORE the $('.link-popup').magnificPopup() function call!
        $('.subscribe-btn').on('click', function (event) {
            var datahref = $(this).data('href');
            var email = $(this)
                .closest('form')
                .find('input[type=email]')
                .eq(0)
                .val();
            email = encodeURIComponent(email);
            datahref = datahref + '?mail1=' + email;
            if ($("#pre_select_newsletter0").val()) {
                datahref = datahref + '&pre_select_newsletter0=1';
            }
            if ($("#pre_select_newsletter1").val()) {
                datahref = datahref + '&pre_select_newsletter1=1';
            }
            if ($("#pre_select_newsletter2").val()) {
                datahref = datahref + '&pre_select_newsletter2=1';
            }
            if ($("#pre_select_newsletter3").val()) {
                datahref = datahref + '&pre_select_newsletter3=1';
            }
            if ($("#pre_select_newsletter5").val()) {
                datahref = datahref + '&pre_select_newsletter5=1';
            }
            if ($("#pre_select_newsletter7").val()) {
                datahref = datahref + '&pre_select_newsletter7=1';
            }
            if ($("#pre_select_newsletter9").val()) {
                datahref = datahref + '&pre_select_newsletter9=1';
            }
            $(this).attr('href', datahref);
        });

        // Bookmark link click
        $('.bookmark-logged-out').on('click', function () {
            Cookies.set('bookmark-logged-out', $(this).data('entry-id'), { expires: 1 });
        });

        // check if cookie set from logged out state
        if (Cookies.get('bookmark-logged-out')) {
            var bookmarkEntryId = Cookies.get('bookmark-logged-out');
            var $bookmarkButton = $('.link-bookmark[data-entry-id="' + bookmarkEntryId + '"]')
            // if exists, if not yet added, add bookmark
            if ($bookmarkButton.length && $bookmarkButton.val() == 'Add') {$bookmarkButton.trigger('click');}
            // remove cookie either way
            Cookies.set('bookmark-logged-out', "", -1);
        }

        // popup
        $('.link-popup').magnificPopup({
            type: 'ajax',
            fixedContentPos: false,
            callbacks: {
                elementParse: function (item) {
                    if (item.el.hasClass('subscribe-btn') || item.el.hasClass('creative-btn')) {
                        // subscribe popup
                    } else {
                        let data = item.el.data();
                        item.src = item.src.split('?')[0]; // Remove query string from href for security
                        if (data.path !== null) {
                            let path = data.path;
                            if (path != '/' && decodeURIComponent(path) != '/') {
                                item.src += '?path=' + encodeURIComponent(data.path);
                            }
                        }
                    }
                },
                ajaxContentAdded: function () {
                    // popupPos(); calls function that leaves a gap at top of page
                    // Add aria-label to close button for accessibility
                    $('.mfp-close').attr('aria-label', 'Close popup');
                    loadNewsletterSignup();

                    $('.secondary-popup').magnificPopup({
                        type: 'ajax',
                        fixedContentPos: false,
                        callbacks: {
                            ajaxContentAdded: function () {
                                // popupPos(); calls function that leaves a gap at top of page
                                $('a').on('click', function () {
                                    return -1;
                                });
                            },
                        }
                    });

                    $('#survey_popup_freeform').submit(function (event) {
                        Cookies.set('gg_survey_submitted', 1, { expires: 100 });
                        return true;
                    });

                    $('.cancel-popup').on('click', function (event) {
                        event.preventDefault();
                        $.magnificPopup.close();
                    });

                    /*** Focus trapping inside popup ***/
                    setTimeout(() => {
                        let $popup = $('.mfp-content');
                        if (!$popup.length) {
                            console.warn("No .mfp-content found! Focus trapping won't work.");
                            return;
                        }
                        // console.log("Popup content found!");

                        let focusableElements = $popup.find('a, button, input, textarea, select, [tabindex]:not([tabindex="-1"])')
                            .filter(':visible:not([disabled])');

                        // if (focusableElements.length === 0) {
                        //     console.warn("No focusable elements found inside popup!");
                        //     return;
                        // }

                        // console.log("Focusable elements found:", focusableElements);

                        let firstFocusable = focusableElements.first();
                        let lastFocusable = focusableElements.last();

                        // console.log("First focusable:", firstFocusable);
                        // console.log("Last focusable:", lastFocusable);

                        firstFocusable.attr('tabindex', '0');
                        lastFocusable.attr('tabindex', '0');

                        $popup.on('keydown', function (e) {
                            // console.log("Key pressed:", e.key);

                            if (e.key === 'Tab') {
                                if (e.shiftKey && document.activeElement === firstFocusable[0]) {
                                    // console.log("Shift + Tab detected on first focusable element. Looping to last.");
                                    e.preventDefault();
                                    setTimeout(() => lastFocusable.trigger('focus'), 10);
                                } else if (!e.shiftKey && document.activeElement === lastFocusable[0]) {
                                    // console.log("Tab detected on last focusable element. Looping to first.");
                                    e.preventDefault();
                                    setTimeout(() => firstFocusable.trigger('focus'), 10);
                                }
                            }
                        });
                    }, 500);
                },
                // beforeClose: function () {
                //     console.log("Closing popup, focus returning to trigger.");
                // }
            }
        });









        $('.header, .header *').click(function (event) {
            if ($('.mfp-ready').length) {$.magnificPopup.close();}
        });

        // This function leaves a gap at top of page
        // function popupPos() {
        //     if ($win.scrollTop() < 300) {
        //         $('.mfp-bg, .mfp-wrap').css(
        //             'top',
        //             $('.header').outerHeight() + 34
        //         );
        //     }
        // }

        // Now that the popup code is loaded, show the items with ajax links
        $('.link-popup').show();

        // Newsletter form: Newsletter selection js
        document.addEventListener("DOMContentLoaded", function () {
            const dropdownButton = document.querySelector(".multi-select-dropdown");
            const dropdownMenu = document.querySelector(".list-checkboxes");

            // Ensure the menu is initially hidden
            dropdownMenu.style.display = "none";

            dropdownButton.addEventListener("click", function () {
                const isExpanded = dropdownButton.getAttribute("aria-expanded") === "true";

                // Toggle the menu visibility
                dropdownButton.setAttribute("aria-expanded", !isExpanded);
                dropdownMenu.style.display = isExpanded ? "none" : "block";

                // Move focus to the first checkbox when opening the menu
                if (!isExpanded) {
                    const firstMenuItem = dropdownMenu.querySelector(".list-checkbox");
                    if (firstMenuItem) firstMenuItem.focus();
                }
            });

            // Close dropdown when clicking outside, but allow clicks inside the menu
            document.addEventListener("click", function (event) {
                if (!dropdownButton.contains(event.target) && !dropdownMenu.contains(event.target)) {
                    dropdownButton.setAttribute("aria-expanded", "false");
                    dropdownMenu.style.display = "none";
                }
            });

            // Prevent clicks inside the dropdown from closing it
            dropdownMenu.addEventListener("click", function (event) {event.stopPropagation();});

            // Close dropdown on Escape key
            document.addEventListener("keydown", function (event) {
                if (event.key === "Escape") {
                    dropdownButton.setAttribute("aria-expanded", "false");
                    dropdownMenu.style.display = "none";
                    dropdownButton.focus();
                }
            });
        });



        // // Cookies logic for the survey popup (old)
        // var viewedSurveyPopup = Cookies.get('gg_survey_popup_viewed') || 0;
        // var submitted = Cookies.get('gg_survey_submitted') || 0;
        // viewedSurveyPopup++;
        // if (viewedSurveyPopup <= 3 && submitted == 0) {
        //     $('.link-survey-popup-trigger').click();
        //     Cookies.set('gg_survey_popup_viewed', viewedSurveyPopup, {expires: 1});
        // } else {
        //     Cookies.set('gg_survey_popup_viewed', viewedSurveyPopup, {expires: 1});
        // }
        // // Cookies logic for the survey popup ends here

        function getRandomInt(max) {
            return Math.floor(Math.random() * Math.floor(max)) + 1;
        }

        // // Load popup on third pageview
        // (function () {

        //     // create cookies, if they don't exist set them to 0
        //     var viewed = Cookies.get('gg_popup_viewed') || 0;
        //     var visited = Cookies.get('gg_visited') || 0;

        //     // increment visited by 1
        //     visited++;

        //     // On the third visit show the pop up if the user hasn't already seen it
        //     if (visited > 2 && viewed == 0) {

        //         // Open popup
        //         /*	If on topic or article pages, change the frequency so
        //             the fixed bottom and overlay popup don't show up at
        //             the same time */
        //         if ($('#donation-fixed-bottom').length > 0) {
        //             switch (getRandomInt(2)) {
        //                 case 1:
        //                     // Show bottom popup
        //                     break;
        //                 case 2:
        //                     $('.link-popup-trigger').click();
        //                     $('.link-popup-trigger').addClass('on_article_page');

        //                     // $('.link-survey-popup-trigger').click();
        //                     // $('.link-survey-popup-trigger').addClass('on_article_page');
        //                     break;
        //             }
        //         } else {
        //             $('.link-popup-trigger').click();
        //             //$('.link-popup-trigger').click();
        //             //Commented the newsletter signup for
        //         }
        //         // Increase count so it gets set and expires
        //         Cookies.set('gg_visited', visited, {expires: 1});

        //     } else if (visited < 3) {
        //         // set new cookie value to match visits
        //         Cookies.set('gg_visited', visited, {expires: 1});
        //         return false;
        //     }

        //     var confirmation_check;
        //     // If they click the close button, hide for 1 day
        //     $(document).on(
        //         'click',
        //         '.mfp-close',
        //         function (e) {
        //             Cookies.set('gg_popup_viewed', 1, {expires: 1});

        //         // If they click the sign up button, hide for 300 days
        //         }).on(
        //         'click',
        //         '#mc-embedded-subscribe-form input.form-btn',
        //         function (e) {
        //             Cookies.set('gg_popup_viewed', 1, {expires: 300});
        //             clearInterval(confirmation_check);

        //             confirmation_check = setInterval(function () {
        //                 if ($('.confirmation-popup').length > 0 && $('#mce-success-response').html().replace(/\s/g,'') != "") {
        //                     $('.confirmation-popup .popup-content').toggleClass('hidden');
        //                     $('html, body').animate({
        //                         scrollTop: $('.confirmation-popup').offset().top + 500
        //                     }, 500);
        //                     //Send to GTM after successful submission
        //                     dataLayer.push({
        //                         'event': 'GGSubscriptionPopupSubmit',
        //                         'DLV_SUBMIT':'success'
        //                     });
        //                     clearInterval(confirmation_check);
        //                 } else if ($('#mce-error-response').html().replace(/\s/g,'') != "") {
        //                     clearInterval(confirmation_check);
        //                 } else {
        //                     $('#mce-success-response').html('');
        //                 }
        //             }, 200);
        //             // ga('send', 'event', 'Donate', 'donate', 'Winter 2017 Campaign');
        //     });
        // })();

        //Cookies logic for the survey popup (new, includes exceptions for visibility of termly banner)
        (function () {
            // Retrieve cookies or default to 0 if not set
            var viewed = Cookies.get('gg_popup_viewed') || 0;
            var visited = Cookies.get('gg_visited') || 0;

            // Increment visit count
            visited++;

            // Check if the termly consent banner is present and visible
            var termlyBannerVisible = $('#termly-consent-banner:visible').length > 0; // Modify selector as needed

            // Force open the newsletter popup if qs exist
            if (window.location.search.includes('popup=newsletter')) {$('.link-popup-trigger').click();} else {
                // On the third visit, show the popup if the user hasn't seen it AND if the termly banner is NOT visible
                if (visited > 2 && viewed == 0 && !termlyBannerVisible) {
                    if ($('#donation-fixed-bottom').length > 0) {
                        switch (getRandomInt(2)) {
                            case 1:
                                // Show bottom popup
                                break;
                            case 2:
                                $('.link-popup-trigger').click();
                                $('.link-popup-trigger').addClass('on_article_page');
                                break;
                        }
                    } else {$('.link-popup-trigger').click();}

                    // Save visit count in a cookie
                    Cookies.set('gg_visited', visited, { expires: 1 });
                } else if (visited < 3) {
                    // Update visit count cookie
                    Cookies.set('gg_visited', visited, { expires: 1 });
                    return false;
                }
            }

            // If they click the close button, hide for 1 day
            $(document).on('click', '.mfp-close', function (e) {
                Cookies.set('gg_popup_viewed', 1, { expires: 1 });
            });

            // If they click the subscribe button, hide for 300 days
            $(document).on('click', '#mc-embedded-subscribe-form input.form-btn', function (e) {
                Cookies.set('gg_popup_viewed', 1, { expires: 300 });
            });

        })();
        $(document).on('click', '.t-consentPrompt button, .t-consentPrompt .close-btn', function () {
            // Hide the Termly banner
            $('.t-consentPrompt').fadeOut();

            // Allow popups on the next visit
            Cookies.set('gg_visited', 2, { expires: 1 }); // Sets just below the trigger threshold
        });




        $('body').on('change', '#mce-MMERGE5', function () {
            let valueSelected = this.value;
            if (valueSelected == 'other') {$('.other-source').removeClass('hide');} else {
                $('input[name="MMERGE7"]').val('');
                $('.other-source').addClass('hide');
            }
        });

        // extra handling for login popup window - Adrienne added to original HB code
        $('body').on('click', 'a.toggle-login-trigger', function (event) {
            event.preventDefault();
            $('.toggle-login-viz').slideToggle(400);
        });

        $('.toggle-login-trigger').parent().on('click', function () {
            //console.log('1');
            // $('.popup-body form-popup').css('display');
            // $('.popup-body ul').css('display');
            // $('.popup-body form+p').css('margin-right', '40px')
        });
        $('.popup-link-close toggle-login-trigger')
            .parent()
            .on('click', function () {

            });

        // Nav Secondary mobile version
        $('.nav-secondary').prepend(
            '<a href="#" class="nav-title" id="nav-title">' +
            $('.nav-secondary .current').text() +
            '</a>'
        );
        $('.nav-secondary')
            .not('.nav-disabled')
            .on('click', 'li a', function (event) {
                var mytext = $(this).text();
                var myhash = $(this).prop('hash');
                if (myhash) {
                    // This lets there be normal links and hashlinks
                    event.preventDefault();
                }
                //console.log(myhash);
                $('#nav-title').text(mytext);
                $('.nav-secondary li').removeClass('current');
                $('.toggle-from-nav').removeClass('current');
                $(this).parent('li').addClass('current');
                $(myhash).addClass('current');
            });

        $win.on('load resize', function () {
            isMobile = $win.width() > 1024 ? false : true;

            // Responsive sidebar items position
            $('.section-topics .widget-books').css(
                'top',
                $('.section-topics .widget-support').outerHeight() + 30
            );
        });

        $win
            .on('scroll', function () {
                if (
                    !isMobile &&
                    $('.section-topics').length &&
                    !$('.article-primary-full').length &&
                    $('.section-body .tabs-primary').length
                ) {
                    var $section = $('.section-body .tabs-primary');
                    var pageTop = $win.scrollTop();
                    var pageBottom = pageTop + $win.height();
                    var elementTop = $section.offset().top;
                    var elementBottom = elementTop + $section.outerHeight();

                    if (pageBottom >= elementBottom) {
                        if (
                            $section.find('.tab.current .btn-load-more').length
                        ) {
                            $section
                                .find('.tab.current .btn-load-more')
                                .click();
                        }
                    }
                }

                if ($win.scrollTop() > 300) {$('.link-top').addClass('active');} else {$('.link-top').removeClass('active');}
            })
            .on('load resize', function () {
                if ($win.width() > 767) {
                    $(
                        '.widget-primary:not(.widget-primary-small, .widget-primary--ignore)'
                    ).equalizeHeight();
                } else {
                    $('.widget-primary:not(.widget-primary-small, .widget-primary--ignore)').height(
                        'auto'
                    );
                }
            })
            .on('load', function () {
                /* Script checking the hash value and adding the current class to the correct secondary nav item */
                var hashValue = window.location.hash.substring(1);
                if (hashValue) {
                    if (hashValue) {$('#section-account').hide();}
                    $('.nav-secondary li').each(function () {
                        $(this).removeClass('current');
                        var hrefValue = $(this).find('a').attr('href');
                        if (hrefValue && hrefValue == '#' + hashValue) {$(this).addClass('current');}
                    });
                    if (hashValue.startsWith('panel-')) {
                        // Find the corresponding tab button
                        const tabButton = document.getElementById('tab-' + hashValue.replace('panel-', ''));

                        // If we found the button, simulate a click
                        if (tabButton) {tabButton.click();}
                    }
                }

                $('.nav-secondary .nav-title').on('click', function (event) {
                    event.preventDefault();

                    $(this).closest('.nav-secondary').toggleClass('active');
                });

                initIsotope($grid);
                isotopeMagic();
            });

        // Check if '.form-influence' exists in the DOM
        // Load the influence form via JS instead of in template directly
        if ($('div.form-influence').length > 0) {
            // Get the URL from the 'data-src' attribute
            var url = $('div.form-influence').data('src');

            // Fetch and load the content
            $.get(url, function (data) {$('div.form-influence').html(data);});
        }

        // Initialize Isotope on the currently active tab on document ready
        $('.tab.current .isotope-container').each(function () {initializeIsotopeForContainer(this);});


        // init logged in elements
        showAdminOnlyMeta();
        // set click listener & scroll observer for video & podcast pagination
        initializeObserver();
        ajaxClickHandler();
        getCsrfToken();

        setupAddToAnyTracking(); // Set up the configuration once
        initializeAddToAny(); // Initialize all AddToAny elements
        // console.log('dataLayer available:', window.dataLayer ? 'Yes' : 'No');

        // home page dynamic load only
        if (window.location.pathname === '/') {loadHomePageContent();}

        // Quiz page dynamic load only
        if (window.location.pathname.includes('/quizzes/take_quiz')) {loadQuizPageHandler();}

        // need CSRF to run bookmark initialization, running here for non-ajax loaded versions
        $('.list-actions').each(function () {initBookmarkButtons(this);});

        if (adminLoggedIn) {
            if (!getCookie("adminBarState").length) {$("#toggle_button").html("Hide");} else {
                $("#toggle_button").html("Show");
                $("#admin_stats").hide();
            }
            $("#toggle_button").on("click", function () {
                console.log("called");
                if (!getCookie("adminBarState").length) {
                    setCookie("adminBarState", false, 1);
                    $("#toggle_button").html("Show");
                    $("#admin_stats").hide();
                } else {
                    setCookie("adminBarState", true, -10);
                    $("#toggle_button").html("Hide");
                    $("#admin_stats").show();
                }
            });
        }

        /**
         * CSRF is set via JS in _base layout
         * This is a fall-back, if it isn't set, fetch the CSRF token via AJAX
         */
        function getCsrfToken() {
            // Get the CSRF token from the DOM
            var csrfDomElement = $('#csrf_token');
            // check if it is set properly
            if (csrf_token && csrf_token.indexOf('csrf_token') > 0) {
                // not set yet, something is wrong
                let csrf_token = csrfDomElement.val();
                console.log('setting csrf, possibly an error', csrf_token);
            }

            // fallback to AJAX fetching of CSRF token if we still don't have it
            // TODO: this is likely not needed anymore
            if (!csrf_token || csrf_token.indexOf('csrf_token') > 0) {
                // Send AJAX request to get the CSRF token
                $.ajax({
                    url: '/_ajax/csrf_token',
                    type: 'GET',
                    dataType: 'json', // Expect a JSON response
                    success: function (response) {
                        // Process the response and set the CSRF token in the hidden input field
                        $('#csrf_token').val(response.csrf_token);
                    },
                    error: function (xhr, status, error) {
                        // Handle any errors during the AJAX request
                        console.error('error:', xhr, status, error);
                        return false;
                    }
                });
            }
        }

        initAudioPlayers();
    });
    // END OF DOCUMENT READY

    // Don't submit newsletter signup if no newsletters selected
    $('#mc-embedded-subscribe').on('click', function (e) {
        e.preventDefault();
        if ($('#mc_embed_signup input[type=checkbox]:checked').length > 0) {
            $mc_form = $('#mc-embedded-subscribe-form');
            $mc_form.submit();
        } else {$('#mce_newsletter_checkbox_error').show();}
    });

    $.fn.equalizeHeight = function () {
        var maxHeight = 0,
            itemHeight;

        for (var i = 0; i < this.length; i++) {
            itemHeight = $(this[i]).height();
            if (maxHeight < itemHeight) {
                maxHeight = itemHeight;
            }
        }

        return this.height(maxHeight);
    };

    function initIsotope(grid) {
        grid.isotope({
            itemSelector: '.isotope-item',
            layoutMode: 'fitRows'
        });

        grid.on('arrangeComplete', function () {$win.trigger('resize');});
    }

    function isotopeMagic(nextHref) {
        // If an AJAX request is already loading, exit the function to prevent multiple simultaneous requests
        if (ajaxLoading) {return;}

        // Set the global variable with current one
        $container = $('.tab.current').find('.isotope-container');

        // Get the parent tab of the isotope container
        $parent = $container.closest('.tab');

        // ensure it is intitialized
        if (!$container.hasClass('isotope')) {initIsotope($container);}

        // Check if the parent tab has the 'init-audio' class
        let initAudio = $parent.hasClass('init-audio');
        var nextPageHref;

        if (typeof nextHref !== 'undefined') {
            // use href passed into function
            nextPageHref = nextHref;
        } else {
            // find href from dynamically loaded content
            nextPageHref = $parent.find('.isotope-container-dummy .pagination a').attr('href');
        }

        // Get the "Show More" link element
        let showMoreLink = $parent.find('.show-more-container a');
        let showMoreDiv = $parent.find('.show-more-container');

        // Check if the last isotope item is visible or if the container itself is visible
        if ($container.find('.isotope-item:last').is(':visible') || $container.is(':visible')) {
            // Get new elements to insert into the isotope grid
            let $dummyContainer = $parent.find('.isotope-container-dummy');
            let $newEls = $dummyContainer.find('.isotope-item');

            // If new elements exist, insert them into the isotope grid
            if (typeof $newEls !== 'undefined') {

                $container.isotope('insert', $newEls);
                $dummyContainer.remove();

                // Callback function to handle additional loading actions
                loadMoreCallback($container);

                // If there is no next page, remove the "Show More" link
                if (nextPageHref === undefined && $newEls.length > 0) {
                    console.log('no more data to show, removing showMoreLink');
                    showMoreDiv.removeClass('loading');
                    showMoreDiv.remove();
                    return;
                }

                // Update the "Show More" link with the next page href
                showMoreLink.attr('href', nextPageHref);
                initializeObserver();
                $container.isotope('layout');

                // Initialize audio players if required
                if (initAudio) {initAudioPlayers();}

                // Set the first-load flag to 'no' after the initial load
                if ($(showMoreLink).data('first-load') === 'yes') {
                    $(showMoreLink).attr('data-first-load', 'no');
                }
            }
        }
    }

    // Initialize observer
    function initializeObserver() {
        var $showMoreContainer = $('.tab.current .show-more-container'); // make sure it targets the correct container
        if ($showMoreContainer.length === 0) {
            return; // Exit if not found
        }

        observer = new IntersectionObserver(function (entries) {
            entries.forEach(entry => {
                if (entry.isIntersecting) {
                    $showMoreContainer.find('a').click();
                    observer.unobserve(entry.target); // Optionally, unobserve after triggering
                }
            });
        }, { threshold: [1.0] }); // Threshold at 1.0 means 100% of the target must be visible to trigger

        observer.observe($showMoreContainer[0]); // Observe the actual container, not just the link
    }


    // Video & podcast tab AJAX loaders
    function ajaxClickHandler() {
        $(".show-more-container a").click(function (e) {
            e.preventDefault();

            if (ajaxLoading) {return;}

            const $this = $(this);
            const targetContainer = $this.data('target');
            let href = $this.attr("href");

            // append first pagination segment if first load
            if ($this.attr('data-first-load') === 'yes') {
                href += '/P0/';
            }

            // set loading flag
            ajaxLoading = true;
            $this.parent('.show-more-container').addClass('loading');

            // get new articles and pagination
            $.get(href, {}, function (data) {
                // remove existing pagination
                $(targetContainer).find(".pagination").remove();

                const content = $(data);
                // look in new content for next link
                const nextHref = content.find('.pagination a').attr('href');

                $parent = $container.closest('.tab');
                // add temporary 'dummy' div to tab
                $parent.append(content);

                // set new click listener with new pagination links
                ajaxClickHandler();

                // Delay the re-observation to ensure DOM is fully updated
                setTimeout(function () {
                    ajaxLoading = false;

                    // remove loading spinner
                    $this.parent('.show-more-container').removeClass('loading');

                    isotopeMagic(nextHref);
                    initializeObserver();

                    $container.isotope('layout');
                    showAdminOnlyMeta();
                }, 500); // Adjust delay as needed

            });
        });
    }

    // Function to initialize Isotope for a container
    function initializeIsotopeForContainer(container) {
        // set global to current container
        $container = $(container);
        if (!$container.data('isotope-initialized')) {  // Check if Isotope was already initialized
            $container.isotope({
                itemSelector: '.isotope-item',
                layoutMode: 'masonry'  // or any layout mode you are using
            });
            $container.data('isotope-initialized', true);
        }
    }


    //Setting listener once newsletter sign-up modal is opened
    function loadNewsletterSignup() {
        $('.multi-select-dropdown').click(function () {$(this).next('ul').toggleClass('multi-select-open');});
        $('.multi-select-dropdown').keypress(function (e) {
            if (e.which == 13 || e.which == 32) {
                e.preventDefault();
                $('.multi-select-dropdown').click();
            }
        });
    }

    /**
     * Loads the content for the home page by calling the `loadHomePageContainer` function for various container IDs.
     * It also sets up the carousel for the "Keys to Wellbeing" container.
     */
    function loadHomePageContent() {
        // Get any container to fetch the AJAX URL
        const ajaxUrl = '/_ajax/home-dynamic-content?force_static=1';

        $.ajax({
            url: ajaxUrl,
            type: 'GET',
            success: function (response) {
                const $responseHtml = $(response);
                // Process each container
                ['most-popular-container', 'most-recent-container', 'quote-of-the-day-container'].forEach(function (containerId) {
                    const $container = $('#' + containerId);
                    const $newContent = $responseHtml.filter('#' + $container.data('ajax-target-id')).children();
                    if ($container.length && $newContent.length) {
                        $container.fadeOut(function () {
                            $container.removeClass('loading')
                                .css('min-height', '')
                                .html($newContent)
                                .fadeIn();

                            // Show "See All" button if it exists
                            const $seeAllBtn = $container.parent().find('.btn-see-all');
                            if ($seeAllBtn.length) {
                                $seeAllBtn.removeClass('hidden')
                                    .css('opacity', 0)
                                    .show()
                                    .animate({ opacity: 1 }, 200);
                            }
                        });
                    }
                });

                // Handle carousel separately
                const $carouselContainer = $('#keys-to-wellbeing-container');
                const $carouselContent = $responseHtml.filter('#ajax-keys-to-wellbeing').children();
                if ($carouselContainer.length && $carouselContent.length) {
                    $carouselContainer.html($carouselContent)
                        .css('opacity', 0);

                    $carouselContainer.find('.owl-carousel').owlCarousel({
                        loop: true,
                        margin: 55,
                        nav: true,
                        mouseDrag: false,
                        responsive: {
                            0: { items: 1 },
                            768: { items: 2 },
                            992: { items: 3 }
                        }
                    });

                    $carouselContainer.animate({ opacity: 1 }, 400, function () {$carouselContainer.removeClass('loading');});
                }
            },
            error: function (xhr, status, error) {
                console.error('Error loading home page content:', error);
            }
        });
    }

    /**
     * Handles the behavior of the quiz page when radio buttons are changed.
     * This function listens for 'change' events on the document and checks if the
     * target element is a radio button. If it is, it checks if the radio button
     * is part of a 'write-in' option and toggles the visibility of the corresponding
     * write-in input field accordingly.
     */
    function loadQuizPageHandler() {
        document.addEventListener('change', function (e) {
            if (e.target.type === 'radio') {
                const mappingMatch = e.target.id.match(/mapping(\d+)_user_answer/);
                if (mappingMatch) {
                    const mappingId = mappingMatch[1];
                    const writeInField = document.getElementById(`mapping${mappingId}_write_in`);

                    if (writeInField) {
                        const isWriteIn = e.target.value === 'write-in';

                        if (isWriteIn) {
                            // Show immediately when selecting write-in
                            writeInField.classList.remove('hide');
                            // Use setTimeout to ensure display:none is removed first
                            setTimeout(() => {writeInField.classList.remove('animate-hidden');}, 10);
                        } else {
                            // Animate out first
                            writeInField.classList.add('animate-hidden');
                            // Add .hide class after animation completes
                            setTimeout(() => {writeInField.classList.add('hide');}, 300); // Match transition duration
                        }

                        // Update ARIA attributes
                        const writeInRadio = document.querySelector(`input[name="mapping${mappingId}_user_answer"][value="write-in"]`);
                        if (writeInRadio) {
                            writeInRadio.setAttribute('aria-expanded', isWriteIn);
                        }

                        // Focus the input if write-in is selected
                        if (isWriteIn) {
                            setTimeout(() => {
                                const input = writeInField.querySelector('input');
                                if (input) input.focus();
                            }, 50);
                        }
                    }
                }
            }
        });
    }

    $(document).on('click', function (e) {
        if (e.target.className != 'dropdown-wrapper' && e.target.className != 'list-checkboxes' && e.target.className != 'list-checkbox-item' && e.target.className != 'multi-select-dropdown' && e.target.className != 'list-checkboxes multi-select-open' && e.target.className != 'list-checkbox') {
            if ($('.multi-select-dropdown').next('ul').hasClass('multi-select-open')) {$('.multi-select-dropdown').next('ul').removeClass('multi-select-open');}
        }
    });

})(jQuery, window, document);


// Set up the AddToAny configuration and callbacks just once (on initial page load)
function setupAddToAnyTracking() {
    // Set up original AddToAny config
    window.a2a_config = window.a2a_config || {};

    // Add direct event listeners to any anchor within AddToAny containers
    $(document).on('click', '.a2a_kit a[class^="a2a_button_"]', function (e) {
        // Extract the service name from the class or href
        let service = 'unknown';

        // Try to get from class first (more reliable)
        let classMatch = $(this).attr('class').match(/a2a_button_([a-zA-Z0-9_]+)/);
        if (classMatch) {
            service = classMatch[1];
        }
        // If class pattern doesn't match, try to extract from URL
        else {
            let hrefMatch = $(this).attr('href').match(/add_to\/([a-zA-Z0-9_]+)\?/);
            if (hrefMatch) {
                service = hrefMatch[1];
            }
        }

        // If it's the menu button, use a generic name
        if ($(this).hasClass('a2a_dd')) {
            service = 'share_menu';
        }

        // Get the URL being shared from the container's data attribute
        let url = $(this).closest('.a2a_kit').data('a2a-url') || window.location.href;
        let title = $(this).closest('.a2a_kit').data('a2a-title') || document.title;

        // comment for debugging purposes
        console.log('Share click detected:', {
            'service': service,
            'url': url,
            'title': title
        });

        // Push to dataLayer
        if (window.dataLayer) {
            window.dataLayer.push({
                'event': 'social_share',
                'share_platform': service,
                'share_url': url,
                'share_title': title,
                'content_type': 'article'
            });
            // console.log('Event pushed to dataLayer');
        } else {
            console.warn('dataLayer not available');
        }
    });

}

// Initialize AddToAny for a specific scope or the entire document
function initializeAddToAny(scope = $(document)) {
    // Make sure the AddToAny library is loaded
    if (typeof a2a !== 'undefined' && typeof a2a.init_all === 'function') {
        // If a specific scope is provided and it's not the entire document
        const a2aContainers = scope.find('.a2a_kit');
        if (a2aContainers.length > 0) {a2a.init_all('page');} else if (scope.is(document) || scope === $(document)) {
            // Initialize all AddToAny containers on the page
            a2a.init_all('page');
        }
    }
}

function areCookiesEnabled() {
    var cookieEnabled = (navigator.cookieEnabled) ? true : false;

    if (typeof navigator.cookieEnabled == "undefined" && !cookieEnabled) {
        document.cookie = "testcookie";
        cookieEnabled = (document.cookie.indexOf("testcookie") != -1) ? true : false;
    }
    return (cookieEnabled);
}

function setCookie(c_name, value, expiredays) {
    var exdate = new Date()
    exdate.setDate(exdate.getDate() + expiredays)
    document.cookie = c_name + "=" + escape(value) + ";path=/" + ((expiredays == null) ? "" : ";expires=" + exdate.toUTCString())

    //console.log('COOKIE: ' + c_name + 'created expires on ' + exdate.toUTCString());
}

function getCookie(cname) {
    var name = cname + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') {
            c = c.substring(1);
        }
        if (c.indexOf(name) == 0) {
            return c.substring(name.length, c.length);
        }
    }
    return "";
}

function copyContent(element) {
    $(element).select();
    console.log($(element).text());
    navigator.clipboard.writeText($(element).text());
}
function selectText(element) {$(element[0]).select();}


$.fn.andSelf = function () {
    return this.addBack.apply(this, arguments);
}


/**
 * Initializes additional functionality for newly loaded content, including bookmark buttons, audio players, and AddToAny sharing.
 *
 * @param {Object} newObj - The container element that holds the newly loaded content.
 */
function loadMoreCallback(newObj) {

    initBookmarkButtons(newObj);
    initAudioPlayers(newObj);
    // initialize AddToAny for the new content
    initializeAddToAny(newObj);
}

/**
 * Initializes bookmark buttons by sending an AJAX request to update bookmarks and set up event handlers.
 *
 * @param {Object} newObj - The container element to find bookmark buttons within.
 */
function initBookmarkButtons(newObj) {
    // Find all bookmark buttons within the newObj container
    let bookmarkButtons = $(newObj).find('.bookmark-button');

    // Get the CSRF token from the hidden input field
    if (!csrf_token) {
        let csrf_token = $('#csrf_token').val();
    }

    // Iterate over each bookmark button
    bookmarkButtons.each(function () {
        // Reference to the current button element
        let button = $(this);

        // Extract data attributes from the current button
        let entryId = button.data('entry_id');

        // Create the payload for the AJAX request
        let payload = {
            csrf_token: csrf_token,
        };

        // Send AJAX request to update the bookmark button
        $.ajax({
            url: '/_ajax/bookmark_button/' + entryId,
            type: 'POST',
            data: payload,
            success: function (response) {
                // Insert the response HTML into the button container
                button.html(response);

                // Add click event handler for logged-out bookmark links
                button.find('.bookmark-logged-out').on('click', function () {
                    Cookies.set('bookmark-logged-out', $(this).data('entry-id'), { expires: 1 });
                });

                // Show and process bookmark objects
                let links = button.find('.link-popup');
                links.each(function () {$(this).removeClass("link-popup").show();});

                // Initialize Magnific Popup on the new items
                initMagnificPopup(links);
            },
            error: function (xhr, status, error) {
                // Handle any errors during the AJAX request
                console.error('Error bookmark:', error);
            }
        });
    });
}


function initMagnificPopup(target) {
    $(target).magnificPopup({
        type: 'ajax',
        fixedContentPos: false,
        callbacks: {
            ajaxContentAdded: function () {
                // popupPos();
                /* ADRIENNE ADDED THIS BLOCK TO MAKE NESTED LINKS WORK */
                $('.secondary-popup').magnificPopup({
                    type: 'ajax',
                    fixedContentPos: false,
                    callbacks: {
                        ajaxContentAdded: function () {
                            popupPos();

                            $('a').on('click', function () {
                                return -1;
                            });
                        }
                    }
                });

                $('.cancel-popup').on('click', function (event) {
                    event.preventDefault();
                    $.magnificPopup.close();
                });
                /* END ADDED CODE */
                $('a').on('click', function () {
                    return -1;
                });
            }
        }
    });
}

// function popupPos() {
//     var $win = $(window);
//     if ($win.scrollTop() < 300) {
//         $('.mfp-bg, .mfp-wrap').css(
//             'top',
//             $('.header').outerHeight() + 34
//         );
//     }
// }

/**
 * Initializes Plyr audio players for all audio elements with the 'data-plyr-player' attribute within the specified scope.
 * This function is used to set up the audio playback functionality on the page.
 *
 * @param {string|HTMLElement} [scope=document] - The scope within which to find the audio elements. Can be a CSS selector string or an HTMLElement.
 */
function initAudioPlayers(scope = document) {
    // If scope is a string selector, get the DOM element
    const container = scope.jquery ? scope[0] : (typeof scope === 'string' ? document.querySelector(scope) : scope);
    // Find all audio elements with data-plyr-player attribute
    const audioElements = container.querySelectorAll('audio[data-plyr-player]');

    // Initialize Plyr for each audio element
    audioElements.forEach(audio => {
        if (audio.hasAttribute('data-plyr_disable_volume')) {
            // minimal player, for podcast home page features
            const controls = [
                'play',
                'progress',
                'mute',
            ];
            const player = new Plyr(audio, {
                controls: controls
            });
            return true;
        } else {
            const player = new Plyr(audio, {});}
    });
}

/**
    * function to show elements that are for admin only users such as view count metadata
    * relies on global adminLoggedIn variable being set in layouts/_base template
    * @returns null
    */
function showAdminOnlyMeta() {
    $('.admin-only.hidden').each(function () {
        if (!adminLoggedIn) {
            // remove element
            $(this).remove();
        } else {
            // show element
            $(this).removeClass('hidden');
        }
    });
}
// Function to check if the div is taller than the browser window
function isDivTallerThanWindow(divId) {
    // Get the div element
    const div = document.getElementById(divId);

    // Get the div height and window height
    const divHeight = div.offsetHeight;
    const windowHeight = window.innerHeight;

    // Check if the div is taller than the window
    return divHeight > windowHeight;
}
// Registration Popup
let validate_email_timer,
    validate_password_timer,
    email_passed = false,
    password_passed = false,
    checkbox_passed = false;

(function ($) {
    function scheduleEmailValidate() {
        clearTimeout(validate_email_timer);
        validate_email_timer = setTimeout(function () {validate_email();}, 300);
    }

    function schedulePasswordValidate() {
        clearTimeout(validate_password_timer);
        validate_password_timer = setTimeout(function () {validate_password();}, 300);
    }

    // --- Delegated listeners (work even if fields appear later) ---
    $(document)
        .on('input change keyup paste blur', '#reg-email', scheduleEmailValidate)
        .on('input change keyup paste blur', '.password', schedulePasswordValidate)
        .on('change', '#field-accept', function () {
            checkbox_passed = this.checked;
            enable_register_button();
        });

    // Initial pass on ready (covers prefilled/restored values)
    $(function () {
        scheduleEmailValidate();
        schedulePasswordValidate();
        enable_register_button();
    });

    // --- Option A: short-burst polling on likely fill moments (delegated) ---
    const watchers = new Map();

    function startWatcher($el, onChange, opts) {
        const el = $el[0];
        if (!el) return; // field not in DOM yet
        let last = el.value;
        const every = (opts && opts.interval) || 120;  // ms
        const max = (opts && opts.maxMs) || 6000; // stop after 6s
        const started = Date.now();

        stopWatcher($el);
        const id = setInterval(function () {
            const cur = el.value;
            if (cur !== last) {
                last = cur;
                onChange(); // schedules validation
            }
            if (Date.now() - started > max) {stopWatcher($el);}
        }, every);
        watchers.set(el, id);
    }

    function stopWatcher($el) {
        const el = $el[0];
        const id = watchers.get(el);
        if (id) { clearInterval(id); watchers.delete(el); }
    }

    // Start/stop the watcher using delegated events
    $(document).on('focus pointerdown', '#reg-email, #field-password, #field-conf-pass', function () {
        const $t = $(this);
        if ($t.is('#reg-email')) {
            startWatcher($t, scheduleEmailValidate);
        } else {
            startWatcher($t, schedulePasswordValidate);
        }
    });
    $(document).on('input change blur', '#reg-email, #field-password, #field-conf-pass', function () {stopWatcher($(this));});

    // Re-check when the page is shown or tab becomes visible (BFCache / overlays)
    window.addEventListener('pageshow', function () {
        scheduleEmailValidate();
        schedulePasswordValidate();
    });
    document.addEventListener('visibilitychange', function () {
        if (!document.hidden) {
            scheduleEmailValidate();
            schedulePasswordValidate();
        }
    });
})(jQuery);

// --- Validators (now defensive against missing fields) ---

function validate_email() {
    const $el = $('#reg-email');
    if (!$el.length) {
        // Field not present; keep things disabled
        email_passed = false;
        enable_register_button();
        return;
    }

    let email = ($el.val() ?? '').toString().trim();

    // Clear previous messages
    $el.removeClass('validate-error');
    $el.next('.validate-message').remove();

    // Format check
    const email_regex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!email_regex.test(email)) {
        $el.addClass('validate-error');
        $('<span class="validate-message">Invalid email format</span>').insertAfter($el);
        email_passed = false;
        enable_register_button();
        return;
    }

    // Availability check
    $.ajax({
        url: '/_ajax/user_with_email/' + encodeURIComponent(email),
        method: 'GET',
        // be tolerant: server might return 0/1 as text OR a JSON boolean/object
        dataType: 'text'
    }).done(function (resp) {
        // Accept several shapes: "0"/"1", 0/1, true/false, {exists:true}
        let exists = false;
        try {
            // If server sent JSON, parse it; otherwise Number() handles "0"/"1"
            const parsed = (typeof resp === 'string' && resp.trim().startsWith('{')) ? JSON.parse(resp) : resp;
            if (typeof parsed === 'object' && parsed !== null) {
                exists = !!(parsed.exists || parsed.taken || parsed.count > 0);
            } else {
                exists = (parsed === true) || (Number(parsed) > 0);
            }
        } catch (e) {
            exists = Number(resp) > 0;
        }

        if (exists) {
            $el.addClass('validate-error');
            $('<span class="validate-message">This email is taken</span>').insertAfter($el);
            email_passed = false;
        } else {
            email_passed = true;
        }
    }).fail(function () {
        email_passed = false;
        $el.addClass('validate-error');
        $('<span class="validate-message">Error checking email</span>').insertAfter($el);
    }).always(function () {enable_register_button();});
}

function validate_password() {
    const $p1 = $('#field-password');
    const $p2 = $('#field-conf-pass');
    if (!$p1.length || !$p2.length) {
        password_passed = false;
        enable_register_button();
        return;
    }

    let pass1 = $p1.val() ?? '';
    let pass2 = $p2.val() ?? '';

    password_passed = false;

    // Must contain 1 lowercase, 1 uppercase, 1 number, min 7 chars
    if (/^(?=(.*[a-z]){1,})(?=(.*[A-Z]){1,})(?=(.*[\d]){1,})(?!.*\s).{7,}$/.test(pass1)) {
        $p1.next('.validate-message.requirement').remove();
        if (pass1 !== pass2) {
            if ($p2.val() !== '') {
                if ($p2.next('.validate-message.same').length === 0) {
                    $('<span class="validate-message same">The passwords entered do not match</span>').insertAfter($p2);
                }
                $('.password').addClass('validate-error');
            }
        } else {
            $p1.next('.validate-message').remove();
            $p2.next('.validate-message').remove();
            $('.password').removeClass('validate-error');
            $('.password').next('.validate-message').remove();
            password_passed = true;
        }
    } else {
        if ($p1.next('.validate-message.requirement').length === 0) {
            $('<span class="validate-message requirement">The password entered does not meet the requirements</span>').insertAfter($p1);
        }
        if (pass1 === pass2) {$p2.next('.validate-message.same').remove();}
        $('.password').addClass('validate-error');
    }
    enable_register_button();
}

function enable_register_button() {
    const $btn = $('#register-button');
    if (email_passed && password_passed && checkbox_passed) {
        $btn.removeClass('disabled').prop('disabled', false);
    } else {
        $btn.addClass('disabled').prop('disabled', true);
    }
}