
function Bus( url, onSend, onReceive )
{
	this.url = url;
    this.onSend = onSend;
    this.onReceive = onReceive;

	this.httpGetObj  = this.httpObject();
	this._interval = 2;
	
	this.timerStart();
}


    ///////////////////////////
    // Periodic Server Check //

Bus.prototype.timerStart = function() 
{
    this._missedChecks = 0;

	var thisObj = this;

	clearInterval(this.timerID);
	this.timerID = setInterval(function() { thisObj.checkServer(); }, this._interval * 1000);
};

Bus.prototype.checkServer = function() 
{
    // If the last "checkServer" is still waiting for a response, then do not send another one.
	if (this.httpGetObj.readyState != 4 && this.httpGetObj.readyState != 0)
	{
	    this._missedChecks++;

        // If over 5 had to be skipped because one request is hung-up, then cancel
        // that request, and start a new one.
        // Cancel the current request (its taking too long)
	    if ( this._missedChecks > 5 )
	        this.timerStart();

	    return;
	}


	this.httpGetObj.open('POST', this.url, true);

	var thisObj = this;
    this.httpGetObj.onreadystatechange = function() 
    {
        if (thisObj.httpGetObj.readyState === 4) 
        {
	        if ( thisObj.httpGetObj.status != 200 && thisObj.httpGetObj.status != 304 )
		        alert( 'POST request error: ' + thisObj.httpGetObj.statusText + ' (' + thisObj.httpGetObj.status + ') ['+thisObj.httpGetObj.responseText+']' ) ;

            // Update Client-State with info from the Server
            this.onReceive( thisObj.httpGetObj.responseText );
        }
    }

	this.httpGetObj.send( this.onSend() );
};

Bus.prototype.stop = function() 
{
	clearInterval(this.timerID);
};






    //////////
    // Misc //

Bus.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;
};
