// For original FULL CODE COMMENTS grab the original lightbox source: http://www.huddletogether.com/projects/lightbox2/releases/lightbox2.03.3.zip
//	Lightbox v2.03.3 by Lokesh Dhakar
//	http://huddletogether.com/projects/lightbox2/
//	Licensed under the Creative Commons Attribution 2.5 License
//
// feb/20/2009: Modifed by tony to be Pano Aware, uses /wp-content/imgcheck.php via ajax xmlHttpRequest to examine images
// 
// modifed this heavily to remove redundant objects and to simplify excessive layering of objects upon objects and elements within elements.
// removed the attachement to the window.onload event because this does not trigger until ALL the bloody images are loaded by the browser.. and by then
// users have clicked or want to click the already loaded images. - it's too damn slow and too late.



// -----------------------------------------------------------------------------------
//	Configuration
// -----------------------------------------------------------------------------------
var LBoverlayOpacity  = 0.80;	    // controls transparency of shadow overlay
var LBanimate         = false;	    // toggles resizing animations
var LBresizeSpeed     = 10;		    // controls the speed of the image resizing animations (1=slowest and 10=fastest)
var LBborderSize      = 10;         //if you adjust the padding in the CSS, you will need to update this variable
var _LBdebugger       = false;       //false to disable the debug messages, requires <div id='debug_window'></div> somewhere.
var _LBdebugVersion   = '1.93.36';
var _LBcheckImgPath   = '/wp-content/';
var _LBtargetMapDiv   = 'mapWrapper'; //'mapwrapper';
var LBpanoWidth,LBpanoHeight;
var LBflashLoaded      =false;
if(LBanimate == true){
    LBoverlayDuration = .250;	    // shadow fade in/out duration
    if(LBresizeSpeed > 10){ LBresizeSpeed = 10;}
    if(LBresizeSpeed < 1) { LBresizeSpeed = 1;}
    LBresizeDuration  = (11 - LBresizeSpeed) * 0.15;
} else { 
    LBoverlayDuration = 0;
    LBresizeDuration  = 0;
}
var LBisIE            = document.all?true:false;
var LBfirstLoad       = 0;

// -----------------------------------------------------------------------------------
//	Global Variables
// -----------------------------------------------------------------------------------
var LBobjMap;
var LBobjBody;
var LBimageArray = new Array;
var LBactiveImage = -1; //disable refreshes ...
var LBobjOverlay;
var LBobjLightbox;
var LBobjOuterImageContainer;
var LBobjImageContainer;
var LBobjPanoContainer;
var LBshutterLinks = {};
var preloadNextImage = {};
var preloadPrevImage = {};
var LBurlCache = new Array;
var LBurlStatus = new Array;;
var LBcalls =0; //used by debugger

/*
// Provide the XMLHttpRequest class for IE 5.x-6.x:
if( typeof XMLHttpRequest == "undefined" ) XMLHttpRequest = function() {
  try { return new ActiveXObject("Msxml2.XMLHTTP.6.0") } catch(e) {}
  try { return new ActiveXObject("Msxml2.XMLHTTP.3.0") } catch(e) {}
  try { return new ActiveXObject("Msxml2.XMLHTTP") } catch(e) {}
  try { return new ActiveXObject("Microsoft.XMLHTTP") } catch(e) {}
  throw new Error( "This browser does not support XMLHttpRequest." )
};
*/

//####################################################################################
LBxmlhttp = {  //############## Tonys xml pano scanner Class ###########################
//####################################################################################
// reads an image and reports if it is pano or not 
// via the header and html - header is faster.
// can read whole data blocks into any div
// -----------------------------------------------------------------------------------
    loadExternalContent : function (url, target) { //requests a whole url to be read
// -----------------------------------------------------------------------------------    
        var req;
        document.getElementById(target).innerHTML = ' Fetching data...';

        if( typeof XMLHttpRequest == "undefined" ) XMLHttpRequest = function() {
          try { return new ActiveXObject("Msxml2.XMLHTTP.6.0") } catch(e) {}
          try { return new ActiveXObject("Msxml2.XMLHTTP.3.0") } catch(e) {}
          try { return new ActiveXObject("Msxml2.XMLHTTP") } catch(e) {}
          try { return new ActiveXObject("Microsoft.XMLHTTP") } catch(e) {}
          throw new Error( "This browser does not support XMLHttpRequest." )
        };

        //if (window.XMLHttpRequest) {
            req = new XMLHttpRequest();
        //} else if (window.ActiveXObject) {
        //    req = new ActiveXObject("Microsoft.XMLHTTP");
        //}
        if (req !== undefined) {
            req.onreadystatechange = function() {LBxmlhttp.loadExternalContentDone(req, url, target);};
            req.open("GET", url, true);
            req.send("");
        }
    },
// -----------------------------------------------------------------------------------
    loadExternalContentDone : function (req, url, target) { //services the request
// -----------------------------------------------------------------------------------
        var theInnerHtml,d;
        switch(req.readyState) { 
            case 3: //Headers returned
            break;
            case 4: //document data has been returned.
                d=document.getElementById(target);
                if (req.status == 200) { 
                    d.innerHTML = req.responseText;
                } else {
                    d.innerHTML=" loadExternalContent Error:\n"+ req.status + "\n" +req.statusText;
                }
                req.abort(); //close the object we are done.
            break;
            case 0:
            case 1: //OPEN just completed
            case 2: //the URL was sent successfully, now waiting response
            break;
        }
    },
// -----------------------------------------------------------------------------------
    isPano : function(url,index){ // check if url is a pano
// -----------------------------------------------------------------------------------
                        //???????????????????????????????????????????????????????????????????????
                       // LBdebug.echo('['+index+'] rqRedy=0 Loading isPano Scan for '+url+'<br>');
                        //???????????????????????????????????????????????????????????????????????
        if(LBurlCache[url]){
            return LBurlStatus[url];
        }else{
            LBurlStatus[url]=-1;
            LBurlCache[url]=true;
            
            LBxmlhttp.readHeader(url,index);
            
            return -1;
        }
    },
// -----------------------------------------------------------------------------------
    readHeader : function (url,index) { //requests only the header to be read
// -----------------------------------------------------------------------------------
     var req;
        if( typeof XMLHttpRequest == "undefined" ) XMLHttpRequest = function() {
          try { return new ActiveXObject("Msxml2.XMLHTTP.6.0") } catch(e) {}
          try { return new ActiveXObject("Msxml2.XMLHTTP.3.0") } catch(e) {}
          try { return new ActiveXObject("Msxml2.XMLHTTP") } catch(e) {}
          try { return new ActiveXObject("Microsoft.XMLHTTP") } catch(e) {}
          throw new Error( "This browser does not support XMLHttpRequest." )
        };

        req = new XMLHttpRequest();

        //if (window.XMLHttpRequest) {
        //    req = new XMLHttpRequest();
        //} else if (window.ActiveXObject) {
        //    req = new ActiveXObject("Microsoft.XMLHTTP");
        //}
        if (req !== undefined) {
            req.onreadystatechange = function() {LBxmlhttp.loadExternalHeaderDone(req, index, url);};
            req.open("HEAD", url, true);
            req.send("");
        }
    },
// -----------------------------------------------------------------------------------
    loadExternalHeaderDone : function (req, index, url) { //services header request
// -----------------------------------------------------------------------------------
        var isPano, is404;
        //readystate = 0 ;the initial value
        //readystate = 1 ;OPEN the open() method has been successfully called. 
        //readystate = 2 ;SENT the UA successfully completed the request, but no data has yet been received
        //readystate = 3 ;RECV immediately before receiving the message body (if any). all http headers have been received.
        //               ;does this mean we can abort on a HEAd request? and just take the response header at readyState=3?
        //readystate = 4 ;the data transfer has been completed.
        
        switch(req.readyState){ 
            case 4: // data loaded ...
                if (req.status == 200) {
                    isPano=parseInt(req.getResponseHeader("isPano"));
                    is404=parseInt(req.getResponseHeader("is404"));
                
                    LBurlCache[url]=true;
                    LBurlStatus[url]=isPano;
                    LBshutterLinks[index].isPano=isPano;
                
                    if(is404){
                        LBshutterLinks[index].isPano=-3; //kill the thing as it is not a pano or an image so dont open it.
                    
                        //???????????????????????????????????????????????????????????????????????
                        //LBdebug.echo('['+index+'] rqRedy=4 <b>isPano='+isPano+' '+url+'</b><br><br>');
                       // LBdebug.echo('['+index+'] rqRedy=4 <b>is404='+is404+' Target URL is missing!</b><br>');
                        //???????????????????????????????????????????????????????????????????????
                    }else{
                        //???????????????????????????????????????????????????????????????????????
                        //LBdebug.echo('['+index+'] rqRedy=4 <b>isPano='+isPano+' '+url+'</b><br>');
                        //???????????????????????????????????????????????????????????????????????
                    }
                }else{
                       //LBdebug.echo('['+index+'] rqRedy=4 <b>isPano='+isPano+' '+url+'</b><br>');
                       //LBdebug.echo('['+index+'] rqRedy=4 <b>Error imgcheck.php is missing... ['+req.status+']['+req.statusText+']</b><br>');
                }
                req.abort(); // I have the data so kill it.
            break;
            case 0: //INIT
            case 1: //OPEN has completed successfully .. what if not successful? will it lock up?
            case 2: //SENT the url...
            case 3: //headers are recieved ; Recieving data now
                //???????????????????????????????????????????????????????????????????????
//                LBdebug.echo('['+index+'] rqRedy='+req.readyState+' '+url+'<br>');
                //???????????????????????????????????????????????????????????????????????
            break;
        }
    },
// -----------------------------------------------------------------------------------
    loadContent : function (name, div) {
// -----------------------------------------------------------------------------------
        LBxmlhttp.loadExternalContent(name,div);
        return false;
    }
};
//#######   End LBxmlhttp ##############################################################
//####################################################################################


