var last_update = new Date();
function $(id) {
	return document.getElementById(id);
}
function dateToStr(date) {
  var year = date.getYear();
  if (year < 1000) year += 1900;

  var month = date.getMonth() + 1;
  if(month < 10) month = "0" + month;
  
  var day = date.getDate();
  if (day < 10) day = "0" + day;
  
  var hour = date.getHours();
  if (hour < 10) hour = "0" + hour;

  var min = date.getMinutes();
  if (min < 10) min = "0" + min;

  var sec = date.getSeconds();
  if (sec < 10) sec = "0" + sec;
  
  return "" + year + "-" + month + "-" + day + " " + hour + ":" + min + ":" + sec;
}
function escapeHTML(str) {
    var div = document.createElement('div');
    var text = document.createTextNode(str);
    div.appendChild(text);
    return div.innerHTML;
}
function parseRecords(xml) {

	d = $("dataTable");
	for (i = d.rows.length-1; i >= 0; i--) d.deleteRow(i);
	
	record = xml.getElementsByTagName("POST");
	for (i = 0; i < record.length; i++) {
		tr = document.createElement("tr");
		td = document.createElement("td");
		td.innerHTML = "<img src='images/dymek.gif' class='dymek'/><b>" + record[i].getAttribute("autor") + "</b> (" + record[i].getAttribute("data") + "):<br/> " + record[i].childNodes[0].nodeValue;
		tr.appendChild(td);
		d.appendChild(tr);
	}

}
function initShout() {
	prepareForm();
	last_update = new Date();
	advAJAX.get({
		url : "shout.php",
		onInitialization : function() {
			tr = document.createElement("tr");
			td = document.createElement("td");
			td.innerHTM = 'Pobieranie danych...';
			tr.appendChild(td);
			$("dataTable").appendChild(tr);
		},
		onComplete : function(obj) {
			tr = document.createElement("tr");
			td = document.createElement("td");
			td.innerHTM = '';
			tr.appendChild(td);
			$("dataTable").appendChild(tr);
		},		
		onError : function(obj) {
			tr = document.createElement("tr");
			td = document.createElement("td");
			td.innerHTM = 'Błąd podczas pobierania danych.';
			tr.appendChild(td);
			$("dataTable").appendChild(tr);
		},		
		onSuccess : function(obj) {
			parseRecords(obj.responseXML);
		}
	});	
}
function fetchNewRow() {
	last_update = new Date();
	advAJAX.get({
		url : "shout.php",
		onSuccess : function(obj) {
			parseRecords(obj.responseXML);
		}
	});	
}
function updateShout() {
	advAJAX.get({
		url : "shout.php?a=update&date=" + dateToStr(last_update),
		onSuccess : function(obj) {
			if (obj.responseText == "1")
				fetchNewRow();
		}
	});	
}
function prepareForm() {
	advAJAX.assign($("shoutForm"), {
		onError : function(obj) {
			tr = document.createElement("tr");
			td = document.createElement("td");
			td.innerHTM = 'Błąd podczas wysyłania.';
			tr.appendChild(td);
			$("dataTable").appendChild(tr);
		},		
		onSuccess : function(obj) {
			$("shoutForm").shout_text.value="";
			updateShout();
		}
		
	});
}
setInterval("updateShout()",15000);
