/*
Medikey - Javascript Library
-------------------------------------------------------------------------------
Autori...:  Thierry CHILOSI [t.chilosi@dsmedigroup.com]
			Michele LIGUORI []

Funzione.:	Funzioni di controllo generale per pagine HTML. In questo file non
			ci sono funzioni con collegamento specifico ad alcuna pagina sono
			tutte riutilizzabili.
			

			Trim(s)
			ritorna una stringa senza spazi davanti o dietro.
			
			IsEmpty(c,nome)
			quando un campo non puo essere lasciato vuoto.
			
			CheckOption(c,nome,min,max)
			quando deve essere selezionato almeno uno campo option fra min e max.
			solo per i checkbox!
			
			CheckChoice(c,nome,index)
			quando indice (index) del campo c va per forza selezionato.
			
			CheckValidDate(cG,cM,cA,nome)
			controllo che i valori contenuti in 3 campi data corrispondano ad una
			data valida.
			
			CheckList(c,nome)
			quando va selezionato un indice diverso da 0 dalla combobox.
			
			CheckAlfa(c,l,nome)
			quando un campo deve essere lungo almeno l caratteri che non possono
			contenere degli numeri.
			
			CheckNum(c,l,nome)
			quando un campo deve essere lungo almeno l caretteri che possono
			contenere solamente numeri.
			
			CheckDay(c,l,nome)
			verifica che il campo giorno sia lungo di almeno l(2) caratteri
			e che essi siano compresi fra 0 e 31.
			
			CheckYear(c,l,nome,min,max)
			verifica che un campo sia numerico,lungo almeno l(4) e il valore
			compreso fra min e max.
			
			CheckLen(c,l,nome)
			verifica che un campo contenga esattamente l caratteri.
			
			CheckLenMin(c,l,nome)
			verifica che un campo contenga almeno l caratteri.
			
			CheckLenMax(c,l,nome)
			verifica che un campo contenga al massimo l caratteri.
			
			CheckLenMinMax(c,min,max,nome)
			verifica che un campo contenga fra min e max caratteri.
			
			CheckTel(c,nome)
			verifica che i caratteri del campo siano quelli di un numero di
			telefono.  Non accetta lettere.
			
			CheckCf(c)
			verifica che il campo contenga un valore di Codice Fiscale
			
			CheckPi(c)
			verifica che il campo contenga un valore di Codice Fiscale
			
			CheckCfPi(c)
			verifica Partita IVA se 11 caratteri, altrimenti Codice Fiscale
			
			CheckPwd(c1,c2)
			verifica che due campi rispettino la caratteristica di password
			medikey.
			
			CheckLogin(c,nome)
			Controlla la username.
			
			CheckEmail(c)
			controlla la validita di un campo email.
			
			checkChars(c,index) !!! PRIVATE
			verifica che i caratteri contenuti nel campo siano tutti quelli
			contenuti dentro una stringa(index).
			
Ritorno..:	Valori restituiti dalle funzioni di controllo
			true:	la funzione non ha rilevato alcun errore
			false:	la funzione ha rillevato un errore


Variabili:	Tutte le funzioni seguono le seguenti regole di nomenclatura
			s			stringa (si usa anche s1,s2,temp...)
			c			campo HTML come TextBoxo OptionBox (si usa anche c1,c2...)
			nome		nome del campo come viene mostrato all'utente
			min,max		valori numerici di minimo o massimo
			index		indice

Modifiche:	Elencare le modifiche
		<sigla>	<data>	<modifica>
-------------------------------------------------------------------------------
*/

function Trim(s)
{
	s=""+s;
	while( s.length>0 && s.charAt(0)==' ' ) 
	{
		s=s.substr(1,s.length-1);
	}
	while( s.length>0 && s.charAt(s.length-1)==' ' ) 
	{
		s=s.substr(0,s.length-1);
	}
	return s;	
}

function IsEmpty(c,nome) 
{ 
	c.value=Trim(c.value);
	if ( c.value=="" )
	{  
		alert("Attenzione: il campo '"+nome+"' e' obbligatorio!");
		c.focus();
		return false;   
	}
	return true;
}

