/* ------------------------ VARIABLES GLOBALES ------------------------ */

var speedShowBoxAlbum = 1500;
var effectShowBoxAlbum = "easeOutExpo";

var speedHideBoxAlbum = 800;
var effectHideBoxAlbum = "easeInExpo";

var speedShowListAlbums = 500;
var effectShowListAlbums = "easeOutExpo";

var speedHideListAlbums = 500;
var effectHideListAlbums = "easeInExpo";

var timeToHideBigPhoto = 250;
var timeToShowBigPhoto = 250;

var speedChangePage = 1000;

var currentPage = 1;
var numPagesTotales = 0;

/* ------------------------ INIT ------------------------ */
$(document).ready(function(){
	// On récupère les albums photos
	getAlbumsPhotos('');
	
	// on initialise la liste déroulante des années
	initListesDeroulantes();
	
	// on initialise le form 
	iniFormSelectAlbum();
});

/* ------------------------ EVENEMENTS ------------------------ */
/* initOverlayLogin
 * 
 * Initialisation des evenements lies a l'overlay d'authentification
 * 
 */
function initOverlayAlbum(){
	// On adapte la hauteur des overlay à la fenêtre courante
	$("#overlayAlbum").css({
		"height": viewportHeight+"px"
	});
	$("#trueOverlayAlbum").css({
		"height": viewportHeight+"px"
	});
	
	// Lorsque'on clique sur un album, on récupère les photos
	$(".boxAlbum").click(getPhotos);
	
	// Lorsque'on clique sur en dehors du bloc de formulaire d'authentification, on masque l'overlay de login
	$("#overlayAlbum").click(handleClickOnOverlayAlbum);

}

function initAlbum(){
	
	// OVER/OUT sur l'image de l'album
	$(".imgAlbum").hover(
    	function () {	
			overImgAlbum(this);
      	}, 
      	function () {
	  		outImgAlbum(this);
      	}
    );
	
	// OVER/OUT sur le titre de l'album
	$(".titleAlbum").hover(
    	function () {	
			overDescAlbum(this);
      	}, 
      	function () {
	  		outDescAlbum(this);
      	}
    );
	
	// OVER/OUT sur la date de l'album
	$(".dateAlbum").hover(
    	function () {	
			overDescAlbum(this);
      	}, 
      	function () {
	  		outDescAlbum(this);
      	}
    );
	
	// OVER/OUT sur le texte de l'album
	$(".textAlbum").hover(
    	function () {	
			overDescAlbum(this);
      	}, 
      	function () {
	  		outDescAlbum(this);
      	}
    );
}

function iniFormSelectAlbum(){
	// on écoute le changement de la liste déroulante des années
	$('.boxOptionYear .lineOption').click(function(){
		// on remet la page 1
		currentPage = 1;
		// on relance la récupération
		getAlbumsPhotos('');
	});
}

/* ------------------------ FONCTIONS ------------------------ */

function getPhotos(e){
	var $this = $(this);
	// on récupère l'identifiant de l'album
	curBoxAlbum = $(e.target).parents('.boxAlbum').length > 0 ? $(e.target).parents('.boxAlbum') : $(e.target);
	curIdAlbum = curBoxAlbum.attr('id');
	curIdAlbum = curIdAlbum.replace('album_', '');
	
	// si on a récupéré un identifiant d'album
	if(curIdAlbum != '')
	{
		aPost = {
			get_photos: true,
			id_album: curIdAlbum
		};	
	
		// on soumet le form en ajax
		$.ajax({
			type: "POST",
			url: "ws/medias/get_photos.php",
			data: aPost,
			dataType:"json",
			success:function(returnedJson){			
				if (!returnedJson["b_error"]) {
					// mise à jour du contenu de l'album
					$('.lineBoxPhotos').html(returnedJson['html_album_content']);
					// on montre l'overalay de l'album
					showOverlayAlbum($this);
					$('body').animate({scrollTop : 0},1000);
					if (navigator.userAgent.match('MSIE') || navigator.userAgent.match('Firefox')){
						document.documentElement.scrollTop = 0;
					}

					initEventPhoto();
				}
			}
		});
	}
}

