// utils pour navigation
var page = 0;
var idGalerie = -1;
var idPhoto = -1;
var arrTextes = [];
var arrGaleries = [];
var arrRubriques = [];
var arrSelection = [];
var arrContenus = [];
var arrPages = new Array("Contact", "Biography", "Clients", "Books", "Videos", "Exhibitions", "Credits");
var longeurArr;
var pathPhotos = "photos/";
// mur de liens
var fontsize;
//
// INITIALISATION
//
$(document).ready( chargeXml );

function chargeXml() {
	
	resizeWindow( false );
	
	$.ajax({type: "GET", url: "data.php", dataType: "xml",
			success: function(xml) {
				// pages
				$(xml).find('contenu').each( function() {
					var arrPage = [];
					arrPage.push( $(this).find('colonne1').text() );
					arrPage.push( $(this).find('colonne2').text() );
					arrPage.push( $(this).find('colonne3').text() );	
					arrContenus.push( arrPage );
				});
				// categories
				$(xml).find('cat').each( function() {
					arrRubriques.push( $(this).text() );
				});
				// selection
				$(xml).find('home').each( function() {
					// textes home
					arrTextes.push( $(this).find('chapeau').text());
					arrTextes.push( $(this).find('corps').text());
					 // titre # dossier # [fichiers] < > [legendes] # [tailles]
					var arrPho = [];
					var arrLeg = [];
					var arrSiz = [];
					// titre
					arrSelection.push( $(this).find('titre').text() );
					arrSelection.push( $(this).find('dossier').text() +"/" );
					// images
					$(this).find('img').each( function() {
						arrPho.push( $(this).attr('file') );
						arrLeg.push( $(this).text() );
						arrSiz.push( $(this).attr('width') +"|"+ $(this).attr('height') );
					});
					arrSelection.push( arrPho );
					arrSelection.push( arrLeg );
					arrSelection.push( arrSiz );
				});
				// liens vers séries
				$(xml).find('serie').each( function() {
					// creation des tableaux
					var arrGal = []; // titre # client # dossier # [rubriques] # [fichiers] < > [legendes] # [tailles]
					var arrRub = []; // rubriques
					var arrPho = []; // fichiers
					var arrLeg = []; // legendes
					var arrSiz = []; // tailles
					var arrLin = []; // liens
					// ajouts
					arrGal.push( $(this).find('titre').text() ); // titre
					arrGal.push( $(this).find('client').text() ); // client
					arrGal.push( $(this).find('dossier').text() +"/" ); // dossier
					// rubriques
					//
					$(this).find('rub').each( function() {
						arrRub.push( $(this).text() ); // rubrique
					});
					arrGal.push( arrRub ); // array rubriques
					// fichiers
					$(this).find('img').each( function() {
						arrPho.push( $(this).attr('file') ); // image
						arrLeg.push( $(this).text() ); // legende
						arrSiz.push( $(this).attr('width') +"|"+ $(this).attr('height') ); // size
						arrLin.push( $(this).attr('lien') ); // lien
					});
					arrGal.push( arrPho ); // array fichiers
					arrGal.push( arrLeg ); // array legendes
					arrGal.push( arrSiz ); // array legendes
					arrGal.push( arrLin ); // array legendes
					// push final
					arrGaleries.push( arrGal );
				});
				// galeries
				// creation
				init();
            }
	});
}

function init() {
	
	// page
	//
	$("#page").append( $(document.createElement("div")).attr("id", "bottom") );
	$("#bottom").append( $(document.createElement("div")).attr("id", "menu") );
	$("#bottom").append( $(document.createElement("div")).attr("id", "colonne1") );
	$("#bottom").append( $(document.createElement("div")).attr("id", "colonne2") );
	$("#bottom").append( $(document.createElement("div")).attr("id", "colonne3") );
	$("#menu").append( "<ul>" );
	for (var i = 0; i < arrPages.length; i++) {
		$("#menu").append( "<li><a id=\"btpage"+ i +"\" href=\"javascript:void()\" onClick=\"creePage('"+ i +"')\">"+ arrPages[ i ] +"</a></li>" );
	}
	$("#menu").append( "</ul>" );
	//
	creeMurLiens();
	//
	creePage( 0 );
	//
	// clic galerie
	$("#bouton").click( nextImage );
	//
	// clavier
	$(window).keydown(function(e){ 
		switch (e.keyCode) { 
			case 37: // flèche gauche
				e.preventDefault();
				prevImage();
				break;
			case 38: // flèche haut
				e.preventDefault();
				gotoTop();
				break;
			case 39: // flèche droite 
				e.preventDefault();
				nextImage();
				break; 
			case 40: // flèche bas 
				e.preventDefault();
				gotoBottom();
				break;
		}
	});
	//
	// listener resize
	jQuery(window).bind('resize', function(){ resizeWindow(true); } );
	jQuery(window).bind('scroll', scrollPage );
}