function CheckOption(c,nome,min,max) 
{ 
	for ( var i=min; i<=max; i++ )
	{
		if ( c[i].checked ) return true;
	}
	alert("Attenzione: E' necessario fare una scelta per il campo '"+nome+"'!");
	return false;
}

function CheckChoice(c,nome,index)
{ 
	if ( c[index].checked )	return true;
	alert("Attenzione: Non e' possibile proseguire se non si accetta il campo '"+nome+"'!");
	return false;
}

function CheckValidDate(cG,cM,cA,nome)
{
	var g=cG.value;
	var m=cM.value;
	var a=cA.value;
	var bisestile=false;
 
	if ( (a%4==0) && ( (a%400==0) || (a%100!=0) ) ) bisestile=true;
	
	if  ((((m==11)||(m==4)||(m==6)||(m==9))&&(g>30))||(bisestile && (m==2) && (g>29))||( !bisestile && (m==2) && (g>28) )) 
		{ 
			alert("Attenzione: l'informazione '"+nome+"' non ha un valore valido!");
			cG.focus();
			return false;
		}
	return true;        
}          

function CheckList(c,nome) 
{ 
	if ( c.selectedIndex==0 )
	{  
		alert("Attenzione: selezionare una scelta valida per il campo '"+nome+"'!");
		c.focus();
		return false;   
	}
	return true;
}

function CheckList_nm(c,nome) 
{ 
	if ( c.selectedIndex==0 )
	{  
		if (c.value!=-1)
		{
			alert("Attenzione: selezionare una scelta valida per il campo '"+nome+"'!");
			c.focus();
			return false;   
		}
	}
	return true;
}


function CheckAlfa(c,l,nome)
{
	var s=c.value;
	if ( l>0 && s.length<l )
	{
		alert("Attenzione: Il campo "+nome+" deve contenere almeno "+ l +" caratteri.");
		c.focus();
		return false;
	}  
	for (i=0;i<s.length;i++)
	{
		if ( (s.charAt(i)>="0") && (s.charAt(i)<="9") ) 
		{
			alert("Attenzione: Il campo "+nome+" non deve contenere caratteri numerici.");
			c.focus();
			return false;
		}
	}
	return true;
}  

function CheckNum(c,l,nome)
{
	var s=c.value;
	if ( l>0 && s.length<l ) 
	{
		alert("Attenzione: Il campo "+nome+" deve contenere almeno "+ l +" caratteri.");
		c.focus();
		return false;
	}  
	for (i=0;i<s.length;i++) 
	{
		if ((s.charAt(i)<"0") || (s.charAt(i)>"9")) 
		{
			alert("Attenzione: Il campo "+nome+" deve contenere solo numeri.");
			c.focus();
			return false;
		}  
	}
	return true;
}  
    
function CheckDay(c,l,nome)
{
	if (!CheckNum(c,l,nome)) return false;
	var s=c.value;
	if ( s<0 || s>31 ) 
	{
		alert("Attenzione: Il campo "+nome+" non ha un valore valido.");
		c.focus();
		return false;
	}  
	return true;
}

function CheckYear(c,l,nome,min,max)
{
	if (!CheckNum(c,l,nome)) return false;
	var s=c.value;
	if ( s<min || s>max ) 
	{
		alert("Attenzione: Il campo "+nome+" non ha un valore valido.");
		c.focus();
		return false;
	}  
	return true;
}

function CheckLen(c,l,nome)
{
	var s=c.value;
	if ( l>0 && s.length!=l ) 
	{
		alert("Attenzione: Il campo "+nome+" deve contenere "+ l +" caratteri.");
		c.focus();
		return false;
	}  
	return true;
}

function CheckLenMin(c,l,nome)
{
	var s=c.value;
	if ( l>0 && s.length<l ) 
	{
		alert("Attenzione: Il campo "+nome+" deve contenere almeno "+ l +" caratteri.");
		c.focus();
		return false;
	}  
	return true;
}

