var CyclicBanners = {
	banners : new Array(),
	add : function(cyclicBanner) {
		CyclicBanners.banners[CyclicBanners.banners.length] = cyclicBanner; 
	},
	next : function(id) {
		for (var i=0;i<CyclicBanners.banners.length;i++) {
			var banner = CyclicBanners.banners[i];
			if (banner.id == id) banner.next(); 
		}
	}
};
function CyclicBanner(conf)
{
	if (!conf) return;
	this.images = conf.images ? conf.images : new Array();
	this.index = conf.index ? conf.index : 0;
	this.id = conf.id ? conf.id : 'cyclicBanner';
	this.timeout = conf.timeout ? conf.timeout : 10000;
	
	this.banner = document.getElementById(this.id);
	this.buttons = new Array();
	this.cyclicBanner = this;
	this.callback = null;
	this.fakeA = document.createElement('form');
	
	this.run = function() {
		if (!this.banner) return;
		CyclicBanners.add(this);
		this.banner.className = 'CyclicBanner';
		this.banner.cyclicBanner = this;
		this.addAction(this.banner, this.bannerClicked);
		for(var i=0;i<this.images.length;i++) {
			var button = document.getElementById(this.id + '_button_' + i);
			if (button) {
				this.buttons[this.buttons.length] = button;
				this.addAction(button, this.buttonAction);
				button.className = 'CyclicBanner_button';
				button.cyclicBanner = this;
			}
		}
		with (this.fakeA) {
			target = '_blank';
			class = 'CyclicBanner_fakeA';
			action = '#';
			method = 'get';
		}
		this.banner.parentNode.appendChild(this.fakeA);
		this.show(this.index);
		return this;
	};	
	
	this.bannerClicked = function() {
		this.cyclicBanner.fakeA.submit();
		return this;
	};
	this.next = function() {
		this.index++;
		this.show(this.index);
		return this;
	};
	this.prev = function() {
		this.index--;
		this.show(this.index);
		return this;
	};
	this.show = function(index) {
		this.index = index;
		if (this.index < 0) this.index = this.images.length;
		if (this.index >= this.images.length) this.index = 0;
		if (this.banner) {
			var image = this.images[this.index];
			this.banner.src = image.image;
			this.fakeA.action = image.url;
		}
		for (var i=0;i<this.buttons.length;i++) {
			this.buttons[i].className = 'CyclicBanner_button';
			if (i == index) this.buttons[i].className = 'CyclicBanner_button_selected';
		}
		clearTimeout(this.callback);
		this.callback = null;
		this.callback = setTimeout('CyclicBanners.next("' + this.id + '")', this.timeout);
		return this;
	};
	this.buttonAction = function() {
		var data = this.id.split('_button_');
		var index = parseInt(data[1], 10);
		this.cyclicBanner.show(index);
		return this.cyclicBanner;
	};
	this.addAction = function(element, action) {
		if (element.attachEvent) {
			element.attachEvent('onclick', action);
		} else {
			element.addEventListener('click', action, false);
		}
	};
	return this;
}
