﻿/**
* Ajax
* 
* @author     banhthidiem <banhthidiem@gmail.com>
* @copyright  2007 Bach Khoa Computer Inc.
* @version    $Id: AjaxBTD.js, v2.0 2007/10/18
*/

function AjaxBTD(funcCallBack) {

	function createAjax() {
		var xml;
		try {
			if (window.ActiveXObject) {
				xml = new ActiveXObject("Microsoft.XMLHTTP");
			}
			else {
				xml = new XMLHttpRequest();
			}
		}
		catch (e) {
			alert("Error creating the XMLHttpRequest object.");
			xml = null;
		}
		return xml;
	};

	this.xmlHttp = createAjax();

	this.createParaPost = function(paras) {
		var result = "";
		for (var key in paras) {
			if (typeof (paras[key]) == "object") continue;
			if (result != "") result += "&";
			result += key + "=" + encodeURIComponent(paras[key]);
		}
		return result;
	};

	this.handleServerResponse = function() {
		if (this.xmlHttp == null) return;
		if (this.xmlHttp.readyState == 4) {
			if (this.xmlHttp.status == 200) {
				if ((funcCallBack != null) && (funcCallBack instanceof Function)) {
					funcCallBack(this.xmlHttp.responseText);
				}
			}
			else {
				//	alert("There was a problem accessing the server: " + this.xmlHttp.statusText);
			}
		}
	};
};

AjaxBTD.prototype = {

	processGET: function(url) {
		if (this.xmlHttp == null) return;
		if (this.xmlHttp.readyState == 4 || this.xmlHttp.readyState == 0) {
			this.xmlHttp.open("GET", url, true);
			var self = this;
			this.xmlHttp.onreadystatechange = function(e) {
				self.handleServerResponse();
			};
			this.xmlHttp.send(null);
		}
	},

	processPostAsync: function(url, paras) {
		if (this.xmlHttp == null) return;
		if (this.xmlHttp.readyState == 4 || this.xmlHttp.readyState == 0) {
			this.xmlHttp.open("POST", url, true);
			this.xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
			var self = this;
			this.xmlHttp.onreadystatechange = function(e) {
				self.handleServerResponse();
			};
			this.xmlHttp.send(createParaPost(paras));
		}
	},

	processPostSync: function(url, paras) {
		if (this.xmlHttp == null) return;
		var result = "";
		if (this.xmlHttp.readyState == 4 || this.xmlHttp.readyState == 0) {
			this.xmlHttp.open("POST", url, false);
			this.xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
			this.xmlHttp.send(createParaPost(paras));

			if (this.xmlHttp.status == 200) {
				result = this.xmlHttp.responseText;
			}
		}
		return "";
	},

	abort: function() {
		if (this.xmlHttp == null) return;
		this.xmlHttp.abort();
	}
};
