Anastasis.DetailEdit=function(idFormPrincipale,prepare_url,progress_url)
{
	var me=this;
	this.idFormPrincipale=idFormPrincipale;
	//anastasis.syncLoadScript("FormSender",true);	
	this.formSender=new Anastasis.FormSender(prepare_url,progress_url);
}

Anastasis.DetailEdit.prototype.register=function(idForm,nomeCampoFile,contenitoreID)
{	
	if(nomeCampoFile && !document.getElementById(contenitoreID))
	{
		var inp=document.createElement("input");
		inp.type="hidden";
		inp.id=contenitoreID;
		inp.name=contenitoreID;
		document.getElementById(this.idFormPrincipale).appendChild(inp);
	}
	this.formSender.register(idForm,nomeCampoFile,contenitoreID);
}

Anastasis.DetailEdit.prototype.invioFormPrincipale=function()
{
	var form=document.getElementById(this.idFormPrincipale);
	form.submit();	
}



Anastasis.DetailEdit.prototype.saveObjectAsNew=function()
{
	if (confirm("Attenzione, l'operazione puo' avere effetti collaterali in termini di consistenza delle relazioni: proseguire ugualemnte?"))	{
		document.getElementById("forced_post_save").value="post_save_as_new";
		return this.saveObject();
	}
}


Anastasis.DetailEdit.prototype.saveObject=function()
{
	if(!this.checkAll()) return;
	var me=this;	
	this.formSender.send(function(){me.invioFormPrincipale();});
}

Anastasis.DetailEdit.prototype.delObject=function(input_id)
{
	if (confirm("Confermare la cancellazione della scheda"))
	{  
		if(document.getElementById(input_id))
	    	document.getElementById(input_id).value="post_delete";
	    else
	    {
	    	var inp=document.createElement("input");
	    	inp.type="hidden";
	    	inp.id=input_id;
	    	inp.name=input_id;
	    	inp.value="post_delete";
	    	document.getElementById(this.idFormPrincipale).appendChild(inp);
	    }
	    document.getElementById(this.idFormPrincipale).submit();
	} 	
}

Anastasis.DetailEdit.prototype.backgroundSave=function(callback,loseCheck)
{
	// per compatibiliÃ  con le altre chiamate, in checkAll il par assume il significato di loseCheck
	// in modo che chi non lo passa continua a richiedere lo strictCheck
	if(!this.checkAll(loseCheck)) return;
	var me=this;	
	
	var action=function()
	{
		var handle=function(response){if(callback)callback(response);};
		anastasis.ajax.sendForm(me.idFormPrincipale,handle);				
	};	
	this.formSender.send(action);
  //Se nessun form di allegati si ï¿½ registrato, invia subito
  	  		 
}

Anastasis.DetailEdit.prototype.getInputInfo=function(input,info)
{
	var rep="";	
	if(document.getElementById("info_"+input.id))
	{
		var infostring=document.getElementById("info_"+input.id).value;
		var reg=new RegExp(info+'=(.*?)(\\||$)');
		var tmp=infostring.match(reg);
		if(tmp) rep=tmp[1];
	}
	if(!rep && document.getElementById(info+"_"+input.id))
	{
		rep=document.getElementById(info+"_"+input.id).value;
	}
	return rep;
}

