jQuery.fn.gallery = function(customSettings) {
	var settings = jQuery.extend({}, jQuery.fn.gallery.defaults, customSettings);
	var numLoadedImages = 0;
	var galleryElement = this;
	var bookmarkLinkElement = null;
	var metadataElement = null;
	var photoElement = null;
	var photoLinkElement = null;
	var metadataLinkElement = null;
	var metadataTitleElement = null;
	var metadataDescriptionElement = null;
	var thumbnailsElement = null;
	var thumbnailsOverlayElement = null;
	var thumbnailsLoadingElement = null;
	var thumbnailButtons = null
	var previousButton = null;
	var previousButtonTop = null;
	var nextButton = null;
	var nextButtonTop = null;
	var sponsorLogoElement = null;
	var photoTextLinkElement = null;
	var photoSurroundElement = null;
	var photoSurroundElementLeft = null;
	var photoSurroundElementTop = null;
	var photoSurroundElementRight = null;
	var photoSurroundElementBottom = null;
	var overlayNavigationButtons = null;
	var thumbnailNavigationButtons = null;
	var thumbnailsPrevButton = null;
	var thumbnailsNextButton = null;
	var thumbnailsPrevButtonInner = null;
	var thumbnailsNextButtonInner = null;
	var loadingImages = false;
	var thumbnailIndentWidth = 0;
	var imageNumElement = null;
	var galleryImagesNumElement = null;
	var galleryNavElement = null;
	var thumbnailsWidth = 0;
	var tweetButton = null;
	var galleryData = {
		currentPos: 0
	};
	var metadataVisible = true;
	var currentMousePos = null;
	var numThumbnailsPerPage = 0;
	var facebookPhotoButton = null;
	var twitterPhotoButton = null;

	var titleHeight = 0;
	var footerHeight = 0;
	var headerHeight = 0;
	var metadataHeight = 0;
	if (settings.showTitle) {
		titleHeight = settings.titleHeight;
	}
	if (settings.showFooter) {
		footerHeight = settings.footerHeight;
	}
	if (settings.showHeader) {
		headerHeight = settings.footerHeight;
	}
	galleryElement.width(settings.width);
	galleryElement.css('min-height', settings.height + 'px');

	galleryElement.addClass('gallery-loading');
	if (!settings.targetUrl) {
		galleryElement.removeClass('gallery-loading');
		galleryElement.addClass('gallery-error');
		debug('targetUrl is null; you must supply a targetUrl for gallery AJAX requests.');
		return;
	}

	jQuery.ajax({
		dataType: 'json',
		data: jQuery.extend({}, settings, {
			pageUrl: window.location.href
		}),
		error: function(request, error, e) {
			galleryElement.addClass('gallery-error');
			galleryElement.removeClass('gallery-loading');
			if (settings.debug) {
				debug(request);
				debug(error, true);
			}
		},
		success: function(response) {
			if (response.error || !response.data) {
				galleryElement.addClass('gallery-error');
				galleryElement.removeClass('gallery-loading');
				if (settings.debug) {
					debug(response.error);
					debug(response.data, true);
				}
			} else {
				galleryData = jQuery.extend(galleryData, response.data);
				if (settings.debug) {
					debug(response);
					debug(galleryData);
				}
				try {
					numLoadedImages = response.data.photos.length;
					initialiseGallery(response);
				} catch (e) {
					debug(e, true);
					galleryElement.html('&#xa0;');
					galleryElement.addClass('gallery-error');
				}
				galleryElement.removeClass('gallery-loading');
			}
		},
		type: 'post',
		url: settings.targetUrl
	});

	function debug(obj, stack) {
		try {
			if (window.console && window.console.debug) {
				window.console.debug(obj);
				if (stack) {
					window.console.debug('Stack:\n\t' + printStackTrace().join('\n\t'));
				}
			} else if (window.console && window.console.log) {
				window.console.log(obj);
				if (stack) {
					window.console.log('Stack:\n\t' + printStackTrace().join('\n\t'));
				}
			}
		} catch (e) {
		}
	}

	
	
	function print_r(theObj){
		  if(theObj.constructor == Array ||
		     theObj.constructor == Object){
		    document.write("<ul>")
		    for(var p in theObj){
		      if(theObj[p].constructor == Array||
		         theObj[p].constructor == Object){
		document.write("<li>["+p+"] => "+typeof(theObj)+"</li>");
		        document.write("<ul>")
		        print_r(theObj[p]);
		        document.write("</ul>")
		      } else {
		document.write("<li>["+p+"] => "+theObj[p]+"</li>");
		      }
		    }
		    document.write("</ul>")
		  }
		}
	
	
	function showPhoto(elementNum, overlayNavClicked) {

		try {
			galleryData.currentPos = elementNum;
			//metadataElement.fadeOut(250);
			if (settings.showThumbnails) {
				thumbnailButtons.switchClass('selected', 'unselected', 250);
				jQuery(galleryElement.selector + ' .photo-thumbnail-' + elementNum).switchClass('unselected', 'selected', 250);
			}
			photoElement.fadeOut(250, function() {
				if (window.location && window.location.hash != undefined) {
					window.location.hash = '#' + galleryData.photos[elementNum].seoAddress + '-' + elementNum;
				}
				if (settings.countDown) {
					imageNumElement.text(galleryData.gallery.numPhotos - elementNum);
				} else {
					imageNumElement.text(elementNum + 1);
				}
				if (galleryData.photos[elementNum].width >= galleryData.photos[elementNum].height && galleryData.photos[elementNum].height <= settings.height) {
					photoElement.width(settings.width);
					var h = settings.width * (galleryData.photos[elementNum].height / galleryData.photos[elementNum].width); 
					photoElement.css("height",h+"px");
					//photoElement.Height(settings.width * (galleryData.photos[elementNum].height / galleryData.photos[elementNum].width));
				} else {
					//photoElement.innerHeight(settings.height);
					photoElement.css("height",settings.height+"px");
					photoElement.width(settings.height * (galleryData.photos[elementNum].width / galleryData.photos[elementNum].height));
				}

				
				
				if (parseInt((settings.height - photoElement.height()) / 2) > 0) {
					photoElement.css('padding-top', parseInt((settings.height - photoElement.height()) / 2) + 'px');
				} else {
					photoElement.css('padding-top', '0px');
				}
				if (!settings.overlayNavigation || overlayNavClicked) {
					if (galleryData.currentPos < galleryData.photos.length - 1) {
						nextButton.fadeIn(250);
						nextButtonTop.fadeIn(250);
					} else if (galleryData.currentPos == numLoadedImages - 1) {
						nextButton.fadeOut(250);
						nextButtonTop.fadeOut(250);
					}
					if (galleryData.currentPos > 0) {
						previousButton.fadeIn(250);
						previousButtonTop.fadeIn(250);
					} else {
						previousButton.fadeOut(250);
						previousButtonTop.fadeOut(250);
					}
				}
				if (galleryData.photos[elementNum].linkUrl) {
					if (settings.useFoodNetworkRecipeBoxBookmarking) {
						bookmarkLinkElement
								.attr('href', '/recipe-box/select-folder/' + galleryData.photos[elementNum].recipeId)
								.attr('title', galleryData.photos[elementNum].name + settings.bookmarkSuffix);
					} else {
						bookmarkLinkElement
								.attr('href', galleryData.photos[elementNum].linkUrl)
								.attr('title', galleryData.photos[elementNum].name + settings.bookmarkSuffix);
					}
					if (galleryData.photos[elementNum].linkText.length > 0) {
						photoTextLinkSpanElement.text(galleryData.photos[elementNum].linkText)
					} else {
						photoTextLinkSpanElement.text(settings.photoLinkText);
					}
					photoTextLinkElement
							.attr('href', galleryData.photos[elementNum].linkUrl)
							.attr('title', 'Go to ' + galleryData.photos[elementNum].name)
							.show();
					photoLinkElement
							.attr('href', galleryData.photos[elementNum].linkUrl)
							.attr('title', galleryData.photos[elementNum].name + settings.bookmarkSuffix)
							.show();
					metadataLinkElement
							.attr('href', galleryData.photos[elementNum].linkUrl)
							.attr('title', galleryData.photos[elementNum].name + settings.bookmarkSuffix)
							.show();
					if (galleryData.photos[elementNum].linkUrl.match(/^(ht|f)tp:\/\//)) {
						photoTextLinkElement.attr('target', '_blank');
						photoLinkElement.attr('target', '_blank');
						metadataLinkElement.attr('target', '_blank');
					} else {
						photoTextLinkElement.attr('target', '');
						photoLinkElement.attr('target', '');
						metadataLinkElement.attr('target', '');
					}
				} else {
					photoLinkElement.hide();
					photoTextLinkElement.hide();
					metadataLinkElement.hide();
				}
				photoElement.attr('src', galleryData.photos[elementNum].photoUrl);
				metadataTitleElement.text(galleryData.photos[elementNum].name);
				metadataDescriptionElement.text(galleryData.photos[elementNum].description);
				if (settings.overlayMetadata) {
					metadataElement.css('top', (settings.height - metadataElement.innerHeight()) + 'px');
				}
				//metadataElement.fadeIn(250);
				photoElement.fadeIn(250);

				if (settings.showTwitterPhotoButton) {
					insertTwitterPhotoButton(window.location.href);
				}
				if (settings.showFacebookPhotoButton) {
					insertFacebookPhotoButton(window.location.href);
				}

				if (galleryData.photos[elementNum].sponsorLogo) {
					sponsorLogoElement.attr('src', galleryData.photos[elementNum].sponsorLogo);
					sponsorLogoElement.show();
				} else if (galleryData.gallery.sponsorLogo) {
					sponsorLogoElement.attr('src', galleryData.gallery.sponsorLogo);
					sponsorLogoElement.show();
				} else {
					sponsorLogoElement.attr('src', '/assets/shared/gallery/images/generic/blank.gif');
					sponsorLogoElement.hide();
				}

				centreSelectedThumbnail();
				if (settings.trackClicks && typeof(pageTracker) != 'undefined') {
					pageTracker._trackPageview(window.location.pathname + window.location.hash);
				}
			});
		} catch (e) {
			
			debug(e, true);
		}
		
		return false;
	}

	function initialiseGallery(response) {
		
		try {
			if (settings.debug) {
				debug(response);
			}
			galleryElement.html(response.data.wireframe);
			photoSurroundElement = jQuery(galleryElement.selector + ' .photo-surround');
			sponsorLogoElement = jQuery(galleryElement.selector + ' .sponsor-logo');
			metadataElement = jQuery(galleryElement.selector + ' .gallery-metadata');
			photoElement = jQuery(galleryElement.selector + ' .gallery-content .gallery-photo');
			photoLinkElement = jQuery(galleryElement.selector + ' .gallery-content .gallery-photo-url');
			photoTextLinkElement = jQuery(galleryElement.selector + ' .gallery-content a.photo-link');
			photoTextLinkSpanElement = jQuery(galleryElement.selector + ' .gallery-content a.photo-link span');
			metadataLinkElement = jQuery(galleryElement.selector + ' .gallery-content .gallery-metadata-url');
			metadataTitleElement = jQuery(galleryElement.selector + ' .gallery-content .gallery-metadata .photo-title');
			metadataDescriptionElement = jQuery(galleryElement.selector + ' .gallery-content .gallery-metadata .photo-description');
			previousButton = jQuery(galleryElement.selector + ' .gallery-nav a.previousButton');
			nextButton = jQuery(galleryElement.selector + ' .gallery-nav a.nextButton');
			previousButtonTop = jQuery(galleryElement.selector + ' .gallery-nav-top a.previousButtonTop');
			nextButtonTop = jQuery(galleryElement.selector + ' .gallery-nav-top a.nextButtonTop');
			overlayNavigationButtons = jQuery(galleryElement.selector + ' .gallery-nav a.previousButton, ' + galleryElement.selector + ' .gallery-nav a.nextButton');
			topNavigationButtons = jQuery(galleryElement.selector + ' .gallery-nav a.previousButtonTop, ' + galleryElement.selector + ' .gallery-nav a.nextButtonTop');
			imageNumElement = jQuery(galleryElement.selector + ' .image-num');
			galleryImagesNumElement = jQuery(galleryElement.selector + ' .gallery-images-num');
			bookmarkLinkElement = jQuery(galleryElement.selector + ' .gallery-nav .gallery-bookmark-link');

			var elementNum = 0;
			if (window.location.hash && window.location.hash.match(/^#?[a-z0-9\-]+-\d+$/)) {
				elementNum = parseInt(window.location.hash.replace(/^#?[a-z0-9\-]+-([0-9]+)$/, '$1'));
			}

			photoSurroundElement.height(settings.height);
			photoSurroundElement.width(settings.width);
			if (settings.countDown) {
				imageNumElement.text(galleryData.gallery.numPhotos);
			}
			galleryElement.addClass(settings.theme);
			if (jQuery.browser.msie && jQuery.browser.version >= 7 && jQuery.browser.version < 8) {
				galleryElement.addClass('ie7');
			}
			if (settings.showThumbnails) {
				var thumbnails = '';
				var positioning = 0;
				for (var i = 0; i < galleryData.photos.length; i++) {
					if (settings.squareThumbnails) {
						if (galleryData.photos[i].width > galleryData.photos[i].height) {
							positioning = parseInt((settings.thumbnailHeight - (settings.thumbnailHeight * (galleryData.photos[i].width / galleryData.photos[i].height))) / 2);
							thumbnails += '<a style="height: ' + settings.thumbnailHeight + 'px; width: ' + settings.thumbnailHeight + 'px;" href="#' + galleryData.photos[i].seoAddress + '-' + i + '" class="photo-thumbnail-' + i + ' photo-thumbnail"><img src="' + galleryData.photos[i].photoUrl + '" alt="' + galleryData.photos[i].name + '" title="' + galleryData.photos[i].name + '" style="height: ' + settings.thumbnailHeight + 'px; left: ' + positioning + 'px;" /></a>';
						} else {
							positioning = parseInt((settings.thumbnailHeight - (settings.thumbnailHeight * (galleryData.photos[i].height / galleryData.photos[i].width))) / 2);
							thumbnails += '<a style="height: ' + settings.thumbnailHeight + 'px; width: ' + settings.thumbnailHeight + 'px;" href="#' + galleryData.photos[i].seoAddress + '-' + i + '" class="photo-thumbnail-' + i + ' photo-thumbnail"><img src="' + galleryData.photos[i].photoUrl + '" alt="' + galleryData.photos[i].name + '" title="' + galleryData.photos[i].name + '" style="width: ' + settings.thumbnailHeight + 'px; top: ' + positioning + 'px;" /></a>';
						}
					} else {
						thumbnails += '<a href="#' + galleryData.photos[i].seoAddress + '-' + i + '" class="photo-thumbnail-' + i + ' photo-thumbnail"><img src="' + galleryData.photos[i].photoUrl + '" alt="' + galleryData.photos[i].name + '" title="' + galleryData.photos[i].name + '" style="height: ' + settings.thumbnailHeight + 'px;" /></a>';
					}
				}

				thumbnailsElement = jQuery(galleryElement.selector + ' .gallery-content .gallery-thumbnails');
				thumbnailsOverlayElement = jQuery(galleryElement.selector + ' .gallery-content .gallery-thumbnails-overlay');
				thumbnailsLoadingElement = jQuery(galleryElement.selector + ' .gallery-content .gallery-thumbnails-loading');
				thumbnailsElement.html(thumbnails);

				thumbnailButtons = jQuery(galleryElement.selector + ' .gallery-content .gallery-thumbnails a');
				/*if (jQuery.browser.msie && jQuery.browser.version >= 7 && jQuery.browser.version < 8) {
					thumbnailsElement.height(settings.thumbnailHeight + 10);
				} else {*/
					thumbnailsElement.height(jQuery(thumbnailButtons[0]).outerHeight());
					var offset = thumbnailsElement.offsetParent().offset();
					thumbnailsOverlayElement.height(jQuery(thumbnailsElement).outerHeight());
					thumbnailsOverlayElement.width(settings.width);
					thumbnailsOverlayElement.css('top', offset.top + 'px');
					thumbnailsOverlayElement.css('left', offset.left + 'px');
					thumbnailsLoadingElement.height(jQuery(thumbnailsElement).outerHeight());
				//}
				thumbnailsElement.width(((((settings.width
						- parseInt(thumbnailsElement.css('margin-left').replace(/[^0-9]+/, '')))
						- parseInt(thumbnailsElement.css('margin-right').replace(/[^0-9]+/, '')))
						- parseInt(thumbnailsElement.css('padding-left').replace(/[^0-9]+/, '')))
						- parseInt(thumbnailsElement.css('padding-right').replace(/[^0-9]+/, ''))));

				thumbnailButtons = jQuery(galleryElement.selector + ' .gallery-content .gallery-thumbnails a');
				thumbnailButtons.click(thumbnailClick);

				for (numThumbnailsPerPage = 0; thumbnailsElement.width() > numThumbnailsPerPage * (jQuery(thumbnailButtons[0]).outerWidth() + settings.thumbnailExtraWidth); numThumbnailsPerPage++){}

				jQuery(galleryElement.selector + ' .photo-thumbnail-0').addClass('selected');

				setThumbnailsWidth();
			}
			if (settings.showTitle) {
				jQuery(galleryElement.selector + ' h2').text(galleryData.gallery.name);
				jQuery(galleryElement.selector + ' h2').css('display', 'block');
			}
			if (galleryData.photos[elementNum].linkUrl) {
				if (settings.useFoodNetworkRecipeBoxBookmarking) {
					bookmarkLinkElement
							.attr('href', '/recipe-box/select-folder/' + galleryData.photos[elementNum].recipeId)
							.attr('title', galleryData.photos[elementNum].name + settings.bookmarkSuffix);
				} else {
					bookmarkLinkElement
							.attr('href', galleryData.photos[elementNum].linkUrl)
							.attr('title', galleryData.photos[elementNum].name + settings.bookmarkSuffix);
				}
				photoTextLinkElement
						.attr('href', galleryData.photos[elementNum].linkUrl)
						.attr('title', 'Go to ' + galleryData.photos[elementNum].name)
						.show();
				photoLinkElement
						.attr('href', galleryData.photos[elementNum].linkUrl)
						.attr('title', galleryData.photos[elementNum].name + settings.bookmarkSuffix)
						.show();
				metadataLinkElement
						.attr('href', galleryData.photos[elementNum].linkUrl)
						.attr('title', galleryData.photos[elementNum].name + settings.bookmarkSuffix)
						.show();
				if (galleryData.photos[elementNum].linkUrl.match(/^(ht|f)tp:\/\//)) {
					photoTextLinkElement.attr('target', '_blank');
					photoLinkElement.attr('target', '_blank');
					metadataLinkElement.attr('target', '_blank');
				} else {
					photoTextLinkElement.attr('target', '');
					photoLinkElement.attr('target', '');
					metadataLinkElement.attr('target', '');
				}
			} else {
				photoLinkElement.hide();
				photoTextLinkElement.hide();
				metadataLinkElement.hide();
			}

			if (galleryData.photos[elementNum].width >= galleryData.photos[elementNum].height && galleryData.photos[elementNum].height <= settings.height) {
				photoElement.width(settings.width);
				var h = settings.width * (galleryData.photos[elementNum].height / galleryData.photos[elementNum].width); 
				//photoElement.height(settings.width * (galleryData.photos[elementNum].height / galleryData.photos[elementNum].width));
				photoElement.css("height", h+"px");
			} else {
				//photoElement.height(settings.height);
				photoElement.css("height", settings.height+"px");
				photoElement.width(settings.height * (galleryData.photos[elementNum].width / galleryData.photos[elementNum].height));
			}

			bookmarkLinkElement.text(settings.bookmarkLinkText);
			if (!settings.showBookmarkLink) {
				bookmarkLinkElement.hide();
			}
			if(galleryData.photos[elementNum].linkText.length > 0)
			{
				photoTextLinkSpanElement.text(galleryData.photos[elementNum].linkText);
			}
			else photoTextLinkSpanElement.text(settings.photoLinkText);
			if (!settings.showPhotoLink) {
				photoLinkElement.hide();
			}
			photoElement.attr('src', galleryData.photos[elementNum].photoUrl);
			metadataTitleElement.text(galleryData.photos[elementNum].name);
			metadataDescriptionElement.text(galleryData.photos[elementNum].description);
			previousButton.click(prevButtonClick);
			previousButtonTop.click(prevButtonClick);
			nextButton.click(nextButtonClick);
			nextButtonTop.click(nextButtonClick);

			photoSurroundElementLeft = photoSurroundElement.offset().left;
			photoSurroundElementTop = photoSurroundElement.offset().top;
			photoSurroundElementRight = photoSurroundElementLeft + photoSurroundElement.width();
			photoSurroundElementBottom = photoSurroundElementTop + photoSurroundElement.height();

			var photoElementPaddingTop = parseInt((settings.height - photoElement.height()) / 2);
			if (photoElementPaddingTop > 0) {
				photoElement.css('padding-top', photoElementPaddingTop + 'px');
			} else {
				photoElement.css('padding-top', '0px');
			}

			if (settings.showThumbnails) {
				thumbnailsPrevButton = jQuery(galleryElement.selector + ' .thumbnails-prev-button');
				thumbnailsPrevButton.height(jQuery(thumbnailButtons[0]).innerHeight());
				thumbnailsPrevButton.addClass('disabled');

				thumbnailsNextButton = jQuery(galleryElement.selector + ' .thumbnails-next-button');
				thumbnailsNextButton.height(jQuery(thumbnailButtons[0]).innerHeight());

				var page = Math.floor(elementNum / numThumbnailsPerPage); // Page is 0-based, as are elementNum and currentPos.
				var indent = page * (thumbnailsElement.outerWidth() - 5);
				if (galleryData.gallery.numPhotos == numLoadedImages && page == Math.floor((numLoadedImages - 1) / numThumbnailsPerPage)) {
					thumbnailsNextButton.addClass('disabled');
				}

				thumbnailsPrevButtonInner = jQuery(galleryElement.selector + ' .thumbnails-prev-button span');
				thumbnailsPrevButtonInner.height(thumbnailsPrevButton.innerHeight());

				thumbnailsNextButtonInner = jQuery(galleryElement.selector + ' .thumbnails-next-button span');
				thumbnailsNextButtonInner.height(thumbnailsNextButton.innerHeight());

				thumbnailsPrevButton.click(thumbnailsPrevButtonClick);
				thumbnailsNextButton.click(thumbnailsNextButtonClick);
			}

			galleryNavElement = jQuery(galleryElement.selector + ' .gallery-nav');
			galleryNavElement.height(footerHeight)
			previousButton.hide();
			previousButtonTop.hide();
			if (((footerHeight - parseInt(jQuery(galleryElement.selector + ' .gallery-nav p').height())) / 2) > 0) {
				jQuery(galleryElement.selector + ' .gallery-nav p')
						.css('padding-top', ((footerHeight - parseInt(jQuery(galleryElement.selector + ' .gallery-nav p').height())) / 2) + 'px');
			} else {
				jQuery(galleryElement.selector + ' .gallery-nav p')
						.css('padding-top', '0px');
			}
			galleryImagesNumElement.text(galleryData.gallery.numPhotos);
			if (settings.overlayNavigation) {
				jQuery(document).bind('mousemove', trackMouse);
				galleryNavElement.addClass('overlay');

				overlayNavigationButtons.height(settings.height);
				jQuery(galleryElement.selector + ' .gallery-nav a span').height(settings.height);
				overlayNavigationButtons.css('display', 'none');
				//overlayNavigationButtons.width(settings.width / 2);
			} else {
				galleryNavElement.addClass('inline');
				jQuery(galleryElement.selector + ' .gallery-nav a')
						.css('top', photoSurroundElement.height() + 'px')
						.height(footerHeight);
				jQuery(galleryElement.selector + ' .gallery-nav a span')
						.height(footerHeight);
			}
			if (settings.showHeader) {
				jQuery(galleryElement.selector + ' .gallery-nav-top')
						.show()
						.height(headerHeight);
				jQuery(galleryElement.selector + ' .gallery-nav-top a')
						.height(headerHeight);
				jQuery(galleryElement.selector + ' .gallery-nav-top a span')
						.height(headerHeight);
			} else {
				jQuery(galleryElement.selector + ' .gallery-nav-top')
						.hide();
			}
			if (settings.overlayMetadata) {
				metadataElement.addClass('overlay');
			} else {
				metadataElement.addClass('inline');
			}
			metadataElement.width(settings.width);
			if (settings.overlayMetadata) {
				metadataElement.css('top', (settings.height - metadataElement.innerHeight()) + 'px');
			} else {
				metadataHeight = metadataElement.height();
			}
			photoLinkElement.width(settings.width);
			photoLinkElement.height(settings.height - metadataElement.height());
			metadataLinkElement.width(settings.width);
			metadataLinkElement.height(metadataElement.height());
			metadataLinkElement.css('top', photoLinkElement.height() + 'px');

			facebookPhotoButton = jQuery(galleryElement.selector + ' .facebook-photo-button');
			twitterPhotoButton = jQuery(galleryElement.selector + ' .twitter-photo-button');

			if (settings.showTwitterButton) {
				insertTwitterButton(window.location.href);
			}

			if (settings.showFacebookButton) {
				insertFacebookButton(window.location.href);
			}

			if (settings.showTwitterPhotoButton) {
				insertTwitterPhotoButton(window.location.href);
			}

			if (settings.showFacebookPhotoButton) {
				insertFacebookPhotoButton(window.location.href);
			}


			if (galleryData.photos[elementNum].sponsorLogo) {
				sponsorLogoElement.attr('src', galleryData.photos[elementNum].sponsorLogo);
				sponsorLogoElement.show();
			} else if (galleryData.gallery.sponsorLogo) {
				sponsorLogoElement.attr('src', galleryData.gallery.sponsorLogo);
				sponsorLogoElement.show();
			} else {
				sponsorLogoElement.attr('src', '/assets/shared/gallery/images/generic/blank.gif');
				sponsorLogoElement.hide();
			}
			if (galleryData.currentPos != elementNum) {
				showPhoto(elementNum);
				setThumbnailsWidth();
			}
		} catch (e) {
			
			debug(e, true);
		}
		
	}

	function insertTwitterButton(url) {
		try {
			if (!url) {
				url = window.location.href;
			}
			url = url.replace(/#.*$/, '');
			jQuery(galleryElement.selector + ' .twitter-button').html('<iframe src="http://api.tweetmeme.com/button.js?url=' + escape(url) + '&#x26;style=' + settings.twitterButtonLayout + '" style="height:15px;width:60px;border:0px;overflow:hidden;" border="0" marginheight="0" marginwidth="0" frameborder="0" scrolling="no"></iframe>');
		} catch (e) {
			debug(e, true);
		}
	}

	function insertFacebookButton(url) {
		try {
			if (!url) {
				url = window.location.href;
			}
			url = url.replace(/#.*$/, '');
			jQuery(galleryElement.selector + ' .facebook-button').html('<iframe id="gallery-facebook-button-' + settings.galleryId + '" src="http://www.facebook.com/plugins/like.php?href=' + escape(url) + '&amp;layout=' + settings.facebookButtonLayout + '&amp;show_faces=false&amp;width=450&amp;action=like&amp;colorscheme=light&amp;height=35" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:50px; height:35px;" allowTransparency="true"></iframe>');
		} catch (e) {
			debug(e, true);
		}
	}

	function insertTwitterPhotoButton(url) {
		try {
			if (!url) {
				url = window.location.href;
			}
			url = url.replace(/#.*$/, '');
			twitterPhotoButton.html('<iframe src="http://api.tweetmeme.com/button.js?url=' + escape(url) + '&#x26;style=' + settings.twitterButtonLayout + '" style="height:15px;width:60px;border:0px;overflow:hidden;" border="0" marginheight="0" marginwidth="0" frameborder="0" scrolling="no"></iframe>');
		} catch (e) {
			debug(e, true);
		}
	}

	function insertFacebookPhotoButton(url) {
		try {
			if (!url) {
				url = window.location.href;
			}
			url = url.replace(/#.*$/, '');
			facebookPhotoButton.html('<iframe id="gallery-facebook-photo-button-' + settings.galleryId + '" src="http://www.facebook.com/plugins/like.php?href=' + escape(url) + '&amp;layout=' + settings.facebookButtonLayout + '&amp;show_faces=false&amp;width=450&amp;action=like&amp;colorscheme=light&amp;height=35" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:275px; height:35px;" allowTransparency="true"></iframe>');
		} catch (e) {
			debug(e, true);
		}
	}

	function setThumbnailsWidth() {
		try {
			thumbnailButtons.each(function() {
				var img = new Image();
				img.src = jQuery(this).attr('src');

				/*if (img.complete) {
					thumbnailsWidth += jQuery(this).outerWidth();
					centreSelectedThumbnail();
				} else {
					img.onload = function() {
						thumbnailsWidth += jQuery(this).outerWidth();
						centreSelectedThumbnail();
					}
				}*/
			});
			thumbnailsWidth = ((numLoadedImages * (jQuery(thumbnailButtons[0]).width() + settings.thumbnailExtraWidth)) - parseInt(jQuery(thumbnailButtons[0]).css('border-right-width').replace(/[^0-9]+/, '')));

			thumbnailIndentWidth = numThumbnailsPerPage * (jQuery(thumbnailButtons[0]).width() + settings.thumbnailExtraWidth);
			if (settings.debug) {
				debug('thumbnailsWidth: ' + thumbnailsWidth);
			}
		} catch (e) {
			debug(e, true);
		}
	}

	function trackMouse(e) {
		try {
			if (e.pageX > photoSurroundElementLeft && e.pageX < photoSurroundElementRight && e.pageY > photoSurroundElementTop && e.pageY < photoSurroundElementBottom && metadataVisible) {
				//metadataElement.fadeOut(250);
				if (galleryData.currentPos < galleryData.photos.length - 1) {
					nextButton.fadeIn(250);
				}
				if (galleryData.currentPos > 0) {
					previousButton.fadeIn(250);
				}
				metadataVisible = false;
				currentMousePos = e;
			} else if ((e.pageX < photoSurroundElementLeft || e.pageX > photoSurroundElementRight || e.pageY < photoSurroundElementTop || e.pageY > photoSurroundElementBottom) && !metadataVisible) {
				//metadataElement.fadeIn(250);
				overlayNavigationButtons.fadeOut(250);
				metadataVisible = true;
				currentMousePos = e;
			}
		} catch (e) {
			debug(e, true);
		}
	}

	function thumbnailClick() {
		try {
			return showPhoto(parseInt(jQuery(this).attr('class').replace(/^.*photo-thumbnail-([0-9]+) ?.*$/g, '$1')));
		} catch (e) {
			debug(e, true);
		}
	}

	function prevButtonClick() {
		try {
			return showPhoto(--galleryData.currentPos, true);
		} catch (e) {
			debug(e, true);
		}
	}

	function nextButtonClick() {
		try {
			return showPhoto(++galleryData.currentPos, true);
		} catch (e) {
			debug(e, true);
		}
	}

	function thumbnailsPrevButtonClick() {
		try {
			if (jQuery(this).hasClass('disabled')) return false;

			return scrollThumbnailsLeft();
		} catch (e) {
			debug(e, true);
		}
	}

	function thumbnailsNextButtonClick() {
		try {
			if (jQuery(this).hasClass('disabled')) return false;

			return scrollThumbnailsRight();
		} catch (e) {
			debug(e, true);
		}
	}

	function scrollThumbnailsLeft() {
		try {
			var indent = parseInt(thumbnailsElement.css('text-indent').replace(/[^0-9]+/g, ''));
			if (indent - thumbnailIndentWidth > 0) {
				thumbnailsElement.animate({
					textIndent: '-' + (indent - thumbnailIndentWidth) + 'px'
				});
			} else {
				thumbnailsElement.animate({
					textIndent: '0px'
				});
				thumbnailsPrevButton.addClass('disabled');
			}
			thumbnailsNextButton.removeClass('disabled');
		} catch (e) {
			debug(e, true);
		}
	}

	function scrollThumbnailsRight() {
		var loadImages = false;
		var showThumbnailButton = false;

		try {
			var indent = parseInt(thumbnailsElement.css('text-indent').replace(/[^0-9]+/g, ''));
			if (indent + thumbnailIndentWidth < thumbnailsWidth - thumbnailsElement.width()) {
				showThumbnailButton = true;
				thumbnailsElement.animate({
					textIndent: '-' + (indent + thumbnailIndentWidth) + 'px'
				});
			} else {
				thumbnailsElement.animate({
					textIndent: '-' + (thumbnailsWidth - thumbnailsElement.width()) + 'px'
				});

				if (thumbnailsWidth > thumbnailsElement.width()) {
					showThumbnailButton = true;
				}
				if (galleryData.gallery.numPhotos > numLoadedImages) {
					showThumbnailButton = true;
					loadImages = true;
				} else {
					thumbnailsNextButton.addClass('disabled');
				}
			}
			if (showThumbnailButton) {
				thumbnailsPrevButton.removeClass('disabled');
			}

			if (loadImages && !loadingImages) {
				loadingImages = true;
				thumbnailsOverlayElement.fadeIn(250);
				jQuery.ajax({
					dataType: 'json',
					data: jQuery.extend({}, settings, {
						offset: numLoadedImages
					}),
					error: function(request, error, e) {
						galleryElement.addClass('gallery-error');
						galleryElement.removeClass('gallery-loading');
						if (settings.debug) {
							debug(request);
							debug(error, true);
						}
						loadingImages = false;
					},
					success: function(response) {
						if (response.error || !response.data) {
							galleryElement.addClass('gallery-error');
							galleryElement.removeClass('gallery-loading');
							if (settings.debug) {
								debug(response.error);
								debug(response.data, true);
							}
							thumbnailsOverlayElement.fadeOut(250);
						} else {
							try {
								appendPhotos(response.data.photos, function() {
									thumbnailsElement.animate({
										textIndent: '-' + (indent + thumbnailIndentWidth) + 'px'
									});
								});
								if (galleryData.gallery.numPhotos == numLoadedImages) {
									thumbnailsNextButton.addClass('disabled');
								}
							} catch (e) {
								if (settings.debug) {
									debug(e, true);
								}
								galleryElement.addClass('gallery-error');
							}
							galleryElement.removeClass('gallery-loading');
						}
						loadingImages = false;
						thumbnailsOverlayElement.fadeOut(250);
					},
					type: 'post',
					url: settings.targetUrl
				});
			}
		} catch (e) {
			
			debug(e, true);
		}
	}

	function centreSelectedThumbnail() {
		try {
			var loadImages = false;
			if (settings.centreThumbnails && settings.showThumbnails) {
				var selectedThumbnail = jQuery(galleryElement.selector  + ' .gallery-thumbnails a.selected');

				var leftPoint = (thumbnailsElement.width() - selectedThumbnail.width()) / 2;
				var indent = 0;
				for (var i = 0; i < parseInt(selectedThumbnail.attr('class').replace(/^.*photo-thumbnail-([0-9]+) ?.*$/g, '$1')); i++) {
					indent += jQuery(thumbnailButtons[i]).width() + settings.thumbnailExtraWidth;
				}
				indent -= leftPoint;
				if (indent < 0) {
					indent = 0;
					thumbnailsPrevButton.addClass('disabled');
				} else {
					thumbnailsPrevButton.removeClass('disabled');
				}

				if (indent > thumbnailsWidth - thumbnailsElement.width()) {
					indent = (thumbnailsWidth - thumbnailsElement.width());
					thumbnailsNextButton.addClass('disabled');
					if (numLoadedImages < galleryData.gallery.numPhotos) {
						loadImages = true;
					}
				} else {
					thumbnailsNextButton.removeClass('disabled');
				}
				thumbnailsElement.animate({
					textIndent: '-' + indent + 'px'
				});
			} else if (settings.showThumbnails) {
				var selectedThumbnail = jQuery(galleryElement.selector  + ' .gallery-thumbnails a.selected');

				var page = Math.floor(galleryData.currentPos / numThumbnailsPerPage);
				var indent = page * (thumbnailsElement.outerWidth() - 5);
				if (page == 0) {
					thumbnailsPrevButton.addClass('disabled');
				} else {
					thumbnailsPrevButton.removeClass('disabled');
				}

				if (page == Math.floor((numLoadedImages - 1) / numThumbnailsPerPage)) {
					if (page > 0) {
						indent = (thumbnailsWidth - thumbnailsElement.width());
					} else {
						indent = 0;
					}
					if (page == Math.floor((galleryData.gallery.numPhotos - 1) / numThumbnailsPerPage)) {
						thumbnailsNextButton.addClass('disabled');
					}
					if (numLoadedImages < galleryData.gallery.numPhotos) {
						loadImages = true;
					}
				} else {
					thumbnailsNextButton.removeClass('disabled');
				}
				thumbnailsElement.animate({
					textIndent: '-' + indent + 'px'
				});
			} else if (galleryElement.currentPos == numLoadedImages - 1 && numLoadedImages < galleryData.gallery.numPhotos) {
				loadImages = true;
			}

			if (loadImages && !loadingImages) {
				loadingImages = true;
				thumbnailsOverlayElement.fadeIn(250);
				jQuery.ajax({
					dataType: 'json',
					data: jQuery.extend({}, settings, {
						offset: numLoadedImages
					}),
					error: function(request, error, e) {
						galleryElement.addClass('gallery-error');
						galleryElement.removeClass('gallery-loading');
						if (settings.debug) {
							debug(request);
							debug(error, true);
						}
						loadingImages = false;
						thumbnailsOverlayElement.fadeOut(250);
					},
					success: function(response) {
						if (response.error || !response.data) {
							galleryElement.addClass('gallery-error');
							galleryElement.removeClass('gallery-loading');
							if (settings.debug) {
								debug(response.error);
								debug(response.data, true);
							}
						} else {
							try {
								appendPhotos(response.data.photos, centreSelectedThumbnail);
							} catch (e) {
								if (settings.debug) {
									debug(e, true);
								}
								galleryElement.addClass('gallery-error');
							}
							galleryElement.removeClass('gallery-loading');
						}
						loadingImages = false;
						thumbnailsOverlayElement.fadeOut(250);
					},
					type: 'post',
					url: settings.targetUrl
				});
			}
		} catch (e) {
			
			debug(e, true);
		}
	}

	function appendPhotos(photos, callback) {
		try {
			var start = numLoadedImages; 
			for (var i = 0; i < photos.length; i++) {
				galleryData.photos.push(photos[i]);
				numLoadedImages++;
			}
			if (settings.showThumbnails) {
				var thumbnails = '';
				for (var i = 0; i < photos.length; i++) {
					var positioning = 0;
					if (photos[i].width > photos[i].height) {
						positioning = parseInt((settings.thumbnailHeight - (settings.thumbnailHeight * (photos[i].width / photos[i].height))) / 2);
						thumbnails += '<a style="height: ' + settings.thumbnailHeight + 'px; width: ' + settings.thumbnailHeight + 'px;" href="#' + photos[i].seoAddress + '-' + (i + start) + '" class="photo-thumbnail-' + (i + start) + ' photo-thumbnail"><img src="' + photos[i].photoUrl + '" alt="' + photos[i].name + '" title="' + photos[i].name + '" style="height: ' + settings.thumbnailHeight + 'px; left: ' + positioning + 'px;" /></a>';
					} else {
						positioning = parseInt((settings.thumbnailHeight - (settings.thumbnailHeight * (photos[i].height / photos[i].width))) / 2);
						thumbnails += '<a style="height: ' + settings.thumbnailHeight + 'px; width: ' + settings.thumbnailHeight + 'px;" href="#' + photos[i].seoAddress + '-' + (i + start) + '" class="photo-thumbnail-' + (i + start) + ' photo-thumbnail"><img src="' + photos[i].photoUrl + '" alt="' + photos[i].name + '" title="' + photos[i].name + '" style="width: ' + settings.thumbnailHeight + 'px; top: ' + positioning + 'px;" /></a>';
					}
				}
				thumbnailsElement.append(thumbnails);

				thumbnailButtons = jQuery(galleryElement.selector + ' .gallery-content .gallery-thumbnails a');
				thumbnailButtons.click(thumbnailClick);

				setThumbnailsWidth();
				if (callback) {
					callback();
				}
			}
		} catch (e) {
			
			debug(e, true);
		}
	}

	return galleryElement;
};

jQuery.fn.gallery.defaults = {
	autoScroll: false,
	bookmarkLinkText: 'Save recipe',
	bookmarkSuffix: ' - FoodNetwork',
	centreThumbnails: false,
	countDown: false,
	debug: false,
	facebookButtonLayout: 'standard',
	footerHeight: 50,
	galleryId: null,
	headerHeight: 50,
	height: 315,
	overlayMetadata: true,
	overlayNavigation: false,
	photoLinkText: 'Go to recipe',
	showBookmarkLink: false,
	showFacebookButton: true,
	showFacebookPhotoButton: false,
	showFooter: true,
	showHeader: true,
	showPhotoLink: true,
	showThumbnails: true,
	showTitle: true,
	showTwitterButton: true,
	showTwitterPhotoButton: false,
	squareThumbnails: true,
	targetUrl: '/gallery/load',
	theme: 'generic',
	thumbnailHeight: 60,
	thumbnailExtraWidth: 15,
	titleHeight: 37,
	title: '',
	trackClicks: true,
	twitterButtonLayout: 'compact',
	useFoodNetworkRecipeBoxBookmarking: true,
	width: 420
};

if (tweetmeme_url == undefined) {
	var tweetmeme_url = window.location.href;
}

if (tweetmeme_style == undefined) {
	var tweetmeme_style = 'compact';
}

