// masquage du contenu le temps de l'initialitation
var c = document.getElementById('container');
c.style.position = 'absolute';
c.style.left = (window.width | document.body.clientWidth) + 'px';

if( navigator.userAgent.match(/iPad/i) ) {
	document.body.className += ' ios';
}

jQuery(document).ready(function($)
{
	$.Site.css({
		'position': 'relative'
	});
	
	// attente du chargement de tous les éléments (images...)
	$.Window.load(function()
	{
		// initialisation
		$(this).initialize();
		
		var $container = $('#container');
		
		// affichage du contenu
		if( $.Site.hasClass('home') || $.Site.hasClass('campagne') || $.Site.hasClass('catalogue') || $.Site.hasClass('accessoires') )
		{
			$container.css({
				'top': $.Site.css('padding-top'),
				'left': $.Site.css('padding-left')
			});
		}
		else {
			$container.css({
				'position': 'relative',
				'top': 0,
				'left': 0
			});
		}
		
	});
	
	// affichage détail articles
	$('.article .details').hide();
	$('.article .show_details').click(function(evt){
		evt.preventDefault();
		var $btn = $(this);
		var $article = $btn.parents('.article');
		var $details = $article.find('.details');
		if( $btn.hasClass('hide') ) {
			$btn.removeClass('hide');
		}
		else {
			$btn.addClass('hide');
		}
		$details.slideToggle('fast', function(){
			if( $btn.stop(true, true).hasClass('hide') ) {
				$.scrollTo($details, 'normal');
			}
			else {
				$.scrollTo($article, 'normal');
			}
		});
	});
	
	
	// affichage detailTexte articles
	$('.article .detailsTexte').hide();
	$('.article .show_detailsTexte').click(function(evt){
		evt.preventDefault();
		$(this).parents('.article').find('.detailsTexte').toggle();
	});
	
	
	
	$.Window.resize(function(evt){
		$(this).resizeWindow();
	});
	
});


/* Utils */

(function($) {
	
	$.fn.realHeight = function()
	{
		$element = $(this);
		return $element.outerHeight(true) - parseInt($element.css('padding-top')) - parseInt($element.css('padding-bottom')) - parseInt($element.css('border-top-width')) - parseInt($element.css('border-bottom-width')) - parseInt($element.css('margin-top')) - parseInt($element.css('margin-bottom'));
	}
	
	$.fn.realWidth = function()
	{
		$element = $(this);
		return $element.outerWidth(true) - parseInt($element.css('padding-left')) - parseInt($element.css('padding-right')) - parseInt($element.css('border-left-width')) - parseInt($element.css('border-right-width')) - parseInt($element.css('margin-left')) - parseInt($element.css('margin-right'));
	}
	
	Array.prototype.max = function() {
		var max = this[0];
		var len = this.length;
		for (var i = 1; i < len; i++) if (this[i] > max) max = this[i];
		return max;
	}
	
	Array.prototype.min = function() {
		var min = this[0];
		var len = this.length;
		for (var i = 1; i < len; i++) if (this[i] < min) min = this[i];
		return min;
	}

})(jQuery);


/* Config */

(function($) {
	
	$.Body = $('body');
    
    $.Window = $(window);
	
	$.Site = $('#site');
	
	$.Sidebar = $('#sidebar');
	
	$.Events = {
		
		ACTIVE_CATEGORY: 'activeCategory',
		DESACTIVE_CATEGORY: 'desactiveCategory',
		WINDOW_RESIZE: 'windowResize',
		IMAGE_LOADED: 'imageLoaded'
		
	}
	
	$.Config = {
		home: {
			maxHeight: 800
		},
		catalogue: {
			maxHeight: 800
		}
	}
	
})(jQuery);


/* Resize All */

(function($) {
	
	var resizeTimer;
	
	$.fn.resizeWindow = function()
	{
		this.each(function(){
			
			var self = this;
			
			clearTimeout(resizeTimer);
			resizeTimer = setTimeout(function()
			{
				$.Body.triggerHandler($.Events.WINDOW_RESIZE, self);
			}, 
			100);
			
		});

		return this;
	}

})(jQuery);


/* Initialize */