//####################################################################################
Object.extend(Element, { //####### Element Object manipulations ######################
//####################################################################################
//	Additional methods for Element
	getWidth: function(element) {
	   	element = $(element);
	   	return element.offsetWidth; 
	},
	setWidth: function(element,w) {
	   	element = $(element);
	
	    	element.style.width = w +"px";
	},
	getHeight: function(element) {
	   	element = $(element);
	   	return element.offsetHeight; 
	},
	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;
	},
/*    setZpos: function(element,z){
	   	element = $(element);
    	element.style.z-index = z;    
    },
*/
    getXpos: function(element){
    	element = $(element);
	    
        var curleft = 0;
        if(element.offsetParent){
            while(1){
                curleft += element.offsetLeft;
                if(!element.offsetParent){
                    break;
                }
                element = element.offsetParent;
            }
        }else if(element.x){
            curleft += element.x;
        }
        return curleft;
    },
    getYpos: function(element) {
    	element = $(element);
        var curtop = 0;
        if(element.offsetParent){
            while(1){
                curtop += element.offsetTop;
                if(!element.offsetParent){
                    break;
                }
                element = element.offsetParent;
            }
        }else if(element.y){
            curtop += element.y;
        }
        return curtop;
    }
    
    
});
//############# END Element Object Manipulations #####################################

//####################################################################################
//######################### Array Functions ##########################################
Array.prototype.removeDuplicates = function () {
// -----------------------------------------------------------------------------------
//	Extending built-in Array object
//	- array.removeDuplicates()
//	- array.empty()
    for(var i = 0; i < this.length; i++){
        for(var j = this.length-1; j>i; j--){        
            if(this[i][0] == this[j][0]){
                this.splice(j,1);
            }
        }
    }
}
// -----------------------------------------------------------------------------------
Array.prototype.empty = function () {
// -----------------------------------------------------------------------------------
	for(var i = 0; i <= this.length; i++){
		this.shift();
	}
}
// -----------------------------------------------------------------------------------
Array.prototype.removeElement = function (id) {
// -----------------------------------------------------------------------------------
//	Extending built-in Array object
    this.splice(id,1);
}
// -----------------------------------------------------------------------------------
Array.prototype.activeLength = function () {
// -----------------------------------------------------------------------------------
    var len=0;
    for(var i = 0; i < this.length; i++){
        if($this[i][0]<0){
            //bad record   
        }else{
            len++;
        }
    }
    return len;
}



//######################## END Array Functions########################################
//####################################################################################


