/*
 * ----------------------------------------------------------------------------------------------
 * Class: Carousel containerID - string - The ID of the HTML element containing
 * the carousel items options - object - rotationSpeed - the speed that the
 * carousel autorotates at animationSpeed - the speed the carousel animates at
 * ----------------------------------------------------------------------------------------------
 */
function Carousel(containerID, options) {
	// store options
	this.options = options;

	// set variables
	this.containerID = containerID
	this.container = $('#' + this.containerID);
	this.rotationSpeed = (options.rotationSpeed) ? options.rotationSpeed : 5000;
	this.animationSpeed = (options.animationSpeed) ? options.animationSpeed
			: 500;
	this.currIndex = 0;
	this.maxIndex = 0;
	this.timer = null;
	this.animating = false;

	// Method: init
	this.init = function() {
		var classRef = this;

		// add event handlers to carousel nav items
		$('#' + this.containerID + ' .carousel_nav a').each(function(i) {
			$(this).bind("click", function(e) {
				classRef.change(i);
				clearInterval(classRef.timer);
				return false;
			});
		});

		this.maxIndex = $('#' + this.containerID + ' .carousel_item').length - 1; // find
		// number
		// of
		// carousel
		// items
		$('#' + this.containerID + ' .carousel_item:first').addClass('active')
				.css('display', 'block'); // show first carousel item
		$('#' + this.containerID + ' .carousel_nav').css('display', 'block'); // display
		// the
		// carousel
		// nav

		this.timer = setInterval(function() {
			classRef.change(false)
		}, this.rotationSpeed); // itialize the auto rotate timer
	}

	// Method: change
	this.change = function(newIndex) {
		if (!this.animating) {
			var classRef = this;
			this.animating = true;

			var newIndex = (newIndex === false) ? this.currIndex + 1 : newIndex; // determine
			// the
			// newIndex
			// if
			// auto
			// rotate
			// is
			// being
			// used
			newIndex = (newIndex > this.maxIndex) ? 0 : newIndex; // make sure
			// newIndex
			// doesn't
			// go past
			// the
			// maxIndex

			var currCarousel = $('#' + this.containerID + ' .carousel_item.active');
			var newCarousel = $('#' + this.containerID + ' .carousel_item')[newIndex];
			var currNav = $('#' + this.containerID + ' .carousel_nav li.active');
			var newNav = $('#' + this.containerID + ' .carousel_nav li')[newIndex];

			currCarousel.fadeOut(this.animationSpeed, function() {

				currNav.removeClass('active');
				$(newNav).addClass('active');

				$(newCarousel).fadeIn(this.animationSpeed, function() {
					currCarousel.removeClass('active');
					$(newCarousel).addClass('active');

					classRef.currIndex = newIndex;
					classRef.animating = false;
				});
			});
		}
	}

	this.init();
}



