PageSourceSearch

https://www.amc.edu/wp-content/themes/amc-child-core/js/scripts.js?ver=20260911-145955

js amc.edu collected 2026-09-24 17:17:31 UTC 117,167 bytes, 3,916 lines download raw bytes

1/* Child-Theme Scripts */
2
3/*---------------------------------------
4* Detect User Agent Script
5* http://cssuseragent.org
6*----------------------------------------
7* This is by far the best detection script I've found. 
8* Using javascript means that this will work with caching. W00t. 
9*
10* Adds user agent classes to the <html> element on your page including OS
11* and browser version.
12* 
13* This script has support for about every device imaginable so if you
14* want to create specific styles for a symbian browser, go to town. It
15* has gotten me out of a few sticky situations.
16*
17* Used in combination with Browserstack: https://browserstack.com/
18* will keep your clients happy.
19* 
20* If you don't need/want this, just remove it or comment it out.
21* 
22*/
23
24var cssua=function(n,l,p){var q=/\s*([\-\w ]+)[\s\/\:]([\d_]+\b(?:[\-\._\/]\w+)*)/,r=/([\w\-\.]+[\s\/][v]?[\d_]+\b(?:[\-\._\/]\w+)*)/g,s=/\b(?:(blackberry\w*|bb10)|(rim tablet os))(?:\/(\d+\.\d+(?:\.\w+)*))?/,t=/\bsilk-accelerated=true\b/,u=/\bfluidapp\b/,v=/(\bwindows\b|\bmacintosh\b|\blinux\b|\bunix\b)/,w=/(\bandroid\b|\bipad\b|\bipod\b|\bwindows phone\b|\bwpdesktop\b|\bxblwp7\b|\bzunewp7\b|\bwindows ce\b|\bblackberry\w*|\bbb10\b|\brim tablet os\b|\bmeego|\bwebos\b|\bpalm|\bsymbian|\bj2me\b|\bdocomo\b|\bpda\b|\bchtml\b|\bmidp\b|\bcldc\b|\w*?mobile\w*?|\w*?phone\w*?)/,
25x=/(\bxbox\b|\bplaystation\b|\bnintendo\s+\w+)/,k={parse:function(b,d){var a={};d&&(a.standalone=d);b=(""+b).toLowerCase();if(!b)return a;for(var c,e,g=b.split(/[()]/),f=0,k=g.length;f<k;f++)if(f%2){var m=g[f].split(";");c=0;for(e=m.length;c<e;c++)if(q.exec(m[c])){var h=RegExp.$1.split(" ").join("_"),l=RegExp.$2;if(!a[h]||parseFloat(a[h])<parseFloat(l))a[h]=l}}else if(m=g[f].match(r))for(c=0,e=m.length;c<e;c++)h=m[c].split(/[\/\s]+/),h.length&&"mozilla"!==h[0]&&(a[h[0].split(" ").join("_")]=h.slice(1).join("-"));
26w.exec(b)?(a.mobile=RegExp.$1,s.exec(b)&&(delete a[a.mobile],a.blackberry=a.version||RegExp.$3||RegExp.$2||RegExp.$1,RegExp.$1?a.mobile="blackberry":"0.0.1"===a.version&&(a.blackberry="7.1.0.0"))):x.exec(b)?(a.game=RegExp.$1,c=a.game.split(" ").join("_"),a.version&&!a[c]&&(a[c]=a.version)):v.exec(b)&&(a.desktop=RegExp.$1);a.intel_mac_os_x?(a.mac_os_x=a.intel_mac_os_x.split("_").join("."),delete a.intel_mac_os_x):a.cpu_iphone_os?(a.ios=a.cpu_iphone_os.split("_").join("."),delete a.cpu_iphone_os):a.cpu_os?
27(a.ios=a.cpu_os.split("_").join("."),delete a.cpu_os):"iphone"!==a.mobile||a.ios||(a.ios="1");a.opera&&a.version?(a.opera=a.version,delete a.blackberry):t.exec(b)?a.silk_accelerated=!0:u.exec(b)&&(a.fluidapp=a.version);a.edge&&(delete a.applewebkit,delete a.safari,delete a.chrome,delete a.android);if(a.applewebkit)a.webkit=a.applewebkit,delete a.applewebkit,a.opr&&(a.opera=a.opr,delete a.opr,delete a.chrome),a.safari&&(a.chrome||a.crios||a.fxios||a.opera||a.silk||a.fluidapp||a.phantomjs||a.mobile&&
28!a.ios?(delete a.safari,a.vivaldi&&delete a.chrome):a.safari=a.version&&!a.rim_tablet_os?a.version:{419:"2.0.4",417:"2.0.3",416:"2.0.2",412:"2.0",312:"1.3",125:"1.2",85:"1.0"}[parseInt(a.safari,10)]||a.safari);else if(a.msie||a.trident)if(a.opera||(a.ie=a.msie||a.rv),delete a.msie,delete a.android,a.windows_phone_os)a.windows_phone=a.windows_phone_os,delete a.windows_phone_os;else{if("wpdesktop"===a.mobile||"xblwp7"===a.mobile||"zunewp7"===a.mobile)a.mobile="windows desktop",a.windows_phone=9>+a.ie?
29"7.0":10>+a.ie?"7.5":"8.0",delete a.windows_nt}else if(a.gecko||a.firefox)a.gecko=a.rv;a.rv&&delete a.rv;a.version&&delete a.version;return a},format:function(b){var d="",a;for(a in b)if(a&&b.hasOwnProperty(a)){var c=a,e=b[a],c=c.split(".").join("-"),g=" ua-"+c;if("string"===typeof e){for(var e=e.split(" ").join("_").split(".").join("-"),f=e.indexOf("-");0<f;)g+=" ua-"+c+"-"+e.substring(0,f),f=e.indexOf("-",f+1);g+=" ua-"+c+"-"+e}d+=g}return d},encode:function(b){var d="",a;for(a in b)a&&b.hasOwnProperty(a)&&
30(d&&(d+="\x26"),d+=encodeURIComponent(a)+"\x3d"+encodeURIComponent(b[a]));return d}};k.userAgent=k.ua=k.parse(l,p);l=k.format(k.ua)+" js";n.className=n.className?n.className.replace(/\bno-js\b/g,"")+l:l.substr(1);return k}(document.documentElement,navigator.userAgent,navigator.standalone);
31
32
33/*!------------------------------------------------------
34* jQuery nearest v1.0.3
35* http://github.com/jjenzz/jQuery.nearest
36* ------------------------------------------------------
37* Copyright (c) 2012 J. Smith (@jjenzz)
38* Dual licensed under the MIT and GPL licenses:
39* http://www.opensource.org/licenses/mit-license.php
40* http://www.gnu.org/licenses/gpl.html
41*
42* Have you ever tried to find the nearest element down in
43* the DOM that wasn't a child? Then jQuery nearest is for you.
44* And it works traversing both up and down, finding...wait
45* for it...the nearest element. 
46* 
47* Like this: jQuery(this).nearest('.overlay');
48*/
49
50(function(a,b){a.fn.nearest=function(c){var d,g,f,e,h,i=b.querySelectorAll;function j(k){g=g?g.add(k):a(k)}this.each(function(){d=this;a.each(c.split(","),function(){e=a.trim(this);if(!e.indexOf("#")){j((i?b.querySelectorAll(e):a(e)))}else{h=d.parentNode;while(h){f=i?h.querySelectorAll(e):a(h).find(e);if(f.length){j(f);break}h=h.parentNode}}})});return g||a()}}(jQuery,document));
51
52
53
54/*
55* Get Viewport Dimensions
56* returns object with viewport dimensions to match css in width and height properties
57* ( source: http://andylangton.co.uk/blog/development/get-viewport-size-width-and-height-javascript )
58*/
59function updateViewportDimensions() {
60	var w=window,d=document,e=d.documentElement,g=d.getElementsByTagName('body')[0],x=w.innerWidth||e.clientWidth||g.clientWidth,y=w.innerHeight||e.clientHeight||g.clientHeight;
61	return { width:x,height:y };
62}
63// setting the viewport width
64var viewport = updateViewportDimensions();
65
66
67/*
68* Throttle Resize-triggered Events
69* Wrap your actions in this function to throttle the frequency of firing them off, for better performance, esp. on mobile.
70* ( source: http://stackoverflow.com/questions/2854407/javascript-jquery-window-resize-how-to-fire-after-the-resize-is-completed )
71*/
72var waitForFinalEvent = (function () {
73	var timers = {};
74	return function (callback, ms, uniqueId) {
75		if (!uniqueId) { uniqueId = "Don't call this twice without a uniqueId"; }
76		if (timers[uniqueId]) { clearTimeout (timers[uniqueId]); }
77		timers[uniqueId] = setTimeout(callback, ms);
78	};
79})();
80
81// how long to wait before deciding the resize has stopped, in ms. Around 50-100 should work ok.
82var timeToWaitForLast = 100;
83
84
85/*
86* Here's an example so you can see how we're using the above function
87*
88* This is commented out so it won't work, but you can copy it and
89* remove the comments.
90*
91*
92*
93* If we want to only do it on a certain page, we can setup checks so we do it
94* as efficient as possible.
95*
96* if( typeof is_home === "undefined" ) var is_home = $('body').hasClass('home');
97*
98* This once checks to see if you're on the home page based on the body class
99* We can then use that check to perform actions on the home page only
100*
101* When the window is resized, we perform this function
102* $(window).resize(function () {
103*
104*    // if we're on the home page, we wait the set amount (in function above) then fire the function
105*    if( is_home ) {
106*		waitForFinalEvent( function() {
107*
108*			// update the viewport, in case the window size has changed
109*			viewport = updateViewportDimensions();
110*
111*			// if we're above or equal to 768 fire this off
112*			if( viewport.width >= 768 ) {
113*				console.log('On home page and window sized to 768 width or more.');
114*			} else {
115*				// otherwise, let's do this instead
116*				console.log('Not on home page, or window sized to less than 768.');
117*			}
118*
119*		}, timeToWaitForLast, "your-function-identifier-string"); }
120*	});
121*
122* Pretty cool huh? You can create functions like this to conditionally load
123* content and other stuff dependent on the viewport.
124* Remember that mobile devices and javascript aren't the best of friends.
125* Keep it light and always make sure the larger viewports are doing the heavy lifting.
126*
127*/
128
129/*
130* We're going to swap out the gravatars.
131* In the functions.php file, you can see we're not loading the gravatar
132* images on mobile to save bandwidth. Once we hit an acceptable viewport
133* then we can swap out those images since they are located in a data attribute.
134*/
135function loadGravatars() {
136	// set the viewport using the function above
137	viewport = updateViewportDimensions();
138	// if the viewport is tablet or larger, we load in the gravatars
139	if (viewport.width >= 768) {
140		jQuery('.comment img[data-gravatar]').each(function(){
141			jQuery(this).attr('src',jQuery(this).attr('data-gravatar'));
142		});
143	}
144} // end function
145
146// menu navigation with arrow keys
147;(function($) {
148	$('.menu-item a').on('keydown', function(e) {
149		// left key
150		if (e.which === 37) {
151			e.preventDefault()
152			$(this)
153				.parent()
154				.prev()
155				.children('a')
156				.focus()
157		}
158		// right key
159		else if (e.which === 39) {
160			e.preventDefault()
161			$(this)
162				.parent()
163				.next()
164				.children('a')
165				.focus()
166		}
167		// down key
168		else if (e.which === 40) {
169			e.preventDefault()
170			if ($(this).next().length) {
171				$(this)
172					.next()
173					.find('li:first-child a')
174					.first()
175					.focus()
176			} else {
177				$(this)
178					.parent()
179					.next()
180					.children('a')
181					.focus()
182			}
183		}
184		// up key
185		else if (e.which === 38) {
186			e.preventDefault()
187			if (
188				$(this)
189					.parent()
190					.prev().length
191			) {
192				$(this)
193					.parent()
194					.prev()
195					.children('a')
196					.focus()
197			} else {
198				$(this)
199					.parents('ul')
200					.first()
201					.prev('a')
202					.focus()
203			}
204		}
205	})
206})(jQuery)
207
208// Aria Responsive Menu toggle
209;(function($) {
210	'use strict'
211	// menu toggle (adjust for your responsive menu)
212	$('.menu-toggle').on('click', function() {
213		$('.primary-menu nav ul').toggle()
214		var visible = $('.primary-menu nav ul').is(':visible')
215		if (visible) {
216			$(this)
217				.addClass('open')
218				.attr('aria-expanded', 'true')
219		} else {
220			$(this)
221				.removeClass('open')
222				.attr('aria-expanded', 'false')
223		}
224	})
225})(jQuery)
226
227// Skip Link script
228;(function() {
229	var is_webkit = navigator.userAgent.toLowerCase().indexOf('webkit') > -1,
230		is_opera = navigator.userAgent.toLowerCase().indexOf('opera') > -1,
231		is_ie = navigator.userAgent.toLowerCase().indexOf('msie') > -1
232
233	if (
234		(is_webkit || is_opera || is_ie) &&
235		document.getElementById &&
236		window.addEventListener
237	) {
238		window.addEventListener(
239			'hashchange',
240			function() {
241				var id = location.hash.substring(1),
242					element
243
244				if (!/^[A-z0-9_-]+$/.test(id)) {
245					return
246				}
247
248				element = document.getElementById(id)
249
250				if (element) {
251					if (
252						!/^(?:a|select|input|button|textarea)$/i.test(
253							element.tagName
254						)
255					) {
256						element.tabIndex = -1
257					}
258
259					element.focus()
260				}
261			},
262			false
263		)
264	}
265})()
266
267// Comment form script with ARIA labels and validation
268/**
269 * Handle submission of comment form. Checks field values before submitting.
270 */
271
272jQuery('document').ready(function($) {
273	var commentForm = $('#commentform')
274	/**
275	 * Add aria-live attribute so message errors appended to input fields will be read by assistive technology.
276	 */
277
278	commentForm.attr('aria-live', 'polite')
279	/**
280	 * Add a comment status region with role=status to provide feedback on errors or successes.
281	 * Set tabindex=-1 so that this container can receive focus.
282	 */
283	commentForm.prepend(
284		'<div id="comment-status" aria-live="assertive" role="status" tabindex="-1"></div>'
285	)
286	var statusdiv = $('#comment-status')
287	var list
288	$('a.comment-reply-link').click(function() {
289		list = $(this)
290			.parents('.comment')
291			.attr('id')
292	})
293
294	commentForm.submit(function() {
295		//serialize and store form data in a variable
296		var formdata = commentForm.serialize()
297
298		$('#commentform .plate-comment-error').remove()
299		$('#commentform .plate-field-error').remove()
300		var hasError = false
301		/**
302		 * Find all form fields with aria-required=true to test values before submitting.
303		 * If error generated, print error.
304		 */
305		$('#commentform [aria-required=true]').each(function() {
306			var id = $(this).attr('id') + '-error'
307			if ($.trim($(this).val()) == '') {
308				var labelText = $(this)
309					.prev('label')
310					.html()
311				// add aria-describedby with reference ID for error message.
312				$(this).attr('aria-describedby', id)
313				$(this)
314					.parent()
315					.append(
316						' <span class="plate-field-error" id="' +
317							id +
318							'">' +
319							labelText +
320							': ' +
321							plateComments.required +
322							'</span>'
323					)
324				hasError = true
325			}
326			if (
327				$(this).attr('name') == 'email' &&
328				$.trim($(this).val()) != ''
329			) {
330				var value = $(this).val()
331				var valid = plateValidateEmail(value)
332				if (!valid) {
333					$(this).attr('aria-describedby', id)
334					$(this)
335						.parent()
336						.append(
337							' <span class="plate-field-error"id="' +
338								id +
339								'">' +
340								plateComments.emailInvalid +
341								'</span>'
342						)
343					hasError = true
344				}
345			}
346		})
347
348		/**
349		 * If an error is generated, return without submitting the form & set focus to status div.
350		 */
351		if (hasError) {
352			statusdiv
353				.html(
354					'<p class="plate-comment-error">' +
355						plateComments.error +
356						'</p>'
357				)
358				.focus()
359			return false
360		}
361
362		/**
363		 * If no field errors, notify user that message is processing.
364		 */
365		statusdiv.html(
366			'<p class="yourtheme-comment-processing">' +
367				plateComments.processing +
368				'</p>'
369		)
370
371		//Extract action URL from commentform
372		var formurl = commentForm.attr('action')
373
374		//Post Form with data
375		$.ajax({
376			type: 'post',
377			url: formurl,
378			data: formdata,
379			dataType: 'json',
380			error: function(XMLHttpRequest, textStatus, errorThrown) {
381				// [localize]
382				statusdiv
383					.html(
384						'<p class="plate-comment-error">' +
385							plateComments.flood +
386							'</p>'
387					)
388					.focus()
389			},
390			success: function(data, textStatus) {
391				var success = data.success
392				var message = data.response
393				var status = data.status
394				if (success) {
395					/**
396					 * Because the successful comment message includes a link, set focus to the message to give easy access to user.
397					 */
398
399					statusdiv
400						.html(
401							'<p class="plate-comment-success" >' +
402								status +
403								'</p>'
404						)
405						.focus()
406					//alert(data);
407
408					if ($('#comments').has('ol.commentlist').length > 0) {
409						if (list != null) {
410							$('#' + list).prepend(message)
411						} else {
412							$('.commentlist').append(message)
413						}
414					} else {
415						$('#comments').append('<ol class="commentlist"></ol>')
416						$('ol.commentlist').html(message)
417					}
418					commentForm.find('textarea[name=comment]').val('')
419				} else {
420					/**
421					 * Set focus to error field so user can quickly tab forward into comment fields.
422					 */
423					statusdiv
424						.html(
425							'<p class="plate-comment-error" >' + status + '</p>'
426						)
427						.focus()
428					commentForm.find('textarea[name=comment]').val('')
429				}
430			}
431		})
432		return false
433	})
434
435	/**
436	 * Function to validate email format.
437	 *
438	 * @param value Email address to test
439	 *
440	 * @return boolean
441	 */
442	function plateValidateEmail(value) {
443		var filter = /^([\w-\+.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/
444		if (filter.test(value)) {
445			return true
446		} else {
447			return false
448		}
449	}
450})
451
452function megaMenuCurrentParentClass($){
453
454	// console.log('megaMenuCurrentParentClass($)');
455	var mpci = $('.menu-panel-item.current_page_item').parents('li').addClass('current_page_ancestor');
456	// console.log('mpci',mpci);
457
458}	// end megaMenuCurrentParentClass()
459
460function openMobileNavPanel($){
461
462	$('.mobile-nav-button').on('click', function(evt){
463		evt.preventDefault();
464		$('header.page-header').toggleClass('mb-nav-open');
465		$('body').toggleClass('modal-open');
466	});
467
468	// $('.search-button').on('click', function(evt){
469	// 	evt.preventDefault();
470	// 	viewport = updateViewportDimensions();
471	
472	// 	if( viewport.width < 1180 ){
473	// 		$('header.page-header').toggleClass('mb-nav-open');
474	// 		$('body').toggleClass('modal-open');
475	// 	}
476
477	// });
478
479	$('.has-menu-panel .chevron').on('click', function(){
480	
481		var thisPanel = $(this);
482		if( viewport.width < 1180 ){
483			var isPanelOpen = thisPanel.closest('li').hasClass('panel-open');
484
485			switch(true){
486
487				case( isPanelOpen ):
488					thisPanel.closest('li').removeClass('panel-open');
489					break;
490
491				case( !isPanelOpen ):
492					$('li.has-menu-panel').removeClass('panel-open');
493					thisPanel.closest('li').addClass('panel-open');
494					break;
495
496				default:
497					break;
498			}
499
500		}
501
502	});
503
504}	// end openMobileNavPanel()
505
506function showMobileCurrentPageAncestor($){
507
508	$('li.current_page_ancestor').each( function(){
509
510		if( viewport.width < 1180 ){
511			$(this).addClass('panel-open');
512		}
513
514	});
515
516}	// end showMobileCurrentPageAncestor()
517
518function duplicateFooterPhoneSocialsToMobileMenu($){
519
520	var footerPhoneSocials = $('footer.footer .logo-phone .phone').html();
521	$('header.header .other-buttons').after('<div class="phone"><div class="phone-wrap">'+footerPhoneSocials+'</div></div>');
522
523}	// end duplicateFooterPhoneSocialsToMobileMenu()
524
525function newsTeaserShowMorePosts($){
526
527	$('.show-more-button button').on('click', function(evt){
528		evt.preventDefault();
529
530		$(this).fadeOut(300);
531		$(this).parent().siblings('.news-teaser').find('.card:nth-child(n+3)').fadeIn(300);
532
533
534	});
535
536}	// end newsTeaserShowMorePosts()
537
538function closeAccordionTabs($){
539
540	$('.accordion .tab-label').on('click', function(){
541		var isChecked = $(this).siblings('input[type="checkbox"]').is(':checked');
542		if( !isChecked ){
543			// console.log('isNotChecked', isChecked);
544			$('.accordion input[type="checkbox"]').removeAttr('checked');
545		}
546
547		// get the ID from the parent div
548		var id = $(this).parents('.tab').attr('id');
549		console.log('id', id);
550		if( id === 'our_providers' ){
551			$('.tab-content.our-providers').html('');
552			// clone the contents of #hits in to the .tab-content.our-providers
553			$('.our-providers-wrapper').clone().appendTo('.tab-content.our-providers');
554		}
555
556		// waitForFinalEvent( function() {
557		// 	console.log('waitForFinalEvent - closeAccordionTabs()');
558		// 	// fire off some things that help with a11y
559		// 	accordionTabTopOffsets($);
560		// }, 1000, "some-function-identifier-string");
561
562	});
563
564}	// end closeAccordionTabs()
565
566function jumpToFromSidebarNav($){
567
568	$('a.jump-to-locations, ul.physician-jump-menu a, ul.location-jump-menu a').on('click', function(evt){
569		evt.preventDefault();
570
571		var href = $(this).attr('href');
572		console.log('href',href);
573
574		var target = $(href);
575		console.log('target',target);
576
577		switch(href){
578			
579			case '#our_providers':
580				$('.tab-content.our-providers').html('');
581				// clone the contents of #hits in to the .tab-content.our-providers
582				$('.our-providers-wrapper').clone().appendTo('.tab-content.our-providers');
583				break;
584
585			default:
586				// intentionally blank
587				break;
588
589		}
590
591		// how tall the open tab, and then subtract from the offset
592		var tabH = 0;
593		var openTab = $('.accordion input[name="rd"]:checked');
594		console.log('openTab', openTab);
595		if( typeof openTab !== 'undefined' && openTab.length > 0 ) tabH = openTab.siblings('.tab-content').outerHeight();
596		console.log('tabH', tabH);
597
598		if( target.length > 0 ){
599			console.log('target.offset()', target.offset());
600			$("html, body").animate({ scrollTop: parseInt( target.offset().top - 125 - tabH ) }, "slow");
601			target.find('label').trigger('click');
602		}
603
604	});
605
606}	// end jumpToFromSidebarNav()
607
608function fireSplideJS($){
609
610	var elms = document.getElementsByClassName( 'splide' );
611	for ( var i = 0; i < elms.length; i++ ) {
612		var isProgramsSlider = elms[ i ].closest('.programs-slider');
613		var isProgramPageSlider = elms[ i ].closest('.program-slider');
614		var isQuoteAltSlider = elms[ i ].closest('.quote-alt-slider');
615
616		var splide_args = {};
617		switch(true){
618
619			case( isProgramsSlider instanceof HTMLElement ):	// Slider on the EDUCATION template page
620				splide_args = {
621					perPage: 4,
622					perMove: 1,
623					padding: {
624						left: 0,
625						right: 100
626					},
627					pagination: false,
628					gap: 30,
629					breakpoints: {
630						1600: {
631							perPage: 3,
632						},
633						952: {
634							padding: { left: '2rem' }
635						},
636						860: {
637							perPage: 2,
638						},
639						540: {
640							perPage: 1,
641						},
642					}
643				};
644				break;
645
646			case( isProgramPageSlider instanceof HTMLElement ):	// Slider on the PROGRAM template page
647				splide_args = {
648					perPage: 4,
649					perMove: 1,
650					padding: {
651						left: 0,
652						right: 100
653					},
654					pagination: false,
655					gap: 30,
656					breakpoints: {
657						1600: {
658							perPage: 3,
659						},
660						952: {
661							padding: { left: '2rem' }
662						},
663						860: {
664							perPage: 2,
665						},
666						540: {
667							perPage: 1,
668							padding: { right: 60 }
669						},
670					}
671				};
672				break;
673
674			case( isQuoteAltSlider instanceof HTMLElement ):	// Slider in the QUOTE ALT module
675				splide_args = {
676					type: 'loop',
677					pagination: false,
678					autoHeight: true,
679				}
680				break;
681
682			default:
683				splide_args = splide_args;
684				break;
685
686		}	// end switch()
687
688		if( splide_args ) new Splide( elms[ i ], splide_args ).mount();
689
690	}
691
692}	// end fireSplideJS()
693
694function fireVenobox2(){
695
696	new VenoBox({
697		selector: '.venobox',
698		titleattr: 'data-title',
699		infinigall: true,
700		numeration: true,
701		spinner: 'swing'
702		// is called after gallery navigation step
703		// onNavComplete: function(obj, gallIndex, thenext, theprev){
704		// 	console.log('POST NAV');
705		// 	console.log('current gallery index: ' + gallIndex);
706		// 	console.log(thenext);
707		// 	console.log(theprev);
708		// },
709		// is called after new content loaded
710		// onCon
711	});
712
713}	// end fireVenobox2()
714
715function backToTop($){
716
717	$('.back-to-top a').on('click', function(evt){
718		evt.preventDefault();
719		$("html, body").animate({ scrollTop: 0 }, "slow");
720	});
721
722}   // end backToTop()
723
724function heroAccordion($, viewport){
725
726	// console.log('heroAccordion()');
727
728	// Source: http://www.designchemical.com/blog/index.php/jquery/jquery-simple-horizontal-accordion/
729	// but heavily modified
730	var hasHorizontalAccordion = $("#accordion");
731	if( hasHorizontalAccordion.length && parseInt(hasHorizontalAccordion.length) > 0 ){
732
733		// console.log('hasHorizontalAccordion',hasHorizontalAccordion);
734
735		var panelCount = parseInt( $("#accordion").attr('data-panel-count') );
736		// console.log('panelCount',panelCount);
737
738		// if( viewport.width >= 768 ){
739
740			// 	var firstPanelWidth		= '66.66%';
741			// 	var otherPanelsWidth	= '33.33%';
742
743			// 	switch(true){
744
745			// 		case( panelCount == 3 ):
746			// 			firstPanelWidth		= '50%';
747			// 			otherPanelsWidth	= '25%';
748			// 			break;
749
750			// 		default:
751			// 			// intentionally blank using previously set values
752			// 			break;
753
754			// 	}	// endswitch
755			// 	console.log('firstPanelWidth',firstPanelWidth);
756			// 	console.log('otherPanelsWidth',otherPanelsWidth);
757
758		// }else{
759			
760			// 	var firstPanelWidth		= '100%';
761			// 	var otherPanelsWidth	= '100%';
762
763		// }
764
765		var activeItem = $("#accordion li.active");
766		$("#accordion").on('click focus', 'li', function(){
767			$(activeItem).removeClass('active');
768			$("#accordion li.active").removeClass('active');
769			$(this).addClass('active');
770			activeItem = this;
771		});
772
773		// $("#accordion").on('click', 'a', function(evt){
774		// 	// evt.preventDefault();
775		// 	evt.stopPropagation();
776
777		// 	// animate the opacity of #accordion to 0
778		// 	$("body").animate({
779		// 		opacity: 0
780		// 	}, 500, function(){
781
782		// 		// setTimeout(function(){
783		// 			$("#accordion li.active").removeClass('active');
784		// 			$("#accordion li:first-of-type").addClass('active');
785		// 		// }, 500);
786
787		// 	});
788
789		// 	// setTimeout(function(){
790		// 	// 	$("#accordion li.active").removeClass('active');
791		// 	// 	$("#accordion li:first-of-type").addClass('active');
792		// 	// }, 500);
793
794		// 	// window.location.href = $(this).attr('href');
795		// });
796
797
798	}
799
800}	// end heroAccordion()
801
802function fireToolTip($){
803
804	var hasTooltop = $('.amc-tooltip svg');
805	if( hasTooltop.length > 0 ){
806
807		$('.amc-tooltip svg').each(function(){
808
809			var $tt_svg = $( this );
810			var boundingClientRect = $tt_svg.offset();
811
812			$tt_svg.tooltipster({
813				theme: ['tooltipster-light', 'tooltipster-amc'],
814				maxWidth: 300,
815				side: 'bottom',
816				trigger: 'click',
817				repositionOnScroll: true,
818				contentCloning: true,
819				functionPosition: function(instance, helper, position){
820					position.coord.top += -5;
821					position.coord.left = parseInt( boundingClientRect.left - 9 );
822					return position;
823				}
824			});
825
826			$tt_svg.siblings('.text').on('click', function(){
827				var $tt_text = $( this );
828				$tt_text.siblings('svg').trigger('click');
829			});
830
831			// $( this ).on('keyup', function(){
832			// 	alert('go');
833			// });
834
835		});
836
837	}
838
839}	// end fireToolTip()
840
841function conditionsAToZShowHideItems($){
842
843	$('.a-to-z-bar li a').on('click', function(evt){
844		evt.preventDefault();
845
846		$('.a-to-z-bar li').removeClass('active');
847		$(this).parent().addClass('active');
848		var selected_letter = $(this).attr('href').replace('#', '');
849
850		$('.conditions-terms div').css({ 'opacity': 0, 'height': 0 });
851		$('.conditions-terms div[data-letter='+selected_letter+']').css({ 'opacity': 1, 'height': 'auto' });
852
853	});
854
855}	// end conditionsAToZShowHideItems()
856
857function SearchItem({ html, hit, components }) {
858	// console.log('SearchItem', hit);
859	return html `${hit.name}`;
860}
861
862function SearchItemLocation({ html, hit, components }) {
863	// console.log('Location', hit);
864	return html `<a href="${hit.permalink}" class="result result-location">
865		<span class="location">${hit.location_name}</span>
866	</div>`;
867}	// end SearchItemLocation()
868
869function SearchItemPhysician({ html, hit, components }) {
870	// console.log('Physician', hit);
871
872	// var facultity_indicator_div = AMC_THEMES_URL + "/amc-child-core/images/faculty_indicator.svg" ;
873	// var facultity_indicator_div = hit.faculty_indicator ? `<div class="faculty-indicator"><img src="${AMC_THEMES_URL}/amc-child-core/images/faculty_indicator.svg" width="35" height="35" alt="Member of AMC Faculty" /></div>` : '';
874
875	// console.log('has_facultity_indicator', hit.faculty_indicator.length, hit.faculty_indicator);
876
877	//console.log('AMC_THEMES_URL',AMC_THEMES_URL);
878
879	if( hit.faculty_indicator.length > 0 ){
880
881		return html `<a href="${hit.permalink}" class="result result-physician">
882			<img src="${hit.photo.src}" width="${hit.photo.width}" height="${hit.photo.height}" alt="${hit.display_name_with_post_nominals} bio image" />
883			<span>
884				<h3>${hit.display_name_with_post_nominals}</h3>
885				<div>
886					<span class="department">${hit.department_1}</span>
887					<div class="faculty-indicator"><img src="${AMC_THEMES_URL}/amc-child-core/images/faculty_indicator.svg" width="18" height="18" alt="Member of AMC Faculty" /></div>
888				</div>
889			</span>
890		</a>`;
891
892	}else{
893
894		return html `<a href="${hit.permalink}" class="result result-physician">
895			<img src="${hit.photo.src}" width="${hit.photo.width}" height="${hit.photo.height}" alt="${hit.display_name_with_post_nominals} bio image" />
896			<span>
897				<h3>${hit.display_name_with_post_nominals}</h3>
898				<div>
899					<span class="department">${hit.department_1}</span>
900				</div>
901			</span>
902		</a>`;
903
904	}
905
906}	// end SearchItemPhysician()
907
908function SearchItemSpecialty({ html, hit, components }) {
909	// console.log('Specialty', hit);
910	return html `<a href="${hit.permalink}" class="result result-specialty">
911		<span class="specialty test">${hit.name}</span>
912	</div>`;
913	// var html =  '<a href="${hit.permalink}" class="result result-specialty">';
914	// html += '<span class="specialty test">${hit._highlight.name.value}</span>';
915	// html += '</div>';
916	// return html;
917}	// end SearchItemSpecialty()
918
919function SearchItemNews({ html, hit, components }) {
920	// console.log('News', hit);
921
922	// output the date on the card in Month D, Year format - this is in MS in JavaScript to x1000 for the PHP generated timestamp that comes from Algolia data
923	var date = new Date(hit.timestamp * 1000);
924	var daynum = date.getDate();
925	var month = date.getMonth();
926	var monthText = intToMonth(month);
927	var year = date.getFullYear();
928	var date_for_card = monthText+' '+daynum+', '+year;
929	var hour = date.getHours();
930	var mins = date.getMinutes();
931	var date_for_card_attribute = year+'-'+((month+1) < 10 ? '0'+(month+1) : (month+1))+'-'+daynum+' '+(hour < 10 ? '0'+hour : hour)+':'+(mins < 10 ? '0'+mins : mins);
932
933	return html `<a href="${hit.permalink}" class="result result-news">
934		<time datetime="${date_for_card_attribute}">${date_for_card}</time><br/>
935		<span class="news">${hit.name}</span>
936	</div>`;
937}	// end SearchItemNews()
938
939function SearchItemNewsRemote({ html, hit, components }) {
940	// console.log('In the News', hit);
941
942	// output the date on the card in Month D, Year format - this is in MS in JavaScript to x1000 for the PHP generated timestamp that comes from Algolia data
943	var date = new Date(hit.timestamp * 1000);
944	var daynum = date.getDate();
945	var month = date.getMonth();
946	var monthText = intToMonth(month);
947	var year = date.getFullYear();
948	var date_for_card = monthText+' '+daynum+', '+year;
949	var hour = date.getHours();
950	var mins = date.getMinutes();
951	var date_for_card_attribute = year+'-'+((month+1) < 10 ? '0'+(month+1) : (month+1))+'-'+daynum+' '+(hour < 10 ? '0'+hour : hour)+':'+(mins < 10 ? '0'+mins : mins);
952
953	return html `<a href="${hit.permalink}" target="_blank" rel="noopener" class="result result-news">
954		<time datetime="${date_for_card_attribute}">${date_for_card}</time><br/>
955		<span class="news">${hit.name}</span>
956	</div>`;
957}	// end SearchItemNewsRemote()
958
959function amcAlgoliaAutocomplete($){
960
961	// allow the aa-Panel to remain open on local -- helpful with debugging and development work
962	const isLocal = $('body').hasClass('local');
963	// console.log('isLocal', isLocal);
964
965	const isDebug = $('body').hasClass('has-debug-search');
966	// console.log('isDebug', isDebug);
967
968	const hasAutoCompleteSearch = $('#autocomplete');
969	// console.log('hasAutoCompleteSearch', hasAutoCompleteSearch);
970	
971	if( hasAutoCompleteSearch.length && hasAutoCompleteSearch.length > 0 ){
972
973		const type = hasAutoCompleteSearch.attr('data-type');
974		// console.log('type', type);
975
976		var algolia_core = {
977			"application_id": SEARCH_APP,
978			"search_api_key": SEARCH_KEY,
979			"debug": ( isDebug ? true : false ),
980			"container": '#autocomplete',
981			"openOnFocus": ( isLocal ? true : false )
982		};
983
984		// conditional statement for things like input placeholder and used indices
985		switch(true){
986
987			case( type == 'specialties' ):
988				var algolia_more = {
989					"placeholder": 'Browse Care & Treatment...',
990					"indexNames": [ 'amc_specialties' ]
991				};
992				break;
993
994			case( type == 'all-news' ):
995				var algolia_more = {
996					"placeholder": 'Search News Articles...',
997					"indexNames": [ 'amc_posts_news' ],
998				};
999				break;
1000
1001			case( type == 'in-the-news' ):
1002				var algolia_more = {
1003					"placeholder": 'Search Media Mentions...',
1004					"indexNames": [ 'amc_posts_in_the_news' ],
1005				};
1006				break;
1007
1008			default:	// home page search
1009				var algolia_more = {
1010					"placeholder": 'Browse providers, locations and services...',
1011					"indexNames": [ 'amc_physicians', 'amc_locations', 'amc_specialties' ],
1012				};
1013				break;
1014
1015		}
1016		var algolia = Object.assign(algolia_core, algolia_more);
1017		console.log('algolia', algolia);
1018
1019		/* Initialize Algolia client */
1020		const searchClient = algoliasearch(
1021				algolia.application_id,
1022				algolia.search_api_key
1023			);
1024		var app_id = algolia.application_id;
1025		var api_key = algolia.search_api_key;
1026
1027		const { createAlgoliaInsightsPlugin } = window[ '@algolia/autocomplete-plugin-algolia-insights' ];
1028		// insightsClient('init', { app_id, api_key });
1029		var insightsClient = window.aa;
1030		insightsClient('setUserToken', UNIQUE_ID);
1031		const algoliaInsightsPlugin = createAlgoliaInsightsPlugin({ insightsClient,
1032			onItemsChange({ insights, insightsEvents }) {
1033				const events = insightsEvents.map((insightsEvent) => ({
1034					...insightsEvent,
1035					eventName: 'Result Viewed from Autocomplete',
1036				}));
1037				insights.viewedObjectIDs(...events);
1038			},
1039			onSelect({ insights, insightsEvents }) {
1040				const events = insightsEvents.map((insightsEvent) => ({
1041					...insightsEvent,
1042					eventName: 'Result Selected from Autocomplete',
1043				}));
1044				insights.clickedObjectIDsAfterSearch(...events);
1045			},
1046		});
1047
1048		const { autocomplete, getAlgoliaResults } = window['@algolia/autocomplete-js'];
1049
1050		function debouncePromise(fn, time) {
1051			let timerId = undefined;
1052		
1053			return function debounced(...args) {
1054				if (timerId) {
1055					clearTimeout(timerId);
1056				}
1057			
1058				return new Promise((resolve) => {
1059					timerId = setTimeout(() => resolve(fn(...args)), time);
1060				});
1061			};
1062		}
1063
1064		const timeout = 250;	// this is the pause time for the debounce
1065
1066		const debounced = debouncePromise((items) => Promise.resolve(items), timeout);
1067
1068		switch(true){
1069
1070			case( type == 'specialties' ):
1071				// console.log("HERE");
1072				let aa_spec_query = new URL(window.location).searchParams.get("search");
1073				const { refresh }  = autocomplete({
1074					debug: algolia.debug,
1075					container: algolia.container,
1076					initialState: {
1077						query: ( aa_spec_query && aa_spec_query.length > 0 ? aa_spec_query : '' ),
1078						isOpen: ( aa_spec_query && aa_spec_query.length > 0 ? true : false )
1079					},
1080					placeholder: algolia.placeholder,
1081					openOnFocus: algolia.openOnFocus,
1082					plugins: [algoliaInsightsPlugin],
1083
1084					render({ elements, render, html }, root) {
1085						const { results } = elements;
1086
1087						render(
1088							html `<div className="aa-PanelLayout">
1089							<div className="aa-PanelSections">
1090								<div className="aa-PanelSection aa-PanelSection--left panel-specialties">
1091									<h2>Specialties</h2>
1092									<div class="aa-Results aa-Panel--scrollable">${results}</div>
1093									<a href="/search/#tab-specialties" class="amc-button">View More Specialties</a>
1094								</div>
1095							</div>
1096						</div>
1097						<div class="aa-SourceFooter"><a href="/search/">Full Site Search <svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path fill="currentColor" d="M11 5C9.031 5 7.46 6.441 7.125 8.313c-1.89.476-3.531 1.707-4.25 3.656h-.031L.719 17.938A6.955 6.955 0 0 0 0 21c0 3.855 3.145 7 7 7c3.473 0 6.367-2.55 6.906-5.875A2.983 2.983 0 0 0 16 23c.813 0 1.55-.34 2.094-.875C18.633 25.449 21.527 28 25 28c3.855 0 7-3.145 7-7c0-.973-.2-1.906-.563-2.75l-2.28-6.375l-.032-.031v-.031c-.73-1.774-2.348-3.012-4.25-3.5C24.539 6.44 22.969 5 21 5c-1.855 0-3.363 1.285-3.813 3h-2.375C14.364 6.285 12.855 5 11 5zm0 2c1.191 0 2 .809 2 2v1h6V9c0-1.191.809-2 2-2c1.191 0 2 .809 2 2v.906l.906.094c1.485.156 2.766 1.191 3.344 2.531c.008.02.023.043.031.063l.75 2.125A6.94 6.94 0 0 0 25 14c-2.926 0-5.426 1.816-6.469 4.375A3.013 3.013 0 0 0 16 17c-1.05 0-1.996.543-2.531 1.375C12.426 15.816 9.926 14 7 14c-1.07 0-2.09.254-3 .688l.75-2.032v-.031C5.332 11.078 6.559 10.16 8.094 10L9 9.906V9c0-1.191.809-2 2-2zm-4 9c2.773 0 5 2.227 5 5s-2.227 5-5 5s-5-2.227-5-5c0-.707.176-1.36.438-1.969c.015-.039.015-.086.03-.125A4.977 4.977 0 0 1 7 16zm18 0c2.773 0 5 2.227 5 5s-2.227 5-5 5s-5-2.227-5-5s2.227-5 5-5zm-9 3c.563 0 1 .438 1 1c0 .563-.438 1-1 1c-.563 0-1-.438-1-1c0-.563.438-1 1-1z"></path></svg></a></div>`,
1098							root
1099						);
1100
1101					},
1102
1103					getSources({ query }) {
1104						return debounced([{
1105							sourceId: 'results',
1106							getItemInputValue: ({ item }) => item.query,
1107							getItems() {
1108								return getAlgoliaResults({
1109									searchClient,
1110									queries: [{
1111										indexName: algolia.indexNames[0],
1112										query,
1113										params: {
1114											hitsPerPage: 10,
1115										},
1116									}],
1117								});
1118							},
1119							getItemUrl({ item }) {
1120								// console.log('item', item);
1121								return item.permalink;
1122							},
1123							templates: {
1124								item({ html, item, components }) {
1125									return SearchItemSpecialty({ html, hit: item, components });
1126								},
1127								noResults() {
1128									return 'No results...';
1129								},
1130							}
1131						}])
1132					}
1133				
1134				});
1135				refresh();
1136				break;
1137
1138			case( type == 'all-news' ):
1139				let aa_allnews_query = new URL(window.location).searchParams.get("search");
1140				autocomplete({
1141					debug: algolia.debug,
1142					container: algolia.container,
1143					initialState: {
1144						query: ( aa_allnews_query && aa_allnews_query.length > 0 ? aa_allnews_query : '' ),
1145						isOpen: ( aa_allnews_query && aa_allnews_query.length > 0 ? true : false )
1146					},
1147					placeholder: algolia.placeholder,
1148					openOnFocus: algolia.openOnFocus,
1149					plugins: [algoliaInsightsPlugin],
1150
1151					render({ elements, render, html }, root) {
1152						const { news_results } = elements;
1153
1154						render(
1155							html `<div className="aa-PanelLayout">
1156								<div className="aa-PanelSections">
1157									<div className="aa-PanelSection aa-PanelSection--left panel-news">
1158										<h2>News Articles</h2>
1159										<div class="aa-Results aa-Panel--scrollable">${news_results}</div>
1160									</div>
1161								</div>
1162							</div>
1163							<div class="aa-SourceFooter"><a href="/search/#news" onclick="return false">View All News Results <svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32">
1163<path fill="currentColor" d="M11 5C9.031 5 7.46 6.441 7.125 8.313c-1.89.476-3.531 1.707-4.25 3.656h-.031L.719 17.938A6.955 6.955 0 0 0 0 21c0 3.855 3.145 7 7 7c3.473 0 6.367-2.55 6.906-5.875A2.983 2.983 0 0 0 16 23c.813 0 1.55-.34 2.094-.875C18.633 25.449 21.527 28 25 28c3.855 0 7-3.145 7-7c0-.973-.2-1.906-.563-2.75l-2.28-6.375l-.032-.031v-.031c-.73-1.774-2.348-3.012-4.25-3.5C24.539 6.44 22.969 5 21 5c-1.855 0-3.363 1.285-3.813 3h-2.375C14.364 6.285 12.855 5 11 5zm0 2c1.191 0 2 .809 2 2v1h6V9c0-1.191.809-2 2-2c1.191 0 2 .809 2 2v.906l.906.094c1.485.156 2.766 1.191 3.344 2.531c.008.02.023.043.031.063l.75 2.125A6.94 6.94 0 0 0 25 14c-2.926 0-5.426 1.816-6.469 4.375A3.013 3.013 0 0 0 16 17c-1.05 0-1.996.543-2.531 1.375C12.426 15.816 9.926 14 7 14c-1.07 0-2.09.254-3 .688l.75-2.032v-.031C5.332 11.078 6.559 10.16 8.094 10L9 9.906V9c0-1.191.809-2 2-2zm-4 9c2.773 0 5 2.227 5 5s-2.227 5-5 5s-5-2.227-5-5c0-.707.176-1.36.438-1.969c.015-.039.015-.086.03-.125A4.977 4.977 0 0 1 7 16zm18 0c2.773 0 5 2.227 5 5s-2.227 5-5 5s-5-2.227-5-5s2.227-5 5-5zm-9 3c.563 0 1 .438 1 1c0 .563-.438 1-1 1c-.563 0-1-.438-1-1c0-.563.438-1 1-1z"></path></svg></a></div>`,
1164							root
1165						);
1166
1167					},
1168
1169					getSources({ query }) {
1170						return debounced([{
1171							sourceId: 'news_results',
1172							getItemInputValue: ({ item }) => item.query,
1173							getItems() {
1174								return getAlgoliaResults({
1175									searchClient,
1176									queries: [{
1177										indexName: algolia.indexNames[0],
1178										query,
1179										params: {
1180											hitsPerPage: 10,
1181										},
1182									}],
1183								});
1184							},
1185							getItemUrl({ item }) {
1186								// console.log('item', item);
1187								return item.permalink;
1188							},
1189							templates: {
1190								item({ html, item, components }) {
1191									return SearchItemNews({ html, hit: item, components });
1192								},
1193								noResults() {
1194									return 'No results...';
1195								},
1196							}
1197						}])
1198					}
1199				
1200				});
1201				break;
1202
1203			case( type == 'in-the-news' ):
1204				autocomplete({
1205					debug: algolia.debug,
1206					container: algolia.container,
1207					placeholder: algolia.placeholder,
1208					openOnFocus: algolia.openOnFocus,
1209					plugins: [algoliaInsightsPlugin],
1210
1211					render({ elements, render, html }, root) {
1212						const { news_results } = elements;
1213
1214						render(
1215							html `<div className="aa-PanelLayout">
1216							<div className="aa-PanelSections">
1217								<div className="aa-PanelSection aa-PanelSection--left panel-news">
1218									<h2>News Articles</h2>
1219									<div class="aa-Results aa-Panel--scrollable">${news_results}</div>
1220								</div>
1221							</div>
1222						</div>`,
1223							root
1224						);
1225
1226					},
1227
1228					getSources({ query }) {
1229						return debounced([{
1230							sourceId: 'news_results',
1231							getItemInputValue: ({ item }) => item.query,
1232							getItems() {
1233								return getAlgoliaResults({
1234									searchClient,
1235									queries: [{
1236										indexName: algolia.indexNames[0],
1237										query,
1238										params: {
1239											hitsPerPage: 10,
1240										},
1241									}],
1242								});
1243							},
1244							getItemUrl({ item }) {
1245								// console.log('item', item);
1246								return item.permalink;
1247							},
1248							templates: {
1249								item({ html, item, components }) {
1250									return SearchItemNewsRemote({ html, hit: item, components });
1251								},
1252								noResults() {
1253									return 'No results...';
1254								},
1255							}
1256						}])
1257					}
1258				
1259				});
1260				break;
1261
1262			default:
1263				autocomplete({
1264					debug: algolia.debug,
1265					container: algolia.container,
1266					placeholder: algolia.placeholder,
1267					openOnFocus: algolia.openOnFocus,
1268					plugins: [algoliaInsightsPlugin],
1269		
1270					render({ elements, render, html }, root) {
1271						const { results, results2, results3 } = elements;
1272
1273						render(
1274							html `<div className="aa-PanelLayout">
1275								<div className="aa-PanelSections">
1276									<div className="aa-PanelSection aa-PanelSection--left panel-physicians">
1277										<h2>Providers</h2>
1278										<div class="aa-Results aa-Panel--scrollable">${results}</div>
1279										<a href="/find-a-doctor/" class="more-link">View More Providers</a>
1280									</div>
1281									<div className="aa-PanelSection aa-PanelSection--center panel-locations">
1282										<h2>Locations</h2>
1283										<div class="aa-Results aa-Panel--scrollable">${results2}</div>
1284										<a href="/locations/" class="more-link">View More Locations</a>
1285									</div>
1286									<div className="aa-PanelSection aa-PanelSection--right panel-specialties">
1287										<h2>Specialties</h2>
1288										<div class="aa-Results aa-Panel--scrollable">${results3}</div>
1289										<a href="/care-treatment/" class="more-link">View More Specialties</a>
1290									</div>
1291								</div>
1292							</div>
1293							<div class="aa-SourceFooter">
1294								<span class="wrapper">
1295									Not seeing what you're looking for?<br/>
1296									<a href="/search/" class="amc-button">
1297										<svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" role="img" width="1.5em" height="1.5em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32">
1297<path fill="currentColor" d="M19 3C13.488 3 9 7.488 9 13c0 2.395.84 4.59 2.25 6.313L3.281 27.28l1.439 1.44l7.968-7.969A9.922 9.922 0 0 0 19 23c5.512 0 10-4.488 10-10S24.512 3 19 3zm0 2c4.43 0 8 3.57 8 8s-3.57 8-8 8s-8-3.57-8-8s3.57-8 8-8z"></path></svg>
1298										Try a full Site Search 
1299									</a>
1300								</span>
1301							</div>`,
1302							root
1303						);
1304					},
1305		
1306					getSources({ query }) {
1307						return debounced([{
1308							sourceId: 'results',
1309							getItemInputValue: ({ item }) => item.query,
1310							getItems() {
1311								return getAlgoliaResults({
1312									searchClient,
1313									queries: [{
1314										indexName: algolia.indexNames[0],
1315										query,
1316										params: {
1317											hitsPerPage: 3,
1318										},
1319									}],
1320								});
1321							},
1322							getItemUrl({ item }) {
1323								// console.log('item', item);
1324								return item.permalink;
1325							},
1326							templates: {
1327								item({ html, item, components }) {
1328									return SearchItemPhysician({ html, hit: item, components });
1329								},
1330								noResults() {
1331									return 'No results...';
1332								},
1333							}
1334						},
1335						{
1336							sourceId: 'results2',
1337							getItemInputValue: ({ item }) => item.query,
1338							getItems({ query }) {
1339								return getAlgoliaResults({
1340									searchClient,
1341									queries: [{
1342										indexName: algolia.indexNames[1],
1343										query,
1344										params: {
1345											hitsPerPage: 6,
1346										},
1347									}],
1348								});
1349							},
1350							getItemUrl({ item }) {
1351								// console.log('item', item);
1352								return item.permalink;
1353							},
1354							templates: {
1355								item({ html, item, components }) {
1356									return SearchItemLocation({ html, hit: item, components });
1357								},
1358								noResults() {
1359									return 'No results...';
1360								},
1361							}
1362						},
1363						{
1364							sourceId: 'results3',
1365							getItemInputValue: ({ item }) => item.query,
1366							getItems({ query }) {
1367								return getAlgoliaResults({
1368									searchClient,
1369									queries: [{
1370										indexName: algolia.indexNames[2],
1371										query,
1372										params: {
1373											hitsPerPage: 6,
1374										},
1375									}],
1376								});
1377							},
1378							getItemUrl({ item }) {
1379								// console.log('item', item);
1380								return item.permalink;
1381							},
1382							templates: {
1383								item({ html, item, components }) {
1384									return SearchItemSpecialty({ html, hit: item, components });
1385								},
1386								noResults() {
1387									return 'No results...';
1388								},
1389							}
1390						}]);
1391					},
1392
1393					// onStateChange({ state, prevState }) {
1394					// 	if(state.isOpen && !prevState.isOpen){
1395					// 		$('html, body').animate({
1396					// 			scrollTop: $(".search-bar").offset().top - 100
1397					// 		}, 100);
1398					// 	}
1399					// },
1400				});
1401				// if the user clicks into an input field in the .aa-Form scroll the page to the top of the element .search-bar
1402				$(document).on('focus', '.aa-Form input', function(){
1403					$('html, body').animate({
1404						scrollTop: $(".search-bar").offset().top - 100
1405					}, 100);
1406				});
1407				break;
1408
1409		}
1410
1411	}else{
1412		console.log('Page does not have AutoComplete.js');
1413		return false;
1414	}
1415
1416}	// end amcAlgoliaAutocomplete()
1417
1418function instantSearchItemPhysician(hit){
1419	// console.log('physician',hit);
1420
1421	// fall back if the "photo" is empty coming from Algolia
1422	item = amc_check_for_profile_image(hit);
1423
1424	var facultity_indicator_url = AMC_THEMES_URL + "/amc-child-core/images/faculty_indicator.svg" ;
1425
1426	var data_attributes = 'data-insights-object-id="'+hit.objectID+'"'
1427		+' data-insights-position="'+hit.__position+'"'
1428		+' data-insights-query-id="'+hit.__queryID+'"';
1429
1430	var html = '<a href="'+hit.permalink+'" class="ais-Hits-item card card-physicians" '+data_attributes+'>';
1431	html += '	<div class="image" style="background-image: url('+hit.photo.src+');">&nbsp;</div>';
1432	html += '	<div class="details">';
1433	html += '		<h2 class="name">'+hit.display_name_with_post_nominals+'</h2>';
1434	html += '		<div class="departments">';
1435	html += '			<span>Department of</span>';
1436	html += '			'+hit.department_1;
1437	html += '		</div>';
1438	html += '		<div class="specialties">'+hit.specialties_first_2+'</div>';
1439	if( hit.faculty_indicator ) html += '		<div class="faculty-indicator"><img src="'+facultity_indicator_url+'" width="35" height="35" alt="Member of AMC Faculty" /></div>';
1440	if( hit.primary_care ) html += '		<div class="primary-care">Primary Care</div>';
1441	html += '	</div>';
1442	html += '	<div class="contact">';
1443	html += '		<span>View Profile</span>';
1444	html += '	</div>';
1445	html += '</a>';
1446	html = html.replace('&amp;', '&');
1447
1448	return html;
1449
1450}	// end instantSearchItemPhysician()
1451
1452function instantSearchItemResearcher(hit){
1453	// console.log('researcher',hit);
1454
1455	var data_attributes = 'data-insights-object-id="'+hit.objectID+'"'
1456		+' data-insights-position="'+hit.__position+'"'
1457		+' data-insights-query-id="'+hit.__queryID+'"';
1458
1459	var html = '<a href="'+hit.permalink+'" class="ais-Hits-item card card-researchers" '+data_attributes+'>';
1460	html += '	<div class="image" style="background-image: url('+hit.photo.src+');">&nbsp;</div>';
1461	html += '	<div class="details">';
1462	html += '		<h2 class="name">'+hit.display_name_with_post_nominals+'</h2>';
1463	html += '		<div class="title">'+hit.title+'</div>';
1464	html += '	</div>';
1465	html += '	<div class="contact">';
1466	html += '		<div class="research-group">'+hit.research_group+'</div>';
1467	html += '		<div class="email-address">';
1468	html += '			<span>';
1469	html += '				<svg width="16" viewBox="0 0 32 32" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"><path d="M3 8v18h26V8zm4.313 2h17.375L16 15.781zM5 10.875l10.438 6.969l.562.343l.563-.343L27 10.875V24H5z" fill="currentColor"></path></svg>';
1470	html += '				<span>'+hit.email_address+'</span>';
1471	html += '			</span>';
1472	html += '		</div>';
1473	html += '	</div>';
1474	html += '</a>';
1475	return html;
1476
1477}	// end instantSearchItemResearcher()
1478
1479function instantSearchItemPages(hit){
1480	// console.log('page',hit);
1481
1482	var body_content = get_content_from_aloglia_flexible_content(hit, 'specialty');
1483	var heading_class = ( body_content.length ? '' : 'no-body-content' );
1484	// console.log('body_content', body_content);
1485
1486	var data_attributes = 'data-insights-object-id="'+hit.objectID+'"'
1487		+' data-insights-position="'+hit.__position+'"'
1488		+' data-insights-query-id="'+hit.__queryID+'"';
1489
1490	var html = '<a href="'+hit.permalink+'" class="ais-Hits-item card card-page" '+data_attributes+'>';
1491	html += '		<h2 class="name '+heading_class+'">'+hit._highlightResult.name.value+'</h2>';
1492	html +=			body_content;
1493	html += '</a>';
1494	html = html.replace('&amp;', '&');
1495
1496	return html;
1497
1498}	// end instantSearchItemPages()
1499
1500function instantSearchItemEvents(hit){
1501	// console.log('event', hit);
1502
1503	var html = '<a href="'+hit.permalink+'" class="event card card-event event-41374">';
1504
1505	html += '<div class="top">';
1506	html += '	<div class="date">';
1507	html += '		<span class="month">'+hit.month_str+'</span>';
1508	html += '		<span class="day">'+hit.day_str+'</span>';
1509	html += '	</div>';
1510	html += '	<div class="title">';
1511	html += '		<h2>'+hit.title+'</h2>';
1512	if( hit.campus_str ){
1513		html += '		<h3>'+hit.campus_str+'</h3>';
1514	}
1515	html += '		<div class="time-range">'+hit.start_time+'</div>';
1516	html += '		<div class="category">'+hit.categories_str+'</div>';
1517	html += '	</div>';
1518	html += '</div>';
1519	html += '<div class="bottom">';
1520	html += '	<div class="image">';
1521	html += '		<img src="'+hit.image.src+'" width="'+hit.image.width+'" height="'+hit.image.height+'" alt="'+hit.image.alt+'" />';
1522	html += '	</div>';
1523	html += '	<div class="intro">';
1524	html += '		<div class="line-clamp line-clamp-4">'+hit.intro+'</div>';
1525	html += '	</div>';
1526	html += '</div>';
1527	html += '</a>';
1528
1529	return html;
1530
1531}	// end instantSearchItemEvents()
1532
1533function instantSearchItemNews(hit){
1534	// console.log('news',hit);
1535
1536	var body_content = get_content_from_aloglia_flexible_content(hit, 'specialty');
1537	var heading_class = ( body_content.length ? '' : 'no-body-content' );
1538	// console.log('body_content', body_content);
1539
1540	// output the date on the card in Month D, Year format - this is in MS in JavaScript to x1000 for the PHP generated timestamp that comes from Algolia data
1541	var date = new Date(hit.timestamp * 1000);
1542	var daynum = date.getDate();
1543	var month = date.getMonth();
1544	var monthText = intToMonth(month);
1545	var year = date.getFullYear();
1546	var date_for_card = monthText+' '+daynum+', '+year;
1547	var hour = date.getHours();
1548	var mins = date.getMinutes();
1549	var date_for_card_attribute = year+'-'+((month+1) < 10 ? '0'+(month+1) : (month+1))+'-'+daynum+' '+(hour < 10 ? '0'+hour : hour)+':'+(mins < 10 ? '0'+mins : mins);
1550
1551	var data_attributes = 'data-insights-object-id="'+hit.objectID+'"'
1552	+' data-insights-position="'+hit.__position+'"'
1553	+' data-insights-query-id="'+hit.__queryID+'"';
1554
1555	var html = '<a href="'+hit.permalink+'" class="ais-Hits-item card card-news" '+data_attributes+'>';
1556	html += '		<time datetime="'+date_for_card_attribute+'">'+date_for_card+'</time>';
1557	html += '		<h2 class="name '+heading_class+'">'+hit._highlightResult.name.value+'</h2>';
1558	html +=			body_content;
1559	html += '</a>';
1560
1561	return html;
1562
1563}	// end instantSearchItemPages()
1564
1565function instantSearchItemLocation(hit){
1566	// console.log('location',hit);
1567
1568	var data_attributes = 'data-insights-object-id="'+hit.objectID+'"'
1569		+' data-insights-position="'+hit.__position+'"'
1570		+' data-insights-query-id="'+hit.__queryID+'"';
1571
1572	var html = '<a href="'+hit.permalink+'" class="ais-Hits-item card card-location" '+data_attributes+'>';
1573	html += '	<div class="image" style="background-image: url(\''+hit.location_image.src+'\');">&nbsp;</div>';
1574	html += '	<div class="details">';
1575	html += '		<h2 class="name">';
1576	html += '			'+hit._highlightResult.location_name.value;
1577	html += '			<span class="sub-name">'+hit._highlightResult.location_name2.value+'</span>';
1578	html += '		</h2>';
1579	if( hit['text-address'].length > 0 ){
1580		html += '		<div class="data-row address">';
1581		html += '			<h3>Address</h3>';
1582		html += '			<span>';
1583		html += '				'+hit._highlightResult.address_1.value;
1584		if( hit.address_2.length > 0 ) html += 		'	<br/>'+hit._highlightResult.address_2.value;
1585		if( hit.floor_suite.length > 0 ) html += 	'	<br/>'+hit._highlightResult.floor_suite.value;
1586		if( hit.floor_suite_2.length > 0 ) html += 	'	<br/>'+hit._highlightResult.floor_suite_2.value;
1587		html += '				<br/>'+hit._highlightResult.city.value+', '+hit._highlightResult.state.value+' '+hit._highlightResult.zip_code.value;
1588		// if( hit['directions-url'].length > 0 ) html += '<br/><a href="'+hit['directions-url']+'" class="get-directions" target="_blank" rel="noopener"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32">
1588<path fill="currentColor" d="M16 3c-4.957 0-9 4.043-9 9c0 1.406.57 3.02 1.344 4.781c.773 1.762 1.77 3.633 2.781 5.375a101.333 101.333 0 0 0 4.063 6.407L16 29.75l.813-1.188s2.039-2.917 4.062-6.406c1.012-1.742 2.008-3.613 2.781-5.375C24.43 15.02 25 13.406 25 12c0-4.957-4.043-9-9-9zm0 2c3.879 0 7 3.121 7 7c0 .8-.43 2.316-1.156 3.969c-.727 1.652-1.73 3.484-2.719 5.187c-1.57 2.711-2.547 4.145-3.125 5c-.578-.855-1.555-2.289-3.125-5c-.988-1.703-1.992-3.535-2.719-5.187C9.43 14.316 9 12.8 9 12c0-3.879 3.121-7 7-7zm0 5a1.999 1.999 0 1 0 0 4a1.999 1.999 0 1 0 0-4z"/></svg> Get Directions</a>';
1589		html += '			</span>';
1590		html += '		</div>';
1591	}
1592
1593	if( hit.hours.length > 0 ) html += '				<div class="data-row office-hours"><h3>Hours</h3><span>'+hit.hours+'</span></div>';
1594	if( hit.call_for_appointment.length > 0 ) html += '	<div class="data-row phone-num"><h3>Call for Appointment</h3><span>'+hit.call_for_appointment+'</span></div>';
1595	if( hit.office_phone.length > 0 ) html += '			<div class="data-row phone-num"><h3>Office Phone</h3><span>'+hit.office_phone+'</span></div>';
1596	// if( hit.office_fax.length > 0 ) html += '			<div class="data-row phone-num"><h3>Office Fax</h3><span>'+hit.office_fax+'</span></div>';
1597	if( hit.referral_fax.length > 0 ) html += '			<div class="data-row phone-num"><h3>Referral Fax</h3><span>'+hit.referral_fax+'</span></div>';
1598
1599	html += '	';
1600	html += '	';
1601	html += '	</div>';
1602	html += '	<div class="contact">';
1603	html += '		<span>Learn more</span>';
1604	html += '	</div>';
1605	html += '</a>';
1606	return html;
1607
1608}	// end instantSearchItemLocation()
1609
1610function instantSearchItemSpecialty(hit){
1611	// console.log('specialty', hit,);
1612
1613	var body_content = get_content_from_aloglia_flexible_content(hit, 'specialty');
1614	var heading_class = ( body_content.length ? '' : 'no-body-content' );
1615	// console.log('body_content', body_content);
1616
1617	var data_attributes = 'data-insights-object-id="'+hit.objectID+'"'
1618		+' data-insights-position="'+hit.__position+'"'
1619		+' data-insights-query-id="'+hit.__queryID+'"';
1620
1621	var html = '<a href="'+hit.permalink+'" class="ais-Hits-item card card-specialty" '+data_attributes+'>';
1622	html += '		<h2 class="name '+heading_class+'">'+hit._highlightResult.name.value+'</h2>';
1623	html +=			body_content;
1624	html += '</a>';
1625
1626	return html;
1627
1628}	// end instantSearchItemSpecialty()
1629
1630function get_content_from_aloglia_flexible_content(hit = false, type = 'page'){
1631
1632	if( !hit ) return false;
1633	// console.log(type, hit);
1634
1635	// look at the content type fields (in the _highlightResult) and see if there are any matches
1636	// "basic_wysiwyg", "accordion_module", "quote_module", and "content_columns" (more complex!)
1637
1638	var html = '';
1639	// console.log(hit._highlightResult);
1640
1641	switch(true){
1642
1643		case( hit._highlightResult["basic_wysiwyg"] !== undefined ):
1644		case( hit._highlightResult["accordion_module"] !== undefined ):
1645		case( hit._highlightResult["quote_module"] !== undefined ):
1646		case( hit._highlightResult["list_cards"] !== undefined ):
1647
1648			let module_type = hit._highlightResult['basic_wysiwyg'];
1649			switch(true){
1650
1651				case( hit._highlightResult["basic_wysiwyg"] !== undefined ):
1652					module_type = hit._highlightResult["basic_wysiwyg"];
1653					break;
1654
1655				case( hit._highlightResult["accordion_module"] !== undefined ):
1656					module_type = hit._highlightResult["accordion_module"];
1657					break;
1658
1659				case( hit._highlightResult["quote_module"] !== undefined ):
1660					module_type = hit._highlightResult["quote_module"];
1661					break;
1662
1663				case( hit._highlightResult["list_cards"] !== undefined ):
1664					module_type = hit._highlightResult["list_cards"];
1665					break;
1666
1667				default:
1668					module_type = module_type
1669					break;
1670
1671			}	// end switch()
1672			// console.log('WHAT IS IT?',module_type);
1673			// console.log('basic_wysiwyg',hit._highlightResult[module_type]);
1674
1675			let item = false;
1676			let arrLen = module_type.length;
1677			// console.log('arrLen',arrLen);
1678			let matchLevel = 'none';
1679			// find the first match that is "matchLevel = full" or "matchLevel = partial"
1680			for( let step = 0; step < arrLen; step++ ){
1681				matchLevel = module_type[step]['matchLevel'];
1682				if( matchLevel == 'full' || matchLevel == 'partial' ){
1683					// console.log('matchLevel', matchLevel, module_type[step]);
1684					item = module_type[step];
1685					break;
1686				}else{
1687					item = module_type[step];
1688				}
1689			}
1690
1691			// we will just use the first match - doesn't really matter if there are additional ones
1692			let match = item['value'];
1693			let output = get_substring_from_algolia_hit_with_mark(match);
1694			if( output == '' ) output += match;
1695		
1696			html += '	<div class="result line-clamp line-clamp-3" data-match-level="'+matchLevel+'">';
1697			html += '	'+output;
1698			html += '	</div>';
1699			break;
1700
1701		// case( hit._highlightResult["accordion_module"] !== undefined ):
1702		// 	console.log('accordion_module',hit._highlightResult["accordion_module"]);
1703		// 	break;
1704
1705		default:
1706			html = '';
1707			// html += '<!-- There are no flexbile content modules in this page to build search content from. -->';
1708			// html += '	<div class="result line-clamp line-clamp-1">';
1709			// html += '		There are no flexbile content modules in this page to build search content from.';
1710			// html += '	</div>';
1711			break;
1712
1713	}	// end switch()
1714
1715	return html;
1716
1717}	// end get_content_from_aloglia_flexible_content()
1718
1719function htmlSubstring(s, n){
1720    var m, r = /<([^>\s]*)[^>]*>/g,
1721        stack = [],
1722        lasti = 0,
1723        result = '';
1724
1725    //for each tag, while we don't have enough characters
1726    while ((m = r.exec(s)) && n) {
1727        //get the text substring between the last tag and this one
1728        var temp = s.substring(lasti, m.index).substr(0, n);
1729        //append to the result and count the number of characters added
1730        result += temp;
1731        n -= temp.length;
1732        lasti = r.lastIndex;
1733
1734        if (n) {
1735            result += m[0];
1736            if (m[1].indexOf('/') === 0) {
1737                //if this is a closing tag, than pop the stack (does not account for bad html)
1738                stack.pop();
1739            } else if (m[1].lastIndexOf('/') !== m[1].length - 1) {
1740                //if this is not a self closing tag than push it in the stack
1741                stack.push(m[1]);
1742            }
1743        }
1744    }
1745
1746    //add the remainder of the string, if needed (there are no more tags in here)
1747    result += s.substr(lasti, n);
1748
1749    //fix the unclosed tags
1750    while (stack.length) {
1751        result += '</' + stack.pop() + '>';
1752    }
1753
1754    return result;
1755
1756}	// end htmlSubstring()
1757
1758function get_substring_from_algolia_hit_with_mark(str = false){
1759
1760	if( !str ) return '';
1761
1762	let debug = [];
1763
1764	debug['str'] = str;
1765	let item_len = str.length;
1766
1767	let found_open = str.indexOf("<mark>");		// length = 6
1768	let extra_start = 20;						// extra amount to grab before <mark>
1769	let start = 0;								// default to zero
1770	let result = '';							// default to empty
1771	debug['extra_start'] = extra_start;
1772
1773	if( found_open >= 0 ){
1774
1775		if( found_open < extra_start ) extra_start = found_open;
1776		debug['found_open'] = found_open;
1777
1778		start = found_open - extra_start;
1779		debug['start'] = start;
1780		
1781		result = str.substring(start);
1782		result = htmlSubstring(result, 400);
1783		debug['result'] = result;
1784
1785	}
1786
1787	// console.log('debug',debug);
1788
1789	if( start > 0 ) result = '...'+result;
1790
1791	return result;
1792
1793}	// end get_substring_from_algolia_hit_with_mark
1794
1795function amcAlgoliaInstantSearch($){
1796	// console.log('here - amcAlgoliaInstantSearch()');
1797
1798	const hasInstantSearch = $('.ais-InstantSearch');
1799	// console.log('hasInstantSearch', hasInstantSearch);
1800
1801	if( hasInstantSearch.length == 0 ){
1802		console.log('Page does not have InstantSearch.js');
1803		return false;
1804	}
1805
1806	const type = hasInstantSearch.attr('data-type');
1807	console.log('type', type);
1808
1809	var algolia_core = {
1810		"application_id": SEARCH_APP,
1811		"search_api_key": SEARCH_KEY
1812	};
1813
1814	/* Initialize Algolia client */
1815	const searchClient = algoliasearch(
1816		algolia_core.application_id,
1817		algolia_core.search_api_key
1818	);
1819
1820	// conditional statement for things like input placeholder and used indices
1821	switch(true){
1822
1823		case( type == 'find-a-doctor' ):
1824			var algolia_more = {
1825				"placeholder": 'Browse providers...',
1826				"indexName": 'amc_physicians'
1827			};
1828			break;
1829
1830		case( type == 'locations-providers' ):
1831			var algolia_more = {
1832				"placeholder": 'Browse locations...',
1833				"indexName": 'amc_physicians'
1834			};
1835			break;
1836
1837		case( type == 'locations' ):
1838			var algolia_more = {
1839				"placeholder": 'Browse locations...',
1840				"indexName": 'amc_locations'
1841			};
1842			break;
1843
1844		case( type == 'researchers' ):
1845			var algolia_more = {
1846				"placeholder": 'Browse Faculty & Researchers...',
1847				"indexName": 'edu_researchers'
1848			};
1849			break;
1850
1851		case( type == 'full-site-search-edu' ):
1852			var algolia_more = {
1853				"placeholder": 'Browse Faculty & Researchers, and other information...',
1854				"indexName": 'edu_researchers'
1855			};
1856			break;
1857
1858		default:	// type == 'full-site-search' -- hopefully!!
1859			var algolia_more = {
1860				"placeholder": 'Find providers, locations, services, and other information...',
1861				// "indexNames": [ 'amc_physicians', 'amc_locations', 'amc_specialties' ]
1862				"indexName": 'amc_physicians'
1863			};
1864			break;
1865
1866	}	// end switch()
1867	var algolia = Object.assign(algolia_core, algolia_more);
1868	console.log('algolia', algolia);
1869
1870	var search = instantsearch({
1871		indexName: algolia_more.indexName,
1872		searchClient,
1873		routing: true		// https://www.algolia.com/doc/guides/building-search-ui/going-further/routing-urls/js/#basic-urls
1874	});
1875	console.log('search', search);
1876
1877	var timeout = 250;	// this is the pause time for the debounce
1878
1879	var queryHook = _.debounce(function(query, search){
1880			search(query)
1881		},timeout);
1882
1883	// define and ouput InstantSearch.js in the page ------------------------
1884	switch(true){
1885
1886		case( type == 'find-a-doctor' ):
1887			search.addWidgets([
1888				instantsearch.widgets.clearRefinements({
1889					container: '#clear-refinements',
1890				}),
1891				
1892				// Source: https://www.algolia.com/doc/api-reference/widgets/refinement-list/js/
1893				instantsearch.widgets.menu({
1894					container: '#refinement-first-letter',
1895					attribute: 'last_name_first_letter',
1896					operator: 'and',
1897					limit: 26,
1898					sortBy: ['name:asc']
1899				}),
1900				instantsearch.widgets.stats({
1901					container: '#counts',
1902					templates: {
1903						text(data){
1904							return showAISstats($, data, 'amc_physicians', 'hidden');
1905						}
1906					}
1907				}),
1908				instantsearch.widgets.refinementList({
1909					container: '#refinement-specialties',
1910					attribute: 'specialties_items',
1911					limit: 10,
1912					searchable: true,
1913					searchablePlaceholder: 'Filter specialties...',
1914					// showMore: true,
1915					// showMoreLimit: 25,
1916					// sortBy: ['isRedined']
1917				}),
1918				instantsearch.widgets.refinementList({
1919					container: '#refinement-locations',
1920					attribute: 'locations',
1921					limit: 10,
1922					searchable: true,
1923					searchablePlaceholder: 'Filter locations...',
1924					// showMore: true,
1925					// showMoreLimit: 25,
1926					// sortBy: ['isRedined']
1927				}),
1928				instantsearch.widgets.menu({
1929					container: '#refinement-primary-care',
1930					attribute: 'primary_care',
1931					sortBy: ['name:desc'],
1932					templates: {
1933						item({ count, label }) {
1934							switch(true){
1935
1936								case( label == 'true' ):
1937									label = 'Yes';
1938									break;
1939
1940								default:	// this is "NO"
1941									label = 'No';
1942									break;
1943
1944							}	// end switch()
1945							let radio = '';
1946							radio += '<svg width="16" class="unchecked" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"><path fill="currentColor" d="M12 22a10 10 0 1 1 10-10a10 10 0 0 1-10 10zm0-18a8 8 0 1 0 8 8a8 8 0 0 0-8-8z"/></svg>';
1947							radio += '<svg width="16" class="checked" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"><g fill="currentColor"><path d="M12 2a10 10 0 1 0 10 10A10 10 0 0 0 12 2zm0 18a8 8 0 1 1 8-8a8 8 0 0 1-8 8z"/><path d="M12 7a5 5 0 1 0 5 5a5 5 0 0 0-5-5z"/></g></svg>';
1948							refinementMenuClickHelper($);	// the Algolia DOM rewrites on each selection, so retrigger this here!
1949							return `<label>${radio} ${label}</label>`;
1950						},
1951					}
1952				}),
1953				instantsearch.widgets.refinementList({
1954					container: '#refinement-languages',
1955					attribute: 'languages_spoken_facet',
1956					limit: 10,
1957					searchable: true,
1958					searchablePlaceholder: 'Filter languages...',
1959					// showMore: true,
1960					// showMoreLimit: 25,
1961					// sortBy: ['isRedined']
1962				}),
1963		
1964				instantsearch.widgets.searchBox({
1965					container: '#searchbox',
1966					placeholder: algolia.placeholder,
1967					autofocus: true,
1968					queryHook: queryHook
1969					// queryHook: debounce(search, 1500)
1970				}),
1971		
1972				instantsearch.widgets.configure({
1973					hitsPerPage: 20,
1974					clickAnalytics: true,
1975					userToken: UNIQUE_ID
1976				}),
1977		
1978				instantsearch.widgets.voiceSearch({
1979					container: '#voicesearch',
1980				}),
1981
1982				instantsearch.widgets.pagination({
1983					container: '#pagination',
1984					showPrevious: false,
1985					showNext: false,
1986					padding: 2
1987				}),
1988			
1989				instantsearch.widgets.hits({
1990					container: '#hits',
1991					templates: {
1992						item(item) {
1993							return instantSearchItemPhysician(item);
1994						},
1995						noResults() {
1996							return 'No doctors were found...';
1997						},
1998						// HIGHLIGHT - https://www.algolia.com/doc/api-reference/widgets/highlight/js/
1999					},
2000				}),
2001			]);
2002			document.getElementById('refinement-first-letter').style.display = 'block';
2003			break;
2004
2005		case( type == 'locations-providers' ):
2006			console.log('locations-providers');
2007			// get the data-loc-name from the page
2008			var loc_name = $('#hits_our_providers').attr('data-loc-name');
2009			console.log('loc_name', loc_name);
2010			search.addWidgets([
2011				instantsearch.widgets.refinementList({
2012					container: '#refinement-locations',
2013					attribute: 'locations',
2014					limit: 1,
2015					searchable: true,
2016					searchablePlaceholder: 'Filter locations...',
2017					// showMore: true,
2018					// showMoreLimit: 25,
2019					// sortBy: ['isRedined']
2020				}),
2021				instantsearch.widgets.configure({
2022					hitsPerPage: 3,
2023					clickAnalytics: true,
2024					userToken: UNIQUE_ID,
2025					disjunctiveFacetsRefinements: {
2026						locations: [loc_name]
2027					}
2028				}),
2029			
2030				instantsearch.widgets.hits({
2031					container: '#hits',
2032					templates: {
2033						item(item) {
2034							return instantSearchItemPhysician(item);
2035						},
2036						noResults() {
2037							return 'No doctors were found...';
2038						},
2039						// HIGHLIGHT - https://www.algolia.com/doc/api-reference/widgets/highlight/js/
2040					},
2041				}),
2042			]);
2043			break;
2044
2045		case( type == 'locations' ):
2046			search.addWidgets([
2047				instantsearch.widgets.clearRefinements({
2048					container: '#clear-refinements',
2049				}),
2050				
2051				// Source: https://www.algolia.com/doc/api-reference/widgets/refinement-list/js/
2052				/*
2053				instantsearch.widgets.refinementList({
2054					container: '#refinement-first-letter',
2055					attribute: 'last_name_first_letter',
2056					operator: 'and',
2057					sortBy: ['name:asc']
2058				}),
2059				instantsearch.widgets.refinementList({
2060					container: '#refinement-primary-care',
2061					attribute: 'primary_care',
2062				}),
2063				*/
2064				instantsearch.widgets.refinementList({
2065					container: '#refinement-specialties',
2066					attribute: 'specialties_items',
2067					limit: 10,
2068					searchable: true,
2069					searchablePlaceholder: 'Filter specialties...',
2070					// showMore: true,
2071					// showMoreLimit: 25,
2072					// sortBy: ['name:asc']
2073				}),
2074		
2075				instantsearch.widgets.searchBox({
2076					container: '#searchbox',
2077					placeholder: algolia.placeholder,
2078					autofocus: true,
2079					queryHook: queryHook
2080				}),
2081		
2082				instantsearch.widgets.configure({
2083					hitsPerPage: 20,
2084					clickAnalytics: true,
2085					userToken: UNIQUE_ID
2086				}),
2087		
2088				instantsearch.widgets.voiceSearch({
2089					container: '#voicesearch',
2090				}),
2091
2092				instantsearch.widgets.pagination({
2093					container: '#pagination',
2094					showPrevious: false,
2095					showNext: false,
2096					padding: 2
2097				}),
2098			
2099				instantsearch.widgets.hits({
2100					container: '#hits',
2101					templates: {
2102						item(item) {
2103							return instantSearchItemLocation(item);
2104						},
2105						noResults() {
2106							return 'No doctors were found...';
2107						},
2108						// HIGHLIGHT - https://www.algolia.com/doc/api-reference/widgets/highlight/js/
2109					},
2110				}),
2111			]);
2112			break;
2113
2114		case( type == 'researchers' ):
2115			search.addWidgets([
2116				instantsearch.widgets.clearRefinements({
2117					container: '#clear-refinements',
2118				}),
2119				
2120				// Source: https://www.algolia.com/doc/api-reference/widgets/refinement-list/js/
2121				instantsearch.widgets.refinementList({
2122					container: '#refinement-first-letter',
2123					attribute: 'last_name_first_letter',
2124					operator: 'and',
2125					sortBy: ['name:asc']
2126				}),
2127				/*
2128				instantsearch.widgets.refinementList({
2129					container: '#refinement-primary-care',
2130					attribute: 'primary_care',
2131				}),
2132				*/
2133				instantsearch.widgets.refinementList({
2134					container: '#refinement-research-group-items',
2135					attribute: 'research_group_items',
2136					limit: 10,
2137					searchable: true,
2138					searchablePlaceholder: 'Filter Research Groups...',
2139					// showMore: true,
2140					// showMoreLimit: 25,
2141					// sortBy: ['name:asc']
2142				}),
2143				instantsearch.widgets.searchBox({
2144					container: '#searchbox',
2145					placeholder: algolia.placeholder,
2146					autofocus: true,
2147					queryHook: queryHook
2148				}),
2149		
2150				instantsearch.widgets.configure({
2151					hitsPerPage: 20,
2152					clickAnalytics: true,
2153					userToken: UNIQUE_ID
2154				}),
2155		
2156				instantsearch.widgets.voiceSearch({
2157					container: '#voicesearch',
2158				}),
2159
2160				instantsearch.widgets.pagination({
2161					container: '#pagination',
2162					showPrevious: false,
2163					showNext: false,
2164					padding: 2
2165				}),
2166			
2167				instantsearch.widgets.hits({
2168					container: '#hits',
2169					templates: {
2170						item(item) {
2171							return instantSearchItemResearcher(item);
2172						},
2173						noResults() {
2174							return 'No faculty or researchers were found...';
2175						},
2176						// HIGHLIGHT - https://www.algolia.com/doc/api-reference/widgets/highlight/js/
2177					},
2178				}),
2179
2180			]);
2181			break;
2182
2183		case( type == 'full-site-search-edu' ):
2184			
2185			// const makeHits = instantsearch.connectors.connectHits(
2186			// 	function renderHits({ hits }, isFirstRendering) {
2187			// 		hits.forEach(hit => {
2188			// 			console.log(hit);
2189			// 		});
2190			// 	}
2191			// );
2192
2193			search.addWidgets([
2194
2195				instantsearch.widgets.searchBox({
2196					container: '#searchbox',
2197					placeholder: algolia.placeholder,
2198					autofocus: true,
2199					queryHook: queryHook
2200				}),
2201		
2202				instantsearch.widgets.configure({
2203					hitsPerPage: 20,
2204					clickAnalytics: true,
2205					userToken: UNIQUE_ID
2206				}),
2207		
2208				instantsearch.widgets.voiceSearch({
2209					container: '#voicesearch',
2210				}),
2211
2212				instantsearch.widgets.pagination({
2213					container: '#pagination-researchers',
2214					showPrevious: false,
2215					showNext: false,
2216					padding: 2
2217				}),
2218
2219				instantsearch.widgets.stats({
2220					container: '#stats-researchers',
2221					templates: {
2222						text(data){
2223							return showAISstats($, data, 'edu_researchers');
2224						}
2225					}
2226				}),
2227
2228				instantsearch.widgets.hits({
2229					container: '#hits-researchers',
2230					templates: {
2231						item(item) {
2232							return instantSearchItemResearcher(item);
2233						},
2234						noResults() {
2235							return 'No researchers were found...';
2236						},
2237						// HIGHLIGHT - https://www.algolia.com/doc/api-reference/widgets/highlight/js/
2238					},
2239				}),
2240
2241				instantsearch.widgets
2242					.index({ indexName: 'edu_pages' })
2243					.addWidgets([
2244						instantsearch.widgets.configure({
2245							hitsPerPage: 20
2246						}),
2247
2248						instantsearch.widgets.pagination({
2249							container: '#pagination-pages',
2250							showPrevious: false,
2251							showNext: false,
2252							padding: 2
2253						}),
2254
2255						instantsearch.widgets.stats({
2256							container: '#stats-pages',
2257							templates: {
2258								text(data) {
2259									return showAISstats($, data, 'edu_pages');
2260								}
2261							}
2262						}),
2263
2264						instantsearch.widgets.hits({
2265							container: '#hits-pages',
2266							templates: {
2267								item(item) {
2268									return instantSearchItemPages(item);
2269								},
2270								noResults() {
2271									return 'No pages were found...';
2272								},
2273							},
2274						}),
2275					]),
2276
2277				instantsearch.widgets
2278					.index({ indexName: 'edu_posts_college' })
2279					.addWidgets([
2280						instantsearch.widgets.configure({
2281							hitsPerPage: 20,
2282							facetFilters: ['post_categories:college'],
2283						}),
2284
2285						instantsearch.widgets.pagination({
2286							container: '#pagination-news',
2287						}),
2288
2289						instantsearch.widgets.stats({
2290							container: '#stats-news',
2291							templates: {
2292								text(data) {
2293									return showAISstats($, data, 'edu_posts_college');
2294								}
2295							}
2296						}),
2297
2298						instantsearch.widgets.hits({
2299							container: '#hits-news',
2300							templates: {
2301								item(item) {
2302									return instantSearchItemNews(item);
2303								},
2304								noResults() {
2305									return 'No news items were found...';
2306								},
2307							},
2308						}),
2309					]),
2310
2311				instantsearch.widgets
2312					.index({ indexName: 'edu_events' })
2313					.addWidgets([
2314						instantsearch.widgets.configure({
2315							hitsPerPage: 20
2316						}),
2317
2318						instantsearch.widgets.pagination({
2319							container: '#pagination-events',
2320							showPrevious: false,
2321							showNext: false,
2322							padding: 2
2323						}),
2324
2325						instantsearch.widgets.stats({
2326							container: '#stats-events',
2327							templates: {
2328								text(data) {
2329									return showAISstats($, data, 'edu_events');
2330								}
2331							}
2332						}),
2333
2334						instantsearch.widgets.hits({
2335							container: '#hits-events',
2336							templates: {
2337								item(item) {
2338									return instantSearchItemEvents(item);
2339								},
2340								noResults() {
2341									return 'No events were found...';
2342								},
2343							},
2344						}),
2345					]),
2346
2347
2348			]);
2349
2350			break;
2351
2352		default:	// type == 'full-site-search' -- hopefully!!
2353			
2354			const makeHits = instantsearch.connectors.connectHits(
2355				function renderHits({ hits }, isFirstRendering) {
2356					hits.forEach(hit => {
2357						console.log('hit',hit);
2358					});
2359				}
2360			);
2361
2362			search.addWidgets([
2363
2364				instantsearch.widgets.searchBox({
2365					container: '#searchbox',
2366					placeholder: algolia.placeholder,
2367					autofocus: true,
2368					queryHook: queryHook
2369				}),
2370		
2371				instantsearch.widgets.configure({
2372					hitsPerPage: 20,
2373					clickAnalytics: true,
2374					userToken: UNIQUE_ID
2375				}),
2376		
2377				instantsearch.widgets.voiceSearch({
2378					container: '#voicesearch',
2379				}),
2380
2381				instantsearch.widgets.pagination({
2382					container: '#pagination-physicians',
2383					showPrevious: false,
2384					showNext: false,
2385					padding: 2
2386				}),
2387
2388				instantsearch.widgets.stats({
2389					container: '#stats-physicians',
2390					templates: {
2391						text(data){
2392							return showAISstats($, data, 'amc_physicians');
2393						}
2394					}
2395				}),
2396
2397				instantsearch.widgets.hits({
2398					container: '#hits-physicians',
2399					templates: {
2400						item(item) {
2401							return instantSearchItemPhysician(item);
2402						},
2403						noResults() {
2404							return 'No doctors were found...';
2405						},
2406						// HIGHLIGHT - https://www.algolia.com/doc/api-reference/widgets/highlight/js/
2407					},
2408				}),
2409
2410				instantsearch.widgets
2411					.index({ indexName: 'amc_pages' })
2412					.addWidgets([
2413						instantsearch.widgets.configure({
2414							hitsPerPage: 20
2415						}),
2416
2417						instantsearch.widgets.pagination({
2418							container: '#pagination-pages',
2419							showPrevious: false,
2420							showNext: false,
2421							padding: 2
2422						}),
2423
2424						instantsearch.widgets.stats({
2425							container: '#stats-pages',
2426							templates: {
2427								text(data) {
2428									return showAISstats($, data, 'amc_pages');
2429								}
2430							}
2431						}),
2432
2433						instantsearch.widgets.hits({
2434							container: '#hits-pages',
2435							templates: {
2436								item(item) {
2437									return instantSearchItemPages(item);
2438								},
2439								noResults() {
2440									return 'No pages were found...';
2441								},
2442							},
2443						}),
2444					]),
2445
2446				instantsearch.widgets
2447					.index({ indexName: 'amc_locations' })
2448					.addWidgets([
2449						instantsearch.widgets.configure({
2450							hitsPerPage: 20
2451						}),
2452
2453						instantsearch.widgets.pagination({
2454							container: '#pagination-locations',
2455						}),
2456
2457						instantsearch.widgets.stats({
2458							container: '#stats-locations',
2459							templates: {
2460								text(data) {
2461									return showAISstats($, data, 'amc_locations');
2462								}
2463							}
2464						}),
2465
2466						instantsearch.widgets.hits({
2467							container: '#hits-locations',
2468							templates: {
2469								item(item) {
2470									return instantSearchItemLocation(item);
2471								},
2472								noResults() {
2473									return 'No locations were found...';
2474								},
2475							},
2476						}),
2477					]),
2478
2479				instantsearch.widgets
2480					.index({ indexName: 'amc_specialties' })
2481					.addWidgets([
2482						instantsearch.widgets.configure({
2483							hitsPerPage: 20,
2484						}),
2485
2486						instantsearch.widgets.pagination({
2487							container: '#pagination-specialties',
2488						}),
2489
2490						instantsearch.widgets.stats({
2491							container: '#stats-specialties',
2492							templates: {
2493								text(data) {
2494									return showAISstats($, data, 'amc_specialties');
2495								}
2496							}
2497						}),
2498
2499						instantsearch.widgets.hits({
2500							container: '#hits-specialties',
2501							templates: {
2502								item(item) {
2503									return instantSearchItemSpecialty(item);
2504								},
2505								noResults() {
2506									return 'No specialties were found...';
2507								},
2508							},
2509						}),
2510					]),
2511
2512				instantsearch.widgets
2513					.index({ indexName: 'amc_posts_news' })
2514					.addWidgets([
2515						instantsearch.widgets.configure({
2516							hitsPerPage: 20,
2517						}),
2518
2519						instantsearch.widgets.pagination({
2520							container: '#pagination-news',
2521						}),
2522
2523						instantsearch.widgets.stats({
2524							container: '#stats-news',
2525							templates: {
2526								text(data) {
2527									return showAISstats($, data, 'amc_posts_news');
2528								}
2529							}
2530						}),
2531
2532						instantsearch.widgets.hits({
2533							container: '#hits-news',
2534							templates: {
2535								item(item) {
2536									return instantSearchItemNews(item);
2537								},
2538								noResults() {
2539									return 'No news items were found...';
2540								},
2541							},
2542						}),
2543					]),
2544
2545				instantsearch.widgets
2546					.index({ indexName: 'amc_events' })
2547					.addWidgets([
2548						instantsearch.widgets.configure({
2549							hitsPerPage: 20
2550						}),
2551
2552						instantsearch.widgets.pagination({
2553							container: '#pagination-events',
2554							showPrevious: false,
2555							showNext: false,
2556							padding: 2
2557						}),
2558
2559						instantsearch.widgets.stats({
2560							container: '#stats-events',
2561							templates: {
2562								text(data) {
2563									return showAISstats($, data, 'amc_events');
2564								}
2565							}
2566						}),
2567
2568						instantsearch.widgets.hits({
2569							container: '#hits-events',
2570							templates: {
2571								item(item) {
2572									return instantSearchItemEvents(item);
2573								},
2574								noResults() {
2575									return 'No events were found...';
2576								},
2577							},
2578						}),
2579					]),
2580
2581			]);
2582			break;
2583
2584	}	// end switch()
2585
2586	const insightsMiddleware = instantsearch.middlewares.createInsightsMiddleware({
2587		insightsClient: null,
2588		onEvent(event) {
2589			const { widgetType, eventType, payload, hits } = event;
2590			if (widgetType === 'ais.hits' && eventType === 'view') {
2591				if( typeof dataLayer !== 'undefined') dataLayer.push({ event: 'Hits Viewed' });
2592				// console.log('insightsMiddleware event', event);
2593			}
2594		}
2595	});	  
2596	search.use(insightsMiddleware);
2597
2598	search.start();
2599
2600}	// end amcAlgoliaInstantSearch()
2601
2602function refinementMenuClickHelper($){
2603
2604	$('#refinement-primary-care li.ais-Menu-item').on('click', function(){
2605		// console.log('click - need to figure out how to trigger a click on the contained LABEL');
2606	});
2607
2608}	// end refinementMenuClickHelper()
2609
2610function switchTabsIfNoStats($, data_tab){
2611
2612	// console.log('data_tab', data_tab);
2613
2614	let index = data_tab.attr('tab-index');
2615	let hits = data_tab.attr('data-hits');
2616
2617	// console.log('index', index);
2618	// console.log('hits', hits);
2619
2620	return [index, hits];
2621
2622}	// end switchTabsIfNoStats()
2623
2624function targetAIStabWithStats($){
2625
2626	let new_active = $('.tabs').attr('data-new-active');
2627	// console.log('new_active', new_active, typeof new_active);
2628
2629	// detect the current active tab
2630	let active_tab = $('.tabs .tablinks.active');
2631	// console.log('active_tab =', active_tab.attr('data-tab'), active_tab);
2632
2633	// get the stats for the current active tab, and if the returned "hits" count is greater than zero, return false to stay on this tab
2634	let need_switch = switchTabsIfNoStats($, active_tab);
2635	// console.log('need_switch', need_switch, typeof need_switch);
2636	if( need_switch[1] > 0 ) return false;
2637
2638	// if the above returned "hits" count was zero, let's look at which tab has results and more to the first one that does
2639	let tabs = $('.tabs .tablinks').each(function(i){
2640
2641		let index = $(this).attr('tab-index');
2642		let hits = $(this).attr('data-hits');
2643		// console.log('index', index, 'hits', hits, 'new_active', new_active);
2644
2645		if( hits > 0 ){
2646			$('.tablinks, .tabcontent').removeClass('active');
2647			$('.tabs').attr('data-new-active', index).find('.tablinks[tab-index="'+index+'"]').addClass('active').trigger('click');
2648			// $('.tabs').removeAttr('data-new-active');
2649			return false;
2650		}
2651
2652	});
2653
2654}	// end targetAIStabWithStats()
2655
2656function showAISstats($, data, idx, location = 'tab'){
2657
2658	// console.log('location', location);
2659
2660	let tab = $('.tabs .tablinks[tab-index="'+idx+'"]');
2661	tab.attr('data-hits', data.nbHits);
2662
2663	waitForFinalEvent( function() {
2664		targetAIStabWithStats($);
2665	}, 250, "your-function-identifier-string");
2666
2667	// console.log("$('body').hasClass('local')", $('body').hasClass('local'));
2668
2669	// noAIShitsLoadNextTab($, data.nbHits);
2670	switch(true){
2671
2672		// actually output if "hidden" location and on "local" or body.hasClass('show-ais-count')
2673		case( ( $('body').hasClass('local') || $('body').hasClass('show-ais-count') ) && location == 'hidden' ):
2674			return `&nbsp;<br/>algolia result count: ${data.nbHits} results found`;
2675			break;
2676
2677		// if "hidden" location, output in an HTML comment on "dev"
2678		case( location == 'hidden' ):
2679			return `<!-- // algolia result count: ${data.nbHits} results found -->`;
2680			break;
2681
2682		// output so the counts can be displayed in the tab (like on the full site search)
2683		case( location == 'tab' ):
2684			return `(${data.nbHits})`;
2685			break;
2686
2687		// default return nothing
2688		default:
2689			return false;
2690			break;
2691
2692	}	// end switch()
2693
2694}	// end showAISstats()
2695
2696function algoliaPassSearchToOtherIndices($){
2697
2698	// console.log('algoliaPassSearchToOtherIndices()');
2699
2700	// take what is in the autocomplete search and pass to full site search when .aa-SourceFooter button is clicked
2701	$('body').on('click', '.aa-Panel .aa-SourceFooter a', function(evt){
2702		evt.preventDefault();
2703		var aa_Input_val = $('.aa-Input').val();
2704		window.location.href = '/search/?amc_physicians%5Bquery%5D='+aa_Input_val;
2705		return false;
2706	});
2707
2708	$('body').on('click', '.aa-PanelSection .amc-button', function(evt){
2709		evt.preventDefault();
2710		var aa_Input_val = $('.aa-Input').val();
2711		var href = $(this).attr('href');
2712
2713		switch(true){
2714
2715			case( href == '/find-a-doctor/' ):
2716				href += '?amc_physicians%5Bquery%5D='+aa_Input_val;
2717				break
2718
2719			case( href == '/locations/' ):
2720				href += '?amc_locations%5Bquery%5D='+aa_Input_val;
2721				break
2722
2723			case( href == '/search/#tab-specialties' ):
2724				href = 'search/?amc_physicians%5Bquery%5D='+aa_Input_val+'#tab-specialties';
2725				break
2726
2727			case( href == '/care-treatment/' ):
2728				href += '?search='+aa_Input_val;
2729				break
2730
2731			default:
2732				// do nothing
2733				break;
2734
2735		}	// endswitch()
2736		
2737		// console.log('href', href);
2738
2739		window.location.href = href;
2740		return false;
2741
2742	});
2743
2744	// look at the URL and if there is a search query present load that into the Autocomplete.js
2745	var qs = (function(a) {
2746		if (a == "") return {};
2747		var b = {};
2748		for (var i = 0; i < a.length; ++i)
2749		{
2750			var p=a[i].split('=', 2);
2751			if (p.length == 1)
2752				b[p[0]] = "";
2753			else
2754				b[p[0]] = decodeURIComponent(p[1].replace(/\+/g, " "));
2755		}
2756		return b;
2757	})(window.location.search.substr(1).split('&'));
2758	
2759	// console.log('qs', qs);
2760
2761	var search_term = false;
2762	switch(true){
2763
2764		case( qs.hasOwnProperty('amc_specialties[query]') ):
2765			search_term = qs['amc_specialties[query]'];
2766			break;
2767
2768		default:
2769			break;
2770
2771	}
2772
2773	if( search_term ){
2774
2775		// console.log('search_term', search_term);
2776		const s = new Date();
2777		var start = s.getTime();
2778		setTimeout( function(){
2779			// console.log('fire load search_term = '+search_term);
2780			$('.aa-Input').val(search_term);
2781			$('.aa-Input').trigger('focus');
2782			const e = new Date();
2783			var end = e.getTime();
2784			var total = end - start;
2785			// console.log('total', total);
2786		}, 1500)
2787		
2788	}
2789
2790}	// end algoliaPassSearchToOtherIndices()
2791
2792function amc_check_for_profile_image(item = null){
2793
2794	// console.log('item', item);
2795
2796	return item;
2797
2798	// fall back if the "photo" is empty coming from Algolia
2799	if( item.photo.length == 0 ){
2800		item.photo.src = '/wp-content/themes/amc-child-core/images/default-profile-image-min.png';
2801		item.photo.width = 160;
2802		item.photo.height = 205;
2803	}
2804
2805	return item;
2806
2807}	// end amc_check_for_profile_image()
2808
2809function siblingNavToggle($){
2810
2811	// when a 'sibling-nav-toggle' item is clicked
2812	$('.sibling-nav-toggle').on('click', function(){
2813
2814		var is_open = $(this).parent().hasClass('sub-open');
2815		if( is_open ){
2816			$(this).parent().removeClass('sub-open');
2817		}else{
2818			$(this).parent().addClass('sub-open');
2819		}
2820
2821	});
2822
2823	// when a 'more-expand' item is clicked
2824	$('.more-expand').on('click', function(){
2825
2826		var is_open = $(this).parent().hasClass('more-open');
2827		if( is_open ){
2828			$(this).parent().removeClass('more-open');
2829		}else{
2830			$(this).parent().addClass('more-open');
2831		}
2832
2833	});
2834
2835	// if the more icon is present but there are actually no children, hide the more icon
2836	$('.sidebar ul.menu .sub-menu').each(function(){
2837		
2838		var has_children = $(this).find('li').length;
2839		if( has_children > 0 ){
2840			$(this).siblings('span.more-expand').css({ 'opacity': 1, 'visibility': 'visible' } );
2841		}
2842
2843	});	// end each()
2844
2845}	// end siblingNavToggle()
2846
2847function desktopSeachHasFocus($){
2848
2849	var search_el_focus = $('.search-field').is(':focus');
2850	if( search_el_focus ){
2851		$('form.search-form').addClass('search-focus');
2852	}else{
2853		$('form.search-form').removeClass('search-focus');
2854	}
2855
2856}	// end desktopSeachHasFocus()
2857
2858function toggleDesktopSearch($){
2859
2860	// when the desktop search icon is clicked, toggle the "search-open" class on the header.page-header element
2861	$('.search-button').on('click', 'a', function(evt){
2862		// evt.stopPropegation();
2863		evt.preventDefault();
2864		
2865		$search_open = $('header.page-header').hasClass('search-open');
2866		if( !$search_open ){
2867			$('header.page-header').addClass('search-open');
2868			$('.search-field').select();
2869			desktopSeachHasFocus($);
2870		}else{
2871			$('header.page-header').removeClass('search-open');
2872		}
2873
2874	});
2875
2876	// add/remove class if the search field has focus
2877	$('.search-field').focusin(function(){
2878		desktopSeachHasFocus($);
2879	});
2880	$('.search-field').focusout(function(){
2881		desktopSeachHasFocus($);
2882	});
2883
2884}	// end toggleDesktopSearch()
2885
2886function closeNotificationBar($){
2887
2888	viewport = updateViewportDimensions();
2889
2890	$('.notification-alert-bar .notification-close').on('click', function(evt){
2891		evt.preventDefault();
2892
2893		// console.log('click notification-close');
2894		$('.notification-alert-bar').fadeOut( function(){
2895			$('header.page-header').removeClass('notification-bar-one');
2896			$('header.page-header').removeClass('notification-bar-two');
2897			$('header.page-header').addClass('notification-bar-off');
2898
2899			if( viewport.width <= 768 ){
2900				$('#container').css('margin-top', 0);
2901			}else{
2902				$('#container').css('margin-top', 0);
2903				$('#header.page-header').css('top', 0);
2904			}
2905
2906			// get the hashval so we have a cookiename
2907			var cookie_val = {};
2908			cookie_val['hashval'] = $('.notification-alert-bar').attr('data-message-hash');
2909			setCookie(cookie_val['hashval'], true, 1);
2910		});
2911
2912	});
2913
2914}	// end closeNotificationBar()
2915
2916function closeCookiePolicyBar($){
2917
2918	const closeButton = document.getElementById("close-button");
2919	const cookieBar = document.getElementById("cookie-bar");
2920
2921	let site_id = 'amhsCookiesAccepted';
2922	// which site?
2923	switch(true){
2924
2925		case( $('body').hasClass('site-id-3') ):
2926			site_id = 'amcCookiesAccepted';
2927			break;
2928
2929		default:
2930			site_id = site_id;
2931			break;
2932
2933	}
2934	
2935	closeButton.addEventListener("click", function() {
2936		// Set a cookie here
2937		var date = new Date();
2938		date.setTime(date.getTime() + (24 * 60 * 60 * 1000)); // 24 hours
2939		var expires = "expires=" + date.toUTCString();
2940		document.cookie = site_id+"=true; " + expires + "; path=/";	// Adjust expires and path as needed
2941	
2942		// Hide the cookie bar after setting the cookie
2943		cookieBar.style.display = "none";
2944	});
2945	
2946	// Check if cookie exists to hide the bar initially
2947	if (getCookie(site_id)) {
2948	  cookieBar.style.display = "none";
2949	}
2950
2951}	// end closeCookiePolicyBar()
2952
2953/**
2954 * Fire the tabs in the page
2955 * Source (based on): https://www.w3schools.com/howto/howto_js_tabs.asp
2956 */
2957function fireTabbedContent($){
2958
2959	$('.tab-row').on('click', 'button', function(evt){
2960		evt.preventDefault();
2961		
2962		// Declare all variables
2963		var i, tabcontent, tablinks, tabName;
2964
2965		tabName = $(this).attr('data-tab');
2966
2967		// if this is the "Conditions / A-to-Z" tab, show or hide it
2968		if( tabName == 'tab-AtoZ' ){
2969			// Do stuff
2970			// console.log('tab-2 is checked');
2971			$('.a-to-z-bar').removeClass('hide');
2972		}else{
2973			// console.log('tab-2 is unchecked');
2974			$('.a-to-z-bar').addClass('hide');
2975		}
2976
2977		// Get all elements with class="tabcontent" and hide them
2978		tabcontent = document.getElementsByClassName("tabcontent");
2979		for (i = 0; i < tabcontent.length; i++) {
2980			tabcontent[i].className = tabcontent[i].className.replace(" active", "");
2981		}
2982	  
2983		// Get all elements with class="tablinks" and remove the class "active"
2984		tablinks = document.getElementsByClassName("tablinks");
2985		for (i = 0; i < tablinks.length; i++) {
2986			tablinks[i].className = tablinks[i].className.replace(" active", "");
2987		}
2988	  
2989		// Show the current tab, and add an "active" class to the button that opened the tab
2990		document.getElementById(tabName).className += ' active';
2991		evt.currentTarget.className += " active";
2992
2993	});
2994
2995}	// end fireTabbedContent()
2996
2997function setCookie(cname, cvalue, exdays, explict_date = false) {
2998	const d = new Date();
2999	d.setTime(d.getTime() + (exdays*24*60*60*1000));
3000	let expires = d.toUTCString();
3001	cvalue['expires']	= expires;
3002	document.cookie = cname + "=" + cvalue + ";expires=" + expires + ";path=/";
3003}
3004
3005function getCookie(cname) {
3006	let name = cname + "=";
3007	let decodedCookie = decodeURIComponent(document.cookie);
3008	let ca = decodedCookie.split(';');
3009	for(let i = 0; i <ca.length; i++) {
3010		let c = ca[i];
3011		while (c.charAt(0) == ' ') {
3012			c = c.substring(1);
3013		}
3014		if (c.indexOf(name) == 0) {
3015			return c.substring(name.length, c.length);
3016		}
3017	}
3018	return "";
3019}
3020
3021/**
3022 * Example - not actually used here
3023 */
3024function checkCookie() {
3025	let username = getCookie("username");
3026	if (username != "") {
3027		alert("Welcome again " + username);
3028	} else {
3029		username = prompt("Please enter your name:", "");
3030		if (username != "" && username != null) {
3031			setCookie("username", username, 365);
3032		}
3033	}
3034}
3035
3036// function addStateToTabs($){
3037
3038// 	$('.tabbed-content').on('click', '.tablinks', function(){
3039
3040// 		// get the data-tab values
3041// 		window.location.href.replace(window.location.hash, '');
3042// 		let targetTab = $(this).attr('data-tab');
3043// 		console.log('targetTab', targetTab);
3044// 		history.replaceState( { tab: targetTab }, targetTab, window.location+'#'+targetTab );
3045// 		// window.location.hash = targetTab;
3046
3047// 	});
3048
3049// }	// end addStateToTabs()
3050
3051function deeplinkToTab($){
3052
3053	// look to see if the link has a hash, and if it is something on this same page, scroll to it
3054
3055	/* Allow a hashtag to be passed in the URL so any tab can be loaded directly */
3056	// if( location.hash.length > 4 && location.hash.substr(0,5) == '#tab-' ){
3057	// 	var tab = location.hash.replace('#', '');
3058	// 	$('.tabbed-content .tab-row button').each(function(i){
3059	// 		if( $(this).attr('data-tab') == tab ){
3060	// 			$(this).trigger('click');
3061	// 		}
3062	// 	});
3063	// }
3064
3065}	// end deeplinkToTab()
3066
3067function intToMonth(int){
3068
3069	var month;
3070	switch(true){
3071
3072		case( int == 1 ):
3073			month = 'February';
3074			break;
3075
3076		case( int == 2 ):
3077			month = 'March';
3078			break;
3079
3080		case( int == 3 ):
3081			month = 'April';
3082			break;
3083
3084		case( int == 4 ):
3085			month = 'May';
3086			break;
3087
3088		case( int == 5 ):
3089			month = 'June';
3090			break;
3091
3092		case( int == 6 ):
3093			month = 'July';
3094			break;
3095
3096		case( int == 7 ):
3097			month = 'August';
3098			break;
3099
3100		case( int == 8 ):
3101			month = 'September';
3102			break;
3103
3104		case( int == 9 ):
3105			month = 'October';
3106			break;
3107
3108		case( int == 10 ):
3109			month = 'November';
3110			break;
3111
3112		case( int == 11 ):
3113			month = 'December';
3114			break;
3115
3116		default:
3117			month = 'January';
3118			break;
3119
3120	}	// end switch()
3121
3122	return month;
3123
3124}	// end intToMonth()
3125
3126function toggleMobileShowHideFilters($){
3127
3128	$('.filter-buttons').on('click', '#show-hide', function(){
3129
3130		// does the "left-panel" container have the "filters-hide" class
3131		let hideFilters = $('.left-panel').hasClass('filters-hide');
3132		if(hideFilters){
3133			$('.left-panel').removeClass('filters-hide');
3134		}else{
3135			$('.left-panel').addClass('filters-hide');
3136		}
3137
3138	});
3139
3140}	// end toggleMobileShowHideFilters()
3141
3142function accordionTabTopOffsets($){
3143
3144	$('.accordion .tab').each(function(){
3145		$(this).find('.position-block').remove();
3146		$top = $(this).offset().top;
3147		$(this).attr('data-top-offset', $top);
3148		// $(this).css({ 'position': 'relative' });
3149		// $(this).prepend('<div class="position-block" style="position: absolute; top: 0; left: 0;">top: '+$top+'</div>');
3150	});
3151
3152}	// end accordionTabTopOffsets()
3153
3154function tableContentLinks($){
3155
3156	viewport = updateViewportDimensions();
3157	accordionTabTopOffsets($);
3158
3159	$('.table-content').on('click', 'a[href^="#"]', function(evt){
3160		evt.preventDefault();
3161
3162		// console.log('viewport', viewport);
3163		var href = $(this).attr('href');
3164		// console.log('href',href);
3165		var target = $(href);
3166		// console.log('target',target);
3167
3168		// how tall the open tab, and then subtract from the offset
3169		var tabH = 0;
3170		var openTab = $('.accordion input[type="checkbox"]:checked');
3171		// console.log('openTab', openTab);
3172		if( typeof openTab !== 'undefined' && openTab.length > 0 ) tabH = openTab.siblings('.tab-content').outerHeight();
3173		// console.log('tabH', tabH);
3174
3175		if( target.length > 0 ){
3176			// $(this).parents('.tab').addClass('clicked-to-anchor');
3177			// console.log('THIS PARENT DIV - YYYYYYYYYY', $(this).parents('.tab'));
3178			// console.log('target.offset()', target.offset());
3179
3180			// $top = parseInt( target.offset().top );
3181			// console.log('$top', $top);
3182			// $top_adjust = parseInt( $top - 125 );
3183			// console.log('$top_adjust', $top_adjust);
3184			
3185			$top = parseInt( target.attr('data-top-offset') );
3186			// console.log('$top', $top);
3187
3188			switch(true){
3189
3190				case( viewport.width < 768 ):
3191					$top_adjust = 5;
3192					break;
3193
3194				default:
3195					$top_adjust = 135;
3196					break;
3197
3198			}
3199
3200			// console.log('$top_adjust', $top_adjust);
3201			$top_total = parseInt( $top - $top_adjust );
3202			// console.log('$top_total', $top_total);
3203
3204			$("html, body").animate({ scrollTop: $top_total }, "slow");
3205			target.find('label').trigger('click');
3206		}
3207
3208		// $("html, body").animate({ scrollTop: parseInt( $(this).offset().top - 125 - tabH ) }, "slow");
3209		// $($(this).attr('href')).find('label').trigger('click');
3210
3211		// $('.table-content table').removeAttr('id');
3212		$('.back-to-table').remove();
3213		// add a link back to the table when the accordion is open
3214		var launchTableID = $(this).closest('table').attr('id');
3215		$(this).closest('table').addClass('launch-table');
3216		var accordionOpen = $('.accordion input[type="checkbox"]:checked');
3217		if( typeof accordionOpen !== 'undefined' && accordionOpen.length > 0 ){
3218			accordionOpen.siblings('.tab-content').find('.back-to-table').remove();
3219			accordionOpen.siblings('.tab-content').prepend('<div class="back-to-table"><a href="#'+launchTableID+'">Back to Table</a></div>');
3220		}
3221
3222	});
3223
3224	$('body').on('click', '.back-to-table a', function(evt){
3225		evt.preventDefault();
3226		// Get ID from element with .launch-table
3227		var launchTableID = $('.launch-table').attr('id');
3228		var launchTableOffset = $('#'+launchTableID).offset().top;
3229		// console.log('launchTableOffset', launchTableOffset);
3230		$("html, body").animate({ scrollTop: parseInt( launchTableOffset - 115 ) }, "slow");
3231		$(this).closest('.tab').find('label').trigger('click');
3232		$('.launch-table').removeClass('launch-table');
3233		$('.back-to-table').remove();
3234	});
3235
3236}	// end tableContentLinks()
3237
3238function autoFitFontInContainer($){
3239
3240	$('.splide__slide').find('h2.slide-title').each(function(i){
3241
3242		var container_w = $(this).width();
3243		var content_w = $(this).find('span').width();
3244
3245		if( content_w > container_w ){
3246			var font_size = $(this).css('font-size');
3247			updateFixTextSize($, $(this).find('span'), 24, content_w, container_w, 0);
3248		}
3249
3250
3251	});
3252
3253}	// end autoFitFontInContainer()
3254
3255/**
3256 * $ -- jQuery
3257 * element -- jQuery Element we are working with
3258 * fontsize -- starting font-site, some as what is in the design or larger
3259 * self -- width in pixels of the element
3260 * parent -- width in pixels of the parent container we want to be inside
3261 * count -- limit for how many self-calls to the function can be made
3262 */
3263function updateFixTextSize($, element, fontsize, self, parent, count){
3264
3265	element = ( !element ) ? null : element;
3266	fontsize = ( !fontsize ) ? 50 : fontsize;
3267	self = ( !self ) ? 0 : self;
3268	parent = ( !parent ) ? 0 : parent;
3269	count = ( !count ) ? 0 : count;
3270
3271	if( count > 50 ){	// this is so we don't end up an infinate loop!
3272		return false;
3273	}
3274
3275	if( self > parent ){
3276
3277		/*
3278		console.log('=== COUNT '+count+' ==============================================');
3279		console.log('element',element.html());
3280		console.log('fontsize',fontsize);
3281		console.log('self',self);
3282		console.log('parent',parent);
3283		*/
3284
3285		var fontsize = parseInt( fontsize - 1 );
3286
3287		element.css({
3288			'font-size': fontsize+'px',
3289			'line-height': 'normal'
3290		});
3291
3292		count++;
3293
3294		self = element.width();
3295		updateFixTextSize($, element, fontsize, self, parent, count);
3296
3297	}
3298
3299	return false;
3300
3301}	// end updateFixTextSize()
3302
3303function moveAndTriggerModals($){
3304	// move each modal that is defined to the bottom of the BODY
3305	$('.modal').each(function(){
3306		var $isMobile = isMobileDevice();
3307		// console.log('$isMobile', $isMobile);
3308		var $modal = $(this);
3309		if($isMobile){
3310			$modal.remove();
3311		}else{
3312			$modal.appendTo(document.body);
3313		}
3314	});
3315	$('.model-open').on('click', function(evt){
3316		evt.preventDefault();
3317		// get the data-modal-id
3318		var $modalID = $(this).attr('data-modal-id');
3319		$('#'+$modalID).addClass('open');
3320	});
3321	$('.modal-close').on('click', function(){
3322		$('.modal').removeClass('open');
3323	});
3324}	// end moveAndTriggerModals()
3325
3326function isMobileDevice(){
3327	const isMobileDevice = /Mobi/i.test(window.navigator.userAgent)
3328	return isMobileDevice;
3329}	// end isMobileDevice()
3330
3331function hashInAddressBar($){
3332
3333	// is conditions page?
3334	var isConditions = $('body').hasClass('care-treatment');
3335
3336	if( window.location.hash ){
3337		let hash = window.location.hash.replace('#', '');
3338		let button = 'button[data-tab="'+hash+'"]';
3339		// console.log('button', button);
3340		let tab = $(button);
3341		if(tab.length > 0){
3342			$(tab).trigger('click');
3343		}
3344	}
3345
3346	// // do this if on the "Care & Treatment" (Conditions) page
3347	// if(isConditions){
3348	// 	console.log('isConditions', isConditions);
3349	// 	// active tab
3350	// 	var activeTab = $('.tabbed-content button.active').attr('data-tab');
3351	// 	if( 'tab-AtoZ' != activeTab ){
3352	// 		console.log('activeTab', activeTab);
3353	// 		$('a[href~="#tab-AtoZ"]').on('click', function(evt){
3354	// 			evt.preventDefault();
3355	// 			console.log('clicked');
3356	// 			$(this).trigger('click');			
3357	// 		});
3358	// 	}
3359		
3360	// }
3361
3362}	// end hashInAddressBar()
3363
3364function algoliaSearchHelpers($){
3365
3366	$('#refinement-specialties').on('change keyup', 'input.ais-SearchBox-input', function(){
3367		let val = $(this).val();
3368		if( val.length > 0 ){
3369			$('#refinement-specialties .ais-RefinementList-list').addClass('searching');
3370		}else{
3371			$('#refinement-specialties .ais-RefinementList-list').removeClass('searching');
3372		}
3373	}).keypress(function(event) {
3374		// doing this as there is usability issues with Algolia Search and "enter" key
3375        if (event.keyCode == 13) {
3376            event.preventDefault();
3377        }
3378    });
3379
3380	$('#refinement-specialties').on('click', '.ais-SearchBox-reset', function(){
3381		let hasClass = $('#refinement-specialties .ais-RefinementList-list').hasClass('searching');
3382		if( hasClass ){
3383			$('#refinement-specialties .ais-RefinementList-list').removeClass('searching');
3384		}
3385	});
3386
3387	$('#refinement-specialties').on('click', '.ais-RefinementList-item', function(){
3388		let hasClass = $('#refinement-specialties .ais-RefinementList-list').hasClass('searching');
3389		if( hasClass ){
3390			$('#refinement-specialties .ais-RefinementList-list').removeClass('searching');
3391		}
3392	});
3393
3394    $('#refinement-locations').on('change keyup', 'input.ais-SearchBox-input', function(){
3395        let val = $(this).val();
3396        if( val.length > 0 ){
3397            $('#refinement-locations .ais-RefinementList-list').addClass('searching');
3398        }else{
3399            $('#refinement-locations .ais-RefinementList-list').removeClass('searching');
3400        }
3401    }).keypress(function(event) {
3402        // doing this as there is usability issues with Algolia Search and "enter" key
3403        if (event.keyCode == 13) {
3404            event.preventDefault();
3405        }
3406    });
3407
3408    $('#refinement-locations').on('click', '.ais-SearchBox-reset', function(){
3409        let hasClass = $('#refinement-locations .ais-RefinementList-list').hasClass('searching');
3410        if( hasClass ){
3411            $('#refinement-locations .ais-RefinementList-list').removeClass('searching');
3412        }
3413    });
3414
3415    $('#refinement-locations').on('click', '.ais-RefinementList-item', function(){
3416        let hasClass = $('#refinement-locations .ais-RefinementList-list').hasClass('searching');
3417        if( hasClass ){
3418            $('#refinement-locations .ais-RefinementList-list').removeClass('searching');
3419        }
3420    });
3421
3422    $('#refinement-languages').on('change keyup', 'input.ais-SearchBox-input', function(){
3423        let val = $(this).val();
3424        if( val.length > 0 ){
3425            $('#refinement-languages .ais-RefinementList-list').addClass('searching');
3426        }else{
3427            $('#refinement-languages .ais-RefinementList-list').removeClass('searching');
3428        }
3429    }).keypress(function(event) {
3430        // doing this as there is usability issues with Algolia Search and "enter" key
3431        if (event.keyCode == 13) {
3432            event.preventDefault();
3433        }
3434    });
3435
3436    $('#refinement-languages').on('click', '.ais-SearchBox-reset', function(){
3437        let hasClass = $('#refinement-languages .ais-RefinementList-list').hasClass('searching');
3438        if( hasClass ){
3439            $('#refinement-languages .ais-RefinementList-list').removeClass('searching');
3440        }
3441    });
3442
3443    $('#refinement-languages').on('click', '.ais-RefinementList-item', function(){
3444        let hasClass = $('#refinement-languages .ais-RefinementList-list').hasClass('searching');
3445        if( hasClass ){
3446            $('#refinement-languages .ais-RefinementList-list').removeClass('searching');
3447        }
3448    });
3449
3450	$('#autocomplete').on('change keyup', '.aa-Input', function(){
3451		// do nothing here
3452	}).keypress(function(event){
3453        // doing this as there is usability issues with Algolia Search and "enter" key
3454        if (event.keyCode == 13) {
3455            event.preventDefault();
3456        }
3457	});
3458
3459}	// end sepcialtiesSearchVal()
3460
3461function mobileReturnToFilters($){
3462
3463	$('a[href="#filters"]').on('click', function(evt){
3464		evt.preventDefault();
3465		$("html, body").animate({ scrollTop: $("#top").offset().top }, "slow");
3466	});
3467
3468}	// end mobileReturnToFilters()
3469
3470function a11y_fixes($){
3471
3472	console.log('--- A11Y Fixes -----------------------------');
3473
3474	// fixes the "empty form button" in the Algolia AutoComplete
3475	$('button.aa-ClearButton').append('<span>Clear search</span>');
3476	$('button.aa-SubmitButton').append('<span>Begin search</span>');
3477
3478	// fixes the "missing label" in the Algolia InstantSearch with an "aria-label" on the form input
3479	$('.ais-SearchBox-input').each(function(){
3480		$(this).attr('aria-label', $(this).attr('placeholder'));
3481	});
3482
3483}	// end a11y_fixes()
3484
3485function mobileSidebarPanel($){
3486
3487	viewport = updateViewportDimensions();
3488
3489	$el = $('.sidebar__inner');
3490
3491	if( $el.length == 1 && viewport.width < 768 ){
3492		// console.log('fire mobileSidebarPanel()');
3493
3494		$el.detach();
3495
3496		var panelContent = '' +
3497			'<div class="sidebar-mobile">' +
3498				'<a href="#open-mobile-panel" class="panel-header">';
3499
3500		var panelHeaderText = '';
3501		var panelBodyHeader = '';
3502		switch(true){
3503
3504			case( $('body').hasClass('single-specialties') ):
3505				panelHeaderText = 'Providers, Locations & More';
3506				break;
3507
3508			case( $('body').hasClass('single-physicians') ):
3509				panelHeaderText = 'Physician Bio Navigation';
3510				break;
3511
3512			case( $('body').hasClass('single-offices') ):
3513				panelHeaderText = 'Location Info Navigation';
3514				break;
3515
3516			default:
3517				panelHeaderText = 'Section Navigation';
3518				break;
3519			
3520		}	// end switch()
3521
3522		panelContent += '' +
3523				'<span>' +panelHeaderText+ '</span>';
3524
3525		panelContent += '' +
3526				'<svg width="128" viewBox="0 0 32 32" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"><path d="M4.219 10.781L2.78 12.22l12.5 12.5l.719.687l.719-.687l12.5-12.5l-1.438-1.438L16 22.562z" fill="currentColor"/></svg>' +
3527			'</a>';
3528
3529		if( panelBodyHeader && panelBodyHeader.length > 0 ){
3530			panelContent += '' +
3531				'<style>' +
3532				'body .sidebar-mobile .panel-body ul.menu.jump-menu::before { content: \''+panelBodyHeader+'\';}' +
3533				'</style>';
3534		}
3535
3536		panelContent += '' +
3537			'<div class="panel-body">' +
3538			'</div>' +
3539		'</div>';
3540
3541		$('.page-content').before(panelContent);
3542		$('body .sidebar-mobile .panel-body').append($el);
3543
3544		$('body').on('click', '.sidebar-mobile a.panel-header', function(evt){
3545			evt.preventDefault();
3546			var isOpen = $('.sidebar-mobile').hasClass('open');
3547			if( isOpen ){
3548				$('body').removeClass('sidebar-mobile-open');
3549				$('.sidebar-mobile').removeClass('open');
3550			}else{
3551				$('.sidebar-mobile').addClass('open');
3552				$('body').addClass('sidebar-mobile-open');
3553			}
3554		});
3555
3556		$('body').on('click', '.sidebar-mobile ul.menu.jump-menu', function(evt){
3557			var isOpen = $('.sidebar-mobile').hasClass('open');
3558			if( isOpen ){
3559				$('body').removeClass('sidebar-mobile-open');
3560				$('.sidebar-mobile').removeClass('open');
3561			}
3562		});
3563
3564	}
3565
3566}	// end mobileSidebarPanel()
3567
3568function hasNotificationAdjustHeaderAndContainer($){
3569
3570	viewport = updateViewportDimensions();
3571
3572	// is there a Notification Bar?
3573	$hasNotificationBar = $('.notification-alert-bar');
3574	// if( $hasNotificationBar.length > 0 ){
3575		$notificationBar_H = $hasNotificationBar.innerHeight();
3576		$notificationBar_H = ( !$notificationBar_H ? 0 : $notificationBar_H );
3577
3578		$headerBar_H = $('#header').height();
3579
3580		$adminBar_H = $('#wpadminbar').height();
3581		$adminBar_H = ( !$adminBar_H ? 0 : $adminBar_H );
3582		// console.log('$adminBar_H', $adminBar_H);
3583
3584		// $notificationBar_H = ( $notificationBar_H < 50 ? 50 : $notificationBar_H );
3585		// console.log('$notificationBar_H >>>> ', $notificationBar_H);
3586		// console.log('$headerBar_H >>>> ', $headerBar_H);
3587		// if( $notificationBar_H > 0 && $headerBar_H > 0 ){
3588
3589			$container_H = $notificationBar_H;
3590			// if viewport <= 768
3591			if( viewport.width <= 768 ){
3592				$container_H = $notificationBar_H + $headerBar_H;
3593				$container_H = ( $container_H == $headerBar_H ? 0 : $container_H );
3594			}else{
3595				$container_H = $container_H + $headerBar_H;
3596			}
3597
3598			console.log('adminBar_H:', $adminBar_H);
3599			console.log('notificationBar_H:', $notificationBar_H);
3600			console.log('headerBar_H:', $headerBar_H);
3601			console.log('container_H:', $container_H);
3602
3603			// $headerBar_H = $notificationBar_H + $adminBar_H;
3604			$headerBar_H = $notificationBar_H;
3605
3606			$('#container').css('margin-top', $container_H+'px');
3607			$('#header').css('top', ($headerBar_H+$adminBar_H)+'px');
3608			$hasNotificationBar.css('top', '-'+$notificationBar_H+'px').show();
3609		// }
3610	// }
3611
3612}	// end hasNotificationAdjustHeaderAndContainer()
3613
3614/**
3615 * look at the page content and if there are .our-people-section elements, build a jump link list
3616 */
3617function peopleJumpLinksBuilder($){
3618
3619	var $peopleSections = $('.our-people-section');
3620	if( $peopleSections.length > 1 ){
3621		var $jumpLinks = '<ul class="jump-links">';
3622		$peopleSections.each(function(i){
3623			var $title = $(this).find('h2.title').text();
3624			var $id = $(this).attr('id');
3625			var counter = i + 1; // add 1 to the index to start the counter at 1 instead of 0
3626			$jumpLinks += '<li '+( counter == 1 ? 'class="active"' : '' )+'><a href="#'+$id+'">'+$title+'</a></li>';
3627		});
3628		$jumpLinks += '</ul>';
3629		$('.people-jump-links .wrap').html($jumpLinks);
3630	}
3631
3632	/*
3633	// if the page has .fc-type-our-people-choices, build the jump links and add inside .sticky bar
3634	var $peopleChoices = $('.fc-type-our-people-choices');
3635	if( $peopleChoices.length > 0 ){
3636
3637		// add the sticky bar with .sticky class at the start of the main#content element
3638		var $stickyBar = '<div class="sticky"><div class="people-jump-links full-width"><div class="wrap"></div></div></div>';
3639		// if there is .hero or .breadcrumbs add after those or just add at the start of #content
3640		var $hero = $('.hero');
3641		var $breadcrumbs = $('.breadcrumbs');
3642
3643		switch(true){
3644
3645			case( $hero.length > 0 ):
3646				// $hero.after($stickyBar);
3647				$('#content').prepend($stickyBar);
3648				break;
3649
3650			case( $breadcrumbs.length > 0 ):
3651				$breadcrumbs.after($stickyBar);
3652				break;
3653
3654			default:
3655				$('#content').prepend($stickyBar);
3656				break;
3657
3658		}	// end switch()
3659
3660		var $jumpLinks = '<ul class="jump-links">';
3661		$peopleChoices.each(function(i){
3662			var $title = $(this).find('h2.title').text();
3663			var $id = $(this).attr('id');
3664			var counter = i + 1; // add 1 to the index to start the counter at 1 instead of 0
3665			$jumpLinks += '<li '+( counter == 1 ? 'class="active"' : '' )+'><a href="#'+$id+'">'+$title+'</a></li>';
3666		});
3667		$jumpLinks += '</ul>';
3668		$('.people-jump-links .wrap').html($jumpLinks);
3669	}
3670	*/
3671
3672	$('.people-jump-links').on('click', 'a', function(evt){
3673		evt.preventDefault();
3674		// if window width <= 768, subtract 50 from the scroll position
3675		var $additionalScroll = ( viewport.width <= 768 ? 75 : 175 );
3676		// scroll to the clicked item
3677		var $href = $(this).attr('href');
3678		$("html, body").animate({ scrollTop: $($href).offset().top - $additionalScroll }, "slow");
3679		// change the active class to the clicked item
3680		$('.people-jump-links li').removeClass('active');
3681		$(this).parent().addClass('active');
3682	});
3683
3684	// update the active class based on the scroll position
3685	$(window).on('scroll', function(){
3686		var $scrollPos = $(document).scrollTop();
3687		$peopleSections.each(function(i){
3688			var $id = $(this).attr('id');
3689			var $top = $(this).offset().top - 200;
3690			if( $scrollPos >= $top ){
3691				$('.people-jump-links li').removeClass('active');
3692				$('.people-jump-links li').eq(i).addClass('active');
3693			}
3694		});
3695	});
3696
3697}	// end peopleJumpLinksBuilder()
3698
3699function anchorClickToID($){
3700
3701	$('.entry-content a[href^="#"]:not([href="#modal-open"])').on('click', function(evt){
3702		evt.preventDefault();
3703		var $href = $(this).attr('href');
3704		var offset = ( viewport.width <= 768 ? 75 : 175 );
3705		$("html, body").animate({ scrollTop: $($href).offset().top - offset }, "slow");
3706	});
3707
3708}	// end anchorClickToID()
3709
3710function setupModalOpeners($){
3711
3712	// console.log('fire setupModalOpeners()');
3713
3714	const $modalOpeners = $('[data-modal-id]');
3715
3716	$modalOpeners.each(function(){
3717		const $mo = $(this);
3718		$mo.on('click', function(evt){
3719			evt.preventDefault();
3720			const str_id = $mo.attr('data-modal-id');
3721			$('#'+str_id).addClass('open');
3722		});
3723
3724		$('.modal-close').on('click', function(){
3725			$('.modal').removeClass('open');
3726		});
3727
3728	});
3729
3730}	// end setupModalOpeners()
3731
3732/**
3733 * GLOBAL VARS
3734 */
3735var sidebar;
3736
3737/**
3738 * Has jQuery Loaded?  If so, do the things!
3739 */
3740(function($) {
3741	"use strict";
3742	
3743	// Source: https://github.com/algolia/search-insights.js
3744	// Source: https://www.jsdelivr.com/package/npm/search-insights
3745	var ALGOLIA_INSIGHTS_SRC = "https://cdn.jsdelivr.net/npm/[email protected]";
3746	!function(e,a,t,n,s,i,c){
3747		e.AlgoliaAnalyticsObject=s,e[s]=e[s]||function(){
3748			(e[s].queue=e[s].queue||[]).push(arguments)
3749		},
3750		i=a.createElement(t),
3751		c=a.getElementsByTagName(t)[0],
3752		i.async=1,
3753		i.src=n,
3754		c.parentNode.insertBefore(i,c)
3755	}(window,document,"script",ALGOLIA_INSIGHTS_SRC,"aa");
3756	// const aa = import("search-insights");
3757
3758	aa('init', {
3759		appId: SEARCH_APP,
3760		apiKey: SEARCH_KEY,
3761		useCookie: true
3762	});
3763	// console.log('aa',aa);
3764	console.log('window', window);
3765	// ----------------------------------------------------------------------
3766
3767	viewport = updateViewportDimensions();
3768
3769	// remove <p> tags around images everywhere
3770	$('p > img').unwrap();
3771	
3772	fireTabbedContent($);
3773	openMobileNavPanel($);
3774
3775	newsTeaserShowMorePosts($);
3776	closeAccordionTabs($);
3777
3778	jumpToFromSidebarNav($);
3779	fireSplideJS($);
3780
3781	fireVenobox2();
3782	conditionsAToZShowHideItems($);
3783
3784	siblingNavToggle($);
3785	backToTop($);
3786
3787	closeNotificationBar($);
3788	closeCookiePolicyBar($);
3789	hashInAddressBar($);
3790
3791	algoliaSearchHelpers($);
3792	mobileReturnToFilters($);
3793
3794	deeplinkToTab($);
3795	toggleMobileShowHideFilters($);
3796
3797	tableContentLinks($);
3798	autoFitFontInContainer($);
3799
3800	peopleJumpLinksBuilder($);
3801	// addStateToTabs($);
3802
3803	// fire if the viewport is at "desktop" size of bigger
3804	if(viewport.width >= 1180){
3805		toggleDesktopSearch($);
3806	}
3807
3808	window.onresize = (event) => {
3809		viewport = updateViewportDimensions();
3810		// code here on resize
3811		accordionTabTopOffsets($);
3812		heroAccordion($, viewport);
3813		fireToolTip($);
3814		hasNotificationAdjustHeaderAndContainer($);
3815	};
3816
3817	// Store the initial scroll position
3818	var lastScrollTop = 0;
3819
3820	// Add a scroll event listener
3821	window.addEventListener("scroll", function() {
3822		// Get the current scroll position
3823		var currentScrollTop = window.pageYOffset || document.documentElement.scrollTop;
3824		var scrolling = 'down';
3825
3826		// Compare the current scroll position with the last one
3827		if(currentScrollTop > lastScrollTop){
3828			$('body').attr('data-scrolling', 'down');
3829		}else{
3830			$('body').attr('data-scrolling', 'up');
3831			var scrolling = 'up';
3832		}
3833
3834		switch(true){
3835
3836			case( currentScrollTop > 250 && scrolling == 'down' ):
3837				$('body').addClass('hasScroll-show');
3838				break;
3839
3840			case( currentScrollTop > 150 && scrolling == 'down' ):
3841				$('body').addClass('hasScroll-hide');
3842				break;
3843
3844			case( currentScrollTop > 0 && scrolling == 'down' ):
3845				$('body').addClass('hasScroll');
3846				break;
3847
3848			case( currentScrollTop > 0 && scrolling == 'up' ):
3849				$('body').addClass('hasScroll');
3850				$('body').removeClass('hasScroll-hide');
3851				break;
3852
3853			default:
3854				$('body').removeClass('hasScroll-hide');
3855				$('body').removeClass('hasScroll-show');
3856				$('body').removeClass('hasScroll');
3857				break;
3858
3859		} // end switch()
3860
3861		// Update the last scroll position
3862		lastScrollTop = currentScrollTop;
3863	}, false);
3864
3865	window.onload = (event) => {
3866
3867		console.log('WINDOW LOADED');
3868
3869		// code here on load complete
3870		megaMenuCurrentParentClass($);
3871		showMobileCurrentPageAncestor($);
3872
3873		duplicateFooterPhoneSocialsToMobileMenu($);
3874		heroAccordion($, viewport);
3875
3876		fireToolTip($);
3877		algoliaPassSearchToOtherIndices($);
3878
3879		mobileSidebarPanel($);
3880		hasNotificationAdjustHeaderAndContainer($);
3881
3882		anchorClickToID($);
3883		setupModalOpeners($);
3884
3885		function scriptsHhasDataInstantDone(){
3886			var data_instant_done = jQuery('body').attr('data-instant-done');
3887			if( !data_instant_done ){
3888				setTimeout(function() {scriptsHhasDataInstantDone()}, 1000);
3889			}else{
3890				// console.log('before algoliaAutocomplete()');
3891				amcAlgoliaAutocomplete($);
3892				amcAlgoliaInstantSearch($);
3893			}
3894		}	// end scriptsHhasDataInstantDone()
3895		scriptsHhasDataInstantDone();
3896
3897		let aa_search = new URL(window.location).searchParams.get("search");
3898		// console.log('aa_search', aa_search);
3899		if( aa_search ){
3900			waitForFinalEvent( function() {
3901				// console.log('waitForFinalEvent', aa_search);
3902				$('body .autocomplete .aa-Input').trigger('focus');
3903
3904			}, 1000, "your-function-identifier-string");
3905		}
3906
3907		waitForFinalEvent( function() {
3908			// console.log('waitForFinalEvent - standalone');
3909			// fire off some things that help with a11y
3910			a11y_fixes($);
3911			refinementMenuClickHelper($);
3912		}, 1000, "some-function-identifier-string");
3913
3914	};
3915
3916})(jQuery);

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.