/*
	Lightbox JS: Fullsize Image Overlays 
	by Lokesh Dhakar - http://www.huddletogether.com

	For more information on this script, visit:
	http://huddletogether.com/projects/lightbox/

	Licensed under the Creative Commons Attribution 2.5 License - http://creativecommons.org/licenses/by/2.5/
	(basically, do anything you want, just leave my name and link)

	Table of Contents
	-----------------
	Configuration

	Functions
	- getPageScroll()
	- getPageSize()
	- pause()
	- getKey()
	- listenKey()
	- showLightbox()
	- hideLightbox()
	- initLightbox()
	- addLoadEvent()

	Function Calls
	- addLoadEvent(initLightbox)

*/



//
// Configuration
//

// If you would like to use a custom loading image or close button reference them in the next two lines.
var imgPath = 'media/images/lightbox';
var loadingImage = imgPath + 'Loading.gif';		
var closeButton = imgPath + 'Close.gif';		

var shadowNE = imgPath + 'ShadowNE.png';
var shadowSW = imgPath + 'ShadowSW.png';
var shadowSE = imgPath + 'ShadowSE.png';
var shadowNW = imgPath + 'ShadowNW.png';

var timer;
var objOverlay, objLightbox, objImage;

var imgPreload;

var width, height, x, y, dWidth, dHeight, dX, dY;

var heightDone = false;
var widthDone = false;

var steps = 10;  // number of steps while enlarging/shrinking
var interval = 25;  // number of milliseconds between steps

var minOpac = 10;  // minimum opacity (0 to 100)
var dO = 100 - minOpac;  // change in opacity



//
// getPageScroll()
// Returns array with x,y page scroll values.
// Core code from - quirksmode.org
//
function getPageScroll(){

	var yScroll;

	if(self.pageYOffset){
		yScroll = self.pageYOffset;
	}else if(document.documentElement && document.documentElement.scrollTop){	// Explorer 6 Strict
		yScroll = document.documentElement.scrollTop;
	}else if(document.body){	// all other Explorers
		yScroll = document.body.scrollTop;
	}

	var arrayPageScroll = new Array('',yScroll) 
	return arrayPageScroll;
}


//
// getPageSize()
// Returns array with page width, height and window width, height
// Core code from - quirksmode.org
// Edit for Firefox by pHaez
//
function getPageSize(){

	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
	var pageHeight;
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	}else{ 
		pageHeight = yScroll;
	}

	// for small pages with total width less than width of the viewport
	var pageWidth;
	if(xScroll < windowWidth){
		pageWidth = windowWidth;
	}else{
		pageWidth = xScroll;
	}

	var arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight) 
	return arrayPageSize;
}


//
// pause(numberMillis)
// Pauses code execution for specified time. Uses busy code, not good.
// Code from http://www.faqts.com/knowledge_base/view.phtml/aid/1602
//
function pause(numberMillis){
	var now = new Date();
	var exitTime = now.getTime() + numberMillis;
	while(true){
		now = new Date();
		if(now.getTime() > exitTime)
			return;
	}
}

//
// getKey(key)
// Gets keycode. If 'x' is pressed then it hides the lightbox.
//
function getKey(e){
	if(e == null){	// ie
		keycode = event.keyCode;
	}else{	// mozilla
		keycode = e.which;
	}
	key = String.fromCharCode(keycode).toLowerCase();

	if(key == 'x'){	hideLightbox(); }
}


//
// listenKey()
//
function listenKey(){	document.onkeypress = getKey; }