//####################################################################################
var _LBLightbox = Class.create();  //########### Light Box Class ########################
//####################################################################################
_LBLightbox.prototype = {
//####################################################################################
//------------------------------------------------------------------------------------
    initialize: function() {	
//------------------------------------------------------------------------------------
	// Constructor runs on completion of the DOM loading. calls updateImageList 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 debugger ###############################################
        //########################################################################
        //return;
        
        var debugWindow=document.getElementById('debug_window');
        LBdebug = {
            echo : function (msg){
                if('object' == typeof debugWindow && _LBdebugger && debugWindow){
                    debugWindow.innerHTML+='['+getMicroTime()+'] '+msg;
                }
            },
            clear : function (msg){
                if ( 'object' == typeof debugWindow && _LBdebugger && debugWindow ){
                    debugWindow.innerHTML='['+getMicroTime()+'] '+msg+'<br>';
                }else{
                    if(('object' != typeof debugWindow) && _LBdebugger ){
                        document.write('No debug window found, add &lt;div id=debug_window>&lt;/div> to the page');
                    }
                }
            }
        };
       //???????????????????????????????????????????????????????????????????????
       // LBdebug.clear('Debug initialized: ver '+_LBdebugVersion+'<br>');
       //???????????????????????????????????????????????????????????????????????
        //########################################################################
        //#### END Debugger ######################################################
        //########################################################################
        


    // initialize()		
		this.updateImageList();
        //Get the map info for relocation...

        LBobjMap  = document.getElementById(_LBtargetMapDiv);
        if(!LBobjMap){ 
         //   LBdebug.echo ("Map object is empty<br>");
        }else{
           // LBdebug.echo("LBobjMap.id  = "+ LBobjMap.id + "<br>");
        }    
        LBobjBody = document.getElementsByTagName("body").item(0);
/*
        LBobjBody.onresize= function () { 
            LBdebug.echo ("LBActiveImage="+LBactiveImage+" Resize Event A Triggered<br>");
            if(LBactiveImage>-1){ myLightbox.resizeWindow(); } 
        }
*/        
        if(typeof LBobjMap == 'object'){
           // LBdebug.echo ("LBobjMap is an object!!!!<br>");
            if(LBobjMap!=null){
                LBdebug.echo ("LBobjMap is NOT null!!!!<br>");
                if(LBobjMap.id == _LBtargetMapDiv){
                    //then I guess it must be valid?
                    LBobjBody = document.getElementById(_LBtargetMapDiv);
                    resizeData= new Array (Element.getXpos(LBobjMap),Element.getYpos(LBobjMap),Element.getWidth(LBobjMap),Element.getHeight(LBobjMap));
                    LBdebug.echo("<b>xpos="+resizeData[0]+" ypos="+resizeData[1]+" Width="+resizeData[2]+" Height="+resizeData[3]+" </b><br>");
                }else{
                    LBdebug.echo ("it still errored!!! <br>");
                }
            }else{
                LBdebug.echo ("but LBobjMap is null.<br>");
                LBdebug.echo ("So no map is present!!!<br>");
            }
        }else{
            LBdebug.echo ("LBobjMap is NOT an object at all!!!!<br>");
        }
      
        
        //TODO  - Resize this container so that it floats in an absolute position over the map
        //      - If and only if the map is present
        //The shaded overlay
            LBobjOverlay = document.createElement("div");
    		LBobjOverlay.setAttribute('id','stimuli_overlay');
    		LBobjOverlay.style.display = 'none';
    		LBobjOverlay.onclick = function() { myLightbox.end(); }
    		LBobjBody.appendChild(LBobjOverlay);
                        
        //TODO  - Resize this container so that it floats in an absolute position over the map
        //      - If and only if the map is present
        //      - Then make all objects and images render themselves relative to this container
    	//The topmost lightbox container	
            LBobjLightbox = document.createElement("div");
    		LBobjLightbox.setAttribute('id','stimuli_lightbox');
    		LBobjLightbox.style.display = 'none';
    		    LBobjLightbox.onclick = function(e) {	// close Lightbox if user clicks shadow overlay
    			if (!e) var e = window.event;
    			var clickObj = Event.element(e).id;
    			if ( clickObj == 'stimuli_lightbox') {
    				myLightbox.end();
    			}
    		};
		    LBobjBody.appendChild(LBobjLightbox);
        //}
        
    //An outer container for the images within
		LBobjOuterImageContainer = document.createElement("div");
		LBobjOuterImageContainer.setAttribute('id','stimuli_outerImageContainer');
		LBobjLightbox.appendChild(LBobjOuterImageContainer);
		
		// 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.
		if(LBanimate){
			Element.setWidth('stimuli_outerImageContainer', 25);
			Element.setHeight('stimuli_outerImageContainer', 25);			
		} else {
			Element.setWidth('stimuli_outerImageContainer', 1);
			Element.setHeight('stimuli_outerImageContainer', 1);			
		}
		
        LBobjImageContainer = document.createElement("div");
		LBobjImageContainer.setAttribute('id','stimuli_imageContainer');
		LBobjOuterImageContainer.appendChild(LBobjImageContainer);
	
		var LBobjLightboxImage = document.createElement("img");
		LBobjLightboxImage.setAttribute('id','stimuli_lightboxImage');
//		Element.setZpos('stimuli_lightboxImage','-1');
        LBobjImageContainer.appendChild(LBobjLightboxImage);
       
		//LBobjBody.appendChild(LBobjLightboxImage);
        
        LBobjPanoContainer= document.createElement("div");                
		LBobjPanoContainer.setAttribute('id','stimuli_panoContainer');                  
		LBobjImageContainer.appendChild(LBobjPanoContainer);
        

        //Loading Animation
		var objLoading = document.createElement("div");
		objLoading.setAttribute('id','stimuli_loading');
		LBobjImageContainer.appendChild(objLoading);
	
		var objLoadingLink = document.createElement("a");
		objLoadingLink.setAttribute('id','stimuli_loadingLink');
		objLoadingLink.setAttribute('href','#');
		objLoadingLink.onclick = function() { myLightbox.end(); return false; }
		objLoading.appendChild(objLoadingLink);

        //Display Data container for LOWER links and nav
        var objImageDataContainer = document.createElement("div");
		objImageDataContainer.setAttribute('id','stimuli_imageDataContainer');
		LBobjLightbox.appendChild(objImageDataContainer);

        //Caption under the image.
		var objImageData = document.createElement("div");
		objImageData.setAttribute('id','stimuli_imageData');
		objImageDataContainer.appendChild(objImageData);
       	
		var objImageDetails = document.createElement("div");
		objImageDetails.setAttribute('id','stimuli_imageDetails');
		objImageData.appendChild(objImageDetails);

/*        var objPrevLink = document.createElement("a");
		objPrevLink.setAttribute('id','stimuli_prevLink');
		objPrevLink.setAttribute('href','#');
		objImageDetails.appendChild(objPrevLink);
*/	
//		var objCaption = document.createElement("span");
//		objCaption.setAttribute('id','stimuli_caption');
//		objImageDetails.appendChild(objCaption);
	
		var objNumberDisplay = document.createElement("span");
		objNumberDisplay.setAttribute('id','stimuli_numberDisplay');
		objImageDetails.appendChild(objNumberDisplay);

//		jQuery("<div>Click the picture and drag</div>").appendTo('#stimuli_imageDetails');
 /*       var objNextLink = document.createElement("a");
		objNextLink.setAttribute('id','stimuli_nextLink');
		objNextLink.setAttribute('href','#');
		objImageDetails.appendChild(objNextLink);
*/
		
//		var objBottomNav = document.createElement("div");
//		objBottomNav.setAttribute('id','stimuli_bottomNav');
//		objImageData.appendChild(objBottomNav);

        //hovering navigation <<  >>
//		var objHoverNav = document.createElement("div");
//		objHoverNav.setAttribute('id','stimuli_hoverNav');
//		objImageDataContainer.appendChild(objHoverNav);
//	    Element.hide('stimuli_hoverNav');

        
	

    
		/*
        var objBottomNavCloseLink = document.createElement("a");
		objBottomNavCloseLink.setAttribute('id','stimuli_bottomNavClose');
		objBottomNavCloseLink.setAttribute('href','#');
		objBottomNavCloseLink.onclick = function() { myLightbox.end(); return false; }
		objBottomNav.appendChild(objBottomNavCloseLink);
        */

        //Create Data container for the Overlayed hover navigation
/*
		var objHoverNav = document.createElement("div");
		objHoverNav.setAttribute('id','stimuli_hoverNav');
		LBobjImageDataContainer.appendChild(objHoverNav);
	    Element.hide('stimuli_hoverNav');
		
		var objNextLink = document.createElement("a");
		objNextLink.setAttribute('id','stimuli_nextLink');
		objNextLink.setAttribute('href','#');
		objHoverNav.appendChild(objNextLink);
*/	
        
	},
//------------------------------------------------------------------------------------
	updateImageList: function() {	
//------------------------------------------------------------------------------------
    //to be triggered by ajax content refreshes
	// updateImageList()
    //return; //disabled (for firefox test)
	// Loops through anchor tags looking for 'lightbox' references and applies onclick
	// events to appropriate links. You can rerun after dynamically adding images w/ajax.
		//killLightbox();
        if(LBflashLoaded){
            swfobject.removeSWF("stimuli_panoContainer");
            LBflashLoaded=false;
            LBobjPanoContainer= document.createElement("div");                
		    LBobjPanoContainer.setAttribute('id','stimuli_panoContainer');                  
//		    Element.setZpos('stimuli_panoContainer','10');
		    LBobjImageContainer.appendChild(LBobjPanoContainer);
        }
   
        if (!document.getElementsByTagName){ return; }
		var anchors = document.getElementsByTagName('a');
		var areas = document.getElementsByTagName('area');
		var stimuli_image_title="";
        var lastURL='';
        var imageNum = 0;
        LBshutterLinks={};
        LBimageArray.empty(); //empty it out...
        LBurlCache.empty();
        LBurlStatus.empty();

        //LBoriginalArray.empty(); //empty it out...

        //LBfirstLoad++;
        
		// loop through all anchor tags
		for (var i=0; i<anchors.length; i++){
			var anchor = anchors[i];
			var relAttribute = String(anchor.getAttribute('rel'));
			stimuli_image_title = "";
            // use the string.match() method to catch 'lightbox' references in the rel attribute
			if (anchor.getAttribute('href') && (relAttribute.toLowerCase().match('lightbox'))){
                //if(LBfirstLoad==1){
                //    LBoriginalArray[anchor.getAttribute('href')]=true;
                //}else{
                //    if(LBoriginalArray[anchor.getAttribute('href')]==true){
                //        continue;  //dont load it again.
                //    }
                //}
 
            
                //LBdebug.echo("href="+anchor.getAttribute('href')+" alt="+anchor.getAttribute('alt')+" title="+anchor.getAttribute('title')+"<br>");
                // check for title-less links, and grab image title if needed
					//var possibleLightboxImageTitles = [ anchor['title'], anchor.childNodes[0]['title'], anchor.childNodes[0]['alt'], anchor.getAttribute('href') , " " ];
					if(stimuli_image_title == "" &&  anchor['title'] != '') {
						stimuli_image_title = anchor['title'] ;
					}
                    if(stimuli_image_title == "" && anchor.childNodes.length!=0 ) {
						stimuli_image_title = anchor.childNodes[0]['title'];
					}
                    if(stimuli_image_title == "" &&  anchor.childNodes.length!=0) {
						stimuli_image_title = anchor.childNodes[0]['alt'];
					}
                    if(stimuli_image_title == "" &&  anchor.getAttribute('href')  != '') {
						stimuli_image_title = anchor.getAttribute('href') ;
					}else{
                        stimuli_image_title =" ";
                    }
            
                stimuli_image_title =" "; //<a href='http://www.homequestgroup.com' target=_blank><font size=-2>Powered By Homequest</font></a>";

				//anchor.onclick = function () {myLightbox.start(this,imageNum); return false;}
				//anchor.onclick="javascript: myLightbox.start(this,"+imageNum+"); return false;";
                eval("anchor.onclick = function () {myLightbox.start(this,"+imageNum+"); return false;}");

                
                LBshutterLinks[imageNum] = {link:anchor.getAttribute('href'),title:stimuli_image_title,isPano:-2}
		        LBimageArray[imageNum] =new Array(LBshutterLinks[imageNum].link, LBshutterLinks[imageNum].title);
                var __src=_LBcheckImgPath+"imgcheck.php?report_type=js&find_pano=1&url="+LBshutterLinks[imageNum].link;

       //???????????????????????????????????????????????????????????????????????    		    
                //LBdebug.echo("examining a["+imageNum+"]["+LBshutterLinks[imageNum].link+"]<br>");
       //???????????????????????????????????????????????????????????????????????
                
                LBshutterLinks[imageNum].isPano=LBxmlhttp.isPano(__src,imageNum);
                lastURL=LBshutterLinks[imageNum].link;
                imageNum++;
			}
		}
		// 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'));
            		
            stimuli_image_title = "";
			// use the string.match() method to catch 'lightbox' references in the rel attribute
			if (area.getAttribute('href') && (relAttribute.toLowerCase().match('lightbox'))){
    			/*
                var possibleLightboxImageTitles = [area.getAttribute('title'), area.childNodes[0]['title'], area.childNodes[0]['alt'], area.getAttribute('href'), " "];
	    		var possible_Int = 0;
		    	while (stimuli_image_title == ("")) {
			    	stimuli_image_title = possibleLightboxImageTitles[possible_Int];
				    possible_Int++;
			    }*/
                	if(stimuli_image_title == "" &&  area.getAttribute('title') != '') {
						stimuli_image_title = area.getAttribute('title');
					}
                    if(stimuli_image_title == "" && area.childNodes.length!=0 ) {
						stimuli_image_title = anchor.childNodes[0]['title'];
					}
                    if(stimuli_image_title == "" &&  area.childNodes.length!=0) {
						stimuli_image_title = area.childNodes[0]['alt'];
					}
                    if(stimuli_image_title == "" &&  area.getAttribute('href')  != '') {
						stimuli_image_title = area.getAttribute('href') ;
					}else{
                        stimuli_image_title =" ";
                    }
                
                    stimuli_image_title =""; //<a href='http://www.homequestgroup.com' target=_blank><font size=-2>Powered By Homequest</font></a>";
                  
				//area.onclick = eval("function () {myLightbox.start(this,"+imageNum+"); return false;}");
                //area.onclick="javascript: myLightbox.start(this,"+imageNum+"); return false;";
                eval("area.onclick = function () {myLightbox.start(this,"+imageNum+"); return false;}");

                
                //function () {myLightbox.start(this,imageNum); return false;}
			    LBshutterLinks[imageNum] = {link:area.getAttribute('href'),title:stimuli_image_title,isPano:-2}
		        LBimageArray[imageNum] =new Array(LBshutterLinks[imageNum].link, LBshutterLinks[imageNum].title);
			
                var __src=_LBcheckImgPath+"imgcheck.php?report_type=js&find_pano=1&url="+LBshutterLinks[imageNum].link;

       //???????????????????????????????????????????????????????????????????????    		    
                //LBdebug.echo("examining A["+imageNum+"]["+LBshutterLinks[imageNum].link+"]<br>");
       //???????????????????????????????????????????????????????????????????????
                
    		    LBshutterLinks[imageNum].isPano=LBxmlhttp.isPano(__src,imageNum);
                lastURL=LBshutterLinks[imageNum].link;
                imageNum++;
			}
		}
	    LBimageArray.removeDuplicates();
	    //imageNum=0; //find the original image num
	    //if(lastURL!=''){
        //    while(LBimageArray[imageNum][0]!=lastURL) { imageNum++; };
	    //    imageNum++;
        //}
	},
