var digits = "0123456789";

function isEmpty(s)
{   
return ((s == null) || (s.length == 0))
}

function isDigit (c)
{   return ((c >= "0") && (c <= "9"))
}


function warnInvalid (theField, s)
{   
    theField.focus();
    theField.select();
    alert(s);
    return false;
}


function stripCharsNotInBag (s, bag)

{   var i;
    var returnString = "";

    // Search through string's characters one by one.
    // If character is in bag, append to returnString.

    for (i = 0; i < s.length; i++)
    {   
        // Check that current character isn't whitespace.
        var c = s.charAt(i);
        if (bag.indexOf(c) != -1) returnString += c;
    }

    return returnString;
}

function checkNumber (theField, emptyOK) 
{   

if (isEmpty(theField.value)) return true; 
    else 
    {  var normalizedNumber = stripCharsNotInBag(theField.value, digits) 
       if (theField.value != normalizedNumber)  
	{
	  alert ("Il campo " + emptyOK + " deve essere numerico!");	
	  theField.focus();
	  return false;			
        }   
       else  
          return true; 
      
    } 
} 

function charNS (c, s)
{  
	if (s.value.length > c) 
	{
	alert ("Campo troppo lungo! (Max " + c + " caratteri!)");
	s.focus();			
	return false;
    	}
return true;
}

function charNSF(c, s, f)
{  
	if (s.value.length != c && s.value.length != 0) 
	{
	alert ("Lunghezza campo " + f + " errato! (Deve essere di " + c + " caratteri!)");
	s.focus();			
	return false;
    	}
return true;
}


function isLunghezzaCFCorretta(campo, nomeCampo)
{  
	if (campo.value.length != 11 && campo.value.length != 16) 
	{
	alert ("Lunghezza campo " + nomeCampo + " errato! ");
	campo.focus();			
	return false;
    	}
return true;
}

function charPIVA (lung, s)
{  

	if (s.value.length != lung && s.value.length != 0) 
	{
		alert ("Lunghezza campo partita Iva errato! (Deve essere di " + lung + " caratteri!)");
	s.focus();			
	return false;
}
     	
return true;
}


function checkEmail(theField,IDmail)
{
	if (theField.value.length != 0)
	{
		if ((theField.value.indexOf("@") == -1) || (theField.value.indexOf(".") == -1) || (theField.value.length < 7))
		{
			alert ("E-mail non corretta!");
			theField.focus();
			return false;
		}

		return true;	
	}
}
	
function checkEmailUguali(theField,theField2)
{
	if (theField.value != theField2.value)
	{
		alert ("Il campo E-Mail e la conferma non coincidono");
		theField.focus();
		return false;
	}
return true;
}

function checkEmpty(theField, IDtheField)
{
	if (theField.value == "")
	{
		alert ("Inserire " + IDtheField +"! (Campo Obbligatorio)");
		theField.focus()
		return false;
	}
return true;
}


function checkEmptyF(theField, IDtheField, flag)
{
	if (theField.value == "" && flag == "S")
	{
		alert ("Inserire " + IDtheField +"! (Campo Obbligatorio)");
		theField.focus()
		return false;
	}
return true;
}

function checkEmptyzerocombo(theField, IDtheField)
{
   if (theField.selectedIndex)
   {
		if (theField.options[theField.selectedIndex ].value == "")
		{
         alert ("selezionare " + IDtheField +"! (Campo Obbligatorio)");
         theField.focus()
         return false;
		}
      return true;
   }
   return true;
}

function checkEmptyzerocomboF(theField, IDtheField, flag)
{
   if (theField.selectedIndex)
   {
		if (theField.options[theField.selectedIndex ].value == "" && flag == "S" )
		{
         alert ("selezionare " + IDtheField +"! (Campo Obbligatorio)");
         theField.focus()
         return false;
		}
      return true;
   }
   return true;
}



function CheckCons(theField)
  {
	if (theField[0].checked == false)
	     {
	    alert("Attenzione! Non si è dato il consenso. Per continuare la registrazione, dare il consenso alla legge sulla privacy ");
	    return false;	
  	    }

return true;
  }	
  