//
// showLightbox()
// Preloads images. Places new image in lightbox then centers and displays.
//
function showLightbox(objLink, e){
	// prep objects
//	var objLink;

	if(!e) e = window.event;
//	if(e.target) objLink = e.target;
//	else if(e.srcElement) objLink = e.srcElement;

	objOverlay = document.getElementById('overlay');
	objLightbox = document.getElementById('lightbox');
	objImage = document.getElementById('lightboxImage');
	var objLoadingImage = document.getElementById('loadingImage');

	var arrayPageSize = getPageSize();
	var arrayPageScroll = getPageScroll();

	// get dimensions and position of small image on page
	width = objLink.firstChild.width;
	height = objLink.firstChild.height;

	if(e.offsetX){
		// calculate the position from the coordinates of the click
		// does not work in firefox
		x = e.clientX - e.offsetX;
		y = arrayPageScroll[1] + e.clientY - e.offsetY;
	}else{
		// get position for firefox
		// will work in other browsers but not IE
		x = objLink.firstChild.x + document.getElementById("container").offsetLeft;  // adjusts for offset of container. moves it too far in safari
		y = objLink.firstChild.y;
	}


//alert('x: '+x+', y: '+y);


	// adjust for shadow around lightbox
	x -= 4;
	y -= 4;

	// center loadingImage on small image if it exists
	if(objLoadingImage){
		objLoadingImage.style.top = Math.round(y + ((height - objLoadingImage.height) / 2)) + 'px';
		objLoadingImage.style.left = Math.round(x + ((width - objLoadingImage.width) / 2)) + 'px';
		objLoadingImage.style.display = 'block';
	}

	// set height of Overlay to take up whole page and show
	objOverlay.style.height = arrayPageSize[1] + 'px';
	objOverlay.style.display = 'block';

	// preload image
	imgPreload = new Image();

	imgPreload.onload=function(){
		objImage.src = objLink.href;

		// center lightbox and make sure that the top and left values are not negative
		// and the image placed outside the viewport
		var lightboxTop = Math.round(arrayPageScroll[1] + ((arrayPageSize[3] - imgPreload.height) / 2) - 4);
		var lightboxLeft = Math.round(((arrayPageSize[0] - imgPreload.width) / 2) - 4);

		// get changes in dimensions and position from small image to large image
		dWidth = imgPreload.width - width;
		dHeight = imgPreload.height - height;
		dX = lightboxLeft - x;
		dY = lightboxTop - y;

		// A small pause between the image loading and displaying is required with IE,
		// this prevents the previous image displaying for a short burst causing flicker.
/*		if(navigator.appVersion.indexOf("MSIE")!=-1){
			pause(250);
		}
*/
		if(objLoadingImage){	objLoadingImage.style.display = 'none'; }

		// Hide select boxes as they will 'peek' through the image in IE
		var selects = document.getElementsByTagName("select");
		for(var i = 0; i != selects.length; i++){
			selects[i].style.visibility = "hidden";
		}

		objLightbox.style.display = 'block';

		// animate the image enlarging
		heightDone = false;
		widthDone = false;
		enlarge(width, height, x, y, minOpac);

		// After image is loaded, update the overlay height as the new image might have
		// increased the overall page height.
		arrayPageSize = getPageSize();
		objOverlay.style.height = (arrayPageSize[1] + 'px');

		// Check for 'x' keypress
		listenKey();

		return false;
	}

	imgPreload.src = objLink.href;
}


//
//enlarge()
//
function enlarge(curWidth, curHeight, curLeft, curTop, opacity){
	// calculate new size and position
	if(curWidth < imgPreload.width){
		curWidth += dWidth/steps;
		curLeft += dX/steps;

		if(curWidth >= imgPreload.width){
			// image was enlarged too much due to rounding, so fix size and position
			curWidth = imgPreload.width;
			curLeft = x + dX;
			widthDone = true;
		}
	}

	if(curHeight < imgPreload.height){
		curHeight += dHeight/steps;
		curTop += dY/steps;

		if(curHeight >= imgPreload.height){
			// image was enlarged too much due to rounding, so fix size and position
			curHeight = imgPreload.height;
			curTop = y + dY;
			heightDone = true;
		}
	}

	if(opacity < 100){
		opacity += dO/steps;

		if(opacity > 100){
			opacity = 100;
		}
	}

	// set size and position
	objImage.style.width = Math.round(curWidth) + "px";
	objImage.style.height = Math.round(curHeight) + "px";

	objLightbox.style.left = (curLeft < 0) ? "0px" : Math.round(curLeft) + "px";
	objLightbox.style.top = (curTop < 0) ? "0px" : Math.round(curTop) + "px";

	// set opacity
	objLightbox.style.opacity = opacity/100;
	// for IE
	objImage.style.filter = "alpha(opacity=" + opacity + ")";

	if(heightDone && widthDone){
		clearTimeout(timer);
		// show the close button
		document.getElementById('closeButton').style.display = '';
	}else{
		timer = setTimeout("enlarge("+curWidth+", "+curHeight+", "+curLeft+", "+curTop+", "+opacity+")", interval);
	}
}


