function Carousel(el, autoRotate) {
	this.el = $(el);
	this.nextEl = $('#next');
	this.prevEl = $('#previous');
	
	this.currentFrame = 0;
	
	this.frames = this.el.find('.frame');
		
	this.el.css('overflow', 'hidden');
	
	var that = this;
	this.nextEl.click(function() {
		that.next();
		return false;
	});
	
	this.prevEl.click(function() {
		that.prev();
		return false;
	});
	
	this.duration = 1000;
	this.easeFunc = 'easeOutCubic';
	
	this.transitioning = false;
	
	this.setAutoRotate(autoRotate);
}

Carousel.showText = function(frame) {
	frame.find('.text').animate({opacity:1}, 2000);
}

Carousel.prototype = {
	setAutoRotate: function(duration) {
		this.autoRotate = duration;
		
		if (this.autoRotate) {
			var that = this;
			this.autoRotateTimer = setInterval(function() {
				that.next();
			}, duration);
		}
		else if (this.autoRotateTimer) {
			clearInterval(this.autoRotateTimer);
		}
	},
	next: function() {
		if (this.transitioning) return;
		this.transitioning = true;
		var frame = $(this.frames.get(this.currentFrame));
		this.currentFrame = (this.currentFrame + 1)  % this.frames.size();
		var nextFrame = $(this.frames.get(this.currentFrame));
		
		// Slide this frame out
		frame.animate({left:-frame.width()}, this.duration, this.easeFunc);
		
		// Slide the next frame in
		var that = this;
		nextFrame.css({left:nextFrame.width(), display:'block'}).find('.text').css('opacity', 0);
		nextFrame.animate({left:0}, this.duration, this.easeFunc).queue(function() {
			$(this).dequeue();
			that.transitioning = false;
			Carousel.showText(nextFrame);
		});
	},
	prev: function() {
		if (this.transitioning) return;
		this.transitioning = true;

		var frame = $(this.frames.get(this.currentFrame));
		this.currentFrame --;
		if (this.currentFrame < 0) this.currentFrame = this.frames.size() - 1;
		var nextFrame = $(this.frames.get(this.currentFrame));
		
		// Slide this frame out
		frame.animate({left:frame.width()}, this.duration, this.easeFunc);
		
		// Slide the next frame in
		var that = this;
		nextFrame.css({left:-nextFrame.width(), display:'block'}).find('.text').css('opacity', 0);
		nextFrame.animate({left:0}, this.duration, this.easeFunc).queue(function() {
			$(this).dequeue();
			that.transitioning = false;
			Carousel.showText(nextFrame);
		});
	}
};
