(function($, undefined){
	$.fn.helioReferences = function(){
		init();
		
		var $this = this.first();
		
		$this.find("#liste-cats a").click(loadSubset);
		
			//ouverture automatique si on a une ancre dans l'url
		if(window.location.hash){
			$(window.location.hash).find('a[rel="lightbox"]').click();
			/*$.colorbox({
				open: true,
				href: $(window.location.hash).attr('href'),
				width: 800,
				rel: 'nofollow',
				onComplete: animVisuels
			});*/
		}
		
		/**
		 * Charge le contenu de la page liste de référence
		 */
		function loadSubset(e){
			$.ajax({
				url: $(this).attr("href"),
				dataType: "html",
				success: showSubset
			})
			var parent = $(this).parent("li");
			parent.addClass("active");
			$this.find("#liste-cats li").not(parent).removeClass("active");
			
			e.preventDefault();
		}
		
		/**
		 * Affiche les références chargées via quicksand
		 */
		function showSubset(data, textStatus, XMLHttpRequest){
			var subset = $(data).find("#references li");
			$("#references").quicksand(subset, {adjustHeight: 'auto', attribute: 'id', enhancement: centreVisuels}, activeLightbox);
		}
		
		/**
		 * Exécuté au chargement d'une liste de références :
		 * - liens en lightbox
		 * - visuels centrés verticalement
		 */
		function init(){
			centreVisuels();
			activeLightbox();
		}
		
		/**
		 * Centre les visuels verticalement
		 */
		function centreVisuels(){
			$(".reference-list .visuel").each(function(){
				var $cur = $(this);
				var img = $cur.find("img");
				var margin = Math.min(($cur.innerHeight() - img.height()) / 2);
				img.css('margin-top', margin);
			});
		}
		
		/**
		 * Active l'ouverture en lightbox
		 */
		function activeLightbox(){
			$("a[rel='lightbox']").colorbox({
				width: 800,
				rel: 'nofollow',
				onComplete: animVisuels
			});
		}
		
		/**
		 * Anime les visuels présents dans la lightbox
		 */
		function animVisuels(){
			HeliopsisUtils.initLinks($("#cboxLoadedContent"));
			var maxHeight = 0;
			$("#cboxLoadedContent .visuels img").each(function(){
				var h = $(this).height();
				if(h > maxHeight) maxHeight = h;
			});
			$("#cboxLoadedContent .visuels").cycle({height: maxHeight});
			$.colorbox.resize();
		}
	}
})(window.jQuery);
