function createXMLHttp()
{
	var xmlhttp; 

	/*@cc_on
	
	@if(@_jscript_version >= 5)
	
	try
	{ 
		xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
	}
	catch(e)
	{
		try
		{
			xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
		}
		catch(e)
		{
			xmlhttp = false;
		}
	}
	
	@else
	
	xmlhttp = false;
	
	@end @*/
	
	if(!xmlhttp && typeof XMLHttpRequest != 'undefined')
	{
		try
		{
			xmlhttp = new XMLHttpRequest();
		}
		catch(e)
		{
			xmlhttp = false;
		}
	}
	
	return xmlhttp;
}

function nsResolver(prefix) {
	if(prefix == 'html')
	{
		return 'http://www.w3.org/1999/xhtml';
	}
	else if(prefix == 'dpg')
	{
		return 'http://www.polkapowered.com/xmlns/DynamicPhotoGallery/1.0'
	}
	else 
	{
		// This shouldn't happen
		return null;
	}
}

function localName(element)
{
	if(element.localName)
	{
		return element.localName;
	}
	
	var tagName = element.tagName
	var nsPos = tagName.indexOf(":");
	if(nsPos == -1)
	{
		return tagName;
	}
	
	return tagName.slice(nsPos + 1);
}

function enableDynamicNavigation()
{
	// Get all tumbnail link tags:
	var tumbnailLinkTagList = document.getElementsByTagName("a");
	var tumbnailLinkTags = new Array();
	for(var i = 0; i < tumbnailLinkTagList.length; ++i)
	{
		if(tumbnailLinkTagList[i].id.indexOf("thumbnail-link") > -1)
		{
			tumbnailLinkTags.push(tumbnailLinkTagList[i]);
		}
	}

	// Loop through the thumbnail links and assign dynamic code to them:
	for(var i = 0; i < tumbnailLinkTags.length; ++i)
	{
		tumbnailLinkTags[i].onclick = function() { loadImage(this.id.slice(15)); return false; };
	}

	// Preload the "loadingwheel":
	var img = new Image();
	img.src = "images/loading_wheel.gif";
}

function createLoadingWheel(width, height)
{
	var wheel = document.createElement("img");
	wheel.src = "images/loading_wheel.gif";
	wheel.width = "200";
	wheel.height = "200";
	wheel.id = "current-photo";
	wheel.className = "loading";

	// Set container padding for centering the loading wheel:
	var paddingHorizontal = ((width / 2) - (wheel.width / 2)) + "px";
	var paddingVertical = ((height / 2) - (wheel.height / 2)) + "px";

	wheel.style.paddingLeft = paddingHorizontal;
	wheel.style.paddingRight = paddingHorizontal;
	wheel.style.paddingTop = paddingVertical;
	wheel.style.paddingBottom = paddingVertical;

	return wheel;
}

function createImg(src, width, height)
{
	var imgElement = document.createElement("img");
	imgElement.id = "current-photo";
	imgElement.src = src;
	imgElement.width = width;
	imgElement.height = height;

	return imgElement;
}

function createErrorBoxContent(description)
{
	var closeButton = document.createElement("input");
	closeButton.type = "button";
	closeButton.onclick = function()
	{
		var displayElement = document.getElementById("current-photo");
		var displayParentElement = displayElement.parentNode;
	
		// Replace the loading wheel with an empty element:
		var emptyElement = document.createElement("div");
		emptyElement.id = "current-photo"
		emptyElement.textContent = " ";
		emptyElement.style.width = displayElement.clientWidth + "px";
		emptyElement.style.height = displayElement.clientHeight + "px";
		displayParentElement.replaceChild(emptyElement, displayElement);

		// Close the ErrorBox:
		var errorBoxElement = document.getElementById("error-box");
		var errorBoxElementParent = errorBoxElement.parentNode;
		errorBoxElementParent.removeChild(errorBoxElement);
		
		// Allow loading of new image:
		loadingImage = false;
	};
	closeButton.value = "Lukk vindu";

	var textBlock = document.createElement("div");
	textBlock.className = "text-block";
	textBlock.innerHTML = "<h1>Ops!</h1><p>En feil oppsto under lastingen av det valgte bildet. Vennligst prøv igjen senere.</p><p><strong>Detaljert informasjon: </strong>" + description + "</p>";
	textBlock.appendChild(closeButton);
	
	var errorDialogImage = document.createElement("img");
	errorDialogImage.src = "images/tango_dialog_error.png";
	errorDialogImage.className = "dialog-error-image";
	errorDialogImage.alt = "Feil";
	
	var content = document.createElement("div");
	content.className = "error-box-content";
	content.appendChild(errorDialogImage);
	content.appendChild(textBlock);

	return content;
}

