img=document.createElement('img');

for(var i=0;i<images.length;i++){
	img.src=gallery_folder+images[i];
}

viewport={
	width: null,
	height: null
}

image={
	width: null,
	height: null
};

imgvals=[];

curimg=2;

$(document).ready(function(){
	setImage(0, false);

	$("#controlUI a").eq(0).click(function(){
		setImage(curimg-1, true, "right");
		return false;
	});
	$("#controlUI a").eq(1).click(function(){
		setImage(curimg+1, true, "left");
		return false;
	});

	$(document).keydown(function(e){
		if(e.keyCode==37){
			setImage(curimg-1, true, "right");
			return false;
		}
		if(e.keyCode==39){
			setImage(curimg+1, true, "left");
			return false;
		}
		if(e.keyCode==38 || e.keyCode==40)
			return false;
	})
});

$(window).resize(function(){
	updateView($(window).width(), $(window).height());
});

function setImage(index, doanim, dir){
	if(index==-1){
		index=images.length-1;
	}
	if(index==images.length){
		index=0;
	}
	curimg=index;
	if(!imgvals[index])
		imgvals[index]=$.parseJSON($.ajax({
			"url":"getsize.php?file="+gallery_folder+images[index],
			"async":false
		}).responseText);

	image.width=imgvals[index][0];
	image.height=imgvals[index][1];

	if(doanim){
		var loc=$("#gallery img").position();
		var right=loc.left + image.width + 2000;
		var left=loc.left+5000;

		$("#gallery img").stop(true,false);

		var anim1=(dir=="left"?{"margin-left":"-="+right}:{"margin-left":"+="+left});
		var anim2=(dir=="left"?$(window).width()+1000+"px":0-image.width-1000);

		$("#gallery img").animate(anim1,function(){ 
			$("#gallery img.display").attr('src',gallery_folder+images[index]);

			$("#gallery img").css('margin-left',anim2);
			updateLabel(index);
			updateView($(window).width(), $(window).height());
			$("#gallery img").animate({"margin-left":"0"});
		});
	}
	else{
		$("#gallery img.display").attr('src',gallery_folder+images[index]);
		updateLabel(index);
		updateView($(window).width(), $(window).height());
	}
}

function updateLabel(index){
	imgarr=images[index].split("/");
	imgtext=imgarr[imgarr.length-2];
	if(text=folder_names[imgtext])
		$("#name").text(text);
	else
		$("#name").text(imgtext);

	Cufon.refresh("#name");
}

function updateView(width, height){
	imwidth=image.width;
	imheight=image.height;
	if(image.height>height){
		ratio=height / image.height;
		imwidth=Math.floor(image.width * ratio);
		imheight=height;
	}
	if(imwidth > width){
		ratio=width / imwidth;
		imheight=imheight * ratio;
		imwidth=width;
	}
	$("#gallery").add("#gallery img.display").css({'height': imheight+"px", "width":imwidth+"px"});
}


