
/*******************/
/** EXTENDS ARRAY **/
/*******************/

Array.prototype.in_array = function(p_val) {
    for(var i = 0; i < this.length; i++) {
        if(this[i] == p_val) {
            return true;
        }
    }
    return false;
};


/*****************/
/** CLASSE I18N **/
/*****************/

function I18n(default_culture, available_cultures)
{
	this.culture = default_culture;
	
	this.available_cultures = available_cultures;
	
	this.translations = new Array();
	
	for(var i = 0; i < available_cultures.length; i++)
	{
		this.translations[available_cultures[i]] = new Array();
	}	
	
	/* détection de la culture contenue dans l'url */
	var url = window.location.href;
	var url_parts = url.split('/');
	
	for(var i = 0; i < url_parts.length; i++)
	{
		if( available_cultures.in_array(url_parts[i]) )
		{
			this.culture = url_parts[i];
		}
	}
}

I18n.prototype = {
	
	getCulture: function()
	{
		return this.culture;
	},
	
	getAvailbableCultures: function()
	{
		return this.available_cultures;
	},

	translate: function(libelle)
	{
		return this.translations[this.culture][libelle];
	}
	
};


/*******************/
/** CONFIGURATION **/
/*******************/

// delay d'activation rollover
var delay_rollover = 800;

// effet d'activation d'un projet sur la home
var easing_active_projet = 'easeInOutExpo';

//effet de desactivation d'un projet sur la home
var easing_desactive_projet = 'easeInOutExpo';

// delay affichage du site
var delay_display_page = 2000;

// delay diaporama home et liste projet
var delay_diaporama = 6000;

// durée d'affichage du diaporama
var duration_display_diaporama = 2000;

// delay d'affichage des vignettes de la liste
var delay_vignette = 5000;

//durée du switch de menuList
var duration_switch_menuList = 500;

//durée de fermeture du diaporama
var duration_hide_diaporama = 'fast';

// durée d'affichage d'une image du diaporama
var duration_display_image = 1000;

// effet d'affichage d'une image du diaporama
var easing_display_image = 'easeInOutExpo';

//durée d'affichage du journal
var duration_display_journal = 2000;

//durée de fermeture du journal
var duration_hide_journal = 'normal';

//durée d'affichage de la page
var duration_display_page = 1000;

//durée de fermeture de la page
var duration_hide_page = 'normal';

// durée d'affichage d'une fiche projet
var duration_display_fiche = 500;

// effet d'affichage d'une fiche projet
var esaing_display_fiche = 'easeInOutExpo';

// durée d'affichage/masquage de la carte sur la page contact
var duration_toggle_map = 'normal';

// durée d'affichage/masquage des blocs toggles (en savoir plus, commentaires...)
var duration_toggle_default = 'normal';

// durée d'affichage/masquage de la liste
var duration_toggle_list = 'normal';


// contante page title
var page_title = 'Cellules Studio - ';

// marge entre 2 fiches projet
var margin_between_two_fiches = 0;

// largeur minimale d'une photo du diaporama
var diapo_image_min_width = 1400;


/**********************/
/** Traductions I18n **/
/**********************/

// Nouvelle instance I18n (langue par defaut: fr, langues disponnibles: fr, en)
var i18n = new I18n('fr', ['fr','en']);

// détection de la culture dans l'url
i18n.getCulture();

// traduction
i18n.translations['fr']['refermer'] = 'Refermer';
i18n.translations['en']['refermer'] = 'Hide';
i18n.translations['fr']['see_more'] = 'En savoir plus';
i18n.translations['en']['see_more'] = 'See more';


/**************************/
/** DYNAMISATION DU SITE **/
/**************************/


/*
 * Highlight et défilement d'une liste de projets (Home)
 */
function ListHighlightToggle($list)
{
	this.list = $list.find('ul li');;
	
	this.currentProjet = this.list.filter(':first');
	
	this.timer = null;
	this.timeout = null;
}

