(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 wallpaperPanel;
		
		var myAnim;
		
		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",
		order: "DESC",
		source: null, //SET IN CORE.SSSI
		currentPage: 1,
		requestedPage: 1,
		highestPageVisited: 1,
		slideshowState:"play",
		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;
			/* create div to insert navigation into */
			var elNav = document.createElement('div');
			elNav.id = "vision-gallery-nav";
			
			/* insert the div after the gallery */
			var elemView = document.getElementById("vision-gallery-view");
			var insertionPoint = document.getElementById("vision-gallery-moreinfo");
			elemView.insertBefore(elNav, insertionPoint);

			/* 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();
			}
			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 = '';
			}
			var gallery = vision.gallery,
				getRef = glow.net.get("/cgi-perl/apps/ifl/queryengine.pl/apps/vision/"+vision.gallery.version+"/gallery?pagesize=" + vision.gallery.queryEnginePageSize + ";page=" + vision.gallery.queryEnginePage +";sort_1="+vision.gallery.sort+";sortsense_1=" + vision.gallery.order + ";attrib_1=source;oper_1=contains;val_1_1=" + vision.gallery.source + ";OutputFormat=JSON;OutputContent=ISO-8859-1", {
				//getRef = glow.net.get("/cgi-perlx/apps/ifl/queryengine.pl/apps/vision/gallery?Config=ratings;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= 	 /testsite/visionapps/ugc/dev/ugc-uploadbridge.shtml ;OutputFormat=JSON;OutputContent=ISO-8859-1;JSEscape=1", {
			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);
				
				/* 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 widescreen - add description text */
					if (vision.gallery.type == "widescreen") {
						
						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 == "widescreen") {
					var nameTitle = '<p><a href="' + vision.gallery.assetpage +  gallery.cache[i].id + '" class="vision-gallery-'+vision.gallery.action+'"><span class="title">'+trimtitle+'</span></a></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></p>';		
					}
				}
				imgType = gallery.cache[i].file_type;
			
				/* 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
				 
				*/
				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 && isNaN(text)){
				
				// Strip out all line breaks.
				text = text.replace(new RegExp( "\\n\\s\\n", "g" ), " ");
				text = text.replace(new RegExp( "\\r", "g" ), " ");
				    
				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.length == length)){
					text = trimtext[0];
				}
				else{
					text = trimtext[0] +"...";
				}
			}
			else if (!isNaN(text) && text != null){
				text = text;
			}
			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>';
			}
			
			/*
			 
			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';
				}			
			
				/*
				var lbBody = '<div id="vision-gallery-image">'+
					'<span></span>'+
					'<img src="/apps/vision/gallery/assets'+vision.gallery.cache[id].site+'/'+layouttype+'/'+vision.gallery.cache[id].file_root+'.jpg" alt="'+title+'" />' +
					'</div>' +
					'<div id="vision-gallery-lbratings-overlay">' +
						'<div class="tl"></div>' +
						'<div class="tr"></div>' +
						'<div class="ratings-tb"><div></div></div>' +
							ratingsForm +
						'<div class="bl"></div>' +
						'<div class="br"></div>' +
						'<div class="ratings-bb"><div></div></div>' +
					'</div>';
				*/
				
				/* 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('+itemid+');return false;">Download wallpaper</a></p>';
			}
			if (vision.gallery.fullscreen == "true") {
				lbBody += '<p class="vision-gallery-fullscreen-btn">&nbsp;</p>';
			}
			
			lbBody += '</div>';
			
			//show author
			var name = vision.gallery.cache[id].user_name;
			if ((name != '') && (vision.gallery.author != 'false')){
				if (vision.gallery.copyright == "copyright") {
					lbBody += '<div class="vision-gallery-lbauthor">&copy; '+ name +'</div>';
				} else {
					lbBody += '<div class="vision-gallery-lbauthor">'+ vision.gallery.copyright +' '+ name +'</div>';
				}
			}
			else {
				lbBody += '';
			}
			
			/* 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);

			/* 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 10px 259px");
				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 == "4_3") {
				glow.dom.get("#vision-gallery-lightboxnav").addClass("nav-spacing");
				glow.dom.get("#vision-gallery-lightboxnav").css("padding-left", "40%");				
			}
			else if (layouttype == "mixed_portrait") {
				glow.dom.get(".vision-gallery-image").addClass("mixed-portrait");
				glow.dom.get(".mixed-portrait").css("padding","0 43px");
				
			}
			else if (layouttype == "mixed_landscape") {
				glow.dom.get(".vision-gallery-image").addClass("mixed-landscape");
				glow.dom.get(".mixed-landscape").css("padding","90px 0");			
			}
			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");
			}
			
			/*
			  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";
					};
				}
			 }
			 
			 /*
			   Add a click event to the close link - will also stop any animations in progress if the lightbox is shut and one is running
			 */
			var closebutton = glow.dom.get("#vision-lightbox-close");
				var closer = glow.events.addListener(
						closebutton,
						 'click',
						function (event) {
							if(myAnim){
								myAnim.stop();
							}
							return false;
						        }
						);
		},
		
		/*
			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");
		},
		
		/* Place holder for functionality which will come in later release */
		
		downloadWallpaper: function(id) {
			alert("Id of this asset is: "+id);	
		},
		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);
				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