function CheckLenMax(c,l,nome)
{
	var s=c.value;
	if ( l>0 && s.length>l ) 
	{
		alert("Attenzione: Il campo "+nome+" deve contenere meno di "+ l +" caratteri.");
		c.focus();
		return false;
	}  
	return true;
}

function CheckLenMinMax(c,min,max,nome)
{
	return CheckLenMin(c,min,nome) && CheckLenMax(c,max,nome);
}
   
function CheckTel(c,nome)
{
	var x;
	var s=c.value;
	for ( var i=0; i<s.length; i++ ) 
	{
		x=s.charAt(i);
		if (((x<"0") || (x>"9")) && ((x!="+") && (x!=".") && (x!="/") && (x!="-")))
		{
			alert("Attenzione: numero di "+nome+" non valido.");
			c.focus();
			return false;
		}
	}
	return true;
}  

function CheckCf(c)
{
	sCf=c.value.toString();
	sCf=sCf.toUpperCase();
	c.value=sCf;

	dispari = " 01000507091315171921999999999999990100050709131517192102041820110306081214161022252423"
	pari    = " 00010203040506070809999999999999990001020304050607080910111213141516171819202122232425"
	sCf = " " + sCf;
	s=0;
	
	for ( i=1; i<=15; i++ )
	{
		a=parseInt((sCf.charCodeAt(i)-48)*2+1);
		if (parseInt(i/2) * 2 == i) 
		{
			if (pari.substr(a,2)=="08")	s+=8;
			if (pari.substr(a,2)=="09")	s+=9;
			s+=parseInt(pari.substr(a,2));
		}
		else 
		{
			if (dispari.substr(a,2)=="08") s+=8;
			if (dispari.substr(a,2)=="09") s+=9;
			s+=parseInt(dispari.substr(a,2));
		}
	}
	a=parseInt((sCf.charCodeAt(16)-48)*2+1);
	e1=parseInt(pari.substr(a,2));
	e2=parseInt((s-(parseInt(s/26))*26));
	if (e1!=e2)
	{
		alert('Codice fiscale errato');
		c.focus();
		return false;
	}
	else return true;
}

function CheckPi(c)
{
	var sPI=c.value.toString();
	var d=0;
	for( i=0; i<=10; i=i+2 )
	{
		d+=parseInt(sPI.charAt(i));
	}
	var p=0;
	var v=0;
	for ( i=1; i<=9; i=i+2 )
	{
		if (parseInt(sPI.charAt(i))<5) v=parseInt(sPI.charAt(i))*2;
		else v=parseInt(sPI.charAt(i))*2-9;
		p=p+v;
	}
	var s=d+p;
	if ( (s%10)==0 ) return true;
	else
	{
		alert('Partita Iva non valida');
		c.focus();
		return false;
	}
} 

function CheckCfPi(c)
{
	var s=c.value.toString();
	if (s.length==11) return CheckPi(c);
	else return CheckCf(c);
}

function CheckPwd(c1,c2) 
{
	s1 = c1.value;
	s2 = c2.value;

	if (s1 != s2) 
	{
		alert ("\nLe due password non sono uguali.")
		c1.focus();
		c1.select();
		return false;
	}
	s1 = Trim(s1);
	if ( s1=="" || s1.length<7 || s1.length>20 )
	{
		alert("Password errata!  La password deve essere di almeno 7 caratteri e non piu di 20 caratteri. Sono consentiti solo lettere e numeri!");
		c1.focus();
		c1.select();
		return false;
	}
	return checkChars(c1,4);
}

function CheckLogin(c,nome) 
{
	s = c.value;
	s = Trim(s);
	if ( s=="" || s.length<6 || s.length>20 )
	{
		alert("Attenzione: Il campo "+nome+" deve essere di almeno 6 caratteri e non piu di 20 caratteri!");
		c.focus();
		c.select();
		return false;
	}
	return checkChars(c,4);
}

function CheckWebmail(c,nome) 
{
	s = c.value;
	s = Trim(s);
	if ( s=="" || s.length<4 || s.length>25 )
	{
		alert("Attenzione: Il campo "+nome+" deve essere di almeno 4 caratteri e non piu di 25 caratteri!");
		c.focus();
		c.select();
		return false;
	}
	return checkChars(c,4);
}

