/******************************************
# LIGHTBOX - version 2 - 16.08.2008
# Auteur : Julien Theler - www.twiip.ch
# Contact : julien.theler@twiip.ch
# Licence : CC-by-nc
******************************************/


/*Chemin absolu du dossier lightbox*/
var lbPath = '';

/*Initialisation de variables globales*/
var imageSrc = '';
var imageWidth = 0;
var imageHeight = 0;
var contenuContent = '';
var contenuWidth = 0;
var arrayImages = new Array();
var arrayTitres = new Array();
var arrayPosition = 0;

/*Variables destinées à contenir des noeuds*/
var ciblebox = '';
var cibleswitch = '';
var arrowleft = '';
var arrowright = '';
var cibleloader = '';
var cibleimage = '';
var ciblecontenu = '';
var ciblecount = '';
var cibleclose = '';

var open = 0; //Interromp l'affichage de l'image si on a cliqué dessus pour la fermer avant qu'elle ne soit entièrement affichée
var closeHeight = 20; //Hauteur du lien "fermer", la variable sert à ajuster le positionnement vertical de l'image en prenant en compte cette hauteur

var openPHP = 0;//Indique qu'une fenêtre susceptible de contenir une page php est ouverte.

function initLightbox(path){
	lbPath = path;
	
	/*Ajout dynamique des objets utilisés par les lightbox*/
		//Div servant à griser l'écran
		var div = document.createElement("div");
		div.id = 'lightbox';
		div.style.display = 'none';
		div.style.opacity = '0.40';
		div.style.filter = 'filter:alpha(opacity=40)';
		document.body.appendChild(div);
		
		//Loader
		var div = document.createElement("div");
		div.id = 'loader';
		div.style.display = 'none';
		div.style.opacity = '0.40';
		div.style.filter = 'filter:alpha(opacity=40)';
		div.innerHTML = '<img src="'+lbPath+'loader.gif" />';
		document.body.appendChild(div);
		
		//Div destinée à contenir l'image
		var div = document.createElement("div");
		div.id = 'divbox';
		div_content = '<div name="marginBody"><div id="ciblecontenu" style="display: none; opacity: 0; filter:alpha(opacity=0);"></div></div>';
		div_content += '<a href="javascript:closebox(75);"><img id="cibleimage" src="" style="display: none; width: 0px; height: 0px; margin-top: 0px;" /></a>';
		div_content += '<div style="top: 0px; left: 0px;" id="count"></div>';
		div_content += '	<div name="marginBody"><div id="close" style="display: none; height: 0px;">';
		div_content += '		<table cellspacing="0" cellpadding="0" width="100%;"><tr>';
		div_content += '			<td align="left" width="30px"><a href="javascript:changeImage(\'-1\');" id="arrowleft" style="display: none;">&nbsp;</a></td>';
		div_content += '			<td align="center"><a href="javascript:closebox(75);">fermer</a></td>';
		div_content += '			<td align="right" width="30px"><a href="javascript:changeImage(\'+1\');" id="arrowright" style="display: none;">&nbsp;</a></td>';
		div_content += '		</tr></table>';
		div_content += '	</div></div>';
		div_content += '</div>';
		div.innerHTML = div_content;
		document.body.appendChild(div);
		
		//Image servant à passage progressif d'une image à l'autre
		var img = document.createElement("img");
		img.src = '';
		img.id = 'cibleswitch';
		img.style.display = 'none';
		img.style.opacity = '1';
		img.style.filter = 'filter:alpha(opacity=100)';
		img.style.width = '0px';
		img.style.height = '0px';
		img.style.top = '0px';
		img.style.left = '0px';
		document.body.appendChild(img);
}

function setVariables(contenu, image, width, height, array, position, titres){
	contenuContent = contenu;
	contenuWidth = parseInt(width);
	imageSrc = image;
	imageWidth = parseInt(width);
	imageHeight = parseInt(height);
	arrayImages = array;
	arrayTitres = titres;
	arrayPosition = parseInt(position);
}

