/**
 * @author bentaber
 * @classDescription QuoteRotator
 * @constructor
 * 
 * Dumb rules:
 * 
 * Always show two at once.
 * Files are saved in an order that makes sense. So just loop through in order
 * Start randomly within the order.
 * 
 * When showing one, if two are displayed, remove the longest visible
 * 
 */

var QuoteRotator = function() {
	this.quotes = [];
	this.visibleQuotes = [];
	
	this.timeouts = [];	
	this.fader = new Fader();
	
	for (var i=0; i<this.QUOTE_COUNT; i++) {
		this.quotes.push({
			src: this.PATH + i + this.FILE_TYPE,
			isVisible: false
		});
	}
	
	this.displayedQuoteIdx = Math.round(Math.random() * (this.quotes.length - 1));
	this.elContainer = document.getElementById(this.EL_CONTAINER_ID); 
};

QuoteRotator.prototype.EL_CONTAINER_ID = "quoteContainer";
QuoteRotator.prototype.MAX_SIMULTANEOUS_DISPLAYED = 2;
QuoteRotator.prototype.QUOTE_COUNT = 50;
QuoteRotator.prototype.FILE_TYPE = ".png";
QuoteRotator.prototype.PATH = "common/img/quotes/quote_";
QuoteRotator.prototype.CSS_CLASS = "people-quote";
QuoteRotator.prototype.QUOTE_DISPLAY_TIME = 9000;

QuoteRotator.prototype.setSpeed = function(speed) {
	this.fader.INTERVAL = speed.interval;
	this.fader.FRAME_TIME = speed.frameTime;
	this.QUOTE_DISPLAY_TIME = speed.quoteDisplayTime;
	
	this.reset();
};

QuoteRotator.prototype.showNextQuote = function() {
	if (this.MAX_SIMULTANEOUS_DISPLAYED == this.visibleQuotes.length) {
		// hide first quote, move second quote to first pos
		this.removeQuote(this.visibleQuotes.shift());	
	}
	
	var quote = this.quotes[this.displayedQuoteIdx++ % this.quotes.length];
	this.showQuote(quote);
};

QuoteRotator.prototype.showQuote = function(quote) {
	quote.el = Element.create("img", { 
		src: quote.src,
		classname: this.CSS_CLASS 
	}, null, this.elContainer);

	this.visibleQuotes.push(quote);
	this.fader.fadeIn(quote.el);
	
	// show next quote
	var theQuoteRotator = this;
	this.timeouts.push(setTimeout(
		function() {
			theQuoteRotator.showNextQuote();		
		},
		this.QUOTE_DISPLAY_TIME
	));
};

QuoteRotator.prototype.removeQuote = function(quote) {
	this.fader.fadeOut(quote.el, true);
	
	//delete quote.el;
};

QuoteRotator.prototype.reset = function() {
	for (var i=0; i<this.timeouts.length; i++) {
		clearTimeout(this.timeouts[i]);
	}
	this.timeouts = [];
	
	this.showNextQuote();
};
