var requestProgress = false;
var lastChatID = 0;

$(document).ready(function() {

  $("#minichat form").submit(function() {
    $("#minichat input").attr("disabled", "disabled");
    var pText = $("#minichat input").val();
    $.post("mini/chat_post.php", {text: pText}, function() {
      $("#minichat input").removeAttr("disabled");
      $("#minichat input").focus();
      $("#minichat input").val("");
    });
    return false;
  });
  
  if($("#minichat").length > 0) {
    fetchChats();
    setInterval(function() { fetchChats(); }, 5000);
  }
  
});

function fetchChats() {
  if(requestProgress == true) return false;
  else requestProgress = true;
  $.post("mini/chat.php", {lastid: lastChatID}, function(data) {
    requestProgress = false;
    chatRequests = data;
    if(chatRequests.allowed == 0) {
      $("#minichat div").html("<span class=\"error\">You don't have access to the chat at this time.</span>");
      requestProgress = 0;
      return true;
    } else {
      if(chatRequests.chatsnr > 0) {
        $.each(chatRequests.chats, function(i,chat) {
          elementHTML = "<span>";
          elementHTML += chat.ctext + "<br />";
          elementHTML += "<a href=\"profile.php?id=" + chat.user + "\">"+ chat.uname + " (#" + chat.user + ")</a>";
          elementHTML += "</span>";
          
          if(lastChatID == 0) {
            $("#minichat div").append(elementHTML);
          } else {
            $("#minichat div span:last").remove();
            $("#minichat div span:first").before(elementHTML);
          }
          
        });
        lastChatID = chatRequests.lastChatID;
      }
    }
  }, "json");
}