function openbox(element){

	if(openPHP == 1){
		ciblecontenu.style.display = 'none';
		openPHP = 2;
	}
	
	ciblebox = document.getElementById('lightbox');
	cibleswitch = document.getElementById('cibleswitch');
	arrowleft = document.getElementById('arrowleft');
	arrowright = document.getElementById('arrowright');
	cibleloader = document.getElementById('loader');
	cibleimage = document.getElementById('cibleimage');
	ciblecontenu = document.getElementById('ciblecontenu');
	ciblecount = document.getElementById('count');
	cibleclose = document.getElementById('close');
	
	lightbox(0, element);
}

function lightbox(opacite, element){

	if(ciblebox.style.display == 'none'){
		ciblebox.style.display = '';
	}
	//On grise l'écran
	opacite = parseInt(opacite)+15;
	ciblebox.style.opacity = (opacite/100);
	ciblebox.style.filter = 'alpha(opacity='+opacite+')';
	if(opacite != 75){
		setTimeout("lightbox('"+opacite+"', '"+element+"')",10);
	}
	else{
		open = 1;
		if(element == 'image'){
			//Affichage de l'image
			loadImage();
		}
		else if(element == 'contenu'){
			loadContenu();
		}
		else if(element == 'contenuPHP'){
			loadContenuPHP();
		}
	}
}

function closebox(opacite){

	if(openPHP == 2){
		ciblecontenu.style.display = '';
		
		cibleimage.style.display = 'none';
		cibleimage.style.width = '0px';
		cibleimage.style.height = '0px';
		cibleimage.style.marginTop = '0px';
		
		ciblecount.style.display = 'none';
		ciblecount.innerHTML = '';
		ciblecount.style.top = '0px';
		ciblecount.style.left = '0px';
		
		arrowleft.style.display = 'none';
		arrowright.style.display = 'none';
		
		openPHP = 1;
	}else{
		open = 0;
		openPHP = 0;
		if(opacite == '75'){
			
			ciblecontenu.style.display = 'none';
			ciblecontenu.innerHTML = '';
			ciblecontenu.style.opacity = 0;
			ciblecontenu.style.filter = 'alpha(opacity=0)';
				
			cibleimage.style.display = 'none';
			cibleimage.style.width = '0px';
			cibleimage.style.height = '0px';
			cibleimage.style.marginTop = '0px';
			
			ciblecount.style.display = 'none';
			ciblecount.innerHTML = '';
			ciblecount.style.top = '0px';
			ciblecount.style.left = '0px';
			
			cibleclose.style.display = 'none';
			cibleclose.style.height = '0px';
			
			arrowleft.style.display = 'none';
			arrowright.style.display = 'none';
			
			cibleswitch.style.display = 'none';
		}	
		opacite = parseInt(opacite)-15;
		ciblebox.style.opacity = (opacite/100);
		ciblebox.style.filter = 'alpha(opacity='+opacite+')';
		if(opacite != 0){
			setTimeout("closebox('"+opacite+"')",10);
		}
		else{
			cibleloader.style.display = 'none';
			ciblebox.style.display = 'none';
		}
	}
}


	/*Fonctions spécifiques à l'affichage de texte*/
	function loadContenu(){
		ciblecontenu.innerHTML = decodeURIComponent(contenuContent).replace(/\+/g, ' ');
		ciblecontenu.style.width = contenuWidth+"px";
		ciblecontenu.style.display = '';
		afficherContenu(0);
	}
	
	function loadContenuPHP(){
		openPHP = 1;
		var XHR = initXHR();
		
		//On associe un traitement (une fonction anonyme en l'occurrence) à cet indicateur d'évènement.
		XHR.onreadystatechange  = function()
		{
			//L'état 4 signifie que la réponse est envoyée par le serveur et disponible. 
			if(XHR.readyState  == 4)
			{
				//Ce status signifie ok, sinon un code d'erreur quelconque est envoyé, 404 par exemple.
				if(XHR.status  == 200){
					ciblecontenu.innerHTML = XHR.responseText;
				}
				else{
					ciblecontenu.innerHTML="Error code " + XHR.status;
				}
				ciblecontenu.style.width = contenuWidth+"px";
				ciblecontenu.style.display = '';
				afficherContenu(0);
			}else{
				cibleloader.style.display = '';
			}
		}; 

		XHR.open("GET", decodeURIComponent(contenuContent).replace(/\+/g, ' '),  true); 
		XHR.send(null); 
	}
	
	function afficherContenu(opacite){
		if(open == 1){
			opacite = parseInt(opacite)+10;
			ciblecontenu.style.opacity = (opacite/100);
			ciblecontenu.style.filter = 'alpha(opacity='+opacite+')';
			if(opacite != 100){
				setTimeout("afficherContenu('"+opacite+"')",80);
			}
			else{
				cibleloader.style.display = 'none';
				var coordonnees = findPos(ciblecontenu);
				ciblecount.style.width = contenuWidth+"px";
				ciblecount.style.left = coordonnees[0]+3+'px';
				ciblecount.style.top = (-290)+'px'; //ce chiffre découle du margin-top à -270px de ciblecontenu, défini dans la feuille de style
				afficherTitre();
				cibleclose.style.width = contenuWidth+30+"px"; //les 30 correspondent au padding de la divcontenu
				afficherClose(0);
			}
		}
	}

	
