/**
 * @version            1.1
 *
 * @author             Rémi Prévost <remi-at-ixmedia-dot-com>
 * @copyright          (C) 2007. All rights reserved.
 * @classDescription   A nice alternative to Thickbox and Lightbox
 * @license            http://creativecommons.org/licenses/by-nc/3.0/
 * 
 * @thanks             To http://panic.com for their getHeight() et getScroll() function
 *
 * @package            jQuery Plugins
 * @subpackage         ixBox
 */

(function($) {

	$(document).ready(ixbox_init);

	/* Sélecteurs pour les ixBox */
	var ixbox_selecteurs    = 'a.ixbox';

	/* Sélecteurs pour les ixBox */
	var ixbox_imgpath      = '/img/ixbox/';

	/* Easing pour l'animation d'ouverture
	 * Inscire '' pour aucune */	
	var ixbox_open_easing   = 'easeout';

	/* Vitesse pour l'animation d'ouverture */		
	var ixbox_open_speed    = 300;

	/* Vitesse pour l'apparition des contrôles */			
	var ixbox_controls_speed   = 400;

	/* Vitesse pour l'apparition du titre */			
	var ixbox_title_speed   = 400;

	/* Easing pour l'animation de fermeture
	 * Inscire '' pour aucune */		
	var ixbox_close_easing  = 'easein';

	/* Vitesse pour l'animation de fermeture */			
	var ixbox_close_speed   = 300;

	/* Opacité finale pour l'animation de fermeture	 */			
	var ixbox_close_opacity   = 0.6;	
	
	/* Est-ce qu'on met une ombre derrière l'image? */			
	var ixbox_shadow   	= true;
	
	var ixbox_languages = new Array;
	var ixbox_languages_default = "en";
	
	// Langage: francais
	ixbox_languages['fr-ca'] = new Array;
	ixbox_languages['fr-ca']['close_label'] = "fermer";
	ixbox_languages['fr-ca']['close_title'] = "Fermer l'image";
	ixbox_languages['fr-ca']['prev_title']  = "Image précédente";
	ixbox_languages['fr-ca']['next_title']  = "Image suivante";

	// Langage: english
	ixbox_languages['en'] = new Array;
	ixbox_languages['en']['close_label'] = "close";
	ixbox_languages['en']['close_title'] = "Close the image";
	ixbox_languages['en']['prev_title']  = "Previous image";
	ixbox_languages['en']['next_title']  = "Next image";
	
	// Détermination du langage de la page	
	var ixbox_lang = $('html').attr("xml:lang") || $('html').attr("lang") || ixbox_languages_default;


	/**
	 * Initialise les liens utilisant ixBox
	 */
	var ixbox_c = 1;
	var ixbox_a = false;
	function ixbox_init() {
		$(ixbox_selecteurs).click(function() {
			ixbox_show(this);
			return false;
		});
		$(window).resize(function() {
			ixbox_recenter();
		});
	}
	
	/**
	 * Affiche la ixBox
	 * @param {Object} el
	 */
	function ixbox_show(el) {
		if (ixbox_a === true) { return false; }
		ixbox_a = true;
		// On ferme les ixBox déja présentes
		$('#ixbox_img').attr("id","ixbox2_img");
		var ixbox = $('#ixbox2_img');
		if (ixbox.length != 0) {
			$('#ixbox_title, #ixbox_fermer, #ixbox_suivant, #ixbox_precedent').remove();
			ixbox = ixbox[0];
			ixbox_kill(ixbox);
		}

		// On définit quelques variables de base
		var el   = $(el);
		var img  = el[0].href;
		var title= el[0].title;
		var rel  = el.attr("rel");	
		
		// Code de Thickbox pour gérer les images suivantes/précédentes
		var ixbox_liens = $("a[@rel="+rel+"]").get();
		var ixbox_trouve = false;
		var ixbox_next = null;
		var ixbox_prev = null;
		for (var compteur = 0; ((compteur < ixbox_liens.length) && (ixbox_next === null)); compteur++) {
				if (!(ixbox_liens[compteur].href == img)) {
					if (ixbox_trouve) {	ixbox_next = ixbox_liens[compteur]; }
					else {              ixbox_prev = ixbox_liens[compteur]; }
				} else {
					ixbox_trouve = true;
				}
		} // Fin du code de Thickbox (Merci Cody Lindley!)
		
	
		// Paramètres de la vignette
		var el_img = $('img',el);
		var el_img_height = el_img.outerHeight();
		var el_img_width= el_img.outerWidth();
		
	
		var position = el_img.offset();		
		//$('body').append('<div id="ixbox_minioverlay" style="left: '+position.left+'px; top: '+position.top+'px; width: '+el_img_width+'px; height: '+el_img_height+'px;"></div>');
		//$('#ixbox_minioverlay').css("opacity",0.7);
		
		// On préload l'image
		var imgPreloader = new Image();
		imgPreloader.onload = function(){
			imgPreloader.onload = null;
			$('#ixbox_minioverlay').fadeOut(function() {
				$(this).remove();
			});
			
			// Resizing large images - orginal by Christian Montoya + Cody Lindley
			var pagesize = ixbox_getPageSize();
			var x = pagesize[0] - 150;
			var y = pagesize[1] - 150;
			var imageWidth = imgPreloader.width;
			var imageHeight = imgPreloader.height;
			if (imageWidth > x) {
				imageHeight = imageHeight * (x / imageWidth);
				imageWidth = x;
				if (imageHeight > y) {
					imageWidth = imageWidth * (y / imageHeight);
					imageHeight = y;
				}
			} else if (imageHeight > y) {
				imageWidth = imageWidth * (y / imageHeight);
				imageHeight = y;
				if (imageWidth > x) {
					imageHeight = imageHeight * (x / imageWidth);
					imageWidth = x;
				}
			}
			
			imgPreloader.width = imageWidth;
			imgPreloader.height = imageHeight;
			
			// End Resizing		
	
			// On ajoute le code HTML
			$('body').append('<img id="ixbox_img" style="width: '+el_img_width+'px; height: '+el_img_height+'px; position: absolute; left: -999999px;" src="'+img+'" alt="" />');

			var version = parseInt($.browser.version);
			if ($.browser.msie && version <= 6) {
				$('body').addClass("ie6")
			}
			
			// On trouve la position de la vignette

//			alert(imgPreloader.width);

			var new_top =  parseInt(((ixbox_getheight() - imgPreloader.height) / 2) + ixbox_getscroll());
			var new_left = ($(window).width() - imgPreloader.width ) / 2;

			// On garde en mémoire avec quelle vignette est associée notre image
			el_img.attr("ixbox_id",ixbox_c);
			$('#ixbox_img').attr("ixbox_original", ixbox_c);
			ixbox_c++;

			var ixbox_shadow_temp = ixbox_shadow;
			if ($.browser.msie) { ixbox_shadow = false; }
			if ($.browser.msie && version > 6 && ixbox_shadow_temp) { ixbox_shadow = true; }
			if (!ixbox_shadow) {
				$('#ixbox_img').css("border","2px solid #000");
			}
						
			// On anime!
			
			//alert(position.top);
			
			$('#ixbox_img').css({ opacity: "0.2", left: position.left+"px", top: position.top+"px" });
//			alert(new_left);
//			$('#ixbox_img').css({left: new_left+'px', top: new_top+'px'});
			
			$('#ixbox_img').animate({
										left: new_left+"px",
										top: new_top+"px",
										width: imgPreloader.width+"px",
										height: imgPreloader.height+"px",
										opacity: 1
									}, ixbox_open_speed, ixbox_open_easing, function() {
										
										// Le bouton "Fermer"
										$('body').append('<a class="ixbox_controls" title="'+ixbox_languages[ixbox_lang]['close_title']+'" id="ixbox_fermer" href="javascript://">'+ixbox_languages[ixbox_lang]['close_label']+'</a>');
										$('#ixbox_fermer')
											.css({
													left: (new_left + imgPreloader.width - 50) + "px",
													top : (new_top - 20) + "px"
												});

										// Si on est dans un groupe
										if (ixbox_next || ixbox_prev) {
											if (ixbox_next) {
												$('body').append('<a class="ixbox_controls" title="'+ixbox_languages[ixbox_lang]['next_title']+'" id="ixbox_suivant" href="javascript://"></a>')
												$('#ixbox_suivant')
													.css({
															left: (new_left + imgPreloader.width - 20) + "px",
															top : (new_top + (imgPreloader.height / 2)) + "px"
													})											
													.click(function() { ixbox_show(ixbox_next); });
											}
											if (ixbox_prev) {
												$('body').append('<a class="ixbox_controls" title="'+ixbox_languages[ixbox_lang]['prev_title']+'" id="ixbox_precedent" href="javascript://"></a>')
												$('#ixbox_precedent')
													.css({
															left: (new_left - 20) + "px",
															top : (new_top + (imgPreloader.height / 2)) + "px"
													})
													.click(function() { ixbox_show(ixbox_prev); });
											}												
										}
																													
										// Le titre, s'il y en a un
										if(title) {
											$('body').append('<div class="ixbox_controls" id="ixbox_title"></div>');

											$('#ixbox_title')
												.html("<p style=\"display: block;\">"+title+"</p>")
												.css( {
														left: (new_left + 10) + "px",
														width: (imgPreloader.width - 20)+"px"
												})
												.css({
														top : (new_top +imgPreloader.height - 10 - $('#ixbox_title').height()) + "px"
												});
										} 
										
										var version = parseInt($.browser.version);		
										if ($.browser.msie && version >= 7) {										
											$('.ixbox_controls').show();
										} else {
											$('.ixbox_controls').fadeIn(ixbox_controls_speed);
										}
										
										// Les handlers d'évènements
										$('#ixbox_img, a#ixbox_fermer').click(function() {
											var ixbox = $('#ixbox_img')[0];
											ixbox_kill(ixbox);
											return false;
										});
																	
										$(document).keyup( function(e){ var key = e.keyCode; if(key == 27){
											var ixbox = $('#ixbox_img')[0];
											ixbox_kill(ixbox);
											return false;
										}});
										
										ixbox_a = false;
										
									
										if (ixbox_shadow) {
											ixbox_ombre();
										}
										
										ixbox_recenter();
										
									});
									
		}
		imgPreloader.src = img;
	}
	
	/**
	 * Re-centre la ixBox
	 */
	function ixbox_recenter() {
		if ($('#ixbox_img').length == 0) { return false; }
		
		var img_width = $('#ixbox_img').width();
		var img_height = $('#ixbox_img').height();
				
		var new_top =  parseInt(((ixbox_getheight() - img_height) / 2) + ixbox_getscroll());
		var new_left = ($(window).width() - img_width ) / 2;			

		$('#ixbox_img').css({
							left: new_left,
							top: new_top
							});
							
		$('#ixbox_fermer').css({
								left: (new_left + img_width - 50) + "px",
								top : (new_top - 20) + "px"
								});
								
		$('#ixbox_suivant').css({
								left: (new_left + img_width - 20) + "px",
								top : (new_top + (img_height / 2)) + "px"
								});
								
		$('#ixbox_precedent').css({
								left: (new_left - 20) + "px",
								top : (new_top + (img_height / 2)) + "px"
								});
		
		if ($("#ixbox_title").length) {
			$('#ixbox_title').css({
									left: (new_left + 10) + "px",
									top : (new_top +img_height - 10 - $('#ixbox_title').height()) + "px",
									width: (img_width - 20)+"px"
								});
		}

		ixbox_ombre_recenter();
	}
	
	/**
	 * Créé l'ombre
	 */
	function ixbox_ombre() {
		$('body').append('<div id="ixbox_r"></div><div id="ixbox_br"></div><div id="ixbox_b"></div><div id="ixbox_bl"></div><div id="ixbox_l"></div><div id="ixbox_tl"></div><div id="ixbox_t"></div>');
		$('#ixbox_r, #ixbox_br, #ixbox_b, #ixbox_bl, #ixbox_l, #ixbox_tl, #ixbox_t').addClass("ixbox_ombres").css("display","none");		
		ixbox_ombre_recenter();
		var version = parseInt($.browser.version);		
		if ($.browser.msie && version >= 7) {
			$('.ixbox_ombres').show();
		} else {
			$('.ixbox_ombres').fadeIn(ixbox_controls_speed);
		}
	}
	
	/**
	 * Positionne l'ombre
	 */
	function ixbox_ombre_recenter() {
		var ixleft  = $('#ixbox_img').css('left');
		ixleft = parseInt(ixleft.replace("px","")) - 1;
		var ixtop   = $('#ixbox_img').css('top');
		ixtop = parseInt(ixtop.replace("px",""));
		
		var ixwidth = $('#ixbox_img').width();
		var ixheight = $('#ixbox_img').height();
		
		$('#ixbox_r').css({
							background: 'url('+ixbox_imgpath+'shadows/right.png)',
							width: '18px',
							height: (ixheight - 17)+'px',
							top: (ixtop - 12)+"px",
							left: (ixleft + ixwidth + 1) +"px"
							});
							
		$('#ixbox_br').css({
							background: 'url('+ixbox_imgpath+'shadows/bottom-right.png)',
							width: '31px',
							height: '49px',
							top: (ixtop + ixheight - 29)+"px",
							left: (ixleft + ixwidth - 12) +"px"
							});		
							
		$('#ixbox_b').css({
							background: 'url('+ixbox_imgpath+'shadows/bottom.png)',
							width: (ixwidth - 35)+'px',
							height: '20px',
							top: (ixtop + ixheight)+"px",
							left: (ixleft + 23) +"px"
							});													

		$('#ixbox_bl').css({
							background: 'url('+ixbox_imgpath+'shadows/bottom-left.png)',
							width: '35px',
							height: '37px',
							top: (ixtop + ixheight - 17)+"px",
							left: (ixleft - 12) +"px"
							});	
							
		$('#ixbox_l').css({
							background: 'url('+ixbox_imgpath+'shadows/left.png)',
							width: '14px',
							height: (ixheight - 33)+'px',
							top: (ixtop + 16)+"px",
							left: (ixleft - 12) +"px"
							});			
							
		$('#ixbox_tl').css({
							background: 'url('+ixbox_imgpath+'shadows/top-left.png)',
							width: '34px',
							height: '28px',
							top: (ixtop - 12)+"px",
							left: (ixleft - 12) +"px"
							});								

		$('#ixbox_t').css({
							background: 'url('+ixbox_imgpath+'shadows/top.png)',
							width: (ixwidth - 1)+'px',
							height: '13px',
							top: (ixtop - 12)+"px",
							left: (ixleft + 22) +"px"
							});		
	}
	
	/**
	 * Détruit les ixBox actuelles
	 * @param {Object} el
	 */
	function ixbox_kill(el) {
		if (!el) {
			return false;
		}
		var id = $(el).attr("ixbox_original");
		var el_img = $('img[@ixbox_id='+id+']');
		var position = el_img.offset();
		$('.ixbox_controls, .ixbox_ombres').remove();
		$(el).animate({
					left: position.left+"px",
					top: position.top+"px",
					width: el_img.width()+"px",
					height: el_img.height()+"px",
					opacity: ixbox_close_opacity
				},ixbox_close_speed,ixbox_close_easing,function() {
					if(this.parentNode)$(this).remove();
				});		
	}

	// Taken from Thickbox
	function ixbox_getPageSize(){
		var de = document.documentElement;
		var w = window.innerWidth || self.innerWidth || (de&&de.clientWidth) || document.body.clientWidth;
		var h = window.innerHeight || self.innerHeight || (de&&de.clientHeight) || document.body.clientHeight;
		arrayPageSize = [w,h];
		return arrayPageSize;
	}


	// Taken from Panic.com which took it from Quirksmode.org
	
	/**
	 * Retourne la taille de la fenetre
	 */
	function ixbox_getheight() {
		if (document.all) { return (document.documentElement.clientHeight) ? document.documentElement.clientHeight : document.body.clientHeight;	}
		else { return window.innerHeight; }
	}
	/**
	 * Retourne la position de la scrollbar verticale
	 */
	function ixbox_getscroll() {
		if (document.all) { return (document.documentElement.scrollTop) ? document.documentElement.scrollTop : document.body.scrollTop; }
		else { return window.pageYOffset; }
	}
		
})(jQuery);
