var maxSecondsWait= 5;
var timeOutCheckWait= 500;
var timeoutMsg1= 'Il server tarda a rispondere!';
var timeoutMsg2= 'Ritentare fra qualche secondo o segnalare il problema all\'assistenza';
function XHConn(){
	var xmlhttp = null;
	var result= true;
	var browser = navigator.userAgent.toUpperCase();
	if(typeof(XMLHttpRequest) === "function" || typeof(XMLHttpRequest) === "object"){
				xmlhttp = new XMLHttpRequest();
	}
	else if(window.ActiveXObject && browser.indexOf("MSIE 4") < 0){
		if(browser.indexOf("MSIE 5") < 0){
			xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
		}
		else{
			xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
		}
	}
	if (xmlhttp===null){result= false;}
	this.connect = function(sURL, mMethod, sVars, fnDone, fnError){
		var callupDate = new Date();
  		var callupStart = callupDate.getTime();
  		var checkWaitInitialized = false;
		var checkSpentTime=function(){};
  		var maxWait;
		var timeoutID= 0;
		var sMethod = mMethod.toUpperCase();
		xmlhttp.open(sMethod, sURL, true);
		xmlhttp.setRequestHeader("connection", "close");
		if(sMethod == "POST"){
			xmlhttp.setRequestHeader("Method", "POST "+sURL+" HTTP/1.1");
        	xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
			xmlhttp.setRequestHeader('Content-Length', sVars.length);
		}
		xmlhttp.onreadystatechange = function(){
			if (xmlhttp.readyState == 4){
				if(xmlhttp.status == 200){
					window.clearTimeout(timeoutID);
					fnDone(xmlhttp);
			   	}
				else{
					fnError(xmlhttp);
				}
			}
			else if(!checkWaitInitialized){
				maxWait= maxSecondsWait * 1000;
				checkSpentTime= function(){
					callupDate = new Date();
					if((callupDate.getTime() - callupStart) > maxWait) {
						//Expired time!!
						xmlhttp.onreadystatechange= function(){return;};
						xmlhttp.abort();
						alert(timeoutMsg1);
						alert(timeoutMsg2);
  						location.reload(true);
					} 
					else {
						timeoutID= window.setTimeout(checkSpentTime, timeOutCheckWait);
					}
          		};
				checkSpentTime();
				checkWaitInitialized = true;
				
          	}
		}
		xmlhttp.send(sVars);
	}
	return result;
};
function errorHandler(xhr){
	alert("HTTP error: "+xhr.status);
}
