﻿var LC = {};
if(document.location.href.indexOf("localhost") != -1) LC.base = "http://localhost/lutherie-clanet/";
else LC.base = "http://www.lutherie-clanet.com/";

// speciale dédicasse à Pedro pour les Nodes, le SiteTree et l'ancre à plusieurs morceaux !!

LC.init = function()
{
	//LC.initDebug();
	$("#sidebar").css("display", "none");
	LC.separator = "//";
	LC.loader = "<img class='loader' src='" + LC.base + "images/loader.gif' width='16' height='16' />";
	LC.URLLoaded = {};
	LC._nextId = 0;
	
	LC.initSiteTree();
	LC.initWork();
	LC.initMain();
	
	LC.initLinks();
	LC.initSWFAddress();
}

/* Récupère la position verticale de la cible (node) et fait scroller le browser pour l'atteindre */
LC.scrollPage = function(node)
{
	var label = node.label;
	var a = $("a[href="+LC.base + node.path()+"/]");
	var value = a.position().top;
	$("html").animate({scrollTop: value}, 500);
	$("body").animate({scrollTop: value}, 500);
}

// SITE TREE

// Initialisation du Tree
LC.initSiteTree = function()
{
	LC.tree = new LC.Tree();
	
	var a = $("#sidebar a");
	
	// Parcourt des liens de la sidebar
	for (var i = 0; i < a.length; i++)
	{
		var href = a[i].href;
		href = href.split(LC.base).join("");
		var segments = href.split("/");
		
		var node;
		var parentNode = LC.tree.root;
		
		// Ajout des enfants dans le noeud parent
		for (var j = 0; j < segments.length; j++) 
		{
			nodeId = segments[j];
			
			if (!nodeId.length) break;
			if (parentNode.getChild(nodeId) == undefined) 
			{
				node = new LC.Node(nodeId, parentNode);
				parentNode.addChild(node);
			}
			
			parentNode = parentNode.getChild(nodeId);
		}
	}
}

LC.Tree = function()
{
	this.root = new LC.Node();
	this.label = "";
	
	// Activation d'un noeud dans l'arbre quand on clique sur un lien
	this.activateLink = function()
	{
		this.blur();
		var path = this.href;
		path = path.split(LC.base).join("");
		if(path.charAt(path.length - 1) == "/") path = path.substr(0, path.length - 1);
		
		var ids = path.split("/");
		var n = ids.length;
		
		var parentNode = LC.tree.root;
		var node;
		
		// Toggle active des noeuds de niveau 1
		if(n == 1)
		{
			id = ids[0];
			
			if(id == "#") return;
			
			node = parentNode.getChild(id);
			
			node.clicked = true;
			node.active = !node.active;
			
			// Clic sur un lien d'ancre ex: "contactez-l'atelier"
			if($(this).parent()[0].tagName != "H2") 
			{
				node.active = true;
				LC.scrollPage(node);
			}
		}
		else
		{
			// Parcourt les node du tree
			for (var i = 0; i < n; i++)
			{
				id = ids[i];
				node = parentNode.getChild(id);
				
				if(parentNode != LC.tree.root)
				{
					// Désactiver les autres nodes
					for (var j = 0; j < parentNode.children.length; j++)
					{
						parentNode.children[j].active = false;
					}
				}
				
				node.active = true;
				node.clicked = true;
				parentNode = node;
			}
		}
		
		// Mise a jour de l'ancre
		LC.tree.updateHash();
		return false;
	}
	
	// Synchro Tree / Hash
	this.updateHash = function()
	{
		var hash = [];
		var children = LC.tree.root.children;
		var child;
		var childActivePath;
		for (var i = 0; i < children.length; i ++)
		{
			child = children[i];
			childActivePath = child.getActivePath();
			if(childActivePath) hash.push(childActivePath);
		}
		
		// Mise à jour de l'ancre
		SWFAddress.setValue(hash.join(LC.separator));
	}
	
	// Synchro Hash > Tree
	this.updateTree = function(hashTree)
	{
		this.browseChildren(this.root, hashTree.root);
	}
	
	this.browseChildren = function(node, hashNode)
	{
		var nodeChildren = node.children;
		if(!nodeChildren || !hashNode) return;
		var hashChildren = hashNode.children;
		if(!hashChildren) return;
		var n = nodeChildren.length;
		var nh = hashChildren.length;
		var child;
		var childLabel;
		var childActive;
		var hashChild;
		
		// Parcourt les noeuds de l'arbre
		for (var i = 0; i < n ; i++)
		{
			active = false;
			child = nodeChildren[i];
			childLabel = child.label;
			
			// noeud déjà actif ?
			childActive = child.active;
			
			// 
			if(nh == 0) { child.deactivate() }
			
			// Cherche parmis les hashNodes si un correspond au noeud en cours de traitement
			for (var j = 0; j < nh; j++)
			{
				hashChild = hashChildren[j];
				if(childLabel == hashChild.label) 
				{
					child.active = true;
					// Traitement récursif pour descendre au niveau inférieur
					this.browseChildren(child, hashChild);
					break;
				}
				else if(j == nh - 1)
				{
					//child.active = false;
					child.deactivate();
				}
			}
			
			//if(childActive != child.active || child.clicked) 
			//{	
				LC.nodeChange(child);
				child.clicked = false;
			//}	
		}
	}
	
	this.path = function() { return ""; }
	this.toString = function() { return "[tree]"; }
}

