// -- modified to not use paging features.
// -----------------------------------------------------------------------------------
//
//	Lightbox v2.02
//	by Lokesh Dhakar - http://www.huddletogether.com
//	3/31/06
//
//	For more information on this script, visit:
//	http://huddletogether.com/projects/lightbox2/
//
//	Licensed under the Creative Commons Attribution 2.5 License - http://creativecommons.org/licenses/by/2.5/
//
//	Credit also due to those who have helped, inspired, and made their code available to the public.
//	Including: Scott Upton(uptonic.com), Peter-Paul Koch(quirksmode.org), Thomas Fuchs(mir.aculo.us), and others.
//
//
// -----------------------------------------------------------------------------------
/*

	Table of Contents
	-----------------
	Configuration
	Global Variables

	Extending Built-in Objects
	- Object.extend(Element)

	Lightbox Class Declaration
	- initialize()
	- start()
	- changeImage()
	- resizeImageContainer()
	- showImage()
	- updateDetails()
	- updateNav()
	- enableKeyboardNav()
	- disableKeyboardNav()
	- keyboardAction()
	- preloadNeighborImages()
	- end()

	Miscellaneous Functions
	- getPageScroll()
	- getPageSize()
	- showSelectBoxes()
	- hideSelectBoxes()
	- initLightbox()

	Function Calls
	- addLoadEvent(initLightbox)

*/
// -----------------------------------------------------------------------------------

//
//	Configuration
//
var myLightbox;
var fileLoadingImage = GE_baselink + "html_view/images/overlay_loading.gif";
var fileBottomNavCloseImage = GE_baselink + "html_view/images/overlay_close.gif";
//var videoPlayerPath = GE_baselink + "html_view/flash/video.swf";
//var resizeSpeed = 10;	// controls the speed of the image resizing (1=slowest and 10=fastest)
//var borderSize = 35;	//if you adjust the padding in the CSS, you will need to update this variable
//var imageArray = new Array();
var activeImage;

if(resizeSpeed > 10){ resizeSpeed = 10;}
if(resizeSpeed < 1){ resizeSpeed = 1;}
resizeDuration = (11 - resizeSpeed) * 0.15;

// -----------------------------------------------------------------------------------

//
//	Additional methods for Element added by SU, Couloir
//	- further additions by Lokesh Dhakar (huddletogether.com)
//
Object.extend(Element, {
	setWidth: function(element,w) {
	   	element = $(element);
    	element.style.width = w +"px";
	},
	setHeight: function(element,h) {
   		element = $(element);
    	element.style.height = h +"px";
	},
	setTop: function(element,t) {
	   	element = $(element);
    	element.style.top = t +"px";
	},
	setSrc: function(element,src) {
    	element = $(element);
    	element.src = src;
	},
	setHref: function(element,href) {
    	element = $(element);
    	element.href = href;
	}
});

// -----------------------------------------------------------------------------------

//
//	Lightbox Class Declaration
//	- initialize()
//	- start()
//	- changeImage()
//	- resizeImageContainer()
//	- showImage()
//	- updateDetails()
//	- updateNav()
//	- enableKeyboardNav()
//	- disableKeyboardNav()
//	- keyboardNavAction()
//	- preloadNeighborImages()
//	- end()
//
//	Structuring of code inspired by Scott Upton (http://www.uptonic.com/)
//
var Lightbox = Class.create();

