(function ($) {
	$.fn.carousel = function (c) {
		return this.each(function () {
			$settings = Array();
			$settings['opts'] = $.extend({
				onScroll: function (a) { }
			},
			$.fn.carousel.defaults, c);
			$settings['totalWidth'] = 0;
			$settings['itemWidth'] = 0;
			$settings['count'] = 0;
			$settings['maxOfset'] = 0;
			$settings['move'] = 0;
			$settings['visibleWidth'] = 0;
			$settings['visibleItems'] = 0;
			$this = $(this);
			$items = $("ul li", $this);
			if ($items.length > 0) {
				$settings['count'] = $items.length;
				$settings['itemWidth'] = $($items[0]).outerWidth(true);
				$settings['visibleWidth'] = $(".viewport", $this).width();
				$settings['visibleItems'] = $settings['visibleWidth'] / $settings['itemWidth'];
				$settings['totalWidth'] = $settings['count'] * $settings['itemWidth'];
				$settings['move'] = $settings['opts'].moveCount * $settings['itemWidth'];
				$settings['maxOfset'] = $settings['totalWidth'] - $settings['visibleWidth'];
				if ($settings['maxOfset'] > 0) {
					$settings['maxOfset'] = -$settings['maxOfset']
				} else {
					$settings['maxOfset'] = 0
				}
			} else {
				return false;
			}
			$('ul', $this).css("width", $settings['totalWidth']);
			$.fn.carousel.setControls($settings, $this);
			var b = -$settings['itemWidth'] * $settings['opts'].firstItemIndex;
			$('ul', $this).css({ left: b });
			$this.bind('click', {
				parent: $this,
				settings: $settings
			},
			function (evt) {
				$target = $(evt.target);
				if ($target.is('.ctrl')) {
					evt.preventDefault();
					$.fn.carousel.scroll($target.attr('href'), evt.data.parent, evt.data.settings)
				}
			})
		})
	};
	$.fn.carousel.scroll = function (a, b, c) {
		$curOfset = parseInt(b.find('ul').css("left").replace('px', ''));
		$newOfset = 0;
		switch (a) {
			case '#back':
				$newOfset = $curOfset + c['move'];
				if ($newOfset > 0) { $newOfset = 0; }
				$this.trigger('back');
				break;
			case '#fwd':
				$newOfset = $curOfset - c['move'];
				if ($newOfset < c['maxOfset']) {
					$newOfset = c['maxOfset']
				}
				$this.trigger('fwd');
				break;
		}
		b.find('ul').animate({ left: $newOfset }, c['opts'].speed, function () { $.fn.carousel.setControls(c, b); });
		c['opts'].onScroll(-$newOfset / c['itemWidth']);
		return true;
	};
	$.fn.carousel.setControls = function (a, b) {
		$back = b.find('.ctrl[href="#back"]');
		$fwd = b.find('.ctrl[href="#fwd"]');
		$back.removeClass('disabled');
		$fwd.removeClass('disabled');
		$ofset = b.find('ul').css("left").replace('px', '');
		if ($ofset == 0) {
			$back.addClass('disabled')
		}
		if ($ofset <= a['maxOfset']) {
			$fwd.addClass('disabled')
		}
		return true;
	};
	$.fn.carousel.defaults = {
		moveCount: 1,
		speed: 500,
		firstItemIndex: 0
	}
})(jQuery);
