/*
 * Author: Brendan Do
 * Title: Image Rotator jQuery Plugin
 * Version: 1.0
 */
(function($){
	$.fn.ImageRotator = function(options) {
		// Set defaults
		var element = this;
		var rotateIntImages;
		var defaults = {
			opacityTime: 1000,
			timer: 3000,
			startIndex: 0,
			onTransitionStart: function(){},
			onTransitionComplete: function(){},
			onTransitionChange: function(){}
		};
		var options = $.extend(defaults, options);
		
		var instanceOptions = {
			startTimer: startTimer,
			stopTimer: stopTimer
		};
		
		function startTimer(){
			rotateIntImages = setInterval(rotate, options.timer);
		}	
		
		function stopTimer(){
			clearInterval(rotateIntImages);
		}			
		
		function rotate(){	
			// Get the current & next image
			var current = $(element).find('li.show');
			var next = $(element).find('li.show').next();
			var nextImage = next.find('img');
			var currentImage = current.find('img');
			
			// When it reaches the end, rotate it back to the first image
			if(current.next().length == 0){
				next = $(element).find('li:first');
				nextImage = next.find('img');
			}
			
			// Run custom function if it exists on image change
			options.onTransitionChange(currentImage, nextImage);			
			
			// Set the fade in effect for the next image
			next
				.css({opacity: 0.0})
				.removeClass('hide')
				.addClass('show')
				.animate({opacity: 1.0}, options.opacityTime);
			
			// Hide the current image
			current
				.animate({opacity: 0.0}, options.opacityTime)
				.removeClass('show')
				.addClass('hide');	
			
			// Run custom function if it exists upon disply the image
			options.onTransitionComplete(image);
		};		
		
		// Hide all images
		$(element).find('li').addClass('hide');
		
		// Get the first image and display it
		$(element).find('li:nth(' + options.startIndex + ')')
			.removeClass('hide')
			.addClass('show');
		var image = $(element).find('li:nth(' + options.startIndex + ')').find('img');
		
		// Run custom function if it exists when the first image displays
		options.onTransitionStart(image);
			
		// Call the rotator function to run the image rotator
		startTimer();
		
		return instanceOptions;
	};
})(jQuery);
