/*

	Lightbox "1.5" by Jonathan Amend is a standalone Lightbox 2.0 with video support and without Effects

// -----------------------------------------------------------------------------------
//
//	Lightbox v2.04
//	by Lokesh Dhakar - http://www.lokeshdhakar.com
//	Last Modification: 2/9/08
//
//	For more information, visit:
//	http://lokeshdhakar.com/projects/lightbox2/
//
//	Licensed under the Creative Commons Attribution 2.5 License - http://creativecommons.org/licenses/by/2.5/
//  	- Free for use in both personal and commercial projects
//		- Attribution requires leaving author name, author link, and the license info intact.
//	
//  Thanks: Scott Upton(uptonic.com), Peter-Paul Koch(quirksmode.com), and Thomas Fuchs(mir.aculo.us) for ideas, libs, and snippets.
//  		Artemy Tregubenko (arty.name) for cleanup and help in updating to latest ver of proto-aculous.
//
// -----------------------------------------------------------------------------------
/*

    Table of Contents
    -----------------
    Configuration

    Lightbox Class Declaration
    - initialize()
    - updateImageList()
    - start()
    - changeImage()
    - resizeImageContainer()
    - showImage()
    - updateDetails()
    - updateNav()
    - enableKeyboardNav()
    - disableKeyboardNav()
    - keyboardAction()
    - preloadNeighborImages()
    - end()
    
    Function Calls
    - document.observe()
   
*/
// -----------------------------------------------------------------------------------




//
// Configuration
//

// If you would like to use a custom loading image or close button reference them in the next two lines.
var loadingImage = 'img/loading.gif';		
var closeButton = 'img/close.gif';		
var imageArray;
var activeImage;
var ajaxCache;

var lightbox;

//
// 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;
	}
}

