var imgIndex = 0;
var imgArray = new Array();
var progressBarTimer;
var bigimage;
var counter;
var scrollTop;
var thumbs;


var AMZN = "http://amzn.valamit.com/";
//var AMZN = "../../";

document.addEventListener("DOMContentLoaded", onDomLoad, false);

function onDomLoad() {
	handleNavigationFrames();
	counter = document.getElementById('counter');
	if (counter) {
		counter.src = AMZN + "Resources/pbar.gif";
		counter.onclick = function() {
			gotoContentPage();
		}
	}
	bigimage = document.getElementById("bigimage");	
	if (bigimage) {
		bigimage.onclick = function() {
			gotoContentPage();
		}
	}
	imgArray = fillImageArray();
	locationChanged();
	handleGestures();
	handleMouseWheel();
}


window.onhashchange = locationChanged;
function locationChanged() {
	if (location.hash.length == 0 || location.hash == "#") {
		hideImage();
		document.documentElement.scrollTop = scrollTop;
		document.body.scrollTop = scrollTop;
		if (document.location.href.indexOf('TopPhotos') < 0) {
			setBackgroundImage();
		}
		return;
	}

	var imgSource = unescape(location.hash.substring(1, 99));
	if (imgSource)  {
		scrollTop = document.documentElement.scrollTop == 0 ? document.body.scrollTop : document.documentElement.scrollTop;
		document.getElementById("container").style.display = "none";
		imgIndex = findImageIndex(imgArray, imgSource);
		showImage(imgIndex);
	} 
}


function showImage(imgIndex) {
	bigimage.style.visibility ="hidden";
	document.documentElement.style.overflow = "hidden";
	var glassPane = document.getElementById("glassPane");
	if (glassPane) {
		glassPane.style.display = "block";
	}
	progressBarTimer = setTimeout("document.getElementById('counter').style.visibility = 'visible'", 600);

	hideInfo();
	if (imgIndex < 0) {
		imgIndex = 0;
	}
	var preloadedImage = new Image();
	preloadedImage.onload = imageLoaded;	
	preloadedImage.title = imgArray[imgIndex].title;
	preloadedImage.id = imgArray[imgIndex].id;
	preloadedImage.wiki = imgArray[imgIndex].wiki;

	//preloadedImage.src = "images/" + imgArray[imgIndex].src + ".jpg";
	preloadedImage.src = AMZN + getCurrentPage() + "/images/" + imgArray[imgIndex].src + ".jpg";
}




function hideImage() {
	// to avoid flickering
	if (bigimage){
		bigimage.src = "";
		bigimage.style.visibility ="hidden";
	}
	var glassPane = document.getElementById("glassPane");
	if (glassPane) {
		glassPane.style.display = "none";
	}
	hideInfo();
	document.documentElement.style.overflow = "auto";
	document.getElementById("container").style.display = "block";
}


function gotoContentPage() {
	document.location.hash='';
}


function isImageVisible() {
	var container = document.getElementById("container");
	if (container) {
		return container.style.display == "none";
	}
}


function imageLoaded() {

	// adjust preloaded image width, height and position
	var preloadedImage = this;
	preloadedImage.origWidth = preloadedImage.width;
	preloadedImage.origHeight = preloadedImage.height;
	if (!isMobile()) {
		fitToScreen(preloadedImage);
	}

	// copy attributes from the preloaded image to the image contained in the html document
	bigimage.src = preloadedImage.src;
	bigimage.width = preloadedImage.width;      
	bigimage.height = preloadedImage.height;
	bigimage.style.top = preloadedImage.style.top;
	bigimage.origWidth = preloadedImage.origWidth;
	bigimage.origHeight = preloadedImage.origHeight;
	bigimage.style.border = preloadedImage.style.border;	

	if (isMobile()) {
		bigimage.removeAttribute('style');
		bigimage.className = "bigImageMobile";
		window.scrollTo(0,1);
	}

	// prepare the title of the htmlImage
	var lastSlash = preloadedImage.src.lastIndexOf("/");
	var lastPoint = preloadedImage.src.lastIndexOf(".");
	var imgSource = preloadedImage.src.substring(lastSlash + 1, lastPoint);
	imgSource = imgSource.replace("%20", " ");
	imgSource = imgSource.replace("%20", " ");
	bigimage.filename = imgSource + ".jpg";
	bigimage.title = preloadedImage.title;
	bigimage.wiki = preloadedImage.wiki;
	bigimage.srcid = preloadedImage.id;
	showInfo();	
	cacheNeighbourImages();

	clearTimeout(progressBarTimer);
	document.getElementById('counter').style.visibility = "hidden";
	progressBarTimer=setTimeout("bigimage.style.visibility = 'visible'", 200);	
}


