$(document).ready(function(){
  $("form").submit(function(){
    var shout = $("form input").val();
    var liHtml;
    var repeat;
    if (shout.length > 100) {
      $("#page-wrap").prepend("<span id='warning'>You have exceeded 100 characters!</span>");
      $("form input[name=shout]").val("").focus();
      return false;
    } 
    else {
      $("ul#shouts li").each(function(i){
        liHtml = $(this).html();
        if (shout == liHtml) {
         repeat = true;
        }
      });
      if (repeat != true){
        $.post($(this).attr('action'), $(this).serialize(), function(data){
          $("#warning").remove();
          $("ul#shouts").prepend("<li>" + data + "</li>");
          $("ul#shouts li:nth-child(11)").hide();
          $("form input[name=shout]").val("").attr("disabled", "disabled");
          setTimeout('enableShouting()', 10000);
        }, "text");
        return false;        
      }
      else {
        return false;
      }    
    }
  });
  
  $("input[name='shout']").focus();

  setInterval('getShouts()', 10000);
});

function enableShouting(){
  $("form input[name=shout]").removeAttr('disabled');
}

function getShouts(){
  $.get("/recent", '', function(data){
    var newLi = $(data)[0];
    newLi = $(newLi).html();
    var oldLi = $("ul#shouts li:first-child").html();
    if (oldLi != newLi) { $("ul#shouts").html(data).effect("highlight", { color: '#fff' }, 3000); }
  });
}

