if (typeof LoginGlobals === "undefined") {
	var LoginGlobals = {};
}

var ERROR_NOT_LOGGED_IN = -1;

// @todo move all functions and options into this object
var Gallery = {
	containerDivSel:     "#main_lightbox",	// The jQuery selector for the div that is displayed as a dialog (must be an id)
	collectionListDivSel:"#gallery_collection_list",	// The jQuery selector for the div containing a list of collections
	gallerifficOptions:  {},	// The options object to initialize gallerific with
	login:               {},	// login options
	lightbox:            {},	// lightbox options
	loadingMsg:          '',	// html displayed while the gallery is loading
	collectionDivSel:    "#collection",	// The div housing the image gallery
	imageDivSel:         "#collection_thumbs",	// The div housing the image gallery
	imageInfoDivSel:     "div.caption",	// The div housing the image metadata (titles, artists, ...)
	effectiveUserSel:    "#radius-widget-gallery-effective-user",	// input with the current user's id
	uniqueHashPrefixSel: '#gallery_request_time',
	slideoutMainDivSel:  '.slideout_content_main',
	vertCenteredClass:   'vertically_centered',
	logoutButtonSel:     'a.accountlogout_btn'	// The logout button
};

var LightBoxGlobals = {
	loadingMsg:               '<div class="loading_box"><img class="loading_animation" src="/_media/gallery/WaitingAnimation.gif" width="80" height="80" alt="" />&nbsp;&nbsp;Loading...</div>',
	addToLightboxBtnSel:      'a.addtolightbox_btn',
	removeFromLightboxBtnSel: 'a.removefromlightbox_btn',
	switchLightboxBtnSel:     'a.switchlightbox_btn',
	viewLightboxBtnSel:       'a.userviewlightbox_btn',
	// view lightbox button on the collection window
	colViewLightboxBtnSel:    '#collection_image_info a.userviewlightbox_btn',
	submitLightboxItemChange: '.lightbox_submitting',
	lightboxLoginContentSel:  '.lightbox_login_contents',
	switchUsersDivSel:        '#sidebar_switch_lightbox',
	accountSettingsBtnSel:    'a.accountsettings_btn',
	removeImgBtnSel:          'a.lightbox_removeimage_btn',
	viewImgBtnSel:            'a.lightbox_viewimage_smlbtn',
	reviewRequestSideBtnSel:  '#requestreviewsidebar_btn',
	reviewThankyouMsgSel:     '.lightbox_review_request_thanks',	// div containing "thank you for your review" message
	reviewSubmittingSel:      '.lightbox_review_request_submitting',	// div containing "submitting review" message
	reviewContentSel:         '.lightbox_review_request_contents',	// div containing review intro text and form
	reviewMainDivSel:         '#sidebar_review_request',			// div containing all request a review html
	quoteRequestBtnSel:       'a.requestquote_btn',
	quoteThankyouMsgSel:      '.lightbox_quote_request_thanks',
	quoteSubmittingSel:       '.lightbox_quote_request_submitting',
	quoteContentSel:          '.lightbox_quote_request_contents',
	quoteMainDivSel:          '#sidebar_quote_request',
	loginMainDivSel:          '#lightbox_login',
	closeButtonSel:           'a.close_box',
	forgotPasswordSel:        '#itr_forgot_password',
	newLightboxAccountSel:    '#lightbox_newaccount',
	viewLightboxSel:          'a.load_lightbox',
	logoutButtonSel:          'a.accountlogout_btn',	// The logout button
	quotePhotograph:          '#quote__photograph__text'	//The photograph to be reviewed
};

Gallery.loadingMsg = '<div class="loading_box"><img class="loading_animation" src="/_media/gallery/WaitingAnimation.gif" width="80" height="80" alt="" />&nbsp;&nbsp;Loading...</div>';
Gallery.noImagesMsg = '<div class="loading_box">There are no images in this collection...</div>';