/*Fonctions spécifiques à l'affichage d'image*/
	function loadImage(){
		cibleimage.src = lbPath+'white.png';
		//Préchargement de l'image et affichage d'un loader
		var XHR = initXHR()
		// chargement de l'image
		XHR.open("GET", imageSrc, true);
		// Attente de l'état 4 (-> OK)
		XHR.onreadystatechange = function () {
			// l'état est à 4, requête reçue
			if(XHR.readyState != 4){
				cibleloader.style.display = '';
			}
			else{
				cibleimage.style.display = '';
				setTimeout("afficherImage(20, 20)", 10);
			}
		}
		XHR.send(null);
	}
	
	function afficherImage(largeur, hauteur){
		if(open == 1){
			//Calcul de la modification de la hauteur et de la largeur
			var addToWidth = ((imageWidth-largeur)/4);
			addToWidth = (addToWidth < 30 ? 30 : addToWidth);
			var addToHeight = ((imageHeight-hauteur)/4);
			addToHeight = (addToHeight < 30 ? 30 : addToHeight);
		
			if(largeur < imageWidth){
				largeur = parseInt(largeur)+addToWidth;
				if(largeur > imageWidth){
					largeur = imageWidth;
				}
				cibleimage.style.width = largeur+'px';
				//setTimeout("afficherImage('"+largeur+"', 0)",10);
			}
			if(hauteur < imageHeight){
				hauteur = parseInt(hauteur)+addToHeight;
				if(hauteur > imageHeight){
					hauteur = imageHeight;
				}
				cibleimage.style.marginTop = "-"+((hauteur/2)+closeHeight)+"px";
				cibleimage.style.height = hauteur+'px';
				//setTimeout("afficherImage('"+imageWidth+"', "+hauteur+")",10);
			}
			if(largeur < imageWidth || hauteur < imageHeight){
				setTimeout("afficherImage('"+largeur+"', "+hauteur+")",1);
			}
			else{
				cibleloader.style.display = 'none';
				cibleimage.src = imageSrc;
				cibleclose.style.width = imageWidth+"px";
				afficherParcourir();
				afficherClose(0);
			}
		}
	}

	/*Fonctions sevant à parcourir les images d'une array dans la box*/
		function changeImage(sens){
			cibleloader.style.display = '';
			arrayPosition = arrayPosition+parseInt(sens);
			imageSrc = arrayImages[arrayPosition];
			//Affichage ou non des liens pour parcourir l'array
			afficherParcourir();
			
			var XHR = initXHR()
			XHR.open("GET", lbPath+'lightboxClass.php?url='+imageSrc); //timestamp en parametre pour empecher la mise en cache
			// Attente de l'état 4 (-> OK)
			XHR.onreadystatechange = function () {
				// l'état est à 4, requête reçue
				if(XHR.readyState == 4){
					var xml = XHR.responseXML;
					var width = xml.getElementsByTagName('width')[0].firstChild.data;
					var height = xml.getElementsByTagName('height')[0].firstChild.data;
					switchResize(width, height, imageWidth, imageHeight, 0, 0, 1);
				}
			}
			XHR.send(null);
		}
		
		function switchResize(width, height, curwidth, curheight, senswidth, sensheight, preload){
			if(preload == 1){
				//Préchargement de l'image et affichage d'un loader
				var XHR = initXHR();
				// chargement de l'image
				XHR.open("GET", imageSrc, true);
				// Attente de l'état 4 (-> OK)
				XHR.onreadystatechange = function () {
					// l'état est à 4, requête reçue
					if(XHR.readyState != 4){
						cibleloader.style.display = '';
					}
					else{
						//Détermine s'il faut agrandir ou retrécir l'image, dans le sens de la largeur puis de la hauteur
						if(width < imageWidth){
							senswidth = -1;
						}
						else{
							senswidth = 1;
						}
						if(height < imageHeight){
							sensheight = -1;
						}
						else{
							sensheight = 1;
						}
						switchResize(width, height, imageWidth, imageHeight, senswidth, sensheight);
					}
				}
				XHR.send(null);
			}
			//Redimensionnement de l'image
			else{
				if(open == 1){
					var hasWidthDiff = ((senswidth == -1 && curwidth > width) || (senswidth == 1 && curwidth < width) ? 1 : 0);
					var hasHeightDiff = ((sensheight == -1 && curheight > height) || (sensheight == 1 && curheight < height) ? 1 : 0);
					
					if(curwidth != width || curheight != height){
						cibleimage.src = lbPath+'white.png';
					}
					
					//Calcul de la modification de la hauteur et de la largeur
					var addToWidth = Math.abs(((width-curwidth)/4));
					addToWidth = (addToWidth < 30 ? 30 : addToWidth);
					var addToHeight = Math.abs(((height-curheight)/4));
					addToHeight = (addToHeight < 30 ? 30 : addToHeight);
					
					hauteur = parseInt(curheight);
					if(hasHeightDiff){
						hauteur = parseInt(curheight)+(sensheight*addToHeight);
						if((sensheight == -1 && hauteur < height) || (sensheight == 1 && hauteur > height)){
							hauteur == height;
						}
						cibleimage.style.marginTop = "-"+((hauteur/2)+closeHeight)+"px";
						ciblecount.style.top = (parseInt(cibleimage.style.marginTop.replace(/px/, ''))-20)+'px';
						cibleimage.style.height = hauteur+'px';
					}
					
					largeur = parseInt(curwidth);
					if(hasWidthDiff){
						largeur = parseInt(curwidth)+(senswidth*addToWidth);
						if((senswidth == -1 && largeur < width) || (senswidth == 1 && largeur > width)){
							largeur == width;
						}
						cibleclose.style.width = largeur+'px';
						cibleimage.style.width = largeur+'px';
						var coordonnees = findPos(cibleimage);
						ciblecount.style.width = largeur+"px";
						ciblecount.style.left = coordonnees[0]+6+'px';
					}
					
					if(hasWidthDiff || hasHeightDiff){
						setTimeout("switchResize('"+width+"', '"+height+"', '"+largeur+"', '"+hauteur+"', '"+senswidth+"', '"+sensheight+"')",10);
					}
					else{
						imageWidth = curwidth;
						imageHeight = curheight;
						//Préparation de l'image temporaire pour le changement
						var coordonnees = findPos(cibleimage);
						cibleswitch.style.left = coordonnees[0]+'px';
						cibleswitch.style.top = coordonnees[1]+document.documentElement.scrollTop+'px';
						cibleswitch.style.width = cibleimage.style.width;
						cibleswitch.style.height = cibleimage.style.height;
						cibleswitch.src = cibleimage.src;
						cibleswitch.style.display = '';
						setTimeout("cibleimage.src = imageSrc", 20);
						setTimeout("switchImage(100)", 20);
					}
				}
			}
		}
		
		function switchImage(opacite){
			//Disparition progressive de l'ancienne image
			cibleloader.style.display = 'none';
			opacite = parseInt(opacite)-25;
			cibleswitch.style.opacity = (opacite/100);
			cibleswitch.style.filter = 'alpha(opacity='+opacite+')';
			if(opacite != 0){
				setTimeout("switchImage('"+opacite+"')",30);
			}
			else{
				//On fait disparaitre l'image temporaire
				cibleswitch.style.display = 'none';
				cibleswitch.style.opacity = '1';
				cibleswitch.style.filter = 'alpha(opacity=100)';
			}
		}
	
	
	
