// Global Variables
// -------------------------------------

// Global SWFObject Variables
var expressInstall = "/nuclear/media/swf/swfobject/expressInstall.swf";
var version = "9.0.115";
var params = { quality: 'autohigh', wmode: 'opaque', bgcolor: '#000000' };
var attributes = {  };
        
// Create Lightbox Elements
var container       = new Element('div', { 'id': 'lightbox-container'}).setStyle({ visibility: 'hidden' });
var overlay         = new Element('div', { 'id': 'overlay' }).setStyle({ display: 'none' });
var lightbox        = new Element('div', { 'id': 'lightbox' }).setStyle({ display: 'none' });
var video           = new Element('div', { 'id': 'video' });
var lightboxBottom  = new Element('div', { 'id': 'lightbox-bottom' });
var videoPlayer     = new Element('div', { 'id': 'player', 'class' : 'close' });
var videoReplace    = new Element('div', { 'id': 'video-replace' });
var videoReplaceP   = new Element('p');
    
var close           = new Element('div', { 'id': 'close-video' });
var closeButton     = new Element('p');

// For Browser Sniffing of IE6
var ua = navigator.userAgent.toLowerCase();
var client = {
    isIE:       ua.indexOf('msie') > -1,
    isIE7:      ua.indexOf('msie 7') > -1 };
var ltIE7 = client.isIE && !client.isIE7;

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

var ceAnchorElementMethods = {
	hasRel: function(element, rel) {
		if (!(element = $(element))) return;
			var elementRel = element.rel;
			return (elementRel.length > 0 && (elementRel == rel ||
				new RegExp("(^|\\s)" + rel + "(\\s|$)").test(elementRel)));
	}
	
};

Element.addMethods('a', ceAnchorElementMethods);

// Anchors
function initAnchor() {
    // Find video name
    if ($('video-player') ) { var videoName = $('video-button').title.slice(9,-6); };
    
	/* Add custom link tracking to all links */
	$(document.body).select('a').invoke('observe', 'click', trackLink);
	
	/* Handle External Links */
    $(document.body).select('a[rel~="external"]').invoke('addClassName', 'external').invoke('writeAttribute', { 'target': '_blank' } )
	
	/* Handle Video Links */
	$(document.body).select('a[type~="application/x-shockwave-flash"]').invoke('observe', 'click', function(e) {
        Event.stop(e);
        $(lightbox.id).visible() ? closeVideo(videoName) : openVideo(videoName);
	});
}

function initVideo() {
    if ($('video-player') ) {
        
        // Create 'close' button for lightbox
        close.appendChild(closeButton);
        
        videoPlayer.appendChild(videoReplaceP);
        videoPlayer.insertBefore(videoReplace, videoReplaceP);
        lightbox.appendChild(close);
        video.appendChild(videoPlayer);
        lightbox.appendChild(video);
        lightbox.appendChild(lightboxBottom);
    	container.appendChild(overlay);
    	container.appendChild(lightbox);
        $(document.body).appendChild(container);
        
        videoReplaceP.replace('<p id="video-backup-text">In order to view this video, please download the latest version of <a rel="external" href="http://get.adobe.com/flashplayer/" title="adobe.com | Adobe - Adobe Flash Player" tabindex="0">Adobe&#x2019;s Flash Player</a></p>');
    }
};

function openVideo(videoName) {    
    // Assign 'flashvars'. 'fparam' is movie name
    var videoUrl = $('video-button').href.split('=')[1];
    var flashvars = { fparam: videoUrl };
    var attributes = { tabindex: '0' }
    
    var topHeight = ((document.documentElement.clientHeight - 515)/2) + 'px';
    window.onresize = function() {
        lightbox.setStyle({ top: ((document.documentElement.clientHeight - 515)/2) + 'px' })
    };
    
    // Make lightbox visible
    container.setStyle({ visibility: 'visible' });
    lightbox.setStyle({ display: 'block', top: topHeight });
    
    // Insert 'close' button into HTML
    close.insertBefore($('video-button'), closeButton);
    
    // Change 'class' and 'title' attributes
    $('video-button').writeAttribute("class", "close");
    $('video-button').writeAttribute("title", "Close the " + videoName + " video");
       
    // Hides the close button on until after the overlay is done loading 
    close.hide();
    
    // Hides backup text for users without Flash installed
    $('video-backup-text').hide();
    
    // Fixes lightbox to to top of the page in IE6
    if (ltIE7) {
        var fixTop = function(){
            container.style.top = document.documentElement.scrollTop + 'px';
        };
        function addEvent(obj, type, fn) {
            if ( obj.attachEvent ) {
                obj['e'+type+fn] = fn;
                obj[type+fn] = function(){obj['e'+type+fn]( window.event );}
                obj.attachEvent('on'+type, obj[type+fn] );
            } else {
                obj.addEventListener( type, fn, false );
            }
        };
        
        addEvent(window, 'scroll', fixTop);
    };

    // Tranisitions for lightbox
    overlay.appear({ duration:0.5, from:0, to:1.0,
        afterFinish : function() {
            close.appear({ duration:0.6, from:0, to:1 });
            videoPlayer.setStyle({ borderColor: '#fff', borderWidth: '3px', borderStyle: 'solid' });
            videoPlayer.morph('height:486px;', { duration: 0.4,
                afterFinish: function() {
                    swfobject.embedSWF('/nuclear/media/swf/player.swf', videoReplace.id, 863, 486, version, expressInstall, flashvars, params, attributes);
                    
                    // Remember to set focus on the 'close' button in order to follow 508 guidelines
                    $('video-button').focus();
                    
                    // Shows backup text for users without Flash installed
                    $('video-backup-text').appear({ duration:0.2, from:0, to:1 });
                }
            });
        } 
    });            
};

