// -----------------------------------------------------------------------------------
//
//	Videobox 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

    Videobox Class Declaration
    - initialize()
    - updateVideoList()
    - start()
    - resizeVideoContainer()
    - showVideo()
    - updateDetails()
    - end()
    
    Function Calls
    - document.observe()
   
*/
// -----------------------------------------------------------------------------------

//
//  Configurationl
//
VideoboxOptions = 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.VideoboxOptions || {});

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

var Videobox = Class.create();

Videobox.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 video container.
    initialize: function(){
        this.updateVideoList();
        
        if (VideoboxOptions.resizeSpeed > 10)   VideoboxOptions.resizeSpeed = 10;
        if (VideoboxOptions.resizeSpeed < 1)    VideoboxOptions.resizeSpeed = 1;
        
        this.resizeDuration = VideoboxOptions.animate ? ((11 - VideoboxOptions.resizeSpeed) * 0.15) : 0;
        this.overlayDuration = VideoboxOptions.animate ? 0.2 : 0;    // shadow fade in/out duration
        
        // When Videobox starts it will resize itself from 250 by 250 to the current video dimension
        // If animations are turned off, it will be hidden as to prevent a flicker of a
        // white 250 by 250 box.
        var size = (VideoboxOptions.animate ? 250 : 1) + 'px';

        // Code inserts html at the bottom of the page that looks similar to this:
        //
        //  <div id="videobox">
        //      <div id="outerVideoContainer">
        //          <div id="VideoContainer">
        //              <div id="videoboxVideo">
        //              </div>
        //          </div>
        //      </div>
        //      <div id="videoDataContainer">
        //          <div id="videoData">
        //              <div id="videoDetails">
        //                  <span id="videobox_caption"></span>
        //                  <span id="urlDisplay"></span>
        //              </div>
        //              <div id="videobox_bottomNav">
        //                  <a href="#" id="videobox_bottomNavClose">
        //                      <img src="images/close.gif">
        //                  </a>
        //              </div>
        //          </div>
        //      </div>


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

        objBody.appendChild(Builder.node('div',{id:'videobox'}, [
            Builder.node('div',{id:'outerVideoContainer'}, 
                Builder.node('div',{id:'videoContainer'}, [
                    Builder.node('div',{id:'videoboxVideo', style: 'z-index: 99' })
                ])
            ),
            Builder.node('div', {id:'videoDataContainer'},
                Builder.node('div',{id:'videoData'}, [
                    Builder.node('div',{id:'videoDetails'}, [
                        Builder.node('span',{id:'videobox_caption'}),
                        Builder.node('span',{id:'urlDisplay'})
                    ]),
                    Builder.node('div',{id:'videobox_bottomNav'},
                        Builder.node('a',{id:'videobox_bottomNavClose', href: '#' },
                            Builder.node('img', { src: VideoboxOptions.fileBottomNavCloseImage })
                        )
                    )
                ])
            )
        ]));


		$('videobox_overlay').hide().observe('click', (function() { this.end(); }).bind(this));
		$('videobox').hide().observe('click', (function(event) { if (event.element().id == 'videobox') this.end(); }).bind(this));
		$('outerVideoContainer').setStyle({ width: size, height: size });
		$('videobox_bottomNavClose').observe('click', (function(event) { event.stop(); this.end(); }).bind(this));

        var th = this;
        (function(){
            var ids = 
                'videobox_overlay videobox outerVideoContainer videoContainer videoboxVideo videoDataContainer ' + 
                'videoData videoDetails videobox_caption urlDisplay videobox_bottomNav videobox_bottomNavClose';   
            $w(ids).each(function(id){ th[id] = $(id); });
        }).defer();

    },

    //
    // updateVideoList()
    // Loops through anchor tags looking for 'video' references and applies onclick
    // events to appropriate links. You can rerun after dynamically adding videos w/ajax.
    //
    updateVideoList: function() {   
        this.updateVideoList = Prototype.emptyFunction;
        
        $$('a[rel="videobox"]').each(function(video){
            videoId = video.href.split('=');
            videoId = videoId[1];
            video.replace(
                Builder.node('a', {href: video.href, rel: video.rel, title: video.title},
                    Builder.node('img', {src: "http://i.ytimg.com/vi/" + videoId + "/default.jpg", alt: "Click here"})
                )
            )
        });

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

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

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

        new Effect.Appear(this.videobox_overlay, { duration: this.overlayDuration, from: 0.0, to: VideoboxOptions.overlayOpacity });
        
        // setup SWFObject for embed
        this.videoURL = videoLink.href;
        var videoId = this.videoURL.split('=');
        this.videoId = videoId[1];
        this.so = new SWFObject("http://www.youtube.com/v/" + this.videoId, "videobox", 425, 344, "0");
        this.so.addParam("wmode", "transparent");
        this.so.addParam("allowfullscreen", "true");
        this.so.addVariable("fs", "1");
        this.so.setAttribute("id", "videoEmbed");
        
        // Get caption if available.
        this.videoCaption = videoLink.title;

        // calculate top and left offset for the lightbox 
        var arrayPageScroll = document.viewport.getScrollOffsets();
        var videoboxTop = arrayPageScroll[1] + (document.viewport.getHeight() / 10);
        var videoboxLeft = arrayPageScroll[0];
        this.videobox.setStyle({ top: videoboxTop + 'px', left: videoboxLeft + 'px' }).show();
        
        this.videoDataContainer.setStyle({opacity: .0001});
        this.urlDisplay.hide();
        
        this.resizeVideoContainer(435, 344);
    },

    //
    //  resizVideoContainer()
    //
    resizeVideoContainer: function(vidWidth, vidHeight) {

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

        // get new width and height
        var widthNew  = (vidWidth  + VideoboxOptions.borderSize * 2);
        var heightNew = (vidHeight + VideoboxOptions.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.outerVideoContainer, yScale, {scaleX: false, duration: this.resizeDuration, queue: 'front'}); 
        if (wDiff != 0) new Effect.Scale(this.outerVideoContainer, 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.videoDataContainer.setStyle({ width: widthNew + 'px' });
        }).bind(this).delay(timeout / 1000);
        
        new Effect.Appear(this.videoboxVideo, { 
            duration: this.resizeDuration, 
            queue: 'end', 
            afterFinish: (function(){ this.updateDetails(); }).bind(this) 
        });
    },
    
    //
    //  showVideo()
    //  Display video.
    //
    showVideo: function(){
        this.so.write("videoboxVideo");
        new Effect.Appear(this.videoboxVideo, { 
            duration: this.resizeDuration, 
            queue: 'end'
        });
    },

    //
    //  updateDetails()
    //  Display caption, video url, and bottom nav.
    //
    updateDetails: function() {
    
        // if caption is not null
        this.videobox_caption.update(this.videoCaption).show();
        this.urlDisplay.update(this.videoURL).show();

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

    //
    //  end()
    //
    end: function() {
        this.videobox.hide();
        new Effect.Fade(this.videobox_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 Videobox(); });