(function($){
	$.fn.mycarousel = function(){
		return this.each(function(){
			
			//1. get all var together
			
			var $wrapper = $('> div', this).css('overflow','hidden'),
				$slider = $wrapper.find('> ul'),
				$items = $slider.find('> li'),
				$single = $items.filter(':first'),				
				slideWidth = $single.outerWidth(),
				totalSlides = $items.length,
				currentPage=1;
				
			//2. make clone to smooth transition
			
			$items.filter(':first').before($items.slice(-1).clone().addClass('cloned'));
			$items.filter(':last').after($items.slice(0,1).clone().addClass('cloned'));
			$items = $slider.find('> li');//recount li
			
			//3. set the position to the real one
			
			$wrapper.scrollLeft(slideWidth);
			//5. create function gotoslide
			
			function gotoSlide(page, dir){
				var scrollWidth = slideWidth * dir;
				
				$wrapper.filter(':not(:animated)').animate({
					'scrollLeft': '+=' + scrollWidth
				}, 500, function(){
					if(page>totalSlides){
						$wrapper.scrollLeft(slideWidth);
						page=1;
					}else if(page<1){
						$wrapper.scrollLeft(slideWidth * totalSlides)
						page=totalSlides;
					}
					currentPage = page;
				});
				
			}
			
			//4. add the controller
				
			$wrapper.after('<p class="slider-control"><a class="btn-prev" href="#">prev</a><a class="btn-next" href="#">next</a></p>');
			
			//6. bind function to controller
			
			$('a.btn-prev').click(function(){
				gotoSlide(currentPage - 1, -1);	
			});
			
			$('a.btn-next').click(function(){
				gotoSlide(currentPage + 1, 1);	
			});
			
			//7. start the automation!
			
			$(this).bind('next', function(){
				$('a.btn-next').click();						  
			});
			
			var autoscrolling = true;

			$(this).mouseover(function () {
			  autoscrolling = false;
			}).mouseout(function () {
			  autoscrolling = true;
			});
			
			
			setInterval(function () {
			  if (autoscrolling) {
				$wrapper.trigger('next');
			  }
			}, 8000);
			
			
		});						
	};
})(jQuery)