ListHighlightToggle.prototype = {
	
	init: function()
	{
		var self = this;
		
		$.each(this.list, function()
		{
			var item = $(this).find('a');
			var bgColor = item.css('background-color');
		
			item.css({
				'background-color': 'transparent',
				position: 'relative',
				width: '100%',
				'z-index': 1
			});
		
			item.parent()
			.css({
				position: 'relative'
			})
			.prepend('<span style="display:block;width:100%;height:100%;background:'+bgColor+';position:absolute;z-index:0;top:0;left:-'+item.outerWidth()+'px;"></span>');
			
			item.parents('li').mouseover(function()
			{
				self.stop();
				self.desactiveProjet(self.currentProjet);
				
				self.currentProjet = $(this);
		
				// changement d'image de fond si l'on reste plus d'un certain temps
				self.activeProjet(self.currentProjet, delay_rollover);
			})
			.mouseleave(function()
			{
				self.start();
			});
		});
	
		// Activation du premier projet dans la liste et lancement du défilement automatique
		if( this.list.length > 1 && this.currentProjet.length > 0)
		{
			this.activeProjet(this.currentProjet);
		}
	},
	
	start: function()
	{
		var self = this;
		clearInterval(this.timer);
		this.timer = setInterval(function(){ self.nextProjet(self) }, delay_diaporama);
	},
	
	stop: function()
	{
		clearInterval(this.timer);
	},
	
	activeProjet: function(item, delay)
	{
		var self = this;
		// margin-left sur le texte
		item.find('a').stop(true, true).animate({ 'padding-left':'10px', 'color':'#FFF' }, 200);
		// animation de la bande colorée
		item.find('span').stop(true, true).animate({ left: 0 }, 200, easing_active_projet, function()
		{
			// changement d'image de fond si l'on reste plus d'un certain temps
			clearTimeout(self.timeout);
			self.timeout = setTimeout(function(){showImage(item.find('a').attr('id'), duration_display_image)}, delay);
		});
	},

	desactiveProjet: function(item)
	{
		// margin-left sur le texte
		item.find('a').stop(true, true).animate({ 'padding-left':'0', 'color':'#8F8B86' }, easing_desactive_projet);
		// animation de la bande colorée
		item.find('span').stop(true, true).animate({ left: item.width() * -1 +'px' }, easing_desactive_projet);
	},

	nextProjet: function(instance)
	{
		var self = instance || this;
		
		self.desactiveProjet(self.currentProjet);
		
		self.currentProjet = self.currentProjet.next();
		
		if( self.currentProjet.length != 1 )
		{
			self.currentProjet = self.list.filter(':first');
		}
		
		self.activeProjet(self.currentProjet);
	}
};


/*
 * Fiche projet
 */
function Fiche(id, href, $fiche)
{
	this.id = id;
	this.href = href;
	this.title;
	
	this.slug = this.href.split('/');
	this.slug = this.slug[this.slug.length - 1];
		
	this.blockFiche = $('#block_fiche');
	
	this.html = $fiche;
	this.more;
	this.see_more;
	
	if(this.html && this.html.length > 0)
	{
		this.more = this.html.find('.more');
		this.see_more = this.html.find('.see_more');
		
		this.more.hide();
		this.see_more.text(i18n.translate('see_more'))
	}
	
	this.journal = new Journal();
}

