/**
 * AJAX handling methods
 * @version	$Id: class.ajax.js, v1.0 2007/11/29 9:11
 */

function ajax_request()
{
	this.loading_fired = 0;
	this.centerdiv     = null;
	this.xmlhandler    = null;
	this.options       = {
		method      : 'GET',
		asynchronous: true,
		contentType : 'application/x-www-form-urlencoded',
		encoding    : 'UTF-8'
	}
	this.do_request_functon = function() {};
}

/**
 * Initializes the XML handler
 * 
 * @return	boolean
 */
ajax_request.prototype.xml_init = function()
{
	try
	{
		this.xmlhandler = new XMLHttpRequest();
		return (this.xmlhandler.setRequestHeader ? true : false);
	}
	catch (e)
	{
		try
		{
			this.xmlhandler = eval("new A" + "ctiv" + "eX" + "Ob" + "ject('Micr" + "osoft.XM" + "LHTTP');");
			return true;
		}
		catch (e)
		{
			return false;
		}
	}
};

/**
 * Sends data
 * 
 * @param	string	Destination URL
 * @param	string	Type of request
 * @param	string	Request data
 * @return	boolean
 */
ajax_request.prototype.process = function(url, method, body)
{
	if (!(this.xmlhandler || this.xml_init())) return false;
	
	if (!this.readystate_not_ready())
	{
		if (typeof method != 'undefined' && method == 'POST')
		{
			this.options.method = 'POST';
		}
		
		if (/Konqueror|Safari|KHTML/.test(navigator.userAgent))
		{
			var mydate = new Date();
			url += ((url.indexOf('?') > -1) ? '&' : '?') + '__=' + mydate.getTime();
		}
        
		this.xmlhandler.open(this.options.method, url, this.options.asynchronous);
		this.setRequestHeader();
		this.xmlhandler.send(this.options.method == 'POST' ? body : null);
		
		if (this.xmlhandler.readyState == 4 && this.xmlhandler.status == 200)
		{
			return true;
		}
	}
	
	return false;
};

/**
 * Sets the specified request header
 * 
 * @return	void
 */
ajax_request.prototype.setRequestHeader = function()
{
	var headers = {
		'X-Requested-With': 'XMLHttpRequest',
		'X-Prototype-Version': '1.0.0',
		'Accept': 'text/javascript, text/html, application/xml, text/xml'
	};
	
	if (this.options.method == 'POST')
	{
		headers['Content-type'] = this.options.contentType + (this.options.encoding ? '; charset=' + this.options.encoding : '');
		
		if (this.xmlhandler.overrideMimeType && (navigator.userAgent.match(/Gecko\/(\d{4})/) || [0,2005])[1] < 2005)
		{
			headers['Connection'] = 'close';
		}
	}
	
	for (var name in headers)
	{
		this.xmlhandler.setRequestHeader(name, headers[name]);
	}
};

/**
 * Takes an array of: array[field] = value and returns a nice encoded POST string
 * 
 * @param	array	Input POST data
 * @return	string	Encoded POST string
 */
ajax_request.prototype.format_for_post = function(arrayfields)
{
	var str = '';
	
	try
	{
		for (var i in arrayfields)
		{
			str += i + '=' + this.encodeurl(arrayfields[i]) + '&';
		}
	}
	catch (e) {}
	
	return str;
};

/**
 * Hand roll encode URL to UTF-8
 * 
 * @param	string	Input URL
 * @return	string	Parsed URL
 */
ajax_request.prototype.encodeurl = function(url)
{
	url = url.toString();
	var matches = url.match(/[\x90-\xFF]/g);
	
	if (matches)
	{
		for (var i = 0; i < i.length; i++)
		{
			url = url.replace(matches[i], '%u00' + (matches[i].charCodeAt(0) & 0xFF).toString(16).toUpperCase());
		}
	}
	
	return escape(url).replace(/\+/g, '%2B');
};

/**
 * Check to ensure ready state-ness
 * 
 * @return	boolean	False if ready
 */
ajax_request.prototype.readystate_not_ready = function()
{
	return (this.xmlhandler.readyState && this.xmlhandler.readyState < 4);
};

ajax_request.prototype.readystate_ready_and_ok = function()
{
	return (this.xmlhandler.readyState == 4 && this.xmlhandler.status == 200);
};

/**
 * Onready state change event handler
 * 
 * @param	function
 */
ajax_request.prototype.onreadystatechange = function(event)
{
	if (!this.xmlhandler)
	{
		if (!this.xml_init())
		{
			return false;
		}
	}
	
	if (typeof(event) == 'function')
	{
		this.xmlhandler.onreadystatechange = event;
		return true;
	}
	else
	{
		alert("XML Sender OnReadyState event is not a function");
	}
	
	return false;
};

/**
 * Execute javascript returned from the HTML
 *
 * @param	string	Input text
 */
ajax_request.prototype.execute_javascript = function(source_code)
{
	var text_blocks   = new Array();
	var max_iteration = 50;
	var i = 0;
	
	while (_match = source_code.match(new RegExp("<script\\s+?type=['\"]text/javascript['\"]>([^`]+?)</script>", "i")))
	{
		i++;
		
		if (i >= max_iteration)
		{
			break;
		}
		else
		{
			text_blocks[text_blocks.length] = _match[1];
			source_code = source_code.replace(_match[0], '');
		}
	}
	
	try
	{
		if (text_blocks.length)
		{ 
			for (i = 0; i < text_blocks.length; i++)
			{
				eval(text_blocks[i]);
			}
		}
	}
	catch (error) {}
};

/**
 * Retrieve text of an XML document element
 * 
 * @param	string	Prefix
 * @param	string	Local
 * @param	object	XML node
 * @param	string	Index
 * @return	mixed	XML node contents | N/A
 */
ajax_request.prototype.get_element_text_ns = function(prefix, local, parentElem, index)
{
	var result = '';
	
	if (prefix && document.all)
	{
		result = parentElem.getElementsByTagName(prefix + ':' + local)[index];
    }
    else
    {
		result = parentElem.getElementsByTagName(local)[index];
    }
	
	if (result)
	{
		if (result.childNodes.length > 1)
		{
			return result.childNodes[1].nodeValue;
		}
		else
		{
			return result.firstChild.nodeValue;    		
		}
	}
	else
	{
		return 'n/a';
	}
};

/**
 * Waiting message
 * 
 * @param	string	Input text
 */
ajax_request.prototype.show_loading = function(msg)
{
	if (!this.loading_fired)
	{
		this.loading_fired = 1;
		
		if (typeof msg != 'undefined')
		{
			document.getElementById('loading-layer-text').innerHTML = msg;
		}
		
		this.centerdiv         = new center_div();
		this.centerdiv.divname = 'loading-layer';
		this.centerdiv.move_div();
		this.centerdiv.add_shadow('loading-layer-shadow', 'loading-layer-inner');
	}
};

ajax_request.prototype.hide_loading = function()
{
	try
	{
		if (this.centerdiv && this.centerdiv.divobj)
		{
			this.centerdiv.hide_div();
		}
		
		this.centerdiv = null;
	}
	catch (e) {}
	
	this.loading_fired = 0;
	document.getElementById('loading-layer-text').innerHTML = "&#272;ang &#273;&#7885;c d&#7919; li&#7879;u...";
};

try
{
	ajax_request.prototype.xml_init();
}
catch (error) {}
