/**
 * Plugin do plynnej podmiany obrazkow.
 * Innymi slowy - prosty slide effect :)
 * Priorytet - maly rozmiar kodu (stad nie uzywamy alternatywy typu cycle)
 */
(function($) {
	$.fn.wnCrossFade = function(options) {
		var defaults = {
			slideClass : "slide",
			interval: 2500,
			transitionTime: 1100
		};
		
		var options = $.extend(defaults, options);
		var $container;
		var $slides; // wszystkie slajdy
		
		var currentIndex; // index w tablicy $slides aktualnego elementu
		var nextIndex; // index w tablicy $slides nastepnego elementu do pokazania
		var slidesCount; // ilosc slajdow
		
		var retardedBrowser; // okresla czy przegladarka jest uposledzona i nie ogarnie ladnych efektow
		
		/**
		 * Przygotowuje slajdy
		 */
		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);
			});
		};
		
		/**
		 * Odpowidzialne za przejscie samo w sobie
		 */
		var doSlide = function() {
			var $current = $($slides[currentIndex]);
			var $next = $($slides[nextIndex]);
			
			if(retardedBrowser) {
				$slides.hide();
				$current.show();
				//$next.hide();

				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) {
				// jezeli mamy mniej niz 2 slajdy to po prostu nic nie robimy
				return;
			}
			
			prepareSlides();
			setTimeout(doSlide, options.interval);
		});
	};
})(jQuery);