function CheckEmail(c)
{
	var s=c.value;
	/* The following pattern is used to check if the entered e-mail address
	fits the user@domain format.  It also is used to separate the username
	from the domain. */
	var emailPat=/^(.+)@(.+)$/
	var specialChars="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]"
	var validChars="\[^\\s" + specialChars + "\]"
	var firstChars=validChars
	var quotedUser="(\"[^\"]*\")"
	var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/
	var atom="(" + firstChars + validChars + "*" + ")"
	var word="(" + atom + "|" + quotedUser + ")"
	var userPat=new RegExp("^" + word + "(\\." + word + ")*$")
	var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$")

	// Trying to figure out if the supplied address is valid.
	var matchArray=s.match(emailPat);
	if (matchArray==null)
	{
		alert("L'indirizzo Email sembra errato (verificare @ e .)");
		c.select();
		c.focus();	
		return false;
	}
	
	// See if "user" is valid 
	var user=matchArray[1];
	var domain=matchArray[2];
	if (user.match(userPat)==null)
	{
		alert("L'indirizzo Email sembra errato. Nome utente@ non valido.");
		c.select();
		c.focus();		
		return false;
	}

	var IPArray=domain.match(ipDomainPat);
	if (IPArray!=null)
	{
		for (var i=1;i<=4;i++)
		{
			if (IPArray[i]>255) 
			{
				alert("L'indirizzo Email sembra errato. Nome @dominio non valido");
				c.select();
				c.focus();			
				return false;
			}
		}
		return true;
	}

	// Domain is symbolic name
	var domainArray=domain.match(domainPat);
	if (domainArray==null)
	{
		alert("L'indirizzo Email sembra errato.");
		c.select();
		c.focus();		
		return false;
	}

	// Now we need to break up the domain to get a count of how many atoms it consists of.
	var atomPat=new RegExp(atom,"g");
	var domArr=domain.match(atomPat);
	var len=domArr.length;
	if (domArr[domArr.length-1].length<2 || domArr[domArr.length-1].length>3)
	{
		alert("L'indirizzo Email sembra errato. Suffisso dominio errato (2 o 3 caratteri).");
		c.select();
		c.focus();	   
   		return false;
	}

	if (domArr[domArr.length-1].length==3 && len<2)
	{
		alert("L'indirizzo Email sembra errato. Manca il dominio!");
		c.select();
		c.focus();	
		return false;
	}

	return true;
}

// Attento: USO PRIVATO non deve essere utilizzata al difuori di questo file
function checkChars(c,index)
{
	if ( isNaN(index) || index>7 || c.value=="undefined" )
	{
		alert("Errore di implementazione della funzione checkChars!");
		return false;
	}
	
	// Attento: Non toccare l'ordine, aggiungere stringe solo progressivamente!
	var validChars = new Array(8);
	validChars[0] = "0123456789";
	validChars[1] = "abcdefghijklmnopqrstuvwxyz";
	validChars[2] = "abcdefghijklmnopqrstuvwxyz0123456789";
	validChars[3] = "abcdefghijklmnopqrstuvwxyzàèéìòù";
	validChars[4] = "abcdefghijklmnopqrstuvwxyz0123456789.-_";
	validChars[5] = "abcdefghijklmnopqrstuvwxyzàèéìòù0123456789_ -'^`´";
	validChars[6] = "abcdefghijklmnopqrstuvwxyzàèéìòù_0123456789 -£.,@$!&'?%()+#!^`´\n\r";
	validChars[7] = "+-()./ 0123456789";

	var error = "Errore! E' stato digitato un carattere non valido";
	var valid = true;
	var testo = c.value.toLowerCase();
	var temp  = "";
	
	for ( var i=0; i<testo.length; i++ ) 
	{
		temp = testo.substring(i, i+1);
		if ( validChars[index].indexOf(temp)=="-1" ) 
		{
			valid = false;
			break;
		}
	}
	
	if ( !valid ) 
	{
		alert(error);
		c.focus();
		c.select();
		return false;
	}
	else return true;
}