$.fn.carousel2 = function( config ) {

	return this.each(function() {
	
		var options = {
			autoplay 				: 0,
			loop					: false,
			speed					: 400,
			ease					: "easeInOutSine",
		
			backgroundImageScale 	: .7,
			foregroundImageMargins 	: 5,
			foregroundTopMargins 	: 10,
			backgroundImageMargins 	: 5,
			
			thumbnailWidth			: 190,
			thumbnailHeight			: 148
		};
		
		$.extend( options, config );
		
		$(this).addClass("jquery-carousel2");
		
		var ie6 = $.browser.msie && parseInt($.browser.version) <= 6;
		var ie7 = $.browser.msie && parseInt($.browser.version) == 7;
		var ie8 = $.browser.msie && parseInt($.browser.version) == 8;
		var ie = $.browser.msie;
		var ff = $.browser.mozilla;
		var wk = $.browser.safari;
	
		var canvas = $(this);
		var canvasWidth = $(this).width();
		var canvasHeight = $(this).height();
		
		var content = $("ul:first-child,ol:first-child", this);
		var list = $("li", content);
		
		var loopLeft, loopRight;
		
		var imgHeight = 0;
		var imgWidth = 0;
		
		var current = 0;
		var apInterval = null;
		
		var controls = {
			left: $("<div class='leftControl'><span>&lt;</span></div>"),
			right: $("<div class='rightControl'><span>&gt;</span></div>")
		};
		
		var text = {};
		$("span", list).each( function() {
			if (this.className) {
				if (!text[this.className]) text[this.className] = $("<p class='"+this.className+"'></p>");
			};
		} );
		
		var animate = function( instant ) {
				
			var speed = instant==true ? 0 : options.speed;
			
			list.each( function(i) { animateItem( this, speed ) }  );
			if (options.loop) {
				animateItem( loopLeft, speed );
				animateItem( loopRight, speed );
			}
			
			/* Oculta controles */
			controls.left.css({ visibility:(current<=0&&!options.loop?"hidden":"visible") });
			controls.right.css({ visibility:(current>=(list.size()-1)&&!options.loop?"hidden":"visible") });
			
			doScroll( speed )
		};
		
		var animateItem = function( target, speed ) {
			
			var tar = target;
			var i = $(tar).attr("indx");

			if (i == current) {
				var urltar = $("a", tar).attr('href');
				$("a", tar).addClass("selected");
				$("img", tar).animate({ 
					height:imgHeight
				}, speed, "");
				$(tar).animate({
					marginTop:0,
					marginLeft: i==0&&!options.loop?0:-options.foregroundImageMargins+"px",
					marginRight: -options.foregroundImageMargins+"px"
				}, speed, options.ease).css({ });
				
				// Actualiza los campos de texto
				for (j in text) {
					text[j].attr('newContent', $("."+j, tar).html() );
					text[j].stop().fadeTo("fast", 0, function() {
						$(this).html( $(this).attr('newContent') );
						$(this).unbind('click');
						$(this).bind('click', function() { document.location = urltar } ).css({cursor:"pointer"});
						if ($(this).attr('newContent') == "") $(this).hide();
						else $(this).fadeTo("fast", 1).show();
					});
				};
			} else {
				$("a", tar).removeClass("selected");
				$("img", tar).animate({ 
					height:imgHeight*options.backgroundImageScale
				}, speed, options.ease);
				$(tar).animate({
					marginTop:options.foregroundTopMargins+"px",
					left:0,
					marginLeft:options.backgroundImageMargins,
					marginRight:options.backgroundImageMargins
				}, speed, options.ease).css({ "position":"static" });
			};
			
		}
		
		var doScroll = function( speed ) {

			/*content.animate({
				//marginLeft : canvasWidth/2 - (list[current].offset().left - content.offset().left)  - selection.width()/2
				marginLeft : canvasWidth/2 - current*(imgWidth*options.backgroundImageScale + options.backgroundImageMargins*2-(!ff?(ie&&!ie7&&!ie6?0.5:1):0)) - imgWidth/2 + (current==0?0:options.backgroundImageMargins-(ie6?6:ff||ie?0:-1))
			}, speed, options.ease);*/
			//marginLeft : canvasWidth/2 - (list[current].offset().left - content.offset().left)  - selection.width()/2
			
			var realcurrent = current + (options.loop?1:0);
			var targetPos = canvasWidth/2 - realcurrent*(imgWidth*options.backgroundImageScale + options.backgroundImageMargins*2) - imgWidth/2 + (realcurrent==0?0:options.backgroundImageMargins-(ie?1:0)) + (!ff&&!ie6&&!ie7?1:0) - (ie6?5:0);
			
			if (options.loop && (current >= list.size() - 1)  ) targetPos -= (imgWidth-imgWidth*options.backgroundImageScale)/2 + options.backgroundImageMargins*2 - (wk?1:2) - (ie6?5:0);
			
			content.animate({ marginLeft : targetPos }, speed, options.ease );
		};
		
		var init = function() {
		
			// Obtenemos el alto de la primera imagen 
			//imgHeight = $("img:first-child", list).height();
			//imgWidth = $("img:first-child", list).width();
			imgWidth = options.thumbnailWidth || $("img:first-child", list).width();
			imgHeight = options.thumbnailHeight ||$("img:first-child", list).height();
			content.width( (list.size()+(options.loop?2:0)) * imgWidth );
			//content.width( 20000 );
			
			canvas.css( { overflow:"hidden" } );
			content.css( { overflow:"visible" } );
			list.css( { "float":"left", overflow:"visible" } );
			
			$("img", content).css( {
				"vertical-align":"middle",
				overflow:"visible",
				width:"auto"
			});
			
			// absolute position fix para Webkit
			if (!ie) for (i in text) text[i].css( { position:"relative" } );
			
			// Indice a cada elemento
			list.each( function(i) { $(this).attr("indx", i) } );
			
			/* Efecto loop infinito (duplicamos elementos) */
			if (options.loop) {
				// Anterior
				loopLeft = list.eq( list.size()-1 ).clone(true).insertBefore( list.eq( 0 ) );
				// Posterior
				loopRight = list.eq( 0 ).clone(true).insertAfter( list.eq( list.size()-1 )  );
			}			
			
			// Aņadimos controles
			canvas.append( controls.left );
			canvas.append( controls.right );

			// Aņadimos campos de texto
			for (i in text) canvas.append( text[i] );
						
			// Configuraciond e controles
			controls.left.click( prev );
			controls.right.click( next );
			
			// Prevenimos hacer click en elementos de fondo
			$("a", list).click( function(e) {
				if (!$(this).hasClass("selected")) e.preventDefault();
			} );
			
			canvas.disableTextSelect();
			
			animate(true);
			
			if (options.autoplay) apInterval = setInterval( next, options.autoplay );
			
		};
		
		var next = function( e ) {
			if (e && isNaN(e)) { 
				e.preventDefault();
				if (apInterval) clearInterval( apInterval );
				apInterval = null;
			}
			current++;
			if (current > list.size()-1 ) {
				if (options.loop) {
					current = -1; doScroll( 0 );
					current = 0;
				}
				else current = list.size()-1;
			};
			animate();
		};
		
		var prev = function( e ) {
			if (e) { 
				e.preventDefault();
				if (apInterval) clearInterval( apInterval );
				apInterval = null;
			}
			current--;
			if (current < 0) {
				if (options.loop) {
					current = list.size(); doScroll( 0 );
					current = list.size()-1;
				} else current = 0;
			};
			animate();
		};
		
		// Inicializamos al cargar la primera imagen
		var firstImage = $("img:first-child").get(0);
		if (firstImage.complete == true) init();
		else firstImage.onload = init;
	
	});

}