//Funzione che calcola i mesi totali relativi a tutte le abitazioni principali di un utente
//abitazioni già inserite e ceccate per modifica + quelle non ceccate
function SumMounthAbPrincCheck(frmName,p,val)
{
	var obj,obj1, id, mesi=0,mesip=0, newstr;
	var ab = new Array(),ab1 = new Array(), i=0, y=0,ck;

	if (p!='view')
	{
		
		obj=eval('document.'+frmName);
		name=eval('document.'+frmName+'.name');
		//alert(name);
		
		for(j=0;j<obj.elements.length;j++){
			 if(obj.elements[j].type=='hidden'){
				   newstr=obj.elements[j].name;
				   if (newstr.search('btAbitazione')!= -1 ){ //se è di tipo abitazione
	    			   newstr=newstr.replace("btAbitazione","");
		     		   ck=getObj(frmName,'id__seleziona'+newstr);
					   if(ck.checked){ //controllo che il relativo checkbox sia selezionato
						   ab[i]='id_mposs'+newstr;
						   //deb=ab[i];
						   //alert('deb '+deb+' i '+i);
						   i++;
					   }
					   else{
					       ab1[y]='id_mposs'+newstr;
						   //deb=ab[i];
						   //alert('deb '+deb+' i '+i);
						   y++;
					   }
				   }
			   
			 }
		}

        mesi=ab.length*val;
		for (j=0;j<ab1.length;j++){
			id=ab1[j];
			obj1=getObj(frmName,id);
			mesip= parseInt(obj1.value);
			//alert(mesip+'< >'+mesi)
			mesi=mesi+mesip;
		}
		
		//deb=mesi;
        //alert(' deb '+deb);
	}
	
 return mesi;
}

//Funzione che calcola i mesi totali relativi a tutte le abitazioni principali di un utente
//abitazioni già inserite
function SumMounthAbPrinc(frmName,p)
{
	var obj,obj1, id, mesi=0,mesip=0, newstr;
	var ab = new Array(), i=0, y=0;

	if (p!='view')
	{
		
		obj=eval('document.'+frmName);
		name=eval('document.'+frmName+'.name');
		//alert(name);
		
		for(j=0;j<obj.elements.length;j++){
			 if(obj.elements[j].type=='hidden'){
				   newstr=obj.elements[j].name;
				   if (newstr.search('btAbitazione')!= -1 ){
	    			   newstr=newstr.replace("btAbitazione","");
		     		   ab[i]='id_mposs'+newstr;
					   //deb=ab[i];
					  // alert('deb '+deb+' i '+i);
					   i++;
				   }
			   
			 }
		}
		for (j=0;j<ab.length;j++){
			id=ab[j];
			obj1=getObj(frmName,id);
			mesip= parseInt(obj1.value);
			//alert(mesip+'< >'+mesi)
			mesi=mesi+mesip;
		}
		
		//deb=mesi;
        //alert(' deb '+deb);
	}
	
 return mesi;
}

//Funzione che esegue i controlli su assegnazione di abitazione principale e pertinenze
function CtrlICIAbprincPert(frmName,p) 
{
	var obj, obj1, ctrl=true, newstr, dopp=false, tmp=0, mesi;
	var ab = new Array(),pert = new Array(),i=0,y=0;

	tmp=SumMounthAbPrinc(frmName,p);
	
	if (p!='view')
	{
		
		obj=eval('document.'+frmName);
		name=eval('document.'+frmName+'.name');
		//alert(name);
		
		for(j=0;j<obj.elements.length;j++){
		 
		 // alert(tmp);
		// p=obj.elements[j];
		// alert('nome '+p.name);
		 
		  if(obj.elements[j].type=='checkbox') {
			  if(obj.elements[j].checked){
			   newstr=obj.elements[j].name;
			   newstr=newstr.replace("form_basket[_","");
			   newstr=newstr.replace("]",""); 
			   if (newstr.search('abprinc')!= -1 ){
				   newstr=newstr.replace("abprinc","");
				   ab[i]=newstr;
				   mesi='id_mposs'+newstr;
				   //alert('mesi '+mesi);
				   obj1=getObj(frmName,mesi);
                   mesi= parseInt(obj1.value);
				   //alert('mesi '+mesi);
				   i++;
			   } 
			   else {
			       newstr=newstr.replace("seleziona","");  
				   if (newstr==ab[i-1]) dopp=true;
				   pert[i]=newstr; 
				   //alert('pert');
				   y++;
			   }
			  	
			  // alert('->'+newstr+'<-');
			  }
		  }
		  
		}
	  //  alert('->'+ab.length+'<-');
	    if ((ab.length==1)&&(tmp+mesi>12)){
		  alert('ATTENZIONE!\n Il numero dei mesi di possesso di tutte le abitazioni principali deve essre minore di 12.\n' +
                'Usa la pagina di modifica dei dati per sistemare il numero dei mesi di possesso.\n ');
		  ctrl=false;
		}
		if (ab.length>1) {
		  alert('ATTENZIONE!\n Si può selezionare solo un\'abitazione principale per volta.\n');
		  ctrl=false;
		}
		if ((ab.length==0)&&(pert.length>0)) {
		  alert('ATTENZIONE!\n Non si può selezionare una pertinenza senza un\'abitazione principale');
		  ctrl=false;
		}
		if(dopp==true){
		  alert('ATTENZIONE!\n Non si può assegnare ad un immobile sia la categoria pertinenza che abitazione principale');
		  ctrl=false;
		}
	}
	return ctrl;
 }
 
function InputDiv(frmName,p)
{///*'id_qposs_num','id_qposs_den',*/
  var campi=new Array('id_valore','id_aliquota','id_qposs_num',/*'id_detrazione',*/'stop');
  var obj,j=0,ctrl=false,Id;
  
  //alert('debug1 '+p);
 // obj=getObj(frmName,p);
  //alert('debug2');
  Id=p.id;
 // ;
  
  while((campi[j]!='stop')&&(!(ctrl))){
	// alert(campi[j]+' '+Id);
	  if (Id.search(campi[j])) { ctrl=true; }//alert(campi[j]);};
	  j++;
  }
  return ctrl;
}

