<?
ob_start();
include("header.php");

$error = false;
if ($_POST)
{
  if (trim($_POST['username']) == '')
  {
    $error = "You must enter your username (email).";
  }
  else if (trim($_POST['password']) == '')
  {
    $error = "You must enter your password.";
  }
  else
  {
    $id = get_id_by_username_password($_POST['username'], $_POST['password']);
    if ($id > 0)
    {
      $_SESSION['user_id'] = $_s_user_id = $id;
      $_SESSION['admin'] = user_is_admin($id);
      if ($_SESSION['last_page'])
        header("Location:".$_SESSION['last_page']);
      else
        header("Location:home.html");
      $_SESSION['return'] = null;
    }
    else
    {
      $error = "Invalid username (email) / password pair.";
    }
  }
}
ob_flush();
?>

<? if (!$_POST || $error) { ?>
<?   if ($error) { ?>
<div class="error"><?=$error?></div>
<?   } else { ?>
<h1 class="title">log in</h1>
<?   } ?>
<br>
<script type="text/javascript" src="javascript/user-util.js"></script>
<form action="login.html" method="post">
  <table align="center">
    <tr>
      <td>Username (Email)</td>
      <td>
        <input type="text" size="50" name="username" value=""
               onblur="email_addr.ensure_valid(this)"
               onmouseout="email_addr.ensure_valid(this)">
      </td>
    </tr>
    <tr>
      <td>Password</td>
      <td><input type="password" size="50" name="password"></td>
    </tr>
    <tr>
      <td></td>
      <td><input type="submit" value="Log In"></td>
    </tr>
  </table>
  <input type="hidden" name="submitted" value="true">
</form>

<div class="info">
  Or, register as a player
  <a href="user.html" class="dlink">here</a>.
</div>

<script type="text/javascript">
  // Gives the name field focus.
  document.getElementsByName('username')[0].focus();
</script>

<? } ?>
<? include("footer.php"); ?>

