(function(){
/*
	-------------------------------------------------------------
		GALLERY OBJECT
	-------------------------------------------------------------
	*/

		var 	glow;
	        window.vision = window.vision || {};
			
		var htmlNavBoth = '<p class="bothon"><a class="back" href="#" onclick="vision.gallery.getGallery(\'back\');return false;"><span>Back</span></a> <span id="page-count">1 of 12</span> <a class="next" href="#" onclick="vision.gallery.getGallery(\'next\');return false;"><span>Next</span></a></p>',
				  
		htmlNavNone = '<p class="noneon"><a class="back" href="#" onclick="vision.gallery.getGallery(\'back\');return false;"><span>Back</span></a> <span id="page-count">1 of 12</span> <a class="next" href="#" onclick="vision.gallery.getGallery(\'next\');return false;"><span>Next</span></a></p>',
					  
		htmlNavBack = '<p class="backon"><a class="back" href="#" onclick="vision.gallery.getGallery(\'back\');return false;"><span>Back</span></a> <span id="page-count">1 of 12</span> <a class="next" href="#" onclick="vision.gallery.getGallery(\'next\');return false;"><span>Next</span></a></p>',
					  				  
		htmlNavNext = '<p class="nexton"><a class="back" href="#" onclick="vision.gallery.getGallery(\'back\');return false;"><span>Back</span></a> <span id="page-count">1 of 12</span> <a class="next" href="#" onclick="vision.gallery.getGallery(\'next\');return false;"><span>Next</span></a></p>',
	
		
		getElementById = document.getElementById;
		
		var lightbox;
		
		var wallpaperOverlay;
		
		var ratingsForm;

	vision.gallery = {
		init:function(){
			if (glow.isSupported) {
		
				/* add pagination  */
				if(document.getElementById("vision-gallery-view")) {
				vision.gallery.initPagination();
				vision.gallery.initActions();
				vision.gallery.buildLightbox(vision.gallery.layouttype);
				vision.gallery.onLoad();
				}
			}
			
		},
		
		version: "1_3_1",
		order: "DESC",
		source: null, //SET IN CORE.SSSI
		site: null, //SET IN CORE.SSSI
		currentPage: 1,
		requestedPage: 1,
		highestPageVisited: 1,
		totalPages: 1,	//total number of comments divided by page size. Updated after first xhr to queryengine
		totalImages: null,
		empsource: null,
		empdescription: null,
		pagesInCache: 0, // Updated after each xhr to queryengine
		imagesInPage: 10, //OVERIDEABLE IN CORE.SSSI
		queryEnginePageSize: 20, //OVERIDEABLE IN CORE.SSSI
		queryEnginePage: 1, //incremented after each xhr to queryengine
		queryengineData: {}, //object to hold queryengine json after an xhr
		action: null,
		cache: [],
		cacheContainsAllData: false,
		config: null,
		swap: null,
		onLoad:function(){}, //callback function that is called when gallery is displayed
		
		/*  add back text and next link */		
		initPagination: function(){
			var gallery = vision.gallery;

			/* insert nav: provide a next link unless there are less than a page worth of galleries*/
			var htmlNav = htmlNavNext;
			if (gallery.totalImages <= gallery.imagesInPage) {
				var htmlNav = htmlNavNone;
			}	
			
			document.getElementById("vision-gallery-nav").innerHTML = htmlNav;
			gallery.getQueryengineData();

		},
		
		
		getGallery: function(button){
			var gallery = vision.gallery, requestedPage;
			
			/* work out what page is being requested*/
			if (button =="next") {
				requestedPage = vision.gallery.currentPage + 1;
			}
			else {
				requestedPage = vision.gallery.currentPage - 1;
			}
			
			/* ONLY PROCEED IF REQUESTED PAGE EXISTS- i.e in the range 1 to totalPages - this may not be neccessary and next and back links will not appear when out of range */
			if ((gallery.pagesInCache > 0 && requestedPage > gallery.totalPages) || requestedPage == 0) return;
	
			
			/* update currentpage and if necessary highestPageVisited */
			if (button =="next") {
				/* increment currentPage */
				gallery.currentPage++;
				
				/* increment highestPageVisited if needed */
				if (gallery.currentPage > gallery.highestPageVisited){
					gallery.highestPageVisited = gallery.currentPage;
				}
			}
			else {
				/* decrement currentPage */
				gallery.currentPage--;
			}
						
			gallery.displayGalleryFromCache();
			if(button != "back" && !gallery.cacheContainsAllData){
				gallery.getQueryengineData();
			}
			if(!lightbox.isShown){
				document.getElementById('vision-gallery-view').scrollIntoView(true);
				};
			return false;
			
		},

		//queryEngine template for queryEngine data.Data output format is JSON
		getQueryengineData: function(){
			/* If this is a Gallery with Ratings enabled we need to ensure it's using the ratings config */
			if (vision.gallery.rating == "true"){
				var config = 'ratings';
			}
			else {
				var config = '';
			}
			
			if (vision.gallery.site) {
				var getData = "/cgi-perl/apps/ifl/queryengine.pl/apps/vision/"+vision.gallery.version+"/gallery?pagesize=" + vision.gallery.queryEnginePageSize + ";page=" + vision.gallery.queryEnginePage +";sort_1=user_priority;sortsense_1=DESC;sort_2="+vision.gallery.sort+";sortsense_2=" + vision.gallery.order + ";sort_3=user_lastupdate;sortsense_3=DESC;attrib_1=site;oper_1=contains;val_1_1=" + vision.gallery.site + ";OutputFormat=JSON;OutputContent=ISO-8859-1";
			}
			else {
				var getData = "/cgi-perl/apps/ifl/queryengine.pl/apps/vision/"+vision.gallery.version+"/gallery?pagesize=" + vision.gallery.queryEnginePageSize + ";page=" + vision.gallery.queryEnginePage +";sort_1=user_priority;sortsense_1=DESC;sort_2="+vision.gallery.sort+";sortsense_2=" + vision.gallery.order + ";sort_3=user_lastupdate;sortsense_3=DESC;attrib_1=source;oper_1=contains;val_1_1=" + vision.gallery.source + ";OutputFormat=JSON;OutputContent=ISO-8859-1";
			}
			
			var gallery = vision.gallery,
				getRef = glow.net.get(getData, {
			onLoad: function(response) {
					gallery.queryengineData = eval("(" + response.text() +")");
					var oData = vision.gallery.queryengineData;
					gallery.cache = gallery.cache.concat(oData.RECORD);
					gallery.totalPages = Math.ceil(oData.total_hits / gallery.imagesInPage);
					gallery.pagesInCache = Math.ceil(gallery.cache.length / gallery.imagesInPage);
					glow.dom.get("#page-count").html(gallery.currentPage+" of "+vision.gallery.totalPages);
					gallery.queryEnginePage++;
					if (gallery.pagesInCache == gallery.totalPages){
						gallery.cacheContainsAllData = true;
					}
				},
				onError: function(response) {
					alert("Error getting Gallery file: " + response.statusText());
				}
			});

		},
		
		//Import cache images into gallery template from queryEngine 
		displayGalleryFromCache: function(){
			
			var elGallery = document.getElementById("vision-gallery-view"),
				gallery = vision.gallery;
			if(vision.gallery.type == "badge"){
				var titleHTML = '<h2>'+vision.gallery.viewtitle+'</h2><p class="vision-gallery-subtitle">'+vision.gallery.subtitle+'</p>';
			}
			else{
				if (vision.gallery.sortbar != "off"){
					var sortbar = '<p id="vision-gallery-sortbar">View by - <a href="?sort=recent">most recent</a> | <a href="?sort=top">top rated</a> | <a href="?sort=views">most views</a></p>';
				}
				else{
					var sortbar = "";
				}
				var titleHTML = '<h2>'+vision.gallery.viewtitle+'</h2>'+sortbar;
			}
			/* work out what gallery need to be displayed */
			var firstImage = (gallery.currentPage - 1) * gallery.imagesInPage;
			var lastImage = firstImage + gallery.imagesInPage;
			var leftOver = 0;
			if (lastImage > gallery.totalImages){
				lastImage = gallery.totalImages;
				leftOver = gallery.imagesInPage - (gallery.totalImages%gallery.imagesInPage);
			}
			
			/* use cache to insert data into gallery template  */
			var galleryHTML = '<ul id="vision-gallery-grid">';
			for (var i = firstImage; i < lastImage; i++) {
				
				/* Trim description */
				var trimdesc = vision.gallery.trimData(gallery.cache[i].user_description, vision.gallery.desclength);
				
				/* Trim title */
				var trimtitle = vision.gallery.trimData(gallery.cache[i].user_title, vision.gallery.titlelength);
				
				imgType = gallery.cache[i].file_type;
				
				/* If no author wanted */
								
				if(vision.gallery.namelength != "off"){
				
					/* Trim name length if value is given that isn't off */				
					var trimname = vision.gallery.trimData(gallery.cache[i].user_name, vision.gallery.namelength);
				
					/* if two_column - add description text */
					if (vision.gallery.type == "two_column") {
						
						var nameTitle = '<p><a href="' + vision.gallery.assetpage +  gallery.cache[i].id + '" class="vision-gallery-'+vision.gallery.action+'"><span class="title">'+trimtitle+'</span></a><span class="user">By '+trimname+'</span></p><p class="vision-gallery-description">'+trimdesc+'</p>';
					}
					else {
						var nameTitle = '<p><a href="' + vision.gallery.assetpage +  gallery.cache[i].id + '" class="vision-gallery-'+vision.gallery.action+'"><span class="title">'+trimtitle+'</span></a><span class="user">By '+trimname+'</span></p>';
					}
				}
				/* If author wanted */
				else{
					if (vision.gallery.type == "two_column") {
						if (imgType == 'Video'){
							var nameTitle = '<p><a href="' + vision.gallery.assetpage +  gallery.cache[i].id + '" class="vision-gallery-'+vision.gallery.action+' video-playback">';
						}
						else{
							var nameTitle = '<p><a href="' + vision.gallery.assetpage +  gallery.cache[i].id + '" class="vision-gallery-'+vision.gallery.action+'">';
						}
						nameTitle += '<span class="title">'+trimtitle+'</span></a></p><p class="vision-gallery-description">'+trimdesc+'</p>';
					}
					else{
						if (imgType == 'Video'){
							var nameTitle = '<p><a href="' + vision.gallery.assetpage +  gallery.cache[i].id + '" class="vision-gallery-'+vision.gallery.action+' video-playback">';
						}
						else{
							var nameTitle = '<p><a href="' + vision.gallery.assetpage +  gallery.cache[i].id + '" class="vision-gallery-'+vision.gallery.action+'">';
						}
						nameTitle += '<span class="title">'+trimtitle+'</span></a></p>';		
					}
				}
			
				/* Put together grids */
				if (vision.gallery.pageperasset == "true") {
					if (vision.gallery.assetpage !="") { //custom asset page was set
						galleryHTML += '<li><div class="'+imgType+'"><span></span><a href="' + vision.gallery.assetpage +  gallery.cache[i].id + '"><img title="" alt="" src="/apps/vision/gallery/assets/'+ gallery.cache[i].site +'/thumb_'+vision.gallery.thumb+'/'+ gallery.cache[i].file_root+'.jpg" /></a></div>'+nameTitle;
					}
					else {
						galleryHTML += '<li><div class="'+imgType+'"><span></span><a href="'+vision.gallery.assetpage+ gallery.cache[i].id +'"><img title="" alt="" src="/apps/vision/gallery/assets/'+ gallery.cache[i].site +'/thumb_'+vision.gallery.thumb+'/'+ gallery.cache[i].file_root+'.jpg" /></a></div>'+nameTitle;
					}
				}
				else if (vision.gallery.action == 'nolightbox'){
					galleryHTML += '<li><div class="'+imgType+'"><span></span><a href="' + vision.gallery.assetpage +  gallery.cache[i].id +'"><img title="" alt="" src="/apps/vision/gallery/assets/'+ gallery.cache[i].site +'/thumb_'+vision.gallery.thumb+'/'+ gallery.cache[i].file_root+'.jpg" /></a></div>'+nameTitle;
				}
				else {
					galleryHTML += '<li><div class="'+imgType+'"><span></span><a href="' + vision.gallery.assetpage +  gallery.cache[i].id +'" class="vision-gallery-'+vision.gallery.action+'"><img title="" alt="" src="/apps/vision/gallery/assets/'+ gallery.cache[i].site +'/thumb_'+vision.gallery.thumb+'/'+ gallery.cache[i].file_root+'.jpg" /></a></div>'+nameTitle;
				}
				
				/* Check whether or not to insert Rating values */
				if(vision.gallery.rating == 'true'){
					var ratingHTML = vision.gallery.displayRatingValue(vision.gallery.cache[i].id, vision.gallery.cache[i].ratings_wavg, vision.gallery.cache[i].ratings_maxchoice);               
					galleryHTML += ratingHTML + '</li>';
				}
				else {
					galleryHTML += '</li>';
				}
			}
			galleryHTML += '</li>';
			
			/* fill in any empty spaces when there's not a full page of images to show */
			if (lastImage == gallery.totalImages){
				for (var i = 0; i < leftOver; i++) {
					if (vision.gallery.rating == "true"){
						var noimageClass = "noimage noratings";
					}
					else{
						var noimageClass = "noimage";
					}
				galleryHTML += '<li class="'+noimageClass+'"><div class="image"></div><p><span class="title"></span><span class="user"></span></p></li>'
				}	
			}
			galleryHTML += '</ul>';
			 
			//end
			
			/* work out what links should be in pagination navigation */ 
			if (gallery.currentPage == 1){
				var htmlNav = htmlNavNext;
			}
			else if (gallery.currentPage == vision.gallery.totalPages){
				var htmlNav = htmlNavBack;
			}
			else {
				var htmlNav = htmlNavBoth;
			}
			
			var linksHTML = '<div id="vision-gallery-nav">' + htmlNav + '</div>';

			/* insert all html */
			elGallery.innerHTML = titleHTML + galleryHTML + linksHTML;
			vision.gallery.onLoad();
			vision.gallery.initActions();
			
			glow.dom.get("#page-count").html(gallery.currentPage+" of "+vision.gallery.totalPages);
			
			if(vision.gallery.rating == "true"){
				vision.ratings.rankstars();
			};
		},
		
		//check which type of action to use
		initActions:function(){
			if(vision.gallery.bookmarks != "true"){
			var lightboxable = glow.dom.get("a.vision-gallery-lightbox");
			var popoverable = glow.dom.get("a.vision-gallery-popover");
					for (var i=0;i<lightboxable.length;i++){
						lightboxable[i].id = "thumb-"+i;
						var listener = glow.events.addListener(
						        lightboxable[i],
						        'click',
						        function (event) {
								var id = this.id.split("-")[1];
								if(vision.gallery.type != "badge"){
									nid = parseFloat(id);
									if(nid%2 == 0){
									nid = nid / 2;
									}
									else{
										nid = (nid - 1) / 2;
									}
								}
								else{
									nid = parseFloat(id);
								}
								
								newID = nid+ ((vision.gallery.currentPage - 1)*vision.gallery.imagesInPage);					
								vision.gallery.getLightboxData(newID);
								return false;
						        }
						);
					}
					for (var i=0;i<popoverable.length;i++){
						popoverable[i].id = "thumb-"+i;
						popoverable[i].onclick = function() {
								var id = this.id.split("-")[1];
								nid = parseFloat(id);
								newID = nid+ ((vision.gallery.currentPage - 1)*vision.gallery.imagesInPage);					
									vision.gallery.getPopoverData(newID);
									return false;
						}
					}
			}
			else{
				/*
				 
				 If this is a bookmarkable video gallery - we need to know what the ID should be of the EMP video, and where to show it.
				 We get the ID from the URL
				 The element ID should be set as vision-gallery-emp XSSI option
				 
				*/
				if (vision.gallery.empsource != 'default') {
					vision.gallery.showEMP(vision.gallery.empsource, vision.gallery.clipid);
				}
			}
		},
		
		/*
		Function: determines lightbox layout based on param sLayoutType.  Constructs lightbox accordingly.  Styling dealt with in CSS.
		*/		
		
		buildLightbox: function (sLayoutType) {

			//construct a lightbox object
			var opts =  {
				x: "50%",
				y: "20%",
				closeOnMaskClick:false
			};
		
			if (sLayoutType == '16_9') {
				opts.width = 635;
				opts.height = 458;
			}
			else if (sLayoutType == '8_10') {
				opts.width = 375;
				opts.height = 542;

			}
			else if (sLayoutType == '4_3') {
				opts.width = 595;
				opts.height = 540;

			}
			else if (sLayoutType == 'mixed_longdesc') {
				opts.width = 830;
				opts.height = 420;
			}
			else if (sLayoutType == 'mixed_gallery' || '') {
				opts.width = 455;
				opts.height = 540;
			}
			else {
				opts.width = 455;
				opts.height = 540;
			}
			
			lightbox = new glow.widgets.Panel("#gallery-panel", opts);

			/* add class to style panel */
			lightbox.content.addClass("gallery-panel");
			
			return true;
		},
		
		/* Function to get each asset ID and their associated rating values
		display rating stars accordingingly using CSS */
		
		displayRatingValue: function (id, ratings_wavg, ratings_maxchoice) {
			if (ratings_wavg > 0 ) {
				var ratingsHTML =
				'<div class="vision-ratings-view">' +
					'<h3>' + vision.ratings.viewtitle + '</h3>' +
					'<div class="vision-ratings-rank">' +
						'<span class="vision-ratings-score">' + ratings_wavg + '</span> out of <span class="vision-ratings-maxscore">' + ratings_maxchoice + '</span>' +
					'</div>' +
				'</div>';
			}
			else {
				var ratingsHTML =
				'<div class="vision-ratings-view">' +
					'<h3>' + vision.ratings.viewtitle + '</h3>' +
					'<p>Item not yet rated</p>' +
				'</div>';
			}
			return(ratingsHTML);
		},
		
		
		/*
		
		Function to do trimming of names and titles to desired length
		Mimics what's going on in IFL::Template (main.tmpl) too
		
		*/
		trimData:function(text, length){
			if(text != null){
				trim = new RegExp('^(.{0,'+length+'}[^ ]+)'); /* matches any characters between 0 and length, followed by 1 or more characters that are not a whitespace to stop truncation in middle of a word */
		
				trimtext = trim.exec(text);
				if(text.length < length){
					text = trimtext[0];
				}
				else{
					text = trimtext[0] +"...";
				}
			}
			else{
				text = " ";
			}
			return(text);
		},
		
		/*
		 
		 Function to build and popup a lightbox
		 Requires an ID of the asset
		 
		*/
		getLightboxData:function(id){
			var count = id+1;
			
			/*
			
			Get lightbox navigation
			
			*/
				

			if(count == vision.gallery.totalImages){
				var lbNav = '<div class="ft" id="vision-gallery-lightboxnav"><p class="back" title="Back"><a href="#" onclick="vision.gallery.swapLightbox(\'back\','+id+');return false;">Back</a></p><p class="vision-gallery-nav-counter">'+count+' of '+vision.gallery.totalImages+'</p><p class="forwardoff" title="Next"><a href="#">Next</a></p></div>';
			}
			else if(count == 1){
				var lbNav = '<div class="ft" id="vision-gallery-lightboxnav"><p class="backoff" title="Back"><a href="#">Back</a></p><p class="vision-gallery-nav-counter">'+count+' of '+vision.gallery.totalImages+'</p><p class="forward" title="Next"><a href="#" onclick="vision.gallery.swapLightbox(\'next\','+id+');return false;">Next</a></p></div>';
			}
			else if(count == 0){
				var lbNav = '<div class="ft" id="vision-gallery-lightboxnav"><p class="backoff" title="Back"><a href="#">Back</a></p><p class="vision-gallery-nav-counter">'+count+' of '+vision.gallery.totalImages+'</p><p class="forward" title="Next"><a href="#">Next</a></p></div>';
			}
			else{
				var lbNav = '<div class="ft" id="vision-gallery-lightboxnav"><p class="back" title="Back"><a href="#" onclick="vision.gallery.swapLightbox(\'back\','+id+');return false;">Back</a></p><p class="vision-gallery-nav-counter">'+count+' of '+vision.gallery.totalImages+'</p><p class="forward" title="Next"><a href="#" onclick="vision.gallery.swapLightbox(\'next\','+id+');return false;">Next</a></p></div>';
			}
			
			//include 'More info' link to PPA
			if (vision.gallery.moreinfo != 'false') {
				lbNav += '<div class="ppa"><p><a href="'+vision.gallery.assetpage + vision.gallery.cache[id].id+'">More info...</a></p></div>';

			}
		
			
			/*
			 
			Build the contents of the lightbox from the cache
			
			*/			
			var type = vision.gallery.cache[id].file_type;
			var description = vision.gallery.cache[id].user_description;
			var name = vision.gallery.cache[id].user_name;
			var title = vision.gallery.cache[id].user_title;
			var itemid = vision.gallery.cache[id].id;
			var totalRatings = vision.gallery.cache[id].ratings_total;
			var layouttype = vision.gallery.layouttype;
			
			if(description == null){
				description = " ";
			};
			
			if(vision.gallery.namelength != "off"){
				if(name == null){
					name = " ";
				}
				else{
					name = "by " + name;
				}
			}
			else{
				name = "";
			}
			
			if(title == null){
				title= " ";
			}
			else {
				var title = vision.gallery.trimData(title, 45);
			};
			
			var lbHeader = '<h2 class="hd">'+title+' '+name+'</h2>';
			
			var ratingsForm =
			'<div class="ratings-bars"></div>' +
			'<div class="ratings-c">' +
				'<div id="vision-gallery-lightboxrating">'+
					'<h2>Rate:</h2><br/>' +
					'<form method="get" action="/apps/ifl/apps/vision/opinion/log2results/" class="vision-ratings-form" id="formArea-0">' +
						'<div>' +
							'<input type="hidden" name="L2REndPage" value="' + vision.gallery.thanksurl + '" />' +
							'<input type="hidden" name="source" value="' + vision.gallery.source + '::vapp::gallery::' + itemid + '" />' + /* notation ::vapp::gallery::itemid  used to extract correct values into DB table fields */
							'<input type="hidden" name="title" value="' + title + '" />' +
							'<input type="hidden" name="max_choice" value="5" />' +
							'<input type="hidden" name="L2REndPage-non-js" value="" />' +
							'<input type="hidden" name="axis" value="default" />' +
						'</div>' +
						'<div class="vision-ratings-rating">' +
							'<div id="ratingArea-0" class="vision-rating-stars">' +
								'<div class="jsrate">' +
									'<a id="ratingArea-0-rate1" class="" title="1" onfocus="vision.ratings.rater.highlight(\'ratingArea-0\',1);" onclick="return vision.gallery.submitRating(1)" onmouseover="vision.ratings.rater.highlight(\'ratingArea-0\',1);" onmouseout="vision.ratings.rater.reset(\'ratingArea-0\');" href="#"></a>' +
									'<a id="ratingArea-0-rate2" class="" title="2" onfocus="vision.ratings.rater.highlight(\'ratingArea-0\',2);" onclick="return vision.gallery.submitRating(2);" onmouseover="vision.ratings.rater.highlight(\'ratingArea-0\',2);" onmouseout="vision.ratings.rater.reset(\'ratingArea-0\');" href="#"></a>' +
									'<a id="ratingArea-0-rate3" class="" title="3" onfocus="vision.ratings.rater.highlight(\'ratingArea-0\',3);" onclick="return vision.gallery.submitRating(3);" onmouseover="vision.ratings.rater.highlight(\'ratingArea-0\',3);" onmouseout="vision.ratings.rater.reset(\'ratingArea-0\');" href="#"></a>' +
									'<a id="ratingArea-0-rate4" class="" title="4" onfocus="vision.ratings.rater.highlight(\'ratingArea-0\',4);" onclick="return vision.gallery.submitRating(4);" onmouseover="vision.ratings.rater.highlight(\'ratingArea-0\',4);" onmouseout="vision.ratings.rater.reset(\'ratingArea-0\');" href="#"></a>' +
									'<a id="ratingArea-0-rate5" class="" title="5" onfocus="vision.ratings.rater.highlight(\'ratingArea-0\',5);" onclick="return vision.gallery.submitRating(5);" onmouseover="vision.ratings.rater.highlight(\'ratingArea-0\',5);" onmouseout="vision.ratings.rater.reset(\'ratingArea-0\');" href="#"></a>' +
								'</div>' +
							'</div>' +
						'</div>' +
						'<div class="vision-rating-stars"></div>' +
						'<div class="vision-ratings-rating">' +
							/* adding class="vision-ratings-select" below to <select> makes select box disappear - ratings CSS */
							'<select name="choice" class="vision-ratings-select" id="ratingSelect-0"><option value="" selected="selected">- - Select one - -</option><option value="1">1</option><option value="2">2</option><option value="3">3</option><option value="4">4</option><option value="5">5</option></select>' +
						'</div>' +
						'<div class="vision-ratings-submit">' +
							'<input type="submit" value="Submit" title="Submit" class="vision-ratings-submit-btn" src="/apps/vision/ratings/css/f/submit.gif" />' +
						'</div>' +
					'</form>' +
				'</div>' +
			'</div>';
			
			if(type == "Image"){
				if(layouttype == "mixed_gallery" || layouttype == "mixed_portrait" || layouttype == "mixed_landscape" || layouttype == "mixed_longdesc" || layouttype == ""){
					layouttype = 'actual_426';
				}			
			
				/* Cache next image - check for last image in this gallery */
	
				var lbBody = '<div id="vision-gallery-image">'+
					'<span></span>';
					
				var nextImg = new Image();
				nextImg = '/apps/vision/gallery/assets'+vision.gallery.cache[id].site+'/'+layouttype+'/'+vision.gallery.cache[id].file_root+'.jpg"';
					
				if (vision.gallery.swap) {
					lbBody += '<img src="'+nextImg+'" class="vision-gallery-cache-hide" />';
					if (count != vision.gallery.totalImages) { //check for last image
						var nextImgSwap = new Image();
						nextImgSwap = '/apps/vision/gallery/assets'+vision.gallery.cache[id].site+'/'+layouttype+'/'+vision.gallery.cache[id+1].file_root+'.jpg"';
						lbBody += '<img src="'+nextImgSwap+'" id="vision-gallery-cache-swaphide" />';
					}
				}
				else {
					lbBody +=
					'<img src="/apps/vision/gallery/assets'+vision.gallery.cache[id].site+'/'+layouttype+'/'+vision.gallery.cache[id].file_root+'.jpg" alt="'+title+'"'+'" class="vision-gallery-lbimage" />';
				}

				lbBody += '</div>' +
					'<div id="vision-gallery-lbratings-overlay">' +
						ratingsForm +
					'</div>';
					
				vision.gallery.swap = false;
				
				/* call L2R to increment view counter for this asset */
				var l2rEndPage = glow.net.get('/apps/ifl/visionapps/ugc/counter/log2results?ID='+itemid+'&L2REndPage=/apps/vision/gallery/assets'+vision.gallery.cache[id].site+'/'+layouttype+'/'+vision.gallery.cache[id].file_root+'.jpg');
				
			}
			else if(type == "Video"){
				var lbBody = '<div id="vision-gallery-image"><div id="vision-gallery-empLB" class="player"><a href="http://www.adobe.com/go/getflash">Download the Adobe Flash player</a></div></div>';	
			}
			
			if (vision.gallery.rating == "true") {
				var ratingHTML = vision.gallery.displayRatingValue(vision.gallery.cache[id].id, vision.gallery.cache[id].ratings_wavg, vision.gallery.cache[id].ratings_maxchoice);
				lbBody += '<div id="vision-gallery-lbratings">'+ratingHTML;
				    if (totalRatings > 0) {
					lbBody += '<p class="ratings-count">('+totalRatings+' ratings)</p>';
				    }
				lbBody += '</div>';
			}
		
			/* CTA buttons */
			lbBody += '<div id="vision-gallery-cta-buttons">';
			
			if (vision.gallery.rating == "true") {
				lbBody += '<p class="vision-gallery-rate-btn"><a href="#" onclick="vision.gallery.rateCurrentLbAsset('+itemid+');return false;">Rate</a></p>';
				
			}
			if (vision.gallery.wallpaper == "true") {
				lbBody += '<p class="vision-gallery-download-btn"><a href="#" onclick="vision.gallery.downloadWallpaper('+id+');return false;">Download wallpaper</a></p>';
			}
			if (vision.gallery.fullscreen == "true") {
				lbBody += '<p class="vision-gallery-fullscreen-btn">&nbsp;</p>';
			}
			
			lbBody += '</div>';
			
			//show author, age, and location if any exist
			
			var name = vision.gallery.cache[id].user_name;
			var location = vision.gallery.cache[id].user_location;
			var age = vision.gallery.cache[id].user_age;
			
			var userDetails = '';
			
			if ((name != '') && (vision.gallery.author == 'true')){
				if (vision.gallery.copyright == "copyright") {
					userDetails += '&copy; '+ name;
				} else {
					userDetails += vision.gallery.copyright +' '+ name;
				}
			}
			
			if ((vision.gallery.age == 'true') && (age)) { userDetails += '(age '+age+')'; }
			
			if ((vision.gallery.location == 'true') && (location)) { userDetails += ' from '+location; }
			
			if (userDetails.length > 0) {
				//alert("Name, age or location exists. Name: "+name+" Age: "+age+" Location: "+location);
				lbBody += '<div class="vision-gallery-userdetails">'+userDetails+'</div>';
			}
			
			/* call trimData() if description exceeds specified length (200 chars) */
			if ((vision.gallery.layouttype != "mixed_longdesc") && (description.length > 200)) {
				var description = vision.gallery.trimData(description, 200);
			}
		
			if (description != ' ') {
				lbBody += '<div class="vision-gallery-lightboxdesc">';
				var description = vision.gallery.trimData(description, 130);
				lbBody += '<p>'+description+'</p></div>';
			}
			else {
				lbBody += '<div class="vision-gallery-lightboxdesc nodesc"> </div>';
			}
			
			/*
			Put lightbox content into the lightbox itself
			*/
			lightbox.header.html(lbHeader);
			
			lightbox.body.html(lbBody);
			
			if(vision.gallery.rating == "true"){
				vision.ratings.rankstars();
			}
			
			lightbox.footer.html(lbNav);
			
			//If ratings on, move 'more info' link inline with nav buttons
			if (vision.gallery.rating == 'true') {
				glow.dom.get(".ppa").css("margin-top", "220px");
			}
			

			/* all HTML has been created & attached to the lightbox object.  Now we need to create elements to attach CSS specific to each layout type */
			
			if (layouttype == 'mixed_gallery' || layouttype == 'mixed_portrait' || layouttype == 'mixed_landscape' || layouttype == 'actual_426') {
				glow.dom.get("#vision-gallery-lightboxnav").addClass("nav-spacing");
				glow.dom.get(".nav-spacing").css("padding-left", "35%");					
			}
			
			if (layouttype == 'mixed_gallery' || layouttype == 'actual_426') {
				glow.dom.get("#vision-gallery-image").addClass("vision-gallery-image-mixed_gallery");
				glow.dom.get("#vision-gallery-image").css("position", "absolute");
				glow.dom.get("#vision-gallery-lbratings").css("position", "absolute").css("margin-top", "425px");
				glow.dom.get(".vision-gallery-lightboxdesc").css("position", "absolute").css("margin-top", "474px").css("line-height", "1.6em");
				glow.dom.get("#vision-gallery-lightboxnav").css("position", "absolute").css("margin-top", "215px");
				glow.dom.get("#vision-gallery-cta-buttons").css("position", "absolute").css("margin", "432px 255px 249px").css("width", "170px");
				glow.dom.get(".panel-bd").css("height", "300px").css("_height", "300px");
				glow.dom.get(".panel-ft").css("height", "245px").css("_height", "245px");
			}
			
			else if (layouttype == '16_9') {
				/*ensure nav controls are in the centre based on layout type */
				glow.dom.get("#vision-gallery-image").addClass("vision-gallery-image-16_9");
				glow.dom.get("#vision-gallery-cta-buttons").css("margin", "5px -5px 0 0");
				glow.dom.get("#vision-gallery-lightboxnav").css("margin", "15px 0");
				glow.dom.get(".vision-gallery-lightboxdesc").css("line-height", "1.6em");
				glow.dom.get("#vision-gallery-lbratings p").css("margin-top", "15px");
				glow.dom.get("#vision-gallery-lightboxnav").addClass("nav-spacing");
				glow.dom.get(".nav-spacing").css("padding-left", "40%");
			}
			else if (layouttype == "8_10") {
				glow.dom.get("#vision-gallery-lightboxnav").addClass("nav-spacing");
				glow.dom.get(".nav-spacing").css("padding-left", "33%");				
			}
			else if (layouttype == "mixed_longdesc") {
				glow.dom.get("#vision-gallery-lightboxnav").addClass("nav-spacing");
				glow.dom.get(".nav-spacing").css("padding-left", "43%");
				glow.dom.get(".vision-gallery-image").css("width", "426");
				glow.dom.get("#lightbox_"+sLayoutType+" .vision-gallery-lightboxdesc").addClass('vision-gallery-longdesc');
				glow.dom.get("#lightbox_"+sLayoutType+" .vision-gallery-image").addClass('vision-gallery-longdesc-image');				
			}
			else {
				glow.dom.get("#vision-gallery-image").addClass("vision-gallery-image-mixed_gallery");
			}
			
			/* add extra spacing if CTA buttons are present */
			if ((vision.gallery.wallpaper == "true") || (vision.gallery.rating == "true") || (vision.gallery.fullscreen == "true")) {
				glow.dom.get("#vision-gallery-lightboxnav").addClass("cta-buttons");
			}
			else {
				glow.dom.get(".vision-gallery-lightboxdesc").css("margin-top", "435px");
				glow.dom.get("#vision-gallery-lightboxnav").css("margin-top", "185px");
				glow.dom.get(".panel-ft").css("height", "215px");
			}
			
			/* add extra spacing if Ratings turned on */
			
			if (vision.gallery.rating == "true") {
				glow.dom.get(".vision-gallery-lightboxdesc").addClass("ratings-on");
			}
			
			/* Ensure author appears in right place whether ratings on/off */
			if (vision.gallery.rating == 'false') {
					glow.dom.get(".vision-gallery-userdetails").css("margin", "430px 10px 0 0");
					glow.dom.get(".vision-gallery-lightboxdesc").css("margin-top", "445px");
			}
			
			
			/*
			  Display the correct lightbox type
			*/
			 if(type == "Video"){
				if(vision.gallery.empsource != "default"){
					lightbox.hide();
					vision.gallery.showEMP(vision.gallery.empsource, itemid);
					if(vision.gallery.empdescription != "default"){
						vision.gallery.showEMPDesc(vision.gallery.empdescription, id);
					}
				}
				else{
					lightbox.show();
					glow.dom.get(".custom-panel").addClass("widescreen-emp");
					vision.gallery.showEMP("vision-gallery-empLB", itemid);
				}
			 }
			 else{
				lightbox.show();

				/* If fullscreen is enabled, we now need to embed the transparent button, once the HTML has been attached to the lightbox */
				if (vision.gallery.fullscreen == "true") {
				
					/* Fullscreen config options */
					var options = {
						showTitle: true,
						showDescription: true,
						showAuthor: true
					};
					
					var queryURL = "/cgi-perl/apps/ifl/queryengine.pl/apps/vision/"+vision.gallery.version+"/gallery?config=main;pagesize=" + vision.gallery.queryEnginePageSize + ";page=" + vision.gallery.queryEnginePage +";sort_1=moderation_lastupdate;sortsense_1=" + vision.gallery.order + ";sort_2=user_priority;attrib_1=source;oper_1=contains;val_1_1=" + vision.gallery.source + ";OutputFormat=JSON;OutputContent=ISO-8859-1";					
					
					var fullscreenFlashBtn = new glow.embed.Flash("/apps/vision/"+vision.gallery.version+"/gallery/swf/FullscreenGallery.swf", ".vision-gallery-fullscreen-btn", "9", {
		            			height: "19px",
								width: "26px",
								id: "vision-gallery-fullscreen-btn-flash-"+itemid,
								className: "vision-gallery-fullscreen-btn-flash",
								params: { wmode: "transparent"}
								}).embed();
					
				//FullscreenGallery = function(swf, queryUrl, configObject)
				vision.gallery.bridge = new FullscreenGallery(glow.dom.get("#vision-gallery-fullscreen-btn-flash-"+itemid)[0], queryURL, options);
				
				btnA = glow.dom.create('<a href="#" onclick="vision.gallery.showFullScreen('+itemid+');return false;" id="vision-gallery-fullscreen-btn-a-'+itemid+'" class="vision-gallery-fullscreen-btn-a">Fullscreen</a>').prependTo(".vision-gallery-fullscreen-btn");
				glow.dom.get(".vision-gallery-fullscreen-btn")[0].onmouseover = 
					function(){
						glow.dom.get(".vision-gallery-fullscreen-btn-a")[0].className = "vision-gallery-fullscreen-btn-a-hover";
					};
				glow.dom.get(".vision-gallery-fullscreen-btn")[0].onmouseout = 
					function(){
						glow.dom.get(".vision-gallery-fullscreen-btn-a-hover")[0].className = "vision-gallery-fullscreen-btn-a";
					};
				}
			 }
	
			//ensure that if the close button is clicked on a panel that it checks for the wallpaper overlay, and closes with the panel
			glow.events.addListener(
				'.panel-close',
				'click',
				function () {
					if (glow.dom.get(".vision-gallery-wallpaper-overlay").length > 0) {
						wallpaperOverlay.hide();
						wallpaperOverlayStep2.hide();
					}
				}
				
			);
		},
		
		/*
			display message such as "Rating.." while waiting for AJAX response.  Passes values off to vision.ratings.rater.chooseAction() which will then submit form and return AJAX thank you response
		*/
		submitRating: function(id) {
			glow.dom.get("#vision-gallery-lightboxrating").css("display", "none");
			
			glow.events.addListener (
				".vision-ratings-form",
				"click",
				function () {
					var progressMsg = glow.dom.get("#vision-gallery-lightboxrating").after("<h2 id='rating-progress'>Rating...</h2>");
					vision.ratings.rater.chooseAction('ratingArea-0', id);
				}
			)
			setTimeout("vision.gallery.showRatingsPanel()", 2000);
		},
		
		/* Ratings enabled includes Ratings core.js - use that functionality instead of duplicating here */
		rateCurrentLbAsset: function(id) {
			var ratings_overlay = glow.dom.get("#vision-gallery-lbratings-overlay");
			
			/* Hide Ratings overlay */
			glow.events.addListener (
				".vision-ratings-rating",
				"click",
				function(){					
					setTimeout("vision.gallery.fadeRatingsOverlay()", 3000);
				}
			)
			
			/* Show ratings overlay if it's not currently showing */
			glow.events.addListener (
				".vision-gallery-rate-btn",
				"click",
				function () {
					if (glow.dom.get("#vision-gallery-lbratings-overlay").css("opacity") == '0'){
						glow.anim.css("#vision-gallery-lbratings-overlay", 1, {
							"opacity" : {to:1}
						}).start();
					}
					glow.dom.get("#vision-gallery-lbratings-overlay").css("display", "block");
				}
			)
		},
		
		fadeRatingsOverlay: function() {
			var anim = glow.anim.css("#vision-gallery-lbratings-overlay", 1, {
				"opacity" : {to:0}
			}).start();
			setTimeout("vision.gallery.hideOverlay()", 2000);
		},
		hideOverlay: function() {
			glow.dom.get("#vision-gallery-lbratings-overlay").css("display", "none");
		},
		
		showRatingsPanel: function() {
			glow.dom.get("#rating-progress").css("display", "none");
			glow.dom.get("#vision-gallery-lightboxrating").css("display", "block");
		},
		
		/* Download process for wallpaper.  Pass in ID */
		
		downloadWallpaper: function(id) {
			
			//close any wallpaper overlays if they're open
			if (glow.dom.get(".vision-gallery-wallpaper-overlay").length > 0){
				wallpaperOverlay.hide();
				wallpaperOverlayStep2.hide();
			}
			
			// Two options:  4:3 or 16:9 dimension image
			
			var assetID = vision.gallery.cache[id].id;
			var assetSite = vision.gallery.cache[id].site;
			var assetRoot = vision.gallery.cache[id].file_root;
			var assetTitle = vision.gallery.cache[id].user_title;
			
			var layout = vision.gallery.layouttype;

			var stepCount = 1;
			
			
			//create step 1 overlay html
			
				var overlayHTMLStep1 = glow.dom.create('<div class="vision-gallery-wallpaper-overlay">' +
									'<div class="wallpaper-back"><a href="#" class="vision-gallery-wallpaper-back-step1">< Back to Image Gallery</a></div>' +
									'<hr />' +
									'<h2>Download as wallpaper</h2>' +
										'<div class="wallpaper-container">'+
											'<p class="wallpaper-step-count">Step 1 of 2<br/></p>' +
											'<p class="wallpaper-screen-type">What type of screen do you use?</p>' +
												'<div class="wallpaper-size">' +
													'<div class="wallpaper-standard"><img src="/apps/vision/1_3_1/gallery/assets/testing/wallpaper_142_105.jpg" alt="Standard 4:3 aspect ratio" width="142" height="105" /> <p><a href="#">Standard (4:3)</a></p></div>' +
													'<div class="wallpaper-wide"><img src="/apps/vision/1_3_1/gallery/assets/testing/wallpaper_186_105.jpg" alt="Wide 16:9 aspect ratio" width="186" height="105" /><p><a href="#">Wide (16:9)</a></p></div>' +
												'</div>' +
										'</div>' +
								'</div>');
				
				wallpaperOverlay = new glow.widgets.Overlay(overlayHTMLStep1, {
					modal: false,
						x: "50%",
						y: "30%"
				});
				
			//CSS changes based on layout type
			if (layout == 'mixed_gallery') {
				glow.dom.get(".vision-gallery-wallpaper-overlay").css("width", "425px").css("height","350px");
				glow.dom.get(".wallpaper-container").css("margin-left", "4%");
				glow.dom.get(".wallpaper-step-count").css("margin-left", "39%");
				glow.dom.get(".wallpaper-screen-type").css("margin-left", "25%");
			}

			wallpaperOverlay.show();
			
	
			//hide overlay if back link clicked
			var backStep1 = glow.dom.get(".vision-gallery-wallpaper-back-step1");
			var hideWallpaperOverlay = glow.events.addListener(
				backStep1,
				"click",
				function() {
					wallpaperOverlay.hide();
					glow.events.removeListener(".vision-gallery-wallpaper-back-step1");
				});
			
			
			var wallpaperStandardSelected = glow.events.addListener(
				".wallpaper-standard",
				"click",
				function () {
					wallpaperStep2('standard');
				}
			)
			
			var wallpaperWideSelected = glow.events.addListener(
				".wallpaper-wide",
				"click",
				function () {
					wallpaperStep2('wide');
				}
			)
			
			function wallpaperStep2(type) {
				
				stepCount = 2;
				
				if (type == 'standard') {
					var path = "wall_sxga";
					
					var overlayHTMLStep2 = glow.dom.create('<div class="vision-gallery-wallpaper-overlay-step2">' +
					'<div class="wallpaper-back"><a href="#" class="vision-gallery-wallpaper-back-step2">< Back to Image Gallery</a></div>' +
					'<hr />' +
					'<h2>Download as wallpaper</h2>' +
						'<div class="wallpaper-container">'+
							'<p class="wallpaper-step-count">Step 2 of 2<br/></p>' +
							'<p class="wallpaper-screen-type">Right-click the image below and select to save the image to your computer</p>' +
							'<div class="wallpaper-size">' +
									'<div class="wallpaper-'+type+' wallpaper-thumb selected-standard" id="wallpaper-'+type+'"><img src="/apps/vision/1_3_1/gallery/assets/testing/wallpaper_142_105.jpg" alt="Standard 4:3 aspect ratio of '+assetTitle+'" width="142" height="105" /> <p>Standard (4:3)</p></div>' +
									'<br clear="all" /><div id="wallpaper-cta-buttons"><p class="wallpaper-back-btn"><a href="#">Back</a></p> <p class="wallpaper-done-btn"><a href="#">Done</a></p></div>'+
								'</div>' +
						'</div>' +
					'</div>');
					
				
				}
				else if (type == 'wide')
				{
					var path = "wall_uxga";
					
					var overlayHTMLStep2 = glow.dom.create('<div class="vision-gallery-wallpaper-overlay-step2">' +
					'<div class="wallpaper-back"><a href="#" class="vision-gallery-wallpaper-back-step2">< Back to Image Gallery</a></div>' +
					'<hr />' +
					'<h2>Download as wallpaper</h2>' +
						'<div class="wallpaper-container">'+
							'<p class="wallpaper-step-count">Step 2 of 2<br/></p>' +
							'<p class="wallpaper-screen-type">Right-click the image below and select to save the image to your computer</p>' +
							'<div class="wallpaper-size">' +
									'<div class="wallpaper-'+type+' wallpaper-thumb selected-wide" id="wallpaper-'+type+'"><img src="/apps/vision/1_3_1/gallery/assets/testing/wallpaper_142_105.jpg" alt="Wide 16:9 aspect ratio of '+assetTitle+'" width="185" height="110"/> <p>Wide (16:9)</p></div>' +
									'<br clear="all" /><div id="wallpaper-cta-buttons"><p class="wallpaper-back-btn"><a href="#">Back</a></p> <p class="wallpaper-done-btn"><a href="#">Done</a></p></div>'+
								'</div>' +
						'</div>' +
					'</div>');
					
					glow.dom.get(".wallpaper-screen-type").css("margin-left", "0");
				}
				else {
					alert("Type is neither standard or wide!");
				}

					wallpaperOverlayStep2 = new glow.widgets.Overlay(overlayHTMLStep2, {
						modal: false,
						x: "50%",
						y: "30%"
	
					});

					
					glow.dom.get(".wallpaper-screen-type").css("margin-left", "0");
					glow.dom.get(".wallpaper-step-count").css("margin-left", "33%");
					
					var wallpaperThumb = glow.dom.get(".wallpaper-thumb img");
					//wallpaperThumb.attr("src", "http://"+vision.gallery.downloadserver+"/apps/vision/"+vision.gallery.version+"/gallery/assets"+assetSite+"/"+path+"/"+assetRoot+".jpg");
					
					var downloadURL = "http://open.live.bbc.co.uk/dynamic_images/vapps_wallpaper_"+type+"_"+id+"/http://www.bbc.co.uk/apps/vision/gallery/assets/"+assetSite+"/"+path+"/"+assetRoot+".jpg";
					
					/*test to see if IC will serve up a wallpaper sized image with logo. Requires yaml metadata filename and image filename match*/
					var test = "http://open.live.bbc.co.uk/dynamic_images/vapps_wallpaper_"+type+"/extdev.bbc.co.uk/apps/vision/recipes/"+type+"_test.jpg";
					
					wallpaperThumb.attr("src", test);
				//CSS changes for mixed layout type (default to 16:9 layout)	
				if (layout == 'mixed_gallery') {
					glow.dom.get(".vision-gallery-wallpaper-overlay-step2").css("width", "425px").css("height","350px");
					glow.dom.get(".wallpaper-container").css("margin-left", "7%");
					glow.dom.get(".wallpaper-size").css("padding-top","10px");
				}
					
					wallpaperOverlayStep2.show();
					wallpaperOverlay.hide();
			
				//ensure both overlays disappear when going back to lightbox	
				var hideWallpaperOverlay2 = glow.events.addListener(
					".vision-gallery-wallpaper-back-step2",
					"click",
					function() {
						wallpaperOverlayStep2.hide();
					});
				
				var wallpaperDone = glow.events.addListener(
				".wallpaper-done-btn",
				"click",
				function() {
					//hide both overlays
					wallpaperOverlay.hide();
					wallpaperOverlayStep2.hide();
				});
				
				var wallpaperBack = glow.events.addListener(
				".wallpaper-back-btn",
				"click",
				function() {
					//remove highlight
					glow.dom.get(".wallpaper-wide").css("background-color", "#313131");
					glow.dom.get(".wallpaper-standard").css("background-color", "#313131");
					glow.dom.get(".wallpaper-screen-type").css("margin-left", "22%");
					
					//show 1st step before closing 2nd step panel to prevent flicker (it will remain behind 2nd step overlay regardless)
					wallpaperOverlay.show();
					wallpaperOverlayStep2.hide();
				});
				
			}

		},
	
		showFullScreen: function(id) {
			alert("Id of this asset is: "+id);
		},
		
		/*
		 
		 Function to build a popover (for the badge) and show it
		 Just needs an ID of an asset
		 
		*/
		getPopoverData:function(id){
			count = id+1;
			var grid = document.getElementById("vision-gallery-grid").innerHTML;
			var nav = document.getElementById("vision-gallery-nav").innerHTML;
			var type = vision.gallery.cache[id].file_type;
			var description = vision.gallery.cache[id].user_description;
			var name = vision.gallery.cache[id].user_name;
			var title = vision.gallery.cache[id].user_title;
			var itemid = vision.gallery.cache[id].id;

			if(description == null){
				description = " ";
			};
			if(name ==null){
				name = " ";
			}
			else{
				name = "by " + name;
			};
			if(title == null){
				title= " ";
			};
			closeButton = "<a href='#' class='vision-gallery-close'><img src='/apps/vision/gallery/css/badge/f/close.gif' alt='Close'></a>"
			img = '<li class="vision-gallery-popoverarea">'+closeButton+'<div id="vision-gallery-lightboximg"><span></span><img src="/apps/vision/gallery/assets/'+ vision.gallery.cache[id].site +'/thumb_286/'+ vision.gallery.cache[id].file_root +'.jpg" alt="Close lightbox" title="Close lightbox" /></div></li>';
			
			document.getElementById("vision-gallery-grid").innerHTML = img;
			//document.getElementById("vision-gallery-nav").innerHTML = "<p>"+title+" "+name+"</p>";
			document.getElementById("vision-gallery-nav").innerHTML = "";
			imgtitle = '<h2>'+title+' '+name+'</h2>';
			
			
			
			/*
			 
			 Wire close button up to replace the popover with the saved contents of the grid on click
			 
			*/
			closebutton = glow.dom.get(".vision-gallery-close");
				var returngrid = glow.events.addListener(
						closebutton,
						 'click',
						function (event) {
							document.getElementById("vision-gallery-grid").innerHTML = grid;
							document.getElementById("vision-gallery-nav").innerHTML = nav;
							vision.gallery.initActions();
							return false;
						        }
						);
			
					
		},
		
		
		/*
		
		EMP JS - shows the EMP vid in an element we specify
		Needs a valid element ID and an asset ID
		
		*/
		
		showEMP:function(element, itemid){
			var emp = new bbc.Emp();  
				emp.setWidth(vision.gallery.empwidth);  
				emp.setHeight(vision.gallery.empheight);    
				emp.setDomId(element);
				if (vision.gallery.site) {
					emp.setPlaylist("http://"+vision.gallery.domain+"bbc.co.uk/apps/ifl/apps/vision/"+vision.gallery.version+"/gallery/queryengine?config=emp;attrib_1=site;oper_1=eq;val_1_1="+vision.gallery.site+";attrib_2=id;oper_2=eq;val_2_1="+itemid+";");
				}
				else {
					emp.setPlaylist("http://"+vision.gallery.domain+"bbc.co.uk/apps/ifl/apps/vision/"+vision.gallery.version+"/gallery/queryengine?config=emp;attrib_1=source;oper_1=eq;val_1_1="+vision.gallery.source+";attrib_2=id;oper_2=eq;val_2_1="+itemid+";");
				}
				emp.write();
		},
		
		showEMPDesc:function(element, itemid){
			document.getElementById(element).innerHTML = "<p class='vision-emp-title'>"+vision.gallery.cache[itemid].user_title+"</p><p class='vision-emp-name'>"+vision.gallery.cache[itemid].user_name+"</p><p class='vision-emp-description'>"+vision.gallery.cache[itemid].user_description+"</p>";
			
		},
		
		/*
		 
		 Function to swap the contents of the lightbox on paging
		 Needs to know which way it's going and what the current id is
		 
		*/
		swapLightbox:function(direction,id){
				
				//get value for swapping page behind lightbox next
				if(direction == "back"){
					pageSwap = id;
				}
				else if(direction == "next"){
					pageSwap = id+1;
				}
				//pick which way to go next and swap page if on last
				if(pageSwap%vision.gallery.imagesInPage == 0){			
					if(direction == "back"){
						nextid = id-1
						vision.gallery.getGallery('back');
					}
					else if(direction == "next"){
						nextid = id+1
						vision.gallery.getGallery('next');
					}
				}
				else if(direction == "back"){
					nextid = id-1
				}
				else if(direction == "next"){
					nextid = id+1
				}
				
				vision.gallery.swap = true;
				
				vision.gallery.getLightboxData(nextid);
				return false;
		}
		
	}//end gallery object
	
	//Gets glow - sets what modules we need for comments from glow. Add any new ones here. Calls vision.gallery.init when done to do onload functions
	gloader.load(["glow", "1", "glow.dom", "glow.events", "glow.anim", "glow.data", "glow.net", "glow.widgets.Panel", "glow.widgets.Mask", "glow.embed"], {
			async: true,
			onLoad: function(glowInstance) {
			glow = glowInstance;
			glow.ready(vision.gallery.init);
			//window.glow = glow;
		     }
		     });
	
	
})();//endenclosure
