 /*
	Dynamic Javascript template - nac-cna.ca

	n.b. all segments of the URL are available, 
	however they are offset by 1.
	(ie "" is considered segment_2's value)
*/

// GLOBAL FEEDBACK WIDGET SCRIPT
	
$(document).ready(function(){
	if ($('#feedbackWidget').length !== 0){
		$('.button-input-group input').each(function(){
			$(this).siblings('label').hide();
			$(this).after('<button class="bttn bttn_submit white" value="'+$(this).val()+'">'+$(this).next("label").find(".label-text").text()+'</button>').hide();

			// attach an event handler to the button
			$(this).next('button').on('click',function(e){
				e.preventDefault();
				$(this).prev('input').prop("checked", true);
				//alert($(this).text());

				switch($(this).val()){
					case "no":
				        $.ajax({ 
				            url         : "https://nac-cna.ca/en/includes/feedback-widget-email-no",
				            success : function(data){
				                log(data); // do what you like with the response
				                var feedbackWidgetNo = data;
						        //log(feedbackWidgetNo);
								$('#feedbackWidget input[name=email]').val(feedbackWidgetNo);
								$('#feedbackWidget').animate({ height: '380px' }, 500);
								$('#step1 .g-recaptcha').appendTo("#step2 .g-recaptcha-centered");
								$('#step1').animate({ opacity: 0 }, 500, function(){
									//
									$(this).hide('fast');
									$('#step2').animate({ opacity: 100 }, 800 ).fadeIn();
								});
							    return false;
				            },
				            error : function(response){
				                log("Didn't work!");
				                log(response); // do what you like with the response
				            }
				        });
						break;
					default:
				        $.ajax({ 
				            url         : "https://nac-cna.ca/en/includes/feedback-widget-email-yes",
				            success : function(data){
				                //log(data); // do what you like with the response
				                var feedbackWidgetYes = data;
						        //log(feedbackWidgetYes);
								$('#feedbackWidget input[name=email]').val(feedbackWidgetYes);
								$('#feedbackWidget').trigger('valid.fndtn.abide');
							    return false;
				            },
				            error : function(response){
				                log("Didn't work!");
				                log(response); // do what you like with the response
				            }
				        });
						break;
				}
				return false;
			});
		});
		
		$('#feedbackWidget input[type=submit]').click(function(e){
			e.preventDefault();
			$('#feedbackWidget').submit();
			//$('#feedbackWidget').trigger('valid.fndtn.abide');
		});

		$('#feedbackWidget').on('valid.fndtn.abide', function (e) {
	        e.preventDefault();
			if( $('.g-recaptcha-response-value').length !== 0 && $('.g-recaptcha-response-value').attr('data-response') !== undefined ){
				//log('begin sending feedback');
				$('#feedbackWidget .bttn_submit').prop("disabled", true).addClass('bttn_disabled');
	        	var form = $(this);
	        	$.ajax({ 
	            	url         : form.attr('action'),
	            	type        : form.attr('method'),
	            	data        : form.serialize(), // data to be submitted
	            	success : function(response){
		            	// show our "thank you" message (queued fx)
		            	$('#feedback_form_contain').animate({ opacity: "0" }, 800 ).queue(function() {$(this).slideUp().dequeue().siblings('#feedback_form_thanks').slideDown('fast').delay(4000).slideUp();});
		
	                	//log(response); // do what you like with the response
				    	return false;
	            	},
	            	error : function(response){
	                	log("Didn't work!");
	                	log(response); // do what you like with the response
	            	},
	            	beforeSend : function(response){
	                	form.find(".bttn_submit").prop("disabled", true).addClass('bttn_disabled').after('<!-- <label class="clearfix">Please wait while it is being processed...</label> -->');
	            	}
	        	});
			}
		    return false;
	    });

	}
});
	// GLOBAL LOADING SPINNER SCRIPT
	$(document).ready(function(){
	$(".spinner").click(function () {
		$(".spinner.clicked").removeClass("clicked");
		$(this).addClass("clicked").delay(50000).queue(function () {$(this).removeClass("clicked").dequeue();});
	});
});
	
	// GLOBAL REDIRECT MODAL
	// // RENTAL TIMED TICKET REDIRECT
$(document).ready(function () {
	// Check if there's at least one link with the class .redirect_modal
	if ($('.redirect_modal').length > 0) {
		var redirectTimer;

		$('.redirect_modal').on('click', function (e) {
			e.preventDefault();
			var ticketUrl = $(this).data('ticket-url');
			var delay = 15000;
			// Clear any existing timer
			clearTimeout(redirectTimer);
			// Set the new redirect timer
			redirectTimer = setTimeout(function () {
				window.location.href = ticketUrl;
			}, delay);
		});

		$(document).on('click', '#ticketModal .close-reveal-modal', function () {clearTimeout(redirectTimer);});

		$(document).on('keyup', function (e) {
			if (e.key === "Escape") {clearTimeout(redirectTimer);}
		});

		$(document).on('closed.zf.reveal', '#ticketModal', function () {clearTimeout(redirectTimer);});

		// Cancel on body class removal of reveal-modal-open
		const bodyObserver = new MutationObserver((mutations) => {
			mutations.forEach((mutation) => {
				if (mutation.type === 'attributes' && mutation.attributeName === 'class') {
					if (!document.body.classList.contains('reveal-modal-open')) {clearTimeout(redirectTimer);}
				}
			});
		});

		bodyObserver.observe(document.body, {
			attributes: true,
			attributeFilter: ['class']
		});
	}
	});
	
	// GLOBAL language toggle modal
	$(document).ready(function () {$(".langSelect_modal_open").trigger("click");});
	
	// After Reveal initialization
	$('[data-reveal]').on('open.fndtn.reveal', function() {
		// Listen for the modal open event
		$('body').addClass('reveal-modal-open');
		$('.contentWrapper').attr('aria-hidden', 'true');
	
		// Prevent modal close on content click
		$('.reveal-modal').on('click', function (e) {
			e.stopPropagation(); // Prevent click propagation
		});
	
		// Ensure close works as expected
		$('.close-reveal-modal').on('click', function () {
			$(this).closest('.reveal-modal').foundation('reveal', 'close');
		});
		
		const modal = $(this);
	
		// Store last focus
		modal.data('previousFocus', document.activeElement);
	
		// Focus first focusable element
		setTimeout(() => {
			const firstFocusable = modal[0].querySelector('button, [href], input, [tabindex]:not([tabindex="-1"])');
			firstFocusable?.focus();
		}, 100);
	
		// Trap focus
		modal.on('keydown', function(e) {
			if (e.key === 'Tab') {
			const focusable = modal.find('button, [href], input, select, [tabindex]:not([tabindex="-1"])');
			const first = focusable[0];
			const last = focusable[focusable.length - 1];
	
			if (e.shiftKey && document.activeElement === first) {
				e.preventDefault();
				last.focus();
			} else if (!e.shiftKey && document.activeElement === last) {
				e.preventDefault();
				first.focus();
			}
			}
		});
	});
	
	// On close
	$('[data-reveal]').on('closed.fndtn.reveal', function() {
		const previousFocus = $(this).data('previousFocus');
		previousFocus?.focus();
	
		$('body').removeClass('reveal-modal-open');
		$('.contentWrapper').attr('aria-hidden', 'false');
	});
	
	//GLOBAL VIDEO MODAL
	$(document).ready(function () {
		$(".js-modal-btn:not(.channel-vimeo)").modalVideo();
		$(".js-modal-btn.channel-vimeo").modalVideo({ channel: 'vimeo' }); 
	});


