
var pageMgr = new pageMgr();

function stripInitialBlank(value){
	var indx = 0;
	while(	indx<value.length&&
				(value[indx]==" "||
				value[indx]=="\n"||
				value[indx]=="\r"||
				value.charCodeAt(indx)==9||
				value.charCodeAt(indx)==13||
				value.charCodeAt(indx)==10||
				value.charCodeAt(indx)==32))
		indx++;
		
	return value.substring(indx, value.length);
		
	//return value.slice(indx);
}

/*
Invia una notifica di un evento al server previa
conferma da parte dell'utente:
	reqtype:	typo richiesta
	objname:	identificativo dell'oggetto che ha generato l'evento
	objid:		id dell'oggetto client
	eventid:	identicativo dell'evento generato
	actionid:	identificativo azione
	container:	oggetto DOM che contiene il nodo
	params:		parametri associati all'evento 
	msg:		messaggio mostrato all'utente che avr la possibilit di
				scelgliere se proseguire con la chiamata ajax
*/
function _sendWithConfirm(	serviceid,
							target,
							params,
							msg){
	if(confirm(msg))
		this.sendRequest(	reqtype,
							params);
}

/*
Invia una notifica di un evento al server:
	reqtype:	typo richiesta
	objname:	identificativo dell'oggetto che ha generato l'evento
	objid:		id dell'oggetto client
	eventid:	identicativo dell'evento generato
	actionid:	identificativo azione
	container:	oggetto DOM che contiene il nodo
	params:		parametri associati all'evento  
*/
function _sendRequest(	serviceid, 
						target,
						params){

	//alert("params='"+params+"'");
	
	if(this.busy==false){
		this.timout=40;
		this.busy=true;
		this.xmlhttp.open(	this.method,					this.listener+"?serviceId="+serviceid+"&target="+target+"&"+params,
							true);
		//alert (this.listener+"?serviceId="+serviceid+"&target="+target+"&"+params);
		this.onreadystatechange=this.handler();
		this.xmlhttp.send(null);
		//this.onreadystatechange=this.handler();
	}else{
		alert("Errore: Un'altra richista http e' gia' attiva!");
		node=document.getElementById(target+"0");
		if(node!=null){
			node.innerHTML="";
		}
	}
}

/*
Invia una notifica di un evento al server:
	reqtype:	typo richiesta
	objname:	identificativo dell'oggetto che ha generato l'evento
	objid:		id dell'oggetto client
	eventid:	identicativo dell'evento generato
	actionid:	identificativo azione
	container:	oggetto DOM che contiene il nodo
	params:		parametri associati all'evento  
*/
function _sendDoubleRequest(	serviceid, 
						target,
						params){

	_sendRequest(	serviceid, 
						target,
						params);
	while(this.busy==true);
		
	_sendRequest(	serviceid, 
						target,
						params);

}

/*
riempie un tag html con un elenco di tag html
	target:	tag in cui iniettare il codice html
	body:	elenco di tag da iniettare in target
*/
function _executeInject(target, body){
	//alert("inject\ntarget="+target);
	// ricerco il target
	if(body!=""){
		node=document.getElementById(target);
		//alert("vediamo se  valorizzato...");
		if(node!=null){
			//alert("ok trovato");
			node.innerHTML=body;

		}
	}
	//alert(target+"--"+body);
}

/*
appende in un tag html un elenco di tag
	target:	tag in cui iniettare il codice html
	body:	elenco di tag da iniettare in target
*/
function _executeAppend(target, body){
	//alert("inject\ntarget="+target);
	// ricerco il target
	if(body!=""){
		node=document.getElementById(target);
		//alert("vediamo se  valorizzato...");
		if(node!=null){
			//alert("ok trovato");
			//alert(node.innerHTML);
			//alert('BODY = '+body);
			node.innerHTML=node.innerHTML+body;

		}
	}
	//alert(target+"--"+body);
}

/*
mostra un messaggio all'utente
*/
function _showTrace(msg){
	alert("Trace:\n"+msg);
}

/*
mostra un messaggio di errore all'utente
*/
function _showError(msg){
	alert("Error:\n"+msg);
}

/*
esegue un comando.
*/
function _executeCmd(command){
	//alert(command);
	command=stripInitialBlank(command);
	//alert(command);
	if(command!=""){
		var itemList=new Array();
		itemList=command.split("|");
	
		if(itemList[0]=="inject")
			this.executeInject(itemList[1],itemList[2]);
		
		else if(itemList[0]=="shwerr")
			this.showError(itemList[1]);

		else if(itemList[0]=="shwtrc")
			this.showTrace(itemList[1]);

		else if(itemList[0]=="append")
			this.executeAppend(itemList[1],itemList[2]);
		
		else alert("incorrect communication:"+command);
		
	}
}