function prevImage() {
	targetPhoto = Number(idPhoto)-1;
	if ((targetPhoto >= longeurArr) || (targetPhoto < 0)) {
		gotoBottom();
	} else {
		gotoTop();
		idPhoto = targetPhoto;
		afficheGalerieImage();
	}
}
function nextImage() {
	targetPhoto = Number(idPhoto)+1;
	if ((targetPhoto >= longeurArr) || (targetPhoto < 0)) {
		gotoBottom();
	} else {
		gotoTop();
		idPhoto = targetPhoto;
		afficheGalerieImage();
	}
}
function gotoBottom() {
	// on descend
	$("html, body").animate({scrollTop: $(window).height()}, 700);
}
function gotoTop() {
	// on descend monte
	$("html, body").animate({scrollTop: 0}, 700);
}

function creeMurLiens() {
	// ajout des liens dans le div correspondant
	for (var i = 0; i < arrGaleries.length; i++) {
		$("#links").append( "<a id=\"serie"+ i +"\" name=\""+ i +"\" href=\"#"+ convertionTexte( arrGaleries[ i ][ 0 ] ) +"\">"+ arrGaleries[ i ][ 0 ] +"</a>" );
		//
		$("#serie"+ i).mouseover( function() {
			for (var j = 0; j < arrRubriques.length; j++) {
				if (arrGaleries[ $(this).attr('name') ][ 3 ][ j ] == "1") {
					$("#rub"+ j).addClass("rubriqueRollY");
				} else {
					$("#rub"+ j).addClass("rubriqueRollN");
				}
			}
		});
		$("#serie"+ i).mouseout( function() {
			for (var j = 0; j < arrRubriques.length; j++) {
				$("#rub"+ j).removeClass("rubriqueRollY");
				$("#rub"+ j).removeClass("rubriqueRollN");
			}
		});
		$("#serie"+ i).click( gotoTop );
		//
		if ((i+1) < arrGaleries.length) $("#links").append(" ");
		else $("#links").append(". ");
	}
	for (var i = 0; i < arrRubriques.length; i++) {
		$("#links").append( "<a id=\"rub"+ i +"\" name=\""+ i +"\" href=\"javascript:void()\">"+ arrRubriques[ i ] +"</a>" );
		//
		$("#rub"+ i).mouseover( function() {
			for (var j = 0; j < arrGaleries.length; j++) {
				if (arrGaleries[ j ][ 3 ][ $(this).attr('name') ] == "1") {
					$("#serie"+ j).addClass("serieRollY");
				} else {
					$("#serie"+ j).addClass("serieRollN");
				}
			}
		});
		$("#rub"+ i).mouseout( function() {
			for (var j = 0; j < arrGaleries.length; j++) {
				$("#serie"+ j).removeClass("serieRollY");
				$("#serie"+ j).removeClass("serieRollN");
			}
		});
		//
		if ((i+1) < arrRubriques.length) $("#links").append(" ");
		else $("#links").append(". ");
	}
	//
	resizeWindow( false );
	// on affiche le mur de liens
	$("#links").fadeTo("1000", 1);
	// bottom
	$("#bottom").fadeTo("200", 1);
	// chargeGalerie
	
	jQuery(window).bind('hashchange', changeHash);
	
	var myFile = document.location.toString();
	if (!myFile.match('#')) chargeGalerie();
	else changeHash();
}

function changeHash() {
	var myFile = document.location.toString();
	var checkpage = myFile.split('#')[1];
	for (var k = 0; k < arrGaleries.length; k++) {
		if (convertionTexte(arrGaleries[ k ][ 0 ]) == checkpage) afficheSerie( k );
	}
}


function afficheSerie( id ) {
	idGalerie = id;
	chargeGalerie();
	gotoTop();
}

