// Zmienna globalna
var xmlhttp;

aaManageEvent(window,"load",setUp);

function setUp() {
  aaManageEvent(aaElem('commentform'),"submit",saveComment);
  setInterval(checkNewComment,15000);
}

function checkNewComment() {
  if (!xmlhttp) xmlhttp = aaGetXmlHttpRequest();
  if (!xmlhttp) return;
  xmlhttp.open('GET', 'getcomments.php?post=' + post, true);
  xmlhttp.onreadystatechange = updateComments;
  xmlhttp.send(null);
}

function updateComments() {
  if(xmlhttp.readyState == 4 && xmlhttp.status==200) {
    eval("var polled = " + xmlhttp.responseText);
    for (var i = 0; i < polled.length; i++) {
      var polledId = "div" + polled[i].id;
      var elem = aaElem(polledId);
      if (!elem) { 
         appendComment(polled[i]);     
      }
    }
  }
}

// Zapisuje nowy komentarz
function saveComment(evnt) {
  evnt = (evnt) ? evnt : window.event;
  aaCancelEvent(evnt);
  if (!xmlhttp) xmlhttp = aaGetXmlHttpRequest();
  var commentText = document.getElementById("comment").value;
  modText = commentText.split(/\n/).join("<br />");
  var param = "comment=" + modText;
  xmlhttp.open('POST', 'addComment.php', true);
  xmlhttp.onreadystatechange = addComment;
  xmlhttp.setRequestHeader('Content-Type',
    'application/x-www-form-urlencoded');
  xmlhttp.send(param);
  return false;
}

function addComment() {
  if(xmlhttp.readyState == 4 && xmlhttp.status==200) {
      eval("var newComment = " + xmlhttp.responseText);
      appendComment(newComment);
  }
}

function appendComment(comment) {  
   var newDiv = document.createElement("div");
   var newName = "div"+comment.id;
   newDiv.setAttribute("id",newName);
   newDiv.setAttribute("class","comment");
   newDiv.innerHTML = comment.content;
   aaElem("list").appendChild(newDiv);
   Fat.fade_element(newName,null,800,"#ffff00","#eeeeee"); 
}
