var fileLoadingImage = "/img/bg-loading.gif";
var fileBottomNavCloseImage = "/img/btn-close.gif";
var videoPlayerPath = "/flash/video.swf";

var resizeSpeed = 10;	// controls the speed of the image resizing (1=slowest and 10=fastest)

var GE_MediaOverlay = Class.create( {

	started:false,
	resizeDuration:0,
	captions:false,
	mode:null,
	anchorInfo: {
		el: null,
		href: null,
		title: null,
		rel: null
	},

	initialize: function() {
		if(resizeSpeed > 10){ resizeSpeed = 10;}
		if(resizeSpeed < 1){ resizeSpeed = 1;}
		this.resizeDuration = (11 - resizeSpeed) * 0.15;

		var self = this;
		this.overlay = new Element("div",{className:"overlay",style:"display:none;",title:"click to close"}).observe("click", function(e) { self.end(); e.stop(); });
		this.media_player = new Element("div",{className:"mp_window",style:"display:none;"})
			.insert(
				this.outer_container = new Element("div",{className:"outer_container"})
					.insert(
						this.top_nav = new Element("div",{className:"top_nav"})
							.insert(
								this.close_link = new Element("button",{type:'button'})
									.insert( new Element("img",{src:fileBottomNavCloseImage,alt:"close"}) )
									.setStyle({width:'47px',height:'14px',textAlign:'right',border:'0',background:'transparent'})
									.observe("click",function(e) { self.end(); e.stop(); })
							)
					)
					.insert(
						new Element("div",{className:"content_container"})
							.insert( this.flash_container = new Element("div",{className:"flash_container"}).update("<div style=\"display:none\"></div>"))
							.insert( this.loading = new Element("div",{className:"loading",title:"click to close"}).observe("click", function(e) { self.end(); e.stop(); }) )
					)
					.insert(
						this.meta_container = new Element("div",{className:"meta_container"})
							.insert( this.caption = new Element("span",{className:"caption"}))
					)
			);
		document.body.appendChild(this.overlay);
		document.body.appendChild(this.media_player);
			
		Event.observe( window, "unload", this.unload.bind(this), false);
		Event.observe( window, "resize", this.positionOverlay.bind(this));
		this.started = false;
	},
	
	positionOverlay: function() {
		var overlayHeight = $(document.body).getHeight()+'px';
		this.overlay.setStyle({height:overlayHeight});
	},

	addAnchor: function(a) {
		var self = this;
		$(a).observe("click", function(e) {self.start(this); e.stop();} );
	},

	fetchMediaData:function() {
		var fHref = unescape(this.anchorInfo.href);
		if (fHref.indexOf('http://')==-1) {
			wHref = window.location.href;
			wHref = wHref.substring(0,wHref.lastIndexOf('/')+1);
			fHref = wHref + fHref;
		}
		var filePath = fHref.substring(0,fHref.lastIndexOf('.'));
		var fileName = filePath.substring(filePath.lastIndexOf('/')+1);
		
		var jsonFileName = '/json/'+fileName+".json";
		
		new Ajax.Request( jsonFileName, {
			onSuccess:function(transport) {
				var data = transport.responseText.evalJSON();
				this.mode = data.mode;
				this.initVideo(data);
			}.bind(this),
			onFailure:function() {
				//alert('Error loading video content.');
			}.bind(this)
		});
		
	},

	//
	//	start()
	//	Display overlay and lightbox. If image is part of a set, add siblings to imageArray.
	//
	start: function(a) {

		GE_MediaOverlay.hideSelectBoxes();

		this.anchorInfo = {
			el: $(a),
			href: a.getAttribute('href'),
			title: a.getAttribute('title'),
			rel: a.getAttribute('rel')
		};

		// stretch overlay to fill page and fade in
		this.positionOverlay();
		new Effect.Appear(this.overlay, {
			from: 0.0, 
			to: 0.8,
			duration: 0.2,
			beforeStart:
				function() {
					this.outer_container.setStyle({height:'250px',width:'250px'});
				}.bind(this),
			afterFinish:
				function() {
					var scrollY = document.viewport.getScrollOffsets().top;
					var winHeight = document.viewport.getHeight();
					var lightboxTop = scrollY + ((winHeight / 2) - 125);
					this.media_player.setStyle({top:lightboxTop+'px'});
					this.media_player.show();
					this.resetDisplay();
					this.fetchMediaData();
				}.bind(this)
		});

		this.started = true;
	},

	initVideo: function(data) {
		var mp_width = data.mp_width || 401;
		var mp_height = data.mp_height + 20 || 320;
		
		var flashvars = {};
		flashvars.GE_baselink=GE_baselink;
		flashvars.title=data.title;
		flashvars.flv_path=data.flv_path;
		flashvars.captions_path=data.captions_path;
		flashvars.css_path=data.css_path;
		flashvars.captions_path=data.captions_path;
		flashvars.refresh_rate=data.refresh_rate || 200;

		var params = {};
		params.bgcolor="#000000";
		params.scale="noscale";

		var attributes = {};
		attributes.id="video_player";
		
		swfobject.embedSWF(videoPlayerPath, this.flash_container.down().identify(), mp_width, mp_height, "8",null, flashvars, params, attributes);
		
		this.resizeImageContainer(mp_width,mp_height,function(){
			this.loading.hide();
			this.flash_container.show();
			this.updateDetails();
		}.bind(this));

		//create movie information
		this.meta_container.insert({top:
			this.movie_details = new Element("div",{className:"movie_details"})
				.insert( this.movie_info = new Element("div",{className:"movie_info"}))
				.insert( this.movie_links = new Element("ul",{className:"movie_links"}))
		});
		if (data.title) this.movie_info.insert( new Element("h3",{className:"movie_title"}).insert(data.title) );
		if (data.description) { 
			this.movie_info.insert( 
				new Element("div",{className:"movie_desc"}).insert(data.description)
			);
		}
		if (data.captions_path) {
			this.movie_links.insert( 
				new Element("li",{className:"movie_captions"})
					.insert( 
						this.movie_captions = new Element("a",{href:"#"})
							.insert("Turn on Closed Captioning")
							.observe('click', this.toggleCaptions.bindAsEventListener(this))												
					)
			); 
		}
		if (this.anchorInfo.href.substring(this.anchorInfo.href.lastIndexOf('.'))=='.m4v' && !(this.anchorInfo.el.up('.Television')||data.disable_download)) {
			this.movie_links.insert(
				new Element("li",{className:"movie_download"})
					.insert( new Element("a",{href:this.anchorInfo.href,title:'Download ' + data.title + ' video (M4V)',target:'_blank'}).insert("Download Video (M4V)") )
			);
		}
		if (data.transcript_url) {
			this.movie_links.insert( 
				new Element("li",{className:"movie_transcript"})
					.insert( new Element("a",{href:data.transcript_url,target:'_blank'}).insert( (data.transcript_file_extension)?'Download Transcript (' + data.transcript_file_extension + ')':'Download Transcript (PDF)' ) )
			);								
		}
		if (data.additional_file_url) {
			this.movie_links.insert( 
				new Element("li",{className:"movie_additional"})
					.insert( new Element("a",{href:data.additional_file_url,target:'_blank'}).insert( data.additional_file_name + ' (' + data.additional_file_extension + ')' ) )
			);								
		}
		if (data.more_url) {
			this.movie_details.insert(
				new Element("p",{className:"movie_more"})
					.insert( new Element("a",{href:data.more_url,target:'_blank'}).insert(data.more_text) )
			);
		}
	},
	
	//
	//	resetDisplay()
	//
	resetDisplay: function() {
		// hide elements during transition
		this.loading.show();
		this.flash_container.hide().setStyle({backgroundColor:'transparent'});
		this.close_link.hide();
		this.meta_container.hide();
	},

	//
	//	resizeImageContainer()
	//
	resizeImageContainer: function(imgWidth, imgHeight, fn ) {

		// get current height and width
		var wCur = this.outer_container.getWidth();
		var hCur = this.outer_container.getHeight();
		var tCur = this.media_player.cumulativeOffset().top;

		// get new width and height
		var wNew = (imgWidth  + (70));
		var hNew = (imgHeight  + (40));
		var tNew = ((15+35+hNew+52) > document.viewport.getHeight()) ? document.viewport.getScrollOffsets().top + 15 : document.viewport.getScrollOffsets().top + ((document.viewport.getHeight() / 2) - ((15+35+hNew+52)/2));
		
		new Effect.Parallel([
			new Effect.Morph( this.outer_container, {style:'width:'+wNew+'px;height:'+hNew+'px;'} ),
			new Effect.Morph( this.media_player, {style:'top:'+tNew+'px;'} )
		],{duration: 0.65, afterFinish:fn});

		var widthStyle = {width:imgWidth+'px'};
		this.top_nav.setStyle(widthStyle);
		this.meta_container.setStyle(widthStyle);

	},

	//
	//	updateDetails()
	//	Display caption, image number, and bottom nav.
	//
	updateDetails: function() {
		this.caption.update('');
		new Effect.Appear(this.meta_container, { duration: 0.65, afterFinish: this.updateNav.bind(this) });
	},

	//
	//	updateNav()
	//	Display appropriate previous and next hover navigation.
	//
	updateNav: function() {
		var self = this;
		new Effect.Appear(this.close_link, { duration: 1.0, afterFinish: function(){ self.close_link.focus(); } });
		this.enableKeyboardNav();
	},
	
	//
	//	toggleCaptions()
	//
	toggleCaptions: function(e) {
		e.stop();
		if (this.captions) {
			this.getPlayer().disableCaptions();
			this.movie_captions.update('Turn on Closed Captioning');
			this.captions=false;
		}
		else {
			this.getPlayer().enableCaptions();
			this.movie_captions.update('Turn off Closed Captioning');
			this.captions=true;
		}
	},

	//
	//	enableKeyboardNav()
	//
	enableKeyboardNav: function() {
		document.onkeydown = function(e) {
			var keycode;
			if (e == null) { // ie
				keycode = event.keyCode;
			} else { // mozilla
				keycode = e.which;
			}

			var key = String.fromCharCode(keycode).toLowerCase();

			if((key == 'x') || (key == 'o') || (key == 'c')){	// close lightbox
				this.end();
			} else if(key == 'p'){	// display previous image
				if(this.activeImage != 0){
					this.disableKeyboardNav();
					this.changeImage(activeImage - 1);
				}
			} else if(key == 'n'){	// display next image
				if(this.activeImage != (this.imageArray.length - 1)){
					this.disableKeyboardNav();
					this.changeImage(activeImage + 1);
				}
			}
		}.bindAsEventListener(this);
	},

	//
	//	disableKeyboardNav()
	//
	disableKeyboardNav: function() {
		document.onkeydown = '';
	},


	end: function() {
		this.disableKeyboardNav();
		var p = this.getPlayer();
		if (p.stopVideo) {
			p.stopVideo();
		} else {
			p.stopPlayer();
		}
		if (this.movie_details) { this.movie_details.remove(); this.movie_details = null; }
		this.meta_container.hide();
		this.close_link.hide();
		this.media_player.hide();

		new Effect.Fade(this.overlay,
			{ duration: 0.5, afterFinish:function(){
					this.flash_container.update("<div style=\"display:none\"></div>");
				}.bind(this)
			}
		);

		GE_MediaOverlay.showSelectBoxes();

		this.started = false;
	},
	
	unload: function() {
		if (this.mode == 'video' && this.started ) {
			var p = this.getPlayer();
			if (p.stopVideo) {
				p.stopVideo();
			} else {
				p.stopPlayer();
			}
		}
	},

	getPlayer: function() {
		if (navigator.appName.indexOf("MSIE") != -1) {
			return window['video_player'];
		} else {
			return document['video_player'];
		}
	}

});

GE_MediaOverlay._instance = null;
GE_MediaOverlay.getInstance = function() {
	if (GE_MediaOverlay._instance == null) GE_MediaOverlay._instance = new GE_MediaOverlay();
	return GE_MediaOverlay._instance;
};

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

GE_MediaOverlay.showSelectBoxes = function(){
	$$("select").each( function(el){ el.show(); } );
};

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

GE_MediaOverlay.hideSelectBoxes = function(){
	$$("select").each( function(el){ el.hide(); } );
};

GE_MediaOverlay.query_media_id = document.location.href.toQueryParams().media_id;

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

document.observe('dom:loaded', function() {
	var mo = GE_MediaOverlay.getInstance();
	$$('.media-overlay').each(function(el){
		el = $(el);
		mo.addAnchor(el);
		el.writeAttribute('title',el.readAttribute('title') + ' (opens in a new layer)');
		var media_id = GE_MediaOverlay.query_media_id;
		if (media_id) {
			var href = el.readAttribute("href");
			var id = href.substring(href.lastIndexOf("/")+1, href.lastIndexOf("."));
			if (id == media_id && !mo.started) {
				mo.start(el);
			}
		}
	});
});