﻿// documento XML
var _xDoc;

/** (C) HTML.IT - insieme di funzioni ed oggetti utili per interagire con ajax */

/** FUNZIONI */

	// funzione per prendere un elemento con id univoco
		function prendiElementoDaId(id_elemento) {
			var elemento;
			if(document.getElementById)
				elemento = document.getElementById(id_elemento);
			else
				elemento = document.all[id_elemento];
			return elemento;
		};
	
	// 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";
		
		
// funzione di caricamento testo,
// accetta una stringa contenente
// il nome di un file da leggere
function caricaTesto(nomeFile) {

  // variabili di funzione
  var
    // assegnazione oggetto XMLHttpRequest
    ajax = assegnaXMLHttpRequest(),
    // assegnazione elemento del documento
    elemento = prendiElementoDaId("contenuto-dinamico"),
    // risultato booleano di funzione
    usaLink = true;
  
  // se l'oggetto XMLHttpRequest non è nullo
  if(ajax) {
    // il link al file non deve essere usato
    usaLink = false;

    // impostazione richiesta asincrona in GET
    // del file specificato
    ajax.open("get", nomeFile, true);

    // rimozione dell'header "connection" come "keep alive"
    ajax.setRequestHeader("connection", "close");

    // impostazione controllo e stato della richiesta
    ajax.onreadystatechange = function() {
      
      // verifica dello stato
      if(ajax.readyState === readyState.COMPLETATO) {
        // verifica della risposta da parte del server
        if(statusText[ajax.status] === "OK")
          // operazione avvenuta con successo
          elemento.innerHTML=ajax.responseText;
        else {
          // errore di caricamento
          elemento.innerHTML = "Impossibile effettuare l'operazione richiesta.<br />";
          elemento.innerHTML += "Errore riscontrato: " + statusText[ajax.status];
        }
      } 
    }

    // invio richiesta
    ajax.send(null);
  }
   
  return usaLink;
} 


// funzione di caricamento testo,
// accetta una stringa contenente
// il nome di un file da leggere
function caricaXML(nomeFile) {

  // variabili di funzione
  var
    // assegnazione oggetto XMLHttpRequest
    ajax = assegnaXMLHttpRequest(),
    // assegnazione elemento del documento
    elemento = prendiElementoDaId("contenuto-dinamico"),
    // risultato booleano di funzione
    usaLink = true;
  
  // se l'oggetto XMLHttpRequest non è nullo
  if(ajax) {
    // il link al file non deve essere usato
    usaLink = false;

    // impostazione richiesta asincrona in GET
    // del file specificato
    ajax.open("get", nomeFile, true); // IMPORTANTE!!! false = chiamata sincrona

    // rimozione dell'header "connection" come "keep alive"
    ajax.setRequestHeader("connection", "close");

    // impostazione controllo e stato della richiesta
	ajax.onreadystatechange = function() {

	// verifica dello stato
	if(ajax.readyState === readyState.COMPLETATO) {

		// verifica della risposta da parte del server
		if(statusText[ajax.status] === "OK") {

		// verifica della validità dell'XML restituito dal server
		if(ajax.responseXML)
		{
			_xDoc=ajax.responseXML;
			// IMPORTANTE!!! IMPLEMENTARE QUESTA FUNZIONE PER LEGGERE L'XML
			parseXML();
		}
		else
			// visualizzazione contenuto letto
			// evitando di scrivere la risposta in modo
			// interpretabile dal browser
			elemento.innerHTML = "L'XML restituito dalla richiesta non è valido.<br />" +
				ajax.responseText.split('<').join("&lt;").split('>').join("&gt;");
		}
		else
		// errore di caricamento
		elemento.innerHTML = "Impossibile effettuare l'operazione richiesta.<br />" +
				"Errore riscontrato: " + statusText[ajax.status];
	};
	};

    // invio richiesta
    ajax.send(null);
  }
   
  return usaLink;
}

// funzione per leggere il contenuto presente
// all'interno di un nodo XML, ad esempio
// su <guida>ajax</guida> restituisce solo ajax
function leggiContenuto(item, nomeNodo) {
  return item.getElementsByTagName(nomeNodo).item(0).firstChild.nodeValue;
};

function SelectNodes(pathNodo)
{
	return _xDoc.getElementsByTagName(pathNodo);
}

function SelectChildren(nodoPadre,nomeFiglio)
{
	return nodoPadre.getElementsByTagName(nomeFiglio);
}

function GetAttributeValue(nodo,nomeAttr)
{
	return nodo.getAttribute(nomeAttr);
}

/*
function SelectChildren(nodoPadre,pathChildren)
{
	var xPath=pathChildren.split('/');
	var xNode=nodoPadre;
	var xTemp;
	for (i=0;i<xPath.length;i++)
	{
		xTemp=xNode.getElementsByTagName(xPath[i]);
		alert(xTemp.length);
	}
	return xNode;
}
*/

function SelectSingleNode(pathNodo,nomeAttr,valoreAttr)
{
	var nodes=SelectNodes(pathNodo);
	for (i=0;i<nodes.length;i++)
	{
		if (nodes[i].getAttribute(nomeAttr)==valoreAttr)
		{
			return nodes[i];
		}
	}
	return null;
}

function SelectSingleNodeValue(pathNodo,nomeAttr,valoreAttr)
{
	var nodes=SelectNodes(pathNodo);
	for (j=0;j<nodes.length;j++)
	{
	//alert(nodes[j].getAttribute(nomeAttr) + " - " + valoreAttr);
		if (nodes[j].getAttribute(nomeAttr).toString()==valoreAttr)
			return(nodes[j].childNodes[0].nodeValue);
	}
	/*
	for (i=0;i<nodes.length;i++)
	*/
	{/*
		//if (nodes[i].getAttribute(nomeAttr)==valoreAttr)
		//{
			//return nodes[i].nodeValue;
			//alert(nodes[i].getAttribute(nomeAttr));
			//return;
			//return nodes[valoreAttr].nodeValue;
		//}
		*/
	}
	
}