(function($) {
	
	$.fn.initialize = function()
	{
		resize();
		$.Body.bind($.Events.WINDOW_RESIZE, function(){ resize() });
		
		// Home
		$('#menu').Menu();
		$('#images_home').NavigationConnexion('#menu');
		$('#images_home').resizeHomeContent('li img', 3, 2);
		
		// Campagne
		$('#campagne_slider').Slider({
			prevBtn: $('.navigation .prev'),
			nextBtn: $('.navigation .next')
		});
		
		$gallery = $('#gallery');
		
		// Catalogue
		$gallery.StepSlider({
			child_selector: 'a',
			rows: 2,
			columnsDisplay: 4,
			prevBtn: $('.navigation .prev'),
			nextBtn: $('.navigation .next')
		});
		
		// controle de l'état de chargement des images de la gallery
		$gallery.bind($.Events.IMAGE_LOADED, function(evt, image){
			images_loaded++;
			if( images_loaded >= nb_images ) {
				// Diaporama catalogue
				$gallery.gallery({
					imageMarginWidth: 0,
					imageMarginHeight: 200
				});
			}
		});
		
		// écoute du chargement des images du diaporama
		var $gallery_images = $gallery.find('img');
		var nb_images = $gallery_images.length;
		var images_loaded = 0;
		$gallery_images.each(function(){
			if( this.complete ) {
				$gallery.triggerHandler($.Events.IMAGE_LOADED, this);
			}
			else {
				this.onLoad = function() {
					$gallery.triggerHandler($.Events.IMAGE_LOADED, this);
				};
				this.onError = function() {
					$gallery.triggerHandler($.Events.IMAGE_LOADED, this);
				};
			}
		});
		
		function resize()
		{
			var $container = $('#container');
			
			// resize site
			if( $.Site.hasClass('home') || $.Site.hasClass('campagne') || $.Site.hasClass('catalogue') || $.Site.hasClass('accessoires') )
			{
				$.Site.height( $.Body.height() - parseInt($.Site.css('padding-top')) - parseInt($.Site.css('padding-bottom')) - parseInt($.Site.css('margin-top')) - parseInt($.Site.css('margin-bottom')) );
				
				$container.height( $.Site.realHeight() - ($container.outerHeight(true) - $container.realHeight()) );
			}

			// resize container
			$container.width( ($.Site.realWidth() - $.Sidebar.outerWidth()) - ($container.outerWidth(true) - $container.realWidth()) );
			
			// resize images height boutique
            
			$('.imageResize').css('height', 'auto');
                                                  
			var imageResizeHeight = $.Body.height() - parseInt($.Site.css('padding-top')) - parseInt($.Site.css('padding-bottom')) - parseInt($.Site.css('margin-top')) - parseInt($.Site.css('margin-bottom'));
			imageResizeHeight -= parseInt($container.css('padding-top')) + parseInt($container.css('padding-bottom')) + parseInt($container.css('margin-top')) + parseInt($container.css('margin-bottom'))
			$('.imageResize').css('max-height', imageResizeHeight );  
   

			// resize images width boutique
			var imageResizeWidth = $container.realWidth() - $("#stores .textes").outerWidth(true) - parseInt($('.imageResize').css('marginLeft')) - parseInt($('.imageResize').css('marginRight'));
			$('.imageResize').css('max-width', imageResizeWidth);       
            
			$('#sidebar').height($container.innerHeight());
		}
	}
	
})(jQuery);


/* Menu */

(function($) {
	
	$.fn.Menu = function() {
		
		this.each(function(){
			
			var $self = $(this)
				$submenus = $self.find('.submenu');
			
			$self.find('a').filter('.selected').next('ul').addClass('active');
			$self.find('a').filter('.selected').parents('ul').addClass('active').prev('a').addClass('selected');
			
			$submenus.not('.active').hide();
			
			$submenus.prev('a').click(
				function(evt){
					evt.preventDefault();
					var $item = $(this)
						$submenu = $item.next('ul');
					
					if( $submenu.hasClass('active') ) {
						$submenu.removeClass('active').stop(true, true).slideUp('100');
						$submenu.find('.submenu').removeClass('active').stop(true, true).slideUp('100');
					}
					else {
						$submenus.not($submenu.parents('.submenu')).stop(true, true).removeClass('active');
						$submenus.not('.active').slideUp('100');
						$submenu.addClass('active')
						$submenu.stop(true, true).slideDown('100');
					}					
				}
			);
			
		});
		
		return this;
	}
	
})(jQuery);


/* MainNav */

