var galleryMaxWidth = 850;
var galleryMaxHeight = 400;
var animateSpeed = 100;

/**
 * Display a photo gallery.
 *
 * @param string selector		A CSS selector representing the ToolGridMode container with the gallery in it.
 * @param string galleryTitle	A CSS selector representing the element with the title to be used in it.
 */
function showGallery(selector, galleryTitle)
{
	if (window.showGalleryIE6)
	{
		/* This is for IE6. It mutilates the code below, so instead, there's a separate implementation.
		 * The implementation gets loaded by a conditional comment elsewhere.
		 */
		return showGalleryIE6(selector, galleryTitle);
	}
	
	var cursorStyle = 'pointer';
	if (jQuery.browser.msie) cursorStyle = 'hand';
	
	var gallery = $(selector);
	var itemHeight = $("img", gallery).eq(0).attr("height");

	var container = document.body;
	
	var overlay = document.createElement("div");	
	$(overlay).css({ position: 'fixed', top: 0, left: 0, width: '100%', height: '100%', zIndex: 10000, background: 'black', opacity: 0 })
		.addClass("gallery-overlay")
		.html("<img src='tools/images/thickbox_loadingAnimation.gif' width='208' height='13' style='position: absolute; left: 50%; top: 50%; margin-top: -6px; margin-left: -104px;' />");
	$(container).append(overlay);
	var navOuter = document.createElement("div");
	$(navOuter).css({ position: 'fixed', bottom: 0, left: 0, right: 0, background: 'black', opacity: 0, zIndex: 10001 })
		.addClass("gallery-nav");

	var nav = document.createElement("div");
	var lButton = document.createElement('div');
	var rButton = document.createElement('div');
	$(lButton)
		.css({position: 'absolute', left: '-30px', top: '50%', fontSize: '20px', width: '35px', background: 'black', color: 'white'})
		.html('<a></a>')
		.children("a")
		.text('<')
		.css({width: '30px', height: '30px', left: 0, position: 'absolute', top: '-15px', lineHeight: '30px', background: 'white' });
	$(rButton)
		.css({position: 'absolute', right: '-30px', top: '50%', fontSize: '20px', width: '35px', background: 'black', color: 'white'})
		.html('<a></a>')
		.children("a")
		.text('>')
		.css({width: '30px', height: '30px', right: 0, position: 'absolute', top: '-15px', lineHeight: '30px', background: 'white'});
	$(nav).css({ position: 'absolute', left: '50%', top: '10px' });
	
	galleryTitle = galleryTitle ? $(galleryTitle).text() : "";
	
	$(container).append(navOuter);
	$(navOuter).append(nav);
	
	$(navOuter).append(lButton).append(rButton);
	$(lButton).css({ textAlign: 'center' });
	$(rButton).css({ textAlign: 'center' });
	
	$("img", gallery).each(function() {	
		var n = this.cloneNode(true);
		$(n).attr("parent-id", $(this).parent().attr("id"));
		var c = document.createElement("div");
		$(c).addClass("gallery-item").append(n);
		$(nav).append(c);
	});
	
	var items = $('.gallery-item', nav);
	var item0 = $(items.eq(0));
	var dimensions = [ item0.width() ];
	var dimensions2 = [ item0.width() ];
	dimensions.push(parseFloat(item0.css('padding-left')));
	dimensions.push(parseFloat(item0.css('padding-right')));
	dimensions.push(parseFloat(item0.css('border-left-width')));
	dimensions.push(parseFloat(item0.css('border-right-width')));
	dimensions.push(parseFloat(item0.css('margin-left')));
	dimensions.push(parseFloat(item0.css('margin-right')));

	dimensions2.push((item0.css('padding-left')));
	dimensions2.push((item0.css('padding-right')));
	dimensions2.push((item0.css('border-left-width')));
	dimensions2.push((item0.css('border-right-width')));
	dimensions2.push((item0.css('margin-left')));
	dimensions2.push((item0.css('margin-right')));
	var width = 0;
	for (var i = 0; i < dimensions.length; i++) {
		if (!isNaN(dimensions[i]))
			width += dimensions[i];
	}
	var itemWidth = width;
	
	// width += 10;
	dimensions = [ item0.height() ];
	jQuery.each([ 'top', 'bottom' ], function(i, v) {
		dimensions.push(parseFloat(item0.css('padding-' + v)), parseFloat(item0.css('margin-' + v)), parseFloat(item0.css('border-' + v + '-width')));
	});
	var height = 0;
	jQuery.each(dimensions, function(i, v) {
		if (!isNaN(v))
			height += v;
	});
	$(nav).css("height", height + 'px');
	$(navOuter).css("height", height + 20);
	$(nav).css("width", (width * items.size()) + 'px');
	/*
	if ((width * items.size()) > $(navOuter).width())
	{
		$(nav).css({ left: 0 });
	}
	else
	{
		$(nav).css({ marginLeft: ((0 - (width * items.size())) / 2) + 'px' });
	}
	*/
	
	var lastResize = false;
		
	var body = document.createElement("div");

	$(window).bind("resize", function() {
		if (!navOuter.parentNode) {
			$(window).unbind("resize", arguments.callee);
			return;
		}

		var doResize = function() {
			var w = $(body).width();
			var h = $(body).height();
			w += parseFloat($(body).css('padding-left'));
			w += parseFloat($(body).css('padding-right'));
			w += parseFloat($(body).css('border-left-width'));
			w += parseFloat($(body).css('border-right-width'));
			h += parseFloat($(body).css('padding-top'));
			h += parseFloat($(body).css('padding-bottom'));
			h += parseFloat($(body).css('border-top-width'));
			h += parseFloat($(body).css('border-bottom-width'));
			h += $(navOuter).height();
			$(body)[$(body).css('opacity') < 1 ? 'css' : 'animate']({marginTop: (0-(h/2))+'px', marginLeft: (0-(w/2))+'px' }, {speed: animateSpeed, queue:false});
			
			var cWidth = $(lButton).width() * 2;
			var tWidth = $(window).width() - cWidth;
		
			if (tWidth < (width * items.size()))
			{
				var lPos = $(lButton).width();
				var current = $(".current", nav)[0];
				var p = current.parentNode.firstChild;
				var index = 0;
				while (p && p != current) {
					p = p.nextSibling;
					index++;
				}
				var cPos = (index * itemWidth);
				var middle_b = lPos + ($(window).width() / 2);
				
				var middle_e = (width * items.size()) - middle_b;
				
				$(nav).animate({ marginLeft: 0, left: 0 - (cPos - middle_b) - (itemWidth / 2) }, { speed: animateSpeed });
				$(lButton).fadeIn(animateSpeed);
				$(rButton).fadeIn(animateSpeed);
			}
			else
			{
				$(nav).animate({ left: '50%', marginLeft: ((0 - (width * items.size())) / 2) + 'px' }, { speed: animateSpeed });
				$(lButton).fadeOut(animateSpeed);
				$(rButton).fadeOut(animateSpeed);
			}
			$(".gallery-item:not(.current)", nav).animate({ opacity: '0.6' }, { speed: animateSpeed });
			$(".gallery-item.current", nav).animate({ opacity: '1' }, { speed: animateSpeed });
		}
		
		/* Safari sends continuous resize events. This doesn't hurt anyone else, so... */
		clearTimeout(lastResize);
		lastResize = setTimeout(doResize, 100);
	}); // .trigger("resize");
		
	// $(".gallery-item", nav).width() * $(".gallery-item", nav).size());
	// $(navOuter).css({height: $(".gallery-item", nav).height() + 20});
	$(body).css({ position: 'fixed', top: '50%', left: '50%', zIndex: 10002, border: '2px solid white', color: 'white', opacity: 0, padding: '1em' });
	$(body).addClass("gallery-current");
	
	$(lButton).click(function() {
		$(".previous", body).click();
	}).css({ cursor: cursorStyle });
	$(rButton).click(function() {
		$(".next", body).click();
	}).css({ cursor: cursorStyle });
	var wasNext = false;
	
	$("img", nav).css({ cursor: cursorStyle })
		.hover(function() { $(this).parent().animate({ opacity: 1 }, { speed: animateSpeed }) }, function() { $(this).parent().animate({ opacity: $(this).parent().hasClass('current') ? 1 : 0.6 }, { speed: animateSpeed }) })
		.click(function() {
		var clickedImage = this.parentNode;
		
		$(".gallery-item", nav).removeClass("current");
		$(clickedImage).addClass("current");
		var id = $(this).attr('parent-id');
		
		var i = new Image();
		var p = this.src.split('/');
		var n = p.pop().split(';');
		var name = n.pop();
		
		var size = $("#" + $(this).attr('parent-id') + " .record-image-dimensions").text().split(";");
		size[0] = parseInt(size[0]);
		size[1] = parseInt(size[1]);
		
		/* Fix width to max(min(galleryMaxWidth, body width), image width); height to min(galleryMaxHeight, body height - nav height, image height)
		 * This defines the minimum size; it allows it to grow as large as necessary.
		 */
		var maxWidth = Math.min(galleryMaxWidth, $(overlay).width() - 80);
		var maxHeight = Math.min(galleryMaxHeight, $(window).height() - $(navOuter).height() - 120 /* for the h2 */);
		
		if (size[0] > maxWidth)
		{
			var r = size[0] / maxWidth;
			size[1] /= r;
			size[1] = Math.floor(size[1]);
		}
		size[0] = maxWidth;
		size[1] = maxHeight; // Math.min(size[1], maxHeight);
		
		// ixnay
		size[0] = galleryMaxWidth;
		size[1] = galleryMaxHeight;
		
		var color;
		if (n.length > 2)
			color = n[2];
		
		var n2 = [ size[0], size[1] ];
		if (color !== void(0)) n2.push(color);
		n2.push(name);
		
		name = n2.join(';');
		p.push(name);
		
		var title = $(this).attr('alt');

		$(body).hover(function() {
			$('.previous, .next, h2 img, .details', this).fadeIn(animateSpeed);
			wasNext = true;
		}, function() {
			$('.previous, .next, h2 img, .details', this).fadeOut(animateSpeed);
			wasNext = false;
		});
		
		var hide = function()
		{
			$(navOuter).animate({ opacity: 0 }, { speed: 400, queue: false, complete: function() { $(navOuter).remove(); } });
			$(body).animate({ opacity: 0 }, { speed: 400, queue: false, complete: function() { $(body).remove(); } });
			$(overlay).animate({ opacity: 0 }, { speed: 400, queue: false, complete: function() { $(overlay).remove(); } });
		}
		i.onload = function() {
			$(body).html("<img src='" + i.src + "' height='" + i.height + "' width='" + i.width + "'><br><h2 class='title'></h2><div class='details'></div>")
				.children('h2')
				//.append('<img src="images/info-button.png" /><span></span>')
				//.children('span').text(title)
				.text(title);
			$(body).children("img").css({ opacity: 0 });
			/*
			$(body).children('img').click(function() {
				var p = this.src.split('/');
				var n = p.pop().split(';');
				p.push(n.pop());
				window.open(p.join('/'), '_blank');
			}).css({ cursor: 'pointer' });
			*/
			
			$(body).children('h2.title')
				.children('img')
				.css({ display: 'none' });
			if (!title)
				$(body).children('h2.title').remove();
				
			var m = $("#" + id + " .record-details").html();
			
			if (m.replace(/\s/g, '') != '') {
				$(body).children(".details")
					.html($("#" + id + " .record-details").html() || "")
					.css({ position: 'absolute', left: '0', right: '0', bottom: '3em', color: 'white', display: 'none', opacity: 0.65, padding: '1em' })
					.css({ background: "black" });
			} else $(body).children('.details').remove();
			
			$(body).append("<a class='previous'>&lt;</a><a class='next'>&gt;</a>")
				.append("<a class='close'><span>X</span> Close</a><h2 class='gallery-title'></h2>");
			if (galleryTitle)
				$(body).children('h2.gallery-title').text(galleryTitle);
			else
				$(body).children('h2.gallery-title').remove();
			if (!wasNext) $(".previous, .next", body).css({ display: 'none' });
			wasNext = false;
			// if (!clickedImage.previousSibling) $('.previous', body).remove();
			// if (!clickedImage.nextSibling) $('.next', body).remove();
			$(".previous", body).css({ cursor: cursorStyle }).click(function() {
				var previous = clickedImage.previousSibling;
				if (!previous) previous = clickedImage.parentNode.lastChild;
				if (!$.support.opacity)
					$(this).bind("mouseout", function(e) {
						e.stopPropagation();
						$(this).unbind("mouseout", arguments.callee);
					});
				//wasNext = true;
				$("img", previous).click();
				return false;
			}).attr('href', '#');
			$(".next", body).css({ cursor: cursorStyle }).click(function() {
				var next = clickedImage.nextSibling;
				if (!next) next = clickedImage.parentNode.firstChild;
				//wasNext = true;
				if (!$.support.opacity)
					$(this).bind("mouseout", function(e) {
						e.stopPropagation();
						$(this).unbind("mouseout", arguments.callee);
					});
				$("img", next).click();
				return false;
			}).attr('href', '#');
			$(".close", body).css({ cursor: cursorStyle }).click(function() {
				hide();
			});
			var h = i.height;
			var w = i.width;
			// $("h2", body).css({ margin: 0, fontWeight: 'normal', padding: '0 12px' });
			var hh = $("h2.title", body).height() || 0;
			var tpos = (0 - (hh + h)) / 2;
			tpos -= ($(navOuter).height() / 2);
			// tpos -= 12;
			// $(body).css({ marginTop: tpos + 'px', marginLeft: ((0 - w) / 2) + 'px' })
			$(window).trigger('resize');
			var node = $(body).children('img').andSelf();
			node.animate({ opacity: 1 }, { speed: animateSpeed, complete: function() {
				if (!$.support.opacity)
				{
					body.style.filter = '';
					$('img', body)[0].style.filter = '';
				}
			} });	
		}
		
		// p.push(name);
		var b = $(body);	
		var c = ($("img", body).size() == 0)? b : $("img", body);
		
		c.animate({ opacity: 0 }, { speed: animateSpeed, complete: function() {
			i.src = p.join('/');
		} });
		$(window).trigger("resize");
	});			
	
	$(body).css({ opacity: 0 });
	$(container).append(body);
	$(overlay).animate({ opacity: 0.7 }, { speed: 400, queue: false });	
	$(navOuter).animate({ opacity: 1 }, { speed: 400, queue: false });
	
	$("img", nav).eq(0).click();
}
