// -----------------------------------------------------------------------------------
//
//	Flash v2.04
//	by Yong Jie - http://yjwong.blogspot.com/
//	Last Modification: 6/6/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: Lokesh Dhaka for Lightbox v2.04
//
// -----------------------------------------------------------------------------------
/*

    Table of Contents
    -----------------
    Configuration

    Flashbox Class Declaration
    - initialize()
    - updateFlashList()
    - start()
    - resizeFlashContainer()
    - showFlash()
    - updateDetails()
    - end()
    
    Function Calls
    - document.observe()
   
*/
// -----------------------------------------------------------------------------------

//
//  Configurationl
//
FlashboxOptions = Object.extend({
    fileLoadingImage:        'http://roregister.net/images/blog/lightbox/images/loading.gif',
    fileBottomNavCloseImage: 'http://roregister.net/images/blog/lightbox/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: 10          // if you adjust the padding in the CSS, you will need to update this variable
}, window.FlashboxOptions || {});

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

var Flashbox = Class.create();

Flashbox.prototype = {
    // initialize()
    // Constructor runs on completion of the DOM loading.
    // The function inserts html at the bottom of the page which is used to display the shadow
    // overlay and the flash container.
    initialize: function(){
        this.updateFlashList();
        
        if (FlashboxOptions.resizeSpeed > 10)   FlashboxOptions.resizeSpeed = 10;
        if (FlashboxOptions.resizeSpeed < 1)    FlashboxOptions.resizeSpeed = 1;
        
        this.resizeDuration = FlashboxOptions.animate ? ((11 - FlashboxOptions.resizeSpeed) * 0.15) : 0;
        this.overlayDuration = FlashboxOptions.animate ? 0.2 : 0;    // shadow fade in/out duration
        
        // When Flashbox starts it will resize itself from 250 by 250 to the current flash dimension
        // If animations are turned off, it will be hidden as to prevent a flicker of a
        // white 250 by 250 box.
        var size = (FlashboxOptions.animate ? 250 : 1) + 'px';

        // Code inserts html at the bottom of the page that looks similar to this:
        //
        //  <div id="flashbox">
        //      <div id="outerFlashContainer">
        //          <div id="FlashContainer">
        //              <div id="flashboxFlash">
        //              </div>
        //          </div>
        //      </div>
        //      <div id="flashDataContainer">
        //          <div id="flashData">
        //              <div id="flashDetails">
        //                  <span id="flashbox_caption"></span>
        //                  <span id="urlDisplay"></span>
        //              </div>
        //              <div id="flashbox_bottomNav">
        //                  <a href="#" id="flashbox_bottomNavClose">
        //                      <img src="images/close.gif">
        //                  </a>
        //              </div>
        //          </div>
        //      </div>


        var objBody = $$('body')[0];
        
        objBody.appendChild(Builder.node('div',{id:'flashbox_overlay'}));

        objBody.appendChild(Builder.node('div',{id:'flashbox'}, [
            Builder.node('div',{id:'outerFlashContainer'}, 
                Builder.node('div',{id:'flashContainer'}, [
                    Builder.node('div',{id:'flashboxFlash', style: 'z-index: 99' })
                ])
            ),
            Builder.node('div', {id:'flashDataContainer'},
                Builder.node('div',{id:'flashData'}, [
                    Builder.node('div',{id:'flashDetails'}, [
                        Builder.node('span',{id:'flashbox_caption'}),
                        Builder.node('span',{id:'urlDisplay'})
                    ]),
                    Builder.node('div',{id:'flashbox_bottomNav'},
                        Builder.node('a',{id:'flashbox_bottomNavClose', href: '#' },
                            Builder.node('img', { src: FlashboxOptions.fileBottomNavCloseImage })
                        )
                    )
                ])
            )
        ]));


		$('flashbox_overlay').hide().observe('click', (function() { this.end(); }).bind(this));
		$('flashbox').hide().observe('click', (function(event) { if (event.element().id == 'flashbox') this.end(); }).bind(this));
		$('outerFlashContainer').setStyle({ width: size, height: size });
		$('flashbox_bottomNavClose').observe('click', (function(event) { event.stop(); this.end(); }).bind(this));

        var th = this;
        (function(){
            var ids = 
                'flashbox_overlay flashbox outerFlashContainer flashContainer flashboxFlash flashDataContainer ' + 
                'flashData flashDetails flashbox_caption urlDisplay flashbox_bottomNav flashbox_bottomNavClose';   
            $w(ids).each(function(id){ th[id] = $(id); });
        }).defer();

    },

    //
    // updateFlashList()
    // Loops through anchor tags looking for 'flash' references and applies onclick
    // events to appropriate links. You can rerun after dynamically adding flash w/ajax.
    //
    updateFlashList: function() {   
        this.updateFlashList = Prototype.emptyFunction;

        document.observe('click', (function(event){
            var target = event.findElement('a[rel^=flashbox]');
            if (target) {
                event.stop();
                this.start(target);
            }
        }).bind(this));
    },
    
    //
    //  start()
    //  Display overlay and flash.
    //
    start: function(flashLink) {    

        $$('select', 'object', 'embed').each(function(node){ node.style.visibility = 'hidden' });

        // stretch overlay to fill page and fade in
        var arrayPageSize = this.getPageSize();
        $('flashbox_overlay').setStyle({ width: arrayPageSize[0] + 'px', height: arrayPageSize[1] + 'px' });

        new Effect.Appear(this.flashbox_overlay, { duration: this.overlayDuration, from: 0.0, to: FlashboxOptions.overlayOpacity });
        
        // setup SWFObject for embed
        this.flashURL = flashLink.href;
        this.so = new SWFObject(this.flashURL, "flashbox", 1024, 768, "0");
        this.so.setAttribute("id", "flashEmbed");

        // Get caption if available.
        this.flashCaption = flashLink.title;

        // calculate top and left offset for the lightbox 
        var arrayPageScroll = document.viewport.getScrollOffsets();
        var flashboxTop = arrayPageScroll[1] + (document.viewport.getHeight() / 10);
        var flashboxLeft = arrayPageScroll[0];
        this.flashbox.setStyle({ top: flashboxTop + 'px', left: flashboxLeft + 'px' }).show();
        
        this.flashDataContainer.setStyle({opacity: .0001});
        this.urlDisplay.hide();
        
        this.resizeFlashContainer(1034, 768);
    },

    //
    //  resizFlashContainer()
    //
    resizeFlashContainer: function(flaWidth, flaHeight) {

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

        // get new width and height
        var widthNew  = (flaWidth  + FlashboxOptions.borderSize * 2);
        var heightNew = (flaHeight + FlashboxOptions.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.outerFlashContainer, yScale, {scaleX: false, duration: this.resizeDuration, queue: 'front'}); 
        if (wDiff != 0) new Effect.Scale(this.outerFlashContainer, xScale, {scaleY: false, duration: this.resizeDuration, delay: this.resizeDuration}); 

        var timeout = 0;
        if ((hDiff == 0) && (wDiff == 0)){
            timeout = 100;
            if (Prototype.Browser.IE) timeout = 250;   
        }
        
        (function(){
            this.flashDataContainer.setStyle({ width: widthNew + 'px' });
        }).bind(this).delay(timeout / 1000);
        
        new Effect.Appear(this.flashboxFlash, { 
            duration: this.resizeDuration, 
            queue: 'end', 
            afterFinish: (function(){ this.updateDetails(); }).bind(this) 
        });
    },
    
    //
    //  showFlash()
    //  Display flash.
    //
    showFlash: function(){
        this.so.write("flashboxFlash");
        new Effect.Appear(this.flashboxFlash, { 
            duration: this.resizeDuration, 
            queue: 'end'
        });
    },

    //
    //  updateDetails()
    //  Display caption, flash url, and bottom nav.
    //
    updateDetails: function() {
    
        // if caption is not null
        this.flashbox_caption.update(this.flashCaption).show();
        this.urlDisplay.update(this.flashURL).show();

        new Effect.Parallel(
            [ 
                new Effect.SlideDown(this.flashDataContainer, { sync: true, duration: this.resizeDuration, from: 0.0, to: 1.0 }), 
                new Effect.Appear(this.flashDataContainer, { sync: true, duration: this.resizeDuration }) 
            ], 
            { 
                duration: this.resizeDuration, 
                afterFinish: (function() {
	                // update overlay size and update nav
	                var arrayPageSize = this.getPageSize();
	                this.flashbox_overlay.setStyle({ height: arrayPageSize[1] + 'px' });
                    this.showFlash();
                }).bind(this)
            } 
        );
    },

    //
    //  end()
    //
    end: function() {
        this.flashbox.hide();
        new Effect.Fade(this.flashbox_overlay, { 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;
		} 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 Flashbox(); });