//function for get an object by the id
function $(objId){ return document.getElementById(objId);}

//function to return the XMLHttpRequest object supported by current browser
function createXMLHttpRequest( ) {
    try{ return new ActiveXObject("Msxml2.XMLHTTP");} catch (e) {}
    try{ return new ActiveXObject("Microsoft.XMLHTTP");} catch (e) {}
    try{ return new XMLHttpRequest(); }catch (e) {}
    return null;
}

var caller = new Caller();

function Caller(url,useCache,method){
	if (caller && caller.xhr && caller.xhr.readyState != 4){
		caller.xhr.abort();
		caller.response = null;
		caller.onGetResponse();
	}
	this.xhr = null;
	this.url = url;
	this.method = method;
	this.useCache = useCache;

	this.onRequesting = null;
	this.onGetResponse = null;
	this.onError = null;

	this.error = null;
	this.response = null;
	
	this.request=function(){
		
		if (!this.url){ 
			this.error = this.url = " Not found.";
			if (this.onError) this.onError();
			return;
		}
		if (this.method==null){
			this.method = "GET";
		}
		if (this.xhr == null || this.xhr.readyState == 4){
			this.xhr = createXMLHttpRequest();
			if (!this.xhr){
				this.error = "createXMLHttpRequest Failed.";
				if (this.onError) this.onError();
				return;
			}
		}
		this.xhr.onreadystatechange = 
	    	function() {
	    		try{
				//the task..
			    if (caller.xhr.readyState != 4)  {
			    	if (caller.onRequesting) caller.onRequesting();
			    }else{
				    if (caller.xhr.status == 200)  {
				    	// status 200 is no error state.
					    caller.response = caller.xhr.responseText;
				    	if (caller.onGetResponse) caller.onGetResponse();
				    }else if (caller.xhr.status == 404){
				    	caller.error = caller.url + " not found.";
				    	if (caller.onError) caller.onError();
				    }else{
				    	caller.error = "Server is busy";
				    	if (caller.onError) caller.onError();
				    }
			    }
			    }catch(e){}
			}
		var sendUrl = this.url + "";
		if (!this.useCache){
			sendUrl = sendUrl + "&uid=" + uID();
		}
	    this.xhr.open(this.method, sendUrl, true);
	    this.xhr.send(null);
	}
}

function uID(){
	var now = new Date();
	return now.getYear()+","+now.getMonth()+","+now.getDate()+","+new Date().getMilliseconds();
}

