
(function() {
	jQuery.fn.tkRotate = function(settings) {

		var config = {
			'time': 1250,
			'delay': 5000
		};
		if( settings ) {
			$.extend(config, settings);
		}

		return this.each( function() {

			var $obj = $(this);

			// if this is not an img element
			if( $obj[0].nodeName.toUpperCase() !== 'IMG' ) {
				return;
			}

			var index = 1;
			var imgCount = config.images.length;

			if( imgCount < 2 )
				return;  // nothing to rotate
		
			var images = config.images;
			
			setTimeout(function() { init(); }, config.delay);
			
			var preload = document.createElement('img');
			preload.src = images[1];
			
			var init = function() {
			
				var position = $obj.offset();
				var img_id = $obj.attr('id');
	
				var $markup = $(
					'<div id="' + img_id + '_tkRotateTop"><img src="' + images[index - 1] + '" alt="" /></div>' +
					'<div id="' + img_id + '_tkRotateBottom"><img src="' + images[index] + '" alt="" /></div>'
				);
				
				$('body').append($markup);
			
				var bottom = $('#' + img_id + '_tkRotateTop');
				var top = $('#' + img_id + '_tkRotateBottom');
			
				top.css({'position':'absolute', opacity:0.0}).css(position);
				bottom.css({'position':'absolute'}).css(position);
				
				var test = function() {				
					top.css(position).stop().animate({opacity: 1.0}, config.time, function() {
						index = (index < (imgCount - 1) ? index + 1 : 0);  // advance or reset the index
						bottom.find('img:eq(0)').attr('src', top.find('img:eq(0)').attr('src') );  // copy the top image to the bottom
						top.css({opacity: 0.0});  // hide the top image
						top.find('img:eq(0)').attr('src', images[ index ]);  // preload the next image into the hidden top container
					});
				}
				
				test();
				setInterval(function() { test(); }, config.delay);
				
			} // init = function()
	
		});
	};
})(jQuery);