function CtrlICIAliVal(frmName,action) 
{
	var obj;
	var rec  = false;
	var ctrl = true;
	var tmp;

	if (action=='pro')
	   return ctrl;

	if (action!='view')
	{
		obj=eval('document.'+frmName);
		
		//	name=eval('document.'+frmName+'.name');
		//	alert(name);
		
		for(j=0;j<obj.elements.length;j++) {
			// alert(obj.elements[j].name);
			// alert(tmp);
			pObj=obj.elements[j];
			// alert('nome '+pObj.name);
			
			//alert('nome '+pObj.name+' tipo '+pObj.type);
			
			if (pObj.name.substring(0,6) == 'valore'){
			   //alert('Trovato valore');
			   rec=true;
			}
			
			
//			if(obj.elements[j].type=='checkbox') rec=true;

////////////////////////////////////////////////////////////
//  disabilito il controllo sul valore 0.0 dell'aliquota
////////////////////////////////////////////////////////////
//			if(InputDiv(frmName,pObj)) {
//				if(obj.elements[j].value=='0,00') { 
//					ctrl=false;
//					// alert(obj.elements[j].id +' debug '+ obj.elements[j].value);
//				}
//			}
////////////////////////////////////////////////////////////
		}
	
		if(ctrl==false) alert('ATTENZIONE!\n'+
		                      'I campi valore, aliquota, e quota di possesso devono essere diversi da zero.\n'+
	                          'Correggi quelli marcati in rosso prima di proseguire.');
	

		//alert(' rec '+rec+' action '+action);
		if ((rec==false)&&(action=='ins')) 
		{
			alert('ATTENZIONE!\n'+
				'Per il calcolo deve essere presente almeno un\'unità immobiliare.\n'+
				'Inseriscine almeno una prima di proseguire.');
			ctrl=false;
		}

	}
	return ctrl;
 }

function CtrlICIRate(frmName,nIciTotale,idField) 
{
    var num=false;
    var obj;
    var str;

    obj = getObj(frmName,idField);
    //alert('debug '+obj.value);
    str = obj.value;
    num = isNumber(str.charAt(0));
    //alert('debug ' + num);
    if(num==true)
    {   if(nIciTotale<0) alert('Valore totale di imposta non corretto.');
    } 
    else alert('Valore inserito non corretto.\r\n Inserire solo numeri positivi.');

    return num;
    //alert('num '+num);
    //alert('nIciTotale '+nIciTotale);
}

//Attualmente non usata
function CalcICIRate(frmName,nIciTotale) {

var campi=new Array('id_tprec','tprimname','tsecname','tultname','stop');
var num=false,prim=0,sec=0,prec=0;
var objp,objs,obju;

obj = getObj(frmName,campi[0]);
num=isNumber(obj.value);
//alert('num '+obj.value);
if(num==true){
	if(nIciTotale>0){
	    prec=obj.value;
		prec=prec.replace('.','');
		prec=prec.replace(',','.');
		if (prec==0){
			prim=nIciTotale/2;
			sec=nIciTotale/2;
		} else {
			 
			 prim=prec/2;
			 if(prim>nIciTotale) prim=nIciTotale;
			 sec=nIciTotale-prim;
		}
	    objp= getObj(frmName,campi[1]);
		objp.value=prim;
		alert(objp.name+' '+objp.value);
		objs= getObj(frmName,campi[2]);
		objs.value=sec;
		alert(objs.name+' '+objs.value);
		obju= getObj(frmName,campi[3]);
		obju.value=nIciTotale;
		alert(obju.name+' '+obju.value);
	} else alert('Valore totale di imposta non corretto.');
} else alert('Valore inserito non corretto.\r\n Inserire solo numeri positivi.');

}


/* controlla il campo di salvataggio nome file abbia un valore valido */
function ctrlICIProfileLoad(frmName)
{
	var campi=new Array('id_save','id_load','id_idprofilo','stop');
	var strAlert=new Array('Il nome del file corrisponde ad un profilo già esistente.\r\nSovrascriverlo?');
	var msgErr=new Array(' può contenere solo caratteri alfanumerici (lettere e numeri) e non'
	                      +'  può essere vuoto.\r\nTi chiediamo cortesemente di ricompilarlo correttamente.','stop');
	
	var ret=false,ind=0;
	
	objSel = getObj(frmName,campi[1]);
	if((objSel)&&(objSel!=null))
	{	
		ind=objSel.selectedIndex;
		if(ind!=0)
		{	//SetParm(frmName, campi[2], objSel.options[ind].value);
			//SetParm(frmName, campi[1], ind);//objSel.options[ind].text);
			ret=true;
		}
	}
	if(ret==false) alert('Non si è selezionato nessun profilo ICI.\r\n'+
                      'Per caricare un profilo ICI valido selezionarlo dall\'elenco sottostante.');
	
	return ret;
}
//

function ctrlICIMove(frmName)
{
   var campi=new Array('id_cliente','sel','stop');
   var msgErr='Selezionare un\'anagrafica a cui associare il file ICI.';
   var objSel,obj,ret=true,msg=false,val;
    
	objSel = getObj(frmName,campi[0]); //il cliente deve essere settato
	    if(objSel.selectedIndex==0) {
		  ret=false;
		  msg=true;
		}
	obj = getObj(frmName,campi[1]);
	val=parseInt(obj.value);
//	alert(val+'||'+obj.value+'||'+);
    if(val==objSel.options[objSel.selectedIndex].value) { //se il cliente selezionato non è
	//	  alert('=');
		  ret=false;                      //stato cambiato non faccio nulla
	}
	if(msg==true)  alert(msgErr);
	
	return ret;

}