function chargeGalerie() {
	//
	document.title = ( ((idGalerie == -1) ? "Geoffroy de Boismenu" : "Geoffroy de Boismenu - "+ arrGaleries[ idGalerie ][ 0 ]) );
	//
	$("#loader").fadeTo("fast", 1);
	$("#infos").empty();
	//
	$("#serie"+ idGalerie).addClass("alreadySeen");
	idPhoto = 0;
	$("#galerie").empty();
	//
	$("#intro").empty();
	var texteIntro = arrTextes[ 1 ];
		var arrayIntro = texteIntro.split("<br />");
	texteIntro = "";
	for (var i = 0; i<arrayIntro.length; i++)
		texteIntro += "<br /><span class=\"legende-texte\">"+ arrayIntro[ i ] +"</span>";
	
	$("#intro").append( "<img src=\"img/Logo.png\" width=\"72\" height=\"82\" /><br /><br /><br /><span class=\"legende-titre\">"+ arrTextes[ 0 ] +"</span>"+ texteIntro);
	
	$("#intro").fadeTo( .5, ((idGalerie == -1) ? 1 : 0) );

	longeurArr = ((idGalerie == -1) ? arrSelection[ 2 ].length : arrGaleries[ idGalerie ][ 4 ].length );
	
	// chargement des images
	for (var i = 0; i < longeurArr; i++) {
		var pathImage = ((idGalerie == -1) ? (arrSelection[ 1 ] + arrSelection[ 2 ][ i ]) : (arrGaleries[ idGalerie ][ 2 ] + arrGaleries[ idGalerie ][ 4 ][ i ]) );
		//
		$("#galerie").append( $(document.createElement("div")).attr("id", "img"+ i ).hide() );
		$("#img"+ i).css({position: "absolute", top: "0px", right: "0px"});
		pathPhotos2 = ((idGalerie == -1) ? "" : pathPhotos);
		$("#img"+ i).append( $(document.createElement("img")).attr("src", pathPhotos2 + pathImage ) );
	}
	
	// lance affichage
	afficheGalerieImage();
}

function afficheGalerieImage() {
	
	// test
	$("#loader").fadeTo("fast", 1);
	
	if ( $("#img"+ idPhoto).children("img").width() > 0 ) {
		$("#loader").hide();
		for (var i = 0; i < longeurArr; i++) $("#img"+ i).fadeTo( "slow", ((idPhoto == i) ? 1 : 0));
		afficheGalerieImageLoaded();
	} else {
		for (var i = 0; i < longeurArr; i++) $("#img"+ i).fadeTo( "slow", 0 );
		$("#img"+ idPhoto).children("img").load( function() {
			$("#img"+ idPhoto).stop();
			$("#img"+ idPhoto).fadeTo( "slow", 1 );
			$("#loader").hide();
			afficheGalerieImageLoaded();
		} );
	}
	
}
function afficheGalerieImageLoaded() {
	//
	resizeWindow( false );
	// infos
	$("#infos").empty();
	$("#infos").append( "<a href=\""+ (Number(idPhoto)-1) +"\"><</a>" );
	$("#infos").append( "<a href=\""+ (Number(idPhoto)+1) +"\">&nbsp;></a>&nbsp;" );
	$("#infos").append( "<span class=\"numeroPhoto\">"+ (Number(idPhoto)+1) +"/"+ longeurArr +" </span>" );
	$("#infos").append( "<br /><br />" );
	
	$("#boutonimg").width( $("#img"+ idPhoto).width() );
	$("#boutonimg").height( $("#img"+ idPhoto).height() );
	//
	if (idGalerie == -1) {
		var arr = arrSelection[ 3 ][ idPhoto ].split("|");
		titreLegende = arr[ 0 ];
		if (arr[ 2 ] != "") {
			texteLegende = "<a class=\"lienLegende\" href=\"http://"+ arr[ 2 ] +"\">"+ arr[ 1 ] +"</a>";
		} else {
			texteLegende = arr[ 1 ];
		}
	} else {
		titreLegende = arrGaleries[ idGalerie ][ 0 ];
		if (arrGaleries[ idGalerie ][ 7 ][ idPhoto ] != "") {
			texteLegende = "<a class=\"lienLegende\" href=\"http://"+ arrGaleries[ idGalerie ][ 7 ][ idPhoto ] +"\" target=\"_blank\">"+ arrGaleries[ idGalerie ][ 5 ][ idPhoto ] +"</a>";
		} else {
			texteLegende = arrGaleries[ idGalerie ][ 5 ][ idPhoto ];
		}
	}
	//
	$("#infos").append( "<b>"+ titreLegende +"</b><br />"+ texteLegende );
	//
	scrollPage();
	// clicks
	$("#infos").find("a").click( function(e) {
		if ($(this).attr("class") != "lienLegende") {
			var targetPhoto = $(this).attr("href");
			e.preventDefault();
			if ((targetPhoto >= longeurArr) || (targetPhoto < 0)) {
				$('html, body').animate({scrollTop: $(window).height()}, 500);
			} else {
				idPhoto = targetPhoto;
				afficheGalerieImage();
			}
		}
	});
}

