var CONTENT_DIV = getObjectById("content"),
    isAjaxRunning = false,                                                  //Impedisce che vengano eseguite richieste Ajax Multiple
    maxTime = 0,                                                            //Tempo massimo di esecuzione per ajax in secondi
    ajaxRequestsBaseUrl = "http://www.romaincasa.net/";         //Url al quale inviare le richieste Ajax




function XMLhttpREQUEST(){

  var XHR = null,
  browserUtente = navigator.userAgent.toUpperCase();

 if(typeof(XMLHttpRequest) === "function" || typeof(XMLHttpRequest) === "object")  // browser standard con supporto nativo, non importa il tipo di browser
  XHR = new XMLHttpRequest();


 else
   if(window.ActiveXObject &&  browserUtente.indexOf("MSIE 4") < 0)
     if(browserUtente.indexOf("MSIE 5") < 0)  // la versione 6 di IE ha un nome differente per il tipo di oggetto ActiveX
       XHR = new ActiveXObject("Msxml2.XMLHTTP");
     else   // le versioni 5 e 5.5 invece sfruttano lo stesso nome
       XHR = new ActiveXObject("Microsoft.XMLHTTP");

 return XHR;
}

function ajaxPOSTrequest(url, vars, values, maxtime){
  if(isAjaxRunning)
    return false;

  //Backup Content
  CONTENT_DIV_INNER_HTML = CONTENT_DIV.innerHTML;

  //Loading Image
  CONTENT_DIV.innerHTML = "<img src=\"images/loading.gif\" align=center style=\"padding-top:50px\">";


  var
    ajax = XMLhttpREQUEST(),
    contentDIV = getObjectById("content"),
    requestDate = new Date(),
    requestStartTime = requestDate.getTime();//,
    maxTime = maxtime;

  if(ajax) {
    isAjaxRunning = true;

    ajax.open("post", ajaxRequestsBaseUrl+url, true);
    ajax.setRequestHeader("connection", "close");
    ajax.setRequestHeader("content-type", "application/x-www-form-urlencoded");

    ajax.onreadystatechange = function() {
      if(ajax.readyState === readyState.COMPLETATO) {   // se la richiesta è già stata completata
        checkMaxTime = function(){};          // annulliamo la funzione di verifica tempo
        isAjaxRunning = false;

        if(statusText[ajax.status] === "OK") {
          CONTENT_DIV.innerHTML = ajax.responseText;
          loadRetrivedJS(CONTENT_DIV);
          //alert("COMPLETE CODE PLEASE");
          resizeGUI();
        }
        else{
          alert("Impossibile effettuare l'operazione richiesta.\nErrore riscontrato: " + statusText[ajax.status]);
          //RESTORE OLD CONTENT_DIV
          CONTENT_DIV.innerHTML = CONTENT_DIV_INNER_HTML;
        }
      }
      if(maxTime < 1000) {
          maxTime = maxTime * 1000;// conversione in millisecondi
          checkMaxTime = function() {
            requestDate = new Date();
            if((requestDate.getTime() - requestStartTime) > maxTime) {
              alert("Timeout waiting for server response, please try again!");
              ajax.onreadystatechange = function(){return;};
              ajax.abort();
              isAjaxRunning = false;
              CONTENT_DIV.innerHTML = CONTENT_DIV_INNER_HTML;
            }
            else  // se invece il tempo è inferiore al timeout
              setTimeout(checkMaxTime, 100);
          };
          checkMaxTime();
        }
      };

    var varsString = "";
    for(var i = 0; i < vars.length; i++)
      varsString += escape(vars[i]) + "=" + escape(values[i]) + "&";
    ajax.send(varsString);
  }
}

function loadRetrivedJS(element){
	var head = document.getElementsByTagName("head").item(0);

	var tags = "";
	for(var i = 0; i< element.childNodes.length; i++)
		if(element.childNodes[i].tagName == "SCRIPT")
			if(element.childNodes[i].src != "undefined" && element.childNodes[i].src.length ){
				var url=element.childNodes[i].src;
				removeLoadedScript(head,url);
				element.removeChild(element.childNodes[i]);
				loadScript(url);
			// 				alert("loaded: " + url);
			}
			else
				eval(element.childNodes[i].innerHTML);
				//alert("Attenzione: Non e' attualmente supportato il caricamento dinamico di script inline!");
		else
			loadRetrivedJS(element.childNodes[i]);
}

function removeLoadedScript(head, url){

  for(var i = 0; i< head.childNodes.length; i++)
    if(head.childNodes[i].tagName == "SCRIPT")
      if(head.childNodes[i].src == url){
        head.removeChild(head.childNodes[i]);
      }
}











/** FUNZIONI */


	
	// funzione per assegnare un oggetto XMLHttpRequest
		function assegnaXMLHttpRequest() {
			var
				XHR = null,
				browserUtente = navigator.userAgent.toUpperCase();
			if(typeof(XMLHttpRequest) === "function" || typeof(XMLHttpRequest) === "object")
				XHR = new XMLHttpRequest();
			else if(window.ActiveXObject && browserUtente.indexOf("MSIE 4") < 0) {
				if(browserUtente.indexOf("MSIE 5") < 0)
					XHR = new ActiveXObject("Msxml2.XMLHTTP");
				else
					XHR = new ActiveXObject("Microsoft.XMLHTTP");
			}
			return XHR;
		};



/** OGGETTI / ARRAY */

	// oggetto di verifica stato
		var readyState = {
			INATTIVO:	0,
			INIZIALIZZATO:	1,
			RICHIESTA:	2,
			RISPOSTA:	3,
			COMPLETATO:	4
		};

	// array descrittivo dei codici restituiti dal server
	// [la scelta dell' array � per evitare problemi con vecchi browsers]
		var statusText = new Array();
		statusText[100] = "Continue";
		statusText[101] = "Switching Protocols";
		statusText[200] = "OK";
		statusText[201] = "Created";
		statusText[202] = "Accepted";
		statusText[203] = "Non-Authoritative Information";
		statusText[204] = "No Content";
		statusText[205] = "Reset Content";
		statusText[206] = "Partial Content";
		statusText[300] = "Multiple Choices";
		statusText[301] = "Moved Permanently";
		statusText[302] = "Found";
		statusText[303] = "See Other";
		statusText[304] = "Not Modified";
		statusText[305] = "Use Proxy";
		statusText[306] = "(unused, but reserved)";
		statusText[307] = "Temporary Redirect";
		statusText[400] = "Bad Request";
		statusText[401] = "Unauthorized";
		statusText[402] = "Payment Required";
		statusText[403] = "Forbidden";
		statusText[404] = "Not Found";
		statusText[405] = "Method Not Allowed";
		statusText[406] = "Not Acceptable";
		statusText[407] = "Proxy Authentication Required";
		statusText[408] = "Request Timeout";
		statusText[409] = "Conflict";
		statusText[410] = "Gone";
		statusText[411] = "Length Required";
		statusText[412] = "Precondition Failed";
		statusText[413] = "Request Entity Too Large";
		statusText[414] = "Request-URI Too Long";
		statusText[415] = "Unsupported Media Type";
		statusText[416] = "Requested Range Not Satisfiable";
		statusText[417] = "Expectation Failed";
		statusText[500] = "Internal Server Error";
		statusText[501] = "Not Implemented";
		statusText[502] = "Bad Gateway";
		statusText[503] = "Service Unavailable";
		statusText[504] = "Gateway Timeout";
		statusText[505] = "HTTP Version Not Supported";
		statusText[509] = "Bandwidth Limit Exceeded";


