/**
 * Cross Fade effect plugin
 *  * 
 * @author createIT team 2010 <http://code.createit.pl>
 */
(function($) {
	$.fn.wnCrossFade = function(options) {
		var defaults = {
			slideClass : "slide", // class of the slide container
			interval: 2500, // exposure time
			transitionTime: 1100, // time of aniation itself
			random: false // do we show slides one after another or randomly?
		};
		
		var options = $.extend(defaults, options);
		var $container;
		var $slides; 
		
		var currentIndex; // index of the current elements of $slides 
		var nextIndex; // index of the next slide
		var slidesCount; // no of slides
		
		var retardedBrowser; // tells if we should avoid nice effects
		
		/**
		 * Prepares the show
		 */
		var prepareSlides = function() {
			currentIndex = 0;
			nextIndex = 1;
			
			$slides.filter(":gt(0)").hide();
			
			$slides.css("position", "absolute").each(function(i) {
				$(this).css("z-index", i+10);
			});
		};
		
		/**
		 * The one responsible for crossfade effect
		 */
		var doSlide = function() {
			var $current = $($slides[currentIndex]);
			var $next = $($slides[nextIndex]);

			currentIndex = nextIndex;
			if(options.random) {
				nextIndex = getRandomIndex(currentIndex);
			} else {
				nextIndex = (1+currentIndex)%slidesCount;
			}
			
			if(retardedBrowser) {
				$slides.hide();
				$current.show();
				
				setTimeout(doSlide, options.interval);
			} else {
				$current.fadeOut(options.transitionTime);
				$next.fadeIn(options.transitionTime, function() {
					
					setTimeout(doSlide, options.interval);
				});				
			}
		};
		
		/**
		 * Get the random index, but not the one given as a parameter
		 */
		var getRandomIndex = function(notWantedIndex) {
			var index = Math.floor(Math.random()*slidesCount);

			if(index == notWantedIndex) {
				return getRandomIndex(notWantedIndex);
			}
			
			return index;
		};
		
		return this.each(function() {
			$container = $(this);
			retardedBrowser = ($.browser.msie && $.browser.version < 9) || ($.browser.mozilla && parseInt($.browser.version) <  4);
			
			$slides = $("> ."+options.slideClass, $container);
			slidesCount = $slides.length;
			
			if(slidesCount < 2) {
				// shut down if we don't have even 2 slides
				return;
			}
			
			prepareSlides();
			setTimeout(doSlide, options.interval);
		});
	};
})(jQuery);