Fiche.prototype = {
	
	load: function(href)
	{
		// désactivation du clic de navigation entre les projets
		if( is_loading == false )
		{
			is_loading = true;
		}
		
		if( href == this.href )
		{
			return;
		}
		
		this.href = href;
		
		$('.bg_image').stop(true, true);
		
		this.loadFiche(href);
	},
	
	loadFiche: function(href)
	{
		var self = this;
		
		$('.bg_image').fadeOut(duration_hide_diaporama, function()
		{
			$.ajax({
				url: href, 
				success: function(data)
				{
					self.blockFiche.append(data);
					
					var fiches = self.blockFiche.find('.fiche_projet');
					
					$fiche = fiches.last();
				
					var newFiche = new Fiche($fiche.find('.close_projet').attr('rel'), href, $fiche);
					
					// si il y a une ancienne fiche d'affichée on la fait sortir puis on la retire du DOM
					if( fiches.length > 1 )
					{
						fiches.first().animate({ 'margin-left': fiches.outerWidth(true) * -1 }, duration_display_fiche, esaing_display_fiche, function()
						{
							$(this).remove();
							delete self;
							self = null;
							is_loading = false;
							newFiche.init();
						
							newFiche.journal.load();
						});
					}
				},
				dataType: 'html',
				cache: false
			});
		});
	},
	
	init: function()
	{
		this.title = this.html.find('h1').text();
		
		document.title = page_title + this.title;
		
		$.address.value(this.slug);

		this.activeListLinkByProjectId(this.id);
		
		//this.more = this.html.find('.more');
		//this.see_more = this.html.find('.see_more');
		
		this.addNextEventHandler();
		this.addMoreEventHandler();
		this.addShowJournalEventHandler();
		
		if( $.event.global.externalChange !== true )
		{
			this.initNavigationEvent();
		}
	},
	
	activeListLinkByProjectId: function(id)
	{
		$('.list a.active').removeClass('active');
		$('.list a[rel='+id+']').addClass('active');
	},
	
	addNextEventHandler: function()
	{
		var self = this;
		
		this.html.find('.next_projet').click(function(event)
		{
			if( event.currentTarget.href.search('projets') == -1 )
			{
				event.preventDefault();
				if( is_loading === false )
				{
					self.load(event.currentTarget.href);
				}
			}
		});
	},
	
	addMoreEventHandler: function()
	{
		var self = this;
		
		this.see_more.click(function(e)
		{
			e.preventDefault();
			
			self.more.slideToggle(duration_toggle_default, function()
			{
				self.see_more.text( $(this).is(':visible') ? i18n.translate('refermer') : i18n.translate('see_more') );
			});
		});
	},
	
	addShowJournalEventHandler: function()
	{
		var self = this;
		
		this.html.find('a.link_journal').click(function(e)
		{
			e.preventDefault();
			
			self.journal.show(e.currentTarget.href);
		});
	},
	
	initNavigationEvent: function()
	{
		var self = this;
		
		var is_first_fiche = true;
		
		// ecouteur de changement d'url via le navigateur
		$.address.bind('externalChange', function(event)
		{
			var href = document.location.pathname.split('/');
			
			// si ce n'est pas la première fiche visitée
			if( event.value != '/' && !is_first_fiche )
			{
				// préparation de l'url
				href.pop();
				if( href.in_array('selection') )
				{
					href.pop();
				}
				
				href = href.join('/');
				
				self.load(href + event.value);
			}
			// s'il s'agit de la première fiche visitée
			if(event.value == '/' || document.location.href.search('projets') != -1)
			{
				document.location.href = '/' + i18n.getCulture() + '/'+ getCategory() +'/projets';
			}
			
			if(is_first_fiche) is_first_fiche = false;
		});
	}
	
};


/*
 * Journal d'un projet
 */
function Journal()
{
	this.bg_image = $('.bg_image');
	
	this.journal = $('#journal');
	
	this.images = [];
	
	this.images_diapo = [];
	
	this.index = 1;
}

