// -----------------------------------------------------------------------------------
//
//    Lightbox v2.04
//    by Lokesh Dhakar - http://www.lokeshdhakar.com
//    Last Modification: 2/9/08
//
//    For more information, visit:
//    http://lokeshdhakar.com/projects/lightbox2/
//
//    Licensed under the Creative Commons Attribution 2.5 License - http://creativecommons.org/licenses/by/2.5/
//      - Free for use in both personal and commercial projects
//        - Attribution requires leaving author name, author link, and the license info intact.
//    
//  Thanks: Scott Upton(uptonic.com), Peter-Paul Koch(quirksmode.com), and Thomas Fuchs(mir.aculo.us) for ideas, libs, and snippets.
//          Artemy Tregubenko (arty.name) for cleanup and help in updating to latest ver of proto-aculous.
//
// -----------------------------------------------------------------------------------

//
//  Configurationl
//
LightboxOptions = Object.extend({
    fileLoadingImage:        'images/loading.gif',     
    fileBottomNavCloseImage: 'images/closelabel.gif',

    overlayOpacity: 0.8,   // controls transparency of shadow overlay

    animate: true,         // toggles resizing animations
    resizeSpeed: 7,        // controls the speed of the image resizing animations (1=slowest and 10=fastest)

    borderSize: 0,         //if you adjust the padding in the CSS, you will need to update this variable

    // When grouping images this is used to write: Image # of #.
    // Change it for non-english localization
    labelImage: "Image",
    labelOf: "of"
}, 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() {    
        if (LightboxOptions.resizeSpeed > 10) LightboxOptions.resizeSpeed = 10;
        if (LightboxOptions.resizeSpeed < 1)  LightboxOptions.resizeSpeed = 1;

        this.resizeDuration = LightboxOptions.animate ? ((11 - LightboxOptions.resizeSpeed) * 0.15) : 0;
        this.overlayDuration = LightboxOptions.animate ? 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 = (LightboxOptions.animate ? 250 : 1) + 'px';
        
        this.idToShow = null;
        

        // Code inserts html at the bottom of the page that looks similar to this:
        //
        //  <div id="overlay"></div>
        //  <div id="lightbox">
        //      <div id="outerImageContainer">
        //          <div id="imageContainer">
        //              <img id="lightboxImage">
        //              <div style="" id="hoverNav">
        //                  <a href="#" id="prevLink"></a>
        //                  <a href="#" id="nextLink"></a>
        //              </div>
        //              <div id="loading">
        //                  <a href="#" id="loadingLink">
        //                      <img src="images/loading.gif">
        //                  </a>
        //              </div>
        //          </div>
        //      </div>
        //      <div id="imageDataContainer">
        //          <div id="imageData">
        //              <div id="imageDetails">
        //                  <span id="caption"></span>
        //                  <span id="numberDisplay"></span>
        //              </div>
        //              <div id="bottomNav">
        //                  <a href="#" id="bottomNavClose">
        //                      <img src="images/close.gif">
        //                  </a>
        //              </div>
        //          </div>
        //      </div>
        //  </div>


        var objBody = $$('body')[0];

        objBody.appendChild(Builder.node('div',{id:'overlay'}));

        $('overlay').hide().observe('click', (function() { this.end(); }).bind(this));
        //$('lightbox').hide().observe('click', (function(event) { if (event.element().id == 'lightbox') this.end(); }).bind(this));
        //$('outerImageContainer').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));
        //$('loadingLink').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 = 
        //        'overlay';   
        //    $w(ids).each(function(id){ th[id] = $(id); });
        //}).defer();
    },

    //
    //  start()
    //  Display overlay and lightbox. If image is part of a set, add siblings to imageArray.
    //
    start: function(newId, param2, param3) {
    
        var baseHeight = $(newId).offsetHeight;
        var baseWidth = $(newId).offsetWidth;
        this.idToShow = newId;    
        if(newId == 'thickbox_graphics')
        {
        
            $$('select', 'object', 'embed').each(function(node){ node.style.visibility = 'hidden' });

            // stretch overlay to fill page and fade in
            var arrayPageSize = this.getPageSize();
            $('overlay').setStyle({ width: arrayPageSize[0] + 'px', height: arrayPageSize[1] + 'px', position: 'fixed', top: '0px', left: '0px', zIndex: '100', backgroundColor: '#000000' });

            new Effect.Appear($('overlay'), { duration: this.overlayDuration, from: 0.0, to: LightboxOptions.overlayOpacity });


            // calculate top and left offset for the lightbox 
            var arrayPageScroll = document.viewport.getScrollOffsets();
            var lightboxTop = (document.viewport.getHeight() - arrayPageScroll[1]) / 2;
            var lightboxLeft = arrayPageScroll[0];
        
            // we expect every thickbox here to be 644x461px
            lightboxLeft = (document.documentElement.clientWidth - 250) / 2;
            lightboxTop = (document.documentElement.clientHeight - 250) / 2;

            $(this.idToShow).setStyle({ top: lightboxTop + 'px', left: lightboxLeft + 'px', width: 208 + 'px', height: 13 + 'px'}).show();
            $(this.idToShow + "_content").hide();
            $(this.idToShow + "_close").hide();
            $(this.idToShow + "_loading").show();
            $(this.idToShow + "_text").innerHTML = param3;
            $(this.idToShow + "_image").src = "";
            this.marginSize = 20;
            
            imgPreloader = new Image();
            imgPreloader.onload = function()
            {
                $(this.prnt.idToShow + "_image").src = imgPreloader.src;
                
                this.prnt.resizeContainer(imgPreloader.width, imgPreloader.height, this.prnt);
            }
            imgPreloader.prnt = this;
            
            imgPreloader.src = param2;
        }
    },

    //
    //  resizeImageContainer()
    //
    resizeContainer: function(imgWidth, imgHeight, prnt) {

        // get current width and height
        var widthCurrent  = $(this.idToShow).getWidth();
        var heightCurrent = $(this.idToShow).getHeight();
        

        // get new width and height
        var widthNew  = imgWidth  + prnt.marginSize * 2 + 30;
        var heightNew = imgHeight + prnt.marginSize * 2 + $(this.idToShow + "_text").getHeight() + $(this.idToShow + "_close").getHeight();
                                                                   
        // 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.idToShow), yScale, {scaleX: false, duration: this.resizeDuration, queue: 'front', scaleContent: false, scaleFromCenter: true}); 
        if (wDiff != 0) new Effect.Scale($(this.idToShow), xScale, {scaleY: false, duration: this.resizeDuration, delay: this.resizeDuration, scaleContent: false, scaleFromCenter: true}); 

        // 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.showContent();
        }).bind(this).delay(this.resizeDuration);
        (function(){

            new Effect.Fade($(this.idToShow + "_loading"), { duration: this.overlayDuration });
        }).bind(this).delay(this.resizeDuration);

    },
    
    showContent: function(){
        new Effect.Appear($(this.idToShow + '_content'), { 
            duration: this.resizeDuration, 
            queue: 'end' 
        });
        new Effect.Appear($(this.idToShow + '_close'), { 
            duration: this.resizeDuration, 
            queue: 'end' 
        });
    },
    
    //
    //  end()
    //
    end: function() {
        $(this.idToShow).hide();
        $(this.idToShow + "_content").hide();
        new Effect.Fade($('overlay'), { duration: this.overlayDuration });
        $$('select', 'object', 'embed').each(function(node){ node.style.visibility = 'visible' });
        
        this.idToShow = null;
    },

    //
    //  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];
    }
};