/***********************************************************
* (C) 2008-2009 CRM150.com                                 *
* This is Not a freeware.                                  *
* version     : 1.0.0.                                     *
* author      : CRM150.com (zshejxing@163.com).            *
* date        : 2008/12/20                                 * 
***********************************************************/
var GlobalAjaxSave = new Array();
function Ajax(form,completeBack,errorBack,endFront,noSend){
	this.req;
	this.dataArray = new Array();
	this.saves = new Array();
	this.form = new Object();
	this.msg;
	this.status = "free";
	this.dataEmpty = true;
	if(completeBack)this.onComplete = typeof(completeBack) != 'string'?completeBack : eval(completeBack);
	if(errorBack)this.onError = typeof(errorBack) != 'string'?errorBack : eval(errorBack);
	this.error = null;
	if(endFront)for(var i=0;i<GlobalAjaxSave.length;i++)GlobalAjaxSave[i].end();
	GlobalAjaxSave.push(this);
	if(form){
		this.setForm(form);
		this.makeData();
		if(!noSend)return this.send();
	}
}
Ajax.prototype.setForm = function(form){
	this.form = (typeof(form) == "object")?form : Doc.getElementsByName(form)[0];
}
Ajax.prototype.save = function(value,key){
	if(typeof(key) == "undefined")key = this.saves.length;
	this.saves[key] = value;
}
Ajax.prototype.getSave = function(key){
	if(typeof(key) == "undefined")return this.saves;
	try{
		return this.saves[key];
	}catch(e){}
	return "";
}
Ajax.prototype.clearSaves = function(){
	this.saves.length = 0;
}
Ajax.prototype.getStatus = function(){
	if(!this.req || this.req.readyState == 4 || this.req.readyState == 0){
		return "free";
	}else{
		return "busy";
	}
}
Ajax.prototype.setMsg = function(msg){
	this.msg = msg.toString();
	return true;
}
Ajax.prototype.getReq = function(){
	var req;
	if(window.XMLHttpRequest){
    	req = new XMLHttpRequest();
    	if(req.overrideMimeType){
        	req.overrideMimeType('text/xml');
        }
	}else if(window.ActiveXObject){
    	try {
      		req = new ActiveXObject("Msxml2.XMLHTTP");
        }catch(e){
        	try{
            	req = new ActiveXObject("Microsoft.XMLHTTP");
        	}catch(e){}
      	}
	}
	return req;
}
Ajax.prototype.abort = function(){
	if(this.req)this.req.abort();
}
Ajax.prototype.send = function(toPage,method,synchronous){
	if(this.dataEmpty)return false;
	this.req = this.getReq();
	var theThis = this;
	if(!toPage && this.form)toPage = this.form.action;
	if(!method)method = this.form.method?this.form.method:"POST";
	if(!this.req || !toPage)return false;
	var d = new Date();
	this.makeData("__data_source=Ajax&__send_time="+d.getTime(),"data");
	
	var dataStr = this.dataArray.join("&");

	if(method.toLowerCase() == "get")toPage +="?"+dataStr;
	if(this.getStatus() == "free"){
		this.req.open(method,toPage,isUndefined(synchronous)?true : synchronous);
		this.req.onreadystatechange = function(){theThis.readyStateChange();};
		if(method.toLowerCase() == "get"){
			dataStr = null;
		}else{
			this.req.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
		}
		this.req.send(dataStr);
	}
	return true;
}
Ajax.prototype.readyStateChange = function(){
	if(this.req && this.req.readyState == 1){
		//this.onLoading();
	}else if(this.req && this.req.readyState == 2){
		//this.onLoaded();
	}else if(this.req && this.req.readyState == 3){
		//this.onInterActive();
	}else if(this.req && this.req.readyState == 4){
		if(this.req && this.req.status == 0){
			this.onAbort(this.req.status);
		}else if(this.req.status == 200){
			GlobalAjaxSave.remove(this);
			if(this.req)this.onComplete(this.req.responseText,this.req.responseXML);
		}else{
			GlobalAjaxSave.remove(this);
			if(this.req)this.onError(this.req.status,this.req.statusText,this.req.responseText);
		}
		//this.abort();
		this.req = null;
	}
}