Journal.prototype = {
	
	load: function()
	{
		var self = this;
		
		this.bg_image.empty();
		
		$.ajax({
			url: '/'+ i18n.culture +'/diaporama/getDiaporamaForProjet?json=true', 
			success: function(images)
			{
				var first = true;
				for(var i = 0; i < images.length; i++)
				{
					self.createImageDiapo(images[i], first);
					first = false;
				}
			},
			dataType: 'json',
			cache: false
		});
	},
	
	createImageDiapo: function(image, first)
	{
		var self = this;
		
		if( image )
		{
			var img = new Image()
			img.src = image.src;
			img.alt = image.alt;
			img.className = image.className;
			img.style.display = 'none';
			
			if(first)
			{
				if(img.complete) self.firstImageDiapoOnLoadHandler([{currentTarget: img}]);
				else img.onload = function(){ self.firstImageDiapoOnLoadHandler(arguments) };
			}
			else {
				if(img.complete) self.imageDiapoLoaded([{currentTarget: img}]);
				else img.onload = function(){ self.imageDiapoLoaded(arguments) };
			}
			
			self.images_diapo.push(img);
			
			self.bg_image.append(img);
		}
	},
	
	firstImageDiapoOnLoadHandler: function(args){
		var journal = new Journal;
		journal.firstImageDiapoLoaded(journal, args[0]);
	},
	
	firstImageDiapoLoaded: function(journal, e)
	{
		if( e != null )
		{
			var image = $(e.currentTarget);
		}
		else {
			var image = $('.bg_image img:first');
		}
		
		resizeImage(image);
		
		image.show();
		
		journal.bg_image.fadeIn(duration_display_diaporama);
	},
	
	imageDiapoLoaded: function(args)
	{
		var e = args[0];
		if( e != null )
		{
			resizeImage($(e.currentTarget));
		}
	},
	
	show: function(url)
	{
		var self = this;
		
		if( history.pushState )
		{
			history.pushState(null, null, url);
		}
		
		var wrap = $('#wrap');
		
		wrap.fadeOut(duration_hide_page, function()
		{
			$.ajax({
				url: url, 
				success: function(content)
				{
					$('body').removeClass().addClass('projet journal');
					$('#wrap_content').html(content);
					$('#header').hide();
					
					self.journal = $('#journal');
				
					self.pagination = { current: [], total: [] };
					self.pagination.current = self.journal.find('.pagination .current');
					self.pagination.total = self.journal.find('.pagination .total');
					self.citation = self.journal.find('cite');
					
					self.images = self.bg_image.find('img');
				
					self.gotoImage(self.index);
				
					self.addJournalEventHandler();
				
					wrap.fadeIn(duration_display_journal);
				},
				dataType: 'html',
				cache: false
			});
		});
	},
	
	close: function(url)
	{
		var self = this;
		var wrap = $('#wrap');
		
		wrap.fadeOut(duration_hide_journal, function()
		{
			// on revient à la première image
			/*var currentImg = $(self.images[self.index - 1]);
			var firstImg = $(self.images[0]);
			
			if( currentImg.get(0) != firstImg.get(0) )
			{
				self.index = 1;
				currentImg.stop(true, true).fadeOut(duration_display_image);
				firstImg.stop(true, true).fadeIn(duration_display_image);
			}*/
						
			$.ajax({
				url: url, 
				data: { with_sidebar: true }, 
				success: function(content)
				{
					$('body').removeClass().addClass('projet fiche');
					$('#wrap_content').html(content);
					$('#wrap').width('948px');
					$('#header').show();
				
					//initSidebarTab();
				
					var $fiche = $('.fiche_projet');
					var fiche = new Fiche($fiche.find('.close_projet').attr('rel'), url, $fiche);
					fiche.init();
					fiche.journal.index = self.index;
				
					var menu = new menuList($('#sidebar'));
					menu.init();
				
					wrap.fadeIn(duration_display_page);
				
					if( history.pushState )
					{
						history.pushState(null, fiche.title, fiche.href);
					}
				},
				dataType: 'html',
				cache: false
			});
		});
	},
	
	addJournalEventHandler: function()
	{
		var self = this;
		
		// pagination event
		this.journal.find('.pagination a').click(function(e)
		{
			e.preventDefault();
			
			//self.index = Number(self.journal.find('.pagination .current').text());
			
			if( $(this).hasClass('next') )
			{
				self.nextImage();
			}
			else {
				self.prevImage();
			}
			
			var total = Number(self.pagination.total.text());
			
			if( self.index < 1 )
			{
				self.index = total;
			}
			else if( self.index > total )
			{
				self.index = 1;
			}
			
			var current = (self.index < 10) ? '0'+self.index : self.index;
			var citation = $(self.images[self.index - 1]).attr('alt');
			
			self.pagination.current.html(current);
			
			self.citation.text(citation);
		});
		
		// bouton ferme event
		this.journal.find('.close_journal').click(function(e)
		{
			e.preventDefault();
			
			/*if( history.pushState )
			{
				history.pushState(null, event.currentTarget.title, e.currentTarget.href);
			}*/
			
			self.close(e.currentTarget.href);
		});
	},
	
	nextImage: function()
	{
		if( this.images.length < 2 ) {
			return false;
		}
		var currentImg = $(this.images[this.index - 1]);
		var nextImg = $(this.images[this.index]);
		if( nextImg.length == 0 ) {
			nextImg = $(this.images[0]);
			if( nextImg.length == 0 ) {
				return false;
			}
		}
		
		this.index++;
		
		currentImg.stop(true, true).fadeOut(duration_display_image);
		nextImg.stop(true, true).fadeIn(duration_display_image);
	},

	prevImage: function()
	{
		if( this.images.length < 2 ) {
			return false;
		}
		var currentImg = $(this.images[this.index - 1]);
		var nextImg = $(this.images[this.index - 2]);
		if( nextImg.length == 0 ) {
			nextImg = $(this.images[this.images.length - 1]);
			if( nextImg.length == 0 ) {
				return false;
			}
		}
		
		this.index--;
		
		currentImg.stop(true, true).fadeOut(duration_display_image);
		nextImg.stop(true, true).fadeIn(duration_display_image);
	},
	
	gotoImage: function(key, fade)
	{
		var self = this;
		
		if(fade)
		{
			$(self.images).not(':eq('+ self.index - 1 +')').stop(true, true).fadeOut(duration_display_image);
			$(self.images[self.index - 1]).fadeIn(duration_display_image);
		}
		else {
			$(self.images).not(':eq('+ self.index - 1 +')').hide();
			$(self.images[self.index - 1]).show();
		}
		
		self.pagination.current.text( (self.index < 10) ? '0'+self.index : self.index );
		self.citation.text( $(self.images[self.index - 1]).attr('alt') );
	}
	
};


