/**
 * XMLHTTPRequest javascript implementation
 * 
 * Usage:
 *  var xhr = new HTTPRequest();
 *  
 *  xhr.setMode(true); // true -- ASYNC mode, false -- SYNC
 *  xhr.setMethod('POST'); // GET | POST
 *  xhr.setHandler(myHandler); // handler for ASYNC mode
 *  var retval = xhr.request('page'); // retval contains response text. for SYNC mode.
 *  var retval = xhr.request('page', 'text'); // POST method
 *  
 *  function myHandler(xhr) {
 *      // xhr == [XMLHTTPRequest object]
 *  }
 * 
 */

function HTTPRequest() {
	
	var __xhr_this = this;
	
	this.async   = true;
	this.method  = 'GET';
	this.handler = null;
	
	this.request = function(url, body) {
		
		if (window.ActiveXObject) {
			this.xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
		} else {
			this.xmlHttp = new XMLHttpRequest();
		}
		
		if (typeof body == 'undefined') {
			body = '';
		}
		
		if (this.async) {
			this.xmlHttp.onreadystatechange = this.handleResponse;
		}
		
		this.xmlHttp.open(this.method, url, this.async);
		
		if (this.method == 'POST') {
			/**
			 * POST method
			 */
			//this.xmlHttp.setRequestHeader('Content-Length', body.length);
			//this.xmlHttp.sendAsBinary(body);
			this.xmlHttp.setRequestHeader('Content-Type',  "application/x-www-form-urlencoded");
			this.xmlHttp.send(body);
		} else {
			/**
			 * GET method
			 */
			this.xmlHttp.send(null);
		}
		
		if (!this.async) {
			return this.xmlHttp.responseText;
		}
	};
	
	this.handleResponse = function() {
		if (__xhr_this.xmlHttp.readyState == 4) {
			if (__xhr_this.handler != null) {
				/**
				 * Call user defined handler
				 */
				__xhr_this.handler(__xhr_this.xmlHttp);
			} else {
				/**
				 * Default handler. Define global variable
				 */
				var XHR_RESPONSE_TEXT = __xhr_this.xmlHttp.responseText;
			}
		}
	};
	
	this.setHandler = function(handler) {
		this.handler = handler;
	};
	
	this.getHandler = function() {
		return this.handler;
	};
	
	this.setMode = function(async) {
		this.async = async;
	};
	
	this.getMode = function() {
		return this.async;
	};
	
	this.setMethod = function(method) {
		this.method = method;
	};
	
	this.getMethod = function() {
		return this.method;
	};
}