//------------------------------------------------------------------------------------
	start: function(imageLink,imageID) {	
//------------------------------------------------------------------------------------
	//	start()
		if(LBshutterLinks[imageID].isPano<0 || LBshutterLinks[imageID].isPano==null){
            if(LBshutterLinks[imageID].isPano < -1){
                window.alert('Bad or missing Image one');
                killLightbox();
            }else{
             //   window.alert('Scanning Images For Image Information - Please wait 1 second');
            }
            return false;   //just ignore clicks if the pano is not scanned yet. Or if it is a bad 404 image
        }
        
        hideSelectBoxes();
		hideFlash();
		// stretch overlay to fill page and fade in
        LBcalls+=1;
       //???????????????????????????????????????????????????????????????????????
        //LBdebug.echo('total Clicks');
        //LBdebug.echo(LBcalls+'<br>');
       //???????????????????????????????????????????????????????????????????????

		var arrayPageSize = getPageSize();
		Element.setWidth('stimuli_overlay', arrayPageSize[0]);
		Element.setHeight('stimuli_overlay', arrayPageSize[1]);
		new Effect.Appear('stimuli_overlay', { duration: LBoverlayDuration, from: 0.0, to: LBoverlayOpacity });

        LBactiveImage = imageID;
		this.resizeWindow();
	if(LBshutterLinks[imageID].isPano)
		jQuery("<div>Click the picture and drag</div>").appendTo('#stimuli_imageDetails');

	},
