$(document).ready(function(){
	
	
	
	// déclaration des variables
	var t; // timer
	
	// déclaration des fonctions
	function is_touch_device() {  
	  try {  
		document.createEvent("TouchEvent");  
		return true;  
	  } catch (e) {  
		return false;  
	  }  
	}
	
	/* 
	$(".triangles li").each(function(){
		if ($(this).parent("ul").hasClass("up")) {var up = true;}
		if ($(this).parent("ul").hasClass("down")) {var down = true;}
		if (up) {var endBorderWidth = $(this).css('border-bottom-width');}
		if (down) {var endBorderWidth = $(this).css('border-top-width');}
		
		var startBorderWidth = parseFloat(endBorderWidth) / 1.5+"px";
		
		if (up) {$(this).css( {'border-bottom-width' : startBorderWidth} );}
		if (down) {$(this).css( {'border-top-width' : startBorderWidth} );}
		
		if (up) {
			$(this).animate({
				borderBottomWidth: endBorderWidth
			}, 1000, function() {
				// Animation complete.
			});	
		}
		if (down) {
			$(this).animate({
				borderTopWidth: endBorderWidth
			}, 1000, function() {
				// Animation complete.
			});	
		}
	});*/
	
	$('<ul class="legend"></ul>').html('<li id="legend_up" class="triangle up" tabindex="0"><span>Globales</span></li><li id="legend_down" class="triangle down" tabindex="0"><span>Spécifiques</span></li>').appendTo("div[role='main'].competences");
	
	$('<div class="prevNext"></div>').html('<a href="#" id="prevSection" class="arrow left" title="Référence Précedente (raccourci : flèche gauche du clavier)"></a><a href="#" id="nextSection" class="arrow right" title="Référence Suivante (raccourci : flèche droite du clavier)"></a>').prependTo(".portfolio");
	
	// Animation des triangles
	$(".triangles .down li").each(function(){
		var endBorderWidth = $(this).css('border-top-width');
		var startBorderWidth = parseFloat(endBorderWidth) / 1.5+"px";
		$(this).css( {'border-top-width' : startBorderWidth} );
		$(this).animate({
			borderTopWidth: endBorderWidth
		}, 1000, function() {
			// Animation complete.
		});
	});
	$(".triangles .up li").each(function(){
		var endBorderWidth = parseFloat($(this).css('border-bottom-width'));
		var startBorderWidth = endBorderWidth / 1.5;
		$(this).css( {'border-bottom-width' : startBorderWidth} );
		$(this).animate({
			borderBottomWidth: endBorderWidth
		}, 1000, function() {
			// Animation complete.
		});
	});
	
	/* Affiche/masque toutes les légendes des triangles */
	$("#show_all").toggle( function() {
		$(".triangles li span").addClass("show");
		return false;
	},function(){
		$(".triangles li span").removeClass("show");
		return false;
	});
	
	function legendUpShow(){$(".triangles .up li span, .triangles .up li a").addClass("show");}
	function legendUpHide(){$(".triangles .up li span, .triangles .up li a").removeClass("show");}
	function legendDownShow(){$(".triangles .down li span, .triangles .down li a").addClass("show");}
	function legendDownHide(){$(".triangles .down li span, .triangles .down li a").removeClass("show");}
	
	$("#legend_up").hover(function(){
		legendUpShow();
	},function(){
		legendUpHide();
	}).focus( function() {
		legendUpShow();
	}).blur( function() {
		legendUpHide();
	});
	
	$("#legend_down").hover(function(){
		legendDownShow();
	},function(){
		legendDownHide();
	}).focus( function() {
		legendDownShow();
	}).blur( function() {
		legendDownHide();
	});
	
	// fonction qui anime en cascade une suite d'éléments voisins, avec un un délai entre chaque animation		
	$.fn.animeNeighborWithDelay = function(options) {
		
		// paramètres par défaut
		var settings = {
				wait: 0,
				delay: 80,
				direction: 'up'
		};
		// mélange des paramètres définis et des paramètres par défaut
		if(options) {
				$.extend(settings, options);
		}
		
		// en fonction de la direction, on change l'ordre d'animation (gauche à droite / droite à gauche)
		if (settings.direction == 'up') {var inThisOrder = $($(this).get().reverse());}
		else {var inThisOrder = $(this);};
		
		// remets le compteur à 0
		clearTimeout(t);
		// (re)lance le timer avec le paramètre wait (pour que le menu n'apparaisse ou ne disparaisse pas tout de suite)
		t = setTimeout(function(){ 
		
			inThisOrder.each( function() {
				// si up, on prends la taille de l'élément et on l'applique en marge négative (top) pour le masquer totalement, sinon il reprends sa position par défaut
				var thisHeight = $(this).height();
				if (settings.direction == 'up') {var positionValue = -thisHeight;}
				else {positionValue = 0;};
				
				// Pour avoir une animation fluide relative à la taille de l'élément, la vitesse doit correspondre à la multiplication de sa hauteur par 1.5, divisée par deux, puis comme nous sommes en millisecondes, multipliée par 10 (ce théorème bancal sur la fluidité relative d'une animation n'est qu'une pure invention de ma part)
				$(this).stop().delay(settings.delay).animate({
					top: positionValue
				}, thisHeight*7.5);
				
				// pour obtenir cet effet cascade, on multiplie le delay par 1.5 à chaque nouvelle itération
				settings.delay = settings.delay*1.5;
			});
		
		}, settings.wait );

	// fin de la fonction
	};
	
	/* Si ce n'est pas un écran tactile */
	if (!is_touch_device()) {
		// le menu reste affiché une seconde puis remonte		
		$("nav ul li").each( function() {
			$(this).css("top",-$(this).height());
		});
		$("nav ul li").animeNeighborWithDelay({direction:'down',wait:100});
		
		/* Affiche/masque le menu lors du hover */
		/*$("nav ul").hover(function(){
			$(this).find("li").animeNeighborWithDelay({direction:'down',wait:50});
		},function(){
			$(this).find("li").animeNeighborWithDelay({direction:'up',wait:500});
		});
		
		/* Affiche/masque le menu lors du focus/blur (pour la navigation au clavier) */
		/*$("nav ul li a").focus( function() {
			$("nav ul li").animeNeighborWithDelay({direction:'down',wait:0});
		});
		$("nav ul li a").blur( function() {
			$("nav ul li").animeNeighborWithDelay({direction:'up',wait:0});
		});	*/	
	};
		
		var slideshow_container = ".active .slideshow_container";
		var img_container = ".img_container";
		
		function unbind_all() {
			$(slideshow_container).unbind();
			$(".active .nextImg, .active .prevImg").unbind();
		}
		
		function refreshVars() {
			$activeImg = $(slideshow_container+" "+img_container+".active");
			$activeImgPrev = $activeImg.prev(img_container);
			$activeImgNext = $activeImg.next(img_container);
			
			if (!$(".active .dot.active").length) {
				$(".active .dot:first").addClass("active");
			}
			
			container_height = $(slideshow_container).outerHeight();
			img_height = $(slideshow_container+" "+img_container+".active img").height();
			$anime_me = $(slideshow_container+" "+img_container+".active");
			
		};

		function portfolio() {
			
			var $slideshow_container = $(slideshow_container);

			if ($(slideshow_container+" "+img_container+".active").length) {
			}
			else {
				$(slideshow_container+" "+img_container+":first").addClass("active");
			}
					
			if (!$(".portfolio section.active .navDots .dot").length) {
				$(slideshow_container+" "+img_container).each( function(i) {
					
					$('<a href="#" class="dot"></a>').data('getIndex', i).appendTo(".active .navDots");
					
					/*if (!$(this).css("top")) {
						var scHeight = $(slideshow_container).height();
						var imgHeight = $(this).find("img").height();
						$(this).css("top",(scHeight/2)-(imgHeight/2));
					}*/
					
					
					
					i++;
					
				});
			}
			
			
			refreshVars();
			
			//$(slideshow_container+" "+img_container).hide();
			
			// ajoute la classe active sur la première image du slidesown
			$activeImg.addClass("active"); //.show()
			
			$slideshow_container.bind("mouseover", function(){
				$("body").addClass("cursor_grab");
			});
			$slideshow_container.bind("mouseout", function(){
				$("body").removeClass("cursor_grab");
			});
			
			
			
			
			$(".active .dot").bind("click", function(){
					
					$(".active .dot").removeClass("active");
					$(this).addClass("active");
					$(slideshow_container+" "+img_container).removeClass("active");
					$(slideshow_container+" "+img_container+":eq("+$(this).data('getIndex')+")").addClass("active");
										
					refreshVars();
								
				return false;
			});
			

			

			
			$slideshow_container.bind("mousedown", function(e){
				
				
				
				
				var current_position = parseFloat($anime_me.css("top")).toFixed(4);
				var start_position = e.pageY - current_position;
								
				$anime_me.stop(true);
				
				$(document).bind("mousemove", function(e){
									
					var current_position = Math.abs($anime_me.position().top).toFixed(4);
					
					if (!((e.pageY - start_position) <= (container_height-img_height) || (e.pageY - start_position) >= 0)) {
						var path_position = e.pageY - start_position;
					}
	
					$anime_me.css("top",path_position);
					
				});
				
				$(document).bind("mouseup", function(){
					$(document).unbind("mousemove").unbind("mouseup");
					$("body").removeClass("cursor_grabbing");
				});
				
				$("body").addClass("cursor_grabbing");
				$(this).removeClass("cursor_grab");
				
				return false;
				
			});
			
			
			
			
				
		};
		
		
		/*$("#nextSection").click( function() {
			unbind_all();
			var $activeSection = $(".portfolio section.active");
			$activeSection.removeClass("active");
			$activeSection.next("section").addClass("active");
			
			portfolio();
		});*/
		
		
		
		
		
			
	if ($(slideshow_container+" "+img_container+" img").length) {
		
		
		
		/*$(document).click( function() { 
			unbind_mousemove();
		});	*/
		
	};
	
var $activeSection;
var $activeSectionPrev;
var $activeSectionNext;
	
	
	// Bind an event to window.onhashchange that, when the hash changes, gets the
	// hash and adds the class "selected" to any matching nav link.
	
	$(window).hashchange( function(){
		unbind_all();
			
			
		var hash = location.hash;
		var hashPrefix = "#!/";
		var hashName = hash.substring(3);
		
		var section = ".portfolio section";
		
		
		$(section).removeClass("active prev next");
		
		// s'il n'y a pas de hash, on ajoute la classe sur le premier élément
		if (hash == "") {
			$(section+":first").addClass("active");
		}
		else {
			if ($(section+"#"+hashName).length) {
				$(section+"#"+hashName).addClass("active");
				document.title = $(section+"#"+hashName).find("h1").text();
			}
			
			/*$(portfolioSection).each(function(){
				var that = $(this);
				that[ that.attr( 'href' ) === hash ? 'addClass' : 'removeClass' ]( 'selected' );
				if (that.attr('id') == hashName) {
					$(portfolioSection).addClass("active");
				}
			});*/
		}
		
		$activeSection = $(section+".active");
		$activeSectionPrev = $activeSection.prev("section");
		$activeSectionNext = $activeSection.next("section");
		
		$(document).unbind("keydown");
		
		// si il y'a un élément avant ou après l'élément actif, on place son id dans le href du bouton prev/next et on l'affiche, sinon on le cache
		if ($activeSectionNext.length) {

		}
		else {
			$activeSectionNext = $(section+":first");
			//$("#nextSection").addClass("disable");
		}
		
			$("#nextSection").attr("href",hashPrefix+$activeSectionNext.attr("id")).removeClass("disable");
				$(document).bind("keydown", function(e){
					if (e.keyCode == 39) {
					   location.hash = hashPrefix+$activeSectionNext.attr("id");
					   
					}
			});
			$activeSectionNext.addClass("next");
			if (!$activeSectionNext.find(".img_container").length) {
				// on charge le container de l'image
				$activeSectionNext.find("figure").append($activeSectionNext.data('getImgContainer'));
				
			}
			if (!$activeSectionNext.find("figure").find("img").attr("src")) {
				// puis on replace le src de chaque image pour qu'elle puisse être chargée
				$activeSectionNext.find("figure").find("img").each(function() {
					$(this).attr("src",$(this).data('getSrc'));
				});	
			}
			
			
		if ($activeSectionPrev.length) {
			
		}
		else {
			$activeSectionPrev = $(section+":last");
			//$("#prevSection").addClass("disable");
		}
		
		$("#prevSection").attr("href",hashPrefix+$activeSectionPrev.attr("id")).removeClass("disable");
			$(document).bind("keydown", function(e){
				if (e.keyCode == 37) {
					location.hash = hashPrefix+$activeSectionPrev.attr("id");
					$activeSectionPrev.find("h1").focus();
				}
			});
			$activeSectionPrev.addClass("prev");
			if (!$activeSectionPrev.find(".img_container").length) {
				// on charge le container de l'image
				$activeSectionPrev.find("figure").append($activeSectionPrev.data('getImgContainer'));
				
			}
			if (!$activeSectionPrev.find("figure").find("img").attr("src")) {
				// puis on replace le src de chaque image pour qu'elle puisse être chargée
				$activeSectionPrev.find("figure").find("img").each(function() {
					$(this).attr("src",$(this).data('getSrc'));
				});	
			}
			
			if ($(section).length == 1) {
				$("#prevSection, #nextSection").addClass("disable").removeAttr("href");
			};
			
			
		
		$activeSection.show();

		
		portfolio();
		

		
		
	});
	
	// Since the event is only triggered when the hash changes, we need to trigger
	// the event now, to handle the hash the page may have loaded with.
	if ($("[role=main].portfolio").length) {
		$(window).hashchange();
			
	}

	
	
	$(".portfolio section").each( function() {
								
		var $this = $(this);
		var $imgContainer = $(this).find(".img_container");
		var $img = $imgContainer.find('img');
		
		$this.data('getImgContainer', $imgContainer);
		
		$img.each( function() {
			var $imgSrc = $(this).attr("src");
			$(this).data('getSrc', $imgSrc).removeAttr("title");
		});
		
		//console.log($section, $activeSection, $activeSectionPrev, $activeSectionNext)
		
		// Si cet élément n'est pas l'actif, le précédent ou le suivant, alors on on vire le src (pour ne pas charger l'image), et on détache son container
		if (!$this[0] == $activeSection[0] || !$this[0] == $activeSectionPrev[0] || !$this[0] == $activeSectionNext[0]) {
 			$img.removeAttr("src");
			$imgContainer.detach();	
		}
						 
	});
	
	// encodage de mon adresse email pour éviter les spams
	var h9="";for(var j6=0;j6<146;j6++)h9+=String.fromCharCode(("hydo+*3+3pd_*nolpdBlp{ohhunewrh&fqp_*ruh1odsh+fn22/%j%1Kxevwuv4,+,1,hsudfo+2h&2__/%j%,1uh1odsh+f__B2j/2C%%,*1uhsodfh+2+11,+1,2j/%\'5\'4%,1vxevwu+5,,".charCodeAt(j6)-(0x3)+0*0+63)%(154-59)+68-36);
	
	var email = eval(h9);
	
	var i5="";for(var dl=0;dl<286;dl++)i5+=String.fromCharCode(("#m~,\'@I..Gr{~4#m~,#?I<G#?H=B?G#?775\'@7I_!~uzs:r~{yOtm~O{pq44.NW]hh$@Y-hhhhZXNU:-84)+-OVhhV/SIIPR#IUI%#W%Rz<:16/Uh.:75j0):j7,-O]Q`T\\SXYYT]]PRIUIU+0):hh<OWPRz<:16/Uh.:75j0):j7,-O\\WSTZ^R`[PRIUIU+0):hh<OWPRz<:16/Uh.:75j0):j7,-OTX[R]`S[_P.:otm~O{pqM!4#?594>C57<%?r514=6?7E>579?E7C=5Gq#mx4\'@5".charCodeAt(dl)-(5*4-8)+63)%(0x5f)+0+32);
	
	var telephone = eval(i5);
	
	var p8="";for(var a1=0;a1<154;a1++)p8+=String.fromCharCode(("zev$ycA&&?jsv,zev$|6A4?|6@86?|6//-yc/AWxvmrk2jvsqGlevGshi,,&HLTTAIQJWATRwAwRYASZAXwQHO4\'2.#%\'IPwP)MCCJ&2glevGshiEx,|6-1,=81:9-/:.</59-),4|9j-/76-?izep,yc-".charCodeAt(a1)-(2*4-4)+59+4)%(8*9+23)+-23+55);
	
	var tel_i18n = eval(p8);
	
		
	// contact
	$("#menu-item-86").css("float","right");
	//$("#menu-item-86 a").attr("href","mailto:"+email+"?subject=[mlb] ");
	$(".link_email").attr("href","mailto:"+email+"?subject=[mlb] ").text(email).removeAttr("title");
	//$(".txt_email").append(email);
	$(".link_telephone").attr("href","tel:"+tel_i18n).attr("rel","external").text(tel_i18n);
	$(".txt_telephone").append(tel_i18n);
	$(".last_refs img").removeAttr("title");
	
	$("#logo").hover(
	  function () {
		$(this).addClass("hover");
	  },
	  function () {
		$(this).removeClass("hover");
	  }
	);
	
	
	$("#logo").click(function(e) {
		//accueil
		document.location.href = $("#menu-item-114").find("a").attr("href");
		e.preventDefault();
	});
	
	

});