function ctrlICIProGestSave(frmName)
{
	var campi=new Array('id_save','id_cliente','id_nomifile','stop');
	var strAlert='Il nome del file corrisponde ad un profilo già esistente.\r\nSovrascriverlo?';
	var msgErr=' può contenere solo caratteri alfanumerici (lettere e numeri) e non'
	                      +'  può essere vuoto.\r\nTi chiediamo cortesemente di ricompilarlo correttamente.';
	var msg = 'Si è scelto di salvare la situazione attuale ICI con il nome ';
		
	var exit=false,exist=false, ret=false, fl=2, str='';
	var minlen=1, numopt=0, valopt,j=0;
	var tmp1,tmp2;
	
	obj = getObj(frmName,campi[0]);
	if((obj)&&(obj!=null))
	{	str=obj.value;
		fl=str.length;
		if (fl<minlen)exit=true;
		else exit=(!(isAlfaNum(str)));
	}
 
    if (exit==true) 
	{	alert('Attenzione!\r\nIl campo del file' + msgErr);
		obj.focus();
		ret=false;
	} 
	/*else if (exist==true) 
	{	if (confirm (strAlert)) ret=true;
		else ret=false;
	} */
	else {ret=true;
 
		objSel = getObj(frmName,campi[1]); //il cliente deve essere settato
	    if(objSel.selectedIndex==0) {
		  ret=false;
		  alert('Selezionare la scheda anagrafica a cui associare il file ICI.');
		}
		else {
		  objSel = getObj(frmName,campi[2]); 
	      if(obj = getObj(frmName,campi[0]))	nome=obj.value;
		
		  val=objSel.value;
		  valString=val.split('|');
		  presente=false;
		  for(i=0; i<valString.length; i++) {
		    if(valString[i].toLowerCase()==nome.toLowerCase()){
		      ret=false; 
			  presente=true;
			}
		  }
		  if (presente==true) ret=confirm('L\'anagrafica selezionata contiene già un file ICI chiamato '+nome+'.\r\nSovrascrivere?');
			//alert('ret '+ret+'exist '+exist);
		  if 	(ret==true) ret=confirm (msg+str+'.\r\nConferma?');
		}
	}
	return ret; 
}

/* controlla il campo di salvataggio nome file abbia un valore valido */
function ctrlICIProfileSave(frmName)
{
	var campi=new Array('id_save','id_load','id_idprofilo','id_sottoprofilo','stop');
	var strAlert='Il nome del file corrisponde ad un profilo già esistente.\r\nSovrascriverlo?';
	var msgErr=' può contenere solo caratteri alfanumerici (lettere e numeri) e non'
	                      +'  può essere vuoto.\r\nTi chiediamo cortesemente di ricompilarlo correttamente.';
	var msg = 'Si è scelto di salvare la situazione attuale ICI con il nome ';
		
	var exit=false,exist=false, ret=false, fl=2, str='';
	var minlen=1, numopt=0, valopt,j=0;
	var tmp1,tmp2;
	
	obj = getObj(frmName,campi[0]);
	if((obj)&&(obj!=null))
	{	str=obj.value;
		fl=str.length;
		if (fl<minlen)exit=true;
		else exit=(!(isAlfaNum(str)));
	}
   
    if (exit==false) 
	{	objSel = getObj(frmName,campi[1]);
		numopt = objSel.length;
		while ((j<numopt)&&(!exist))
		{	tmp1=objSel.options[j].text.toLowerCase();
		    tmp2=str.toLowerCase();
		    //alert(tmp1);
			//alert(tmp2);
			if (tmp1==tmp2) 
			{	SetParm(frmName, campi[2], objSel.options[j].value);
				exist=true;
			}
			j++;
		}
	}
   	
    if (exit==true) 
	{	alert('Attenzione!\r\nIl campo del file' + msgErr);
		obj.focus();
		ret=false;
	} 
	else if (exist==true) 
	{	if (confirm (strAlert)) ret=true;
		else ret=false;
	} 
	else {ret=true;}
    
	objSel = getObj(frmName,campi[3]); //il sottoprofilo deve essere selezionato
    if(objSel.selectedIndex==0) {
	  ret=false;
	  alert('Selezionare il sottoprofilo in cui salvare il file ICI.');
	}
	//alert('ret '+ret+'exist '+exist);
	if 	(ret==true) ret=confirm (msg+str+'.\r\nConferma?');
	
	return ret; 
}

/* controlla che campi di inserimento sottoprofilosianocorretti */
function ctrlICISubpro(frmName)
{

	var campi=new Array('id_nome','id_fiscale','stop');
	var campName=new Array('Nome','Cod. fisc./P. IVA','stop');
	var strAlert=new Array('Nome sottoprofilo non valido: ','Campo obbligatorio','stop');
	var msgErr=new Array(' può contenere solo caratteri alfanumerici (lettere e numeri) e non'
	                      +'  può essere vuoto.\r\nTi chiediamo cortesemente di ricompilarlo correttamente.',
						  ' è obbligatorio!',' può contenere solo caratteri alfanumerici (lettere e numeri) e non'
	                      +'  può essere vuoto.\r\nTi chiediamo cortesemente di ricompilarlo correttamente.',
						  ' è obbligatorio!','stop');
	
	var campErr=new Array(0,0,'stop');

	var exit=false, ret=true, fl=2, str='', j=0;
	var minlen=1;

	while((campi[j]!='stop')&&(!exit)) 
	{	obj = getObj(frmName,campi[j]);
		if((obj)&&(obj!=null))
		{	str=obj.value;
			fl=str.length;
			if(fl<minlen) {
			  exit=true;
			  //alert('If '+fl+' '+str);
			}
			else {
			  exit=(!(isAlfaNumSpace(str)));  
			  //alert('Else '+fl+' '+str);
			}
		}
    	j++;
	}

	if (exit==true)
	{	alert('Attenzione!\r\nIl campo '+ campName[--j] + msgErr[campErr[j]]);
		obj.focus();
		ret=false;
	}

	return ret;
}

