
$(function(){
	var carousel = $('#carousel');
	var image_wrap = $('<div id="carousel-images" />');
	var previous = $('<div id="carousel-previous" />');
	var next = $('<div id="carousel-next" />');
	var images = carousel.find('img');
	var first_image = $(images[0]);
	var first_image_width = 0;
	var is_animating = false;
	var image_count_in_window = 4;
	
	if(!first_image.length){ return; }
	
	first_image[0].onload = function(){
		first_image_width = first_image.outerWidth();
		
		if(images.length > image_count_in_window){
			carousel.wrapInner(image_wrap);
			carousel.append(previous);
			carousel.append(next);
			
			next.show();
			
			next.click(function(){
				advance(1);
				previous.fadeIn('normal');
				
				var offset = parseInt(first_image.css('margin-left').replace('px', ''));
				if(-offset >= first_image_width * (images.length-(image_count_in_window+1))){
					next.fadeOut('normal');
				}
			});
			previous.click(function(){
				advance(-1);
				next.fadeIn('normal');
				
				var offset = parseInt(first_image.css('margin-left').replace('px', ''));
				if(offset >= -first_image_width){ previous.fadeOut('normal'); }
			});
			
			function advance(i){
				if(is_animating){ return; }
				is_animating = true;
				first_image.animate({ 'margin-left': (i>0?'-=':'+=') + first_image_width + 'px' }, 1000, function(){ is_animating = false; });
			}
		}
	};
});
