
function addPortale(robo){
        showPortali();

        numerorobo = robo.substr(7,12);
        numerorobo = numerorobo.replace(' ','');
        ////window.alert(numerorobo);
        if (numerorobo<MAX_PORTALI-1){

                my_element = document.getElementById(robo);
                my_element.style.display = 'block';
        }
        correctField(robo,'accetto');



}

function removePortale(robo){

        var my_select = document.getElementById('select_'+robo);
        my_div = document.getElementById(robo);
        my_div.style.display = 'none';
        my_select.selectedIndex = "0";


}	

function resetPortali(totPortali){

        document.getElementById('iscrizione_portali').checked = true;
        document.getElementById('portale0').style.display = 'none';
        document.getElementById('select_portale0').selectedIndex = '0';

        document.getElementById('nessun_portale').style.display = 'block';

        for (i = 1; i <= totPortali; i++){

                document.getElementById('select_portale'+i).selectedIndex = '0';
                my_div = document.getElementById('portale'+i);
                my_div.style.display = 'none';


        }

}

function showPortali(){

        document.getElementById('iscrizione_portali').checked = false;
        document.getElementById('portale0').style.display = 'block';
        document.getElementById('nessun_portale').style.display = 'none';

}
	/*
function checkChars (string) {
	
	var i;

	//troppo corto o troppo lungo
	if ( (string.length<4) || (string.length>15) ){
		uncorrectField('nickname','Deve avere pi&ugrave; di 4 caratteri ma meno di 15');
		return false;
	}else{
		for (i = 0; i < string.length; i++) {  // Search through string and append to unfiltered values to returnString.
			var c = string.charAt(i);
			if (allowed.indexOf(c) == -1) {function_Chars(); return false; }
		}
		if (string.length==0){
			function_void	(); return false;
		}		
	}	
	return true;

}
*/

// Tiro su lo script remoto
/*
function include_dom(script_filename) {

    var html_doc = document.getElementsByTagName('head').item(0);
    var js = document.createElement('script');
    js.setAttribute('language', 'javascript');
    js.setAttribute('type', 'text/javascript');
    js.setAttribute('src', script_filename);
    return html_doc.appendChild(js);

}

*/



// ==========================================0

var errors = new Array();
var fieldsRequired = new Array(
	'nickname',
	'password',
	'ripetipassword',
	'email',
	'accetto'
);
var fieldsRequiredEdit = new Array(
	'nome',
	'cognome',
	'provincia',
	'comune',
	'data_d',
	'data_m',
	'data_y',
	'sesso',
	'nazione'
);


// caratteri non ammessi
/*
function function_Chars() {
 		document.getElementById('nickname').focus();
 		//document.getElementById('nickname').select();	
 		//document.getElementById('msg_nickname').style.display = 'block';
 		//document.getElementById('msg_nickname').innerHTML = 'Il nickname scelto contiene caratteri non accettati. Inserire solo lettere in minuscolo o numeri.'; 		
 		uncorrectField('nickname','solo lettere minuscole, numeri e il carattere _');
		
}
*/
// caratteri non ammessi
/*
function function_void() {
 		document.getElementById('nickname').focus();
 		//document.getElementById('nickname').select();	
 		uncorrectField('nickname','Compila questo campo');
 		//document.getElementById('msg_nickname').style.display = 'block';
 		//document.getElementById('msg_nickname').innerHTML = 'Compila questo campo'; 		
		
}*/



//controllo lunghezza e confronto se ha compilato la ripetizione
function checkPassword(p1,p2){	
	
	//window.alert('0');
	
	
	//se ripeti password � stata compilata confronto le stringhe altrimenti controllo solo la lunghezza
	if ( (p2.value.length>0) && (p2.value.length<PASSWORD_MIN_LENGTH) ){

		//se la lunghezza era ok, controllo che siano uguali
		if (!errors['password']){
			
			
			if (p1.value!=p2.value){ 				
				
		 		uncorrectField('ripetipassword','Le due password non coincidono');
			}else{
				
				//document.getElementById('msg_password').style.display = 'none';				
				//document.getElementById('msg_ripetipassword').style.display = 'none';				
				correctField('password','ripetipassword');
			}	
		}	
		
	}else{		
		
		//controllo lunghezza della prima
		if ( (p1.value.length<PASSWORD_MIN_LENGTH) ){
			uncorrectField('password','Lunghezza min '+PASSWORD_MIN_LENGTH);		
		}else {
 			correctField('password','ripetipassword');	
 		}  
	   				

	}
	
}


