;(function($, window, document, undefined) {
    var $win = $(window);
    var $doc = $(document);

    $doc.ready(function() {
        var isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);

        // bind a listener to the body for the dynamically created
        // form sign in modal
        $("body").on("submit", ".form-signin form", function()
        {
            // Update the retrun value to return the user to the current page
            $(".form-signin form").find(".hiddenFields input[name='RET']").val(window.location.href);
        });

        // Init custom scroll

        $('.social-stream').niceScroll({
            cursorwidth: 8,
            cursorborder: 0,
            cursorborderradius: 0,
            cursorcolor: '#c2c2c2',
            background: '#d8d8d8',
            autohidemode: false
        });

        // Open Subscription Box
        $(document).on('focus', '.form-subscribe .email-field', function(event) {
            event.stopPropagation();

            var parent = $(event.currentTarget).closest('.form-subscribe');
            parent.find('.custom-select').dropdown();
            parent.find('.form-body').addClass('expand');
            parent.find('.form-group-hidden').addClass('expand');
            setTimeout(function() {$('.social-stream').getNiceScroll().resize();}, 500);
            
            parent.one('click', function (e) {e.stopPropagation();});
        }).on('click', function(e) {
            if ($('.form-subscribe .form-group-hidden.expand').length > 0 && !$(e.target).closest('.form-subscribe').length > 0) {
                $('.form-subscribe .form-body').removeClass('expand');
                $('.form-subscribe .form-group-hidden').removeClass('expand');
                setTimeout(function() {$('.social-stream').getNiceScroll().resize();}, 500);
            }
        }).on('click', '.mfp-close, .popup__btn, .popup-track-close, .close-popup, .popup-track-login', function (e) {
            Cookies.set('ssir_popup_closed', 1, { expires: 1 });
        }).on('click', '.popup-action-subscribed', function (e) {
            Cookies.set('ssir_popup_subscribed', 1, { expires: 365 });
        });

        // Open Modals
        var setupMagnificPopup = function() {
            $('.modal-trigger').magnificPopup({
                type: 'ajax',
                closeOnBgClick: false,
                fixedContentPos: true,
                fixedBgPos: true,
                callbacks: {
                    ajaxContentAdded: function() {
                        $('.custom-select').dropdown();
                        $('.offset-nav').removeClass('slideIn');

                        $('.open-part2').on('click', function(event) {
                            event.preventDefault();

                            $('.popup-part2').removeClass('hidden');
                        });

                        $('.open-international').on('click', function(event) {
                            event.preventDefault();

                            $('.popup-part3').removeClass('hidden');
                        });

                        // Set Active International Subscription
                        $('.custom-radio-alt label').on('click', function() {
                            var colIndex = $(this).closest('td').index();
                            var rowIndex = $(this).closest('tr').index();

                            $('.form-subscription-international th, .form-subscription-international td').removeClass('active');

                            $('.form-subscription-international th').eq(colIndex).addClass('active');
                            $('.form-subscription-international tr').eq(rowIndex).find('td').eq(0).addClass('active');
                        });

                        /* Don't select elements if placeholder is natively supported*/
                        if (!$.support.placeholder) {
                            $('input[placeholder], textarea[placeholder]').doPlaceholders();
                        }
                        //Re-init event on popup trigger links
                        setupMagnificPopup();
                    },
                    close: function() {
                        $('.offset-nav').addClass('hide');
                        setTimeout(function() {$('.offset-nav').removeClass('hide');}, 300);
                        $('html').css({'overflow':'auto'});
                        $('html').removeClass('no-scroll');
                        $('body').removeClass('no-scroll');
                    }
                }
            });
        };
        //Init popups
        setupMagnificPopup();

        // Toggle Search Box
        $('.btn-search').on('click', function(event) {
            event.stopPropagation();

            $('#search-container div.gsc-clear-button').on('click', function(event) {
                event.preventDefault();

                $('#search-container').removeClass('show');
            })

            $(this).siblings('#search-container').addClass('show');
        });

        $('.search').on('click', function(event) {event.stopPropagation();});

        //JS Smooth scroll to block
        $('.js-scroll-to').on('click', function(event){
            if ($('#'+$(this).data('block-id')).length)
            {
                $('html, body').animate({
                    scrollTop: $('#'+$(this).data('block-id')).offset().top
                }, 2000);
            }
            return false;
        });

        // Open Comments
        $('#comment').on('focus', function() {$('.hiddenFields').siblings().slideDown();});

        // Show Tablet Navigation
        $('.nav-trigger').on('click', function(event) {
            event.preventDefault();
            $('body, html').addClass('no-scroll');
            $('.offset-nav').addClass('slideIn');
        });

        // Hide Tablet Navigation
        $('.offset-nav .close, .offset-nav-dropdown .close').on('click', function(event) {
            event.preventDefault();

            $('body, html').removeClass('no-scroll');
            $('body, .offset-nav').removeClass('overflow');
            $('.offset-nav, .offset-nav-dropdown').removeClass('slideIn');
        });

        // set nav menu height based on current window size
        function setNavHeight() {
            $('.offset-nav-body').css({
                height: function() {
                    return $win.height() - 70;
                }
            });

            $('.offset-nav-dropdown-body').css({
                height: function() {
                    return $win.height() - 70;
                }
            });
        }

        setNavHeight();
        window.addEventListener('orientationchange', setNavHeight );
        window.addEventListener('resize', setNavHeight );


        function setCaptionWidth() {
            $('.wp-caption').css({
                width: function() {
                    return $(this).find('img').width('100%'); // should fix problem caused when resizing page
                    //return $(this).find('img').width();
                }
            });

            $('.offset-nav-dropdown-body').css({
                height: function() {
                    return $win.height() - 70;
                }
            });
        }

        setCaptionWidth();
        window.addEventListener('resize', setCaptionWidth );

        // moves series boxes to the bottom when the window is too small
        function moveArticleBoxes() {
            box = $('.seriesbox, .innerbox').not('.no-move');
            if ( box.length > 0) {
                if($win.width() < 479) {
                    $(box).each(function( index ) {
                        if (! $.hasData(this) ) {
                            $( this ).data('movedFrom',$( this ).prevAll().length);
                            $( this ).appendTo('.article-entry:first');
                        }
                    })
                } else {
                    $(box).each(function( index ) {
                        if ($.hasData(this) ) {
                            moveTo = $('.article-entry:first').children().eq( $( this ).data('movedFrom') );
                            $( this ).removeData();
                            $( this ).appendTo(moveTo);
                        }
                    })
                }
            }		
        }

        moveArticleBoxes();
        window.addEventListener('resize', moveArticleBoxes );


        // Open Secondary Mobile Navigation (fix +'>')
        $('.has-submenu > a').on('click', function(event) {
            event.preventDefault();

            $('body, html').animate({
                'scrollTop': 0
            }, 300);
            $('body').addClass('overflow');
            $('.offset-nav').addClass('overflow');
            $(this).next().addClass('slideIn');
        });

        $('.offset-nav-dropdown .back').on('click', function(event) {
            event.preventDefault();

            $('body').removeClass('overflow');
            $('.offset-nav').removeClass('overflow');
            $(this).closest('.offset-nav-dropdown').removeClass('slideIn');
        });

        if($win.width() < 768) {
            $('.form-group-hidden > .form-row > p').insertAfter( $('.form-group-hidden .form-actions .btn') );
        }

        $.fn.doPlaceholders = function() {
            if ($.support.placeholder) {
                return this;
            }

            var $fields = this.filter(function () {
                // Don't re-initialize
                return !$(this).data('didPlaceholders');
            });

            $fields.on('focus blur', function(event) {
                var placeholder = this.getAttribute('placeholder');

                if (event.type === 'focus' && placeholder === this.value) {
                    this.value = '';
                } else if (event.type === 'blur' && this.value === '') {
                    this.value = placeholder;
                }
            });

            // Set the initial value to the title
            $fields.each(function() {
                if (this.value === '') {
                    this.value = this.getAttribute('placeholder');
                }
            });

            // Mark the fields as initialized
            $fields.data('didPlaceholders', true);

            // Alllow
            return $fields;
        };

        $.support.placeholder = (function() {
            return 'placeholder' in document.createElement('input');
        })();

        /* Don't select elements if placeholder is natively supported*/
        if (!$.support.placeholder) {
            $('input[placeholder], textarea[placeholder]').doPlaceholders();
        }

        //**** OLD SCRIPTS NEEDED ON NEW DESIGN ****//
        /* rotate doesn't exists... ?? */
        // $('#img_rotate45').rotate(10);
        // $('#img_rotate45_b').rotate(10);
        // $('#img_rotate45_sub').rotate(10);

        $('.blink').focus(function () {
            if ($(this).val() == $(this).attr('title')) {$(this).val('');}
        }).blur(function () {
            if ($(this).val() == '') {$(this).val($(this).attr('title'));}
        });

        $('.print').click(function() {
            window.print();
            return false;
        });

        $('#reset-popup-cookies').click(function() {
            Cookies.remove('ssir_popup_closed');		// 1 day
            Cookies.remove('ssir_popup_subscribed');	// 365 day
            Cookies.remove('ssir_pages');
            console.log(Cookies.get('ssir_newsletter'));
        });
        $('#reset-popup-cookies-all').click(function() {
            Cookies.remove('ssir_newsletter');			// 30 days
            Cookies.remove('ssir_popup_closed');		// 1 day
            Cookies.remove('ssir_popup_subscribed');	// 365 day
            Cookies.remove('ssir_pages');
            console.log(Cookies.get('ssir_newsletter'));
        });

        function showPopups(ssir_logged_in) {
            var testing = false;
        
            // Settings
            var show_on_page = 2;
            var cycle_length = 30; // days
            var group_id = 3; // what kind of user
        
            // See if newsletter has been shown
            var ssir_newsletter = Cookies.get('ssir_newsletter');
            if (ssir_newsletter == undefined) ssir_newsletter = 0;
        
            // See if user has subscribed
            var ssir_popup_subscribed = Cookies.get('ssir_popup_subscribed');
            if (ssir_popup_subscribed == undefined) ssir_popup_subscribed = 0;
        
            // See if popup has been shown
            var ssir_popup_closed = Cookies.get('ssir_popup_closed');
            if (ssir_popup_closed == undefined) ssir_popup_closed = 0;
        
            // keep track of how many pages have been visited
            // separate because this is a session-based counter with a different expiration
            var on_pages = Cookies.get('ssir_pages');
            if (on_pages == undefined) on_pages = 0;

            on_pages ++;
        
            Cookies.set('ssir_pages', on_pages, { expires: 1 });
        
            const termlyCacheRaw = localStorage.getItem('TERMLY_API_CACHE');
            let showPopup = false;

            if (termlyCacheRaw) {
                try {
                    const termlyConsent = JSON.parse(termlyCacheRaw);
                    console.log(termlyConsent?.TERMLY_COOKIE_CONSENT.value);
                    if (termlyConsent?.TERMLY_COOKIE_CONSENT.value.performance === true) {
                        showPopup = true; // ✅ user allowed advertising cookies
                    } else {
                        console.log('Performance not consented — skipping popup');
                    }
                } catch (e) {
                    console.error('Failed to parse TERMLY_COOKIE_CONSENT:', e);
                }
            }
            // if it is the second page visited, and you're not logged in, open a popup
            if (testing || (on_pages >= show_on_page && showPopup)) {
                if (ssir_newsletter == 0 && ssir_popup_subscribed == 0 && !isSafari) {
                    setTimeout(() => openSubPop('newsletter'), 1000);
                } else if (ssir_logged_in == 0 && (ssir_popup_closed == 0 && ssir_popup_subscribed == 0 && (group_id == 0 || group_id == 1 || group_id == 3))) {
                    setTimeout(() => openSubPop('subscribe'), 1000);
                }
            }
        }

        (async () => {
            const ssir_logged_in = await fetchAndInjectHTML('/defer-load/is-logged-in', null, false);
            showPopups(ssir_logged_in);
        })();

        // trigger the proper popup by emulating a link click
        // yes, it's convoluted, but that's how it is
        function openSubPop(name) {
            switch(name) {
                case 'newsletter':
                    $( "#popup-trigger" ).attr('href', 'https://ssir.org/popups/newsletter_20181210_2');
                    $( "#popup-trigger" ).attr('data-popup_label', 'newsletter 20181210_2');
                    Cookies.set('ssir_newsletter', 1, { expires: 365 });
                    break;
                default:
                    $( "#popup-trigger" ).attr('href', 'https://ssir.org/popups/subscribe_20200601');
                    $( "#popup-trigger" ).attr('data-popup_label', 'subscribe 20200601');
                    break;
            }

            setupMagnificPopup();

            $("#popup-trigger").trigger("click");
            setTimeout(function () { dataLayer.push({'event': 'popup-load', 'popup-label': $( "#popup-trigger" ).attr('data-popup_label')}); }, 1000);
        }

        //**** END OLD SCRIPTS ****//
        
        $doc.on('click', '.citation-block__copy', function () {
            $('.citation-copied').remove();
            let target_id = $(this).data('target');
            let range = document.createRange();
            range.selectNode(document.getElementById(target_id));
            window.getSelection().removeAllRanges(); // clear current selection
            window.getSelection().addRange(range); // to select text
            document.execCommand("copy");
            window.getSelection().removeAllRanges();// to deselect
            $('#' + target_id).append('<svg class="citation-copied" xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-check-circle"><path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"></path><polyline points="22 4 12 14.01 9 11.01"></polyline></svg>');
        }).on('click', '.btn-cite', function () {$('#citation-popup').removeClass('hidden');}).on('click', '.citation-close', function () {$('#citation-popup').addClass('hidden');}).on('click', '.citation-backdrop', function (e) {
            if (e.target.id == 'citation-popup') {$('#citation-popup').addClass('hidden');}
        }).on('change', '#citation-selector', function () {
            let citation_style = $(this).val();
            $('#citation-content').html(citations[citation_style]);
        });

        $('.ico-close').click(function () {
            $('.hovertext').removeClass('show');
            $('.arrowblock').removeClass('show');
        });

        $('.hoverlink').click(function (e) {
            if (!$(e.target).is('.ico-close'))
            {
                $('.hovertext', this).toggleClass('show');
                $('.arrowblock', this).toggleClass('show');
            }
        });
        
        $( ".hoverlink" ).hover(
            function() {
                $('.hovertext', this).addClass('show');
                $('.arrowblock', this).addClass('show');
            }, function() {
                $('.hovertext', this).removeClass('show');
                $('.arrowblock', this).removeClass('show');
            }
         );
        
        if($win.width() < 480) {
            $('.presenters .hoverlink').click(function () {
                $('.arrowblock', this).hide();
                $('.hovertext', this).css({
                    'position': 'absolute',
                    'top': $win.scrollTop(),
                    'width' : $win.width(),
                    'left' : '0px',
                    'right' : '0px',
                    'margin': '0'
                });
                
            });
        }
        
        $('.js-collapse-if-empty').each(function() {
            var this_html = $(this).html().trim();
            console.log("STRLEN:" + this_html.length);
            if (this_html.length == 0) {$(this).hide();}
        });

        // Ads
        $(document).ready(function () {moveGoogleAds();});

        var moving_ads = 0;
        $(window).resize(function () {
            clearTimeout(moving_ads);
            moving_ads = setTimeout(function () {moveGoogleAds();}, 500);
        });

        var google_ads_at = 'desktop';

        function moveGoogleAds() {
            var pathArray = window.location.pathname.split('/'),
                segment_1 = pathArray[1]; // Getting the first segment

            if ($(window).width() < 768 && google_ads_at == 'desktop') {
                $('.desktop-ad-container').each(function (e) {
                    var ad_zone_id = $(this).data('ad-key');

                    if ($('.mobile-ad-container[data-ad-key="' + ad_zone_id + '"]').length > 0) {
                        var ad_unit = $(this).children().detach();
                        ad_unit.appendTo('.mobile-ad-container[data-ad-key="' + ad_zone_id + '"]');
                    }
                });
                google_ads_at = 'mobile';
            } else if ($(window).width() > 767 && google_ads_at == 'mobile') {
                $('.mobile-ad-container').each(function (e) {
                    var ad_zone_id = $(this).data('ad-key');
                    var ad_unit = $(this).children().detach();

                    if ($('.desktop-ad-container[data-ad-key="' + ad_zone_id + '"]').length > 0) {
                        ad_unit.appendTo('.desktop-ad-container[data-ad-key="' + ad_zone_id + '"]');
                    }
                });
                google_ads_at = 'desktop';
            }
        }
    });
})(jQuery, window, document);