/*
processa un elenco di comandi
*/
function _executeCmds(){
	//alert("_executeCmds");
	commands=this.xmlhttp.responseText;
	//alert("prima ("+commands.charCodeAt(0)+") "+commands.length);
	
	commandsStripped=stripInitialBlank(commands);
	//alert("dopo ("+commandsStripped.charCodeAt(0)+") "+commandsStripped.length);
	
	//if(commandsStripped[0]=="\r")
	//	alert("spazio");
	//else
	//	alert("boooo:"+commandsStripped.charCodeAt(0));
	
	var cmdList = new Array();
	cmdList=commandsStripped.split('@');
	//alert("numero comandi: "+ cmdList.length);
	for(indx=0;indx<cmdList.length;indx++){
		//alert("index "+indx);
		this.executeCmd(cmdList[indx]);
	}
}

/*
handler di risposta ad una chiamata ajax
*/
function processResponse(){

	this.timout--;
	
	if(this.timout!=0){
	
		if (pageMgr.xmlhttp.readyState == 4){
  			if(pageMgr.xmlhttp.status == 200){
	  			//ok, reimposto il gestore ajax e richiama l'apposto handler
	  			pageMgr.reset();
	    		pageMgr.executeCmds();
	  		}else{
	  			// errore http
	  			pageMgr.reset();
	    		alert("Operazione fallita, http error: " + pageMgr.xmlhttp.status);
	    	}
	    }
	}else{
		// timeout scaduto
		pageMgr.reset();
		alert("Timeout error");
	}
}

/*
handler dell'evento asincrono
*/
function _handler(){
	//setTimeout("processResponse();",this.delay);
	pageMgr.timerID=setInterval("processResponse();",this.delay);	
}

function _reset(){
	clearInterval(pageMgr.timerID);
	this.timerID=0;
	this.busy=false;
	this.timout=40;
}

function pageMgr(){

	// identificativo dell'itervallo settato nel metodo _handler
	this.timerID=0;
	//-----------------

	// semaforo che impone la serializzazione di eventuali chiamate multiple non permesse
	// dall'attuale tecnologia ajax
	this.busy=false;
	//-----------------
	
	// tempo massimo di attesa per una chiamata ajax ( vedi script initapp.js )
	this.timout=40;
	//-----------------
	
	// ritardo introdotto per gestire le chiamate ajax. vedi script initapp.js
	this.delay=250;
	//-----------------
	
	// metodo utilizzato per inviare i dati http tramite ajax
	this.method="get";
	//-----------------
	
	// servlet che rimane in ascolto delle chiamate ajax. vedi script initapp.js
	//this.listener="http://"+domain+"/"+listener;
	this.listener="http://www.wcn2009.org/sites/0/IT/listner.tpl";
	//-----------------
	
	// handle che processa le risposte alle chiamat eajax
	this.handler=_handler;
	//-----------------
	
	// metodo che invia dati in formato http tramite ajax al server
	this.sendRequest=_sendRequest;
	//-----------------
	
	// metodo che invia dati in formato http tramite ajax al server
	this.sendDoubleRequest=_sendDoubleRequest;
	//-----------------
	
	// metodo che invia dati in formato http tramite ajax al server previa 
	// conferma da parte dell'utente.
	this.sendWithConfirm=_sendWithConfirm;
	//-----------------
	
	// oggetto che implemente le chimate http asincrone. fa riferimento
	// alla libreria sarissa
	this.xmlhttp = new XMLHttpRequest();
	//-----------------
	
	// metodo che esegue una serie di comandi pervenuti dal server
	// dopo una chiamate ajax
	this.executeCmds=_executeCmds;
	//-----------------
	
	// metodo che esegue un singolo comando proveniente dal server
	// a seguito di una chiamata ajax
	this.executeCmd=_executeCmd;
	//-----------------
	
	// iniezione di codice html in un tag della pagina
	this.executeInject=_executeInject;
	//-----------------
	
	// mostra un messaggio di errore
	this.showError=_showError;
	//-----------------
	
	// mostra un messaggio informativo
	this.showTrace=_showTrace;
	//-----------------
	
	// inietta un elenco di tag html in un contenitore in aggiunta a quelli 
	// gi esistenti
	this.executeAppend=_executeAppend;
	//-----------------
	
	// inizializza il gestore delle chiamate ajax
	this.reset=_reset;
	//-----------------

}