var maxBoxSize = 780;
var loadingBoxWidth = 300;
var loadingBoxHeight = 75;
var maxRetries = 3;
var currentTry = 1;
var viewerFileName = '_displayImage.php';
var galleryBodyFileName = '_viewGallery.php';
var imageIdPrefix = 'img_';
var showing;
var toHide;
var yPadding = 70;
var xPadding = 20;

$(document).ready(function () {
	$('.galleryWideMessageTitle a').click(function () {
		setUpLazyGalleryLoad(this);
		return false;
	});
	$('#modalCloseBtn').click(function () {
		hideModals();
	});			
});

function setUpLazyGalleryLoad(galleryAnchor)
{
	var containingDiv = $(galleryAnchor).parents('.galleryWideMessageTitle').parent().get(0);
	if ($(containingDiv).children('.galleryWideMessageContent').length != 1) {
		var link = $(galleryAnchor).attr('href');
		var idMatches = /.*id=([0-9]+)/i.exec(link);
		var galleryId = idMatches[1];
		if (isNaN(galleryId)) {
			alert("Unable to load gallery.");
			return;
		}
		var getGalleryAddr = galleryBodyFileName + "?id=" + galleryId;
		var bodyText = $.ajax({
							type: 'GET',
							url: galleryBodyFileName,
							data: 'id=' + galleryId,
							async: false
						}).responseText;
		$(containingDiv).append(bodyText);
		initLazyLoadedGallery(containingDiv);
	} else {
		$(containingDiv).children('.galleryWideMessageContent').toggle();
	}
}

function initLazyLoadedGallery(galleryContainer)
{
	$(galleryContainer).find('.galleryThumbnail').hover(function() {
		$(this).find('.galleryDetails').show();
		if (showing != null && showing != this) {
			$(showing).find('.galleryDetails').hide();
		}
		if (toHide == this) {
			toHide = null;
		}
		showing = this;
	}, function () {
		toHide = this;
		setTimeout("conditionalHide()", 1000);
	});
	$(galleryContainer).find('.galleryThumbnail').find('a').each(function () {
		setupLiveGalleryLink(this);
	});
}

function conditionalHide()
{
	if (toHide != null) {
		$(toHide).find('.galleryDetails').hide();
		toHide = null;
	}
}

function setupLiveGalleryLink(queryResultObject)
{
	$(queryResultObject).click(function() {
		setImageCaptionControls(this);
		currentTry = 1;
		var fullThumbViewerPath = $(this).find('img').attr('src');
		var fullImageViewerPath = '/personal/gallery/_displayImage.php?image_id=' + $(this).attr('id').substr(imageIdPrefix.length) + '&scale=scaled&size=' + maxBoxSize + '&cache=true';
		$('.frameControls').hide();
		$('#modalCloseBtn').hide();		
		$('#modal').children('img.imageViewing').remove();
		$('#modal').children('.loadingLabelBox').remove();		
		fetchAndDisplayImage(fullImageViewerPath);
		return false;
	});
}

function setImageCaptionControls(thumbnailLink)
{
	$(".informationContainer").html($(thumbnailLink).parents('.galleryThumbnail').find('.thumbnailDescription').html());
	$(".informationContainer").append("<br />");
	$(".informationContainer").append($(thumbnailLink).parents('.galleryThumbnail').find('.thumbnailTags').html());
	var previousThumb = null;
	if ($(thumbnailLink).parents('.galleryThumbnail').prev('.galleryThumbnail').length == 0) {
		previousThumb = $(thumbnailLink).parents('.galleryThumbnail').siblings('.galleryThumbnail').last().get(0);
	} else {
		previousThumb = $(thumbnailLink).parents('.galleryThumbnail').prev('.galleryThumbnail').get(0);
	}
	var previousThumbViewerPath = $(previousThumb).find('img').attr('src');
	var previousFullViewerPath = previousThumbViewerPath.substr(0, previousThumbViewerPath.indexOf(viewerFileName) + viewerFileName.length);
	previousFullViewerPath = previousFullViewerPath + '?image_id=' + $(previousThumb).find('a').attr('id').substr(imageIdPrefix.length) + '&scale=scaled&size=' + maxBoxSize + '&cache=true';
	$('.previousContainer').unbind('click');
	$('.previousContainer').click(function () {
		$('.frameControls').hide();
		$('#modalCloseBtn').hide();
		setImageCaptionControls($(previousThumb).find('a'));
		$('#modal').children('img.imageViewing').remove();
		$('#modal').children('.loadingLabelBox').remove();		
		fetchAndDisplayImage(previousFullViewerPath);
	});
	
	var nextThumb = null;
	if ($(thumbnailLink).parents('.galleryThumbnail').next('.galleryThumbnail').length == 0) {
		nextThumb = $(thumbnailLink).parents('.galleryThumbnail').siblings('.galleryThumbnail').first().get(0);
	} else {
		nextThumb = $(thumbnailLink).parents('.galleryThumbnail').next('.galleryThumbnail').get(0);
	}
	var nextThumbViewerPath = $(nextThumb).find('img').attr('src');
	var nextFullViewerPath = nextThumbViewerPath.substr(0, nextThumbViewerPath.indexOf(viewerFileName) + viewerFileName.length);
	nextFullViewerPath = nextFullViewerPath + '?image_id=' + $(nextThumb).find('a').attr('id').substr(imageIdPrefix.length) +  '&scale=scaled&size=' + maxBoxSize + '&cache=true';
	$('.nextContainer').unbind('click');
	$('.nextContainer').click(function () {
		$('.frameControls').hide();
		$('#modalCloseBtn').hide();
		setImageCaptionControls($(nextThumb).find('a'));
		$('#modal').children('img.imageViewing').remove();
		$('#modal').children('.loadingLabelBox').remove();	
		fetchAndDisplayImage(nextFullViewerPath);
	});
}

