(function($){

	$.fn.pdImageRotator = function(options)
	{
		var o = $.extend({
			rowTimeOut: 8000,
			imageTimeOut: 150,
			fadeOut: 300,
			fadeIn: 500,
			imagesList: [],
			imagesPath: ''
	  	}, options);

		var $elems = $(this);
		var length = $elems.size();
		var imgBuffer = [];   
	    var rotIndex = -1;
	    var imagesListLength = o.imagesList.length;
	    
	    var rotateCountdown = length;
	    var preloadCountdown = 0;
	    var timeOutReady = false;	  
	    
	    init();
	    return this;
			
	    function init() 
	    {         
			prepareNextRound();	
	    };
	    
		function rotate() 
		{
			rotateCountdown = length;
			$elems.each(function(i)
			{
				var that = this;
				setTimeout(function(){ rotateSingle($(that), i); }, o.imageTimeOut * (i+1));													
			});			
		};

		function rotateSingle($e, i)
		{
			
			var targetHeight = imgBuffer[i][0].height;
			var targetWidth = imgBuffer[i][0].width;

			$('img', $e).animate({ height: '0', width: '70px', marginTop: '35px' }, o.fadeOut, 'swing' , function(){
					var href = $.data(imgBuffer[i][0], 'href');
					if(href) $e.filter('a').attr('href', href);
					else $e.filter('a').removeAttr('href');
					imgBuffer[i]
						.css({ height: '0', width: targetWidth, marginTop: '35px'})
						.appendTo($e.empty())
						.animate({ height: targetHeight + 'px', marginTop: (70 - targetHeight)/2 + 'px' }, o.fadeIn, 'swing');					
				});

		
			// Alternate fading animation:
/*			
			$('img', $e).fadeOut(o.fadeOut, function(){					
					imgBuffer[i].hide().appendTo($e.empty()).fadeIn(o.fadeIn);					
				});
//*/				
			var that = this;	
			if(--rotateCountdown <= 0) setTimeout( prepareNextRound, o.imageTimeOut * (i+1));
		};

		function prepareNextRound()
		{						
			preloadCountdown = $elems.size();			
			imgBuffer = [];
			timeOutReady = false;
			var that = this;
			for(var i = 0, l = preloadCountdown; i <l; i++)
			{
				rotIndex = (rotIndex + i+1) % imagesListLength;
				var img = document.createElement('img')
				imgBuffer[i] = $(img)				
					.bind('load', function(){ --preloadCountdown; preloadCallback(); })
					.attr({
						'src': o.imagesPath + o.imagesList[rotIndex].file,
						'alt': o.imagesList[rotIndex].alt,
						'title': o.imagesList[rotIndex].title
					});
				if(o.imagesList[rotIndex].href) $.data(img, 'href', o.imagesList[rotIndex].href);			
			}		
			setTimeout(function(){ timeOutReady = true; preloadCallback(); }, o.rowTimeOut);	
		};

		function preloadCallback()
		{
			if(preloadCountdown <= 0 && timeOutReady) rotate();
		};
	};
	
})(jQuery);
