/**
 * Cross Fade effect plugin
 *  * 
 * @author createIT team 2010 <http://code.createit.pl>
 */
(function($) {
	$.fn.wnCrossFade = function(options) {
		var defaults = {
			slideClass : "slide",
			interval: 2500,
			transitionTime: 1100
		};
		
		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]);
			
			if(retardedBrowser) {
				$slides.hide();
				$current.show();
				
				currentIndex = nextIndex;
				nextIndex = (1+currentIndex)%slidesCount;
						
				setTimeout(doSlide, options.interval);
			} else {
				$current.fadeOut(options.transitionTime);
				$next.fadeIn(options.transitionTime, function() {
					currentIndex = nextIndex;
					nextIndex = (1+currentIndex)%slidesCount;
					
					setTimeout(doSlide, options.interval);
				});				
			}
			
			
		};
		
		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);
