var Gallery = new Class({
	Implements: [Options],
	options: {
		interval: 5000,
		duration: 500
	},

	/**
	 * Constructor
	 * @param {Object} element
	 */
	initialize: function (element) {
		this._element = document.id(element);
		this._items   = this._element.getElements('.item');
		this._slide   = this._element.getElement('.slide');
		this._currentItem = 0;
		this._tween   = new Fx.Tween(this._slide, {
			'property': 'margin-left'
		});

		//set the appropriate width for the slider
		var viewportWidth = this._slide.getParent().getSize().x
		var slideWidth = this._items.length * viewportWidth;

		this._slide.setStyle('width', slideWidth);

		if (this._items.length > 1) {
			this._timer = window.setInterval((function () {
				this.slideTo(this._currentItem+1);
			}).bind(this), this.options.interval);
		}
	},

	/**
	 * Slide the slide to an arbitrary index
	 * @param {Object} index
	 */
	slideTo: function (itemIndex) {
		if (itemIndex == this._items.length) itemIndex = 0;

		var leap, duration, offset;

		leap = itemIndex - this._currentItem;
		leap = leap < 0 ? leap * -1 : leap;
		duration = this.options.duration * leap;
		offset = itemIndex * 664;
		
		this._tween.options.duration = duration;
		this._tween.start(offset * -1);
		this._currentItem = itemIndex;
	}
});

window.addEvent('domready', function () {
	$$('.gallery').each(function (el) {
		new Gallery(el);
	});
});

