
fade_done = false;
ajax_done = false;
img_url = "";
link = "";
counter = 0;

var reloader;

var http  = getHTTPObject(); // We create the HTTP Object

function fadeInStartTimer()
{
	Effect.Appear('active_photo');

	if(!reloader)
		perslide = 0;
	else
		perslide = 4000;

	reloader = setTimeout("nextPhoto('next')", perslide);
}

// Load the next photo in the slideshow (Ajax function 3)
function nextPhoto(direction)
{
	if(document.getElementById('active_photo'))
	{
		fade_done = false;
		ajax_done = false;
		clearTimeout(reloader);

		// Fade out old picture
		Effect.Fade('active_photo',{afterFinish:finishFade});

		dt = new Date();
		http.open("GET", 'media_server.php?gallery=' + galleryID + '&stamp='+dt+'&rank='+counter+'&dir='+direction, true);
		http.onreadystatechange = function() {
			if(http.readyState == 4)
			{
				result = http.responseText.split("<!-- SEPERATOR -->");

				img_url = result[0];
				counter = result[1];

				ajax_done = true;
				showNew();
			}
		}
		http.send(null);
	}
}

function finishFade()
{
	fade_done = true;
	showNew();
}

function showNew()
{
	if(fade_done && ajax_done)
	{
		photoElm = document.getElementById('active_photo');
		photoElm.src = img_url;

		// Bug fix: If image is already loaded, the "onload" event will never trigger and the image will not load.
		// This checks to see if the image is already loaded, and if so, we call the function instantly.
		//if(photoElm.complete)
			//fadeInStartTimer();
		//else
			photoElm.onload = fadeInStartTimer;

		fade_done = false;
		ajax_done = false;
	}
}