// -----------------------------------------------------------------------------------
//
//	(v)box 0.9 - based heavily on Lokesh Dakar's Lightbox v2.02, but modified to run 
//  all kinds of media and multi-layer pages on top of each other.
//	by Giles Copp (www.versionindustries.com), 3rd August 2006
//
//	My modification is intended to be much more flexible and enable a site to run entirely
//	under lightbox, layering content upon content and without ever leaving the page.
//
//	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.
//
//
//	this script automatically lightboxes all links.
// 	to prevent this on a link, give it a rel="normal" attribute.
// 	to provide an alternative destination for lightboxing, give it a rel="alt:page.htm" attribute.
//
// -----------------------------------------------------------------------------------
//
//	Configuration
//
var borderSize = 10;	//if you adjust the padding in the CSS, you will need to update this variable

// -----------------------------------------------------------------------------------

//
//	Global Variables
//
var objBody;
var globalZIndex = 50;	// will be incremented for subsequent lightboxes. starts at 50 to avoid any low-level junk

// -----------------------------------------------------------------------------------

//
//	Additional methods for Element added by SU, Couloir
//	- further additions by Lokesh Dhakar (huddletogether.com)
//
Object.extend(Element, {
	getWidth: function(element) {
	   	element = $(element);
	   	return element.offsetWidth; 
	},
	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; 
	}
});

// -----------------------------------------------------------------------------------

//
//	Lightbox Class Declaration
//	Structuring of code inspired by Scott Upton (http://www.uptonic.com/)
//
var Lightbox = Class.create();

