// -----------------------------------------------------------------------------------
//	FeatureBox by View 2008
//	Based on lightbox v2.03.3 by Lokesh Dhakar - http://www.huddletogether.com
//	Licensed under the Creative Commons Attribution 2.5 License - http://creativecommons.org/licenses/by/2.5/
// -----------------------------------------------------------------------------------
//
//	Configuration
//

var overlayOpacity = 0.3;	// controls transparency of shadow overlay

var animate = true;			// toggles resizing animations
var resizeSpeed = 7;		// controls the speed of the image resizing animations (1=slowest and 10=fastest)

var borderSize = 10;		//if you adjust the padding in the CSS, you will need to update this variable

// -----------------------------------------------------------------------------------

//
//	Global Variables
//
var imageArray = new Array;
var activeImage;
var init = true;

if(animate == true){
	overlayDuration = 0;	// shadow fade in/out duration
	if(resizeSpeed > 10){ resizeSpeed = 10;}
	if(resizeSpeed < 1){ resizeSpeed = 1;}
	resizeDuration = (11 - resizeSpeed) * 0.15;
} else { 
	overlayDuration = 0;
	resizeDuration = 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;
	}
});

// -----------------------------------------------------------------------------------

//
//	Extending built-in Array object
//	- array.removeDuplicates()
//	- array.empty()
//


// -----------------------------------------------------------------------------------

Array.prototype.empty = function () {
	for(i = 0; i <= this.length; i++){
		this.shift();
	}
}

// -----------------------------------------------------------------------------------

//
//	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 Swfbox = Class.create();

