(function ($) {
  $.fn.scrollingcarousel = function (options) {
	var opts = $.extend({}, $.fn.scrollingcarousel.defaults, options);
    return this.each(function () {
	    var $carousel = $(this);
		var $ul = $('ul:first', $carousel);
		var $prev = $(opts.prev, $carousel.parent());
		var $next = $(opts.next, $carousel.parent());
		var w=0;
		var cw = $carousel.width();
		var _containerWidth = $carousel.parent().width();
		$ul.children().each(function(){
			w += $(this).outerWidth(true);
		});
		var max = w - cw;
		// calculate speed
		var _speed = w / opts.rate;
		// start the carousel
		move('forward',_speed);
		// events 
		$carousel.hover(
			function() {
				$ul.stop();
			}, 
			function() {
				move($ul.attr('class'),_speed);
			}
		);
		$prev.hover(
			function() {
				$ul.stop();
				moveEnd('back');
			}, 
			function() {
				$ul.stop();
				move('forward',_speed);
			}
		);
		$next.hover(
			function() {
				$ul.stop();
				moveEnd('forward');
			}, 
			function() {
				$ul.stop();
				move('back',_speed);
			}
		);
		$prev.add($next).click(function(e){
			e.preventDefault();
		});
		if($('.item-info',$ul).size() > 0) {
			$ul.children().hover(
				//mouseover
				function(e){
					var _mousepos = e.pageX,
						$li = $(this),
						$next = $li.next(),
						$previous = $li.prev(),
						$info = $('.item-info',$li);
					if(_containerWidth - _mousepos <= 200){
						$info.addClass('left');
					} 
					$li.css('z-index','90');
					$next.add($previous).css('z-index','1');
					if($.browser.msie) $li.css('position','relative');
					$info.show();
				},
				//mouseout
				function(e){
					var $li = $(this),
						$next = $li.next(),
						$previous = $li.prev(),
						$info = $('.item-info',$li);
					$info.hide();
					// cleanup
					$info.removeClass('left');
					$li.css('z-index','50');
					$next.add($previous).css('z-index','50');
					if($.browser.msie) $li.css('position','static');
				}
			);
		}
		// private
		function move(direction,speed){
			var d = (direction == 'forward') ? (-1 * max) + 'px' : '0px';
			$ul.attr('class','').addClass(direction);
			$ul.animate({ 
			 	left: d
			}, speed,'linear',function(){
				var newdir = (direction == 'forward') ? 'back' : 'forward';
				$ul.attr('class','').addClass(newdir);
				move(newdir,speed);
			});
		}
		function moveEnd(direction) {
			$ul.stop();
			var end = (direction == 'forward') ? -1 * max + 'px' : '0px';
			var speed =opts.hoverspeed;
			$ul.animate({
				left: end
			},speed,'linear');
		}
	    });
  	};
	// plugin defaults
	$.fn.scrollingcarousel.defaults={
		prev:'.prev',
		next:'.next',
		rate:0.098,
		hoverspeed:5000
	};	
})(jQuery);