//
//shrink()
//
function shrink(curWidth, curHeight, curLeft, curTop, opacity){
	// calculate new size and position
	if(curWidth > width){
		curWidth -= dWidth/steps;
		curLeft -= dX/steps;
		if(curWidth <= width){
			// image was shrunk too much due to rounding, so fix size and position
			curWidth = width;
			curLeft = x;
			widthDone = true;
		}
	}

	if(curHeight > height){
		curHeight -= dHeight/steps;
		curTop -= dY/steps;
		if(curHeight <= height){
			// image was shrunk too much due to rounding, so fix size and position
			curHeight = height;
			curTop = y;
			heightDone = true;
		}
	}

	if(opacity > minOpac){
		opacity -= dO/steps;

		if(opacity < minOpac){
			opacity = minOpac;
		}
	}

	// set size and position
	objImage.style.width = Math.round(curWidth) + "px";
	objImage.style.height = Math.round(curHeight) + "px";

	objLightbox.style.left = (curLeft < 0) ? "0px" : Math.round(curLeft) + "px";
	objLightbox.style.top = (curTop < 0) ? "0px" : Math.round(curTop) + "px";

	// set opacity
	objLightbox.style.opacity = opacity/100;
	// for IE
	objImage.style.filter = "alpha(opacity=" + opacity + ")";

	if(heightDone && widthDone){
		clearTimeout(timer);
		hideLightbox();
	}else{
		timer = setTimeout("shrink("+curWidth+", "+curHeight+", "+curLeft+", "+curTop+", "+opacity+")", interval);
	}
}


//
// closeLightbox()
//
function closeLightbox(){
	// hide the close button
	document.getElementById('closeButton').style.display = 'none';

	// animate the image shrinking
	heightDone = false;
	widthDone = false;
	shrink(width + dWidth, height + dHeight, x + dX, y + dY, 100);
}


//
// hideLightbox()
//
function hideLightbox(){
	// get objects
	objOverlay = document.getElementById('overlay');
	objLightbox = document.getElementById('lightbox');

	// hide lightbox and overlay
	objOverlay.style.display = 'none';
	objLightbox.style.display = 'none';

	// make select boxes visible
	var selects = document.getElementsByTagName("select");
    for(var i = 0; i != selects.length; i++){
		selects[i].style.visibility = "visible";
	}

	// disable keypress listener
	document.onkeypress = '';
}