function menuList($menu)
{
	var self = this;
		
	this.menu = $menu;
	this.tabs = $menu.find('#list_link a');
}

menuList.prototype = {
	
	init: function()
	{
		var self = this;
		
		var activeTab = self.tabs.filter('.active');
		var notActiveTabs = (activeTab.length > 0) ? self.tabs.not('.active') : self.tabs.not(':first');
		
		$.each(notActiveTabs, function(i, link)
		{
			var block = self.menu.find(link.rel).hide();
		});
		
		self.tabs.click(function(e)
		{
			e.preventDefault();
			self.openTab(e.currentTarget.rel);
		});
		
		// chargement ajax si lien mot clef
		/*self.menu.find('.tab a').click(function(e)
		{
			if( e.currentTarget.href.search('type') != -1 )
			{
				e.preventDefault();
				self.loadContent(e.currentTarget.href);
			}
		});*/
		
		self.initListeProjets();
	},
	
	openTab: function(id)
	{
		var self = this;
		
		self.tabs.removeClass('active').filter('[rel="'+id+'"]').addClass('active');
		
		self.menu.find('.tab').stop(true).fadeOut(duration_switch_menuList, function()
		{
			var newTab = $(this).filter(id);
			setTimeout(function(){ newTab.fadeIn(duration_switch_menuList); }, 500);
		});
		
		$.ajax({
			url: '/' + i18n.getCulture() + '/projet/resetFilter', 
			data: { category: getCategory() }, 
			success: function()
			{
				if( id == '#title' )
				{
					$.get('/' + i18n.getCulture() + '/projet/setListAlphabetique', { category: getCategory() });
				}
			},
			dataType: 'html',
			cache: false
		});
	},
		
	loadContent: function(url)
	{
		var self = this;
		
		var content = $('#list') || $('#content_right_projet');
		
		content.fadeOut(duration_toggle_list, function()
		{
			content.load(url, function()
			{
				self.initListeProjets();
				
				content.fadeIn(duration_toggle_list);
			});
		});
		
		var urlPath = url.split('/');
		var keyword = urlPath[urlPath.length - 1];
		
		window.location.hash = keyword;
		
		// sous-menu "types"
		$('.tab .sublist').remove();
		$('.tab a').removeClass('active');
		
		$.ajax({
			url: '/' + i18n.getCulture() + '/projet/getProjetsLinksByKeywords', 
			data: { category: getCategory(), keyword: keyword }, 
			success: function(html)
			{
				$('.tab a.'+ keyword).addClass('active').parents('li').after('<li>'+ html +'</li>');
			},
			dataType: 'html',
			cache: false
		});
	},
	
	initListeProjets: function()
	{
		var self = this;
		
		// On rend toute la vignette cliquable
		$('ul#selected_projets li, ul#list_projets li').css('cursor','pointer').click(function(e)
		{
			document.location = $(e.currentTarget).find('a').attr('href');
		});
		
		// Rollover vignette projet en sélection
		$('#selected_projets li').mouseenter(function()
		{
			// on arrête le défilement auto
			stopVignetteDefile();
			
			// changement d'image de fond si l'on reste plus d'un certain temps
			currentVignette.removeClass('highlight');
			currentVignette = $(this);
			currentVignette.addClass('highlight');
			
			clearInterval(timeout);
			timeout = setTimeout(function(){showImage(currentVignette.attr('id'), duration_display_image)}, delay_rollover);
		})
		.mouseleave(function()
		{
			timer = setInterval(nextVignette, delay_vignette);
		});
		
		// Défilement automatique des projets
		if( $('#selected_projets li').length > 0 )
		{
			currentVignette = $('#selected_projets li:first');
			currentVignette.addClass('highlight');
			
			timer = setInterval(nextVignette, delay_vignette);
		}
		
		// Affichage des infos sur chaque vignette projet de la liste
		$.each($('#list_projets li'), function()
		{
			var vignette = $(this);
			var blockInfo = vignette.find('div');
			var posHiddenBlockInfo = parseInt(vignette.css('height')) + parseInt(vignette.css('padding-top')) + parseInt(vignette.css('padding-bottom')) +'px';
			blockInfo.css({ top:  posHiddenBlockInfo });
			
			$(this).mouseenter(function()
			{
				blockInfo.stop(true).animate({ top: 0 }, 100);
			})
			.mouseleave(function()
			{
				blockInfo.stop(true).animate({ top: posHiddenBlockInfo }, 100);
			});
		});
	}
	
};



