/******************************************************
 * Name: PhotoBox Library
 * Version: 0.1
 * Date: March, 2007
 * Author: Josh Sorem
 * Credits: Inspiration and guidance taken from LightBox
 * 		http://www.huddletogether.com/projects/lightbox/lightbox.js
 * Notice: For free use and redistribution with this
 *		   notice attached.
 * Copyright 2006-2009.  All rights reserved.
 ******************************************************/

var PhotoBox = {}
PhotoBox["loadingImage"] = "images/loading.gif";
PhotoBox["closeImage"] = "images/close.gif";
PhotoBox["nextImage"] = "images/next.gif";
PhotoBox["previousImage"] = "images/previous.gif";

PhotoBox["albums"] = {}
PhotoBox["albums"].count = 0;

PhotoBox.init = function()
{
	// First step, add onclicks to each of the anchors in the document that 
	// have a target="photobox"
	var anchors = document.getElementsByTagName("a");
	var linksfound = 0;

	for(var i = 0; i < anchors.length; i++)
	{
		var anchor = anchors[i];
		if(anchor.target == "photobox")
		{	// We're only looking for anchors with targets == to "photobox".			
			var rel = anchor.rel;
			if(rel != "")
			{	// If there is a rel specified, then the user intends on having
				// the current anchor be part of an album.  Let's add the anchor
				// to the appropriate album (and build that album if necessary).
				if(!PhotoBox["albums"][rel])
				{
					PhotoBox["albums"][rel] = new Array();
					PhotoBox["albums"].count++;
				}
				PhotoBox["albums"][rel].push(anchor);
			}
			// And we'll need to add a click handler to the anchor in order to 
			// get the PhotoBox to show up when the user clicks the link.
			anchor.onclick = function() { PhotoBox.show(this); return false; }
			linksfound++;
		}
	}
	
	// We only need to continue at this point if there are links in the
	// document with target="photobox".
	if(linksfound == 0)
		return;
	
	// OK, next step will be to set up the overlay that dims out the background content.
	var overlay = document.createElement("div");
	overlay.id = "photoboxOverlay";
	overlay.onclick = function() { PhotoBox.hide(); return false; }
	overlay.style.display = "none";
	overlay.style.position = "absolute";
	overlay.style.top = "0px";
	overlay.style.left = "0px";
	overlay.style.zIndex = "100";
	overlay.style.width = "100%";
    overlay.style.filter = "alpha(opacity: 75)";  // IE/Win
    overlay.style.KHTMLOpactiy = 75/100; // Safari<1.2, Konqueror
    overlay.style.MozOpacity = 75/100; // Older Mozilla and Firefox
    overlay.style.opacity = 75/100; // Safari 1.2, newer Firefox and Mozilla, CSS3
    
	// have to set the height at some point....base it off of page height?  window height?
	document.body.insertBefore(overlay, document.body.firstChild);
	
	// Here we'll add a loading image if that image is actually found on the server.
	var preloader = new Image();
	preloader.onload = function()
	{
		var loadinglink = document.createElement("a");
		loadinglink.href = "#";
		loadinglink.onclick = function() { PhotoBox.hide(); return false; }
		overlay.appendChild(loadinglink);

		var loadingimage = document.createElement("img");
		loadingimage.src = PhotoBox["loadingImage"];
		loadingimage.id = "photoboxLoadingImage";
		loadingimage.style.position = "absolute";
		loadingimage.style.zIndex = "120";
		loadinglink.appendChild(loadingimage);

		preloader.onload = function() {}; // clear onload, as IE will flip out w/animated gifs
		
		return false;
	}
	preloader.src = PhotoBox["loadingImage"];
	
	// And, finally, we'll set up the actual display box.
	var display = document.createElement("div");
	display.id = "photoboxDisplay";
	display.style.display = "none";
	display.style.position = "absolute";
	display.style.zIndex = "140"; 
	document.body.insertBefore(display, overlay.nextSibling);
	
	// And add a close link to it
	var closelink = document.createElement("a");
	closelink.href = "#";
	closelink.title = "Click to close";
	closelink.onclick = function() { PhotoBox.hide(); return false; }
	display.appendChild(closelink);
	
	var closeimagepreload = new Image();
	closeimagepreload.onload = function()
	{
		var closeimage = document.createElement("img");
		closeimage.src = PhotoBox["closeImage"];
		closeimage.id = "closeButton";
		closeimage.style.position = "absolute";
		closeimage.style.zIndex = "200";
		closelink.appendChild(closeimage);
		
		return false;
	}
	
	closeimagepreload.src = PhotoBox["closeImage"];
	
	// And now, we'll add an img element to display the picture
	var image = document.createElement("img");
	image.id = "photoboxImage";
	display.appendChild(image);
	
	// And a div to hold the captions and navigation
	var details = document.createElement("div");
	details.id = "photoboxDetails";
	display.appendChild(details);
	
//	var navigation = document.createElement("div");
//	navigation.id = "photoboxNav";
//	navigation.style.display = "none";
//	details.appendChild(navigation);

	var caption = document.createElement("div");
	caption.id = "photoboxCaption";
	caption.style.display = "none";
	details.appendChild(caption);

	var nextlink = document.createElement("a");
	nextlink.href = "#";
	nextlink.id = "photoboxNext";
	nextlink.title = "Click for next image."
	details.appendChild(nextlink);

	var nextimage = document.createElement("img");
	nextimage.src = PhotoBox["nextImage"];
	nextimage.alt = "Next";
	nextlink.appendChild(nextimage);

	var prevlink = document.createElement("a");
	prevlink.href = "#";
	prevlink.id = "photoboxPrevious";
	prevlink.title = "Click for previous image."
	details.appendChild(prevlink);

	var previmage = document.createElement("img");
	previmage.src = PhotoBox["previousImage"];
	previmage.alt = "Previous";
	prevlink.appendChild(previmage);
}

