var fileLoadingImage = "images/loading.gif";
var fileBottomNavCloseImage = "images/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( {

	htmlEl:null,
	started:false,
	resizeDuration:0,
	imageArray:new Array(),
	activeImage:null,
	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;

		this.htmlEl = $(document.documentElement);

		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.image = new Element("img") )
							.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"}))
							.insert(
								new Element("div",{id:"imageNav"})
									.insert(
										new Element("a",{id:"prevImg",href:"#"})
											.insert("previous")
									)
									.insert(new Element("span",{id:"numberDisplay"}))
									.insert(
										new Element("a",{id:"nextImg",href:"#"})
											.insert("next")
									)
							)
					)
			);
		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 arrayPageSize = getPageSize();
		//var overlayHeight = arrayPageSize[1]+'px';
		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 = fileName+".json";
		
		new Ajax.Request( jsonFileName, {
			onSuccess:function(transport) {
				var data = transport.responseText.evalJSON();
				this.mode = data.mode;
			
				switch(this.mode) {
					case ('video'):
						this.initVideo(data);
						break;
					case ('swf'):
						this.initFlash(data);
						break;
					case ('image'):
						this.initImage(data);
					default:
						break;
				}
			}.bind(this),
			onFailure:function() {
				this.mode = 'image';
				this.initImage();
			}.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')
		}

		this.imageArray = [];
		imageNum = 0;

		// stretch overlay to fill page and fade in
		this.positionOverlay();
		new Effect.Parallel( [
				new Effect.Appear(this.overlay, {from: 0.0, to: 0.8}),
				new Effect.Morph(this.htmlEl, {style:'background-color:#2e2f30'})
		],{ 
			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 docHeight = $(document.body).getHeight();
					var lightboxTop = scrollY + ((winHeight / 2) - 125);
					// var lightboxTop = scrollY + (docHeight / 15);
					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);
		
		
/*
		var so = new SWFObject(videoPlayerPath,"video_player",mp_width,mp_height,"8","#000000");
		so.addParam('scale', 'noscale');
	    so.addVariable("GE_baselink", GE_baselink);
	    so.addVariable("title", data.title);
	    so.addVariable("flv_path", data.flv_path);
	    so.addVariable("captions_path", data.captions_path);
	    so.addVariable("css_path", data.css_path);
	    so.addVariable("refresh_rate", data.refresh_rate || 200);
		so.write(this.flash_container);
*/		
		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',function(){ this.toggleCaptions(); }.bindAsEventListener(this))												
							.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) )
			);
		}
	},
	
	initFlash: function(data) {
		this.flash_container.setStyle({backgroundColor:'#fff'});
		var mp_width = data.mp_width || 401;
		var mp_height = data.mp_height || 300;
		
		var flashvars = {};

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

		var attributes = {};
		attributes.id="swf_player"
		
		swfobject.embedSWF(data.swf_path, this.flash_container.down().identify(), mp_width, mp_height, "8",null, flashvars, params, attributes);

		/*
		var so = new SWFObject(data.swf_path,"swf_player",mp_width,mp_height,"8","#FFFFFF");
		so.addParam('scale', 'noscale');
		so.write(this.flash_container);
		*/
		
		this.resizeImageContainer(mp_width,mp_height,function(){
			this.loading.hide();
			this.flash_container.show();
			this.updateDetails();
		}.bind(this));
	},
	
	initImage: function(data) {
		if (data) {
			this.imageArray.push([this.anchorInfo.href]);
			//create download 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.image_path) {
				this.movie_links.insert(
					new Element("li",{className:"movie_transcript"})
						.insert( new Element("a",{href:data.image_path,title:'Download ' + data.title + ' Image (' + data.download_extension + ')',target:'_blank'}).insert("Download Image (" + data.download_extension + ", " + data.download_size + ")") )
				);
			}
		} else {
			this.imageArray.push(new Array(this.anchorInfo.href, this.anchorInfo.title));
		}
		this.changeImage(imageNum);
	},
	
	//
	//	changeImage()
	//	Hide most elements and preload image in preparation for resizing image container.
	//
	changeImage: function(imageNum) {

		this.activeImage = imageNum;	// update global var

		var imgPreloader = new Image();

		// once image is preloaded, resize image container
		
		var self = this;
		imgPreloader.onload=function(){
			$(self.image).writeAttribute({src: self.imageArray[self.activeImage][0]});
			self.resizeImageContainer(imgPreloader.width, imgPreloader.height, function(){ self.showImage() });
		}
		imgPreloader.src = this.imageArray[this.activeImage][0];
	},

	//
	//	resetDisplay()
	//
	resetDisplay: function() {
		// hide elements during transition
		this.loading.show();
		this.flash_container.hide().setStyle({backgroundColor:'transparent'});
		this.image.hide();
		this.close_link.hide();
		this.meta_container.hide();
		// this.caption.hide();
		$('imageNav').hide();
		$('numberDisplay').hide();
		$('prevImg').hide();
		$('nextImg').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);

	},

	//
	//	showImage()
	//	Display image and begin preloading neighbors.
	//
	showImage: function(){

		this.loading.hide();
		new Effect.Appear(this.image, { duration: 0.5, queue: 'end', afterFinish: this.updateDetails.bind(this) });
		this.preloadNeighborImages();

	},

	//
	//	updateDetails()
	//	Display caption, image number, and bottom nav.
	//
	updateDetails: function() {

		if (this.mode!='video') {
			if (this.anchorInfo.title && !this.movie_details) {
				this.caption.show().update(this.anchorInfo.title);
			} else {
				this.caption.hide().update('');
			}

			// if image is part of set display 'Image x of x'
			if(this.imageArray.length > 1 && this.mode=='img'){
				$('numberDisplay').show().update( (this.activeImage + 1) + " of " + this.imageArray.length);
			}
		} else {
			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;

		if (this.mode!='video') {
			if (this.mode=='img') {
				new Effect.Appear(this.close_link, { duration: 0.5, afterFinish: function(){ self.close_link.focus(); } });
				new Effect.Appear('imageNav', { duration: 0.5 });
			} else {
				new Effect.Appear(this.close_link, { duration: 1.0, afterFinish: function(){ self.close_link.focus(); } });
			}

			// if not first image in set, display prev image button
			if(this.activeImage != 0){
				$('prevImg').show().onclick = function() {
					self.changeImage(this.activeImage - 1); return false;
				}
			}

			// if not last image in set, display next image button
			if(this.activeImage != (this.imageArray.length - 1)){
				$('nextImg').show().onclick = function() {
					self.changeImage(this.activeImage + 1); return false;
				}
			}
		} else {
			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 = '';
	},


	//
	//	preloadNeighborImages()
	//	Preload previous and next images.
	//  XXX: not sure where vars are declared in this fn
	//
	preloadNeighborImages: function(){

		if((this.imageArray.length - 1) > this.activeImage){
			preloadNextImage = new Image();
			preloadNextImage.src = this.imageArray[this.activeImage + 1][0];
		}
		if(this.activeImage > 0){
			preloadPrevImage = new Image();
			preloadPrevImage.src = this.imageArray[this.activeImage - 1][0];
		}

	},

	end: function() {
		this.disableKeyboardNav();
		if (this.mode=='video') {
			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.Parallel( [
				new Effect.Fade(this.overlay),
				new Effect.Morph(this.htmlEl,{style:'background-color:#e8ebef'})
			],
			{ duration: 0.5, afterFinish:function(){
					this.image.src = "";
					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() {

	el = $('video_a');
	var mo = GE_MediaOverlay.getInstance();
	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);
		}
	}	
});

