
var VerificaPartitaIva = true;
var VerificaCF = true;

function FormFillByArray(target,row){
	
			$(target).find('input, textarea, select').each(function() {
				//alert(this.value);
				var tag = $(this).get(0).nodeName.toLowerCase();
				var id = $(this).attr('id');
				var name = $(this).attr('name');
				var type = $(this).attr('type');
				var valore_nuovo = row[name];
            //console.log(row);
            //console.log('cerco JSON --->'+tag+'--'+name+'--'+id+'--'+type+'--> '+valore_nuovo+' --->'+row[name]);
                //if (typeof row[name] === 'object' && row[name] !== null) console.log(name+'is array');
				//alert(tag+'--'+name+'--'+id+'--'+type+'--'+valore_nuovo);
               /* if (valore_nuovo!=="undefined" && valore_nuovo!="" && valore_nuovo!=undefined) {
                    if  (isJson(valore_nuovo)) {
                        console.log('json valido --->'+tag+'--'+name+'--'+id+'--'+type+'--'+valore_nuovo);
                    } else {
                        console.log('json NON valido --->'+tag+'--'+name+'--'+id+'--'+type+'--'+valore_nuovo);
                    }
                } */
				//if (valore_nuovo!="") {
					if (tag=='input') {
						if (type=='radio') {
							$(this).filter("input[value='"+valore_nuovo+"']").attr('checked','checked');
						} else if (type=='checkbox') {
							//alert(tag+'--'+name+'--'+id+'--'+type+'--'+valore_nuovo);
							if (valore_nuovo!="" && valore_nuovo!=undefined && valore_nuovo!="undefined") {
								$(this).prop("checked",true);
							} else {
								$(this).prop("checked",false);
							}
							//$(this).attr('checked','checked');
						} else { 
							$(this).val(valore_nuovo);
						}
					} else if (tag=='textarea') {
						$(this).val(valore_nuovo);
					} else if (tag=='select') {
						$(this).val(valore_nuovo);
					}
				//}
			});
}
/*
function isJson(str) {
            try {
                return JSON.parse(str);
            } catch (e) {
                return false;
            }
}

function IsStringValidJSON(stringa){
      if (/^[\],:{}\s]*$/.test(stringa.replace(/\\["\\\/bfnrtu]/g, '@').
      replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']').
      replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {

        //the json is ok
        return true;
      } else {

        //the json is not ok
        return false;
      }
}
*/
/* SOSTITUITA DALL'UTILIZZO DI BBQ JQUERY codice incluso in fondo
function getUrlVars(data){
	var vars = [], hash;
	var hashes = data.split('&');
	for(var i = 0; i < hashes.length; i++){
		hash = hashes[i].split('=');
		vars.push(hash[0]);
		vars[hash[0]] = hash[1];
	}
	return vars;
}
*/		


function DisabilitaFormUniversale(target){

	
		$(target).find('input,select').not(".ExludeAnyway").attr('disabled', true);
		//$(target).find('input,select').css({'border':'3px solid #CCC'});
		$(target).find('input,select').not(".ExludeAnyway").css({'color':'#CCC'});
		$(target).find('.tastoSalva').not(".ExludeAnyway").hide(); //'input[name="email"]'
		$(target).find('.tastoModifica').not(".ExludeAnyway").attr('disabled', false);
		// appendo un'area sensibile per evitare i problemi di firefox con i click sui disabled elements
		$(target).css({'position':'relative'}); // potrebbe causare problemi????
		$(target).append('<div class="areaDisab" style="position:absolute;left:0;right:0;top:0;bottom:0;z-index:900;"></div>'); //border:1px solid #000
		$('.areaDisab').on('click',function(){ 
											//$(this).remove(); 
											AbilitaFormUniversale(target);
											if (typeof CustomForm_Abilita == 'function') {  CustomForm_Abilita(target); }
											});
}


function AbilitaFormUniversale(target){
		$(target).find('input,select').not(".ExludeAnyway").attr('disabled', false);
		$(target).find('input,select').not(".ExludeAnyway").css({'color':'#333'});
		$(target).find('.tastoSalva').not(".ExludeAnyway").show();
		$(target).find('.tastoModifica').not(".ExludeAnyway").attr('disabled', true);
		$('.areaDisab').remove();
}