//
// initLightbox()
// Function runs on window load, going through link tags looking for rel="lightbox".
// These links receive onclick events that enable the lightbox display for their targets.
// The function also inserts html markup at the top of the page which will be used as a
// container for the overlay pattern and the inline image.
//
function initLightbox(){

	if(!document.getElementsByTagName){ return; }
	var anchors = document.getElementsByTagName("a");

	// loop through all anchor tags
	for(var i=0; i<anchors.length; i++){
		var anchor = anchors[i];

		if(anchor.getAttribute("href") && (anchor.getAttribute("target") == "lightbox")){  // changed "rel" to "target" to work with existing site structure
			anchor.firstChild.setAttribute('title', 'Click to enlarge');
		//	var oldClassName = anchor.firstChild.getAttribute('class');  // this doesn't work in IE
		//	anchor.firstChild.setAttribute('class', 'lightboxSmallImage' + ((oldClassName != null)?' '+oldClassName:''));  // styles are not applied when using this method
			var oldClassName = anchor.firstChild.className;
			anchor.firstChild.className = 'lightboxSmallImage' + ((oldClassName != null)?' '+oldClassName:'');
			anchor.onclick = function (e) {showLightbox(this, e); return false;}
		}
	}

	// the rest of this code inserts html at the top of the page that looks like this:
	//
	// <div id="overlay">
	//	<a href="#" onclick="closeLightbox(); return false;"><img id="loadingImage" /></a>
	// </div>
	// <div id="lightbox">
	//	<div id="shadowNE">
	//		<div id="shadowSW">
	//			<div id="shadowSE">
	//				<div id="shadowNW">
	//					<a href="#" onclick="closeLightbox(); return false;" title="Click to close">
	//						<img id="closeButton" />
	//						<img id="lightboxImage" />
	//					</a>
	//				</div>
	//			</div>
	//		</div>
	//	</div>
	// </div>

	var objBody = document.getElementsByTagName("body").item(0);

	// create overlay div and hardcode some functional styles (aesthetic styles are in CSS file)
	var objOverlay = document.createElement("div");
	objOverlay.setAttribute('id','overlay');
	objOverlay.onclick = function () {closeLightbox(); return false;}
	objOverlay.style.display = 'none';
	objOverlay.style.position = 'absolute';
	objOverlay.style.top = '0';
	objOverlay.style.left = '0';
	objOverlay.style.zIndex = '90';
 	objOverlay.style.width = '100%';
	objBody.insertBefore(objOverlay, objBody.firstChild);

	var arrayPageSize = getPageSize();
	var arrayPageScroll = getPageScroll();

	// preload and create loader image
	var imgPreloader = new Image();

	// if loader image found, create link to hide lightbox and create loadingimage
	imgPreloader.onload=function(){

		var objLoadingImageLink = document.createElement("a");
		objLoadingImageLink.setAttribute('href','#');
		objLoadingImageLink.onclick = function () {closeLightbox(); return false;}
		objOverlay.appendChild(objLoadingImageLink);

		var objLoadingImage = document.createElement("img");
		objLoadingImage.src = loadingImage;
		objLoadingImage.setAttribute('id','loadingImage');
		objLoadingImage.style.position = 'absolute';
		objLoadingImage.style.zIndex = '150';
		objLoadingImageLink.appendChild(objLoadingImage);

		imgPreloader.onload=function(){};	// clear onLoad, as IE will flip out w/animated gifs

		return false;
	}

	imgPreloader.src = loadingImage;

	// create lightbox div, same note about styles as above
	var objLightbox = document.createElement("div");
	objLightbox.setAttribute('id','lightbox');
	objLightbox.style.display = 'none';
	objLightbox.style.position = 'absolute';
	objLightbox.style.zIndex = '100';
	objBody.insertBefore(objLightbox, objOverlay.nextSibling);

	// create shadow
	var objShadowNE = document.createElement("div");
	objShadowNE.setAttribute('id','shadowNE');
	objLightbox.appendChild(objShadowNE);

	var objShadowSW = document.createElement("div");
	objShadowSW.setAttribute('id','shadowSW');
	objShadowNE.appendChild(objShadowSW);

	var objShadowSE = document.createElement("div");
	objShadowSE.setAttribute('id','shadowSE');
	objShadowSW.appendChild(objShadowSE);

	var objShadowNW = document.createElement("div");
	objShadowNW.setAttribute('id','shadowNW');
	objShadowSE.appendChild(objShadowNW);

	// create link
	var objLink = document.createElement("a");
	objLink.setAttribute('href','#');
	objLink.setAttribute('title','Click to close');
	objLink.onclick = function () {closeLightbox(); return false;}
	objShadowNW.appendChild(objLink);

	// preload and create close button image
	var imgPreloadCloseButton = new Image();

	// if close button image found,
	imgPreloadCloseButton.onload=function(){

		var objCloseButton = document.createElement("img");
		objCloseButton.src = closeButton;
		objCloseButton.setAttribute('id','closeButton');
		objCloseButton.style.position = 'absolute';
		objCloseButton.style.zIndex = '200';
		objCloseButton.style.display = 'none';
		objLink.appendChild(objCloseButton);

		return false;
	}

	imgPreloadCloseButton.src = closeButton;

	// preload shadow images
	var imgPreloadShadowNE = new Image();
	var imgPreloadShadowSW = new Image();
	var imgPreloadShadowSE = new Image();
	var imgPreloadShadowNW = new Image();
	
	imgPreloadShadowNE.src = shadowNE;
	imgPreloadShadowSW.src = shadowSW;
	imgPreloadShadowSE.src = shadowSE;
	imgPreloadShadowNW.src = shadowNW;

	// create image
	var objImage = document.createElement("img");
	objImage.setAttribute('id','lightboxImage');
	objLink.appendChild(objImage);
}


//
// addLoadEvent()
// Adds event to window.onload without overwriting currently assigned onload functions.
// Function found at Simon Willison's weblog - http://simon.incutio.com/
//
function addLoadEvent(func){
	var oldonload = window.onload;
	if(typeof window.onload != 'function'){
		window.onload = func;
	}else{
		window.onload = function(){
			oldonload();
			func();
		}
	}
}


addLoadEvent(initLightbox);	// run initLightbox onLoad
