var SlideShow = new Class({
	Implements: [Options],

	initialize: function (el, options) {
		this.setOptions(options);

		this.element  = el;
		this.viewport = el.getElement('.viewport');
		this.slide    = el.getElement('.slide');
		this.items    = el.getElements('.item');
		this.currentIndex = 0;

		var tweenOptions = {
			property: 'margin-top',
			'link': 'ignore',
			onStart: (function () {
				this.tweenRunning = true;
			}).bind(this),
			onComplete: (function () {
				this.tweenRunning = false;
			}).bind(this)
		}

		this.tween = new Fx.Tween(this.slide, tweenOptions);

		this.nextBtn = new Element('img', {'src': this.options.nextButton, 'class': 'next-btn'});
		this.prevBtn = new Element('img', {'src': this.options.previousButton, 'class': 'prev-btn inactive'});

		this.element.adopt(this.nextBtn, this.prevBtn);

		$$(this.nextBtn, this.prevBtn).addEvent('click', (function (evt) {
			var clickedElm = document.id(evt.target);

			if (clickedElm.hasClass('next-btn')) {
				this.showItem(this.currentIndex + 1);
			} else {
				this.showItem(this.currentIndex - 1);
			}
		}).bind(this));
	},
	
	showItem: function (index) {
		if (index < 0 || index >= this.items.length || this.tweenRunning) {
			return;
		}

		var viewportHeight = this.viewport.getSize().y;
		var newOffset = viewportHeight * index * -1;

		this.tween.start(newOffset);
		this.currentIndex = index;

		if (index == 0) {
			this.prevBtn.addClass('inactive');
		} else if (index == this.items.length - 1) {
			this.nextBtn.addClass('inactive');
		}

		if (index > 0 ) {
			this.prevBtn.removeClass('inactive');
		} else if (index < this.items.length - 1) {
			this.nextBtn.removeClass('inactive');
		}
	}
});

window.addEvent('domready', function () {
	$$('.slideshow').each(function (element) {
		var options = {
			'nextButton': '/images/carrousel-arrow-down.png',
			'previousButton': '/images/carrousel-arrow-up.png'};

		new SlideShow(element, options);
	});
});