//controllo le lunghezze che le due password siano uguali
function checkRipetiPassword(p1,p2,nextfield){
	
	//window.alert('0');
	
	
	//controllo che l'utente abbia gi� inserito la prima pass
	if (p1.value.length<PASSWORD_MIN_LENGTH){
		
		uncorrectField('password','La password deve essere lunga almeno '+PASSWORD_MIN_LENGTH+' caratteri');		
	}else{
		
		//controllo lunghezza
		if ( (p1.value.length<PASSWORD_MIN_LENGTH) && (p2.value.length<PASSWORD_MIN_LENGTH) ){		
			
			uncorrectField('password','La password deve essere lunga almeno '+PASSWORD_MIN_LENGTH+' caratteri');
					
		}else{	
						
			//se la lunghezza era ok, controllo che siano uguali			
			if (p1.value!=p2.value){ 				
				
		 		uncorrectField('ripetipassword','Le due password non coincidono');
			}else{
											
				correctField('ripetipassword',nextfield);
			}				
			
		}
		
		
	}
	
}

//controllo la email
function checkEmail(){
	
    var email = document.getElementById('email');
    var pattern=/^([a-zA-Z0-9_.-])+@([a-zA-Z0-9_.-])+\.([a-zA-Z])+([a-zA-Z])+/;

    if(pattern.test(email.value)){
                correctField('email','prefisso');
                return true;
    }else{
                uncorrectField('email','Non sembra essere un indirizzo e-mail valido');
                return false;
    }
	
}

function checkTutto(my_action){
    
	var nerrors = 0;

	if (my_action=='edit'){
		fieldsRequired = fieldsRequiredEdit
	}
	
	//controllo se sono stati compilati tutti i campi
	for (i=0;i<fieldsRequired.length;i++){
       currField = fieldsRequired[i];
       switch (currField){
            case "password":

                //lunghezza password
                if ( (document.getElementById(currField).value.length<PASSWORD_MIN_LENGTH) ){
                    uncorrectField('password','Lunghezza min '+PASSWORD_MIN_LENGTH);
                }else {
                    correctField('password','ripetipassword');
                }

            break;
            case "ripetipassword":
                checkPassword(document.getElementById('password'),document.getElementById(currField));
            break;
            case "nickname":
                if ( (document.getElementById(currField).value.length!=0) ){
                    checkNickname(document.getElementById(currField).value);
                }else{
                    uncorrectField('nickname','non &egrave; stato selezionato alcun nickname')
                }
            break;
            case "sesso":
                if ( (!document.getElementById('sesso_m').checked) && (!document.getElementById('sesso_f').checked) ){
                    uncorrectField('sesso','selezionare il sesso');
                }else{
                    correctField('sesso','accetto');
                }
            break;
            case "data_m":
            case "data_y":
            case "data_d":
                if ( (document.getElementById(currField).value.length==0) ){
                    uncorrectField('datadinascita','il formato della data non &egrave; valido');
                }else{
                    checkDate();
                    //correctField('datadinascita','accetto');
                }
            break;
            case "accetto":
                if (!document.getElementById('accetto').checked){
                    uncorrectField('accetto','&egrave; necessario accettare le condizioni');
                }else{
                    correctField('accetto','accetto');
                }
            break;
            case "provincia":
                ////window.alert(document.getElementById('provincia').value);
                if (document.getElementById('provincia').value=='0'){
                    uncorrectField('provincia','nessuna provincia selezionata');
                }else{
                    correctField('provincia','accetto');
                }
            break;
            case "email":
                ////window.alert(document.getElementById('provincia').value);
                if (document.getElementById('email').value=='0'){
                    uncorrectField('email','campo mancante');
                }else{
                    checkEmail();
                }
            break;
            default:

                if (document.getElementById(currField).value.length=='0'){
                    uncorrectField(currField,'campo mancante');
                }else{
                    correctField(currField,'accetto');
                }
       }
	}	

	//controllo se ci sono errori
	for ( currError in errors ) {
       if (errors[currError]) {
        nerrors++;
        //window.alert(currError);
       }
	}
	
	
	////window.alert(nerrors);
	
	//ci sono errori, rimango nel form
	if (nerrors>0){		
		location.href = '#';
		return false;
	}
	

}