(function($) {
	
	$.fn.NavigationConnexion = function(nav) {
		
		var $nav = $(nav);
		
		$nav.find('a')
		.removeClass('active')
		.bind('mouseover', function(evt)
		{
			$.Body.triggerHandler($.Events.ACTIVE_CATEGORY, evt.currentTarget.rel);
		})
		.bind('mouseout', function(evt)
		{
			$.Body.triggerHandler($.Events.DESACTIVE_CATEGORY, evt.currentTarget.rel);
		});
		
		this.each(function(){
			
			var $self = $(this);
			
			$self.children()
			.removeClass('active')
			.bind('mouseenter', function(evt)
			{
				
				$.Body.triggerHandler($.Events.ACTIVE_CATEGORY, evt.currentTarget.id);
			})
			.bind('mouseleave', function(evt)
			{
				$.Body.triggerHandler($.Events.DESACTIVE_CATEGORY, evt.currentTarget.id);
			});
			
			$self.children().each(function(){
				var $category = $(this);
				$category.find('.overlay').css({
					'top': $(this).height()
				});
			});
			
		});
		
		$.Body
		.bind($.Events.ACTIVE_CATEGORY, function(evt, id) {
				$nav.find('a[rel="'+id+'"]').addClass('active');
				var category = $(document.getElementById(id));
				category.addClass('active');
				category.find('.overlay').stop(true).animate(
					{
						'top': 0
					},
					0 
				);
			}
		)
		.bind($.Events.DESACTIVE_CATEGORY, function(evt, id) {
				$nav.find('a[rel="'+id+'"]').removeClass('active');
				var $category = $(document.getElementById(id));
				$category.removeClass('active');
				$category.find('.overlay').stop(true).animate(
					{
						'top': $(this).height()
					},
					0 
				);
			}
		);
		
		return this;
	};
	
})(jQuery);


/* Menu */

(function($) {
	
	$.fn.resizeHomeContent = function(child_selector, columns, rows) {
		
		this.each(function(){
			
			var $self = $(this),
				$childs = $self.find(child_selector);
				
				var imagesMaxWidth = 0;
				var imagesMaxHeight = 0;
				
				// récupération de la largeur et hauteur maximum des images
				$childs.each(function(){
					
					var $child = $(this);
					
					var width = $child.width();
					var height = $child.height();
					
					if( width > imagesMaxWidth ) {
						imagesMaxWidth = width;
					}
					
					if( height > imagesMaxHeight ) {
						imagesMaxHeight = height;
					}
					
				});
			
			resize();
			
			$.Body.bind($.Events.WINDOW_RESIZE, function() {
				resize();
			});
			
			function resize()
			{
				// re-init
				$self.width('auto');
				$self.height('auto');
				
				// hauteur = hauteur visible
				$self.height($self.parent().realHeight());
				
				// max Height
				if( $self.height() > $.Config.home.maxHeight ) {
					$self.height($.Config.home.maxHeight);
				}
				
				// largeur et hauteur maximum du contenu
				var maxWidth = Math.floor($self.realWidth() / columns);
				var maxHeight = Math.floor($self.realHeight() / rows);
				
				// coeficient de réduction en hauteur (hauteur disponnible / hauteur image max)
				var coef = maxHeight / imagesMaxHeight;
				
				$childs.each(function(){
					
					var $child = $(this);
					var $container = $child.parent();
					
					// hauteur de l'image
					var height = this.naturalHeight || $child.attr('height');
					var width = this.naturalWidth || $child.attr('width');
					
					// hauteur réduite suivant le coeficient
					$child.width( Math.round(width * coef) );
					$child.height( Math.round(height * coef) );
					
					// si largeur encore trop grande on réduit l'image suivant la largeur maximum
					if($container.outerWidth(true) > maxWidth) {
						var imageWidth = maxWidth - ($container.outerWidth(true) - $container.realWidth());
						$child.height('auto');
						$child.width(imageWidth);
					}
					
					// repositionnement du masque de couleur en dehors du bloc
					$container.find('.overlay').css({
						'top': $child.outerHeight()
					});
				});
				
				// max élements par lignes (clear:left;)
				var nbChilds = $childs.length;
				for(var i = 0; i < nbChilds; i++) {
					$child = $($childs[i]);
					if( i % columns == 0 ) {
						$child.parent().css({
							'clear': 'left'
						});
					}
				}
				/*
				// calcule de la largeur de la ligne la plus longue
				var columnsTotalWidth = new Array();
				var currentColumn = 0;
				var nbChilds = $childs.length;
				for(var i = 0; i < nbChilds; i++) {
					$child = $($childs[i]);
					if( i > 0 && i % columns == 0 ) {
						currentColumn++;
						$child.parent().css({
							'clear': 'left'
						});
					}
					if( typeof(columnsTotalWidth[currentColumn]) != 'number' ) {
						columnsTotalWidth[currentColumn] = 0;
					}
					columnsTotalWidth[currentColumn] += $child.parent().outerWidth(true);
				}
				
				// largeur totale = largeur de la ligne la plus longue
				$self.width(columnsTotalWidth.max() + columns);
				*/
			}
			
		});
			
		return this;
	};

})(jQuery);


