
function UserHandling() { }

UserHandling.current_user_ = null;

UserHandling.init = function()
{
	if (UserHandling.current_user_ == null)
	{
		$('#logoutContainer').hide();
		UserHandling.check_form();
		$('#loginUsername').focus();
	}
	else
	{
		$('#loginContainer').hide();
		$('#logoutName').html(UserHandling.current_user_.Name);
	}
	
	$('#loginUsername').bind("change", function(e) { UserHandling.check_form(); });
	$('#loginPassword').bind("change", function(e) { UserHandling.check_form(); });
	$('#loginUsername').bind("keyup", function(e) { UserHandling.check_form(); });
	$('#loginPassword').bind("keyup", function(e) { UserHandling.check_form(); });
	
	$('#loginForm').bind("submit", function(e)
	{
		e.preventDefault();
	
		if (!UserHandling.check_form())
		{
			return;
		}
	
		$('#loginContainer').hide("slide", { direction: "down" }, function()
		{
			$('#loginMessage').html("");
		
			// Note: This delays login action until slide down animation completes, but it is an easy way of preventing show animation to start before the hide animation has finished
			jQuery.getJSON("functions/login.php?Name=" + $('#loginUsername').attr("value") + "&Password=" + $('#loginPassword').attr("value"), function(data)
			{
				if (data.Status.Success)
				{
					UserHandling.current_user_ = data.Data;
					$('#logoutName').html(UserHandling.current_user_.Name);
					$('#logoutContainer').show("slide", { direction: "down" }, function(e) { $('#logoutSubmit').focus(); });
					update_stuff();
				}
				else
				{
					UserHandling.current_user_ = null;
					$('#loginMessage').html("login failed, " + data.Status.Error.toLowerCase());
					$('#loginContainer').show("slide", { direction: "down" }, function(e) { $('#loginUsername').focus() });
				}
			});
			
			$('#loginPassword').attr("value", "");
			UserHandling.check_form();
		});
	});
	
	$('#logoutSubmit').bind("click", function(e)
	{
		$('#logoutContainer').hide("slide", { direction: "down" }, function()
		{
			jQuery.getJSON("functions/logout.php", function(data)
			{
				UserHandling.current_user_ = null;
				$('#loginContainer').show("slide", { direction: "down" }, function(e) { $('#loginUsername').select(); });
				update_stuff();
			});
		});
	});
}

UserHandling.check_form = function()
{
	if ($('#loginUsername').attr("value") == "" || $('#loginPassword').attr("value") == "")
	{
		$('#loginSubmit').attr("disabled", "disabled");
		return false;
	}
	else
	{
		$('#loginSubmit').removeAttr("disabled");
		return true;
	}
}