LC.Node = function (label, parent, active)
{
	if(active == undefined) active = false;
	this.label = label ? label : "";
	this.active = active;
	this.parent = parent;
	this.children = [];
	this.childrenByLabel = {};
	this.clicked = false;
	this.depth = 0;
	if(parent) this.depth = parent.depth + 1;
	
	this.deactivate = function()
	{
		this.active = false;
		var n = this.children.length;
		if(this.chidren && this.chidren.length)
		{
			for(var i = 0; i < n; i ++)
			{
				this.children[i].deactivate();
			}
		}
	}
	
	this.getActivePath = function()
	{
		var p;
		if(!this.active) 
		{
			p = "";
		}
		else
		{
			p = this.path();
			if(this.children.length)
			{
				var child;
				for  (var i = 0; i < this.children.length; i++)
				{
					child = this.children[i];
					if(child.active) p = child.getActivePath();
				}
			}
		}
		
		return p;
	}
	
	this.path = function()
	{
		var path = "";
		if(this.parent) 
		{
			pp = this.parent.path();
			if(pp.length) path = pp + "/";
		}
		
		return path + this.label;
	}
	this.toString = function () {
        return this.parent ? this.label + ' ' + this.parent.toString() : "";
    };
	
	this.addChild = function(child)
	{
		this.children.push(child);
		this.childrenByLabel[child.label] = child;
	}
	
	this.getChild = function(label)
	{
		return this.childrenByLabel[label];
	}
}


// Arbre temporaire crée à partir du hash
LC.HashTree = function(hash)
{
	this.label = "";
	this.root = new LC.Node("#");
	this.path = function()
	{
		return "[hash tree]";
	}
	
	this.toString = function () {
        return "HASH";
    };
	
	if (hash.indexOf("/") == 0) hash = hash.substr(1);
	
	// Le hashTree a autant de branche qu'il y a de sections dans l'ancre
	var sections = hash.split(LC.separator);
	var section;
	
	for (var i = 0; i < sections.length; i++) 
	{
		section = sections[i];
		
		var parentNode = this.root;
		var nodes = section.split("/");
		var node;
		
		// Chaque section contient une succession d'id de noeud
		for (var j = 0; j < nodes.length; j++) 
		{
			nodeId = nodes[j];
			if (!nodeId.length) continue;
			else
			{
				node = new LC.Node(nodeId, parentNode, true);
				parentNode.addChild(node);
				parentNode = node;
			}
		}
	}
}

LC.initSWFAddress = function()
{
	SWFAddress.addEventListener("change", LC.handleChange);
}

LC.handleChange = function()
{
	var hashTree = new LC.HashTree(SWFAddress.getValue());
	LC.tree.updateTree(hashTree);
}

LC.nodeChange = function(node)
{
	var root = LC.tree.root;
	if(node.depth == 1)
	{		
		switch(node.label)
		{
			case "creations" : 
			case "reparations-et-personnalisations" : 
			case "presentation" : 
			case "informations" : 
			case "liens" : 
				LC.slideToggleNode(node);
				break;
			
		}
	}
	else if(node.active)
	{
		if(node.depth == 2 && node.parent.label == "reparations-et-personnalisations") LC.repairSlideToggleNode(node);
		else if(node.depth == 3 && node.parent.parent.label == "creations") LC.loadCreaNode(node);
	}
}


