/**
 * CAjaxBoy
 * @version 1.0.8
 */

function CAjaxBoy ()
{
	document.AjaxBoy = this;
	this.charset = 'UTF-8';
	/* XMLHttpRequest */
	this.req = null;
	
	/** Requests History */
	this.history = new Array();
	/** Put in history last request */
	this.history_put = false;
	/** Maximum history len */
	this.history_max = 25;
	/** Current history position */
	this.history_pos = 0;
	
	// Run when xml load begin //
	this.loadBegin = null;
	this.loadOk = null;
	this.loadError = null;
	
/**
 * Create XMLHttpRequest Object
 */ 
this.createXHR = function ()
{
	if(window.XMLHttpRequest) // branch for native XMLHttpRequest object
	{
		try {this.req = new XMLHttpRequest();}
		catch(e) {return null;}
	}
	else if(window.ActiveXObject) // branch for IE/Windows ActiveX version
	{
		try {this.req = new ActiveXObject("Msxml2.XMLHTTP");}
		catch(e)
		{
			try {this.req = new ActiveXObject("Microsoft.XMLHTTP");}
			catch(e) {return null;}
		}
	}
	this.req.onreadystatechange = this.processReqChange;
};

this.replaceContent = function (id, new_content)
{
	var ids = id.toString().split(',');
	for (var i=0; i<ids.length; i++)
	{
		block = document.getElementById(ids[i]);
		if (!block) continue;
		try {
			block.innerHTML = new_content? new_content : '';
		}
		catch(e) {
			alert('Block id="'+ids[i]+'" treat error!');
		}
	}
};

/**
 * Handle recived data
 */
this.treatReceiveData = function (xml)
{
//	xml = this.req.responseXML.getElementsByTagName("xml");
	// Clear blocks //
	clear = xml[0].getElementsByTagName("clear");
	if (clear)
		for( i=0; i<clear.length; i++)
			this.replaceContent(clear[i].getAttribute('block_id'), null);
	// Replace content blocks //
	content = xml[0].getElementsByTagName("content");
	if (content)
		for( i=0; i<content.length; i++)
			this.replaceContent(content[i].getAttribute('block_id'), content[i].firstChild.nodeValue);
	// Set page title //
	page_title = xml[0].getElementsByTagName("title");
	if (page_title && page_title.length > 0)
		document.title = page_title[0].firstChild.nodeValue
	// Set page status //
	page_status = xml[0].getElementsByTagName("status");
	if (page_status && page_status.length > 0)
		window.status = page_status[0].firstChild.nodeValue
	// Run eval blocks //
	eval_code = xml[0].getElementsByTagName("eval");
	if (eval_code)
		for( i=0; i<eval_code.length; i++) {
			eval(eval_code[i].firstChild.nodeValue);
		}
};

/**
 * Add last request to history
 */
this.addHistory = function(xml)
{
	if(!this.history_put) return;
	this.history_put = false;
	
	if (this.history.length < this.history_max)
		this.history[this.history.length] = null;
		
	for (var i=this.history.length-1; i>0; i--)
		this.history[i] = this.history[i-1];
	
	this.history[0] = new Array(/*this.reg.URL*/null, xml);
	
	this.history_pos = 0;
	
};

this.goHistory = function(pos)
{
	if (isNaN(pos) || pos<0 || pos >= this.history.length) return;
	this.history_pos = pos;
	this.treatReceiveData(this.history[this.history_pos][1]);
};

/**
 * Request process change event handle
 */
this.processReqChange = function ()
{
	try
	{
		if (document.AjaxBoy.req.readyState == 4 )
		{
			if (document.AjaxBoy.req.status == 200 )
			{
				var xml = document.AjaxBoy.req.responseXML.getElementsByTagName("xml");
				document.AjaxBoy.treatReceiveData(xml);
				document.AjaxBoy.addHistory(xml);
				document.AjaxBoy.req.abort();
				if (document.AjaxBoy.loadOk) document.AjaxBoy.loadOk();
			}
			else 
				throw(new Error());
		}
	}
	catch(e) {
		document.AjaxBoy.history_put = false;	
		document.AjaxBoy.req.abort();
		if (document.AjaxBoy.loadError) document.AjaxBoy.loadError();
	}
};


/**
 * Request data by GET
 *
 * @param string url
 * @param boolean nohistory IF true result not added to histury. By default GET requests added into history 
 */
this.runGetQuery = function (url, nohistory)
{
		this.createXHR();
		this.req.open('GET', url, true);
//		this.req.URL = url;
		if (!nohistory) this.history_put = true;
		this.req.send(null);
		if (this.loadBegin) this.loadBegin();
};

	
this.runPostQuery = function (form)
{
    var data = new CAjaxForm().getFormData(form);

    if (form.method.toString().toUpperCase()  == 'POST') {
      	url =  form.action;
    	divide = form.action.toString().search(/\?/);
      	if (divide!=-1) {
      		url =  form.action.toString().slice(0, divide);
      		data = form.action.toString().slice(divide+1)+'&'+data;
    	}
		this.createXHR();
	    this.req.open('POST', url, true);
	    this.req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset='+this.charset);
	    this.req.send(data);
	    if (this.loadBegin) this.loadBegin();
    }
    else {
      this.runGetQuery(form.action + (form.action.toString().search(/\?\S+=/)!=-1 ? '&'+data : '?'+data));
    }
};

}