/*global ActiveXObject*/
/*global window*/
function AjaxHandler()
{
	// debug
	var debug = false;
	
	var that = this;
	this.updating = false;
	
	this.abort = function() {
		if (that.updating) {
			that.updating=false;
			that.xmlhttp.abort();
			that.xmlhttp=null;
		}
	};
	
	this.call = function(url, getVars, postVars, callbackFunction, params) {
		
		if (that.updating) {
			return false;
		}
		
		that.xmlhttp = null;
		if (window.XMLHttpRequest) {
			that.xmlhttp = new XMLHttpRequest();
		}
		else {
			that.xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
		}
		
		if (that.xmlhttp === null) {
			return false;
		}
		else {
			that.xmlhttp.onreadystatechange = function() {
				if (that.xmlhttp.readyState == 4) {
		  			that.updating = false;
		  			
		  			if(callbackFunction != undefined && callbackFunction != null) {
		  				callbackFunction(that.xmlhttp.responseText, params, that.xmlhttp.status, that.xmlhttp.responseXML);
		  			}
				}
			};
			
			that.updating = new Date();
			// set the timestamp
			getVars.tid = that.updating.getTime();
			var getString = that.createQueryString(getVars);
			var postString = that.createQueryString(postVars);
			
			if (postString.length > 0) {				
				var uri = url; // + '?' + that.updating.getTime();
				if(getString != '') {
					uri += '?' + getString;
				}
				that.xmlhttp.open("POST", uri, true);
				that.xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
				that.xmlhttp.setRequestHeader("Content-Length", postString.length);
				that.xmlhttp.send(postString);
			}
			else {
				var uri = url;
				if(getString != '') {
					uri += '?' + getString;
				}
				
				DebugLog("ajax: " + uri, debug);
				that.xmlhttp.open("GET", uri, true);
				that.xmlhttp.send(null);
			}
			return true;
		}
	};
	
	this.createQueryString = function(passVars)
	{
		var string = '';
		for(var key in passVars) {
			key = encodeURIComponent(key);
			value = passVars[key];
			value = encodeURIComponent(value);
			
			if(string == '') {
				string = key + '=' + value;
			}
			else {
				string += '&' + key + '=' + value;
			}
		}
		
		return string;
	}
	
}