//{ DEBUG
LC.initDebug = function()
{
	var output = $("<div id='out' />");
	//output.css("background-color", "#eee");
	output.css("font-family", "Courier New");
	output.css("font-size", "12px");
	output.css("width", "250px");
	output.css("height", "100%");
	output.css("position", "absolute");
	//output.css("text-align", "right");
	output.css("overflow", "scroll");
	output.css("top", "0");
	output.css("float", "left");
	$("#page").before(output);
	LC.log("DEBUG READY!");
}

LC.log = function(msg)
{
	$("#out").append(msg + "<br />");
}
//}

//{ LINKS

LC.initLinks = function()
{
	var a = $("a");
	a.each(LC.initLink);
}

LC.initLink = function()
{
	$(this).click(LC.tree.activateLink);
}

// Compteur pour déterminer un ID unique
LC.nextId = function() { return LC._nextId++; }

LC.trackLink = function(context)
{
	var value;
	
	switch(context.tagName)
	{
		case "A":
			value = context.href;
			break;
		case "H2":
			value = context.title + "-" + ($(context).parent().children(".content").css("display") == "none" ? "open" : "close");
			break;
		case "IMG":
			value = context.src;
			break;
	}
	
	// clean up
	if(value) 
	{
		value = "/" + value.split(LC.base).join("");
		
		// track
		try
		{
			var pageTracker = _gat._getTracker("UA-3307432-1");
			pageTracker._trackPageview(value);
		}
		catch(err) {}
	}
}

//}


//{ HOME

LC.initMain = function()
{
	$("h2.title").each(LC.initTitle);
	$("#bottom .content").append("contact@lutherie-clanet.com");
}

LC.initTitle = function()
{
	var aa = $("#sidebar a");
	var a;
	for(var i = 0; i < aa.length; i++)
	{
		if(aa[i].innerHTML == this.innerHTML) 
		{
			a = aa[i];
			break;
		}
	}
	
	$(this).html(a);
	this.title = a.innerHTML;
	$(a).data("backgroundColor", $(a).css("backgroundColor"));
	$(a).data("textColor", $(a).css("color"));
	$(this).mouseover(LC.titleOver);
	$(this).mouseout(LC.titleOut);
	$("a", this).click(LC.titleClick);
	$(this).css("cursor", "pointer");
}
LC.titleClick = function ()
{
	LC.trackLink($(this).parent()[0]);
}
LC.titleOver = function()
{
	var a = $("a", this);
	a.animate({color:"#fff", backgroundColor:"#333"}, { queue:false, duration:200 });
}
LC.titleOut = function()
{
	var a = $("a", this);
	a.animate({color:a.data("textColor"), backgroundColor:a.data("backgroundColor")}, { queue:false, duration:200 });
}

//}

//{ WORK


LC.initWork = function()
{
	LC.initCrea();
	LC.initRepair();
}

//}

//{ CREATIONS

LC.initCrea = function()
{
	// Récupérer le menu dans la sidebar
	var creaMenu = $("#sidebar ul li a[title=Créations]").parent().children("ul");
	$("#crea .menu").html(creaMenu);
	
	// Block contact
	$("#crea .contact").css("display", "none");
	
	// Ecouter les clics
	$("#crea .menu li li a").each(LC.initCreaMenu);
	
	// Désactiver les clics au premier niveau (catégories de guitares)
	var category = $(">li>a", creaMenu);
	
	category.click(LC.disableClick);
	category.css("cursor", "default");
}

LC.disableClick = function()
{
	this.blur();
	return false;
}

LC.initCreaMenu = function()
{
	if(this.id == undefined || this.id.length == 0) 
	{
		this.id = "crea_" + LC.nextId();
	}
	
	$(this).css("cursor", "pointer");
}

