/**
 * XMLHttpRequest Object Pool
 *
<script type="text/javascript" src="xmlhttp.js"></script>
<script type="text/javascript">
function test(obj)
{
    alert(obj.statusText);
}

xmlhttp.send_request('GET', 'http://www.ugia.cn/wp-data/test.htm', '', test);
xmlhttp.send_request('GET', 'http://www.ugia.cn/wp-data/test.htm', '', test);
xmlhttp.send_request('GET', 'http://www.ugia.cn/wp-data/test.htm', '', test);
xmlhttp.send_request('GET', 'http://www.ugia.cn/wp-data/test.htm', '', test);

alert('Pool length:' + xmlhttp.object_pool.length);
</script>

 */ 

var xmlhttp =
{
	//定义对象池
	object_pool : [],

	//获得对象池中已经创建的对象如果没有则重新创建对象
	get_instance : function()
	{
		with(this)
		{
			for(var i = 0;i < object_pool.length;i++)
			{
				if (object_pool[i].readyState == 0 || object_pool[i].readyState == 4)
				{
					return object_pool[i];//如果有空闲对象则直接返回空闲对象
				}
			}

			//由于对象池中没有以创建的空闲对象所以创建新对象
			//IE5中不支持push方法 所以对象池中对象数量作为新对象所在数组的下标
			object_pool[object_pool.length] = create_obj();

			return object_pool[object_pool.length - 1];//返回可使用的 XMLHTTP 对象
		}
	},

	//创建 XMLHTTP 对象
	create_obj : function()
	{
		if(window.XMLHttpRequest) //先检测非 IE 的 XMLHTTP 对象是否存在 如果存在则创建 否则进行 IE 的 XMLHTTP创建
		{
			var xmlhttp_object = new XMLHttpRequest();
		}
		else
		{
			MSXML = ['MSXML2.XMLHTTP.5.0', 'MSXML2.XMLHTTP.4.0', 'MSXML2.XMLHTTP.3.0', 'MSXML2.XMLHTTP', 'Microsoft.XMLHTTP'];
			for(var n = 0 ; n < MSXML.length ; n++)
			{
				try
				{
					var xmlhttp_object = new ActiveXObject(MSXML[n]);
					break;
				}
				catch (e)
				{
				}
			}
		}

		//mozilla某些版本没有readyState属性
		if (xmlhttp_object.readyState == null)
		{
			xmlhttp_object.readyState = 0;

			xmlhttp_object.addEventListener("load", function ()
			{
				xmlhttp_object.readyState = 4;

				if (typeof xmlhttp_object.onreadystatechange == "function")
				{
					xmlhttp_object.onreadystatechange();
				}
			},  false);
		}

		return xmlhttp_object;
	},

	//发送请求(方法[POST,GET], 地址, 数据, 回调函数名)
	send_request : function (method, url, data, callback_name, param)
	{
		//从对象池获取实例
		var send_object = this.get_instance();

		//加随机数防止缓存
		if (url.indexOf("?") > 0)
		{
			url += "&randnum=" + Math.random();
		}
		else
		{
			url += "?randnum=" + Math.random();
		}

		try
		{

			with(send_object)
			{
				//创建一个新的http请求，并指定此请求的方法、URL以及验证信息
				send_object.open(method, url, true);
				
				//设定请求编码方式
				setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
				send(data);

				onreadystatechange = function()
				{
					if (readyState==4 && (status == 200 || status == 304))
					{
						callback_name(send_object, param);
					}
				}
			}
		}
		catch(e)
		{
			//弹出异常错误
			alert('ERROR:'+e);
		}
		
	}
};