// DYNAMIC SCRIPTS
	
			$(document).ready(function () {
				$(".header--info-trigger").click(function () {$('.header--image-info-content').fadeToggle('fast').delay(50).toggleClass('active');});

				if ($(".pill-hotlinks").length != 0) {
					const scrollContainer = document.querySelector('.pill-hotlinks');
					const scrollBtnLeft = document.querySelector('.scroll-btn.left');
					const scrollBtnRight = document.querySelector('.scroll-btn.right');
	
					updateScrollButtons = function() {
						var scrollLeft = scrollContainer.scrollLeft;
						var scrollWidth = scrollContainer.scrollWidth;
						var containerWidth = scrollContainer.offsetWidth;
	
						var btnLeftState = (scrollLeft > 0) ? 'block' : 'none';
						var btnRightState = (scrollLeft + containerWidth < scrollWidth) ? 'block' : 'none';
						$(scrollBtnLeft).css("display",btnLeftState);
						$(scrollBtnRight).css("display",btnRightState);
					};
	
					updateScrollButtons(); // Initial check
	
					$(scrollContainer).on('scroll', Foundation.utils.debounce(function(e){updateScrollButtons();}, 100));
	
					$(scrollBtnLeft).on('click', function () {
						scrollContainer.scrollBy({
							left: -800, // Adjust scroll value as needed
							behavior: 'smooth'
						});
					});
	
					$(scrollBtnRight).on('click', function () {
						scrollContainer.scrollBy({
							left: 800, // Adjust scroll value as needed
							behavior: 'smooth'
						});
					});
				}

				// Close element by clicking away
				$(document).click(function (e) {
					var container = $(".header--image-info-content, .header--info-trigger");
					// if the target of the click isn't the container nor a descendant of the container
					if (!container.is(e.target) && container.has(e.target).length === 0) {$('.header--image-info-content').fadeOut('fast').delay(50).removeClass('active');}
				});

				var showLiveNowCard = function(){
					// hide all .soon and .live elements
					$(".live_now_card .soon, .live_now_card .live").hide();

					const now = Math.floor(Date.now() / 1000);
					var cards = $(".live_now_card_contain .live_now_card");
					cards.each(function(){
						if ($(this).attr("data-starts-at") != null){
							// each livestream's start time
							var startTime = $(this).attr("data-starts-at");
							var endTime = $(this).attr("data-ends-at");
	
							// difference between now and its start time, in minutes
							var startOffset = Math.floor((startTime - now) / 60);
	
							//log("Event starts at: " + $(this).attr("data-starts-at"));
							//log("Event ends at: " + $(this).attr("data-ends-at"));
							//log("Current epoch: " + now);
							//log("Diff: " + startOffset);
	
							if(startOffset < 120 && startOffset > 0){
								$(".viewport-large-up").find(".live_now_card[data-starts-at='"+ startTime +"'] .soon").css("display","flex");
								$(".live_now_card[data-starts-at='"+ startTime +"'] .soon").css("display","flex");
							}	
							if(startOffset < 0 && endTime > now){
								$(".viewport-large-up").find(".live_now_card[data-starts-at='"+ startTime +"'] .live").css("display","flex");
								$(".live_now_card[data-starts-at='"+ startTime +"'] .live").css("display","flex");
							}
							if(startOffset < 120 && endTime > now){$(this).slideToggle();}
						}
					});
				};
				showLiveNowCard();

			});

			
$(document).ready(function(){
	if ( typeof $.fn.selectric !== 'undefined' && $.isFunction($.fn.selectric) ) {
		$('.selectric').selectric({
			disableOnMobile: false,
			responsive: false,
			arrowButtonMarkup: '<b class="button">&#x25be;</b>'
		});

		// bind change event to select
		$('.genre_dropdown').on('change', function () {
			var url = $(this).val(); // get selected value
			if (url) { // require a URL
				window.location = url; // redirect
			}
			return false;
		});
	}
});

			//-----------------------------------------------------------------------
//EVENT SLICK START------------------------------------------------------
//-----------------------------------------------------------------------
$(document).ready(function () {
	if ($('body').hasClass('touch-device')) {
		$('.event-slick').each(function() {
			if (!$(this).hasClass('noslide')) {
				$(this).attr('class', 'event-slick content-slider touch-horizontal-scroll');
			}
		});
	}

	if (typeof $.fn.slick !== 'undefined' && $.isFunction($.fn.slick) && !$('body').hasClass('touch-device')) {
		// Hide empty event lists
		$("#upcoming_events ul").each(function () {
			if ($(this).find("li.no-results").length !== 0) {$(this).parents(".discipline_events").hide();}
		});
		
		// Clean up and prepare sliders
		$('.event-slick').find('.event-cache-seed').remove();
		$('.event-slick').addClass('content-slider');

		// Find and setup sliders
		$('.event-slick').each(function() {
			var $slider = $(this);
			
			// Skip sliders with "noslide" class
			if ($slider.hasClass('noslide')) {
				return; // Skip this iteration
			}

			// Check if already initialized
			if ($slider.hasClass('slick-initialized')) {$slider.slick('unslick');}
			
			// Determine number of slides based on classes
			var slidesToShow = $slider.hasClass('slide-5') ? 5 : 
						($slider.hasClass('slide-4') ? 4 : 3);
			
			// Initialize slick
			$slider.slick({
				dots: true,
				infinite: false,
				slidesToShow: slidesToShow,
				slidesToScroll: slidesToShow,
				prevArrow: '<button type="button" class="svg slick-prev"><i class="fa-solid fa-caret-left"></i></button>',
				nextArrow: '<button type="button" class="svg slick-next"><i class="fa-solid fa-caret-right"></i></button>',
				responsive: [
					{
						breakpoint: 980,
						settings: {
						slidesToShow: 3.05,
						slidesToScroll: 3,
						arrows: true
						}
					},
					{
						breakpoint: 768,
						settings: {
						slidesToShow: 2.05,
						slidesToScroll: 2,
						dots: false,
						arrows: true
						}
					},
					{
						breakpoint: 481,
						settings: {
						slidesToShow: 1.05,
						slidesToScroll: 1,
						dots: false,
						arrows: true
						}
					}
				]
			});
		});
	}
});
//-----------------------------------------------------------------------
//EVENT SLICK END--------------------------------------------------------
//-----------------------------------------------------------------------
			// STORY SLIDER SLICK START
