var slideshow = {

	init : function()
	{
		this.container = $("#slideshow");
		
		$("#slideshow").click(function(){ document.location = "/gallery"; });
		
		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);
	},
	

	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 });
		$("img",this.container).fadeIn(this.speed);
		

		this.imgtimeout = setTimeout('slideshow.fadeImage()',this.speed*5);
		
		this.previous_image=this.current_image;
		
		if(this.current_loop>=this.loop||this.number_of_images==1) 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)
	{
		if(this.imgs[this.previous_image].link!=undefined)
		{
$("a",this.container).fadeOut(this.speed/2,function(){$("a",slideshow.container).remove();});
		}
		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.speed = slideshowdata.speed;
		slideshow.init();
	});
	
});