LC.loadCreaNode = function(node)
{
	var a = $("a[href=" + LC.base + node.path() + "/]")[0];
	a.blur();
	
	LC.trackLink(a);
	
	var h = $('#crea .imageContainer').height();
	if(h == 0) h = 30;
	
	// Première sélection d'une créa
	if(LC.currentCrea == undefined)
	{
		// Ouverture du imageContainer
		$("#crea .imageContainer").slideDown("slow");
	}
	
	// Evite de cliquer un élément ouvert
	if(LC.currentCrea != undefined && LC.currentCrea == a.id) return false;
	else
	{
		// Restaure le curseur "pointer" sur l'élément ouvert précédemment
		$("#" + LC.currentCrea).css("cursor", "pointer");
		$("#crea .selected").removeClass("selected");
		
		// Retire curseur "pointer" sur l'élement cliqué
		$(a).css("cursor", "default");
		$(a).addClass("selected");
		
		// Récupère, cache et place les images affichées dans la frisé dans l'élément du menu corespondant
		var currentContent = $('#crea .imageContainer .content');
		currentContent.css("display", "none");
		//
		var menuContainer = $("#" + LC.currentCrea).parent();
		currentContent.appendTo(menuContainer);
	}
	
	// Stockage de l'id de l'élément affiché
	LC.currentCrea = a.id;
	
	// Chargement de la page
	if(!LC.URLLoaded[a.href]) 
	{
		// On place un loader dans le menu
		$(a).after("<div class='content'></div>");
		$("#crea .imageContainer").html("<div class='content'>" + LC.loader + '</div>');
		$('#crea .imageContainer .content').css("height", h);
		$('#crea .imageContainer .content').css("display", "block");
		
		$.ajax({
			url: a.href,
			success: function(data)
			{
				LC.updateCrea(data);
			}
		});
		
		return false;
	}
	else
	{
		// La page a déjà été chargée, on peut afficher la liste des réparations éffectuées
		//$(">.content", $("#" + LC.currentCrea).parent()).slideDown();
		
		$("#crea .imageContainer .imagePan").html("");
		
		// Et on affiche les images dans la frise
		LC.displayCrea();
		
		return false;
	}
	
	return false;
}

LC.updateCrea = function(html)
{
	// Active le flag de chargement
	var href = $("#" + LC.currentCrea)[0].href;
	LC.URLLoaded[href] = true;
	
	// Mise à jour du menu : la liste des travaux effectués et la série d'images
	// sont placés dans le div en dessous de l'élément du menu qui vient d'être ouvert
	var data = $(".post", html);
	var content = $("#" + LC.currentCrea).parent().children("div.content");
	content.html(data);
	content.css("display", "none");
	
	// Suivi du chargement des images
	var img = $("img", content);
	img.css("display", "none");
	
	// Lorsque le chargement sera terminé, on affichera la frise d'images
	LC.displayCrea();
}


LC.displayCrea = function()
{
	var crea = $("#" + LC.currentCrea).parent().children("div.content");
	var imgs = $("img", crea);
	LC.currentCreaThumb = null;
	
	var contact = $("#crea .contact");
	contact.css("display", "block");
	
	if(!crea.hasClass("ready")) 
	{
		crea.addClass("ready");
		
		var technicalInfo = $("ul", crea);
		technicalInfo.wrap("<div class='tech'></div>"); 
		technicalInfo.before("<div class='thumb'><div class='thumbContent' /></div>");
		technicalInfo.after(contact);
		technicalInfo.after("<div class='gallery'></div>");
		technicalInfo.parent().after("<div class='imagePan' />");
		
		imgs.css("display", "none");
		
		if(imgs.length)
		{
			var thumbContainer = $(".thumb", crea);
			var thumb = $("<img src='" + imgs[0].src + "'/>");
			
			thumb.load(LC.initThumb);
			thumbContainer.html(thumb);
			
			// Affichage auto de la première image
			imgs.each(LC.initGallery);
			imgs.load(LC.updateGallery);
		}
	}
	
	LC.imagePan = $(".imagePan", crea);	
	
	imgs = $(".gallery img", crea);
	if(imgs.length)
	{
		LC.currentCreaThumb = null;
		LC.loadPan(imgs[0]);
	}
	
	// Supression du loader
	var container = $('#crea .imageContainer');
	container.html("");
	
	crea.appendTo(container);
	crea.css("display", "block");
}

LC.addContactBlock = function(technicalInfo)
{
	var s = '<p class="contact">Pour connaître les tarifs, <a href="informations">contactez l’atelier</a></p>';
	technicalInfo.after(s);
	LC.initLinks(technicalInfo);
}

