
function addListener(eventSource, eventName, eventHandler, capturing) {
	eventSource.addEventListener ? eventSource.addEventListener(eventName, eventHandler, capturing) : eventSource.attachEvent ?
	eventSource.attachEvent("on" + eventName, eventHandler) : eventSource["on" + eventName] = eventHandler;
}

function cancelImageLink(e) {
	if (!e) e = window.event;
	return cancel(e);
}

function scaleImageToFitRect(imageElement, w, h) {
	var scaleAmount = 1.0;

	if( imageElement.width > imageElement.height ) {

		// resize to maintain proper aspect ratio
		if( imageElement.width > w ) {
			scaleAmount = w / imageElement.width;
		}

		if( imageElement.height > h ) {
			if( (h / imageElement.height) < scaleAmount ) {
				scaleAmount = h / imageElement.height;
			}
		}
	} else {
		// resize to maintain proper aspect ratio
		if( imageElement.height > h ) {
			scaleAmount = h / imageElement.height;
		}

		if( imageElement.width > w ) {
			if( (w / imageElement.width) < scaleAmount ) {
				scaleAmount = w / imageElement.width;
			}
		}
	}

	//alert(imageElement.width + ", " + imageElement.height);
	//alert( scaleAmount );

	if( scaleAmount != 1.0 ) {

        	var newWidth = imageElement.width * scaleAmount;
		var newHeight = imageElement.height * scaleAmount;

		if( imageElement.width > imageElement.height ) {
			imageElement.height = newHeight;
			imageElement.width = newWidth;
		} else {
			imageElement.width = newWidth;
			imageElement.height = newHeight;
		}
	}
	
}

var mediumImage = null;

function highlightThumbnail(e) {
	if (!e) e = window.event;

	var source = e.target ? e.target : e.srcElement;
	source.style.cursor = "pointer";

	mediumImage = document.getElementById("mediumImage");
	if( mediumImage ) {
		RemoveMediumImage(mediumImage);
	}

	document.getElementById("mediumImageLoadingImage").style.display = "block";

	mediumImage = document.createElement("img");
	mediumImage.id = "mediumImage";
	addListener(mediumImage, "load", mediumImageFinishedLoading, false);

	var thumbnailURL = source.src;

	// trying setting the URL to thumbnail URL but change to _m.*
	if( (thumbnailURL.indexOf("_m.jpg") != -1) || (thumbnailURL.indexOf("_m.png") != -1) ) {
		mediumImage.src = source.src;
	} else if( thumbnailURL.indexOf("_t.jpg") != -1) {
		mediumImage.src = source.src.replace("_t.jpg", "_m.jpg");
	} else if( thumbnailURL.indexOf("_t.png") != -1) {
		mediumImage.src = source.src.replace("_t.png", "_m.png");
	} else {
		mediumImage.src = source.src;
	}
}

function RemoveMediumImage(element) {
	document.getElementById("mediumImageArea").removeChild(element);
}

var maxMediumImageWidth = 400;
var maxMediumImageHeight = 400;

function mediumImageFinishedLoading(e) {
	if (!e) e = window.event;
	var source = e.target ? e.target : e.srcElement;

	//source = document.getElementById("mediumImage");
	source = mediumImage;
	
	//alert(source.width + ", " + source.height);

	// resize to maintain proper aspect ratio
	scaleImageToFitRect(source, maxMediumImageWidth, maxMediumImageHeight);	

	centerMediumImage(source);

	document.getElementById("mediumImageArea").appendChild(source);
	
	document.getElementById("mediumImageLoadingImage").style.display = "none";
}

function centerMediumImage(el) {
	//el.style.paddingTop = ((maxMediumImageHeight - el.height) / 2) + "px";
	//el.style.paddingLeft = ((maxMediumImageWidth - el.width) / 2) + "px";

	//alert(el.style.paddingLeft);
}