function verificaCampi(form)
  {
 if(   	
   	checkEmptyzerocombo(form.ana_tiposogg, "Tipo soggetto") && 
   	checkEmpty(form.ana_ragsoc, "Ragione sociale") &&
   	charNS(40, form.ana_ragsoc) &&
   	checkEmpty(form.ana_viares, "Via di Residenza") &&
   	charNS(30, form.ana_viares) &&
   	charNS(5, form.ana_civres) &&
   	checkEmpty(form.ana_civres, "Numero Civico") &&
   	checkNumber(form.ana_civres, "Numero Civico") &&
   	charNS(3, form.ana_sufres) &&
   	charNS(3, form.ana_scalares) &&
   	charNS(3, form.ana_pianores) &&
   	checkEmpty(form.ana_capres, "CAP") &&
   	checkNumber(form.ana_capres, "CAP") &&
   	charNSF(5, form.ana_capres, "CAP") &&
   	checkEmpty(form.ana_locres, "Località di Residenza") &&
   	charNS(30, form.ana_locres) &&
   	charNS(35, form.ana_luogonas) &&
      checkEmptyF(form.ana_luogonas, "Luogo di nascita",co[form.ana_tiposogg.value][0]) &&
      checkEmptyF(form.ana_datanas, "Data nascita",co[form.ana_tiposogg.value][0]) &&
   	CtlDate(form.ana_datanas, "Data nascita") && 
      checkEmptyF(form.ana_codfis, "Codice fiscale",co[form.ana_tiposogg.value][1]) &&
      charNSF(16, form.ana_codfis, "Codice fiscale" ) &&
      checkEmptyF(form.ana_pariva, "Partita IVA",co[form.ana_tiposogg.value][2]) &&
   	checkNumber(form.ana_pariva, "Partita IVA") &&
   	charPIVA (pi[form.ana_pivanaz.value], form.ana_pariva) &&
   	checkEmpty(form.ana_numtel, "Numero Telefonico") &&
   	charNS(15, form.ana_numtel) &&
   	checkEmpty(form.ana_des_numtel, "Descrizione Numero Telefonico") &&
   	charNS(30, form.ana_des_numtel) &&
   	charNS(15, form.ana_numtel2) &&
   	charNS(30, form.ana_des_numtel2) &&
   	charNS(15, form.ana_numfax) &&
   	charNS(30, form.ana_des_numfax) &&
   	checkEmpty(form.ana_email, "E-mail") &&
   	charNS(50, form.ana_email) &&
   	checkEmail(form.ana_email, "conferma e-mail") &&
   	checkEmailUguali(form.ana_email, form.ana_emailConf) &&
   	checkEmptyzerocomboF(form.ana_doc_tipo, "Tipo documento",co[form.ana_tiposogg.value][4]) && 
      checkEmptyF(form.ana_doc_numero, "Numero documento",co[form.ana_tiposogg.value][4]) &&
   	charNS(20, form.ana_doc_numero) &&
      checkEmptyF(form.ana_doc_rila, "Ente di rilascio documento",co[form.ana_tiposogg.value][4]) &&
   	charNS(40, form.ana_doc_rila) &&
      checkEmptyF(form.ana_doc_sca, "Data scadenza documento",co[form.ana_tiposogg.value][4]) &&
   	CtlDate(form.ana_doc_sca, "Data scadenza documento") &&
      checkEmptyF(form.ana_soggetto, "Legale rappresentante",co[form.ana_tiposogg.value][5]) &&
   	charNS(40, form.ana_soggetto) &&
   	CheckCons(form.ConsPrivacy) 
   ) 
	{ 
		return true;
	}
else
	{
		return false;
	}
  }


function CtlDate(valdata,nomedata) 
{

if (isEmpty(valdata.value)) return true; 


if (isDate(valdata.value))
	{
		return true;
	}
else
	{
		alert (nomedata + " errata");
		valdata.focus();
		return false;
	}

}


/************************************************************
* FileName:    DateValidation.js                            *
* Description: This is a clientside javascript library      *
*              containing functions for date validations.   *
************************************************************/
//Time Constants
var OneMinute = 60 * 1000
var OneHour = OneMinute * 60
var OneDay = OneHour * 24
var OneWeek = OneDay * 7

/************************************************************
* Function:    isDate                                       *
* Description: Determines whether the form field passed     *
*              contains a valid date.                       *
* Parameters:  Field - the HTML form field object to        *
*              validate.                                    *
************************************************************/      
function isDate(inputStr) {

	// convert hyphen delimiters to slashes

	if (inputStr.length != 10) return false;


	while (inputStr.indexOf("-") != -1) {
		inputStr = inputStr.replace("-","/")
	}
	var delim1 = inputStr.indexOf("/")
	var delim2 = inputStr.lastIndexOf("/")
	if (delim1 != -1 && delim1 == delim2) {
		// there is only one delimiter in the string
		return false
	}
	if(delim1 != -1) {
	// there are delimiters; extract component values
		var dd = parseInt(inputStr.substring(0,delim1),10)
		var mm = parseInt(inputStr.substring(delim1 + 1,delim2),10)
		var yyyy = parseInt(inputStr.substring(delim2 + 1, inputStr.length),10)
	} else {
		// there are no delimiters; extract component values
		var dd = parseInt(inputStr.substring(0,2),10)
		var mm = parseInt(inputStr.substring(2,4),10)
		var yyyy = parseInt(inputStr.substring(4,inputStr.length),10)
	}

	if (isNaN(mm) || isNaN(dd) || isNaN(yyyy)) {
		// there is a non-numeric character in one of the component values
		return false
	}
	if (mm < 1 || mm > 12) {
		// month value is not 1 thru 12
		return false
	}
	if (dd < 1 || dd > 31) {
		// date value is not 1 thru 31
		return false
	}

	// validate year, allowing for checks between year ranges
	// passed as parameters from other validation functions
	if (yyyy > 100 && yyyy < 1000){
            return false;
      }
	if (yyyy < 100) {
		// entered value is two digits, which we allow for 1930-2029
		if (yyyy >= 30) {
			yyyy += 1900
		} else {
			yyyy += 2000
		}
	}
	if (yyyy > 3000) {
		return false;
	}
      //Make sure user entered a valid day for the month specified
	if (!checkMonthLength(mm,dd)) {
		return false
	}
	//Check for leapyear problems
	if (mm == 2) {
		if (!checkLeapMonth(mm,dd,yyyy)) {
			return false
		}
	}
	// Redisplay value using the standard date delimiter
	inputStr = mm + "/" + dd + "/" + yyyy;
	
	// Everything was ok
	return true

}