/* Vignette de la fiche technique */
LC.initThumb = function()
{
	var thumbContainer = $("#crea .imageContainer .thumb");
	var thumbContent = $(this).wrap("<div class='thumbContent' />");
	
	var containerWidth = thumbContainer.width();
	var containerHeight = thumbContainer.height();
	var containerRatio = containerWidth / containerHeight;
	
	var thumbWidth = this.width;
	var thumbHeight = this.height;
	var thumbRatio = thumbWidth / thumbHeight;
	
	if(thumbRatio > containerRatio)
	{
		thumbContent.width(thumbWidth); 
		thumbContent.height(containerHeight);
		$(this).css("width", containerHeight * thumbRatio);
		$(this).css("height", containerHeight);
	}
	else
	{
		thumbContent.width(containerWidth); 
		thumbContent.height(thumbHeight); 
		$(this).css("width", containerWidth);
		$(this).css("height", containerWidth / thumbRatio);
	}
}

/* Vignette de la gallery */
LC.initGallery = function()
{
	var gallery = $(".gallery", $(this).parent().parent());
	var img = $(this);
	img.appendTo(gallery);
	img.wrap("<div class='crop'/>");
	img.click(LC.updatePanClick);
	img.css("cursor", "pointer");
	img.css("display", "block");
}

LC.updateGallery = function()
{
	var w = this.width;
	var h = this.height;
	var r = w / h;
	
	if(w > h)
	{
		$(this).css("width", 50 * r)
		$(this).css("height", 50);
	}
	else
	{
		$(this).css("width", 50);
		$(this).css("height", 50 / r);
	}
	var img = $(this);
}

LC.updatePanClick = function()
{
	var img = $(this);
	LC.loadPan(img[0]);
}

LC.loadPan = function(thumb)
{
	if($(thumb).parent().hasClass("selected")) return;
	
	LC.trackLink(thumb);
	
	// Restaure la vignette sélectionnée
	if(LC.currentCreaThumb) LC.currentCreaThumb.removeClass("selected");
	
	LC.currentCreaThumb = $(thumb).parent();
	LC.currentCreaThumb.addClass("selected");
	
	var img = $(LC.getImageFromThumb(thumb));
	LC.imagePan.html(img);
	img.css("display", "none");
	//LC.imagePan.fadeIn("slow");
	
	img.load(LC.updatePan);
}

LC.updatePan = function()
{
	LC.panWidth = parseInt(LC.imagePan.css("width"));
	LC.panHeight = parseInt(LC.imagePan.css("height"));
	
	LC.panContent = LC.imagePan.children("img");
	LC.panContent.css("display", "none");
	LC.panContentWidth = LC.panContent.width();
	LC.panContentHeight = LC.panContent.height();
	LC.imagePan.scrollLeft(0);
	LC.imagePan.scrollTop(0);
	
	//imagePan.unbind("mousemove");
	//imagePan.mousemove(function(e)
	//{
		//var kX;
		//var kY;
		//
		//if(e.pageX)
		//{
			//kX = (e.pageX - imagePan.offset().left) / panWidth;
			//kY = (e.pageY - imagePan.offset().top) / panHeight;
		//}
		//else
		//{
			//kX = 0.5;
			//kY = 0.5;
		//}
		//
		//var left = kX * (contentWidth-panWidth);
		//imagePan.scrollLeft(left);
		//
		//var top = kY * (contentHeight-panHeight);
		//imagePan.scrollTop(top);
	//});
	
	// Centre l'image
	//imagePan.mousemove();
	
	LC.clearPan();
	LC.panContent.unbind("mouseover");
	LC.panContent.mouseover(LC.startPan);
	LC.panContent.unbind("mouseout");
	LC.panContent.mouseout(LC.stopPan);
	
	$("img", LC.imagePan).fadeIn("slow");
	LC.panLoop(true);
}

LC.startPan = function ()
{
	LC.panMouseOut = false;
	//var imagePan = $("#crea .imageContainer .imagePan");
	
	LC.imagePan.unbind("mousemove");
	LC.imagePan.mousemove(LC.mousemove);
	
	clearInterval(LC.panInterval);
	LC.panInterval = setInterval("LC.panLoop()", 75);
}

LC.mousemove = function (e)
{
	LC.mouseX = e.pageX;
	LC.mouseY = e.pageY;
}