$(document).ready(function () {
	if ( typeof $.fn.slick !== 'undefined' && $.isFunction($.fn.slick) ) {
		$(".story-slider").each(function () {
			if ($(this).find("li.no-results").length !== 0) {$(this).parents(".discipline_events").hide();}
		});
	
		$('.story-slider').find('.event-cache-seed').remove();
		$('.story-slider').addClass('content-slider');
		$('.story-slider:not(.noslide)').slick({
			dots: true,
			infinite: false,
			slidesToShow: 3,
			slidesToScroll: 3,
			prevArrow: '<button type="button" class="svg slick-prev"><i class="fa-solid fa-caret-left"></i></button>',
			nextArrow: '<button type="button" class="svg slick-next"><i class="fa-solid fa-caret-right"></i></button>',
			responsive: [
				{
					breakpoint: 980,
					settings: {
						slidesToShow: 3.25,
						slidesToScroll: 3,
						arrows: true
					}
				},
				{
					breakpoint: 768,
					settings: {
						slidesToShow: 2.15,
						slidesToScroll: 1,
						dots: false,
						arrows: true
					}
				},
				{
					breakpoint: 481,
					settings: {
						slidesToShow: 1.15,
						slidesToScroll: 1,
						dots: false,
						arrows: true
					}
				}
			]
		});
	}
});
// STORY SLIDER SLICK END
			$(document).ready(function(){
	
	$( ".nac_video_list.hide_coming_soon .coming_soon" ).remove();

	if ( typeof $.fn.slick !== 'undefined' && $.isFunction($.fn.slick) ) {
		
		$('.nac_video_list.slide-4').addClass('content-slider');
		$('.nac_video_list.slide-3').addClass('content-slider');
		
		$('.nac_video_list.slide-4').slick({
			dots: true,
			infinite: false,
			slidesToShow: 4,
			slidesToScroll: 3,
			prevArrow: '<button type="button" class="svg slick-prev"><i class="fa-solid fa-caret-left"></i></button>',
			nextArrow: '<button type="button" class="svg slick-next"><i class="fa-solid fa-caret-right"></i></button>',
			responsive: [
				{
					breakpoint: 980,
					settings: {
						slidesToShow: 3.25,
						slidesToScroll: 3,
						arrows: true
					}
				},
				{
					breakpoint: 768,
					settings: {
						slidesToShow: 2.15,
						slidesToScroll: 2,
						dots: false,
						arrows: true
					}
				},
				{
					breakpoint: 481,
					settings: {
						slidesToShow: 1.25,
						slidesToScroll: 1,
						dots: false,
						arrows: true
					}
				},
			]
		});
	
		$('.nac_video_list.slide-3').slick({
			dots: true,
			infinite: false,
			slidesToShow: 3,
			slidesToScroll: 2,
			prevArrow: '<button type="button" class="svg slick-prev"><i class="fa-solid fa-caret-left"></i></button>',
			nextArrow: '<button type="button" class="svg slick-next"><i class="fa-solid fa-caret-right"></i></button>',
			responsive: [
				{
					breakpoint: 980,
					settings: {
						slidesToShow: 3.25,
						slidesToScroll: 3,
						arrows: true
					}
				},
				{
					breakpoint: 768,
					settings: {
						slidesToShow: 2.15,
						slidesToScroll: 2,
						dots: false,
						arrows: true
					}
				},
				{
					breakpoint: 481,
					settings: {
						slidesToShow: 1.15,
						slidesToScroll: 1,
						dots: false,
						arrows: true
					}
				},
			]
		});
	}
});

			//-----------------------------------------------------------------------
//----- EVENT SEARCH BOX START ------------------------------------------
//-----------------------------------------------------------------------

function filterEvents() {
	var input, filter, ul, li, obj, a, txt, i, txtValue;
	input = $("#searchInput");
	filter = input.val().toUpperCase();
	if (filter.length == 0){
		$("#eventSearch").hide();
		$('body').removeClass('search-box-active');
		return;
	} else {
		if (filter.length > 1){
			//log('length: '+filter.length);
			ul = $("#eventSearch");
			li = ul.find("li");
			for (i = 0; i < li.length; i++) {
				obj = li.eq(i);
				txtValue = obj.find(".eventSearch---item--content-wrapper").contents().text().replace(/\s+/g, " ").trim();
				//log(txtValue);
				if (txtValue.toUpperCase().indexOf(filter) > -1) {
					obj.hide(0);
					obj.addClass("display");
					obj.show(0,function(){
					obj.find('img.lazy').lazy({
							bind: "event",
                			delay: 0
						});
					});
					ul.show(0);
				} else {
					obj.hide(0);
					obj.removeClass("display");
				}
				$('body').addClass('search-box-active');
			}
			
			if (!$(".eventSearch--item").is(":visible")) {ul.show().find(".eventSearch--item.noevents").show();}
		}
	}
}

$(document).ready(function(){

		$( ".drop-down-parent" ).click(function() {
			$( this ).toggleClass( "selected" );
			$( ".drop-down-options" ).slideToggle( "fast" );
		});

		$(".eventSearchBox--link").click(function(){
			$('.eventSearch--item').removeClass('clicked');
			$(this).parent('.eventSearch--item').addClass('clicked');
		});

		$("#searchInput").click(function () {$(this).addClass('active');});

		// KEYBOARD ARROWS NAVIGATION
		document.addEventListener('keydown', e => {
			if (e.key !== 'ArrowUp' && e.key !== 'ArrowDown') return;
			const focusElem = document.querySelector(':focus');
			const tabElements = [...document.querySelectorAll('#searchInput, #eventSearch, .eventSearch--item.display>a')];
			const tabElementsCount = tabElements.length - 1;
			if (!tabElements.includes(focusElem)) return;
			e.preventDefault();
			const focusIndex = tabElements.indexOf(focusElem);
			let elemToFocus;
			if (e.key === 'ArrowUp') elemToFocus = tabElements[focusIndex > 0 ? focusIndex - 1 : tabElementsCount];
			if (e.key === 'ArrowDown') elemToFocus = tabElements[focusIndex < tabElementsCount ? focusIndex + 1 : 0];
			elemToFocus.focus();
		});

		// Close element by clicking close class
		$(".searchClose").click(function () {
			$('#searchInput').val('').removeClass('active');
			$("#eventSearch").slideUp('');
			$('body').removeClass('search-box-active');
			// $(".searchClose").hide('');
		});

		// Close element by pressing the ESC key.
		$(document).keyup(function (e) {
			if ($('#searchInput').hasClass('active') && e.keyCode === 27) { // ESC
				$('#searchInput').val('').removeClass('active');
				$("#eventSearch").slideUp('');
				$('body').removeClass('search-box-active');
				// $('.searchClose').hide('');
			}
		})

		// Close element by clicking away
		$(document).click(function (e) {
			var container = $(".search-box");
			// if the target of the click isn't the container nor a descendant of the container
			if (!container.is(e.target) && container.has(e.target).length === 0) {
				$('#searchInput').val('');
				$("#searchInput").removeClass('active');
				$("#eventSearch").slideUp('');
				$('body').removeClass('search-box-active');
				// $('.searchClose').fadeOut('');
			}
		});

		// Scroll input to top on mobile
		$("#searchInput").click(function () {
			if (!$("body").hasClass("viewport-xxlarge-up")) {
				// MOBILE SCRIPTS
				$([document.documentElement, document.body]).animate({
					scrollTop: $("#searchInput").offset().top -20
				}, 500);
			} else {
				// DESKTOP SCRIPTS
			}
		});
		$("#searchInput").on('keyup', Foundation.utils.debounce(function(e){ 
			filterEvents();
			if (!e.target.value) {
				$("#eventSearch").hide();
				$('body').removeClass('search-box-active');
			}
		}, 500));

	
	// CHANGE PLACEHOLDER BASED ON VIEWPORT
		if (!$("body").hasClass("viewport-xlarge-up")) {
		// MOBILE PLACEHOLDER
			//ENGLISH
			$('#home.en #searchInput').attr('placeholder', 'Find an event');
			$('#home.en #searchInput').focus(function () {
				$(this).attr('placeholder', 'Try a title, or genre...')
			}).blur(function () {
				$(this).attr('placeholder', 'Find an event')
			})
			//FRENCH
			$('#home.fr #searchInput').attr('placeholder', 'Trouver un événement');
			$('#home.fr #searchInput').focus(function () {
				$(this).attr('placeholder', 'Essayez de taper un titre')
			}).blur(function () {
				$(this).attr('placeholder', 'Trouver un événement')
			})
		} else {
		// DESKTOP PLACEHOLDER
			//ENGLISH
			$('#home.en #searchInput').attr('placeholder', 'What would you like to experience next?');
			$('#home.en #searchInput').focus(function () {
				$(this).attr('placeholder', 'Try typing a title, day of the week, or a genre...')
			}).blur(function () {
				$(this).attr('placeholder', 'What would you like to experience next?')
			})
			//FRENCH
			$('#home.fr #searchInput').attr('placeholder', 'Qu’aimeriez-vous découvrir ensuite?');
			$('#home.fr #searchInput').focus(function () {
				$(this).attr('placeholder', 'Essayez de taper un titre, un jour de la semaine ou un genre...')
			}).blur(function () {
				$(this).attr('placeholder', 'Qu’aimeriez-vous découvrir ensuite?')
			})
		}
});