function creePage( id ) {
	// boutons
	$("#btpage"+ page).removeClass("actif");
	page = id;
	$("#btpage"+ page).addClass("actif");
	// contenus
	$("#colonne1").stop().hide().empty();
	$("#colonne2").stop().hide().empty();
	$("#colonne3").stop().hide().empty();
	//
	if (page == 1) $("#colonne1").addClass("big");
	else $("#colonne1").removeClass("big");
	if (page == 1) $("#colonne2").addClass("small");
	else $("#colonne2").removeClass("small");
	
	if ((page == 3) || (page == 4) || (page == 5)) $("#colonne1").addClass("double");
	else $("#colonne1").removeClass("double");
	if ((page == 3) || (page == 4) || (page == 5)) $("#colonne2").addClass("double");
	else $("#colonne2").removeClass("double");
	
	$("#colonne1").append( arrContenus[ page ][ 0 ] );
	$("#colonne1").delay( 0 ).fadeTo( 500, 1 );
	//
	$("#colonne2").append( arrContenus[ page ][ 1 ] );
	$("#colonne2").delay( 200 ).fadeTo( 500, 1 );
	//
	$("#colonne3").append( arrContenus[ page ][ 2 ] );
	$("#colonne3").delay( 400 ).fadeTo( 500, 1 );
}


/*********************************************************************************
* RESIZE DE LA FENETRE ***********************************************************
*********************************************************************************/
function resizeWindow( isResized ) {
	
	var sizeImage = false;
	if (idPhoto != -1) sizeImage = ((idGalerie == -1) ? arrSelection[ 4 ][ idPhoto ] : arrGaleries[ idGalerie ][ 6 ][ idPhoto ]);
	//
	var ww = $(window).width();
	var hh = $(window).height();
	
	if (sizeImage) {
		var ai = sizeImage.split("|");
		var wI = ai[ 0 ];
		var hI = ai[ 1 ];
	}
	
	$("#page").height( (hh*2) );
	$("#galerie").width( ww-85 );
	$("#links").css({top: hh});
	$("#loader").css({top: (hh/2) - 13, left: (ww/2) - 13 });
	
	if (sizeImage) {
		var img = $("#img"+ idPhoto).children("img");
		var winw = ww - 170;
		var winh = hh - 125;
		var ratioImg = (Math.ceil((wI / hI)*100))/100;
		var ratioWin = (Math.ceil((winw / winh)*100))/100;
		// hauteur max de la fenetre
		var maxHeight = hh - 125;
		var maxWidth  = ww - 170;
		// test si hauteurMax > hauteur normale de l'image
		maxHeight = ((maxHeight > hI) ? hI : maxHeight);
		maxWidth = ((maxWidth > wI) ? wI : maxWidth);
		
		if (ratioImg < ratioWin) {
			img.css({height: maxHeight, width: (maxHeight * ratioImg)});
		} else {
			img.css({width: maxWidth, height: (maxWidth / ratioImg)});
		}
		
		if (isResized) {
			$("#infos").css({top: 45 + img.height() });
			$("#intro").css({top: 20 + img.height() - $("#intro").height() });
		} else {
			$("#infos").animate({top: 45 + img.height() }, 300);
			$("#intro").animate({top: 20 + img.height() - $("#intro").height() }, 300);
		}
		
		$("#bottom").css({top: ($(window).height() + 127 + img.height() - $("#intro").height()) });
		$("#bottom").css({width: $(window).width() });
	} else {
		
		$("#bottom").css({top: $(window).height()*2 });
		
	}
	
	fontsize = 5;
	$("#links").css("font-size", fontsize +"px");
	$("#links").css("line-height", (fontsize/1.3) +"px");
	resizeMurLiens();
	
	// scroll auto
	if (isResized) {
		if ( $(window).scrollTop() > (hh/5)*4 ) {
			$('html, body').animate({scrollTop: hh}, 0);
		}
	}
}

function resizeMurLiens() {
	var img = $("#img"+ idPhoto).children("img");
	// croissance
	fontsize += 1;
	// mise en place
	$("#links").css("font-size", fontsize +"px");
	$("#links").css("line-height", (fontsize/1.25) +"px");
	// test
	var margeFenetre = 260;
	if ( $("#links").height() < (img.height()-140)) resizeMurLiens();
}

function convertionTexte( txt ) {
	txt = txt.toLowerCase();
	temp = txt.replace(/[àâä]/gi,"a");
	temp = temp.replace(/[éèêë]/gi,"e");
	temp = temp.replace(/[îï]/gi,"i");
	temp = temp.replace(/[ôö]/gi,"o");
	temp = temp.replace(/[ùûü]/gi,"u");
	temp = temp.replace(" & ","-");
	temp = temp.replace(/[&]/gi,"-");
	temp = temp.replace(/[ ]/gi,"-");
	temp = temp.replace(/[']/gi,"-");
	return temp;
}

function scrollPage() {
	var facteurOp = 1 - ($(window).scrollTop() / ($(window).height()-30));
	$(window).scrollLeft( 0 );
	if (idGalerie == -1) $("#intro").fadeTo(0, facteurOp);
	$("#galerie").fadeTo(0, facteurOp);
	$("#infos").fadeTo(0, facteurOp);	
}
