;(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);

            $this.closest('.has-dd').addClass('focused');
        });

        $('.nav-primary li').each(function() {
            var $this = $(this);

            if ($this.is(':last-child')) {$this.addClass('last');}
        });

        $('.nav-primary .last a').on('focusout', function(event) {$(this).closest('.has-dd.focused').removeClass('focused');});

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

                $(this).closest('li').addClass('focused');
            }
        });

        // Open the tab on page load
        $('.tabs-nav li a').each(function(index) {

            $hash = window.location.hash.toLowerCase();
            $hashText = $hash.substr(1);

            //This is just in case there are some entries with different hash text.
            //$tab_text = $(this).text().toLowerCase().replace(' ', '_');
            //Removes any question mask for an empty string and any space for an -
            $tab_text1 = $(this).text().toLowerCase().replace(/\s/g, "_").replace(/\?/g,"");
            //There might be hashes with - instead of _
            $tab_text2 = $(this).text().toLowerCase().replace(/\s/g, "-").replace(/\?/g,"");
            $tab_link = $(this).attr("href");

            if ($hash == $tab_link || $hashText == $tab_text1 || $hashText == $tab_text2) {
                //Make sure classes are set correctly in case hashes do not match
                //Make sure we only remove current class from desire tab
                $(this).parents("ul").first().find("li").removeClass('current');
                $(this).parent().addClass('current');
            }

            //Make sure to only remove the current class from target element
            $($hash).parent().find(".tab").removeClass("current");
            $($hash).addClass('current');

            const targetContainer = $($tab_link).find('.isotope-container');

            // Initialize Isotope for the new active tab
            initializeIsotopeForContainer(targetContainer);
        });

        //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);
        });

        // Slider
        var slides = $('.slider-primary .slide').length;
        var random = Math.floor(Math.random() * slides) + 1;

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

        $('.slider .slide a').on('keyup', function(e) {
            var slider = $(this).closest('.owl-carousel');
            var keyCode = e.keyCode || e.which;

            if (keyCode == 9) {
                if (e.shiftKey) {
                    if (!$(this).closest('.owl-item').hasClass('active')) {slider.trigger('prev.owl.carousel');}
                } else {
                    if (!$(this).closest('.owl-item').hasClass('active')) {slider.trigger('next.owl.carousel');}
                }
            }
        });

        // 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() {
            // This class will be added to active tab link
            // and the content container
            var activeTabClass = 'current';

            // If the first tab isn't the active tab we need to set it
            if ($('.tabs-nav').find('.current').length == 0) {
                firstTabNav = $('.tabs-nav').find('li').first();
                // Get the href since that'll be the tab ID to set current as well
                targetTab = firstTabNav.find('a').attr('href');
                // Set the tab-nav as current
                firstTabNav.addClass(activeTabClass);
                // Set the tab-body as current
                $('.tabs-body')
                    .find('.tab' + targetTab)
                    .addClass(activeTabClass);
            }

            $('.tabs-nav a').on('click', function(event) {
                var $tabLink = $(this);
                var $targetTab = $($tabLink.attr('href'));

                // set global vars based on current tab
                $parent = $targetTab;
                $conatiner = $parent.find('.isotope-container');

                window.location.hash = $tabLink.attr('href');
                $tabLink
                    .parent() // go up to the <li> element
                    .add($targetTab)
                    .addClass(activeTabClass)
                    .siblings()
                    .removeClass(activeTabClass);

                event.preventDefault();

                // add check to ensure isotope is initialized
                var isoCheck = $grid.data('isotope');
                if (isoCheck)
                {$grid.isotope('destroy');}

                let showMoreLink = $parent.find('.show-more-container a');
                initIsotope($container);

                // check if request is first page or not
                if (showMoreLink.attr('data-first-load') === 'yes') {
                    let href = showMoreLink.attr('href') + '/P0';
                    $container.isotope('layout')
                    isotopeMagic(href);
                } else {isotopeMagic();}
                $('.isotope-filter li:first').addClass(activeTabClass);

            });
        })();

        $('.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-dummy .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');
        });

        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 ajaxContainer = $this.parents('.tab').find('.ajax-container');
            const item = $this.data('item');
            ajaxLoading = true;

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

        function loadMoreContent($button, $container, item) {
            // 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;
                    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';
            }
            $(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 {
                        // login popup
                        // get data element data-path from opener
                        let data = item.el.data();
                        // remove query string from href, prevent hacking attempt
                        item.src = item.src.split('?')[0];
                        // set the source of the ajax popup, add the path GET variable
                        // should be url encoded in the template
                        if (data.path !== null) {
                            let path = data.path;
                            if (path != '/' && decodeURIComponent(path) != '/') {
                                item.src += '?path=' + encodeURIComponent(data.path);
                            }
                        }
                    }
                },
                ajaxContentAdded: function() {
                    popupPos();
                    loadNewsletterSignup();
                    /* 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;
                                });
                            },
                        }
                    });

                    // Submit the survey form and set cookie, so users do not see the popup again
                    $('#survey_popup_freeform').submit(function(event) {
                        Cookies.set('gg_survey_submitted', 1, {expires: 100});
                        //Added cookie for 100 days, need to confirm
                        return true;
                    });

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

                    /* END ADDED CODE */
                    $('a').on('click', function() {
                        return -1;
                    });
                }
            }
        });

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

        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();

        // Cookies logic for the survey popup
        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');
            });
        })();

        $('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');}
                    });
                }

                $('.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();

        // 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;
                    }
                });
            }
        }
    });




    // 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');

        // 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('div.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');
                    showMoreLink.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);

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);
}


function loadMoreCallback(newObj) {

    initBookmarkButtons(newObj);

    // only if a2a addtoany is defined
    if (typeof a2a !== 'undefined' && typeof a2a.init_all === 'function') {a2a.init_all();}

}

/**
 * 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
        );
    }
}


function initAudioPlayers() {
    $('.audio-block').each(function (i, e) {
        eAudio = document.createElement('audio');
        if (eAudio.canPlayType && eAudio.canPlayType("audio/mpeg")) {
            $('<audio  data-able-player controls id="audio_recent_' + $(e).data('count') + '" preload="none"><source src="' + $(e).data('url') + '" type="audio/mpeg"> Your browser does not support the audio element.</audio>').insertAfter($(e));
        } else {
            $('<object id="audio_recent_' + $(e).data('count') + '" type="application/x-shockwave-flash" data="https://greatergood.berkeley.edu/swf/player_mp3_maxi.swf" width="200" height="20"><param name="movie" value="https://greatergood.berkeley.edu/swf/player_mp3_maxi.swf" /><param name="FlashVars" value="mp3=' + $(e).data('count') + '&bgcolor1=189ca8&bgcolor2=085c68" /></object>').insertAfter($(e));
        }
        $(e).remove();
        new AblePlayer('#audio_recent_' + $(e).data('count'));
    });
}

/**
    * 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');
        }
    });
}