Swfbox.prototype = {
	
	// initialize()
	// Constructor runs on completion of the DOM loading. Calls updateSwfList 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.updateSwfList();

		// Code inserts html at the bottom of the page that looks similar to this:
		//
		//	<div id="swfOverlay"></div>
		//	<div id="swfbox">
		//		<div id="outerSwfContainer">
		//			<div id="swfContainer">
		//				<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="featureDataContainer">
		//			<div id="featureData">
		//				<div id="imageDetails">
		//					<span id="caption"></span>
		//					<span id="numberDisplay"></span>
		//				</div>
		//				<div id="featureBottomNav">
		//					<a href="#" id="featureBottomNavClose">
		//						<img src="images/close.gif">
		//					</a>
		//				</div>
		//			</div>
		//		</div>
		//	</div>


		var objBody = document.getElementsByTagName("body").item(0);
		
		var objswfOverlay = document.createElement("div");
		objswfOverlay.setAttribute('id','swfOverlay');
		objswfOverlay.style.display = 'none';
		objswfOverlay.onclick = function() { mySwfbox.end(); }
		objBody.appendChild(objswfOverlay);
		
		var objSwfbox = document.createElement("div");
		objSwfbox.setAttribute('id','swfbox');
		objSwfbox.style.display = 'none';
		objSwfbox.onclick = function(e) {	// close Swfbox is user clicks shadow overlay
			if (!e) var e = window.event;
			var clickObj = Event.element(e).id;
			if ( clickObj == 'swfbox') {
				mySwfbox.end();
			}
		};
		objBody.appendChild(objSwfbox);
			
		var objouterSwfContainer = document.createElement("div");
		objouterSwfContainer.setAttribute('id','outerSwfContainer');		
		objSwfbox.appendChild(objouterSwfContainer);

		// When Swfbox 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 objswfContainer = document.createElement("div");
		objswfContainer.setAttribute('id','swfContainer');
		objouterSwfContainer.appendChild(objswfContainer);
	
		var objSwfboxIFRAME = document.createElement("iframe");
		objSwfboxIFRAME.setAttribute('id','SWFIFRAME');
		objSwfboxIFRAME.style.width = "945px";
		objSwfboxIFRAME.style.height = "570px";
		objSwfboxIFRAME.style.border = "none";
		objSwfboxIFRAME.scrolling="no";
		objSwfboxIFRAME.frameBorder="0";
		objswfContainer.appendChild(objSwfboxIFRAME);

		/*var objSwfboxImage = document.createElement("img");
		objSwfboxImage.setAttribute('id','lightboxImage');
		objswfContainer.appendChild(objSwfboxImage);*/

	},


	//
	// updateSwfList()
	// Loops through anchor tags looking for 'lightbox' references and applies onclick
	// events to appropriate links. You can rerun after dynamically adding images w/ajax.
	//
	updateSwfList: 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('swfbox'))){
				anchor.onclick = function () {mySwfbox.start(this); return false;}
			}
		}

	},
	
	
	//
	//	start()
	//	Display overlay and lightbox. If image is part of a set, add siblings to imageArray.
	//
	start: function(imageLink) {	
		
		//hideSelectBoxes();
		hideFlash();

		if (Prototype.Browser.IE)
		{
			$$('select').each(function(node){ node.style.visibility = 'hidden' });
			
		} 

		// stretch overlay to fill page and fade in
		var arrayPageSize = getPageSize();
		Element.setWidth('swfOverlay', arrayPageSize[0]);
		Element.setHeight('swfOverlay', arrayPageSize[1]);

		new Effect.Appear('swfOverlay', { duration: overlayDuration, from: 0.0, to: overlayOpacity });

		imageArray = [];
		imageNum = 0;		

		if (!document.getElementsByTagName){ return; }
		var anchors = document.getElementsByTagName( imageLink.tagName);

		// Takes the url from the link 
		//var linkValue = imageLink.getAttribute('href');
		//document.getElementById('printLink').href = linkValue;

		// if image is NOT part of a set..
		if((imageLink.getAttribute('rel') == 'swfboxiframe')){
			// add single image to imageArray
			imageArray.push(new Array(imageLink.getAttribute('href'), imageLink.getAttribute('title')));			
		} else {
		// if image is part of a set..

			// 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') == imageLink.getAttribute('rel'))){
					imageArray.push(new Array(anchor.getAttribute('href'), anchor.getAttribute('title')));
				}
			}
			while(imageArray[imageNum][0] != imageLink.getAttribute('href')) { imageNum++;}
		}

		// calculate top and left offset for the lightbox 
		var arrayPageScroll = getPageScroll();
		var lightboxTop = arrayPageScroll[1] + (arrayPageSize[3] / 10);
		var lightboxLeft = arrayPageScroll[0];


		Element.setTop('swfbox', lightboxTop);
		Element.setLeft('swfbox', lightboxLeft);
		

		Element.show('swfbox');
			

		Element.setWidth('outerSwfContainer', 945);
		Element.setHeight('outerSwfContainer', 570);


		mySwfbox.enableKeyboardNav();

		this.changeImage(0);
	},

	//
	//	changeImage()
	//	Hide most elements and preload image in preparation for resizing image container.
	//
	changeImage: function(imageNum) {	
		
		activeImage = imageNum;	// update global var
		this.loadInfo(imageArray[0][0]);
	},
	//
	loadInfo: function(url) {
		
			//var myAjax = new Ajax.Request(
			//url,
			//{method: 'get', parameters: "", onComplete: this.processInfo.bindAsEventListener(this)}
			//);
			
			var div = document.getElementById('SWFIFRAME');
			
			/*var swfIframe = document.createElement("iframe");
			swfIframe.setAttribute('id','SWFIFRAME');
			swfIframe.style.width = "945px";
			swfIframe.style.height = "570px";
			swfIframe.style.border = "none";
			swfIframe.scrolling="no";
			swfIframe.frameBorder="0";
			div.appendChild(swfIframe);*/
			div.src = url;
			
		},
	
	// Display Ajax response
	//processInfo: function(response){
		//if(init){
			
			//var str = response.responseText; //.toLowerCase().indexOf('body')
			//str=str.replace(/[^~]*(<!-- Start Lightbox Content -->)/, "")
			//str=str.replace(/(<!-- End Lightbox Content -->)[^~]*/, "")
			//div.innerHTML = str;
			//var x = div.getElementsByTagName("script"); 
			//for(var i=0;i<x.length;i++)
			//{
