var windowWidth,
	windowHeight,
	originalPhotoHeight,
	originalPhotoWidth
	inSpace = false,
	info = false,
	ajaxUrl = "/process/ajax",
	formOnFocus = false,
	ctrlClick = false,
	albumChange = false,
	currentPhotoID = 0,
	viewAll_currentAlbum = 0,
	viewAll_currentPhoto = 0,
	viewAll_oldPositions = new Array();

/* Helper function for reverse iteration */
$.fn.reverse = function() {
    return this.pushStack(this.get().reverse(), arguments);
};

$(document).ready(function()
{
	/* Initializes the history object */
	$.history.init(handleHistory);

	/* Preloads common used images */
	$.preloadImages("/images/arrows.png", "/images/ajax-loader.gif", "/images/ajax-loader-b.gif");

	/* Gets the current dimensions of the window */
	windowWidth = $(window).width();
	windowHeight = $(window).height();

	/* Form focus states for the keypress function */
	$("form input, form textarea").live("focus", function() { formOnFocus = true; });	
	$("form input, form textarea").live("focusout", function() { formOnFocus = false; });	

	/* Photo information close button */
	$("#closeInfo a").attr("href", "#").live("click", function()
	{
		hideInfo();

		return false;
	});
	
	$("#openInfo a").attr("href", "#").live("click", function()
	{
		toggleInfo();

		return false;
	});
	
	$("#gotoSpace, #outofSpace").attr("href", "#").live("click", function()
	{
		toggleSpace();

		return false;
	});

	$("a[name=about]").attr("href", "#about");
	$("a[name=view-all]").attr("href", "#view-all");
	$("a[name=contacts]").attr("href", "#contacts");

	if ($(".photoArrows#left a").attr("name") == "") { $(".photoArrows#left a").remove(); } else { $(".photoArrows#left a").attr("href", "").live("click", function(event)
	{
		prevPhoto();

		event.preventDefault();
		return false;
	}); }

	if ($(".photoArrows#right a").attr("name") == "") { $(".photoArrows#right a").remove(); } else { $(".photoArrows#right a").attr("href", "").live("click", function(event)
	{
		nextPhoto();
		
		event.preventDefault();
		return false;
	}); }

	if ($(".albumArrows#down a").attr("name") == "") { $(".albumArrows#down a").remove(); } else { $(".albumArrows#down a").attr("href", "").live("click", function(event)
	{
		nextAlbum();
		
		event.preventDefault();
		return false;
	}); }

	if ($(".albumArrows#up a").attr("name") == "") { $(".albumArrows#up a").remove(); } else { $(".albumArrows#up a").attr("href", "").live("click", function(event)
	{
		prevAlbum();
		
		event.preventDefault();
		return false;
	}); }


	$("#close a").attr("href", "#"+currentPhotoID);

	if ($("#viewAll").length > 0)
	{
		$("#viewAll .photosContainer a").each(function()
		{
			$(this).attr("href", "#"+$(this).attr("name"));
		});

		var albumsCount = $("#viewAll .albumContainer").length;

		for (var i = 0; i < albumsCount; i++)
		{
			viewAll_oldPositions[i] = 1;
		}

		viewAll_currentPhoto = 1;

		changeViewAllAlbumPosition(1);		
	}

	if ($(".overlay").length > 0)
	{
		$("#arrowKeys").hide();
		$("#close").show();
	}

	if ($(".photo").length > 0)
	{
		$(".photo").css({width : "auto"});
		
		$("#info").hide();
	}
	
	$(".horScrollArrows#right").find("a").live("click", function(event)
	{
		if ($("#viewAll").length > 0)
		{
			var btn = $(this).parents(".albumContainer"),
				album = (btn.index("#viewAll .albumContainer")) + 1;
			
			changeViewAllAlbumPosition(album);
			
			changeViewAllPhotoPosition(viewAll_currentPhoto + 1, true);
			
			event.preventDefault();
			return false;
		}
	});
	
	$(".horScrollArrows#left").find("a").live("click", function(event)
	{
		if ($("#viewAll").length > 0)
		{
			var btn = $(this).parents(".albumContainer"),
				album = (btn.index("#viewAll .albumContainer")) + 1;
			
			changeViewAllAlbumPosition(album);
			
			changeViewAllPhotoPosition(viewAll_currentPhoto - 1, true);
			
			event.preventDefault();
			return false;
		}
	});
});

