var Carousel = Class.create({

	'initialize': function()
	{
		this.cover = $('sidebartop').down(1);
		this.coverWidth = this.cover.getWidth();

		this.bar = $('sidebartop').down(2);
		this.items = this.bar.select('p');
		this.numItems  = this.items.length;
		this.itemWidth = this.items[0].getWidth();

		this.numShown = Math.ceil(this.coverWidth / this.itemWidth);
		this.moveNum = Math.min(this.numShown, this.numItems - this.numShown);
		this.moveDistance = this.moveNum * this.itemWidth;

		this.currentPos = 0;
		this.autoInterval = 7000;

		$('carousel-left').observe('click', this.moveRight.bind(this));
		$('carousel-right').observe('click', this.moveLeft.bind(this));

		this.autoTimeout = window.setTimeout(this.moveLeft.bind(this), this.autoInterval);
	},

	'moveLeft': function()
	{
		window.clearTimeout(this.autoTimeout);
		this.autoTimeout = window.setTimeout(this.moveLeft.bind(this), this.autoInterval);

		if (this.currentPos + this.numShown + this.moveNum >= this.numItems) {

			var resortedItems = this.items.slice(this.currentPos).concat(this.items.slice(0, this.currentPos));
			resortedItems.each(function(e){
				this.bar.removeChild(e);
				this.bar.appendChild(e);
			}.bind(this));
			this.items = resortedItems;

			this.bar.setStyle({'left': '0px'});
			this.currentPos = 0;
		}

		new Effect.Move(this.bar, {
			'x': - this.moveDistance,
			'y': 0,
			'mode': 'relative',
			'duration': 0.6,
			'queue': {
				'position': 'end',
				'scope': 'assetlistscope',
				'limit': 1
			},
			'afterFinish': function () {this.currentPos += this.moveNum;}.bind(this)
		});
	},

	'moveRight': function()
	{
		window.clearTimeout(this.autoTimeout);
		this.autoTimeout = window.setTimeout(this.moveLeft.bind(this), this.autoInterval);

		if (this.currentPos < this.moveNum) {

			var resortedItems = this.items.slice(this.currentPos + this.numShown).concat(this.items.slice(0, this.currentPos + this.numShown));
			resortedItems.each(function(e) {
				this.bar.removeChild(e);
				this.bar.appendChild(e);
			}.bind(this));
			this.items = resortedItems;

			this.bar.setStyle({'left': '-' + this.itemWidth * (this.numItems - this.numShown) + 'px'});
			this.currentPos = this.numItems - this.numShown;
		}

		new Effect.Move(this.bar, {
			'x': this.moveDistance,
			'y': 0,
			'mode': 'relative',
			'duration': 0.6,
			'queue': {
				'position': 'end',
				'scope': 'assetlistscope',
				'limit': 1
			},
			'afterFinish': function () {this.currentPos -= this.moveNum;}.bind(this)
		});
	}
});

document.observe('dom:loaded', function() {
	window.myCarousel = new Carousel();
});
