//
//	Configuration
//
var fallbackOverlayImage = "images/overlay.png";			// Fallback overlay used with browsers that have opacity problems
var overlayOpacity = 0.8;									// Controls transparency of shadow overlay

//
//	Global Variables
//
var elementArray = new Array;
var activeElement;
var userAgent = navigator.userAgent.toLowerCase();

var overlayDuration = 0;

//
//	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";
	},
	setLeft: function(element,l) {
	   	element = $(element);
    	element.style.left = l +"px";
	},
	setSrc: function(element,src) {
    	element = $(element);
    	element.src = src; 
	},
	setHref: function(element,href) {
    	element = $(element);
    	element.href = href; 
	},
	setInnerHTML: function(element,content) {
		element = $(element);
		element.innerHTML = content;
	}
});

var Lightbox = Class.create();

Lightbox.prototype = {
	
	// initialize()
	// Constructor runs on completion of the DOM loading. Calls updateElementList and then
	// 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.updateElementList();

		// 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">
		//				<div id="lightboxcontent">
		//					<div id="lightboxswf">
		//					</div>
		//				</div>
		//			</div>
		//		</div>
		//	</div>

		var objBody = document.getElementsByTagName("body").item(0);
		
		var objOverlay = document.createElement("div");
		objOverlay.setAttribute('id','overlay');
		
		// The mozilla flavors on the mac, specifically Firefox and Camino have difficulties displaying flash over anything with dynamically generated opacity.
		// Here we're using the fallBackOverlayImage to alleviate this problem.    This is a semi-transparent png which is included with the script.
		if (userAgent.indexOf('mac') != -1 && userAgent.indexOf('firefox')!=-1 || userAgent.indexOf('camino')!=-1) {
			objOverlay.style.backgroundImage = 'url('+fallbackOverlayImage+')';
			objOverlay.style.backgroundRepeat = 'repeat';
		}else{
			objOverlay.style.backgroundColor = '#000000';
		}
		objOverlay.style.display = 'none';
		objOverlay.onclick = function() { myLightbox.end(); }
		objBody.appendChild(objOverlay);
		
		var objLightbox = document.createElement("div");
		objLightbox.setAttribute('id','lightbox');
		objLightbox.style.display = 'none';
		objLightbox.onclick = function(e) {
			if (!e) var e = window.event;
			var clickObj = Event.element(e).id;
			if ( clickObj == 'lightbox') {
				myLightbox.end();
			}
		};
		objBody.appendChild(objLightbox);
			
		var objOuterImageContainer = document.createElement("div");
		objOuterImageContainer.setAttribute('id','outerImageContainer');
		objLightbox.appendChild(objOuterImageContainer);

		var objImageContainer = document.createElement("div");
		objImageContainer.setAttribute('id','imageContainer');
		objOuterImageContainer.appendChild(objImageContainer);
		
		var objContent = document.createElement("div");
		objContent.setAttribute('id','lightboxcontent');
		objImageContainer.appendChild(objContent);
		
		objLightboxSwf = document.createElement("div");
		objLightboxSwf.setAttribute('id','lightboxswf');
		objLightboxSwf.style.position = 'relative';
		objLightboxSwf.style.zIndex = 101; // Safari
		objLightboxSwf.style.display = 'none';
		objContent.appendChild(objLightboxSwf);
	},

	//
	// updateElementList()
	// Loops through anchor tags looking for 'lightbox' references and applies onclick
	// events to appropriate links. You can rerun after dynamically adding images w/ajax.
	//
	updateElementList: function() {	
		if (!document.getElementsByTagName){ return; }
		var anchors = document.getElementsByTagName('a');
		var areas = document.getElementsByTagName('area');

		// Loop through all anchor tags...
		for (var i=0; i<anchors.length; i++){
			var anchor = anchors[i];
			
			var relAttribute = String(anchor.getAttribute('rel'));
			
			// Use the string.match() method to catch 'lightbox' references in the rel attribute
			if (anchor.getAttribute('href') && (relAttribute.toLowerCase().match('lightbox'))){
				anchor.onclick = function () {myLightbox.start(this); return false;}
			}
		}

		// Loop through all area tags...
		// ToDo: Combine anchor & area tag loops
		for (var i=0; i< areas.length; i++){
			var area = areas[i];
			
			var relAttribute = String(area.getAttribute('rel'));
			
			// Use the string.match() method to catch 'lightbox' references in the rel attribute...
			if (area.getAttribute('href') && (relAttribute.toLowerCase().match('lightbox'))){
				area.onclick = function () {myLightbox.start(this); return false;}
			}
		}
	},
	
	//
	//	start()
	//	Display overlay and lightbox. If element is part of a set, add siblings to elementArray.
	//
	start: function(elementLink) {	

		//hideSelectBoxes();		
		//hideFlash();
		
		// stretch overlay to fill page and fade in
		var arrayPageSize = getPageSize();
		Element.setWidth('overlay', arrayPageSize[0]);
		Element.setHeight('overlay', arrayPageSize[1]);
		
		// Again, if the user is on a Mac and has a Mozilla flavor browser, we can't use dynamically generated opacity or you will experience problems with the Flash movies.
		if (userAgent.indexOf('mac') != -1 && userAgent.indexOf('firefox')!=-1 || userAgent.indexOf('camino')!=-1) {
			Element.show('overlay');
		}else{ // Non-Mac, carry on as usual.
			new Effect.Appear('overlay', { duration: 0, from: 0.0, to: overlayOpacity });
		}

		elementArray = [];
		elementNum = 0;		

		if (!document.getElementsByTagName){ return; }
		var anchors = document.getElementsByTagName(elementLink.tagName);
		
		// If the image or SWF is not a part of the set...
		if((elementLink.getAttribute('rel') == 'lightbox')){
			// Add single image or SWF to elementArray
			if(elementLink.getAttribute('href').endsWith('swf')) { // SWF
				elementArray.push(new Array(elementLink.getAttribute('href'), elementLink.getAttribute('title'), elementLink.getAttribute('width'), elementLink.getAttribute('height')));
			} else { // Image
				elementArray.push(new Array(elementLink.getAttribute('href'), elementLink.getAttribute('title')));
			}				
		} else {
		// Image or SWF is not part of a set...
				
			// Loop through anchors, find other images/SWF's in the set, and add them to elementArray
			for (var i=0; i<anchors.length; i++){
				var anchor = anchors[i];
				if (anchor.getAttribute('href') && (anchor.getAttribute('rel') == elementLink.getAttribute('rel'))){
					if(anchor.getAttribute('href').endsWith('swf')) { // SWF
						elementArray.push(new Array(anchor.getAttribute('href'), anchor.getAttribute('title'), anchor.getAttribute('width'), anchor.getAttribute('height')));
					} else {
						elementArray.push(new Array(anchor.getAttribute('href'), anchor.getAttribute('title')));
					}
				}
			}
			elementArray.removeDuplicates();
			while(elementArray[elementNum][0] != elementLink.getAttribute('href')) { elementNum++;}
		}
		/* REMOVED BECAUSE OF INCONSISTENT PLACEMENT BETWEEN IE AND FF -WR
		// Calculate top and left offset for the lightbox 
		var arrayPageScroll = getPageScroll();
		var lightboxTop = arrayPageScroll[1] + (arrayPageSize[3] / 10);
		var lightboxLeft = arrayPageScroll[0];
		Element.setTop('lightbox', lightboxTop);
		Element.setLeft('lightbox', lightboxLeft);
		*/
		Element.show('lightbox');
		
		this.changeElement(elementNum);
	},

	//
	//	changeElement()
	//	Hide most elements and preload image in preparation for resizing the element container.
	//
	changeElement: function(elementNum) {	
		
		activeElement = elementNum;	// Update global var

		if (elementArray[activeElement][0].endsWith('swf')){ // SWF
		this.showElement();
			// No preloading needed here, if a preloader is needed for the Flash movie, it should be built into said Flash movie.
			//myLightbox.resizeElementContainer(parseInt(elementArray[activeElement][2]), parseInt(elementArray[activeElement][3]))
		}
	},

	//
	//	showElement()
	//	Display image or SWF and begin preloading neighbors (if image).
	//
	showElement: function(){
		var obj = $('lightboxswf');
		obj.innerHTML = "<object classid=\"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000\" codebase=\"http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,19,0\" width=\""+elementArray[activeElement][2]+"\" height=\""+elementArray[activeElement][3]+"\">" +
			"<param name=\"movie\" value=\""+elementArray[activeElement][0]+"\"/>" +
			"<param name=\"quality\" value=\"high\" />" +
			"<param name=\"allowscriptaccess\" value=\"always\" />" +
			"<param name=\"wmode\" value=\"transparent\" />" +
			"<embed wmode=\"transparent\" allowscriptaccess=\"always\" src=\""+elementArray[activeElement][0]+"\" quality=\"high\" pluginspage=\"http://www.macromedia.com/go/getflashplayer\" type=\"application/x-shockwave-flash\" width=\""+elementArray[activeElement][2]+"\" height=\""+elementArray[activeElement][3]+"\">" +
			"</embed>" +
			"</object>";
		new Effect.Appear('lightboxswf', { duration: 0}); 
	},

	//
	//	updateNav()
	//	Display appropriate previous and next hover navigation.
	//
	updateNav: function() {
	
		this.enableKeyboardNav();
	},

	//
	//	enableKeyboardNav()
	//
	enableKeyboardNav: function() {
		document.onkeydown = this.keyboardAction; 
	},

	//
	//	disableKeyboardNav()
	//
	disableKeyboardNav: function() {
		document.onkeydown = '';
	},

	//
	//	keyboardAction()
	//
	keyboardAction: function(e) {
		if (e == null) { // ie
			keycode = event.keyCode;
			escapeKey = 27;
		} else { // Mozilla
			keycode = e.keyCode;
			escapeKey = e.DOM_VK_ESCAPE;
		}

		key = String.fromCharCode(keycode).toLowerCase();
		
		if((key == 'x') || (key == 'o') || (key == 'c') || (keycode == escapeKey)){	// Close lightbox
			myLightbox.end();
		} else if((key == 'p') || (keycode == 37)){	// Display previous image/SWF
			if(activeElement != 0){
				myLightbox.disableKeyboardNav();
				myLightbox.changeElement(activeElement - 1);
			}
		} else if((key == 'n') || (keycode == 39)){	// Display next image/SWF
			if(activeElement != (elementArray.length - 1)){
				myLightbox.disableKeyboardNav();
				myLightbox.changeElement(activeElement + 1);
			}
		}

	},

	//
	//	end()
	//
	end: function() {
		this.disableKeyboardNav();
		var obj = $('lightboxswf');
		obj.innerHTML = "";
		Element.hide('lightbox');
		new Effect.Fade('overlay', { duration: overlayDuration});
		//showSelectBoxes();
		//showFlash();
	}
}

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

/* NOT USED. OUTPUT USED IN PLACEMENT OF SWF IF PAGE SCROLLED.
PLACEMENT WAS INCONSISTNET BETWEEN FF AND IE -WR

function getPageScroll(){

	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.com
// Edit for Firefox by pHaez
//
// GETS THE CURRENT H X W OF PAGE TO STRETCH THE LIGHTBOX GREY-OUT AREA TO FILL
function getPageSize(){
	
	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 = xScroll;		
	} else {
		pageWidth = windowWidth;
	}

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

function initLightbox() { myLightbox = new Lightbox(); }
Event.observe(window, 'load', initLightbox, false);