PhotoBox.show = function(element)
{
	// set up the elements
	var overlay = document.getElementById("photoboxOverlay");
	var display = document.getElementById("photoboxDisplay");
	var caption = document.getElementById("photoboxCaption");
	var navigation = document.getElementById("photoboxNav");
	var image = document.getElementById("photoboxImage");
	var loadingImage = document.getElementById("photoboxLoadingImage");
	var details = document.getElementById("photoboxDetails");
	
	// get the details (widths, heights) for the browser
	var PageDetails = PhotoBox.getPageDetails();
	
	// center the loading image if it exists
	if(loadingImage)
	{
		loadingImage.style.top = PageDetails["YScroll"] + ((PageDetails["WindowHeight"] - 35 - loadingImage.height) / 2) + "px";
		loadingImage.style.left = ((PageDetails["PageWidth"] - 20 - loadingImage.width) / 2) + "px";
		loadingImage.style.display = "block";
	}
	
	// set up overlay and make it take up the whole page
	overlay.style.height = PageDetails["PageHeight"] + "px";
	overlay.style.display = "block";
	
	// preload the image
	var preload = new Image();
	preload.onload = function()
	{
		image.src = element.href;
		
		// center the display and make sure that the top/left values aren't negative
		var top = PageDetails["YScroll"] + ((PageDetails["WindowHeight"] - 35 - preload.height) / 2)
		var left = (PageDetails["PageWidth"] - 20 - preload.width) / 2;
		
		display.style.top = (top < 0) ? "0px" : top + "px";
		display.style.left = (left < 0) ? "0px" : left + "px";
		
		// set up the caption
		details.style.width = preload.width + "px";
		if(element.title)
		{
			caption.style.display = "block";
			caption.innerHTML = element.title;
		}
		else
		{
			caption.style.display = "none";
		}
		
		// set up the navigation
		var nextbtn = document.getElementById("photoboxNext");
		var prevbtn = document.getElementById("photoboxPrevious");
			
		nextbtn.style.display = "none";
		prevbtn.style.display = "none";
		if(PhotoBox["albums"][element.rel])
		{
//			navigation.style.display = "block";
			
			var album = PhotoBox["albums"][element.rel];
			var index = 0;
			for(var i = 0; i < album.length; i++)
			{
				if(album[i] == element)
				{
					index = i;
					break;
				}
			}

			var nexti = index + 1;
			var previ = index - 1;
			
			if(nexti < album.length)
			{
				nextbtn.onclick = function() { PhotoBox.show(album[nexti]); return false; }
				nextbtn.style.display = "block";
			}
		
			if(previ >= 0)
			{
				prevbtn.onclick = function() { PhotoBox.show(album[previ]); return false; }
				prevbtn.style.display = "block";
			}
		}
		
		// lightbox says we should pause here (250 ms) for good ol' IE
		// we'll see if we need it or not...
		
		// hide the loading image
		if(loadingImage) { loadingImage.style.display = "none"; }
		
		// lightbox also says that IE has a hard time with dropdown menus and z-index (so true...)
		var selects = document.getElementsByTagName("select");
		for(var i = 0; i < selects.length; i++)
		{
			selects[i].style.visibility = "hidden";
		}
		
		display.style.display = "block";
		
		// after the image is loaded, update the overlay height since the image may make the page bigger
		PageDetails = PhotoBox.getPageDetails();
		overlay.style.height = PageDetails["PageHeight"] + "px";
		overlay.style.width = PageDetails["PageWidth"] + "px";
		
		// listen for "x" or "esc"
		PhotoBox.listenForKeyPress(true);
		
		return false;
	}
	
	preload.src = element.href;	
}

