/*
	Dynamic Javascript template - nac-cna.ca

	n.b. all segments of the URL are available, 
	however they are offset by 1.
	(ie "legal" 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         : "/fr/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         : "/fr/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
	
		

	
		

	
		

	// 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>jour"+ daysPlural +"</span>, "; }
					if(data.hours > 0){ hours = this.leadingZeros(data.hours, 1) + " <span>heure"+ hoursPlural +"</span>, "; }
					if(data.min > 0){ minutes = this.leadingZeros(data.min, 1) + " <span>minute"+ minPlural +"</span>, "; }
					seconds = this.leadingZeros(data.sec, 1) + " <span>seconde"+ 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;
			});
		});
	});

	/*
		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);
	/*
		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:0d05fqqvcem',document.getElementById('query-input'),'two-page-form'
									);
			}
			google.setOnLoadCallback(initSearchAutoComplete);
		}
	});


	


