var ajax = {
	xmlObj : false,
	queriesList : Array(),
	statCheckInterval : 50,
	queryTime : 10000,
	timeCounter : 0,
	tid : null,
}

ajax.createObj = function()
{
	var xmlhttp;
	try { xmlhttp = new ActiveXObject( "Msxml2.XMLHTTP" );
	} catch (e) {
		try { xmlhttp = new ActiveXObject( "Microsoft.XMLHTTP" );
		} catch (E) { xmlhttp = false; }
	}
	if (!xmlhttp && typeof XMLHttpRequest!='undefined') { xmlhttp = new XMLHttpRequest(); }
	this.xmlObj = xmlhttp;
}

ajax.query = function( r )
{
	var p = {
		'url'		: '',
		'method'	: 'POST',
		'handler'	: '',
		'error'		: '',
		'indicator'	: false
	};
	p = parseArgs( p, r );
	this.queriesList.push( p );
	if( this.queriesList.length ) {
		this.start();
	}
}

ajax.start = function()
{
	if( !this.xmlObj )
	{
		this.createObj();
	}
	if( this.xmlObj )
	{
		this.showIndicator();
		var url = this.queriesList[0]['url'];
		var params = this.queriesList[0]['method'].toLowerCase() == 'post' ? this.queriesList[0]['params'] : null;
		url += ( url.indexOf('?') == -1 ? '?' : '&') + 'mode=xml&rand=' + Math.random();
		this.xmlObj.open( this.queriesList[0]['method'], url, true );
		this.xmlObj.send( params );
		this.timeCounter = 0;
		this.tid = setTimeout( this.handler, this.statCheckInterval );
	}
}

ajax.showIndicator = function()
{
	var e = this.queriesList[0]['indicator'];
	if( !e ) {
		return;
	}
	if( typeof(e) == 'object' ) {
		if( e[1] == 'background' ) {
			$( e[0] ).style.background = e[2];
		}
	} else {
		$( e ).style.display = '';
	}
}

ajax.hideIndicator = function()
{
	var e = this.queriesList[0]['indicator'];
	if( !e ) { return; }
	if(typeof(e)=='object') {
		if( e[1] == 'background' ) {
			$( e[0] ).style.background = e[3];
		}
	} else {
		$( e ).style.display = 'none';
	}
}

ajax.handler = function()
{
	clearTimeout(ajax.tid);
	if( ajax.xmlObj.readyState == 4 && ajax.xmlObj.status == 200 )
	{
		ajax.hideIndicator();
		eval( ajax.queriesList[0]['handler'] + '()' );
		ajax.queriesList.shift();
		if( ajax.queriesList.length )
		{
			ajax.start();
		}
	}
	else
	{
		ajax.timeCounter += ajax.statCheckInterval;
		if( ajax.timeCounter >= ajax.queryTime ) {
			if( ajax.queriesList[0]['error'] ) {
				ajax.hideIndicator();
				eval( ajax.queriesList[0]['error'] + '()' );
				ajax.queriesList.shift();
			}
		} else {
			ajax.tid = setTimeout( ajax.handler, ajax.statCheckInterval );
		}
	}
	return;
}

ajax.parseResponse = function()
{
	return eval( '(' + this.xmlObj.responseText + ')' );
}

