//Copyright (c) 2004-2008 Anastasis Societa' Cooperativa,Bologna,Italy - www.anastasis.it
//	This copyright notice must stay intact for use.

/*
*
* Attenzione, questa classe sottintende che:
* - i form registrati hanno id che inizia con "upload_NOME" e mi ricavo il NOME
* - Tutti gli altri elementi nel form e nella progress bar usano NOME:
*   - id dell'input file del form: file_NOME
*   - id del div della progressbar: progressbar_NOME
*   - div o span dove inserisco il nome del fil inviato all'nterno della zona della progressbar: nomefile_NOME
*   - div o span dove inserisco la percentuale di progresso all'nterno della zona della progressbar: progresso_NOME
*   - div dell'indicatore della percentuale completata: indicatore_progress_NOME (parte con style="width: 0%")
*   - div che contiente il campo file: div_NOME
*   - div con bottone remove: divremove_NOME
*
* Comunque tollera la mancanza della progressbar o di uno qualunque dei suoi elementi.
* 
*
* L'unica classe pubbica e' FormSender, che espone questi metodi:
* - costruttore FormSender(indirizzo handshake, indirizzo upload, funzione di callback alla fine di tutto l'invio)
* - register (id form da registrare, nome del campo di tipo file del form, id dell'input dove viene inserito l'ID allegato ricevuto in risposta) 
* - send(funzione di callback) - invia tutti e chiama callback; prima naturalmente bisogna registrare i form con file  
*/
       
//---------------------CLASSE-FORM-SENDER-------------------------------------//

//-------METODI PUBBLICI

/**
 * Costruttore.
 * @param url_prepare_upload String; l'url per l'handshake
 * @param url_upload_status String; l'url per il monitoraggio dell'upload; se ่ null non c'่ monitoraggio
 * @param callback Function; la chiama dopo aver inviato tutti i form registrati  
 */
Anastasis.FormSender= function (url_prepare_upload,url_upload_status)
{
  this.forms=new Array();   
  this.url_prepare_upload=url_prepare_upload;
  this.url_upload_status=url_upload_status;
  this.sentForms=0;   
}

/**
 * @param  idForm String-ID; id form da registrare
 * @param nomeCampoFile String; name del campo di tipo file del form
 * @param contenitoreID String-ID;id dell'input dove viene inserito l'ID allegato ricevuto in risposta
 */
Anastasis.FormSender.prototype.register=function(idForm,nomeCampoFile,contenitoreID)
{      
  this.forms.push(new Anastasis.FormToSend(idForm,nomeCampoFile,contenitoreID,this.url_upload_status));
}

Anastasis.FormSender.prototype.unRegister=function(idForm)
{          
  var tmp=new Array(); 
  var removed; 
  for(var i=0;i<this.forms.length;i++)
  {    
    if(this.forms[i].id!=idForm) 
      tmp.push(this.forms[i]);
    else removed=this.forms[i];    
  }
  this.forms=tmp;
  return removed;
}

Anastasis.FormSender.prototype.send=function(callback)
{
  this.callback=callback;
  
  //Se nessun form di allegati si รจ registrato, invia subito  
  if(this.forms.length==0)
  {    
    this.allDone();
    return;
  }
  if(this.url_prepare_upload)
  {
	  //handashake: avverte il server che sta per inviare i form
	  //quando riceve la risposta parte la sendAll
	  var fs=this;   
	  var handle=function(response){fs.sendAll();};
	  anastasis.ajax.send(new Object(),this.url_prepare_upload,"GET",false,true,handle);   	  
  }
  else
  {
  	this.sendAll();
  }
}

/**
 * Comando per rimuovere un file allegato
 */ 
Anastasis.FormSender.prototype.remove=function(url,idForm,nomeCampoFile,contenitoreID,callback)
{
  if(!confirm("Rimuovere l'allegato?\nATTENZIONE: L'operazione non e' reversibile e comporta anche il salvatggio di tutti i dati del modulo.")) return;
  
  var action=function(response)
  			{
  				if(!response.nodeType) response=Anastasis.Utils.parseXML(response);	    	
    			var msg=Anastasis.XMessage.buildXMessage(response);
    			 
  				if(msg.isErrorMessage()) alert(msg.error);
  				else if(callback) callback();
  			}
  anastasis.ajax.send(null,url,"GET",false,true,action);
}

