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

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

		//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 h4').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();
		});

		// Fix article image/caption sizes
		// $('.article-caption').each(function () {
		//	 tempWidth = $(this).siblings('img').width();
		//	 // Conditional in case of image not loading and making the width 0
		//	 if (tempWidth) {
		//		 $(this).width(tempWidth);
		//	 }
		// });

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

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

				initIsotope($grid);

				$('.isotope-filter li:first').addClass(activeTabClass);
				$win.trigger('scroll');
			});
		})();

		$('.isotope-filter a').on('click', function(event) {
			event.preventDefault();

			var $this = $(this);
			var filter = $this.data('filter');
			var $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;
			}

			var $this = $(this);
			var $container = $this.parents('.tab').find('.ajax-container');
			var item = $this.data('item');

			loadMoreContent($this, $container, item);

			ajaxLoading = true;

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

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

		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-survey-popup-trigger').click();
				}
				// 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() {
				$('.nav-secondary .nav-title').on('click', function(event) {
					event.preventDefault();

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

				initIsotope($grid);
				isotopeMagic();
			})
			.on('scroll', function() {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);});
        }
        // init logged in elements
        showAdminOnlyMeta();
    });

	// 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() {
		var $container = $('.tab.current').find('.isotope-container');
		var $parent = $container.closest('.tab');
		var index = $container.data('load');
		if (
			$container.find('.isotope-item:last').is(':visible') ||
			$container.is(':visible')
		) {
			var $newEls = $parent.find(
				'.isotope-container-dummy .isotope-item:lt(' + index + ')'
			);

			if (typeof $newEls !== 'undefined') {
				$container.isotope('insert', $newEls);
			}
		}
	}

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

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