/***** LET'S GO *****/

var timeout = null;
var timerResize = null;

var timer = null;
var currentVignette = null;
var currentProjet = null;

var is_loading = false;

var block_fiche_width = 0;

var nb_images = 0;
var nb_images_loaded = 0;

var images_diapo = [];

var temp = [];


function getUrl()
{
	var url = document.location.href;
	url = url.substring(url.lastIndexOf('.php') + 4, url.length);
	return url;
}

function getCategory()
{
	var url = getUrl();
	url = url.split('/');
	
	for(var i = 0; i < url.length; i++)
	{
		if( url[i] == i18n.getCulture() )
		{
			return url[i + 1];
		}
	}
	
	return url[4];
}


/*
**  onDomReady
*/
jQuery(document).ready(function($)
{
	//init();
	
	var url = getUrl();
	var hash = url.split('#');
	hash = ( hash.length > 1 ) ? hash[hash.length - 1] : '';
	hash = hash.replace('/', '');
	
	if( (url.indexOf('type') != -1  || url.indexOf('projets') != -1 ) && hash.length > 0 )
	{
		var menu = new menuList($('#sidebar'));
		menu.loadContent('/' + i18n.getCulture() + '/'+ getCategory() + '/projets/type/' + hash);
		
		menu.openTab('#type');
		
		init();
	}
	else if( url.indexOf('projet') != -1 && hash.length > 0 )
	{
		document.location = '/' + i18n.getCulture() + '/'+ getCategory() + '/projet/' + hash;
	}
	else {
		init();
	}
});


