
// remap jQuery to $
(function($){


})(window.jQuery);




(function($){

	// Reglages par defaut
	var defaults = {
				conteneurWidth : 740, conteneurHeight:270,
				width: 740, height: 225,  itemWidth : 325, itemHeight : 225, ratio : 0.8, marge : 37, border : '0', ombre : false, radius : 0,
		        nextParam : {'background-image' : 'url(img/next.png)', 'width' : '20px', 'height': '80px', 'cursor':'pointer'},
		        prevParam : {'background-image' : 'url(img/prev.png)', 'width' : '20px', 'height':'80px', 'cursor':'pointer'},
		        defilAuto : true,
		        bgSpan : 'url(img/bgB80.png) repeat',
		        ombreInterne : 'url(img/ombre.png) repeat-y',
		        index : 3
	};
		
	//Recuperation / initialisation des variables globales
 	var o; // Reglages du plugin
    var wStage // Largeur de la scene
    var hStage //  Hauteur de la scene
    var obj  // Stocke l'élément auquel est assigné le plugin dans une variable
    var clicable = true;
    var sens = '+';
    var dim = []; // Dimensions des éléments
    var indice = 0;
    var pause = false;
    var ombres = [];

	// Initialisation des méthodes du plugin
	var methods = {
		/**
		 * Initialisation du carrousel
		 */		
	     init : function(options) {
			
			// Recuperation des options
			o = $.extend(defaults, options);
					
			//Recuperation / initialisation des variables d'environnement
	    	wStage = $(document).width(); // Largeur de la scene
	     	hStage = $(document).height(); //  Hauteur de la scene
	    	obj = $(this); // Stocke l'élément auquel est assigné le plugin dans une variable
	    	
		    return this.each(function(){
		    	var x = 0; 	var w = 0; 	var h = 0; 	var t = 0; 	var z = 0;
		    	var initX = o.width / 2 - o.itemWidth / 2;
		    	// Mise en place des blocs à leur position initiale : cote à cote
		 		obj.children('li').each(function(i, v){
		    		if (i == o.index - 1) {
		    			x = 0;
		    			dim.push({cssObj : {'width' :o.itemWidth + 'px', 'height' : o.itemHeight + 'px', 'left' : initX + 'px', 'top' : 0 + 'px'}, zIndex : obj.children('li').length, assClass:'currentItem'});
		    		} else if (i < o.index - 1 ) {
		    			x = (o.index == 2) ?  0 : parseInt(Math.abs(initX - parseInt(o.itemWidth * Math.pow(o.ratio, o.index - 1 - i))));
			   			w = parseInt(o.itemWidth * Math.pow(o.ratio, o.index - 1 - i));
		    			h = parseInt(o.itemHeight * Math.pow(o.ratio, o.index - 1 - i));
		    			t = o.height / 2 - h /2;
		    			z = o.index - 1 + i;
			   			dim.push({cssObj : {'width' : w + 'px', 'height' : h + 'px', 'left' : x + 'px', 'top': t + 'px'}, zIndex:z, assClass:'prevItem'});
			   			$(this).addClass('prevItem');
		    		} else {
		    			switch (o.index) {
		    				case 2:
		    				//x = ((o.width - 40) / 2) + ((o.width - 40) / 2 - parseInt(dim[0].cssObj.left) - parseInt(dim[0].cssObj.width));
			    			//x = o.width - parseInt(dim[0].cssObj.width);
			    			x = o.width - parseInt(dim[0].cssObj.width) - parseInt(dim[0].cssObj.left);
				   			dim.push({cssObj : {'width' : dim[0].cssObj.width, 'height' : dim[0].cssObj.height, 'left' : x + 'px', 'top': dim[0].cssObj.top}, zIndex:dim[0].zIndex, assClass:'nextItem'});
		    				break;
		    				default:
		    				x = o.width - parseInt(dim[i - (o.index - 1) * (i - (o.index - 1))].cssObj.width) - parseInt(dim[i - (o.index - 1) * (i - (o.index - 1))].cssObj.left);
		    				//x = ((o.width - 40) / 2) + ((o.width - 40) / 2 - parseInt(dim[i - (o.index - 1) * (i - (o.index - 1))].cssObj.left) - parseInt(dim[i - (o.index - 1) * (i - (o.index - 1))].cssObj.width));
		    				w = dim[i - (o.index - 1) * (i - (o.index - 1))].cssObj.width;
		    				h = dim[i - (o.index - 1) * (i - (o.index - 1))].cssObj.height;
		    				t = dim[i - (o.index - 1) * (i - (o.index - 1))].cssObj.top;
			   				z = dim[i - (o.index - 1) * (i - (o.index - 1))].zIndex;
			   				dim.push({cssObj : {'width' : w, 'height' : h, 'left' : x + 'px', 'top': t}, zIndex:z, assClass:'nextItem'});
		    				break;
		    			}
			   			
			   			$(this).addClass('nextItem');
		    		};
		    	});
				if ( o.ombre ) { obj.carrousel('addOmbre') };
				obj.carrousel('setStyle'); // Mise en forme
				obj.carrousel('setGui'); // Ajout des boutons de controle
				obj.carrousel('setEvents'); // Ecouteurs d'evenements
				if (o.defilAuto == true) {obj.carrousel('defilAuto');}
		    
		    });
	
	     },
	     /**
		 * Destruction du carrousel
		 */	
	     destroy : function( ) {
	
	       return this.each(function(){
	         $(window).unbind('.carrousel');
	       })
	
	     },
		 /**
		 * Mise en pause // Reprise
		 */
		 setPause : function(arg) {
			pause = arg;
			obj.carrousel('defilAuto');
		},
	     /**
		 * Mise en forme par defaut
		 */	
	     setStyle : function() {
	     	var x = 0 + parseInt(o.prevParam.width); var l; var cssObj;
	    	obj.children('li').each(function(i, v){
	    		cssObj = {'display' : 'block', 'position' : 'absolute', 'margin' : 0, 'padding' : 0, 'zIndex' : dim[i].zIndex};
	    		$(this).css(cssObj).css(dim[i].cssObj);
	    		$(this).addClass(dim[i].assClass);
	    	});
	    	l = parseInt(dim[dim.length-1].cssObj.left) + parseInt(dim[dim.length-1].cssObj.width) - parseInt(o.nextParam.width);
			obj.css({position:'absolute', left: o.prevParam.width, width:o.width+'px', height:o.height+'px', margin:'0', padding:'0'});
	     	obj.children('li').children('a').css({'background':'url("blank.gif")', 'position' :'absolute', 'left': '0', 'top': '0', 'display' :'block', 'width':'100%', 'height':'100%', 'text-decoration':'none', 'zoom':'1'});
	     	obj.children('li').children('a').children('span').css({'position' :'absolute', 'left': '0', 'bottom': '0', 'width': (o.itemWidth - 10) + 'px', background : o.bgSpan, 'color':'white', 'display':'none', 'padding':'5px', 'zoom':'1'});
	     },
	    /**
		 * Ajout des ombres
		 */	
	     addOmbre : function() {
	     	var w; var l;
	     	$('.ombre').remove();
		     obj.children('li.nextItem').each(function(i, v){	
					$(this).append('<span class="ombre"></span>');
					w = '50px';
					l = parseInt(dim[o.index-1-i-1].cssObj.left) + parseInt(dim[o.index-1-i-1].cssObj.width) - parseInt(dim[o.index-1-i].cssObj.left);
					ombres.push({display:'block', position:'absolute', top:0, left: l + 'px', zIndex:2, width:w, height:'100%', background:o.ombreInterne});
					$(this).children('.ombre').css({display:'block', position:'absolute', top:0, left: l + 'px', zIndex:2, width:w, height:'100%', background:o.ombreInterne});
					
			});
     	 },
	     /**
		 * Ajout des boutons
		 */		     
	     setGui : function() { 
	     	obj.wrap('<div id="carContainer"></div>');
			$('#carContainer').css({display: 'block', width: o.conteneurWidth +'px', height: o.conteneurHeight +'px', border:o.border, position:'relative', top: o.marge + 'px'});
			$('#carContainer').append('<span id="carNext"></span>').prepend('<span id="carPrev"></span>');
			$('#carNext').css(o.nextParam).css({display : 'block', position : 'absolute', zIndex:'100', right : '0px', top : o.height / 2 - parseInt(o.nextParam.height) / 2 + 'px'});
			$('#carPrev').css(o.prevParam).css({display : 'block', position : 'absolute', zIndex:'100', left : '0px', top : o.height / 2 - parseInt(o.prevParam.height) / 2 + 'px'});
			$('#carPrev').click(function(){ if (clicable == true) { pause = true; sens = '-'; indice--; obj.carrousel('defil');}}); // Lance le defilement des éléments
			$('#carNext').click(function(){ if (clicable == true) { pause = true; sens = '+'; indice++; obj.carrousel('defil');}}); // Lance le defilement des éléments
	     },
	     setEvents : function(i) {
	     	obj.children('li.currentItem').unbind();
	     	if (i < 0) { i = dim.length - 1};
	     	obj.children('li.currentItem').hover(
				  function () {
				    pause = true;
				    $(this).children('a').children('span').fadeIn();
				  }, 
				  function () {
				   $(this).children('a').children('span').fadeOut(function(){pause = false});
				  }
				);

	     },
	     /**
	      * Defilement des items
	      */
	     defil : function() {
	     	clicable = false; // Desactive les clics tant que l'animation n'est pas terminée
	     	obj.children('li').unbind(); // Desactive le survol
    		// Réordonne le tableau de dimensions en fonction du sens de rotation
	    	var temp = [];
	    	switch (sens) {
	    		case '+' :
	    		for (var i = 0; i < dim.length; i++) {if (i == dim.length - 1){	temp.push(dim[0]);} else {temp.push(dim[i+1]);}}
	    		break;
	    		case '-' :
	    		for (var i = 0; i < dim.length; i++) {if (i == 0){	temp.push(dim[dim.length-1]);} else {temp.push(dim[i-1]);}}
	    		break;
	    	};
    		dim = temp; // Enregistre le nouvel ordre
			
			
			if (indice == -1) {indice = dim.length - 1} 
    		// Deplacement du dernier / premier element en fonction du sens de clic
			if (sens == '+') {
		    	obj.children('li:not(.temp):eq('+ (dim.length - indice) +')').clone().addClass('temp').css('zIndex', 0).appendTo(obj).fadeOut(600, function(){	obj.children('li.temp').remove(); });
		    	obj.children('li:not(.temp):eq('+(dim.length - indice)+')').css('display', 'none');
		    	obj.children('li:not(.temp):eq('+(dim.length - indice)+')').css(dim[dim.length - indice].cssObj).fadeIn(600);
	    	} else {
	    		obj.children('li:not(.temp):eq('+(dim.length - 1 - indice)+')').clone().addClass('temp').css('zIndex', 10).prependTo(obj).fadeOut(600, function(){ obj.children('li.temp').remove(); });
	    	    obj.children('li:not(.temp):eq('+(dim.length - 1 - indice)+')').css('display', 'none');
	    	    obj.children('li:not(.temp):eq('+(dim.length - 1 - indice)+')').css(dim[(dim.length - 1 - indice)].cssObj).fadeIn(600);
	    	}
	    	if (indice == dim.length) { indice = 0} 
	 		
	 		var dep = 0; // nombre d'elements déplacés  

			obj.children('li.nextItem').removeClass('nextItem');
			obj.children('li:not(.temp)').removeClass().each(function(i, v){$(this).addClass(dim[i].assClass);});

			if ( o.ombre )	{
			 	$('.ombre').remove();
				 obj.children('li.nextItem').each(function(i, v) {
				 	$(this).append('<span class="ombre"></span>');
				 	$(this).children('span').css(ombres[i]);
				 });
			};	
			
			
	 		// Animation des éléments
	 		obj.children('li:not(.temp)').each(function(i, v){
					$(this).css('zIndex', dim[i].zIndex);
					$(this).animate(dim[i].cssObj, function(){
						dep++; 
						// Si tous les éléments ont fini leur déplacement, le clic est réactivé
						if (dep == dim.length) { 
							clicable = true;
						}
					});
			});
			
			obj.carrousel('setEvents'); // Ecouteurs d'evenements

			
	     },
	     /**
	      * Defilement automatique des items
	      */
	     defilAuto : function() {
	     	window.setTimeout(function() {
		    	if (!pause) {
		    	  sens = '+'; indice++; obj.carrousel('defil');
				  obj.carrousel('defilAuto');
		    	}	
			}, 5000);
	      }
	  };
	
	  $.fn.carrousel = function( method, options) {
	      
	    
	    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 on jQuery.tooltip' );
	    }    
	  
	  };


})( jQuery ); // Fin return



// usage: log('inside coolFunc',this,arguments);
// paulirish.com/2009/log-a-lightweight-wrapper-for-consolelog/
window.log = function(){
  log.history = log.history || [];   // store logs to an array for reference
  log.history.push(arguments);
  if(this.console){
    console.log( Array.prototype.slice.call(arguments) );
  }
};



// catch all document.write() calls
(function(doc){
  var write = doc.write;
  doc.write = function(q){ 
    log('document.write(): ',arguments); 
    if (/docwriteregexwhitelist/.test(q)) write.apply(doc,arguments);  
  };
})(document);