Gallery.setupGallerific = function () {
	// Initially set opacity on thumbs and add
	// additional styling for hover effect on thumbs
	var onMouseOutOpacity = 0.67;

	$(Gallery.imageDivSel).find('ul.thumbs li, a.nav_link').opacityrollover({
		mouseOutOpacity:   onMouseOutOpacity,
		mouseOverOpacity:  1.0,
		fadeSpeed:         'fast',
		exemptionSelector: '.selected'
	});
	
	// Initialize Advanced Galleriffic Gallery
	var gallery = $(Gallery.imageDivSel).galleriffic({
		delay:                     2500,
		numThumbs:                 10,
		preloadAhead:              7,
		enableTopPager:            false,
		enableBottomPager:         false,
		imageContainerSel:         '#collection_image',
		enableKeyboardNavigation:  false, // Specifies whether keyboard navigation is enabled
		controlsContainerSel:      '',
		captionContainerSel:       '#collection_image_info',
		loadingContainerSel:       '',
		renderSSControls:          true,
		renderNavControls:         true,
		playLinkText:              '',
		pauseLinkText:             '',
		prevLinkText:              '',
		nextLinkText:              '',
		nextPageLinkText:          'Next',
		prevPageLinkText:          'Previous',
		enableHistory:             false,
		autoStart:                 false,
		syncTransitions:           true,
		defaultTransitionDuration: 900,
		onSlideChange:             function(prevIndex, nextIndex) {
			var img = $(Gallery.imageDivSel + ' img')[nextIndex];
			var imgSrc = img.src;
			var imgFileName = imgSrc.substr(imgSrc.lastIndexOf('/') + 1);
			var imgId = imgFileName.substr(0, imgFileName.length - 4);
			$(LightBoxGlobals.addToLightboxBtnSel).parent().find('input').val(imgId);
			
			if ($(img).hasClass('in_lightbox')) {
				$(LightBoxGlobals.addToLightboxBtnSel).hide();
				$(LightBoxGlobals.removeFromLightboxBtnSel).show();
			} else {
				$(LightBoxGlobals.addToLightboxBtnSel).show();
				$(LightBoxGlobals.removeFromLightboxBtnSel).hide();
			}
			
			// 'this' refers to the gallery, which is an extension of $(Gallery.imageDivSel)
			this.find('ul.thumbs').children()
				.eq(prevIndex).fadeTo('fast', onMouseOutOpacity).end()
				.eq(nextIndex).fadeTo('slow', 1.0);
		},
		onPageTransitionIn:        function() {
			var prevPageLink = this.find('a.prev').css('visibility', 'hidden');
			var nextPageLink = this.find('a.next').css('visibility', 'hidden');
			
			// Show appropriate next / prev page links
			if (this.displayedPage > 0) {
				prevPageLink.css('visibility', 'visible');
			}

			var lastPage = this.getNumPages() - 1;
			if (this.displayedPage < lastPage) {
				nextPageLink.css('visibility', 'visible');
			}

			this.show();
		}
	});

	gallery.find('a.prev').click(function(e) {
		gallery.previousPage();
		e.preventDefault();
	});

	gallery.find('a.next').click(function(e) {
		gallery.nextPage();
		e.preventDefault();
	});
};

/**
 * Add an item to the lightbox
 * 
 * @param object options
 *     elem An element whose parent has a single input containing the picture Id
 *     showProgress A flag
 *     progressType (optional) One of the strings "spinner", "buttonfade"
 *     adding A flag
 */
