//self calling function to make lightbox object
var blast_lightbox = function (){

	var dbg = 0,
	//create lightbox object
	lightbox = {
		currentItem: "",	//	ID of item currently displayed in lightbox
		page: undefined,
		index: undefined,
		items: [],	//	Array of pages/items used to navigate through the lightbox
		galleryLoad: undefined,

		//	Maps page to the lighbox.items array
		mapPage: function(pageHtml,pageNo) {
			var itemElms = glow.dom.create(pageHtml).get(".item");
			pageNo--;	//	Make pageNo zero-based
			lightbox.items[pageNo] = [];	//	Empty the page
			for (var i=0; i<itemElms.length; i++) {
				lightbox.items[pageNo].push(glow.dom.get(itemElms[i]).attr("id").replace(/^item_([0-9]+$)/,"$1"));
			}
		},

		navigate:function(distance) {
			var lb = lightbox,
				showRecUrl;
			if (	//	If the button is disabled return
				(distance < 0 && glow.dom.get("#lb_prev").hasClass("disabled")) ||
				(distance > 0 && glow.dom.get("#lb_next").hasClass("disabled"))
				) {
				return false;
			}
			lb.findCurrentIndex();
			//	Are we at the start or end of the page?
			if (!lb.setNewItem(distance)) {
				return false;	//	return if the next page is not ready - event has been set to call navigate() when ready
			}
			showRecUrl = '\/apps\/ifl\/blast\/gallery\/showrecord?ContentType=text%2Fhtml%3B+charset%3DUTF-8;Id='+
			lb.items[lb.page][lb.index]+
			';Template=lightbox.tmpl';
			lb.open(showRecUrl);
		},

		findCurrentIndex:function() {	//	Find the current item in items array
			var lb = lightbox;
			for (var i=0; i<lb.items.length; i++) {	//	Page level
				for (x=0; x<lb.items[i].length; x++) {	//	Item level
					if (lb.items[i][x] == lb.currentItem) {
						lb.page = i;
						lb.index = x;
					}
				}
			}
		},

		setNewItem: function(distance) {
			var lb = lightbox;
			if (distance > 0 && lb.index == lb.items[lb.page].length-1/*length is not zero based*/) {	//	moving forward at the end of a page
				if (lb.items[lb.page+1]) {	//	Do we have another page available?
					lb.page++;	//	Increment page
					lb.index = 0;	//	Index will be first on page
					blast_gallery.move(1);	//	Move the gallery to the next page
				} else if (lb.page < (gb_qe_n_pages_total-1)) {	//	Are we on the last page?
					//	Next page not yet available, add an event to execute when it's available
					/*lb.galleryLoad = glow.events.addListener(blast_gallery,"pageLoad",function(distance) {
						lb.navigate(distance);
						glow.events.removeListener(lb.galleryLoad);
						return false;
					});*/
				}
			} else if (distance < 0 && lb.index === 0) {	//	Moving back from the start of a page
				if (lb.items[lb.page-1]) {
					lb.page--;	//	Decrement page
					lb.index = lb.items[lb.page].length-1;	//	Index will be last item on new page
					blast_gallery.move(-1);	//	Move the gallery to the previous page
				} else if (lb.page > 1) {	//	Are we on the first page?
					//	Previous page not loaded yet, add event to execute when it's available
					/*lb.galleryLoad = glow.events.addListener(blast_gallery,"pageLoad",function(distance) {
						lb.navigate(distance);
						glow.events.removeListener(lb.galleryLoad);
						return false;
					});*/
				}
			} else {
				lb.index = lb.index + distance;
			}
			return true;
		},

		updatePageNav: function() {
			var lb = lightbox,
				pageSize = gb_qe_pagesize;
			//if (lb.page === undefined || lb.index === undefined) {	//	Find the page/index if we don't have already it
				lb.findCurrentIndex();
			//}
			glow.dom.get("#lb_item").text((lb.page * pageSize) + lb.index + 1);
			glow.dom.get("#lb_total").text(gb_qe_total_hits);
			//	Update navigation buttons
			glow.dom.get("#lb_prev,#lb_next").removeClass("disabled");
			if (lb.page === 0 && lb.index === 0) {	//	First page, first item
				//	Disable prev button
				glow.dom.get("#lb_prev").addClass("disabled");
			} else if (
					(lb.currentItem == lb.items[lb.items.length-1][lb.items[lb.items.length-1].length-1]) ||
					(lb.page * pageSize + lb.index + 1 == gb_qe_total_hits)
					) {
			//} else if (lb.page * pageSize + lb.index + 1 == gb_qe_total_hits) {	//	last page, last item
				//	Disable next button and add event to update when another page is available
				glow.dom.get("#lb_next").addClass("disabled");
			}
		},

		open: function(url) {
			//submit to showrecord
			var request = glow.net.get(url, {
				useCache: true,

			//showrecord onLoad
			onLoad: function handleDataLoad(response) {

				if (dbg) { gb_lib.dbg_msg('lb: have loaded and created contentNode = '+glow.dom.create(response.text())); }

				//reference to the lightbox's content area
				var contentContainer = glow.dom.get("#lightbox .content");

				if (dbg) { gb_lib.dbg_msg('lb: contentContainer before empty = '+contentContainer.html()); }

				//remove any existing content from lightbox
				contentContainer.empty();

				if (dbg) { gb_lib.dbg_msg('lb: contentContainer after empty = '+contentContainer.html()); }

				/* Add defer attribute to script tags to prevent IE ignoring them */
				var lb_html = response.text().replace(/(<script)/g,"$1 defer=\"defer\"");

				//insert new content into lightbox
				glow.dom.create(lb_html).appendTo(contentContainer);

				/* Force IE/Webkit/Opera to load external and execute inline scripts */
				if (isNaN(glow.env.gecko) && isNaN(glow.env.ie)) {
					glow.events.addListener(panel,"afterShow",function(){
						var evalInterval,
						evalTimeout,
						scriptToEval = "",
						scriptElms = glow.dom.get("#ratings_scripts script").filter(function() {
							if(this.src){
								return true
							} else {
								scriptToEval += " " + glow.dom.get(this).html();
								return false
							}
						});
						/* Load external scripts and execute inline onLoad */
						scriptElms.each(function(i) {
							glow.net.loadScript(this.src,{useCache: true});
						});
						/* eval inline scripts after an interval - timeout after 30 seconds */
						evalInterval = setInterval(function(){
							/* vision is created by scripts loaded previously */
							if (typeof(vision) != undefined) {
								eval(scriptToEval);
								clearInterval(evalInterval);
								clearTimeout(evalTimeout);
							}
						},100);
						evalTimeout = setTimeout(function(){
							clearInterval(evalInterval);
						},30000);
					});
				}

				if (dbg) { gb_lib.dbg_msg('lb: contentContainer after append = '+contentContainer.html()); }

				//	Attach events to the close button
				glow.events.addListener("#lightbox .close","click",function() {
					panel.hide();
					return false;
				});

				//	Set up the EMP if required
				if (panel.isShown) {
					lightbox.initEMP();
				} else {
					glow.events.addListener(panel,"afterShow",function() {
						lightbox.initEMP();
						glow.dom.get("#media_embed").css("visibility","visible");
					});
					glow.dom.get("#media_embed").css("visibility","hidden");	//	Avoids momentarily displaying the no js/flash message
				}
				//	Hide the flash before closing to give a smoother fade out
				glow.events.addListener(panel,"hide",function() {
					glow.dom.get("#media_embed").css("visibility","hidden");
				});

				//show the lightbox
				panel.show();

				lightbox.currentItem = glow.dom.get("#lightbox div.content-holder").attr("data-itemid");
				lightbox.updatePageNav();	//	Update lightbox page numbers

				//	Set up previous and next buttons
				glow.events.addListener("#lb_prev","click",function() {
					lightbox.navigate(-1);
					return false;
				});
				glow.events.addListener("#lb_next","click",function() {
					lightbox.navigate(1);
					return false;
				});
			},
				onError: function(response) {
					if (dbg) {gb_lib.dbg_msg("Error getting file: " + response.statusText())};
				}
			});//end showrecord onLoad
		},

		//setup the lightbox
		init: function() {

			if (dbg) { gb_lib.dbg_msg('lb: lightbox init func called'); }			

			var lightboxHTML = glow.dom.create('<div></div>');

			//lightbox panel instance
			panel = new glow.widgets.Panel(lightboxHTML, {
			  template: '<div id="lightbox"><div class="content"></div></div>',
			  width: 564,
			  anim: "fade"
			});

			//add a CSS class to the lightbox
			panel.container.addClass("blast-lightbox");

			//	Add event to update nav on gallery page load
			glow.events.addListener(blast_gallery,"pageLoad",function() {
				blast_lightbox.updatePageNav();
			});
			//	Add event to clear item map on gallery reload
			/*glow.events.addListener(blast_gallery,"afterReload",function() {
				blast_lightbox.items = [];
			});*/
		},//end setup the lightbox

		//	Return media type or false if no EMP
		isEMP: function() {
			var mediaElm = glow.dom.get("#media_embed"),
				mediaType = false;
			if (mediaElm.hasClass("video")) {
				mediaType = "video";
			}
			else if (mediaElm.hasClass("audio")) {
				mediaType = "audio";
			}
			return mediaType;
		},

		writeEMP: function(mediaType) {
			var emp = new embeddedMedia.Player();
			emp.setWidth("512");
			if (mediaType == "audio") {
				emp.setHeight("106");
				emp.set("config_settings_displayMode","audio");
			} else {
				emp.setHeight("323");
			}
			emp.setDomId("media_embed");
			emp.set("config_settings_skin", "black");
			emp.setPlaylist(glow.dom.get("#media_embed").attr("data-playlist"));
			emp.write();
		},

		initEMP:function() {
			var mediaType = lightbox.isEMP();
			if (mediaType) {
				lightbox.writeEMP(mediaType);
			}
		},

		//setup events on gallery thumbnails to invoke lightbox
		set_events: function(nodelist) {

			if (dbg) { gb_lib.dbg_msg('lb: lightbox set_events func called nodelist='+nodelist); }

			//get the links from the passed-in nodelist (from gallery.js script)
			var galleryItems = nodelist.get(".item a");

			//setup onclick events
			glow.events.addListener(galleryItems, "click", function(event) {

				//convert the href page link into one to be ajaxed to showrecord
				var showRecUrl = event.attachedTo.href.replace(/^.+\/(blast)\/.+\/(\d+)/,'\/apps\/ifl\/$1\/gallery\/showrecord?ContentType=text%2Fhtml%3B+charset%3DUTF-8;Id=$2;Template=lightbox.tmpl');

				if (dbg) { gb_lib.dbg_msg('lb: About to do a glow.net.get to: ' + showRecUrl); }

				lightbox.open(showRecUrl);

			return false;
			});//end setup events
		}
	};//end lightbox object  
	return lightbox;       
}();//end self calling function to make lightbox object