//------------------------------------------------------------------------------------
	resizeWindow: function() {	//on any changes to window size it will resize the whole display.... and image sizes...
//------------------------------------------------------------------------------------
		if(LBactiveImage>-1){
            var arrayPageSize = getPageSize();  //resize the gray area on any changes....
		    Element.setWidth('stimuli_overlay', arrayPageSize[0]);
    		Element.setHeight('stimuli_overlay', arrayPageSize[1]);
        
            this.changeImage(LBactiveImage ,0);
        }
        return;
    },
//------------------------------------------------------------------------------------
	changeImage: function(imageID,addIndex) {	
//------------------------------------------------------------------------------------
	//	changeImage()
	//	Hide most elements and preload image in preparation for resizing image container.
		LBactiveImage = parseInt(imageID)+parseInt(addIndex);	// update global var
		// hide elements during transition
	 //   LBdebug.echo('changeImage().Start<br>');
       
    	if(LBshutterLinks[LBactiveImage].isPano<0){
            if(addIndex<0){
                if(LBactiveImage < 1){
                    window.alert('Bad or missing Image two');
                    killLightbox();
                    return false;
                }
            }
            if(addIndex==0){
                addIndex=1;
            }
            if(addIndex > 0){
                if(LBactiveImage > (LBimageArray.length - 2)){
			        window.alert('Bad or missing Image three');
                    killLightbox();
                    return false;
                }
            }
            
            x=window.confirm("Bad or missing Image\n load next image?");
            if(x){
                this.changeImage(LBactiveImage,addIndex);        
                return false;   //just ignore clicks if the pano is not scanned yet.
            }else{
                killLightbox();
                return false;   //just ignore clicks if the pano is not scanned yet.
            }
        }

		if(1+LBanimate){ Element.show('stimuli_loading');}

//		Element.hide('stimuli_lightboxImage'); //this is already hidden by panoContainer
		//Element.hide('stimuli_hoverNav');
		//Element.hide('stimuli_prevLink');
		//Element.hide('stimuli_nextLink');
		Element.hide('stimuli_imageDataContainer');
		//Element.hide('stimuli_numberDisplay');		
        //Element.hide('stimuli_panoContainer');		
	    //Element.hide('stimuli_imageContainer');		
	    //Element.hide('stimuli_outerImageContainer');		
	    
        // once image is preloaded, resize image container
		var scans=0;
       //???????????????????????????????????????????????????????????????????????
	//	LBdebug.echo('LBshutterLinks[LBactiveImage].link='+LBshutterLinks[LBactiveImage].link+'<br>');
    	//LBdebug.echo('LBshutterLinks[LBactiveImage].title='+LBshutterLinks[LBactiveImage].title+'<br>');
    	//LBdebug.echo('[LBactiveImage]='+LBactiveImage+'<br>');
        //LBdebug.echo('LBshutterLinks[LBactiveImage].isPano='+LBshutterLinks[LBactiveImage].isPano+'<br>');
       //???????????????????????????????????????????????????????????????????????
		
        
        //while(LBshutterLinks[LBactiveImage].isPano<0 && scans<1000){
		//    scans++;
        //    LBdebug.echo(scans);
    	//    if (navigator.appVersion.indexOf("MSIE")!=-1){ pause(250); } else { pause(100);} 
	    //}
        

        if(LBflashLoaded){
  		    Element.hide('stimuli_lightboxImage'); //this is already hidden by panoContainer
            swfobject.removeSWF("stimuli_panoContainer");
            LBflashLoaded=false;
            LBobjPanoContainer= document.createElement("div");                
		    LBobjPanoContainer.setAttribute('id','stimuli_panoContainer');                  
//		    Element.setZpos('stimuli_panoContainer','10');
		    LBobjImageContainer.appendChild(LBobjPanoContainer);
        }
	    if(!LBshutterLinks[LBactiveImage].isPano){
            if(typeof imgPreloader == 'undefined'){
		        imgPreloader = new Image();
		    }else{
                delete imgPreloader;
                imgPreloader = new Image();
		    }
    	    imgPreloader.onload=function(){
                imgPreloader.onload=function(){};
                Element.setWidth('stimuli_lightboxImage', imgPreloader.width);
                Element.setHeight('stimuli_lightboxImage', imgPreloader.height);
              
                Element.setWidth('stimuli_imageContainer', imgPreloader.width);
                Element.setHeight('stimuli_imageContainer', imgPreloader.height);
                Element.setWidth('stimuli_outerImageContainer', imgPreloader.width+20); //add border size
                Element.setHeight('stimuli_outerImageContainer', imgPreloader.height+20); 
                
                Element.setSrc('stimuli_lightboxImage', LBimageArray[LBactiveImage][0]);
                if (navigator.appVersion.indexOf("MSIE")!=-1){ pause(50); } else { pause(25);}  //slight delay to allow switching of image

                myLightbox.repositionImageContainer(imgPreloader.width,imgPreloader.height);
                myLightbox.resizeImageContainer(imgPreloader.width, imgPreloader.height);
              	
                //Element.show('stimuli_lightboxImage');
                //Element.show('stimuli_imageContainer');
            }
            
            Element.setSrc('stimuli_lightboxImage', LBimageArray[LBactiveImage][0]);
            Element.hide('stimuli_imageContainer');
            Element.hide('stimuli_lightboxImage');
            imgPreloader.src = LBimageArray[LBactiveImage][0]; //force a reload of the image
            //Element.setSrc('stimuli_lightboxImage', LBimageArray[LBactiveImage][0]);
            //Element.setSrc('stimuli_lightboxImage', 'Themes/Black/images/loading.gif');
              
		}else{
            Element.hide('stimuli_imageContainer');
            Element.hide('stimuli_lightboxImage');
            var aPageSize=getPageSize();
		    var cPageWidth=0,cPageHeight=1,cWinWidth=2,cWinHeight=3;
            if(LBobjMap!=null){
                LBpanoWidth=parseInt(Element.getWidth(LBobjMap)*.90);
                LBpanoHeight=parseInt(LBpanoWidth/1.6666);  //perfect chi ratio
                if(LBpanoHeight+70 > parseInt(Element.getHeight(LBobjMap)*.90 )){  //need operate on the map height...
                    //too tall so resize to the height of the display area.
                    LBpanoHeight=parseInt(Element.getHeight(LBobjMap)*.90)-70;
                    LBpanoWidth=parseInt(LBpanoHeight*1.6666);
                    //..but what if too wide as well? .. I dont think that is possible really.. th
                }
            }else{
                LBpanoWidth=parseInt(Element.getWidth(LBobjBody)*.90);
                LBpanoHeight=parseInt(LBpanoWidth/1.6666);
                if(LBpanoHeight+70 > parseInt(aPageSize[cWinHeight]*.90)){
                    //too tall so resize to the height of the display area.
                    LBpanoHeight=parseInt(aPageSize[cWinHeight]*.90)-70;
                    LBpanoWidth=parseInt(LBpanoHeight*1.6666);
                    //..but what if too wide as well? .. I dont think that is possible really.. th
                }
            }
            

            Element.setWidth('stimuli_panoContainer', LBpanoWidth);
            Element.setHeight('stimuli_panoContainer', LBpanoHeight);
                Element.setWidth('stimuli_imageContainer', LBpanoWidth);
                Element.setHeight('stimuli_imageContainer', LBpanoHeight);
                Element.setWidth('stimuli_outerImageContainer', LBpanoWidth+20); //add border size
                Element.setHeight('stimuli_outerImageContainer', LBpanoHeight+20); 
            
            myLightbox.repositionImageContainer(LBpanoWidth,LBpanoHeight);
            myLightbox.resizeImageContainer(LBpanoWidth,LBpanoHeight);              
            Element.show('stimuli_panoContainer');

		}
	},