function initEventPhoto(){
	// OVER/OUT sur l'image de l'album
	$(".imgPhoto").hover(
    	function () {	
			overImgAlbum(this);
      	}, 
      	function () {
	  		outImgAlbum(this);
      	}
    );
	
	// on initialise le click sur une photo
	$('.imgPhoto').live('click', handleClickOnPhoto);
	$('.imgPhoto a').live('click', function(){return false;});
	
	// on initialise le click sur une grande photo
	$('.imgBigPhoto').live('click', handleClickOnBigPhoto);
}

function handleClickOnPhoto(e){
	// on récupère l'url de l'image à afficher
	curUrlImage = $(e.target).parents('a').attr('href');
	curId = $(e.target).parents('.imgPhoto').attr('id');
		
	switchImage(curUrlImage,curId);
	
	return false;
}

function handleClickOnBigPhoto(e){
	// on récupère l'id de relation
	curId = $(e.target).parents('.imgBigPhoto').attr('rel');
	curImageRelated = $('.imgPhoto[id='+curId+']');

	// on récupère la photo suivante
	curNextImage = curImageRelated.next();

	// si on a rien trouvé, on récupère la première
	if(curNextImage.length == 0) curNextImage = $('.lineBoxPhotos').find('.imgPhoto:first');
	curUrlImage = $(curNextImage).find('a').attr('href');
	curId = $(curNextImage).attr('id');
	
	switchImage(curUrlImage,curId);
	
	return false;
}

function switchImage(urlImage,id){
	// on cache la grande image
	$('.imgBigPhoto').fadeTo(timeToHideBigPhoto, 0, function(){
		// on modifie l'attribut de relation
		$(this).attr('rel', id);
		
		// Image
		curImage = $('<img src="'+urlImage+'" border="0" alt="" />');
		
		$(this).html(curImage);
		
		// On image load
		$(curImage).one("load",function(){
			// on met à jour la taille du bloc de la big image
			var newHeight = $(curImage).outerHeight();
			$('.imgBigPhoto').animate({
				height: newHeight
			}, '500', 'easeInOutExpo', function(){$('.imgBigPhoto').fadeTo(timeToShowBigPhoto, 1);});
			
		}).each(function(){
			if(this.complete || (jQuery.browser.msie && parseInt(jQuery.browser.version,10) == 6))
				$(this).trigger("load");
		});
	});
}

function showOverlayAlbum($boxClicked){
	$("#overlayAlbum").show();
	var flickr_id = $('#overlayAlbum').find('.textAlbum').text();
	$('#overlayAlbum').find('.textAlbum').text($boxClicked.find('.textAlbum').text());
	
	$('.lineBoxPhotos a').lightBox();
	
	if(jQuery.browser['msie'] && parseInt(jQuery.browser['version'],10) < 8)
	{
		$("#trueOverlayAlbum").css('opacity',0);
	}
	$("#trueOverlayAlbum").show();
	if(jQuery.browser['msie'] && parseInt(jQuery.browser['version'],10) < 8)
	{
		$("#trueOverlayAlbum").animate({
			"opacity":0.5
		});
	}
	$("#boxOverlayAlbum").show();
	$("#boxOverlayAlbum").animate({
		"top":100
	}, speedShowBoxAlbum, effectShowBoxAlbum);
	
	if (!isNaN(parseInt(flickr_id))){
		getFlickrAlbum(flickr_id);
	}
	else {
		$('.imgBigPhoto').remove();
	}
}

function getFlickrAlbum(flickr_id){
	var apiKey = 'fffb59845af47263f643bf024f40de21';
	$.getJSON('http://api.flickr.com/services/rest/?method=flickr.photosets.getPhotos&photoset_id='+flickr_id+'&format=json&api_key='+apiKey+'&jsoncallback=?',
		{format: "json"},
		function(datasPhotos) {
			addFlickrAlbum(datasPhotos);
	});
}