/* controlla che campi di login e password abbiano valori validicampi */
function ctrlICIReg(frmName)
{
	var campi=new Array('id_login','id_pw','id_pw2','id_question','id_answer','stop');
	var campName=new Array('Login','Password','"Conferma Password"','Domanda','Risposta','stop');
	var strAlert=new Array('login non valida: ','Password non valida: ','Campo Password diverso dalla sua conferma:','Seleziona una domanda',
	                         'Risposta non valida: ','stop');
	var msgErr=new Array(' può contenere solo caratteri alfanumerici (lettere e numeri) e non'
	                      +'  può essere vuoto.\r\nTi chiediamo cortesemente di ricompilarlo correttamente.',
						  ' è obbligatorio!',' deve essere uguale al campo "Password".\r\n'
						  +' Probabilmente hai commesso un errore di digitazione.\r\n Riprova!','stop');
	var campErr=new Array(0,0,2,1,0,'stop');
	
	var exit=false, ret=true, fl=2, str='', j=0;
	var minlen=1;
	
	while((campi[j]!='stop')&&(!exit)) 
	{	obj = getObj(frmName,campi[j]);
		if((obj)&&(obj!=null))
		{	if(j==2){
				objpass=getObj(frmName,campi[1]);
				str=objpass.value;
				str2=obj.value;
				if(str!=str2)exit=true;
			} else {
	    		str=obj.value;
				fl=str.length;
				if (fl<minlen)exit=true;
				else exit=(!(isAlfaNum(str)));
			}
		}
    	j++;
	}

	if (exit==true)
	{	alert('Attenzione!\r\nIl campo '+ campName[--j] + msgErr[campErr[j]]);
		obj.focus();
		ret=false;
	}
	return ret;
}

// controlla se s è un numero reale
function isFloat (s)
{
	var i,j,k,d;
	d=s.length;d++;
	//alert(s);
	
	for (i=0; i<s.length; i++)
		if ((s.charAt(i)==',')||(s.charAt(i)=='.'))
		  d=i;
    if (d<s.length)
	for (j=d+1; j<s.length; j++)
		if (!isNumber(s.charAt(j)))
	     { return false;}//alert('deb1 '+s.charAt(j)); 
	for (k=0; k<d-1; k++)
		if (!isNumber(s.charAt(k)))
	      {return false;}//alert('deb2 '+s.charAt(k));
	
	return true;
}


// controlla se s è un numero intero
function isInteger (s)
{
	var i;
	for (i=0; i<s.length; i++)
		if (!isNumber(s.charAt(i)))
			return false;
	return true;
}

// controlla se s è una stringa formata dai soli caratteri alfabetici o numerici o da \'àèéìòù
function isAlfaNum (s)
{
	var i;
	for (i=0; i<s.length; i++)
		if (!(isSpec(s.charAt(i), ".") || 
              isSpec(s.charAt(i), "-") || isSpec(s.charAt(i), "_") ||
              isLetter(s.charAt(i)) || isNumber(s.charAt(i))))
			return false;
	return true;
}

// controlla se s è una stringa formata dai soli caratteri alfabetici o numerici oppure
//da spazi dopo il primo carattere
function isAlfaNumSpace (s)
{
	var i;
	for (i=0; i<s.length; i++)
		if (!(isSpec(s.charAt(i), ".") || 
              isSpec(s.charAt(i), "-") || isSpec(s.charAt(i), "_") ||
              isLetter(s.charAt(i)) || isNumber(s.charAt(i)) ||( (isSpec(s.charAt(i), " "))&&(i>1)  )))
			return false;
	return true;
}

// controlla se il carattere c è presente nella stringa spec
function isSpec (c, spec)
{
	var i;
	for (i=0; i<spec.length; i++)
		if (spec.charAt(i)==c)
			return true;
	return false;
}

// controlla se il carattere c è una lettera dell'alfabeto
function isLetter (c)
{
	if ((c>='a' && c<='z') || (c>='A' && c<='Z'))
		return true;
	return false;
}

// controlla se il carattere c è una cifra
function isNumber (c)
{
	if (c>='0' && c<='9')
		return true;
	return false;
}


/*************funzione che controlla il valore di determinati campi*******************/
function ctrlICIParm(frmName,val)
{
	var campi=new Array('id_valore','id_qposs_num','id_qposs_den','id_idaliquota','id_detrazione','stop');
	var minval=new Array(0.01,1,1,1,0,'stop');
	var maxval=new Array(1000000000,1000,1000,2,10000,'stop');
	var tipval=new Array('float','float','int','sel','float','stop');
	var strAlert=new Array(	'Valore inserito non valido: ',
    					     'Parte numeratore della quota di possesso non valido: ',
							 'Parte denominatore della quota di possesso non valido: ',
							 'Aliquota scelta non valida',
							 'Valore della detrazione non valido: ',
							 'stop');
	var j=0,obj,val,val1, is0=0;
	exit=false,ret=true;
	var objnum, objden; // variabili per testare che numeratore <= denominatore 
    
	if(val!='act_cancel'){
		while((campi[j]!='stop')&&(!exit)) 
		{	
	        if(j!=4)
		     obj = getObj(frmName,campi[j]);
			else
			  obj = getObj2(frmName,campi[j]);
//		    obj = getObj(frmName,campi[j]);
			
		    //alert(obj);
			if((obj)&&(obj!=null))
			{
				if(tipval[j]=='sel') 
				  val=str2fl(obj.options[obj.selectedIndex].value);
				else
				  	val=str2fl(obj.value);
				//alert('val'+val+' object ' +obj.value)
				is0=isZero(obj.value);
				if((val==0)&&(is0==0)) exit=true;
				else if(tipval[j]!='sel')
				{
			    	if( (val<minval[j]) || (val>maxval[j])) 
					{	exit=true;
						//alert(val+' '+minval[j]+' '+maxval[j]);
					} 
					
					if(tipval[j]=='int')
					{	val1=parseInt(val);
						if (val!=val1)
							exit=true;
					}
				}
				else if (val=='') exit=true;
				
		    }
	    	j++;
		}
	   
		if (exit==true)
		{	
		    if((j>1)&&(tipval[j-1]!='sel'))
		       alert(strAlert[--j]+ obj.value +'\r\n'+'Range:['+minval[j]+' .. '+maxval[j]+']');
			else if(tipval[j-1]=='sel')
			   alert(strAlert[--j]+ obj.value);
			else alert(strAlert[--j]+ obj.value +'\r\n'+'Inserire solo valori maggiori di 0'); 
			obj.focus();
			ret=false;
		} else{
			objnum=getObj(frmName,campi[1]);
			objden=getObj(frmName,campi[2]);
			//alert('|'+objnum.value+'| |'+objden.value+'|');
			if (str2fl(objnum.value)>str2fl(objden.value)){ alert('Il campo numeratore della quota di possesso deve essere'+
			    ' minore del campo denominatore.'); objnum.focus(); ret=false}
		}
		
	} else 	ret=true;
	
	//alert(ret);
	return ret;
}

