(function ($) {
	$.fn.carousel = function (options) {
		var defaults = {
			nav: '#promo-nav',
			speed: 500
		};

		// Extend our default options with those provided.
		var opts = $.extend(defaults, options);

		var $carousel = $(this);

		$carousel.data('busy', false);

		// set container width, height and overflow. ascertain height from contained images
		var li = $carousel.find('ul li:first');

		var width = li.css('width');
		var unitlessWidth = parseInt(width.substr(0, width.length - 2));

		var offset = 0;

		var $current = $carousel.find('ul li.on')

		// store ref to currently on image
		$carousel.data('current', $current)

		// attach event to all nav anchors
		var $links = $(opts.nav).find('li');
		$links.hover(function() {

			//if carousel is busy, cancel previous animation
			var busy = $carousel.data('busy');

			$links.removeClass('on');
			$(this).addClass('on');

			if (busy) {
				$carousel.stop(true, true);
			}

			// find main related image from parent id
			var imageNumber = $(this).attr('id').substr(2);

			var $selected = $('#pi' + imageNumber)
			var $current = $carousel.data('current')

			//if we are on the currently visible item, do nothing
			if ($current.attr('id') === $selected.attr('id')) {
				return false;
			}

			// flag as busy
			$carousel.data('busy', true);

			// scroll to selected image
			var offset = (imageNumber -1) * unitlessWidth;

			$carousel.animate({
					'left': (0 - offset)
				},
				opts.speed,
				function() {
					// update current ref
					$carousel.data('current', $selected);
					$carousel.data('busy', false);
				}
			);

			return false;
		})

  };
})(jQuery);
