//++
//	GE Lightbox for images, flash and Brightcove video.
//	author: kyle.crouse@frogdesign.com
//	inspired by: http://www.huddletogether.com/projects/lightbox2/
//++
//	4/7/2009 - created
//++
var GE_Lightbox = Class.create({
	beginLoadingContent:function(a) {
		//++
		//	enable loading graphic and determine type of asset to display
		//++
		GE_Lightbox.centerInViewport(this.loading);
		this.loading.setStyle({display:'block',opacity:'1'});
		if (a.rel=='video') { this.fetchData(a); }
		else if (a.rel=='image') { this.fetchImage(a); }
		else if (a.rel=='flash') { this.fetchFlash(a); }
		else { } //TODO: add failure method
	},
	buildErrorMsg:function(msg){
		//++
		//	create html for displaying error message in lightbox after failed bc connect
		//++
		this.lightbox
			.insert( new Element('h2').insert('Video Player') )
			.insert( new Element('p').addClassName('errorMsg').insert(msg) );
	},
	buildFlash:function(url){
		//++
		//	create object/embed for swf
		//++
		this.lightbox
			.insert( new Element('h2').insert('Flash Viewer') )
			.insert( new Element('div',{id:'swfobject'}) );
		var flashvars = {}; 
		var params = {}; 
		params.bgcolor = '#FFFFFF';
		var attributes = {}; 
		swfobject.embedSWF(url, 'swfobject', '685', '386', '9', null, flashvars, params, attributes);
	},
	buildImage:function(img){
		//++
		//	create html for image
		//++
		this.lightbox
			.insert( new Element('h2').insert('Image Viewer') )
			.insert( img );
	},
	buildPlayer:function(data){
		//++
		//	create html for video player
		//++
		var player = new Element('div').addClassName('player').insert( new Element('div',{id:'lb-player'}) );
		var meta = new Element('div').addClassName('meta').insert( new Element('h2').insert('Video Player') ).insert( new Element('h4').insert(data.name) ).insert( data.longDescription );
		if (data.transcript) meta.insert( new Element('p').insert( new Element('a',{href:data.transcript,title:'View Transcript (opens in new window)'}).addClassName('asset_link transcript').insert('View Transcript').observe('click',function(e){e.stop(); window.open(this.href, '', 'width=618,height=750,toolbar=0,scrollbars=1,location=0,menubar=0,resizable=0'); }) ) );
		if (data.links.length>0) {
			var ul = new Element('ul');
			for (var i=0;i<data.links.length;i++) { ul.insert( new Element('li').insert( new Element('a',{href:data.links[i].url}).insert(data.links[i].name) ) ); }
			meta.insert( new Element('h5').insert('More Information') ).insert( ul );
		}
		this.lightbox.insert( player ).insert( meta );
		inspectLinks(meta.select('a'));
		var flashvars = {}; 
		flashvars.playerID = 18808692001;
		flashvars.publisherID = 2133339001;
		flashvars.videoID = data.id;
		flashvars.width = '480';
		flashvars.height = '360';
		var params = {}; 
		params.bgcolor = '#000000';
		params.allowScriptAccess = 'always';
		params.allowFullScreen = 'true';
		params.wmode = 'transparent';
		var attributes = {}; 
		swfobject.embedSWF('http://files.gecompany.com/gecom/tools/GEVideoPlayer.swf', 'lb-player', '100%', '100%', '9', null, flashvars, params, attributes);
	},
	disableKeyboardNav:function() {
		//++
		//	removing bindings for keyboard navigation
		//++
		document.onkeydown = '';
	},
	destroyLightbox:function(){
		//++
		//	remove contents of lightbox for next load
		//++
		this.lightbox.update( this.close_link );
	},
	enableKeyboardNav: function() {
		//++
		//	bind keyboard shortcuts for closing lightbox
		//++
		document.onkeydown = function(e) {
			var keycode;
			if (e == null) { keycode = event.keyCode; } // ie
			else { keycode = e.which; } // mozilla
			var key = String.fromCharCode(keycode).toLowerCase();
			if( (key == 'x') || (key == 'o') || (key == 'c') ) { this.end(); } // close lightbox
		}.bindAsEventListener(this);
	},
	end: function() {
		//++
		//	call functions to close lightbox and restore screen
		//++
		this.disableKeyboardNav();
		GE_Lightbox.stopPlayer();
		this.hideLightbox();
		GE_Lightbox.showSelectBoxes();
	},
	fetchData:function(a){
		//++
		//	get data elements from brightcove and launch process
		//++
		var self = this;
		var href = unescape(a.href);
		var refID = href.substring(href.lastIndexOf('/')+1,href.indexOf('.html'));
		var url = GE_baselink+'html_view/jsp/request_proxy.jsp?url='+encodeURIComponent('http://api.brightcove.com/services/library?command=find_video_by_reference_id&video_fields=id,name,longDescription&reference_id='+refID+'&token=XnxHraRgNso9q5yQza2atYYMSxJTtTsUoN0in3gGD2M.');
		new Ajax.Request(url,{
			onFailure:function(){
				var msg = 'We&rsquo;re sorry, but we are unable to load the requested video at this time.  Please try again later.';
				self.buildErrorMsg(msg);
			},
			onSuccess:function(response){
				var data = response.responseText.evalJSON();
				if (data.error) {
					var msg = '';
					if (data.code=='301') msg = 'We&rsquo;re sorry, but we are unable to load the requested video at this time.  Please try again later.';
					self.buildErrorMsg(msg);
				} else {
					try {
						var longDescJSON = data.longDescription.evalJSON();
						data.links = longDescJSON.related_links;
						data.transcript = longDescJSON.transcript;
						data.longDescription = longDescJSON.description;
					} catch(e) { 
						data.longDescription = '';
						data.transcript = '';
						data.links = []; 
					}
					self.buildPlayer(data);
				}
				self.showLightbox();
			}
		});
	},
	fetchFlash:function(a){
		//++
		//	get flash file and launch process
		//++
		var swf = unescape(a.href);
		this.buildFlash(swf);
		this.showLightbox();
	},
	fetchImage:function(a){
		//++
		//	get requested image and launch process
		//++
		var self = this;
		var img = new Image();
		img.src = unescape(a.href);
		img.alt = a.title;
		img.onload = function(){ self.buildImage(this); self.showLightbox(); };
	},
	hideLightbox:function(){
		//++
		//	fade outlightbox and restore screen
		//++
		var self = this;
		new Effect.Parallel( [
				new Effect.Appear(this.lightbox,{from:1.0,to:0.0,sync:true}),
				new Effect.Appear(this.overlay,{from:0.8,to:0.0,sync:true}),
				new Effect.Morph(this.htmlEl,{style:'background-color:#e8ebef',sync:true})
			],
			{ 
				afterFinish:function(){
					self.lightbox.setStyle({display:'none'});
					self.loading.setStyle({display:'none'});
					self.overlay.setStyle({display:'none'});
					self.destroyLightbox();
				},
				duration:0.2
			}
		);
	},
	initialize:function(){
		//++
		//	create and insert lightbox elements and bind event listeners to window
		//++ 
		var self = this;
		this.htmlEl = $(document.documentElement);
		this.overlay = new Element('div',{title:'click to close this layer'}).addClassName('lb-overlay').setStyle({display:'none'}).observe('click', function(e) { self.end(); e.stop(); });
		this.loading = new Element('div',{title:'click to close this layer'}).addClassName('lb-loading').setStyle({display:'none'}).observe('click', function(e) { self.end(); e.stop(); });
		this.lightbox = new Element('div').addClassName('lb-content').setStyle({display:'none'})
			.insert( this.close_link = new Element('a',{href:'#',title:'close this layer'}).addClassName('close').observe('click',function(e) { self.end(); e.stop(); }) );
		document.body.appendChild(this.overlay);
		document.body.appendChild(this.loading);
		document.body.appendChild(this.lightbox);
		Event.observe(window,'unload',GE_Lightbox.stopPlayer);
		Event.observe(window,'resize',this.positionOverlay.bind(this));
	},
	positionOverlay:function(){
		//++
		//	set overlay height to match body height
		//++
		this.overlay.setStyle({height:$(document.body).getHeight()+'px'});
	},
	showLightbox:function(){
		//++
		//	get position, fade out loading and fade in lightbox
		//++
		var self = this;
		new Effect.Parallel([
				new Effect.Appear(this.loading,{from:1.0,to:0.0,sync:true}),
				new Effect.Appear(this.lightbox,{from:0.0,to:1.0,sync:true})
			],{
				beforeStart:function(){
					GE_Lightbox.centerInViewport(self.lightbox);
					self.lightbox.setOpacity(0).setStyle({display:'block'});
				},
				afterFinish:function(){
					self.loading.setStyle({display:'none'});
					self.enableKeyboardNav();
				},
				duration:0.2
			}
		);
	},
	start:function(a){
		//++
		//	setup screen, display loading and call data fetch
		//++
		var self = this;
		GE_Lightbox.hideSelectBoxes();
		this.positionOverlay();
		new Effect.Parallel([
				new Effect.Appear(this.overlay,{from:0.0,to:0.8,sync:true}),
				new Effect.Morph(this.htmlEl,{style:'background-color:#2e2f30',sync:true})
			],{ 
				beforeStart:function(){
					self.overlay.setOpacity(0).setStyle({display:'block'});
				},
				afterFinish:function() {
					self.beginLoadingContent(a);
				},
				duration:0.2
			}
		);
		GE_Lightbox.trackLightbox(a.href,'start');
	}
});
GE_Lightbox._instance = null;
GE_Lightbox.centerInViewport = function(el){
	//++
	//	center the element within the viewport by updating css top property
	//++
	var h = (el.getHeight()+30)/2;
	var scrollY = document.viewport.getScrollOffsets().top;
	var winHeight = document.viewport.getHeight();
	var top = (scrollY+((winHeight/2) - h));
	el.setStyle({top:(top<0?0:top)+'px'});
};
GE_Lightbox.getInstance = function() {
	//++
	//	create/return a single instance of lightbox
	//++
	if (GE_Lightbox._instance == null) GE_Lightbox._instance = new GE_Lightbox();
	return GE_Lightbox._instance;
};
GE_Lightbox.hideSelectBoxes = function(){
	//++
	//	hide all select elements on the page
	//++
	var els = document.getElementsByTagName('select');
	$A(els).each( function(el){ el.hide(); } );
};
GE_Lightbox.launchExternal = function(rel,href){
	//++
	//	launch lightbox player from an external source
	//++
	var a = new Element('a',{href:href+'.html',rel:rel});
	GE_Lightbox.getInstance().start(a);
};
GE_Lightbox.showSelectBoxes = function(){
	//++
	//	show all select elements on the page
	//++
	var els = document.getElementsByTagName('select');
	$A(els).each( function(el){ el.show(); } );
};
GE_Lightbox.stopPlayer = function(){
	//++
	//	find and stop video player for metrics reporting
	//++
	var p = null;
	if (navigator.appName.indexOf("MSIE") != -1) { p = window['lb-player']; } 
	else { p = document['lb-player']; }
	// if (typeof p.stopVideo!='undefined') { p.stopVideo(); }
};
GE_Lightbox.trackLightbox = function(name,action){
	//++
	//	send omniture call for lightbox activity
	//++
	if (typeof trackFlashPage!='undefined') trackFlashPage(true,'o','lightbox | '+name+' | '+action);
};
GE_Main.mapCSSToFn('lightbox', function(el) {
	//++
	//	instantiate lightbox and convert links with the class 'lightbox' to open the layer
	//++ 
	$(el).observe("click", function(e) { e.stop(); GE_Lightbox.getInstance().start(this); } );	
});