function ctrlICIParm2(frmName,val)
{
	var campi=new Array('id_foglio','id_numero','id_sub','id_categoria','id_rendita',
	                    'id_qposs_num','id_qposs_den','id_idaliquota','id_detrazione','stop');
	var minval=new Array(0,0,0,1,0.01,
	                     1,1,1,0,'stop');
	var maxval=new Array(10000,100000,10000,100,1000000,
	                     1000,1000,2,10000,'stop');
	var tipval=new Array('int','int','int','sel','float',
	                      'float','int','sel','float','stop');
	var strAlert=new Array(	 'Foglio non valido',
	                         'Numero non valido',
							 'Valore Sub non valido',
							 'Categoria catastale non valida',
							 'Rendita catastale non valida',
	                         'Parte numeratore della quota di possesso non valido: ',
							 'Parte denominatore della quota di possesso non valido: ',
							 'Aliquota scelta non valida',
							 'Valore della detrazione non valido: ',
							 'stop');
	var j=0,obj,val,val1, is0=0,isF;
	exit=false,ret=true;
	var objnum, objden;
    
	if(val!='act_cancel'){
		while((campi[j]!='stop')&&(!exit)) 
		{	
		   processa = 1;
		   if (campi[j]=='id_foglio') processa = 0;
		   if (campi[j]=='id_numero') processa = 0;
		   if (campi[j]=='id_sub')    processa = 0;

           if (processa == 1) {
		
		   if(j!=8)
		      obj = getObj(frmName,campi[j]);
			else
			  obj = getObj2(frmName,campi[j]);
		   // alert(obj);
			if((obj)&&(obj!=null))
			{
				if(tipval[j]=='sel') {
				  val=obj.options[obj.selectedIndex].value;
				  if (val=='') val=0;
				}  
				else {
				  	isF=isFloat(obj.value); //alert(obj.value+' float: '+isF);
				  	if ((isF==false)&&( (tipval[j]=='int')||(tipval[j]=='float')) ) exit=true;
					val=str2fl(obj.value);
				}	
				//alert('val '+val+' object ' +obj.value)
				
				is0=isZero(obj.value);
				
				if((val==0)&&(is0==0)) exit=true; 
				else if((tipval[j]!='sel')&&(tipval[j]!='str'))
				{
			    	if( (val<minval[j]) || (val>maxval[j])) 
					{	exit=true;
						//alert(val+' '+minval[j]+' '+maxval[j]);
					} 
					
					if(tipval[j]=='int')
					{	val1=parseInt(val);
						if (val!=val1)
							exit=true;
					}
				}
				else if (val=='') exit=true;
				if(tipval[j]=='str') exit=valutastr(obj.value);
		    }
		    }
	    	j++;
		}
	   
		if (exit==true)
		{	
		    if(j<5){
    			alert(strAlert[--j]+' '+ obj.value); 
			} else if(j==5){
			    alert(strAlert[--j]+' '+ obj.value +'\r\n'+'Inserire solo valori maggiori di 0'); 
			} else {
				if((j>1)&&(tipval[j-1]!='sel')&&(tipval[j-1]!='str'))
			       alert(strAlert[--j]+' '+ obj.value +'\r\n'+'Range:['+minval[j]+' .. '+maxval[j]+']');
				else if(tipval[j-1]=='sel')
				   alert(strAlert[--j]+' '+ obj.value);
				else if(tipval[j-1]=='str')
				   alert(strAlert[--j]+' '+ obj.value);   
				else alert(strAlert[--j]+' '+ obj.value +'\r\n'+'Inserire solo valori maggiori di 0'); 
			}
			
			obj.focus();
			ret=false;
		} else{
			objnum=getObj(frmName,campi[5]);
			objden=getObj(frmName,campi[6]);
			//alert('|'+objnum.value+'| |'+objden.value+'|');
			if (str2fl(objnum.value)>str2fl(objden.value)){ alert('Il campo numeratore della quota di possesso deve essere'+
			    ' minore del campo denominatore.'); objnum.focus(); ret=false; }
		
		}
	} else 	ret=true;
	
	//alert(ret);
	return ret;
}
/********funzione che controlla se la stringa passata inizia per carattere*************/
function valutastr(val){
	var s,ret=false;
	if (val=='') val='0';
	s=val.charAt(0);
	ret=(!(isLetter(s)));
		 
	return ret;
}

