(function($){
	$.fn.ImageRotator = function($options)
	{	
		window.clearInterval(window.auto_play_intervals);
		
		var $defaults = {
			container_selector  	: 'div.auto-play',
			image_selector    	: 'img',
			auto_play		: true,
			AUTO_PLAY_INTERVAL 	: 5000,
			FADE_INTERVAL 		: 2000
		};
		
		// extend the options
		var $opts = $.extend($defaults, $options);

		// bring the options to the galleria object
		for (var i in $opts) {
			if (i) {
				$.fn.ImageRotator[i]  = $opts[i];
			}
		}
		
		var initAutoPlayGallery = function(event, data) {
			
			window.clearInterval(window.auto_play_intervals);
			
			$($opts['container_selector']).each( function() {
	
				var children = $($opts['image_selector'], this);
				
				if(children.length > 1) {
					children.each( function() {
						$(this).fadeOut(0);
					});
					
					$(children[0]).fadeIn(0);
					
					window.auto_play_intervals = window.setInterval(rotateAutoPlayGallery, $opts['AUTO_PLAY_INTERVAL']);
				}
			});
		}
		
		var rotateAutoPlayGallery = function() {
			
			$($opts['container_selector']).each( function() {
		
				var children = $($opts['image_selector'], this);

				for(var i = 0; i < children.length; i++) {
			
					var target = children[i];
			
					if( $(target).css('display') !== "none" ) {
						//log('opacity IS 1');
						$(target).fadeOut($opts['FADE_INTERVAL']);
			
						if (i == children.length-1) {
							$( children[0] ).fadeIn($opts['FADE_INTERVAL']);
						}
						else {
							$( children[i+1] ).fadeIn($opts['FADE_INTERVAL']);
						}
				
						break;
					}
				}
			});
		}
		
		initAutoPlayGallery(null, null);
		
		return this;
	}
	
})(jQuery);

$(document).ready( function() {
	$('.auto-play').ImageRotator({'image_selector':'div.gallery_image'});
});

$(document).bind("AJAX_CONTENT_REFRESHED", function() {
	$('.auto-play').ImageRotator({'image_selector':'div.gallery_image'});
});
