var Alternating = {
	_count: 0,
	load: function() {
		$$('.abox').each(function(ele, pos) {
			if(!ele.id) ele.id = "alternating-box-" + Alternating._count++;
			new Alternating.Box(ele.id);
		});
	}
};

Alternating.Box = Class.create();
Object.extend(Alternating.Box.prototype, {
	initialize: function(id, opt) {
		this._cookies = new CookieJar();
		this._current = 0;
		this._elements = new Array();
		this._control = null;
		this._controls = new Array();
		this._executor = null;
		var control = null;
		var length = 0;
		
		var cookieCurrent = this._cookies.get('alternating_header');
		if(cookieCurrent)
			this._current = cookieCurrent;
		
		$(id).next = this.next.bind(this);
		$(id).previous = this.previous.bind(this);
		$(id).selekt = this.select.bind(this);
		
		$(id).select('.abox_control').each(function(ele, pos) {
			this._control = ele;	
		}.bind(this));
		
		var regex = /url\((.*)\)/;
		$(id).select('div').each(function( ele, pos ) {
			if(bg = regex.exec(ele.style.background)) {
				img = new Image();
				img.src = bg[1];
			}
		});
		
		$(id).select('.abox_element').each(function(ele, pos) {
			this._elements.push(ele);
			length = this._elements.length;
			control = new Element('li');
			if(ele.hasClassName('current')) {
				this._current = length;
				control.addClassName('current');
			}
			control.update(length);
			control.abox_id = length-1;
			control.observe('click', function(event) {
				$(id).selekt(event.element().abox_id);
			}.bind(this));
			this._control.appendChild(control);
			this._controls.push(control);
			
			//new Effect.Fade(ele, {to: .01, duration: 0});
		}.bind(this));
		this.draw();
	},
	
	next: function() {
		this._current++;
		this.draw();
	},
	
	previous: function() {
		this._current--;
		this.draw();
	},
	
	select: function(num) {
		this._current = num-1;
		this.next();
	},
	
	draw: function() {
		if(this._executor != null) this._executor.stop();
		this._cookies.remove('alternating_header');
		this._cookies.put('alternating_header', this._current);
		this._executor = new PeriodicalExecuter(this.next.bind(this), this.options.speed)
		this._elements.each(function(ele, pos) {
			//if(this._current !== pos) new Effect.Fade(ele, {to: 0, duration: 0});
			ele.removeClassName('current');
		});
		this._controls.each(function(ele, pos) {
			ele.removeClassName('current');
		});
		
		if(this._elements[this._current] != undefined) {
			this._elements[this._current].addClassName('current');
			this._controls[this._current].addClassName('current');
			//new Effect.Fade(this._elements[this._current], {to: 1, from: 0, duration: 1});
		} else if(this._elements[0] != undefined) {
			this._current = 0;
			this._elements[this._current].addClassName('current');
			this._controls[this._current].addClassName('current');
			//new Effect.Fade(this._elements[this._current], {to: 1, from: 0, duration: 1});
		} else { return; }
		
	},
	
	options: {
		speed: 14
	}
});