//controllo il formato della data
function checkDate(){
	
	var day = document.getElementById('data_d').value;
	var month = document.getElementById('data_m').value-1;
	
	var dummy_year = document.getElementById('data_y').value;
	var year = dummy_year.substr(2,2);
	var date_errors = 0;
	
	//var dummy_date = day+month+year;
	
   var source_date = new Date(year,month,day);
	
	  if(day != source_date.getDate())
	  {
	   // alert('Day is not valid!');
	   	date_errors ++;	    
	  }
	  if(dummy_year != source_date.getFullYear())
	  {
	    //alert('Year is not valid!');
	   	date_errors ++;
	  }
	
	  if(month != source_date.getMonth())
	  {
	    //alert('Month is not valid!');
	   	date_errors ++;
	  }

   if (!date_errors)
   	correctField('datadinascita','comune');
   else
   	uncorrectField('datadinascita','il formato della data non &egrave; valido');
	

   return true;
		
		
}


//cellulare
function checkCell(){	

	var prefisso = document.getElementById('prefisso').value;
	var numero = document.getElementById('numero').value;
	
	
	//siccome non � obbligario, se � vuoto non me ne frega un cazzo
	//if (prefisso.length=='0' && numero.length=='0'){
		
		if ( (prefisso.length!='3') || (numero.length<'6') || (numero.length>'7') ) {
			if ((prefisso.length!='0' && numero.length!='0')){
				uncorrectField('cellulare','numero di cellulare non &egrave; valido (es. 349 1234567)');
			}
		}else{
			correctField('cellulare','portale0');			
		}
	
	//}
	
}

//checkbox finale: adesso inutile
function checkAccetto(){
		/*accetto = document.getElementById('accetto').value;
		//window.alert(accetto);*/
		if (!document.getElementById('accetto').checked){
			uncorrectField("accetto","E' necessario accettare le condizioni");	
		}else{
			correctField('accetto');
		}
}

//mostra il check e focus su campo successivo
function correctField(currfield,nextfield){			
		
		
		
		errors[currfield] = 0;		
		
		//portale di iscrizione			
		if (currfield.substr(0,7)=='portale'){
			
			////window.alert(currfield);
			
			document.getElementById('reg_check_'+currfield).innerHTML = '<img alt=\"ok\" src=\"/img/Community/check.gif\"/>';
			
															
		}else{
		
			switch (currfield){
								
				
				
				//cellulare
				case 'cellulare':
					if ( (document.getElementById('numero').value.length==0) || (document.getElementById('prefisso').value.length==0) ){
						uncorrectField(currfield,'prefisso o numero non compilati');															
					}				
					
					document.getElementById('msg_'+currfield).style.display = 'none';		
					document.getElementById('reg_check_'+currfield).innerHTML = '<img alt=\"ok\" src=\"/img/Community/check.gif\"/>';
				
					document.getElementById(nextfield).focus();				
				break;	
				
				//data di nascita
				case 'datadinascita':
	
					if ( (document.getElementById('data_d').value.length==0) || (document.getElementById('data_m').value.length==0) || (document.getElementById('data_y').value.length==0) ){
						uncorrectField('datadinascita','data incompleta');															
					}				
					
					document.getElementById('msg_'+currfield).style.display = 'none';		
					document.getElementById('reg_check_'+currfield).innerHTML = '<img alt=\"ok\" src=\"/img/Community/check.gif\"/>';
					
					//document.getElementById(nextfield).focus();							
							
				break;
				
				//tutti gli altri casi			
				default:			
					
					var vuoto = 0;
					
					////window.alert(currfield.substr(0,7)=='portale');
									
					//se l'elemento esiste
					if (document.getElementById(currfield)){					
						//se � vuoto mostro errore
						if (document.getElementById(currfield).value.length=="0") {	
												
							uncorrectField(currfield,'campo incompleto');												
							vuoto=1;
							//alert(currfield+' vuoto!');
						}					
					}
					
					//mostro msg e check 				
					if (!vuoto){
						//alert('ghesboro'+currfield);
						document.getElementById('msg_'+currfield).style.display = 'none';		
						
			
						document.getElementById('reg_check_'+currfield).innerHTML = '<img alt=\"ok\" src=\"/img/Community/check.gif\"/>';
						
						if (document.getElementById(nextfield)){
							document.getElementById(nextfield).focus();							
							
						}
					}									
			}
		
		}

}

