// AJAX Function 
// Utilizzo:
// var ajaxCaller = new AjaxCaller();
// ajaxCaller.effettuaChiamataAjax("async", // action
// 			  												 null,   // id element innerHTML (Se viene passato l'elemento con l'id relativo viene popolato con l'html restituito)
// 																 true,   // showalert (Mostra in un messaggio alert il testo contenuto nel tag ritornato <alert>Testo</alert>)
// 																 "tipoRaggServ="+tipoRaggServ+"&action="+action+"&idBO="+idBO, // get per la chiamata asincrona
// 																 function(){controllaConStoredCallbak(ajaxCaller);}); // funzione di callback (per avere il riferimento al caller 
//																																											// č necessario costruire la funzione anonima come nell'esempio)
//
// L'XML generato dalla chiamate deve essere naturalmente ben formato e 
// deve avere definiti due tag obbligatori: <esito> e <descrizione>,
// dove esito č un valore numerico che per OK deve essere uguale a 0 (zero)
// qualora sia diverso da 0 apparirā un alert a schermo con la descrizione 
// inserita nel tag <descrizione>
//
// Esempio di callback:
//
// function controllaConStoredCallbak(ajaxCaller){
//	
//   var objNameConf = objControllaConStored+"_conf";
//
//	 // Verifico l'esito della chiamata Ajax.
//	           
//   if (ajaxCaller.esitoChiamataAjax.esito == 0){
//          document.all[objNameConf].value = "Y";
//  } else  {
//          document.all[objNameConf].value = "F";
//  }
//
// }
//
//
//
// Se si vuole utilizzare il popolamento integrato di un innerHTML č obbligatorio
// utilizzare il tag <inner_html> da cui verrā estratto appunto l'xml da inserire
// nell'oggetto html indicato dal parametro id element innerHTML.
// Sotto un esempio di xml ben formato col tag inner_html all'interno.
//
//				<?xml version="1.0" ?>
//				<asyncxmlresponse>
//					<esito>0</esito>
//					<descrizione>OK</descrizione>
//					<inner_html>
//						<select>
//							<option value="1">Uno</option>
//							<option selected="true" value="2">Due</option>
//						</select>
//					</inner_html>
//				</asyncxmlresponse>
///////////////////////////////////////////////////////////////

EsitoChiamataAjax = function(xml){
	
	try {
		if (typeof xml != 'undefined' && 
			(typeof xml.parseError == 'undefined' || xml.parseError.errorCode == 0)
			){
			this.xml = xml;	
			this.esito = this.getValueByTagName("esito");
			this.descrizione = this.getValueByTagName("descrizione");
		} else {
			alert("Si e' verificato un problema durante il parsing dell'xml di risposta: \n"+xml.parseError.reason);
		}
	} catch (ex){
		this.esito = -999;
		this.descrizione = "Errore durante l'invocazione ["+ex.description+"]";
	}
	
}

EsitoChiamataAjax.prototype = {

	xml: new Object(),
	esito: -9999,
	descrizione: 'Non inizializzato',
	getEsito: function (){
		return this.esito;
	},
	
	getValueByTagName: function (tagName){		
		var element = (this.xml).getElementsByTagName(tagName)[0];
		var value = element.firstChild.data;
		return value;
			
	},
	getListByTagName: function (tagName){ 
		var list = (this.xml).getElementsByTagName(tagName);
		return list;
			
	},
	getSingleNode: function (xpath){
		return (this.xml).selectSingleNode(xpath);
	},
	getInnerHtml: function (){
		return this.getSingleNode('//inner_html').firstChild.xml;
	},
	getValueElementListByTagAndIndex: function(tagName, numElement){
		var list = this.getListByTagName(tagName);
		var element = list[numElement];
		var value = element.firstChild.data;
		return value;
	
  }
	
}

var xmlHttpRequest;

AjaxCaller = function(){}

AjaxCaller.prototype = {
	
	idElementToRefresh : null,
	esitoChiamataAjax: null,
	callbackFunction: null,
	showAlert: false,
	asyncRequest: true,
	
	effettuaChiamataAjax: function(invokedUrl, idElement, showAlert, params, callback) { // Stringa di parametri divisi da &
		
		this.showAlert = showAlert;
		this.callbackFunction = callback;
		this.idElementToRefresh = idElement;
		
		if (window.XMLHttpRequest) { // Non valido per Internet Explorer
			xmlHttpRequest = new XMLHttpRequest();
		} else if (window.ActiveXObject) { // Internet Explorer
			xmlHttpRequest = new ActiveXObject("Microsoft.XMLHTTP");
		}
		try {
			if (xmlHttpRequest) {
				var verificaStato = this.verificaStato;
				var innerRef = this;
				xmlHttpRequest.onreadystatechange = function(){
																												verificaStato(innerRef);
																											};
				xmlHttpRequest.open("POST", invokedUrl, this.asyncRequest);
			} else {
				alert("Si č verificato un errore imprevisto");
				return;
			}
			// Lunghezza per la post
			xmlHttpRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
			xmlHttpRequest.setRequestHeader("Content-length", params.length);
			xmlHttpRequest.setRequestHeader("Connection", "close");
			xmlHttpRequest.send(params);
			
		} catch (ajaxException) {
			alert("Si č verificato un problema: "+ajaxException.description);
		}
		
		return this.esitoChiamataAjax;
	},
	
	verificaStato : function(ajaxCaller) {

		if (xmlHttpRequest.readyState == 4) { // Operazione completata
			if (xmlHttpRequest.status == 200) { // OK 
				
				ajaxCaller.esitoChiamataAjax = new EsitoChiamataAjax (xmlHttpRequest.responseText);
				
				if (ajaxCaller.esitoChiamataAjax.esito == 0){

					if (ajaxCaller.idElementToRefresh != null && ajaxCaller.idElementToRefresh != ''){
						var elementToRefresh = document.getElementById(ajaxCaller.idElementToRefresh);
						
						if (typeof elementToRefresh != 'undefined'){
							elementToRefresh.innerHTML = ajaxCaller.esitoChiamataAjax.getInnerHtml();
						} else {
							alert('Si č verificato un errore applicativo: l\'elemento con id ['+ajaxCaller.idElementToRefresh+'] č indefinito.');
						}
					
					} 
					
					if(typeof ajaxCaller.showAlert != 'undefined' && ajaxCaller.showAlert){
						try{
							alert(ajaxCaller.esitoChiamataAjax.getValueByTagName("alert"));
						} catch (alertException){
								// Elemento alert non presente nell'XML
							}
					}
				
				} else {
					alert(ajaxCaller.esitoChiamataAjax.descrizione);
				}		
				
			} else {
				alert("Si č verificato un problema: " + xmlHttpRequest.statusText);
			}
				
				// Eseguo la callback se č stata passata
				
				if (typeof ajaxCaller.callbackFunction == 'function'){
					ajaxCaller.callbackFunction.call(this);
				}
			}
	}
	
}
