/* BUG SOLVE
 *
 * This code solves many problems related to when IE6 users have page loads set to always
 ************************************************************************************************/
try {
  document.execCommand("BackgroundImageCache", false, true);
} catch(err) {}


// Stick all javascript in a self-executing function
// to create a specific namespace for this application
( function() {

	var isFireFox=false;
	if (navigator.userAgent.indexOf("Firefox")!=-1) {
		isFireFox=true;
	}
	
	var isFireFoxPC = false;
	if (isFireFox && navigator.userAgent.indexOf("Windows") != -1) {
		isFireFoxPC = true;
	}
	
	var isIE = window.ActiveXObject ? true : false; // ActiveX is only used in Internet Explorer
	var isIE6=isIE;
	    
	var isIE7=false;
	if (window.external && (typeof window.XMLHttpRequest == "object")) {
		isIE7=true;
		isIE6=false;
	}

	var isSafari3=false;
    if (navigator.userAgent.indexOf("Version/3")!=-1 && navigator.userAgent.indexOf("Safari")!=-1) {
		isSafari3=true;
    }

	var imageCropDimensions = function(imagesize, holdersize) {
		var holderratio=holdersize[0]/holdersize[1];	
		var returndimensions =  new Array();
		if ((holderratio) < (imagesize[0]/imagesize[1])) {
			returndimensions[0] = parseInt(Math.abs(holdersize[1] * (imagesize[0]/imagesize[1])));
			returndimensions[1] = holdersize[1];
			returndimensions[2] = parseInt((returndimensions[0] - holdersize[0])/2);
			returndimensions[3] = 0;
		}
		else {
			returndimensions[0] = holdersize[0];
			returndimensions[1] = parseInt(Math.abs(holdersize[0] * (imagesize[1]/imagesize[0])));
			returndimensions[2] = 0;
			returndimensions[3] = parseInt((returndimensions[1] - holdersize[1])/2);
		}
		return returndimensions;
	}

	// Function to create a custom time date string from a date object
	var makeDateTimeStringFromDateObject = function(dateObj) {
		var returnstring = makeDoubleDigit(dateObj.getDate())+"/"+makeDoubleDigit(dateObj.getMonth()+1)+"/"+dateObj.getFullYear()+"/";
		returnstring += makeDoubleDigit(dateObj.getHours())+"/"+makeDoubleDigit(dateObj.getMinutes()+1)+"/"+makeDoubleDigit(dateObj.getSeconds());
		return returnstring;
	}


	// Function to convert a time string in format dd/mm/yy/hh/mm/ss
	// to date string in form dd/mm/yy
	var makeDateStringFromDateTimeString = function(timestring) {
		var stringarray = timestring.split("/");
		var returnstring = stringarray[0]+"/"+stringarray[1]+"/"+stringarray[2]; 
		return returnstring;
	}
	
	/* FUNCTION trimToMaxCharWords() by Alex Kearns
	 *
	 * This function takes a string of words and returns a string of words that has a max char
	 * length of maxcharacters. Ie, it trims words off the end of the string so the string is
	 * below or equal to maxcharacters. It adds a "..." at end if words are trimmed
	 ************************************************************************************************/
	var trimToMaxCharWords = function(wordstring,maxcharacters) {
	    var wordarray = wordstring.split(" ");
	    var numwords=wordarray.length;
	    var newstring="";
	    var laststring="";
	    for (var counter=0; counter<numwords; counter++) {
	        laststring=newstring
	        if (counter!=0) {
	            newstring+=(" "+wordarray[counter]);
	        }
	        else {
	            newstring+=wordarray[counter];
	        }
	        if (newstring.length>maxcharacters) {
	            return (laststring+"...");
	        }
	    }
	    return newstring;
	}

	// Function to check that a string is not full of empty spaces
	var checkForChars = function(anystring) {
		var foundchar=false;
		for (var counter=(anystring.length-1); counter>=0; counter--) {
			if (anystring[counter] != " ") {
				foundchar=true;
				break;	
			}	
		}
		return foundchar;
	}		
	
	// Functionthat returns a reversed copy of the submitted array
	var getReversedArray = function(inarray) {
		var returnarray = new Array();
		var arraylength = inarray.length
		for (var counter=0; counter<arraylength; counter++) {
			returnarray[arraylength-1-counter]=inarray[counter];
		}
	return returnarray;
	} 
	
	var makeDoubleDigit = function(anynum) {
		if (anynum == 0) {
			return "00";	
		}
		if (anynum < 10) {
			return "0"+anynum;	
		}
		else {
			return anynum;	
		}
	}
	
	// This function returns true if it can find any of the words
	// in searchterms within the image-name, description, and keywords
	// fields of the imaheholder
	var isSearchTermInImage = function(searchterms, imageholder) {
		// Clean up search string
		// Then split into seperate wprds
		if (searchterms == "Search") {
			searchterms=" ";	
		}
		searchterms = searchterms.replace(/'/g,"");
		searchterms = searchterms.replace(/"/g,'');
		searchterms = searchterms.toLowerCase();
		searchterms = searchterms.split(" ");
	
		// Now join all the fields that need search into one string
		var searchtext = " "+$(imageholder).find("span.image-name").text()+" ";
		searchtext+=$(imageholder).find("span.description").text()+" ";
		searchtext+=$(imageholder).find("span.keyword").text()+" ";
		searchtext=searchtext.toLowerCase();
									
			// Now compare each of the search words with the text that needs searching 
		var searchtermsfound=false;
		for (var counter=0; counter<searchterms.length; counter++) {
			if (searchtext.search(searchterms[counter]) != -1) {
				searchtermsfound=true;
				break;
			}
		}
		return searchtermsfound;
	}
	
	
	// Function for alpha sorting a jQuery array by an element within
	// each jquery object in the array.
	var getAlphaSortedJQueryArray = function(jqueryarray, textelement) {
		var returnarray = new Array();
		var jqueryarraylength=jqueryarray.length
		for (var counter=0; counter<jqueryarraylength; counter++) {
			returnarray[counter]=$(jqueryarray[counter]).find(textelement).text()+"-|-"+counter;
		}
		returnarray.sort();
		for (var counter=0; counter<jqueryarraylength; counter++) {
			returnarray[counter]=jqueryarray[parseInt(returnarray[counter].split("-|-")[1])];
		}
		return returnarray;
	}
			
	var getDateSortedJQueryArray = function(jqueryarray, dateelement) {
		var returnarray=new Array();
		var numofitems=jqueryarray.length;
		for (var counter=0; counter<numofitems; counter++) {
			returnarray[counter] = jqueryarray[counter];
		}
		
		var secondsinyear=60*60*24*30*12;
		var secondsinmonth=60*60*24*30;
		var secondsinday=60*60*24;
		var secondsinhour=60*60;
		var secondsinminutes=60;
		
		var sortfunction = function(a,b) {
			var adatetext=$(a).find(dateelement).text();
			var avalue=(parseInt(adatetext.split("/")[3],10)*secondsinhour)+(parseInt(adatetext.split("/")[4],10)*secondsinminutes)+(parseInt(adatetext.split("/")[5],10))+(parseInt(adatetext.split("/")[0],10)*secondsinday)+(parseInt(adatetext.split("/")[1],10)*secondsinmonth)+(parseInt(adatetext.split("/")[2],10) * secondsinyear);
			var bdatetext=$(b).find(dateelement).text();
			var bvalue=(parseInt(bdatetext.split("/")[3],10)*secondsinhour)+(parseInt(bdatetext.split("/")[4],10)*secondsinminutes)+(parseInt(bdatetext.split("/")[5],10))+(parseInt(bdatetext.split("/")[0],10)*secondsinday)+(parseInt(bdatetext.split("/")[1],10)*secondsinmonth)+(parseInt(bdatetext.split("/")[2],10) * secondsinyear);
			
			// alert(adatetext+ " " + avalue + " | "+bdatetext+ " " + bvalue + " | " + (avalue-bvalue));
			return (avalue-bvalue);	
		}
		returnarray.sort(sortfunction);
		return returnarray;
	}

	// Function that returns dimensions (width, height, marginbleft and margintop) to make an image
	// fit perfectly within a box of size set by containerhieght and containeriwdith
	// There is also the option of providing offset margins
	// Plus, if an image object is provided, the function sets the size of that to the dimensions 
	var sizeImageToFitBox = function(imageObj, origwidth, origheight, containerwidth, containerheight, specleftoffset, spectopoffset) {
		var newwidth, newheight, marginleft, marginright;
		if (origwidth/origheight > containerwidth/containerheight) {
			newheight=parseInt(origheight/origwidth*containerwidth);
			newwidth=containerwidth;
		}
		else {
			newwidth=parseInt(origwidth/origheight*containerheight);
			newheight=containerheight;
		}
		marginleft = parseInt((containerwidth-newwidth)/2)+specleftoffset;
		margintop = parseInt((containerheight-newheight)/2)+spectopoffset;
		if (imageObj) {
			$(imageObj)
			.css({height: newheight, width: newwidth, marginLeft: marginleft, marginTop: margintop});
		}
		return [newwidth, newheight, marginleft, margintop];
	}


	    function pageScrollY() {
	        var y;
	        if (self.pageYOffset) { // all except Explorer
	            y = self.pageYOffset;
	        }
	        else if (document.documentElement && document.documentElement.scrollTop) { // Explorer 6 Strict
	            y = document.documentElement.scrollTop;
	        }
	        else if (document.body) { // all other Explorers
	            y = document.body.scrollTop;
	        }
	    return y;
	    }
	
	    function findPos(obj) {
	        var curleft = curtop = 0;
	        if (obj.offsetParent) {
	            curleft = obj.offsetLeft
	            curtop = obj.offsetTop
	            while (obj = obj.offsetParent) {
	                curleft += obj.offsetLeft
	                curtop += obj.offsetTop
	            }
	        }
	        return [curleft,curtop];
	    }   
	
		var isOverElement = function(mousepos, element) {
			var elementpos=findPos($(element).get()[0]);
			if (mousepos[0] > elementpos[0] && mousepos[0] < (elementpos[0]+$(element).width()) && mousepos[1] > elementpos[1] && mousepos[1] < (elementpos[1]+$(element).height())) {
				return true;
			}
			else {
				return false;
			}
		}
	
		var specialIsOverElement = function(mousepos, element) {
			var elementpos=findPos($(element).get()[0]);
			if (mousepos[0] > elementpos[0] && mousepos[0] < (elementpos[0]+parseInt($(element).css("width"))) && mousepos[1] > elementpos[1] && mousepos[1] < (elementpos[1]+parseInt($(element).css("height")))) {
				return true;
			}
			else {
				return false;
			}
		}
	
	    function checkwhere(e) {
	        xCoord = false;
	        yCoord = false;
	        if (document.layers){
	            xCoord = e.x;
	            yCoord = e.y;
	        }
	        else if (document.all){
	            xCoord = event.clientX;
	            yCoord = event.clientY;
	        }
	        else if (document.getElementById){
	            xCoord = e.clientX;
	            yCoord = e.clientY;
	        }
	        if (isIE || isFireFox) {
	            yCoord+=pageScrollY();
	        }
	        return [xCoord, yCoord];
	    }
	
	var galleryGlobalDaysArray = new Array('Sunday','Monday','Tuesday','Wednesday', 'Thursday','Friday','Saturday');
	var galleryGlobalMonthsArray = new Array("January","February","March","April","May","June", "July","August","September","October","November","December");
	var galleryGlobalMonthsShortArray = new Array("Jan","Feb","Mar","Apr","May","Jun", "Jul","Aug","Sep","Oct","Nov","Dec");
	var galleryGlobalOneDay=1000*60*60*24;
	var galleryGlobalDaySuffixArray=new Array("st","nd","rd","th","th","th","th","th","th","th","th","th","th","th","th","th","th","th","th","th", "st","nd","rd","th","th","th","th","th","th","th","st","nd","rd","th","th","th","th","th","th","th");


	$(document).ready( function() {
	
	
		if (isFireFox) {
			$("body").addClass("browser-type-firefox");
		}	

		if (isFireFoxPC) {
			$("body").addClass("browser-type-firefoxPC");
		}	

		if (isIE6) {
			$("body").addClass("browser-type-ie6");
		}
		
		if (isIE7) {
			$("body").addClass("browser-type-ie7");
		}

		if (isSafari3) {
			$("body").addClass("browser-type-safari3");
		}

		if (isIE6 || isIE7) {
		    document.body.ondrag = function () { return false; };
		}

		$("div.gallery-container").each( function() {
		
			var galleryUserName= $(this).find("span.main-user-name").text();
			var galleryUserId= $(this).find("span.main-user-id").text();
			var galleryUserSession= $(this).find("span.main-session-code").text();
			var isLoggedIn = ($(this).find("span.main-is-logged-in").text() == "true") ? true : false;
			
			var testflag=false;
			var galleryIdCounter=1;
			var galleryNumCounter=1;
	
			var imageDrag=false;
			var popupOffsetX="";
			var popupOffsetY="";
			var popupOrigX;
			var popupOrigY;
			var selectedImage="";
			var returnScroll=false;
			var initialiseGalleryAlbum;
			var thisGallery=this;
			var imagePopup = $(this).find("div.image-popup");
			var uploadInstructions = $(this).find("div.upload-instructions");
			
			var albumHolder = $(this).find("div.album-holder");
			var albumHolderStage = $(albumHolder).find("div.album-carousel-stage");
			var	thisSlideShowHolder = $(thisGallery).find("div.slideshow-holder");
			var galleryInfoHolderTop = $(thisGallery).find("h3.album-info");
			var galleryInfoPhotoName = $(galleryInfoHolderTop).find("a.photo-name"); 
			var galleryInfoAlbumName = $(galleryInfoHolderTop).find("a.album-name");
			
			var galleryIsEmpty=false;
			
			// As we always start on the master album page, we add a special class to the title
			// to remove the album name and a few other little touches
			// We'll also add a click event to it, which will always return the user to the all photos album
			$(galleryInfoHolderTop)
			.addClass("album-info-main-album-selected")
			.click( function() {
				$(albumHolder).find("a.album-block-view-all-images").click();				
				return false;	
			});
			
			
			// Cancel click event on photo name element
			$(galleryInfoPhotoName).click( function() {
				return false;	
			});
				
			var createNewAlbumBlock = $(this).find("div.album-holder div.album-block-create");
			
			$(createNewAlbumBlock).hover( function() {
				$(this).addClass("album-block-hover");
			}, function() {
				$(this).removeClass("album-block-hover");
			});
	
			var prototypeImageInfoComment = $(thisGallery).find("div.image-info-holder div.image-info-comments-block").html();
	
			var slideshowOpen=false;
			var imageInfoBoxOpen=false;
			var menuSortPhotoOpen=false;
			var menuSortAlbumOpen=false;

			
			var imageInfoHolder=$(this).find("div.image-info-holder");
			var lastAlbumBlockHover="";
			
			var thisProgressBarBlock=$(thisGallery).find("div.gallery-progress-meter-holder");
			var thisGalleryFaderBlock=$(thisGallery).find("div.gallery-fader-block");
			
			var thisAlbumBlockProgressBar=$(thisGallery).find("div.album-block-progress-meter-holder");
			var thisAlbumBlockFader=$(thisGallery).find("div.album-block-fader");
			
			var searchBoxFocused = true;
			
			var popUpConfirmMessageOpen = false;
			var popUpRotatingImage = false;
			var popUpNameEditOpen = false;
			var currentlySorting=false;
			var currentlySearching=false;
			var generatingSlideshow=false;
			
			var	currentlySortingAlbums=false;
			
			
			var mainStagePageInfo = $(thisGallery).find("p.main-stage-page-info:eq(0)");

			// Function to fade out search box and sort menu when they are disabled
			var fadeOutSortAndSearch = function() {
				$(thisGallery).find("div.search-box:eq(0)").css({opacity: 0.3}).addClass("search-box-disabled");
				$(thisGallery).find("div.photo-sort-menu-holder:eq(0)").css({opacity: 0.3}).addClass("photo-sort-menu-disabled");	
			} 

			var fadeInSortAndSearch = function() {
				$(thisGallery).find("div.search-box:eq(0)").css({opacity: 1}).removeClass("search-box-disabled");	
				$(thisGallery).find("div.photo-sort-menu-holder:eq(0)").css({opacity: 1}).removeClass("photo-sort-menu-disabled");	
			} 


			// function to show an error message and then fade it out
			var displayGalleryErrorMessage = function(thismessage) {
				$(thisGallery).find("p.gallery-error-message").css({display:"none"});
				var newerrorel = $('<p class="gallery-error-message">'+thismessage+'</p>');
				$(thisGallery).find("div.gallery").append(newerrorel);
				setTimeout( function() {
					$(newerrorel).animate({opacity: 0}, 500, function() {
						$(this).remove();
					});
				},3000);
				return;						
			}

			// funciton for loading empty gallery images
			// This has been duplicated in a few places - should consolidate at some point
			var updateemptythumbs = function(thumbelement) {
				var thisthumbinfo=$(thumbelement).find("span.thumb-info");
				if(thisthumbinfo.length > 0) {
					var thisthumbinfotext = $(thisthumbinfo).text();
					var thisthumbsrc=thisthumbinfotext.split("|")[0];
					var thisthumbwidth=parseInt(thisthumbinfotext.split("|")[1].split(",")[0]);
					var thisthumbheight=parseInt(thisthumbinfotext.split("|")[1].split(",")[1]);
					$(thisthumbinfo).remove();
					var newthumbimage=$('<img src="'+thisthumbsrc+'" alt="" height="'+thisthumbheight+'" width="'+thisthumbwidth+'" />');
					$(thumbelement).prepend(newthumbimage);
					var topmargin=parseInt((146-thisthumbheight)/2);
					var leftmargin=parseInt((150-thisthumbwidth)/2);
					$(newthumbimage).css({marginLeft: leftmargin, marginTop: topmargin, visibility: "visible" });
					$(newthumbimage).addClass("awaiting-initialisation");
				}
			}
	
			// Function to delete an image from an album
			var deleteImage = function(imageholder) {
				if (!isLoggedIn) {
					return false;	
				}
								
				var selectedgalleryalbum=$(thisGallery).find("div.gallery-album-selected");
				var thisimageid=parseInt($(imageholder).find("span.image-id").text());
				var thisimageposition=parseInt($(imageholder).find("span.image-pos").text());
				var thisalbumid = $(selectedgalleryalbum).find("span.album-id").text();
				var needloadingimagenum=thisimageposition+15+(15-((thisimageposition) % 15));
				$(selectedgalleryalbum).find("div.image-holder:has(span.image-src):eq("+needloadingimagenum+")").each( function() {
					updateemptythumbs(this);
				});
	
				var nowtimedate= makeDateTimeStringFromDateObject(new Date());
				var ismasteralbum = ($(imageholder).parents(".gallery-album").get()[0].className.indexOf("gallery-album-master") != -1) ? true : false;

				var ajaxPhotoId = thisimageid;
				
				// AJAX Call
				// Overview: This AJAX request is called when a user chooses to delete an image
				// The server should delete the image identified by the unique identifier photoId or almbumPhotoId
				// If photoId is set, then we are dealing with a master image, else an album copy of the image

				$.post("/gallerydemo/mobykogallery/assets/ajax/delete-image-from-album.php", {photoId: ajaxPhotoId, albumId: thisalbumid, albumUpdateDate:nowtimedate}, function(xml) {
					// Ajax call back function
					// In this case, we just silently fail if there is a failure.
				}); 
				
				// End of Ajax Call

				if (ismasteralbum) {
					// If the image to be deleted is from thr master album, then we really need to also delete
					// it from any other album that contains the image
					// Basically, we'll search for all images with the same id 
					// (including the master image) and delete them 
					$(thisGallery).find("div.gallery div.image-holder span.image-id:contains("+thisimageid+")").each( function() {
						if ($(this).text() == thisimageid) {
							var thisdeletegalleryalbum= $(this).parents(".gallery-album");
							var thisdeletealbumid = $(thisdeletegalleryalbum).find("span.album-id").text();
							var thisdeleteimageholder = $(this).parent();
							$(thisdeleteimageholder).remove();
							$(thisdeletegalleryalbum).find("a.refresh-album").click();
							
							// Now we have to find the album block related to this album
							$(thisGallery).find("div.album-block span.album-id:contains("+thisdeletealbumid+")").each( function() {
								if ($(this).text() == thisdeletealbumid) {
									var thisalbumblock = $(this).parents("div.album-block");
									var thisalbumblocknumholder=$(thisalbumblock).find("div.selected-content h5");
									// Decrement the number of photos in this album
									var newalbumimagenum=parseInt($(thisalbumblocknumholder).text())-1;
									$(thisalbumblocknumholder).text(newalbumimagenum+" photos");
									// Now updated 'album updated' date
									$(thisalbumblock).find("div.selected-content h6").text("Updated "+makeDateStringFromDateTimeString(nowtimedate));
								}
							});
						}
					});
				}
				else { // Here, we just delete the particular album photo and update only details about that album
					$(imageholder).remove();
					$(selectedgalleryalbum).find("a.refresh-album").click();
					// Now decrement num of images listed in relevent album-block
					var albumblocknumholder=$(thisGallery).find("div.album-block-selected:eq(0) div.selected-content h5");
					var newalbumimagenum=parseInt($(albumblocknumholder).text())-1;
					$(albumblocknumholder).text(newalbumimagenum+" photos");
					// Now updated 'album updated' date
					$(thisGallery).find("div.album-block-selected:eq(0) div.selected-content h6").text("Updated "+makeDateStringFromDateTimeString(nowtimedate));
				}
			}
	
			// Function to rotate image on the main gallery carousel 
			var rotateGalleryImage = function(imageholder, newthumbsrc, newimagesrc) {
				var thisimagewidth = parseInt($(imageholder).find("span.image-size").text().split(",")[0]);
				var thisimageheight = parseInt($(imageholder).find("span.image-size").text().split(",")[1]);
				var thisthumbwidth = parseInt($(imageholder).find("img").attr("width"));
				var thisthumbheight = parseInt($(imageholder).find("img").attr("height"));
				// Now save the new values in the imageholder and resize the image
				$(imageholder).find("span.image-src:eq(0)").text(newimagesrc);
				$(imageholder).find("span.image-size:eq(0)").text(thisimageheight+","+thisimagewidth);
				var thisthumbtopmargin = parseInt((146-thisthumbwidth)/2);
				var thisthumbleftmargin = parseInt((150-thisthumbheight)/2);
				
				// NOw we need to rotate all images in the gallery that have the same id
				var thisimageid = $(imageholder).find("span.image-id").text();
				
				// Now lets update the rotation for all the other copies of this phot
				$(thisGallery).find("div.gallery div.image-holder span.image-id:contains("+thisimageid+")").each( function() {
					if ($(this).text() == thisimageid) {
						if ($(this).parent().find("img").length > 0) {
							$(this).parent()
								.find("img:eq(0)")
								.attr("src", newthumbsrc)
								.attr("height", thisthumbwidth)
								.attr("width", thisthumbheight)
								.css({width: thisthumbheight, height: thisthumbwidth})
								.css({marginLeft: thisthumbleftmargin, marginTop: thisthumbtopmargin})
							.end()
							.find("span.thumb-size")
								.text(thisthumbheight+","+thisthumbwidth)
							.end()
							.find("span.image-size")
								.text(thisimageheight+","+thisimagewidth)
							.end()
							.find("span.image-src")
								.text(newimagesrc)
							.end();
							
						}
						else {
							var newthumbinfotext = newthumbsrc+"|"+thisthumbheight+"|"+thisthumbwidth;
							$(this).parent()
								.find("thumb-info")
								.text(newthumbinfotext)
							.end()
							.find("span.thumb-size")
								.text(thisthumbheight+","+thisthumbwidth)
							.end()
							.find("span.image-size")
								.text(thisimageheight+","+thisimagewidth)
							.end();
						}
					}
				});

			}
	
			// Function to find the dimensions and margins for centering an image in a container 
			var centreImageDimensions = function(holderwidth, holderheight, origimagewidth, origimageheight) {
				var imageratio=origimagewidth/origimageheight;
				if (imageratio > holderwidth/holderheight) {
					var imagewidth=holderwidth;
					var imageheight=parseInt(imagewidth/imageratio);
				}
				else {
					var imageheight=holderheight;
					var imagewidth=parseInt(imageheight * imageratio);
				}
				var marginleft = parseInt((holderwidth-imagewidth)/2);
				var margintop = parseInt((holderheight-imageheight)/2);
				return [imagewidth, imageheight, marginleft, margintop];
			}
	
			// Function for returning user to the main gallery screen (from Slideshow)
			// when they click on the album name in the gallery breadcrumb
			$(galleryInfoAlbumName).click( function() {
				if (slideshowOpen && !generatingSlideshow) {
					// The below click faker closes the slideshow
					$(thisSlideShowHolder).find("a.back-to-album").click();
				}
				
				if (imageInfoBoxOpen && !generatingSlideshow) {
					// The below click faker closes the image info panel
					$(imageInfoHolder).find("a.back-to-album").click();
				}
				
				return false;			
			});
	
			// This function ensues that menus slide up when the mosue is not over them
			// And that the search box defocuses when mouse is not over search area
			// Also hides thumbnal pause play hover element
			$(document).mouseover( function() {
				if (menuSortPhotoOpen) {
					$(thisGallery).find("div.photo-sort-menu-holder a.close-menu").click();
				}
				if (menuSortAlbumOpen) {
					$(thisGallery).find("div.album-sort-menu-holder a.close-menu").click();
				}
			});
			
			// Album carousel stuff
			$(this).find("div.album-holder").each( function() {
				var albumCarouselHeight=297;
				var albumStage=$(this).find("div.album-carousel-stage");
				var currentScroll=0;
				var albumCurrentlyScrolling=false;
				var thisalbumHolderStage = this;
				
				var displayAlbumArrows = function() {
					var albumstageheight=$(albumStage).height();
					if (albumstageheight <= (albumCarouselHeight+12)) {
						$(thisalbumHolderStage).find("a.carousel-scroll-down").css({display: "none"});
						$(thisalbumHolderStage).find("a.carousel-scroll-up").css({display: "none"});
					}
					else if (currentScroll == 0) {
						$(thisalbumHolderStage).find("a.carousel-scroll-down").css({display: "block"});
						$(thisalbumHolderStage).find("a.carousel-scroll-up").css({display: "none"});
					}
					else if (currentScroll <= -($(albumStage).height()-albumCarouselHeight)) {
						$(thisalbumHolderStage).find("a.carousel-scroll-down").css({display: "none"});
						$(thisalbumHolderStage).find("a.carousel-scroll-up").css({display: "block"});
					}
					else {
						$(thisalbumHolderStage).find("a.carousel-scroll-down").css({display: "block"});
						$(thisalbumHolderStage).find("a.carousel-scroll-up").css({display: "block"});
					}
				}
				displayAlbumArrows();
	
				// Click faker function for resetting the album block carousel
				$(this).find("a.album-block-reset").click( function() {
					albumCurrentlyScrolling=false;
					currentScroll=0;
					$(albumStage).stop().css({top: currentScroll});
					displayAlbumArrows();
					return false;
				});
	
				// View all videos button
				$(this).find("a.album-block-view-all-images").click( function() {
					if (currentlySearching || currentlySorting || currentlySortingAlbums) {
						return false;	
					}
					if ($(albumHolderStage).find("div.album-block").length > 4) {
						albumCurrentlyScrolling=true;
						currentScroll = 0;	
						$(albumStage).stop().animate({top: 0}, 500, function() {
							albumCurrentlyScrolling=false;	
							displayAlbumArrows();
							$(albumHolderStage).find("div.album-block:eq(0)").click();
						});
					}
					else {
						$(albumHolderStage).find("div.album-block:eq(0)").click();
					}
					return false;
				});

				// Click faker function for scrolling album block carousel to reveal album block at bottom
				$(this).find("a.album-block-scroll-to-end").click( function() {
					if ($(albumHolderStage).find("div.album-block").length > 4) {
						albumCurrentlyScrolling=true;
						currentScroll = -($(albumStage).height()-albumCarouselHeight);	
						$(albumStage).stop().animate({top: currentScroll}, 1000, function() {
							albumCurrentlyScrolling=false;	
							displayAlbumArrows();
						});
					}
					return false;
				});
	
				$(this).find("a.carousel-scroll-up").click( function() {
					if (albumCurrentlyScrolling) {
						return false;	
					}
					albumCurrentlyScrolling=true;
					var previousscrolloffset=currentScroll;
					currentScroll+=albumCarouselHeight;
					if (currentScroll > 0) {
						currentScroll=0;	
					}
					var thisanimatespeed = Math.abs(previousscrolloffset-currentScroll) * 3;
					$(albumStage).animate({top: currentScroll}, thisanimatespeed, function() {
						if (currentScroll == 0) { // Needed for CSS bug
							$(this).css({top: 0});
							displayAlbumArrows();
						}
						albumCurrentlyScrolling=false;	
					});
					displayAlbumArrows();
					return false;
				});		
				
				$(this).find("a.carousel-scroll-down").click( function() {
					if (albumCurrentlyScrolling) {
						return false;	
					}
					albumCurrentlyScrolling=true;
					var previousscrolloffset=currentScroll;
					currentScroll-=albumCarouselHeight;
					var albumstageheight=$(albumStage).height();
					if (albumstageheight < (albumCarouselHeight+12)) {
						albumCurrentlyScrolling=false;
						return false;	
					}
					
					if (currentScroll < -($(albumStage).height()-albumCarouselHeight)) {
						currentScroll = -($(albumStage).height()-albumCarouselHeight);	
					}
					var thisanimatespeed = Math.abs(previousscrolloffset-currentScroll) * 3;
					$(albumStage).animate({top: currentScroll}, thisanimatespeed, function() {
						albumCurrentlyScrolling=false;	
					});
					displayAlbumArrows();
					return false;
				});		
				
			});
			
			$(imagePopup).mouseover( function() {
				return false;
			});
			
			$(uploadInstructions).mouseover( function() {
				return false;
			});
	
			$(document).mouseup( function() {
				if (imageDrag) {
					$(imagePopup).mouseup();
					imageDrag=false;
					if (isIE6 || isIE7) {
						document.body.onselectstart = function () { return true; };
					}
				}
				if (lastAlbumBlockHover) {
					$(lastAlbumBlockHover).removeClass("album-block-drag-hover");
					lastAlbumBlockHover=false;
				}			
			});
					
			$("body").mouseover( function() {
				$(uploadInstructions).css({display:"none"});
				if (!popUpRotatingImage) {
					$(imagePopup).css({ left: -1000, top: -1000});
				}
			});
			
			$(imagePopup).mousedown( function(e) {
				if (popUpRotatingImage || popUpConfirmMessageOpen) {
					return false;	
				}
				if (popUpNameEditOpen) {
					// Need to return true to allow default edit actions
					return true;	
				}
				$(this).addClass("image-popup-drag");
				var initmousepos=checkwhere(e);
				$(this).unbind("mousemove").mousemove( function(e) {
					$(this).unbind("mousemove");			
					var secondmousepos=checkwhere(e);
					if (secondmousepos[0]==initmousepos[0] && secondmousepos[1]==initmousepos[1]) {
						$(this).mouseup();
						return false;	
					}  
					$(this).stop().css({opacity: 0.85});
					var mouseclickpos = checkwhere(e);
					var origpopuppos = findPos($(selectedImage).parent().get()[0]);
					popupOrigX=origpopuppos[0];
					popupOrigY=origpopuppos[1];
		
					if (mouseclickpos[0]) {
						popupOffsetX = mouseclickpos[0]-popupOrigX+10; 
						popupOffsetY = mouseclickpos[1]-popupOrigY+10; 
					}
					imageDrag=true;
					if (isIE6 || isIE7) {
						document.body.onselectstart = function () { return false; };
					}
					$(this).css({opacity: 0.7, left: popupOrigX-10, top: popupOrigY-10});
					return false;
				});
				return false;
			});
	
	
			//Image Info Box Functions
			// The Image nfo box is launched when a user clicks on the eye
			// icon on the image popup or when they simply click on an image
			$(imageInfoHolder).each( function() {
				var selectedimagenum=0;
				var currentlyselectedimage="";
				var thisinfoholder=this;
				var firstloadedimage="";
				var lastloadedimage="";
				var imageinfonumofimages="";
	
				var thisholderwidth=771;
				var containerwidth=442;
				var containerheight=408;
				var containermargin=30;
				var imageinfoblockprototype=$(this).find("div.image-info-content").clone();
				var imageInfoStage=$(this).find("div.image-info-stage");
				var imageinfocurrentlyscrolling=true;
				var imageinfoalbumname="";
				
				var imageInfoToSomewhereButton = $(imageInfoHolder).find("a.back-to-somewhere:eq(0)");
				var imageInfoToSomewhereButtonOpen = false;
							
				// This function creates a new image info block, taking info from the image supplied in the argument
				// It also sets up a variety of actions, such as printing the photo, sending it to a friend, etc.
				var createimageinfoblock = function(imageobj) {
					var newimageinfoblock=$(imageinfoblockprototype).clone();
					var thisimageparent=$(imageobj).parent();
					var thisimagename=$(thisimageparent).find("span.image-name").text();
					var thisimagealbum=imageinfoalbumname;
					var thisimagekeyword=$(thisimageparent).find("span.keyword").text();
					var thisimagedescription=$(thisimageparent).find("span.description").text();
					var thisimagedate=$(thisimageparent).find("span.date").text();
					var thisimagesrc=$(thisimageparent).find("span.image-src").text();
					var thisimagecreator=$(thisimageparent).find("span.created-by").text();
					var deleteconfirmmessageopen=false;
					var rotatemessageopen=false;
					var previousdescriptiontext=thisimagedescription;
					var numofnewcomments = parseInt($(thisimageparent).find("span.num-of-new-comments").text());
					var commentsnumtext = (numofnewcomments > 0) ? "("+numofnewcomments+")" : "";
					var imageinfopurchasedcontent=false;
					
					// Dealing with purchased content
					if ($(thisimageparent).find("span.source").text()=="PURCHASED") {
						imageinfopurchasedcontent=true;
						$(newimageinfoblock).addClass("image-info-holder-purchased-content");
					}
					
					// This code is repeated elsewhere in this function
					// Could do with integrating 
					// This code sets up the top margin for the image info menu
					// so that it lines up with the top of the images
					var tempthisimagesize=$(imageobj).parent().find("span.image-size").text().split(",");
					var tempthisimagesrc=$(imageobj).parent().find("span.image-src").text();
					var tempimagedimensions = centreImageDimensions(containerwidth, containerheight, parseInt(tempthisimagesize[0]), parseInt(tempthisimagesize[1]));
					var thisinfoimagetopmargin=tempimagedimensions[3];
					if (isIE6 || isIE7) {
						thisinfoimagetopmargin = (thisinfoimagetopmargin <= 50) ? thisinfoimagetopmargin : 50;
					}
					else {
						thisinfoimagetopmargin = (thisinfoimagetopmargin <= 65) ? thisinfoimagetopmargin : 65;
					}
					$(newimageinfoblock).find("div.image-info-text h3").text("This Photo").css({marginTop: thisinfoimagetopmargin });


					$(newimageinfoblock).find("div.image-info-text p.image-info-name span").text(thisimagename);
					$(newimageinfoblock).find("div.image-info-text p.image-info-created-by span").text(thisimagecreator);
					$(newimageinfoblock).find("div.image-info-text a.image-info-comments span").text(commentsnumtext);
					$(newimageinfoblock).find("div.image-info-text p.image-info-album span").text(thisimagealbum);
					$(newimageinfoblock).find("div.image-info-text p.image-info-keyword span").text(thisimagekeyword);
					if (imageinfopurchasedcontent) {
						$(newimageinfoblock).find("div.image-info-text p.image-info-description span").text(trimToMaxCharWords(thisimagedescription,200));
						$(newimageinfoblock).find("div.image-info-text p.image-info-date").html("Purchased on <span>"+makeDateStringFromDateTimeString(thisimagedate)+"</span");
					}
					else {
						$(newimageinfoblock).find("div.image-info-text p.image-info-description span").text(thisimagedescription);
					$(newimageinfoblock).find("div.image-info-text p.image-info-date span").text(makeDateStringFromDateTimeString(thisimagedate));
					}
					
					var thistexteditblock = $(newimageinfoblock).find("textarea.image-info-description-edit-block");
					var imageinfosendblock=$(newimageinfoblock).find("div.image-info-send-block");
					var imageinfocommentblock=$(newimageinfoblock).find("div.image-info-comments-block");

					var setUpBackToSomeWhereButton = function(imageinfoblock, callback) {
						imageInfoToSomewhereButtonOpen = true;
						$(imageInfoToSomewhereButton)
						.addClass("back-to-somewhere-visible")
						.unbind()
						.css({opacity: 0})
						.animate( {opacity: 1}, 500)
						.click( function() {
							imageInfoToSomewhereButtonOpen=false;
							$(this)
							.unbind()
							.animate({opacity: 0}, 500, function() {
								$(this).removeClass("back-to-somewhere-visible");
							});
							$(imageinfoblock).animate( {opacity: 0}, 500, function() {
								$(this).css({display:"none"});
								if (callback) {
									callback();
								}
							});
							return false;
						});
					}
					
					var imageinfocommentsloading=false;
					// This function is called when the user clicks on the comments button
					$(newimageinfoblock).find("div.image-info-text a.image-info-comments").click( function() {
						
						if (imageinfocommentsloading || imageinfopurchasedcontent) {
							return false;
						}
						imageinfocommentsloading=true;
						
						var ajaxloader=$('<span class="ajax-loader">Loading</span>');
						$(this).parent().append(ajaxloader);

						var thisclickedbutton = this;
						
						var thiscommentimageid = $(thisimageparent).find("span.image-id").text();
						
						var ismasteralbum = ($(thisimageparent).parents(".gallery-album").get()[0].className.indexOf("gallery-album-master") != -1) ? true : false;
		
						if (ismasteralbum) {
							var ajaxPhotoId = thiscommentimageid;
							var ajaxAlbumPhotoId = "";	
						} 
						else {
							var ajaxPhotoId = "";
							var ajaxAlbumPhotoId = thiscommentimageid;	
						}
				
						// AJAX Call
						// Overview: This request is made when a viewer chooses to view comments for a particular image
						// Variables: We send the id of the photo either as photoId if a master image, or albumPhotoId if 
						// an album photo
						// Response: The server returns a list of comments in XML format
						
						$.post("/gallerydemo/mobykogallery/assets/ajax/get-comments-for-image.php", { photoId: thiscommentimageid, albumPhotoId: thiscommentimageid}, function(xml) {
							
							// Ajax call back
							// NOTE that this callback is a big function, and extends down to the End of ajax comment below
											
							// Clear the comments number on the button because user will now have seen the comments
							$(thisclickedbutton).find("span").text("");
														
							setUpBackToSomeWhereButton(imageinfocommentblock);
							var prototypeCommentSubject, newcontent, commentcarouselstage;
							$(imageinfocommentblock)
							.each( function() {
								// Clean out any existing content and replace with a clone of the prototype content
								// Also clone prtotype comment subject block
								newcontent = $(prototypeImageInfoComment).clone();
								$(this).empty().append(newcontent);
								commentcarouselstage = $(this).find("div.image-comments-carousel-stage");
								prototypeCommentSubject = $(commentcarouselstage).find("div.comment-subject-holder:eq(0)").clone();
								$(commentcarouselstage).empty();
								
								// Now paste in the comment got by ajax
								
								$(xml).find("comment").each( function() {
									var newcommentblock = $(prototypeCommentSubject).clone();
									$(newcommentblock).find("div.comment-face-holder img").attr("src",$(this).find("face-image-src").text());
									$(newcommentblock).find("div.comment-details h5").text($(this).find("name").text());
									$(newcommentblock).find("div.comment-details span.date").text($(this).find("date").text());
									$(newcommentblock).find("div.comment-details span.time").text($(this).find("time").text());
									$(newcommentblock).find("span.comment-id").text($(this).find("comment-id").text());
									$(newcommentblock).find("p.comment-body").text($(this).find("body-text").text());
									
									$(commentcarouselstage).append(newcommentblock);
								});
								
								// Set the Total comment and new comment fields
								$(this).find("p.image-info-comments-num-of span.new-comments").text(numofnewcomments+" New");
								$(this).find("p.image-info-comments-num-of span.total-comments").text($(xml).find("comment").length+" Total");

								// Finally, reset numofcomments to zero for next time
								$(thisimageparent).find("span.num-of-new-comments").text("0")
								numofnewcomments=0;
							})
							.css({display: "block", opacity: 0})
							.animate({ opacity: 1}, 500, function() {
								
								imageinfocommentsloading=false;
								$(ajaxloader).remove();

								$(imageinfocommentblock).each( function() {
									
									var commentcarousel = $(this).find("div.image-comments-carousel");
									var expandedcarouselheight = 233;
									var contractedcarouselheight= 125;
									var commentcarouselheight = 233;
									var numofcomments = $(commentcarouselstage).find("div.comment-subject-holder").length;
									var carouseltopoffset = 0;
									var previouscarouseltopoffset = 0;
									var carouselstageheight = $(commentcarouselstage).height();
									var commentuparrow = $(this).find("a.image-comments-carousel-up");
									var commentdownarrow = $(this).find("a.image-comments-carousel-down");
									var commentsscrolling = false;
									var commentpostblock = $(this).find("div.comments-block-post-message");
									var postblockexpanded=false;
									var postblockanimating = false;
									var postblockexpandedheight=200;
									var postblockcontractedheight=86;
									
									var updatecommentcarouselarrows = function() {
										if (carouselstageheight < commentcarouselheight) {
											$(commentuparrow).css({display: "none"});
											$(commentdownarrow).css({display: "none"});
										}
										else if (carouseltopoffset == 0) {
											$(commentuparrow).css({display: "none"});
											$(commentdownarrow).css({display: "block"});
										}
										else if (carouseltopoffset  <= -(carouselstageheight - commentcarouselheight)) {
											$(commentuparrow).css({display: "block"});
											$(commentdownarrow).css({display: "none"});
										}
										else {
											$(commentuparrow).css({display: "block"});
											$(commentdownarrow).css({display: "block"});
										}
									}
									
									updatecommentcarouselarrows();
									
									var initialiseImageInfoComment = function(thissubjectblock) {
										$(thissubjectblock).find("a.delete").click( function() {
											var deleteconfimblock = $('<div class="delete-confirmation">Delete this post? <a href="#">Yes</a> <a href="#">No</a></div');
											$(this).parent().append(deleteconfimblock);
											$(deleteconfimblock).animate({ width: 140 }, 500, function() {
												$(this).find("a").click( function() {
													var thisoption = $(this).text();
													switch(thisoption) {
														case "No":
															$(deleteconfimblock).animate({width: 0}, 500, function() {
																$(this).remove();
															});
														break;
														case "Yes":
															$(thissubjectblock)
															.animate({opacity: 0}, 500, function() {
																if (isIE7 || isIE6) {
																	$(this).css({visibility:"hidden"});
																}
																$(this).animate({ height: 0}, 500, function() {
																	// Find id at last possible moment to give greater chance
																	// that an id has been returned to the comment by the server
																	var thiscommentid = $(thissubjectblock).find("span.comment-id").text();
																	$(this).remove();
																	
																	// Update the total comment number
																	var prevcommenttotal = parseInt($(imageinfocommentblock).find("p.image-info-comments-num-of span.total-comments").text(),10);
																	$(imageinfocommentblock).find("p.image-info-comments-num-of span.total-comments").text((prevcommenttotal-1)+" Total");

																	// AJAX CALL
																	// Overview: This request takes place when a user chooses
																	// to delete a comment linked to a photo
																	// Variables: We simply send the id of the comment that
																	// is to be deleted

																	$.post("/gallerydemo/mobykogallery/assets/ajax/delete-image-comment.php", {commentId: thiscommentid }, function(xml) {
																		// Ajax callback
																		// In this case, we fail silently
																	});
																	
																	// End of Ajax call
																	
																	
																	// Update carouselvariables
																	carouselstageheight = $(commentcarouselstage).height();
																	updatecommentcarouselarrows();
																});
															});
														break;
													}
													return false;
												});
												
											});
											return false;
										});
									}
									
									$(this).find("div.comment-subject-holder").each( function() {
										initialiseImageInfoComment(this);
									});
									
									$(commentdownarrow).click( function() {
	
										if (commentsscrolling) {
											return false;	
										}
										commentsscrolling = true;
										var newoffset = carouseltopoffset - commentcarouselheight;
										carouseltopoffset = (newoffset < -(carouselstageheight - commentcarouselheight)) ? -(carouselstageheight - commentcarouselheight) : newoffset;
										var animatespeed = parseInt(Math.abs(carouseltopoffset - previouscarouseltopoffset))*4;
										previouscarouseltopoffset=carouseltopoffset;
										updatecommentcarouselarrows();
										$(commentcarouselstage).animate( { top: carouseltopoffset }, animatespeed, function() {
											commentsscrolling=false;
										});
										return false;
									});
									
									$(commentuparrow).click( function() {
										if (commentsscrolling) {
											return false;	
										}
										commentsscrolling = true;
										var newoffset = carouseltopoffset + commentcarouselheight;
										carouseltopoffset = (newoffset >=0 ) ? 0 : newoffset;
										var animatespeed = parseInt(Math.abs(carouseltopoffset - previouscarouseltopoffset))*4;
										previouscarouseltopoffset=carouseltopoffset;
										updatecommentcarouselarrows();
										$(commentcarouselstage).animate( { top: carouseltopoffset }, animatespeed, function() {
											commentsscrolling=false;
										});
										return false;
									});
	
									$(commentpostblock).find("div.top-box p").click( function() {
										if (!postblockexpanded) {
											$(commentpostblock).find("a.post-comment").click();
										}
									});
									
									$(commentpostblock).find("a.post-comment").click( function() {
										if (!postblockexpanded) {
											if (postblockanimating) {
												return false;	
											}
											postblockanimating = true;
											postblockedexpanded = true;
											$(commentpostblock).find("textarea").css({display:"block"});
											$(commentpostblock).animate({ height: postblockexpandedheight }, 500, function() {
												postblockanimating=false;
												postblockexpanded = true;
											});
											$(commentcarousel).animate({ height: contractedcarouselheight }, 500, function() {
												commentcarouselheight = contractedcarouselheight;
												updatecommentcarouselarrows();
											});
										}
										else {
											// Post message
											var newcommentext = $(commentpostblock).find("textarea").val();
											
											if (newcommentext != "") {
												
												var animatespeed = parseInt(Math.abs(carouseltopoffset - 0))*2+1;
												if (animatespeed > 500) {
													animatespeed=500;
												}

												$(commentcarouselstage).animate({top: 0}, animatespeed, function() {
													previouscarouseltopoffset=0;
													carouseltopoffset=0;
													updatecommentcarouselarrows();

													var newcommenttimedate = new Date();
											        var newcommentdate=newcommenttimedate.getDate();
											        var newcommentmonth=newcommenttimedate.getMonth()
											        var newcommentyear=newcommenttimedate.getFullYear();
													
													
													var newcommentdatetext = galleryGlobalMonthsShortArray[newcommentmonth]+" ";
													newcommentdatetext+= newcommentdate+galleryGlobalDaySuffixArray[newcommentdate]+" ";
													newcommentdatetext+= makeDoubleDigit(newcommentyear-2000);
													
													var newcommenttimetext = makeDoubleDigit(newcommenttimedate.getHours() % 12)+":";
													newcommenttimetext += makeDoubleDigit(newcommenttimedate.getMinutes())
													if ((newcommenttimedate.getHours() / 12) >= 1) {
														newcommenttimetext+="pm";
													}
													else {
														newcommenttimetext+="am";
													}
																								
													var newcommentblock = $(prototypeCommentSubject).clone();
													if (isIE6 || isIE7) {
														$(newcommentblock).find("div.comment-face-holder").addClass("ie-opacity-fix");
														$(newcommentblock).find("div.comment-details").addClass("ie-opacity-fix");
														$(newcommentblock).find("p.comment-body").addClass("ie-opacity-fix");
													}
													$(newcommentblock).find("div.comment-face-holder img").attr("src",$(thisGallery).find("span.face-image-src:eq(0)").text());
													$(newcommentblock).find("div.comment-details h5").text($(thisGallery).find("span.main-user-name:eq(0)").text());
													$(newcommentblock).find("div.comment-details span.date").text(newcommentdatetext);
													$(newcommentblock).find("div.comment-details span.time").text(newcommenttimetext);
													$(newcommentblock).find("span.comment-id").text("");
													$(newcommentblock).find("p.comment-body").text(newcommentext);
													
													initialiseImageInfoComment(newcommentblock);
													
													$(newcommentblock).css({opacity: 0})
													$(commentcarouselstage).prepend(newcommentblock);
													
													$(newcommentblock).animate({opacity: 1}, 500)
													$(commentpostblock).find("a.clear-comment").click();
													
													// Update height of carousel stage to take accunt of the newly added comment
													carouselstageheight = $(commentcarouselstage).height();
													
													// Update the total comment number
													var prevcommenttotal = parseInt($(imageinfocommentblock).find("p.image-info-comments-num-of span.total-comments").text(),10);
													$(imageinfocommentblock).find("p.image-info-comments-num-of span.total-comments").text((prevcommenttotal+1)+" Total");

													var ismasteralbum = ($(thisimageparent).parents(".gallery-album").get()[0].className.indexOf("gallery-album-master") != -1) ? true : false;
									
													if (ismasteralbum) {
														var ajaxPhotoId = thiscommentimageid;
														var ajaxAlbumPhotoId = "";	
													} 
													else {
														var ajaxPhotoId = "";
														var ajaxAlbumPhotoId = thiscommentimageid;	
													}
													
													// AJAX CALL
													// Add comment to database
													// Overview: This request takes place when the user adds a comment
													// to the database
													// Variables: we send the photoId or albumPhotoId (deopending whether a
													// a master image or not), plus the commenttext, authorId, galleryUserId,
													// authorName (might not need these author one because they are the 
													// logged in user) and the current datetime  
													var thisajaxdate = makeDateTimeStringFromDateObject(newcommenttimedate);
													$.post("/gallerydemo/mobykogallery/assets/ajax/create-new-image-comment.php", {photoId:ajaxPhotoId, albumPhotoId: ajaxAlbumPhotoId, commentText: newcommentext, authorId: galleryUserId, authorName:galleryUserName, datetime:thisajaxdate}, function(xml) {
														var commentreturnid = $(xml).find("comment-id").text();
														$(newcommentblock).find("span.comment-id").text(commentreturnid);
													});
													
													// End of Ajax request
												}); 
											} 
										} 
										
										return false;	
									});
									
									$(commentpostblock).find("a.clear-comment").click( function() {
										if (postblockexpanded) {
											if (postblockanimating) {
												return false;	
											}
											postblockanimating = true;
											postblockedexpanded = true;
											$(commentpostblock).animate({ height: postblockcontractedheight }, 500, function() {
												$(commentpostblock).find("textarea").css({display:"none"}).text("").val("");
												postblockanimating=false;
												postblockexpanded=false;
											});
											$(commentcarousel).animate({ height: expandedcarouselheight }, 500, function() {
												commentcarouselheight = expandedcarouselheight;
												updatecommentcarouselarrows();
											});
										}
										else {

										} 
										
										return false;	
									});
									
									
									
								});
							});
						});
						
						return false;
					});
					
					// End of AJAX Request

					// This function is called when the user clicks on the send to friend option
					$(newimageinfoblock).find("div.image-info-text a.image-info-send").click( function() {
						if (imageinfopurchasedcontent) {
							return false;	
						}
						setUpBackToSomeWhereButton(imageinfosendblock);
						$(imageinfosendblock)
						.css({display: "block", opacity: 0})
						.animate({ opacity: 1}, 500, function() {
								
						});
						return false;
					});

					// These are all the send to friend functionality
					$(newimageinfoblock).find("div.image-info-send-block").each( function() {
						var sendPopupMessageOpen=false;
						var sendPopupMessage = $(this).find("div.send-popup-message");
						var popupMessageTimer=false;
							
						$(this).find("div.send-popup-message a.close").click( function() {
							if (popupMessageTimer) {
								clearTimeout(popupMessageTimer);
								popupMessageTimer="";
							}

							$(sendPopupMessage)
							.find("div.inner")
								.stop()
								.animate( {top: 146}, 500, function() {
									$(sendPopupMessage).css({display:"none"});
									sendPopupMessageOpen=false;
								})
							.end()

							return false;
						});
							
						// Function for displaying a popup message in the send-to area of the app
						var displaySendPopupMessage = function(titletext, message, autoclose) {
							if (popupMessageTimer) {
								clearTimeout(popupMessageTimer);
								popupMessageTimer="";
							}
							if (autoclose) {
								$(sendPopupMessage).find("a.close").css({display:"block"});
							}
							else {
								$(sendPopupMessage).find("a.close").css({display:"none"});
							}
							$(sendPopupMessage)
							.css({display:"block"})
							.find("div.inner")
							.stop()
								.find("h5")
									.html(titletext)
								.end()
								.find("p")
									.html(message)
								.end()
								.animate( {top: 0}, 500, function() {
									if (autoclose) {
										popupMessageTimer = setTimeout( function() {
											$(sendPopupMessage).find("a.close").click();
										}, 3000);
									}
									sendPopupMessageOpen=true;
								})
							.end()
						}
								
						$(this)
						.find("div.send-block-from")
							.each( function() {
								var thissendblockfrom = this;
								$(this).find("span").mouseover( function() {
									var savedtext = $(this).text();
									var editinput = $('<input value="'+savedtext+'" />');
									var textholder = this;
									var editmouseoutfunction="";
									sendFromEditOpen=true;
									$(thissendblockfrom).append(editinput);
									$(editinput)
									.focus()
									.blur(function() {
										var finishedtext=$(this).val();	
										if (!checkForChars(finishedtext)) {
											finishedtext=savedtext;
										}
										$(textholder).text(finishedtext)
										$(this).remove();
										sendFromEditOpen=false;
										
									})
									.keydown( function(e) {
										if (e.keyCode == 13) {
											$(this).blur();
										}
									})
									.mouseout( function() {
										$(this).blur();
										return false;
									});
									return false;
								});
							})
						.end()

						$(this)
						.find("div.send-block-to")
							.each( function() {
								
								var thissendblock = this;
								$(this)
								.find("input")
									.unbind()
									.focus( function() {
										var thisstartval= $(this).val();
										if (thisstartval == "Enter email") {
											$(this).val("")
										}
										$(this).addClass("send-selected");
									})
									.mouseover( function() {
										$(this).focus();
										return false;	
									})
									.blur( function() {
										var thisstartval= $(this).val();
										if (thisstartval == "") {
											$(this).val("Enter email")
										}
										$(this).removeClass("send-selected");
									})
									.keydown( function(e) {
										if (e.keyCode == 13) {
											$(thissendblock).find("a.send-block-to-add-email").click();
											$(this).focus();
											return false;
										}
									})
								.end()
								
								$(this)
								.find("a.send-block-to-add-email")
								.unbind()
								.click( function() {
									var newemailaddress = $(thissendblock).find("input").val();
									if (newemailaddress != "" && newemailaddress != "Enter email") {
										var emailrepositry = $(imageinfosendblock).find("div.send-block-receivees");
										var newemailreceivee = $('<p><span>'+newemailaddress+'</span><a href="#">x</a> </p>');
										$(emailrepositry).prepend(newemailreceivee);
										$(newemailreceivee).find("a").click( function() {
											$(newemailreceivee).remove();
											return false;	
										});
										$(thissendblock).find("input").val("Enter email").focus();

									}
									return false;
								})									
							})
						.end()
							
						$(this)
						.find("div.send-block-to-message-block")
							.each( function() {
								var thissendblock=this;
								$(this)
								.find("a.send-block-to-message-clear")
									.click( function() {
										$(thissendblock).find("textarea").val("").text("");
										return false;
									})
								.end()
									
								$(this)
								.find("a.send-block-to-message-send")
									.click( function() {
										var emailsarray = new Array() 
											
										$(imageinfosendblock).find("div.send-block-receivees span").each( function() {
											emailsarray[emailsarray.length]=$(this).text();
												
										});
											
										var inputboxtext = $(imageinfosendblock).find("div.send-block-to input").val();
										if (inputboxtext && inputboxtext != "Enter email") {
											emailsarray[emailsarray.length]=inputboxtext;
										}
										if (emailsarray.length < 1) { 
											displaySendPopupMessage("Email alert", "Please enter <span>at least one</span> email address.", true);
										}
										else {
											var pluralise = emailsarray.length > 1 ? "s" : ""; 
											displaySendPopupMessage("Email confirmation", "You picture has been sent. Your friend"+pluralise+" will <span>receive an email</span> containing your picture shortly.", true);
											$(imageinfosendblock).find("div.send-block-to input").val("Enter email");
											$(imageinfosendblock).find("div.send-block-receivees").empty();
											
											var thisemailimageid = $(thisimageparent).find("span.image-id").text();

											var emailliststring = emailsarray.join(" ");
											var ismasteralbum = ($(thisimageparent).parents(".gallery-album").get()[0].className.indexOf("gallery-album-master") != -1) ? true : false;
									
											if (ismasteralbum) {
												var ajaxPhotoId = thisemailimageid;
												var ajaxAlbumPhotoId = "";	
											} 
											else {
												var ajaxPhotoId = "";
												var ajaxAlbumPhotoId = thisemailimageid;	
											}

											// AJAX CALL
											// Email image to list of recipients
											// Send photoid/albumphotoid and space delineated list of email addresses
											// Note, at present no front end checking of email addresses has been done
											$.post("/gallerydemo/mobykogallery/assets/ajax/send-image-to-friends.php", { photoId: ajaxPhotoId, albumPhotoId: ajaxAlbumPhotoId, emailList: emailliststring }, function() {
												// Callback function
												// At present, we will fail silently if there is a failure.
											});
											
											// End of ajax call
										}
										return false;
									})
								.end()
							})
						.end()
					});

					// This function takes place when a user mouseovers the image name text
					// when in the image info screen
					$(newimageinfoblock).find("div.image-info-text p.image-info-name span").mouseover( function() {
						if (imageinfopurchasedcontent) {
							return false;	
						}
						var savedtext = $(thisimageparent).find("span.image-name").text();
						var thisinputholder = $('<li class="image-info-name-edit-input-holder"><input value="'+savedtext+'" /></li>');
						
						var editinput = $(thisinputholder).find("input");
						var nameholder = this;
						var editmouseoutfunction="";
						$(this).parents("ul.image-info-photo-details").append(thisinputholder);
						
						$(editinput)
						.focus()
						.blur(function() {
							var finishedtext=$(this).val();	
							if (!checkForChars(finishedtext)) {
								finishedtext=savedtext;
							}
							$(nameholder).text(trimToMaxCharWords(finishedtext,25))
							$(thisimageparent).find("span.image-name").text(finishedtext);
							$(thisinputholder).remove();
							
							if (finishedtext != savedtext) {
								var ismasteralbum = ($(thisimageparent).parents(".gallery-album").get()[0].className.indexOf("gallery-album-master") != -1) ? true : false;

								var ajaxPhotoId = $(thisimageparent).find("span.image-id").text();

								// Now lets update the name for all the other copies of this photo
								$(thisGallery).find("div.gallery div.image-holder span.image-id:contains("+ajaxPhotoId+")").each( function() {
									if ($(this).text() == ajaxPhotoId) {
										$(this).parent().find("span.image-name").text(finishedtext);
									}
								});

								// AJAX Call
								// Update name of image
								// Send photoId  and new name
								// Return success failure
								$.post("/gallerydemo/mobykogallery/assets/ajax/update-image-name.php", {photoId: ajaxPhotoId, newPhotoName: finishedtext}, function(xml) {
									// We fail sliently again;
								});
								// End of Ajax call
							}

						})
						.keydown( function(e) {
							if (e.keyCode == 13) {
								$(this).blur();
							}
						})
						.mouseout( function() {
							$(this).blur();
							return false;
						});
						return false;	
					});


					
					// This function takes place when a user mouseovers the description text
					// The function allows the user to edit the description text
					$(newimageinfoblock).find("div.image-info-text p.image-info-description span").mouseover( function() {
						if (imageinfopurchasedcontent) {
							return false;
						}
						
						var thisdescriptiontext = this;
						var thisdescriptiontextheight=$(thisdescriptiontext).height();
						
						$(thisdescriptiontext).css({display:"none"});
						
						$(thistexteditblock)
						.text($(newimageinfoblock).find("div.image-info-text p.image-info-description span").text())
						.css({display:"block", height: thisdescriptiontextheight+16})
						.focus()
						.blur(function() {
							var enteredtext=$(this).val();
							if (enteredtext=="") {
								enteredtext=previousdescriptiontext;
							}
							$(thisdescriptiontext)
							.text(enteredtext);
							$(this).css({display:"none"});
							$(thisdescriptiontext).css({display: "block"});
							$(thisimageparent).find("span.description").text(enteredtext);
							if (isLoggedIn && enteredtext != previousdescriptiontext) {
								
								var ismasteralbum = ($(thisimageparent).parents(".gallery-album").get()[0].className.indexOf("gallery-album-master") != -1) ? true : false;
								var ajaxPhotoId = $(thisimageparent).find("span.image-id").text();

								// Now lets update the description for all the other copies of this phot
								$(thisGallery).find("div.gallery div.image-holder span.image-id:contains("+ajaxPhotoId+")").each( function() {
									if ($(this).text() == ajaxPhotoId) {
										$(this).parent().find("span.description").text(enteredtext);
									}
								});

								// AJAX Call
								// Update description text for this image
								// Overview: This request is called when the user updates the description text
								// for a photo 
								// Variables: Photoid plus new 
								// photo description text

								$.post("/gallerydemo/mobykogallery/assets/ajax/update-photo-description.php", {photoId: ajaxPhotoId, photoDescription: enteredtext}, function(xml) {
									// Call back
									// In this case, we silently fail
								});
								
								// End of Ajax call
							}
							previousdescriptiontext=enteredtext;
						})
						.keydown( function(e) {
							if (e.keyCode == 13) {
								$(this).blur();	
								return false;
							}
						})
						.mouseout( function() {
							$(this).blur();
						});
					});
									
	
					// This function is called when a user decides to print an image from the image info pane
					// The function creates a new page containing the image, and then sets up the system print box
					$(newimageinfoblock).find("div.image-info-text a.image-info-print").click( function() {
						
						var thisimagename = $(thisimageparent).find("span.image-name").text();
						var thisdescription = $(thisimageparent).find("span.description").text();
						var thisimagesrc = $(thisimageparent).find("span.image-src").text();
						
						var insertHTML = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">\n';
						insertHTML += '<html xmlns="http://www.w3.org/1999/xhtml" lang="en-gb" xml:lang="en-gb">\n';
						insertHTML += '\t<head>\n';
						insertHTML += '\t\t<title>Mobyko Image Gallery.</title>\n';
						insertHTML += '\t\t<meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />\n';
						insertHTML += '\t\t<meta name="language" content="en-gb" />\n';
						insertHTML += '\t\t<meta http-equiv="content-language" content="en-gb" />\n';
						insertHTML += '\t\t<meta name="description" content="Try the photo gallery before you join Mobyko. You\'ll see how easy it is to organise your photos into albums. You can also add comments and share with friends." />\n';
						insertHTML += '\t\t<meta name="keywords" content="address addressbook book backup back-up back up calendar messages mobile names numbers online phone photos save SMS sync synchronization synchronisation text texts videos" />\n';
						insertHTML += '\t\t<style type="text/css" media="screen">\n';
						insertHTML += '\t\t\th1 {\n'; 
						insertHTML += '\t\t\t\tfont-size: 20px;\n';
						insertHTML += '\t\t\t\tfont-family: Verdana, "sans-serif";\n';
						insertHTML += '\t\t\t}\n';
						insertHTML += '\t\t\timg {\n';
						insertHTML += '\t\t\t\tdisplay: block;\n';	
						insertHTML += '\t\t\t}\n';
						insertHTML += '\t\t\tp {\n';
						insertHTML += '\t\t\t\tfont-size: 12px;\n';
						insertHTML += '\t\t\t\tfont-family: Verdana, "sans-serif";\n';
						insertHTML += '\t\t\t}\n';
						insertHTML += '\t\t</style>\n';
						insertHTML += '\t</head>\n';
						insertHTML += '\t<body>\n';
						insertHTML += '\t\t<h1>'+thisimagename+'</h1>\n';
						insertHTML += '\t\t<img src="'+thisimagesrc+'" />\n';
						insertHTML += '\t\t<p>'+thisdescription+'</p>\n';
						insertHTML += '\t</body>\n';
						insertHTML += '</html>';
						
						var newwindow = window.open();
						newwindow.document.write(insertHTML);
						newwindow.document.close();
						newwindow.print();
						newwindow.close();
						
						return false;
					});
	
					
					// This function is called when a user decides to delete an image from the 
					// Image info panel
					$(newimageinfoblock).find("div.image-info-text a.image-info-delete").click( function() {
						if (deleteconfirmmessageopen) {
							return false;	
						}
						
						deleteconfirmmessageopen=true;					
						$(newimageinfoblock)
						.find("div.image-info-text div.image-info-delete-confirm")
						.css({display:"block"})
						.stop()
						.animate({height: 21}, 500, function() {
							var thisconfirmbox=this;
							var deletingimage=false;
							$(this).find("a").unbind().click( function() {
								switch($(this).text()) {
									case "Yes":
										if (deletingimage) {
											return false;	
										}
										deletingimage=true;
										deleteImage(thisimageparent);
										$(imageInfoHolder).find("a.back-to-album").click()
									break;
									case "No":
										$(thisconfirmbox)
										.stop()
										.animate({height: 0}, 500, function() {
											$(this).css({display: "none"});
											deleteconfirmmessageopen=false;
										});
									break;
								}
								return false;	
							});
							
						});
	
						return false;
					});
					
					var aboutPhotoShowing=false;
					var animatingAboutPhoto=false;
					// This action is called when a user clicks on the About photo action
					$(newimageinfoblock).find("div.image-info-text a.image-info-about").click( function() {
						if (animatingAboutPhoto) {
							return false;	
						}
						if (!aboutPhotoShowing) {
							animatingAboutPhoto=true;
							var margintopoffset = 0;
							if (isIE6 || isIE7) {
								margintopoffset=-80;
								$(this)
								.parent()
								.siblings()
								.css({minHeight:0})
								.not(".image-info-show-actions")
								.css({overflow: "hidden"});
							}
							$(this)
							.parent()
							.animate({marginTop: 21+margintopoffset}, 500, function() {
								$(newimageinfoblock)
								.find("div.image-info-text li.image-info-show-actions")
									.css({display: "block"})
									.animate({opacity: 1}, 500)
								.end();
								$(newimageinfoblock)
								.find("ul.image-info-photo-details")
									.css({display: "block"})
									.animate({opacity: 1}, 500, function() {
										animatingAboutPhoto=false;
										aboutPhotoShowing=true;	
									})
								.end()
							})
							.siblings()
							.not(".image-info-show-actions")
							.animate({height: 0}, 500);
						
						}
						else {
							$(newimageinfoblock).find("div.image-info-text a.image-info-show-actions").click();							
						}
						return false;
					});
					
					$(newimageinfoblock).find("div.image-info-text a.image-info-show-actions").click( function() {
						if (animatingAboutPhoto) {
							return false;	
						}
						if (aboutPhotoShowing) {
							animatingAboutPhoto=true;
							if (keywordeditblockopen) { // Close the keyword edit block if it is open, and save changes
								$(newimageinfoblock).find("div.image-info-text div.image-info-keyword-edit-block a.close-keyword-edit").click();
							}
							$(this)
							.parent()
							.animate({opacity: 0}, 200, function() {
								$(this).css({display: "none"});
								$(this).siblings().not(".image-info-about").animate({ height: 20}, 500, function() {
									if (isIE6 || isIE7) {
										$(this).css({overflow: "visible"});
										if (isIE7) {
											$(this).css({height:"auto", minHeight: 20});
										}
									}
									else {
										$(this).css({height: "auto"});
									}
								});
							});
							if (isIE6 || isIE7) {
								$(newimageinfoblock).find("div.image-info-text a.image-info-about").parent().animate({ marginTop: 25 }, 500);
															
							}
							$(newimageinfoblock)
							.find("ul.image-info-photo-details")
								.animate({opacity: 0}, 200, function() {
									$(this).css({display: "none"});
									animatingAboutPhoto=false;
									aboutPhotoShowing=false;	
								})
							.end()
						}
						return false;
					});
					
					var findWordInList = function(word, wordarray) {
						var wordfound=false;
						for (var counter=(wordarray.length-1); counter>=0; counter--) {
							if (word == wordarray[counter]) {
								wordfound=true;
								break;	
							}
						}
					return wordfound;	
					}
	
					var findNewKeywords = function(oldkeywords, newkeywords) {
						var returnarray = new Array();
						for (var counter=(newkeywords.length-1); counter>=0; counter--) {
							if (!findWordInList(newkeywords[counter], oldkeywords) && newkeywords[counter] !=" ") {
								returnarray[returnarray.length]=newkeywords[counter];
							}
						}
						return returnarray;
					}
					
					var findRemovedKeywords = function(oldkeywords, newkeywords) {
						var returnarray = new Array();
						for (var counter=(oldkeywords.length-1); counter>=0; counter--) {
							if (!findWordInList(oldkeywords[counter], newkeywords) && oldkeywords[counter] !=" ") {
								returnarray[returnarray.length]=oldkeywords[counter];
							}
						}
						return returnarray;
					}
					
					var keywordeditblockopen=false;
					// This function is called when a user decides to edit or add keywords 
					$(newimageinfoblock).find("div.image-info-text p.image-info-keyword a.add-keywords").click( function() {
						if (keywordeditblockopen || imageinfopurchasedcontent) {
							return false;
						}
						keywordeditblockopen=true;
						
						var thiskeywordtext=$(this).parent().find("span");
						var thiskeywordblock=$(newimageinfoblock).find("div.image-info-text div.image-info-keyword-edit-block");
						$(thiskeywordblock).find("textarea").text($(thiskeywordtext).text());
	
						var previouskeywords = $(thiskeywordtext).text();
	
						$(thiskeywordblock)
						.css({display:"block"})
						.stop()
						.animate({height: 100}, 750, function() {
						
							$(this).find("textarea")
							.unbind()
							.focus()
							.keydown( function(e) {
								if (e.keyCode == 13) {
									$(thiskeywordblock).find("a.close-keyword-edit").click();	
									return false;
								}
							})
							.keyup( function(e) {
								if (e.keyCode == 13) {
									// $(thiskeywordblock).find("a.close-keyword-edit").click();	
									return false;
								}
								else {
									$(thiskeywordtext).text($(this).val());
								}
							});
	
							$(thiskeywordblock).find("a.close-keyword-edit").unbind().click( function() {
								$(thiskeywordblock).animate({height:0}, 750, function() {
									
									var newkeywordtext = $(thiskeywordtext).text()
									if (previouskeywords != newkeywordtext) {   

										var ismasteralbum = ($(thisimageparent).parents(".gallery-album").get()[0].className.indexOf("gallery-album-master") != -1) ? true : false;
										var ajaxPhotoId = $(thisimageparent).find("span.image-id").text();
										
										// Now update keywords for images in other albums that have the same id
										$(thisGallery).find("div.gallery div.image-holder span.image-id:contains("+ajaxPhotoId+")").each( function() {
											if ($(this).text() == ajaxPhotoId) {
												$(this).parent().find("span.keyword").text(newkeywordtext);
											}
										});

										// AJAX CALL
										// Overview: This ajax call sends a list of keywords for this image 
										// Variables: Sends keywords as " " delineated string and id of master image
										// Returns sucess or failure
										$.post("/gallerydemo/mobykogallery/assets/ajax/add-remove-keywords.php", {photoId: ajaxPhotoId, keywords:newkeywordtext }, function(xml) {

										});
										
										// End of Ajax Call
									}
									keywordeditblockopen=false;
								});
								return false;
							});
							
						});
						
						return false;
					});
	
	
					// This function is called when a user decides to rotate an image from the 
					// Image info panel
					$(newimageinfoblock).find("div.image-info-text a.image-info-rotate").click( function() {
						if (rotatemessageopen || imageinfopurchasedcontent) {
							return false;
						}
						rotatemessageopen=true;
						
						$(newimageinfoblock)
						.find("div.image-info-text div.image-info-rotate-message")
						.css({display:"block"})
						.stop()
						.animate({height: 21}, 500, function() {
							var thisconfirmbox=this;
							var rotatingimage=true;
	
							var ismasteralbum = ($(thisimageparent).parents(".gallery-album").get()[0].className.indexOf("gallery-album-master") != -1) ? true : false;
							if (ismasteralbum) {
								var ajaxPhotoId = $(thisimageparent).find("span.image-id").text();
								var ajaxAlbumPhotoId = "";	
							} 
							else {
								var ajaxPhotoId = "";
								var ajaxAlbumPhotoId = $(thisimageparent).find("span.image-id").text();	
							}


							// AJAX Call
							// Rotate an image
							// Overview: This function takes place when the user decides to rotate an image
							// Variables: photoId and ajaxAlbumPhotoId
							// Response: Should return urls to the rotated image and its thumb 

							$.post("/gallerydemo/mobykogallery/assets/ajax/rotate-image.php", {photoId: ajaxPhotoId, albumPhotoId: ajaxAlbumPhotoId}, function(xml) {
								var returnedimagesrc=$(xml).find("image-src").text();
								var returnedthumbsrc=$(xml).find("thumb-src").text();
								
								// Need to delete these 2 lines once backend sorted					
								// Pretend that the following was returned from the Ajax request
								returnedimagesrc=$(thisimageparent).find("span.image-src").text();
								returnedthumbsrc=$(thisimageparent).find("img").attr("src");
								
								rotateGalleryImage(thisimageparent, returnedthumbsrc, returnedimagesrc);
								setupimageinfoimageloader(newimageinfoblock, imageobj);
	
								$(newimageinfoblock).find("div.image-info-text div.image-info-rotate-message").animate({ height: 0}, 500, function() {
									$(this).css({display: "none"});
									rotatemessageopen=false;
								});
							});

							// End of Ajax call
						});
	
						return false;
					});
	
					// This function is called when a user wants to make an image the album cover
					// by clicking on the make album cover linke of the image info panel
					$(newimageinfoblock).find("div.image-info-text a.image-info-album-cover").click( function() {
						var newalbumimagesrc=$(imageobj).attr("src");
						var	newalbumimagesize = new Array();
						newalbumimagesize[0]=parseInt($(imageobj).attr("width"));
						newalbumimagesize[1]=parseInt($(imageobj).attr("height"));
	
						var th1dimensions = imageCropDimensions(newalbumimagesize, [72, 95]);
						var th1dimensionsns = imageCropDimensions(newalbumimagesize, [40, 50]);
	
						// Now load the images into the Album Block
						$(albumHolderStage).find("div.album-block-selected").each( function() {
							var newnscoverthumb = $('<img class="ns-main-thumb" src="'+newalbumimagesrc+'" />');
							$(newnscoverthumb)
							.css({width: th1dimensionsns[0], height: th1dimensionsns[1]})
							.css({left: -th1dimensionsns[2], top: -th1dimensionsns[3]});
							$(this).find("img.ns-main-thumb").before(newnscoverthumb).remove();
							var newmaincoverthumb = $('<img class="main-thumb" src="'+newalbumimagesrc+'" />');
							$(newmaincoverthumb)
							.css({width: th1dimensions[0], height: th1dimensions[1]})
							.css({left: -th1dimensions[2], top: -th1dimensions[3]});
							$(this).find("img.main-thumb").before(newmaincoverthumb).remove();
						});
						
						// Now remove all instances of span.cover-thumb from this gallery
						// and add a span.cover-thumb to thisimageparent
						$(thisGallery).find("div.gallery-album-selected span.cover-thumb").remove();
						$(thisimageparent).append('<span class="meta cover-thumb">true</span>');

						var ismasteralbum = ($(thisimageparent).parents(".gallery-album").get()[0].className.indexOf("gallery-album-master") != -1) ? true : false;
						if (ismasteralbum) {
							var ajaxPhotoId = $(thisimageparent).find("span.image-id").text();
							var ajaxAlbumPhotoId = "";	
						} 
						else {
							var ajaxPhotoId = "";
							var ajaxAlbumPhotoId = $(thisimageparent).find("span.image-id").text();	
						}
						// Ajax call
						// Make image album image
						// Overview: This request is called when a users decides to make a particular image
						// the front cover image of its album
						// Variables: Sends photoId albumPhotoId 

						$.post("/gallerydemo/mobykogallery/assets/ajax/make-album-cover.php", {photoId: ajaxPhotoId, albumPhotoId: ajaxAlbumPhotoId}, function(xml) {
							// In this case, we fail silently
						});
						
						// End of Ajax Call

						return false;
					});
	
	
					return newimageinfoblock;
				} 
				
				var createsizedinfoimage = function(imageobj) {			
					var thisimagesize=$(imageobj).parent().find("span.image-size").text().split(",");
					var thisimagesrc=$(imageobj).parent().find("span.image-src").text();
					var imagedimensions = centreImageDimensions(containerwidth, containerheight, parseInt(thisimagesize[0]), parseInt(thisimagesize[1]));
					
					var imagewidth=imagedimensions[0];
					var imageheight=imagedimensions[1];
					var marginleft=imagedimensions[2];
					var margintop=imagedimensions[3];
					var newimage=$('<img src="'+thisimagesrc+'" />');
					if (isIE6 || isIE7) {
						// Need to set padding top for IE to prevent image jumping
						$(newimage).css({paddingTop:margintop, marginLeft:marginleft, width:imagewidth, height:imageheight});
					}
					else {
						$(newimage).css({marginTop:margintop, marginLeft:marginleft, width:imagewidth, height:imageheight});
					}
					return newimage;
				}
	
				// This function takes an image info block and a main gallery stage image
				// And sets up the loading routines for the image info image
				// It also ensures that the image info options are lined up with the top of the image
				var setupimageinfoimageloader = function(imageinfoblock, thisimage) {
					var loadergraphic=$('<div class="image-loader-graphic"><h3>Loading image</h3></div>');
					$(imageinfoblock)
					.find("div.image-info-image-block")
					.empty()
					.append(loadergraphic)
					.append(createsizedinfoimage(thisimage))
					.find("img")
					.css({opacity: 0})
					.load(function() {
						$(loadergraphic).animate({opacity: 0}, 500, function() {
							$(this).remove();
						});
						$(this).animate({opacity: 1}, 500);
					});
					
				}
				
				// This function creates imageinfoblocks for the images before
                // and after thisimage, and appends them before and after
                // in the image info carousel
                var loadbeforeafterimageinfo = function(thisimage) {
                    var currentlyselectedgallery = $(thisGallery).find("div.gallery-album-selected");
                    var previousimageinfoblock=false;
                
                    var thisimageholder=$(thisimage).parent();
                    if (selectedimagenum > 0 && firstloadedimage == selectedimagenum && $(thisimageholder).prev()) {
                        // var previousimage=$(thisimageholder).prev(".image-holder").find("img");
                        var previousimage=$(currentlyselectedgallery).find("div.image-holder:eq("+(selectedimagenum-1)+")").find("img");
                        if($(previousimage).length < 1) {
                            // The gallery image has not been loaded so load
                            var thisimageblock = $(currentlyselectedgallery).find("div.image-holder:eq("+(selectedimagenum-11)+")");
                            updateemptythumbs(thisimageblock);
                            $(currentlyselectedgallery).find("a.initialise-latest-image").click();
                            previousimage = $(thisimageblock).find("img");
                        }
                        previousimageinfoblock=createimageinfoblock(previousimage);
                        if (isFireFox) {
                            $(previousimageinfoblock).css({display: "none"}); // Needed to prevent flicker in firefox
                        }
                        $(imageInfoStage)
                        .prepend(previousimageinfoblock);
                        setupimageinfoimageloader(previousimageinfoblock, previousimage);
                        firstloadedimage=selectedimagenum-1;
                    }
                    if (selectedimagenum < (imageinfonumofimages-1) && lastloadedimage == selectedimagenum && $(thisimageholder).next()) {
                        var nextimage=$(currentlyselectedgallery).find("div.image-holder:eq("+(selectedimagenum+1)+")").find("img");
                        if(!$(nextimage).length) {
                            // The gallery image has not been loaded so load
                            var thisimageblock = $(currentlyselectedgallery).find("div.image-holder:eq("+(selectedimagenum+1)+")");
                            updateemptythumbs(thisimageblock);
                            $(currentlyselectedgallery).find("a.initialise-latest-image").click();
                            nextimage = $(thisimageblock).find("img");
                        }
                        var nextimageinfoblock=createimageinfoblock(nextimage);
                        $(imageInfoStage)
                        .append(nextimageinfoblock);
                        setupimageinfoimageloader(nextimageinfoblock, nextimage);
                        lastloadedimage=selectedimagenum+1;
                    }
                    if (isFireFox && previousimageinfoblock) { // Needed as part of preventing flicker in Firefox
                        $(previousimageinfoblock).css({display:"block"});
                    }
                    $(imageInfoStage).css({top: -((containerheight+containermargin)*(selectedimagenum-firstloadedimage)) });
                } 
				
				// This function ensures that the carousel up and down arrows are only
				// visible when they have to be
				var updateimageinfoarrows = function() {
					if (imageinfonumofimages<=1) {
						$(imageInfoHolder).find("a.image-info-scroll-up").css({display: "none"});
						$(thisGallery).find("a.image-info-scroll-down").css({display: "none"});
					}
					else if (selectedimagenum==0) {
						$(thisGallery).find("a.image-info-scroll-up").css({display: "none"});	
						$(thisGallery).find("a.image-info-scroll-down").css({display: "block"});
					}				
					else if (selectedimagenum >= (imageinfonumofimages-1)) {
						$(thisGallery).find("a.image-info-scroll-up").css({display: "block"});
						$(thisGallery).find("a.image-info-scroll-down").css({display: "none"});
					}
					else {
						$(thisGallery).find("a.image-info-scroll-up").css({display: "block"});
						$(thisGallery).find("a.image-info-scroll-down").css({display: "block"});
					}
				}
							
				$(imagePopup)
				.find("h4.image-popup-image-name")
					.mouseover( function() {
						if (imageDrag || returnScroll) {
							return false;	
						}
						if ($(selectedImage).parent().find("span.source").text()=="PURCHASED") {
							return false;	
						}
						var savedtext = $(selectedImage).parent().find("span.image-name").text();
						var thisinputholder = $('<div class="image-popup-name-edit-input-holder"><input value="'+savedtext+'" /></div>');
						
						var editinput = $(thisinputholder).find("input");
						var popupnameholder = this;
						var editmouseoutfunction="";
						popUpNameEditOpen=true;
						$(this).parent().append(thisinputholder);
						
						$(editinput)
						.focus()
						.blur(function() {
							var finishedtext=$(this).val();	
							if (!checkForChars(finishedtext)) {
								finishedtext=savedtext;
							}
							$(popupnameholder).text(trimToMaxCharWords(finishedtext,16))
							$(selectedImage).parent().find("span.image-name").text(finishedtext);
							$(thisinputholder).remove();
							popUpNameEditOpen=false;
							
							if (finishedtext != savedtext) {
								var ismasteralbum = ($(selectedImage).parents(".gallery-album").get()[0].className.indexOf("gallery-album-master") != -1) ? true : false;

								var ajaxPhotoId = $(selectedImage).parent().find("span.image-id").text();

								// Now lets update the description for all the other copies of this phot
								$(thisGallery).find("div.gallery div.image-holder span.image-id:contains("+ajaxPhotoId+")").each( function() {
									if ($(this).text() == ajaxPhotoId) {
										$(this).parent().find("span.image-name").text(finishedtext);
									}
								});

								// AJAX Call
								// Update name of image
								// Send photoId  and new name
								// Return success failure
								$.post("/gallerydemo/mobykogallery/assets/ajax/update-image-name.php", {photoId: ajaxPhotoId, newPhotoName: finishedtext}, function(xml) {
									// We fail sliently again;
								});
								// End of Ajax call
							}

						})
						.keydown( function(e) {
							if (e.keyCode == 13) {
								$(this).blur();
							}
						})
						.mouseout( function() {
							$(this).blur();
							return false;
						});
						return false;	
					})
				.end();



				$(imagePopup).find("a.delete-image")
				.mouseup( function(){ return false; })
				.mousedown( function() { return false; })
				.click( function() {
					
					if (popUpConfirmMessageOpen || popUpRotatingImage) {
						return false;	
					}
					popUpConfirmMessageOpen=true;
					
					$(imagePopup).find("h4,h5,h6,a.rotate-image, a.delete-image").animate({opacity: 0}, 500);
					$(imagePopup)
					.find("div.image-popup-delete-warning")
					.empty()
					.html('<p>Are you <strong>sure</strong> you want to delete this image? <a href="#">Yes</a> <a href="#">No</a></p>')
					.css({display:"block"})
					.animate({height: 50}, 500, function() {
						
						var thisconfirmblock=this;
						$(this).find("a").unbind()
						.mousedown( function() { return false })
						.mouseup( function() { return false })
						.click( function() {
							switch($(this).text()) {
								case "Yes":
								
								deleteImage($(selectedImage).parent());
								$(imagePopup).animate({opacity: 0},500, function() {
									$(thisconfirmblock).stop().css({height: 0, display:"none"});
									$(imagePopup).find("h4,h5,h6,a.rotate-image, a.delete-image").stop().css({opacity: 1});
									$(imagePopup)
									.css({ left: -1000, top: -1000})
									.css({opacity: 1});
	
									popUpConfirmMessageOpen=false;
								});
								break;
								
								case "No":
								$(thisconfirmblock).animate({ height: 0}, 500, function() {
									$(this).css({display: "none"});
								});
								$(imagePopup).find("h4,h5,h6,a.rotate-image,a.delete-image").animate({opacity: 1}, 500, function() {
									popUpConfirmMessageOpen=false;
								});
								break;	
							}
							return false;
						});
						
					}); 
					return false;
				});
	
	
				$(imagePopup).find("a.rotate-image")
				.mouseup( function(){ return false; })
				.mousedown( function() { return false; })
				.click( function() {
					if (popUpRotatingImage || popUpConfirmMessageOpen) {
						return false;	
					}
					popUpRotatingImage=true;		
					var thisimageholder = $(selectedImage).parent();
					var thisimageid=parseInt($(thisimageholder).find("span.image-id").text());
					var thisconfirmblock = $(imagePopup).find("div.image-popup-delete-warning");
	
					$(imagePopup).find("h4,h5,h6,a.delete-image, a.rotate-image").stop().animate({opacity: 0}, 500);
					$(thisconfirmblock)
					.html('<p>Please wait while we create your rotated image</p>')
					.css({display:"block"})
					.animate({height: 50}, 500, function() {
						// AJAC call to rotate image
						// Rotate an image
						var ismasteralbum = ($(selectedImage).parents(".gallery-album").get()[0].className.indexOf("gallery-album-master") != -1) ? true : false;
						if (ismasteralbum) {
							var ajaxPhotoId = $(selectedImage).parent().find("span.image-id").text();
							var ajaxAlbumPhotoId = "";	
						} 
						else {
							var ajaxPhotoId = "";
							var ajaxAlbumPhotoId = $(selectedImage).parent().find("span.image-id").text();	
						}

						// AJAX Call
						// Rotate an image
						// Overview: This function takes place when the user decides to rotate an image from the image popup
						// Variables: photoId and ajaxAlbumPhotoId
						// Response: Should return urls to the rotated image and its thumb 

						$.post("/gallerydemo/mobykogallery/assets/ajax/rotate-image.php", {photoId: ajaxPhotoId, albumPhotoId: ajaxAlbumPhotoId}, function(xml) {
							
							var returnedimagesrc=$(xml).find("image-src").text();
							var returnedthumbsrc=$(xml).find("thumb-src").text();
								
							// Need to delete these 2 lines once backend sorted					
							// Pretend that the following was returned from the Ajax request
							returnedimagesrc=$(selectedImage).parent().find("span.image-src").text();
							returnedthumbsrc=$(selectedImage).parent().find("img").attr("src");
								
							rotateGalleryImage($(selectedImage).parent(), returnedthumbsrc, returnedimagesrc);
							// Bit of a hack
							// quickly change flag so mouseover will work for this element
							// then reset flag to prevent other mouseovers				
							popUpRotatingImage=false;
							$(selectedImage).mouseover();
							popUpRotatingImage=true;
									
							$(thisconfirmblock).animate({ height: 0}, 500, function() {
								$(this).css({display: "none"});
							});
							$(imagePopup).find("h4,h5,h6,a.delete-image, a.rotate-image").stop().animate({opacity: 1}, 500, function() {
								popUpRotatingImage=false;
							});
						});
						
						// End of ajax call
					});
							
					return false;
				});
	
	
				// Open Image Info Box when the eye icon is clicked
				// This function is now also called when a user simply clicks on a photo
				// And in fact now the eye doesn't even display
				
				$(imagePopup).find("a.info-image")
				.mouseup( function(){ return false; })
				.mousedown( function() {
					return false;
				}).click( function() {
					imageinfocurrentlyscrolling=true;
					imageInfoBoxOpen=true;

					currentlyselectedimage=selectedImage;
					imageinfonumofimages=$(thisGallery).find("div.gallery-album-selected div.image-holder:has(span.image-src)").length;
					imageinfoalbumname=$(thisGallery).find("div.gallery-album-selected span.album-name").text();
					var newimageinfoblock=createimageinfoblock(selectedImage);
					selectedimagenum=parseInt($(selectedImage).parent().find("span.image-pos").text());
					firstloadedimage=selectedimagenum;
					lastloadedimage=selectedimagenum;
					updateimageinfoarrows();
					// setupimageinfoimageloader(newimageinfoblock, selectedImage);
					$(imageInfoHolder)
					.find("div.image-info-stage")
					.empty()
					.append(newimageinfoblock)
					.end(); // Back to imageInfoHolder
					
					// Now call the function to load image info above and below current image
					loadbeforeafterimageinfo(selectedImage);

					$(imageInfoHolder)
					.css({display: "block", opacity: 0})
					.animate({opacity: 1}, 500, function() {
						$(this).css({opacity: 1});

						// Fade out search box and menu 
						fadeOutSortAndSearch();

						$(galleryInfoHolderTop).addClass("album-info-panel-open");

						// Hide the main carousel up arrow
						$(thisGallery).find("a.main-scroll-up").addClass("hide");
	
						setupimageinfoimageloader(newimageinfoblock, selectedImage);

						imageinfocurrentlyscrolling=false;
						$(galleryInfoPhotoName).css({display:"inline"}).text(trimToMaxCharWords($(selectedImage).parent().find("span.image-name").text(), 20));
						$(galleryInfoAlbumName).removeClass("album-name-selected");

					});
					return false;	
				});
		
				// Fade out the Image Info Box when the album button is clicked
				$(this).find("a.back-to-album").click( function() {
					if (imageInfoToSomewhereButtonOpen) {
						$(imageInfoToSomewhereButton).click();
					}
					imageinfocurrentlyscrolling=true;

					// Remove hidden class from the main gallery up arrow
					$(thisGallery).find("a.main-scroll-up").removeClass("hide");

					$(thisinfoholder).animate({opacity: 0}, 500, function() {
						$(this).css({display: "none"});
						$(imageInfoStage).empty();
						firstloadedimage="";
						lastloadedimage="";
						imageinfonumofimages="";
						$(galleryInfoPhotoName).css({display:"none"}).text("");
						$(galleryInfoAlbumName).addClass("album-name-selected");
						$(imageInfoToSomewhereButton).unbind();
						// Fade in search box and menu 
						fadeInSortAndSearch();
						$(galleryInfoHolderTop).removeClass("album-info-panel-open");
						imageInfoBoxOpen=false;
					});
					return false;
				});
				
				$(this).find("a.image-info-scroll-up").click( function() {
					if (imageinfocurrentlyscrolling) {
						return false;	
					}
					if (selectedimagenum < 1) {
						return false;
					}
					imageinfocurrentlyscrolling=true;
					currentlyselectedimage=$(currentlyselectedimage).parent().prev().find("img");
					selectedimagenum--;
					updateimageinfoarrows();
					if (imageInfoToSomewhereButtonOpen) {
						$(imageInfoToSomewhereButton).click();
					}
					$(imageInfoStage).animate({top: -((containerheight+containermargin)*(selectedimagenum-firstloadedimage)) }, 1000,
					function() {
						$(galleryInfoPhotoName).text(trimToMaxCharWords($(currentlyselectedimage).parent().find("span.image-name").text(),20));
						loadbeforeafterimageinfo(currentlyselectedimage);
						imageinfocurrentlyscrolling=false;
					});
					return false;
				});
	
				$(this).find("a.image-info-scroll-down").click( function() {
					if (imageinfocurrentlyscrolling) {
						return false;	
					}
					if (selectedimagenum >= (imageinfonumofimages-1)) {
						return false;	
					}
					imageinfocurrentlyscrolling=true;
					currentlyselectedimage=$(currentlyselectedimage).parent().next().find("img");
					selectedimagenum++;
					updateimageinfoarrows();
					if (imageInfoToSomewhereButtonOpen) {
						$(imageInfoToSomewhereButton).click();
					}
					$(imageInfoStage).animate({top: -((containerheight+containermargin)*(selectedimagenum-firstloadedimage)) }, 1000,
					function() {
						$(galleryInfoPhotoName).text(trimToMaxCharWords($(currentlyselectedimage).parent().find("span.image-name").text(),20));
						loadbeforeafterimageinfo(currentlyselectedimage);
						imageinfocurrentlyscrolling=false;	
					});
					return false;
				});
			});
	
	
			// Function addImageToAlbumGallery
			// This funciton adds an image to an album gallery. It deals with initialisation of the new image
			// so that it can be dragged, deleted, rotated etc. It also adds the required num of empty image holders
			// And it also hides the image if it does not meet the current search criteria for that gallery.
			var addImageToAlbumGallery= function(imagetoadd, thisalbumgallery, isnewgallery) {
				var thisimageid=$(imagetoadd).parent().find("span.image-id").text();
				var newimage=$(imagetoadd).parent().clone();
				
				if (isnewgallery) {
					$(thisalbumgallery)
					.find("div.image-holder:eq(0)")
						.after(newimage)
						.remove()
					.end()
					.removeClass("gallery-album-new");
					$(newimage).find("span.image-pos").text("0");
				}
				else {
					var endimageindex=$(thisalbumgallery).find("div.image-holder img").length-1;
					if (endimageindex > -1) {
						// There is at least one displayed image
						// So paste our new image after it
						$(thisalbumgallery)
						.find("div.image-holder:eq("+endimageindex+")")
						.after(newimage);
					}
					else {
						// Otherwise, try to paste the new image after the last hidden image
						endimageindex=$(thisalbumgallery).find("div.image-holder-hidden img").length-1;
						if (endimageindex > -1) {
							$(thisalbumgallery)
							.find("div.image-holder-hidden:eq("+endimageindex+")")
								.after(newimage)
							.end();
						}
						else {
						// This has no visible or hidden images so must be an empty gallery (though not a new one)
						// In which case paste the new image at the very start.
						$(thisalbumgallery).prepend(newimage);
						}
					}
	
					// check to see if image contains search term for that album
					// If not, hide it by changing the class
					var albumsearchterm = $(thisalbumgallery).find("span.album-search-term").text();
					var searchterminimage=isSearchTermInImage(albumsearchterm, newimage);
					if (!searchterminimage) {
						$(newimage)
						.removeClass("image-holder")
						.addClass("image-holder-hidden");
					}
					else {
						// Only have to remove one of the empty images if 
						// the image is visible - ie meets the search criteria
						$(thisalbumgallery)
						.find("div.image-holder:eq("+(endimageindex+2)+")")
						.remove();
					}
					
		
					// Adjust image pos varable (used to prevent safari bug)
					$(newimage).find("span.image-pos").text((endimageindex+1).toString());
					
											
					if ($(thisalbumgallery).find("div.image-holder div.empty-image").length == 0) {
					// No empty image holders keft so add 15 more
					var imageposcounter=endimageindex+2;
					var insertHTML="";
						for (var counter2=imageposcounter;counter2<(imageposcounter+15); counter2++) {
							insertHTML+='<div class="image-holder">';
							if ((counter2 % 2)==0) {
								insertHTML+='<div class="empty-image-landscape empty-image"></div>';	
							}
							else {
								insertHTML+='<div class="empty-image-portrait empty-image"></div>';	
							}
							insertHTML+='<span class="image-pos">'+counter2+'</span>';
							insertHTML+='</div>';
						}
					}
					$(thisalbumgallery).append(insertHTML);
					// NOw me need to attach events to the new empty images
					$(thisalbumgallery).find("a.initialise-empty-images").click();
				}
				$(newimage).find("img").addClass("awaiting-initialisation");
				// Now initialise image in the context of its album
				$(thisalbumgallery).find("a.initialise-latest-image").click();

				return newimage;
			}
	
	
	
			$(imagePopup).mouseup( function(e) {
	
				// We want to prevent this action when an image
				// is currently being deleted or rotated
				if (popUpRotatingImage || popUpConfirmMessageOpen) {
					return false;	
				}
				if (popUpNameEditOpen) {
					// Need to return true to allow default edit actions
					return true;	
				}
				if (!imageDrag) {
					$(this).unbind("mousemove");			
					$(this).find("a.info-image").click();
					$(this).css({top: -1000, left: -1000});
					$(this).removeClass("image-popup-drag");
					return false;	
				}
	
				imageDrag=false;
				if (isIE6 || isIE7) {
					document.body.onselectstart = function () { return true; };
				}
				// Remove any hover effects on album blocks
				if (lastAlbumBlockHover) {
					$(lastAlbumBlockHover).removeClass("album-block-drag-hover")
					lastAlbumBlockHover=false;	
				}
				
				var droppos=checkwhere(e);
	
				var albumfound=false;
	
				// The content of this if block
				// takes place if the image was dropped on a 'create new album block';
				if (isOverElement(droppos, createNewAlbumBlock)) {
					var latestalbumblock=$(albumHolderStage).find("div.album-block-new");
					var thisimageid=$(selectedImage).parent().find("span.image-id").text();
	
					var thisalbumid =  $(latestalbumblock).find("span.album-id").text();
					var thisalbumgallery="";
					
					var thesealbumgalleries=$(thisGallery).find("div.gallery-album");
					var numofthesegalleries=$(thesealbumgalleries).length;
					for (var counter=0; counter<numofthesegalleries; counter++) {
					if ($(thesealbumgalleries[counter]).find("span.album-id").text() == thisalbumid) {
							thisalbumgallery=thesealbumgalleries[counter];
							break;
						}
					}
	
					var newalbumfirstimage = addImageToAlbumGallery(selectedImage, thisalbumgallery, true) // The true says this is a new album
						
					$(latestalbumblock).removeClass("album-block-new");
					$(latestalbumblock).removeClass("album-block-hidden");
	
					var newimagesize=[$(selectedImage).width(), $(selectedImage).height()];
					var dimensions1 = imageCropDimensions(newimagesize, [40, 50]);
					var previousimagesize=[$(selectedImage).width(), $(selectedImage).height()];
					var dimensions2 = imageCropDimensions(previousimagesize, [29, 29]);
					var dimensions3 = imageCropDimensions(newimagesize, [72, 95]);
					var dimensions4 = imageCropDimensions(previousimagesize, [53, 53]);
	
					$(latestalbumblock)
					.find("div.ns-small-thumb-holder img") 
						.attr("src", "/gallerydemo/mobykogallery/assets/ui/empty.image.gif")
						.css({width: dimensions2[0], height: dimensions2[1]})
						.css({left: -dimensions2[2], top: -dimensions2[3]})
					.end()
					.find("div.small-thumb-holder img") 
						.attr("src", "/gallerydemo/mobykogallery/assets/ui/empty.image.gif")
						.css({width: dimensions4[0], height: dimensions4[1]})
						.css({left: -dimensions4[2], top: -dimensions4[3]})
					.end()
					.find("img.ns-main-thumb")
						.attr("src", $(selectedImage).attr("src"))
						.css({width: dimensions1[0], height: dimensions1[1]})
						.css({left: -dimensions1[2], top: -dimensions1[3]})
					.end()
					.find("img.main-thumb")
						.attr("src", $(selectedImage).attr("src"))
						.css({width: dimensions3[0], height: dimensions3[1]})
						.css({left: -dimensions3[2], top: -dimensions3[3]})
					.end();
	
					// If picture was added to a new album, then we need
					// to create a new, new album gallery and album block, so to speak
					
					var emptygalleryhtml='<div class="gallery-album gallery-album-new">';
					emptygalleryhtml+='<span class="meta album-name">New album '+(galleryNumCounter++)+'</span>';
					emptygalleryhtml+='<span class="meta album-search-term">Search</span>';
					emptygalleryhtml+='<span class="meta album-id">awaiting</span>';
					emptygalleryhtml+='<span class="meta album-date-created"></span>';
					emptygalleryhtml+='<span class="meta album-date-updated"></span>';
					emptygalleryhtml+='<a href="#" class="meta scroll-gallery-up">Scroll up</a>';
					emptygalleryhtml+='<a href="#" class="meta scroll-gallery-down">Scroll down</a>';
					emptygalleryhtml+='<a href="#" class="meta display-album">Display album</a>';
					emptygalleryhtml+='<a href="#" class="meta reset-album">Reset album</a>';
					emptygalleryhtml+='<a href="#" class="meta refresh-album">Refresh album</a>';
					emptygalleryhtml+='<a href="#" class="meta initialise-latest-image">Initialise latest image</a>';
					emptygalleryhtml+='<a href="#" class="meta initialise-empty-images">Initialise latest images</a>';
					emptygalleryhtml+='<a href="#" class="meta launch-slideshow">Initialise latest images</a>';
					emptygalleryhtml+='</div>';
					
					$(thisGallery).find("div.gallery-inner").append(emptygalleryhtml);
					$(thisGallery).find("div.gallery-album-new").each( initialiseGalleryAlbum);
					// Now scroll gallery carousel to reveal new empty album block if necessary 
					$(thisGallery).find("div.album-holder a.album-block-scroll-to-end").click();
					albumfound=true;									
	
					var newdate = new Date();
					var datestring=makeDateTimeStringFromDateObject(newdate);
	
					// Now update the date created and date updated values in both thisalbumgallery and latestalbumblock
					$(thisalbumgallery).find("span.album-date-created,span.album-date-updated").text(datestring);
					$(latestalbumblock).find("span.album-block-album-date-created").text(datestring);
					$(latestalbumblock).find("div.selected-content h6").text("Updated "+makeDateStringFromDateTimeString(datestring));
					
					var ismasteralbum = ($(selectedImage).parents(".gallery-album").get()[0].className.indexOf("gallery-album-master") != -1) ? true : false;
					if (ismasteralbum) {
						var ajaxPhotoId = $(selectedImage).parent().find("span.image-id").text();
						var ajaxAlbumPhotoId = "";	
					} 
					else {
						var ajaxPhotoId = "";
						var ajaxAlbumPhotoId = $(selectedImage).parent().find("span.image-id").text();	
					}
					var thisnewalbumname = $(thisalbumgallery).find("span.album-name").text();
					
					
					// AJAX CALL
					// Create new album and add picture, date-time created
					// Overview: This call is made when a user drags an image to the 'new' album block
					// in the processs creating a new album, and adding a new image to it.
					// Send picture photoid/albumphotoid, date-time created
					// Get back album id and picture id, and update these values in the DOM
					
					$.post("/gallerydemo/mobykogallery/assets/ajax/create-album-and-add-image.php", {photoId: ajaxPhotoId, albumPhotoId: ajaxAlbumPhotoId, albumName: thisnewalbumname, createdDate: datestring }, function(xml) {
						
						// CHANGE
						// No longer need a new photo id, because we are simply
						// using the id from the photo from which we are creating a new photo
						var returnedalbumid = $(xml).find("album-id").text();
						$(thisalbumgallery).find("span.album-id").text(returnedalbumid);
						$(latestalbumblock).find("span.album-id").text(returnedalbumid);
					});
					
					// End of Ajax Call
				}
				else {
					if (isOverElement(droppos, albumHolderStage)) {
						var thesealbums=$(albumHolderStage).find("div.album-block");
						var numofalbums = thesealbums.length;
						  
						for (var counter=0; counter<(numofalbums-1); counter++) {
							var thisalbum=thesealbums[counter];  
							// If the album has already been selected - ie is current album
							// Then there is no need to add the image
							// So check next album
							if (thisalbum.className.indexOf("album-block-selected") != -1 || thisalbum.className.indexOf("album-block-master") != -1) {
								continue;
							}
							
							var activezone = thisalbum;
		
							if (isOverElement(droppos, activezone)) {
								var thisalbumid=$(thisalbum).find("span.album-id").text();
								
								$(thisGallery).find("div.gallery-album").each( function() {
									if ($(this).find("span.album-id").text() == thisalbumid) {
										
										// Now check to see if this album already contains this photo
										var photoalreadyinalbum = false;
										var existingphotoid = $(selectedImage).parent().find("span.image-id").text();
										$(this).find("span.image-id:contains("+existingphotoid+")").each( function() {
											if ($(this).text() == existingphotoid) {
												
												displayGalleryErrorMessage("Album already contains that photo");
												photoalreadyinalbum = true;
											}
											
										});
		
										if (!photoalreadyinalbum) {
											albumfound=true;
											var newalbumimage = addImageToAlbumGallery(selectedImage, this, false) // The false says not a new album
											
											// Now update album-block - thisalbum - with new picture
			
											var newimagesize=[$(selectedImage).width(), $(selectedImage).height()];
											var dimensions1 = imageCropDimensions(newimagesize, [34, 34]);
											var dimensions3 = imageCropDimensions(newimagesize, [53, 53]);
			
											var newdate = new Date();
											var datestring=makeDateTimeStringFromDateObject(newdate);
		
											// Now update the date updated values in both this gallery and this album block
											$(this).find("span.album-date-updated").text(datestring);
											$(thisalbum).find("div.selected-content h6").text("Updated "+makeDateStringFromDateTimeString(datestring));
		
											$(thisalbum)
											.find("div.ns-small-thumb-holder img")
												.attr("src", $(selectedImage).attr("src"))
												.css({width: dimensions1[0], height: dimensions1[1]})
												.css({left: -dimensions1[2], top: -dimensions1[3]})
											.end()
											.find("div.small-thumb-holder img")
												.attr("src", $(selectedImage).attr("src"))
												.css({width: dimensions3[0], height: dimensions3[1]})
												.css({left: -dimensions3[2], top: -dimensions3[3]})
											.end();
		
											// If dropped image was from a master album, then it must be a master image
											var ismasteralbum = ($(selectedImage).parents(".gallery-album").get()[0].className.indexOf("gallery-album-master") != -1) ? true : false;
											if (ismasteralbum) {
												var ajaxPhotoId = $(selectedImage).parent().find("span.image-id").text();
												var ajaxAlbumPhotoId = "";	
											} 
											else {
												var ajaxPhotoId = "";
												var ajaxAlbumPhotoId = $(selectedImage).parent().find("span.image-id").text();	
											}
	
											// AJAX CALL
											// Add picture to an album
											// Send picture id and album id and update date
											// Get back picture id, and update these values in the DOM
											// CHANGE
											// We now simply use the existing id from the copied album
											$.post("/gallerydemo/mobykogallery/assets/ajax/add-image-to-album.php", { photoId: ajaxPhotoId, albumPhotoId: ajaxAlbumPhotoId, dateTime: datestring}, function(xml) {
												// Ajax call back
												// We attach the id to the new album image
												// CHANGE no need to attach new id because it is simply a copy of the existing id
												
											});
											
											// End of Ajax call
										}
		
									}
								});
		
								break;
							} 
						}
					}
				}
				if (albumfound) {
					var newimagepopup = $(imagePopup).clone();
					$(imagePopup)
					.css({top: -1000, left: -1000, opacity: 1})
					.removeClass("image-popup-drag");
					
					$(thisGallery).append(newimagepopup);
					$(newimagepopup).animate({opacity: 0}, 500, function() {
						$(this).remove();
					}); 
				}			
				else { 
					returnScroll=true;
					
					var returnScrollSpeed=500;
					if (isIE6 || isIE7) {
						returnScrollSpeed=1;
					}
					$(this).animate({top: popupOrigY, left: popupOrigX}, returnScrollSpeed, function() {
						$(this).animate({opacity: 0.01}, returnScrollSpeed, function() {
							$(this).css({opacity: 1});
							$(this).css({top: -1000, left: -1000});
							$(this).removeClass("image-popup-drag");
							returnScroll=false;
						});
					});
				}
				return false;
			});
	
	    	$(document).mousemove( function(e) {
	 			if (!imageDrag) {
	 				return;
	 			}
	    		var mousepos=checkwhere(e);
				/* $("div#header").text(mousepos[0]); */
	    		$(imagePopup).css({left: mousepos[0]-popupOffsetX, top: mousepos[1]-popupOffsetY});
	    		
	    		// Now check if mouse is in the album block area. 
	    		// If so, check to see if mouse is over one of the album blocks
	    		// If so add hover highight
	
				if (isOverElement(mousepos, createNewAlbumBlock)) {
					$(createNewAlbumBlock).addClass("album-block-drag-hover");
					lastAlbumBlockHover=createNewAlbumBlock;
				}
				else if (isOverElement(mousepos, albumHolderStage)) {
	
					var thesealbums=$(albumHolderStage).find("div.album-block");
					var numofalbums = thesealbums.length;
					var noalbumselected=true;
					
					for (var counter=0; counter<(numofalbums-1); counter++) {
						var thisalbum=thesealbums[counter];  
	
						// For all album blocks but currently selected one
						if (thisalbum.className.indexOf("album-block-selected") == -1) {
							var activezone=thisalbum;
		
							if (specialIsOverElement(mousepos, activezone)) {
								if (lastAlbumBlockHover != thisalbum) {
									if (lastAlbumBlockHover) {
										$(lastAlbumBlockHover).removeClass("album-block-drag-hover");
									}
									$(thisalbum).addClass("album-block-drag-hover");
									lastAlbumBlockHover=thisalbum;
								}
								noalbumselected=false;
								break;
							}
						}
					}
					if (noalbumselected && lastAlbumBlockHover) {
						$(lastAlbumBlockHover).removeClass("album-block-drag-hover");
						lastAlbumBlockHover=false;
					}
					 
				}
				else if (lastAlbumBlockHover) {
					$(lastAlbumBlockHover).removeClass("album-block-drag-hover");
					lastAlbumBlockHover=false;
				}    		 			
	    	});
	
			$(this).find("a.main-scroll-up").click( function() {
				$(thisGallery).find("div.gallery-album-selected a.scroll-gallery-up").click();
				return false;
			});
	
			$(this).find("a.main-scroll-down").click( function() {
				$(thisGallery).find("div.gallery-album-selected a.scroll-gallery-down").click();
				return false;
			});
	
	
			// Add an empty gallery
	
			var emptygalleryhtml='<div class="gallery-album gallery-album-new">';
			emptygalleryhtml+='<span class="meta album-name">New album '+(galleryNumCounter++)+'</span>';
			emptygalleryhtml+='<span class="meta album-search-term">Search</span>';
			emptygalleryhtml+='<span class="meta album-id">new awaiting</span>';
			emptygalleryhtml+='<span class="meta album-date-created"></span>';
			emptygalleryhtml+='<span class="meta album-date-updated"></span>';
			emptygalleryhtml+='<a href="#" class="meta scroll-gallery-up">Scroll up</a>';
			emptygalleryhtml+='<a href="#" class="meta scroll-gallery-down">Scroll down</a>';
			emptygalleryhtml+='<a href="#" class="meta display-album">Display album</a>';
			emptygalleryhtml+='<a href="#" class="meta reset-album">Reset album</a>';
			emptygalleryhtml+='<a href="#" class="meta refresh-album">Refresh album</a>';
			emptygalleryhtml+='<a href="#" class="meta initialise-latest-image">Initialise latest image</a>';
			emptygalleryhtml+='<a href="#" class="meta initialise-empty-images">Initialise latest images</a>';
			emptygalleryhtml+='<a href="#" class="meta launch-slideshow">Launch gallery</a>';
			emptygalleryhtml+='</div>';
			$(this).find("div.gallery-inner").append(emptygalleryhtml);
	
	
			$(this).find("div.gallery-album").each( initialiseGalleryAlbum = function() {
			
				var thisgalleryalbum=this;
				var itemholdersize = [150, 146];
				var viewportheight = 438;
				var itemsperpage = 15;
				var initialiseEmptyImage;
				var initialiseGalleryImage;
				var numitems = $(this).find("div.image-holder").length;
				var numofdisplayitems = $(this).find("div.image-holder span.image-id").length; 
				
				if (this.className.indexOf("gallery-album-master") != -1) {
					var isMasterGallery=true;	
				}
				else {
					var isMasterGallery=false;	
				}
				
				var mainGalleryScrolling=false;
				// The below takes account of the number of extra empty image holders
				// that will be added to the stage 
				numitems+=(itemsperpage-(numitems % itemsperpage));
				var numpages = parseInt(numitems/itemsperpage);
				if (numitems % itemsperpage != 0) {
					numpages++;
				}
				var currentpage=0;	
				
				if (this.className.indexOf("gallery-album-new") !=-1) {
					$(this).removeClass("gallery-album-new");
					var galleryalbumnew=true;
				}
				else {
					var galleryalbumnew=false;
				}
	
	
				// Add Album to left hand columne area
				var numofimages = $(this).find("div.image-holder span.image-src").length;
				var lastimageindex = numofimages-1;
	
				var lastimage;
				var lastimagesize = new Array();
	
				var firstimage;
				var firstimagesize = new Array();
				var firstimageindex = 0;
				
				var th1dimensions = [0,0];
				var th2dimensions = [0,0];
				var th1dimensionsns = [0,0];
				var th2dimensionsns = [0,0];
	
				if (!galleryalbumnew) {
					// If an image has been set as the album cover thum (ie, it cantains span.cover-thumb)
					// then we use that image for the album cover, else we use the first image in the album
					if ($(this).find("span.cover-thumb:eq(0)").length > 0) {
						var coverimageholder=$(this).find("span.cover-thumb:eq(0)").parent();
						if ($(coverimageholder).find("img").length > 0) {
							firstimage=$(coverimageholder).find("img");
							firstimagesrc=$(firstimage).attr("src");
							firstimagesize[0]=parseInt($(firstimage).parent().find("span.thumb-size").text().split(",")[0]);
							firstimagesize[1]=parseInt($(firstimage).parent().find("span.thumb-size").text().split(",")[1]);
						}
						else {
							firstimage=$(coverimageholder).find("span.thumb-info");
							firstimagesrc=$(firstimage).text().split("|")[0];
							firstimagesize[0]=parseInt($(firstimage).text().split("|")[1].split(",")[0]);
							firstimagesize[1]=parseInt($(firstimage).text().split("|")[1].split(",")[1]);
						}
					}
					else {
						if ($(this).find("div.image-holder:eq("+firstimageindex+") img").length > 0) {
							firstimage=$(this).find("div.image-holder:eq(0) img");
							firstimagesrc=$(firstimage).attr("src");
							firstimagesize[0]=parseInt($(firstimage).parent().find("span.thumb-size").text().split(",")[0]);
							firstimagesize[1]=parseInt($(firstimage).parent().find("span.thumb-size").text().split(",")[1]);
						}
						else if ($(this).find("div.image-holder:eq("+firstimageindex+") span.thumb-info").length > 0) {
							firstimage=$(this).find("div.image-holder:eq("+firstimageindex+") span.thumb-info");
							firstimagesrc=$(firstimage).text().split("|")[0];
							firstimagesize[0]=parseInt($(firstimage).text().split("|")[1].split(",")[0]);
							firstimagesize[1]=parseInt($(firstimage).text().split("|")[1].split(",")[1]);
						}
						else {
							firstimagesrc="/gallerydemo/mobykogallery/assets/ui/empty.image.grey.gif";
							firstimagesize[0]=1;
							firstimagesize[1]=1;
						}
					}
					
					if ($(this).find("div.image-holder:eq("+lastimageindex+") img").length > 0) {
						lastimage=$(this).find("div.image-holder:eq("+lastimageindex+") img");
						lastimagesrc=$(lastimage).attr("src");
						lastimagesize[0]=parseInt($(lastimage).parent().find("span.thumb-size").text().split(",")[0]);
						lastimagesize[1]=parseInt($(lastimage).parent().find("span.thumb-size").text().split(",")[1]);
					}
					else if ($(this).find("div.image-holder:eq("+lastimageindex+") span.thumb-info").length > 0) {
						lastimage=$(this).find("div.image-holder:eq("+lastimageindex+") span.thumb-info")
						lastimagesrc=$(lastimage).text().split("|")[0];
						lastimagesize[0]=parseInt($(lastimage).text().split("|")[1].split(",")[0]);
						lastimagesize[1]=parseInt($(lastimage).text().split("|")[1].split(",")[1]);
					}
					else {
						lastimagesrc="/gallerydemo/mobykogallery/assets/ui/empty.image.gif";
						lastimagesize[0]=1;
						lastimagesize[1]=1;
					}
					
					var th1dimensions = imageCropDimensions(firstimagesize, [72, 95]);
					var th2dimensions = imageCropDimensions(lastimagesize, [53, 53]);
					var th1dimensionsns = imageCropDimensions(firstimagesize, [40, 50]);
					var th2dimensionsns = imageCropDimensions(lastimagesize, [29, 29]);
				}
	
				/* Generate HTML for Album blocks */
				var selectedclasstext="";
				if (this.className.indexOf("gallery-album-selected") !=-1) {
					selectedclasstext = " album-block-selected";
					if (this.className.indexOf("gallery-album-master") !=-1) {
						selectedclasstext += " album-block-master";
					}
				}			
				else if (galleryalbumnew) {
					selectedclasstext = " album-block-new album-block-hidden";
				}
				
				var insertHTML='<div class="album-block'+selectedclasstext+'">';
				insertHTML+='<div class="new-album-holder">';
				insertHTML+='<div></div>';
				insertHTML+='<h4>Drag photos here to create a new album</h4>';
				insertHTML+='</div>';
				insertHTML+='<div class="not-selected">';
				insertHTML+='<div class="holder">';
				if (galleryalbumnew) {
					insertHTML+='<img class="ns-main-thumb" src="/gallerydemo/mobykogallery/assets/ui/empty.image.gif" alt="" />';
					insertHTML+='<div class="ns-small-thumb-holder">';
					insertHTML+='<div>';
					insertHTML+='<img src="/gallerydemo/mobykogallery/assets/ui/empty.image.gif" alt="" />';
				}
				else {
					insertHTML+='<img class="ns-main-thumb" src="'+firstimagesrc+'" alt="" ';
					insertHTML+='style="width: '+th1dimensionsns[0]+'px; height: '+th1dimensionsns[1]+'px; ';
					insertHTML+='left: '+(-th1dimensionsns[2])+'px; top: '+(-th1dimensionsns[3])+'px;" />';
					insertHTML+='<div class="ns-small-thumb-holder">';
					insertHTML+='<div>';
					insertHTML+='<img src="'+lastimagesrc+'" alt="" ';
					insertHTML+='style="width: '+th2dimensionsns[0]+'px; height: '+th2dimensionsns[1]+'px; ';
					insertHTML+='left: '+(-th2dimensionsns[2])+'px; top: '+(-th2dimensionsns[3])+'px;" />';
				}
				insertHTML+='</div>';
				insertHTML+='</div>';
				insertHTML+='</div>';
				insertHTML+='<h4>'+$(thisgalleryalbum).find("span.album-name").text()+'</h4>';
				insertHTML+='</div>';
				insertHTML+='<div class="selected-content">';
				insertHTML+='<div class="thumbs-holder">';
				insertHTML+='<img class="main-thumb" src="'+firstimagesrc+'" alt="" ';
				insertHTML+='style="width: '+th1dimensions[0]+'px; height: '+th1dimensions[1]+'px; ';
				insertHTML+='left: '+(-th1dimensions[2])+'px; top: '+(-th1dimensions[3])+'px;" />';
				insertHTML+='<div class="small-thumb-holder">'
				insertHTML+='<div>';
				insertHTML+='<img src="'+lastimagesrc+'" alt="" ';								
				insertHTML+='style="width: '+th2dimensions[0]+'px; height: '+th2dimensions[1]+'px; ';
				insertHTML+='left: '+(-th2dimensions[2])+'px; top: '+(-th2dimensions[3])+'px;" />';
				insertHTML+='</div>';
				insertHTML+='</div>';
				insertHTML+='</div>';
				insertHTML+='<div class="album-block-delete-warning"></div>';
				insertHTML+='<h4>'+trimToMaxCharWords($(thisgalleryalbum).find("span.album-name").text(),20)+'</h4>';
				insertHTML+='<span class="meta album-block-full-album-name">'+$(thisgalleryalbum).find("span.album-name").text()+'</span>';
				insertHTML+='<h5>'+(lastimageindex+1)+' photos</h5>';
				insertHTML+='<h6>Updated '+makeDateStringFromDateTimeString($(thisgalleryalbum).find("span.album-date-updated").text())+'</h6>';
				if (!isMasterGallery) {	
					insertHTML+='<a href="#" class="album-block-delete-album">Delete album</a>';
				}
				insertHTML+='</div>';
				insertHTML+='<span class="meta album-id">'+$(thisgalleryalbum).find("span.album-id").text()+'</span>';
				insertHTML+='<span class="meta album-block-album-date-created">'+$(thisgalleryalbum).find("span.album-date-created").text()+'</span>';
				insertHTML+='</div>';
	
				var latestalbumblock=$(insertHTML);
				$(albumHolderStage).append(latestalbumblock);
	
				$(latestalbumblock).hover( function() {
					$(this).addClass("album-block-hover");
				}, function() {
					$(this).removeClass("album-block-hover");
					
				});
					
				// Album click event
				// This selects the album unless already selected or new album block
				$(latestalbumblock).click( function() {
	
					// Prevent using from switching albums while a search, sort or slideshow generation is taking place.
					if (currentlySearching || currentlySorting || generatingSlideshow) {
						return false;	
					}
						
					var thisalbumblock=this;
	
					// If an empty gallery, simply return 
					if (this.className.indexOf("album-block-new") != -1) {
						return false;
					}
					
					// If slideShow has been selected deselect it.
					if (slideshowOpen) {
						$(thisGallery).find("div.slideshow-holder a.back-to-album").click();
						slideshowOpen=false;
					}
				
					if (imageInfoBoxOpen) {
						$(imageInfoHolder).find("a.back-to-album").click();
						imageInfoBoxOpen=false;
					}
				
					// Or If gallery already selected, simply return
					if (this.className.indexOf("album-block-selected") != -1) {
						return false;
					}
	
					var thisalbumid=$(this).find("span.album-id").text();
					$(thisGallery).find("div.album-block-selected").removeClass("album-block-selected");
					$(this).addClass("album-block-selected");
				
					$(thisGallery).find("div.gallery-album-selected").removeClass("gallery-album-selected");
		
					$(thisGallery).find("div.gallery-album").each( function() {
						if ($(this).find("span.album-id").text() == thisalbumid) {
							$(this).addClass("gallery-album-selected");
							$(this).find("a.display-album").click();
							var updatenumofimages=$(this).find("div.image-holder span.image-src, div.image-holder-hidden span.image-src").length;
							$(thisalbumblock).find("div.selected-content h5").text(updatenumofimages+ " photos");
						} 
					});
					
					return false;	
				});

				$(latestalbumblock).find("h4").mouseover( function() {
					// Album name can only be edited in album blocks that are currently selected
					// Also, you can't edit the master albu, block name (hence, the second condition in the if statement)
					if ($(latestalbumblock).get()[0].className.indexOf("album-block-selected") != -1 && $(latestalbumblock).get()[0].className.indexOf("album-block-master") == -1) {
						var editinput = $('<input class="album-block-name-edit-input" value="'+$(latestalbumblock).find("div.selected-content span.album-block-full-album-name").text()+'" />');
						var thisalbumname = this;
						var editmouseoutfunction="";
						var savedalbumname=$(latestalbumblock).find("div.selected-content span.album-block-full-album-name").text();
						$(this).parent().append(editinput);
						
						$(editinput)
						.focus()
						.blur(function() {
							// Make sure that new album name is not empty and is at least 3 characters long
							var newalbumnametext=$(this).val();	
							if (!checkForChars(newalbumnametext)) {
								newalbumnametext=savedalbumname;
							}
							$(latestalbumblock)
							.find("h4")
								.text(trimToMaxCharWords(newalbumnametext,20))
							.end()
							.find("div.selected-content span.album-block-full-album-name")
								.text(newalbumnametext)
							.end()
							$(thisGallery).find("div.gallery-album-selected span.album-name").text(newalbumnametext);
							$(galleryInfoAlbumName).text(trimToMaxCharWords(newalbumnametext,25));
							
							// Only send update text to server
							// if it has actually changed
							
							if (newalbumnametext != savedalbumname) {
								var renamealbumid = $(latestalbumblock).find("span.album-id").text();
															
								// AJAX Call
								// Update name of album
								// Send album id and new album name
								// Resturn success failure
								
								$.post("/gallerydemo/mobykogallery/assets/ajax/update-album-name.php",{ albumId: renamealbumid, newName: newalbumnametext }, function() {
									// We'll fail silently for the present
								});
								
								// End of Ajax call
							}
							
							// Putting the below in a settimeout
							// rather than executing it straight away
							// prevents Safari crashing for some reason
							setTimeout( function() {
								$(editinput).remove();
							},100);
								
						})
						.keydown( function(e) {
							if (e.keyCode == 13) {
								$(this).blur();
							}
						})
						.keyup( function() {
							$(galleryInfoAlbumName).empty().text(trimToMaxCharWords($(this).val(),25));
						})
						.mouseout( function() {
							$(this).blur();
						});
						
					}
				});
				
				var deleteGallery = function(agallery, analbumblock) {
					var thisalbumid=$(agallery).find("span.album-id").text();
					var previousalbumblock=$(analbumblock).prev();
					$(analbumblock).animate({opacity: 0}, 500, function() {
						$(this).animate({height: 0}, 500, function() {
							$(this).remove();
							$(albumHolderStage).find("a.album-block-reset").click();
						});
					});
					$(agallery).animate({opacity: 0}, 500, function() {
						$(this).remove();
						$(previousalbumblock).click();
						
						// AJAX Call
						// Delete an album and all its pictures
						// Send album id. Return success
						// Action - delete the album and all album images linked to that album
						
						$.post("/gallerydemo/mobykogallery/assets/ajax/delete-album.php", { albumId: thisalbumid }, function() {
							// Ajax callback
							// Fail or succeed silently
						});
						
						// End of Ajax call
						
					});
				}
				$(latestalbumblock).find("a.album-block-delete-album").click( function() {
					$(latestalbumblock)
					.find("div.selected-content")
						.find("a.album-block-delete-album, h4, h5, h6")
							.animate({opacity: 0}, 500, function() {
								$(this).css({visibility: "hidden"});	
							})
						.end()
					.end()
					$(latestalbumblock)
					.find("div.album-block-delete-warning")
					.empty()
					.html('<p>Are you <strong>sure</strong> you want to delete this album?<br /><a href="#">Yes</a> <a href="#">No</a></p>')
					.css({display:"block"})
					.animate({height: 40}, 500, function() {
						
						var thisconfirmblock=this;
						$(this).find("a").unbind()
						.mousedown( function() { return false })
						.mouseup( function() { return false })
						.click( function() {
							switch($(this).text()) {
								case "Yes":
								
								deleteGallery(thisgalleryalbum,latestalbumblock);


								break;
								
								case "No":
								$(thisconfirmblock).animate({ height: 0}, 500, function() {
									$(this).css({display: "none"});
								});
								$(latestalbumblock)
								.find("div.selected-content")
									.find("a.album-block-delete-album, h4, h5, h6")
										.css({visibility:"visible"})
										.animate({opacity: 1}, 500, function() {
										})
									.end()
								.end()
								break;	
							}
							return false;
						});
						
					}); 
					return false;
				});


				// NOw add required number of empty image holders 
				var numempties = itemsperpage-(numofimages % itemsperpage);
				insertHTML="";
				for (var counter2=numofimages;counter2<(numofimages+numempties); counter2++) {
					insertHTML+='<div class="image-holder">';
					if ((counter2 % 2)==0) {
						insertHTML+='<div class="empty-image-landscape empty-image"></div>';	
					}
					else {
						insertHTML+='<div class="empty-image-portrait empty-image"></div>';	
					}
					insertHTML+='<span class="image-pos">'+counter2+'</span>';
					insertHTML+='</div>';
				}
				$(this).append(insertHTML);
	
				// Ie reached here

				// Position images in the center of their holder
				$(this).find("div.image-holder img").each( function() {
					var topmargin=parseInt((146-parseInt($(this).parent().find("span.thumb-size").text().split(",")[1]))/2);
					var leftmargin=parseInt((150-parseInt($(this).parent().find("span.thumb-size").text().split(",")[0]))/2);

					$(this).css({marginLeft: leftmargin, marginTop: topmargin, visibility: "visible" });
				});


				$(this).find("div.image-holder img").each( initialiseGalleryImage = function() {
					
					$(this).mousedown( function(e) {
						if (isIE6 || isIE7) {
							return false;	
						}
						var holder = $(this).parent();
						var imagepos = parseInt($(holder).find("span.image-pos").text());
						if ((imagepos > ((currentpage+1)*itemsperpage-1)) || imagepos < (currentpage*itemsperpage)) {
							return false;
						}
						returnScroll=false;
						$(this).mouseover();
						var mouseclickpos = checkwhere(e);
						var holderpos = findPos($(this).parent().get()[0]);
						popupOffsetX = mouseclickpos[0]-holderpos[0]+10; 
						popupOffsetY = mouseclickpos[1]-holderpos[1]+10;
						$(imagePopup).mousedown();
						return false;
					});
	
	
					$(this).mouseover( function() {
						
						if (imageDrag || returnScroll) {
							return false;
						}
						
						// We cancel any mouseovers while an image is being rotated
						if (popUpRotatingImage) {
							return false;	
						}

						$(uploadInstructions).css({display: "none"});
						var holder = $(this).parent();
						var imagepos = parseInt($(holder).find("span.image-pos").text());
						
						if ((imagepos > ((currentpage+1)*itemsperpage-1)) || imagepos < (currentpage*itemsperpage)) {
							return false;
						}
	
						if (popUpConfirmMessageOpen) {
							$(imagePopup).find("h4,h5,h6,a.rotate-image,a.delete-image").stop().css({opacity: 1});
							$(imagePopup)
							.find("div.image-popup-delete-warning")
							.stop()
							.css({display:"none", height:0});
							popUpConfirmMessageOpen=false;	
						}

						if (popUpNameEditOpen) {
							$(imagePopup).find("div.image-popup-name-edit-input-holder").remove();
							popUpNameEditOpen=false;
						}
						
						selectedImage=this;
						$(imagePopup).stop();

						// Deal with purchased content
						if ($(selectedImage).parent().find("span.source").text() == "PURCHASED") {
							$(imagePopup).addClass("image-popup-purchased-content");	
						}
						else {
							$(imagePopup).removeClass("image-popup-purchased-content");	
						}

						var newpopupimage=$(selectedImage).clone();
						var holderposition = findPos($(holder).get()[0]);
						var holderwidth = $(holder).width();
						var thumbwidth = $(this).width();
						var thumbheight = $(this).height();
						var popupwidth = 150;
						var popupthumblmargin = parseInt((popupwidth-thumbwidth)/2);
						var popupthumbbmargin = parseInt($(this).css("marginTop"));
						var popupleft = holderposition[0] + parseInt((holderwidth-popupwidth)/2);
						var popuptop = holderposition[1];
	
						$(imagePopup)
						.find("div.image-popup-image-holder img")
							.remove()
						.end()
						.find("div.image-popup-image-holder")
							.prepend(newpopupimage)
						.end()
						.find("img")
							.css({marginLeft: popupthumblmargin, marginBottom: popupthumbbmargin})
							.css({marginTop: popupthumbbmargin, marginRight: 0})
							.css({width: thumbwidth, height: thumbheight})
							.end()
						.find("h4").text(trimToMaxCharWords($(holder).find("span.image-name").text(), 16))
							.end()
						.find("h5").text(trimToMaxCharWords($(thisGallery).find("div.gallery-album-selected span.album-name").text(), 16))
							.end()
						.find("h6").text(makeDateStringFromDateTimeString($(holder).find("span.date").text()))
							.end()
						.css({ left: popupleft, top: popuptop, opacity: 1});
	

						return false;
					});
				});
				
				// Function for updating the page info details that appear at the bottom left of the mian stage
				// Details of the images currently being displayedae shown
				// plus what search term is currently active.
				// It also deals with a clear filter button for clearing the search term;
				var updatePageInfoDetails = function() {

					// This has changed so we display page rather than range of items
					// But have left previous funcitonality in in case we need it in the future
					var thisstartrange = currentpage*itemsperpage+1;
					var thisendrange = thisstartrange+itemsperpage-1;
					thisstartrange = (thisstartrange > numofdisplayitems) ? numofdisplayitems : thisstartrange;
					thisendrange = (thisendrange > numofdisplayitems) ? numofdisplayitems : thisendrange;
					
					// $(mainStagePageInfo).find("span.visible-images").text(thisstartrange+"-"+thisendrange);
					// $(mainStagePageInfo).find("span.total-images").text(numofdisplayitems);
					
					$(mainStagePageInfo).find("span.visible-images").text(currentpage+1);
					$(mainStagePageInfo).find("span.total-images").text(parseInt(numitems/itemsperpage));
					
					var currentsearchterm = $(thisgalleryalbum).find("span.album-search-term:eq(0)").text();
					if (currentsearchterm != "Search" && currentsearchterm !="") {
						$(mainStagePageInfo).addClass("page-info-search-active");
						$(mainStagePageInfo).find("span.image-filter").text("| Images filtered by '"+trimToMaxCharWords(currentsearchterm,16)+"' | ");
						$(mainStagePageInfo).find("a.clear-filter").unbind("click").click( function() {
							$(thisGallery).find("div.search-box input:eq(0)").attr("value","Search");
							$(thisGallery).find("div.search-box a.search-submit:eq(0)").click();
							return false;
						});
					}
					else {
						$(mainStagePageInfo).removeClass("page-info-search-active");
					}
				}
	
				var updateArrows = function() {
					if (numitems <= itemsperpage) {
						$(thisGallery).find("a.main-scroll-up").css({display: "none"});
						$(thisGallery).find("a.main-scroll-down").css({display: "none"});
					}
					else if (currentpage==0) {
						$(thisGallery).find("a.main-scroll-up").css({display: "none"});	
						$(thisGallery).find("a.main-scroll-down").css({display: "block"});
					}				
					else if (currentpage >= (numpages-1)) {
						$(thisGallery).find("a.main-scroll-up").css({display: "block"});
						$(thisGallery).find("a.main-scroll-down").css({display: "none"});
					}
					else {
						$(thisGallery).find("a.main-scroll-up").css({display: "block"});
						$(thisGallery).find("a.main-scroll-down").css({display: "block"});
					}
					updatePageInfoDetails();
					
				}
				
				var loadnextpageofimages = function() {
					var startloadnewthumb=((currentpage+1)*itemsperpage);
					var endloadnewthumb=((currentpage+2)*itemsperpage)-1;
					startloadnewthumb = startloadnewthumb < (numitems-1) ? startloadnewthumb : (numitems-1);
					endloadnewthumb = endloadnewthumb < (numitems-1) ? endloadnewthumb : (numitems-1);
					
					for (var counter=startloadnewthumb; counter<=endloadnewthumb; counter++) {
						$(thisgalleryalbum).find("div.image-holder:eq("+counter+")").each( function() {
							updateemptythumbs(this);
						});
					}
					$(thisgalleryalbum).find("a.initialise-latest-image").click();
				}
	
	
				$(this).find("a.scroll-gallery-up").click( function() {
					if (mainGalleryScrolling) {
						return false;	
					}
					mainGalleryScrolling=true;
					currentpage--; 
					$(thisgalleryalbum).animate({top: -(currentpage*viewportheight)}, 1000, function() {
						loadnextpageofimages();
						mainGalleryScrolling=false;
					});
					updateArrows();
					return false;
				});
	
				$(this).find("a.scroll-gallery-down").click( function() {
					if (mainGalleryScrolling) {
						return false;	
					}
					mainGalleryScrolling=true;
					currentpage++; 
					$(thisgalleryalbum).animate({top: -(currentpage*viewportheight)}, 1000, function() {
						loadnextpageofimages();
						mainGalleryScrolling=false;	
					});
					updateArrows();
					return false;
				});
				
				$(this).find("a.display-album").click( function() {
					var thissearchterm = $(thisgalleryalbum).find("span.album-search-term").text();
					
					$(thisGallery).find("div.search-box input").attr("value",thissearchterm);
	
					numitems=$(thisgalleryalbum).find("div.image-holder").length;
					numofdisplayitems=$(thisgalleryalbum).find("div.image-holder span.image-id").length;
					numpages = parseInt(numitems/itemsperpage);
					if ($(thisgalleryalbum).get()[0].className.indexOf("gallery-album-master") != -1) {
						$(galleryInfoHolderTop).addClass("album-info-main-album-selected");
					}
					else {
						$(galleryInfoHolderTop).removeClass("album-info-main-album-selected");
					}
					$(galleryInfoAlbumName).text(trimToMaxCharWords($(thisgalleryalbum).find("span.album-name").text(),25));

					loadnextpageofimages();		
					updateArrows();
				});	
	
	
				$(this).find("a.refresh-album").click( function() {
	
					numitems=$(thisgalleryalbum).find("div.image-holder").length;
					numofdisplayitems=$(thisgalleryalbum).find("div.image-holder span.image-id").length;
					
					// Check that we have the correct number of empty images
					var numofnonempties=$(thisgalleryalbum).find("div.image-holder:has(span.image-src)").length;
					var correctnumofempties=15-(numofnonempties % itemsperpage);
					correctnumofempties = (correctnumofempties == 0) ? 15 : correctnumofempties;
					var numofempties=numitems-numofnonempties;
					
					if (numofempties > correctnumofempties) {
						for (var counter=numitems-1; counter>=(numofnonempties+correctnumofempties); counter--) {
							$(thisgalleryalbum).find("div.image-holder:eq("+counter+")").remove()
						}
						numitems=counter+1;
					}
					else if (numofempties < correctnumofempties) {
						
						if ($(thisgalleryalbum).find("div.image-holder:eq("+(numitems-1)+") div.empty-image-portrait").length > 0) {
							var orientationchanger=1;	
						}
						else {
							var orientationchanger=0;	
						}
						
						var diff=correctnumofempties-numofempties;
						for (var counter=0; counter<diff; counter++) {
							insertHTML+='<div class="image-holder">';
							if (((counter+orientationchanger) % 2)==0) {
								insertHTML+='<div class="empty-image-landscape empty-image"></div>';	
							}
							else {
								insertHTML+='<div class="empty-image-portrait empty-image"></div>';	
							}
							insertHTML+='<span class="image-pos">'+counter2+'</span>';
							insertHTML+='</div>';
						}
						$(thisgalleryalbum).append(insertHTML);
						// Update numitems
						numitems+=diff;
					}
										
					// NOw me need to attach events to the new empty images
					$(thisgalleryalbum).find("a.initialise-empty-images").click();
					
					for (var counter=0; counter<numitems; counter++) {
						$(thisgalleryalbum).find("div.image-holder:eq("+counter+")").find("span.image-pos").text(counter);
					}
	
					numpages = parseInt(numitems/itemsperpage);
					updateArrows();
				});
				
				
				$(this).find("a.reset-album").click( function() {
					// Reset the album galleries variables, so first pages shows
					currentpage=0;
					$(thisgalleryalbum).css({top: 0});
	
					updateArrows();
				});	
	
	
				
				$(this).find("div.image-holder div.empty-image").each( initialiseEmptyImage = function() {
					$(this).mouseover( function() {
						if (imageDrag || returnScroll || galleryIsEmpty) {
							return false;
						}
						if (!popUpRotatingImage) {
							$(imagePopup).css({ left: -1000, top: -1000});
						}
						var holder = $(this).parent();
						var imagepos = parseInt($(holder).find("span.image-pos").text());
						if ((imagepos > ((currentpage+1)*itemsperpage-1)) || imagepos < (currentpage*itemsperpage)) {
							return false;
						}
						// edgeleftoffset ensure that the uplaod instructions popup is right aligned
						// when an empoty image at the right hand side of the screen is mouseovered 
						if ((imagepos % 5) == 4) {
							var edgeleftoffset = 148;	
						}
						else {
							var edgeleftoffset = 0;	
						}
						var holderpos=findPos(this);
						var paneloffset= new Array();
						if (this.className.indexOf("portrait") !=-1) {
							if (edgeleftoffset == 0) {
								paneloffset=[-15, -2];
							}
							else {
								paneloffset=[-17, -2];
							}
						}
						else {
							paneloffset=[-2, -17];
						}
						$(uploadInstructions).css({top: holderpos[1]+paneloffset[1], left: holderpos[0]+paneloffset[0]-edgeleftoffset});
						$(uploadInstructions).css({display:"block"});
						return false;
					});
				});
	
				$(this).find("a.initialise-latest-image").click( function() {
					var justaddedimage=$(thisgalleryalbum).find("img.awaiting-initialisation");
					$(justaddedimage)
						.removeClass("awaiting-initialisation")
						.each(initialiseGalleryImage);
					return false;
				});			
	
				$(this).find("a.initialise-empty-images").click( function() {
					var newemptyimages=$(thisgalleryalbum).find("div.empty-image");
					$(newemptyimages)
						.each(initialiseEmptyImage);
					return false;
				});		
				
				
				/* Launch slideshow stuff*/
				$(this).find("a.launch-slideshow").click( function() {
					
					if (generatingSlideshow) {
						return false;	
					}

					var numSlideShowImages=$(thisGallery).find("div.gallery-album-selected div.image-holder span.image-src").length;
					if (numSlideShowImages == 0) {
						return false;	
					}

					generatingSlideshow=true;
					slideshowOpen=true;
					
					var carouselthumbdimensions=60;
					var carouselthumbmarginright=8;
					var slideshowvisiblethumbs=9;
					var slideshowleftmostthumb=0;
					var slideshowCarouselStage=$(thisSlideShowHolder).find("div.slideshow-carousel-stage");
					var slideshowCarouselHolder=$(thisSlideShowHolder).find("div.slideshow-carousel-holder");
					var slideShowStage=$(thisSlideShowHolder).find("div.main-stage");
					var slideshowStageHolder=$(slideShowStage).parent()
;
					var slideshowimagedimensions=[642, 370];
					var enlargedimageratio=1.184;
					var slideshowPlaying=true;
					var slideshowSpeed=2000;
					var currentSlideShowImage=0;
					var maxSlideshowSpeed=9500;
					var minSlideshowSpeed=500;
					var slideshowTimer="";
					var slideshowAnimateFunc="";
					var slideshowMouseOverPause=false;
					var slideshowMainImage=$(thisSlideShowHolder).find("img.main-image");
					var slideShowControls=$(thisSlideShowHolder).find("div.slideshow-controls-holder");
					var slideShowControlsVisible=false;
					var slideshowEnlargedImageHolder=$(thisSlideShowHolder).find("div.slideshow-enlarged-image-holder");
					var slideshowPreviousSelectedImage="";
					


					var enlargingImageActive=false;
					var enlargedSlideshowOn=false;
					var enlargedHolderSize=[760,438];
					var enlargedHolderRatio=760/438;
					
					var slideshowThumbnailPausePlay = $(thisSlideShowHolder).find("div.slideshow-carousel-pause-play");
					var slideshowthumbpausebutton = $(slideshowThumbnailPausePlay).find("a.slideshow-carousel-pause");
					var slideshowthumbplaybutton = $(slideshowThumbnailPausePlay).find("a.slideshow-carousel-play");
					
					// Pause play thumbnail button functions
					// This button appears when a user rolls over one of the thumbnails in the slideshow
					$(slideshowthumbpausebutton)
					.css({display: "block"})
					.unbind("click").click( function() {
						$(this).css({display: "none"});
						$(slideshowthumbplaybutton).css({display: "block"});
						$(slideShowControls).find("a.slideshow-controls-pause").click();
						return false;
					});
					
					$(slideshowthumbplaybutton)
					.css({display: "none"})
					.unbind("click").click( function() {
						$(this).css({display: "none"});
						$(slideshowthumbpausebutton).css({display: "block"});
						$(slideShowControls).find("a.slideshow-controls-play").click();
						return false;
					});
						
					// The following two events are needed to successfully
					// fade in/out the controls when user mouseovers
					// or mouseexits a sildeshow image.
					
					var thisMouseMoveFunction = function() {
						if (slideShowControlsVisible && !enlargingImageActive) {
							slideShowControlsVisible=false;
							$(slideShowControls)
							.stop()
							.animate({opacity: 0}, 500, function() {
								$(this).css({display: "none"});
								slideshowMouseOverPause=false;
								slideshowTimer=setTimeout( function() {
									slideshowAnimateFunc();
								}, slideshowSpeed)
							});
						}
						return false;
					}
					
					
					$(document).unbind("mousemove", thisMouseMoveFunction).bind("mousemove",thisMouseMoveFunction); 
					$(document).unbind("mouseover", thisMouseMoveFunction).bind("mouseover",thisMouseMoveFunction); 
					$(thisSlideShowHolder).unbind("mouseover", thisMouseMoveFunction).bind("mouseover",thisMouseMoveFunction); 
					
					$(slideShowControls).unbind("mouseover").mouseover( function() {
						return false;
					});
	
					$(slideShowControls).unbind("mousemove").mousemove( function() {
						return false;
					});
						
					$(thisSlideShowHolder)
					.css({display:"block", opacity: 0})
					.animate({opacity: 1}, 500, function() {
						
						// Turns highlight off on All My Photos header
						$(galleryInfoHolderTop).addClass("album-info-panel-open");
						
						// Fade out search box and menu 
						fadeOutSortAndSearch();
	
						// Hide main gallery carousel up arrow by adding hide class
						$(thisGallery).find("a.main-scroll-up").addClass("hide");
	
						// Add selected class to labum name to turn it white again
						$(thisGallery).find("div.gallery h3.album-info a.album-name").removeClass("album-name-selected");

						// Extend the width of stage to hold all the thumbnails
						$(slideshowCarouselStage).css({width: (numSlideShowImages+1)*(carouselthumbdimensions+carouselthumbmarginright)});
				
						// Set the width of main stage so that it can contain all the images on one row 
						// $(slideShowStage).css({ width: slideshowimagedimensions[0]*numSlideShowImages});
	
						var initialiseSlideshow = function(startimageholder, increment) { 
						
							if ((startimageholder+increment) > numSlideShowImages) {
								var endimageholder = numSlideShowImages;
							}
							else {
								var endimageholder = startimageholder+increment;
							}
												
							var firstimagecheck=true;
							$(thisGallery)
							.find("div.gallery-album-selected div.image-holder")
							.slice(startimageholder, endimageholder)
							.each( function() {
								
								var thisgalleryimageholder=this;
								
								var thismainimageloaded=false;
								var thismainimagesrc=$(thisgalleryimageholder).find("span.image-src").text();
								var thismainimagename=$(thisgalleryimageholder).find("span.image-name").text();
								var thismainimagedimensions=$(thisgalleryimageholder).find("span.image-size").text();
								var thismainimagethumbmaster=$(thisgalleryimageholder).find("img");
								var thismainimagepos=parseInt($(thisgalleryimageholder).find("span.image-pos").text());
								var savedthumbdetails="";
								
								// Aprox left offset of centre of the thumb 
								var thisthumbcentreoffset=(carouselthumbdimensions+8)*thismainimagepos+parseInt(carouselthumbdimensions/2);

								var thisthumbnailholder=$('<div class="slideshow-thumb-holder"></div>');

								if ($(thismainimagethumbmaster).length > 0) {
									var thismainimagethumbsrc=$(thismainimagethumbmaster).attr("src");
									var thismainimagethumbwidth=parseInt($(thismainimagethumbmaster).attr("width"));
									var thismainimagethumbheight=parseInt($(thismainimagethumbmaster).attr("height"));
									$(thisthumbnailholder).append('<img src="'+thismainimagethumbsrc+'" alt="" height="'+thismainimagethumbheight+'" width="'+thismainimagethumbwidth+'" /><div class="carousel-thumb-opacity"></div>');
								}
								else {
									savedthumbdetails=$(thisgalleryimageholder).find("span.thumb-info").text();
									var thismainimagethumbsrc=savedthumbdetails.split("|")[0];
									var thismainimagethumbwidth=savedthumbdetails.split("|")[1].split(",")[0];
									var thismainimagethumbheight=savedthumbdetails.split("|")[1].split(",")[1];
									$(thisthumbnailholder).append('<span class="meta thumb-info">'+savedthumbdetails+'</span><div class="carousel-thumb-opacity"></div>');
								}
		
								$(thisSlideShowHolder).find("div.slideshow-carousel-stage").append(thisthumbnailholder);
								
								// store the opacity thumb element in this variable for use later
								var thisthumbopacityelement=$(thisthumbnailholder).find("div.carousel-thumb-opacity");
		
								// alert($(thisthumbnailholder).html());
								var thisslideshowthumb = $(thisthumbnailholder).find("img");
								// Check if gallery image has been loaded
								// If so, then size it correctly
								if ($(thisslideshowthumb).length > 0) {
									var thumbwidth=thismainimagethumbwidth;
									var thumbheight=thismainimagethumbheight;
									if (thumbwidth > thumbheight) {
										thumbheight=parseInt(thumbheight/thumbwidth*carouselthumbdimensions);
										thumbwidth=carouselthumbdimensions;
									}
									else {
										thumbwidth=parseInt(thumbwidth/thumbheight*carouselthumbdimensions);
										thumbheight=carouselthumbdimensions;
									}
									$(thisslideshowthumb)
									.css({height: thumbheight, width:thumbwidth })
									.css({marginLeft: parseInt((carouselthumbdimensions-thumbwidth)/2)})
									.css({marginTop: parseInt((carouselthumbdimensions-thumbheight)/2)})
									.css({marginBottom: 0, marginRight: 0});
								}
								
								// Hover funtion for when user hovers over a slideshow thumbnail
								// It reveals a pause - play button among other things
								$(thisthumbnailholder)
								.hover( function() {
									
									// This gids the sleidshow controls 
									thisMouseMoveFunction();
									
									$(this).addClass("hover");
									var thishoveroffset=parseInt($(slideshowCarouselStage).css("left")) + thisthumbcentreoffset-8;
									$(slideshowThumbnailPausePlay)
									.css({left: thishoveroffset })
									.addClass("slideshow-carousel-pause-play-hover");
								}, function(e) {
									var relTarg = e.relatedTarget || e.fromElement;
									
									var ieweirdflag=true;
									if (isIE6 || isIE7) {
										if (relTarg.tagName=="IMG") {
											ieweirdflag = false;
										}
									}

									if (ieweirdflag && relTarg && relTarg.className != "slideshow-carousel-pause" && relTarg.className != "slideshow-carousel-play") {
										$(this).removeClass("hover");
										$(slideshowThumbnailPausePlay).removeClass("slideshow-carousel-pause-play-hover");
									}
									else {
										$(slideshowThumbnailPausePlay).unbind("mouseout").mouseout( function(e) {
											var relTarg = e.relatedTarget || e.fromElement;
											if (relTarg != $(thisthumbopacityelement).get()[0]) {
												$(thisthumbnailholder).removeClass("hover");
												$(slideshowThumbnailPausePlay).removeClass("slideshow-carousel-pause-play-hover");
											}
										});
									}
									
								});
														
								// Now add the full images to the main stage
								var thisbackimageholder=$('<div class="back-image-block"></div>');
								$(slideShowStage).append(thisbackimageholder);
		
								var imagewidth=parseInt(thismainimagedimensions.split(",")[0]);
								var imageheight=parseInt(thismainimagedimensions.split(",")[1]);
								
								var imageratio=imagewidth/imageheight;
								if (imageratio > slideshowimagedimensions[0]/slideshowimagedimensions[1]) {
									imagewidth=slideshowimagedimensions[0];
									imageheight=parseInt(imagewidth/imageratio);
								}
								else {
									imageheight=slideshowimagedimensions[1];
									imagewidth=parseInt(imageheight * imageratio);
								}
								var thismarginleft=parseInt((slideshowimagedimensions[0]-imagewidth)/2);
								var thismargintop=parseInt((slideshowimagedimensions[1]-imageheight)/2);
								var thisimagename=thismainimagename;
								var thisimagesrc=thismainimagesrc;
		


								// Check to see if this is the first image the album. If so
								// Setup the main image to have the same dimensins and src 
								// as the first image in the album
								if (startimageholder==0 && firstimagecheck) {
									firstimagecheck=false;
									$(slideshowMainImage)
									.attr("src", thisimagesrc)
									.css({height: imageheight, width:imagewidth })
									.css({marginLeft: thismarginleft})
									.css({marginTop: thismargintop})
									.css({marginBottom: 0, marginRight: 0})
									.unbind("mouseover")
									.mouseover( function() {
										$(thisbackimageholder).find("img").mouseover();
										return false;	
									})
									.unbind("mousemove")
									.mousemove( function() {
										return false;	
									});
								}
								
								
								var thismainimagestatus="not loaded";
								// Create click faker  to load main slideshow image for this thumbnail image
								var loadthismainimageclicker=$('<a class="meta slideshow-load-main-image"></a>');
								$(thisthumbnailholder).append(loadthismainimageclicker);
		
								$(loadthismainimageclicker).click( function() {
									if (thismainimagestatus=="loaded" || thismainimagestatus=="loading") {
										return false;	
									}
									thismainimagestatus="loading";
									$(thisbackimageholder).append('<img src="'+thisimagesrc+'" alt="'+thisimagename+'" />');
			
									$(thisbackimageholder)
									.find("img")
									.css({height: imageheight, width:imagewidth })
									.css({marginLeft: thismarginleft})
									.css({marginTop: thismargintop})
									.css({marginBottom: 0, marginRight: 0});
									
		
									$(thisbackimageholder).find("img").mousemove( function() {
										return false;
									});
									
									$(thisbackimageholder).find("img").load( function() {
										
										$(slideshowStageHolder).find("div.image-loader-graphic").remove();
										
										// Now add main image hover function
										$(this).mouseover( function() {
											clearTimeout(slideshowTimer);
											slideshowMouseOverPause=true;
											if (!slideShowControlsVisible) {
												$(slideShowControls)
												.css({opacity: 0, display: "block"})
												.stop()
												.animate({opacity: 0.75}, 500, function() {
													slideShowControlsVisible=true;
													});
											}
											return false;
										});
										
										thismainimagestatus="loaded";
									});
									return false;
								});
								// Now add thumbnail click event using these stored values
								$(thisthumbnailholder).click( function() {
									
									// This takes place when a user clicks on a thumbnail in the slideshow
									var thisimagepos=thismainimagepos;
									
									currentSlideShowImage=thisimagepos;
									$(galleryInfoPhotoName)
									.css({display: "inline" })
									.text(trimToMaxCharWords(thismainimagename, 20));
									$(thisSlideShowHolder).find("div.slideshow-carousel-holder div.thumbnail-selected").removeClass("thumbnail-selected");
									$(this).addClass("thumbnail-selected");
									
									// Dimension the controls correctly
									// Depending on whether large slideshow is selected or not
									
									if (enlargedSlideshowOn) {
										$(slideShowControls)
										.css({width: parseInt(imagewidth*enlargedimageratio)-18})
										.css({top: parseInt(thismargintop*enlargedimageratio+imageheight*enlargedimageratio)-47})
										.css({left: parseInt(thismarginleft*enlargedimageratio)+9});
									}
									else {
										$(slideShowControls)
										.css({width: imagewidth-18})
										.css({top: thismargintop+imageheight-47})
										.css({left: thismarginleft+9});
									}
									
									// Function for fading out old image
									
									var fadeoutmainimage = function(callback) {	
										// Remove any stray loader graphics
										$(slideshowStageHolder).find("div.image-loader-graphic").remove();

										// $(slideShowStage).css({ top: -(thisimagepos*slideshowimagedimensions[1])});
										
										// The slideshow no longer works by moving a carousel in the background
										// Instead we hide all of the background images off screen with a 
										// negative top and left offset, and then set offsets to zero to reveal them
										
										$(slideShowStage).find("div.back-image-block-show").removeClass("back-image-block-show");	
										$(thisbackimageholder).addClass("back-image-block-show");

										$(slideshowMainImage)
										.unbind("mouseover")
										.mouseover( function() {
											$(thisbackimageholder).find("img").mouseover();
											return false;	
										})

										if (enlargedSlideshowOn) {
											
											$(slideshowEnlargedImageHolder)
											.find("div.slideshow-enlarged-image-front")
											.css({opacity: 1});
											
											var enlargedimagewidth = parseInt(imagewidth * enlargedimageratio);
											var enlargedimageheight = parseInt(imageheight * enlargedimageratio);
											
											var enlargedmarginleft = parseInt(thismarginleft * enlargedimageratio);
											var enlargedmargintop = parseInt(thismargintop * enlargedimageratio);
									
											var newenlargedimage = $('<img src="'+thisimagesrc+'" height="'+enlargedimageheight+'" width="'+enlargedimagewidth+'" />');
											
											$(newenlargedimage)
											.css({height: enlargedimageheight, width: enlargedimagewidth})
											.css({marginLeft: enlargedmarginleft, marginTop: enlargedmargintop});
											
											$(slideshowEnlargedImageHolder)
											.find("div.slideshow-enlarged-image-back")
											.empty()
											.append(newenlargedimage);
											$(slideshowEnlargedImageHolder)
											.find("div.slideshow-enlarged-image-front")
												.animate({opacity: 0}, 500, function() {
													var copiedimage=$(newenlargedimage).clone()
													$(this).empty().append(copiedimage);
													$(copiedimage).mouseover( function() {
														$(thisbackimageholder).find("img").mouseover();
														return false;
													})
													.mousemove( function() {
														return false;	
													});
													$(slideshowMainImage)
													.css({height: imageheight, width:imagewidth })
													.css({marginLeft: thismarginleft})
													.css({marginTop: thismargintop})
													.css({marginBottom: 0, marginRight: 0})
													.attr("src", thisimagesrc)
														callback();
													})
											.end()
											// twat13
											
										}
										else {
											$(slideshowMainImage)
											.parent()
											.stop()
											.css({display: "block", opacity: 1})
											.animate({opacity: 0}, 500, function() {
												$(slideshowMainImage)
												.css({height: imageheight, width:imagewidth })
												.css({marginLeft: thismarginleft})
												.css({marginTop: thismargintop})
												.css({marginBottom: 0, marginRight: 0})
												.attr("src", thisimagesrc)
												.parent().css({display: "none"});
				
												callback();
											});
										}
									}
		
									if (thismainimagestatus !="loaded") {
										// Main image not yet loaded 	
										if (thismainimagestatus == "not loaded") {
											var loadergraphic=$('<div class="image-loader-graphic"><h3>Loading image</h3></div>');
											$(slideshowStageHolder).append(loadergraphic);
											$(loadthismainimageclicker).click(); // Run image loader function
										}
										// Cycle loaded check until image is loaded
										setTimeout( function() {
											if (thismainimagestatus!="loaded") {
												var thisfunc=arguments.callee;
												setTimeout(function() {
													thisfunc();
												}, 300);
											}	
											else {
												// Start loading next image in cycle
												if ((currentSlideShowImage+1) < numSlideShowImages) {
													$(slideshowCarouselStage).find("div.slideshow-thumb-holder:eq("+(currentSlideShowImage+1)+") a.slideshow-load-main-image").click();
												}
		
												// And restart image cycling
												fadeoutmainimage( function() {
													slideshowTimer=setTimeout(function() {
														slideshowAnimateFunc()
													}, slideshowSpeed);
												});
											}
											
										}, 300);
										
										// We do not want to call slideShowAnimateFunc for next image
										// Until this one is fully loaded
										clearTimeout(slideshowTimer);
										return;
									}
									// Make sure that we remove any stray loader graphics
		
									clearTimeout(slideshowTimer);
									
									fadeoutmainimage( function() {
										slideshowTimer=setTimeout(function() {
											slideshowAnimateFunc()
										}, slideshowSpeed);
									});
									
								});
		
							});
						
							$(thisSlideShowHolder).find("div.slideshow-loader-block").each( function() {
								var percentcompleted = Math.ceil((endimageholder)/numSlideShowImages*100);
								$(this).find("h3 span").text(percentcompleted+"%");
								$(this).find("div span").css({width:(percentcompleted+"%")});
							});
												
							if ((endimageholder+1) < numSlideShowImages) {
								setTimeout( function() {
									initialiseSlideshow(endimageholder, 10);
								},1);
							}
							else {
								$(slideshowMainImage).parent().css({display: "block", opacity:"1"});
								
								if (isIE6 || isIE7) {
									$(slideshowCarouselStage).parent().addClass("ie-opacity-fix");
									$(thisSlideShowHolder).find("a.back-to-album").addClass("ie-opacity-fix");
								}
								
								$(thisSlideShowHolder).find("div.slideshow-loader-block").animate({opacity: 0}, 500, function() {
									$(this).css({display: "none"});
									generatingSlideshow=false;
									if (isIE6 || isIE7) {
										$(slideShowStage).addClass("ie-opacity-fix");
										$(slideshowStageHolder).addClass("ie-opacity-fix");
									}
									
									$(slideshowCarouselStage).find("div.slideshow-thumb-holder:eq(0) a.slideshow-load-main-image").click();
									$(slideshowCarouselStage).find("div.slideshow-thumb-holder:eq(1) a.slideshow-load-main-image").click();
									$(slideshowCarouselStage).find("div.slideshow-thumb-holder:eq(2) a.slideshow-load-main-image").click();
									$(slideshowCarouselStage).find("div.slideshow-thumb-holder:eq(0)").click();
	
									slideshowAnimateFunc = function() {
										if (slideshowPlaying) {
											if (!slideshowMouseOverPause) { // Pause animation when mouse is over slideshow image 
												if (++currentSlideShowImage >= numSlideShowImages) {
													currentSlideShowImage=0;
												}
												$(slideshowCarouselStage).find("div.slideshow-thumb-holder:eq("+currentSlideShowImage+")").click();
												// Start loading the image for the next two thumbs
												// So hopefully, they will already be loaded by the time
												// we cycle to display them
												if ((currentSlideShowImage+1) < numSlideShowImages) {
													$(slideshowCarouselStage).find("div.slideshow-thumb-holder:eq("+(currentSlideShowImage+1)+") a.slideshow-load-main-image").click();
												}
												if ((currentSlideShowImage+2) < numSlideShowImages) {
													$(slideshowCarouselStage).find("div.slideshow-thumb-holder:eq("+(currentSlideShowImage+2)+") a.slideshow-load-main-image").click(); 
												}
											}
										}
									}
							
									var slideshowleftarrow=$(thisSlideShowHolder).find("a.slideshow-carousel-left");
									var slideshowrightarrow=$(thisSlideShowHolder).find("a.slideshow-carousel-right");
									var slideshowcarouselscrolling=false;
				
									// Helper function for checking whether the next slideshow thumbs are loaded
									// If not, it loads those thumbs.
									var checknextthumbsloaded = function() {		
										var startcheckthumbnum=slideshowleftmostthumb+(2*slideshowvisiblethumbs);
										var endcheckthumbnum=slideshowleftmostthumb+(3*slideshowvisiblethumbs);
										endcheckthumbnum = (endcheckthumbnum > numSlideShowImages) ? numSlideShowImages-1 : endcheckthumbnum; 
										startcheckthumbnum = (startcheckthumbnum > numSlideShowImages) ? numSlideShowImages-1 : startcheckthumbnum; 
										for (var counter=startcheckthumbnum; counter <= endcheckthumbnum; counter++) {
											$(slideshowCarouselStage).find("div.slideshow-thumb-holder:eq("+counter+")").each( function() {
												if ($(this).find("img").length < 1) {
													var thisthumbinfo = $(this).find("span.thumb-info").text();
													var thumbwidth=parseInt(thisthumbinfo.split("|")[1].split(",")[0]);
													var thumbheight=parseInt(thisthumbinfo.split("|")[1].split(",")[1]);
													var thisthumbsrc=thisthumbinfo.split("|")[0];
													if (thumbwidth > thumbheight) {
														thumbheight=parseInt(thumbheight/thumbwidth*carouselthumbdimensions);
														thumbwidth=carouselthumbdimensions;
													}
													else {
														thumbwidth=parseInt(thumbwidth/thumbheight*carouselthumbdimensions);
														thumbheight=carouselthumbdimensions;
													}
													$(this)
													.prepend('<img src="'+thisthumbsrc+'" height="'+thumbheight+'" width="'+thumbwidth+'" />')
													.find("img")
													.css({height: thumbheight, width:thumbwidth })
													.css({marginLeft: parseInt((carouselthumbdimensions-thumbwidth)/2)})
													.css({marginTop: parseInt((carouselthumbdimensions-thumbheight)/2)})
													.css({marginBottom: 0, marginRight: 0});
												}									
											});
										}
									}
				
									// Function for updating display of slideshow carousel arrows
									var updateslideshowarrows = function() {
										if (numSlideShowImages <= slideshowvisiblethumbs) {
											$(slideshowleftarrow).css({display: "none"});
											$(slideshowrightarrow).css({display: "none"});
										}
										else if (slideshowleftmostthumb <= 0) {
											$(slideshowleftarrow).css({display: "none"});
											$(slideshowrightarrow).css({display: "block"});
										}
										else if (slideshowleftmostthumb >= (numSlideShowImages-1-slideshowvisiblethumbs)) {
											$(slideshowleftarrow).css({display: "block"});
											$(slideshowrightarrow).css({display: "none"});
										}
										else {
											$(slideshowleftarrow).css({display: "block"});
											$(slideshowrightarrow).css({display: "block"});
										}
									}
									updateslideshowarrows();
									$(slideshowrightarrow).unbind("click").click( function() {
										if (slideshowcarouselscrolling) {
											return false;
										}
										slideshowcarouselscrolling=false;
										var previousleftthumb=slideshowleftmostthumb;
										slideshowleftmostthumb=slideshowleftmostthumb+slideshowvisiblethumbs;
										if (slideshowleftmostthumb >= (numSlideShowImages-slideshowvisiblethumbs)) {
											slideshowleftmostthumb = numSlideShowImages-slideshowvisiblethumbs;
										}
										var animationtime=Math.abs(slideshowleftmostthumb-previousleftthumb)*120;
										updateslideshowarrows();
										$(slideshowCarouselStage).animate({ left: -(slideshowleftmostthumb * (carouselthumbdimensions+carouselthumbmarginright))}, animationtime, "linear", function() {
											checknextthumbsloaded();
											slideshowcarouselscrolling=false;
										});
										return false;
									});
									$(slideshowleftarrow).unbind("click").click( function() {
										if (slideshowcarouselscrolling) {
											return false;
										}
										slideshowcarouselscrolling=false;
										var previousleftthumb=slideshowleftmostthumb;
										slideshowleftmostthumb=slideshowleftmostthumb-slideshowvisiblethumbs;
										if (slideshowleftmostthumb < 0) {
											slideshowleftmostthumb = 0;
										}
										var animationtime=Math.abs(slideshowleftmostthumb-previousleftthumb)*120;
										updateslideshowarrows();
										$(slideshowCarouselStage).animate({ left: -(slideshowleftmostthumb * (carouselthumbdimensions+carouselthumbmarginright))}, animationtime, "linear", function() {
											slideshowcarouselscrolling=false;
										});
										return false;
											
									});
									
									
									// We reset all the slideshow HTML when the back to album button is clicked
									// So it is all ready again when we launch the sldieshow again	
									$(thisSlideShowHolder).find("a.back-to-album").unbind("click").click( function() {
										
										// Remove mosuemove event on document
										$(document).unbind("mousemove", thisMouseMoveFunction); 
										$(document).unbind("mouseover", thisMouseMoveFunction); 
										$(thisSlideShowHolder).unbind("mouseover", thisMouseMoveFunction); 

										$(thisSlideShowHolder).animate({ opacity: 0 }, 500, function() {
											clearTimeout(slideshowTimer);
											$(this).css({display: "none"});
											
											$(slideshowStageHolder).removeClass("main-stage-holder-enlarged");
											$(slideshowEnlargedImageHolder).stop().css({display: "none"});
											
											if (isIE6 || isIE7) {
												
												// Ie bug fix 
												// For some reason, display none does not work on 
												// slideshowEnlargedImageHolder in ie, so we have
												// to completely remove it, and generate its html again
												var previouselement = $(slideshowEnlargedImageHolder).prev();
												$(slideshowEnlargedImageHolder).stop().remove();
												var ieInsertHTML='<div class="slideshow-enlarged-image-holder">';
												ieInsertHTML += '<div class="slideshow-enlarged-image-back"></div>';
												ieInsertHTML += '<div class="slideshow-enlarged-image-front"></div>';
												ieInsertHTML += '</div>';
												$(previouselement).after(ieInsertHTML);
											}
											
											$(thisSlideShowHolder).find("div.slideshow-carousel-holder").stop().css({display:"block", opacity: 1})
											$(thisSlideShowHolder).find("a.slideshow-carousel-right, a.slideshow-carousel-left").stop().css({visibility:"visible"});	

											$(galleryInfoPhotoName).css({display: "none"});
											$(slideshowCarouselStage).css({left: 0}).empty();
											$(slideShowStage).empty().css({top:0});
											$(thisSlideShowHolder).find("div.slideshow-loader-block").css({display: "block", opacity: 1});
											$(thisSlideShowHolder).find("div.slideshow-loader-block div span").css({width: 0});
											$(thisSlideShowHolder).find("div.slideshow-loader-block h3 span").text("0%");
											$(slideShowControls).css({opacity: 0});
											$(slideShowControls).find("a").unbind();
											
											// Remove hidden class from the main gallery up arrow
											$(thisGallery).find("a.main-scroll-up").removeClass("hide");
											
											// Add selected class to labum name to turn it white again
											$(thisGallery).find("a.album-name").addClass("album-name-selected");
											
											// Reveal thumbnails if they have been hidden
											$(thisSlideShowHolder).find("a.slideshow-carousel-right").css({opacity: 1})
											$(thisSlideShowHolder).find("a.slideshow-carousel-left").css({opacity: 1})
											$(slideshowCarouselStage).css({opacity: 1});
											$(slideshowStageHolder).css({top: 0});
											$(slideShowControls).find("span").text("");  
											$(slideShowControls).find("a.slideshow-controls-zoom").css({display:"block"});
											$(slideShowControls).find("a.slideshow-controls-show").css({display:"none"});
											
											fadeInSortAndSearch();
											$(galleryInfoHolderTop).removeClass("album-info-panel-open");
											slideshowOpen=false;
										});
										return false;
									});
				
										
									// Slideshow controlls stuff
										
									$(slideShowControls).find("a").unbind("hover").hover( function() {
										var thistext=$(this).text();
										$(slideShowControls).find("div.controls-content span").text(thistext);
									}, function() {
										$(slideShowControls).find("div.controls-content span").text("");
									});
										
									// Now set up the timed animation
				
									/* var slideshowPlaying=true;
									var slideshowSpeed=2000;
									var currentSlideShowImage; */
														
									$(slideShowControls).find("a").unbind("click").click( function() {
										var thistext=$(this).text();
										switch (thistext) {
											case "Pause":
												slideshowPlaying=false;
												clearTimeout(slideshowTimer);
												$(this).css({ display: "none"});
												$(slideShowControls).find("a.slideshow-controls-play").css({display:"block"});
												$(slideshowthumbpausebutton).css({display: "none"});
												$(slideshowthumbplaybutton).css({display: "block"});
											break;	
											case "Slower":
												slideshowSpeed+=500;
												slideshowSpeed = (slideshowSpeed > maxSlideshowSpeed) ? maxSlideshowSpeed : slideshowSpeed;  
												if (slideshowSpeed < 5500) {
													var textspeed=parseInt((5500-slideshowSpeed)/500);
												}
												else {
													var textspeed ="1/"+(11-parseInt((10000-slideshowSpeed)/500)).toString();
												}
												$(this).parent().find("span").text("Slower x"+(textspeed));  
											break;	
											case "Faster":
												slideshowSpeed-=500;
												slideshowSpeed = (slideshowSpeed < minSlideshowSpeed) ? minSlideshowSpeed : slideshowSpeed;
												if (slideshowSpeed < 5500) {
													var textspeed=parseInt((5500-slideshowSpeed)/500);
												}
												else {
													var textspeed ="1/"+(11-parseInt((10000-slideshowSpeed)/500)).toString();
												}
												$(this).parent().find("span").text("Faster x"+(textspeed));  
											break;	
											case "Hide thumbnails":
												enlargingImageActive=true // This prevents slideshow controsl dissapearing;
												$(slideShowControls).stop().css({opacity: 0, display:"none"});

												$(thisSlideShowHolder)
												.find("a.slideshow-carousel-right, a.slideshow-carousel-left")
												.stop()
												.animate({opacity: 0}, 500, function() {
													$(this).css({visibility:"hidden"});	
												});
												
												$(thisSlideShowHolder).find("div.slideshow-carousel-holder").animate( {opacity: 0}, 500, function() {
													$(this).css({display: "none"});
													$(slideshowStageHolder).addClass("main-stage-holder-enlarged");
													$(slideshowEnlargedImageHolder).css({display: "block"});
													var standardsizeimage = $(thisGallery).find("div.gallery-album-selected div.image-holder:eq("+currentSlideShowImage+")");
													var enlargedimagesrc= $(standardsizeimage).find("span.image-src").text();
													var normalwidth = parseInt($(standardsizeimage).find("span.image-size").text().split(",")[0]);
													var normalheight = parseInt($(standardsizeimage).find("span.image-size").text().split(",")[1]);
													var newenlargedimage = $('<img src="'+enlargedimagesrc+'" height="'+normalheight+'" width="'+normalwidth+'" />');
													var normaldimensions = sizeImageToFitBox(newenlargedimage, normalwidth, normalheight, slideshowimagedimensions[0], slideshowimagedimensions[1],63,0);
													var enlargedimensions = sizeImageToFitBox("", normaldimensions[0], normaldimensions[1], enlargedHolderSize[0], enlargedHolderSize[1],0,0);
													$(slideshowEnlargedImageHolder).find("div.slideshow-enlarged-image-front").empty().append(newenlargedimage);
													$(slideshowEnlargedImageHolder).find("div.slideshow-enlarged-image-back").empty().append($(newenlargedimage).clone());
													$(newenlargedimage).unbind("mouseover").mouseover( function() {
														$(slideshowMainImage).mouseover();
														return false;
													})
													.unbind("mousemove")
													.mousemove( function() {
														return false;	
													});
													// Resize slideshow controls to fit this image
													$(slideShowControls)
													.css({width: parseInt(enlargedimensions[0])-18})
													.css({top: parseInt(enlargedimensions[3]*enlargedimageratio+enlargedimensions[1])-47})
													.css({left: parseInt(enlargedimensions[2])+9});
													enlargedSlideshowOn=true;
													$(slideshowEnlargedImageHolder).find("div.slideshow-enlarged-image-front").css({display:"block", opacity: 1});

													$(newenlargedimage).animate({ height: enlargedimensions[1], width: enlargedimensions[0], marginTop: enlargedimensions[3], marginLeft: enlargedimensions[2]}, 500, function() {
														slideShowControlsVisible=false;
														$(slideshowMainImage).mouseover();
														enlargingImageActive=false; //Reenables hiding of slideshow controls
														enlargedSlideshowOn=true;
													});
												});
												$(this).parent().find("span").text("");  
												$(this).css({display:"none"});
												$(slideShowControls).find("a.slideshow-controls-show").css({display:"block"});
											break;	
											case "Show thumbnails":
												enlargingImageActive=true // This prevents slideshow controsl dissapearing;
												$(slideShowControls).stop().css({opacity: 0, display:"none"});
												var endwidth = parseInt($(slideshowEnlargedImageHolder).find("div.slideshow-enlarged-image-back img").attr("width"));
												var endheight = parseInt($(slideshowEnlargedImageHolder).find("div.slideshow-enlarged-image-back img").attr("height"));
												var enddimensions = sizeImageToFitBox("", endwidth, endheight, slideshowimagedimensions[0], slideshowimagedimensions[1],63,0);
												$(slideshowEnlargedImageHolder).find("div.slideshow-enlarged-image-front").css({display:"block", opacity: 1});
												// Resize slideshow controls to fit this image
												$(slideShowControls)
												.css({width: parseInt(enddimensions[0])-18})
												.css({top: parseInt(enddimensions[3]+enddimensions[1])-47})
												.css({left: parseInt(enddimensions[2])+9-63});
												$(slideshowEnlargedImageHolder)
												.find("div.slideshow-enlarged-image-front img")
												.animate({ height: enddimensions[1], width: enddimensions[0], marginTop: enddimensions[3], marginLeft: enddimensions[2]}, 500, function() {
													$(slideshowStageHolder).removeClass("main-stage-holder-enlarged");
													$(slideshowEnlargedImageHolder).css({display: "none"});
													enlargedSlideshowOn=false;
													slideShowControlsVisible=true;
													enlargingImageActive=false;
													$(thisSlideShowHolder).mouseover();													
													slideShowControlsVisible=false;
													$(slideshowMainImage).parent().css({opacity: 1, display:"block"}); 
													$(thisSlideShowHolder)
													.find("a.slideshow-carousel-right, a.slideshow-carousel-left")
													.css({visibility:"visible"})
													.animate({opacity:1 }, 500) 
													$(thisSlideShowHolder)
													.find("div.slideshow-carousel-holder")
													.css({display:"block"})
													.stop()
													.animate({opacity: 1}, 500, function() {
														$(this).css({opacity: 1});
													});
												});

												$(this).parent().find("span").text("");  
												$(this).css({display:"none"});
												$(slideShowControls).find("a.slideshow-controls-zoom").css({display:"block"});
											break;	
											case "Play":
												$(this).css({ display: "none"});
												$(slideShowControls).find("a.slideshow-controls-pause").css({display:"block"});
												slideshowPlaying=true;
												slideshowAnimateFunc();
												$(slideshowthumbpausebutton).css({display: "block"});
												$(slideshowthumbplaybutton).css({display: "none"});
											break;	
											case "Back to start":
												$(slideshowCarouselStage).find("div.slideshow-thumb-holder:eq(0)").click();
											break;	
										}
										return false;
									});
	
								});
								
							}
						} 
						initialiseSlideshow(0,10);
	
						
					});
					return false;
				});
	
	
			});
			
			// Initialises the album that is selected on load
			$(this).find("div.gallery-album-selected a.display-album").click();
			
			// Slide show launcher stuff 
			
			$(this).find("a.slideshow-launcher").click( function() {
				$(thisGallery).find("div.gallery-album-selected a.launch-slideshow").click();
				return false;
			});
			
			$(this).find("div.photo-sort-menu-holder").each( function() {
				var thismenu=this;
				var thisdropdown=$(this).find("div.photo-sort-sub-options");
				
				// Cancel mouseover action on menu so that the mouseover event
				// does not reach the document, where it would close the menu
				$(this).mouseover( function() {
					return false;	
				});
				
				$(this).find("a.main-option").mouseover( function() {
					if (slideshowOpen || imageInfoBoxOpen) {
						return false;	
					}
					if (!menuSortPhotoOpen) {
	
						if (searchBoxFocused) {
							// This prevents weird effect when search box input is focused
							// while the the sort menu animates down
							$(thisGallery).find("div.search-box input").blur();
						}
	
						$(this).addClass("menu-hover");
						menuSortPhotoOpen=true;
						$(thisdropdown)
						.css({display: "block"})
						.stop()
						.animate({height: 65}, 500, function() {
							$(this).find("a").addClass("menu-hover-enabled");
						});
					}
				});
				
				$(this).find("a.main-option").click( function() {
					return false;
				});
	
				$(this).find("a.close-menu").click( function() {
					if (menuSortPhotoOpen) {
						menuSortPhotoOpen=false;
						$(thisdropdown)
						.find("a").removeClass("menu-hover-enabled")
						.end()
						.stop()
						.animate({height: 0}, 500, function() {
							$(this).css({display: "none"});	
							$(thismenu).find("a.main-option").removeClass("menu-hover");
						});
					}
					return false;
				});
				
				$(this).find("div.photo-sort-sub-options a").click( function() {
	
					if (currentlySorting || generatingSlideshow || currentlySearching) {
						return false;
					}
					
					// No point doing search if no image in this album
					var numAlbumImages=$(thisGallery).find("div.gallery-album-selected div.image-holder span.image-src").length;
					if (numAlbumImages == 0) {
						return false;	
					}

					currentlySorting=true;
					
					if (slideshowOpen) {
						$(thisSlideShowHolder).find("a.back-to-album").click();
					}
	

					if (imageInfoBoxOpen) {
						// The below click faker closes the image info panel
						$(imageInfoHolder).find("a.back-to-album").click();
					}
					
					var thissortaction=$(this).text();
					
					$(thisProgressBarBlock)
					.css({opacity: 0, display:"block"})
					.find("h3")
					.html("Sorting images: <span>0%</span>")
					.end()
					.find("div span")
					.css({width: 0});
	
					$(thisGalleryFaderBlock)
					.css({opcity: 0, display:"block"})
					.animate({opacity: 0.9}, 500, function() {
						$(thisProgressBarBlock).animate({opacity: 1}, 500, function() {
	
							switch(thissortaction) {
								case "Newest":
									var sortedimages = getDateSortedJQueryArray($(thisGallery).find("div.gallery-album-selected div.image-holder:has(span.image-src)"), "span.date");
									sortedimages = getReversedArray(sortedimages);
								break;
							
								case "Oldest":
									var sortedimages = getDateSortedJQueryArray($(thisGallery).find("div.gallery-album-selected div.image-holder:has(span.image-src)"), "span.date");
								break;
							
								case "Name A-Z":
									var sortedimages = getAlphaSortedJQueryArray($(thisGallery).find("div.gallery-album-selected div.image-holder:has(span.image-src)"), "span.image-name");
								break;
							
								case "Name Z-A":
									var sortedimages = getAlphaSortedJQueryArray($(thisGallery).find("div.gallery-album-selected div.image-holder:has(span.image-src)"), "span.image-name");
									sortedimages = getReversedArray(sortedimages);
								break;
							}
							
							
							var numofsortedimages = sortedimages.length;
							
							var sortimages = function(startimagenum, decrement) {
								if ((startimagenum-decrement)<0) {
									var endimagenum=0;	
								}
								else {
									var endimagenum=startimagenum-decrement;	
								}
								// alert(startimagenum+" "+endimagenum);
								for (var counter=startimagenum; counter>=endimagenum; counter--) {
									$(sortedimages[counter]).each( function() {
										if (counter <= 30) {
											updateemptythumbs(this);
										}
										$(thisGallery).find("div.gallery-album-selected").prepend(this);
									});
								}
								$(thisGallery).find("div.gallery-album-selected").find("a.initialise-latest-image").click();
								
								var sortpercent= Math.ceil((numofsortedimages-endimagenum)/numofsortedimages*100);
								$(thisProgressBarBlock).find("h3 span").text(sortpercent+"%");
								$(thisProgressBarBlock).find("div span").css({width: sortpercent+"%"});
	
								if (endimagenum>0) {
									var thisfunc=arguments.callee;
									setTimeout( function() {
										thisfunc(endimagenum-1, decrement)
									},1);
								}
								else {
									
									// This click faker refreshes the selectd album gallery, ensuring that there
									// are the correct number of empties, and that all images have the correct image-pos vals 
									$(thisGallery).find("div.gallery-album-selected a.refresh-album").click();
									
									// This click faker resets the selected gallery album so the first page of images
									// are displayed. 
									$(thisGallery).find("div.gallery-album-selected a.reset-album").click();
									
									$(thisProgressBarBlock).animate({opacity: 0}, 500, function() {
										$(this).css({display:"none"});
										$(thisGalleryFaderBlock).animate({opacity: 0}, 500, function() {
											$(this).css({display:"none"});
											currentlySorting=false;
										});
									});	
								}
	
							}
							sortimages(numofsortedimages-1, 10);
						});
					});
	
	
	
					return false;	
				});
	
			});
			
	
			// Search box stuff
			$(this).find("div.search-box").each( function() {
				var thissearchbox=this;
				var thissearchinput=$(this).find("input");
	
				$(thissearchinput)
				.mousedown( function() {
					if (slideshowOpen || imageInfoBoxOpen) {
						return false;	
					}
				})
				.focus( function() {
					var searchBoxFocused=true;
					$(this).addClass("search-focused");
					if ($(this).val()=="Search") {
						$(this).val("");	
					}
				})
				.blur( function() {
					var searchBoxFocused=true;
					$(this).removeClass("search-focused");
					if ($(this).val()=="") {
						$(this).val("Search");	
					}
				});
				$(this).find("a.search-submit").click( function() {
					
					if (currentlySorting || generatingSlideshow || currentlySearching) {
						return false;	
					}

					if (slideshowOpen || imageInfoBoxOpen) {
						return false;	
					}

					if (slideshowOpen) {
						// Close slideshow if it laoded using the below click faker
						$(thisSlideShowHolder).find("a.back-to-album").click();	
					}

					if (imageInfoBoxOpen) {
						// The below click faker closes the image info panel
						$(imageInfoHolder).find("a.back-to-album").click();
					}

					var searchwords = $(thissearchinput).val();

					var numGalleryImages=$(thisGallery).find("div.gallery-album-selected span.image-src").length;
					if (numGalleryImages == 0) {
						return false;	
					}

					currentlySearching=true;
					
					$(thissearchinput).blur();
															
					// Here, we need to join into a single array all the images that are currently displayed 
					// with the images that are hidden because they don't currently meet the search criteria.   
					var thesegalleryimages = $(thisGallery).find("div.gallery-album-selected div.image-holder:has(span.image-src)");
					var imagelength1 = thesegalleryimages.length;
					var thesehiddengalleryimages = $(thisGallery).find("div.gallery-album-selected div.image-holder-hidden"); 
					var imagelength2 = thesehiddengalleryimages.length;
	
					var allgalleryimages = new Array();
					
					// Recursive function for displaying only images that meet search criteria
					// Plus, generating progress meter
					var filtertheseimages = function(searchterms, startimagenum, decrement, totalnumofimages) {
						
						if ((startimagenum-decrement) < 0) {
							var endimagenum=0;	
						}
						else {
							var endimagenum=startimagenum-decrement;	
						}
						
						for (var counter=startimagenum; counter>=endimagenum; counter--) {
							$(allgalleryimages[counter]).each( function() {
								var thissearchedimage=this;
								// Firstly, find out if this image is hidden or displayed
								// and set the this displayed flag accordingly
								if (this.className.indexOf("image-holder-hidden") != -1) {
									var thisdisplayed=false;	
								}
								else {
									var thisdisplayed=true;	
								}
								
									
								var searchtermsfound = isSearchTermInImage(searchwords,this);
								
								if (searchtermsfound && !thisdisplayed) {
									// If image meets search criteria but is hidden
									// We need to move it from hidden storage to the display stage
									// updating its class along the way
									$(thissearchedimage)
									.removeClass("image-holder-hidden")
									.addClass("image-holder")
								}
								else if (!searchtermsfound && thisdisplayed) {
									// If image does not meet search criteria but is displayed
									// We need to move it from the displat stage to hidden storage
									// updating its class along the way
									$(thissearchedimage)
									.addClass("image-holder-hidden")
									.removeClass("image-holder");
								}
							});
						}	
	
						var sortpercent= Math.ceil((totalnumofimages-endimagenum)/totalnumofimages*100);
						$(thisProgressBarBlock).find("h3 span").text(sortpercent+"%");
						$(thisProgressBarBlock).find("div span").css({width: sortpercent+"%"});
	
	
						if (endimagenum != 0) {
							var thisfunc=arguments.callee;
							setTimeout( function() {
								thisfunc(searchterms, endimagenum-1, decrement, totalnumofimages);
							}, 1);
						}
						else {
							var imageposcounter = 0;
													
							$(thisGallery)
							.find("div.gallery-album-selected div.image-holder:has(span.image-src)")
							.each( function() {
								if (imageposcounter < 30) {
									updateemptythumbs(this);
								}
								imageposcounter++;
							});
	
							$(thisGallery).find("div.gallery-album-selected").find("a.initialise-latest-image").click();
	
							// This click faker refreshes the selectd album gallery, ensuring that there
							// are the correct number of empties, and that all images have the correct image-pos vals 
							$(thisGallery).find("div.gallery-album-selected a.refresh-album").click();
									
							// This resets the selected album, so the first page of images are displayed
							$(thisGallery).find("div.gallery-album-selected a.reset-album").click();
	
							$(thisProgressBarBlock).animate({opacity: 0}, 500, function() {
								$(this).css({display:"none"});
								$(thisGalleryFaderBlock).animate({opacity: 0}, 500, function() {
									$(this).css({display:"none"});
									currentlySearching=false;
								});
							});	
						}
					}
	
	
					$(thisProgressBarBlock)
					.css({opacity: 0, display:"block"})
					.find("h3")
					.html("Filtering images: <span>0%</span>")
					.end()
					.find("div span")
					.css({width: 0});
	
					$(thisGalleryFaderBlock)
					.css({opcity: 0, display:"block"})
					.animate({opacity: 0.9}, 500, function() {
						$(thisProgressBarBlock).animate({opacity: 1}, 500, function() {
					
							var testsearchtext="";
							// Join the two groups of images into a single array
							// Plus add all the searcheable text together into one string
							// We will sue this string as a quick and dirty method
							// to check whether there will be at least one image that will meet
							// the search term
							for (var counter=0; counter<imagelength1; counter++) {
								allgalleryimages[counter]=thesegalleryimages[counter];
								testsearchtext+=$(allgalleryimages[counter]).find("span.image-name").text()+" ";
								testsearchtext+=$(allgalleryimages[counter]).find("span.description").text()+" ";
								testsearchtext+=$(allgalleryimages[counter]).find("span.keyword").text()+" ";
							}
							for (var counter=imagelength1; counter<(imagelength1+imagelength2); counter++) {
								allgalleryimages[counter]=thesehiddengalleryimages[counter-imagelength1];
								testsearchtext+=$(allgalleryimages[counter]).find("span.image-name").text()+" ";
								testsearchtext+=$(allgalleryimages[counter]).find("span.description").text()+" ";
								testsearchtext+=$(allgalleryimages[counter]).find("span.keyword").text()+" ";
							}
							
							// Here we check to see if any of the search terms match all the images
							// searcheable text. Later, we check to see if each individual image matches
							// the term.
							
							var testsearcharray = searchwords.toLowerCase().split(" ");
							var testsearchfound = false;
							var testsearchtext = testsearchtext.toLowerCase();
							for (var testcounter=testsearcharray.length-1; testcounter>=0; testcounter--) { 
								if (testsearchtext.indexOf(testsearcharray[testcounter]) != -1) {
									testsearchfound=true;
								}
							}
							
							if (testsearchfound || searchwords=="Search" || searchwords=="") {
								// Store the current search term for the current gallery album
								// So we can display it whenever someone comes back to this gallery album
								if (searchwords != "") {
									$(thisGallery).find("div.gallery-album-selected span.album-search-term").text(searchwords);
								}
								else {
									$(thisGallery).find("div.gallery-album-selected span.album-search-term").text("Search");
								}
								filtertheseimages(searchwords, allgalleryimages.length-1, 10, allgalleryimages.length);
							}
							else {
								var previoussearchterm = $(thisGallery).find("div.gallery-album-selected span.album-search-term").text();
								if (previoussearchterm=="") {
									previoussearchterm="Search";	
								}
								$(thissearchinput).val(previoussearchterm);
								$(thisProgressBarBlock).animate({opacity: 0}, 500, function() {
									$(this).css({display:"none"});
									$(thisGalleryFaderBlock).animate({opacity: 0}, 500, function() {
										$(this).css({display:"none"});
										currentlySearching=false;
										displayGalleryErrorMessage("No images matched '"+trimToMaxCharWords(searchwords)+"'");
									});
								});	

							}
						});
					});
					
					return false;
				});	
			
				$(this).find("form").submit( function() {
					$(thissearchbox).find("a.search-submit").click();
					return false;
				});
			});
	
	
			/* Album block sort funcitonality here */
			$(this).find("div.album-sort-menu-holder").each( function() {
				var thismenu=this;
				var thisdropdown=$(this).find("div.album-sort-sub-options");
				currentlySortingAlbums=false;
	
				// Cancel mouseover action on menu so that the mouseover event
				// deos not reach the document, where it would close the menu
				$(this).mouseover( function() {
					return false;	
				});
				
				$(this).find("a.main-option").mouseover( function() {
					if (!menuSortAlbumOpen) {
						$(this).addClass("menu-hover");
						menuSortAlbumOpen=true;
						$(thisdropdown)
						.css({display: "block"})
						.stop()
						.animate({height: 65}, 500, function() {
							$(this).find("a").addClass("menu-hover-enabled");
						});
					}
				});
				
				$(this).find("a.main-option").click( function() {
					return false;
				});
	
				$(this).find("a.close-menu").click( function() {
					if (menuSortAlbumOpen) {
						menuSortAlbumOpen=false;
						$(thisdropdown)
						.find("a").removeClass("menu-hover-enabled")
						.end()
						.stop()
						.animate({height: 0}, 500, function() {
							$(this).css({display: "none"});	
							$(thismenu).find("a.main-option").removeClass("menu-hover");
						});
					}
					return false;
				});
				
				$(this).find("div.album-sort-sub-options a").click( function() {
	
					if (currentlySortingAlbums) {
						return false;
					}
					currentlySortingAlbums=true;
					
					if (slideshowOpen) {
						$(thisSlideShowHolder).find("a.back-to-album").click();
					}
	
					if (imageInfoBoxOpen) {
						// The below click faker closes the image info panel
						$(imageInfoHolder).find("a.back-to-album").click();
					}

					var thissortaction=$(this).text();
					
					$(thisAlbumBlockProgressBar)
					.css({opacity: 0, display:"block"})
					.find("h3")
					.html("Sorting albums: <span>0%</span>")
					.end()
					.find("div span")
					.css({width: 0});
	
					$(thisAlbumBlockFader)
					.css({opcity: 0, display:"block"})
					.animate({opacity: 0.9}, 500, function() {
						$(thisAlbumBlockProgressBar).animate({opacity: 1}, 500, function() {
	
							switch(thissortaction) {
								case "Newest":
									var sortedalbums = getDateSortedJQueryArray($(albumHolderStage).find("div.album-block").not(".album-block-new"), "span.album-block-album-date-created");
									sortedalbums = getReversedArray(sortedalbums);
								break;
							
								case "Oldest":
									var sortedalbums = getDateSortedJQueryArray($(albumHolderStage).find("div.album-block").not(".album-block-new"), "span.album-block-album-date-created");
								break;
							
								case "Name A-Z":
									var sortedalbums = getAlphaSortedJQueryArray($(albumHolderStage).find("div.album-block").not(".album-block-new"), "div.selected-content h4");
								break;
							
								case "Name Z-A":
									var sortedalbums = getAlphaSortedJQueryArray($(albumHolderStage).find("div.album-block").not(".album-block-new"), "div.selected-content h4");
									sortedalbums = getReversedArray(sortedalbums);
								break;
							}
							
							var numofsortedalbums = sortedalbums.length;
							
							var sortalbums = function(startalbumnum, decrement) {
								if ((startalbumnum-decrement)<0) {
									var endalbumnum=0;	
								}
								else {
									var endalbumnum=startalbumnum-decrement;	
								}
								// alert(startimagenum+" "+endimagenum);
								for (var counter=startalbumnum; counter>=endalbumnum; counter--) {
									$(sortedalbums[counter]).each( function() {
										$(albumHolderStage).prepend(this);
									});
								}
								
								var sortpercent= Math.ceil((numofsortedalbums-endalbumnum)/numofsortedalbums*100);
								$(thisAlbumBlockProgressBar).find("h3 span").text(sortpercent+"%");
								$(thisAlbumBlockProgressBar).find("div span").css({width: sortpercent+"%"});
	
								if (endalbumnum>0) {
									var thisfunc=arguments.callee;
									setTimeout( function() {
										thisfunc(endalbumnum-1, decrement)
									},1);
								}
								else {
									// Prepend All Photo master album at front, so that it always
									// appears as the first album in the album list
									$(albumHolderStage).prepend($(albumHolderStage).find("div.album-block-master"));
									
									// Now reset albumHolderStage positions using click faker function
	 								$(thisGallery).find("div.album-holder a.album-block-reset").click();
	 								
									$(thisAlbumBlockProgressBar).animate({opacity: 0}, 500, function() {
										$(this).css({display:"none"});
										$(thisAlbumBlockFader).animate({opacity: 0}, 500, function() {
											$(this).css({display:"none"});
											currentlySortingAlbums=false;
										});
									});	
								}
	
							}
							sortalbums(numofsortedalbums-1, 3);
						});
					});
	
					return false;	
				});
	
			});
	
	
			$(this).find("div.gallery a.gallery-colour-scheme-selector").click( function() {
				return false;
			});
			
			
			//
			
			$(albumHolder).find("a.carousel-scroll-up").click();
			
			// If there are no images in the main album, then we want the empty popup to remain visible
			if ($(thisGallery).find("div.gallery-album-master div.image-holder span.image-id").length == 0) {
				var copyofuploadinstructions = $(uploadInstructions).clone(); 
				$(copyofuploadinstructions).css({top: 9, left: 0, display:"block"});
				$(thisGallery).find("div.gallery-album-master:eq(0)").append(copyofuploadinstructions);
				
				if (isIE6) {
					// Dunno why but ie6 won't show the block if I don't do this
					$(copyofuploadinstructions).css({backgroundPosition: "0 0"});
				}
				galleryIsEmpty=true;
			}
	
		});
		
	});

})();

