(function($)
{
	$.fn.cb_carousel = function()
	{
		return this.each(function()
		{
			var element = $(this);
			if(element.children('img').length > 1)
			{
				var busy = false;
				var currentImage = 0;
				var imageWidth = element.children('img').width();
				var numberOfImages = element.children('img').length;
				element.append($('<div class="cb_carousel"><a href="#" class="go_left"></a><a href="#" class="go_right"></a></div>').css({ width: imageWidth * numberOfImages, height: element.children('img').height() }));
				element.children('img').each(function(i)
				{
					$(this).css({ position: 'absolute', top: 0, left: i * imageWidth }).prependTo(element.children('.cb_carousel'));
				});
				$('.cb_carousel .go_left').click(function()
				{
					if(!busy)
					{
						imageWidth = $(this).siblings('img:first').width();
						numberOfImages = $(this).siblings('img').length;
						currentImage = (parseFloat($(this).siblings('img:first').css('margin-left')) / imageWidth) + 1;
						busy = true;
						$(this).siblings('img').stop().animate({ 'margin-left': currentImage * imageWidth }, 700, function()
						{
							busy = false;
						});
						if(currentImage >= 0)
						{
							$(this).hide();
						}
						if(currentImage > (numberOfImages - 1) * -1)
						{
							$(this).siblings('.go_right').show();
						}	
					}
					return false;
				}).hide();
				$('.cb_carousel .go_right').click(function()
				{
					if(!busy)
					{
						imageWidth = $(this).siblings('img:first').width();
						numberOfImages = $(this).siblings('img').length;
						currentImage = (parseFloat($(this).siblings('img:first').css('margin-left')) / imageWidth) - 1;
						busy = true;
						$(this).siblings('img').stop().animate({ 'margin-left': currentImage * imageWidth }, 700, function()
						{
							busy = false;
						});
						if(currentImage < 0)
						{
							$(this).siblings('.go_left').show();
						}
						if(currentImage <= (numberOfImages - 1) * -1)
						{
							$(this).hide();
						}
					}
					return false;
				});
			}
		});
	};
})(jQuery);
