
var MagmaGallery = {
	currentIndex: 0,
	fadeTimeout: null,
	activeLayer: 0,

	imageDuration: 3000,
	effectDuration: 2000,

	init: function() {
		$("div.gallery_item").hide();

		// show first image
		$("#gallery_img" + this.activeLayer)[0].src = $(".gallery_item > .gallery_image")[0].src;
		$("#breadcrumb").html($(".gallery_item > .gallery_head:eq(0)").html());
		$("#gallery_details").html($(".gallery_item > .gallery_comment:eq(0)").html());
		$("#gallery_img1").hide();

		if($(".gallery_item > .gallery_image").length > 1) {
			// set first timeout
			var that = this;
			this.fadeTimeout = window.setTimeout(function() { that.switchTo(that.currentIndex + 1); }, this.imageDuration);
		} else {
			// hide controls
			$("#slide_opacity").hide();
			$("#slide_arrows").hide();
		}
	},

	switchTo: function(index) {
		var that = this;

		if(index < 0)
			index = $(".gallery_item > .gallery_image") - 1;

		this.currentIndex = index % $(".gallery_item > .gallery_image").length;

		// clear timeout
		window.clearTimeout(this.fadeTimeout);

		// fade image
		$("#gallery_img" + ((this.activeLayer + 1) % 2))[0].src = $(".gallery_item > .gallery_image")[this.currentIndex].src;
		$("#gallery_img" + ((this.activeLayer + 1) % 2)).fadeIn(this.effectDuration, function() {
			$("#breadcrumb").html($(".gallery_item > .gallery_head:eq(" + that.currentIndex + ")").html());
			$("#gallery_details").html($(".gallery_item > .gallery_comment:eq(" + that.currentIndex + ")").html());
		});
		$("#gallery_img" + this.activeLayer % 2).fadeOut(this.effectDuration);
		this.activeLayer++;

		// set new timeout		
		this.fadeTimeout = window.setTimeout(function() { that.switchTo(that.currentIndex + 1); }, this.imageDuration + this.effectDuration);
	},

	forward: function() {
		this.switchTo(this.currentIndex + 1);
	},

	backward: function() {
		this.switchTo(this.currentIndex - 1);
	}
}


