//created by EASE 17/07/07
//requires scriptaculous effects & prototype
//example call is:
// var slideshow = new Slideshow({	imageRoot:'img/scroll_images/', 
//									imageSrcs:new Array('autumn_lake.gif', 'summer_lake.gif'), 
//									delay:3000, 
//									targetImg:'image_scroll_area_img',
//									imageWidth:457,
//									imageHeight:222
//								});

function Slideshow(options){
	this.imageSrcs = options.imageSrcs;
	this.delay = options.delay;
	this.targetImg = options.targetImg;
	this.imageRoot = options.imageRoot;
	this.imageWidth = options.imageWidth;
	this.imageHeight = options.imageHeight;
	this.nextImageIndex = 1;  //because first image is already loaded.
	this.allImagesLoaded = false;
	this.nextImage;
	this.imageLoaded=false;
	this.timerElapsed=false;
	this.loopCount=0;
	this.loopLimit = options.loopLimit || 100000;
	this.errorReporting = options.errorReporting;
}

Slideshow.prototype = {
	logErrors: function(error){
		if(this.errorReporting){
			$('errors').innerHTML += error+'<br>'; 
		}
	},
	
	start: function(){
		this.loopCount++;
		if(this.loopCount > this.loopLimit) return;
		this.logErrors('starting....');
		this.timerElapsed = false;
		this.loadImage();
		setTimeout(this.timer.bind(this), this.delay);	
	},
	
	loadImage: function(){
		this.logErrors('in loadImage');
		this.logErrors(this.imageSrcs[this.nextImageIndex]);
		if(!this.allImagesLoaded){
			this.logErrors('in if')
			
			this.nextImage = new Image(this.imageWidth, this.imageHeight);
			this.nextImage.src = this.imageRoot+this.imageSrcs[this.nextImageIndex];
			this.logErrors(this.nextImage.src);
			this.logErrors(typeof(this.nextImage.complete));
			if(!this.nextImage.complete){
				this.imageLoaded=false;
				this.logErrors('about to load image');
				this.nextImage.onload = function(){ this.imageLoaded=true; this.logErrors('in loadImage onLoad'); this.scrollImages();}.bind(this);
			}else{	
				this.logErrors('in complete');
				this.imageLoaded=true;
				this.scrollImages();
			}
			//alert('in loadImage IF st');
		}else{
			this.imageLoaded=true;
			this.scrollImages();
		}
	},
	
	timer: function(){
		this.logErrors('in timer');
		this.timerElapsed=true;
		this.scrollImages();
	},
	
	scrollImages: function(){
		this.logErrors('in scrollImage');
		this.logErrors(this.timerElapsed+' --- '+this.imageLoaded);
		if(!this.timerElapsed || !this.imageLoaded) return;	
		this.logErrors('after return');
		new Effect.Fade(this.targetImg, {afterFinish:this.afterFade.bind(this)});
	},
	
	afterFade: function(){
		this.logErrors('in afterFade');
		$(this.targetImg).src = this.imageRoot+this.imageSrcs[this.nextImageIndex];
		this.nextImageIndex++;
		if(this.nextImageIndex == this.imageSrcs.length){
			this.nextImageIndex=0;
			this.allImagesLoaded=true;
		}
		new Effect.Appear(this.targetImg, {afterFinish:this.start.bind(this)});
	}
}