//-----------------------------------------------------------------------
//----- EVENT SEARCH BOX END --------------------------------------------
//-----------------------------------------------------------------------


		

	
		

	
		



	// Countdown
	$(document).ready(function(){

		if ( typeof $.fn.countdown !== 'undefined' && $.isFunction($.fn.countdown) ) {

			if( $('#countdown').length !== 0 ){
				var countdownDate = $('#countdown').data("countdown-date-timestamp");
				if( Date.now() > countdownDate ){
					var days,hours,minutes,seconds,daysPlural,hoursPlural,minPlural,secPlural;
					days = hours = minutes = seconds = "";
		
					$('#countdown').countdown({
						// date format must be: "September 26, 2014 19:00:00"
						date: $('#countdown').data("countdown-date"),
						beforeStart: function() {$(this.el).parents(".countdown_timer").show();},
						render: function(data) {
							if(data.days > 1){ daysPlural = "s"; } else { daysPlural = ""; }
							if(data.hours > 1){ hoursPlural = "s"; } else { hoursPlural = ""; }
							if(data.min > 1){ minPlural = "s"; } else { minPlural = ""; }
							if(data.sec > 1 || data.sec < 1){ secPlural = "s"; } else { secPlural = ""; }
		
							if(data.days > 0){ days = this.leadingZeros(data.days, 1) + " <span>day"+ daysPlural +"</span>, "; }
							if(data.hours > 0){ hours = this.leadingZeros(data.hours, 1) + " <span>hour"+ hoursPlural +"</span>, "; }
							if(data.min > 0){ minutes = this.leadingZeros(data.min, 1) + " <span>minute"+ minPlural +"</span>, "; }
							seconds = this.leadingZeros(data.sec, 1) + " <span>second"+ secPlural +"</span>";
		
							return $(this.el).html(
								"<span>"
								+ days
								+ hours
								+ minutes
								+ seconds
								+ "</span>"
							);
						}
					});
				}
			}
		}
	});

	// form labels
	$(document).ready(function(){
		if ($('[data-abide]').length !== 0){
			$("[data-abide] label .label-heading").append(":");
			$("[data-abide] label select, [data-abide] label textarea, [data-abide] label input[type='text'], [data-abide] label input[type='email'], [data-abide] label input[type='tel'], [data-abide] label input[type='number'], [data-abide] label input[type='url'], [data-abide] label input[type='radio']").each(function(){$(this).parents("label").find(".label-text").not('.label-inline,.label-question').append(":");});
			$("[data-abide] .radio-group,[data-abide] .mixed-group").each(function(){$(this).find(".label-text").first().not('.label-inline,.label-question').append(":");});
		}
	});

	// character count
	$.fn.charCount = function(pluginOptions){

		// default configuration properties
		var defaults = {	
			allowed: 125,		
			warning: 1,
			css: 'counter',
			counterElement: 'span',
			cssWarning: 'warning',
			cssExceeded: 'exceeded-count',
			counterText: ''
		}; 

		var options = $.extend(defaults, pluginOptions); 

		var calculate = function(obj){
			var count = $(obj).val().length;
			var available = options.allowed - count;
			if(available <= options.warning && available >= 0){$(obj).siblings("span.counter").addClass(options.cssWarning);} else {$(obj).siblings("span.counter").removeClass(options.cssWarning);}
			if(available < 0){$(obj).siblings("span.counter").addClass(options.cssExceeded);} else {$(obj).siblings("span.counter").removeClass(options.cssExceeded);}
			$(obj).siblings("span.counter").html(options.counterText + available);
		};	

		this.each(function() {
			if(!$(this).siblings("span").hasClass("counter")){
				$(this).addClass('has-counter');
				$(this).after('<'+ options.counterElement +' class="' + options.css + '">'+ options.counterText +'</'+ options.counterElement +'>');
			}
			calculate(this);
			$(this).keyup(function(){calculate(this);});
			$(this).change(function(){calculate(this);});
		});
	};

	// form labels
	$(document).ready(function(){
		if ($('#jsl_email').length !== 0){
		    $('#jsl_email').on('valid.fndtn.abide', function (e) {
		        e.preventDefault();
		        var form = $(this);

		        $.ajax({ 
		            url         : form.attr('action'),
		            type        : form.attr('method'),
		            data        : form.serialize(), // data to be submitted
		            success : function(response){
			            // show our "thank you" message (queued fx)
			            form.parent().parent().animate({ opacity: "0" }, 800 ).queue(function() {
							$(this).slideUp().dequeue().siblings('#form_thanks').slideDown('fast').queue(function() {$(this).fadeIn().dequeue();});
					    });
					    log('test');
					    return false;
		            },
		            error : function(response){
		                log("Didn't work!");
		                log(response); // do what you like with the response
		            },
		            beforeSend : function(response){
		                $("#jsl_email input:submit").addClass('bttn_disabled');
		            }
		        });
		    });
		}
	});

	$.fn.preventDoubleSubmission = function () {
		$(this).on('valid.fndtn.abide', function (e) {
			var $form = $(this);
			if ($form.data('submitted') === true) {
				// Previously submitted - don't submit again
				//alert('Form already submitted. Please wait.');
				e.preventDefault();
			} else {
				$form.find(".bttn:submit").prop("disabled", true).addClass('bttn_disabled');
				$form.data('submitted', true);
			}
		});
	};

	// hide event strip if empty
	$(document).ready(function(){
		$(".upcoming_events").each(function () {
			if ($(this).find(".event-slick---item").not(".more").length == 0) {$(this).hide();}
		});
	});

	
		
		
		
		
		
	

	// Hide [NAC] from discipline label on mobile
	document.addEventListener('DOMContentLoaded', function() {
		const eventListItems = document.querySelectorAll('.fullwidth_event_list---item');
		
		eventListItems.forEach(item => {
			const disciplineSpan = item.querySelector('.discipline span');
			if (!disciplineSpan) return;

			let text = disciplineSpan.textContent.trim();
			
			// Handle English "NAC" at start
			if (text.startsWith('NAC ')) {
				disciplineSpan.innerHTML = `<span class="nac-label">NAC</span> ${text.slice(4)}`;
			} 
			// Handle French CNA variations
			else {
				// Handle "du CNA" pattern
				const duCNAMatch = text.match(/(du\s+)?CNA\b/i);
				if (duCNAMatch) {
					const index = duCNAMatch.index;
					const matchLength = duCNAMatch[0].length;
					
					// Reconstruct text with wrapped CNA
					const beforeText = text.slice(0, index);
					const afterText = text.slice(index + matchLength);
					
					disciplineSpan.innerHTML = `${beforeText}<span class="nac-label">${duCNAMatch[0]}</span>${afterText}`;
				}
			}
		});
	});

	// scroll-to an element from a navigation item
	$(document).ready(function(){
		$("[data-scrollto-nav] li a[data-scrollto]").each(function(){
			$(this).on('click', function() {
				gotoAnchor($("#"+$(this).data("scrollto")),300);
				return false;
			});
		});
	});

	// add audio playlist when needed
	$(document).ready(function(){
		if ($("[data-audio-playlist]").length !== 0){
			//log($("[data-audio-playlist]").attr("data-audio-playlist-id"));
			$("[data-audio-playlist]").addClass("audio-player-playlist");
	
			$('<link/>', {
				rel: 'stylesheet',
				type: 'text/css',
				href: '/assets/js/mediaelement/build/mediaelementplayer.min.css'
			}).appendTo('head');
			$('<link/>', {
				rel: 'stylesheet',
				type: 'text/css',
				href: '/assets/js/mediaelement/plugins/dist/playlist/playlist.min.css'
			}).appendTo('head');
			$('<link/>', {
				rel: 'stylesheet',
				type: 'text/css',
				href: '/assets/css/audio-player-playlist.css'
			}).appendTo('head');

			$.getScripts({
				urls: ['/assets/js/mediaelement/build/mediaelement-and-player.min.js', '/assets/js/mediaelement/plugins/dist/playlist/playlist.min.js'],
				cache: true,  // Default
				async: false, // Default
				success: function(response) {
					//log('done');
					$("[data-audio-playlist]").each(function() {
						var audioplaylist = $(this);
						var entryid = $(this).attr("data-audio-playlist-id");
						log($(this).attr("data-audio-playlist-id"));

						var audioplay = $.get( "/en/includes/audio_player?entry_id="+entryid, function(data) {
							//log( "success" );
							audioplaylist.append(data);
						}).done(function() {
							//log( "second success" );
						    audioplaylist.find('.mejs__player').mediaelementplayer();
						}).fail(function() {
							log( "error: player didn't load" );
						});
					});
				}
			});
		}
	});

	/*
		redirect users based on query string parameter
		
		nb this will pass query params along also,
		but will need to be encoded, like so:
		linking to: https://nac-cna.ca/en/about?redirect=https://nac-cna.ca/en/contact%3Fredirected_from%3Dhttps://nac-cna.ca/en/about
		will result in: https://nac-cna.ca/en/contact?redirected_from=https://nac-cna.ca/en/about
	*/
	$(document).ready(function(){
		if ( typeof $.query !== 'undefined' ) {
			if ($.query.get('redirect')){
				var is_url = function(str){
					regexpUrl = /^(?:(?:https?|ftp):\/\/)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,})))(?::\d{2,5})?(?:\/\S*)?$/;
					if (regexpUrl.test(str))
					{ return true; }
					else { return false; }
				};
				var destinationUrl = $.query.get('redirect');
				if (is_url(destinationUrl)){
					window.location.href = destinationUrl;
				}
			}
		}
	});
	/*
		verify captcha response
	*/
	var verifyRecaptchaCallback = function(response){
		$(".g-recaptcha-response-value").remove();
		$("body").append("<div class='g-recaptcha-response-value' data-response='"+ response +"'></div>");
		//$("input[name='captcha']").val(response);
		//log(response);
	};
	

	/*
		convert a duration of time, i.e., number of seconds to colon-separated time string (hh:mm:ss)
	*/
	(function($){
		$.toHHMMSS = function (t){
			var sec_num = parseInt(t, 10); // don't forget the second param
			var hours   = Math.floor(sec_num / 3600);
			var minutes = Math.floor((sec_num - (hours * 3600)) / 60);
			var seconds = sec_num - (hours * 3600) - (minutes * 60);
		
			if (hours   < 10) {hours   = "0"+hours;}
			if (minutes < 10) {minutes = "0"+minutes;}
			if (seconds < 10) {seconds = "0"+seconds;}
			return hours+':'+minutes+':'+seconds;
		}
	})(jQuery);

	/*
    	fn for omitting empty inputs
		(pass the form element as a param to omit all empty inputs in submission)
	*/
	(function($){
		$.DisableNullFields = function(form) {
			$(form).find('select, input').each(function(i) {
				var $input = $(this);
				if ($input.val() == ''){
					$input.attr('disabled', 'disabled');
				}
			});
		}
	})(jQuery);

	/*
		resize an iframe once it has loaded
	*/
	/*! jquery-iframe-auto-height - v2.0.0
	*  Release on: 2015-06-28
	*  Copyright (c) 2015 Jesse House
	*  Licensed The Unlicense */
	!function(a,b){"function"==typeof define&&define.amd?define([],function(){return b()}):"object"==typeof exports?module.exports=b():b()}(this,function(){!function(a){a.fn.iframeAutoHeight=function(b){function c(a){g.debug&&g.debug===!0&&window.console&&console.log(a)}function d(b,d){c("Diagnostics from '"+d+"'");try{c("  "+a(b,window.parent).contents().find("body")[0].scrollHeight+" for ...find('body')[0].scrollHeight"),c("  "+a(b.contentWindow.document).height()+" for ...contentWindow.document).height()"),c("  "+a(b.contentWindow.document.body).height()+" for ...contentWindow.document.body).height()")}catch(e){c("  unable to check in this state")}c("End diagnostics -> results vary by browser and when diagnostics are requested")}var e;if(a.browser===e){var f=[];return f.push("WARNING: you appear to be using a newer version of jquery which does not support the $.browser variable."),f.push("The jQuery iframe auto height plugin relies heavly on the $.browser features."),f.push("Install jquery-browser: https://raw.github.com/house9/jquery-iframe-auto-height/master/release/jquery.browser.js"),alert(f.join("\n")),a}var g=a.extend({heightOffset:0,minHeight:0,maxHeight:0,callback:function(){},animate:!1,debug:!1,diagnostics:!1,resetToMinHeight:!1,triggerFunctions:[],heightCalculationOverrides:[]},b);return c(g),this.each(function(){function b(a){var b=null;return jQuery.each(f,function(c,d){return a[d]?(b=h[d],!1):void 0}),null===b&&(b=h["default"]),b}function e(e){g.diagnostics&&d(e,"resizeHeight"),g.resetToMinHeight&&g.resetToMinHeight===!0&&(e.style.height=g.minHeight+"px");var f=a(e,window.parent).contents().find("body"),h=b(a.browser),i=h(e,f,g,a.browser);c(i),i<g.minHeight&&(c("new height is less than minHeight"),i=g.minHeight),g.maxHeight>0&&i>g.maxHeight&&(c("new height is greater than maxHeight"),i=g.maxHeight),i+=g.heightOffset,c("New Height: "+i),g.animate?a(e).animate({height:i+"px"},{duration:500}):e.style.height=i+"px",g.callback.apply(a(e),[{newFrameHeight:i}])}var f=["webkit","mozilla","msie","opera","chrome"],h={};h["default"]=function(a,b,c){return b[0].scrollHeight+c.heightOffset},jQuery.each(f,function(a,b){h[b]=h["default"]}),jQuery.each(g.heightCalculationOverrides,function(a,b){h[b.browser]=b.calculation});var i=0,j=this.contentDocument||this.contentWindow.document;if(c(this),g.diagnostics&&d(this,"each iframe"),g.triggerFunctions.length>0){c(g.triggerFunctions.length+" trigger Functions");for(var k=0;k<g.triggerFunctions.length;k++)g.triggerFunctions[k](e,this)}if(a.browser.webkit||a.browser.opera||a.browser.chrome){c("browser is webkit (Safari/Chrome) or opera"),a(this).load(function(){var a=0,b=this,d=function(){e(b)};0===i?a=500:b.style.height=g.minHeight+"px",c("load delay: "+a),setTimeout(d,a),i++});var l=a(this).attr("src");a(this).attr("src",""),a(this).attr("src",l)}else"complete"===j.readyState?e(this):a(this).load(function(){e(this)})})}}(jQuery)});
	(function( jQuery ) {
		var matched,
			userAgent = navigator.userAgent || "";
	
		// Use of jQuery.browser is frowned upon.
		// More details: http://api.jquery.com/jQuery.browser
		// jQuery.uaMatch maintained for back-compat
		jQuery.uaMatch = function( ua ) {
			ua = ua.toLowerCase();
	
			var match = /(chrome)[ \/]([\w.]+)/.exec( ua ) ||
				/(webkit)[ \/]([\w.]+)/.exec( ua ) ||
				/(opera)(?:.*version)?[ \/]([\w.]+)/.exec( ua ) ||
				/(msie) ([\w.]+)/.exec( ua ) ||
				ua.indexOf("compatible") < 0 && /(mozilla)(?:.*? rv:([\w.]+))?/.exec( ua ) ||
				[];
	
			return {
				browser: match[ 1 ] || "",
				version: match[ 2 ] || "0"
			};
		};
	
		matched = jQuery.uaMatch( userAgent );
	
		jQuery.browser = {};
	
		if ( matched.browser ) {
			jQuery.browser[ matched.browser ] = true;
			jQuery.browser.version = matched.version;
		}
	
		// Deprecated, use jQuery.browser.webkit instead
		// Maintained for back-compat only
		if ( jQuery.browser.webkit ) {
			jQuery.browser.safari = true;
		}
	
	}( jQuery ));

	$(document).ready(function(){
		if ( $.fn.iframeAutoHeight !== 'undefined' && $.isFunction($.fn.iframeAutoHeight)  ) {
			$('.iframe-resize').iframeAutoHeight({debug: false});
		}
	});

	/*
		validate modal forms added via Ajax
		
		nb this relies on a "modalform"
		https://nac-cna.ca/en/segment_1?value=9&modalform=1
	*/
	$(document).ready(function(){
		if ( typeof $.query !== 'undefined' ) {
			if ($.query.get('modalform')){
				$("body").bind("DOMNodeInserted",function(){
				    $(document).foundation('reflow');

					if ($('#newsletter_form form').length !== 0){
						$('#newsletter_form form').on('valid.fndtn.abide', function (e) {
					        // e.preventDefault();
					        var form = $(this);
					        $.ajax({ 
					            url         : form.attr('action'),
					            type        : form.attr('method'),
					            data        : form.serialize(), // data to be submitted
					            success : function(response){
						            // show our "thank you" message (queued fx)
						            $('#form_contain').animate({ opacity: "0" }, 800 ).queue(function() {
										$(this).slideUp().dequeue().siblings('#form_thanks').slideDown('fast').queue(function() {$(this).fadeIn().dequeue().parents('#newsletter_form').delay(4000).slideUp();});
								    });
					
					                log(response); // do what you like with the response
					            },
					            error : function(response){
					                log("Didn't work!");
					                log(response); // do what you like with the response
					            },
					            beforeSend : function(response){
					                form.find(".bttn_submit").prop("disabled", true).addClass('bttn_disabled').after('<!-- <label class="clearfix">Please wait while your donation is being processed...</label> -->');
					            }
					        });
					    });
					}
				});
			}
		}
	});

	(function ($) {
	'use strict';

	window.boDomain = "https://arts.nac-cna.ca/en/";
	window.boCookieDomain = ".nac-cna.ca";
	window.apiEnabled = "nac-cna.ca" == "nac-cna.test" ? false : true;
	window.addFavoriteUrl = window.boDomain + "api/favorites/add/productionId";
	window.removeFavoriteUrl = window.boDomain + "api/favorites/remove/productionId";
	window.boDataUrl = window.boDomain + "api/constituent-cookies";
	window.boPrefix = "_bo_";
	window.favoriteCookieName = window.boPrefix + "favorites";
	window.loginPrompted = window.boPrefix + "nac_lp";
	window.updatedConstData = false;
	window.promptedToLogin = "0";
	window.firstFav = true;

	window.initFavorites = function () {
		//Add screen reader notification div on wish list toggle
		$('body').append('<div id="wishlist-announcement" class="sr-only" aria-live="assertive"></div>');

		let favorites = Cookies.get(window.favoriteCookieName);
		window.promptedToLogin = Cookies.get(window.loginPrompted);
		
		if (favorites === null || typeof(favorites) == 'undefined' || favorites == "[]") {
			
			$('.favourite-button').each(function () {
				$(this).addClass('production-add-favorite');
				$(this).show().append(window.getIcons("empty",true));
				$(this).attr('aria-pressed', 'false');
			});

			favorites = {};
			favorites.pNos = new Array();
			window.currentFavorites = favorites;
			//log("first fav log 1a");
			//log(favorites);
			window.updateFavorites(favorites);
			//log("first fav log 1b");
			//log(favorites);

			return;
		}

		//log("first fav log 2a");
		//log(favorites);
		favorites = JSON.parse(favorites);
		window.currentFavorites = favorites;
		//log("first fav log 2b");
		//log(favorites);
		updateFavoritesQuantity(favorites.pNos.length);

		$('.favourite-button').each(function () {
			let productionId = parseInt($(this).attr('data-production-id'));
			//log(productionId);

			if (favorites.pNos.includes(productionId)) {
				$(this).addClass('production-remove-favorite');
				$(this).show().append(window.getIcons("filled",true));
				$(this).attr('aria-pressed', 'true');
				$(this).attr('title', 'Remove from wish list');
			} else{
				$(this).addClass('production-add-favorite');
				$(this).show().append(window.getIcons("empty",true));
				$(this).attr('aria-pressed', 'false');
				$(this).attr('title', 'Add to wish list');
			}
		});
	};


	/*
		update the cart icon with a number, w/pulse animation
	*/
	window.updateCart = function(cartTotal) {
		var $cartIcon = $('.mywishlist .global-header__svg--cart');
		var $cart = $('.global-header__quantity--cart');
	
		$cart.html(cartTotal);

		if (cartTotal > 0) {
			$cart.show();
			$cart.removeClass("hidden pulse").css("display","grid").addClass("pulse");
		} else {$cart.hide();}
	};

	window.getIcons = function(status,shouldAnimate) {
		// kinda hacky, but the shouldAnimate param chooses whether to add the animations
		let animationTime = 0.25; // in seconds
	
		let random = Math.floor(Math.random() * 100000000);
	
		let emptyHeart = `
		<svg id="Group_91" aria-hidden="true" tabindex="-1" data-name="Group 91" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 437.85">
			<path d="m244,41.85l11.1,12,12-11.98C300.6,9.22,347-5.64,392.6,1.95c68.9,11.48,119.4,71.1,119.4,141v5.8c0,41.5-17.2,81.2-47.6,109.5l-180.7,168.7c-7.5,7-17.4,10.9-27.7,10.9s-20.2-3.9-27.7-10.9L47.59,258.25C17.23,229.95,0,190.25,0,148.75v-5.8C0,73.05,50.52,13.43,119.4,1.95c44.7-7.59,92,7.27,124.6,39.9-.9,0,0,.01,0,0h0Zm11.1,79.9l-45-46.8c-21.7-20.82-52.5-30.7-82.8-25.66-45.75,7.63-79.3,47.26-79.3,93.66v5.8c0,28.2,11.71,55.2,32.34,74.4l175.66,164,175.7-164c20.6-19.2,32.3-46.2,32.3-74.4v-5.8c0-46.4-33.6-86.03-79.3-93.66-30.3-5.04-61.1,4.84-82.8,25.66l-46.8,46.8Z" transform="translate(0 0)" fill="currentColor"/>
		</svg>
		`;
	
		let filledHeart = `
		<svg id="Layer_1" aria-hidden="true" tabindex="-1" data-name="Layer 1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 437.85">
			<path id="path-fill-${random}" d="m47.6,258.25l180.7,168.7c7.5,7,17.4,10.9,27.7,10.9s20.2-3.9,27.7-10.9l180.7-168.7c30.4-28.3,47.6-68,47.6-109.5v-5.8c0-69.9-50.5-129.5-119.4-141-45.6-7.6-92,7.3-124.6,39.9l-12,12-12-12C211.4,9.25,165-5.65,119.4,1.95,50.5,13.45,0,73.05,0,142.95v5.8c0,41.5,17.2,81.2,47.6,109.5h0Z" fill="currentColor" stroke="none" opacity="${shouldAnimate ? 0 : 1}" />
			<animate xlink:href="#path-fill-${random}" attributeName="opacity" from="${shouldAnimate ? 0 : 1}" to="1" dur="${animationTime}s" fill="freeze" />
		</svg>
		`;
	
		let circledHeart = `
		<svg id="Component_29_1" aria-hidden="true" tabindex="-1" data-name="Component 29 – 1" xmlns="http://www.w3.org/2000/svg" width="40" height="40" viewBox="0 0 40 40">
			<g id="Group_3143" data-name="Group 3143" transform="translate(0 0)">
				<g id="Group_2835" data-name="Group 2835" transform="translate(0 0)">
				<g id="ellipse-${random}" data-name="Ellipse 46" fill="none" stroke="currentColor" stroke-width="1" opacity="${shouldAnimate ? 0 : 1}">
					<circle cx="20" cy="20" r="20" stroke="none"/>
					<circle cx="20" cy="20" r="19.5" fill="none"/>
				</g>
				</g>
			</g>
			<path id="path-fill-${random}" data-name="Path 188" d="M279.664,157.638a5.707,5.707,0,0,0-8.621.679,5.745,5.745,0,0,0-4.6-2.333,5.8,5.8,0,0,0-4.02,1.654,5.707,5.707,0,0,0-1.671,4.014,8.732,8.732,0,0,0,.5,2.871,6,6,0,0,0,.626,1.223c.279.431.538.787.757,1.072a10.49,10.49,0,0,0,.952,1.052c.421.411.767.732,1.018.962s.636.574,1.14,1c.574.5.992.877,1.258,1.115s.636.591,1.125,1.062a17.3,17.3,0,0,1,2.416,2.834.572.572,0,0,0,.491.273.589.589,0,0,0,.514-.273,18.117,18.117,0,0,1,1.546-2.011q.909-1.012,1.509-1.579c.406-.38.995-.912,1.751-1.586.467-.416.844-.732,1.1-.962s.581-.548.985-.952a12.278,12.278,0,0,0,.952-1.038c.233-.287.477-.649.757-1.072a6.686,6.686,0,0,0,1.018-2.518,7.076,7.076,0,0,0,.155-1.476A5.718,5.718,0,0,0,279.664,157.638Zm-8.618,2.464" transform="translate(-251.049 -144.356)" fill="currentColor" stroke="none" opacity="${shouldAnimate ? 0 : 1}" />
			<animate xlink:href="#ellipse-${random}" attributeName="opacity" from="${shouldAnimate ? 0 : 1}" to="1" dur="${animationTime}s" fill="freeze" />
			<animate xlink:href="#path-fill-${random}" attributeName="opacity" from="${shouldAnimate ? 0 : 1}" to="1" dur="${animationTime}s" fill="freeze" />
		</svg>`;
	
		switch (status) 
		{
			case "empty": return emptyHeart;
			case "filled": return filledHeart;
			case "circled": return circledHeart;
		
			default: return emptyHeart;
		}
	};

	// check if cookies are enabled by trying to store one and then retrieve it
	// see below for the rationale of why we have to do that. we can't just use
	// navigator.cookieEnabled because that returns `true` even if we're not on
	// https and our cookies won't be stored correctly.
	window.checkCookieSupport = function() {
		if (window.cookiesEnabled != null) {
			return window.cookiesEnabled;
		}
		var domain = window.location.hostname;
		domain = domain.replace(/^www\./, '');
		domain = domain.replace(/^stage\./, '');
		domain = domain.replace(/^test\./, '');
		Cookies.set('cookies-enabled', 'true', {
			expires: new Date().getTime() + 1000,
			domain: domain,
			path: '/',
			secure: true,
		});
		if (Cookies.get('cookies-enabled')) {
			window.cookiesEnabled = true;
		}
		else {
			window.cookiesEnabled = false;
		}
		return cookiesEnabled;
	};

	window.getNumber = function(value, defaultValue = 0) {
		let num = parseInt(value, 10);
		return isNaN(num) ? defaultValue : num;
	};

	/*
		returns an array of (performanceID, timestamp)
		if the cookie is not already set or is malformed, will set it to empty array
	*/
	window.getFavorites = function() {
		var favorites = {};
		try {
			//favorites = JSON.parse(unescape(Cookies.get(window.boPrefix + 'favorites')));
			//log("fav log 1a");
			//log(favorites);
			favorites = JSON.parse(Cookies.get(window.favoriteCookieName));
			//log("fav log 1b");
			//log(favorites);
		}
		catch (_a) {
			// console.warn('malformed favorites string, resetting');
			//console.clear();
			favorites = {};
			favorites.pNos = new Array();
			//log("fav log 1c");
			//log(favorites);
		}
		return favorites;
	};
	
	/*
		adds a performance with a given performanceID - DOM only
	*/
	window.addToFavourites = function(productionId) {
		// log the response
		log('performance '+ productionId +' added to favorites');
		$('.favourite-button[data-production-id="'+ productionId +'"]').each(function(){
			// Update ARIA attributes first
			$(this).attr('aria-pressed', 'true'); 
			// Then make visual changes
			$(this)
				.removeClass('production-add-favorite is-loading')
				.addClass('production-remove-favorite')
				.hide()
				.empty()
				.append(window.getIcons("filled",true))
				.prepend('<span class="wishlist-notify wishlist-add"></span>')
				.removeAttr('disabled')
				.show();
		});

		$('#wishlist-announcement').text('Event added to wish list');
		
		let favoritesQuantity = window.getNumber($('.global-header__quantity--wish-list').html());
		window.updateFavoritesQuantity(++favoritesQuantity);
		window.favorite(productionId);
	};
	
	/*
		removes a performance with a given performanceID - DOM only
	*/
	window.removeFromFavourites = function(productionId) {
		// log the response
		log('performance '+ productionId +' removed from favorites');
		$('.favourite-button[data-production-id="'+ productionId +'"]').each(function(){
			// Update ARIA attributes first
			$(this).attr('aria-pressed', 'false');
			// Then make visual changes
			$(this)
				.removeClass('production-remove-favorite is-loading')
				.addClass('production-add-favorite')
				.hide()
				.empty()
				.append(window.getIcons("empty",true))
				.prepend('<span class="wishlist-notify wishlist-remove"></span>')
				.removeAttr('disabled')
				.show();
		});

		$('#wishlist-announcement').text('Event removed from wish list');
		
		let favoritesQuantity = window.getNumber($('.global-header__quantity--wish-list').html());
		if (favoritesQuantity.length == 1) {$('.global-header__quantity--wish-list').hide('slow');}
		window.updateFavoritesQuantity(--favoritesQuantity);
		window.unfavorite(productionId);
	};

	/*
		adds a performance with a given performanceID
	*/
	window.favorite = function(performanceID) {
		var favorites = window.getFavorites();
		// remove current performance ID from cookie if we already
		// have it favorited. this is basically unfavorite()
		// but calling that would needlessly update the cookie
		favorites.pNos = favorites.pNos.filter(function (x) { return x != performanceID; });
		//log("fav log 3");
		//log(favorites);
		favorites.pNos.push(performanceID);
		window.setFavoritesCookie(favorites);
	};

	/*
		removes a performance with a given performanceID
	*/
	window.unfavorite = function(performanceID) {
		var favorites = this.getFavorites();
		favorites.pNos = favorites.pNos.filter(function (x) { return x != performanceID; });
		//favorites = favorites.filter(function (x) { return x.performanceID != performanceID; });
		//log("fav log 4");
		//log(favorites);
		window.setFavoritesCookie(favorites);
	};

	window.updateFavorites = function(favorites) {
		//var favorites = window.getFavorites();
		//log("fav log 5");
		//log(favorites);
		window.setFavoritesCookie(favorites);
	};

	/*
		sets the favorites cookie to the provided value, with a 1 year expiration
		(helper function)
	*/
	window.setFavoritesCookie = function(value) {
		// if this check isn't here, we get into an infinite loop and crash the tab
		// this happens because we fire off a `notify()` call, which makes all favorites
		// elements call `getFavorites()`, which in turn realises that our favorites
		// cookie is empty, and calls `clear()` to reset it... which then calls this
		// function again. good times.
		if (!window.checkCookieSupport()) {
			// console.warn('you have cookies disabled, or you\'re not browsing through a secure connection so saving cookies won\'t work');
			return;
		}
		var previousFavorites = window.currentFavorites;
		window.currentFavorites = value;
		var d = new Date();
		var year = d.getFullYear();
		var month = d.getMonth();
		var day = d.getDate();
		var yearInFuture = new Date(year + 1, month, day);
		var domain = window.location.hostname;
		domain = domain.replace(/^www\./, '');
		domain = domain.replace(/^stage\./, '');
		domain = domain.replace(/^test\./, '');
		Cookies.set(window.favoriteCookieName, JSON.stringify(value), {
			expires: yearInFuture,
			//domain: this.options.boCookieDomain,
			domain: domain,
			secure: true,
		});
	};

	window.updateFavoritesQuantity = function(favoritesQuantity) {
		let $favorites = $('.global-header__quantity--wish-list');
		$favorites.html(favoritesQuantity);
	
		if (favoritesQuantity > 0) {
			$favorites.show();
			$favorites.removeClass("hidden").css("display","grid");
			
			// timeout required so animation finishes before class is removed
			// allows animation to be applied repeatedly
			var timeout = null;
			
			function pulse() {
			  $favorites.addClass("pulse");
			  if (timeout) {
				clearTimeout(timeout);
				timeout = null;
			  }
			  timeout = setTimeout(function () {$favorites.removeClass("pulse");}, 1000); // 1 second delay for 600ms animation seems fair
			}
			pulse();
		} else {$favorites.hide();}
	};

	window.updateGlobalConstData = function() {
		// populate a global var for constituency IDs
		if (Cookies.get(window.boPrefix + 'const_ids') !== undefined){
			window.constituencies = atob(Cookies.get(window.boPrefix + 'const_ids')).split(",").map((item) => +item);
		}

		// populate a global var for renewable package IDs
		if (Cookies.get(window.boPrefix + 'sub_ids') !== undefined){
			window.renewal_sub_ids = atob(Cookies.get(window.boPrefix + 'sub_ids')).split(",").map((item) => +item);
		}
	};

	window.grokConstData = function(data) {
		//log(data.const_ids);
		log("Constituent IDs: " + atob(data.const_ids) + ", " + "Sub renewal IDs: " + atob(data.sub_ids));
	};

}(jQuery, window));

