// JavaScript Document
var slideshow = Class.create();
slideshow.prototype = {	
	
	initialize: function(container, path) {
	if (!$(container)) {
		throw(container+" doesn't exist!");
		return false;
	}
	this.direction = 1;
	this.counter = -1;
	this.start_frame = -1;
	this.end_frame =  null;
	this.delay = 500;
	this.container = container;
	this.names = null;
	this.oldImage = null;
	this.imgLoading = false;
	this.path = path;
	},
	
	setImages: function(images, nr) {
		this.counter = 0;
		this.start_frame = -1;
		this.end_frame = images.length;
		this.names = images;
		this.imgLoading = false;
		this.removeImage(1000);
	},
	
	
	removeImage: function(waitTime){
		if(!this.imgLoading){
			this.imgLoading = true;
			$('diashowLoader').show();
			if($(this.container).childElements().length >= 1)
				new Effect.Opacity($(this.container).childElements()[0], {duration:0.8, from: 1, to: 0, afterFinish: this.deleteImage.bind(this) });
			setTimeout(this.showImage.bind(this),waitTime);
		}
	},
	
	deleteImage: function(){
		if($(this.container).childElements().length >= 1)
			$(this.container).childElements()[0].remove();
	},
	
	
	showImage: function(){
		var url = "images/" + this.names[this.counter];
		
		var currentImg = Builder.node('img', { className : 'slideElement', src: url });
		Element.setStyle(currentImg, {
			'opacity':'0',
			'width':'622px',
			'height':'400px'
		});
		$(this.container).appendChild(currentImg);
		currentImg.onload = (function(){
			this.preloadImage();
			new Effect.Opacity(currentImg, {duration:1.2, from: 0, to: 1, afterFinish: this.setImageLoaded.bind(this) });
			$('diashowLoader').hide();
		}).bind(this);
	},
	
	setImageLoaded: function(){
		this.imgLoading = false;
		if($(this.container).childElements().length > 3)
			$(this.container).childElements()[2].remove();
	},
	
	preloadImage: function(){
		imgPreloader = new Image();
		var img_number = this.counter+this.direction;
		if(img_number > 0 && img_number < this.end_frame)
			imgPreloader.src = "images/" + this.names[img_number];
	},
	
	previous: function(){
		this.counter--;
		if (this.counter == this.start_frame){
			this.counter = this.end_frame-1; 
		}
		this.direction = -1;
		this.removeImage(0);
	},
	
	next: function(){
		this.counter++;
		if (this.counter == this.end_frame){
			this.counter = this.start_frame+1; 
		}
		this.direction = 1;
		this.removeImage(0);
		setTimeout(this.next.bind(this),'6000');
	},
	
	auto: function(images, nr){
		this.counter = -1;
		this.start_frame = -1;
		this.end_frame = images.length;
		this.names = images;
		this.imgLoading = false;
		setTimeout(this.next.bind(this),'100');
	}
}

var gallery;
