var wyswietl = 30;
var start = "./ajax/chat.php?go=start";
var zapodaj = "./ajax/chat.php?show="+wyswietl+"&id=";
var wsadzij = "./ajax/chat.php";		  
var lastid=0;

window.onload = initJavaScript;

function initJavaScript() {
	start_id();
	SprawdzName();
}

function start_id(){
	if (starto.readyState == 4 || starto.readyState == 0) {
	starto.open("GET",start + '&lastid='+ lastid + '&rand='+Math.floor(Math.random() * 1000000),true);
	starto.onreadystatechange = handleStart_id;
	starto.send(null);
	}
}

function handleStart_id(){
  if (starto.readyState == 4) {
		results = starto.responseText;
		if(results) {
		
		lastid = results;
		zapodaj_to();
		
		}
		setTimeout('start_id();',12000); 
  }
  
}

function zapodaj_to() {
	if (zapodajo.readyState == 4 || zapodajo.readyState == 0) {
  		zapodajo.open("GET",zapodaj+lastid,true);
		zapodajo.onreadystatechange = handleZapodaj_to;
    	zapodajo.send(null);
	}
}

function handleZapodaj_to() {
  if (zapodajo.readyState == 4) {
  	results = zapodajo.responseText.split('---');
	
	document.getElementById("content").innerHTML= results[0];
	lastid = results[1];
  	
  } 
}

function wsadzij_to() {
  Text = document.getElementById("text").value;
  if (Text != '' & (wsadzo.readyState == 4 || wsadzo.readyState == 0)) {
  Name = document.getElementById("name").value;
  PostParameter = 'name='+ Name+'&text='+ Text;
  wsadzo.open("POST", wsadzij, true);
  wsadzo.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
  wsadzo.onreadystatechange = handleWsadz;
  wsadzo.send(PostParameter);
  document.getElementById("text").value = '';
  } else {
		setTimeout('zapodaj_to();',1000); 
  }
}

function handleWsadz() {
  if (wsadzo.readyState == 4) {
  	start_id(); 
  }
}

function SprawdzName(){
	losowyName = document.forms['chat'].elements['name'];
	if (losowyName.value == '') {
		losowyName.value = 'nick'+ Math.floor(Math.random() * 10000);
	}
}

function getHTTPObject() {
  var xmlhttp;
  /*@cc_on
  @if (@_jscript_version >= 5)
    try {
      xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
      try {
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
      } catch (E) {
        xmlhttp = false;
      }
    }
  @else
  xmlhttp = false;
  @end @*/
  if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
    try {
      xmlhttp = new XMLHttpRequest();
    } catch (e) {
      xmlhttp = false;
    }
  }
  return xmlhttp;
}
var wsadzo = getHTTPObject(); 
var zapodajo = getHTTPObject();  
var starto = getHTTPObject();