/* Main class for asynchron connections */
/* url - target url of xml or textfile 	*/
/* ..  */

var ajax_connections = Array();
var ajax_open_connections = 0;


var ajax = function(url, method, mode, data, done, error)
{
	/* Constructor and globals */
	this.address	= url;
	this.onSuccess 	= (typeof (done) == 'function')?(done):(function(){});
	this.onError	= (typeof (error) == 'function')?(error):(function(){});
	this.method		= (method == 'POST')?'POST':'GET';
	this.async		= (mode == 'sync')?false:true;
	this.data		= data || null;
	this.id			= ajax_open_connections;

	ajax_connections[this.id] = this;
	
	if(window.XMLHttpRequest)
	{
		this.connection = new XMLHttpRequest();
	}
	else if(window.ActiveXObject)
	{
		this.connection = new ActiveXObject("Microsoft.XMLHTTP");
	}
	else
	{
		new this.onError(1, "Unable to get AJAX object");
	}
	
	/* Methods */
	this.send = function()
	{
		if(typeof (ajax_on_open) == 'function')
		{
			ajax_on_open();
		}
		if(this.connection)
		{
			this.connection.open(this.method, this.address, this.async);
			if(this.method == 'POST')
			{
				this.connection.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=iso-8859-1');
			}
			
			if(this.async)
			{
				this.connection.onreadystatechange = new Function("ajax_onReadyStateChange(" + this.id + ")");
			}
			this.connection.send(this.data);
			if(!this.async)
			{
				return this.getContent();
			}
		}
		else
		{
			new this.onError(1, "Unable to get AJAX object");
		}
	}
	
	this.getContent = function()
	{
		//alert(this.connection.responseText);
		if(typeof (ajax_on_close) == 'function')
		{
			ajax_on_close(this.connection.responseText.length);
		}
		if(this.connection.responseText.substr(0, 5) == "<?xml")
		{
			if(this.connection.responseXML.getElementsByTagName('error')[0])
			{
				new this.onError(4, this.connection.responseXML.getElementsByTagName('error')[0].firstChild.nodeValue);
			}
			return this.connection.responseXML;
		}
		else if(this.connection.responseText != "")
		{
			return this.connection.responseText;
		}
		else
		{
			new this.onError(3, "No file content");
			return false;
		}

	}
	this.readyStateChange = function()
	{
		if(this.connection)
		{
			if (this.connection.readyState==4)
			{

				if (this.connection.status == 200)
				{
					var content = this.getContent();
					if(content)
					{
						new this.onSuccess(content);
					}
				}
				else if (this.connection.status == 404)
				{
					new this.onError(2, "404: File not found");
				}
				else
				{
					new this.onError(2, this.connection.status + ": Unable to load file");
				}
			}
		}
		else
		{
			new this.onError(1, "Unable to get AJAX object");
		}		
	}
}
function ajax_onReadyStateChange(id)
{
	ajax_connections[id].readyStateChange();
}