function fetchAndDisplayImage(path) {
	$('#hiddenSizerImage').attr('src', '');
	initModal();
	$('#hiddenSizerImage').load(function () {
		if ($(this).attr('src') != "") {
			$('#modal').children('img.imageViewing').remove();
			$('#modal').children('.loadingLabelBox').remove();
			injectImage(this);
		}
	});
	$('#hiddenSizerImage').error(function () {
		currentTry++;
		var retryImage = this;
		var retryPath = $(this).attr('src');
		if (currentTry <= maxRetries) {
			$.get('_resetSession.php', function () {
				$(retryImage).attr('src', '');
				$(retryImage).attr('src', retryPath + '&try=' + currentTry);
			});
		}
	});
	$('#hiddenSizerImage').attr('src', path);
}

function initModal() {
	$('#grayout').hide();
	$('#loadingMessage').show();
	var loadingMessage = document.createElement('div');
	$(loadingMessage).text('Loading image...')
	$(loadingMessage).addClass('loadingLabelBox');
	$('#modal').append(loadingMessage);
	$('#modal').css("width", loadingBoxWidth);
	$('#modal').css("height", loadingBoxHeight);
	$('#modal').css("top", calculateYPlacement($(window).height(), 
			   loadingBoxHeight, 
			   $(document).scrollTop()));
	$('#modal').css("left", calculateXPlacement($(window).width(), 
												loadingBoxWidth, 
												$(document).scrollLeft()));
	$('#modal').show();
}

function injectImage(imageObject)
{
	var imageWidth = determineOutputWidth(imageObject);
	var imageHeight = determineOutputHeight(imageObject);
	var newImage = document.createElement("IMG");
	$(newImage).addClass("imageViewing");
	newImage.setAttribute("src", $(imageObject).attr('src'));
	$(newImage).css("border", "none");
	$(newImage).css("margin", "0");
	$(newImage).css("padding", "0");
	newImage.style.width = imageWidth + "px";
	newImage.style.height = imageHeight + "px";
	newImage.style.boder = "none";
	newImage.style.margin = "0";
	newImage.style.padding = "0";
	newImage.id = "modalIFrame";
	$('#modal').css("width", imageWidth);
	$('#modal').css("height", imageHeight + 50);
	$('#modal').css("top", calculateYPlacement($(window).height(), 
			   imageHeight + yPadding, 
			   $(document).scrollTop()));
	$('#modal').css("left", calculateXPlacement($(window).width(), 
												imageWidth + xPadding, 
												$(document).scrollLeft()));
	$('.informationContainer').css("width", imageWidth - 75);
	$(".frameControls").show();
	displayCloseButton();
	/*$('#modal').animate({width: imageWidth + "px", 
		 				 height: imageHeight + "px",
		 				 top: calculateYPlacement($(window).height(), 
		 						 				  imageHeight, 
		 						 				  $(document).scrollTop()),
		 				 left: calculateXPlacement($(window).width(), 
		 						 				   imageWidth, 
		 						 				   $(document).scrollLeft())
		 				 }, 500, 'swing', function () {
		 					 				displayCloseButton();
		 				 				  });*/
	$('#modal').prepend(newImage);
}

function hideModals() {
	$('#grayout').hide();
	//$('#modal').children().remove();
	$('#modal').children('img.imageViewing').remove();
	$('#modal').children('.loadingLabelBox').remove();	
	$('.frameControls').hide();
	$('#modal').hide();
	$('#modalCloseBtn').hide();
}

function displayCloseButton() 
{
	$('#modalCloseBtn').css("top", ($('#modal').position().top - 15));
	$('#modalCloseBtn').css("left",($('#modal').position().left + $('#modal').width() - 15));
	$('#modalCloseBtn').click(function () {
		hideModals();
	});
	$('#modalCloseBtn').show();
}

function determineOutputHeight(imageObject)
{
	if (isBiggerThanMax(imageObject)) {
		var curHeight = $(imageObject).height();
		var curWidth = $(imageObject).width();
		if (curHeight > curWidth) {
			return getMaxBoxSize();
		} else {
			return (curHeight * getMaxBoxSize()) / curWidth;
		}
	} else {
		return $(imageObject).height();
	}
}

function determineOutputWidth(imageObject)
{
	if (isBiggerThanMax(imageObject)) {
		var curHeight = $(imageObject).height();
		var curWidth = $(imageObject).width();
		if (curWidth > curHeight) {
			return getMaxBoxSize();
		} else {
			return (curWidth * getMaxBoxSize()) / curHeight;
		}
	} else {
		return $(imageObject).width();
	}
}

function getMaxBoxSize()
{
	var viewPortMin = Math.min($(window).height(), $(window).width());
	if ((viewPortMin - 100) < maxBoxSize) {
		return viewPortMin - 100;
	} else {
		return maxBoxSize;
	}
}

function isBiggerThanMax(imageObject)
{
	return $(imageObject).width() > getMaxBoxSize() || $(imageObject).height() > getMaxBoxSize();
}

function calculateYPlacement(outerFrameHeight, innerFrameHeight, offset)
{
	return (outerFrameHeight / 2) - (innerFrameHeight / 2) + offset;
}

function calculateXPlacement(outerFrameWidth, innerFrameWidth, offset)
{
	return (outerFrameWidth / 2) - (innerFrameWidth / 2) + offset;
}