function resizeMediumImage() {
	document.getElementById("mediumImageLoadingImage").style.display = "none";

	var source = document.getElementById("mediumImage");

	scaleImageToFitRect(source, maxMediumImageWidth, maxMediumImageHeight);	

	centerMediumImage(source);

	source.style.visibility = "visible";
}

function cancel(e) {
	if( e && e.preventDefault ) {
		e.preventDefault();		// DOM style
	}

	if( e && e.returnValue )
		e.returnValue = false;	// IE style

	return false;			// IE style
}

function showPopUpWindow(e) {
	if (!e) e = window.event;
	var source = e.target ? e.target : e.srcElement;

	if( windowVisible == false ) {
		document.body.style.overflow = "hidden";
		var popUpWindow = document.getElementById("popUpWindowDiv");
		
		getWindowSize();
		getScrollXY();
		SetPopUpWindowSize(clientWindowWidth, clientWindowHeight);
		grayOut(true);

		popUpWindow.style.display = "block";
		windowVisible = true;
	}

	LoadFullSizeImage(source.src, maxScaledFullImageWidth, maxScaledFullImageHeight);
}

function hidePopUpWindow(e) {

	if( windowVisible == true ) {
		if (!e) e = window.event;
		var source = e.target ? e.target : e.srcElement;

		var popUpWindow = document.getElementById("popUpWindowDiv");

		popUpWindow.style.display = "none";
		grayOut(false);
		windowVisible = false;
		document.body.style.overflow = "scroll";
		cancel(e);
	}
}

function initHandlers() {
	getWindowSize();
	var allImgs = document.getElementById("thumbnailImageArea").getElementsByTagName("img");
	for (var i in allImgs) {
		if( i == "length") continue;

		var img = allImgs[i];
		var newImg = document.createElement("img");
		newImg.src = img.src;

		newImg.width = img.width;
		newImg.height = img.height;

		//  -20 to compensate for scroll-bar
		if( img.width > (windowThumbnailAreaWidth-20) ) {
			var scaleAmount = (windowThumbnailAreaWidth-20) / img.width;

			var imageWidth = newImg.width * scaleAmount;
			var imageHeight = newImg.height * scaleAmount;

			newImg.width = imageWidth;
			newImg.height = imageHeight;
		}

		document.getElementById("popUpWindowThumbnailArea").appendChild(newImg);

		addListener(img, "mouseover", highlightThumbnail, false);
		addListener(img, "click", showPopUpWindow, false);
		addListener(newImg, "click", showPopUpWindow, false);
	}

	addListener(document.getElementById("closePopUp"), "click", hidePopUpWindow, false);
	addListener(window, "resize", handleClientWindowResize, false);
	addListener(document.getElementById("mediumImage"), "load", mediumImageFinishedLoading, false);

	document.getElementById("mediumImageArea").style.width = maxMediumImageWidth + "px";
	document.getElementById("mediumImageArea").style.height = maxMediumImageHeight + "px";

	//centerMediumImage(document.getElementById("mediumImage"));

	var allLinks = document.getElementById("thumbnailImageArea").getElementsByTagName("a");
	for (var i in allLinks) {
		if( i == "length") continue;

		addListener(allLinks[i], "click", cancelImageLink, false);
	}	
}

function handleClientWindowResize(e) {
	if( (windowVisible == false) )
		return;

	if (!e) e = window.event;
	var source = e.target ? e.target : e.srcElement;

	var popUpWindow = document.getElementById("popUpWindowDiv");

	getWindowSize();
	getScrollXY();
	grayOut(true);

	SetPopUpWindowSize(clientWindowWidth, clientWindowHeight);

	LoadFullSizeImage(popUpWindowMainImage.src, maxScaledFullImageWidth, maxScaledFullImageHeight);
}

var windowTopFixedWidth = 46;
var windowBottomFixedWidth = 16;
var windowSidesFixedHeight = 128;
var windowSidesPadding = 16;
var windowTopBottomPadding = 34;
var windowThumbnailAreaWidth = 150;
var windowVisible = false;