//mostra la cross
function uncorrectField(currfield,msg){							
		
	
		errors[currfield] = 1;
		////window.alert(currfield+errors[currfield]);
				
		
		
		document.getElementById('msg_'+currfield).style.display = 'block';			
		document.getElementById('msg_'+currfield).innerHTML = msg;	
		document.getElementById('reg_check_'+currfield).style.display = 'block';	
		document.getElementById('reg_check_'+currfield).innerHTML = '<img alt=\"ok\" src=\"/img/Community/cross.gif\"/>';
		
		//alert(currfield);
		
		if (document.getElementById(currfield))
			document.getElementById(currfield).focus();			
							
		////window.alert(document.getElementById('reg_check_'+currfield).innerHTML);
	
}
// ==========================================0


function checkAvailability(nickname) {

    $('#reg_check_nickname').css('display','block');
    $('#reg_check_nickname').children('img').remove();
    $('#reg_check_nickname').append('<img src=\'/img/Community/ajaxload_16.gif\'>');

    $.ajax({
    type: 'POST',
    url: '/services/Frontend/check_username.php',
    dataType: 'xml',
    data: 'username='+nickname,
    success: function(xml) {

        if ($(xml).find('error').text())
        {            
            uncorrectField('nickname','Nickname gi&agrave; occupato');
        }
        else
        {
            correctField('nickname','password');
        }

    }
    });

}

function checkEditPassword(){
	
	var nerrors = 0;		
	var my_password = document.getElementById('password');
	var my_ripetipassword = document.getElementById('ripetipassword');
	var my_oldpassword = document.getElementById('oldpassword');

	if ( (my_password.value<PASSWORD_MIN_LENGTH) ) 
		uncorrectField('password','Lunghezza min '+PASSWORD_MIN_LENGTH);		
	else{
		if (my_password.value.length==0) 
			uncorrectField('password','Campo mancante');
		else
			correctField('password','ripetipassword');	
			
		if (my_ripetipassword.value.length==0) 
			uncorrectField('ripetipassword','Campo mancante');
		else
			correctField('ripetipassword','ripetipassword');	
					
		if (my_oldpassword.value.length==0) 
			uncorrectField('oldpassword','Campo mancante');
		else
			correctField('oldpassword','password');			
			
		if ( ((my_password.value.length!=0) && (my_ripetipassword.value.length!=0)) && (my_password.value!=my_ripetipassword.value)  ){
			uncorrectField('password','Le due password non coincidono');
			uncorrectField('ripetipassword','Le due password non coincidono');
		}else{
			correctField('password','ripetipassword');	
			correctField('ripetipassword','ripetipassword');		
		}
	}
	////window.alert(errors.length);
		
							
	//controllo se ci sono errori
	for ( currError in errors ) {
   if (errors[currError]) {
   	nerrors++;
   }   
	}
	
	
	//ci sono errori, rimango nel form
	if (nerrors>0){		
		return false;
	}
		
}


function checkNickname(nickname)
{

    var pattern=/^([a-z0-9]+)$/;
    var pattern_min=/^([a-z]+)$/;

    

    if ( (document.getElementById('nickname').value.length<NICKNAME_MIN_LENGTH) || (document.getElementById('nickname').value.length>NICKNAME_MAX_LENGTH) || (!pattern.test(document.getElementById('nickname').value)) )
        {
            if (document.getElementById('nickname').value.length<NICKNAME_MIN_LENGTH)
                uncorrectField('nickname','Deve avere più di '+NICKNAME_MIN_LENGTH+' caratteri');
            else
                if (document.getElementById('nickname').value.length>NICKNAME_MAX_LENGTH)
                uncorrectField('nickname','Deve avere meno di '+NICKNAME_MAX_LENGTH+' caratteri');
            else
                if ( (document.getElementById('nickname').value) != (document.getElementById('nickname').value.toLowerCase()) )
                uncorrectField('nickname','Deve contenere solo lettere minuscole');
            else
                if (!pattern.test(document.getElementById('nickname').value))
                uncorrectField('nickname','Deve contenere solo lettere e numeri');
                
               
        }
    else
        checkAvailability(document.getElementById('nickname').value);

}