LightBoxGlobals.updateLightbox = function (options) {
	var showProgress = options.showProgress;
	var progressType = options.progressType;
	
	if (showProgress) {
		if (progressType == "spinner") {
			// Make the "Submitting..." message visible
			$(LightBoxGlobals.lightboxLoginContentSel).hide();
			$(Gallery.slideoutMainDivSel).addClass(Gallery.vertCenteredClass);
			$(LightBoxGlobals.submitLightboxItemChange).show();
			
			// Display the "Submitting..." message
			LoginGlobals.showLogin();
		} else if (progressType == "buttonfade") {
			// Dim the button
			$(options.elem).fadeTo('fast', 0.33);
		}
	}
	
	var id = $(options.elem).parent().find('input').val();
	var uid = $(Gallery.effectiveUserSel).val();
	
	// add the image to the lightbox
	$.ajax({
		type:	"POST",
		url:	"/_modules/gallery.php?ajax=1&action=" + (options.adding ? "addtolightbox" : "removefromlightbox"),
		data:	"pic=" + id + (uid ? "&uid=" + uid : ''),
		dataType:	"json",
		success:	function (data, textStatus) {
			if (showProgress) {
				if (progressType == "spinner") {
					// Hide the "loading..." message
					$(LightBoxGlobals.submitLightboxItemChange).hide();
					$(Gallery.slideoutMainDivSel).removeClass(Gallery.vertCenteredClass);
				} else if (progressType == "buttonfade") {
					// Un-dim the button
					$(options.elem).fadeTo('fast', 1);
				}
			}
			
			LightBoxGlobals.onAddToLightbox(data, options.adding, options);
		},
		error:	function (XMLHttpRequest, textStatus, errorThrown) {
			if (showProgress) {
				if (progressType == "spinner") {
					// Hide the "loading..." message
					$(LightBoxGlobals.submitLightboxItemChange).hide();
					$(Gallery.slideoutMainDivSel).removeClass(Gallery.vertCenteredClass);
				} else if (progressType == "buttonfade") {
					// Un-dim the button
					$(options.elem).fadeTo('fast', 1);
				}
			}
			
			alert('An error occurred while updating your lightbox.');
		}
	});
	
	return false;
};

Gallery.processResponse = function () {
	// Add event handlers for the "View My Lightbox" button
	// in the collection window
	$(LightBoxGlobals.colViewLightboxBtnSel).click(function () {
		fnLoadLightbox({ overlapContent: true });
	});
	
	// Add event handlers for the "Add to Lightbox" button
	$(LightBoxGlobals.addToLightboxBtnSel).click(function () {
		LightBoxGlobals.updateLightbox({
			elem: this,
			showProgress: true,
			progressType: "buttonfade",
			adding: true
		});
		
		return false;
	});

	// Add event handlers for the "Remove from Lightbox" button
	$(LightBoxGlobals.removeFromLightboxBtnSel).click(function () {
		LightBoxGlobals.updateLightbox({
			elem: this,
			showProgress: true,
			progressType: "buttonfade",
			adding: false
		});
		
		return false;
	});

	// Add event handlers for the "Request a Quote" button
	$(LightBoxGlobals.quoteRequestBtnSel).click(function () {
		// The "Request a Quote" form should not be vertically centered
		$(Gallery.slideoutMainDivSel).removeClass(Gallery.vertCenteredClass);
		
		$(LightBoxGlobals.quoteThankyouMsgSel).hide();
		$(LightBoxGlobals.quoteContentSel).show();
		$(LightBoxGlobals.quoteMainDivSel).show('slide', { direction: "right" });
		$(LightBoxGlobals.quotePhotograph).val($('#collection li.selected a.thumb').attr('title'));
		
		LightBoxGlobals.setupQuoteButtons();
		
		return false;
	});

	// Add event handlers for the "Logout" button
	$(Gallery.logoutButtonSel).click(function () {
		// load the image in the gallery
		$.ajax({
			type:	"POST",
			url:	"/modules/cms/logout.php",
			data:	"",
			success: function () {
				$(Gallery.containerDivSel).dialog('close');
			},
			error: function (XMLHttpRequest, textStatus, errorThrown) {
				$(Gallery.containerDivSel).dialog('close');
			}
		});
		
		return false;
	});

	// Disable context menus on images
	$('img').live('contextmenu', function () { return false; });
	
	// Unhide all image info (only the first is shown by default for SEO)
	$(Gallery.imageInfoDivSel).show();
	
	var imageCount = $(Gallery.imageDivSel).find('ul.thumbs li').length;
	
	if (imageCount === 0) {
		$(Gallery.containerDivSel).html(Gallery.noImagesMsg);
	} else {
		Gallery.setupGallerific();
	}
	
	LightBoxGlobals.setupQuoteForm();
};