function UsaAzioniJqueryRegistrazione(data,msg) {
	//alert(data);
	var s=data.split("*");
	var azione = s[0];
	var resto = (s[1]) ? s[1] : data;
	if (azione == "redirect") {
		window.location.href = resto;
	} else if (azione == "errore") {
		$(msg).html(resto); 
	} else if (azione == "richiesta_verifica") {
		//$(target).fadeOut(500); 
		$(msg).html(resto); 
	} else {
		$(msg).html(resto);
	}
}

function ClearInputErrorWarning(target){
	$(target).find('input,div').each(function(){ 
		//$(this).removeClass('warningBorder'); 
		$(this).parent().removeClass('has-error'); 
	});
	return false;
}
function SetInputErrorWarning(obj,msg){
	
	if (typeof warning_mode == "undefined") warning_mode = "alert"; // se non viene settata fuori viene settata qui
	$(obj).parent().addClass('has-error');
	$(obj).parent().find('label').addClass('control-label'); 
	$(obj).focus();
	if (warning_mode=="bootbox") {
		if (msg!="" && msg!=undefined) bootbox.alert('<h4>'+msg+'</h4>', function() {  });
	} else {
		if (msg!="" && msg!=undefined) alert(msg); // non va?
	}
	return false;
}
function FormCheck(target){
	var valid = true;
	//console.log(target);	
	
	// NO non va // prima verifico quelli che, anche se not required, devono comunque essere controllati
	/*$(target, "input, textarea, select").not(".ExludeAnyway").each(function(){
		console.log($(this).attr('name'));
		return false;
		return valid = emailWarnings( this );
		
	});  */
	
	$(target+" .required").not(".ExludeAnyway").each(function(){
		/*var str = $(this).val();
		str.replace(/Tho/g, 'cio');
		$(this).val(str); 
		alert($(this).val());*/
		
		if($(this).attr('name')!="" && $(this).attr('name')!=undefined && $(this).attr('name')!="undefined") { // senza ho avuto problemi
			if($(this).attr('name')=="scheda_collegata") {
				if ($(this).val()=="0" || $(this).val()=="") {
					return valid = SetInputErrorWarning($(this),'Attenzione devi selezionare un centro dalla mappa oppure selezionare una modalità di spedizione differente. ');
					/*bootbox.alert('<h4>Attenzione devi selezionare un centro dalla mappa oppure selezionare una modalità di spedizione differente.</h4>', function() {  });
					return valid = false;*/
				}
			} else {
				if($(this).val()=="" && $(this).attr('type') =="text")
					return valid = SetInputErrorWarning($(this));
				if($(this).val()=="" && $(this).attr('type') =="password")
					return valid = SetInputErrorWarning($(this),'Non hai inserito la password. ');
				if($(this).attr('name')=="PI" && controllaPIVA($(this).val())==false && VerificaPartitaIva==true) 
					return valid = SetInputErrorWarning($(this),'Partita IVA non valida, devi inserire un codice corretto e senza il prefisso "IT" ');
				
				// verifico il codice fiscale ma se esiste anche il required sulla partita iva, non ho neppure bisogno di verificare
				// che la p.i sia corretta perchè quando arrivo al cf la pi è già verificata
				if($(this).attr('name')=="CF") {
					if ($(target+" input[name=PI]").val() != $(this).val() && VerificaCF == true) { // se pi e cf sono uguali allora non verifico 
						if (validaCodiceFiscale($(this).val())==false) { // verifica cf personale, se è false ..
							if ($(this).val().length != 11) {  // verifico che sia almeno 11 caratteri
							// perchè potrebbe essere un cf aziendale ma differente da p.i.
							// se non è 11 cifre allora è un errore
								return valid = SetInputErrorWarning($(this),'Codice Fiscale non valido. ');
							}
						}
					} 
				}
				
				var errore_accettare_condizioni = new Array();
				errore_accettare_condizioni[1] = 'Per procedere devi accettare le condizioni';
				errore_accettare_condizioni[2] = 'To proceed you must accept the terms of use';
				errore_accettare_condizioni[3] = 'Pour continuer, vous devez accepter les conditions d\'utilisation';
				errore_accettare_condizioni[4] = 'Para continuar debes aceptar los términos de uso';
				errore_accettare_condizioni[5] = 'Um fortzufahren, müssen Sie die Nutzungsbedingungen akzeptieren';
				if( ($(this).attr('name') =="condizioni" || $(this).attr('name') =="condizioni_vendita") && $(this).is(":checked")!=true)
					return valid = SetInputErrorWarning($(this).parent().parent(),errore_accettare_condizioni[lingua]);
				
				var errore_selezione_provincia = new Array();
				errore_selezione_provincia[1] = 'Devi selezionare la provincia.';
				errore_selezione_provincia[2] = 'You must select the district.';
				errore_selezione_provincia[3] = 'Vous devez sélectionner la province.';
				errore_selezione_provincia[4] = 'Debes seleccionar la provincia.';
				errore_selezione_provincia[5] = 'Sie müssen die Provinz auswählen.';
				if( ($(this).attr('name') =="provincia" || $(this).attr('name') =="provincia2") && ($(this).val()=="" || $(this).val()==undefined))  
					return valid = SetInputErrorWarning($(this).parent(),errore_selezione_provincia[lingua]);
				
				
				if($(this).attr('name')=="Pec" && isValidEmailAddress( $(this).val())==false )
					return valid = SetInputErrorWarning($(this),'L\'email non è non valida');

				var errore_email_non_valida = new Array();
				errore_email_non_valida[1] = 'L\'email non è non valida';
				errore_email_non_valida[2] = 'The email is not invalid';
				errore_email_non_valida[3] = 'L\'email n\'est pas invalide';
				errore_email_non_valida[4] = 'El correo electrónico no es inválido';
				errore_email_non_valida[5] = 'Die E-Mail ist nicht ungültig';
				if($(this).attr('name')=="email" && isValidEmailAddress( $(this).val())==false )
					return valid = SetInputErrorWarning($(this),errore_email_non_valida[lingua]);
				
				if($(this).attr('name')=="email_conferma") {
					if($(this).val()!=$(target+" input[name=email]").val())
					return valid = SetInputErrorWarning($(this),'Devi inserire la stessa email in entrambi i campi');
				}
			}
		}
		
	});
	return valid;
}

