/*
 * jQuery Carousel v1.0 by Craig Freer / Together Agency
 */
 
;(function($) {

	$.fn.Carousel = function(settings){

		settings = jQuery.extend({
			pause: 8000,
			duration: 1500
		}, settings);

		this.each(function() {

			var obj = $(this);
			var current = 1;
			var isAnimating = false;
			var zIndex = 1;
			var paused = false;

			function next() {
				if (!paused) {
					frame = ((current+1)>5) ? 1 : current+1;
					displayFrame(frame);
				}
			}

			function playPause() {
				if (paused) {
					paused = false;
					timeout = setTimeout(function() { next(); }, settings.pause);	
				} else {
					paused = true;
					clearTimeout(timeout);
				}
				$('#oCarouselControlPause').toggleClass('paused');
			}

			function displayFrame(frame) {
				if (isAnimating) return;
				isAnimating = true;
				clearTimeout(timeout); //stop automatic progression.
				setPlayHead(frame);
				
				$("ul li:nth-child("+frame+")", obj).css('zIndex', zIndex++).fadeIn(settings.duration, function() {
					$(this).siblings().hide();
					isAnimating = false;
					current = frame;
					timeout = setTimeout(function(){ next(); }, settings.pause);
				});
			}

			function setPlayHead(frame) {
				$('#oCarouselControl div').removeClass('on');
				$('#oCarouselControl div:nth-child('+frame+')').addClass('on');
			}

			function init() {
				$('#oCarouselControl div a[rel]').removeAttr('href').bind('click', function() { //remove links from each number, and add a click action.
					var slide = $(this).attr('rel');
					displayFrame(slide);
				}).css('cursor', 'pointer');
				$('ul li', obj).each(function() {
					$(this).css('zIndex', zIndex);
					zIndex++;
				});
				$('ul li:first-child', obj).css('zIndex', zIndex++);
				$('#oCarouselControlPause').removeAttr('href').bind('click', function() { playPause(); }).css('cursor', 'pointer');
			}

			//setup and init
			init();

			//run
			var timeout = setTimeout(function() { next(); }, settings.pause);

		});
	};
})(jQuery);



