/**
 *	Ajax 封装类 1.0
 *
 *	@description:
 *		Ajax类，用于初始化对象和向服务器端发送数据
 *
 *		@onSuccess:function,当成功请求数据时触发
 *		@onFail:function,当请求数据失败时触发
 */
function Ajax(onSuccess, onFail) {
	this.OnSuccess = onSuccess;
	if (onFail)
		this.OnFail = onFail;

	//初始化XMLHttpRequest
	if (window.XMLHttpRequest) {
		this.xhr = new XMLHttpRequest();
	} else {
		try{
			this.xhr = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			this.xhr = new ActiveXObject("Microsoft.XMLHTTP");
		}
	}

	this.async = true;
	this.dataType = "text";
}

/**
 *	@Ajax.prototype
 *
 *	@description:
 *		ajax类的属性和方法成员
 */
Ajax.prototype = {
	/**
	 *	@setXML
	 *	@description:
	 *		设置获取的数据类型为XML
	 */
	setXML: function() {
		this.dataType = "xml";
	},

	/**
	*	@send
	*	@description:
	*		向服务器端发送数据
	*
	*
	*		@url:string,发送的url
	*		@data:string,发送的数据，格式参照a=aaa&b=bbb
	*		@method:string,发送方式，post/get
	*		@encoding:string,发送数据的编码方式，仅post时有效
	*/
	send: function(url, data, method, encoding) {
		var meth = "get";
		var contentType = "application/x-www-form-urlencoded";

		//发送类型
		if (method && method == "post")
			meth = "post";

		//根据发送类型get/post，解析url和发送头
		if (meth == "post") {
			if (encoding)
				contentType += '' + encoding;
			else
				contentType += ";charset=GBK";
		} else if(data) {
			url  = url + "?" + data + "&reqTime=" + new Date().getTime();
			data = null;
		}

		//发送数据
		var me = this;
		this.xhr.open(meth.toUpperCase(), url, this.async);
		this.xhr.onreadystatechange = function() {
			me.onStateChg.call(me);
		}
		if (meth == "post")
			this.xhr.setRequestHeader("Content-Type", contentType);
		this.xhr.send(data);
	},

	/**
	*	@post
	*	@description:
	*		通过post方式向服务器端发送数据
	*/
	post: function(url, data, encoding) {
		this.send(url, data, "post", encoding);
	},

	/**
	*	@get
	*	@description:
	*		通过get方式向服务器端发送数据
	*/
	get: function(url, data) {
		this.send(url, data);
	},

	/**
	*	@onStateChg
	*	@description:
	*		内部方法，仅在send中调用，当readyState发生改变时触发
	*/
	onStateChg: function() {
		//请求状态未就绪时不做任何事
		if (this.xhr.readyState != 4)
			return;

		//根据状态码触发请求成功/失败的function
		if (this.xhr.status >= 200 && this.xhr.status < 300) {
			if (this.dataType == "xml") {
				this.Data = this.xhr.responseXML;
			} else {
				this.Data = this.xhr.responseText;
			}

			this.OnSuccess();
		} else if (this.OnFail) {
			this.OnFail();
		}
	}
}