(function($){

	$.fn.slideshow = function(params) {
		
		return this.each(function() {
		
			var cont = $(this);
			var stage = cont.find('.stage');
			var slides = cont.find('.slide');
			var play = $('<a class="slideshowplay"></a>');
			cont.append(play);
			var stop = $('<a class="slideshowstop"></a>');
			cont.append(stop);
			var pause = $('<a class="slideshowpause"></a>');
			cont.append(pause);
			/*
			var arrowleft = cont.find('.arrow-left');
			var arrowright = cont.find('.arrow-right');
			*/
			var dot_wrapper = cont.find('.dots');
			var dots = dot_wrapper.find('.dot');
			var timer;
			var delay = 6500;
			var crossfade = 1000;
			var old = 0;
			var cr = 0;
			var ns = slides.length;
			var wait = 0;
			
			var fading = false;
			
			var sw = slides.eq(0).width();
			var sh = slides.eq(0).height();
			
			stage.css({position:'relative'});
			slides.css({position:'absolute',top:0,left:0}).hide();
			slides.eq(0).show();

			/*
			arrowleft.click(prev);
			arrowright.click(next);
			*/
			
			stop.click(function() {
				clearTimeout(timer);
			});
			
			play.click(function() {
				clearTimeout(timer);
				timer = setTimeout(next, delay);
			});
			
			pause.click(function() {
				clearTimeout(timer);
				timer = setTimeout(next, delay*2);
			});

			dots.click(function(){
				clearTimeout(timer);
				var ps = dots.index(this);
				if (ps != cr)
				{
					old = cr;
					cr = ps;
					return go(0,5000);
				}
				else
				{
					return false;
				}
			});
			
			fix_dot();

			function go(dir,wait)
			{
				if (fading)
				{
					//sto ancora facendo una transizione...
				}
			
				fading = true;
			
				clearTimeout(timer);
				fix_dot();
				slides.stop();
				
				/*
				if ( dir < 0 || ( dir == 0 && cr < old ) )
				{
					//vado indietro
					slides.eq(old).css({left:0}).animate({left:sw});
					slides.eq(cr).show().css({left:-sw}).animate({left:0});
				}
				else
				{
					//vado avanti
					slides.eq(old).css({left:0}).animate({left:-sw});
					slides.eq(cr).show().css({left:sw}).animate({left:0});
				}*/
				//stage.animate({left:offset});
				
				slides.css('z-index',0);
				
				slides.eq(old).css('z-index',1).css({opacity:1});
				
				slides.stop();
				
				slides.eq(cr).show().css({opacity:0}).css('z-index',2).animate({opacity:1}, crossfade, function() {
					fading = false;
				});
				
				timer = setTimeout(next,delay+wait);
				return false;
			}
			
			function next()
			{
				clearTimeout(timer);
				old = cr;
				cr++;
				if (cr > ns-1)
				{
					cr=0;
				}
				return go(1,0);
			}
			
			/*
			function prev()
			{
				clearTimeout(timer);
				old = cr;
				cr--;
				if (cr < 0)
				{
					cr=ns-1;
				}
				return go(-1,0);
			}
			*/
			function fix_dot()
			{
				clearTimeout(timer);
				dots.removeClass('cdot');
				dots.eq(cr).addClass('cdot');
			}

		});
	}

})(jQuery)
