function _ims_templates_onload() {
	var code_to_run = [];
	var add = function ( c ) {
		code_to_run.push( c );
	}
	var runall = function ( ) {
		for(var i=0; i < code_to_run.length; i++) {
			if( typeof(code_to_run[i])=='function')
				code_to_run[i]();
			else {
				try { eval(code_to_run[i]); }
				catch( exc ) { 'Note: some error occurred!'; }
			}
		}
	}
	this.add = add;
	this.run = runall;
	this.code_to_run = code_to_run;
}

var IMS_Onload = new _ims_templates_onload();

// Prevent Empty Searches
function searchCheck(q)  {
  if (q.value == 'SEARCH TEXT' || q.value.search(/^\s*$/) >=0)  {
    alert('Please enter a search phrase.');
    return false;
  }
  return true;
}

// Store the Sub Navigation and clone a version for the mobile version modal window.
var leftNav = $('.leftNav-wrap').html();
// Place that cloned navigation into BS's modal markup
$('<div class="modal fade" tabindex="-1" id="leftNav" aria-labelledby="modalTitle"><div class="modal-dialog modal-lg modal-dialog-centered" role="document"><div class="modal-content"><div class="modal-header"><p class="modal-title" id="modalTitle"><strong>In this section...</strong></p><button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button></div><div class="modal-body">'+leftNav+'</div></div></div></div>').insertBefore('.leftNav-wrap');

function openParentDropdown(thisLink) {
	const mediaQuery = window.matchMedia('(max-width: 992px)');
	if (mediaQuery.matches) {
		// if the current page is within a dropdown, open that dropdown
		var containingDropdownMenu = thisLink.closest('.dropdown-menu');
		if (containingDropdownMenu) {
			containingDropdownMenu.addClass('show');
			containingDropdownMenu.prev().addClass('show');
			containingDropdownMenu.prev().attr('aria-expanded', 'true');
		}
	}
	return false;
}

// Highlight the active main menu section
$(function(){
	var currentIsAssigned = false;
	
	// account for special case pages
	var pathCleaned = location.pathname;
	if (pathCleaned.includes('/seer-inquiry/')) {
		pathCleaned = '/seer-inquiry/';
	} else if (pathCleaned.includes('/seertools/seerrx')) {
		pathCleaned = '/tools/seerrx/';
	} else if (pathCleaned.includes('/seertools/glossary')) {
		pathCleaned = '/seertools/glossary/'
	} else if (pathCleaned.includes('/seertools/hemelymph')) {
		pathCleaned = '/tools/heme/';
	} else if (pathCleaned.includes('/vtr/profile/')) {
		pathCleaned = '/vtr/';
	} else if (pathCleaned.includes('/vtr/')) {
		var pathPortions = pathCleaned.split("/vtr/");
		var suffix = pathPortions[pathPortions.length -1];
		pathCleaned = '/vtr/' + suffix;
	} else if (pathCleaned.includes('/oncologytoolbox/')) {
		pathCleaned = '/data-software/';
	} else if (pathCleaned.includes('/news/')) {
		pathCleaned = '/news/';
	}
	var match = $('#topnav a[href="' + pathCleaned + '"]');
	if (match.length != 0) {
		match.closest('li').addClass('current-page');
		match.parentsUntil('.navbar-nav').addClass('contains-current');
		openParentDropdown(match);
		currentIsAssigned = true;
	}
    
	// if there is no exact match from the main menu, look for an ancestor of the current page in the main menu instead
	if (!currentIsAssigned && $(".leftNav")) {
		// find the lowest-level a.active or a.active's parent from the leftnav that's contained in the topnav
		var topnavLinks = $('#topnav .dropdown-item:not(".dropdown-header")').add($('.unlisted-children'));
		$(topnavLinks).each(function(){
			$this = $(this);
			// does the leftnav list headed by this href contain a.active?
			var matchActive = $('#leftNav li > a[href="' + $this.attr('href') + '"]');

			if (matchActive.length != 0) {
				// does this link have a child that is active?
				if (matchActive.hasClass("active") || matchActive.parent().has("a.active").length != 0) {
					$this.closest('li').addClass('current-page');
					$this.parentsUntil('.navbar-nav').addClass('contains-current');
					openParentDropdown($this);
					currentIsAssigned = true;
				} 
			}
		});
		if (!currentIsAssigned) {
			// if we still haven't found a topnav link to highlight, assign current-page to the landing link of the leftnav section
			var sectionLink = $('#topnav a[href="' + $("#leftNav:first-child a").attr('href') + '"]');
			var closestLink = sectionLink.closest('li');
			if (!closestLink) {
				closestLink = sectionLink;
			}
			closestLink.addClass('current-page');
			sectionLink.parentsUntil('.navbar-nav').addClass('contains-current');
			openParentDropdown(sectionLink);
		}
	}
	return false;
})
// if the window is resized from mobile menu dimensions to desktop main menu dimensions, collapse any open menu items
function collapseMenuDropdown(prevWidth, currentWidth) {
	if (prevWidth < 992 && currentWidth >= 992) {
		var dropdownMenus = $('.navbar-nav .dropdown-menu');
		$(dropdownMenus).each(function(){
			var $this = $(this);
			$this.removeClass('show');
			$this.prev().removeClass('show');
			$this.prev().attr('aria-expanded', 'false');
		})
		// if mobile menu was open, remove the darkened backdrop
		if ($('.offcanvas-backdrop').has('show')) {
			$('.offcanvas-backdrop').removeClass('show');
		}
	}
	return false;
}
// if the window is resized from mobile menu dimensions to desktop main menu dimensions, expand the current section dropdown if applicable
function expandMenuDropdown(prevWidth, currentWidth) {
	if (prevWidth >= 992 && currentWidth < 992) {
		// if mobile menu is open, show the darkened backdrop
		if ($('.offcanvas').has('show')) {
			$('.offcanvas-backdrop').addClass('show');
		}
		$('li.dropdown.contains-current button').addClass('show');
		$('li.dropdown.contains-current button').attr('aria-expanded', 'true');
		$('ul.contains-current').attr('aria-expanded', 'true');
		$('ul.contains-current').addClass('show');
		$('ul.contains-current').attr('data-bs-popper', 'none');
	}
	return false;
}
// close offcanvas main nav on resize from desktop main menu dimensions to mobile main menu dimensions
function closeMenuResize(prevWidth, currentWidth) {
	if (prevWidth >= 992 && currentWidth < 992) {
		$('#topnav .offcanvas').removeClass('show');
	}
	return false;
}