//------------------------------------------------------------------------------------
    repositionImageContainer : function (xOffset,yOffset){
//------------------------------------------------------------------------------------
       //???????????????????????????????????????????????????????????????????????
        //LBdebug.echo('imageNum='+imageNum+' height of Container='+Element.getHeight('stimuli_outerImageContainer')/2+'<br>')
       //???????????????????????????????????????????????????????????????????????

		// calculate top and left offset for the lightbox 
    		var arrayPageScroll = getPageScroll();
	    	var lightboxTop = parseInt (arrayPageScroll[1] + (arrayPageSize[3] / 2)-(yOffset/2) )-40;
		    var lightboxLeft =  arrayPageScroll[0]; //parseInt(arrayPageSize[2]/2)-parseInt(xOffset/2)-100;
//             arrayPageScroll[0];
		    Element.setTop('stimuli_lightbox', lightboxTop);
		    Element.setLeft('stimuli_lightbox', lightboxLeft);
            Element.show('stimuli_lightbox');
    
    },
	//	resizeImageContainer()
//------------------------------------------------------------------------------------
	resizeImageContainer: function( imgWidth, imgHeight) {
//------------------------------------------------------------------------------------
		// get current width and height
       //???????????????????????????????????????????????????????????????????????
	//	LBdebug.echo('Does it even get here?'+imgWidth+' '+imgHeight+'<br>');
       //???????????????????????????????????????????????????????????????????????

		this.widthCurrent = Element.getWidth('stimuli_outerImageContainer');
		this.heightCurrent = Element.getHeight('stimuli_outerImageContainer');
		// get new width and height
		var widthNew = (imgWidth  + (LBborderSize * 2));
		var heightNew = (imgHeight  + (LBborderSize * 2));
       //???????????????????????????????????????????????????????????????????????
	//	LBdebug.echo('widthNew='+widthNew+' heightNew='+heightNew+'<br>');
       //???????????????????????????????????????????????????????????????????????

		// scalars based on change from old to new
		this.xScale = ( widthNew / this.widthCurrent) * 100;
		this.yScale = ( heightNew / this.heightCurrent) * 100;
		// calculate size difference between new and old image, and resize if necessary
		wDiff = this.widthCurrent - widthNew;
		hDiff = this.heightCurrent - heightNew;
		if(!( hDiff == 0)){ new Effect.Scale('stimuli_outerImageContainer', this.yScale, {scaleX: false, duration: LBresizeDuration, queue: 'front'}); }
		if(!( wDiff == 0)){ new Effect.Scale('stimuli_outerImageContainer', this.xScale, {scaleY: false, delay: LBresizeDuration, duration: LBresizeDuration}); }
		// if new and old image are same size and no scaling transition is necessary, 
		// do a quick pause to prevent image flicker.
		if((hDiff == 0) && (wDiff == 0)){
			if (navigator.appVersion.indexOf("MSIE")!=-1){ pause(25); } else { pause(10);} 
		}
       //???????????????????????????????????????????????????????????????????????
        //LBdebug.echo('imgHeight='+imgHeight+' imgWidth='+imgWidth+'<br>');
       //???????????????????????????????????????????????????????????????????????

		//Element.setHeight('stimuli_prevLink', 40);
		//Element.setHeight('stimuli_nextLink', 40);
		Element.setWidth( 'stimuli_imageDataContainer', widthNew);
		
        myLightbox.showImage();

	},
//------------------------------------------------------------------------------------
	showImage: function(){
//------------------------------------------------------------------------------------
	//	showImage()
	//	Display image and begin preloading neighbors.
		Element.hide('stimuli_loading');
        
        //var scans=0;
        //while(LBshutterLinks[LBactiveImage].isPano<0 && scans<1000){
		//    scans++;
    	//    if (navigator.appVersion.indexOf("MSIE")!=-1){ pause(250); } else { pause(100);} 
	    //}
        if(!LBshutterLinks[LBactiveImage].isPano){
    		   new Effect.Appear('stimuli_lightboxImage', { duration: LBresizeDuration, queue: 'end', afterFinish: function(){	Element.show('stimuli_imageContainer'); Element.show('stimuli_lightboxImage'); } });
               myLightbox.updateDetails();
		}else{
            Element.show('stimuli_panoContainer');
                var flashvars = {};
                var params = {};
                var attributes = {};
                flashvars.allowfullscreen=true;
                params.allowfullscreen=true;
                attributes.allowfullscreen=true;
                swfobject.embedSWF("/wp/wp-content/plugins/lightbox-2/krpano.swf?pano=/wp/wp-content/plugins/lightbox-2/settings.xml&sphere="+LBshutterLinks[LBactiveImage].link+"&allowfullscreen=true",
                    "stimuli_panoContainer", LBpanoWidth, LBpanoHeight, "9.0.0", "/wp/wp-content/plugins/lightbox-2/expressinstall.swf",flashvars,params,attributes);
                myLightbox.updateDetails();
                LBflashLoaded=true;
                Element.show('stimuli_imageContainer');
		}
        this.preloadNeighborImages();
	},