PhotoBox.hide = function()
{
	// get elements
	var overlay = document.getElementById("photoboxOverlay");
	var display = document.getElementById("photoboxDisplay");
	
	overlay.style.display = "none";
	display.style.display = "none";
	
	// show the selects again...stupid IE
	var selects = document.getElementsByTagName("select");
	for(var i = 0; i < selects.length; i++)
	{
		selects[i].style.visibility = "visible";
	}
	
	// stop listening for "x" or "esc"
	PhotoBox.listenForKeyPress(false);
}

PhotoBox.listenForKeyPress = function(active)
{
	if(document.onkeydown)
	{
		PhotoBox["originalKeypressHandler"] = document.onkeydown;
	}
	
	if(active)
	{
		document.onkeydown = function(e)
		{
			e = (e) ? e : window.event;
			var key = (e.charCode) ? e.charCode : e.keyCode;
			
			switch(key)
			{
				case 27:	// ESC
				case 88:	// X
					PhotoBox.hide();
					break;
				case 37:	// Left Arrow
				case 80:	// P
					var prevbtn = document.getElementById("photoboxPrevious");
					if(prevbtn && prevbtn.onclick)
					{
						prevbtn.onclick();
						return false;
					}
					break;
				case 39:	// Right Arrow
				case 78:	// N
					var nextbtn = document.getElementById("photoboxNext");
					if(nextbtn && nextbtn.onclick)
					{
						nextbtn.onclick();
						return false;p
					}
					break;
				default:
					//alert(key);
					break;
			}
		}
	}
	else
	{
		if(PhotoBox["originalKeypressHandler"])
		{
			document.onkeydown = PhotoBox["originalKeypressHandler"];
		}
		else
		{
			document.onkeydown = "";
		}
	}
}

PhotoBox.getPageDetails = function()
{	// essentially taken directly from http://www.huddletogether.com/projects/lightbox/lightbox.js
	// and adapted to suit my tastes
	var xScroll, yScroll;
	
	if (window.innerHeight && window.scrollMaxY) {	
		xScroll = document.body.scrollWidth;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}
	
	var windowWidth, windowHeight;
	if (self.innerHeight) {	// all except Explorer
		windowWidth = self.innerWidth;
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}	
	
	// for small pages with total height less than height of the viewport
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else { 
		pageHeight = yScroll;
	}

	// for small pages with total width less than width of the viewport
	if(xScroll < windowWidth){	
		pageWidth = windowWidth;
	} else {
		pageWidth = xScroll;
	}

	var scrollpos;

	if (self.pageYOffset) {
		scrollpos = self.pageYOffset;
	} else if (document.documentElement && document.documentElement.scrollTop){	 // Explorer 6 Strict
		scrollpos = document.documentElement.scrollTop;
	} else if (document.body) {// all other Explorers
		scrollpos = document.body.scrollTop;
	}

	var details = 
	{
		PageWidth: pageWidth,
		PageHeight: pageHeight,
		WindowWidth: windowWidth,
		WindowHeight: windowHeight,
		YScroll: scrollpos,
		XScroll: ''
	}
	
	return details;
}