// double scrollbar
// https://github.com/avianey/jqDoubleScroll
jQuery.fn.doubleScroll=function(l){var e={contentElement:void 0,scrollCss:{"overflow-x":"auto","overflow-y":"hidden"},contentCss:{"overflow-x":"auto","overflow-y":"hidden"},onlyIfScroll:!0,resetOnWindowResize:!1,timeToWaitForResize:30};$.extend(!0,e,l),$.extend(e,{topScrollBarMarkup:'<div class="doubleScroll-scroll-wrapper" style="height: 20px;"><div class="doubleScroll-scroll" style="height: 20px;"></div></div>',topScrollBarWrapperSelector:".doubleScroll-scroll-wrapper",topScrollBarInnerSelector:".doubleScroll-scroll"});var o=function(l,e){if(e.onlyIfScroll&&l.get(0).scrollWidth<=l.width()+1)return void l.prev(e.topScrollBarWrapperSelector).remove();var o=l.prev(e.topScrollBarWrapperSelector);if(0==o.length){o=$(e.topScrollBarMarkup),l.before(o),o.css(e.scrollCss),l.css(e.contentCss),o.bind("scroll.doubleScroll",function(){l.scrollLeft(o.scrollLeft())});var r=function(){o.scrollLeft(l.scrollLeft())};l.bind("scroll.doubleScroll",r)}var t;t=l.find(void 0!==e.contentElement&&0!==l.find(e.contentElement).length?e.contentElement:">:first-child"),$(e.topScrollBarInnerSelector,o).width(t.outerWidth()) +1,o.width(l.width()),o.scrollLeft(l.scrollLeft())};return this.each(function(){var l=$(this);if(o(l,e),e.resetOnWindowResize){var r,t=function(){o(l,e)};$(window).bind("resize.doubleScroll",function(){clearTimeout(r),r=setTimeout(t,e.timeToWaitForResize)})}})};