$(document).ready(function(){
	window.initFavorites();
	
	$(document).on('click','.production-add-favorite', function (e) {
		e.preventDefault();
		$(this).addClass('is-loading').attr('disabled', true);
		let el = $(this);
		let productionId = $(this).data('production-id');
		let url = window.addFavoriteUrl;
		url = url.replace('productionId', productionId);

		if(window.apiEnabled){
			$.ajax({
				method: 'POST',
				async: true,
				url: url,
    			xhrFields: {
					withCredentials: true
    			},
    			crossDomain: true,
				success: function(response){window.addToFavourites(productionId);},
				error: function(response){
					log("no connection to API");
				},
				complete: function(){window.loginPrompt();}
			});
		} else {
			window.addToFavourites(productionId);
			log("no connection to API - faking wishlist functionality (add)");
			window.loginPrompt();
		}
	});
	
	$(document).on('click','.production-remove-favorite', function (e) {
		e.preventDefault();
		$(this).addClass('is-loading').attr('disabled', true);
		let el = $(this);
		let productionId = $(this).data('production-id');
		let url = window.removeFavoriteUrl;
		url = url.replace('productionId', productionId);

		if(window.apiEnabled){
			$.ajax({
				method: 'POST',
				async: true,
				url: url,
    			xhrFields: {
					withCredentials: true
    			},
    			crossDomain: true,
				success: function(response){window.removeFromFavourites(productionId);},
				error: function(response){
					log("no connection to API");
				}
			});
		} else {
			log("no connection to API - faking wishlist functionality (remove)");
			window.removeFromFavourites(productionId);
		}
	});

	window.userLoggedIn = (Cookies.get(window.boPrefix + 'logged_in') == 1) ? true : false;

	if (window.userLoggedIn){
		// patron is logged-in to NAC account
		// populate global vars for patron data
		window.firstName = Cookies.get(window.boPrefix + 'first_name');
		window.constIds = Cookies.get(window.boPrefix + 'const_ids');
		window.subIds = Cookies.get(window.boPrefix + 'sub_ids');
		window.userIsSubscriber = (Cookies.get(window.boPrefix + 'is_subscriber') == 1) ? true : false;

		var myAccountLabel = $('#nav_utility .myaccount .myaccount_label');
		window.myAccountGreeting = (typeof(window.firstName) != 'undefined') ? "Hi "+window.firstName+"!" : myAccountLabel.html();
		myAccountLabel.html(window.myAccountGreeting);

		var cartTotal = 0;
		if(Cookies.get(window.boPrefix + 'basket_count') !== undefined){
			cartTotal = parseInt(JSON.parse(Cookies.get(window.boPrefix + 'basket_count')), 10);
			window.updateCart(cartTotal);
		}

		$('body').addClass('is_logged_in');

		// is this a sales page with subscriber-specific content?
		if ( $('body').hasClass('sales-page') ){
			// get fresh subscriber data
			$.ajax({
				method: 'POST',
				async: true,
				url: window.boDataUrl,
    			xhrFields: {
					withCredentials: true
    			},
    			crossDomain: true,
				success: function(){
					log("fetched constituent data");
					//log("new constituent IDs: " + Cookies.get(window.boPrefix + 'const_ids'));
					if (
						window.constIds != Cookies.get(window.boPrefix + 'const_ids') ||
						window.subIds != Cookies.get(window.boPrefix + 'sub_ids')
					){
						log("constituent data is different, or was empty at runtime");
						window.updatedConstData = true;
						window.updateGlobalConstData();

						if (typeof(window.constituencies) == "object"){
							// adjust page elements for current subscribers
							for( i of window.constituencies ){
								// if current subscriber ID in cookie
								if(i == '42'){$("body").addClass("subscriber-25-26");} else if(i == '26'){$("body").addClass("subscriber-24-25");}
							}
						}

						if (typeof(window.renewal_sub_ids) == "object"){
							// adjust page elements for renewable packages/addons
							for( i of window.renewal_sub_ids ){
								// todo - show subscribe bar copy
								$(".subscribe_bar.package-" + i).addClass("renewable");
								// todo - show correct button text
								//$("button.dropdown.package-" + i).addClass("renewable");
								// show renew pill on dropdown options
								$(".dropdown-list [data-package-id='"+ i +"']").addClass("renewable");
								// buy button on package pages including button text
								$(".package-button.package-" + i).addClass("renewable");
							}
						}
					}
				},
				error: function(){
					log("failed to fetch constituent data");
				}
			});
		}
		window.updateGlobalConstData();
	}
});

	
		/*
			pre-escaped to accept query params for modal windows, etc.
			https://nac-cna.ca/en/segment_1?value=9&modal=1&context=foo
		*/

		$(document).ready(function(){
	 
});