function displayErrorBox(description)
{
	var backgroundOverlay = document.createElement("div");
	backgroundOverlay.className = "error-box-overlay";

	var errorBox = document.createElement("div");
	errorBox.id = "error-box";
	errorBox.appendChild(backgroundOverlay);
	
	document.body.appendChild(errorBox);	

	var content = createErrorBoxContent(description);

	errorBox.appendChild(content);
}

function loadImage(id)
{
	// As long as we're not loading an image already:
	if(!loadingImage)
	{
		loadingImage = true;
		try
		{
			// Fetch the elements we're modifying:
			var currentElement = document.getElementById("current-photo");
			var currentParentElement = currentElement.parentNode;
		
			// Replace the currently showing photo with the loading wheel:
			var wheelElement = createLoadingWheel(currentElement.clientWidth, currentElement.clientHeight);
			currentParentElement.replaceChild(wheelElement, currentElement);
			
			// Load info about the requested image from the server:
			var request = createXMLHttp();
			request.open('GET', 'get_photo.php?id=' + id, true);
			request.onreadystatechange = function (aEvt)
			{
				if(request.readyState == 4)
				{
					if(request.status == 200)
					{
						var xmlDocument = request.responseXML;
						var rootNode = xmlDocument.documentElement;
						
						if(rootNode && localName(rootNode) == "photo" && rootNode.namespaceURI == nsResolver('dpg'))
						{
							displayImage(rootNode);
						}
						else if(rootNode && localName(rootNode) == "error" && rootNode.namespaceURI == nsResolver('dpg'))
						{ 
							displayErrorBox(rootNode.textContent);
						}
						else
						{
							displayErrorBox("Unknown error while loading image with ID " + id + ".");
						}
					}
					else
					{
						displayErrorBox("Error code " + request.status + " while loading image with ID " + id + ".");
					}
				}
			};
			
			request.send(null); 
		}
		catch(e)
		{
			alert("Error occured\n\n" + e);
			loadingImage = false;
		}
	}
}

function displayImage(photoNode)
{
	var xmlDocument = photoNode.ownerDocument

	// Get address, height, width of photo:
	var photoId = photoNode.getAttribute("id");
	var photoLocation = photoNode.getAttribute("src");
	var photoHeight = photoNode.getAttribute("height");
	var photoWidth = photoNode.getAttribute("width");
	
	// Start loading the new image:
	var img = new Image();
	
	img.onload = function() {
	    // Fetch the elements we're modifying:
	    var currentElement = document.getElementById("current-photo");
	    var currentParentElement = currentElement.parentNode;
	
		// Image has finished loading, insert it into the DOM:
		var imageElement = createImg(photoLocation, photoWidth, photoHeight);
		currentParentElement.replaceChild(imageElement, currentElement);
	
		// Success!
		loadingImage = false;
	};

	var errorFunc = function() {
		displayErrorBox("Unknown error while loading image file at \"" + photoLocation + "\".");
	};

	// Connect callbacks:
	img.onerror = errorFunc;
	img.onabort = errorFunc;
	
	// Initiate load:
	img.src = photoLocation;
}

loadingImage = false;