var windowPercentHeight = 0.95;
var windowPercentWidth = 0.95;

var maxFullImageWidth = 800;
var maxFullImageHeight = 600;
var maxScaledFullImageWidth, maxScaledFullImageHeight;

function SetPopUpWindowSize(w, h) {
	var popUpWindowTable = document.getElementById("popUpWindowTable");
	var scaleAmount = 1.0;
	document.getElementById("popUpWindowThumbnailArea").style.width = windowThumbnailAreaWidth + "px";

	overallWidth = windowThumbnailAreaWidth + windowSidesPadding + maxFullImageWidth;
	overallHeight = windowTopBottomPadding + maxFullImageHeight;

	if( overallWidth > (w*windowPercentWidth) ) {
		scaleAmount = (w*windowPercentWidth) / overallWidth;
	}

	if( overallHeight > (h*windowPercentHeight) ) {
		if( ((h*windowPercentHeight) / overallHeight) < scaleAmount ) {
			scaleAmount = ((h*windowPercentHeight) / overallHeight);
		}
	}

	if( scaleAmount != 1.0 ) {
		overallWidth *= scaleAmount;
		overallHeight *= scaleAmount;

		overallWidth = Math.round(overallWidth);
		overallHeight = Math.round(overallHeight);
	}	

	popUpWindowTable.width = overallWidth;
	popUpWindowTable.height = overallHeight;

	document.getElementById("topMiddleWindow").style.width = (popUpWindowTable.width - windowTopFixedWidth) + "px";
	document.getElementById("bottomMiddleWindow").style.width = (popUpWindowTable.width - windowBottomFixedWidth) + "px";

	document.getElementById("lowerSideLeftWindow").style.height = (overallHeight - windowSidesFixedHeight) + "px";
	document.getElementById("lowerSideRightWindow").style.height = (overallHeight - windowSidesFixedHeight) + "px";
	
	maxScaledFullImageWidth = (overallWidth - windowThumbnailAreaWidth - windowSidesPadding);
	maxScaledFullImageHeight = (overallHeight - windowTopBottomPadding);

	var popUpWindowMainImageArea = document.getElementById("popUpWindowMainImageArea");
	popUpWindowMainImageArea.style.width = maxScaledFullImageWidth + "px";
	popUpWindowMainImageArea.style.height = maxScaledFullImageHeight + "px";

	var popUpWindowMainImageTD = document.getElementById("popUpWindowMainImageTD");
	popUpWindowMainImageTD.style.width = maxScaledFullImageWidth + "px";
	popUpWindowMainImageTD.style.height = maxScaledFullImageHeight + "px";

	document.getElementById("popUpWindowThumbnailArea").style.height = maxScaledFullImageHeight + "px";
	
	var popUpWindow = document.getElementById("popUpWindowDiv");

	popUpWindow.style.left = (scrOfX + ((w * 0.5) - (overallWidth * 0.5))) + "px";
	popUpWindow.style.top = (scrOfY + ((h * 0.5) - (overallHeight * 0.5))) + "px";
	document.getElementById("popUpWindowMainImageArea").style.width = "auto";
	document.getElementById("popUpWindowMainImageArea").style.height = "auto";
}

var popUpWindowMainImage = null;

function FullSizeImageLoadFinished(e) {

	if (!e) e = window.event;
	var source = e.target ? e.target : e.srcElement;

	var scaleAmount = 1.0;

	source = source ? source : popUpWindowMainImage;

	document.getElementById("popUpWindowMainImageArea").appendChild(source);

	scaleImageToFitRect(source, maxScaledFullImageWidth, maxScaledFullImageHeight);
	
	document.getElementById("popUpWindowLoadingImage").style.display = "none";
}

