var images = new Array();

function writeImage(url, maxDimension, alt, nodeId) {
	if (url == '') {
		showError();
		return;
	}

	// These have to be before we set image onload or src otherwise
	// they could be undefined in showImage.
	var showedImage = false;
	
	var img = document.createElement('img');   
	img.onload = showImage;
	img.onerror = showError;
	img.onabort = showError;
	img.src = url;
	img.alt = alt;
	images.push(img); // prevent img from being GC'ed
	
	function showImage() {
	    if (showedImage) { return; }
	    
    	var div = document.getElementById(nodeId);
		
		// Calculate dimension of image such that it is not upsampled, maintains
		// its aspect ratio, and fits into the square defined by maxDimension
		
		// Deal with Safari weirdness: We need to get add image to the
		// document before we can find it's width and height.
		// This might cause flickering so we only do it if necessary.
		var imageAppended = false;
		if (img.width == 0) { 
			div.appendChild(img);
			imageAppended = true;
		}
		
		var width = img.width;
		var height = img.height;
		
		if (img.width > img.height) {
			if (img.width > maxDimension) {
				width = maxDimension;
				height = img.height * maxDimension / img.width;
			}
		} else {
			if (img.height > maxDimension) {
				height = maxDimension;
				width = img.width * maxDimension / img.height;
			}
		}
		
		img.width = width;
		img.height = height;
		if (!imageAppended) {
			div.appendChild(img);
		}
		showedImage = true;
	}
	
	function showError() {
		var div = document.getElementById(nodeId);
		div.innerHTML = 'Image Not Available';
	}
}