// This function updates the ARIA attributes for the toggled mobile elements (main navigation and search)
// Documentation: https://www.fourfront.us/blog/jquery-window-width-and-media-queries
function checkSize(){
	// Checking for the state of the Main Menu toggle. If it's there, it means we are mobile so move AddThis.
    if ($("#mainNavToggler").css("display") == "block" ){
		$('.addthis_inline_share_toolbox').insertAfter("#mainNavToggler");
	// Main Menu toggle is not there, then we are in desktop mode.
	} else {
		$(".addthis_inline_share_toolbox").insertBefore($(".search form"));
	}
}

// 508 tabs with keyboard support
function InitializeTabInterface(){
	var $container = '.tab-interface';

	$($container +'  > ul').attr('role','tablist');
	$($container +' [role="tablist"] li').attr('role','presentation');
	$('[role="tablist"] a').attr({
		'role' : 'tab',
		'tabindex' : '-1'
	});

	// Make each aria-controls correspond id of targeted section (re href)
	$('[role="tablist"] a').each(function() {
		$(this).attr(
			'aria-controls', $(this).attr('href').substring(1)
		);
	});

	// Make the first tab selected by default and allow it focus
	$('[role="tablist"] li:first-child a').attr({
		'aria-selected' : 'true',
		'tabindex' : '0'
	});

	// Make each section focusable and give it the tabpanel role
	$($container +' > section').attr({
		'role' : 'tabpanel'
	});

	// Make first child of each panel focusable programmatically
	$($container +' section[role="tabpanel"] > *:first-child').attr({
		'tabindex' : '0'
	});

	// Make all but the first section hidden (ARIA state and display CSS)
	$('[role="tabpanel"]:not(:first-of-type):not(#requests-display-tab-content):not(#publications-display-tab-content)').attr({
		'aria-hidden' : 'true'
	});

	// Change focus between tabs with arrow keys
	$('[role="tab"]').on('keydown', function(e) {

	// define current, previous and next (possible) tabs
	var $original = $(this);
	var $prev = $(this).parents('li').prev().children('[role="tab"]');
	var $next = $(this).parents('li').next().children('[role="tab"]');
	var $target;

	// find the direction (prev or next)
	switch (e.keyCode) {
		case 37:
			$target = $prev;
			break;
		case 39:
			$target = $next;
			break;
		default:
			$target = false;
			break;
	}

	if ($target.length) {
		$original.attr({
			'tabindex' : '-1',
			'aria-selected' : null
		});
		$target.attr({
			'tabindex' : '0',
			'aria-selected' : true
		}).focus();
	}

	// Hide panels
	$($container +' [role="tabpanel"]').attr('aria-hidden', 'true');

	// Show panel which corresponds to target
	$('#' + $(document.activeElement).attr('href').substring(1)).attr('aria-hidden', null);
});
	
// Handle click on tab to show + focus tabpanel
$('[role="tab"]').on('click', function(e) {
	e.preventDefault();

	// remove focusability [sic] and aria-selected
	$('[role="tab"]').attr({'tabindex': '-1', 'aria-selected' : null });

	// replace above on clicked tab
	$(this).attr({'aria-selected' : true, 'tabindex' : '0' });

	// Hide panels
	$($container +' [role="tabpanel"]').attr('aria-hidden', 'true');

	// show corresponding panel
	$('#' + $(this).attr('href').substring(1)).attr('aria-hidden', null);});
}

