/*****************************************************
* Slideshow
*
* TODO: add caption and navigation, random slides
******************************************************/

var Slide = Class.create({
	initialize: function(src) {
		this.src = src;
		this.image = new Image(); // preload image
		this.image.src = src;
	},

	setCaption: function(caption) {
		this.caption = caption;
	},
	
	setAlt: function(alt) {
		this.alt = alt;
	}
	
});

var Slideshow = Class.create({
	initialize: function(slides, holderelm) {
		this.elm = $(holderelm);
		this.elm.setStyle({backgroundColor: "#000"});
		this.slide = document.createElement("img");
		// check if holder elment contains an image (this will be replaced by the slideshow)
		if (this.elm.getElementsByTagName("IMG").length >0) {
			this.elm.replaceChild(this.slide,this.elm.getElementsByTagName("IMG")[0]);
		} else {
			// insert a new child element
			this.elm.appendChild(this.slide);
		}
		this.slideDuration = 3;
		this.transitionDuration = .5;
		this.currentSlide = 0;
		this.slides = slides;
		this.showSlide();
	},
	
	addSlide: function(slide) {
		this.slides.push(slide);
	},
	
	setSlideDuration: function(duration) {
		this.slideDuration = duration;
	},
	
	setTransitionDuration: function(duration) {
		this.transitionDuration = duration;
	},
	
	forward: function() {
		this.currentSlide>=(this.slides.size()-1)?this.currentSlide = 0:this.currentSlide++;
	},
	
	back: function() {
		this.currentSlide==0?this.currentSlide = this.slides.size()-1:this.currentSlide--;
	},
	
	showSlide: function() {
		Effect.Fade(this.slide,{duration:this.transitionDuration/2,to:.01});
		this.transition = new PeriodicalExecuter(this.appear.bind(this), this.transitionDuration/2);
	},
	
	appear: function() {
		this.slide.src = this.slides[this.currentSlide].src;
		Effect.Appear(this.slide,{duration:this.transitionDuration/2, from:.01});
		this.transition.stop();
	},
	
	showNextSlide: function() {
		this.forward();
		this.showSlide();
	},

	showPreviousSlide: function() {
		this.back();
		this.showSlide();
	},
	
	startShow: function() {
		this.show = new PeriodicalExecuter(this.showNextSlide.bind(this), this.slideDuration);
	},
	
	stopShow: function() {
		this.show.stop();
	},
	
	fadeTo: function(color) {
		this.elm.setStyle({backgroundColor: color});
	},
	
	randomize: function() {
		this.slides.sort(randomOrder);
	},
	
	toString: function() {
		var str = "";
		this.slides.each(function(s, index) {
			str += index + ": " + s.src + "\n";
		});
		return str;
	}
});

// Utitlity function for random ordering of an array
var randomOrder = function (){
	return (Math.round(Math.random())-0.5);
}
