jQuery.fn.carousel = function(){
	
	$(this).each(function(){
	
		var bounds = $('div.bounds', this);
		var ul = $('div.bounds > ul', this);
		var p  = $('a.previous', this);
		var n  = $('a.next', this);
		var w  = $(bounds).width();
		var items = $('li', ul);
		var item_width = $(items).width();
		var item_margin = parseInt($(items).css('margin-right'));
		var list_width = $(items).length * (item_width+item_margin);
		var moving = false;
		
		var min = 0;
		var max = w - list_width + item_margin;
		
		$(ul).css('width', list_width+'px');
		
		if($(ul).width() > w){
		
			function checkpos(){
				var pos = $(ul).position();
				$(p).toggle(pos.left < min);
				$(n).toggle(pos.left > max);
				moving = false;
			}
			
			function next(){
				if(!moving){
					moving = true;
					var pos = $(ul).position();
					var d = Math.max(pos.left - w - item_margin, max);
					if(pos.left <= d) d = 0;				
					$(ul).animate({
						left: d
					}, 1000, function() {
						checkpos();
					});
				}
			}
			
			function previous(){
				if(!moving){
					moving = true;
					var pos = $(ul).position();
					var d = Math.min(pos.left + w + item_margin, min);
					$(ul).animate({
						left: d
					}, 1000, function() {
						checkpos();
					});
				}	
			}
		
			$(p).click(function(event){
				event.preventDefault();
				previous();
			});
			
			$(n).click(function(event){
				event.preventDefault();
				next();
			});
			
			var current = $('li.current', ul);
			if(current[0]){
				var pos = $(current).position();
				if(pos.left > w){
					var d = Math.min(Math.max(-pos.left, max), min);
					$(ul).css('left', d);
				}
			}
		
			checkpos();
			
			if($(this).hasClass('slideshow')){
				setInterval(next, 5000);
			}
			
		}
	
	});
		
};

$(window).load(function(){

	$('div.carousel').carousel();

});