//VARIABILI GLOBALI

Anastasis.FormSender.sentFilesCounter=0;

//-------METODI PRIVATI

Anastasis.FormSender.prototype.sendAll=function()
{          
  var fs=this;  
  for(var i=0;i<this.forms.length;i++)
  {    
    this.forms[i].invio(function(formSent,reply){fs.onFormSent(formSent,reply);});
  }
}

Anastasis.FormSender.prototype.onFormSent=function(formSent,reply)
{
  if(formSent.hasFile() || formSent.isExternalLink())
  {
    if(!document.getElementById(formSent.contenitoreID))
    {
      throw "Errore in salvataggio: Missing input container for ID Allegato";
    }
    var idAllegato=-1;
    try
    {    	    	
    	var xmldoc=null;
    	if(!reply.nodeType) reply=Anastasis.Utils.parseXML(reply);	
    	
    	var msg=Anastasis.XMessage.buildXMessage(reply); 
      
      if(msg.isErrorMessage())
      {
      	idAllegato=null;   	
        alert("Errore: "+msg.error);
      }
   	  else
   	  {
      	var figghio=msg.message.firstChild;
      	
  	  	while(figghio)
  	  	{
  	  		if(figghio.tagName) switch(figghio.tagName)
  	  		{
  	  				case "idAllegato":
  	  			if(figghio.text) //IE
  	  				idAllegato=figghio.text;
  	  			else
  	  				idAllegato=figghio.textContent;
  	  			break;
  	  			
  	  				case "errore":
  	  			var errore="";
  	  			if(figghio.text) //IE
  	  				errore=figghio.text;
  	  			else
  	  				errore=figghio.textContent;
  	  			alert(errore);
  	  			throw errore;
  	  			break;
  					case "campo":
  				var nome=""; var valore="";
  				var nipote=figghio.firstChild;
  				while(nipote)
  				{
  					switch(nipote.tagName)
  					{
  							case "name":
  						nome=nipote.text ? nipote.text : nipote.textContent;
  						break;	
  							case "value":
  						valore=nipote.text ? nipote.text : nipote.textContent;
  						break;					
  					}
  					nipote=nipote.nextSibling;
  				}
  				try{document.getElementById(nome).value=valore;}catch(e){alert("Manca il campo: "+nome);}
  				break;
  					default:
  				var inp=document.getElementById(figghio.tagName);
  				if(inp)
  				{
  					if(inp.tagName=="input")
  						inp.value=figghio.text ? figghio.text : figghio.textContent;
  				}
  				else
  				{		
  					var inp=document.createElement("input");
  					inp.type="hidden";
  					inp.name=figghio.tagName;
  					inp.value=figghio.textContent;				
  					document.getElementById(formSent.contenitoreID).parentNode.appendChild(inp);
  				}
  	  		}
  	  		figghio=figghio.nextSibling;	
  	  	}	 
      } 		  	
    }     
    catch(e){alert(e); idAllegato=-1;}
    if(idAllegato==-1) try { idAllegato=parseInt(reply); } catch(e){alert("Error in upload reply: \n"+reply);}
    document.getElementById(formSent.contenitoreID).value=idAllegato;
  }
  
  this.sentForms++;
  if(this.sentForms==this.forms.length) 
  {    
    this.allDone();
  }
}

Anastasis.FormSender.prototype.allDone=function()
{
	Anastasis.FormSender.sentFilesCounter=0;
	if(this.callback) this.callback();
}

//---------------------CLASSE-FORM-TO-SEND------------------------------------//

Anastasis.FormToSend=function (id,nomeCampoFile,contenitoreID,url_upload_status)
{
  this.id=id;
  this.formNode=document.getElementById(id);
  this.nomeCampoFile=nomeCampoFile;
  this.contenitoreID=contenitoreID;  
  this.supportUploadStatus=false;
  if(url_upload_status)this.supportUploadStatus=true; 
  try
  {
    this.nome=id.match(/upload_(.*)/)[1];
  } catch(e){alert("L'attributo ID del form non inizia con upload_");}
  
  this.progressBar=new Anastasis.ProgressBar(this.nome,url_upload_status);
}