function emailWarnings( thiss ){
//console.log(thiss.val());
	return false;
	// se il valore è stato inserito allora le email devono essere sempre controllate, required o no
	if($(thiss).val()!="" && $(thiss).val()!=undefined && $(thiss).val()!="undefined") { // senza ho avuto problemi
	
		if($(thiss).attr('name')=="Pec" && isValidEmailAddress( $(thiss).val())==false )
			return valid = SetInputErrorWarning($(thiss),'L\'email non è non valida');

		var errore_email_non_valida = new Array();
		errore_email_non_valida[1] = 'L\'email non è non valida';
		errore_email_non_valida[2] = 'The email is not invalid';
		errore_email_non_valida[3] = 'L\'email n\'est pas invalide';
		errore_email_non_valida[4] = 'El correo electrónico no es inválido';
		errore_email_non_valida[5] = 'Die E-Mail ist nicht ungültig';
		if($(thiss).attr('name')=="email" && isValidEmailAddress( $(thiss).val())==false )
			return valid = SetInputErrorWarning($(thiss),errore_email_non_valida[lingua]);
		
		if($(thiss).attr('name')=="email_conferma") {
			if($(thiss).val()!=$(target+" input[name=email]").val())
			return valid = SetInputErrorWarning($(thiss),'Devi inserire la stessa email in entrambi i campi');
		}
	}

}


function controllaPIVA( piva )
{
    if ( piva.length == 11 )
    {
		//13020460153
        //var codiceUFFICIOiva = parseInt( piva.substr( 0, 3 ) ) ;
        //if ( codiceUFFICIOiva <= 0 || codiceUFFICIOiva > 121 ) return false ;
    
        var X = 0 ;
        var Y = 0 ;
        var Z = 0 ;
    
        // cifre posto dispari ... ma per un array indicizzato a zero, la prima cifra ha indice zero ... appunto !
        X += parseInt( piva.charAt(0) ) ;
        X += parseInt( piva.charAt(2) ) ;
        X += parseInt( piva.charAt(4) ) ;
        X += parseInt( piva.charAt(6) ) ;
        X += parseInt( piva.charAt(8) ) ;

        // cifre posto pari ... ma per un array indicizzato a zero, la prima cifra ha indice uno ...
        Y += 2 * parseInt( piva.charAt(1) ) ;    if ( parseInt( piva.charAt(1) ) >= 5 ) Z++ ;
        Y += 2 * parseInt( piva.charAt(3) ) ;    if ( parseInt( piva.charAt(3) ) >= 5 ) Z++ ;
        Y += 2 * parseInt( piva.charAt(5) ) ;    if ( parseInt( piva.charAt(5) ) >= 5 ) Z++ ;
        Y += 2 * parseInt( piva.charAt(7) ) ;    if ( parseInt( piva.charAt(7) ) >= 5 ) Z++ ;
        Y += 2 * parseInt( piva.charAt(9) ) ;    if ( parseInt( piva.charAt(9) ) >= 5 ) Z++ ;
        
        var T = ( X + Y + Z ) % 10 ;

        var C = ( 10 - T ) % 10 ;

        return ( piva.charAt( piva.length - 1 ) == C ) ? true : false ;
		
    } else if ( piva.toLowerCase().substr( 0, 2 ) == "sm") {
		return true;
	} else {
		return false;
	}
}