/* Slider */

(function($) {

	$.fn.Slider = function(settings) {

		this.each(function(){
			
			var $self = $(this),
				$container = $self.find('ul'),
				$items = $container.children('li'),
				nbItems = $items.length
				current = 0;
			
			$items.css({
				'float': 'left'
			});
			
			$self.css({
				'position': 'relative'
			});
			
			$container.css({
				'position': 'absolute'
			});
			
			resize();
			
			$.Body.bind($.Events.WINDOW_RESIZE, function(evt, id) {
				resize();
			});

			settings.prevBtn.click(function(evt){
				evt.preventDefault();
				gotoIndex(current - 1, 0);
			});

			settings.nextBtn.click(function(evt){
				evt.preventDefault();
				gotoIndex(current + 1, 0);
			});
			
			gotoIndex(current);
			
			function resize()
			{
				$parent = $self.parent();
				//$parent.height($.Site.realHeight());
				
				$self.height(0);
				$self.height($parent.height());
				$items.width($self.width());
				$items.height($self.height());
				$self.width($items.width());
				$container.width( $items.width() * nbItems );

				$items.each(function(){
					var $item = $(this);
					var $image = $item.find('img');
					if( $image[0].complete ) {
						resizeImage($image);
					}
					else {
						$image[0].onLoad = function() {
							resizeImage($image);
						}
						$image[0].error = function() {
							resizeImage($image);
						}
					}
				});
			}
			
			function resizeImage($image) {
				var $cartouche = $image.next('.cartouche');
				$image.width('auto');
				$image.height( $image.parent().height() - ($cartouche.outerHeight(true)) );
				$cartouche.width($image.width());
			}

			function gotoIndex(index, duration) {
				if(index < 0 || index >= nbItems ) return false;
				current = index;
				duration = duration || 0;
				$container.animate(
					{
						'left': $items.width() * index * -1
					}, 
					duration,
					'easeOutExpo'
				);
				
				if(index == 0) {
					settings.prevBtn.addClass('inactive');
				}
				else {
					settings.prevBtn.removeClass('inactive');
				}
				if(index == (nbItems - 1)) {
					settings.nextBtn.addClass('inactive');
				}
				else {
					settings.nextBtn.removeClass('inactive');
				}
				
				return true;
			}
			
		});

		return this;
	};

})(jQuery);


/* SnapSlider */

