var WMSlideshow = Class.create();

WMSlideshow.prototype = {
	initialize: function(containerid, speed, duration, pause, random) {
		this.images = new Array();
		this.cid = containerid;
		this.current = 0;
		this.speed = speed;
		this.duration = duration;
		this.pause = pause;
		this.random = random;
	},

	addImage: function(img) {
		this.images.push(img);
	},

	slideToImage: function(id) {
		if (this.images.length > 0) {
			var img = this.images[id];

			this.time = 0;

			document.getElementById(this.cid + "_second").innerHTML = img.getHtml();

			this.doSlide();
		}
	},

	doSlide: function() {
		this.time += this.speed;
		var firopa = Math.cos((this.time / this.duration) * (Math.PI/2));
		var secopa = 1; //Math.pow((this.time / this.duration), 8);
		this.setOpacity(document.getElementById(this.cid + "_first"), firopa);
		this.setOpacity(document.getElementById(this.cid + "_second"), secopa);


		if (this.time < this.duration)
			setTimeout(this.cid + ".doSlide()", this.speed);
		else { 
			document.getElementById(this.cid + "_first").style.zIndex = 10;
			document.getElementById(this.cid + "_second").style.zIndex = 20;
			document.getElementById(this.cid + "_first").innerHTML = document.getElementById(this.cid + "_second").innerHTML;
			setTimeout(this.cid + ".continueSlide()", 1000); // Give the browser a little time to load
		}
	},

	continueSlide: function() {
		document.getElementById(this.cid + "_first").style.zIndex = 20;
		document.getElementById(this.cid + "_second").style.zIndex = 10;
		this.setOpacity(document.getElementById(this.cid + "_first"), 1);
		this.setOpacity(document.getElementById(this.cid + "_second"), 0);
		setTimeout(this.cid + ".slide()", this.pause-1000);		
	},

	setOpacity: function(elem, opac) {
		if (elem.filters && elem.filters.alpha)
			elem.filters.alpha.opacity=Math.round(opac*100);
		else	
			elem.style.opacity = opac;
	},

	slide: function() {
		if (this.images.length <= 0) {
			return;
		}		

		var next = this.current+1;
		
		if (next == this.images.length) {
			next = 0;
		}
		if (this.random==true) {
			next = this.current;
			while(next == this.current) {
				next = Math.floor(Math.random() * Math.max(1, this.images.length) );
			}
		}
		
		this.setOpacity(document.getElementById(this.cid + "_first"), 1);
		this.setOpacity(document.getElementById(this.cid + "_second"), 0);
		if (document.getElementById(this.cid + "_first").innerHTML == "") {
			document.getElementById(this.cid + "_first").innerHTML = this.images[0].getHtml();
			}
		
		this.slideToImage(next);
		
		this.current = next;	
	}
};

var WMImage = Class.create();

WMImage.prototype = {
	initialize: function(url, width, height) {
		this.url = url;
		this.width = width + "em";
		this.height = height + "em";
		// preload
		this.preload = new Image();
		this.preload.src=this.url;
	},

	getHtml: function() {
		return "<img src='" + this.url + "' style='width: " + this.width + "; height: " + this.height + ";'/>";
	}
};

