// JavaScript Document

// ajaxEngine class
function ajaxEngine()
{
/* Properties */
	// Public
	this.sendTry = 0;
	this.sendTryLimit = 8;
	this.sendTryDelay = 1000; // 1 second
	this.sendTimeout = 3000;
	
	this.sendTimeoutID = null;
	
	this.statusText = null;
	
	this.active = false;
	
	// Private
	this.httpObj = null;
	
/* Methods */
	this.Initialize = function() 
	{
		if( window.ActiveXObject )
		{
			try
			{
				this.httpObj = new ActiveXObject("Microsoft.XMLHTTP");
			}
			catch(e)
			{
				return;
			}
		}
		else
		{
			try
			{
				this.httpObj = new XMLHttpRequest();
			}
			catch(e)
			{
				return;
			}
		}
		
		this.active = true;
	}
	
	this.SendRequest = function(url, params, method, onChangeState)
	{
		// Не занято
		if( this.httpObj.readyState == 4 || this.httpObj.readyState == 0 )
		{
			// Обнуляем попытки
			this.sendTry = 0;
			
			// Получаем строку параметров URL
			var urlParams = this.GetUrlParams(params);
			
			if( method == "GET" )
			{
				this.httpObj.open("GET", url + "?" + urlParams, true);
				this.httpObj.send(null);
			}
			else if( method == "POST" )
			{
				this.httpObj.open("POST", url, true);
				this.httpObj.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
				this.httpObj.setRequestHeader("Content-Length", urlParams);
				this.httpObj.send(urlParams);
			}
			else
			{
				return false;
			}
			
			// Обработчик ответа от сервера
			this.httpObj.onreadystatechange = onChangeState;
			/*
				#readyState == 1 : 	Открыто
				#readyState == 2 : 	Отправка
				#readyState == 3 : 	Прием
				#readyState == 4 : 	Ответ получен
			*/
			//this.sendTimeoutID = setTimeout('TimeIsUp(' + this + ');', this.sendTimeout);
		}
		else
		{
			// Если число попыток достигло максимального...
			if( this.sendTry >= this.sendTryLimit )
			{
				// Прерываем предыдущий сеанс
				this.httpObj.abort();
			}
			else // Иначе пробуем еще раз
			{
				setTimeout('this.SendRequest()', this.sendTryDelay);
				this.sendTry++;
			}
		}
	}
	
	this.GetUrlParams = function(params)
	{
		var paramsStr = "";
		
		for( key in params )
		{
			paramsStr += encodeURIComponent(key) + "=" + encodeURIComponent(params[key]) + "&";
		}
			
		return paramsStr;
	}
	
	this.GetStatus = function() 
	{
		return this.httpObj.status;
	}
	
	this.GetState = function()
	{
		return this.httpObj.readyState;
	}
	
	this.GetXML = function()
	{
		return this.httpObj.responseXML;
	}
	
	this.GetStatusText = function()
	{
		return this.httpObj.statusText;
	}
}
/*
function TimeIsUp( obj )
{
	obj.abort();
	obj.active = false;
	
	clearTimeout(obj.sendTimeoutID);
}*/