(function($) {
	
	$.fn.StepSlider = function(settings) {

		this.each(function(){
			
			var $self = $(this),
				$childs = settings.child_selector ? $self.find(settings.child_selector) : $self.children(),
				nbColumns = Math.ceil($childs.length / settings.rows),
				step = $childs.outerWidth(true),
				current = 0;
			
			// wrap all items
			if( $self.find('.content_slider').length == 0 ){
				$childs.wrapAll('<div class="content_slider" />');
			}
			$content = $self.find('.content_slider');
			
			$content.css({
				'overflow': 'hidden',
				'position': 'absolute',
				'left': '0px'
			});
			
			$childs.css({
				'display': 'block',
				'float': 'left'
			});
			
			resize();
			
			$.Body.bind($.Events.WINDOW_RESIZE, function(evt, id) {
				resize();
			});
			
			$self.css({
				'overflow': 'hidden',
				'position': 'relative'
			});
			
			gotoIndex(0);
			
			settings.prevBtn.click(function(evt){
				evt.preventDefault();
				gotoIndex(current - 1, 200);
			});

			settings.nextBtn.click(function(evt){
				evt.preventDefault();
				gotoIndex(current + 1, 200);
			});
			
			function resize()
			{
				// re-init
				$self.width('auto');
				
				var totalHeight = $self.parent().realHeight();
				
				// max Height
				if( totalHeight > $.Config.catalogue.maxHeight ) {
					totalHeight = $.Config.catalogue.maxHeight;
				}
				
				// resize images
				var imgMarginHeight = parseInt($childs.css('margin-top')) + parseInt($childs.css('margin-bottom'));
				var imgHeight = Math.floor( (totalHeight - $self.next('.cartouche').outerHeight(true)) / settings.rows - imgMarginHeight );
				$images = $childs.find('img').not('.zoom');
				$images.width('auto');
				$images.height(imgHeight);
				
				// image container size (overflow)
				$childs.width($images.width());
				
				settings.columnsDisplay = Math.floor($self.realWidth() / $childs.outerWidth(true));
				
				//$self.width( settings.columnsDisplay * $childs.outerWidth(true) - (parseInt($childs.css('margin-right')) / 2) );
				
				step = $childs.outerWidth(true);

				// container sizes
				$content.height( $childs.outerHeight(true) * settings.rows );
				$content.width( Math.ceil($childs.outerWidth(true) * nbColumns) );

				// gallery height
				$self.height( $content.height() );
		
				gotoIndex(current);
				
				// resize cartouche
				$self.next('.cartouche').width($self.realWidth());
			}
			
			function gotoIndex(index, duration) {
				var maxIndex = nbColumns - settings.columnsDisplay;
				if(index < 0 || index > maxIndex ) return false;
				current = index;
				duration = duration || 0;
				var left = step * index * -1;
				var maxLeft = ($content.realWidth() - $self.realWidth() - ($childs.outerWidth(true) - $childs.realWidth())) * -1;
				$content.animate(
					{
						'left': Math.max(left, maxLeft)
					}, 
					duration,
					'easeOutExpo'
				);
				
				if(index == 0) {
					settings.prevBtn.addClass('inactive');
				}
				else {
					settings.prevBtn.removeClass('inactive');
				}
				if(index == (nbColumns - settings.columnsDisplay)) {
					settings.nextBtn.addClass('inactive');
				}
				else {
					settings.nextBtn.removeClass('inactive');
				}
				
				return true;
			}
			
		});
		
		return this;
	};
	
})(jQuery);


/* Gallery */

