// JavaScript Document
// Script per il controllo della validità del form 
function controllauser(entered) {
	var length = entered.value.length;
	var filter = /^[a-z0-9]{5,15}$/i;
	if(entered.value == ""){
		alert ("Il campo Username è vuoto");
		return false;
	} 
	if (filter.test(entered.value) == false) {	
		alert("Username non valido, può contenere solo numeri o lettere ed essere lungo dai 5 ai 15 caratteri")
		return false;
	}

return true;
}


function controllapwd(enter1, enter2) {
	if(enter1.value == "" || enter2.value == ""){
		alert ("Un campo Password risulta vuoto");
		return false;
	}	
	if (enter1.value != enter2.value) {
		alert ("Le 2 Password inserite non corrispondono");
		return false;
	}
	if (enter1.value.length < 6) {
		alert ("La Password scelta è lunga meno di 6 caratteri");
		return false;
	} 

return true;
}


function controllamail(mail) {
	var str = mail.value;
	var filter=/^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i
	if (filter.test(str)) {
		return true;
	} else {
		alert("Indirizzo email non valido")
		return false;
	}
}

function controllareg(reg) {
	if(reg.value == ""){
		alert ("Seleziona la regione di residenza");
		return false;
	} 

return true;
}

function daysInFebruary (year){
	// Febbraio ha 29 giorni negli anni divisibili per 4,
    // ECCETTO per i secoli che non sono divisibili anche per 400.
    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}
function DaysArray(n, y) {
		var giorni = 31;
		if (n==4 || n==6 || n==9 || n==11) {
		giorni = 30;
		}
		if (n==2){
		giorni = daysInFebruary(y);
		}
		
   return giorni;
}

function controlladata(giorno, mese, anno){
	day = giorno.value;
	month = mese.value;
	year = anno.value;
	if (year=="" || isNaN(year) || year<1900 || year>2006) {
		alert("Devi inserire un anno compreso tra 1900 e 2006");
		return false;
	}
	if (month=="" || month<1 || month>12){
		alert("Non hai selezionato un mese");
		return false;
	}
	if (day=="" || day<1 || day > DaysArray(month, year) ){
		alert("Non hai selezionato un giorno corretto");
		return false;
	}

}

// Funzione principale
function formvalidation(thisform) {
	var controllouser = controllauser(thisform.user);
	var controllopwd = controllapwd(thisform.password1, thisform.password2);
	var controllomail = controllamail(thisform.email);
	var controllodata = controlladata(thisform.giorno, thisform.mese, thisform.anno);
	var controlloreg = controllareg(thisform.regione);
	
	if (controllouser == false) {
		thisform.user.focus(); 
		return false;
	}
	if (controllopwd == false) {
		thisform.password1.focus(); 
		return false;
	}
	if (controllomail == false) {
		thisform.email.focus(); 
		return false;
	}
	if (controllodata == false) {
		thisform.anno.focus(); 
		return false;
	}
	if (controlloreg == false) {
		thisform.regione.focus(); 
		return false;
	}
}