/*
** Initialisation 
*/
function init()
{
	// initialsiation des animations
	initAnimations();
	
	// initialisation du diaporama de fond
	initDiaporama();
	
	$('.more').hide();
}


/*
** Initialisation du diaporama
*/
function initDiaporama()
{
	$('.bg_image img').not(':eq(0)').hide();
	
	$('.bg_image').width(window.innerWidth);
	
	// resize des images à la taille de la fenêtre
	resizeDiaporama();
	
	// resize des images onResize de la fenêtre
	$(window).resize(function()
	{
		clearTimeout(timerResize);
		timerResize = setTimeout(resizeDiaporama, 100);
	});
}

/*
** Initialisation des animations
*/
function initAnimations()
{
	/* Animation d'affichage */
	var background = $('#wrap').css('background-image');
	$('#wrap, #wrap_content').css({'background': '#000000'});
	
	$('.bg_image').hide();
	
	$('#wrap_content').css("opacity","100").hide().fadeIn('slow', function()
	{
		$('#wrap').css({ 'background': background + ' repeat scroll 0 0 transparent' });
		$(this).css({'background': 'none'});
		
		$('.bg_image').fadeIn(delay_display_page);
	});
	
	
	/*
	** page Accueil
	*/
	if( $('body').hasClass('accueil') )
	{
		var listToggle = new ListHighlightToggle($('.last_projets'));
		listToggle.init();
		listToggle.start();
	}
	
	
	/*
	** Inisitalisation de la liste des projets
	*/
	if( $('body').hasClass('list') || $('body').hasClass('keyword') )
	{
		var menu = new menuList($('#sidebar'));
		menu.init();
	}
	
	
	/*
	 * Page Fiche Projet
	 */
	if( $('.fiche_projet').length > 0 )
	{
		// init fiche projet
		var $fiche = $('.fiche_projet');
		var fiche = new Fiche($fiche.find('.close_projet').attr('rel'), document.location.href, $fiche);
		fiche.init();
		
		var menu = new menuList($('#sidebar'));
		menu.init();
		
		// init navigation entre les fiches projet
		$('#sidebar a.projet').click(function(event)
		{
			event.preventDefault();
			fiche.load(event.currentTarget.href);
		});
	}
	
	
	/*
	 * Page Journal
	 */
	if($('#journal').length > 0)
	{
		var journal = new Journal()
		journal.addJournalEventHandler();
	}
	
	
	/*
	** Page contact 
	*/
	if( $('body').hasClass('contact') )
	{
		initPageContact()
	}
	
	
	/*
	 * Blog
	 */
	if( $('body').hasClass('blog') )
	{
		$('.commentaires').hide();
		
		$.each($('.post'), function()
		{
			if( $(this).find('.error').length > 0 )
			{
				$(this).find('.commentaires').show();
			}
		});
		
		$('a.nb_commentaires').click(function(e)
		{
			e.preventDefault();
			$(this).parents('.post').find('.commentaires').toggle(duration_toggle_default);
		});
	}
	
} // end initAnimations()



// Défilement des vignettes de la liste des projets
function nextVignette()
{
	currentVignette.removeClass('highlight');
	
	currentVignette = currentVignette.next()

	if( currentVignette.length != 1 )
	{
		currentVignette = $('#selected_projets li:first');
	}
	
	currentVignette.addClass('highlight');
	
	showImage(currentVignette.attr('id'), duration_display_image);
}

// Arrêt du défilement des vignettes
function stopVignetteDefile()
{
	clearInterval(timer);
}


/*
** Initialisation de la page contact : Animation d'affichage/masquage de la carte sur la page contact
*/
function initPageContact()
{
	$('#wrap').mouseleave(hideMap).mouseenter(showMap);
	
	$('a.show_map').click(function(e)
	{
		e.preventDefault();
		
		if( $('#wrap_content').is(':visible') )
		{
			hideMap();
		}
		else {
			showMap();
		}
	});
}