(function($) {

    $.fn.gallery = function(method) {

        var methods = {

            init : function(options) {
                this.gallery.settings = $.extend({}, this.gallery.defaults, options);
                return this.each(function() {
					
                    var $element = $(this), // reference to the jQuery version of the current DOM element
						element = this, // reference to the actual DOM element
						settings = $element.gallery.settings;
                    
					// récupération des liens (images) de la galerie
					var $imagesLinks = $element.find('a');
					
					var images = new Array();
					
					// récupération des infos images du diapoarama
					$imagesLinks.each(function(){
						var img = {
							'url': this.href,
							'legend': $(this).find('img').attr('alt')
						}
						images.push(img);
					});
					
					settings.images = images;
					
					// création du diaporama
					var $diaporama = $('<div id="'+element.id+'-diaporama" class="gallery-diaporama" />');
					settings.diaporama = $diaporama;
					
					var $list = $('<ul />');
					$diaporama.append($list);
					
					// création des diapos
					var nbImages = images.length;
					for(var i = 0; i < nbImages; i++)
					{
						methods.addDiapo(images[i], i);
					}
					
					// redimensionnement de la galerie à la taille de la fenêtre
					methods.resizeGallery();
					
					$.Body.bind($.Events.WINDOW_RESIZE, function(evt, id) {
						methods.resizeGallery();
					});
					
					// navigation précédent/suivant
					$diaporama.find('.navigation a').click(function(evt){
						evt.preventDefault();
						if(this.rel) {
							methods.gotoIndex(this.rel, settings.animationDuration);
						}
					});
					
					// ajout du bouton de fermeture
					$close_btn = $('<a />');
					$close_btn.addClass('close_btn');
					$close_btn.text('fermer');
					$close_btn.attr('href', '#');
					$close_btn.click(function(evt){
						evt.preventDefault();
						$diaporama.fadeOut(settings.fadeOutDuration);
					});
					$diaporama.find('img').parent().append($close_btn);
					
					// ajout du diapoarama dans le DOM
					$(document.body).append($diaporama.hide());
					
					// affichage du diaporama au click sur un vignette de la gallerie
					$imagesLinks.click(function(evt){
						evt.preventDefault();
						$diaporama.fadeIn(settings.fadeInDuration);
						$target = $(this);
						$element.gallery.settings.index = $target.index();
						methods.gotoIndex(settings.index);
					});
                });

            },
			
			addDiapo: function(image, index) {
				// image
				var img = new Image;
				img.src = image.url;
				img.alt = image.legend;
				if(img.complete) {
					methods.resizeImage(img);
				}
				img.onLoad = function() {
					methods.resizeImage(this);
				}
				
				// legend
				var $header = $('<div class="header" />');
				$header.html(image.legend);
				
				// navigation
				var $nav = $('<span class="navigation" />');
				
				// bouton précédent
				$prev_btn = $('<a />');
				$prev_btn.addClass('prev');
				$prev_btn.html('&lt;');
				var prevImage = $(this).gallery.settings.images[index - 1];
				if( prevImage ) {
					$prev_btn.attr('title', prevImage.legend);
					$prev_btn.attr('href', prevImage.url);
					$prev_btn.attr('rel', index - 1);
				}
				else {
					$prev_btn.addClass('inactive');
					$prev_btn.attr('href', '#');
				}
				$nav.append($prev_btn);
				
				// bouton suivant
				$next_btn = $('<a />');
				$next_btn.addClass('next');
				$next_btn.html('&gt;');
				var nextImage = $(this).gallery.settings.images[index + 1];
				if( nextImage ) {
					$next_btn.attr('title', nextImage.legend);
					$next_btn.attr('href', nextImage.url);
					$next_btn.attr('rel', index + 1);
				}
				else {
					$next_btn.addClass('inactive');
					$next_btn.attr('href', '#');
				}
				$nav.append($next_btn);
				
				// cartouche
				var $cartouche = $('<div class="cartouche" />');
				$cartouche.append($header);
				$cartouche.append($nav);
				
				// container
				var $content = $('<div class="container" />');
				$content.append(img);
				$content.append($cartouche);
				
				// diapo
				var $diapo = $('<li />');
				$diapo.append($content);
				
				$list = $(this).gallery.settings.diaporama.find('ul');
				$list.append($diapo);
			},
			
            // resize image in view
			resizeImage: function(image) {
				var self = this;
				var width = image.naturalWidth || image.width, 
					height = image.naturalHeight || image.height;
				// image non chargée -> on attend
				if( width == 0 || height == 0 ) {
					setTimeout(function(){ self.resizeImage(image) }, 10);
					return;
				}
				var ratio = width / height;
				var maxWidth = (window.innerWidth | document.body.clientWidth) - $(this).gallery.settings.imageMarginWidth;
				var maxHeight =  (window.innerHeight | document.body.clientHeight) - $(this).gallery.settings.imageMarginHeight;
				if( (maxWidth / ratio) > maxHeight ) {
					image.width = Math.round(maxHeight * ratio);
					image.height = Math.round(maxHeight);
				}
				else {
					image.width = Math.round(maxWidth);
					image.height = Math.round(maxWidth / ratio);
				}
				$(image).parent().width(image.width);
			},
			
			// resize all
			resizeGallery: function() {
				var $element = $(this);
				var $diaporama = $element.gallery.settings.diaporama;
				var $list = $diaporama.find('ul');
				var $diapo = $list.find('li');
				$diaporama.width(window.innerWidth | document.body.clientWidth);
				$diaporama.height(window.innerHeight | document.body.clientHeight);
				$list.width($element.gallery.settings.images.length * $diaporama.width());
				$list.height($diaporama.height());
				$diapo.width($diaporama.width());
				$diapo.height($diaporama.height());
				$diapo.find('img').each(function(){
					$element[0].resizeImage(this);
				});
				$element[0].gotoIndex($element.gallery.settings.index);
			},
			
			gotoIndex: function(index, duration) {
				var $element = $(this);
				if(index < 0 || index >= $element.gallery.settings.images.length ) return false;
				$element.gallery.settings.index = index;
				var $diaporama = $element.gallery.settings.diaporama;
				var $list = $diaporama.find('ul');
				duration = duration || 0;
				$list.stop().animate(
					{
						'left': (window.innerWidth | document.body.clientWidth) * index * -1
					}, 
					duration,
					$element.gallery.settings.easing
				);
				return true;
			}

        }
		
		// a private method.
        var helpers = {
            
        }

        if (methods[method]) {
            return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
        } else if (typeof method === 'object' || !method) {
            return methods.init.apply(this, arguments);
        } else {
            $.error( 'Method "' +  method + '" does not exist in pluginName plugin!');
        }

    }

    $.fn.gallery.defaults = {
		imageMarginWidth: 10,
		imageMarginHeight:10,
		index: 0,
		fadeInDuration: 500,
		fadeOutDuration: 500,
		animationDuration: 500,
		easing: 'easeOutExpo'
    }

    $.fn.gallery.settings = {}

})(jQuery);


