(function(window, document, $, undefined){

	var language = $("html").attr("lang");

	'use strict';

  
	//generate mailto
	var generateMailto = function(){
		$( ".mailto_button" ).on( "click", function(event) {
			subject = 'Question Web - '+ $('#haut').text();
			 $(this).attr('href', 'mailto:accueil@hydro.qc.ca?subject='+subject);
		});
	}

	//accordion code addapted to visites section
	var reFormatAccordionCode = function(){
		if ($(".accordionButtonVisites").length) {
			var e = $(".accordionButtonVisites");
			var t = {
				fr: ["Cliquez ici pour agrandir", "Cliquez ici pour réduire"],
				en: ["Click for expanding", "Click to collapse"]
			};
			var n = language == "fr" ? t.fr[0] : t.en[0];
			var r = language == "fr" ? t.fr[1] : t.en[1];

			$('.accordionButtonVisites button').attr('title',n);

			e.on("click", function () {
				var t = $(this);
				var b = $(this).find('button');
				e.removeClass("on");
			   // console.info(r);
				
				$(".accordionContent").fadeOut("normal");
				if (t.next().is(":hidden")) {

					t.addClass("on");
					b.attr('title',r);
					t.next().slideDown("normal", function () {
						$("html,body").animate({
							scrollTop: t.offset().top-100
						}, "normal")
					})

				} else {
					b.attr('title',n);
					t.find(".caption").text(n);
				}
			});
		}
		$(".accordionContent").hide();
	};

	//nos autres site dropdown
	var specialSitesMenu = function(){
		var self = this,
			box_menu = $("#box_otherSitesList"),
			box_menu_btn = box_menu.find("button"),
			box_list = $("#otherSitesList"),
			last_link = $("a",box_list).eq(-1);

		var isClick = false;

		box_menu_btn.on({
			click:function (event) {
			   
				   if (isClick) {
						box_menu_btn.removeClass('active');
						box_list.fadeOut('fast', function () {
						isClick = false;
						box_list.attr('aria-expanded',false);
					   // console.log('expanded false')
					});	
				   }
					else {
					box_menu_btn.addClass('active');
					box_list.fadeIn('fast', function () {
						isClick = true;
						box_list.attr('aria-expanded',true);
						//console.log('expanded true')
					});
				}
			},
			focus:function (event) {
			  
			   $(this).trigger('click');
			}	
		});

		$('.subMenu a').last().focus(function(){
			if(isClick){
				box_menu_btn.trigger('click');
			}
		});

		$('#header-search-form input:first').on({
			focus:function() {
			   if(isClick){
					box_menu_btn.trigger('click');
				}
			}
		});
	};

	//positions map perfectly on left on fiche page
	var mapFichePos = function(){
		var myMap = $("#map-fiche"),
			divLeft, distLeft, leftW,
			myResizeTimeout, totalLeft;
			
		if(myMap.length){
			var setPadding = function(){
				divLeft = myMap.parent().find(".fiche-title");
				distLeft = divLeft.offset().left;
				leftW = divLeft.width();
				//add left values
				totalLeft = Math.floor(distLeft + leftW);
				if($(window).width()>760){
					myMap.css("padding-left", totalLeft);
				}
			};	

			if(myMap.length){
				setPadding();
			}

			//re calculate left value on resize 
			window.onresize = function(){
				clearTimeout(myResizeTimeout);
				myResizeTimeout = setTimeout(setPadding, 100);
			};		
		}	
	

	};

	//comments block hover functionality
	var commentsList = function(){
		var commentsBlock = $(".list-comments"),
			hoverElem;


			// if(commentsBlock.length){
			//	 hoverElem = commentsBlock.find(".has-hover");

			//	 hoverElem.each(function(){
			//		 var blockShown = $(this).find(".is-shown"),
			//			 blockHidden = $(this).find(".is-hidden");

			//		 if(!Modernizr.touch){
			//			 $(this).on({
			//				 mouseenter: function(){
			//					 blockShown.stop().animate({'opacity':'0'},300);
			//				 },
			//				 mouseleave: function(){
			//					 blockShown.stop().animate({'opacity':'1'},300);
			//				 }
			//			 });
			//		 }else{
			//			 blockShown.toggle(function(){
			//				 blockShown.stop().animate({'opacity':'0'},300);
			//			 },function(){
			//				 blockShown.stop().animate({'opacity':'1'},300);
			//			 });
			//		 }
			//	 });
			// }

	};


	//print fiche button
	var printFicheInfo = function(){

		var printBtn = $(".print-btn"),
			hoverElem, newImg,
			bodyElem = $("body");

		if(printBtn.length){	
			printBtn.on("click", function(e){
				
				var scrollTop = $(document).scrollTop();		 
				 
				e.preventDefault();

				bodyElem.addClass("printFiche");

				newImg  = new Image();
				// add fake header for print	
				newImg.onload  = function(){	 
					newImg.id ="printImage";
					bodyElem.prepend(newImg);						 
					window.print();
					$('body').animate({'scrollTop':scrollTop},100);

					bodyElem.removeClass("printFiche");
					//document.getElementById('printImage').remove();
					var element = document.getElementById("printImage");
					element.parentNode.removeChild(element);
				}
				newImg.src = "/themes/visitez/images/bg/bg-header-print.png";
			});
			

		}

	};

	//animation for fiche main links and scroll to effect
	var scrollLinks = function(){
		var myLinks = $(".scroll-link"),
			ficheArrowLink = $(".fiche-arrow")

		myLinks.on("click", function(e){
			e.preventDefault();
			var mysrc = $(this).attr("href"),
			linkTo = $("#" + mysrc.split('#')[1]);
			$("html, body").animate({ scrollTop: linkTo.offset().top }, 500);
		});

		ficheArrowLink.on("click", function(){
			var nextElem = $(this).closest(".fiche").next();
			$("html, body").animate({ scrollTop: nextElem.offset().top }, 500);
		});
	};

	//comments page lazy load
	var commentsPage = function(){

		var commentsBlock = $("#comments-page");

		if(commentsBlock.length){ 

			var visibleRows = 1;
			var rowHeight = $(".fiche").height();
			var offsetFirstRow = $(".fiche:first-child").offset().top;
			var offsetNewRow = offsetFirstRow + (visibleRows*rowHeight);
			var numRows = commentsBlock.children().length
			
			//Affiche le nom de l'installation et le lien 
			$('.fiche-10').each(function(index, element) {
				var name = $(this).data('nom');
				var url = $(this).data('url');
				var lien_array = ['Découvrez cette installation','Discover this facility'];
				var lien = ( $("html").attr("lang") === "fr" ) ? lien_array[0] : lien_array[1];
				
				//console.log(name);
				$(this).find('.comment-title .cell-content').empty();
				$(this).find('.comment-title .cell-content').append('<h2>' + name + '</h2>');
				$(this).find('.comment-title .cell-content').append('<a href=" ' + url + '" class="arrow_link">' + lien + '</a>');
			});
			
			$(window).scroll(function(){
				//if the last row isnt visible yet
				if(visibleRows<numRows){
					var currentScroll = $(document).scrollTop() + $(window).height();
					//if the scroll is equal or greater to the position of the new row
					if(currentScroll>=offsetNewRow){
						visibleRows++;
						offsetNewRow = offsetFirstRow + (visibleRows*rowHeight);
						//detect if on mobile or not
						
						if($(window).innerWidth()>760){
							$(".fiche:nth-child("+visibleRows+")").css({'opacity':'0','top':'100px'}).show();
							$(".fiche:nth-child("+visibleRows+")").animate({top:'-=100px',opacity:'1'},500);
						}
						else{
							$(".fiche:nth-child("+visibleRows+")").css({'opacity':'0'}).show();
							$(".fiche:nth-child("+visibleRows+")").animate({opacity:'1'},500);
						}
						
					}
				}
			})
		}

	};
	var isFr = $("html").attr("lang") === "fr" ? true : false;
	if(isFr){
		sliderBtnText = ["precedant","prochaine"];
	}else{
		sliderBtnText = ["previous","next"];
	}
	
	var displayVisitesScolaire = function() {
		if($.urlParam('scolaire') == 1) {
			$('.anchor-visites-scolaires').show();
			$('.fiche-7').show();	
		}
	}
	
	/* Ajoutele paramètre ?scolaire=1 pour les visites des installations */	
	var addParamToVS = function(){

		var listBlock = $(".install-visites-scolaires");

		if(listBlock.length){ 
			$(listBlock).find('a.arrow_link').each(function(index, element) {
				$(this).attr('href', ($(this).attr('href')+'?scolaire=1'));
			});
		}
	}
	
	$.urlParam = function(name){
		var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
		if (results==null){
		   return null;
		}
		else{
		   return results[1] || 0;
		}
	}
  
	displayVisitesScolaire();
	addParamToVS();
	generateMailto();
	specialSitesMenu();
	reFormatAccordionCode();
	mapFichePos();
	commentsList();
	scrollLinks();
	printFicheInfo();
	commentsPage();
	 //$("select").selectBoxIt();
	

})(window, document, jQuery);
