// -----------------------------------------------------------------------------------
//
//    Lightbox Gallery v2.1
//    by Brandon Kieft
//    9/26/07
//    
//    Based on Lightbox v2.03.3
//    by Lokesh Dhakar - http://www.huddletogether.com
//
//    For more information on Lightbox, visit:
//    http://huddletogether.com/projects/lightbox2/
//
//    Licensed under the Creative Commons Attribution 2.5 License - http://creativecommons.org/licenses/by/2.5/
//    
//    Credit also due to those who have helped, inspired, and made their code available to the public.
//    Including: Scott Upton(uptonic.com), Peter-Paul Koch(quirksmode.org), Thomas Fuchs(mir.aculo.us), and others.
//
//
// -----------------------------------------------------------------------------------
/*

    Table of Contents
    -----------------
    Configuration
    Global Variables

    Extending Built-in Objects    
    - Object.extend(Element)
    - Array.prototype.removeDuplicates()
    - Array.prototype.empty()

    Lightbox Class Declaration
    - initialize()
    - loadXML()
    - updateImageList()
    - createImageArray()
    - start()
    - changeImage()
    - resizeImageContainer()
    - showImage()
    - updateDetails()
    - updateNav()
    - header()
    - unselectedImage()
    - selectedImage()
    - enableKeyboardNav()
    - disableKeyboardNav()
    - keyboardNavAction()
    - preloadNeighborImages()
    - end()
    
    Miscellaneous Functions
    - getPageScroll()
    - getPageSize()
    - getKey()
    - listenKey()
    - showSelectBoxes()
    - hideSelectBoxes()
    - showFlash()
    - hideFlash()
    - hideiFrame()
    - showiFrame()
    - initLightbox()
    
    Function Calls
    - addLoadEvent(initLightbox)
    
*/
// -----------------------------------------------------------------------------------

//    Configuration
var globalImagePath = "Themes/default/images/";    //Set path to images folder - If changing this make sure to also change lines 900 and 909 and the links in the css file.
var fileLoadingImage = globalImagePath+"loading.gif";        
var fileBottomNavCloseImage = globalImagePath+"closelabel.gif";

var overlayOpacity = 0.8;    // 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

var headerDuration = 0.8;    // Controls the speed of the header animations (1=slowest and 10=fastest)

var userXML = false;            // Controls whether the XML is used or not

var headerStartDown = true;        // Controls if the header automatically comes down or not

var minWidth = 0;            // Controls the minimum width of the picture in px

var showHeader = true;        // Controls whether the header is shown or not
// -----------------------------------------------------------------------------------

//    Global Variables
var imageArray = new Array;
var headerImageContainerArray = new Array;
var lightboxArray = new Array;
var header = false;
var start = true;
var currentFullsize=false;
var otherContent=false;
var lightboxNum=0;
var totalLightbox=0;
var initialPageWidth, initialPageHeight, headerIndexCounter, activeImage, drag, x, y, initialScroll;

if(animate == true){
    overlayDuration = 0.2;    // 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;
}

// Code for Microsoft Internet Explorer
if (window.ActiveXObject){IE=true;}
// Code for Mozilla, Firefox, Opera, etc.
else if (document.implementation && document.implementation.createDocument){IE=false;}
//Code if the browser does not support javascript
else {alert('Your browser cannot handle this script');}

// -----------------------------------------------------------------------------------

//    Additional methods for Element added by SU, Couloir
//    - further additions by Lokesh Dhakar (huddletogether.com)
//  - further additions by Brandon
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;
    },
    setBackgroundImage: function(element,backgroundImage) {
        element = $(element);
        element.style.backgroundImage = backgroundImage;
    },
    setPosition: function(element, pos){
        element = $(element);
        element.style.position = pos;
    }
});

// -----------------------------------------------------------------------------------

//    Extending built-in Array object
//    - array.removeDuplicates()
//    - array.empty()
Array.prototype.removeDuplicates = function () {
    for(i = 0; i < this.length; i++){
        for(j = this.length-1; j>i; j--){        
            if(this[i][0] == this[j][0]){
                this.splice(j,1);
            }
        }
    }
}

// -----------------------------------------------------------------------------------

Array.prototype.empty = function () {
    for(i = 0; i <= this.length; i++){
        this.shift();
    }
}

// -----------------------------------------------------------------------------------

//    Lightbox Class Declaration
//    - initialize()
//  - loadXML()
//  - updateImageList()
//  - createImageArray()
//    - start()
//    - changeImage()
//    - resizeImageContainer()
//    - showImage()
//    - updateDetails()
//    - updateNav()
//  - header()
//  - unselectedImage()
//  - selectedImage()
//    - enableKeyboardNav()
//    - disableKeyboardNav()
//    - keyboardNavAction()
//    - preloadNeighborImages()
//    - end()

//    Structuring of code inspired by Scott Upton (http://www.uptonic.com/)

var Lightbox = Class.create();