Anastasis.DetailEdit.prototype.check=function(input,loseCheck)
{
	//alert(input.id+": caller is " + arguments.callee.caller.arguments.callee.caller.toString());
	
	//Se Ã¨ un elemento nascosto nel bottone add di un complexDetailEdit, ignoralo
	if(input.id && input.id.match("#NEWID")) return true;
	
	var value = input.value;
	var label="SCONOSCIUTO";
	
	if(document.getElementById("label_"+input.id))
	{
		label=document.getElementById("label_"+input.id).value;
	}

	var not_null=false;
	if (loseCheck)	{
		// loseCheck needs really-true val to invalidate
		if(document.getElementById("required_"+input.id) && document.getElementById("required_"+input.id).value=="really-true")
			not_null=true;
		}
	else {
		if(document.getElementById("required_"+input.id) && (document.getElementById("required_"+input.id).value=="true" || document.getElementById("required_"+input.id).value=="really-true"))
			not_null=true;
		}
		

	if (not_null && !value)
	{
		alert('Il campo "' + label + '" non puo\' essere vuoto!');
		return false;
	} 
	
	//Se non ï¿½ obbligatorio ed ï¿½ vuoto, va bene cosi'
	if(!value) return true;
	
	var tipo=null;
	if(document.getElementById("type_"+input.id))
	{
		tipo=document.getElementById("type_"+input.id).value;
	}

	if(!tipo) return true;

	switch(tipo)
	{
		case "2":
		/*
		 * Sostituisce la virgola con il punto, in modo da  
		 * essere coerente con il db
		 */
		input.value=input.value.replace(",",".");  
		if(!input.value.match(/^-?[0-9\.]*$/))
		{      
			alert('"'+label+'" deve essere un numero!');
			return false;
		}            
		break;
		case "25": // importo
			/*
			 * Sostituisce la virgola con il punto, elimina eventuiali punti di migliaia, 
			 * spazi e simbolo di euro
			 */
			input.value=input.value.replace(/\.(\d\d\d)/,"$1");
			input.value=input.value.replace(",",".");
			input.value=input.value.replace(/[^0-9^\.^-]*/,"");
			// disclaim: l'accrocchio seguente non è colpa di pego: restava effettivamente uno spazio non altrimenti eliminabile
			if(!input.value.match(/[0-9]$/))
			{
				input.value=input.value.substring(0,input.value.length-1);
			}			
			if(!input.value.match(/^-?[0-9\.]*$/))
			{      
				alert('"'+label+'" deve essere un importo!');
				return false;
			}            
			break;
		case "3":
		/*
		 * Sostituisce - e \ con /
		 * per essere coerente con il db
		 */
		input.value=input.value.replace(/-/g,"/");
		input.value=input.value.replace(/\\/g,"/");
		if (input.value=="NOW()")
		{
			return true;
			break;    
		}
		//Se l'anno e' specificato in due cifre:
		// - se il numero e' <= dell'anno corrente+5 (es. siamo nel 2009 e il numero e' 12)
		//      allora ci aggiuge davanti '20' (e divente 2012)
		// - altrimenti ci aggiunge davanti '19' (ad esempio 1935)
		if (input.value.match(/^\d+\/\d+\/\d\d$/))
		{      
			var els=input.value.match(/(^\d+\/\d+\/)(\d\d)$/);
			var year=els[2];
			var thisyear=(new Date()).getFullYear();
			thisyear=thisyear-2000;
			if(year<=thisyear+5) input.value=els[1]+"20"+year;
			else input.value=els[1]+"19"+year;
		}
		 
		if (!(input.value.match(/^\d+\/\d+\/\d\d\d\d$/)))
		{      
			alert('"'+label+'" deve essere una data valida nel formato gg/mm/aa o gg/mm/aaaa!');
			return false;
		}
		else
		{
			//controllo: 1<=giorno<=31, 1<=mese<=12, 1900<=anno<=2100
			var els=input.value.match(/0?(\d+)\/0?(\d+)\/(\d\d\d\d)/);      
			if(parseInt(els[1])<1 || parseInt(els[1])>31 || parseInt(els[2])<1 || parseInt(els[2])>12 || parseInt(els[3])<1900 || parseInt(els[3])>2100) 
			{      
				alert('"'+label+'" deve essere una data valida nel formato gg/mm/aa o gg/mm/aaaa!');
				return false;
			}
		}            
		break;	
		case "4":      
			if (not_null && !input.checked)
			{
				alert('Il campo "' + label + '" non puo\' essere vuoto!');
				return false;
			}        
			break;  
	}	
	return true;
}

Anastasis.DetailEdit.prototype.checkAll=function(loseCheck)
{
	var ok=true;	
	
	var inputs=new Array();
	var forms=document.getElementsByTagName("form");
	for(var i in forms)
	{
		if(!forms[i]) continue;
		if(forms[i].nodeType!=1) continue;
		var tmp=forms[i].getElementsByTagName("input");
		for(var i in tmp)
		{
			inputs=inputs.concat(tmp[i]);
		}
	}
				
	for(var i in inputs)
	{
		if(!inputs[i]) continue;
		if(inputs[i].nodeType!=1) continue;
		if(inputs[i].type=="hidden" || inputs[i].type=="button") continue;
		ok=ok & this.check(inputs[i],loseCheck);
		if(!ok) 
		{
			inputs[i].focus();
			return false;
		}
	}
	
	var inputs=document.getElementsByTagName("select");	
	for(var i in inputs)
	{
		if(!inputs[i]) continue;
		if(inputs[i].nodeType!=1) continue;
		ok=ok & this.check(inputs[i],loseCheck);
		if(!ok) 
		{
			inputs[i].focus();
			return false;
		}
	}	
	
	var inputs=document.getElementsByTagName("textarea");	
	for(var i in inputs)
	{
		if(!inputs[i]) continue;
		if(inputs[i].nodeType!=1) continue;
		ok=ok & this.check(inputs[i],loseCheck);
		if(!ok) 
		{
			inputs[i].focus();
			return false;
		}
	}
	
	return ok;		
}