/*************funzione che controlla il valore di determinati campi*******************/
function ctrlICIParmApply(frmName,val)
{
    //
	var campi=new Array('id_valore','id_qposs_num','id_qposs_den','id_mposs','id_detrazione','stop');
	var minval=new Array(0.01,0,1,1,0,'stop');
	var maxval=new Array(1000000,1000,1000,12,10000,'stop');
	var tipval=new Array('float','float','int','sel','float','stop');
	var strAlert=new Array(	 'Valore inserito non valido: ',
	                         'Parte numeratore della quota di possesso non valido: ',
							 'Parte denominatore della quota di possesso non valido: ',
							 'Numero dei mesi di possesso non valido: ',
							 'Valore della detrazione non valido: ',
							 'stop');
	var j=0,obj,val,val1, is0=0,tmp=0;
	exit=false,ret=true;
    var objnum, objden;
	
	if(val!='act_cancel'){
		while((campi[j]!='stop')&&(!exit)) 
		{	obj = getObj2(frmName,campi[j]);
			
		    //alert(obj);
			if((obj)&&(obj!=null))
			{
				val=str2fl(obj.value);
				
				//alert(' object |' +obj.value+'|')
				is0=isZero(obj.value);
				if((val==0)&&(is0==0)&&(obj.value!='')) exit=true;
				else if((tipval[j]!='sel')&&(obj.value!=''))
				{
			    	if( (val<minval[j]) || (val>maxval[j])) 
					{	exit=true;
						//alert(val+' '+minval[j]+' '+maxval[j]);
					} 
					
					if((tipval[j]=='int')&&(obj.value!=''))
					{	val1=parseInt(val);
						if (val!=val1)
							exit=true;
					}
				}
				else if(tipval[j]=='sel'){
				  tmp=parseInt(obj.options[obj.selectedIndex].value)
				  val=SumMounthAbPrincCheck(frmName,'mod',tmp);
				 
				  if (val>12)exit=true;
				   //alert('tmp '+val);
				}
				//else if (obj.value=='') exit=true;
		    }
	    	j++;
		}
	   
		if (exit==true)
		{	
		   // alert('|'+obj.name+'|'+obj.value+'|');
			if(obj.value!=''){
				if((j>1)&&(tipval[j-1]!='sel'))
			       alert(strAlert[--j]+ obj.value +'\r\n'+'Range:['+minval[j]+' .. '+maxval[j]+']');
				else if(tipval[j-1]=='sel')
				   alert(strAlert[--j]+ obj.value);
				else alert(strAlert[--j]+ obj.value +'\r\n'+'Inserire solo valori maggiori di 0'); 
				obj.focus();
				ret=false;
			}
		} else{
			objnum=getObj(frmName,'id_qposs_num');
			objden=getObj(frmName,'id_qposs_den');
			//alert('|'+objnum.value+'| |'+objden.value+'|');
			if (str2fl(objnum.value)>str2fl(objden.value)){ alert('Il campo numeratore della quota di possesso deve essere'+
			    ' minore del campo denominatore.'); objnum.focus(); ret=false; } 
		
		}
	} else  ret=true;
	
	//alert(ret);
	return ret;
}


/* converte stringa in float 
( si aspetta stringa con il punto come separat. migliaia e virgola come sep. decimali)  */
function str2fl(str){
		var fl;
		str=str.replace('.','');
		str=str.replace(',','.');
	    fl=parseFloat(str);
		if(isNaN(fl)) fl=0;
		return fl;
}
/*********  Controlla se il valore numerico di una stringa è zero***********/
function isZero(str){
	var ret=0,toInt;
	if (str=='0')ret=1 ;
	if (str=='0,0')ret=1;
	if (str=='0,00')ret=1;
	if (str=='0,000')ret=1;
	toInt=parseInt(str);
	if(toInt==0)ret=1;
	
return ret

}

//------------------------------------------------------------------------------	

function ReloadPage( path )	
{	self.location.href = path;
}


function ReloadParentPage( path )	
{	parent.location.href = path;
}


function MM_openBrWindow(theURL,winName,features) { //v2.0
  window.open(theURL,winName,features);
}


function SetParm(frmName, parm, val)
{	//alert('document.'+frmName+'.'+parm+'.value = \''+val+'\'');
	//if(eval( 'document.'+frmName+'.'+parm+'.value = \''+val+'\'' )) alert('Parametro assegnato'); else alert('Parametro non assegnato');;
	eval( 'document.'+frmName+'.'+parm+'.value = \''+val+'\'' );
}

function SetParmId(parm, val)
{	var obj;
    if(obj=document.getElementById(parm))
      obj.value = val;
}

function change(parm, val) 
{
   var obj,id,nome;
   id=val+parm;
   if(obj=document.getElementById(id)){
     nome=obj.src;
     
	 obj.src=nome.replace(".gif","_ani.gif");
   }
}

function replace(parm, val) 
{
   var obj,id,nome;
   id=val+parm;
   if(obj=document.getElementById(id)){
     nome=obj.src;
     obj.src=nome.replace("_ani.gif",".gif");
	}
}

function ConfirmBox(frmName, parm, val, msg)
{	
	if ( confirm( msg ) )
	{	
	    SetParm(frmName, parm, val);
		eval( 'document.'+frmName+'.submit()' );
		
	}
}