LC.panLoop = function (forced)
{
	var kX;
	var kY;
	
	var imagePan = LC.imagePan;
	var panWidth = LC.panWidth;
	var panHeight = LC.panHeight;
	
	var image = LC.panContent;
	var contentWidth = LC.panContentWidth;
	var contentHeight = LC.panContentHeight;
	
	if(forced)
	{
		kX = kY = 0.5;
		LC.lastPanLeft = (contentWidth - panWidth)/2;
		LC.lastPanTop = (contentHeight - panHeight)/2;
		//image.css("display", "none");
		//image.fadeIn("slow");
	}
	else
	{
		kX = (LC.mouseX - imagePan.offset().left) / panWidth;
		kY = (LC.mouseY - imagePan.offset().top) / panHeight;
		
		var left = kX * (contentWidth-panWidth);
		LC.lastPanLeft += (left - LC.lastPanLeft) * 0.5;
		
		var top = kY * (contentHeight-panHeight);
		LC.lastPanTop += (top - LC.lastPanTop) * 0.5;
		
		if(Math.abs(left - LC.lastPanLeft) < 1 && Math.abs(top - LC.lastPanTop) < 1) 
		{
			if(LC.panMouseOut) LC.clearPan();
			else return;
		}
	}
	
	imagePan.scrollLeft(LC.lastPanLeft);
	imagePan.scrollTop(LC.lastPanTop);
}

LC.stopPan = function ()
{
	LC.panMouseOut = true;
}

LC.clearPan = function ()
{
	clearInterval(LC.panInterval);
	LC.imagePan.unbind("mousemove");
	LC.imagePan.mousemove(LC.mousemove);
}

LC.getImageFromThumb = function(target)
{
	var src = target.src;
	src = src.split("thumbs/").join("");
	return "<img src='" + src + "' />";
}

LC.number = function(s)
{
	return parseInt(s.split("px").join(""));
}

//}

//{ REPAIR

LC.initRepair = function()
{
	// Récupérer le menu dans la sidebar
	var sidebarMenu = $("#sidebar ul li a[title=Réparations et personnalisations]").parent().children("ul");
	repairMenu = $("#repair .menu");
	repairMenu.append(sidebarMenu);
	
	var contact = $("#repair .contact");
	contact.appendTo(repairMenu);
	
	// Ecouter les clics
	$("#repair .menu a").each(LC.initRepairMenu);
}

LC.initRepairMenu = function()
{
	if(this.id == undefined || this.id.length == 0) 
	{
		this.id = "repairItem_" + LC.nextId();
	}
	
	$(this).css("cursor", "pointer");
	$(this).click(LC.repairSlideToggle);
}

LC.repairSlideToggleNode = function(node)
{
	var a = $("a[href="+LC.base + node.path()+"/]")[0];
	a.blur();
	
	// Evite de cliquer un élément ouvert
	if(LC.currentRepair != undefined && LC.currentRepair == node.label) return false;
	else
	{
		// Restaure le curseur "pointer" sur l'élément ouvert précédemment
		$("#" + LC.currentRepair).css("cursor", "pointer");
		$("#" + LC.currentRepair).removeClass("selected");
		
		// Retire curseur "pointer" sur l'élement cliqué
		$(a).css("cursor", "default");
		$(a).addClass("selected");
		
		// Récupère, cache et place les images affichées dans la frisé dans l'élément du menu corespondant
		var currentImgs = $('#repair .imageContainer .content img');
		currentImgs.css("display", "none");
		
		var content = $("#" + LC.currentRepair).parent().children("div.content");
		content.after(currentImgs);
		content.slideUp();
	}
	
	LC.trackLink(a);
	
	// Stockage de l'id de l'élément affiché
	LC.currentRepair = a.id;
	
	// On cache la flèche
	$("#repair .arrow").css("display", "none");
	
	// Chargement de la page
	if(!LC.URLLoaded[a.href]) 
	{
		// On place un loader dans le menu
		$(a).after("<div class='content'>" + LC.loader + "</div>");
		$('#repair .imageContainer').scrollLeft(0);
		$('#repair .imageContainer .loader').css("display", "block");
		$('#repair .imageContainer').css("display", "block");
		
		$.ajax({
			url: a.href,
			success: function(data)
			{
				LC.updateRepair(data);
			}
		});
		
		return false;
	}
	else
	{
		// La page a déjà été chargée, on peut afficher la liste des réparations éffectuées
		$(">.content", $("#" + LC.currentRepair).parent()).slideDown();
		
		// Et on affiche les images dans la frise
		LC.displayRepair();
		
		return false;
	}
}

