<?php
require_once('./config.php');

$user = $_POST['user'];
$message = stripslashes($_POST['message']);
if ($user && $message) {
    if ($user != $_COOKIE['name']) {
        talk($config['chat_file'], $_COOKIE['name'], "switching to $user");
        setcookie('name', $user);
    }
    talk($config['chat_file'], $user, $message);
    $focus = "message";
} else {
    $focus = "user";
}

function talk($file, $user, $message) {
    $fh = fopen($file, "a")
        or die("Could not open '$file' to append");
    fwrite($fh, "$user: $message\n")
        or die("Could not write to '$file'");
}

?>
<head>
<style>
body {
 margin: 3;
}
</style>
<script type="text/javascript" src="chat.js"></script>
<script type="text/javascript">
    function init() {
        document.forms['talk'].<?= $focus ?>.focus();
        if (!cookieJar.get('name')) {
            var num = (Math.floor(Math.random() * 9000) + 1000).toString();
            cookieJar.set('name', "Guest "+num);
        }
        document.forms['talk'].user.value = cookieJar.get('name');
        var tail = parent.frames['tail'];
        if (tail.location == "about:blank") {
            tail.location = "tail.php";
        }
    }
</script>
</head>
<body onLoad="javascript: init();">
<form method="POST" name="talk">
<table cellspacing=0 cellpadding=0 border=0>
  <tr>
    <td align="right">Your Name&nbsp;</td>
    <td>
       <input type="text" name="user" size=20 value="<?= $_POST['user'] ?>">
    </td>
  </tr>
  <tr>
     <td align="right">Your Message&nbsp;</td>
     <td><input type="text" name="message" size=50 value=""></td>
  </tr>
  <tr>
     <td>&nbsp;</td>
     <td><input type="submit" name="submit"></td>
  </tr>
</table>
</form>
</body>
