/*!
	Slimbox v2.02 - The ultimate lightweight Lightbox clone for jQuery
	(c) 2007-2009 Christophe Beyls <http://www.digitalia.be>
	MIT-style license.
	
	
*/

// Ne pas utiliser l'alias jQuery déjà utilisé par mootools.
// Prière donc de lancer la fonction jQuery directement
jQuery.noConflict();
(function(jQuery) {

	// Global variables, accessible to Slimbox only
	var win = jQuery(window), options, images, activeImage = -1, activeURL, prevImage, nextImage, compatibleOverlay, middle, centerWidth, centerHeight, ie6 = !window.XMLHttpRequest,
		operaFix = window.opera && (document.compatMode == "CSS1Compat") && (jQuery.browser.version >= 9.3), documentElement = document.documentElement,

	// Preload images
	preload = {}, preloadPrev = new Image(), preloadNext = new Image(),

	// DOM elements
	overlay, center, image, sizer, prevLink, nextLink, bottomContainer, bottom, caption, number;

	/*
		Initialization
	*/

	jQuery(function() {
		// Append the Slimbox HTML code at the bottom of the document
		jQuery("body").append(
			jQuery([
				overlay = jQuery('<div id="lbOverlay" />')[0],
				center = jQuery('<div id="lbCenter" />')[0],
				bottomContainer = jQuery('<div id="lbBottomContainer" />')[0]
			]).css("display", "none")
		);

		image = jQuery('<div id="lbImage" />').appendTo(center).append(
			sizer = jQuery('<div style="position: relative;" />').append([jQuery('<a id="lbCloseLink" href="#" />').add(overlay).click(close)[0],
				prevLink = jQuery('<a id="lbPrevLink" href="#" />').click(previous)[0],
				nextLink = jQuery('<a id="lbNextLink" href="#" />').click(next)[0]
			])[0]
		)[0];

		bottom = jQuery('<div id="lbBottom" />').appendTo(bottomContainer).append([
			
			caption = jQuery('<div id="lbCaption" />')[0],
			number = jQuery('<div id="lbNumber" />')[0],
			vignette = jQuery('<div id="lbVignette" />')[0],
			jQuery('<div style="clear: both;" />')[0]
		])[0];
	});


	/*
		API
	*/

	// Open Slimbox with the specified parameters
	jQuery.slimbox = function(_images, startImage, _options) {
		options = jQuery.extend({
			loop: true,				// Allows to navigate between first and last images
			overlayOpacity: 0.8,			// 1 is opaque, 0 is completely transparent (change the color in the CSS file)
			overlayFadeDuration: 400,		// Duration of the overlay fade-in and fade-out animations (in milliseconds)
			resizeDuration: 400,			// Duration of each of the box resize animations (in milliseconds)
			resizeEasing: "swing",			// "swing" is jQuery's default easing
			initialWidth: 250,			// Initial width of the box (in pixels)
			initialHeight: 250,			// Initial height of the box (in pixels)
			imageFadeDuration: 400,			// Duration of the image fade-in animation (in milliseconds)
			captionAnimationDuration: 400,		// Duration of the caption animation (in milliseconds)
			counterText: "Image {x} sur {y}",	// Translate or change as you wish, or set it to false to disable counter text for image groups
			closeKeys: [27, 88, 67],		// Array of keycodes to close Slimbox, default: Esc (27), 'x' (88), 'c' (67)
			previousKeys: [37],			// Array of keycodes to navigate to the previous image, default: Left arrow (37)
			nextKeys: [39]			// Array of keycodes to navigate to the next image, default: Right arrow (39)
		}, _options);

		// The function is called for a single image, with URL and Title as first two arguments
		if (typeof _images == "string") {
			_images = [[_images, startImage]];
			startImage = 0;
		}

		middle = win.scrollTop() + ((operaFix ? documentElement.clientHeight : win.height()) / 2);
		centerWidth = options.initialWidth;
		centerHeight = options.initialHeight;
		jQuery(center).css({top: Math.max(0, middle - (centerHeight / 2)), width: centerWidth, height: centerHeight, marginLeft: -centerWidth/2}).show();
		compatibleOverlay = ie6 || (overlay.currentStyle && (overlay.currentStyle.position != "fixed"));
		if (compatibleOverlay) overlay.style.position = "absolute";
		jQuery(overlay).css("opacity", options.overlayOpacity).fadeIn(options.overlayFadeDuration);
		position();
		setup(1);

		images = _images;
		
		listeVignette = new Array();
		listeZoom = new Array();
		addVignette();
		//console.log( listeVignette );
		//console.log( listeZoom );
		options.loop = options.loop && (images.length > 1);
		
		return changeImage(startImage);
	};
	
	function addVignette() {
		
		jQuery(document).scrollTop(0);
		
		var compteur = 1;
		jQuery(vignette).html("");
		jQuery(".zoom_produit a").each(
			function(){
				
						listeZoom[compteur] = jQuery(this).attr("href");
						listeVignette[compteur] = jQuery(this).find('img').attr("src");
									
						refArticle = listeVignette[compteur].split('/')[3];
						//console.log(refArticle);
						if (compteur == 1) {
							refArticleLength = refArticle.indexOf('_pdt_1.jpg'); 
						}
						refArticle = refArticle.substring(0,refArticleLength );
						//console.log(refArticleLength);
						//console.log(refArticle);

						jQuery(vignette).append("<img src='/images/produits/"+refArticle+"_vign_pdt_"+compteur+".jpg' alt='' class='"+(parseInt(compteur)-1)+"' />");
						jQuery(vignette).find('img:last').click(function(){
							changeImage(parseInt(jQuery(this).attr('class') ));		
						});
						jQuery(vignette).find('img:first').css('borderColor','#999');
						compteur++;
		});

	}

	jQuery.fn.slimbox = function(_options, linkMapper, linksFilter) {
		linkMapper = linkMapper || function(el) {
			return [el.href, el.title];
		};

		linksFilter = linksFilter || function() {
			return true;
		};

		var links = this;

		return links.unbind("click").click(function() {
			// Build the list of images that will be displayed
			var link = this, startIndex = 0, filteredLinks, i = 0, length;
			filteredLinks = jQuery.grep(links, function(el, i) {
				return linksFilter.call(link, el, i);
			});

			// We cannot use jQuery.map() because it flattens the returned array
			for (length = filteredLinks.length; i < length; ++i) {
				if (filteredLinks[i] == link) startIndex = i;
				filteredLinks[i] = linkMapper(filteredLinks[i], i);
			}

			return jQuery.slimbox(filteredLinks, startIndex, _options);
		});
	};


	/*
		Internal functions
	*/

	function position() {
		var l = win.scrollLeft(), w = operaFix ? documentElement.clientWidth : win.width();
		jQuery([center, bottomContainer]).css("left", l + (w / 2));
		if (compatibleOverlay) jQuery(overlay).css({left: l, top: win.scrollTop(), width: w, height: win.height()});
	}

	function setup(open) {
		jQuery("object").add(ie6 ? "select" : "embed").each(function(index, el) {
			if (open) jQuery.data(el, "slimbox", el.style.visibility);
			el.style.visibility = open ? "hidden" : jQuery.data(el, "slimbox");
		});
		var fn = open ? "bind" : "unbind";
		win[fn]("scroll resize", position);
		jQuery(document)[fn]("keydown", keyDown);
	}

	function keyDown(event) {
		var code = event.keyCode, fn = jQuery.inArray;
		// Prevent default keyboard action (like navigating inside the page)
		return (fn(code, options.closeKeys) >= 0) ? close()
			: (fn(code, options.nextKeys) >= 0) ? next()
			: (fn(code, options.previousKeys) >= 0) ? previous()
			: false;
	}

	function previous() {
		return changeImage(prevImage);
	}

	function next() {
		return changeImage(nextImage);
	}

	function changeImage(imageIndex) {
		if (imageIndex >= 0) {
			activeImage = imageIndex;
			
			jQuery(vignette).find('img').css('borderColor','#ccc');
			jQuery(vignette).find('img.'+activeImage).css('borderColor','#999');
			
			
			activeURL = images[activeImage][0];
			prevImage = (activeImage || (options.loop ? images.length : 0)) - 1;
			nextImage = ((activeImage + 1) % images.length) || (options.loop ? 0 : -1);

			stop();
			center.className = "lbLoading";

			preload = new Image();
			preload.onload = animateBox;
			preload.src = activeURL;
		}

		return false;
	}

	function animateBox() {

		center.className = "";
		jQuery(image).css({backgroundImage: "url(" + activeURL + ")", visibility: "hidden", display: ""});
		jQuery(sizer).width(preload.width);
		jQuery([sizer, prevLink, nextLink]).height(preload.height);
		jQuery(center).css("borderWidth","1px");
		
		jQuery(caption).html(images[activeImage][1] || "");
		jQuery(number).html((((images.length > 1) && options.counterText) || "").replace(/{x}/, activeImage + 1).replace(/{y}/, images.length));

		if (prevImage >= 0) preloadPrev.src = images[prevImage][0];
		if (nextImage >= 0) preloadNext.src = images[nextImage][0];

		centerWidth = image.offsetWidth;
		centerHeight = image.offsetHeight;
		//var top = Math.max(25, middle +25 - (centerHeight / 2));
		var top = 30;
		if (center.offsetHeight != centerHeight) {
			jQuery(center).animate({height: centerHeight, top: top}, options.resizeDuration, options.resizeEasing);
		}
		if (center.offsetWidth != centerWidth) {
			jQuery(center).animate({width: centerWidth, marginLeft: -centerWidth/2}, options.resizeDuration, options.resizeEasing);
		}
		jQuery(center).queue(function() {
			jQuery(bottomContainer).css({width: centerWidth, top: top + centerHeight, marginLeft: -centerWidth/2, visibility: "hidden", display: ""});
			jQuery(image).css({display: "none", visibility: "", opacity: ""}).fadeIn(options.imageFadeDuration, animateCaption);
		});
	}

	function animateCaption() {
		if (prevImage >= 0) jQuery(prevLink).show();
		if (nextImage >= 0) jQuery(nextLink).show();
		jQuery(bottom).css("marginTop", -bottom.offsetHeight).animate({marginTop: 0}, options.captionAnimationDuration);
		jQuery(center).css("borderWidth","1px 1px 0");
		bottomContainer.style.visibility = "";
	}

	function stop() {
		preload.onload = null;
		preload.src = preloadPrev.src = preloadNext.src = activeURL;
		jQuery([center, image, bottom]).stop(true);
		jQuery([prevLink, nextLink, image, bottomContainer]).hide();
	}

	function close() {
		if (activeImage >= 0) {
			stop();
			activeImage = prevImage = nextImage = -1;
			jQuery(center).hide();
			jQuery(overlay).stop().fadeOut(options.overlayFadeDuration, setup);
		}

		return false;
	}

})(jQuery);

jQuery(function($) {
	$("a[rel^='lightbox']").slimbox({/* Put custom options here */}, null, function(el) {
		return (this == el) || ((this.rel.length > 8) && (this.rel == el.rel));
	});
});