﻿DisplayboxOptions = Object.extend({

}, window.DisplayboxOptions || {});

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

var Displaybox = Class.create();

Displaybox.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
		, RelId
    ) {
        //Make Globals
        this.dspOverlayDivId = OverlayDivId;
        this.dspPopContainerDivId = PopContainerDivId;
        this.dspPopBackgroundId = PopBackgroundId;
        this.dspPopFadeInId = PopFadeInId;
        this.dspPopInnerContainerId = PopInnerContainerId;
        this.dspAnimate = Animate;
        this.dspResizeSpeed = ResizeSpeed;
        this.dspOverlayOpacity = OverlayOpacity;
        this.dspFadeInBackgroundColor = FadeInBackgroundColor;
        this.dspFadeFinishBackgroundColor = FadeFinishBackgroundColor;
        this.dspPopupHeightPercentage = PopupHeightPercentage;
        this.dspCloseButtons = CloseButtons;
        this.dspRelId = RelId;

        this.updateImageList();

        this.keyboardAction = this.keyboardAction.bindAsEventListener(this);

        if (this.dspResizeSpeed > 10) this.dspResizeSpeed = 10;
        if (this.dspResizeSpeed < 1) this.dspResizeSpeed = 1;

        this.resizeDuration = this.dspAnimate ? ((11 - this.dspResizeSpeed) * 0.15) : 0;
        this.overlayDuration = this.dspAnimate ? 0.2 : 0;  // shadow fade in/out duration

        // When Displaybox 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.dspAnimate ? 250 : 1) + 'px';

        var objBody = $$('body')[0];

        $(this.dspOverlayDivId).hide().observe('click', (function() { this.end(); }).bind(this));
        $(this.dspPopContainerDivId).hide().observe('click', (function(event) { if (event.element().id == this.dspPopContainerDivId) this.end(); }).bind(this));

        //Close Buttons
        if (this.dspCloseButtons != null) {
            for (i = 0; i < this.dspCloseButtons.length; i++) {
                $(this.dspCloseButtons[i]).observe('click', (function(event) { this.end(); }).bind(this));
            }
        }

        var th = this;
        (function() {
            var ids =
                this.dspOverlayDivId + ' ' + this.dspPopContainerDivId + ' ' + this.dspPopBackgroundId + ' ' + this.dspPopInnerContainerId;
            $w(ids).each(function(id) { th[id] = $(id); });
        }).defer();
    },

    //
    // updateImageList()
    // Loops through anchor tags looking for 'Displaybox' 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^=' + this.dspRelId + ']') || event.findElement('area[rel^=' + this.dspRelId + ']');
            if (target) {
                event.stop();
                this.start(target);
            }
        }).bind(this));
    },

    //
    //  start()
    //  Display overlay and Displaybox. 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.dspOverlayDivId).setStyle({ width: arrayPageSize[0] + 'px', height: arrayPageSize[1] + 'px' });

        new Effect.Appear(this.dspOverlayDivId, { duration: this.overlayDuration, from: 0.0, to: this.dspOverlayOpacity });

        // calculate top and left offset for the Displaybox 
        var arrayPageScroll = document.viewport.getScrollOffsets();
        var DisplayboxTop = arrayPageScroll[1] + (document.viewport.getHeight() / (100 / this.dspPopupHeightPercentage));
        var DisplayboxLeft = arrayPageScroll[0];
        $(this.dspPopContainerDivId).setStyle({ top: DisplayboxTop + 'px', left: DisplayboxLeft + 'px' }).show();

        this.changeImage();
    },

    //
    //  changeImage()
    //  Hide most elements and preload image in preparation for resizing image container.
    //
    changeImage: function() {

        // hide elements during transition
        $(this.dspPopInnerContainerId).hide();

        this.resizeImageContainer();
    },

    //
    //  resizeImageContainer()
    //
    resizeImageContainer: function() {

        // toWidth
        var widthNew = $(this.dspPopBackgroundId).getWidth();
        var heightNew = $(this.dspPopBackgroundId).getHeight();

        // get current width and height and reset container
        $(this.dspPopBackgroundId).setStyle({ width: 25 + 'px', height: 25 + 'px', backgroundColor: this.dspFadeInBackgroundColor });
        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.dspPopBackgroundId, yScale, { scaleX: false, duration: this.resizeDuration, queue: 'front', scaleContent: false });
        if (wDiff != 0) new Effect.Scale(this.dspPopBackgroundId, xScale, { scaleY: false, duration: this.resizeDuration, delay: this.resizeDuration, scaleContent: false, afterFinish: (function() { $(this.dspPopBackgroundId).setStyle({ backgroundColor: this.dspFadeFinishBackgroundColor }); }).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() {
        //$(this.dspOverlayDivId).style.display = 'block';
        new Effect.Appear(this.dspPopInnerContainerId, {
            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 Displaybox
            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.dspPopContainerDivId).hide();
        new Effect.Fade(this.dspOverlayDivId, { 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
            //alert('IE7');
            xScroll = document.body.offsetWidth;
            yScroll = document.body.offsetHeight + document.body.scrollHeight;
        }

        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 () { new Displaybox(); });