//------------------------------------------------------------------------------------
	updateDetails: function() {
//------------------------------------------------------------------------------------
	//	updateDetails()
	//	Display caption, image number, and bottom nav.
		// if caption is not null
       // LBdebug.echo("exec updateDetails<br>");

//		if(LBimageArray[LBactiveImage][1]){
//			    Element.show('stimuli_caption');
//              Element.setInnerHTML( 'stimuli_caption', LBimageArray[LBactiveImage][1]);
//              LBdebug.echo("imageNo: "+LBactiveImage+" is active<br>");
//
//		}
		// if image is part of set display 'Image x of x' 
		if(LBimageArray.length > 1){
       //     LBdebug.echo("LBimageArray.length="+LBimageArray.length+"<br>");

            Element.show('stimuli_numberDisplay');
	
            if(LBactiveImage!= 0){
                if(LBactiveImage != (LBimageArray.length - 1)){
                        //middle image
                        var disp="<table width='100%'><tr>\
                         <td align='left' width='45'><a href='#' id='stimuli_prevLink'><img src='/wp/wp-content/plugins/lightbox-2/Themes/Black/images/prev.gif' border='0'></a></td>\
                         <td align='center'><center>Image " + parseInt(LBactiveImage + 1) + " of " + LBimageArray.length + "</center></td>\
                         <td align='right' width='45'><a href='#' id='stimuli_nextLink'><img src='/wp/wp-content/plugins/lightbox-2/Themes/Black/images/next.gif' border='0'></a></td>\
                        </tr></table>";
    		            Element.setInnerHTML( 'stimuli_numberDisplay', disp);
	                    
                }else{  //last image
                        var disp="<table width=100%><tr>\
                         <td align='left' width='45'><a href='#' id='stimuli_prevLink'><img src='/wp/wp-content/plugins/lightbox-2/Themes/Black/images/prev.gif' border='0'></a></td>\
                         <td align='center'><center>Image " + parseInt(LBactiveImage + 1) + " of " + LBimageArray.length + "</center></td>\
                         <td align='right' width='45'>&nbsp;</td>\
                        </tr></table>";
    		            Element.setInnerHTML( 'stimuli_numberDisplay', disp);
                }
            }else{      //first image)
                        var disp="<table width=100%><tr>\
                         <td align='left' width='45'>&nbsp;</td>\
                         <td align='center'><center>Image " + parseInt(LBactiveImage + 1) + " of " + LBimageArray.length + "</center></td>\
                         <td align='right' width='45'><a href='#' id='stimuli_nextLink'><img src='/wp/wp-content/plugins/lightbox-2/Themes/Black/images/next.gif' border='0'></a></td>\
                        </tr></table>";
    		            Element.setInnerHTML( 'stimuli_numberDisplay', disp);
            }

    
    
    	}else{
        //    LBdebug.echo("LBimageArray has no length<br>");

        }

        Element.show('stimuli_imageDataContainer');
        var arrayPageSize = getPageSize();
		Element.setHeight('stimuli_overlay', arrayPageSize[1]);
		myLightbox.updateNav();

        //lot of pissing around... lets just load the damn thing hey???
		/*new Effect.Parallel(
			[ new Effect.SlideDown( 'stimuli_imageDataContainer', { sync: true, duration: LBresizeDuration, from: 0.0, to: 1.0 }), 
			  new Effect.Appear('stimuli_imageDataContainer', { sync: true, duration: LBresizeDuration }) ], 
			{ duration: LBresizeDuration, afterFinish: function() {
				// update overlay size and update nav
				var arrayPageSize = getPageSize();
				Element.setHeight('stimuli_overlay', arrayPageSize[1]);
				myLightbox.updateNav();
				}
			} 
		);*/
	},
//------------------------------------------------------------------------------------
	updateNav: function() {
//------------------------------------------------------------------------------------
	//	updateNav()
	//	Display appropriate previous and next hover navigation.
		//Element.show('stimuli_hoverNav');
		// if not first image in set, display prev image button
		if(LBactiveImage != 0){
			//Element.show('stimuli_prevLink');
			document.getElementById('stimuli_prevLink').onclick = function() {
				myLightbox.changeImage(LBactiveImage, - 1); return false;
			}
		}
		// if not last image in set, display next image button
		if(LBactiveImage != (LBimageArray.length - 1)){
			//Element.show('stimuli_nextLink');
			document.getElementById('stimuli_nextLink').onclick = function() {
				myLightbox.changeImage(LBactiveImage, + 1); return false;
			}
		}
		this.enableKeyboardNav();
	},
//------------------------------------------------------------------------------------
	enableKeyboardNav: function() {
//------------------------------------------------------------------------------------
		document.onkeydown = this.keyboardAction; 
	},
//------------------------------------------------------------------------------------
	disableKeyboardNav: function() {
//------------------------------------------------------------------------------------
		document.onkeydown = '';
	},
//------------------------------------------------------------------------------------
	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
			if(LBactiveImage != 0){
				myLightbox.disableKeyboardNav();
				myLightbox.changeImage(LBactiveImage, - 1);
			}
		} else if((key == 'n') || (keycode == 39)){	// display next image
			if(LBactiveImage != (LBimageArray.length - 1)){
				myLightbox.disableKeyboardNav();
				myLightbox.changeImage(LBactiveImage, + 1);
			}
		}
	},
//------------------------------------------------------------------------------------
	OLD_preloadNeighborImages: function(){
//------------------------------------------------------------------------------------
	//	preloadNeighborImages()
	//	Preload previous and next images.
	    if((LBimageArray.length - 1) > LBactiveImage){
            if(!LBshutterLinks[LBactiveImage+1].isPano){
    	        preloadNextImage = new Image();
	       		preloadNextImage.src = LBimageArray[LBactiveImage + 1][0];
		    }
	    }
		if(LBactiveImage > 0){
            if(!LBshutterLinks[LBactiveImage-1].isPano){
                preloadPrevImage = new Image();
                preloadPrevImage.src = LBimageArray[LBactiveImage - 1][0];
            }  
        }
	},
    //------------------------------------------------------------------------------------
	preloadNeighborImages: function(){
//------------------------------------------------------------------------------------
	//	preloadNeighborImages()
	//	Preload previous and next images.
	    if((LBimageArray.length - 1) > LBactiveImage){
            if(!LBshutterLinks[LBactiveImage+1].isPano){
    	        if(typeof preloadNextImage[LBactiveImage + 1] == 'undefined'){
                    preloadNextImage[LBactiveImage + 1] = new Image();
	       		}
                if(preloadNextImage[LBactiveImage + 1].src==''){
                    preloadNextImage[LBactiveImage + 1].src = LBimageArray[LBactiveImage + 1][0];
		        }
            }
	    }
		if(LBactiveImage > 0){
            if(!LBshutterLinks[LBactiveImage-1].isPano){
                if(typeof preloadPrevImage[LBactiveImage - 1] == 'undefined'){
                    preloadPrevImage[LBactiveImage - 1] = new Image();
	       		}
                if(preloadPrevImage[LBactiveImage - 1].src==''){
                    preloadPrevImage[LBactiveImage - 1].src = LBimageArray[LBactiveImage - 1][0];
		        }
            }  
        }
	},
    
	//	end()
//------------------------------------------------------------------------------------
	end: function() {
//------------------------------------------------------------------------------------
        LBactiveImage=-1;       //disable page resizing.
        if(LBflashLoaded){
            swfobject.removeSWF("stimuli_panoContainer");
            LBflashLoaded=false;
            LBobjPanoContainer= document.createElement("div");                
		    LBobjPanoContainer.setAttribute('id','stimuli_panoContainer');                  
//		    Element.setZpos('stimuli_panoContainer','10');
		    LBobjImageContainer.appendChild(LBobjPanoContainer);

        }
		this.disableKeyboardNav();
		Element.hide('stimuli_lightbox');
		new Effect.Fade('stimuli_overlay', { duration: LBoverlayDuration});
		showSelectBoxes();
		showFlash();
	}
}
//####################################################################################
//#### END Lightbox Class ############################################################
//####################################################################################