Gallery.onLoadGallery = function (data, textStatus) {
	var response;
	try {
		response = JSON.parse(data);

		// ensure all required fields have been returned
		if (!response || !response.html) {
			throw "InvalidServerResponse";
		}
	} catch (e) {
		alert('An error occurred while loading the collection. Please contact your website administrator if you experience further errors.');
		$(Gallery.containerDivSel).dialog('close');
		return;
	}

	// Display any custom error messages and close the dialog box
	if (response.errormsg !== '') {
		alert(response.errormsg);
		$(Gallery.containerDivSel).dialog('close');
	}

	$(Gallery.containerDivSel).html(response.html);
	Gallery.processResponse();
};

/**
 * Go to the image specified by hash.
 * 
 * @param string hash A string of the form #gallery-image-XXX-YYY
 */
Gallery.onHashChange = function (hash) {
	hash = '#gallery-image-' + $(Gallery.uniqueHashPrefixSel).val() +
			'-' + hash.substr(hash.lastIndexOf('-') + 1);
	
	// @todo history appears broken when visiting a page with a
	//       #gallery-image-XXX-YYY hash without the if
	if (typeof $.galleriffic !== "undefined") {
		$.galleriffic.gotoImage(hash);
	}
};

// @todo The code that processes the JSON response from the server should be in just one function
LoginGlobals.showLogin = function () {
	$('#lightbox_login').show('slide', { direction: "right" });
	
	LoginGlobals.setupCloseButton();
	
	return false;
};

var jqDialog;

/**
 * Process the lightbox data from the server
 * 
 * @author Saint Wesonga
 * @param options An object with lighbox options
 *           overlapContent: Set to true to load any screen on the current
 *                           dialog window content
 */