function closeVideo(videoName) { 
    // Unload SWF  
    swfobject.removeSWF(videoReplace.id);
    
    // Hides backup text for users without Flash installed
    $('video-backup-text').hide();
    
    // Transitions for 'close' button to become 'Play Video'
    close.fade({ duration:0.6, from:1.0, to:0, 
        afterFinish : function() {
            
            // Change 'class' and 'title' attributes
            $('video-button').writeAttribute("class", "open");
            $('video-button').writeAttribute("title", "Replay the " + videoName + " video");
            $('video-player').appendChild($('video-button'));        
            
            // Show Play Video
            close.appear({ duration:0.6, from:0, to:1 });
        } 
    });
    
    // Transitions for lightbox
    videoPlayer.morph('height:0px;', { duration: 0.4,
        afterFinish: function() {
            videoPlayer.setStyle({ borderWidth: '0px' });
    	    overlay.fade({ duration: 0.8, from: 0.9, to: 0,
    	        afterFinish: function() {
    	            container.setStyle({ visibility: 'hidden' });
    	            overlay.setStyle({ display: 'none', opacity: '0' });
    	            lightbox.setStyle({ display: 'none' });
    	            videoPlayer.appendChild(videoReplace);
    	        } 
    	    });                    
        }
    });  
};

function initLightbox() {
    // Closes lightbox on click outside the movie
    overlay.observe('click', function(e) {
        Event.stop(e);
        closeVideo();
    });
}

function initNukes() {
    if($(document.body).hasClassName('meet') ) {
        new SlideTransition('nukes');
        $('content').select('div.section').invoke('addClassName', 'first-nuke');
    }
};

function initTabbed() {
    if($(document.body).hasClassName('history') || $(document.body).hasClassName('equipment') ) {
        new Fabtabs('tabbed');
    };
};


function initIntroVideo(){	
	if(document.body.hasClassName("home") && $('intro-video') ) {
	    $('intro-video').setStyle({ height:'100%', width:'100%', display: 'block' });
		var width = "100%";
		var height = "100%";
		var flashvars = { fparam: 'intro' };
		
		if(! swfobject.hasFlashPlayerVersion(version)){
		    if (Prototype.Browser.IE) {
		        width = document.documentElement.clientWidth;
		        height = document.documentElement.clientHeight;
		    }
		};
		
		Event.observe($('intro-video-button'), 'click', function(e) {
            Event.stop(e);
            closeIntroVideo(); 
        });
        
        document.getElementsByTagName("html")[0].style.overflow = 'hidden';
        swfobject.embedSWF("/nuclear/media/swf/intro.swf", "intro-video", width, height, version, expressInstall, flashvars, params);
    }
}

function closeIntroVideo(){	
    swfobject.removeSWF($('intro-video'));
	if (Prototype.Browser.IE) {
	    $('intro-video').up().removeChild($('intro-video'));
        document.getElementsByTagName("html")[0].style.overflowY = 'auto';
	} else {
	    $('intro-video').fade({ from:1.0, to:0, duration:1,
            afterFinish : function() {
                $('intro-video').up().removeChild($('intro-video'));
                document.getElementsByTagName("html")[0].style.overflowY = 'auto';
            }
	    });
	}
}



/* DOM Loaded Events */
document.observe('dom:loaded', initAnchor);
document.observe('dom:loaded', initIntroVideo);
document.observe('dom:loaded', initVideo);
document.observe('dom:loaded', initNukes);
document.observe('dom:loaded', initTabbed);

/* Window Loaded Events */
Event.observe(window, 'load', initLightbox, false);