
/******************************************************************

Name script  : chatData
Author       : Michael Böke
Website      : http://www.ly2.nl (blog)
Email        : michael.boke@gmail.com
Licence      : Free to use
Copyright    : Credit me
Date         : 15-09-2006
File         : chatData.js het javascript met de handler van de send en
               get mssg.

Description  : Dit is kale chat script waarmee je je eigen chat box
               kan bouwen. De basis functionaliteiten zitten er in
               send mssg, get mssg en een nickname. Dit script heeft
               geen MySQL database nodig alle data wordt in een bestand
               opgeslagen. Dit log bestand is beveiligd met flock
               tegen gelijktijdig schrijven en er zit functie op dat
               de oude data van bv 3 minuten terug worden verwijderd.
               Zo blijft het log bestand klein en snel. De communicatie
               van het zenden en ontvangen van de laatste berichten
               wordt gedaan met java xmlhttp object gedaan ook wel
               Ajax genoemd in de volksmond. Er wordt iedere 3 sec
               voor nieuwe berichten gecontroleerd.
               
               Ik denk dat je voor dit script wel een redelijke snelle
               server nodig hebt als je veel gebruikers gelijktijdig
               wilt severen. Maar goed het is zelf even proberen.
               
Author Note  : Het script werkt goed maar denk er aan dat je de data 
               wat verzonden wordt naar het script van hmtl tags moet 
               ontdoen. Hiervoor zal je zelf een handler moet schrijven.
               Nu kan je namelijk de html tags en eventueel 
               javascripts sturen en die worden dan ook bij alle 
               gebruikers uitgevoerd die op dat moment in de chat box
               zitten.
               
               Tevens ik zou het leuk vinden als je laat weten als je
               wat met dit script doet en bv. nieuwe functionaliteiten 
               er voor schrijft of wat dan ook laat een comment achter
               op mijn blog site.
Changelog    : Nog geen
    
******************************************************************/ 


function chatData() {
	this.init();
}

chatData.prototype.init = function()
{
  this.timeStamp      = 0;                            //default it set to 0 it will get the current server timestamp upon 1st request
  this.interval       = 3000;                         //interval is 3 sec
  this.getUrl         = 'chat.php?action=getmssg';    //url to get the mssg only
  this.postUrl        = 'chat.php?action=sendmssg';   //url to send a new mssg
  this.httpReqObject  = this.httpObject();            //Create new Ajax object
	this.timerID        = null;                         //The timer id that refres to the interval
	
	this.send( false, false );                          //Get the current timestamp and optional data
	this.start();                                       //Start the service and get new messages each interval
	
}

/* start the service */
chatData.prototype.start = function()
{
  var thisObject = this;
	clearInterval(this.timerID);
	this.timerID = setInterval(function() { thisObject.send( false, false ); }, this.interval);
}

/* stop the service */
chatData.prototype.stop = function()
{
  clearInterval(this.timerID);
}

/* reset the service, same as start */
chatData.prototype.reset = function()
{
  this.start();
}

/* Send a request to the server */
chatData.prototype.send = function( nickname, message )
{
  var thisObject = this;

	if (this.httpReqObject !== null && (this.httpReqObject.readyState === 4 || this.httpReqObject.readyState === 0)) {
  	
  	/* the params need to be urlEncoded */
  	var postData = 'timestamp=' + encodeURIComponent(this.timeStamp);

  	if ( nickname == false || message == false ) {
  	  this.httpReqObject.open( 'POST', this.getUrl, true );
	  } else {
  	  this.reset(); //reset the interval (send request are not done in frequent intervals so the normal interval to get the messages is getting reset)
  	  postData+= '&nickname=' + encodeURIComponent(nickname) + '&mssg=' + encodeURIComponent(message);
  	  this.httpReqObject.open( 'POST', this.postUrl, true );
	  }
		this.httpReqObject.setRequestHeader('Content-Type','application/x-www-form-urlencoded; charset=UTF-8');
		this.httpReqObject.onreadystatechange = function() { thisObject.responseHandler(); };
		this.httpReqObject.send(postData);
  	
	} else {
  	/* HTTP object not ready try it 500 milisec later again */
		setTimeout(function() { thisObject.send( nickname, message ); }, 500);
	}
}

/* 
 * The response handler 
 * You need to change the code here if you need to change the actions on the response
 * For now its a simple handler to extract the timestamp and the message and it will
 * put the output in the div
 */
chatData.prototype.responseHandler = function() {

  if (this.httpReqObject !== null && this.httpReqObject.readyState === 4) {
  	var response = this.httpReqObject.responseXML; /* get the XML response */
	
  	/* get the root node */
  	var dataNode = response.getElementsByTagName("data")[0];
  	
  	/* get and set the latest timestamp */
  	this.timeStamp = dataNode.attributes.getNamedItem("timestamp").value;
  	
  	/* find the divObject */
  	chatTextObj = document.getElementById('chatText');
  	
  	/* loop the data node for mssg nodes */
  	for( var x = 0; dataNode.childNodes[x]; x++ ) {
    	if ( dataNode.childNodes[x].nodeName == "mssg" ) {
      	/* add the mssg to the div */
    	  chatTextObj.innerHTML+= "<br /><b>" + dataNode.childNodes[x].attributes.getNamedItem("nickname").value + "&nbsp;(" + dataNode.childNodes[x].attributes.getNamedItem("timestamp").value + "):&nbsp;</b>" + dataNode.childNodes[x].attributes.getNamedItem("mssg").value;
    	  /* scroll down div so the latest text is always visible */
    	  chatTextObj.scrollTop = chatTextObj.scrollHeight - chatTextObj.clientHeight;
  	  }
  	}
	}
};


/* 
 * create a object regardles to the browser type 
 */
chatData.prototype.httpObject = function() {
	var xmlhttp = false;
	
	/*@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 toggleLayer(whichLayer)
{
if (document.getElementById)
{
// this is the way the standards work
var style2 = document.getElementById(whichLayer).style;
style2.display = style2.display? "":"block";
}
else if (document.all)
{
// this is the way old msie versions work
var style2 = document.all[whichLayer].style;
style2.display = style2.display? "":"block";
}
else if (document.layers)
{
// this is the way nn4 works
var style2 = document.layers[whichLayer].style;
style2.display = style2.display? "":"block";
}
}