function addFlickrAlbum(datasPhotos){
	var i = 0;
	var imageArray = new Array();
	$.each(datasPhotos.photoset.photo, function(i,photo){
		var farm = 		photo.farm;
		var server = 	photo.server;
		var secret = 	photo.secret;
		var id = 		photo.id;
		var url = 'http://farm'+photo.farm+'.static.flickr.com/'+photo.server+'/'+photo.id+'_'+photo.secret+'_s.jpg';
		if (i==0){
			$('.imgBigPhoto').html('<img src="'+url.replace('_s.jpg','_z.jpg')+'" border="0" />');
			$('.imgBigPhoto').attr('rel', 'photo_'+id);
		}
		$('.imgBigPhoto').after('<div class="imgPhoto" id="photo_'+id+'"><a href="'+url.replace('_s.jpg','_z.jpg')+'"><img src='+url+' width="106" height="82"/></a></div>');
		
		imageArray[i] = url;
		i++;
		
	});
	$('.imgBigPhoto').remove();
	$('.lineBoxPhotos a').lightBox();
}

function handleClickOnOverlayAlbum(e){
	if (e.target.id == "overlayAlbum") {
		hideOverlayAlbum();
	}
}

function hideOverlayAlbum(){
	$("#boxOverlayAlbum").animate({
		"top":"-150px"
	}, speedHideBoxAlbum, effectHideBoxAlbum, function(){
		$("#overlayAlbum").hide();
		$("#trueOverlayAlbum").hide();
	});
}

function overImgAlbum(curDiv){
	$(curDiv).css({"border":"1px solid #0068AB"});
}

function outImgAlbum(curDiv){
	$(curDiv).css({"border":"1px solid #787878"});
}

function overDescAlbum(curDiv){
	$(curDiv).css({"text-decoration":"underline"});
}

function outDescAlbum(curDiv){
	$(curDiv).css({"text-decoration":"none"});
}

function getAlbumsPhotos(sens){
	aPost = {
		get_albums_photos: true,
		page_to_display: currentPage,
		page: page,
		annee: $('#formSelectAlbum [name=annee]').val()
	};	

	// on soumet le form en ajax
	$.ajax({
		type: "POST",
		url: "ws/medias/get_albums_photos.php",
		data: aPost,
		dataType:"json",
		success:function(returnedJson){			
			if (!returnedJson["b_error"]) {
				// mise à jour de la liste des albums photos
				updateContentAlbumsPhotos(sens, returnedJson);
			}
		}
	});
}

function updateContentAlbumsPhotos(sens, returnedJson){
	// on récupère le html des résultats
	htmlContentAlbumsPhotos = returnedJson["html_list_albums"];
	// mise à jour de la pagination
	$('#contentAlbumsPhotos .contentPaginationContentAlbumsPhotos').html(returnedJson["html_pagination"]);
	// mise à jour du nombre de page
	numPagesTotales = returnedJson["num_pages_totales"];	
	
	// selon le sens de la pagination
	switch(sens)
	{
		case 'next':
			// on ajoute les résultats après ceux affichés
			$('#contentAlbumsPhotos .contentDynamic').after(htmlContentAlbumsPhotos);
			
			// On cache les résultats affichés (le premier bloc)
			$('#contentAlbumsPhotos .contentDynamic:first').slideUp({
				duration:speedChangePage,
				easing:"easeInOutExpo",
				complete:function(){
					// si plus d'un bloc, on supprime le bloc caché
					if($('#contentAlbumsPhotos .contentDynamic').length > 1)
					{
						$(this).remove();
					}
				}
			});

			// on affiche les nouveaux résultats (le dernier bloc)
			$('#contentAlbumsPhotos .contentDynamic:last').slideDown({
				duration:speedChangePage,
				easing:"easeInOutExpo",
				complete:function(){
					// si plus d'un bloc
					if($('#contentAlbumsPhotos .contentDynamic').length > 1)
					{
						// on supprime tous les autres blocs
						$('#contentAlbumsPhotos .contentDynamic:not(:last)').remove();
					}
					initContentAlbumsPhotosDisplayed();
				}
			});
			break;
		case 'last':
			// on ajoute les résultats avant ceux affichés
			$('#contentAlbumsPhotos .contentDynamic').before(htmlContentAlbumsPhotos);

			// On cache les résultats affichés (le dernier bloc)
			$('#contentAlbumsPhotos .contentDynamic:last').slideUp({
				duration:speedChangePage,
				easing:"easeInOutExpo",
				complete:function(){
					// si plus d'un bloc	
					if($('#contentAlbumsPhotos .contentDynamic').length > 1)
					{
						// on supprime le bloc que l'on vient de caché
						$(this).remove();
					}
				}
			});
			
			// on affiche le nouveau contenu (le premier bloc)
			$('#contentAlbumsPhotos .contentDynamic:first').slideDown({
				duration:speedChangePage,
				easing:"easeInOutExpo",
				complete:function(){
					// si plus d'un bloc		
					if($('#contentAlbumsPhotos .contentDynamic').length > 1)
					{
						// on supprime tous les autres blocs (ceux qui ne sont pas premiers)
						$('#contentAlbumsPhotos .contentDynamic:not(:first)').remove();
					}
					initContentAlbumsPhotosDisplayed();
				}
			});
			break;
		default:
			// par défaut on affiche directement les résultats
			$('#contentAlbumsPhotos #listAlbums').html(htmlContentAlbumsPhotos);
			// on montre sans effet le contenu
			$('#contentAlbumsPhotos .contentDynamic').show();
			initContentAlbumsPhotosDisplayed();
			updateMetaFacebook();
			break;
	}
}