$(window).load(function()
{
	/* Photo resize */
	handleResize();
});

$(window).resize(function()
{	
	/* Gets the current dimensions of the window */
	windowWidth = $(window).width();
	windowHeight = $(window).height();
	
	/* Photo resize */
	handleResize();
});

$(document).keydown(function(event)
{
	/* Gets the pressed key */
	var code = (event.keyCode ? event.keyCode : event.which); 

	if (code == 17) { ctrlClick = true; }

	/* Disables scrolling in view all */
	if (((code == 38) || (code == 40)) && ($("#viewAll").length > 0))
	{
		event.preventDefault();
		return false;
	}
});

$(document).keyup(function(event) 
{
	/* Gets the pressed key */
	var code = (event.keyCode ? event.keyCode : event.which); 

	if (code == 17) { ctrlClick = false; }

	if (!formOnFocus)
	{
		/* Calls function based on the pressed key */
		switch(code)
		{
			/* "a" click */
			case 65:
			{
				if (!ctrlClick) { showAbout(); }
				break;
			}
		
			/* "v" click */
			case 86:
			{
				if (!ctrlClick) { showViewAll(); }
				break;
			}
		
			/* "c" click */
			case 67:
			{
				if (!ctrlClick) { showContacts(); }
				break;
			}
		
			/* "i" click */
			case 73:
			{
				toggleInfo();
				break;
			}
		
			/* Space click */
			case 32:
			{
				if ($(".overlay").length == 0)
				{
					toggleSpace();
				}

				break;
			}
		
			/* Esacpe click */
			case 27:
			{
				if ($(".overlay").length > 0)
				{
					$.history.load(currentPhotoID);
				}
				else
				{
					hideInfo();	
				}

				break;
			}
		
			/* Left arrow click */
			case 37:
			{
				if ($("#viewAll").length > 0)
				{
					changeViewAllPhotoPosition(viewAll_currentPhoto - 1, true);
				}
				else
				{
					prevPhoto();
				}

				break;
			}
		
			/* Right arrow click */
			case 39:
			{
				if ($("#viewAll").length > 0)
				{
					changeViewAllPhotoPosition(viewAll_currentPhoto + 1, true);
				}
				else
				{
					nextPhoto();
				}

				break;
			}
		
			/* Up arrow click */
			case 38:
			{
				if ($("#viewAll").length > 0)
				{
					changeViewAllAlbumPosition(viewAll_currentAlbum - 1);
				}
				else
				{
					prevAlbum();
				}

				break;
			}
		
			/* Down arrow click */
			case 40:
			{
				if ($("#viewAll").length > 0)
				{
					changeViewAllAlbumPosition(viewAll_currentAlbum + 1);
				}
				else
				{
					nextAlbum();
				}

				break;
			}

			/* Enter click */
			case 13:
			{
				if ($("#viewAll").length > 0)
				{
					$.history.load($("#viewAll .albumContainer:eq("+(viewAll_currentAlbum-1)+")").find(".photoThumb:eq("+(viewAll_currentPhoto-1)+")").parent().attr("name"));
				}

				break;	
			}

			/* Home click */
			case 36:
			{
				if ($("#viewAll").length > 0)
				{
					changeViewAllPhotoPosition(1, true);
				}

				break;
			}

			/* End click */
			case 35:
			{
				if ($("#viewAll").length > 0)
				{
					changeViewAllPhotoPositionToEnd();
				}

				break;
			}
		}
	}
});

