/**
 * Slideshow
 */
jQuery(function( $ ){
	var $covers  = $('#portadas li'),
		$images  = $covers.children('img'),
		$active  = $covers.filter('.activo'),
		$view    = $('#visor-portada'),
		scrolled = 0,
		hovered	 = 0,
		timer	 = null,
		timer2	 = null,
		hovering = false,
		width	 = $view.find('img').css('left',0).width(),
		quant	 = $covers.length;

	if( $view.length == 0 )
		return;
		
	$covers.hover(function(){
		hovering = true;
		clearTimeout(timer);
		hover( $covers.index(this) );	
	}, function(){
		hovering = false;
		schedule();
	});
	
	schedule();
	
	function schedule(){
		clearTimeout(timer);
		if( !hovering ){
			timer = setTimeout(function(){
				var index = scrolled == quant-1 ? 0 : scrolled + 1;
				hover( index );
			},10000);
		}
	};
	function hover( index ){
		if( index == hovered ) return;
		hovered = index;
		$active.removeClass('activo');
		$active = $covers.eq(index).addClass('activo');
		if( index == scrolled || quant < 1 ) return;
		clearTimeout(timer2);
		timer2 = setTimeout( function(){
			scrolled = index;									  
			var $last = $view.find('img:last');
			var $new = $images.eq(index).clone().insertAfter($last);
			$new.animate({ left : 0 }, 800, function(){
				$last.remove();
				if( scrolled == index )
					schedule();
			});
		}, 500 );
	};
});