// verifica se un valore è intero oppure no
function is_int(value){ 
  if((parseFloat(value) == parseInt(value)) && !isNaN(value)){
      return true;
  } else { 
      return false;
  } 
}

/*function isValidEmailAddress(emailAddress) {
	var pattern = new RegExp(/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i);
	return pattern.test(emailAddress);
};*/

/*
 * Original author:  Sandeep V. Tamhankar (stamhankar@hotmail.com)
 * old Source on http://www.jsmadeeasy.com/javascripts/Forms/Email%20Address%20Validation/template.htm
 * The above address bounces and no current valid address
 * can be found. This version has changes by Craig Cockburn
 * to accommodate top level domains .museum and .name
 * plus various other minor corrections and changes
 *
 * Italian translation by Giulio Chalda Bettega
*  http://blog.chalda.it/?p=11
 */

  function isValidEmailAddress(emailStr) {
        var emailPat = /^(.+)@(.+)$/;
        var specialChars = "\\(\\)<>@,;:\\\\\\\"\\.\\[\\]";
        var validChars = "[^\\s" + specialChars + "]";
        var quotedUser = "(\"[^\"]*\")";
        var ipDomainPat = /^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/;
        var atom = validChars + "+";
        var word = "(" + atom + "|" + quotedUser + ")";
        var userPat = new RegExp("^" + word + "(\\." + word + ")*$");
        var domainPat = new RegExp("^" + atom + "(\\." + atom + ")*$");
        var matchArray = emailStr.match(emailPat);
        if (matchArray == null) {
            //alert("L'email sembra essere sbagliata: (controlla @ e .)");
            return false;
        }
        var user = matchArray[1];
        var domain = matchArray[2];
        if (user.match(userPat) == null) {
            //alert("La parte dell'email prima di '@' non sembra essere valida!");
            return false;
        }
        var IPArray = domain.match(ipDomainPat);
        if (IPArray != null) {
            for (var i = 1; i <= 4; i++) {
                if (IPArray[i] > 255) {
                   // alert("L'IP di destinazione non è valido!");
                    return false;
                }
            }
            return true;
        }
        var domainArray = domain.match(domainPat);
        if (domainArray == null) {
           // alert("La parte dell'email dopo '@' non sembra essere valida!");
            return false;
        }
        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 > 6) {
            //alert("Il dominio di primo livello (es: .com e .it) non sembra essere valido!");
            return false;
        }
        if (len < 2) {
            var errStr = "Manca l'indirizzo del dominio!";
            //alert(errStr);
            return false;
        }
        return true;
    }
//  End -->

function validaCodiceFiscale(cf) {
	  var validi, i, s, set1, set2, setpari, setdisp;
	  if( cf == '' )  return '';
	  cf = cf.toUpperCase();
	  if( cf.length != 16 )
		  return false;
	  validi = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
	  for( i = 0; i < 16; i++ ){
		  if( validi.indexOf( cf.charAt(i) ) == -1 )
			  return false;
	  }
	  set1 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
	  set2 = "ABCDEFGHIJABCDEFGHIJKLMNOPQRSTUVWXYZ";
	  setpari = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
	  setdisp = "BAKPLCQDREVOSFTGUHMINJWZYX";
	  s = 0;
	  for( i = 1; i <= 13; i += 2 )
		  s += setpari.indexOf( set2.charAt( set1.indexOf( cf.charAt(i) )));
	  for( i = 0; i <= 14; i += 2 )
		  s += setdisp.indexOf( set2.charAt( set1.indexOf( cf.charAt(i) )));
	  if( s%26 != cf.charCodeAt(15)-'A'.charCodeAt(0) )
		  return false;
	  return true;
}	
	
	
	
	
	
	
	
