/**
 * JavaScript Ajax Get Class
 *
 * 2010年08月02号
 *
 */

var Ajax = function() {
	this.xmlHttp = false;
	this.isTimeOut = false;
	this.Data = null;
	this.method = "GET";
	this.callback = "";
	this.loading = "";
	this.timeout = "";
	this.timeNum = 0;
	this.step = 1;
	this.timeoutID = null;
	this.errorID = 0;
	this.regex = /[\t\r\n]+/g;
}

Ajax.prototype.createXMLHttpRequest = function() {
	if(window.ActiveXObject){
		this.xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
	}else if(window.XMLHttpRequest){
		this.xmlHttp = new XMLHttpRequest();
	}
}

Ajax.prototype.response = function() {
	try{
		if(this.xmlHttp.readyState == 4) {
			if(this.xmlHttp.status == 200) {
				this.isTimeOut = true;
				if(this.callback != "") eval(this.callback(this.xmlHttp));
			}else{
				this.errorID = this.xmlHttp.status;
			}
		}else{
			this.errorID = this.xmlHttp.readyState;
		}
	}catch(e){
		return false;
	}
}

Ajax.prototype.doAjax = function(url, sync){
	try{
		var owner = this;
		var timeStame = "timeStame=" + new Date().getTime() + "n" + Math.round(Math.random()*100000);
		if(url.indexOf("?") == -1) {
			var url = url + "?" + timeStame;
		}else{
			var url = url + "&" + timeStame;
		}
		url = url.replace(this.regex, "");

		if(this.timeNum > 0) this.iTimeout(owner, this.timeNum);
		
		if(this.loading != "") this.loading();

		this.createXMLHttpRequest();
		this.xmlHttp.onreadystatechange = function() {
			owner.response.call(owner);
		};

		this.method = this.Data == null ? "GET" : "POST";
		
		this.xmlHttp.open(this.method, url, sync);
		this.xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
		
		this.xmlHttp.send(this.Data);
	}catch(e){ }
}

Ajax.prototype.iTimeout = function(owner, time) {
	var owner = this;
	this.timeoutID = setTimeout(function(){owner.sTimeout(owner,time)}, this.step);
}

Ajax.prototype.sTimeout = function(owner,time){    
	var owner = this;
	if(time <= 0) {
		clearTimeout(this.timeoutID);
		delete this.timeoutID;
		if(!this.isTimeOut) {
			if(this.timeout != "") this.timeout(this.errorID);
			this.abort();
		}
	}else{
		if(this.isTimeOut) {
			clearTimeout(this.timeoutID);
			delete this.timeoutID;
		}else{
			time--;
			this.timeoutID = setTimeout(function(){owner.sTimeout(owner,time)}, this.step);
		}
	}
}

Ajax.prototype.abort = function() {
	this.xmlHttp.abort(); 
	delete this.xmlHttp;
}
