// Ajax Request Handler

var BM_AJAX_ASYNC_NOTINIT 		= 0;
var BM_AJAX_ASYNC_SET 			= 1;
var BM_AJAX_ASYNC_SENT 			= 2;
var BM_AJAX_ASYNC_INPROGRESS 	= 3;
var BM_AJAX_ASYNC_COMPLETE 		= 4;
var BM_AJAX_GET					= "GET";
var BM_AJAX_POST				= "POST";

// Initializes Ajax and returns object
function bm_ajax_init()
{
   if (window.ActiveXObject) 
   {
       return new ActiveXObject("Microsoft.XMLHTTP");
   }
   else if (window.XMLHttpRequest) 
   {
       return new XMLHttpRequest();
   }
   else 
   {
      alert("Your browser does not support AJAX.");
      return null;
   }
}

// Generic Ajax request function
function BM_AjaxRequest(method, fn, params, successHandler, failureHandler, progressHandler)
{   
	var s_instance = this;

	function process()
	{
		if (!s_instance)
			return;
			
		var obj = s_instance.htmlObj;

		if (BM_AJAX_ASYNC_INPROGRESS == obj.readyState)
		{
			if (null != s_instance.progressHandler)
			{
				s_instance.progressHandler();
			}
		}
		else if (BM_AJAX_ASYNC_COMPLETE == obj.readyState)
		{
			if (200 == obj.status) 
			{
				if (null != s_instance.successHandler)
				{
					s_instance.successHandler(obj.responseText);
				}
			}
			else
			{
				if (null != s_instance.failureHandler)
				{
					s_instance.failureHandler();
				}
			}
			s_instance = null;
		}
	}

	this.htmlObj = bm_ajax_init();
	if (null != this.htmlObj)
	{
		this.method 			= method;
		this.fn 				= fn;
		this.params				= params;
		this.successHandler 	= successHandler;
		this.failureHandler 	= failureHandler;
		this.progressHandler 	= progressHandler;
				
		// initiate ajax request
        this.htmlObj.onreadystatechange = process;
        this.htmlObj.open(this.method, this.fn, true);

		if (BM_AJAX_GET == this.method)
		{
			this.htmlObj.send(null); 
		}
		else 
		{
			this.htmlObj.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
			this.htmlObj.setRequestHeader("Content-length", this.params.length);
			this.htmlObj.setRequestHeader("Connection", "close");
			this.htmlObj.send(this.params);
		}
	}
}