Lightbox.prototype = {

    // initialize()
    // Constructor runs on completion of the DOM loading. Loops through anchor tags looking for 
    // 'lightbox' references and applies onclick events to appropriate links. The 2nd section of
    // the function inserts html at the bottom of the page which is used to display the shadow 
    // overlay and the image container.
    //
    initialize: function() {
        this.updateImageList();

        objBody = document.getElementsByTagName("body").item(0);
        /*
        var objResizeBar = document.createElement("div");
        objResizeBar.setAttribute('id', 'resizeBar');
        objBody.appendChild(objResizeBar);
        
        var objResizeHandle = document.createElement("div");
        objResizeHandle.setAttribute('id', 'resizeHandle');
        objResizeBar.appendChild(objResizeHandle);
        new Control.Slider('resizeHandle','resizeBar', {range:$R(0,100), onSlide:function(v){$('innerLightbox1').style.width=(v*10)+'px';}});
        */
        var objOverlay = document.createElement("div");
        objOverlay.setAttribute('id','overlay');
        objOverlay.style.display = 'none';
        objOverlay.onclick = function() { myLightbox.end(-1); }
        objBody.appendChild(objOverlay);
        
        var objHeaderContainer = document.createElement("div");
        objHeaderContainer.setAttribute('id','headerContainer');
        objHeaderContainer.style.display = 'none';
        objHeaderContainer.onclick = function(e) {    // close Lightbox if user clicks shadow overlay
            if (!e) var e = window.event;
            var clickObj = Event.element(e).id;
            if ( clickObj == 'headerContainer') {
                myLightbox.end();
            }
        };
        objBody.appendChild(objHeaderContainer);
        
        var objHeader = document.createElement("div");
        objHeader.setAttribute('id','header');
        objHeader.onclick = function(e) {    // close Lightbox if user clicks shadow overlay
            if (!e) var e = window.event;
            var clickObj = Event.element(e).id;
            if ( clickObj == 'header') {
                myLightbox.end(-1);
            }
        };

        objHeaderContainer.appendChild(objHeader);
        
        objHeaderBG = document.createElement("div");
        objHeaderBG.setAttribute('id','headerBG');
        objHeaderBG.style.display = 'none';
        objHeader.appendChild(objHeaderBG);
                
        var objHeaderBar = document.createElement("div");
        objHeaderBar.setAttribute('id','headerBar');
        objHeaderBar.onclick = function() {myLightbox.header();};
        objHeader.appendChild(objHeaderBar);
        
        var objHeaderBarImage = document.createElement("img");
        objHeaderBarImage.setAttribute('id','headerBarImage');
        objHeaderBarImage.setAttribute('src',globalImagePath+'HeaderBar.gif');
        objHeaderBar.appendChild(objHeaderBarImage);
        
        var objHeaderBarLeft = document.createElement("img");
        objHeaderBarLeft.setAttribute('id','headerBarLeft');
        objHeaderBarLeft.setAttribute('src',globalImagePath+'HeaderBarLeft.gif');
        objHeaderBar.appendChild(objHeaderBarLeft);
        
        var objHeaderBarRight = document.createElement("img");
        objHeaderBarRight.setAttribute('id','headerBarRight');
        objHeaderBarRight.setAttribute('src',globalImagePath+'HeaderBarRight.gif');
        objHeaderBar.appendChild(objHeaderBarRight);
        
        var objHeaderBarArrow = document.createElement("div");
        objHeaderBarArrow.setAttribute('id','headerBarArrow');
        objHeaderBar.appendChild(objHeaderBarArrow);
        
        this.newLightbox();
    },
    
    newLightbox:  function(newImage, positionX, positionY, z){
        lightboxNum++;
        totalLightbox++;
        if(!positionX) positionX=0;
        if(!positionY) positionY=0;
        x = positionX;
        y = positionY;
        
        if(lightboxNum==1){
            var objLightbox = document.createElement("div");
            objLightbox.setAttribute('id','lightbox'+lightboxNum);
            if(lightboxNum==1){objLightbox.style.display = 'none';};
            if(lightboxNum>1)objLightbox.style.width= 'auto';
            objLightbox.setAttribute('class','lightbox');
            objLightbox.onclick = function(e) {    // close Lightbox if user clicks shadow overlay
                if (!e) var e = window.event;
                var clickObj = Event.element(e).id;
                if ( clickObj.slice(0,8) == 'lightbox' && clickObj.length==9) {
                    myLightbox.end(-1);
                };
            };
            objBody.appendChild(objLightbox);
        }
        
        var objInnerLightbox = document.createElement("div");
        objInnerLightbox.setAttribute('id','innerLightbox'+lightboxNum);
        objInnerLightbox.className = 'innerLightbox';
        objInnerLightbox.style.left= positionX +'px';
        objInnerLightbox.style.top = positionY+ 'px';
        if(z)objInnerLightbox.style.zIndex = z;
        if(lightboxNum==1)objInnerLightbox.style.position = 'relative';
        document.getElementById('lightbox1').appendChild(objInnerLightbox);
        drag = new Draggable('innerLightbox'+lightboxNum);
        if(lightboxNum != 1){Element.hide('hoverNav1');drag.draw([positionX, positionY], true, 125, 125, lightboxTop);};
        
        var objOuterImageContainer = document.createElement("div");
        objOuterImageContainer.setAttribute('id','outerImageContainer'+lightboxNum);
        objOuterImageContainer.className = 'outerImageContainer';
        objInnerLightbox.appendChild(objOuterImageContainer);

        // 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(animate){
            Element.setWidth('outerImageContainer'+lightboxNum, 250);
            Element.setHeight('outerImageContainer'+lightboxNum, 250);            
        } else {
            Element.setWidth('outerImageContainer'+lightboxNum, 1);
            Element.setHeight('outerImageContainer'+lightboxNum, 1);            
        }
        
        var objImageContainer = document.createElement("div");
        objImageContainer.setAttribute('id','imageContainer'+lightboxNum);
        objImageContainer.className = 'imageContainer';
        objOuterImageContainer.appendChild(objImageContainer);
        
        var objLightboxImage = document.createElement("img");
        objLightboxImage.setAttribute('id','lightboxImage'+lightboxNum);
        objLightboxImage.className = 'lightboxImage';
        objImageContainer.appendChild(objLightboxImage);
    
        var objHoverNav = document.createElement("div");
        objHoverNav.setAttribute('id','hoverNav'+lightboxNum);
        objHoverNav.className = 'hoverNav';
        objOuterImageContainer.appendChild(objHoverNav);
    
        var objPrevLink = document.createElement("a");
        objPrevLink.setAttribute('id','prevLink'+lightboxNum);
        objPrevLink.setAttribute('href','#');
        objPrevLink.className = 'prevLink';
        objHoverNav.appendChild(objPrevLink);
        
        var objNextLink = document.createElement("a");
        objNextLink.setAttribute('id','nextLink'+lightboxNum);
        objNextLink.setAttribute('href','#');
        objNextLink.className = 'nextLink';
        objHoverNav.appendChild(objNextLink);
    
        var objLoading = document.createElement("div");
        objLoading.setAttribute('id','loading'+lightboxNum);
        objLoading.className = 'loading';
        objImageContainer.appendChild(objLoading);
    
        var objLoadingLink = document.createElement("a");
        objLoadingLink.setAttribute('id','loadingLink'+lightboxNum);
        objLoadingLink.className = 'loadingLink';
        objLoadingLink.setAttribute('href','#');
        objLoadingLink.onclick = function() { myLightbox.end(); return false; }
        objLoading.appendChild(objLoadingLink);
    
        var objLoadingImage = document.createElement("img");
        objLoadingImage.setAttribute('src', fileLoadingImage);
        objLoadingLink.appendChild(objLoadingImage);

        var objImageDataContainer = document.createElement("div");
        objImageDataContainer.setAttribute('id','imageDataContainer'+lightboxNum);
        objImageDataContainer.className = 'imageDataContainer';
        objInnerLightbox.appendChild(objImageDataContainer);

        var objImageData = document.createElement("div");
        objImageData.setAttribute('id','imageData'+lightboxNum);
        objImageData.className = 'imageData';
        objImageDataContainer.appendChild(objImageData);
    
        var objImageDetails = document.createElement("div");
        objImageDetails.setAttribute('id','imageDetails'+lightboxNum);
        objImageDetails.className = 'imageDetails';
        objImageData.appendChild(objImageDetails);
    
        var objCaption = document.createElement("span");
        objCaption.setAttribute('id','caption'+lightboxNum);
        objCaption.className = 'caption';
        objImageDetails.appendChild(objCaption);
    
        var objNumberDisplay = document.createElement("span");
        objNumberDisplay.setAttribute('id','numberDisplay'+lightboxNum);
        objNumberDisplay.className = 'numberDisplay';
        objImageDetails.appendChild(objNumberDisplay);

        var objBottomNav = document.createElement("div");
        objBottomNav.setAttribute('id','bottomNav'+lightboxNum);
        objBottomNav.className = 'bottomNav';
        objImageData.appendChild(objBottomNav);
        
        var objBottomNavCloseLink = document.createElement("a");
        objBottomNavCloseLink.setAttribute('id','bottomNavClose'+lightboxNum);
        objBottomNavCloseLink.className = 'bottomNavClose';
        objBottomNavCloseLink.setAttribute('lightboxNum', lightboxNum);
        objBottomNavCloseLink.setAttribute('href','#');
        objBottomNavCloseLink.onclick = function() {myLightbox.end(this.getAttribute('lightboxNum')); return false; }
        objBottomNav.appendChild(objBottomNavCloseLink);
    
        var objBottomNavCloseImage = document.createElement("img");
        objBottomNavCloseImage.setAttribute('src', fileBottomNavCloseImage);
        objBottomNavCloseLink.appendChild(objBottomNavCloseImage);
                
        var objFullsizeImage = document.createElement("img");
        objFullsizeImage.setAttribute('id','fullsize'+lightboxNum);
        objFullsizeImage.setAttribute('src', globalImagePath+'fullsize.gif');
        objFullsizeImage.style.display = 'none';
        objFullsizeImage.onclick = function() {myLightbox.changeImage(activeImage, true);}
        objBottomNav.appendChild(objFullsizeImage);
        
        var arrayPageSize = getPageSize();
        initialPageWidth = arrayPageSize[0];
        initialPageHeight = arrayPageSize[1];

        if(newImage==-1){
            this.end();
        }else if(!start){
            this.changeImage(newImage);
        };
    },
    
    //Loads the XML
    loadXML: function(galleryName){
        var xml = "XML/"+galleryName+".xml";
        xml += ( ( xml.indexOf('?') + 1 ) ? '&' : '?' ) + ( new Date() ).getTime(); //prevent cache
        if(IE) {
            xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
            xmlDoc.async=false;
            xmlDoc.load(xml);
        } else if (document.implementation && document.implementation.createDocument){
            xmlDoc=document.implementation.createDocument("","",null);
            xmlDoc.async=false;
            xmlDoc.load(xml);
        };
    },
    
    // updateImageList()
    // Loops through anchor tags looking for 'lightbox' references and applies onclick
    // events to appropriate links. You can rerun after dynamically adding images w/ajax.
    updateImageList: function() {
        if (!document.getElementsByTagName){ return; }
        var anchors = document.getElementsByTagName('a');
        var areas = document.getElementsByTagName('area');
        
        var length = Math.max(areas.length, anchors.length);
        
        // loop through all anchor tags
        for (var i=0; i<length; i++){
            var anchor = anchors[i];
            var area = areas[i];
            
            if(anchor){
                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.createImageArray(this); return false;}
                }
            }
            if(area){
                var relAttribute = String(area.getAttribute('rel'));
                
                if (area.getAttribute('href') && (relAttribute.toLowerCase().match('lightbox'))){
                    area.onclick = function () {myLightbox.createImageArray(this); return false;}
                }
            }
        }
    },
    
    //Checks if user is using XML or not.
    //If image is part of a set, add siblings to imageArray.
    createImageArray: function(imageLink){

        imageArray = [];
        imageNum = 0;

        if (!document.getElementsByTagName){ return; }
        var anchors = document.getElementsByTagName( imageLink.tagName);
        // if image is NOT part of a set..
        if((imageLink.getAttribute('rel') == 'lightbox')){
            // add single image to imageArray
            imageArray.push(new Array(imageLink.getAttribute('href',2), imageLink.getAttribute('title'), imageLink.getAttribute('width'), '', imageLink.getAttribute('height')));            
        } else {
            if (!userXML) {
                // 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',2), anchor.getAttribute('title'), anchor.getAttribute('width'), anchor.firstChild.getAttribute('src'), anchor.getAttribute('height')));
                        imageArray.push(new Array(anchor.getAttribute('href',2), anchor.getAttribute('title'), anchor.getAttribute('width'), anchor.getAttribute('href',2) , anchor.getAttribute('height')));
                    };
                };
                imageArray.removeDuplicates();
                while(imageArray[imageNum][0] != imageLink.getAttribute('href',2)) { imageNum++;}
            } else if(userXML) {
                imageSet=imageLink.getAttribute('rel');
                imageSet=imageSet.slice(9, imageSet.length-1).toLowerCase();
                myLightbox.loadXML(imageSet);
                var retrieve = xmlDoc.getElementsByTagName(imageSet)[0];
                for (var i=0;i<retrieve.childNodes.length;i++){
                    if(retrieve.childNodes[i].nodeType == 1){
                        imageArray.push(new Array(retrieve.childNodes[i].attributes.getNamedItem("source").value, retrieve.childNodes[i].attributes.getNamedItem("caption").value, retrieve.childNodes[i].attributes.getNamedItem("Width").value, retrieve.childNodes[i].attributes.getNamedItem("thumbnailSource").value, retrieve.childNodes[i].attributes.getNamedItem("Height").value));
                    };
                };
            };
        };
        myLightbox.start();
    },

    //    start()
    //    Display overlay and lightbox.
    start: function() {
        
        var arrayPageSize = getPageSize();
        if(arrayPageSize[1]==arrayPageSize[3]){ headerWidth = arrayPageSize[2]-16 }else{ headerWidth = arrayPageSize[2]-32 };
        Element.setWidth('headerBarImage', headerWidth);
        Element.setWidth('header', headerWidth);
        
        hideSelectBoxes();
        hideFlash();
        hideiFrame();
        headerIndexCounter = 1;
        headerImageContainerArray = [0];
        var headerImageContainerWidth = 0;
        var headerImageContainerWidthTotal = 0;
        //Creates the image thumbnails of the set
        var remove = document.getElementById('headerImageContainer');
        if ((remove)){remove.parentNode.removeChild(remove)};
        var remove = document.getElementById('indexForward');
        if ((remove)){remove.parentNode.removeChild(remove)};
        var remove = document.getElementById('indexBackward');
        if ((remove)){remove.parentNode.removeChild(remove)};
        
        var objHeaderImageContainer = document.createElement("div");
        objHeaderImageContainer.setAttribute('id','headerImageContainer');
        if(!header){objHeaderImageContainer.style.display = 'none'};
        objHeaderBG.appendChild(objHeaderImageContainer);
        
        var objIndexBackward = document.createElement("div");
        objIndexBackward.setAttribute('id','indexBackward');
        objIndexBackward.onclick = function() {headerIndexCounter=headerIndexCounter-2; if(headerImageContainerArray.length-4==headerIndexCounter){myLightbox.changeIndex(1, headerImageContainerArray[headerIndexCounter+2])}else{myLightbox.changeIndex(1, headerImageContainerArray[headerIndexCounter])}};
        objIndexBackward.style.display = 'none';
        objHeaderBG.appendChild(objIndexBackward);        
        
        var objIndexForward = document.createElement("div");
        objIndexForward.setAttribute('id','indexForward');
        objIndexForward.onclick = function() {headerIndexCounter=headerIndexCounter+2; if(headerImageContainerArray.length-2==headerIndexCounter){myLightbox.changeIndex(-1, headerImageContainerArray[headerIndexCounter])}else{myLightbox.changeIndex(-1, headerImageContainerArray[headerIndexCounter-2])}};
        objIndexForward.style.display = 'none';
        objHeaderBG.appendChild(objIndexForward);
        
        if(imageArray.length!=1){
            for (var i=0; i<imageArray.length; i++){
                var w = parseInt(imageArray[i][2])+10;
                if(parseInt(imageArray[i][4]) > 60) {
                    w=parseInt(imageArray[i][2])*60/parseInt(imageArray[i][4]) +10;
                    Element.setWidth('headerIndex'+i, w-10);
                    Element.setHeight('headerIndex'+i, '60');
                };
                if((headerImageContainerWidth + w) >= (headerWidth-20)){
                    headerImageContainerArray.push(headerImageContainerWidth-10,i);
                    var headerOverflow = headerWidth - headerImageContainerWidth;
                    headerImageContainerWidth = 10;
                    Element.setPosition('headerImageContainer', 'absolute');
                };
                var objHeaderIndexBG = document.createElement("div");
                objHeaderIndexBG.setAttribute('id', 'headerIndexBG');
                objHeaderIndexBG.setAttribute('imagenum', i);
                objHeaderImageContainer.appendChild(objHeaderIndexBG);
    
                headerImageContainerWidth = headerImageContainerWidth + w;
                headerImageContainerWidthTotal = headerImageContainerWidthTotal + w;
    
                var objHeaderIndex = document.createElement("img");
                objHeaderIndex.setAttribute('src', imageArray[i][3]);
                objHeaderIndex.setAttribute('id', 'headerIndex'+i);
                objHeaderIndex.className = 'headerIndex';
                objHeaderIndex.setAttribute('imagenum', i);
                objHeaderIndex.onclick = function(){if(parseInt(this.getAttribute('imagenum')) != activeImage){myLightbox.changeImage(parseInt(this.getAttribute('imagenum')))}};
                objHeaderIndexBG.appendChild(objHeaderIndex);
                new Draggable('headerIndex'+i,{revert:true, ghosting:true});
            }
        }
        headerImageContainerArray.push(headerImageContainerWidth - headerOverflow-10, imageArray.length);
        if(headerImageContainerWidthTotal)Element.setWidth('headerImageContainer', headerImageContainerWidthTotal);
        Droppables.add('overlay',{onDrop: function(element, lastelement, event, pointerx, pointery, zIndex){myLightbox.newLightbox(parseInt(element.getAttribute('imagenum')), pointerx, pointery, zIndex)}, accept: 'headerIndex'});

        // stretch overlay to fill page and fade in
        Element.setHeight('overlay', arrayPageSize[1]);
        Element.setWidth('overlay', arrayPageSize[0]);
        new Effect.Appear('overlay', { duration: overlayDuration, queue: {position:'end', scope: 'startScope', limit:2}, from: 0.0, to: overlayOpacity});        

        // calculate top offset for the lightbox and display 
        var arrayPageScroll = getPageScroll();
        lightboxTop = arrayPageScroll[1] + (arrayPageSize[3] / 5);

        Element.setTop('lightbox'+lightboxNum, lightboxTop);
        Element.show('lightbox'+lightboxNum);
        if(start && (imageArray.length >1) && showHeader){new Effect.Appear('headerContainer', {duration: headerDuration, queue: {position:'end', scope: 'startScope', limit:2}, afterFinish: function(){start=false;}})};
        if(!initialScroll) {
            initialScroll = arrayPageScroll[1];
            Element.setTop('headerContainer', initialScroll);
        };
        if(headerStartDown && !header){this.header();};
        
        this.changeImage(imageNum);
    },
    
    changeIndex: function(direction, size){
        new Effect.Move ('headerImageContainer',{ x: direction*size, y: 0, mode: 'relative', queue: 'end'});
        myLightbox.headerNav();
    },
    
    headerNav: function(){
        if(headerIndexCounter == 1){Element.hide('indexBackward')}else{Element.show('indexBackward')};
        if(headerIndexCounter == (headerImageContainerArray.length-2)){Element.hide('indexForward')}else if(imageArray.length!=1){Element.show('indexForward')};
    },

    //    changeImage()
    //    Hide most elements and preload image in preparation for resizing image container.
    changeImage: function(imageNum, fullsize, currentLightbox) {
        lightboxArray.push(lightboxNum, imageNum);
        if(lightboxNum==1)Element.show('innerLightbox1');
        otherContent=false;
        //Element.setInnerHTML('imageContainer'+lightboxNum, '<img id="lightboxImage"><div id="loading"><a href="#" id="loadingLink"><img src="images/loading.gif"></a></div>');
        for (i=0; i<imageArray.length; i++){
            if(document.getElementById('headerIndex'+i))document.getElementById('headerIndex'+i).onclick = '';
        };
        if(totalLightbox==1)myLightbox.unselectedImage();
        activeImage = imageNum;    // update global var
        if(imageNum>=headerImageContainerArray[headerIndexCounter + 1]){
            var size=0;
            while(imageNum>=headerImageContainerArray[headerIndexCounter + 1]){if(headerImageContainerArray.length-4==headerIndexCounter){size=headerImageContainerArray[headerIndexCounter+2]+size; headerIndexCounter=headerIndexCounter+2;}else{size=headerImageContainerArray[headerIndexCounter]+size; headerIndexCounter=headerIndexCounter+2;}};
            myLightbox.changeIndex(-1, size);
        };
        if(imageNum<headerImageContainerArray[headerIndexCounter - 1]){
            var size=0;
            while(imageNum<headerImageContainerArray[headerIndexCounter - 1]){if(headerIndexCounter-3==0){size=headerImageContainerArray[headerIndexCounter-2]+size; headerIndexCounter=headerIndexCounter-2;}else{size=headerImageContainerArray[headerIndexCounter]+size; headerIndexCounter=headerIndexCounter-2;}};
            myLightbox.changeIndex(1, size);
        };
        if(totalLightbox==1)myLightbox.selectedImage();
        
        // hide elements during transition
        if(animate){ Element.show('loading'+lightboxNum);}
        Element.hide('lightboxImage'+lightboxNum);
        Element.hide('hoverNav'+lightboxNum);
        Element.hide('prevLink'+lightboxNum);
        Element.hide('nextLink'+lightboxNum);
        Element.hide('imageDataContainer'+lightboxNum);
        Element.hide('numberDisplay'+lightboxNum);

        if(imageArray.length==1 && imageArray[activeImage][0].slice(0,1)=='<'){
            otherContent=true;
            myLightbox.resizeImageContainer(parseInt(imageArray[activeImage][2]), parseInt(imageArray[activeImage][4]));
        } else {
            imgPreloader = new Image();

            // once image is preloaded, resize image container
            imgPreloader.onload=function(){
                Element.setSrc('lightboxImage'+lightboxNum, imageArray[activeImage][0]);
                myLightbox.resizeImageContainer(imgPreloader.width, imgPreloader.height, fullsize);
            }
            imgPreloader.src = imageArray[activeImage][0];
        };
    },

    //    resizeImageContainer()
    resizeImageContainer: function( imgWidth, imgHeight, fullsize) {
        // get current width and height
        this.widthCurrent = Element.getWidth('outerImageContainer'+lightboxNum);
        this.heightCurrent = Element.getHeight('outerImageContainer'+lightboxNum);

        // get new width and height
        widthNew = (imgWidth  + (borderSize * 2));
        heightNew = (imgHeight  + (borderSize * 2));
        
        getPageSize();
        getPageScroll();
        if(!otherContent){
            if(((heightNew <= (arrayPageSize[3]-lightboxTop+arrayPageScroll[1]-70))&&(widthNew <= arrayPageSize[2]))||fullsize){
                Element.setWidth('lightboxImage'+lightboxNum, imgWidth);
                Element.setHeight('lightboxImage'+lightboxNum, imgHeight);
                Element.hide('fullsize'+lightboxNum);
            } else {
                if(widthNew > arrayPageSize[2]){
                    if((arrayPageSize[2] < minWidth)){ var tempWidth = minWidth;}
                    else{var tempWidth = arrayPageSize[2]};
                    if(minWidth >= widthNew)var tempWidth = widthNew;
                    heightNew = heightNew * (tempWidth/widthNew);
                    widthNew = tempWidth;
                };
                if(heightNew > (arrayPageSize[3]-lightboxTop+arrayPageScroll[1]-70)){
                    if((widthNew * ((arrayPageSize[3]-lightboxTop+arrayPageScroll[1]-70)/heightNew) < minWidth)){ var tempHeight = minWidth*heightNew/widthNew;}
                    else{var tempHeight = arrayPageSize[3]-lightboxTop+arrayPageScroll[1]-70};
                    if(minWidth >= widthNew)var tempHeight = heightNew; 
                    widthNew = widthNew * (tempHeight/heightNew);
                    heightNew = tempHeight;
                };
                Element.setWidth('lightboxImage'+lightboxNum, (widthNew-borderSize*2));
                Element.setHeight('lightboxImage'+lightboxNum, (heightNew-borderSize*2));
                Element.show('fullsize'+lightboxNum);
            };
        };
        if(widthNew<minWidth){widthNew = minWidth;}
        Element.setWidth('imageDataContainer'+lightboxNum, widthNew);
        fullsize=  false;
        currentFullsize=false;
        if((widthNew>arrayPageSize[2])||((heightNew)>arrayPageSize[3])){
            currentFullsize=true;
        };
        
        if(drag && totalLightbox!=1){drag.draw([x, y], true, widthNew/2, heightNew/2, lightboxTop);};
        
        // 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('outerImageContainer'+lightboxNum, this.yScale, {scaleX: false, duration: resizeDuration, queue: 'front'}); }
        if(!( wDiff == 0)){ new Effect.Scale('outerImageContainer'+lightboxNum, this.xScale, {scaleY: false, delay: resizeDuration, duration: resizeDuration}); }

        Element.setHeight('prevLink'+lightboxNum, heightNew);
        Element.setHeight('nextLink'+lightboxNum, heightNew);
        if(wDiff <0)Element.setWidth('innerLightbox'+lightboxNum, widthNew);
        if(heightNew > initialPageHeight){
            Element.setHeight('overlay', heightNew);
        } else {
            Element.setHeight('overlay', initialPageHeight);
        };
        if(widthNew > initialPageWidth){
            Element.setWidth('overlay', widthNew);
        } else {
            Element.setWidth('overlay', initialPageWidth);
        };

        this.showImage();
        
    },
    
    //
    //    showImage()
    //    Display image and begin preloading neighbors.
    //
    showImage: function(){
        Element.hide('loading'+lightboxNum);
        if(!otherContent){
            new Effect.Appear('lightboxImage'+lightboxNum, { duration: resizeDuration, queue: 'end', afterFinish: function(){    myLightbox.updateDetails(); } });
            this.preloadNeighborImages();
        } else {
            new Effect.Appear('imageContainer'+lightboxNum, { duration: 0, queue: 'end', afterFinish: function(){Element.setInnerHTML('imageContainer'+lightboxNum, imageArray[activeImage][0] + '<div id="loading" style="display:none"><a href="#" id="loadingLink"><img src="'+globalImagePath+'loading.gif"></a></div>');}});
        };
    },

    //
    //    updateDetails()
    //    Display caption, image number, and bottom nav.
    //
    updateDetails: function() {
        // Show Caption
        Element.show('caption'+lightboxNum);
        Element.setInnerHTML( 'caption'+lightboxNum, imageArray[activeImage][1]);
        
        // if image is part of set display 'Image x of x' 
        if(imageArray.length > 1){
            Element.show('numberDisplay'+lightboxNum);
            Element.setInnerHTML('numberDisplay'+lightboxNum, "Image " + eval(activeImage + 1) + " of " + imageArray.length);
        }

        
        new Effect.Parallel(
            [ new Effect.SlideDown( 'imageDataContainer'+lightboxNum, { sync: true, duration: resizeDuration, from: 0.0, to: 1.0 }), 
              new Effect.Appear('imageDataContainer'+lightboxNum, { sync: true, duration: resizeDuration }) ], 
            { duration: resizeDuration, afterFinish: function() {
                // update overlay size and update nav
                if(lightboxNum==1)Element.setWidth('innerLightbox'+lightboxNum, widthNew);
                }
            }
        );
        if(totalLightbox==1)myLightbox.updateNav();
    },

    //
    //    updateNav()
    //    Display appropriate previous and next hover navigation.
    //
    updateNav: function() {

        Element.show('hoverNav'+lightboxArray[0]);                

        // if not first image in set, display prev image button
        if(activeImage != 0){
            Element.show('prevLink'+lightboxArray[0]);
            document.getElementById('prevLink'+lightboxArray[0]).onclick = function() {
                myLightbox.changeImage(activeImage - 1); return false;
            }
        }

        // if not last image in set, display next image button
        if(activeImage != (imageArray.length - 1)){
            Element.show('nextLink'+lightboxArray[0]);
            document.getElementById('nextLink'+lightboxArray[0]).onclick = function() {
                myLightbox.changeImage(activeImage + 1); return false;
            }
        };

        for (i=0; i<imageArray.length; i++){
            document.getElementById('headerIndex'+i).onclick = function(){if(parseInt(this.getAttribute('imagenum')) != activeImage){myLightbox.changeImage(parseInt(this.getAttribute('imagenum')))}};
        };
        
        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
            if(activeImage != 0){
                myLightbox.disableKeyboardNav();
                myLightbox.changeImage(activeImage - 1);
            }
        } else if((key == 'n') || (keycode == 39)){    // display next image
            if(activeImage != (imageArray.length - 1)){
                myLightbox.disableKeyboardNav();
                myLightbox.changeImage(activeImage + 1);
            }
        }

    },

    //    preloadNeighborImages()
    //    Preload previous and next images.
    preloadNeighborImages: function(){

        if((imageArray.length - 1) > activeImage){
            preloadNextImage = new Image();
            preloadNextImage.src = imageArray[activeImage + 1][0];
        }
        if(activeImage > 0){
            preloadPrevImage = new Image();
            preloadPrevImage.src = imageArray[activeImage - 1][0];
        }
    
    },
    
    //Show or hide the header
    header: function (){
        if(!header){
            new Effect.SlideDown('headerBG', {duration: headerDuration, queue: {position:'end', scope: 'imageHeaderScope', limit:1}, afterFinish: function(){
                Element.setBackgroundImage('headerBarArrow','url(Themes/default/images/headerBarArrowUp.gif)');
                new Effect.Appear('headerImageContainer', { duration: headerDuration, queue: {position:'end', scope: 'imageHeaderScope', limit:1}, afterFinish: function(){header=true;}})
                myLightbox.headerNav();
            }});
        };
        if(header){
            Element.hide('indexForward');
            Element.hide('indexBackward');
            new Effect.Fade('headerImageContainer', {duration: headerDuration, queue: {position:'end', scope: 'imageHeaderScope', limit:1}, afterFinish: function(){
                new Effect.SlideUp('headerBG', {duration: headerDuration, queue: {position:'end', scope: 'imageHeaderScope', limit:1}, afterFinish: function(){header=false; Element.setBackgroundImage('headerBarArrow', 'url(Themes/default/images/headerBarArrowDown.gif)');}})}
            });
        };
    },

    unselectedImage: function(){
        if(activeImage >= 0){
            for(i=0; i<document.getElementsByTagName('img').length; i++){
                if(document.getElementById('headerIndexSelected')){
                    document.getElementById('headerIndexSelected').setAttribute('id','headerIndexBG');
                };
            };
        };
        return;
    },

    selectedImage: function(){
        for(i=0; i<document.getElementsByTagName('img').length; i++){
            if((document.getElementsByTagName('img')[i].getAttribute('imagenum') == activeImage) && (document.getElementsByTagName('img')[i].parentNode.getAttribute('id')!='headerIndexSelectedGreen')){
                document.getElementsByTagName('img')[i].parentNode.setAttribute('id','headerIndexSelected');
            };
        };
        return;
    },

    //    end()
    end: function(number) {
        if(otherContent){
            var remove = document.getElementById('lightbox1');
            if ((remove)){remove.parentNode.removeChild(remove)};
            otherContent=false;
            lightboxNum=0;
            totalLightbox=0;
            myLightbox.newLightbox(0);
        };
        if(totalLightbox==1 || number==-1){
            for(i=1; i<=lightboxNum; i++){
                if(i!=1){
                    var remove = document.getElementById('innerLightbox'+i);
                    if ((remove)){remove.parentNode.removeChild(remove)};
                } else { Element.hide('lightbox1')};
            };
            lightboxNum=1;
            totalLightbox=1;
            initialScroll = 0;
            lightboxArray=[];
            new Effect.Fade('headerContainer', {duration: overlayDuration, afterFinish: function(){start=true;}});
            Element.setWidth('outerImageContainer'+lightboxNum, 250);
            Element.setHeight('outerImageContainer'+lightboxNum, 250);
            Element.setTop('innerLightbox1', 0);
            Element.setLeft('innerLightbox1', 0);
            this.disableKeyboardNav();
            new Effect.Fade('overlay', { duration: overlayDuration});
            showSelectBoxes();
            showFlash();
            showiFrame();
        } else if(totalLightbox>1 && number!=-1){
            if(number!=1){
                var remove = document.getElementById('innerLightbox'+number);
                if ((remove)){remove.parentNode.removeChild(remove)};
            } else { Element.hide('innerLightbox1')};
            totalLightbox--;
            for(i=0; i<lightboxArray.length; i=i+2){
                if(lightboxArray[i]==number) lightboxArray.splice(i,2);
            };        
            if(totalLightbox==1) {
                lightboxNum=lightboxArray[0];
                myLightbox.updateNav();
            };
        };
    }
}

