var Carousel = Class.create({
	list: null, active: null, executer: null, interval: 4, index: 0,
	initialize: function initialize(list, interval, skiplinks) {
		if(interval && Object.isNumber(interval)) {
			this.interval = interval;
		}
		if((this.list = $(list))) {
			var items = this.list.select('div.carouselfoto').invoke('hide');
			this.show(items[0]);
			this.start();
		}
		if($(skiplinks)) {
			this.skiplinks = $(skiplinks).select('a').invoke('observe', 'click', function(event) {
				event.stop();
				var id = event.findElement('a').readAttribute('href').substr(1);
				this.stop();
				this.hide(this.active);
				this.index = $(id).previousSiblings().size();
				this.show($(id));
				this.start();
			}.bind(this));
		}
	},
	hide: function hide(element) {
		new Effect.Fade(element, {
			duration: 1,
			afterFinish: function updateSkipLinks() {
				this.skiplinks.invoke('removeClassName', 'active');
				this.skiplinks[this.index].addClassName('active');
			}.bind(this)
		});
	},
	show: function show(element) {
		this.active = element;
		new Effect.Appear(this.active, {
			duration: 1
		});
		this.list.select('div.carouselfoto').invoke('removeClassName', 'active');
		this.active.addClassName('active');
	},
	stop: function stop() {
		if(this.executer) this.executer.stop();
	},
	start: function start() {
		this.executer = new PeriodicalExecuter(this.next.bind(this), this.interval);
	},
	next: function next(pe) {
		var next;
		// hide current
		this.hide(this.active);
		// show next
		if( (next = this.active.next('div.carouselfoto')) ) {
			this.index++;
			this.show(next);
		} else {
			this.index = 0;
			this.show(this.active.adjacent('div.carouselfoto').first());
		}
	}
});

document.observe('dom:loaded', function() {
	$(document.body).removeClassName('no-js');
	$$('div#galleryfotos').each(function(container) {
		new Carousel(container, 6, container.previous('ul.bolletjes'));
	});
});
