﻿LightboxOptions = Object.extend({

}, window.LightboxOptions || {});

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

var Lightbox = Class.create();

Lightbox.prototype = {

    // initialize()
    // 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: function(
		  OverlayDivId
		, PopContainerDivId
		, PopBackgroundId
		, PopFadeInId
		, PopInnerContainerId
		, Animate
		, ResizeSpeed
		, OverlayOpacity
		, FadeInBackgroundColor
		, FadeFinishBackgroundColor
		, PopupHeightPercentage
		, CloseButtons
    ) {
        //Make Globals
        this.lbxOverlayDivId = OverlayDivId;
        this.lbxPopContainerDivId = PopContainerDivId;
        this.lbxPopBackgroundId = PopBackgroundId;
        this.lbxPopFadeInId = PopFadeInId;
        this.lbxPopInnerContainerId = PopInnerContainerId;
        this.lbxAnimate = Animate;
        this.lbxResizeSpeed = ResizeSpeed;
        this.lbxOverlayOpacity = OverlayOpacity;
        this.lbxFadeInBackgroundColor = FadeInBackgroundColor;
        this.lbxFadeFinishBackgroundColor = FadeFinishBackgroundColor;
        this.lbxPopupHeightPercentage = PopupHeightPercentage;
        this.lbxCloseButtons = CloseButtons;

        this.updateImageList();

        this.keyboardAction = this.keyboardAction.bindAsEventListener(this);

        if (this.lbxResizeSpeed > 10) this.lbxResizeSpeed = 10;
        if (this.lbxResizeSpeed < 1) this.lbxResizeSpeed = 1;

        this.resizeDuration = this.lbxAnimate ? ((11 - this.lbxResizeSpeed) * 0.15) : 0;
        this.overlayDuration = this.lbxAnimate ? 0.2 : 0;  // shadow fade in/out duration

        // 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.
        var size = (this.lbxAnimate ? 250 : 1) + 'px';

        var objBody = $$('body')[0];

        $(this.lbxOverlayDivId).hide().observe('click', (function() { this.end(); }).bind(this));
        $(this.lbxPopContainerDivId).hide().observe('click', (function(event) { if (event.element().id == this.lbxPopContainerDivId) this.end(); }).bind(this));

        //Close Buttons
        if (this.lbxCloseButtons != null) {
            for (i = 0; i < this.lbxCloseButtons.length; i++) {
                $(this.lbxCloseButtons[i]).observe('click', (function(event) { this.end(); }).bind(this));
            }
        }

        var th = this;
        (function() {
            var ids =
                this.lbxOverlayDivId + ' ' + this.lbxPopContainerDivId + ' ' + this.lbxPopBackgroundId + ' ' + this.lbxPopInnerContainerId;
            $w(ids).each(function(id) { th[id] = $(id); });
        }).defer();
    },

    //
    // 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() {
        this.updateImageList = Prototype.emptyFunction;

        document.observe('click', (function(event) {
            var target = event.findElement('a[rel^=lightbox]') || event.findElement('area[rel^=lightbox]');
            if (target) {
                event.stop();
                this.start(target);
            }
        }).bind(this));
    },

    //
    //  start()
    //  Display overlay and lightbox. If image is part of a set, add siblings to imageArray.
    //
    start: function(imageLink) {

        $$('select', 'object', 'embed').each(function(node) { node.style.visibility = 'hidden' });

        // stretch overlay to fill page and fade in
        var arrayPageSize = this.getPageSize();
        $(this.lbxOverlayDivId).setStyle({ width: arrayPageSize[0] + 'px', height: arrayPageSize[1] + 'px' });

        new Effect.Appear(this.lbxOverlayDivId, { duration: this.overlayDuration, from: 0.0, to: this.lbxOverlayOpacity });

        // calculate top and left offset for the lightbox 
        var arrayPageScroll = document.viewport.getScrollOffsets();
        var lightboxTop = arrayPageScroll[1] + (document.viewport.getHeight() / (100 / this.lbxPopupHeightPercentage));
        var lightboxLeft = arrayPageScroll[0];
        $(this.lbxPopContainerDivId).setStyle({ top: lightboxTop + 'px', left: lightboxLeft + 'px' }).show();

        this.changeImage();
    },

    //
    //  changeImage()
    //  Hide most elements and preload image in preparation for resizing image container.
    //
    changeImage: function() {

        // hide elements during transition
        $(this.lbxPopInnerContainerId).hide();

        this.resizeImageContainer();
    },

    //
    //  resizeImageContainer()
    //
    resizeImageContainer: function() {

        // toWidth
        var widthNew = $(this.lbxPopBackgroundId).getWidth();
        var heightNew = $(this.lbxPopBackgroundId).getHeight();

        // get current width and height and reset container
        $(this.lbxPopBackgroundId).setStyle({ width: 25 + 'px', height: 25 + 'px', backgroundColor: this.lbxFadeInBackgroundColor });
        var widthCurrent = 25;
        var heightCurrent = 25;

        // 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.lbxPopBackgroundId, yScale, { scaleX: false, duration: this.resizeDuration, queue: 'front', scaleContent: false });
        if (wDiff != 0) new Effect.Scale(this.lbxPopBackgroundId, xScale, { scaleY: false, duration: this.resizeDuration, delay: this.resizeDuration, scaleContent: false, afterFinish: (function() { $(this.lbxPopBackgroundId).setStyle({ backgroundColor: this.lbxFadeFinishBackgroundColor }); }).bind(this) });

        // 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;
        }

        (function() {
            this.showImage();
        }).bind(this).delay(timeout / 1000);
    },

    //
    //  showImage()
    //  Display image and begin preloading neighbors.
    //
    showImage: function() {
        new Effect.Appear(this.lbxPopInnerContainerId, {
            duration: this.resizeDuration,
            queue: 'end'
        });
    },


    //
    //  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.lbxPopContainerDivId).hide();
        new Effect.Fade(this.lbxOverlayDivId, { duration: this.overlayDuration });
        $$('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 + (document.documentElement.scrollHeight - 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 () { new Lightbox(); });