function LoadFullSizeImage(smallerURL, maxWidth, maxHeight) {
	document.getElementById("popUpWindowLoadingImage").style.display = "block";

	popUpWindowMainImage = document.getElementById("popUpWindowMainImage");
	if( popUpWindowMainImage ) {
		RemoveFullSizeImage(popUpWindowMainImage);
	}

	popUpWindowMainImage = document.createElement("img");
	popUpWindowMainImage.id = "popUpWindowMainImage";
	addListener(popUpWindowMainImage, "load", FullSizeImageLoadFinished, false);

	var thumbnailURL = smallerURL;

	if( thumbnailURL.indexOf("_m.jpg") != -1 ) {
		popUpWindowMainImage.src = thumbnailURL.replace("_m.jpg", "_full.jpg");
	} else if( thumbnailURL.indexOf("_m.png") != -1 ) {
		popUpWindowMainImage.src = thumbnailURL.replace("_m.png", "_full.png");
	} else if( thumbnailURL.indexOf("_t.jpg") != -1 ) {
		popUpWindowMainImage.src = thumbnailURL.replace("_t.jpg", "_full.jpg");
	} else if( thumbnailURL.indexOf("_t.png") != -1 ) {
		popUpWindowMainImage.src = thumbnailURL.replace("_t.png", "_full.png");
	} else {
		popUpWindowMainImage.src = smallerURL;
	}
}

function RemoveFullSizeImage(element) {
	document.getElementById("popUpWindowMainImageArea").removeChild(element);
}


function grayOut(vis, options) {
	// Pass true to gray out screen, false to ungray
	// options are optional.  This is a JSON object with the following (optional) properties
	// opacity:0-100         // Lower number = less grayout higher = more of a blackout 
	// zindex: #             // HTML elements with a higher zindex appear on top of the gray out
	// bgcolor: (#xxxxxx)    // Standard RGB Hex color code
	// grayOut(true, {'zindex':'50', 'bgcolor':'#0000FF', 'opacity':'70'});
	// Because options is JSON opacity/zindex/bgcolor are all optional and can appear
	// in any order.  Pass only the properties you need to set.
	var options = options || {}; 
	var zindex = options.zindex || 50;
	var opacity = options.opacity || 70;
	var opaque = (opacity / 100);
	var bgcolor = options.bgcolor || '#000000';

	var dark = document.getElementById('darkenScreenObject');
	if( !dark ) {
		// The dark layer doesn't exist, it's never been created.  So we'll
		// create it here and apply some basic styles.
		// If you are getting errors in IE see: http://support.microsoft.com/default.aspx/kb/927917
		var tbody = document.getElementsByTagName("body")[0];
		var tnode = document.createElement('div');           // Create the layer.
		tnode.style.position = 'absolute';                   // Position absolutely
		tnode.style.top  = document.body.scrollTop; //'0px';                           // In the top
		tnode.style.left = document.body.scrollLeft; //'0px';                          // Left corner of the page
		tnode.style.overflow = 'hidden';                     // Try to avoid making scroll bars            
		tnode.style.display = 'none';                        // Start out Hidden
		tnode.id = 'darkenScreenObject';                     // Name it so we can find it later
		tbody.appendChild(tnode);                            // Add it to the web page
		dark = document.getElementById('darkenScreenObject');  // Get the object.
	}

	if( vis ) {
		//set the shader to cover the entire page and make it visible.
	    	dark.style.opacity = opaque;                      
    		dark.style.MozOpacity = opaque;                   
	    	dark.style.filter = 'alpha(opacity='+opacity+')'; 
	    	dark.style.zIndex = zindex;        
    		dark.style.backgroundColor = bgcolor;
		dark.style.top	   = scrOfY + "px";
		dark.style.left	   = scrOfX + "px";
	    	dark.style.width   = clientWindowWidth + "px";
    		dark.style.height  = clientWindowHeight + "px";
	    	dark.style.display = 'block';
	} else {
		dark.style.display = "none";
	}
}

