// Zmienne globalne
var commentCount = 0;
var xmlhttp;

function yellowColor(val) {
   var r="ff";
   var g="ff";
   var b=val.toString(16);
   var newval = "#"+r+g+b;
   return newval;
}

aaManageEvent(window,"load", function() {
  aaManageEvent(document.getElementById('save'),"click",saveComment);

});

function saveComment(evnt) {
 
  // Anuluje zdarzenie
  evnt = evnt ? evnt : window.event;
  aaCancelEvent(evnt);

  // Tworzenie obiektu XHR
  if (!xmlhttp) xmlhttp = aaGetXmlHttpRequest();
  if (!xmlhttp) return;

  // Pobieranie komentarza
  var commentText = document.getElementById("comment").value;
  modText = commentText.split(/\n/).join("<br />");
  var param = "comment=" + modText;
  var url = 'addcomment.php?' + param;
  xmlhttp.open('POST', url, true);

  // Wysyłanie komentarza
  xmlhttp.onreadystatechange = addComment;
  xmlhttp.setRequestHeader('Content-Type',
    'application/x-www-form-urlencoded');
  xmlhttp.send(null);
  return false;
}

// Dodawanie komentarza do listy z wyróżnieniem za pomocą koloru
function addComment() {
  if(xmlhttp.readyState == 4 && xmlhttp.status==200) {
      var modText=xmlhttp.responseText;
      var newDiv = document.createElement("div");
      commentCount++;
      newDiv.setAttribute("id","div"+commentCount);
      newDiv.setAttribute("class","comment");
      newDiv.innerHTML = modText;

      // Dodawanie obiektu do strony
      document.getElementById("list").appendChild(newDiv);

      // Uruchomienie licznika do zmiany kolorów 
      var ctrObj = new Counter("div"+commentCount,0,255);
      ctrObj.countDown();
   }
}

function Counter(id,start,finish) {
   this.count = this.start = start;
   this.finish = finish;
   this.id = id;
   this.countDown = function() {
      this.count+=25;
      if (this.count >= this.finish) {
         document.getElementById(this.id).style.background="transparent";
         this.countDown=null;
         return;
      }
      document.getElementById(this.id).style.backgroundColor=yellowColor(this.count);
      setTimeout(aaBindEventListener(this,this.countDown),100);
   }
}

aaManageEvent(window,"load",function() {
      aaManageEvent(document.getElementById('comment'),"keyup",echoPreview)});

function echoPreview(evnt) {
   var commentText = document.getElementById("comment").value;
   modText = commentText.split(/\n/).join("<br />");
   var previewElem = document.getElementById("preview");
   previewElem.innerHTML = modText;
}