/*
 * Fonctions d'affichage et masquage de la carte en arrière plan
 */
function hideMap()
{
	$('#wrap').css({'position': 'absolute'});
	$('.bg_image').css({ 'z-index': '0' });
	$('#wrap_content, #header, #footer').stop(true, true).fadeOut(duration_toggle_map, function()
	{
		$('#wrap').stop().animate({ width: '258px' }, 500);
	});
}

function showMap()
{
	$('#wrap').stop(true, true).animate({ width: '948px' }, 500, function()
	{
		$('#wrap_content, #header, #footer').fadeIn(duration_toggle_map);
	});
	$('#wrap').css({'position': 'relative'});
	$('.bg_image').css({ 'z-index': '-1' });
}


/*
 * Affichage de l'image de fond relative à l'id passé en paramètre (projet_#) 
 */
function showImage(id, delay)
{
	var bg_images = $('.bg_image img');
	var marge = 0;
	var newImage = bg_images.filter('.'+id);
	var oldImage = bg_images.filter(':visible');
	if(newImage.length > 0 && newImage.attr('class') != oldImage.attr('class'))
	{
		bg_images.css({ 'z-index': 0 });
		oldImage.stop(true, true).css({ 'z-index': bg_images.length }).animate({ left: $(oldImage).width() * -1 }, delay, easing_display_image, function(){ $(this).hide() });
		newImage.css({ left: $(window).width() + marge, 'z-index': bg_images.length - 1 }).show().animate({ left: 0 }, delay, easing_display_image);
	}
}


/*
 * Resize Handler
 */
function resizeDiaporama()
{
	var bg_image = $('.bg_image');
	bg_image.width(window.innerWidth);
	$.each(bg_image.find('img'), function(){ resizeImage($(this)) });
}

/*
 * Resize d'une image à la taille de son parent
 */
function resizeImage($image)
{
	var scene = $image.parent();
    
    var sceneWidth = scene.width();
    var sceneHeight = scene.height();
    var ratioScene = sceneWidth / sceneHeight;

    scene.css('overflow','hidden');
    if(scene.css('position') == 'absolute')
    {
    	scene.css('position','relative');
    }
    
	var img = new Image();
    img.src = $image[0].src;

	if(img.complete) resizeImageOnLoad($image, sceneWidth, sceneHeight, ratioScene);
	else img.onload = resizeImageOnLoad($image, sceneWidth, sceneHeight, ratioScene);
}

function resizeImageOnLoad($image, sceneWidth, sceneHeight, ratioScene)
{
	if($image[0].complete == false)
	{
		setTimeout(function(){ resizeImageOnLoad($image, sceneWidth, sceneHeight, ratioScene) }, 100);
	}
	
	if( $image[0].naturalWidth )
	{
		var imageWidth = $image[0].naturalWidth;
	    var imageHeight = $image[0].naturalHeight;
	}
	else
	{
		var imageWidth = $image[0].width;
        var imageHeight = $image[0].height;
	}
	
	if(imageWidth == 0 || imageHeight == 0) return false;

    var ratioImage = imageWidth / imageHeight;

    if( ratioScene >= ratioImage )
    {
        var height = Math.ceil(sceneWidth / ratioImage);
        $image.css({
            'width': sceneWidth,
            'height': height,
            'position': 'absolute',
            'left': 0,
            'top': Math.round(sceneHeight - height) / 2 +'px'
        });
    }
    else {
        var width = Math.ceil(sceneHeight * ratioImage);
        $image.css({
            //'width': width,
            'height': sceneHeight,
            'position': 'absolute',
            //'left': Math.round(sceneWidth - width) / 2 +'px',
            'top': 0
        });
    }

    // recadrage pour la largeur minimale
    if( parseInt($image.css('width')) < diapo_image_min_width )
	{
		$image.css({
    		'width': diapo_image_min_width,
    		'height': diapo_image_min_width / ratioImage,
    		'left': 0
    	});
	}
}