var getPlayer = function() {
	if (navigator.appName.indexOf("MSIE") != -1) {
		return window['lb-player'];
	} else {
		return $('lb-player');
	}
};
var expandVideoPlayer = function() {
	var player = $(getPlayer());
	var mediaEl = player.up('div');
	var containerEl = mediaEl.up('div'); 
	var canvasEl = new Element('div',{id:'ge-video-canvas'});
	var bg = '000';
	canvasEl.setStyle({backgroundColor:'#'+bg,height:'476px',left:'0',opacity:'0.0',position:'absolute',top:'0',width:'685px',zIndex:'2'});
	containerEl.insert(canvasEl);
	new Effect.Parallel(
		[	new Effect.Appear(canvasEl,{from:0.0,sync:true,to:1.0}),
			new Effect.Morph(containerEl,{style:'height:476px',sync:true})
		],
		{	beforeStart:function(){
				mediaEl.setStyle({opacity:0.0});
			},
			afterFinish:function(){
				//player.onPlayerResized(600,476);
				mediaEl.setStyle({clip:'rect(0px,685px,476px,0px)',opacity:1.0,zIndex:'3'});
			},
			duration: 0.2
		}
	);
};
var collapseVideoPlayer = function() {
	var player = $(getPlayer());
	var mediaEl = player.up('div');
	var containerEl = mediaEl.up('div'); 
	var canvasEl = $('ge-video-canvas');

	mediaEl.setStyle({clip:'rect(0px,480px,386px,0px)',zIndex:'1'});
	containerEl.setStyle({height:'386px'});
	canvasEl.remove();
};