//alert(x[i].text);
			//	eval(x[i].text);
			//}

		//}
	//},

	//
	//	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
			mySwfbox.end();
		} 
	},

	

	//
	//	end()
	//
	end: function() {
		mySwfbox.disableKeyboardNav();
		Element.hide('swfbox');
		new Effect.Fade('swfOverlay', { duration: overlayDuration});
		//showSelectBoxes();
		showFlash();
		if (Prototype.Browser.IE)
		{
			$$('select').each(function(node){ node.style.visibility = 'visible' });
		}
	}
}

// -----------------------------------------------------------------------------------

//
// getPageScroll()
// Returns array with x,y page scroll values.
// Core code from - quirksmode.com
//
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
//
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;
	
//	console.log(self.innerWidth);
//	console.log(document.documentElement.clientWidth);

	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;
	}

//	console.log("xScroll " + xScroll)
//	console.log("windowWidth " + windowWidth)

	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){	
		pageWidth = xScroll;		
	} else {
		pageWidth = windowWidth;
	}
//	console.log("pageWidth " + pageWidth)

	arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight) 
	return arrayPageSize;
}

// -----------------------------------------------------------------------------------

// ---------------------------------------------------

function showSelectBoxes(){
	var selects = document.getElementsByTagName("select");
	for (i = 0; i != selects.length; i++) {
		selects[i].style.visibility = "visible";
	}
}

// ---------------------------------------------------

function hideSelectBoxes(){
	var selects = document.getElementsByTagName("select");
	for (i = 0; i != selects.length; i++) {
		selects[i].style.visibility = "hidden";
	}
}

// ---------------------------------------------------
var tmpString = "";

function showFlash(){	
	
	try{
		//Mac safari doesnt like to chagne the visabliliy of the flahs on the homepage, so we do this
		document.getElementById('banner-home').innerHTML = tmpString;
	}catch(err){}

	var x = document.getElementsByTagName("script"); 
	for(var i=0;i<x.length;i++)
	{
	    //eval(x[i].text);
	    if (
	    (x[i].text.indexOf('setGoogleAnalytics', 0) == -1) &&
	    (x[i].text.indexOf('callPageTracker', 0) == -1)
	    ) {
	        try {
	            eval(x[i].text);
	        }
	        catch (err) { }
	    }
	}
	
	var flashObjects = document.getElementsByTagName("object");
	for (i = 0; i < flashObjects.length; i++) {
		flashObjects[i].style.visibility = "visible";
	}

	var flashEmbeds = document.getElementsByTagName("embed");
	for (i = 0; i < flashEmbeds.length; i++) {
		flashEmbeds[i].style.visibility = "visible";
	}
}

// ---------------------------------------------------


function hideFlash(){

	try{
		//Mac safari doesnt like to chagne the visabliliy of the flash on the homepage, so we do this
		tmpString = document.getElementById('banner-home').innerHTML;
		document.getElementById('banner-home').innerHTML = "";
	}catch(err){}



	var flashObjects = document.getElementsByTagName("object");

	for (i = 0; i < flashObjects.length; i++) {
		//flashObjects[i].style.visibility = "hidden";
		flashObjects[i].style.visibility = "hidden";
	}




	var flashEmbeds = document.getElementsByTagName("embed");
	for (i = 0; i < flashEmbeds.length; i++) {
		//flashEmbeds[i].style.visibility = "hidden";
		flashEmbeds[i].style.visibility = "hidden";
	}


  
}


// ---------------------------------------------------

//
// pause(numberMillis)
// Pauses code execution for specified time. Uses busy code, not good.
// Help from Ran Bar-On [ran2103@gmail.com]
//

function pause(ms){
	var date = new Date();
	curDate = null;
	do{var curDate = new Date();}
	while( curDate - date < ms);
}
/*
function pause(numberMillis) {
	var curently = new Date().getTime() + sender;
	while (new Date().getTime();	
}
*/
// ---------------------------------------------------



function initSwfbox() { mySwfbox = new Swfbox(); }
Event.observe(window, 'load', initSwfbox, false);
//Event.observe(window, 'unload', Event.unloadCache, false);
