//	adjustable settings
var thumbCoordinates = {
	0:{'x':5,'y':5},
	1:{'x':109,'y':5},
	2:{'x':5,'y':109},
	3:{'x':109,'y':109},	
	4:{'x':5,'y':213},
	5:{'x':109,'y':213},
	6:{'x':5,'y':317},
	7:{'x':109,'y':317}
};
var thumbContainerWidth = 204;
var thumbCount = 8;

//=========================================
var currentPhoto;
var photoCount;
var realPhotoCount;
var animating = false;
var firstThumbIndex;

$(document).ready(function(){
	photoCount = 0;
	
	//	quit if there aren't any photos
	if (photos == undefined)
	{	
		return;
	}
	
	//	count the photos
	for(var photo in photos)
		photoCount++;
		
	realPhotoCount = photoCount;
	while (photoCount % thumbCount != 0)
	{
		photoCount++;
	}

	//	set up the thumbnails
	currentPhoto = 0;
	firstThumbIndex = 0;
	
	if (photoCount > thumbCount)
	{
		for (var i = -thumbCount; i < (thumbCount * 2); i++)
		{
			createThumbnail(i,i,false);
		}
	}
	else
	{
		for (var i = 0; i < photoCount; i++)
		{
			createThumbnail(i,i,false);
		}
		$("div.pagingNav").css("display","none");
	}
	
	//	highlight the fist one
	$("#thumbnails img.thumb_0").addClass("current");
	
	//	thumbnail paging: next
	$("div.pagingNav img.next").click(
		function()
		{
			pageThumbnails (false,true);	
			return false;
		}
	).addClass("clickable");
	//	thumbnail paging: previous
	$("div.pagingNav img.previous").click(
		function()
		{
			pageThumbnails (true,true);	
			return false;
		}
	).addClass("clickable");	
	
	//	next image
	$("div.imageNav img.next").click(
		function()
		{
			switchTo (currentPhoto + 1);	
			return false;
		}
	).addClass("clickable");
	
	//	previous image
	$("div.imageNav img.previous").click(
		function()
		{
			switchTo (currentPhoto - 1);
			return false;
		}
	).addClass("clickable");
	
	//	clicking on the main pic goes to the next image
	$("#mainPic").click(
		function()
		{
			switchTo (currentPhoto + 1);
		}
	).addClass("clickable");
	
	$("#photoEmailLink").click (
		function ()
		{
			showEmailForm ();
			return false;
		}
	);
	
	//	set up the image rater
	switchImageRater(0);
});


//	find out where a particular thumbnail should go
function getCoordinates(position)
{
	if (position < 0)
	{
		return shiftCoordinates(getCoordinates(position + thumbCount),-thumbContainerWidth);
	}
	else if (position >= thumbCount)
	{
		return shiftCoordinates(getCoordinates(position - thumbCount),thumbContainerWidth);
	}
	else
	{
		return thumbCoordinates[position];
	}
}

//	helper for getCoordinates
function shiftCoordinates(coords,distance)
{
	var newX = coords['x'] + distance;
	var newY = coords['y'];
	return {'x':newX,'y':newY};
}

//	move the main image to a particular photo index
function switchTo (photoIndex)
{
	if (photoIndex == currentPhoto)
	{
		return;
	}
	
	photoIndex = getIndex(photoIndex);
	
	//turn the page forward if necessary
	if (photoIndex == getIndex(firstThumbIndex + thumbCount) && photoCount > thumbCount)
	{
		pageThumbnails (false,false);
	}
	else if(photoIndex == getIndex(firstThumbIndex - 1) && photoCount > thumbCount)
	{
		pageThumbnails (true,false);
	}
	
	var photo = photos[photoIndex];
	if (photo == undefined)
	{
		if (photoIndex == realPhotoCount)
		{
			return switchTo (0);
		}
		else
		{
			return switchTo (realPhotoCount -1);
		}
	}
	
	$("#thumbnails img.thumb_" + currentPhoto).removeClass("current");
	$("#thumbnails img.thumb_" + photoIndex).addClass("current");
	
	$("#imageTitle").html(photo['Title']);
	
	switchImageRater(photoIndex);
	
	currentPhoto = photoIndex;
	updateMainPicture("mainPic");
	return true;
}

//	make the image rating control refer to the correct image
//	and show the correct current ranking. also watch the updater so we can
//	correct the in-memory photo data when the rating gets updated
function switchImageRater(newIndex)
{
	if (photoCount == 0)
	{
		return;
	}
	$("#imageRating ul").removeClass("rating_" + photos[currentPhoto]['ImageID']).addClass("rating_" + photos[newIndex]['ImageID']);
	setRatingView(photos[newIndex]['ImageID'],photos[newIndex]['Rating']);
	
	//	bind the event to watch for changes
	$("#imageRating").unbind("ratingUpdated");
	$("#imageRating").bind("ratingUpdated",
		function(event,newRating,imageID)
		{
			photos[newIndex]['Rating'] = newRating;
		}
	);
	
	var num = photos[newIndex]['AverageRating'] ? photos[newIndex]['AverageRating'].toFixed (1): '';
	$("#imageRating div.averageRating span.value").html (num);
	if (photos[newIndex]['AverageRating'] == "")
	{
		hide ($("#imageRating div.averageRating"));
	}
	else
	{
		show ($("#imageRating div.averageRating"));
	}
}

