// global variables
var count = 0;          //  simple counter
var delay = 30;         //  set initial refresh timeout to 30 seconds
// functions
function getmessages(chatroom) {
  loadXMLDoc('chatmsg.php', 'chatroom=' + chatroom);
  if (count++ == 0) loadXMLDoc('chatmsg.php', 'chatroom=' + chatroom); // needed for scroller
  setTimeout('getmessages(\'' + chatroom + '\')', delay * 1000);
  if (delay <= 25)  delay += 5;    //  increment refresh timeout by 5 seconds
}
function sendmessage(chatroom) {
  var message    = document.getElementById('message');
  var screenname = document.getElementById('screenname');
  if (screenname.value.length == 0)               // input error checking
    alert('Your Screen Name must first be defined.');
  else if (screenname.value.length >= 40)         // input error checking
    alert('Your Screen Name must be less than 40 characters.');
  else if (message.value.length  >= 2048)         // input error checking
    alert('Your message must be less than 2048 characters.');
  else if (message.value.length > 0) {
    loadXMLDoc('chatmsg.php', 'chatroom=' + chatroom + '&' +
      'screenname=' + screenname.value + '&' + 'message=' + message.value);
    message.value = '';  // clear the input text field
    message.focus();     // reset focus to the input text field
    delay = 5;           // set refresh timeout to 5 seconds
  }
}
function clearmessage(chatroom) {
  loadXMLDoc('chatmsg.php', 'chatroom=' + chatroom + '&' + 'clear=yes');
}
function loadXMLDoc(url, querystring) {
  var xmlhttp = null;  
  if      (window.XMLHttpRequest) xmlhttp = new XMLHttpRequest();
  else if (window.ActiveXObject)  xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
  if (xmlhttp != null) {
    xmlhttp.onreadystatechange = function() {
      if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { // 4 = loaded, 200 = "OK"
        var chatbox = document.getElementById('chatbox');     // find <div id="chatbox">
        chatbox.innerHTML = xmlhttp.responseText;             // replace HTML with URL download
        chatbox.scrollTop = chatbox.scrollHeight;             // set the scroller to the bottom
      }
    }
    xmlhttp.open('POST', url, true);
    xmlhttp.setRequestHeader('Content-type',   'application/x-www-form-urlencoded');
    xmlhttp.setRequestHeader('Content-length', querystring.length);
    xmlhttp.setRequestHeader('Connection',     'close');
    xmlhttp.send(querystring);
  } else alert('Your browser does not support XMLHTTP.');
}