Ajax.prototype.onAbort = function(status){
	//alert("网路不通，请“确定”后再试。");//	
}

Ajax.prototype.onComplete = function(responseText,responseXML){
	//alert("success")//
}

Ajax.prototype.onError = function(status,statusText,responseText){
	alert('有错误发生，操作不成功！ 错误代码:'+status+'.');
}

Ajax.prototype.end = function(){
	if(this.req){
		//this.abort();
		this.req = null;
	}
	GlobalAjaxSave.remove(this);
}

Ajax.prototype.makeData = function(sourceData,sourceType){
	var theData = new Array();
	if(sourceType && sourceType.toLowerCase() == "data"){
		theData = sourceData.split("&");
		for(var i=0;i<theData.length;i++){
			theData[i] = this.urlEncode(theData[i],"1");
		}
	}else{
		if(typeof(sourceData) == "object"){
			var theForm = sourceData;
		}else{
			if(typeof(sourceData) == "undefined" && this.form){
				var	theForm = this.form;
			}else{
				var theForm = Doc.getElementsByName(sourceData)[0];
			}
		}
		this.form = theForm;
		if(!theForm.elements || (theForm.onsubmit && !theForm.onsubmit()))return false;
		var n = theForm.elements.length;
		for(var i=0;i<n;i++){
			elementsName = theForm.elements[i].name;
			if(elementsName && elementsName != ''){
				if(theForm.elements[i].type == "radio" || theForm.elements[i].type == "checkbox"){
					if(theForm.elements[i].checked)theData[theData.length] = this.urlEncode(elementsName) + "=" + this.urlEncode(theForm.elements[i].value);
				}else{
					theData[theData.length] = this.urlEncode(elementsName) + "=" + this.urlEncode(theForm.elements[i].value);
				}
			}
		}
	}
	this.dataArray = this.dataArray.concat(theData);	
	this.dataEmpty = false;
	return true;
}

Ajax.prototype.removeData = function(start,end){
	if(!start && !end){
		this.dataArray.length = 0;
	}else{
		if(start<0 || start>end || end>this.dataArray.length)return false;
		var fArray = this.dataArray.slice(0,start-1);
		var lArray = this.dataArray.slice(end+1);
		this.dataArray = fArray.concat(lArray);
	}
	return true;
}

Ajax.prototype.parseXML = function(XMLstr){
	XMLstr = XMLstr.replace(/[\r\n]/g,"");
	this.arrXML = new Array();
	this.parseXMLer(XMLstr);
	return this.arrXML;
}

Ajax.prototype.parseXMLer = function(XMLstr){
	var arr = new Array();
	var re = new RegExp("<([\\w]+)>(.*?)</\\1>", "gm");
	while(arr = re.exec(XMLstr)){
		this.arrXML[arr[1]] = arr[2];
		this.parseXMLer(arr[2]);
	}
}

Ajax.prototype.parseCXML = function(XMLstr){
	XMLstr = XMLstr.replace(/[\r\n]/g,"");
	this.arrXML = new Array();
	this.parseCXMLer(XMLstr,'this.arrXML[0]');
	return this.arrXML;
}

Ajax.prototype.parseCXMLer = function(XMLstr,os){
	var re = new RegExp("<([\\w]+)>([\\s\\S]*?)</\\1>", "gm");
	var arr = new Array();
	while(arr = re.exec(XMLstr)){
		if(typeof(eval(os))!="object")eval(os+"= new Object()");
		if(!eval(os+"."+arr[1]))eval(os+"."+arr[1]+"=new Array()");
		
		var i = eval(os+"."+arr[1]+".push('"+arr[2]+"')");
		this.parseCXMLer(arr[2],os+"."+arr[1]+"["+(i-1)+"]");
	}
}

Ajax.prototype.urlEncode = function(str,processEqual){
	var escapeStr = escape(str);
	if(processEqual){
		escapeStr = escapeStr.replace(/%5C%3D/gi,'%equal');
		escapeStr = escapeStr.replace(/%3D/gi,'=');
		escapeStr = escapeStr.replace(/%equal/g,'%3D');
	}
	escapeStr = escapeStr.replace(/\+/g,'%2B');
	return escapeStr;
}
