jQuery.noConflict();

(function($) {

/**
 * Headlines will rotate through all elements on the page
 * with a class of 'headline' and 'teaser',
 * highlighting the headline and displaying the teaser for each
 * with a nice fade effect.
 *
 */
Headlines = function(fadetime, delay, on, off)
{	
	/* Seed some values */
	this.index = -1;
	this.headlines = $('.headline');
	this.teasers = $('.teaser');
	this.duration = fadetime;
	this.delay = delay;
	this.milliseconds = 50;
	this.on = (on == null || on == '') ? '#FFFF88' : on;
	this.off = off; // off can be null

	/* Hide all the teasers, initially */
	$('.teaser:visible').hide();
	this.headlines.eq(0).highlightFade({ 
		start: this.on, 
		end: this.off, 
		speed: this.duration * 10 // this seems to look "right"
	});
	this.teasers.eq(0).fadeIn(this.duration);

	/* Start the fade */
	this._timer();
}

Headlines.prototype = {
	_fade: function() {
		if (this.last > -1) {
			this.teasers.eq(this.index).hide(this.duration);
			var _this = this;
			this.teasers.eq(this.last).fadeOut(this.duration, function() {
				_this.teasers.eq(_this.index).fadeIn(_this.duration);
				_this.headlines.eq(_this.index).highlightFade({ 
					start: _this.on, 
					end: _this.off, 
					speed: _this.duration * 10 // this seems to look "right"
				});
			});
		}
		/* clear the first fader */
		clearInterval(this.timer1);

		var _this = this;
		this.timer2 = setInterval(function() { _this._timer() }, _this.delay);
	},
	_timer: function() {
		/* clear the second fader, if it's running */
		if (this.timer2) clearInterval(this.timer2);

		this.last = this.index;
		this.index++;
		/* Reset the counter if we're past the end of the array */
		if (this.index > this.teasers.length - 1) this.index = 0;

		var _this = this;
		this.timer1 = setInterval(function() { _this._fade() }, _this.milliseconds);
	},
	_jump: function(index) {
		/* Don't stop for OOB indices */
		if (!this.teasers.eq(index)) return;
		
		if (this.timer1) clearInterval(this.timer1);
		if (this.timer2) clearInterval(this.timer2);
		$('.teaser:visible').hide();
		this.headlines.css('background-color', this.off);
		this.headlines.eq(index).css('background-color', this.on);
		this.teasers.eq(index).show();
		
		this.index = index;
		if (this.index - 1 < 0) {
			this.last = this.teasers.length - 1;
		} else {
			this.last = this.index - 1;
		}
	},
	pause: function() {
		this.jump(this.index);
	},
	play: function() {
		this._fade();
	}
}

})(jQuery)