/*global window */
var tnElemShowing = false,
	resizeTimer, waitImgTimer,
	pageHasFinishedLoading = false,
	bigImgPrefix = "sm_",
	ignoreWinResize = false,
	lastWrect = {x: 0, y: 0, cx: 0, cy: 0},
	scaleMode,
	IE6 = false,
	imgLoading = false;
//-----------------------------------------------------------------------------------------------------------------------------------------
//Preload images
var pre1 = new Image(),
	pre2 = new Image(),
	pre3 = new Image(),
	pre4 = new Image(),
	pre5 = new Image(),
	pre6 = new Image(),
	prevImgPreloader = new Image(),
	nextImgPreloader = new Image();

pre1.src = "dk_bgfade_300.jpg";
pre2.src = "overlay.png";
pre3.src = "spinningwait.gif";
pre4.src = "dk_previousbtn74x13.gif";
pre5.src = "dk_nextbtn49x13.gif";
pre6.src = "dk_returnbtn54x13.gif";
//-----------------------------------------------------------------------------------------------------------------------------------------
function myElem(elemName) {
	return document.getElementById(elemName);
}
//-----------------------------------------------------------------------------------------------------------------------------------------
function bodyRect() {
	//These are for strict mode doctype
	var obj = {};

	obj.x = 0;
	obj.y = 0;
	obj.cx = document.body.offsetWidth;
	obj.cy = document.body.offsetHeight;

	return obj;
}
//-----------------------------------------------------------------------------------------------------------------------------------------
function windowRect() {
	//These are for strict mode doctype
	var obj = {};

	if (typeof(window.pageXOffset) == 'number') { //Firefox and Safari
		obj.x = window.pageXOffset;
		obj.y = window.pageYOffset;
	}
	else if (typeof(document.documentElement.scrollLeft) == 'number') { // IE
		obj.x = document.documentElement.scrollLeft;
		obj.y = document.documentElement.scrollTop;
	}
	else if (typeof(document.body.scrollLeft) == 'number') { //IE Mac
		obj.x = document.body.scrollLeft;
		obj.y = document.body.scrollTop;
	}

	if (typeof(window.innerWidth) == 'number' && typeof(document.documentElement.scrollLeft) != 'number') { //Safari
		obj.cx = window.innerWidth;
		obj.cy = window.innerHeight;
	}
	else if (typeof(document.documentElement.clientWidth) == 'number') { //IE and Firefox
		obj.cx = document.documentElement.clientWidth;
		obj.cy = document.documentElement.clientHeight;
	}
	else if (typeof(document.body.clientWidth) == 'number') { //IE Mac
		obj.cx = document.body.clientWidth;
		obj.cy = document.body.clientHeight;
	}

	return obj;
}
//-----------------------------------------------------------------------------------------------------------------------------------------
function reloadPageFromServer() {
	// IE doesn't always reload from the server when using "location.reload(true);".
	location.href = location.href; // Refresh page
}
//-----------------------------------------------------------------------------------------------------------------------------------------
function crossBrowserEvent(e) {
	var target, button, wheel;

	if (!e) {
		e = window.event;
	}

	// Get the target element of the event --------------------------------------------------
	target = (e.target) ? e.target : e.srcElement;

	if (target.nodeType == 3) { // defeat Safari bug
		target = target.parentNode;
	}

	// Get mouse button pressed. (1=left, 2=right) ------------------------------------------
	if (e.which) {  // Firefox and Safari
		button = e.which;
		if (button === 2) {
			button = 0;
		}
		else if (button === 3) {
			button = 2;
		}
	}
	else if (e.button) {  // IE
		button = e.button;
	}

	if (button !== 1 && button !== 2) {
		button = 0;
	}

	// Get mouse wheel.---------------------------------------------------------------------
	if (e.wheelDelta) {
		wheel = e.wheelDelta / 120; 
		if (window.opera) {
			wheel = -wheel;
		}
	} 
	else if (e.detail) {
		wheel = -e.detail / 3;
	}

	return {ev: e, target: target, keyCode: e.keyCode, button: button, wheel: wheel, clientX: e.clientX, clientY: e.clientY, shiftKey: e.shiftKey, ctrlKey: e.ctrlKey};
//	alert("target: " + target.tagName + "  keyCode: " + keyCode + "  mouse button: " + button + "  click coords: " + clientX + "," + clientY);
}
//-----------------------------------------------------------------------------------------------------------------------------------------
function killEventDefaultAction(e) {
	if (e.ev.preventDefault) {
		e.ev.preventDefault();
	}
	e.ev.returnValue = false;
}
//-----------------------------------------------------------------------------------------------------------------------------------------
function setOpacity(obj, opacityPercent) {
	//This is faster than changing the object's class
	if (opacityPercent >= 0 && opacityPercent < 100) {
		obj.style.opacity = opacityPercent / 100;                      
		obj.style.filter = "progid:DXImageTransform.Microsoft.Alpha(opacity = " + opacityPercent + ")";
	}
	else {
		obj.style.opacity = "";
		obj.style.filter = "";
	}
}
//-----------------------------------------------------------------------------------------------------------------------------------------
function inBigImgMode() {
	return tnElemShowing;
}
//-----------------------------------------------------------------------------------------------------------------------------------------
function reloadImage(imgElem) {
	var srcParts, reloadAttemptNum, newSrc;

	srcParts = imgElem.src.split("reloadAttempt");
	reloadAttemptNum = (srcParts.length > 1) ? srcParts[1] * 1 : 0;
	if (reloadAttemptNum < 5) {
		reloadAttemptNum += 1;
		newSrc = srcParts[0] + "reloadAttempt" + reloadAttemptNum;
		imgElem.src = newSrc;
	}
	else {
		reloadPageFromServer();
	}
}
//-----------------------------------------------------------------------------------------------------------------------------------------
function showPrevImage() {
	if (inBigImgMode() && typeof(tnElemShowing) == "object" && tnElemShowing.previousSibling) {
		tnElemShowing.previousSibling.onclick();
		return true;
	}
	return false;
}
//-----------------------------------------------------------------------------------------------------------------------------------------
function showNextImage() {
	if (inBigImgMode() && typeof(tnElemShowing) == "object" && tnElemShowing.nextSibling) {
		tnElemShowing.nextSibling.onclick();
		return true;
	}
	return false;
}
//-----------------------------------------------------------------------------------------------------------------------------------------
function placeWaitImg() {
	var wrect = windowRect();
	myElem("imagewait").style.display = "block";
	myElem("imagewait").style.left = (wrect.cx - myElem("imagewait").offsetWidth) / 2 + wrect.x + "px";
	myElem("imagewait").style.top = (wrect.cy - myElem("imagewait").offsetHeight) / 2 + wrect.y + "px";
}
//-----------------------------------------------------------------------------------------------------------------------------------------
function showWaitImg() {
	clearTimeout(waitImgTimer);
	waitImgTimer = setTimeout(placeWaitImg, 250);
}
//-----------------------------------------------------------------------------------------------------------------------------------------
function hideWaitImg() {
	clearTimeout(waitImgTimer);
	myElem("imagewait").style.display = 'none';
}
//-----------------------------------------------------------------------------------------------------------------------------------------
function showToolbar(wrect) {
	myElem("imageToolbar").style.top = wrect.y + "px";
	myElem("imageToolbar").style.display = 'block';
}
//-----------------------------------------------------------------------------------------------------------------------------------------
function enableDisablePrevNext() {
	if (tnElemShowing.previousSibling) {
		setOpacity(myElem("prevBtn"), 100);
		myElem("prevBtn").style.cursor = "pointer";
	}
	else {
		setOpacity(myElem("prevBtn"), 35);
		myElem("prevBtn").style.cursor = "default";
	}

	if (tnElemShowing.nextSibling) {
		setOpacity(myElem("nextBtn"), 100);
		myElem("nextBtn").style.cursor = "pointer";
	}
	else {
		setOpacity(myElem("nextBtn"), 35);
		myElem("nextBtn").style.cursor = "default";
	}
}
//-----------------------------------------------------------------------------------------------------------------------------------------
function showBackground() {
	var bg, brect, wrect, width, height;

	bg = myElem("imagebackground");
	brect = bodyRect();
	wrect = windowRect();
	width = brect.cx;
	height = (brect.cy > wrect.cy) ? brect.cy : wrect.cy;

	if (bg.offsetWidth !== width || bg.offsetHeight !== height) {
		bg.style.width = width + "px";
		bg.style.height = height + "px";
		bg.style.display = "block";
	}
}
//-----------------------------------------------------------------------------------------------------------------------------------------
function getTargetArea(wrect) {
	var tgtWidth, tgtHeight, tgtAspect;
	
	tgtWidth = Math.max(wrect.cx - 60, 135);
	tgtHeight = Math.max(wrect.cy - 86, 135);
	tgtAspect = tgtWidth / tgtHeight;

	return {width: tgtWidth, height: tgtHeight, aspect: tgtAspect};
}
//-----------------------------------------------------------------------------------------------------------------------------------------
function setSizeControls(disableLarge) {
	if (scaleMode === "small") {
		myElem("smBtn").style.textDecoration = "underline";
		myElem("lgBtn").style.textDecoration = "none";
		myElem("autoBtn").style.textDecoration = "none";

		myElem("smBtn").style.color = "#f5b31d";
		myElem("lgBtn").style.color = "#fff";
		myElem("autoBtn").style.color = "#fff";
	}
	else if (scaleMode === "large") {
		myElem("smBtn").style.textDecoration = "none";
		myElem("lgBtn").style.textDecoration = "underline";
		myElem("autoBtn").style.textDecoration = "none";

		myElem("smBtn").style.color = "#fff";
		myElem("lgBtn").style.color = "#f5b31d";
		myElem("autoBtn").style.color = "#fff";
	}
	else {  // Auto
		myElem("smBtn").style.textDecoration = "none";
		myElem("lgBtn").style.textDecoration = "none";
		myElem("autoBtn").style.textDecoration = "underline";

		myElem("smBtn").style.color = "#fff";
		myElem("lgBtn").style.color = "#fff";
		myElem("autoBtn").style.color = "#f5b31d";
	}

	if (disableLarge) {
		myElem("lgBtn").style.cursor = "default";
		myElem("lgBtn").style.color = "#666";
		if (scaleMode === "large") {
			myElem("smBtn").style.color = "#f5b31d";
		}
	}
	else {
		myElem("lgBtn").style.cursor = "pointer";
	}
}
//-----------------------------------------------------------------------------------------------------------------------------------------
function getBigImgPrefix(tnObj, wrect, setOrGet) {
	var orSize, orWidth, orHeight, orAspect, smWidth, smHeight, mdWidth, mdHeight, prefix, targetArea,
		maxSmWidth, maxSmHeight, maxSmAspect, maxMdWidth, maxMdHeight, maxMdAspect;

	// These values must match those in imageprocessor.php
	maxSmWidth = 640;
	maxSmHeight = 480;
	maxMdWidth = 1152;
	maxMdHeight = 768;
	
	targetArea = getTargetArea(wrect);

	// Get dimensions of the original image
	orSize = tnObj.name.split(":");
	orWidth = orSize[0] * 1;
	orHeight = orSize[1] * 1;

	if (orWidth && orHeight) {
		orAspect = orWidth / orHeight;
		maxSmAspect = maxSmWidth / maxSmHeight;
		maxMdAspect = maxMdWidth / maxMdHeight;
	
		// Determine the dimensions of the small image (whether or not it exists)
		if (orAspect >= maxSmAspect) {
			smWidth = Math.min(orWidth, maxSmWidth);
			smHeight = Math.round(smWidth / orAspect);
		}
		else {
			smHeight = Math.min(orHeight, maxSmHeight);
			smWidth = Math.round(smHeight * orAspect);
		}
		
		// Determine the dimensions of the medium image (whether or not it exists)
		if (orAspect >= maxMdAspect) {
			mdWidth = Math.min(orWidth, maxMdWidth);
			mdHeight = Math.round(mdWidth / orAspect);
		}
		else {
			mdHeight = Math.min(orHeight, maxMdHeight);
			mdWidth = Math.round(mdHeight * orAspect);
		}
		
		switch (scaleMode) {
		case "small":
			prefix = "sm_";
			break;
		case "large":
			prefix = (orWidth > smWidth) ? "md_" : "sm_";
			break;
		case "auto":
			prefix = (smWidth >= targetArea.width || smHeight >= targetArea.height || smWidth >= mdWidth) ? "sm_" : "md_";
			break;
		}
	}

	if (setOrGet === "set") {
		bigImgPrefix = prefix;
		setSizeControls(smWidth >= mdWidth);
	}
	else {  // get
		return prefix;
	}
}
//-----------------------------------------------------------------------------------------------------------------------------------------
function placeBigImg(wrect) {
	var x, y;
	
	x = (wrect.cx - myElem("bigimage").offsetWidth) / 2 + wrect.x;
	y = (wrect.cy - myElem("bigimage").offsetHeight) / 2 + wrect.y;
	x = Math.max(x, 0);
	y = Math.max(y, wrect.y + myElem("imageToolbar").offsetHeight);
	myElem("bigimage").style.left = x + "px";
	myElem("bigimage").style.top = y + "px";
}
//-----------------------------------------------------------------------------------------------------------------------------------------
function scaleBigImg(wrect) {
	var targetArea, imgWidth, imgHeight, imgAspect;
	
	targetArea = getTargetArea(wrect);
	imgWidth = myElem("bigimage").offsetWidth - 20; // -20 for the border.
	imgHeight = myElem("bigimage").offsetHeight - 20; // -20 for the border.
	imgAspect = imgWidth / imgHeight;
	
	if (imgWidth > targetArea.width || imgHeight > targetArea.height) {
		if (targetArea.aspect < imgAspect) {
			myElem("bigimage").style.width = targetArea.width + "px";
		}
		else {
			myElem("bigimage").style.height = targetArea.height + "px";
		}
	}
}
//-----------------------------------------------------------------------------------------------------------------------------------------
function showBigImg(wrect) {
	var newWrect;

	myElem("bigimage").style.width = null;
	myElem("bigimage").style.height = null;
	myElem("bigimage").style.display = 'block';
	if (scaleMode === "auto") {
		scaleBigImg(wrect);
	}
	
	placeBigImg(wrect);

	// Recenter if the big image and image info caused scrollbars to appear.
	newWrect = windowRect();
	if (wrect.cx !== newWrect.cx || wrect.cy !== newWrect.cy) {
		placeBigImg(newWrect);
	}
}
//-----------------------------------------------------------------------------------------------------------------------------------------
function preloadNextPrevImgs(wrect) {
	var nextImgObj, prevImgObj;

	if (tnElemShowing.nextSibling) {
		nextImgObj = tnElemShowing.nextSibling;
		nextImgPreloader.src = nextImgObj.src.replace("tn_", getBigImgPrefix(nextImgObj, wrect, "get"));
	}

	if (tnElemShowing.previousSibling) {
		prevImgObj = tnElemShowing.previousSibling;
		prevImgPreloader.src = prevImgObj.src.replace("tn_", getBigImgPrefix(prevImgObj, wrect, "get"));
	}
}
//-----------------------------------------------------------------------------------------------------------------------------------------
function bigImgOnLoad(secondTry) {
	var wrect;

	if (inBigImgMode()) {  // In case the overlay was closed before the big image finished loading
		// Hack for Safari. Sometimes Safari fires onload event before the image dimensions are determined.
		if (!myElem("bigimage").complete && !secondTry) {
			setTimeout("bigImgOnLoad(true)", 50);
			return;
		}

		imgLoading = false;
		ignoreWinResize = true;
		hideWaitImg();
		wrect = windowRect();
		showBigImg(wrect);
		showBackground();  // In case the big image caused scrollbars to appear.  Do not need to hide the imagebackground first like must be done when the window is resized.
		ignoreWinResize = false;

		if (typeof(tnElemShowing) === "object") {
			preloadNextPrevImgs(wrect);
		}
	}
}
//-----------------------------------------------------------------------------------------------------------------------------------------
function enlargeImage(tnElemToShow) {  // The tnElemToShow parameter must be either an img object or an image file name
	var wrect, bigImgSrc;

	if (!pageHasFinishedLoading) {
		return;
	}
	ignoreWinResize = true;
	tnElemShowing = tnElemToShow;  // Keep this line before setting the source (onload will sometimes fire right away and inBigImgMode() will be incorrect)

	// No need to hide the waitImg, imageToolbar, and imagebackground here like must be done when the window is resized.
	myElem("bigimage").style.display = 'none';
	showBackground();
	showWaitImg();

	if (typeof(tnElemShowing) === "object") {
		wrect = windowRect();
		showToolbar(wrect);
		enableDisablePrevNext();
		getBigImgPrefix(tnElemShowing, wrect, "set");
		bigImgSrc = tnElemShowing.src.replace("tn_", bigImgPrefix);
	}
	else {
		bigImgSrc = tnElemShowing;
	}
	ignoreWinResize = false;

	if (myElem("bigimage").src === bigImgSrc || myElem("bigimage").src.substr(myElem("bigimage").src.lastIndexOf("/") + 1) === bigImgSrc) {  // Same image as last time.
		if (!imgLoading) {  // Window resizes can cause the same image to get redisplayed before it has finished loading.
			bigImgOnLoad(false);  // Safari will not fire the onload event when same image is enlarged twice in a row so go right to bigImgOnLoad.
		}
	}
	else {  // Different image
		imgLoading = true;
		myElem("bigimage").src = bigImgSrc;  // Start loading the image
	}
}
//-----------------------------------------------------------------------------------------------------------------------------------------
function doResize() {
	if (inBigImgMode()) {
		ignoreWinResize = true;
		myElem("imagebackground").style.display = 'none';
		myElem("imageToolbar").style.display = 'none';
		hideWaitImg();
		ignoreWinResize = false;
		enlargeImage(tnElemShowing);
	}
}
//-----------------------------------------------------------------------------------------------------------------------------------------
function windowResized() {
	var wrect = windowRect();

	if (wrect.cx !== lastWrect.cx || wrect.cy !== lastWrect.cy) {  // Make sure it's an actual window resize. (IE sends an onresize event for the body element in addition to the window)
		lastWrect = wrect;
		if (!ignoreWinResize) {  // Enlarging a big image may cause scrollbars to appear which would cause an infinite loop without this.		
			//IE likes to send a burst of onresize events all at once.  We only want the last one.
			clearTimeout(resizeTimer);
			resizeTimer = setTimeout(doResize, 1);
		}
	}
}
//-----------------------------------------------------------------------------------------------------------------------------------------
function shrinkImage() {
	if (inBigImgMode()) {
		imgLoading = false;  // Just in case and image was loading and this function was called before its onload event fired.
		tnElemShowing = false;  // Keep this before hiding the overlay elements since they may cause window resize events.

		// Hide all overlay elements
		myElem("imagebackground").style.display = 'none';
		myElem("imageToolbar").style.display = 'none';
		myElem("bigimage").style.display = 'none';
		hideWaitImg();
	}
}
//-----------------------------------------------------------------------------------------------------------------------------------------
function detectKey(e) {
	e = crossBrowserEvent(e);
	
	switch (e.keyCode) {
	case 27: //Escape
		shrinkImage();
		return false;
	case 39: //Right arrow
	case 34: //Page down
		showNextImage();
		return false;
	case 37: //Left arrow
	case 33: //Page up
		showPrevImage();
		return false;
	case 80: //p key
		if (inBigImgMode()) {
			window.open(tnElemShowing.src.replace("tn_", "mx_"));
			return false;
		}
		break;
	}
}
//-----------------------------------------------------------------------------------------------------------------------------------------
function mouseWheel(e) {
	if (inBigImgMode()) {
		e = crossBrowserEvent(e);

		if (e.wheel > 0) {
			showPrevImage();
		}
		else {
			showNextImage();
		}
	
		killEventDefaultAction(e);
	}
}
//-----------------------------------------------------------------------------------------------------------------------------------------
function highlightImg(imgObj) {
	imgObj.style.borderColor = "white";
}
//-----------------------------------------------------------------------------------------------------------------------------------------
function unHighlightImg(imgObj) {
	imgObj.style.borderColor = "#555";
}
//-----------------------------------------------------------------------------------------------------------------------------------------
function disableRightClick(e) {
	e = crossBrowserEvent(e);
	return (e.target.className.indexOf("disableRight") === -1);
}
//-----------------------------------------------------------------------------------------------------------------------------------------
function setScaleMode(btnObj, mode) {
	if (scaleMode !== mode && btnObj.style.color !== "#666") {
		if (mode === "auto" && IE6) {
			alert("This feature is not supported by Internet Explorer version 6 or less.\n\nPlease update your browser to use this feature.");
		}
		else {
			scaleMode = mode;
			enlargeImage(tnElemShowing);
		}
	}
}
//-----------------------------------------------------------------------------------------------------------------------------------------
function initPage() {
	var i, imgElems;

	document.onkeydown = detectKey;
	document.oncontextmenu = disableRightClick;
	document.onmousewheel = mouseWheel;
	if (window.addEventListener) {  // For Firefox
		window.addEventListener('DOMMouseScroll', mouseWheel, false);
	}
	window.onresize = windowResized;

	myElem("bigimage").onload = function () {
		bigImgOnLoad(false);
	};
	myElem("bigimage").onerror = function () {
		reloadImage(this);
	};

	lastWrect = windowRect();
	scaleMode = "small";
	pageHasFinishedLoading = true;
}
//-----------------------------------------------------------------------------------------------------------------------------------------