/* forces save action (probably as a result of a "relation" link request)
 * Step 1: checkAll
 * Step 2: save 
*/
Anastasis.DetailEdit.prototype.forceSave=function(newUrl)
{
    if (document.getElementById("forced_post_save").value=="post_save_new")
    {
		//Lo fa qua anche se lo fa anche backgroundSave, perche' se e' false non deve cambiare l'action del form
      if(!this.checkAll(true)) return;
      if(!newUrl) newUrl="";
      var handle=function(reply)
      {
	      if(!reply.nodeType) reply=Anastasis.Utils.parseXML(reply);	      	   
	      var msg=Anastasis.XMessage.buildXMessage(reply);
	      if(msg.isErrorMessage())
	      {
	      	alert("Error: "+msg.error);
	      	window.location.reload();
	      }
	      else
	      {
		      var id=msg.getContentOf("id");
		      newUrl=newUrl+id;
		      window.location=newUrl;
		  }
      }
      var action=document.getElementById(this.idFormPrincipale).action;
      
      if(action.match("/Index"))
      	action=action.replace("/Index","/ModuleIndex");
	  else if(action.match(/^\?/))
	  	action="ModuleIndex"+action;
	  else throw "Action del form non compatibile: "+action;
	  
	  if(action.match(/q=(\w*)\/detail_edit/))
	  	action=action.replace(/q=(\w*)\/detail_edit/,"q=$1/detail_edit_xml");			
	  else throw "Action del form non compatibile: "+action;
	  
	  //Elimino un eventuale riferimeto al menu
      action=action.replace(/q=[^&]*?\/menu\/[^&]*?&/,""); 
      
      document.getElementById(this.idFormPrincipale).action=action;
      this.backgroundSave(handle,true);
      
	}
    else  {
      if(!this.checkAll(true)) return;
      if(!newUrl) newUrl="";
      var handle=function(reply)
      {
	      if(!reply.nodeType) reply=Anastasis.Utils.parseXML(reply);	      	   
	      var msg=Anastasis.XMessage.buildXMessage(reply);
	      if(msg.isErrorMessage())
	      {
	      	alert("Error: "+msg.error);
	      	window.location.reload();
	      }
	      else
	      {
		      if(newUrl) window.location=newUrl;
		  }
      }
      var action=document.getElementById(this.idFormPrincipale).action;
      
      if(action.match("/Index"))
      	action=action.replace("/Index","/ModuleIndex");
	  else if(action.match(/^\?/))
	  	action="ModuleIndex"+action;
	  else throw "Action del form non compatibile: "+action;
	  
	  if(action.match(/q=(\w*)\/detail_edit/))
	  	action=action.replace(/q=(\w*)\/detail_edit/,"q=$1/detail_edit_xml");			
	  else throw "Action del form non compatibile: "+action;	  
      
      //Elimino un eventuale riferimeto al menu
      action=action.replace(/q=[^&]*?\/menu\/[^&]*?&/,"");
      
      document.getElementById(this.idFormPrincipale).action=action;
      this.backgroundSave(handle,true);
    }
}


Anastasis.DetailEdit.prototype.remove=function(url,idForm,nomeCampoFile,contenitoreID)
{
	var me=this;
	this.formSender.remove(url,idForm,nomeCampoFile,contenitoreID,function(){me.onRemoved(idForm,nomeCampoFile);});
}

/**
 *  Quando viene ricevuta la conferma dell'eliminazione, si elimina davvero
 *  il riferimento al file e si ripristina il form di invio. 
 */ 
Anastasis.DetailEdit.prototype.onRemoved=function(idForm,nomeCampoFile)
{
  /*
  try
  {
    var removed=this.formSender.unRegister(idForm);
    var contenitoreID=removed.contenitoreID;
    var formPrincipale=document.getElementById(this.idFormPrincipale);
    
    var inp=document.createElement("input");
    inp.id=contenitoreID;
    inp.name=contenitoreID;
    inp.type="hidden";
    inp.value="0";  
    formPrincipale.appendChild(inp);    
	//this.backgroundSave(); //inutile...
    
    var nome=removed.nome;       
    document.getElementById("div_"+nome).style.display="";
    document.getElementById("file_"+nome).disabled=false;
    document.getElementById("divremove_"+nome).style.display="none";
    
    var inputs=removed.formNode.getElementsByTagName("input");
    for(var i in inputs)
    {
    	if(inputs[i] && inputs[i].name=="id_attachment")
    	{
    		inputs[i].parentNode.removeChild(inputs[i]);
    		break;
    	}
    }

    
    this.register(idForm,nomeCampoFile,contenitoreID);
  }catch(e) {alert(e);}
  */
  this.backgroundSave(function(){window.location.reload();},true);
}

/* Frasca: sperimentata con successo in iniziative solidali, provo ad introdurla in application: 
 * la chiama detail_edit in esci. Es:
 * 	  	  <a tabindex="60" href="javascript:areusure();" title="indietro">[ Esci ]</a>
 *           <span class="NoVisibility">|</span>
 */
function areusure()	{
if (confirm("Uscire senza salvare?"))
	history.back(); 
}

function confirm_exit()	{
	return confirm("Uscire senza salvare?");
}