/* Main functions */	
function handleResize()
{
	if ($(".photoContainer").length > 0)
	{
		var resizeFactor_X = 1.0,
			resizeFactor_Y = 1.0,
			newPhotoHeight = 0,
			newPhotoWidth = 0,
			pictureTolerance = 10,
			minimumHeight = 340,
			additionalHeight = $("header.center").outerHeight(true) + $(".topButtons").outerHeight(true) + $(".bottomButtons").outerHeight(true) + pictureTolerance;

		$(".photo").css("height", "auto");
		originalPhotoHeight = $(".photo").height();
		originalPhotoWidth = $(".photo").width();

		/* How many times the window is bigger than the original photo */
		resizeFactor_X = windowWidth / originalPhotoWidth;
		resizeFactor_Y = windowHeight / originalPhotoHeight;

		/* Calculates the new photo size */
		newPhotoHeight = Math.floor((Math.min(resizeFactor_X, resizeFactor_Y)*originalPhotoHeight)) - additionalHeight;
		newPhotoWidth = (newPhotoHeight / originalPhotoHeight) * originalPhotoWidth;
	
		/* Minimum height check */
		if (newPhotoHeight < minimumHeight)
		{
			newPhotoHeight = minimumHeight;
			newPhotoWidth = (minimumHeight / originalPhotoHeight) * originalPhotoWidth;
		}
	
		/* If the window is bigger than the original photo, stops resizing it to preserve photo quality */
		if ((newPhotoHeight >= originalPhotoHeight) && (newPhotoWidth >= originalPhotoWidth))
		{
			newPhotoHeight = originalPhotoHeight;
			newPhotoWidth = originalPhotoWidth;
		}
	
		/* Sets the new photo size */
		$(".photo").css({ height: Math.round(newPhotoHeight) });
	
		/* Sets the new photo containers size */
		$(".center").css({width : Math.round(newPhotoWidth) });
	
		/* If the photo is too small, stops resizing the header container */
		if (newPhotoWidth < 500)
		{
			$("header.center").css({width: 500});
		}
	
		/* Checks if the information container exists */
		if ($("#infoContainer").length > 0)
		{
			/* Checks if the container is smaller than the photo */
			if (($("#infoContainer").outerHeight(true) > newPhotoHeight) || ($("#infoContainer").outerWidth(true) > newPhotoWidth))
			{
				$("#infoContainer").hide();
			}
			else
			{
				$("#infoContainer").show();
			}
		}
		
		var arrowsMargin = Math.round((newPhotoHeight - $(".photoArrows").find("span.button").outerHeight()) / 2);
		
		$(".photoArrows").css("margin-top", arrowsMargin);
	}

	if ($(".overlay").length > 0)
	{
		$(".overlay").css({"min-height" : windowHeight - $("header.center").outerHeight(true)});
	}
	
	if ($("#viewAll").length > 0)
	{
		changeViewAllAlbumPosition(viewAll_currentAlbum);
		
		$("#viewAll .albumContainer").each(function()
		{
			var photosContainerWidth = $(this).find(".albumDataContainer:eq(0)").outerWidth(true), tolerance = 200;
			
			$(this).find("img").each(function()
			{
				photosContainerWidth += $(this).outerWidth(true);
			});
			
			
			if (photosContainerWidth+tolerance < windowWidth)
			{
				$(this).find(".horScrollArrows").hide();
			}
			else
			{
				$(this).find(".horScrollArrows").show();
			}
			
		});
	}
}

function changeViewAllAlbumPosition(newPosition)
{
	var newContainer = $("#viewAll .albumContainer:eq("+(newPosition-1)+")");

	if (newContainer.length > 0)
	{
		$("#viewAll .albumContainer").removeClass("current");

		newContainer.addClass("current");

		viewAll_oldPositions[viewAll_currentAlbum - 1] = viewAll_currentPhoto;

		viewAll_currentAlbum = newPosition;

		changeViewAllPhotoPosition(viewAll_oldPositions[newPosition-1], false);

		/* Scrolling events */
		
		/* Scrolls if needed */
		
		var scrollOffset = newContainer.offset().top;
	
		if ((scrollOffset > windowHeight - newContainer.height()) || (scrollOffset < $("#scrollWrapper").scrollTop()))
		{
		//TODO
			$("#scrollWrapper").stop().animate({ scrollTop: scrollOffset + newContainer.height() }, 250);
		}
	}
}