// Fin du chargement AJAX de la page
LC.updateRepair = function(html)
{
	// Active le flag de chargement
	var href = $("#" + LC.currentRepair)[0].href;
	LC.URLLoaded[href] = true;
	
	// Mise à jour du menu : la liste des travaux effectués et la série d'images
	// sont placés dans le div en dessous de l'élément du menu qui vient d'être ouvert
	var data = $(".post .entry ul,.post .entry img", html);
	var content = $("#" + LC.currentRepair).parent().children("div.content");
	content.html(data);
	content.css("display", "none");
	content.fadeIn("fast");
	
	// Suivi du chargement des images
	var img = $("img", content);
	img.css("display", "none");
	
	// Lorsque le chargement sera terminé, on affichera la frise d'images
	LC.loadImages(img, LC.displayRepair);
}

// Affichage d'une réparation
LC.displayRepair = function()
{
	$("#repair .arrow").css("display", "block");
	$('#repair .imageContainer .loader').css("display", "none");
	
	// Les images sont placées dans la frise
	var img = $("img", $("#" + LC.currentRepair).parent());
	img.css("display", "block");
	var container = $('#repair .imageContainer .content');
	container.css("display", "block");
	container.html(img);
	
	// Les paramètres du scroll sont mis à jour
	LC.updateScroll();
}

LC.updateScroll = function()
{
	var imageContainer = $('#repair .imageContainer');
	var content = $('#repair .imageContainer .content');

	// Calcul la taille du contenu : somme de la largeur des images à afficher
	var imgs = content.children("img");
	var contentWidth = 0;
	for (var i = 0 ; i < imgs.length; i++) 
	{
		contentWidth += $(imgs[i]).data("imgWidth");
	}
	
	// Animation
	var scrollWidth = imageContainer.width();
	imageContainer.scrollLeft(0);
	imageContainer.unbind("mousemove");
	
	imageContainer.mousemove(function(e)
	{
		var k = (e.pageX - imageContainer.offset().left) / scrollWidth;
		left = k * (contentWidth-scrollWidth);
		imageContainer.scrollLeft(left);
	});
	
	// Apparition
	content.css("width", contentWidth); // 2010.09 fix
	imageContainer.css("display", "none");
	imageContainer.fadeIn("slow");
	//$("#repair .arrow").fadeIn("slow");
}

//}


// Suivi du chargement d'une liste d'images
LC.loadImages = function(images, callback)
{
	if(callback) LC.imageComplete = callback;
	
	if(images.length == 0) 
	{
		if(LC.imageComplete) LC.imageComplete();
		return;
	}
	
	LC.images = {};
	LC.images.loading = images.length;
	
	// Images loading
	images.load(LC.imageLoaded);
}

LC.imageLoaded = function()
{
	LC.images.loading --;
	
	$(this).data("imgWidth", $(this).width());
	
	// Fin du chargement, éxécution du callback
	if(LC.images.loading == 0 && LC.imageComplete) LC.imageComplete();
}


//{ PRESENTATION

LC.initPresentation = function() 
{
	$("presentation").click(LC.togglePresentation);
}

LC.loadPresentation = function()
{
	LC.presentationLoaded = true;
	$("#biography").load(LC.base + "presentation/bruno-clanet-dit-lamanit/ #content .post");
	$("#workshop").load(LC.base + "presentation/atelier/ #content .post");	
}

LC.loadInformations = function()
{
	LC.informationsLoaded = true;
	
	// Contact
	$("#contacts").css("float", "left");
	$("#contacts").load(LC.base + "informations/contact/ #content .post");
	
	// Accès
	$("#access").css("float", "left");
	$("#access").load(LC.base + "informations/acces/ #content .post");
}


//}

//{ LINKS

LC.loadLinks = function ()
{
	LC.linksLoaded = true;
	$("#links .content").html(LC.loader);
	$("#links .content").load(LC.base + "liens/ #content .post");
}

//}

//{

LC.slideToggleNode = function(node)
{
	var id = node.label;
	if(id == "presentation" && !LC.presentationLoaded) LC.loadPresentation();
	else if(id == "informations" && !LC.informationsLoaded) LC.loadInformations();
	else if(id == "liens" && !LC.linksLoaded) LC.loadLinks();
	
	var content = $(">.content", $("a[href="+LC.base+node.path()+"/]").parent().parent())
	if(node.active) content.slideDown();
	else content.slideUp();
}

//}

$(document).ready(function(){LC.init();});
