 /*
	Dynamic Javascript template - nac-cna.ca

	n.b. all segments of the URL are available, 
	however they are offset by 1.
	(ie "event" 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' }); 
	});


// START DYNAMIC SCRIPTS
	
			
					
					
						
						
							{$(document).ready(function(){
	$('.thumb_contain .play').click(function( event ){
		event.preventDefault();
		var container = $(this).parent();
		$('.thumb_contain iframe').remove();
		$('.thumb_contain .play,.status_contain,.categories').removeClass('now-playing');
		$('.thumb_contain').removeClass('video-playing');
        video = '<iframe src="'+ $(this).next().attr('data-video') +'"></iframe>';
        container.prepend(video);
        container.find('.play,.status_contain,.categories').addClass('now-playing');
        container.addClass('video-playing');
    });
});}

// Event ID: 32651 or 
//Video playing and ordering based on ?video=play parameter adding body class .videoPlay
		function insertVideoEmbed() {
			var $mobileImage = $('.media-slider.mobile .slider_image.first_image');
			var $mobileVideo = $('.media-slider.mobile .slider_video.video_1');
			var $desktopImage = $('.media-slider:not(.mobile) .slider_image.first_image');
			var $desktopVideo = $('.media-slider:not(.mobile) .slider_video.video_1');

			if ($('body').hasClass('videoPlay')) {
				// Move the mobile video slide after the first image slide
				$mobileVideo.insertAfter($mobileImage);
				// For desktop, force first video to autoplay muted in slideshow if window width > 1024px
				if ($(window).width() > 1024) {
					$('.media-slider:not(.mobile) .slider_main_image.slider_video.video_1 iframe').each(function () {
						var src = $(this).attr('src');
						if (!src.includes('autoplay=1')) {
							var muteParam = $(this).closest('.slider_vimeo').length ? 'muted=1' : 'mute=1';
							src += src.includes('?') ? '&autoplay=1&' + muteParam : '?autoplay=1&' + muteParam;
							$(this).attr('src', src);
						}
					});
				}
				// Reorder desktop slides if needed
				if ($desktopVideo.length && $desktopImage.length) {
					$desktopVideo.insertBefore($desktopImage);
				}

				
					// Add video embed container to the header if not already added and window width < 1024px
					if ($(".event_hero_header .flex-video").length === 0 && $(window).width() < 1024) {
						var videoEmbedContainer = '';
						if ('YouTube' === 'YouTube') {
							videoEmbedContainer = `
								<div class="flex-video widescreen vimeo">
									<iframe class="event_hero_header---video" width="100%" height="270px" src="//www.youtube.com/embed/-nHrpHbhXyA?showinfo=0&controls=1&color=white&rel=0hl=en&cc_lang_pref=en&cc_load_policy=1&autoplay=1&mute=1" frameborder="0" allowfullscreen></iframe>
								</div>`;
						} else if ('YouTube' === 'Vimeo') {
							videoEmbedContainer = `
								<div class="flex-video widescreen vimeo">
									<iframe title="vimeo-player" src="https://player.vimeo.com/video/-nHrpHbhXyA?color=a6aed8&byline=0&title=0&portrait=0&autoplay=1&muted=1" width="640" height="360" frameborder="0" allowfullscreen></iframe>
								</div>`;
						}
						if (videoEmbedContainer) {
							$(".event_hero_header").append(videoEmbedContainer);
						}
					}
				
			} else {
				// Remove main image on mobile if body does not have the videoPlay class
				$mobileImage.remove();
			}
		}
		$(document).ready(function () {
			insertVideoEmbed();
		});
$(document).ready(function(){
	// Event title length check 
	
		$(function() {
				var $title = "Nico Paulo";
					var $element = $(".event_title_block h1");
					var $numWords = $title.length;
					var classBasedOnNumWords = "char" + $numWords;

				
					if (($numWords >= 1) && ($numWords < 7)) {
						$element.addClass("xxshort");
					}
					else if (($numWords >= 7) && ($numWords < 14)) {
						$element.addClass("xshort");
					}
					else if (($numWords >= 14) && ($numWords < 20)) {
						$element.addClass("short");
					}
					else if (($numWords >= 20) && ($numWords < 25)) {
						$element.addClass("medium");
					}
					else if (($numWords >= 25) && ($numWords < 30)) {
						$element.addClass("long");
					}
					else if (($numWords >= 30) && ($numWords < 35)) {
						$element.addClass("xlong");
					}
					else if (($numWords >= 35)) {
						$element.addClass("xxlong");
					}

				$element.addClass(classBasedOnNumWords);
		});
	
		
		$(function() {		
				
		});

	
		
});

$(document).ready(function(){

	// Video thumbnails and player
	if( $("ul.video_grid").length > 0 ) {

		$("ul.video_grid").ytplaylist({addThumbs:true, autoPlay: true, holderId: 'ytvideo', secure: true});

		$("ul.video_grid li a").click(function(){
			var inputId = $(this).attr("id");
			var vidurl = $("#videoSlider iframe").attr('src') + "&autoplay=1";
			$("#videoSlider iframe").attr('src',vidurl);
		});

	 	$("#videoSlider").hide();
	 	$("#close").hide();

		if( $("#videoSlider").is(":hidden") ) {
		 	$(".videoLink").click(function() {
	 			$("#videoSlider").show();

	 			if($("body").scrollTop() > $("#videoSlider").offset().top){
		 			gotoAnchor($("#videoSlider"),300);
		 		}
	 			$("#close").show();
				//$("#event_slideshow").hide();
		 	});
		 	$(".bttn_play").click(function() {
		 		$("#videoSlider").show();
		 		$("#close").show();
		 	});
	 	}

		$("#close").click(function(){
			if($("#videoSlider").is(":visible")) {
				//$("#event_slideshow").show();
				$("#videoSlider").fadeOut(650,function(){
					$("#videoSlider #ytvideo *").remove();
				});
			}
		});
	}
	
	// 2018 template showtimes
	$('.multiple_showtimes, .close-pane').click(function(){
		$('.mobile_calendar_listing').slideToggle('slow');
		$('.event_date').toggleClass('open-pane');
	});
	 
});

// 2018 template mobile buy button

$(document).ready(function(){
	$('.event_sales_original').clone().appendTo('.event_sales_clone');
	if ( typeof(addeventatc) !== 'undefined' && typeof(addeventatc) == 'object' ) {
		addeventatc.refresh();
	}
});





$(document).ready(function(){
	$('.primary_credits .bio_circles---item').each(function(){
		let img_h = $('.bio_circles---content img',this).height();
		let txt_h = $('.bio_details',this).height();
		if (img_h < txt_h) {
			$('.bio_circles---content',this).css({'align-items':'start'});
		}
	});
});

$(document).ready(function(){

	//Run event slideshow script
	if ( $('.slider div>*').length==1 && $('#video_slider').hasClass('novideo') ){
		$('#video_slider').hide();
		$('.desktop_nav li.event-nav-slideshow').hide();
	} else {
		if ( typeof $.fn.slick !== 'undefined' && $.isFunction($.fn.slick) ) {
			$('.media-slider .slider:not(.nac_video_list)').slick({
				autoplay: false,
				autoplaySpeed: 5000,
				slidesToShow: 1,
				adaptiveHeight: true,
				slidesToScroll: 1,
				arrows: true,
				prevArrow: '<button type="button" class="slick-prev"><i class="fa-solid fa-caret-left"></i></button>',
				nextArrow: '<button type="button" class="slick-next"><i class="fa-solid fa-caret-right"></i></button>',
				fade: true,
				dots: true
			});
		}
	}

	// hide nav if only one item 
	if ($('.desktop_nav ul li').length === 0) {
		// Hide the .desktop_nav if there are no <li> elements
		$('.desktop_nav').hide();
	}
		
	if ($('.event-parameters li').length === 0) {
		$('.event-parameters').remove();	
	}

	if ($('.premiere_type span').length === 0) {
		$('.premiere_type').remove();
	}
	
});

$(document).ready(function(){
	// direct link to video feature
	if($('.feature-video').length){
		$('.feature-image').hide();
		$('.feature-video').each(function(){
			if( $(this).parent('.show-for-large-up').is(':visible') ){
				var vid = $(this).find('.video-frame');
				if(vid.is('[data-video-autoplay]')){
					log('test');
					vid.attr('src',vid.attr('src')+'&autoplay=1');
				}
			}

			$(this).show();
		});
	}
});

// SALES MODULE ACCORDION
$(document).ready(function () {
	$("#sales_module.accordion").each(function () {
		var $this = $(this);
		var headings = $this.find(".accordion--heading:visible");

		// Hide all panes initially
		$this.find(".pane").hide();

		// Open the first section by default
		var firstHeading = headings.first();
		firstHeading.addClass("current");
		firstHeading.next(".pane").css('display', 'flex'); // Open the first pane

		// Setup click handlers for headings
		headings.click(function () {
			// Toggle the current pane
			$(this).toggleClass("current").next(".pane").slideToggle("slow").css('display', 'flex');
			// Close other panes
			$(this).siblings(".accordion--heading").removeClass("current").next(".pane").slideUp("slow");
		});
	});
});


$(document).ready(function(){	
	$(".chat-display").attr('title', 'Close chat').click(function () {
		var title = 'Close chat' ;
		if( $(this).hasClass('close')){
			title = 'Open chat';
		}
		
		$(this).attr('title', title);

		$(this).toggleClass("close open");
		$(".chat-display-icon").toggleClass("fa-comment-close-regular fa-square-comments-solid");
		$(".video-contain").toggleClass("with-chat");
		$(".donate_callout").toggleClass("with-chat");
		$(".livechat").toggleClass("hide").toggleClass("large-4").toggleClass("columns");
		$(".livevideo").toggleClass("large-8");

		
	});
});


$(document).ready(function () {
	if (typeof $.fn.slick !== 'undefined' && $.isFunction($.fn.slick)) {
		$('.bio-slider').slick({
			dots: false,
			infinite: false,
			speed: 300,
			slidesToShow: 5,
			slidesToScroll: 4,
			arrows: true,
			prevArrow: '<button type="button" class="svg slick-arrow slick-prev"><i class="fa-solid fa-caret-left"></i></button>',
			nextArrow: '<button type="button" class="svg slick-arrow slick-next"><i class="fa-solid fa-caret-right"></i></button>',
			responsive: [
				{
				breakpoint: 1024,
				settings: {
					slidesToShow: 4,
					slidesToScroll: 3,
					infinite: true,
					dots: true
				}
				},
				{
				breakpoint: 769,
				settings: {
					slidesToShow: 4,
					slidesToScroll: 3,
					infinite: true,
					dots: true
				}
				},
				{
				breakpoint: 765,
					settings: "unslick"
				}
				// You can unslick at a given breakpoint now by adding:
				// settings: "unslick"
				// instead of a settings object
			]
		});
	}
});

$(document).ready(function () {
	// hide sponsor block if empty
	if ( !$('.event_sponsors dl').children().length ) { $('.event_sponsors').hide(); }
});
							// external articles slider
$(document).ready(function(){	
	if ( typeof $.fn.slick !== 'undefined' && $.isFunction($.fn.slick) ) {
		$('.article-slick').slick({
			dots: false,
			infinite: true,
			mobileFirst:true,
			slidesToShow: 2,
			slidesToScroll: 2,
			variableWidth: true,
			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: 768,
					settings: {
						slidesToShow: 2,
						slidesToScroll: 2,
						arrows: true,
						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>',
						variableWidth: false
					}
				},
				{
					breakpoint: 481,
					settings: {
						slidesToShow: 1,
						slidesToScroll: 1,
						arrows: true,
						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>',
						variableWidth: false
					}
				}
			]
		});
	}
});
							$(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
					}
				},
			]
		});
	}
});

							$(document).ready(function(){	
	window.addeventasync = function () {
		addeventatc.settings({
			license: "amsloebYizhPwRlDBmZa126305",
			appleical: { show: true, text: "Apple iCal <em>(.ics)</em>" },
			google: { show: true, text: "Google Calendar" },
			outlook: { show: true, text: "Outlook <em>(.ics)</em>" },
			yahoo: { show: false, text: "Yahoo" },
			office365: { show: false, text: "Office 365 <em>(online)</em>" },
			outlookcom: { show: false, text: "Outlook.com <em>(online)</em>" }
		});
	};
});
					
							// EVENT LIVESTREAM COUNTDOWN START --------------------------------	
							
							// EVENT LIVESTREAM COUNTDOWN END  --------------------------------	
						
							
				
		

	
		

	
		
// END DYNAMIC SCRIPTS



	// 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 = "nacweb1" == "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(){
	 
});