(function() {
	var foo = function() {
		var container = document.getElementById('carousel').getElementsByTagName('ul')[0],
			elements = $A(container.getElementsByTagName('li')),
			element = null,
			width = 10,
			need = $('carousel').offsetWidth,
			x = 0,
			y = 0;

		// calculate ul width..
		while (element = elements[x++]) {
			width += element.offsetWidth;
		}

		// add some gap if needed..
		while (width < need) {
			width += (element = elements[y++]).offsetWidth;
			container.appendChild(element.cloneNode(true));
			if (y >= elements.length) {
				y = 0;
			}
		}

		// store container and elements..
		this.elements = (this.container = container).getElementsByTagName('li');

		// bind the next control..
		$('control_next').observe('click', function(evt) {
			if (!this.moving) {
				new Effect.Move(container, {
					x: -this.elements[0].offsetWidth,
					duration: .555,
					beforeSetupInternal: function() {
						this.moving = true;
						this.container.appendChild(this.container.firstChild.cloneNode(true));
					}.bind(this),
					afterFinishInternal: function() {
						this.container.style.left = (parseInt(this.container.style.left) + this.container.firstChild.offsetWidth) + 'px';
						this.container.removeChild(this.container.firstChild);
						this.elements = $A(container.getElementsByTagName('li'));
						this.moving = false;
					}.bind(this)
				});
			}
		}.bind(this));

		// bind the prev control..
		$('control_prev').observe('click', function(evt) {
			if (!this.moving) {
				new Effect.Move(container, {
					x: this.elements[this.elements.length - 1].offsetWidth,
					duration: .555,
					beforeSetupInternal: function() {
						this.moving = true;
						this.container.insertBefore(this.container.lastChild.cloneNode(true), this.container.firstChild);
						this.container.style.left = (parseInt(this.container.style.left || 0) - this.container.lastChild.offsetWidth) + 'px';
					}.bind(this),
					afterFinishInternal: function() {
						this.container.removeChild(this.container.lastChild);
						this.elements = $A(container.getElementsByTagName('li'));
						this.moving = false;
					}.bind(this)
				});
			}
		}.bind(this));
	};

	// put that crap on the load stack..
	document.observe('dom:loaded', foo.bind(foo));
})();
