var slideshow = {

	init : function()
	{
		this.container = $("#slideshow");

		this.number_of_images = this.imgs.length;
		
		if(this.number_of_images==0) return false;
		
		this.current_image = 0;
		this.previous_image = null;
		this.current_loop = 0;
		
		this.hideImages();
		this.container.addClass('loading');
		
		this.imgloadtimeout = setTimeout('slideshow.loadImages()',this.speed*2);
	},
	

	loadImages : function()
	{
		$.each(this.imgs,function(i) {
			this.preload = new Image();
			this.preload.onload = function() { slideshow.isLoaded(i); };
			this.preload.src = this.src;
		});
	},
	
	isLoaded : function(i)
	{
		this.imgs[i].loaded = (this.imgs[i].preload.width!=0) ? true : null;
		if(i==0) { this.showImage(); }
	},
	
	hideImages : function()
	{
		$("img",this.container).hide();
	},
	
	showImage : function(number)
	{
		if(number){ this.current_image=number-1; number=undefined; };
		
		if(!this.imgs[this.current_image].loaded) {
			if(this.current_image!=this.number_of_images-1)
			{
				this.current_image++;
			}
			else
			{
				this.current_image=0;
				this.current_loop++;
			}
		}
		$("img",this.container).attr({	src:this.imgs[this.current_image].src,
																		alt:this.imgs[this.current_image].alt,
																		title:this.imgs[this.current_image].alt });
		$("img",this.container).fadeIn(this.speed);

		$("a",this.container).attr({ href:this.imgs[this.current_image].caption });

		this.imgtimeout = setTimeout('slideshow.fadeImage()',this.speed*5);
		
		this.previous_image=this.current_image;
		
		//console.log(this.current_image);
		
		if(this.number_of_images==1){
			this.pause();
		} else if(this.final_img!=undefined) {
			//console.log('final_img');
			if (this.current_image==this.final_img&&this.current_loop>=this.loop) this.pause();
		} else if (this.current_loop>=this.loop)
		{
			//console.log('no_final_img');
			this.pause();
		}


		if(this.current_image!=this.number_of_images-1)
		{
			this.current_image++;
		}
		else
		{ 
			this.current_image=0;
			this.current_loop++;
		}
	},
	
	pause : function()
	{
		clearTimeout(this.imgtimeout);
		clearTimeout(this.timein);
	},
	
	fadeImage : function(number)
	{
		this.container.removeClass('loading');

		$("img",this.container).fadeOut(this.speed);	
		
		this.timein = setTimeout('slideshow.showImage('+number+')',this.speed);
	}
	
};

window.onunload = function() { 
	clearTimeout(this.linktimein);
	slideshow.pause();
};




$(document).ready(function(){
	
	$.getJSON("/slideshow/", function(json){
		var slideshowdata = json;
		slideshow.imgs = slideshowdata.imgs;
		slideshow.loop = slideshowdata.loop;
		slideshow.final_img = slideshowdata.final_img;
		slideshow.speed = slideshowdata.speed;
		slideshow.init();
	});
	
});