// -----------------------------------------------------------------------------------
// getPageScroll()
// Returns array with x,y page scroll values.
// Core code from - quirksmode.org
function getPageScroll(){

    var yScroll;

    if (self.pageYOffset) {
        yScroll = self.pageYOffset;
    } else if (document.documentElement && document.documentElement.scrollTop){     // Explorer 6 Strict
        yScroll = document.documentElement.scrollTop;
    } else if (document.body) {// all other Explorers
        yScroll = document.body.scrollTop;
    }

    arrayPageScroll = new Array('',yScroll) 
    return arrayPageScroll;
}

// -----------------------------------------------------------------------------------
// getPageSize()
// Returns array with page width, height and window width, height
// Core code from - quirksmode.org
// Edit for Firefox by pHaez
function getPageSize() {

    var xScroll, yScroll;
    var windowWidth, windowHeight;
    
    if (document.documentElement && document.documentElement.clientWidth && document.documentElement.clientHeight) {
        windowWidth = document.documentElement.clientWidth;
        windowHeight = document.documentElement.clientHeight;
    } else if(window.innerWidth && window.innerHeight) {
        windowWidth = window.innerWidth;
        windowHeight = window.innerHeight;
    } else if (document.body) {
        windowWidth = document.body.clientWidth;
        windowHeight = document.body.clientHeight;
    }
    
    var pxW = 0;
    if(window.innerWidth && window.scrollMaxX)
    pxW = windowWidth + window.scrollMaxX;
    
    xScroll = Math.max(Math.max(pxW, document.body.scrollWidth), document.body.offsetWidth);
    
    var pxH = 0;
    if(window.innerHeight && window.scrollMaxY)
    pxH = windowHeight + window.scrollMaxY;
    
    yScroll = Math.max(Math.max(pxH, document.body.scrollHeight), document.body.offsetHeight);
    
    pageHeight = Math.max(yScroll, windowHeight);
    pageWidth = Math.max(xScroll, windowWidth);
    
    arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight)
    return arrayPageSize;
}
// -----------------------------------------------------------------------------------
// getKey(key)
// Gets keycode. If 'x' is pressed then it hides the lightbox.
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 hideiFrame(){
    var iframe = document.getElementsByTagName('iframe');
    for (i = 0; i != iframe.length; i++) {
        iframe[i].style.visibility = 'hidden';
    }
}

// ---------------------------------------------------

function showiFrame(){
    var iframe = document.getElementsByTagName('iframe');
    for (i = 0; i != iframe.length; i++) {
        iframe[i].style.visibility = 'visible';
    }
}

// ---------------------------------------------------

function resizeShadow() {
    var arrayPageSize = getPageSize();
    Element.setWidth('overlay', arrayPageSize[0]);
    Element.setHeight('overlay', arrayPageSize[1]);
}

Event.observe(window, 'resize', resizeShadow, false);

// ---------------------------------------------------

function setHeaderTop() {
    var arrayPageScroll = getPageScroll();
    Element.setTop('headerContainer', arrayPageScroll[1]);
}

Event.observe(window, 'scroll', setHeaderTop, false);

// ---------------------------------------------------

function initLightbox() { myLightbox = new Lightbox()}
Event.observe(window, 'load', initLightbox, false);

