(function($) {
	
	$.fn.carousel = function(numVis) {
	
		// Number of elements in the target to show
		numVis = numVis | 5;
				
		$.each( this, function() {
		
			var elements = $(this).children();
			var elemWidth = elements.width();
			var elemHeight = elements.height();
		
			var source = $(this);
			var id = source.attr('id');
			var height = source.height();
			var width = source.width();
			
			// Inject Carousel Mark-up
			$(this).after('<div id="'+ id +'"><div id="back" class="button"></div><div id="carousel_content"><div><ul></ul></div></div><div id="forward" class="button"></div></div>');
			
			// Remove original content
			$(this).remove();
			
			// Format Injected Content
			$('#' + id + ' div').css('display', 'inline-block').css('float', 'left');
			
			var backBtn = $('#' + id + ' #back');
			backBtn.height(height).width('5%');
			
			var fwdBtn = $('#' + id + ' #forward');
			fwdBtn.height(height).width('5%');
			
			var content = $('#' + id + ' #carousel_content');
			content.height(height).width('90%');
			
			var aperture = content.children('div');
			aperture.height(elemHeight).width('100%').css('overflow', 'hidden').css('position', 'relative');
			
			var slide = aperture.children('ul');
			slide.height(elemHeight).width(elemWidth * elements.length).css('position', 'absolute').css('left', 0);
			
			// Inject Elements into Carousel
			$.each(elements, function() {
				
				slide.append('<li>' + $(this).html() + '</li>');
				
			});
			slide.children('li').css('display', 'inline-block').width(elemWidth);
			
			// Set-up Button funcitonality						
			var ptr = 0;
			
			function checkBtns() {
				if ( ptr > 0 ) {
					backBtn.removeClass('disabled');
				} else {
					backBtn.addClass('disabled');
				}
				
				if ( ptr < ( elements.length - numVis )) {
					fwdBtn.removeClass('disabled');
				} else {
					fwdBtn.addClass('disabled');
				}
			}
			
			backBtn.mouseover(function() { $(this).addClass('active'); }).mouseout(function() { $(this).removeClass('active') });
			
			backBtn.click(function(e){
				if ( ptr > 0 ) {
					ptr--;				
					
					slide.stop().animate({'left' : -elemWidth * ptr }, 200);
					
					checkBtns();
				}
				
			});
			
			fwdBtn.mouseover(function() { $(this).addClass('active'); }).mouseout(function() { $(this).removeClass('active') });
			
			fwdBtn.click(function(e){
				
				if ( ptr < ( elements.length - numVis )) {
					ptr++;
					
					slide.stop().animate({'left' : -elemWidth * ptr }, 200);
					
					checkBtns();
				}
				
			});
			
			checkBtns();
		});
		
	};

})(jQuery);
