// MyAjax Library for AJAX using without server side code generation
// Written by Alex Godunov
//

// Constructor
function myAjax(url)
{	this.ajx = this.Init();
	this.url = url;}

// Responce status definitions
myAjax.prototype.READY_STATE_UNINITIALIZED	= 0;
myAjax.prototype.READY_STATE_LOADING		= 1;
myAjax.prototype.READY_STATE_LOADED			= 2;
myAjax.prototype.READY_STATE_INTERACTIVE	= 3;
myAjax.prototype.READY_STATE_COMPLETE		= 4;

// Print message from myAjax methods
myAjax.prototype.Debug = function (msg)
{
	alert( msg );
}

// Initialize AJAX engine
myAjax.prototype.Init = function ()
{
	var A;

	var msxmlhttp = new Array(
		'Msxml2.XMLHTTP.5.0',
		'Msxml2.XMLHTTP.4.0',
		'Msxml2.XMLHTTP.3.0',
		'Msxml2.XMLHTTP',
		'Microsoft.XMLHTTP');

	for (var i = 0; i < msxmlhttp.length; i++)
	{
		try {
			A = new ActiveXObject(msxmlhttp[i]);
		} catch (e) {
			A = null;
		}
	}

	if(!A && typeof XMLHttpRequest != "undefined")
		A = new XMLHttpRequest();
	if (!A)
		this.Debug("AJAX Engine is Disabled.");

	return A;
}

// function is called on recieving responce
myAjax.prototype.ProcessResponse = function(http_request, process_callback)
{
	try
	{
		if (http_request.readyState == this.READY_STATE_COMPLETE) {
			if (http_request.status == 200) {				//alert( http_request.responseText );
				process_callback( http_request.responseText );
			} else {
				//alert('С запросом возникла проблема.\r\nHTTP Код: ' + http_request.status + "\r\n\r\n" + http_request.responseText);
			}
		}
		else
		{
			//alert('Ajax Response Status: ' + http_request.readyState);
		}
	}
	catch( e1 )
	{		//alert( 'Error' /*e1.description*/ );
		//salert(e1.message);	}
}

// function to send the request
myAjax.prototype.SendRequest = function(method, query_str, callback_fn, post_data)
{
	var cfn = callback_fn;
	var ajx_obj = this;

	if( ajx_obj.ajx.readyState != 0 )
	{		ajx_obj.ajx.abort();
	}
	this.ajx.onreadystatechange = function() {
		ajx_obj.ProcessResponse( ajx_obj.ajx, cfn );
	};

	try
	{
		var rand_req_id = Math.floor(Math.random()*10000) + 100000;
		var req_url = this.url + "?randreqid=" + rand_req_id + ( query_str != "" ? '&' + query_str : "");

		this.ajx.open(method, req_url, true);
		if( method == "POST" )
		{
			this.ajx.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
			//this.ajx.setRequestHeader('Content-Type', 'text/plain; charset=windows-1251');

			// make correct string for post_data
			if( AJAX_REQUEST_CHAR_CODE == 1 )
			{
				var myreg = /\+/g;
	   			post_data = post_data.replace(myreg, "%2B");
	   			myreg = /\//g;
	   			post_data = post_data.replace(myreg, "%2F");

	   			//alert(post_data);
	   		}
		}

		this.ajx.send( (method == "POST" ? 'datacmd=' + post_data : null) );
	}
	catch(e)
	{
    	alert('Error opening URL:' + e.toString() + ':' + e.message);
	}}