/*Fonction affichant le lien pour fermer la box*/
	function afficherClose(hauteur){
		if(open == 1){
			if(hauteur == 0){
				cibleclose.style.display = '';
			}
			if(hauteur != closeHeight){
				hauteur = parseInt(hauteur)+5;
				cibleclose.style.height = hauteur+'px';
				setTimeout("afficherClose("+hauteur+")",10);
			}
		}
	}

/*Fonction affichant les liens pour parcourir les images si nécessaire ainsi que la position de l'image dans la série*/	
	function afficherParcourir(){
		var coordonnees = findPos(cibleimage);
		ciblecount.style.width = imageWidth+"px";
		ciblecount.style.left = coordonnees[0]+3+'px';
		ciblecount.style.top = (parseInt(cibleimage.style.marginTop.replace(/px/, ''))-20)+'px';
		if(arrayImages.length != 0){
			//Affichage de la position de l'image dans l'array
			ciblecount.innerHTML = (arrayPosition+1)+'/'+arrayImages.length;
			ciblecount.style.display = '';
			afficherTitre();
			
			if(arrayPosition == 0){
				arrowleft.style.display = 'none';
				arrowright.style.display = '';
			}
			else if(arrayPosition == (arrayImages.length-1)){
				arrowleft.style.display = '';
				arrowright.style.display = 'none';
			}
			else{
				arrowleft.style.display = '';
				arrowright.style.display = '';
			}
		}
		else{
			afficherTitre();			
			arrowleft.style.display = 'none';
			arrowright.style.display = 'none';
		}
	}
	