Lightbox.prototype = {
	
	/* initialize()
		Constructor is called on completion of the DOM loading, and also by subsequent loads if
		the system is loading an html page with more links. 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() { 
		objBody = document.getElementsByTagName("body").item(0);
		objHTML = document.getElementsByTagName("html").item(0);
		// save overflow - for later use
		objBody.origOverflow = objBody.style.overflow;
		objHTML.origOverflow = objHTML.style.overflow;
		// traverse opening document
		this.traverseLinks( document );
	},
	
	//
	// traverseLinks()
	// goes through the anchors subsidiary to the element passed, and assigns them LB functions.
	//
	traverseLinks: function(lb_parent) {
		
		if (!lb_parent.getElementsByTagName){ return; }
		var anchors = lb_parent.getElementsByTagName('a');

		// loop through all anchor tags
		for (var i=0; i<anchors.length; i++){
			var anchor = anchors[i];
			
			var relAttribute = String(anchor.getAttribute('rel'));
		
			// drop out for normals
			if (relAttribute.toLowerCase().match('normal')) continue;
			
			// otherwise assign.
			anchor.onclick = function () { myLightbox.start(this); return false; }
		}
		
	},
	
	//
	//	start()
	//	Display overlay and lightbox. If image is part of a set, add siblings to imageArray.
	//
	start: function( theLink ) {
		
		// get the link extension etc first.
		targetHref = theLink.href;
		// get extension of the link href. first strip off any GET data, then break by periods and select the last item.
		var portion = targetHref.indexOf('?');
		var url = (portion!=-1) ? targetHref.substring(0,portion) : targetHref;
		var url_pieces = url.split('.');
		var extension = url_pieces.pop();		
		
		// new 2008.06.02
		document.body.style.overflow = 'hidden';
		
		// apply behaviour depending on extension
		switch (extension) {
			
			case 'jpg': case 'jpeg': case 'gif': // images
				var newBox = appendLightBox();
				this.showImage( targetHref, newBox );
				break;
				
			case 'swf': // flash item
				var newBox = appendLightBox();
				// rel attribute should give width and height
				var wh = theLink.getAttribute('rel').split('x');
				this.showFlash( targetHref, newBox, wh[0], wh[1] );
				break;
				
			case 'mp3': case 'wav': // quicktime component
				//var newBox = appendLightBox();
				//this.showAudio( newBox );
				break;
				
			case 'mov': case 'avi': case 'mpg': case 'mpeg': case 'mp4':
				// get dimensions
				var wh = theLink.getAttribute('rel').split('x');
				// for macs, create a lightbox quicktime spot
				if (isMac) {
					var newBox = appendLightBox();
					this.showVideo( targetHref, newBox, parseInt(wh[0]), parseInt(wh[1])+16 );
				}
				// otherwise, do it as a popup window
				else {
					var hWnd = raw_popup( 
						"video.php?u="+escape(targetHref)+"&w="+wh[0]+"&h="+(parseInt(wh[1])+16), 
						'_blank', true, 
						parseInt(wh[0])+30, parseInt(wh[1])+41);
				}
				break;
				
			case 'htm': case 'html': case'php': // go to html
				var newBox = appendLightBox();
				this.showHTML( targetHref, newBox );
				break;
				
		}
		
	},
	
	//
	//	showFlash()
	//	creates an HTML nest for the Flash object and shows it. requires Width and Height for the flash object.
	//
	showFlash: function( theSrc, z_Index, w, h ) {
		
		trace("showFlash: start");
		
		// no close boxes
		Element.hide('htmlCloseBox_'+z_Index);
		
		// adjust the container size
		Element.setWidth( 'outerBoxContainer_'+z_Index, parseInt(w)+20 );
		Element.setHeight( 'outerBoxContainer_'+z_Index, parseInt(h)+20 );
		// hide loader
		Element.hide('lightboxLoad_'+z_Index);
		
		// give the outer box a background, and make the background itself transparent
		Element.setStyle('outerBoxContainer_'+z_Index, { backgroundColor:'#fff' } );
		Element.setStyle('background_'+z_Index, { background:'transparent'} );
		Element.setStyle('boxContainer_'+z_Index, {padding:'10px'} );					// set padding for images. other media do not use padding
		
		// apply the end function to the TD onclick handler
		$('lightboxTD_'+z_Index).onclick = function () { myLightbox.end( z_Index ); }
		
		$('lightboxHTMLContent_'+z_Index).innerHTML = 
				'<object '+
				'	id="insidermap"'+
				'	name="insidermap"'+
				'	classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"  '+
				'	codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,0,0" '+
				'	width="'+w+'" '+
				'	height="'+h+'">'+
				'	<param name="movie" value="'+theSrc+'">'+
				'	<param name="quality" value="high">'+
				'	<param name="menu" value="false">'+
				'	<param name="wmode" value="opaque">'+
				'	<param name="bgcolor" value="#ffffff">'+
				'	<embed '+
				'		name="insidermap"'+
				'		id="insidermap"'+
				'		src="'+theSrc+'" '+
				'		quality="high"'+
				'		menu="false"'+
				'		bgcolor="#ffffff"'+
				'		wmode="opaque"'+
				'		pluginspage="http://www.macromedia.com/go/getflashplayer" '+
				'		type="application/x-shockwave-flash" '+
				'		width="'+w+'" '+
				'		height="'+h+'">'+
				'	</embed>'+
				'</object>';
		
	},
	
	//
	//	showVideo()
	//	creates an HTML nest for a QuickTime component. requires Width and Height for the movie.
	//
	showVideo: function( theSrc, z_Index, w, h ) {
		
		trace("showVideo: start");
		
		// hide loader and image tag
		Element.hide('lightboxLoad_'+z_Index);
		Element.hide('lightboxImage_'+z_Index);
		
		// show the background, HTML sec and close box
		Element.show('background_'+z_Index );
		Element.show('lightboxHTML_'+z_Index );
		Element.show('htmlCloseBox_'+z_Index );
		
		$('lightboxHTMLContent_'+z_Index).innerHTML = 
				'<table style="width:100%;height:100%" border="0"><tr><td align="center" valign="middle">'+
				'<div class="movie_wrapper" style="width:'+w+'px;">'+
				'<object '+
				'	classid="clsid:02bf25d5-8c17-4b23-bc80-d3488abddc6b" '+
				'	width="'+w+'" '+
				'	height="'+h+'" '+
				'	codebase="http://www.apple.com/qtactivex/qtplugin.cab#version=6,0,2,0">'+
				'	<param name="controller" value="true" />	'+
				'	<param name="type" value="video/quicktime" />'+
				'	<param name="autoplay" value="true" />'+
				'	<param name="src" value="'+theSrc+'" />'+
				'	<param name="bgcolor" value="#FFFFFF" />'+
				'	<param name="pluginspage" value="http://www.apple.com/quicktime/download/indext.html" />'+
				'	<embed '+
				'		width="'+w+'" '+
				'		height="'+h+'" '+
				'		controller="true" '+
				'		autoplay="true" '+
				'		src="'+theSrc+'" '+
				'		type="video/quicktime" '+
				'		bgcolor="#FFFFFF" '+
				'		border="0" '+
				'		pluginspage="http://www.apple.com/quicktime/download/indext.html">'+
				'	</embed>'+
				'</object>'+
			
			'</div></td></tr></table>';
		// alert($('lightboxHTMLContent_'+z_Index).innerHTML);
		
	},
	
	//
	//	showHTML()
	//	fetches the URL via Ajax and sets it using innerHTML
	//
	showHTML: function( theSrc, z_Index ) {	

		trace("showHTML: start");

		// hide elements during transition
		Element.show('lightboxLoad_'+z_Index);
		Element.hide('lightboxImage_'+z_Index);
		Element.hide('lightboxHTML_'+z_Index);
		
		// issue ajax update request. issue via post. this should retain GET parameters but also send through
		// the lightbox POST parameter - thus providing scripts with a way to know if they should return
		// an HTML fragment (for the lightbox) or a full HTML page (for non-JS browsers).
		trace("showHTML: firing AJAX");
		var ajax = new Ajax.Updater( 'lightboxHTMLContent_'+z_Index, theSrc, 
											{ 	method:'post', 
												parameters:'lightbox=1', 
												onComplete:function() { trace("showHTML: updater has completed"); myLightbox.displayHTML( z_Index ); }
											} );
											
		trace("ShowHTML: end. Ajax: "+ajax);
	},
	
	// 
	// 	displayHTML()
	// 	formats the HTML field once it's been updated by the Ajax object
	//
	displayHTML: function( z_Index ) {
		
		trace("displayHTML: start");
		
		// traverse the new links just entered
		this.traverseLinks( $('lightboxHTMLContent_'+z_Index) );
		
		trace("displayHTML: links traversed");
		
		// hide loader and appear the background and HTML box
		Element.hide('lightboxLoad_'+z_Index);
		Element.show('background_'+z_Index );
		Element.show('lightboxHTML_'+z_Index );
		Element.show('htmlCloseBox_'+z_Index );
		
		trace("displayHTML: end");
	},
	
	//
	//	showImage()
	//	uses an image object to preload info before showing it.
	//
	showImage: function( theSrc, z_Index ) {

		// hide elements during transition
		Element.show('lightboxLoad_'+z_Index);
		Element.hide('lightboxImage_'+z_Index);
		Element.hide('lightboxHTML_'+z_Index);
		Element.setStyle('background_'+z_Index, { background:'transparent'} );
		
		// apply the end function to the TD onclick handler
		$('lightboxTD_'+z_Index).onclick = function () { myLightbox.end( z_Index ); }
		
		imgPreloader = new Image();
		
		// once image is preloaded, resize image container
		imgPreloader.onload = function() {
			
			// set the source (remember the lightboxImage is still hidden)
			Element.setSrc('lightboxImage_'+z_Index, imgPreloader.src);
			// adjust...
			Element.setStyle('outerBoxContainer_'+z_Index, {backgroundColor:'#fff'} );		// bring in the background - hidden while loading
			Element.setStyle('boxContainer_'+z_Index, {padding:'10px'} );					// set padding for images. other media do not use padding
			Element.setWidth( 'outerBoxContainer_'+z_Index, imgPreloader.width+(borderSize*2) );	// set height and width to image dims
			// only apply the extra height if we're not on IE
			var extraHeight = (isIE) ? 0 : (borderSize*2);
			Element.setHeight( 'outerBoxContainer_'+z_Index, imgPreloader.height+extraHeight );
			// hide the loading div
			Element.hide('lightboxLoad_'+z_Index);
			Element.show('lightboxImage_'+z_Index);
		}
		imgPreloader.src = theSrc;
	},

	//
	//	end()
	//
	end: function( z_Index ) {
		
		// show the scrollbar - NOTE: this is disabled because it forces re-rendering of the Flash element and cuts the music out!
		// Element.setStyle( objHTML, { overflow:objHTML.origOverflow } );
		// Element.setStyle( objBody, { overflow:objBody.origOverflow } );
		
		// new 2008.06.02
		document.body.style.overflow = '';
		
		// remove the lightbox element from the DOM
		objBody.removeChild( $('lightbox_'+z_Index) );
		
		// if there are no more lightboxes, then show the player again
		if (!checkForLightboxes()) $('player').style.visibility = '';
	}
}

function appendLightBox()
{
	/*
		appendLightBox()
		- creates a new instance of the lightBox HTML nest, appended to the body tag.
		- sets the z-index of the new instance above all others using the global z-index setting.
		- returns the z-index of the overlay, which also doubles up as the naming convention for the 'overlay' and 'lightbox' divs.
	*/
		
	// hide the player
	$('player').style.visibility = 'hidden';
	
	// isolate z-indexes of the new elements
	var z = globalZIndex;
	// increment global z index by two
	globalZIndex += 1;

	//	append a new lb_background-class DIV to the body
	var objLightbox = document.createElement("div");
	objLightbox.className = 'lightbox';
	objLightbox.setAttribute('id','lightbox_'+z);
	// make this above all existing elements
	objLightbox.style.zIndex = z;
	objLightbox.style.display = 'none';
	objBody.appendChild(objLightbox);
	
	var closeLink = '<a href="javascript:myLightbox.end('+z+');">(x)</a>';
	
	objLightbox.innerHTML =
		'<div class="overlay" id="overlay_'+z+'"></div>'+
		'<div class="lb_background" id="background_'+z+'">'+
			'<table width="100%" border="0" cellpadding="0" cellspacing="0" class="lightboxTable"><tr><td align="center" id="lightboxTD_'+z+'" height="100%">'+
				'<div class="outerBoxContainer" id="outerBoxContainer_'+z+'">'+
					'<div class="boxContainer" id="boxContainer_'+z+'">'+
						'<div class="lightboxImage"><img hspace="0" vspace="0" id="lightboxImage_'+z+'" /></div>'+
						'<div class="lightboxHTML" id="lightboxHTML_'+z+'">'+
							'<div class="lightboxHTMLContent" id="lightboxHTMLContent_'+z+'"></div>'+
							'<div class="htmlCloseBox" id="htmlCloseBox_'+z+'">'+closeLink+'</div>'+
						'</div>'+
						'<div class="lightboxLoad" id="lightboxLoad_'+z+'">'+
							'<table style="width:100%;height:100%" border="0"><tr><td align="center" valign="middle">'+
								'<a href="javascript:myLightbox.end('+z+');"><img border="0" src="images/loading.gif"></a>'+
							'</td></tr></table>'+
						'</div>'+
					'</div>'+
				'</div>'+
			'</td></tr></table>'
		'</div>';
		
	// alias up the overlay
	var objOverlay = $('overlay_'+z);
	
	// show the lightbox + load image
	Element.show( objLightbox );
	Element.show('lightboxLoad_'+z);
	
	// get document scroll top and full scroll height
	var bodyTop = getScrollTop();
	var bodyScroll = getScrollHeight();
	// move the lightbox down to the top of the viewport
	objLightbox.style.top = bodyTop+'px';
	// move the overlay UP to the top of the document
	objOverlay.style.top = '-'+bodyTop+'px';
	// and resize it to the full height of the document.
	objOverlay.style.height = bodyScroll+'px';
		
	// return the value of z used.
	return z;
}

//
// checkForLightboxes()
// this function is used to detect if there's currently a div of class 'lightbox' in the page.
// 
function checkForLightboxes() 
{
	var classElements = new Array();
	var els = objBody.getElementsByTagName('div');
	var elsLen = els.length;
	for (i = 0, j = 0; i < elsLen; i++) {
		if ( els[i].className=='lightbox' ) return true;
	}
	return false;
}

//
// getPageSize()
//
function getScrollHeight()
{	
	if (window.innerHeight && window.scrollMaxY) return window.innerHeight + window.scrollMaxY;
	else if (document.documentElement && document.documentElement.scrollHeight) return document.documentElement.scrollHeight;
	else if (document.body) return document.body.scrollHeight;
}

function getScrollTop()
{
	if (window.innerHeight) return window.pageYOffset;
	else if (document.documentElement && document.documentElement.scrollTop) return document.documentElement.scrollTop;
	else if (document.body) return document.body.scrollTop;
}

// ---------------------------------------------------
// initLightbox assigns the first row of links.
function initLightbox() { myLightbox = new Lightbox(); }