/**
 * jQuery.ScrollTo
 * Copyright (c) 2007-2009 Ariel Flesler - aflesler(at)gmail(dot)com | http://flesler.blogspot.com
 * Dual licensed under MIT and GPL.
 * Date: 5/25/2009
 *
 * @projectDescription Easy element scrolling using jQuery.
 * http://flesler.blogspot.com/2007/10/jqueryscrollto.html
 * Works with jQuery +1.2.6. Tested on FF 2/3, IE 6/7/8, Opera 9.5/6, Safari 3, Chrome 1 on WinXP.
 *
 * @author Ariel Flesler
 * @version 1.4.2
 *
 * @id jQuery.scrollTo
 * @id jQuery.fn.scrollTo
 * @param {String, Number, DOMElement, jQuery, Object} target Where to scroll the matched elements.
 *	  The different options for target are:
 *		- A number position (will be applied to all axes).
 *		- A string position ('44', '100px', '+=90', etc ) will be applied to all axes
 *		- A jQuery/DOM element ( logically, child of the element to scroll )
 *		- A string selector, that will be relative to the element to scroll ( 'li:eq(2)', etc )
 *		- A hash { top:x, left:y }, x and y can be any kind of number/string like above.
*		- A percentage of the container's dimension/s, for example: 50% to go to the middle.
 *		- The string 'max' for go-to-end. 
 * @param {Number} duration The OVERALL length of the animation, this argument can be the settings object instead.
 * @param {Object,Function} settings Optional set of settings or the onAfter callback.
 *	 @option {String} axis Which axis must be scrolled, use 'x', 'y', 'xy' or 'yx'.
 *	 @option {Number} duration The OVERALL length of the animation.
 *	 @option {String} easing The easing method for the animation.
 *	 @option {Boolean} margin If true, the margin of the target element will be deducted from the final position.
 *	 @option {Object, Number} offset Add/deduct from the end position. One number for both axes or { top:x, left:y }.
 *	 @option {Object, Number} over Add/deduct the height/width multiplied by 'over', can be { top:x, left:y } when using both axes.
 *	 @option {Boolean} queue If true, and both axis are given, the 2nd axis will only be animated after the first one ends.
 *	 @option {Function} onAfter Function to be called after the scrolling ends. 
 *	 @option {Function} onAfterFirst If queuing is activated, this function will be called after the first scrolling ends.
 * @return {jQuery} Returns the same jQuery object, for chaining.
 *
 * @desc Scroll to a fixed position
 * @example $('div').scrollTo( 340 );
 *
 * @desc Scroll relatively to the actual position
 * @example $('div').scrollTo( '+=340px', { axis:'y' } );
 *
 * @dec Scroll using a selector (relative to the scrolled element)
 * @example $('div').scrollTo( 'p.paragraph:eq(2)', 500, { easing:'swing', queue:true, axis:'xy' } );
 *
 * @ Scroll to a DOM element (same for jQuery object)
 * @example var second_child = document.getElementById('container').firstChild.nextSibling;
 *			$('#container').scrollTo( second_child, { duration:500, axis:'x', onAfter:function(){
 *				alert('scrolled!!');																   
 *			}});
 *
 * @desc Scroll on both axes, to different values
 * @example $('div').scrollTo( { top: 300, left:'+=200' }, { axis:'xy', offset:-20 } );
 */
