var Site = {
	initialize: function() {
		var galleries = $(document.body).getElements(".gallery");
		galleries.each(function(gallery) {
			new Carousel(gallery);
		});
	}
};

/**
 * Carousel
 */
var Carousel = new Class({
	initialize: function(element) {
		this.element = $(element);

		this.wrap = this.element.getElement(".wrap");

		this.width = 475; // this.wrap.getCoordinates().width;
		this.position = this.wrap.getScroll();

		this.items = this.wrap.getElement("ul");
		this.activeItem = this.items.getFirst();

		this.scroll = new Fx.Scroll(this.wrap);

		var navigation = new Element("p", {"class": "navigation"}).inject(this.element);

		this.previousLink = new Element("a", {
			"href": "#",
			"class": "previous-link",
			"html": "<span>Vorige</span>",
			"events": {
				"click": this.previousClick.bindWithEvent(this)
			}
		}).inject(navigation);

		this.nextLink = new Element("a", {
			"href": "#",
			"class": "next-link",
			"html": "<span>Volgende</span>",
			"events": {
				"click": this.nextClick.bindWithEvent(this)
			}
		}).inject(navigation);

		this.updateNavigation();
    },

	next: function() {
		this.to(this.activeItem.getNext(), this.width, 0);
	},

	previous: function() {
		this.to(this.activeItem.getPrevious(), -this.width, 0);
	},

	to: function(item, deltaX, deltaY) {
		if(item) {
			this.activeItem = item;
			this.position.x += deltaX;
			this.position.y += deltaY;
			this.scroll.start(this.position.x, 0);
		}

		this.updateNavigation();
	},

	updateNavigation: function() {
		if(this.activeItem) {
			if(this.activeItem.getNext()) {
				this.nextLink.removeClass("disabled");
			} else {
				this.nextLink.addClass("disabled");
			}

			if(this.activeItem.getPrevious()) {
				this.previousLink.removeClass("disabled");
			} else {
				this.previousLink.addClass("disabled");
			}
		} else {
			this.nextLink.addClass("disabled");
			this.previousLink.addClass("disabled");
		}
	},

	nextClick: function(event) {
		event.preventDefault();

		this.next();
	},

	previousClick: function(event) {
		event.preventDefault();

		this.previous();
	}
});

window.addEvent("domready", Site.initialize);