LightBoxGlobals.onLoadLightbox = function (response, options) {
	// Display any custom error messages
	if (response.errormsg !== '') {
		alert(response.errormsg);
		return;
	}

	if (response.errorcode == ERROR_NOT_LOGGED_IN) {
		// Clear the effective user
		$(Gallery.effectiveUserSel).val('');
		
		// $('#lightbox').hide('slide', { direction: "left" });
		
		var overlapContent = options && options.overlapContent;
		
		if (!overlapContent) {
			$(Gallery.containerDivSel).html(response.html);
		} else {
			// Save the current login callback function
			// and switch the onlogin handler to load the lightbox
			var oldCallback = LoginGlobals.onLoginCallback;
			
			// Add/remove the item to/from the lightbox if the login is successful
			LoginGlobals.onLoginCallback = function () {
				$(LightBoxGlobals.colViewLightboxBtnSel).click();
				
				// Restore the old callback
				LoginGlobals.onLoginCallback = oldCallback;
			};
		}
		
		LoginGlobals.showLogin();
		return;
	}
	
	$(Gallery.containerDivSel).html(response.html);
	
	// Display the lightbox content
	$('#lightbox').show();
	
	// Add event handlers for the "Request a Review" button
	$(LightBoxGlobals.reviewRequestSideBtnSel).click(function () {
		$(LightBoxGlobals.reviewThankyouMsgSel).hide();
		$(LightBoxGlobals.reviewContentSel).show();
		$(LightBoxGlobals.reviewMainDivSel).show('slide', { direction: "right" });
		
		// LightBoxGlobals.setupCloseButton();
		
		return false;
	});

	// Add event handlers for the "View" button
	$(LightBoxGlobals.viewImgBtnSel).click(function () {
		var id = $(this).parent().find('input').val();

		// load the image in the gallery
		$.ajax({
			type:	"POST",
			url:	"/_modules/gallery.php?action=displaycollection&ajax=1&pic=" + id,
			data:	 "",
			success: Gallery.onLoadGallery,
			error:		function (XMLHttpRequest, textStatus, errorThrown) {
							alert('An error occurred while loading the gallery. Please try again and contact your website administrator if the problem persists.');
						}
		});

		// pop up the dialog box
		$(Gallery.containerDivSel).html(Gallery.loadingMsg)
						   .dialog('open');
	});

	// Add event handlers for the "Remove" button
	$(LightBoxGlobals.removeImgBtnSel).click(function () {
		var objThis = this;
		var id = $(this).parent().find('input').val();
		var uid = $('#lightbox_effective_user').val();

		// Apply transparency to the item being deleted
		$(objThis).closest('tr').fadeTo('fast', 0.33);
		
		// remove the image from the lightbox
		$.ajax({
			type:	"POST",
			url:	"/_modules/gallery.php?action=removefromlightbox&ajax=1",
			data:	"pic=" + id + "&uid=" + uid,
			dataType:	"json",
			success:	function onRemoveFromLightbox(response) {
							// Display any custom error messages
							if (response.errormsg !== '') {
								alert(response.errormsg);
								return;
							}
			
							$(objThis).closest('tr').fadeSlideOut({speed:1000});
						},
			error:		function (XMLHttpRequest, textStatus, errorThrown) {
							alert('An error occurred while removing the image from your lightbox.');
						}
		});
	});

	// Gets the UID of the user whose lightbox is currently displayed
	LightBoxGlobals.getCurrentUser = function () {
		return $('input[name="target_user"]').val();
	};
	
	// Set up the "My Account Settings" button
	$(LightBoxGlobals.accountSettingsBtnSel).unbind('click').one('click', function() {
		try {
			var options = {
				dataProvider : function () {
									return "target_user=" + LightBoxGlobals.getCurrentUser();
								}
			};
			
			if (jqDialog) {
				jqDialog.remove();
			}
			
			jqDialog = setupUserProfileWindow(this, options);
			jqDialog.dialog('open');
		} catch(e) {
			// Inform the user that something went wrong.
			alert('An error occurred while loading your account settings');
		}
		
		return false;
	});
	
	// Add event handlers for the "Logout" button
	$(LightBoxGlobals.logoutButtonSel).click(function () {
		// load the image in the gallery
		$.ajax({
			type:	"GET",
			url:	"/modules/cms/logout.php",
			data:	"",
			success: function () {
				$(Gallery.containerDivSel).dialog('close');
			},
			error: function (XMLHttpRequest, textStatus, errorThrown) {
				$(Gallery.containerDivSel).dialog('close');
			}
		});
		
		return false;
	});

	// Add the "Switch Lightbox" onclick handler
	$(LightBoxGlobals.switchLightboxBtnSel).click(function() {
		$(LightBoxGlobals.switchUsersDivSel).show('slide', { direction: "right" });
		
		LightBoxGlobals.setupUsers();
		
		return false;
	});
	
	LightBoxGlobals.setupReview();
	
	$('.lightbox_slideout a.close_box').unbind('click').click(function() {
		$(this).closest('.lightbox_slideout').hide('slide', { direction: "right" });
		return false;
	});

	// Disable context menus on images
	$('img').live('contextmenu', function () { return false; });
	
	// Set the current effective user (since this may have changed on this load)
	$(Gallery.effectiveUserSel).val(response.uid);
};

