var Ticker = new Class({

	STATIC_DURATION: 3000,
	TRANSITION_DURATION: 1000,
	
	timeoutVar: null,
	currentAnimation: null,

	initialize: function(containerId) {
		this.containerId=containerId;
	},
	
	load: function() {
		$(this.containerId).addClass("tickerjs");
		// Hide all items
		this.listItems = $A($(this.containerId).getElementsByTagName('li'));
		this.totalItems = this.listItems.length;
		this.hideAll();
		this.listItems.each(function(item) {
			item.addEvent('mouseover', this.handleMouseOver.bind(this));
			item.addEvent('mouseout', this.handleMouseOut.bind(this));
		}.bind(this));
		this.initializeAnimation();
	},
	
	hideAll: function() {
		this.listItems.each(function(item) {
			// Set opacity
			var hideNow = new Fx.Style(item, 'opacity').set(0);
			item.style.display = 'none';
		});
	},
	
	initializeAnimation: function() {
		this.currentItem = 0;
		if (this.totalItems>0) {
			this.fadeIn();
		}
	},
	
	fadeIn: function() {
		var item = this.listItems[this.currentItem];
		item.style.display = 'block';
		this.currentAnimation = new Fx.Style(item, 'opacity', {duration: this.TRANSITION_DURATION, onComplete: this.wait.bind(this)}).start(0,1);
	},
	
	wait:function() {
		this.currentAnimation = null;
		this.timeoutVar = window.setTimeout(this.fadeOut.bind(this), this.STATIC_DURATION);
	},
	
	fadeOut:function() {
		var item = this.listItems[this.currentItem];
		clearTimeout(this.timeoutVar);
		this.timeoutVar = null;
		this.currentAnimation = new Fx.Style(item, 'opacity', {duration: this.TRANSITION_DURATION, onComplete: this.nextItem.bind(this)}).start(1,0);
	},
	
	nextItem: function() {
		var item = this.listItems[this.currentItem];
		item.style.display = 'none';
		this.currentItem = (this.currentItem < this.totalItems-1) ? this.currentItem + 1 : 0;
		this.fadeIn();
	},
	
	handleMouseOver: function() {
		this.pauseAnimation();
	},
	
	handleMouseOut: function() {
		this.restartAnimation();
	},
	
	pauseAnimation: function() {
		if (this.timeoutVar!=null) {
			// In wait phase. Cancel timeout, but not null so can test in mouseout phase
			clearTimeout(this.timeoutVar);
		} else if (this.currentAnimation!=null) {
			this.currentAnimation.stop();
			var reveal = new Fx.Style(this.currentAnimation.element, 'opacity').set(1);
		}
	},
	
	restartAnimation: function() {
		// Always restart from 'wait' phase
		this.wait();
	}
	
});

var bbticker = new Ticker('ticker');