
var BillBoard = new Class({
	Implements: [Options, Events, Chain],
	
	options: {
		start: 0,
		delay: 6,	//in seconds. 0 for off
		offset: {x: 1, y: 40}
	},

	initialize: function(options){
		this.setOptions(options);
		if(!$('billboard')) return;
		
		this.billboards = $$('#billboard div.showcase');
		if (this.billboards.length < 2) return;
		
		this.navigation = new Element('ul');
		this.navigation.inject($$('#billboard div.navigation')[0]);
		new Element('li', {
			'class': 'prev',
			'events': {
				'click': function(e) {
					e.stop();
					this.prev();
				}.bind(this)
			}
		}).inject(this.navigation);
		
		this.billboards.each(function(el, i){
			var li = new Element('li', {
				'events': {
					'click': function(e) {
						e.stop();
						this.switchto(i);
					}.bind(this)
				}
			});
			if (i == this.options.start) li.addClass('active');
			li.inject(this.navigation);
		}.bind(this));
		
		new Element('li', {
			'class': 'next',
			'events': {
				'click': function(e) {
					e.stop();
					this.next();
				}.bind(this)
			}
		}).inject(this.navigation);
				
		this.set(0);
		this.loading = false;
		this.setauto();
	},

	setauto: function() {
		if (this.options.delay.toInt() <= 0) return;
		if(this._auto) $clear(this._auto);
		this._auto = this.next.delay(this.options.delay * 1000, this);
	},

	set: function(i, change){
		if (i == this.active) return;
		change = (change===false?false:true);
		this.active = i;
		this.navigation.getElements('li').each(function(el){ el.removeClass('active'); }.bind(this));
		this.navigation.getElements('li')[(i+1)].addClass('active');
		
		if (!change) return;
		this.billboards.each(function(el){ el.addClass('hidden'); }.bind(this));
		this.billboards[i].removeClass('hidden');
	},

	switchto: function(i){
		if(this.loading || this.active == i) return;
		this.loading = true;
		var old = this.active;
		var cords = this.billboards[old].getCoordinates();
		this.fxOld = new Fx.Tween(this.billboards[old], {duration: 500});
		this.fxNew = new Fx.Tween(this.billboards[i], {duration: 500});
		
		this.set(i, false)
		this.billboards[i].set('opacity', 0);
		this.billboards[i].setStyles({
			'position': 'absolute',
			'top': cords.top.toInt() - this.options.offset.y,
			'left': cords.left.toInt() - this.options.offset.x
		});
		this.billboards[i].removeClass('hidden');
		this.fxOld.start('opacity', 0).chain(function(){
			this.billboards[old].addClass('hidden');
			this.billboards[old].removeProperty('style');
		}.bind(this));
		this.fxNew.start('opacity', 1).chain(function(){
			this.billboards[i].removeProperty('style');
			this.loading = false;
			this.setauto();
		}.bind(this));
	},

	prev: function(){
		var i = this.active - 1;
		if(i < 0) i = this.billboards.length - 1;
		this.switchto(i);
	},

	next: function(){
		var i = this.active + 1;
		if(i >= this.billboards.length) i = 0;
		this.switchto(i);
	}
});

window.addEvent('domready', function(){ new BillBoard(); });