//	page the thumbnails
function pageThumbnails (backwards,selectNewImage)
{
	if (animating)
	{
		return;
	}
	animating = true;
	if (backwards)
	{
		animate(true,thumbContainerWidth);
		firstThumbIndex = getIndex(firstThumbIndex - thumbCount);
		//	remove set of thumbnails on the right, add a new set to the left
		for (var i = 0; i < thumbCount; i++)
		{
			$("#thumbnails img:last").remove();
			createThumbnail(-i - 1,firstThumbIndex - i - 1,true);
		}
	}
	else
	{
		animate(false,thumbContainerWidth);
		firstThumbIndex = getIndex(firstThumbIndex + thumbCount);
		//	remove set of thumbnails on the left, add a new set to the right
		for (var i = 0; i < thumbCount; i++)
		{
			$("#thumbnails img:first").remove();
			createThumbnail(thumbCount + i, firstThumbIndex + thumbCount + i, false);
		}
	}
	
	if (selectNewImage)
	{
		switchTo(firstThumbIndex);
	}
}

//	copied from teamgallery.js. if we can make 'em common, we should, of course
//		MODIFIED QUITE A BIT BECAUSE OF Y coordinate

//	use clone, prepend, and append, basing it on #thumbnailTemplate
//	positions can be [0] [1] [2] [3] [4] where 1 through 3 are visible
function createThumbnail(position,photoIndex,prepend)
{
	photoIndex = getIndex(photoIndex);
	var photo = photos[photoIndex];
	if(photo == undefined)
	{	
		//	fake thumbnail
		if (prepend)
		{
			$("#thumbnailTemplate").clone()
				.prependTo("#thumbnails")
				.addClass("thumb_" + photoIndex);		
		}
		else
		{
			$("#thumbnailTemplate").clone()
				.appendTo("#thumbnails")
				.addClass("thumb_" + photoIndex);		
		}
	}
	else
	{
		//	real thumbnail
		var coords = getCoordinates(position);
			
		if(prepend)
		{
			$("#thumbnailTemplate").clone().attr({
					"src":photo["Thumbnail"],
					"alt":photo["Title"],
					"id":""
				}).css("left",coords['x'])
				.css("top",coords['y'])
				.prependTo("#thumbnails")
				.removeClass("hidden")
				.addClass("thumb_" + photoIndex)
				.addClass("clickable")
				.click(function(){	switchTo(photoIndex);	});
		}
		else
		{
			$("#thumbnailTemplate").clone().attr({
					"src":photo["Thumbnail"],
					"alt":photo["Title"],
					"id":""
				}).css("left",coords['x'])
				.css("top",coords['y'])
				.appendTo("#thumbnails")
				.removeClass("hidden")
				.addClass("thumb_" + photoIndex)
				.addClass("clickable")
				.click(function(){	switchTo(photoIndex);	});
		}	
	}
	
}


//	do the shifting of the thumbnails, once they're all present
//	if previous is true, we're going back, otherwise we're going forward
//	(changed to take the distance parameter to satisfy both pages)
function animate(backwards,distance)
{
	$("#thumbnails img").each(
		function()
		{
			var left = getPixels($(this).css("left"));
			var newleft = left;
			if(backwards)
			{
				newleft = newleft + distance;
			}
			else
			{
				newleft = newleft - distance;
			}
			$(this).animate({
				left:newleft
			},200,function()
			{
				animating = false;
			});
		}			
	);
}


//	just like teampage, except the id of the main image, and checkPhotoSize
function updateMainPicture(id)
{
	//find the right image
	var photo = photos[currentPhoto];
	if(photo == undefined)
	{
		return;
	}	
	
	//	load the image it into a vairiable,
	var img = new Image();
	$(img).load(function()
	{
		//when the variable has its image loaded, swap it into the page
		$("#" + id).attr({
			"src":photo["Large"],
			"alt":photo["Title"]
		});
		
		//update the line (teampage)
		//checkPhotoSize();
	}).attr("src",photo["Large"]);
	
}

//	adjust a number to point to a valid index of photos
function getIndex(number)
{
	while(number < 0)
	{
		number = number + photoCount;
	}
	while (number >= photoCount)
	{
		number = number - photoCount;
	}
	return number;
}


//
//	email functionality
//
function hideEmailForm ()
{
	$("#photoEmailLink").unbind ('click').click (
		function ()
		{
			showEmailForm ();
			return false;
		}
	);
	hide ($("#photoEmailer"));
	hide ($("#photoEmailer div.response"));
}

function showEmailForm ()
{
	$("#photoEmailLink").unbind ('click').click (
		function ()
		{
			hideEmailForm ();
			return false;
		}
	);

	show ($("#photoEmailer"));
	$("#photoEmailSubmit").click (
		function ()
		{
			show ($("#photoEmailer div.response").html("...Sending Your Message...").removeClass("error"));
			
			var to = $("#photoEmailTo").attr("value");
			if (to == "")
			{
				show ($("#photoEmailer div.response").html("Please enter the recipient's email address.").addClass("error"));
				return;
			}
			
			//	make the AJAX submission that sends the email
			var emailInfo = {
				"Action":"PhotoEmail",
				"ImageID":photos[currentPhoto]['ImageID'],
				"To":to,
				"Message":$("#photoEmailMessage").attr("value"),
				"GalleryURL":location.href
			};
			
			setTokenValue (emailInfo);
			
			//	ajax call
			$.post("/imageactions/",emailInfo,function(response,status)
			{
				if(status == "success" && response == "SUCCESS")
				{
					show (
						$("#photoEmailer div.response").html("Your email has been sent. Please feel free to send another.")
						.removeClass("error")
					);
				}
				else
				{
					show (
						$("#photoEmailer div.response").html("Sorry, there was an error sending your email. Please check the email address and try again.")
						.addClass("error")
					);
				}
			},"text");
			
			return false;
		}
	);
}

