$(document).ready(function(){

	var galleryDisclaimer = 'The gallery area of this website contains nudity. You must be aged 18 years or over to view this section of the CosmeticCulture website. By clicking the OK button below you are confirming that you are old enough to view the content within.'; 

	var preOpenGalleryContainer = function(galleryWidth) {
		var currentWidth = $('#divNavAndGallery').width();
		var newWidth = $('#divNav').width() + galleryWidth;
		if (currentWidth != newWidth) {
			$('#divNavAndGallery').width(newWidth);
		}
	};
	
	var preChangePictureCallback = function(galleryWidth) {
		var currentWidth = $('#divNavAndGallery').width();
		var newWidth = $('#divNav').width() + galleryWidth;
		if (currentWidth < newWidth) {
			$('#divNavAndGallery').width(newWidth);
		}
	};
	
	var postChangePictureCallback = function(galleryWidth) {
		// $('#divNavAndGallery').width($('#divNav').width() + $('#divGallery').find(':nth-child(1)').width());
		var currentWidth = $('#divNavAndGallery').width();
		var newWidth = $('#divNav').width() + galleryWidth;
		if (currentWidth > newWidth) {
			$('#divNavAndGallery').width(newWidth);
		}
	};
	
	var buildAndLaunchGallery = function(data) {
		$('#currentgallery').empty();
		$.each(data.api_images, function(i,api_image){
			$("<a>")
				.attr("href", api_image)
				.attr("rel", "prettyPhoto[" + data.gallery_name + "]")
				.attr("title", data.api_descriptions[i])
				.text(data.gallery_name)
				.appendTo("#currentgallery");
		});
		$("a[rel^='prettyPhoto']").prettyPhoto({
			animationSpeed:'slow',
			theme:'light_rounded',
			slideshow:3000, 
			autoplay_slideshow: false,
			preopencallback: preOpenGalleryContainer,
			prechangepicturecallback: preChangePictureCallback,
			changepicturecallback: postChangePictureCallback 
		});
		$('#currentgallery a:eq(0)').click();
	};
			
	var bindNavigationGalleryLinks = function() {
		$('a[id^="navigationgallerylink_"]').click(function(e){
			e.preventDefault();
			e.stopPropagation();

			// // If the gallery is already cached, use that instead.
			var linkId = $(this).attr('id');
			var cacheId = 'cache' + linkId;
			if ($('#' + cacheId).length > 0) {
			
				var data = JSON.parse($('#' + cacheId).text());

				// // Works, but no thumbnail appears
				// $.prettyPhoto.open(data.api_images, data.api_titles, data.api_descriptions);
				
				// // Set up HTML so that prettyPhoto displays thumbnails as well.
				buildAndLaunchGallery(data);

			} else {
			
				var jqxhr = $.getJSON($(this).attr('href'), function(data, textStatus, jqXHR) {
					// // Works, but no thumbnail appears
					// $.prettyPhoto.open(data.api_images, data.api_titles, data.api_descriptions);
					
					// // Set up HTML so that prettyPhoto displays thumbnails as well.
					buildAndLaunchGallery(data);
					
					// // Cache the output
					$('<div/>')
						.attr('id', cacheId)
						.text(JSON.stringify(data))
						.appendTo('#cache');
				})
				// .beforeSend(function(jqXHR, settings) { alert("before send, close existing galleries"); })
				// .success(function(data, textStatus, jqXHR) { alert("second success"); })
				.error(function(jqXHR, textStatus, errorThrown) { alert('error : [' + errorThrown + ']'); });
				// .complete(function(jqXHR, textStatus) { alert("complete"); });

			}
		});
	};

	var buildAndLaunchGalleries = function(data) {
		$('#main_wrapper').remove();
		
		var textToInsert = [];
		var k = 0;
		
		textToInsert[k++] = "<div id='main_wrapper'>";
		textToInsert[k++] = "<div id='wrapper'>";

		// // START : more than 1 =======================================
		
		textToInsert[k++] = "<div id='gall_nav'>";
		textToInsert[k++] = "<div id='gall_nav_top'></div>";
		textToInsert[k++] = "<div id='gall_nav_container'>";
		textToInsert[k++] = "<p>select gallery:</p>";
		textToInsert[k++] = "<ul>";

		// // =======================================
		
		$.each(data.gallery_names, function(i,gallery_name){

			textToInsert[k++] = "<li>";
			textToInsert[k++] = "<div class='linkstyle'>";
			textToInsert[k++] = "<div id='helptool_" + i + "'>";
			textToInsert[k++] = "<a id='navigationgallerylink_" + i + "' href='gallery/gallery_control.php?gallery_name=" + data.url_encoded_gallery_names[i] + "' >" + gallery_name + "</a>";
			textToInsert[k++] = "</div>";
			textToInsert[k++] = "</div>";
			textToInsert[k++] = "</li>";

		});

		// // =======================================

		textToInsert[k++] = "</ul>";
		textToInsert[k++] = "</div>";
		textToInsert[k++] = "<div id='gall_nav_bottom'></div>";
		textToInsert[k++] = "</div>";

		// // END : more than 1 =======================================
		
		textToInsert[k++] = "</div>";
		textToInsert[k++] = "</div>";
		
		$('#divNav').append(textToInsert.join(''));
		bindNavigationGalleryLinks();
		$('#divGalleries').show();
	};
	
	var launchGallery = function(galleryName) {
		// // Get the link whose text is the same as the gallery name & click it
		$('a[id^="navigationgallerylink_"]:contains("' + galleryName + '")').click();
	};
		
	var bindStandaloneGalleryLinks = function() {
		$('a[id^="standalonegallerylink_"]').click(function(e){
			e.preventDefault();
			e.stopPropagation();

			alert(galleryDisclaimer);

			// // If the gallery is already cached, use that instead.
			var linkId = $(this).attr('id');
			var cacheId = 'cache' + linkId;
			if ($('#' + cacheId).length > 0) {
			
				var data = JSON.parse($('#' + cacheId).text());

				// // Set up HTML.
				buildAndLaunchGalleries(data);
				
				// // Launch the specific gallery associated with this standalone link
				launchGallery(data.gallery_name);

			} else {
			
				var jqxhr = $.getJSON($(this).attr('href'), function(data, textStatus, jqXHR) {

					// // Set up HTML.
					buildAndLaunchGalleries(data);
					
					// // Cache the output *before* launching the gallery.
					$('<div/>')
						.attr('id', cacheId)
						.text(JSON.stringify(data))
						.appendTo('#cache');

					// // Launch the specific gallery associated with this standalone link
					launchGallery(data.gallery_name);
					
				})
				// .beforeSend(function(jqXHR, settings) { alert("before send, close existing galleries"); })
				// .success(function(data, textStatus, jqXHR) { alert("second success"); })
				.error(function(jqXHR, textStatus, errorThrown) { alert('error : [' + errorThrown + ']'); });
				// .complete(function(jqXHR, textStatus) { alert("complete"); });

			}
		});
	};
	
	// // ==============================================
	
	$('#launchGalleries').click(function(e){
		e.preventDefault();
		e.stopPropagation();

		alert(galleryDisclaimer);

		// // If the gallery is already cached, use that instead.
		var linkId = $(this).attr('id');
		var cacheId = 'cache' + linkId;
		if ($('#' + cacheId).length > 0) {
		
			var data = JSON.parse($('#' + cacheId).text());

			// // Set up HTML.
			buildAndLaunchGalleries(data);

		} else {
		
			var jqxhr = $.getJSON($(this).attr('href'), function(data, textStatus, jqXHR) {

				// // Set up HTML.
				buildAndLaunchGalleries(data);
				
				// // Cache the output
				$('<div/>')
					.attr('id', cacheId)
					.text(JSON.stringify(data))
					.appendTo('#cache');
			})
			// .beforeSend(function(jqXHR, settings) { alert("before send, close existing galleries"); })
			// .success(function(data, textStatus, jqXHR) { alert("second success"); })
			.error(function(jqXHR, textStatus, errorThrown) { alert('error : [' + errorThrown + ']'); });
			// .complete(function(jqXHR, textStatus) { alert("complete"); });

		}
	});

	$('#closeGalleries').click(function(e){
		e.preventDefault();
		// // Close any opened galleries
		if ($('a.pp_close').length > 0) {
			$('a.pp_close').click();
		}
		// // The rest of the clean up follows ...
		$('#divGalleries').hide();
		$('#main_wrapper').remove();
	});

	// // Bind any standalone gallery link
	bindStandaloneGalleryLinks();

});