Lightbox.prototype = {

	// initialize()
	// Constructor runs on completion of the DOM loading. Loops through anchor tags looking for
	// 'lightbox' references and applies onclick events to appropriate links. The 2nd section of
	// the function inserts html at the bottom of the page which is used to display the shadow
	// overlay and the image container.
	//
	initialize: function() {

		this.anchorInfo = {
			href: null,
			title: null,
			rel: null
		}

		this.htmlEl = null;
		this.captions = false;

		//sets whether the mode is image or media player
		this.mode = null;

		// The rest of this code inserts html at the bottom of the page that looks similar to this:
		//
		//	<div id="overlay"></div>
		//	<div id="lightbox">
		//		<div id="bottomNav">
		//			<a href="#" id="bottomNavClose">
		//				<img src="images/close.gif">
		//			</a>
		//		</div>
		//		<div id="outerImageContainer">
		//			<div id="imageContainer">
		//				<img id="lightboxImage">
		//				<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>
		//					<div id="imageNav">
		//						<a id="prevImg" href="#">previous</a>
		//						<span id="numberDisplay"></span>
		//						<a id="nextImg" href="#">next</a>
		//					</div>
		//				</div>
		//			</div>
		//		</div>
		//	</div>

		//var objBody = document.getElementsByTagName("body").item(0);
		var objBody = document.body;
		objBody.appendChild(
			$(Builder.node("div", {id:"overlay", style:"display:none;"})).observe("click", function(e) { myLightbox.end(); Event.stop(e); })
		);
		objBody.appendChild(
			Builder.node("div", {id:"lightbox", style:"display:none;"}, [
				Builder.node("div", {id:"outerImageContainer"}, [
					Builder.node("div", {id:"bottomNav"},
						$(Builder.node("a", {id:"bottomNavClose",href:"#"},
							Builder.node("img", {id:"bottomNavCloseImg",src:fileBottomNavCloseImage,alt:"Close Button"})
						)).observe("click", function(e) { myLightbox.end(); Event.stop(e); })
					),
					Builder.node("div", {id:"imageContainer"}, [
						Builder.node("div", {id:"flashContainer"}, 'You need to <a href="http://www.adobe.com/shockwave/download/download.cgi?P1_Prod_Version=ShockwaveFlash&promoid=BIOW">download Adobe Flash Player 8</a> to view this content.'),
						Builder.node("img", {id:"lightboxImage"}),
						Builder.node("div", {id:"loading"},
							$(Builder.node("a", {id:"loadingLink",href:"#"},
								Builder.node("img", {src:fileLoadingImage})
							)).observe("click", function(e) { myLightbox.end(); Event.stop(e); })
						)
					])
				]),
				Builder.node("div", {id:"imageDataContainer",className:"clearfix"},
					Builder.node("div", {id:"imageData"},
						Builder.node("div", {id:"imageDetails"}, [
							Builder.node("span", {id:"caption"}),
							Builder.node("div", {id:"imageNav"}, [
								Builder.node("a", {id:"prevImg",href:"#"}, "previous"),
								Builder.node("span", {id:"numberDisplay"}),
								Builder.node("a", {id:"nextImg",href:"#"}, "next")
							])
						])
					)
				)
			])
		);

		Event.observe( window, "unload", this.unload.bind(this), false);
		this.started = false;
	},

	addAnchor: function(anchor) {
		$(anchor).observe("click", function(e) {myLightbox.start(this); Event.stop(e);}.bind(anchor) );
	},

	//
	//	start()
	//	Display overlay and lightbox. If image is part of a set, add siblings to imageArray.
	//
	start: function(imageLink) {

		hideSelectBoxes();

		this.anchorInfo = {
			href: imageLink.getAttribute('href'),
			title: imageLink.getAttribute('title'),
			rel: imageLink.getAttribute('rel')
		}

		imageArray = [];
		imageNum = 0;

		// stretch overlay to fill page and fade in
		var arrayPageSize = getPageSize();
		$('overlay').setAttribute('title','click to close');
		Element.setHeight('overlay', arrayPageSize[1]);
		new Effect.Appear('overlay', { duration: 0.2, from: 0.0, to: 0.8, afterFinish:
			function() {

				myLightbox.htmlEl = $(document.documentElement);
				myLightbox.htmlEl.addClassName('overlay_on');
				myLightbox.bindEnd = myLightbox.callEnd.bindAsEventListener(myLightbox.htmlEl);
				// myLightbox.htmlEl.observe("click", myLightbox.bindEnd);

				// if image is NOT part of a set..
				if(!imageLink.hasClassName('flash')) {
					if(!myLightbox.anchorInfo.rel){
						// add single image to imageArray
						imageArray.push(new Array(myLightbox.anchorInfo.href, myLightbox.anchorInfo.title));
					} else {
					// if image is part of a set..

						anchors = $$('.bhv_overlay');
						// loop through anchors, find other images in set, and add them to imageArray
						for (var i=0; i<anchors.length; i++){
							var anchor = anchors[i];
							if (anchor.getAttribute('href') && (anchor.getAttribute('rel') == myLightbox.anchorInfo.rel)){
								imageArray.push(new Array(anchor.getAttribute('href'), anchor.getAttribute('title')));
							}
						}
						imageArray.uniq();
						while(imageArray[imageNum][0] != myLightbox.anchorInfo.href) { imageNum++;}
					}
				}

				// calculate top offset for the lightbox and display
				var arrayPageSize = getPageSize();
				var arrayPageScroll = getPageScroll();
				var lightboxTop = arrayPageScroll[1] + (arrayPageSize[3] / 15);

				Element.setTop('lightbox', lightboxTop);

				$('lightbox').show();
				myLightbox.resetDisplay();

				if (imageLink.hasClassName('flash')) {

					if (unescape(myLightbox.anchorInfo.href).indexOf('.swf')>0) {

						myLightbox.mode = 'swf';
						$('flashContainer').setStyle({backgroundColor:'#fff'});
						var q = myLightbox.anchorInfo.href.toQueryParams();
						var w = parseInt(q.w);
						var h = parseInt(q.h);
						var so = new SWFObject(myLightbox.anchorInfo.href,"media_player",w,h,"8","#ffffff");
						so.addParam('allowScriptAccess','sameDomain');
						so.addParam('quality','high');
						if (q.clickTAG) { so.addVariable('clickTAG',q.clickTAG); }

						myLightbox.resizeImageContainer(w,h,function(){
							so.write('flashContainer');
							$('loading').hide();
							$('flashContainer').show();
							myLightbox.updateDetails()
						});

					} else {

						myLightbox.mode = 'video';
						var fHref = unescape(myLightbox.anchorInfo.href);
						if (fHref.indexOf('http://')==-1) {
							wHref = window.location.href;
							wHref = wHref.substring(0,wHref.lastIndexOf('/')+1);
							fHref = wHref + fHref;
						}
						var filePath = fHref.substring(0,fHref.lastIndexOf('.'));
						var fileName = filePath.substring(filePath.lastIndexOf('/')+1);
						
						var jsonFileName = fileName+".json";
						
						new Ajax.Request( jsonFileName, {onSuccess:function(transport) {
							var vdata = transport.responseText.evalJSON();

							var mp_width = vdata.mp_width || 401;
							var mp_height = vdata.mp_height + 20 || 320;
							var so = new SWFObject(videoPlayerPath,"media_player",mp_width,mp_height,"8","#000000");
							so.addParam('scale', 'noscale');
						    so.addVariable("flv_path", vdata.flv_path);
						    so.addVariable("captions_path", vdata.captions_path);
						    so.addVariable("css_path", vdata.css_path);
						    so.addVariable("refresh_rate", vdata.refresh_rate || 200);
							so.write('flashContainer');
							myLightbox.resizeImageContainer(mp_width,mp_height,function(){
								$('loading').hide();
								$('flashContainer').show();
								myLightbox.updateDetails()
							});

							//create movie information
							$('imageDetails').appendChild(
								Builder.node("div", {id:"movie_details"}, [
									Builder.node("div", {id:"movie_info"}),
									Builder.node("ul", {id:"movie_links"})
								])
							);
							if (vdata.title) $('movie_info').appendChild(Builder.node("h3", {id:"movie_title"}, vdata.title));
							if (vdata.description) {
								$('movie_info').appendChild(Builder.node("div", {id:"movie_desc"}));
								$('movie_desc').innerHTML = vdata.description;
							}
							if (vdata.captions_path) $('movie_links').appendChild( Builder.node("li", {id:"movie_captions"}, Builder.node("a", {href:"#"}, "Turn on Closed Captioning")) );
							if (myLightbox.anchorInfo.href.substring(myLightbox.anchorInfo.href.lastIndexOf('.'))=='m4v') $('movie_links').appendChild( Builder.node("li", {id:"movie_download"}, Builder.node("a", {href:myLightbox.anchorInfo.href}, "Download Video (M4V)")) );
							if (vdata.transcript_url) $('movie_links').appendChild( Builder.node("li", {id:"movie_transcript"}, Builder.node("a", {href:vdata.transcript_url}, "Download Transcript (TXT)")) );
							if (vdata.more_url) $('movie_details').appendChild(Builder.node("p", {id:"movie_more"}, [Builder.node("a", {href:vdata.more_url}, vdata.more_text)]));
							
							//add js call to flash on caption link
							$('movie_captions').down().observe('click',function(){ myLightbox.toggleCaptions(); });

						}});
					}

					// commented out when the flash player was changed to fixed size
					// $('flashContainer').show();

				} else {

					myLightbox.mode = 'img';
					myLightbox.changeImage(imageNum);

				}
			}
		});

		this.started = true;
	},

	//
	//	changeImage()
	//	Hide most elements and preload image in preparation for resizing image container.
	//
	changeImage: function(imageNum) {

		activeImage = imageNum;	// update global var

		var imgPreloader = new Image();

		// once image is preloaded, resize image container
		imgPreloader.onload=function(){
			Element.setSrc('lightboxImage', imageArray[activeImage][0]);
			myLightbox.resizeImageContainer(imgPreloader.width, imgPreloader.height, function(){ myLightbox.showImage() });
		}
		imgPreloader.src = imageArray[activeImage][0];
	},

	//
	//	resetDisplay()
	//
	resetDisplay: function() {
		// hide elements during transition
		$('loading').show();
		$('flashContainer').hide();
		$('flashContainer').setStyle({backgroundColor:'transparent'});
		$('lightboxImage').hide();
		$('bottomNavCloseImg').hide();
		$('imageDataContainer').hide();
		$('caption').hide();
		$('imageNav').hide();
		$('numberDisplay').hide();
		$('prevImg').hide();
		$('nextImg').hide();
	},

	//
	//	resizeImageContainer()
	//
	resizeImageContainer: function(imgWidth, imgHeight, fn ) {

		// get current height and width
		this.wCur = Element.getWidth('outerImageContainer');
		this.hCur = Element.getHeight('outerImageContainer');

		// get new width and height
		var widthNew = (imgWidth  + (70));
		var heightNew = (imgHeight  + (40));

		// scalars based on change from old to new
		this.xScale = (widthNew / this.wCur) * 100;
		this.yScale = (heightNew / this.hCur) * 100;

		// calculate size difference between new and old image, and resize if necessary
		wDiff = this.wCur - widthNew;
		hDiff = this.hCur - heightNew;

		var effects = [];
		if(!( hDiff == 0)){ effects.push( new Effect.Scale('outerImageContainer', this.yScale, {sync:true, scaleX: false, duration: resizeDuration, queue: 'front'}) ) }
		if(!( wDiff == 0)){ effects.push( new Effect.Scale('outerImageContainer', this.xScale, {sync:true, scaleY: false, delay: resizeDuration, duration: resizeDuration}) ) }

		if (effects.length) {
			new Effect.Parallel( effects, { duration: 0.65, afterFinish:fn } );
		}
		else {
		// if new and old image are same size and no scaling transition is necessary,
		// do a quick pause to prevent image flicker.
			setTimeout( fn, 100 );
		}

		Element.setWidth( 'bottomNav', imgWidth);
		Element.setWidth( 'imageDataContainer', imgWidth);

	},

	//
	//	showImage()
	//	Display image and begin preloading neighbors.
	//
	showImage: function(){

		$('loading').hide();
		new Effect.Appear('lightboxImage', { duration: 0.5, queue: 'end', afterFinish: function(){ myLightbox.updateDetails(); } });
		this.preloadNeighborImages();

	},

	//
	//	updateDetails()
	//	Display caption, image number, and bottom nav.
	//
	updateDetails: function() {

		if (this.mode!='video') {
			if (myLightbox.anchorInfo.title) { $('caption').show().update(myLightbox.anchorInfo.title); }

			// if image is part of set display 'Image x of x'
			if(imageArray.length > 1 && this.mode=='img'){
				$('numberDisplay').show().update( eval(activeImage + 1) + " of " + imageArray.length);
			}
		}
		new Effect.Appear('imageDataContainer', { duration: 0.65, afterFinish: function() { myLightbox.updateNav(); } });

	},

	//
	//	updateNav()
	//	Display appropriate previous and next hover navigation.
	//
	updateNav: function() {

		if (this.mode!='video') {
			if (this.mode=='img') {
				new Effect.Appear('bottomNavCloseImg', { duration: 0.5 });
				new Effect.Appear('imageNav', { duration: 0.5 });
				/*
				new Effect.Parallel(
					[ new Effect.Appear('bottomNavCloseImg', { sync: true, duration: 1.0 }),
					  new Effect.Appear('imageNav', { sync: true, duration: 1.0 }) ],
					{ duration: 0.65 }
				);
				*/
			} else {
				new Effect.Appear('bottomNavCloseImg', { duration: 1.0 });
			}

			// if not first image in set, display prev image button
			if(activeImage != 0){
				$('prevImg').show().onclick = function() {
					myLightbox.changeImage(activeImage - 1); return false;
				}
			}

			// if not last image in set, display next image button
			if(activeImage != (imageArray.length - 1)){
				$('nextImg').show().onclick = function() {
					myLightbox.changeImage(activeImage + 1); return false;
				}
			}
		} else {
			new Effect.Appear('bottomNavCloseImg', { duration: 1.0 });
		}

		this.enableKeyboardNav();
	},
	
	//
	//	toggleCaptions()
	//
	toggleCaptions: function() {
		if (myLightbox.captions) {
			$('media_player').disableCaptions();
			$('movie_captions').down().innerHTML = 'Turn on Closed Captioning';
			myLightbox.captions=false;
		}
		else {
			$('media_player').enableCaptions();
			$('movie_captions').down().innerHTML = 'Turn off Closed Captioning';
			myLightbox.captions=true;
		}
	},

	//
	//	enableKeyboardNav()
	//
	enableKeyboardNav: function() {
		document.onkeydown = this.keyboardAction;
	},

	//
	//	disableKeyboardNav()
	//
	disableKeyboardNav: function() {
		document.onkeydown = '';
	},

	//
	//	keyboardAction()
	//
	keyboardAction: function(e) {
		if (e == null) { // ie
			keycode = event.keyCode;
		} else { // mozilla
			keycode = e.which;
		}

		key = String.fromCharCode(keycode).toLowerCase();

		if((key == 'x') || (key == 'o') || (key == 'c')){	// close lightbox
			myLightbox.end();
		} else if(key == 'p'){	// display previous image
			if(activeImage != 0){
				myLightbox.disableKeyboardNav();
				myLightbox.changeImage(activeImage - 1);
			}
		} else if(key == 'n'){	// display next image
			if(activeImage != (imageArray.length - 1)){
				myLightbox.disableKeyboardNav();
				myLightbox.changeImage(activeImage + 1);
			}
		}


	},

	//
	//	preloadNeighborImages()
	//	Preload previous and next images.
	//
	preloadNeighborImages: function(){

		if((imageArray.length - 1) > activeImage){
			preloadNextImage = new Image();
			preloadNextImage.src = imageArray[activeImage + 1][0];
		}
		if(activeImage > 0){
			preloadPrevImage = new Image();
			preloadPrevImage.src = imageArray[activeImage - 1][0];
		}

	},

	//
	//	end()
	//
	end: function() {
		this.disableKeyboardNav();
		if (this.mode=='video') {
			if (navigator.appName.indexOf("MSIE") != -1) {
				window['media_player'].stopPlayer();
			} else {
				document['media_player'].stopPlayer();
			}
		}
		if ($('movie_details')) $('movie_details').remove();
		$('imageDataContainer').hide();
		$('bottomNavCloseImg').hide();
		$('lightbox').hide();
		myLightbox.htmlEl.removeClassName('overlay_on');
		myLightbox.htmlEl.stopObserving("click", myLightbox.bindEnd);
		new Effect.Fade('overlay', { duration: 0.2, afterFinish:function(){
			$("lightboxImage").src = "";
			$("flashContainer").update("");
		}});
		showSelectBoxes();

		this.started = false;
	},
	
	callEnd: function(e) {
		myLightbox.end();
		Event.stop(e);
	},

	unload: function() {
		if (this.mode == 'video' && this.started ) {
			if (navigator.appName.indexOf("MSIE") != -1) {
				window['media_player'].stopPlayer();
			} else {
				document['media_player'].stopPlayer();
			}
		}
	}
}


