/*** Image fader **/

(function ($) {

	$.fn.imageFader = function ( delay, duration ) {
	
		duration = duration || 2000;
		delay = delay || 3000;
		
		return this.each(function () {
		
			// 1. Setup
			var $list = $(this),
				items = [],
				total = 0,
				currentItem = 1;
				
			$list.find('> li').each(function () {
	            items.push('<li>' + $(this).html() + '</li>');
	        });
				
			total = items.length;
			
			// Remove all items
			$list.find('> li:not(:first)').each(function() {
				$(this).remove();
			}).find('> li:first').css('z-index', 10);
					
			function fader() {
				
				var $insert = $(items[currentItem]).css({
					opacity : 0,
					position : 'absolute',
					left : 0,
					top : 0
				}).prependTo($list).animate({opacity : 1}, duration);
				
				$list.find('> li:last').animate({ opacity : 0}, duration, function(){
					$insert.css({ zIndex : 10});
					$(this).remove();
				});
				
				currentItem++;
				if(currentItem >= total) {
					currentItem = 0;
				}
				
				setTimeout(fader, delay);
				
			}
			
			setTimeout(fader, delay);
			
		});

	};
	
})(jQuery);