(function($)
{
	$.fn.carousel = function(options)
	{
		options = $.extend({},options);
		
		var carousel = $(this);
		
		return this.each(_init);
		
		function _init()
		{
			_buildCarousel();
		}
		
		function _buildCarousel()
		{
			var _viewports = $('li', carousel);
			
			$('dt', _viewports).hide();
			
			var _width = 0;
			
			_viewports.each(function()
			{
				var _viewport = $(this);
				
				var _before = $('dd:first', _viewport);
				var _after = $('dd:last', _viewport);
				
				_after.hide();
				
				var _slider = $('<div />')
					.appendTo(_before)
					.css({
						backgroundImage: 'url(' + _after.find('img').attr('src') + ')'
					});
					
				$('> div', carousel).width(_before.width());
					
				_width+= _before.outerWidth();
			}).not(':first-child').hide();
			
			$('> div', carousel).css({
				overflow: 'hidden',
				position: 'relative'
			})
			.find('ul')
			.width(_width);
			
			setTimeout(_animate, 3000);
			
			function _animate()
			{
				var _slider = $('div', _viewports.not(':hidden'));
				
				_slider.animate({width: '100%'}, 1500, function()
				{
					//setTimeout(function()
					//{
						//_slider.animate({width: '100%'}, 500, function()
						//{
							setTimeout(function()
							{
								if(_viewports.length > 1)
								{
									var current = _viewports.not(':hidden');
									var next = current.next().length
										? _viewports.not(':hidden').not(':animated').next()
										: $(_viewports.get(0));
									
									current.fadeOut(300, function()
									{
										current.find('dd div').width(0);
										
										next.fadeIn(300, function()
										{
											setTimeout(function()
											{
												_animate();
											}, 3000);
										});
									});
								}
								else
								{
									// we need to go fade the inner div out instead
								}
								
								//if()
							},
							2500);
						//});
					//},
					//2500);
				});
			}
		}
	}
})
(jQuery);

$(document).ready(function()
{
	$('#carousel').carousel();
});