// -----------------------------------------------------------------------------------

//
// 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;
	}

	return ['',yScroll];
}

// -----------------------------------------------------------------------------------

//
// 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, windowWidth, windowHeight, pageWidth, pageHeight;

	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;
	}

	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 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;
	}

	return [pageWidth,pageHeight,windowWidth,windowHeight];
}


// ---------------------------------------------------

function showSelectBoxes(){
	$$("select").each( function(el){ el.show() } );
}

// ---------------------------------------------------

function hideSelectBoxes(){
	$$("select").each( function(el){ el.hide() } );
}

// ---------------------------------------------------


function GE_initMediaPlayer(w,h) {

}

function turnoffCaptions() {
	myLightbox.toggleCaptions();
}

GE_Main.addInitFn(
	function() {
		var tmp = $$('.bhv_overlay');
		if (tmp.length>0) { myLightbox = new Lightbox(); }
	}
);

GE_QueryParams = {
	qp:null,
	get:function() {
		if (this.qp == null) {
			this.qp = document.location.href.toQueryParams();
		}
		return this.qp;
	}
}

GE_Main.mapFnToCSS('bhv_overlay',
	function(el) {
		if (myLightbox) {
			myLightbox.addAnchor(el);
			var media_id = GE_QueryParams.get().media_id;
			if (media_id) {
				var href = $(el).readAttribute("href");
				var id = href.substring(href.lastIndexOf("/")+1, href.lastIndexOf("."));
				if (id == media_id && !myLightbox.started) {
					myLightbox.start(el);
				}
			}
		}
	}
);