(function ($) {
	$.fn.carousel = function(){
		function repeat(str,n) {
			return new Array( n + 1 ).join( str );
		}
		
		return this.each(function(){
			//plugin code
			var $wrapper = $('> div', this).css('overflow','hidden'),
				$slider = $wrapper.find('> ul'),
				$items = $slider.find('> li'),
				$single = $items.filter(':first'),
				//outerWidth: width + padding (doesn't include margin)
				singleWidth = $single.outerWidth(),
				// note: doesn't include padding or border
				visible = Math.ceil($wrapper.innerWidth() / singleWidth),
				currentPage = 1,
				pages = Math.ceil($items.length/visible);
				
			if (($items.length % visible) != 0) {
				// create empty list items to pad the pages so they are full
				$slider.append(repeat('<li class="empty" />',visible - ($items.length % visible)));
				// reinitialize to include newly created empty items
				$items = $slider.find('> li');
			}
			
			// clone items from front and back of list to create the infinite effect
			$items.filter(':first').before($items.slice(-visible).clone().addClass('cloned'));
			$items.filter(':last').after($items.slice(0,visible).clone().addClass('cloned'));
			$items = $slider.find('> li'); //reselect
			
			//shift scrollLeft back to real element ie move off the cloned elements and back to 'real' start of list
			$wrapper.scrollLeft(singleWidth*visible);
			
			function gotoPage(page) {
				var dir = page < currentPage ? -1 : 1,
					n = Math.abs(currentPage - page),
					left = singleWidth * dir * visible * n;
					
				$wrapper.filter(':not(:animated)').animate({
					scrollLeft : '+=' + left
				}, 500, function() {
					if (page == 0) {
						$wrapper.scrollLeft(singleWidth * visible * pages);
						page = pages;
					} else if (page > pages) {
						$wrapper.scrollLeft(singleWidth * visible);
						page = 1;
					}
					currentPage = page;
				});
				
				return false;
			}
			
			$wrapper.after('<a class="arrow back">&lt;</a><a class="arrow forward">&gt;</a>');
			
			$('a.back',this).click(function (){
				return gotoPage(currentPage - 1);
			});
			
			$('a.forward',this).click(function() {
				return gotoPage(currentPage + 1);
			});
			
			// this currently refers to the element the plugin was bound to
			$(this).bind('goto',function(event,page){
				gotoPage(page);
			});
			
		});
	};
})(jQuery);