function updateMetaFacebook() {
	urlImg = $('.contentDynamic .boxAlbum:first .imgAlbum img').attr('src');
	title = $('title').text();
	$('head').append('<meta property="og:image" content="'+urlImg+'" />');
	$('head').append('<meta property="og:url" content="'+urlImg+'" />');
	$('head').append('<meta property="og:site_name" content="'+title+'" />');

}

function initContentAlbumsPhotosDisplayed(){
	// pngFix
	$('#contentAlbumsPhotos #listAlbums').pngFix();
	// On initialise les evenements sur les albums
	initAlbum();
	// On init les evenements de l'overlay album photo
	initOverlayAlbum();
	// initialisation de la pagination
	initPaginationContentAlbumsPhotos();
	// mise à jour de la taille du conteneur
	resetHeightSliderContentAlbumsPhotos();
}

function resetHeightSliderContentAlbumsPhotos()
{
	// initialisation de la hauteur
	var height = 0;
	// pour chaque ligne de résultats
	$('#contentAlbumsPhotos .boxAlbum').each(function(){
		// On incrémente la hauteur générale de la hauteur de la ligne
		height += $(this).outerHeight();
	});
	
	// on réinitialise à la fin de l'animation les listes déroulantes pour prendre en compte des changements de position possible
	$('#contentAlbumsPhotos #listAlbums').animate({height: height}, 100, initListesDeroulantes);
	$('#contentAlbumsPhotos .contentDynamic').animate({height: height}, 100, initListesDeroulantes);
}

function initPaginationContentAlbumsPhotos(){
	// click sur le bouton précédent
	$('#contentAlbumsPhotos .btnLast').bind('click',handleClickLastPaginationContentAlbumsPhotos);
	
	// click sur le bouton suivant
	$('#contentAlbumsPhotos .btnNext').bind('click',handleClickNextPaginationContentAlbumsPhotos);
	
	// click sur une page
	$('#contentAlbumsPhotos .numPage:not(.off)').bind('click',handleClickPagePaginationContentAlbumsPhotos);
}

function handleClickLastPaginationContentAlbumsPhotos(){
	$(this).unbind('click',handleClickLastPaginationContentAlbumsPhotos);
	if(currentPage > 1) currentPage--;
	getAlbumsPhotos('last');
}

function handleClickNextPaginationContentAlbumsPhotos(){
	$(this).unbind('click',handleClickNextPaginationContentAlbumsPhotos);
	if(currentPage < numPagesTotales) currentPage++;
	getAlbumsPhotos('next');
}

function handleClickPagePaginationContentAlbumsPhotos(){
	$(this).unbind('click',handleClickPagePaginationContentAlbumsPhotos);
	curSens = (currentPage > $(this).html()) ? 'last' : 'next';
	currentPage = $(this).html();
	getAlbumsPhotos(curSens);
}
