var pictures;
var currentPicture;
var pictureCount;

function Picture(_picName)
{
	this.thumbnail = new Image;
	this.thumbnail.src = "Thumbnails/" + _picName;
	this.mainPicture = null;
	this.picName = _picName;
}


function pageLoaded()
{
	// Generate the thumbnail table with relevant linkages to the 
	// picture viewing page.
	
	var div = document.getElementById("thumbnails");
	
	if (div != null)
	{
		pictures = new Array;
		for ( i = 0; i < gPhotos.length; i++)
		{
			anc = document.createElement("a");
			anc.href = "#";
			anc.onclick = selectImage;
			anc.id = "tn_" + i;
			pictures[i] = new Picture(gPhotos[i].filename);
			img = document.createElement("img");
			img.src = pictures[i].thumbnail.src;
			anc.appendChild(img);
			div.appendChild(anc);
		}
		currentPicture = 0;
		pictures[0].showPicture();
	}
}

function selectImage(evt)
{

	var parts;

	parts = this.id.split("_");
	currentPicture = parseInt(parts[1]);
	pictures[currentPicture].showPicture();
	
	if ( evt && evt.preventDefault)
		evt.preventDefault();
	return false;
}

Picture.prototype.showPicture = function()
{

	var theHolder = document.getElementById("pictureContainer");
  var oldFrame = document.getElementById("pictureFrame");
	var newFrame = document.createElement("div");
	var frag = document.createDocumentFragment();
	var p, img;
	
  if (theHolder != null)
  {
		newFrame.id = 'pictureFrame';
		if (this.mainPicture == null)
		{
			this.mainPicture = new Image;
			this.mainPicture.src = "Pictures/" + this.picName;
		}
		// Check to see if we have already created an image structure
		if (oldFrame.getElementsByTagName("img").length > 0)
		{
			// Yes we have, so need to update the img tag with the new src attribute
			// and change the file name text
			oldFrame.getElementsByTagName("img")[0].src = this.mainPicture.src
			p = document.createElement("p");
			p.appendChild(document.createTextNode(unescape(this.picName)));
			oldFrame.replaceChild(p, oldFrame.getElementsByTagName("p")[0]);
		}
		else
		{
			//
			// And now create the new structure
			//
			img = document.createElement("img");
			img.src = this.mainPicture.src;
			frag.appendChild(img);
			p = document.createElement("p");
			p.appendChild(document.createTextNode(unescape(this.picName)));
			frag.appendChild(p);
			newFrame.appendChild(frag);
			theHolder.replaceChild(newFrame, oldFrame);
		}
}

}

//
// This is the bit that enables all this code to work. It
// adds the onload event handler to the page body tag. This method is used
// so that the page code is absolutely clean in the event that the user does
// not have JS enabled, and hence there is no posibility of error messages
// being generated.
window.onload=pageLoaded;