var Impressions = new Class({
	options: {
		'positions': 1,
		'transition': Fx.Transitions.Quad.easeInOut,
		'duration': 5000,
		'interval': 9000
	},

	elements: [],

	playlist: [],

	current: [],

	zindex: 999999,
	
	lastPosition: null,

	initialize: function(selector, options){
		this.setOptions(options);

		$$(selector).each(function(el, i){
			 this.elements.include(el);
			 el.setStyle('display', 'none');
			 el.setStyle('z-index', 100);
		}.bind(this));

		this.elemWidth  = $$(selector)[0].getFirst().getProperty('width');
		for(i=0; i < this.options.positions; i++) {
			this.display(i);
		}

		this.start();
	},
	
	start: function() {
		this.display.pass([this._getPosition(), true], this).delay(2000);
		this.start.pass([], this).delay(this.options.interval);
	},

	display: function(position, animate) {
		var el = this._getRandom();
		el.setStyle('position', 'absolute');
		el.setStyle('left', position*this.elemWidth);
		el.setStyle('top', 0);
		el.setStyle('z-index', this.zindex);
		this.zindex += 100;

		if(animate) {
			var fx = new Fx.Style(el, 'opacity', {duration: this.options.duration, transition: this.options.transition});
			fx.set(0);
			el.setStyle('display', 'block');
			fx.start(0, 1).
				chain(function(){ 
					this.current[position] = el; 
				}.bind(this)
			);
		} else {
			el.setStyle('display', 'block');
			this.current[position] = el; 
		}
	},

	_getPosition: function() {
		var newPos = $random(0, (this.options.positions-1));
		if(newPos == this.lastPosition) {
			return this._getPosition();
		} else {
			this.lastPosition = newPos;
			return newPos;
		}
	},

	_getRandom: function() {
		if(this.playlist.length == 0) { 
			this.playlist = [];
			this.playlist = this.elements.copy();
		}
		
		var element = this.playlist.getRandom();
		this.playlist.remove(element);
		//console.log('Playlist: '+this.playlist.length);
		return element;
	}
});
Impressions.implement(new Options);

window.addEvent('domready', function(){
	new MultiBox('mb', {useOverlay: true});
});

window.addEvent('load', function(){
	new Impressions("#impressions li", {positions: 4});
});