/*************************************************************
* Function:		checkMonthLength                           *
* Description:	Determines if the month provided has 30 or *
*                 31 days and returns an error if the day    *
*                 provided is invalid                        *
*************************************************************/
function checkMonthLength(mm,dd) {
	var months = new  Array("","January","February","March","April","May","June","July","August","September","October","November","December")
	if ((mm == 4 || mm == 6 || mm == 9 || mm == 11) && dd > 30) {
		alert(months[mm] + " has only 30 days.")
		return false
	} else if (dd > 31) {
		alert(months[mm] + " has only 31 days.")
		return false
	}
	return true
}

/*************************************************************
* Function:		checkLeapMonth                             *
* Description:	Determines if the year provided is a leap  *
*                 year and that the day provided is valid.   *
*************************************************************/
function checkLeapMonth(mm,dd,yyyy) {
	if (yyyy % 4 > 0 && dd > 28) {
		alert("February of " + yyyy + " has only 28 days.")
		return false
	} else if (dd > 29) {
		alert("February of " + yyyy + " has only 29 days.")
		return false
	}
	return true
}

function checkDateRange(date1, date2){
	var Time1
	var Time2

	Time1 = date1.getTime()
	Time2 = date2.getTime()
	
	if(Time1 > Time2){
		alert("Please enter a valid beginning and ending date range.");
		return false;
	}
	return true;
}

function extractMonth(dateValue)
{
	var inputStr = dateValue.value;
	// convert hyphen delimiters to slashes
	while (inputStr.indexOf("-") != -1) {
		inputStr = inputStr.replace("-","/")
	}
	var delim1 = inputStr.indexOf("/")
	var delim2 = inputStr.lastIndexOf("/")
	if (delim1 != -1 && delim1 == delim2) {
		return false;
	}
	if(delim1 != -1) {
	// there are delimiters; extract component values
		var mm = parseInt(inputStr.substring(0,delim1),10)
	} else {
		// there are no delimiters; extract component values
		var mm = parseInt(inputStr.substring(0,2),10)
	}
	return mm;
}

function extractDay(dateValue)
{
	var inputStr = dateValue.value;

	// convert hyphen delimiters to slashes
	while (inputStr.indexOf("-") != -1) {
		inputStr = inputStr.replace("-","/")
	}
	var delim1 = inputStr.indexOf("/")
	var delim2 = inputStr.lastIndexOf("/")
	if (delim1 != -1 && delim1 == delim2) {
		return false;
	}
	if(delim1 != -1) {
	// there are delimiters; extract component values
		var dd = parseInt(inputStr.substring(delim1 + 1,delim2),10)
	} else {
		// there are no delimiters; extract component values
		var dd = parseInt(inputStr.substring(2,4),10)
	}
	return dd;
}

function extractYear(dateValue)
{
	var inputStr = dateValue.value;

	// convert hyphen delimiters to slashes
	while (inputStr.indexOf("-") != -1) {
		inputStr = inputStr.replace("-","/")
	}
	var delim1 = inputStr.indexOf("/")
	var delim2 = inputStr.lastIndexOf("/")
	if (delim1 != -1 && delim1 == delim2) {
		return false
	}
	if(delim1 != -1) {
	// there are delimiters; extract component values
		var yyyy = parseInt(inputStr.substring(delim2 + 1, inputStr.length),10)
	} else {
		// there are no delimiters; extract component values
		var yyyy = parseInt(inputStr.substring(4,inputStr.length),10)
	}
	return yyyy;
}

function controllo_data_sistema(data_form)
{
var today;
today = new Date;

var gg = Number(data_form.value.substring(0,2));
var mm = Number(data_form.value.substring(3,5));
var yyyy = Number(data_form.value.substring(6,10));


var sys_gg = today.getDate();
var sys_mm = today.getMonth();
var sys_yyyy = today.getYear();



if ((sys_yyyy > yyyy) || ((sys_yyyy == yyyy) && (sys_mm > mm)) || ((sys_yyyy == yyyy) && (sys_mm == mm) && (sys_gg > gg)))
	{
		alert("Errore: Data inferiore alla data di oggi!");
		data_form.focus();
		return false;
	}
return true;
}