function ConfirmICIParm2(frmName, parm, val, msg, opt)
{	
   // Michele Secchi
   var al_sel=-1;
   if(val=='act_cancel')
   {
      if(confirm("Attenzione: i dati immessi non saranno salvati. Uscire?"))
      {
         eval( 'document.'+frmName+'.submit()' );
      }
   }
   else
   {
      if(!str2fl(document.forms[1].id_rendita.value))
      {
         alert("Rendita non valida.");
         return;
      }
      qposs_num=parseInt(document.forms[1].id_qposs_num.value);
      id_qposs_den=parseInt(document.forms[1].id_qposs_den.value);
      mesi=parseInt(document.forms[1].id_mposs.value);
      detrazione1=parseFloat(document.forms[1].id_detrazione1.value);
      detrazione2=parseFloat(document.forms[1].id_detrazione2.value);
      if(qposs_num<1||id_qposs_den<1)
      {
         alert("Quota di possesso non valida.");
         return;
      }
      if(qposs_num/id_qposs_den>1)
      {
         alert("Quota di possesso non valida.");
         return;
      }
      for(i=0;i<3;i++)
      {
         if(document.forms[1].tipo_aliquota[i].checked)
         {
            al_sel=i;
            i=3;
         }
      }
      if(al_sel>=0)
      {
         switch(al_sel)
         {
            case 0:
               document.forms[1].id_idaliquota.value=document.forms[1].al_ordinaria.value;
               document.forms[1].id_n_persone.value='';
               //document.forms[1].id_n_persone_det.value='0';
               document.forms[1].id_detrazione.value='0';
               break;
            case 1:
               if(!document.forms[1].id_n_persone.value.length)
               {
                  document.forms[1].id_n_persone.value='1';
               }
               //if(!document.forms[1].id_n_persone_det.value.length)
               //{
               //   document.forms[1].id_n_persone_det.value='0';
               //}
               n_persone=parseInt(document.forms[1].id_n_persone.value);
               if(n_persone<=0)
               {
                  alert('Inserire il numero dei comproprietari (compreso il dichiarante)');
                  document.forms[1].id_n_persone.focus();
                  return;
               }
               //if(document.forms[1].id_detraz_agg.checked)
               //{
               //   document.forms[1].id_detrazione.value=document.forms[1].id_detrazione2.value;
                  //n_persone=parseInt(document.forms[1].id_n_persone_det.value);
                  //if(n_persone<1)
                  //{
                  //   alert('Inserire il numero di persone che usufruiscono della maggiore detrazione.');
                  //   document.forms[1].id_n_persone_det.focus();
                  //   return;
                  //}
               //}
               //else
               //{
                  //document.forms[1].id_n_persone_det.value='0';
                  document.forms[1].id_detrazione.value=document.forms[1].id_detrazione1.value;
               //}
               document.forms[1].id_idaliquota.value=document.forms[1].al_abitazione.value;
               break;
            case 2:
               document.forms[1].id_idaliquota.value=document.forms[1].combo_aliquota.value;
               document.forms[1].id_n_persone.value='';
               //document.forms[1].id_n_persone_det.value='0';
               document.forms[1].id_detrazione.value='0';
               break;
            default:
         }
         if(document.forms[1].id_pertinenza.value=='1')
         {
            if(al_sel==1)
            {
               document.forms[1].is_principale.value='1';
               document.forms[1].is_pertinenza.value='0';
            }
            else
            {
               document.forms[1].is_principale.value='';
               document.forms[1].is_pertinenza.value='';
            }
         }
         else
         {
            document.forms[1].is_principale.value='0';
            document.forms[1].is_pertinenza.value='1';
         }
         n_persone=parseInt(document.forms[1].id_n_persone.value);
         //n_persone_det=parseInt(document.forms[1].id_n_persone_det.value);
         if(al_sel==1)
         {
         if(document.forms[1].id_detraz_agg.checked)
            det1=((detrazione2*mesi/12)/n_persone);
         else
            det1=((detrazione1*mesi/12)/n_persone);
         //if(n_persone_det>0)
         //{
         //   det2=((detrazione2*mesi/12)/n_persone_det);
         //}
         //else
         //{
         //   det2=0;
         //}
         dettot=det1;//+det2;
         document.forms[1].id_detrazione.value=dettot;
         }
         else
            document.forms[1].id_detrazione.value='0';
         if(confirm(msg))
         {
            eval( 'document.'+frmName+'.'+parm+'.value = \''+val+'\'' );
            eval( 'document.'+frmName+'.submit()' );
         }
      }
      else
      {
         alert("Selezionare il tipo di aliquota.");
      }
   }
}

function ConfirmICIParm(frmName, parm, val, msg, opt)
{	
	if(opt==0) 
	{   if (ctrlICIParm(frmName,val))
		{	if ( confirm( msg ) )
			{	SetParm(frmName, parm, val);
				eval( 'document.'+frmName+'.submit()' );
			}
		}
	 } else {
		if (ctrlICIParm2(frmName,val))
		{	if ( confirm( msg ) )
			{	SetParm(frmName, parm, val);
			   	eval( 'document.'+frmName+'.submit()' );
			}
		}
	 
	 }
}

function ConfirmICIParmApply(frmName, parm, val, msg)
{	
	if (ctrlICIParmApply(frmName,val))
	{	if ( confirm( msg ) )
		{	SetParm(frmName, parm, val);
       //     alert( 'document.'+frmName+'.submit()' );
			eval( 'document.'+frmName+'.submit()' );
		}
	}
}

function ConfirmICISubpro(frmName)
{	
	if ( ctrlICISubpro(frmName) )
	{	eval( 'document.'+frmName+'.submit()' );
	}
}

function ConfirmICIReg(frmName)
{	
	if ( ctrlICIReg(frmName) )
	{	eval( 'document.'+frmName+'.submit()' );
	}
}
         
function ConfirmICIProfileSave(frmName, parm, val, msg)
{	
	if (ctrlICIProfileSave(frmName))
	{ //	if ( confirm( msg ) )
		{	SetParm(frmName, parm, val);
			eval( 'document.'+frmName+'.submit()' );
		}
	}
}

function ConfirmICIMove(frmName)
{	
	if (ctrlICIMove(frmName))
	{ 
		eval( 'document.'+frmName+'.submit()' );
	}
}

function ConfirmICIDel(frmName,msg)
{	
	if ( confirm( msg ) )
	{   
	    eval( 'document.'+frmName+'.submit()' );
	    
	}
}

function ConfirmICIProGestSave(frmName, parm, val, msg)
{	
	if (ctrlICIProGestSave(frmName))
	{ //	alert ( frmName +' '+ parm +' '+ val )
		{	SetParm(frmName, parm, val);
			eval( 'document.'+frmName+'.submit()' );
		}
	}
}

function ConfirmICIProfileLoad(frmName, parm, val, msg)
{	
	if (ctrlICIProfileLoad(frmName))
	{ 	if ( confirm( msg ) )
		{	SetParm(frmName, parm, val);
			eval( 'document.'+frmName+'.submit()' );
		}
	}
}

function selSottopro(frmName)
{
 var obj;
    
	obj=getObj(frmName,'gAct');
	//alert(obj.value);
	obj.value='act_load';	
	//alert(obj.value);
	eval( 'document.'+frmName+'.submit()' );

}

function SottoproSub(frmName)
{

   eval( 'document.'+frmName+'.submit()' );

}

function ConfirmCalcICIRate(frmName, val, idField)
{	
	if (CtrlICIRate(frmName,val,idField))
	{  
	//    CalcICIRate(frmName,val);
		eval( 'document.'+frmName+'.submit()' );
    }
}


