window.onload = initJavaScript;
var maxid=-1;

function initJavaScript() {
	document.forms['myform'].elements['comment'].setAttribute('autocomplete','off'); //this non standard attribute prevents firefox' autofill function to clash with this script
	
	checkupdate();
	whoIsOnline();
	}    
	
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;
}

function setCookie(c_name,value,expiredays)
{
var exdate=new Date();
exdate.setDate(exdate.getDate()+expiredays);
document.cookie=c_name+ "=" +escape(value)+
((expiredays==null) ? "" : ";expires="+exdate.toGMTString());
}
function getCookie(c_name)
{
if (document.cookie.length>0)
  {
  c_start=document.cookie.indexOf(c_name + "=");
  if (c_start!=-1)
    {
    c_start=c_start + c_name.length+1;
    c_end=document.cookie.indexOf(";",c_start);
    if (c_end==-1) c_end=document.cookie.length;
    return unescape(document.cookie.substring(c_start,c_end));
    }
  }
return "";
}
//document.write(document.cookie);
  var httprx = getHTTPObject();
  var httpsx = getHTTPObject();
  var httponline =getHTTPObject();
  var xid_new = "";
  var currentChatText ="";
  var lastChatText= "";
  var sendmsg=0;
  var onlineList=0;
  var sortname="all";
  var sorttoname="all";
  var sound3Embed = null;	
  var sound1Frame = null;
//document.forms['myform'].elements['name'].value=getCookie("name");
//document.forms['myform'].elements['toname'].value=getCookie("toname");
//Math.floor(Math.random()*11)
document.forms['myform'].elements['name'].value = (getCookie("name")=="") ? "guest_g"+(Math.floor(Math.random()*899)+100): getCookie("name");
document.forms['myform'].elements['toname'].value=(getCookie("toname")=="") ? "David Toth": getCookie("toname");

function sortComments()
{
maxid=-1;
if (document.forms['myform'].elements['sort'].checked==true) {
sortname=document.forms['myform'].elements['name'].value;
sorttoname=document.forms['myform'].elements['toname'].value;
} else {sortname="all"; sorttoname="all";}
document.getElementById("chattable").innerHTML="";
checkupdate();
}
		function sound1Play() {
				if ( !sound1Frame ) {
					sound1Frame = document.createElement("iframe");
					sound1Frame.src = "frame.html";
					sound1Frame.width = 0;
					sound1Frame.height = 0;
					sound1Frame.style.visibility = "hidden";
				}
				document.body.appendChild(sound1Frame);
			}
			
			function sound1Stop() {
				if ( sound1Frame ) document.body.removeChild(sound1Frame);
			}					
function sound3Play() {
				sound3Stop();
				sound3Embed = document.createElement("embed");
				sound3Embed.setAttribute("src", "pop.wav");
				sound3Embed.setAttribute("hidden", true);
				sound3Embed.setAttribute("autostart", true);
				document.body.appendChild(sound3Embed);
			}
			function sound3Stop() {
				if ( sound3Embed ) {
					document.body.removeChild(sound3Embed);
					sound3Embed = null;
				}
			}
function sendComment() {
	currentChatText = document.forms['myform'].elements['comment'].value;
if (currentChatText==lastChatText) {document.forms['myform'].elements['comment'].value="";
insertNewContent("error","unknown","unknown","tothchat ",document.forms['myform'].elements['name'].value," We are sorry. We do not allow to send the same comment twice.");}
else if (document.forms['myform'].elements['comment'].value != '') {sendComment2();} 
}
function sendComment2()
{
   if (httpsx.readyState == 4 || httpsx.readyState == 0) {
		currentName = document.forms['myform'].elements['name'].value;
		toName = document.forms['myform'].elements['toname'].value;
		setCookie("name",currentName,360);
		setCookie("toname",toName,360);
		
		param = 'n='+ currentName+'&c='+ currentChatText+'&tn='+toName;	
		httpsx.open("POST", "add.php", true);
		httpsx.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
  	httpsx.onreadystatechange = checkupdate();
  	httpsx.send(param);
   lastChatText=currentChatText;
  	document.forms['myform'].elements['comment'].value = '';
	} 
	else {setTimeout('sendComment();',1000);}
}

