var ArtCarousel = new Class({
	
	controls : new Object({
		container : null,
		next : null,
		prev : null,
		earliest : null,
		latest : null,
		button : null
	}),
	timer : null,
	play : true,
	mainID : '',
	currentIdx : 0,
	period : 5,
	
	initialize : function(containerID)
	{
		this.mainID = containerID;
		var labels = ['container', 'next', 'prev', 'earliest', 'latest', 'button'];
		var ok = true;
		labels.each(function(item){
			var el_id = containerID + (item == 'container' ? "" : "_" + item);
			var el = $(el_id);
			if (!el)
			{
				ok = false;
				return;
			}
			this.controls[item] = el;
		}, this);
		if (!ok)
			return;
		
		
		this.controls.next.addEvent('click', function(){ this.togglePlay(false); this.changeItem('next'); return false; }.bind(this) );
		this.controls.prev.addEvent('click', function(){ this.togglePlay(false); this.changeItem('prev'); return false; }.bind(this) );
		this.controls.earliest.addEvent('click', function(){ this.togglePlay(false); this.changeItem('earliest'); return false; }.bind(this) );
		this.controls.latest.addEvent('click', function(){ this.togglePlay(false); this.changeItem('latest'); return false; }.bind(this) );
		
		this.controls.button.addEvent('click', function(){this.togglePlay(); return false;}.bind(this));
		
		this.setCurrentItem();
		this.startTimer();
	},
	
	changeItem : function(mode)
	{
		var params = new Hash({
			'mode' : mode,
			'current' : this.currentIdx
		});
		var req = new Request.HTML({
			url : '/carousel.html',
			method : 'post',
			data : params.toQueryString(),
			update : this.controls.container,
			onSuccess : function() {
				this.setCurrentItem();
				if (this.play)
					this.startTimer();
			}.bind(this)
		}).send();
	},
	
	setCurrentItem : function()
	{
		var el = $(this.mainID + "_current");
		if (el)
			this.currentIdx = el.get('text') - 0;
	},
	
	togglePlay : function(mode)
	{
		if (mode == undefined)
			mode = !this.play;
		this.play = mode;
		if (this.play)
		{
			this.startTimer();
			var img = this.controls.button.getElement('img');
			if (img)
				img.set('src', '/assets/media/stop.gif');
		}
		else
		{
			this.stopTimer();
			var img = this.controls.button.getElement('img');
			if (img)
				img.set('src', '/assets/media/play.gif');
		}
	},
	
	startTimer : function()
	{
		this.timer = this.changeItem.delay(this.period * 1000, this, 'next');
	},
	
	stopTimer : function()
	{
		clearTimeout(this.timer);
	}
});