function changeViewAllPhotoPosition(newPosition, move)
{
	var newContainer = $("#viewAll .albumContainer:eq("+(viewAll_currentAlbum-1)+")").find(".photoThumb:eq("+(newPosition-1)+")");
	
	if (newContainer.length > 0)
	{
		$("#viewAll .albumContainer .photoThumb").removeClass("current");

		newContainer.addClass("current");

		/* Scrolling part */
		if (move)
		{
			var photosContainerWidth = $("#viewAll .albumContainer:eq("+(viewAll_currentAlbum-1)+")").find(".albumDataContainer").outerWidth(true),
				centerWidth = $("#viewAll .center").width();

			$("#viewAll .albumContainer:eq("+(viewAll_currentAlbum-1)+")").find("img").each(function()
			{
				photosContainerWidth += $(this).outerWidth(true);
			});

			if (photosContainerWidth > centerWidth)
			{
				var newMargin = 0,
					leftWidth = $("#viewAll .albumContainer:eq("+(viewAll_currentAlbum-1)+")").find(".albumDataContainer").outerWidth(true),
					gt = 0;

				$("#viewAll .albumContainer:eq("+(viewAll_currentAlbum-1)+")").find(".photoThumb:lt("+(newPosition-1)+")").each(function()
				{
					newMargin -= $(this).outerWidth(true);
				});

				if (newPosition < viewAll_currentPhoto) { gt = newPosition - 1; }
				if (newPosition > viewAll_currentPhoto) { gt = viewAll_currentPhoto - 1; }

				$("#viewAll .albumContainer:eq("+(viewAll_currentAlbum-1)+")").find(".photoThumb:gt("+(gt)+")").each(function()
				{
					leftWidth += $(this).outerWidth(true);
				});

				if (leftWidth >= centerWidth)
				{
					$("#viewAll .albumContainer:eq("+(viewAll_currentAlbum-1)+") .scrollContainer").animate({ marginLeft : newMargin}, 250);
				}
			}
		}

		/* Updates the current position */
		viewAll_currentPhoto = newPosition;
	}
}

function changeViewAllPhotoPositionToEnd()
{
	var firstPass = 0,
		tempWidth = 0,
		count = $("#viewAll .albumContainer:eq("+(viewAll_currentAlbum-1)+")").find(".photoThumb").length,
		centerWidth = $("#viewAll .center").width();

	$("#viewAll .albumContainer:eq("+(viewAll_currentAlbum-1)+")").find(".photoThumb").reverse().each(function()
	{
		tempWidth += $(this).outerWidth(true);
		
		if (tempWidth < centerWidth)
		{
			firstPass++;
		}
	});

	/* First moves to the last moving spot ( first pass and the changes the cursor to the last element */
	changeViewAllPhotoPosition(count-firstPass, true);
	changeViewAllPhotoPosition(count, false);
}

function viewAllSelectCurrentPhoto()
{
	if (currentPhotoID > 0)
	{
		var currentPhoto = $("#viewAll .scrollContainer").find("a[name="+currentPhotoID+"]"),
			albumID = currentPhoto.parents(".albumContainer").index("#viewAll .albumContainer"),
			photoID = currentPhoto.index("#viewAll .albumContainer:eq("+albumID+") a[class != horScrollLinks]"),
			centerWidth = $("#viewAll .center").width();
			
		changeViewAllAlbumPosition(albumID+1);
			
		var firstPass = 0,
			tempWidth = $("#viewAll .albumContainer:eq("+(albumID)+")").find(".albumDataContainer").outerWidth(true),
			count = $("#viewAll .albumContainer:eq("+(albumID)+")").find(".photoThumb").length;

		$("#viewAll .albumContainer:eq("+(albumID)+")").find(".photoThumb").reverse().each(function()
		{
			tempWidth += $(this).outerWidth(true);
		
			if (tempWidth < centerWidth)
			{
				firstPass++;
			}
		});

		if ((photoID+1) > count-firstPass)
		{
			changeViewAllPhotoPosition(count-firstPass, true);
			changeViewAllPhotoPosition(photoID+1, false);
		}
		else
		{
			changeViewAllPhotoPosition(photoID+1, true);
		}
	}
}