function checkupdate()
{
//document.getElementById("test").firstChild.nodeValue+=httprx+"x";
	if(httprx.readyState==4 || httprx.readyState==0)
   {
   time=Math.round(new Date().getTime()/1000);
   httprx.open("GET","get.php?time="+time+'&id='+maxid+'&sn='+sortname+'&stn='+sorttoname,true);
   httprx.onreadystatechange=handlehHttpReceiveChat;
   httprx.send(null);
	}
}
//document.musicApp.beep();
function handlehHttpReceiveChat() {
  if (httprx.readyState == 4) 
  {
    results = httprx.responseText.split('---'); //the fields are seperated by ---
    //document.getElementById("test").firstChild.nodeValue+=results.length+"*"+results[369]+"*";
    if (results.length > 5) {
    //document.getElementById("test").firstChild.nodeValue+=results.length+"*";
    maxid=results[0];
	    //for(i=0;i < (results.length-1);i=i+6) { //goes through the result one message at a time
	    for(i=results.length-7;(i > -1);i=i-6) {
	    //document.getElementById("test").firstChild.nodeValue+=i+",";
	    	insertNewContent(results[i],results[i+1],results[i+2],results[i+3],results[i+4],results[i+5]); //inserts the new content into the page
	    	
	    }
	    if (document.forms['myform'].elements['sound'].checked==true) {sound1Play();}
	    
	 
	 }
	  setTimeout('checkupdate();',2000);
    //setTimeout('receiveChatText();',4000); //executes the next data query in 4 seconds
  }
 
}

function insertNewContent(id,dt,ip,nickname,tonickname,comment) {

	mydoc = document.getElementById("chattable");
	oTr = document.createElement('tr');
	oTd = document.createElement('td');
	oTd.setAttribute('className','t2'); //for IE's sake
	oTd.setAttribute('class','t2');
	oTd.setAttribute('width','12%');
	oTd2= document.createElement('td');
	if (tonickname=="all ") {oMy4= document.createElement('my4b'); oTd.setAttribute('style','background-color:#dBEE44;');}
	else {oMy4= document.createElement('my4');}
	oDate= document.createTextNode(dt);
	oMy4.appendChild(oDate);
	oTd.appendChild(oMy4);
	oB = document.createElement('b');
	oB.setAttribute('title','No.'+id+' IP:'+ip);
	oBtext = document.createTextNode(nickname);
	oB.appendChild(oBtext);
	oB.setAttribute('onclick',"document.forms['myform'].elements['toname'].value='"+nickname+"';");
	oI = document.createElement('i');
	oI.appendChild(document.createTextNode("--> "));
	oB2=document.createElement('b');
	oB2.appendChild(document.createTextNode(tonickname));
	oB2.setAttribute('onclick',"document.forms['myform'].elements['toname'].value='"+tonickname+"';");
	oText = document.createTextNode(comment);
	if (tonickname=="all ") {oTd2.setAttribute("style","background-color: #bbEE22;");}
	oTd2.appendChild(oB);
	oTd2.appendChild(oI);
	oTd2.appendChild(oB2);
	oTd2.appendChild(oText);
	oTr.appendChild(oTd);
	
	oTr.appendChild(oTd2);
	mydoc.insertBefore(oTr, mydoc.firstChild);
}

function whoIsOnline()
{

	if(httponline.readyState==4 || httponline.readyState==0)
   {
   httponline.open("GET","online.php?user="+document.forms['myform'].elements['name'].value,true);
   httponline.onreadystatechange=handleWhoIsOnline;
   httponline.send(null);
	}
}
function handleWhoIsOnline() {

  if (httponline.readyState == 4) 
  {
 
  if (onlineList!=httponline.responseText) 
  {
  onlineList=httponline.responseText;
  onlineDiv=document.getElementById("online");
  results = onlineList.split('---');
  onlineDiv.innerHTML="<b>ONLINE "+((results.length-1)/2)+"</b>";
     //the fields are seperated by ---
    
    if (results.length > 0) {
	    for(i=0;i < (results.length-1);i=i+2) { //goes through the result one message at a time
	    	oA=document.createElement('a');
	    	if (i==0) {results[i]=results[i].substring(2);}
	      oA.appendChild(document.createTextNode(results[i]));
	      oA.setAttribute('onclick',"document.forms['myform'].elements['toname'].value='"+results[i]+"';");
	      if (results[i+1]==0) {oA.setAttribute("style","color:#008000");}
	    	onlineDiv.appendChild(document.createElement('br'));
	    	onlineDiv.appendChild(oA);
	    	    }}
	 
	}
	//document.getElementById("beep").innerHTML += "<bgsound src=pop.wav>";
	//document.getElementById("beep").write('<EMBED SRC="pop.wav" WIDTH=1 HEIGHT=1 HIDDEN="true" AUTOSTART="true" LOOP="false" volume="100">');
	  setTimeout('whoIsOnline();',2000);
  }
 
}
//sound1Play();
//setInterval("sound1Play();",2000);
//setInterval("checkupdate()",1000);
//alert("last");
