/*
Bryan Gullan - jquery image gallery code
*/

$(document).ready(function() {
	$('div#gallery a').click(function(event){
		var startImage = $(this).attr('rel');
		showGallery($('div#gallery'),startImage);
		event.preventDefault();
	});
	$('div.gallery a:not(.galleryignore)').click(function(event){
		var startImage = $(this).attr('rel');
		showGallery($('div.gallery'),startImage);
		event.preventDefault();
	});
});

function closeGallery() {
	$('#galleryLightBox').remove();
	$('#overlay').remove();
	$('select').show();
	$('a.closerlink').unbind('click').unbind('keypress');
	$('#overlay').unbind('click').unbind('keypress');
}

function setupGallery() {
	var galleryHeight = $('#expandedContainer').height();
	var docHeight = $(document).height();
	
	if (galleryHeight + 40 > docHeight) {
		$('body').height(galleryHeight + 60 + 'px');
		docHeight = $(document).height();
		$('#overlay').css({ height: docHeight + 'px' });
	}
	var galleryTopMargin = docHeight - galleryHeight - 40;
	//$('#sitemap-box').css({marginTop: sitemapTopMargin + 'px' });  
	$('#expandedContainer').css({marginTop: 0 + 'px' });  
	
	var closer = $('<a href="#">close lightbox</a>')
	$(closer).click(closeGallery);
	$('a.closerlink').click(closeGallery);
	$('#expandedContainer').append(closer);
	$('#overlay').click(closeGallery);
	$('select').hide();
	$('#expandedContainer').show();
	$('li.previous a').click(function() {
		var thisPic = $(this).attr('rel');
		var previousPic = $(this).attr('href').split('#')[1];
		$('div#' + thisPic).removeClass('showpop').addClass('hidepop');
		$('div#' + previousPic).removeClass('hidepop').addClass('showpop');
		window.scrollTo(0,0);
	});
	$('li.next a').click(function() {
		var thisPic = $(this).attr('rel');
		var nextPic = $(this).attr('href').split('#')[1];
		$('div#' + thisPic).removeClass('showpop').addClass('hidepop');
		$('div#' + nextPic).removeClass('hidepop').addClass('showpop');
		window.scrollTo(0,0);
	});
}

function showGallery(gallery,startImage) {
	var docHeight = $(document).height();
	var docWidth = $(document).width();
	
	$('<div id="overlay"></div>').insertAfter('#wrapper');
	$('<div id="galleryLightBox"></div>').insertAfter('#wrapper');
	
	window.scrollTo(0,0);
	var galleryFolder = $(gallery).attr('title'); //the title attribute is set to be the media bank folder
	$('#overlay').css({ height: docHeight + 'px' ,width: docWidth + 'px'  });
	$('#galleryLightBox').load('/applications/gallery.rm?folder=' + galleryFolder + '&startimage=' +startImage,setupGallery)
	;
}