function handleHistory(hash)
{
	if (hash != "")	
	{
		if ((hash == "about") || (hash == "contacts") || (hash == "view-all"))
		{
			showOverlayPage(hash);
		}
		else
		{
			loadPhoto(hash);
		}
	}
}

/* Buttons functions */

function hideInfo()
{
	info = false;
	
	$("#info").fadeOut("fast");
}

function showInfo()
{
	info = true;
	
	$("#info").fadeIn("fast");
}

function toggleInfo()
{
	if (info)
	{
		hideInfo();
	}
	else
	{
		showInfo();
	}
}

function toggleSpace()
{
	if (inSpace)
	{
		$("html, body").css("background-color", "#f6f6f6");
		
		$("header, .topButtons, .bottomButtons, .photoArrows").css("visibility", "visible");

		$("#gotoSpace").show();
		$("#outofSpace").hide();
		
		$(".photo").css({"-webkit-box-shadow" : "0 0 3px #ccc", "-moz-box-shadow" : "0 0 3px #ccc", "box-shadow" : "0 0 3px #ccc"});

		if ($(".ajaxLoader").length > 0 ) { $(".ajaxLoader").attr("src", "/images/ajax-loader.gif"); }
	}
	else
	{
		$("html, body").css("background-color", "#090909");
		
		$("header, .topButtons, .bottomButtons, .photoArrows").css("visibility", "hidden");
		
		$("#gotoSpace").hide();
		$("#outofSpace").show();
		
		$(".photo").css({"-webkit-box-shadow" : "0 0 3px #000", "-moz-box-shadow" : "0 0 3px #000", "box-shadow" : "0 0 3px #000"});

		if ($(".ajaxLoader").length > 0 ) { $(".ajaxLoader").attr("src", "/images/ajax-loader-b.gif"); }
	}
	
	inSpace = !inSpace;
}

function showOverlayPage(page)
{
	$(".overlay").remove();
	$("#arrowKeys").hide();
	$(".photoContainer").remove();
	$(".topButtons").remove();
	$(".bottomButtons").remove();
	$("header").css("width", "850px");

	$.ajax({
		url : ajaxUrl,
		type : "POST",
		data : "page="+page,
		beforeSend : function()
		{
			if (inSpace)
			{
				$("header").after('<img src="/images/ajax-loader-b.gif" class="ajaxLoader" />');
			}
			else
			{
				$("header").after('<img src="/images/ajax-loader.gif" class="ajaxLoader" />');
			}
		},
		success : function(response)
		{
			$(".ajaxLoader").remove();

			/* Appends the content */
			$("header").after(response);

			/* Makes nice show effect */			
			$(".overlay").hide().slideDown(function()
			{
				handleResize();
				
				if ((currentPhotoID > 0) && (currentPhotoID != "undefined"))
				{
					viewAllSelectCurrentPhoto();
				}
			});

			if ($("#viewAll").length > 0)
			{
				$("#viewAll .photosContainer a").each(function()
				{
					$(this).attr("href", "#"+$(this).attr("name"));
				});
	
				var albumsCount = $("#viewAll .albumContainer").length;

				for (var i = 0; i < albumsCount; i++)
				{
					viewAll_oldPositions[i] = 1;
				}

				viewAll_currentPhoto = 1;

				changeViewAllAlbumPosition(1);
				
				if ((currentPhotoID > 0) && (currentPhotoID != "undefined"))
				{
					viewAllSelectCurrentPhoto();
				}
			}

			if (inSpace) { toggleSpace(); }

			$("#close a").attr("href", "#"+currentPhotoID);
			$("#close").show();
		}
	});
}

function showAbout()
{
	$.history.load("about");
}

function showContacts()
{
	$.history.load("contacts");
}

function showViewAll()
{
	$.history.load("view-all");
}

var hideTimer;

