
var shoutbox    = document.getElementById('shoutbox');
var shouttext   = document.getElementById('shouttext');
var shoutbutton = document.getElementById('shoutbutton');
var lastupdate  = 0;
var updatetime  = 1000; // update every 1 second
var name        = null;

// this file will handle the fn calls
fn_url   = 'shoutbox.php';
fn_debug = false;

// make the width of the shoutbox equal to the width of the input field + the button
shoutbox.style.width  = parseInt(shouttext.offsetWidth) +
                        parseInt(shoutbutton.offsetWidth) + 'px';
shoutbox.style.height = '200px';

shoutbox.value = '';
shouttext.value = 'click here to join...';
setTimeout(update, 10);


shouttext.onfocus = function() {
  if (name == null) {
    name = prompt('enter your display name', '');
    
    if (name == null) {
      shouttext.blur();
    } else {
      fn_call('event', false, name, 'joined the shoutbox');

      shouttext.value = '';
      shouttext.focus();
    }
  }
}


window.onunload = function() {
  if (name != null) {
    fn_url = 'shoutbox.php';
    fn_call('event', false, name, 'left the shoutbox');

    // withoud this the fn_call will fail
    alert('leaving shoutbox...');
  }
}


function shout() {
  var str = shouttext.value;
  
  if (str != '') {
  
    if (str == '/clear') {
      shoutbox.value = '';
    }
    
    else if ((str.indexOf('/name') == 0) ||
             (str.indexOf('/nick') == 0)) {
      var oldname = name;
      name = prompt('enter your display name', '');

      if (name == null) {
        name = oldname;
      } else if (name != oldname) {
        fn_call('event', false, oldname, 'changed his name to: '+name);
      }
    }
    
    else {
      fn_call('shout', false, name, shouttext.value);

      // stop people from speaking to fast
      shoutbutton.disabled = true;
      setTimeout('shoutbutton.disabled = false;', 500);
    }
    
    shouttext.value = '';
  }
}


function updateresult(arr) {
  lastupdate = arr[0];
  arr        = arr[1];

  for (var i = arr.length - 1; i >= 0; i--) {
    shoutbox.value += '\n' + arr[i];
  }

  // change the update time if there is nothing heapening
  if (arr.length == 0) {
    updatetime += (updatetime > 5000) ? 0 : 500; // max 5 sec
  } else {
    // scroll to the bottom
    shoutbox.scrollTop = shoutbox.scrollHeight * 25; // IE fix
    updatetime = 1000;
  }

  setTimeout(update, updatetime);
}


function update() {
  fn_call('update', updateresult, lastupdate);
}

