var Coverflow = new Class({
	
	initialize: function(container, prev, next, sidebar)
	{
		if(!container) return;
		this.itemWidth = 251;
		this.container = container;
		this.scrollContainer = container.getFirst();
		this.direction = 0;
		this.running = false;
		this.enabled = true;
		this.setupContainer();
		
		this.changeImage = false;
		if(sidebar)
		{
			this.changeImage = true;
			this.sidebarImage = sidebar;
			var t = this;
			(function() {t.checkImage()}).delay(250);
		}
		
		if(!this.enabled)
		{
			prev.destroy();
			next.destroy();
			return;
		}
		
		prev.addEvent('click', this.prev.bindWithEvent(this));
		next.addEvent('click', this.next.bindWithEvent(this));
		
		this.fx = new Fx.Tween(this.scrollContainer, {
			property: 'left',
			onComplete: this.fxComplete.bind(this)
		});
		
	},
	
	setupContainer: function()
	{
		var childs = this.scrollContainer.getChildren();
		this.scrollContainer.setStyle('width', this.itemWidth * childs.length);
		if(childs.length < 4)
		{
			this.enabled = false;
		}
		childs.each(function(item) {
			var f = item.getElement('.coverflow-item-flash');
			if(f)
			{
				var options = f.retrieve('flash');
				UFO.create(options, f.get('id'));
			}
		});
	},
	
	prev: function(e) {
		e.stop();
		if(this.running) return;
		this.direction = -1;
		this.scrollContainer.getLast().inject(this.scrollContainer, 'top');
		this.scrollContainer.setStyle('left', this.itemWidth * -1);
		this.fx.start(0);
		this.running = true;
	},
	next: function(e) {
		e.stop();
		if(this.running) return;
		this.direction = 1;
		this.fx.start(this.itemWidth * -1);
		this.running = true;
	},
	fxComplete:function()
	{
		if(this.direction == 1)
		{
			this.scrollContainer.getFirst().inject(this.scrollContainer, 'bottom');
			this.scrollContainer.setStyle('left', 0);
		}
		this.running = false;
		this.checkImage();
	},
	checkImage: function()
	{
		if(!this.changeImage) return;
		this.sidebarImage.set('html', this.scrollContainer.getFirst().getNext().getElement('div.coverflow-item-image').get('html'));
	}
});