$(document).ready(function() {
	// use a styling hook for users with js
	$("body").addClass("js");
	
	// Check the viewport size on page load
	checkSize();
	
	// Check the viewport size on window resize
	// ONLY check the WIDTH on window resize
	var lastWidth = $(window).width();
	$(window).resize(function(){
		if($(window).width()!=lastWidth){
			checkSize();
			currentWidth = $(window).width();
			collapseMenuDropdown(lastWidth, $(window).width());
			expandMenuDropdown(lastWidth, $(window).width());
			lastWidth = currentWidth;
		}
	});
	
	// Left Navigation Menu 
	// add toggle buttons before any sublists in the menu
	$('.leftNav li').children('ul').before('<button class="leftNav-toggle"><span class="visually-hidden">Toggle</span></button>');
	
	// collapse expandable menu sublists which are shown by default  
	$('.leftNav-toggle').attr('aria-expanded', 'false').next().hide();
	
	// show sublist of the active landing site menu item 
	$('.leftNav .active').next().attr('aria-expanded', 'true').next().show();
	
	// if the active page is within a sublist, expand its parent sublist 
	$('.leftNav .active').parents('ul').show().prev("button").attr('aria-expanded', 'true').parent("li").css("background", "#fff"); 
	
	// apply appropriate ARIA expanded attributes on toggle button 
	$('.leftNav-toggle').on( 'click', function(){
		if($(this).attr('aria-expanded') == "true") {
			$(this).attr('aria-expanded', 'false');
		}
		else {
			$(this).attr('aria-expanded', 'true');
		}
		$(this).next().slideToggle();
	});
	
	/* Scan the page and create all modal windows from any .modalItem elements that are found */
	/* create variable to count each modal on a page and append a number to any elements that need to be unique for each window */
	var modalCount = 0;
	
	/* for every .modalItem on the page... */
	$(".modalItem").each(function(){
		
		/* scrape the title for the modal */
		var modalTitle = $(this).find(".modalItem-title").html();
		
		/* scrape the body content of the modal */
		var modalBody = $(this).find(".modalItem-body").html();
		
		/* find the modal trigger and give the data-bs-target attribute a unique ID to target its corresponding modal window */
		$(this).find("[data-bs-toggle]").attr("data-bs-target", "#modal-"+modalCount);
		
		/* assemble the modal window with the content we scaped above, adding unique IDs where applicable, append it to the page */
		$("<div class='modal fade' tabindex='-1' id='modal-"+modalCount+"' aria-labelledby='modalTitle-"+modalCount+"'><div class='modal-dialog modal-lg modal-dialog-centered'><div class='modal-content'><div class='modal-header'><p class='modal-title' id='modalTitle-"+modalCount+"'><strong>"+modalTitle+"</strong></p><button type='button' class='btn-close' data-bs-dismiss='modal' aria-label='Close'></button></div><div class='modal-body'>"+modalBody+"</div></div></div></div>").appendTo(this);
		
		/* up the count */
		modalCount++;
	});
	
	// Stop embedded YouTube videos from continuing to play when modal is closed */
	$(".modal").on("hidden.bs.modal", function() {
		var player = $(this).find("#ytplayer");			// find the YouTube iFrame 
		var vid = player.attr("src");					// save the URL
		player.attr("src","");							// clear it
		player.attr("src",vid);							// add it back
	});
		// Stop embedded html5 videos from continuing to play when modal is closed */
	$(".modal").on("hidden.bs.modal", function() {
		var player1 = $(this).find(".html5-vid");			// find the html5 iFrame 
		$(player1).trigger("pause");
	});
	
	// initialize double scrollbar plugin
	$('.table-responsive').doubleScroll({resetOnWindowResize: true, contentElement: 'table'});
	
	// Expand/Collapse All for Fact Sheets
	$(".expandAll").click(function(){
		// if a button has aria-expanded false, fire toggle
		$(".tog-control button").each(function(){
			if ( $(this).attr("aria-expanded") === "false" ) {
				$(this).click();
			} 
		});
		return false;
	});
	$(".collapseAll").click(function(){
		// if a button has aria-expanded true, fire toggle
		$(".tog-control button").each(function(){
			if ( $(this).attr("aria-expanded") === "true" ) {
				$(this).click();
			} 
		});
		return false;
	});
	
	// Toggles. Parse the page, build toggles with ARIA.
	var togCount = 0;
	$(".tog-control").each(function(){
		var $this = $(this);
		var id = 'toggle-' + togCount;
		$this.next(".tog-content").attr({"id":id}).hide();
		togCount++;
		var panel = $this.next();
		$this.wrapInner('<button aria-expanded="false" aria-controls="'+ id +'">');
		var button = $this.children('button');
		button.on('click', function() {
			var state = $(this).attr('aria-expanded') === 'false' ? true : false;
			$(this).attr('aria-expanded', state);
			panel.slideToggle();
		});
	});
	// open a toggle on page load that has the default-open class using toggle rather than slideToggle
	$('.default-open').each(function(index) {
		$(this).children('button').first().attr('aria-expanded', true);
		$(this).next().toggle();
	});
	
	// Tabs
	InitializeTabInterface();
	
	// Scroll to Top Button //
	if (location.pathname.endsWith('/download')) {
		$('.returntop').attr('href', location.pathname + "#skipnav");
	}

	$(window).scroll(function () {
		if ($(this).scrollTop() >= 150) {
			$('.returntop').fadeIn(200).css('display','inline-block');
		} else {
			$('.returntop').fadeOut(200);
		}
	}); 
});
