var position = 0;
var prefix = "screen";
var suffix = ".png";

function threeDigits(value) {
	value = parseInt(value);
	if (value < 10) {
		return "00" + value;	
	} else if (value < 100) {
		return "0" + value;
	} else {
		return value;
	}
}

function change(position) {
	var nextPosition = threeDigits(position);
	var url = prefix + nextPosition + suffix;
	// $("#current").attr("src", "/img/spacer.gif");
	var nextImg = new Image();
	nextImg.onload = function() {
		$("#current").attr("src", this.src);
	}
	nextImg.src = url; 
}

function preload(position) {
	var url = prefix + threeDigits(position) + suffix;
	var auxImg = new Image();
	auxImg.src = url; 
}

function next() {
	if (position < maxPosition) {
		position +=1;
		change(position);
		if (position < maxPosition) {
			preload(position + 1);
		}
	}
}

function previous() {
	if (position > 0) {
		position -=1;
		change(position);
		if (position > 0) {
			preload(position - 1);
		}
	}
}

function first() {
	position = 0;
	change(position);
}

function last() {
	position = maxPosition;
	change(position);
}

$(function(){
	
	$(".previous").click(function (){
		previous();
		return false;
	});
	
	$(".next").click(function (){
		next();
		return false;
	});
		
	$(".first").click(function (){
		first();
		return false;
	});
	
	$(".last").click(function (){
		last();
		return false;
	});
		
	$(document).keydown(function(e)
	{
		switch(e.which)
		{
			case 8:
			case 37:
			case 38:
				previous();
				break;
			case 13:
			case 27:
			case 39:
			case 40:
				next();
				break;
		}
		return false;
	});

	if (position < maxPosition) {
		preload(position + 1);
	}
	
});