/*
	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         : "/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: '230px' }, 500);
								$('#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         : "/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();
			$('#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();});
	});
});


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

			$(document).ready(function () {
	if ( typeof $.fn.slick !== 'undefined' && $.isFunction($.fn.slick) ) {
		$("#upcoming_events ul").each(function () {
			if ($(this).find("li.no-results").length !== 0) {$(this).parents(".discipline_events").hide();}
		});
	
		$('.event-slick').find('.event-cache-seed').remove();
		$('.event-slick:not(.noslide)').slick({
			dots: true,
			infinite: false,
			slidesToShow: 3.5,
			slidesToScroll: 3,
			prevArrow: '<button type="button" class="svg slick-prev"><i class="fa fa-caret-left"></i></button>',
			nextArrow: '<button type="button" class="svg slick-next"><i class="fa fa-caret-right"></i></button>',
			responsive: [
				{
					breakpoint: 980,
					settings: {
						slidesToShow: 3.5,
						slidesToScroll: 3,
						arrows: true
					}
				},
				{
					breakpoint: 768,
					settings: {
						slidesToShow: 2.5,
						slidesToScroll: 2,
						dots: false,
						arrows: true
					}
				},
				{
					breakpoint: 481,
					settings: {
						slidesToShow: 1.5,
						slidesToScroll: 1,
						dots: false,
						arrows: true
					}
				}
			]
		});
	}
});
			
			
				
											$(document).ready(function(){
							$(".overlay").click(function () {
								$("#image-caption").slideToggle(100);
								$('.more_info .fa').toggleClass('fa-info').toggleClass('fa-close');
							});
							$(".more_info").click(function(){
								$("#image-caption").slideToggle(100);
							$('.more_info .fa').toggleClass('fa-info').toggleClass('fa-close');
							});
						});
									
			
		

	
		

	
		

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

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

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

	// submit an Ajax enewsletter form & show the thank you message
	$(document).ready(function(){
		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> -->');
		            }
		        });
		    });
		}
	});

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

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

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

	/*
		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(){
		$('.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> -->');
					            }
					        });
					    });
					}
				});
			}
		}
	});

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

	// Search bar
	$(document).ready(function(){
		if ( typeof google === 'object' ) {
			google.load('search', '1', {"callback": function() {}});
			var initSearchAutoComplete = function() {
				google.search.CustomSearchControl.attachAutoCompletion(
											'015282198471515675687:tnhesgem08c',document.getElementById('query-input'),'two-page-form'
									);
			}
			google.setOnLoadCallback(initSearchAutoComplete);
		}
	});


	


