/*** Image fader **/

(function ($) {

	$.fn.imageFader = function ( delay, duration ) {

		duration = duration || 2000;
		delay = delay || 3000;
        var timer;

		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);

			$('#slider-buttons a').click(function(){
			     currentItem = $('#slider-buttons li').index($(this).parent('li'));
			     $('#slider-buttons li a').removeClass('active-slide');
			     $(this).addClass('active-slide');
			     clearInterval(timer);
			     fader();
			     timer = setInterval(fader, delay);
			     return false;
			});

			function fader() {

				var $insert = $(items[currentItem]).css({
					opacity : 0,
					position : 'absolute',
					left : 0,
					top : 0
				}).prependTo($list).animate({opacity : 1}, duration);

				$('#slider-buttons li a').removeClass('active-slide');
				$('#slider-buttons li:eq(' + currentItem + ') a').addClass('active-slide');

				$list.find('> li:last').animate({ opacity : 0}, duration, function(){
					$insert.css({ zIndex : 10});
					$(this).remove();
				});

				currentItem++;
				if(currentItem >= total) {
					currentItem = 0;
				}



			}

			timer = setInterval(fader, delay);

		});

	};

})(jQuery);