/*Fonction affichant le titre de l'image s'il existe*/
	function afficherTitre(){
		if(arrayTitres[arrayPosition]){
			ciblecount.style.display = '';
			ciblecount.innerHTML = '<div style="float: left;">'+decodeURIComponent(arrayTitres[arrayPosition]).replace(/\+/g, ' ')+'</div>'+ciblecount.innerHTML;
		}
	}
	
/*Fonction initialisant un objet XHR*/
	function initXHR(){
		var XHR = false; 
		try {
		   XHR = new ActiveXObject("Microsoft.XMLHTTP"); // essayer Internet Explorer 
		}
		catch(e){
			  XHR = new XMLHttpRequest()
		}
		return XHR;
	}
	
/*Fonction remplaçant getElementsByName, qui est mal supporté sous IE*/
	function byName(tag, name){
		var elements = new Array();
		var taglist = document.getElementsByTagName(tag);
		//On parcourt la liste pour voir lesquels ont le nom souhaité
		var id = 0;
		for(i=0; i<taglist.length; i++){
			if(taglist[i].getAttribute("name") == name){
				elements[id] = taglist[i];
				id++;
			}
		}
		return elements;
	}
	
//Retourne la position absolue d'un objet
function findPos(obj){
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		curleft = obj.offsetLeft
		curtop = obj.offsetTop
		while (obj = obj.offsetParent) {
			curleft += obj.offsetLeft
			curtop += obj.offsetTop
		}
	}
	return [curleft,curtop];
}

function isIE(){
	return ((navigator.userAgent.toLowerCase().indexOf("msie") != -1) && (navigator.userAgent.toLowerCase().indexOf("opera") == -1));
}
