
var MagmaSlideshow = {
	prefix: '',
	images: null,
	currentIndex: 0,
	fadeTimeout: null,
	activeLayer: 0,

	imageDuration: 3000,
	effectDuration: 2000,

	init: function(id, imgs) {
		this.prefix = id;
		this.images = imgs;

		// show first image
		$("#" + this.prefix + "img" + this.activeLayer)[0].src = this.images[0];

		if(this.images.length > 1) {
			// initialize buttons
			for(var i = 0; i < this.images.length; i++) {
				$("#" + this.prefix + "selectors").append('<a href="javascript:MagmaSlideshow.fadeTo(' + i + ');" id="' + this.prefix + '_button' + i + '" class="selector"></a>');
			}
			$("#" + this.prefix + "_button0").addClass("active");

			// initialize arrows


			// preload images
			for(var i = 0; i < this.images.length; i++) {
				var img = new Image();
				img.src = this.images[i];
			}

			// set first timeout
			$("#" + this.prefix + "img" + (this.activeLayer + 1)).fadeOut(10);
			var that = this;
			this.fadeTimeout = window.setTimeout(function() { that.fadeTo(that.currentIndex + 1); }, this.imageDuration);
		} else {
			// hide controls
			$("#" + this.prefix + "opacity").hide();
			$("#" + this.prefix + "selectors").hide();
			$("#" + this.prefix + "arrows").hide();
		}
	},

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

		if(index < 0)
			index = this.images.length - 1;

		this.currentIndex = index % this.images.length;

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

		// fade image
		$("#" + this.prefix + "img" + ((this.activeLayer + 1) % 2))[0].src = this.images[this.currentIndex];
		$("#" + this.prefix + "img" + ((this.activeLayer + 1) % 2)).fadeIn(this.effectDuration, function() { $(".selector").removeClass("active"); $("#" + that.prefix + "_button" + that.currentIndex).addClass("active"); });
		$("#" + this.prefix + "img" + this.activeLayer % 2).fadeOut(this.effectDuration);
		this.activeLayer++;

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

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

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