function isMobile() {
	var agent = window.navigator.userAgent;
	if (agent.indexOf("obile") > 0 || agent.indexOf("ndroid") > 0){
		return true;
	}
	return false;
}


function fitToScreen(img) {
	if (!img) {
		return;
	}

	var	windowWidth = document.documentElement.clientWidth;
	var	windowHeight = document.documentElement.clientHeight;

	// no margin in full screen mode
	var pictureMargin = 20;
	img.style.border = "1px solid gray";
	if (window.screen.height - windowHeight < 2) {
		pictureMargin = 0;
		if ((img.origWidth >= window.screen.width) || (img.origHeight >= window.screen.height)) {
			img.style.border = "none";
		}
	}

	var clientWidth  = windowWidth - 2 * pictureMargin;
	var clientHeight = windowHeight - 2 * pictureMargin;

	var WidthRatio  = img.origWidth / clientWidth;
	var HeightRatio = img.origHeight / clientHeight;
	var Ratio = WidthRatio > HeightRatio ? WidthRatio : HeightRatio;

	img.width = Math.min(img.origWidth, img.origWidth / Ratio);
	img.height = Math.min(img.origHeight, img.origHeight / Ratio);
	img.style.top = pictureMargin - 1 + (clientHeight - img.height)/2 +'px';
}



function showInfo() {
	if (!isImageVisible()) return;
	var infoFrame = document.getElementById("infoFrame");
	if (!infoFrame.src) {
		infoFrame.src = "../../info.html";
	} else {
		infoFrame.contentWindow.updateInfos();
	}
	if (!isMobile()) infoFrame.style.visibility = "visible";
}


function hideInfo() {
	if (document.getElementById("info")) {
		document.getElementById("info").style.visibility = "hidden";
		document.getElementById("infoFrame").style.visibility = "hidden";
	}
}



function fillImageArray() {
	if (imgArray.length > 0) {
		return imgArray;
	}
	var anchors = document.getElementsByTagName("a"); 
	var al = anchors.length;
	var k = 0;
	for (var i=0; i<al; i++) {
		var imgName = unescape(anchors[i].hash.substring(1, 99));
		if (imgName) {
			var foto = new Object();
			foto.src = imgName;
			foto.title = anchors[i].title;
			foto.wiki = anchors[i].getAttribute("data-wiki");
			foto.id = anchors[i].getElementsByTagName("span")[0].id;
			imgArray[k++] = foto;
		}
	}
	return imgArray;
}


function findImageIndex(imgArray, imgSource) {
	var i = imgArray.length;
	while (i--) {
		if (imgSource == imgArray[i].src) {
			return i;
		};
	}
	return -1;
}


function showPage(imgIndex) {
	if (imgIndex < 0) { imgIndex = imgArray.length - 1; }
	if (imgIndex > imgArray.length - 1) { imgIndex = 0; }
	if (location.hash.length > 0) {
		location.hash = imgArray[imgIndex].src;
	} 
}


function cacheNeighbourImages() {
	var nextImgIndex = parent.imgIndex + 1;
	var prevImgIndex = parent.imgIndex - 1;
	if (nextImgIndex > parent.imgArray.length - 1) { nextImgIndex = 0; }
	if (prevImgIndex < 0 ) { prevImgIndex = 0; }
	var amzn = AMZN + getCurrentPage() + "/images/";
	var nextImageCached = new Image();
	nextImageCached.src = amzn + imgArray[nextImgIndex].src + ".jpg";
	nextImageCached.onload = function() {
		var prevImageCached = new Image();
		prevImageCached.src = amzn + imgArray[prevImgIndex].src + ".jpg";
	}
}


function setBackgroundImage() { 
	if ("url('" + AMZN + getCurrentPage() + "/images/thumbs.jpg')" == thumbs) return;
	thumbs = "url('" + AMZN + getCurrentPage() + "/images/thumbs.jpg')"; 
	var elems = document.querySelectorAll(".L,.P,.LW");
	var i = elems.length;
	while(i--) {
		elems[i].style.backgroundImage = thumbs;
	}

}


function getCurrentPage() {
	var temp = new Array();
	temp = document.location.pathname.split("/");
	return temp[temp.length-3] + "/" + temp[temp.length-2];
}





//--------------------------------------------------------------------------------------------------
// window/mouse/keyboard/touch event handling
//--------------------------------------------------------------------------------------------------
window.onresize = function() {
	fitToScreen(bigimage);
}  