LightBoxGlobals.onAddToLightbox = function (response, adding, options) {
	var usedSpinner = (options && options.showProgress && options.progressType == "spinner");
	
	if (response.errorcode !== undefined && response.errorcode == ERROR_NOT_LOGGED_IN) {
		// User is not logged in
		// Clear the effective user
		$(Gallery.effectiveUserSel).val('');
		
		// Save the current login callback function
		var oldCallback = LoginGlobals.onLoginCallback;
		
		// Add/remove the item to/from the lightbox if the login is successful
		LoginGlobals.onLoginCallback = function () {
			LightBoxGlobals.updateLightbox({
				elem: (adding ? LightBoxGlobals.addToLightboxBtnSel : LightBoxGlobals.removeFromLightboxBtnSel),
				showProgress: false,
				progressType: "buttonfade",
				adding: adding
			});
			
			// Restore the old callback
			LoginGlobals.onLoginCallback = oldCallback;
		};
		
		// Display the login inputs
		// If we used the "loading" spinner, show the login slideout is
		// visible. Show the lightbox login content (inputs)
		if (usedSpinner) {
			$('p.error_message').hide();
			$(LightBoxGlobals.lightboxLoginContentSel).show();
		} else {
			// Since we did not use the "loading" spinner (displayed in the
			// slideout), show the slideout itself
			LoginGlobals.showLogin();
		}
		
		return;
	}
	
	// Display any custom error messages
	if (response.errormsg !== '') {
		alert(response.errormsg);
		return;
	}
	
	if (response.picture === undefined || (response.added === undefined && response.removed === undefined)) {
		alert('An error occurred while updating your lightbox.');
		return;
	}

	if (usedSpinner) {
		// Close the progress slideout
		$(LightBoxGlobals.loginMainDivSel).find(LightBoxGlobals.closeButtonSel).click();
	}
	
	// The image hash is of the form #gallery-image-XXX-YYY where XXX is the
	// time(stamp) of the gallery load and YYY is the picture id. The
	// request time is stored in a hidden input
	var imgHash = '#gallery-image-' + $(Gallery.uniqueHashPrefixSel).val() + "-" + response.picture;
	var img = $('a[href="' + imgHash + '"]').find('img');
	
	if (response.added) {
		img.addClass('in_lightbox');
	} else {
		img.removeClass('in_lightbox');
	}
	
	$(LightBoxGlobals.addToLightboxBtnSel).toggle();
	$(LightBoxGlobals.removeFromLightboxBtnSel).toggle();
};

/**
 * Set up event handlers used by the "Request a Quote" form
 */
LightBoxGlobals.setupQuoteForm = function () {
	$('form.lightbox_quote').validate({
		errorPlacement:	function(error, element) {
							error.appendTo( element.parent().find("label span") );
						}
	});
	
	$('form.lightbox_quote').submit(function() {
		if ($(this).valid()) {
			// The "Request a Quote" form submitting and thank you messages
			// should be vertically centered
			$(Gallery.slideoutMainDivSel).addClass(Gallery.vertCenteredClass);
			
			$(LightBoxGlobals.quoteThankyouMsgSel).hide();
			$(LightBoxGlobals.quoteContentSel).hide();
			$(LightBoxGlobals.quoteSubmittingSel).show();

		    $(this).ajaxSubmit({
				type: "POST",
				resetForm: true,
				success: function (data, text) {
							$(LightBoxGlobals.quoteContentSel).hide();
							$(LightBoxGlobals.quoteSubmittingSel).hide();
							$(LightBoxGlobals.quoteThankyouMsgSel).show();
						}
			});
		}
		
	    // return false to prevent normal browser submit and page navigation 
	    return false; 
	});
};

/**
 * Used by "Request a Quote"
 */
LightBoxGlobals.setupQuoteButtons = function () {
	$('#sidebar_quote_request .close_box').unbind('click').click(function() {
		// $('#sidebar_quote_request').fadeSlideOut({speed:1000});
		$('#sidebar_quote_request').hide('slide', { direction: "right" });
		return false;
	});

	$('#sidebar_quote_request .submitquote_btn').unbind('click').click(function() {
		$('form.lightbox_quote').submit();
		return false;
	});
};

/**
 * Load the lightbox
 * @param options An object with lightbox loading options
 *           overlapContent: Set to true to load any screen on the current
 *                           dialog window content
 *           initDialog:     Set to true to initialize the jQuery dialog that
 *                           will hold the lightbox
 * @return
 */