//### Utilities ######################################################################
// -----------------------------------------------------------------------------------
// getPageScroll()
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;
}

// -----------------------------------------------------------------------------------
// getDivDims()
function getDivDims(divObj){
//------------------------------------------------------------------------------------
   divDims = {l:parseInt(divObj.offsetLeft),t:parseInt(divObj.offsetTop),w:parseInt(divObj.width),h:parseInt(divObj.height)};
   return divDims;
}

// -----------------------------------------------------------------------------------
function killLightbox(){
// -----------------------------------------------------------------------------------
    if(LBflashLoaded){
        swfobject.removeSWF("stimuli_panoContainer");
        LBflashLoaded=false;
        LBobjPanoContainer= document.createElement("div");                
		LBobjPanoContainer.setAttribute('id','stimuli_panoContainer');        
		LBobjImageContainer.appendChild(LBobjPanoContainer);
    }
    if(typeof myLightbox != 'undefined' ){
        myLightbox.end();
    }
}

// -----------------------------------------------------------------------------------
// getPageSize()
function getPageSize(){
//------------------------------------------------------------------------------------
    
    if(LBobjMap){
	    windowWidth=pageWidth=Element.getWidth(LBobjMap);
        windowHeight=pageHeight=Element.getHeight(LBobjMap);
        LBdebug.echo(_LBtargetMapDiv+": pagesize=(pageWidth,pageHeight,windowWidth,windowHeight)"+pageWidth+','+pageHeight+','+windowWidth+','+windowHeight+'<br>');
	    arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight) 
	    return arrayPageSize;
    }

	var xScroll, yScroll;
	if (window.innerHeight && window.scrollMaxY) { //FF
        LBdebug.echo('uses innerWidth<br>');
		xScroll = window.innerWidth + window.scrollMaxX;
        if (navigator.userAgent.indexOf("Firefox")!=-1){ //FF for sure
        xScroll -= getScrollerWidth();
        }
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (parseInt(document.body.scrollWidth) > parseInt(document.body.offsetWidth)){ // all but Explorer Mac
        LBdebug.echo('uses scrollWidth<br>');
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		LBdebug.echo('uses offsetWidth<br>');
        xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}
	var windowWidth, windowHeight;
	if (self.innerHeight) {	// all except Explorer
		if(document.documentElement.clientWidth){
		    LBdebug.echo('1. FF<br>');
            windowWidth = document.documentElement.clientWidth; 
            if (navigator.userAgent.indexOf("Firefox")!=-1){
                windowWidth = document.documentElement.clientWidth-getScrollerWidth(); //screw me.. what a joke that you need this function!
            }
                
		} else {
            LBdebug.echo('2. other browsers<br>');
			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;
	}

       //???????????????????????????????????????????????????????????????????????
    LBdebug.echo("Full page width="+document.body.offsetWidth+' '+document.body.scrollWidth+"<br>");
	LBdebug.echo("pagesize=(pageWidth,pageHeight,windowWidth,windowHeight)"+pageWidth+','+pageHeight+','+windowWidth+','+windowHeight+'<br>');
       //???????????????????????????????????????????????????????????????????????
	arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight) 
	return arrayPageSize;
}

// -----------------------------------------------------------------------------------
// getKey(key)
function getKey(e){
//------------------------------------------------------------------------------------
	if (e == null) { // ie
		keycode = event.keyCode;
	} else { // mozilla
		keycode = e.which;
	}
	key = String.fromCharCode(keycode).toLowerCase();
	if(key == 'x'){
	}
}
// -----------------------------------------------------------------------------------
// listenKey()
function listenKey () {	document.onkeypress = getKey; }
//------------------------------------------------------------------------------------
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";
	}
}
//------------------------------------------------------------------------------------
function showFlash(){
//------------------------------------------------------------------------------------
	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(){
//------------------------------------------------------------------------------------
	var flashObjects = document.getElementsByTagName("object");
	for (i = 0; i < flashObjects.length; i++) {
		flashObjects[i].style.visibility = "hidden";
	}
	var flashEmbeds = document.getElementsByTagName("embed");
	for (i = 0; i < flashEmbeds.length; i++) {
		flashEmbeds[i].style.visibility = "hidden";
	}
}
//------------------------------------------------------------------------------------
function pause(ms){
//------------------------------------------------------------------------------------
	var date = new Date();
	curDate = null;
	do{var curDate = new Date();}
	while( curDate - date < ms);
}

//------------------------------------------------------------------------------------
function getMicroTime(){
//------------------------------------------------------------------------------------
	var now = new Date().getTime() / 1000;
    return now;
}

var lbObj;
//------------------------------------------------------------------------------------
function initLightbox() { myLightbox = new _LBLightbox(); lbObj = myLightbox; }
//------------------------------------------------------------------------------------
function doResizeWindow() { 
    //LBdebug.echo ("LBActiveImage="+LBactiveImage+" Resize Event B Triggered<br>");
    if(LBactiveImage >-1){ myLightbox.resizeWindow(); } 
}
//------------------------------------------------------------------------------------
function getScrollerWidth() {
//------------------------------------------------------------------------------------
/* TH- lifted this code off the web.. this is bloody ridiculous that you need all this crap to get the scroll bar width.. */
    var scr = null;
    var inn = null;
    var wNoScroll = 0;
    var wScroll = 0;
 
    // Outer scrolling div
    scr = document.createElement('div');
    scr.style.position = 'absolute';
    scr.style.top = '-1000px';
    scr.style.left = '-1000px';
    scr.style.width = '100px';
    scr.style.height = '50px';
    // Start with no scrollbar
    scr.style.overflow = 'hidden';
 
    // Inner content div
    inn = document.createElement('div');
    inn.style.width = '100%';
    inn.style.height = '200px';
 
    // Put the inner div in the scrolling div
    scr.appendChild(inn);
    // Append the scrolling div to the doc
 
    document.body.appendChild(scr);
 
    // Width of the inner div sans scrollbar
    wNoScroll = inn.offsetWidth;
    // Add the scrollbar
    scr.style.overflow = 'auto';
    // Width of the inner div width scrollbar
    wScroll = inn.offsetWidth;
 
    // Remove the scrolling div from the doc
    document.body.removeChild(
    document.body.lastChild);
 
    // Pixel width of the scroller
    return (wNoScroll - wScroll);
}



//### End Utilities ##################################################################
//####################################################################################

Event.observe(window, 'load', initLightbox, false);  
//Event.observe(body, 'onresize', doResizeWindow, false);

//HACK: Add an on resize event so that dimensions can change on a resize of the window
if (typeof window.addEventListener != 'undefined') {
    window.addEventListener("resize", doResizeWindow, false);
}else if (typeof document.addEventListener != 'undefined'){
    document.addEventListener("resize", doResizeWindow, false);
}else if (typeof window.attachEvent != 'undefined'){
    window.attachEvent("onresize", doResizeWindow);
}else{
    window.alert('Failed to attach an Event Listener\n\n Please Report');
}

//initLightbox()

if(_LBdebugger){
    document.write("<div id='debug_window' style='height:100px; overflow:auto; background-color: #FFFFFF; position: absolute; left: 0px; top: 0px;'></div>");
}