;(function( $ ){
	
	var $scrollTo = $.scrollTo = function( target, duration, settings ){
		$(window).scrollTo( target, duration, settings );
	};

	$scrollTo.defaults = {
		axis:'xy',
		duration: parseFloat($.fn.jquery) >= 1.3 ? 0 : 1
	};

	// Returns the element that needs to be animated to scroll the window.
	// Kept for backwards compatibility (specially for localScroll & serialScroll)
	$scrollTo.window = function( scope ){
		return $(window)._scrollable();
	};

	// Hack, hack, hack :)
	// Returns the real elements to scroll (supports window/iframes, documents and regular nodes)
	$.fn._scrollable = function(){
		return this.map(function(){
			var elem = this,
				isWin = !elem.nodeName || $.inArray( elem.nodeName.toLowerCase(), ['iframe','#document','html','body'] ) != -1;

				if( !isWin )
					return elem;

			var doc = (elem.contentWindow || elem).document || elem.ownerDocument || elem;
			
			return $.browser.safari || doc.compatMode == 'BackCompat' ?
				doc.body : 
				doc.documentElement;
		});
	};

	$.fn.scrollTo = function( target, duration, settings ){
		if( typeof duration == 'object' ){
			settings = duration;
			duration = 0;
		}
		if( typeof settings == 'function' )
			settings = { onAfter:settings };
			
		if( target == 'max' )
			target = 9e9;
			
		settings = $.extend( {}, $scrollTo.defaults, settings );
		// Speed is still recognized for backwards compatibility
		duration = duration || settings.speed || settings.duration;
		// Make sure the settings are given right
		settings.queue = settings.queue && settings.axis.length > 1;
		
		if( settings.queue )
			// Let's keep the overall duration
			duration /= 2;
		settings.offset = both( settings.offset );
		settings.over = both( settings.over );

		return this._scrollable().each(function(){
			var elem = this,
				$elem = $(elem),
				targ = target, toff, attr = {},
				win = $elem.is('html,body');

			switch( typeof targ ){
				// A number will pass the regex
				case 'number':
				case 'string':
					if( /^([+-]=)?\d+(\.\d+)?(px|%)?$/.test(targ) ){
						targ = both( targ );
						// We are done
						break;
					}
					// Relative selector, no break!
					targ = $(targ,this);
				case 'object':
					// DOMElement / jQuery
					if( targ.is || targ.style )
						// Get the real position of the target 
						toff = (targ = $(targ)).offset();
			}
			$.each( settings.axis.split(''), function( i, axis ){
				var Pos	= axis == 'x' ? 'Left' : 'Top',
					pos = Pos.toLowerCase(),
					key = 'scroll' + Pos,
					old = elem[key],
					max = $scrollTo.max(elem, axis);

				if( toff ){// jQuery / DOMElement
					attr[key] = toff[pos] + ( win ? 0 : old - $elem.offset()[pos] );

					// If it's a dom element, reduce the margin
					if( settings.margin ){
						attr[key] -= parseInt(targ.css('margin'+Pos)) || 0;
						attr[key] -= parseInt(targ.css('border'+Pos+'Width')) || 0;
					}
					
					attr[key] += settings.offset[pos] || 0;
					
					if( settings.over[pos] )
						// Scroll to a fraction of its width/height
						attr[key] += targ[axis=='x'?'width':'height']() * settings.over[pos];
				}else{ 
					var val = targ[pos];
					// Handle percentage values
					attr[key] = val.slice && val.slice(-1) == '%' ? 
						parseFloat(val) / 100 * max
						: val;
				}

				// Number or 'number'
				if( /^\d+$/.test(attr[key]) )
					// Check the limits
					attr[key] = attr[key] <= 0 ? 0 : Math.min( attr[key], max );

				// Queueing axes
				if( !i && settings.queue ){
					// Don't waste time animating, if there's no need.
					if( old != attr[key] )
						// Intermediate animation
						animate( settings.onAfterFirst );
					// Don't animate this axis again in the next iteration.
					delete attr[key];
				}
			});

			animate( settings.onAfter );			

			function animate( callback ){
				$elem.animate( attr, duration, settings.easing, callback && function(){
					callback.call(this, target, settings);
				});
			};

		}).end();
	};
	
	// Max scrolling position, works on quirks mode
	// It only fails (not too badly) on IE, quirks mode.
	$scrollTo.max = function( elem, axis ){
		var Dim = axis == 'x' ? 'Width' : 'Height',
			scroll = 'scroll'+Dim;
		
		if( !$(elem).is('html,body') )
			return elem[scroll] - $(elem)[Dim.toLowerCase()]();
		
		var size = 'client' + Dim,
			html = elem.ownerDocument.documentElement,
			body = elem.ownerDocument.body;

		return Math.max( html[scroll], body[scroll] ) 
			 - Math.min( html[size]  , body[size]   );
			
	};

	function both( val ){
		return typeof val == 'object' ? val : { top:val, left:val };
	};

})( jQuery );
