var pageLightBoxObject;

PageLightboxOptions = Object.extend({
    fileLoadingImage:        'CSS/images/loading.gif',     
    overlayOpacity: 0.8,
    animate: true, 
    resizeSpeed: 8,
    borderSize: 10
}, window.PageLightboxOptions || {});

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

var PageLightbox = Class.create();

PageLightbox.prototype = {
    initialize: function() {

        this.keyboardAction = this.keyboardAction.bindAsEventListener(this);

        if (PageLightboxOptions.resizeSpeed > 10) PageLightboxOptions.resizeSpeed = 10;
        if (PageLightboxOptions.resizeSpeed < 1) PageLightboxOptions.resizeSpeed = 1;

        this.resizeDuration = PageLightboxOptions.animate ? ((11 - PageLightboxOptions.resizeSpeed) * 0.15) : 0;
        this.pageoverlayDuration = PageLightboxOptions.animate ? 0.2 : 0;  // shadow fade in/out duration

        var size = (PageLightboxOptions.animate ? 250 : 1) + 'px';

        var objBody = $$('form')[0];

        objBody.appendChild(Builder.node('div', { id: 'pageoverlay' }));

        objBody.appendChild(Builder.node('div', { id: 'pagelightbox' }, [
            Builder.node('div', { id: 'pageOuterContainer' },
                Builder.node('div', { id: 'pageContainer' }, [
                    Builder.node('div', { id: 'pageContentDiv' }),
                    Builder.node('div', { id: 'pageloading' },
                        Builder.node('a', { id: 'pageloadingLink', href: '#' },
                            Builder.node('img', { src: PageLightboxOptions.fileLoadingImage, border: 0 })
                        )
                    )
                ])
            )
        ]));


        $('pageoverlay').hide().observe('click', (function() { this.end(); }).bind(this));
        $('pagelightbox').hide().observe('click', (function(event) { if (event.element().id == 'pagelightbox') this.end(); }).bind(this));
        $('pageOuterContainer').setStyle({ width: size, height: size });
        //		$('prevLink').observe('click', (function(event) { event.stop(); this.changeImage(this.activeImage - 1); }).bindAsEventListener(this));
        //		$('nextLink').observe('click', (function(event) { event.stop(); this.changeImage(this.activeImage + 1); }).bindAsEventListener(this));
        //$('pageloadingLink').observe('click', (function(event) { event.stop(); this.end(); }).bind(this));
        //		$('bottomNavClose').observe('click', (function(event) { event.stop(); this.end(); }).bind(this));

        var th = this;
        (function() {
            var ids =
                'pageoverlay pagelightbox pageOuterContainer pageContainer pageloading pageloadingLink';
            $w(ids).each(function(id) { th[id] = $(id); });
        }).defer();
    },


    start: function() {

        $$('select', 'object', 'embed').each(function(node) { node.style.visibility = 'hidden' });

        // stretch overlay to fill page and fade in
        var arrayPageSize = this.getPageSize();
        $('pageoverlay').setStyle({ width: arrayPageSize[0] + 'px', height: arrayPageSize[1] + 'px' });

        new Effect.Appear(this.pageoverlay, { duration: this.pageoverlayDuration, from: 0.0, to: PageLightboxOptions.overlayOpacity });

        // calculate top and left offset for the lightbox 
        var arrayPageScroll = document.viewport.getScrollOffsets();
        var lightboxTop = arrayPageScroll[1] + (document.viewport.getHeight() / 10);
        var lightboxLeft = arrayPageScroll[0];
        this.pagelightbox.setStyle({ top: lightboxTop + 'px', left: lightboxLeft + 'px' }).show();

    },

    //
    //  changeImage()
    //  Hide most elements and preload image in preparation for resizing image container.
    //
    changeImage: function(imageNum) {

        this.activeImage = imageNum; // update global var

        // hide elements during transition
        if (PageLightboxOptions.animate) this.pageloading.show();
        this.lightboxImage.hide();
        this.hoverNav.hide();
        this.prevLink.hide();
        this.nextLink.hide();
        // HACK: Opera9 does not currently support scriptaculous opacity and appear fx
        this.imageDataContainer.setStyle({ opacity: .0001 });
        this.numberDisplay.hide();

        var imgPreloader = new Image();

        // once image is preloaded, resize image container


        imgPreloader.onload = (function() {
            this.lightboxImage.src = this.imageArray[this.activeImage][0];
            this.resizeImageContainer(imgPreloader.width, imgPreloader.height);
        }).bind(this);
        imgPreloader.src = this.imageArray[this.activeImage][0];
    },

    //
    //  resizeImageContainer()
    //
    resizeImageContainer: function(imgWidth, imgHeight) {
        // get current width and height
        var widthCurrent = this.pageOuterContainer.getWidth();
        var heightCurrent = this.pageOuterContainer.getHeight();

        // get new width and height
        var widthNew = (imgWidth + PageLightboxOptions.borderSize * 2);
        var heightNew = (imgHeight + PageLightboxOptions.borderSize * 2);

        // scalars based on change from old to new
        var xScale = (widthNew / widthCurrent) * 100;
        var yScale = (heightNew / heightCurrent) * 100;

        // calculate size difference between new and old image, and resize if necessary
        var wDiff = widthCurrent - widthNew;
        var hDiff = heightCurrent - heightNew;

        if (hDiff != 0) new Effect.Scale(this.pageOuterContainer, yScale, { scaleX: false, duration: this.resizeDuration, queue: 'front' });
        if (wDiff != 0) new Effect.Scale(this.pageOuterContainer, xScale, { scaleY: false, duration: this.resizeDuration, delay: this.resizeDuration });

        // if new and old image are same size and no scaling transition is necessary, 
        // do a quick pause to prevent image flicker.
        var timeout = 0;
        if ((hDiff == 0) && (wDiff == 0)) {
            timeout = 100;
            if (Prototype.Browser.IE) timeout = 250;
        }
    },

    showContent: function(pageContent) {
        this.pageloading.hide();
        $('pageContentDiv').innerHTML = pageContent;
        var tab = $('pageContentDiv').getElementsByTagName('Table')[0];
        //alert(tab.offsetWidth + ' --- ' + tab.offsetHeight);
        this.resizeImageContainer(tab.offsetWidth, tab.offsetHeight + 10);
    },

    showLoading: function() {
        this.pageloading.show();
    },
    hideLoading: function() {
        this.pageloading.hide();
    },

    clearContent: function() {
        this.pageloading.show();
        $('pageContentDiv').innerHTML = '';
    },
    
    //
    //  updateDetails()
    //  Display caption, image number, and bottom nav.
    //
    updateDetails: function() {

        // if caption is not null
        if (this.imageArray[this.activeImage][1] != "") {
            this.caption.update(this.imageArray[this.activeImage][1]).show();
        }

        // if image is part of set display 'Image x of x' 
        if (this.imageArray.length > 1) {
            this.numberDisplay.update(PageLightboxOptions.labelImage + ' ' + (this.activeImage + 1) + ' ' + PageLightboxOptions.labelOf + '  ' + this.imageArray.length).show();
        }

        new Effect.Parallel(
            [
                new Effect.SlideDown(this.imageDataContainer, { sync: true, duration: this.resizeDuration, from: 0.0, to: 1.0 }),
                new Effect.Appear(this.imageDataContainer, { sync: true, duration: this.resizeDuration })
            ],
            {
                duration: this.resizeDuration,
                afterFinish: (function() {
                    // update overlay size and update nav
                    var arrayPageSize = this.getPageSize();
                    this.pageoverlay.setStyle({ height: arrayPageSize[1] + 'px' });
                    this.updateNav();
                }).bind(this)
            }
        );
    },

    //
    //  enableKeyboardNav()
    //
    enableKeyboardNav: function() {
        document.observe('keydown', this.keyboardAction);
    },

    //
    //  disableKeyboardNav()
    //
    disableKeyboardNav: function() {
        document.stopObserving('keydown', this.keyboardAction);
    },

    //
    //  keyboardAction()
    //
    keyboardAction: function(event) {
        var keycode = event.keyCode;

        var escapeKey;
        if (event.DOM_VK_ESCAPE) {  // mozilla
            escapeKey = event.DOM_VK_ESCAPE;
        } else { // ie
            escapeKey = 27;
        }

        var key = String.fromCharCode(keycode).toLowerCase();

        if (key.match(/x|o|c/) || (keycode == escapeKey)) { // close lightbox
            this.end();
        } else if ((key == 'p') || (keycode == 37)) { // display previous image
            if (this.activeImage != 0) {
                this.disableKeyboardNav();
                this.changeImage(this.activeImage - 1);
            }
        } else if ((key == 'n') || (keycode == 39)) { // display next image
            if (this.activeImage != (this.imageArray.length - 1)) {
                this.disableKeyboardNav();
                this.changeImage(this.activeImage + 1);
            }
        }
    },

    //
    //  end()
    //
    end: function() {
        this.disableKeyboardNav();
        this.pagelightbox.hide();
        new Effect.Fade(this.pageoverlay, { duration: this.pageoverlayDuration });
        $$('select', 'object', 'embed').each(function(node) { node.style.visibility = 'visible' });
    },

    //
    //  getPageSize()
    //
    getPageSize: function() {

        var xScroll, yScroll;

        if (window.innerHeight && window.scrollMaxY) {
            xScroll = window.innerWidth + window.scrollMaxX;
            yScroll = window.innerHeight + window.scrollMaxY;
        } else if (document.body.scrollHeight > document.body.offsetHeight) { // all but Explorer Mac
            xScroll = document.body.scrollWidth;
            yScroll = document.body.scrollHeight;
        } else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
            xScroll = document.body.offsetWidth;
            yScroll = document.body.offsetHeight;
        }

        var windowWidth, windowHeight;

        if (self.innerHeight) {	// all except Explorer
            if (document.documentElement.clientWidth) {
                windowWidth = document.documentElement.clientWidth;
            } else {
                windowWidth = self.innerWidth;
            }
            windowHeight = self.innerHeight;
        } else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
            windowWidth = document.documentElement.clientWidth;
            windowHeight = document.documentElement.clientHeight;
        } else if (document.body) { // other Explorers
            windowWidth = document.body.clientWidth;
            windowHeight = document.body.clientHeight;
        }

        // for small pages with total height less then height of the viewport
        if (yScroll < windowHeight) {
            pageHeight = windowHeight;
        } else {
            pageHeight = yScroll;
        }

        // for small pages with total width less then width of the viewport
        if (xScroll < windowWidth) {
            pageWidth = xScroll;
        } else {
            pageWidth = windowWidth;
        }

        return [pageWidth, pageHeight];
    }
}

document.observe('dom:loaded', function () { pageLightBoxObject = new PageLightbox(); });