Anastasis.FormToSend.prototype.invio=function(callback)
{  
  var fts=this;    

	var is_external_link=document.getElementById("is_external_link_"+this.nome);  
  	
  	//Se il campo file c'e' ,a e' vuoto (quindi non era obbligatorio),
  	//e non c'e'  is_external_link oppure c'e' e non e' checkato 
  	//simula un invio corretto ma in realta' non invia nulla
  	
  	if(document.getElementById("file_"+this.nome).value=="" && (is_external_link && !is_external_link.checked))
	{		
		if(callback)callback(fts,"ok"); 
		fts.onInviato("ok");
		return "ok";
	}  	
  	
  	var handle=function(response)
  				{
  					if(callback)callback(fts,response); 
  					fts.onInviato(response);
  				};
  	
  	if(!document.getElementById("file_"+this.nome).disabled)
  	{  	
	  	Anastasis.FormSender.sentFilesCounter++;	  		    	  	  	  
	    this.progressBar.setIdAndNomeFile(Anastasis.FormSender.sentFilesCounter,document.getElementById("file_"+this.nome).value);	    
	    this.formNode.style.display="none";
	    this.progressBar.show();  
	    if(this.supportUploadStatus) setTimeout(function(){fts.progressBar.askProgress();},1500);
  	}    
    anastasis.ajax.sendForm(this.id,handle);
}
    
Anastasis.FormToSend.prototype.onInviato=function(reply)
{    
    this.progressBar.completeProgress();
}

Anastasis.FormToSend.prototype.hasFile=function()
{    
    return ((document.getElementById("file_"+this.nome).value) ? true : false);
}

Anastasis.FormToSend.prototype.isExternalLink=function()
{    
    var is_external_link=document.getElementById("is_external_link_"+this.nome);
    return (is_external_link && is_external_link.checked);
}


//---------------------CLASSE-PROGRESS-BAR------------------------------------//

Anastasis.ProgressBar=function (nome,url_upload_status)
{
  this.id=0;
  this.url_upload_status=url_upload_status;
  this.div=document.getElementById("progressbar_"+nome);
  this.nomefile=document.getElementById("nomefile_"+nome);
  this.progresso= document.getElementById("progresso_"+nome);
  this.indicatore_progressbar=document.getElementById("indicatore_progressbar_"+nome);
}

Anastasis.ProgressBar.prototype.show=function()
{  
  if(this.div)
    this.div.style.display="";
}

Anastasis.ProgressBar.prototype.hide=function()
{
  if(this.div)
    this.div.style.display="none";
}

Anastasis.ProgressBar.prototype.setIdAndNomeFile=function(id,nome)
{  
  this.id=id;
  if(this.nomefile) this.nomefile.innerHTML=nome;
}

Anastasis.ProgressBar.prototype.askProgress=function()
{
  var pb=this;
  var action=function(response){pb.setProgress(response);}  
  anastasis.ajax.send(null,this.url_upload_status+this.id,"GET",false,true,action);  
}
    
Anastasis.ProgressBar.prototype.setProgress=function(response)
{              
  var pb=this;
  
  if(!response.nodeType) response=Anastasis.Utils.parseXML(response);
  response=Anastasis.XMessage.buildXMessage(response);
  
  if(response.type!="status") return;
  
  prog=parseInt(response.getContentOf("status"));
  if(prog<99) 
  {
    if(this.progresso) this.progresso.innerHTML=prog;
    if(this.indicatore_progressbar) this.indicatore_progressbar.style.width=prog+"%";
    setTimeout(function(){pb.askProgress();},500);
  }    
}

Anastasis.ProgressBar.prototype.completeProgress=function()
{            
  if(this.progresso) this.progresso.innerHTML=100;
  if(this.indicatore_progressbar) this.indicatore_progressbar.style.width="100%";      
}