document.onkeydown = function(evt) {
	// no image no event handling
	if (!isImageVisible()) {
		return;
	}
	// workaround for IE and Firefox differences 
	evt = (evt) ? evt : ((event) ? event : null);
	switch(evt.keyCode) {
		case 13 : imgIndex++;  break;
		case 32 : imgIndex++;  break;
		case 34 : imgIndex++;  break;
		case 39 : imgIndex++;  break;
		case 40 : imgIndex++;  break;
		case 33 : imgIndex--;  break; 
		case 37 : imgIndex--;  break;
		case 38 : imgIndex--;  break;
		case 35 : imgIndex = imgArray.length - 1;  break;
		case 36 : imgIndex = 0;  break;
		case 27 : location.hash="";
		default : return;
	}
	showPage(imgIndex);
}



function handleNavigationFrames() {
	var touchStartX;
	var touchStartY;
	var touchStartTime;
	var navFrame = document.getElementById('navFrame');
	var infoFrame = document.getElementById('infoFrame');
	document.onmouseover = document.onmousemove = function(e) {
		if (isMobile()) return;
		var windowWidth =  document.documentElement.clientWidth;
		var x = e.pageX;
		if (x < 20) showFrame(navFrame);
		if (x > 200) hideFrame(navFrame);
		if (x > windowWidth - 20) showFrame(infoFrame);
		if (x < windowWidth - 200) hideFrame(infoFrame);
	};	
	document.ontouchstart = function(e) {
		if (e.touches[0]) {
			touchStartX = e.touches[0].screenX;
			touchStartY = e.touches[0].screenY;
			touchStartTime = new Date().getTime();
		}
		return true;
	}
	document.ontouchmove = function(e) {
		if (touchStartX < 40) e.preventDefault();
	}
	
	document.ontouchend = function(e) {
		if (isImageVisible()) return;
		var triggerOffset = getTriggerOffset(touchStartTime);
		var x = e.changedTouches[0].screenX - touchStartX;
		if (x > triggerOffset && touchStartX < 40) {
			showFrame(navFrame);
		} else {
			hideFrame(navFrame);
		}
	}
}


function showFrame(frame) {
	if (frame.className != "navFrameVisible") {
		frame.className = "navFrameVisible";
	}
}


function hideFrame(frame) {
	if (frame.className != "navFrameHidden") {
		frame.className = "navFrameHidden";
	}
}


function getTriggerOffset(touchStartTime) {
	var triggerOffset = 160;
	if (new Date().getTime() - touchStartTime < 360) {
		triggerOffset = 20;
	}
	return triggerOffset;
}


function handleGestures() {
	var touchStartX;
	var touchStartY;
	var touchStartTime = 0;
	var bigimageLeft = 0;
	bigimage.addEventListener('touchstart', function(e) {
		if (e.touches[0]) {
			touchStartX = e.touches[0].pageX;
			touchStartY = e.touches[0].pageY;
			touchTime = new Date().getTime();
			// double tap disabled, acts like single tap
			if (touchTime - touchStartTime < 400) {
				gotoContentPage();
				e.preventDefault();
				return true;
			}
			touchStartTime = new Date().getTime();
		}
	} , false);  
	
	bigimage.addEventListener('touchmove', function(e) {
		bigimageLeft = e.changedTouches[0].pageX - touchStartX;
		bigimage.style.marginLeft = bigimageLeft + "px";
		e.preventDefault();
	}, false); 	

	bigimage.addEventListener('touchend', function(e) {
		if (!touchStartX) return false;
		bigimageLeft = 0;
		var triggerOffset = getTriggerOffset(touchStartTime);
        if (bigimage.offsetLeft > triggerOffset) {
        	bigimage.className = "bigImageMobileRight";
        	imgIndex--;
        } else if (bigimage.offsetLeft < -triggerOffset) {
			bigimage.className = "bigImageMobileLeft";
        	imgIndex++;
        } else if (bigimage.offsetLeft != 0) {
        	bigimage.style.marginLeft = 0;
        	e.preventDefault();
        }
        return false;
	} , false);
	
	bigimage.addEventListener('transitionend', function(e) {
		showPage(imgIndex);
	}, false);
	
	bigimage.addEventListener('webkitTransitionEnd', function(e) {
		showPage(imgIndex);
	}, false);		

}


function handleMouseWheel() {
	if (window.addEventListener) {
		window.addEventListener('DOMMouseScroll', handleMouseWheelEvent, false);  
	}
	// IE mouse scroll event handler.
	window.onmouseheel = document.onmousewheel = function() {
		handleMouseWheelEvent(event);
	}	
}


function handleMouseWheelEvent(evt) {
	// no image no event handling
	if (!isImageVisible()) {
		return;
	}
	var scrollDirection;    
	if (evt.detail) {
		scrollDirection = evt.detail;
	} else if (evt.wheelDelta) { 
		scrollDirection = -evt.wheelDelta;
	}
	if (scrollDirection > 0) {
		imgIndex++;
	} else {
		imgIndex--;
	}
	showPage(imgIndex);
}