var fnLoadLightbox = function (options) {
	var overlapContent = options && options.overlapContent;
	
	if (!overlapContent) {
		if (options && options.initDialog) {
			Gallery.init();
		}
		
		// pop up the dialog box
		$(Gallery.containerDivSel).html(LightBoxGlobals.loadingMsg)
						   .dialog('open');
	}
	
	// add the image to the lightbox
	$.ajax({
		type:	"GET",
		url:	"/_modules/gallery.php?action=loadlightbox",
		data:	"ajax=1&uid=" + $(Gallery.effectiveUserSel).val(),
		dataType:	"json",
		success:	function (data, textStatus) {
						LightBoxGlobals.onLoadLightbox(data, options);
					},
		error:		function (XMLHttpRequest, textStatus, errorThrown) {
						alert('An error occurred while loading your lightbox.');
					}
	});
	
	return false;
};

/**
 * Initialize the gallery - create the container div if necessary and create
 * the jQuery UI dialog for gallery and lightbox content
 */
Gallery.init = function () {
	// Create the container div if it does not exist
	// Assumes the selector is an id
	if ($(Gallery.containerDivSel).length == 0) {
		$('body').append('<div id="' + Gallery.containerDivSel.substr(1) + '" class="loadedFromGalleryPage"></div>');
	}
	
	$(Gallery.containerDivSel).dialog({
		title: '',
		modal: true,
		autoOpen: false,
		width: 960,
		height: 700,
		dialogClass: 'itr_cms image_gallery',
		resizable: false,
		draggable: false
	}).draggable( 'disable' );
};

Gallery.load = function (collection, picture) {
	$.historyInit(Gallery.onHashChange);
	
	Gallery.init();
	
	// pop up the dialog box
	$(Gallery.containerDivSel).html(Gallery.loadingMsg).dialog('open');

	// Ensure we do not assign a picture if we have been loaded from a gallery
	// page since that implies that the correct image is already being loaded
	// This is set in the widget template file or if the container is
	// dynamically created above. In this case, the #collection div has not
	// been loaded!
	if ($(Gallery.containerDivSel).hasClass('loadedFromGalleryPage') &&
		$(Gallery.collectionDivSel).length > 0) {
		picture = null;
	}
	
	if (!collection && !picture) {
		$(Gallery.containerDivSel).html('')
			.append($(Gallery.collectionDivSel))
			.append($(LightBoxGlobals.quoteMainDivSel))
			.append($(LightBoxGlobals.loginMainDivSel))
			.append($(LightBoxGlobals.newLightboxAccountSel))
			.append($(LightBoxGlobals.forgotPasswordSel));
		Gallery.processResponse();
	} else  {
		var url = '/_modules/gallery.php?action=displaycollection';
		if (collection) {
			url += '&collection=' + collection;
		}
		if (picture) {
			url += '&pic=' + picture;
		}
		
		// fetch the template content
		$.ajax({
			type:	"GET",
			url:	url,
			data:	"ajax=1" + (($(Gallery.effectiveUserSel).val() === undefined) ? '' : "&uid=" + $(Gallery.effectiveUserSel).val()),
			success: Gallery.onLoadGallery,
			error:		function (XMLHttpRequest, textStatus, errorThrown) {
							alert('An error occurred while loading the gallery. Please try again and contact your website administrator if the problem persists.');
							$(Gallery.containerDivSel).dialog('close');
						}
		});
	}
};

Gallery.loadCollectionList = function () {
	$(Gallery.collectionListDivSel).dialog({
		title: 'Choose a Collection',
		modal: true,
		autoOpen: false,
		width: 560,
		height: 400,
		dialogClass: '',
		resizable: false,
		draggable: false
	})
	.show()
	.dialog('open');
};

$(document).ready(function () {
	$('a.load_gallery').click(function () {
		Gallery.load();

		return false;
	});

	// Add the "View My Lightbox" onclick handler
	$('a.collection_load_lightbox').click(fnLoadLightbox);
});