function printscr()
{   /*
	if (document.all)
	{   if (navigator.appVersion.indexOf("5.0") == -1)
		{	var OLECMDID_PRINT = 6;
	        var OLECMDEXECOPT_DONTPROMPTUSER = 2;
	        var OLECMDEXECOPT_PROMPTUSER = 1;
	        var WebBrowser = "<OBJECT ID=\"WebBrowser1\" WIDTH=0 HEIGHT=0 CLASSID=\"CLSID:8856F961-340A-11D0-A96B-00C04FD705A2\"></OBJECT>";
	        document.body.insertAdjacentHTML("beforeEnd", WebBrowser);
	        WebBrowser1.ExecWB(6, 2);
	        WebBrowser1.outerHTML = "";
	    }
		else
		{	self.print();
	    }
	}
	else
	{	self.print();
	}*/
	window.print();
}


//------------------------------------------------------------------------------	


function optSelect(obj) {
	var tmp;
	
	eval('tmp='+obj.name);
	if(obj.checked) tmp=1;
	else tmp=0;
	eval(obj.name+'=tmp');
	
}

function resetOptions(objId) {
	var i=0;
	while(objId[i]!='stop') {
		eval(objId[i]+'=0');
		i++;
	}
}


function getObj(frmName,id) {
	var obj;
	if(obj=eval('document.'+frmName+'.'+id)) return obj;
	else if(obj=document.getElementById(id)) return obj;
	else {
		alert('oggetto non trovato');
		return false;
	}
}

//funzione analoga alla precedente, ma che non fà nessun alert
function getObj2(frmName,id) {
	var obj;
	if(obj=eval('document.'+frmName+'.'+id)) return obj;
	else if(obj=document.getElementById(id)) return obj;
	else {
		//alert('oggetto non trovato');
		return false;
	}
}

function init(frmName,id) {
	var obj;
	obj=getObj(frmName,id);
	obj.focus();
}


function checkFields(frmName,id,alarm) {
	var obj,obj1,obj1Id,complete=true;
	var tmp;
	
	obj=getObj(frmName,id);

	if(obj.type =="text") {
		if(obj.value=='') complete=false;
	} else if(obj.type =="select-one") {
		if(obj.value==0) complete=false;
	} else if(obj.type =="checkbox")  {	
		if(!(obj.checked)) complete=false;
	} else if(obj.type =="radio") {
		eval('tmp='+obj.name);
		if(tmp==0) complete=false;
	}

	if(!complete) {
		if(alarm==true) {
			alert('Mancanza di dati obbligatori');
			obj.focus();
		}
		return false;	
	}
	else return true;
}


function abilita(frmName,id,status) {
	var obj;
	obj=getObj(frmName,id);
	obj.disabled=status;
	if(status==false) {
		obj.focus();
		obj.select();
	}
}

function resizeScreen() {
return;
    var appletWidth=220;
	var appletLeft=860;
	var obj1,obj2;
	if(screen.width==800){
	  //  alert(document.getElementById('appletDiv'));
		if(obj1=document.getElementById('appletDiv')){
		  obj1.style.left=660;
		}
		else alert('oggetto div');
		if(obj2=document.getElementById('appletTMP')){
		  obj2.width=110;
		}
		else alert('oggetto applet');
		
  } 
} 

function Abilitaaliquote()
{
   var al_sel=0;
   for(i=0;i<3;i++)
   {
      if(document.forms[1].tipo_aliquota[i].checked)
      {
         al_sel=i;
         i=3;
      }
   }
   switch(al_sel)
   {
      case 1:
         document.getElementById('parametri').style.visibility="visible";
         document.getElementById('a_aliquote').style.visibility="hidden";
         document.getElementById('div_desc_alq').style.visibility="hidden";
         break;
      case 2:
         document.getElementById('parametri').style.visibility="hidden";
         document.getElementById('a_aliquote').style.visibility="visible";
         document.getElementById('div_desc_alq').style.visibility="visible";
         break;
      default:
         document.getElementById('parametri').style.visibility="hidden";
         document.getElementById('a_aliquote').style.visibility="hidden";
         document.getElementById('div_desc_alq').style.visibility="hidden";
   }
}

function Abilita_n_sogg()
{
   return;
   if(document.getElementById('id_detraz_agg').checked)
      document.getElementById('parametri2').style.visibility="inherit";
   else
      document.getElementById('parametri2').style.visibility="hidden";
}

function CambioUI()
{
   if(document.getElementById('id_tipounitaimm').selectedIndex)
   {
      document.getElementById('div_aliquote').style.visibility="hidden";
      document.getElementById('parametri').style.visibility="hidden";
      //document.getElementById('parametri2').style.visibility="hidden";
      document.getElementById('a_aliquote').style.visibility="hidden";
      document.getElementById('label_r').style.visibility="hidden";
      document.getElementById('label_v').style.visibility="visible";
      document.getElementById('label_rendita').style.visibility="hidden";
      document.getElementById('label_valore').style.visibility="visible";
      document.getElementById('div_desc_alq').style.visibility="hidden";
      document.getElementById('radio1').checked=true;
      document.getElementById('id_n_persone').value="";
      document.getElementById('id_detraz_agg').checked=false;
   }
   else
   {
      document.getElementById('label_rendita').style.visibility="visible";
      document.getElementById('label_valore').style.visibility="hidden";
      document.getElementById('label_v').style.visibility="hidden";
      document.getElementById('label_r').style.visibility="visible";
      document.getElementById('div_aliquote').style.visibility="visible";
   }
}

function CambioPertinenza()
{
   if(document.getElementById('id_pertinenza').selectedIndex)
   {
      document.getElementById('div_aliquote').style.visibility="hidden";
      document.getElementById('parametri').style.visibility="hidden";
      //document.getElementById('parametri2').style.visibility="hidden";
      document.getElementById('a_aliquote').style.visibility="hidden";
      document.getElementById('radio2').checked=true;
      document.getElementById('id_n_persone').value="";
      document.getElementById('id_detraz_agg').checked=false;
   }
   else
   {
      document.getElementById('div_aliquote').style.visibility="visible";
   }
}
