/*!
 * Image Rotetor by Nicola (Rievoluzione.it)
 */

(function($) {



	/**

	 * @private Instance object

	 */

	self = {

		/**

		 * Elemnts

		 */

		rotatorSet: null,

		

		/**

		 * default settings

		 */

		settings: {

			interval: 1500,			

			randomize: true,

			fadetime: 500

		},

	}



	

	/**

	 * Methods

	 */

	var methods = {	

	

		/**

		 *	Init funciton

		 *  Apply setting and start rotation of image

		 */		

		init: function(options){

		

			self.rotatorSet = this;

	

			if( options ){

				$.extend( self.settings, options );

			}

			

			//Set the opacity of all images to 0				

			$(this).find('ul li').css({opacity: 0.0});

			//Get the first image and display it (gets set to full opacity)

			$(this).find('ul li:first').css({opacity: 1.0});		

			

			//console.info('interval', self.rotatorSet.rotator('rotate'));

			setInterval('self.rotatorSet.rotator(\'rotate\')' , self.settings.interval);

			

			$(this).fadeIn(self.settings.fadetime);

			$(this).find('ul li').fadeIn(self.settings.fadetime); // tweek for IE		



			return this;

		},	

	

		/**

		 * rotate function

		 * Rotate all images

		 */

		rotate: function(){

			

			self.rotatorSet.each(function(index, elem){



				//Get the first image

				var current = ($(elem).find('ul li.show')?  $(elem).find('ul li.show') : $(elem).find('ul li:first'));

				if ( current.length == 0 ){

					current = $(elem).find('ul li:first');

				}

				//Get next image, when it reaches the end, rotate it back to the first image

				if( (current.next().length) ){

					if( (current.next().hasClass('show')) ) {

						var next = $(elem).find('ul li:first');

					} else {

						var next = current.next();

					}					

				} else {

					var next = $(elem).find('ul li:first');

				}

	

				//randomize display

				if( self.settings.randomize ){

					var sibs = current.siblings();

					var rndNum = Math.floor(Math.random() * sibs.length );

					var next = $( sibs[ rndNum ] );

				}			



				//Set the fade in effect for the next image, the show class has higher z-index

				next.css({opacity: 0.0}).addClass('show').animate({opacity: 1.0}, self.settings.fadetime);

				//Hide the current image

				current.animate({opacity: 0.0}, self.settings.fadetime).removeClass('show');

			

			});		



		}

	}	

	

	

	/**

	 * Constructor

	 */

	$.fn.rotator = function( method ) {    

		if ( methods[method] ) {

			return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 ));

		} else if ( typeof method === 'object' || ! method ) {

			return methods.init.apply( this, arguments );

		} else {

			$.error( 'Method ' +  method + ' does not exist on jQuery.tooltip' );

		}      

	};	



	

})(jQuery);





/**

 *	Define a rotator object on all rotator divs

 */

$(document).ready(function() {		

	//Load the slideshow

	$('.rotator').rotator();

});