function Lightbox() {
	var fileLoadingImage =         '/images/lightbox/loading.gif';  
    var fileBottomNavCloseImage =  '/images/lightbox/closelabel.gif';
    var borderSize = 10;
    var labelImage = "Image";
	var labelOf = "/";
    
    this.imageArray = [];
    this.activeImage = undefined;
    this.ajaxCache = [];
    
	if (!document.getElementsByTagName){ return; }
	
	this.start = function(imageLink) {
		// Hide select boxes as they will 'peek' through the image in IE
		selects = document.getElementsByTagName("select");
		for (i = 0; i != selects.length; i++) {
			selects[i].style.visibility = "hidden";
		}
		objects = document.getElementsByTagName("object");
		for (i = 0; i != objects.length; i++) {
			if (objects[i].getAttribute("rel") != 'lightbox') objects[i].style.visibility = "hidden";
		}
		embeds = document.getElementsByTagName("embed");
		for (i = 0; i != embeds.length; i++) {
			if (embeds[i].getAttribute("rel") != 'lightbox') embeds[i].style.visibility = "hidden";
		}
		
		var arrayPageSize = this.getPageSize();
		// set height of Overlay to take up whole page
		this.overlay.style.height = (arrayPageSize[1] + 'px');
        this.overlay.style.display = 'block';

		this.imageArray = [];
        var imageNum = 0;
	        
		if ((imageLink.rel == 'lightbox')){
	        // if image is NOT part of a set, add single image to imageArray
	        this.imageArray.push([imageLink.href, imageLink.title]);        
	    } else {
	        // if image is part of a set..
	        var anchors = document.getElementsByTagName("a");
	
			// loop through all anchor tags
			var j = 0;
			for (var i=0; i<anchors.length; i++){
				var anchor = anchors[i];
		
				if (anchor.getAttribute("href") && (anchor.getAttribute("rel") == imageLink.rel)){
					this.imageArray.push([anchor.href, anchor.title]);
					if (anchor.href == imageLink.href) imageNum = j;
					j++;
				}
			}
	    }
	
		var arrayPageScroll = this.getPageScroll();
		var lightboxTop = arrayPageScroll[1] + (arrayPageSize[3] / 10);
		var lightboxLeft = arrayPageScroll[0];
				
		this.lightbox.style.top = (lightboxTop < 0) ? "0px" : lightboxTop + "px";
		this.lightbox.style.left = (lightboxLeft < 0) ? "0px" : lightboxLeft + "px";
		
		this.lightbox.style.display = 'block';
		
		this.changeImage(imageNum);
	}
	
	this.changeImage = function(imageNum) {
		this.activeImage = imageNum;
		
		//this.loading.style.display = 'block';
        this.lightboxImage.style.display = 'none';
        this.hoverNav.style.display = 'none';
        this.prevLink.style.display = 'none';
        this.nextLink.style.display = 'none';
        this.caption.style.display = 'none';
        this.numberDisplay.style.display = 'none';  
		
		// preload image
		var imgPreloader = new Image();
	
		if (this.video && this.video.parentNode == this.imageContainer) {
			this.imageContainer.removeChild(this.video);
		}
		this.lightboxAjax.display = 'none';
	
		/*
		if (this.imageArray[this.activeImage][0].indexOf('.wmv') > 0) {
			var objVideo = document.createElement("div");
			objVideo.setAttribute('id','lightboxVideo');
			var videoSrc = '<OBJECT id="wmp" type="application/x-ms-wmp" rel="lightbox" WIDTH="128" HEIGHT="128" CLASSID="CLSID:6BF52A52-394A-11D3-B153-00C04F79FAA6"';
			videoSrc += 'STANDBY="Loading Windows Media Player components..." TYPE="application/x-oleobject">';
			videoSrc += '<PARAM name="FileName" VALUE="' + lightbox.imageArray[lightbox.activeImage][0] + '">';
			videoSrc += '<PARAM name="URL" VALUE="' + lightbox.imageArray[lightbox.activeImage][0] + '">';
			videoSrc += '<PARAM name="autostart" VALUE="true">';
			videoSrc += '<PARAM name="ShowControls" VALUE="true">';
			videoSrc += '<PARAM name="autosize" VALUE="true">';
			videoSrc += '<PARAM name="StretchToFit" value="false">';
			videoSrc += '<EMBED rel="lightbox" WIDTH="640" HEIGHT="480" TYPE="application/x-ms-wmp" src="' + lightbox.imageArray[lightbox.activeImage][0] + '"';
			videoSrc += 'ShowControls="1" ShowStatusBar="0" ShowDisplay="0" autostart="1" autosize="0" stretchtofit="1"> </EMBED>';
			videoSrc += '</OBJECT>';
			videoSrc += '<script for="wmp" language="jscript" event="PlayStateChange(NewState)">';
			videoSrc += 'if (NewState == 3) lightbox.resizeImageContainer(parseInt(wmp.width), parseInt(wmp.height));';
			videoSrc += '</script>';
			objVideo.innerHTML = videoSrc;
			lightbox.video = objVideo;
			lightbox.lightboxImage.style.display = "none";
			lightbox.imageContainer.appendChild(objVideo);
			
			if (navigator.userAgent.indexOf("MSIE") != -1) {
				lightbox.resizeImageContainer(128, 128);
			} else {
				lightbox.resizeImageContainer(640, 480);
			}
		} else if (this.imageArray[this.activeImage][0].indexOf('.php') > 0) {
			if (this.ajaxCache[this.imageArray[this.activeImage][0]]) {
				this.processAjax(this.ajaxCache[this.imageArray[this.activeImage][0]], this.imageArray[this.activeImage][0]);
			} else {
				sendAjaxCommandC(this.imageArray[this.activeImage][0], '', this.processAjax);
			}
		} else {
		*/
			imgPreloader.onload=function(){
				lightbox.lightboxImage.src = lightbox.imageArray[lightbox.activeImage][0];
				lightbox.lightboxImage.style.display = 'block';
            	lightbox.resizeImageContainer(imgPreloader.width, imgPreloader.height);
			}
			
			imgPreloader.src = this.imageArray[this.activeImage][0];
		//}
	}
	
	this.processAjax = function(data, url) {
		lightbox.ajaxCache[url] = data;
		
		if (lightbox.imageArray[lightbox.activeImage][0] == url) {
			lightbox.lightboxAjax.innerHTML = data;
			lightbox.lightboxAjax.display = 'block';
			lightbox.resizeImageContainer(350, 390);
		}
	}
		
	this.resizeImageContainer = function(imgWidth, imgHeight) {
		// get current width and height
	    var widthCurrent  = this.outerImageContainer.width;
	    var heightCurrent = this.outerImageContainer.height;
	
	    // get new width and height
	    var widthNew = (imgWidth  + borderSize * 2);
		var heightNew = (imgHeight + borderSize * 2);
	
	    this.outerImageContainer.style.width = widthNew + 'px';
	    this.outerImageContainer.style.height = heightNew + 'px';
	    
	    // 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);
		} else {
			pause(100);
		}
		
	    this.prevLink.style.height = imgHeight + 'px';
	    this.prevLink.style.height = imgHeight + 'px';
		this.imageDataContainer.style.width = widthNew + 'px';
	
		this.showImage();
	}
	
	this.showImage = function() {
		this.loading.style.display = 'none';
		this.updateDetails();
		this.preloadNeighborImages();
	}
	
    //
    //  updateDetails()
    //  Display caption, image number, and bottom nav.
    //
	this.updateDetails = function() {
		this.imageDataContainer.style.display = 'block';
		
		if (this.imageArray[this.activeImage][1] != ""){
            this.caption.innerHTML = this.imageArray[this.activeImage][1];
            this.caption.style.display = "block"
        }
		
		if (this.imageArray.length > 1) {
			if (this.ajaxCache[this.imageArray[this.activeImage][0]]) {
				this.numberDisplay.innerHTML = 'Item ' + (this.activeImage + 1) + ' ' + labelOf + '  ' + this.imageArray.length;
			} else {
				this.numberDisplay.innerHTML = labelImage + ' ' + (this.activeImage + 1) + ' ' + labelOf + '  ' + this.imageArray.length;
			}
			this.numberDisplay.style.display = 'block';
		}
		
		var arrayPageSize = this.getPageSize();
		this.overlay.style.height = arrayPageSize[1] + 'px';
		this.updateNav();
	}

    //
    //  updateNav()
    //  Display appropriate previous and next hover navigation.
    //
	this.updateNav = function() {
		this.hoverNav.style.display = 'block';
		if (this.activeImage > 0) this.prevLink.style.display = 'block';
		if (this.activeImage < this.imageArray.length - 1) this.nextLink.style.display = 'block';
		this.enableKeyboardNav();
	}

	//
	// getKey(key)
	// Gets keycode. If 'x' is pressed then it hides the lightbox.
	//
	this.getKey = function(e) {
		if (e == null) e = event; // ie
		
		switch (e.keyCode) {
			case 37: // left
			case 40: // down
			case 97: // a
			case 115: // s
				if (this.activeImage == 0) {
					this.changeImage(this.imageArray.length - 1);
				} else {
					this.changeImage(this.activeImage - 1);
				}
				break;
			case 38: // up
			case 39: // right
			case 100: // d
			case 119: // w
				if (this.activeImage == (this.imageArray.length - 1)) {
					this.changeImage(0);
				} else {
					this.changeImage(this.activeImage + 1);
				}
				break;
			case 35: // end
				this.changeImage(this.imageArray.length - 1);
				break;
			case 36: // home
				this.changeImage(0);
				break;
			case 27: // esc
			case 88: // x
				this.end();
				break;
			default:
				return;
		}
		e.cancel = true;
		try { e.preventDefault(); } catch (e) {}
		e.cancelBubble = true;
		return false;
	}
	
	
	//
	// listenKey()
	//
	this.enableKeyboardNav = function() {	document.onkeydown = function (e) { return lightbox.getKey(e); }; }
	this.disableKeyboardNav = function() { document.onkeydown = ''; }
	
	this.end = function() {
		this.disableKeyboardNav();

		// hide lightbox
		this.lightbox.style.display = 'none';
		this.overlay.style.display = 'none';
		this.imageDataContainer.style.display = 'none';
		
		if (this.video && this.video.parentNode == this.imageContainer) {
			if (this.video.childNodes[0].controls) {
				this.video.childNodes[0].controls.stop();
			}
			this.imageContainer.removeChild(this.video);
		}
		
		this.lightboxAjax.display = 'none';
		
		// make select boxes visible
		selects = document.getElementsByTagName("select");
	    for (i = 0; i != selects.length; i++) {
			selects[i].style.visibility = "visible";
		}
		objects = document.getElementsByTagName("object");
		for (i = 0; i != objects.length; i++) {
			if (objects[i].getAttribute("rel") != 'lightbox') objects[i].style.visibility = "visible";
		}
		embeds = document.getElementsByTagName("embed");
		for (i = 0; i != embeds.length; i++) {
			if (embeds[i].getAttribute("rel") != 'lightbox') embeds[i].style.visibility = "visible";
		}
	}
	
	this.preloadNeighborImages = function(){
		var preloadNextImage, preloadPrevImage;
        if (this.imageArray.length > this.activeImage + 1){
        	/*
        	if (this.imageArray[this.activeImage + 1][0].indexOf('.wmv') > 0) {
        	} else if (this.imageArray[this.activeImage + 1][0].indexOf('.php') > 0) {
        		sendAjaxCommandC(this.imageArray[this.activeImage + 1][0], '', this.processAjax);
            } else {
            */
            	preloadNextImage = new Image();
	            preloadNextImage.src = this.imageArray[this.activeImage + 1][0];
            //}
        }
        if (lightbox.activeImage > 0){
        	/*
        	if (this.imageArray[this.activeImage - 1][0].indexOf('.wmv') > 0) {
        	} else if (this.imageArray[this.activeImage - 1][0].indexOf('.php') > 0) {
        		sendAjaxCommand(this.imageArray[this.activeImage - 1][0], '', this.processAjax);
            } else {
            */
            	preloadNextImage = new Image();
	            preloadNextImage.src = this.imageArray[this.activeImage - 1][0];
            //}
        }
	}
	
	//
    // updateImageList()
    // Loops through anchor tags looking for 'lightbox' references and applies onclick
    // events to appropriate links. You can rerun after dynamically adding images w/ajax.
    //
	this.updateImageList = function() {
		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("rel") && (anchor.getAttribute("rel").indexOf("lightbox") == 0 || anchor.getAttribute("rel") == "[lightbox]")){
				anchor.onclick = function () {lightbox.start(this); return false;}
			}
		}
	}
	
	//
	// getPageScroll()
	// Returns array with x,y page scroll values.
	// Core code from - quirksmode.org
	//
	this.getPageScroll = function(){
	
		var xScroll, yScroll;
	
		if (self.pageYOffset) {
			yScroll = self.pageYOffset;
			xScroll = self.pageXOffset;
		} else if (document.documentElement && document.documentElement.scrollTop){	 // Explorer 6 Strict
			yScroll = document.documentElement.scrollTop;
			xScroll = document.documentElement.scrollLeft;
		} else if (document.body) {// all other Explorers
			yScroll = document.body.scrollTop;
			xScroll = document.body.scrollLeft;
		}
		
		arrayPageScroll = new Array(xScroll,yScroll) 
		return arrayPageScroll;
	}
	
	
	
	//
	// getPageSize()
	// Returns array with page width, height and window width, height
	// Core code from - quirksmode.org
	// Edit for Firefox by pHaez
	//
	this.getPageSize = function(){
		
		var xScroll, yScroll;
		
		if (window.innerHeight && window.scrollMaxY) {	
			xScroll = window.innerWidth + window.scrollMaxX;
			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
			if(document.documentElement.clientWidth){
				windowWidth = document.documentElement.clientWidth; 
			} else {
				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 then height of the viewport
		if(yScroll < windowHeight){
			pageHeight = windowHeight;
		} else { 
			pageHeight = yScroll;
		}
	
		// for small pages with total width less then width of the viewport
		if(xScroll < windowWidth){	
			pageWidth = windowWidth;
		} else {
			pageWidth = xScroll;
		}
	
	
		arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight) 
		return arrayPageSize;
	}
	
      this.updateImageList();

      // When Lightbox starts it will resize itself from 250 by 250 to the current image dimension.
      // If animations are turned off, it will be hidden as to prevent a flicker of a
      // white 250 by 250 box.
      var size = '1px';
      

      // Code inserts html at the bottom of the page that looks similar to this:
      //
      //  <div id="overlay"></div>
      //  <div id="lightbox">
      //      <div id="outerImageContainer">
      //          <div id="imageContainer">
      //              <img id="lightboxImage">
      //              <div style="" id="hoverNav">
      //                  <a href="#" id="prevLink"></a>
      //                  <a href="#" id="nextLink"></a>
      //              </div>
      //              <div id="loading">
      //                  <a href="#" id="loadingLink">
      //                      <img src="images/loading.gif">
      //                  </a>
      //              </div>
      //          </div>
      //      </div>
      //      <div id="imageDataContainer">
      //          <div id="imageData">
      //              <div id="imageDetails">
      //                  <span id="caption"></span>
      //                  <span id="numberDisplay"></span>
      //              </div>
      //              <div id="bottomNav">
      //                  <a href="#" id="bottomNavClose">
      //                      <img src="images/close.gif">
      //                  </a>
      //              </div>
      //          </div>
      //      </div>
      //  </div>


      var objBody = document.getElementsByTagName("body")[0];

	objBody.appendChild(makeElement('div',{id:'overlay'}));

      objBody.appendChild(makeElement('div',{id:'lightbox'}, [
          makeElement('div',{id:'outerImageContainer'}, 
              makeElement('div',{id:'imageContainer'}, [
                  makeElement('img',{id:'lightboxImage'}),
                  makeElement('div',{id:'lightboxAjax'}), 
                  makeElement('div',{id:'hoverNav'}, [
                      makeElement('a',{id:'prevLink', href: '#' }),
                      makeElement('a',{id:'nextLink', href: '#' })
                  ]),
                  makeElement('div',{id:'loading'}, 
                      makeElement('a',{id:'loadingLink', href: '#' }, 
                          makeElement('img', {src: fileLoadingImage})
                      )
                  )
              ])
          ),
          makeElement('div', {id:'imageDataContainer'},
              makeElement('div',{id:'imageData'}, [
                  makeElement('div',{id:'imageDetails'}, [
                      makeElement('span',{id:'caption'}),
                      makeElement('span',{id:'numberDisplay'})
                  ]),
                  makeElement('div',{id:'bottomNav'},
                      makeElement('a',{id:'bottomNavClose', href: '#' },
                          makeElement('img', { src: fileBottomNavCloseImage })
                      )
                  )
              ])
          )
      ]));

 	var ids = 
              ('overlay lightbox outerImageContainer imageContainer lightboxImage hoverNav prevLink nextLink loading loadingLink ' + 
              'imageDataContainer imageData imageDetails caption numberDisplay bottomNav bottomNavClose lightboxAjax').split(' ');
       for (var key in ids) {
       	this[ids[key]] = document.getElementById(ids[key]);
       }
       
      this.overlay.style.display = 'none';
	this.overlay.onclick = function() { lightbox.end(); };
	this.lightbox.style.display = 'none';
	this.lightbox.onclick = function(e) {
		if (!e) e = window.event;
		if (e.srcElement) {
			if (e.srcElement.id == 'lightbox') lightbox.end();
		} else {
			if (e.target.id == 'lightbox') lightbox.end();
		}
	};
	this.outerImageContainer.style.width = size;
	this.outerImageContainer.style.height = size;
	this.imageDataContainer.style.display = 'none';
	this.prevLink.onclick = function(event) { lightbox.changeImage(lightbox.activeImage - 1); return false; };
	this.nextLink.onclick = function(event) { lightbox.changeImage(lightbox.activeImage + 1); return false; };
	this.loadingLink.onclick = function(event) { lightbox.end(); return false; };
	this.bottomNavClose.onclick = function(event) { lightbox.end(); return false; };

}




//
// 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();
		}
	}

}

function makeElement(tag, attrs, children) {
	var el = document.createElement(tag);
	for (var key in attrs) {
		el[key] = attrs[key];
		el.setAttribute(key, attrs[key]);
	}
	if (children) {
		if (children.unshift) {
			for (var key in children) {
				try { el.appendChild(children[key]); } catch (e) {}
			}
		} else {
			el.appendChild(children);
		}
	}
	return el;
}

addLoadEvent(function() {lightbox = new Lightbox()});
