/*
 * ----------------------------------------------------------------------------------------------
 * 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, inst) {
	// 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.rotationSpeed = 4000;
	this.animationSpeed = 500;
	this.currIndex = 0;
	this.maxIndex = 0;
	this.timer = null;
	this.animating = false;

	// Method: init
	this.init = function() {
		var classRef = this;
		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.timer = setInterval(function() { classRef.change(false) }, this.rotationSpeed); // initialize 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
			if (newIndex >= this.maxIndex) {
				//newIndex = this.maxIndex + 1;
			}
			var currCarousel = $('#' + this.containerID + ' .carousel_item.active');
			var newCarousel = $('#' + this.containerID + ' .carousel_item')[newIndex];
			currCarousel.fadeOut(this.animationSpeed, function() {
				$(newCarousel).fadeIn(this.animationSpeed, function() {
					currCarousel.removeClass('active');
					$(newCarousel).addClass('active');
					classRef.currIndex = newIndex;
					classRef.animating = false;
				});
			});
			if (newIndex >= this.maxIndex) {
				clearInterval(this.timer);
			}
		}
	}
	this.init();
}