function loadPhoto(photoID)
{
	$(".overlay").remove();
	$(".photoContainer").remove();
	$(".topButtons").remove();
	$(".bottomButtons").remove();

	$.ajax({
		url : ajaxUrl,
		type : "POST",
		data : "photo="+photoID,
		beforeSend : function()
		{
			if (inSpace)
			{
				$("header").after('<img src="/images/ajax-loader-b.gif" class="ajaxLoader" />');
			}
			else
			{
				$("header").after('<img src="/images/ajax-loader.gif" class="ajaxLoader" />');
			}
		},
		success : function(response)
		{
			$(".ajaxLoader").remove();

			$("header").after(response);

			$(".photo").hide();
			$(".photoContainer").css("visibility", "hidden");
			if (!inSpace)
			{
				$(".topButtons, .bottomButtons").css("visibility", "hidden");
			}

			$("#arrowKeys").show();

			if ($(".photoArrows#left a").attr("name") == "") { $(".photoArrows#left a").remove(); } else { $(".photoArrows#left a").attr("href", "#"); }
			if ($(".photoArrows#right a").attr("name") == "") { $(".photoArrows#right a").remove(); } else { $(".photoArrows#right a").attr("href", "#"); }
			if ($(".albumArrows#down a").attr("name") == "") { $(".albumArrows#down a").remove(); } else { $(".albumArrows#down a").attr("href", "#"); }
			if ($(".albumArrows#up a").attr("name") == "") { $(".albumArrows#up a").remove(); } else { $(".albumArrows#up a").attr("href", "#"); }

			if (!info)
			{
				if (!albumChange)
				{
					$("#info").hide();
				}
				else
				{
					window.clearTimeout(hideTimer);
					hideTimer = window.setTimeout(function() { $("#info").fadeOut(); }, 3000);
				}
			}

			$("#close").hide();
		
			albumChange = false;

			currentPhotoID = photoID;

			if (inSpace)
			{
				$("html, body").css("background-color", "#090909");
		
				$("header, .topButtons, .bottomButtons, .photoArrows").css("visibility", "hidden");
		
				$("#gotoSpace").hide();
				$("#outofSpace").show();
		
				$(".photo").css({"-webkit-box-shadow" : "0 0 3px #000", "-moz-box-shadow" : "0 0 3px #000", "box-shadow" : "0 0 3px #000"});
			}

			/* Resizes after photo load (FIX for not resizing images on slow connection) */
			$(".photo").unbind("load");
			$(".photo").load(function()
			{
				$(".photo").show();

				handleResize();

				$(".photoContainer").css("visibility", "visible").hide().fadeIn(250);
				if (!inSpace)
				{
					$(".topButtons, .bottomButtons").css("visibility", "visible").hide().fadeIn(250);
				}
			});
		}
	});
}

function nextPhoto()
{
	if ($(".overlay").length == 0)
	{
		var nextPhotoID = $(".photoArrows#right a").attr("name");

		if ((nextPhotoID > 0) && (nextPhotoID != 'undefined'))
		{
			$.history.load(nextPhotoID);
		}
		else
		{
			if (inSpace)
			{
				toggleSpace();
			}
		}
	}
}

function prevPhoto()
{
	if ($(".overlay").length == 0)
	{
		var prevPhotoID = $(".photoArrows#left a").attr("name");

		if ((prevPhotoID > 0) && (prevPhotoID != 'undefined'))
		{
			$.history.load(prevPhotoID);
		}
		else
		{
			if (inSpace)
			{
				toggleSpace();
			}
		}
	}
}

function nextAlbum()
{
	if ($(".overlay").length == 0)
	{
		var nextPhotoID = $(".albumArrows#down a").attr("name");

		if ((nextPhotoID > 0) && (nextPhotoID != 'undefined'))
		{
			albumChange = true;

			$.history.load(nextPhotoID);
		}
	}
}

function prevAlbum()
{
	if ($(".overlay").length == 0)
	{
		var prevPhotoID = $(".albumArrows#up a").attr("name");

		if ((prevPhotoID > 0) && (prevPhotoID != 'undefined'))
		{
			albumChange = true;

			$.history.load(prevPhotoID);
		}
	}
}
