//****** Utente insert signup.asp *******

function UtenteInsert(){

  if (UtenteInsertEditValidate('utenteadd'))
  {
    var d = new Date();
    var url = "/controller.asp?action=utente_insert";

    var pars = "nome=" + encodeURIComponent($('#utenteadd_nome').val()) + "&cognome=" + encodeURIComponent($('#utenteadd_cognome').val())
               + "&citta=" + encodeURIComponent($('#utenteadd_citta').val())
               + "&email=" + $('#utenteadd_email').val()
               + "&passwd=" + encodeURIComponent($('#utenteadd_passwd').val())
               + "&nickname=" + $('#utenteadd_nickname').val()
               + "&datanascita=" + $('#utenteadd_datanascita').val() + "&sesso=" + $('#utenteadd_sesso').val()
               + "&fumatore=" + $('#utenteadd_fumatore')[0].checked
               + "&occupazione_id=" + $('#utenteadd_occupazione').val() + "&titolostudio_id=" + $('#utenteadd_titolostudio').val()
               + "&musica=" + $('#utenteadd_musicapreferita').val() + "&squadra=" + $('#utenteadd_squadracalcio').val()
               + "&sportpraticato=" + $('#utenteadd_sportpraticati').val() + "&hobbies=" + $('#utenteadd_hobbies').val()
               + "&privacy=" + $('#utenteadd_privacy')[0].checked
               + "&ts=" + encodeURIComponent(d.getTime());

     $.ajax({
       type: "GET",
       url: url,
       data: pars,
       //Evento di riuscita
       success: function(ResponseText){
        var arr_response = ResponseText.split("|");

        if (arr_response[0]=="ko")
        {
          $.errorBox(arr_response[1])
        }

        if (arr_response[0]=="ok")
        {
          $('#add_form').hide('fast');
          $('#campi_obbligatori').hide('fast');
          $('#success').fadeIn();
        }

       }

     });

  }
}

//***************************************

//****** Messaggio insert (contatta utente) *******

function MessaggioInsert(){

  if (MessaggioInsertValidate())
  {
    $("img#indicator_popup").show();

    var d = new Date();
    var url = "/controller.asp?action=messaggio_insert";

    var frompercorso_id = "";
    if ($('#frompercorso_id').length > 0)
      frompercorso_id = encodeURIComponent($('#frompercorso_id').val());

    var pars = "topercorso_id=" + encodeURIComponent($('#topercorso_id').val()) + "&toutente_id=" + encodeURIComponent($('#toutente_id').val())
               + "&frompercorso_id=" + frompercorso_id
               + "&testo=" + $('#testo_contattautente').val()
               + "&ts=" + encodeURIComponent(d.getTime());

     $.ajax({
       type: "GET",
       url: url,
       data: pars,
       //Evento di riuscita
       success: function(ResponseText){
        $("img#indicator_popup").fadeOut('fast');
        var arr_response = ResponseText.split("|");

        if (arr_response[0]=="ko")
        {
          $.errorBox(arr_response[1])
        }

        if (arr_response[0]=="ok")
        {
          $('#divcontatta').hide('fast');
          $('#success_contattautente').fadeIn();
        }

       }

     });

  }
}

//***************************************


//****** Messaggio insert (contatta utente) *******

function FeedBackInsert(toutente_id){

  if (FeedBackInsertValidate(toutente_id))
  {
    var d = new Date();
    var url = "/controller.asp?action=feedback_insert";

    var pars = "toutente_id=" + toutente_id
               + "&positivo=" + encodeURIComponent($("input[@name='feedbackadd_positivo_" + toutente_id + "']:checked").val())
               + "&affidabile=" + encodeURIComponent( $("input[@name='feedbackadd_affidabilita_" + toutente_id + "']").val() )
               + "&puntuale=" + encodeURIComponent( $("input[@name='feedbackadd_puntualita_" + toutente_id + "']").val() )
               + "&note=" + encodeURIComponent($('#feedbackadd_note_' + toutente_id).val())
               + "&ts=" + encodeURIComponent(d.getTime());

     $.ajax({
       type: "GET",
       url: url,
       data: pars,
       //Evento di riuscita
       success: function(ResponseText){
        var arr_response = ResponseText.split("|");

        if (arr_response[0]=="ko")
        {
          $.errorBox(arr_response[1])
        }

        if (arr_response[0]=="ok")
        {
          $('#feedbackadd_' + toutente_id).hide('fast');
          $('#success_feedback_' + toutente_id).fadeIn();
        }

       }

     });

  }

}

//***************************************

//********* Percorso Insert Light *******
function PercorsoInsertLight(){

  if (PercorsoInsertLightValidate())
  {
    $("img#indicator_popup").show();
    
    var d = new Date();
    var url = "/controller.asp?action=percorso_insert_light";

    var pars = "cittapartenza=" + encodeURIComponent($('#cittapartenza').val())
               + "&indirizzopartenza=" + encodeURIComponent($('#indirizzopartenza').val())
               + "&latpartenza=" + encodeURIComponent( $("#latpartenza").val() ) + "&lngpartenza=" + encodeURIComponent( $("#lngpartenza").val() )
               + "&cittaarrivo=" + encodeURIComponent($('#cittaarrivo').val())
               + "&indirizzoarrivo=" + encodeURIComponent($('#indirizzoarrivo').val())
               + "&latarrivo=" + encodeURIComponent( $("#latarrivo").val() ) + "&lngarrivo=" + encodeURIComponent( $("#lngarrivo").val() )
               + "&ruoloutente=" + encodeURIComponent($("input[@name='ruoloutente']:checked").val())
               + "&nickname=" + encodeURIComponent( $("#addlight_nickname").val() ) + "&email=" + encodeURIComponent( $("#addlight_email").val() )
               + "&ritorno=" + $("input[@name='addlight_ritorno']:checked").val()
               + "&utente_id=" + encodeURIComponent($("#addlight_utente_id").val());
               + "&ts=" + encodeURIComponent(d.getTime());

     $.ajax({
       type: "GET",
       url: url,
       data: pars,
       //Evento di riuscita
       success: function(ResponseText){
        $("img#indicator_popup").fadeOut('fast');
        var arr_response = ResponseText.split("|");

        if (arr_response[0]=="ko")
        {
          $.errorBox(arr_response[1])
        }

        if (arr_response[0]=="ok")
        {
          $('#viaggioadd').hide();
          $('#success_viaggioadd').fadeIn();
        }

       }

     });

  }

}

//***************************************

//******* Login utente **********
	function UtenteLogin()
	{

	  if (LoginValidate())
	  {
        var d = new Date();
        var url = "/controller.asp?action=utente_login";
        var pars = "username=" + document.getElementById('login_email').value + "&password=" + encodeURIComponent(document.getElementById('login_passwd').value) + "&ts=" + encodeURIComponent(d.getTime());

       $.ajax({
         type: "GET",
         url: url,
         data: pars,
         //Evento di riuscita
         success: function(ResponseText){
          var arr_response = ResponseText.split("|");
          if(arr_response[0]=="ko") {
            $.errorBox(arr_response[1]);
          }
          if(arr_response[0]=="ok") {
            $('#loginform').hide();
            document.location.href='/userrides';
          }
         }
       });

     }

	}

//***********************************

//******* Login utente inline (con callback) **********
	function UtenteLoginInLine(callback)
	{

	  if (LoginInLineValidate())
	  {
        var d = new Date();
        var url = "/controller.asp?action=utente_login";
        var pars = "username=" + $("#logininline_email").val() + "&password=" + encodeURIComponent($("#logininline_passwd").val()) + "&ts=" + encodeURIComponent(d.getTime());

       $.ajax({
         type: "GET",
         url: url,
         data: pars,
         //Evento di riuscita
         success: function(ResponseText){
          var arr_response = ResponseText.split("|");
          if(arr_response[0]=="ko") {
            $.errorBox(arr_response[1]);
          }
          if(arr_response[0]=="ok") {
            eval(callback);
          }
         }
       });

     }

	}

//***********************************


//******* Reinvia Attivazione utente **********
	function Reinvia_Attivazione()
	{
	  if (document.getElementById('login_email').value!="")
	  {
        var d = new Date();
        var url = "/controller.asp?action=reinvia_attivazione";
        var pars = "email=" + document.getElementById('login_email').value + "&ts=" + encodeURIComponent(d.getTime());

       $.ajax({
         type: "GET",
         url: url,
         data: pars,
         //Evento di riuscita
         success: function(ResponseText){
          var arr_response = ResponseText.split("|");
          if(arr_response[0]=="ko") {
            $.errorBox(arr_response[1]);
          }
          if(arr_response[0]=="ok") {
            $.successBox(arr_response[1]);
          }
         }
       });
     }
	}

//***********************************

//******* Ricorda password **********

	function InviaPassword()
	{
    $("#messageko").hide();
    $("#messageok").hide();
    $("img#indicator_popup").show();
    var d = new Date();
    var url = "/controller.asp?action=ricorda_password";
    var pars = "email=" + document.getElementById('utente_email').value + "&ts=" + encodeURIComponent(d.getTime());

   $.ajax({
     type: "GET",
     url: url,
     data: pars,
     //Evento di riuscita
     success: function(ResponseText){
      $("img#indicator_popup").fadeOut('fast');
      if(ResponseText=="ko") {
        $("#messageko").fadeIn('slow');
      }
      if(ResponseText=="ok") {
        $("#messageok").fadeIn('slow');
      }
     }
   });

	}

//***********************************

//******* Richiesta Passaggio **********

	function InviaRichiestaPassaggio()
	{
	  if (RichiestaPassaggioValidate())
	  {
      $("#messageko").hide();
      $("#messageok").hide();
      $("img#indicator_popup").show();
      var d = new Date();
      var url = "/controller.asp?action=richiesta_passaggio";

      var frompercorso_id = "";
      if ($('#frompercorso_id').length > 0)
        frompercorso_id = encodeURIComponent($('#frompercorso_id').val());

      var pars = "testo=" + $("#richiestapassaggio_testo").val() +
                 "&frompercorso_id=" + frompercorso_id +
                 "&toutente_id=" + encodeURIComponent($("#toutente_id").val()) +
                 "&topercorso_id=" + encodeURIComponent($("#topercorso_id").val()) +
                 "&ts=" + encodeURIComponent(d.getTime());

      $.ajax({
       type: "GET",
       url: url,
       data: pars,
       //Evento di riuscita
       success: function(ResponseText){
        $("img#indicator_popup").fadeOut('fast');
        if(ResponseText=="ko") {
          $("#messageko").fadeIn('slow');
        }
        if(ResponseText=="ok") {
          $("#richiesta_passaggio").hide();
          $("#messageok").fadeIn('slow');
        }
       }
      });
    }

	}

//***********************************

//******* Utente cambia password **********
	function Utente_ChangePassword()
	{

	  if (ChangePasswordValidate())
	  {
        var d = new Date();
        var url = "/controller.asp?action=utente_cambiopassword";
        var pars = "vecchiapassword=" + encodeURIComponent($('#utente_vecchiapassword').val()) + "&nuovapassword=" + encodeURIComponent($('#utente_nuovapassword').val()) + "&ts=" + encodeURIComponent(d.getTime());

       $.ajax({
         type: "GET",
         url: url,
         data: pars,
         //Evento di riuscita
         success: function(ResponseText){

          var arr_response = ResponseText.split("|");

          if(arr_response[0]=="ko") {
            $.errorBox(arr_response[1]);
          }
          if(arr_response[0]=="ok") {
            $('#modifica_password').hide();
            $('#success').fadeIn();
          }

         }
       });

     }

	}

//***********************************

//******* Verifica Utente loggato **********

	function Utente_Loggato()
	{
    var d = new Date();
    var url = "/controller.asp?action=utente_loggato";
    return $.ajax({type: "GET", url: url, async: false}).responseText;
	}

//**********************************

//****** Richiesta Contatto *******

function RichiestaContatto(){

	  if (ValidaModuloContatto())
	  {
      var d = new Date();
      var url = "/controller.asp?action=richiesta_contatto";
      var pars = "nome=" + encodeURIComponent($('#help_nome').val()) +
                 "&cognome=" + encodeURIComponent($('#help_cognome').val()) +
                 "&telefono=" + encodeURIComponent($('#help_telefono').val()) +
                 "&email=" + $('#help_email').val() +
                 "&richiesta=" + encodeURIComponent($('#help_richiesta').val()) +
                 "&codicecaptcha=" + $('#help_codicecaptcha').val() + "&ts=" + encodeURIComponent(d.getTime());

       $.ajax({
         type: "GET",
         url: url,
         data: pars,
         //Evento di riuscita
         success: function(ResponseText){
          var arr_response = ResponseText.split("|");
          if (arr_response[0]=="ko") {
            $.errorBox(arr_response[1])
            $('#help_codicecaptcha').val('');
            $('#captcha').attr("src","/inc/aspcaptcha.asp?ts=" + encodeURIComponent(d.getTime()));
          }
          else {
            $("#modulo_richiesta").hide();
            $.successBox(arr_response[1]);
          }
         }
       });
     }

}

//***********************************************



// *************** utility function **********************

function getData(addyear)
{
  //prende in ingresso un parametro che viene sommato all'anno della data di sistema
  //se passato zero restituisce la data di sistema nel formato italiano
  var d = new Date();
  var giorno = ((d.getDate()<10) ? "0" : "") + d.getDate();
  var mese   = ( ((d.getMonth()+1)<10) ? "0" : "" ) + ( d.getMonth() + 1 );
  var anno   = ( d.getFullYear() + addyear );

  return(giorno + "/" + mese + "/" + anno);
}

function trim(str) {
  return str.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
}

function ReloadPage() {
  var d = new Date();
  self.location.reload(true);
}

function LoginInLineMessaggio() {
  $('#loginform').hide();
  $('#menuutente').show();

  $('#boxutente').css('width','350px');
  $('#boxutente').css('text-align','center');
  $('#boxutente_content').load('/inc/boxutente.asp?load=true');

  jQuery(document).trigger('close.facebox');
  $('#divcontatta').slideToggle();
}


function LoginInLinePassaggio(percorso_id) {
  $('#loginform').hide();
  $('#menuutente').show();

  $('#boxutente').css('width','350px');
  $('#boxutente').css('text-align','center');
  $('#boxutente_content').load('/inc/boxutente.asp?load=true');

  var url = "/inc/richiedipassaggio.asp?percorso_id=" + percorso_id;
  $('div#facebox div.content').load(url);

}

function RimuoviClassMenu(listelements, classname)
{
  for (i=0;i<=listelements.length;i++)
  {
    $("#" + listelements[i]).removeClass(classname);
  }

}

function AttivaClassMenu(elementid, classname)
{
  $('#' + elementid).addClass(classname);
}

// ***************    Funzioni di validazione form   **********

function PercorsoInsertValidate(){

  $("#percorsoadd_cittapartenza_suggest").removeClass("suggested_rosso");
  $("#percorsoadd_cittaarrivo_suggest").removeClass("suggested_rosso");
  $("#percorsoadd_periodoinizio").removeClass("sfondo_rosso");
  $("#percorsoadd_orapartenza").removeClass("sfondo_rosso");
  $("#percorsoadd_oraarrivo").removeClass("sfondo_rosso");


  if ($("#percorsoadd_cittapartenza").val() == "" || $("#percorsoadd_cittapartenza").val() == "null")
  {
    $.errorBox('Citt&agrave; partenza obbligatorio');
    $("#percorsoadd_cittapartenza_suggest").addClass("suggested_rosso");
    return (false);
  }

  if ($("#percorsoadd_cittaarrivo").val() == "" || $("#percorsoadd_cittaarrivo").val() == "null")
  {
    $.errorBox('Citt&agrave; arrivo obbligatorio');
    $("#percorsoadd_cittaarrivo_suggest").addClass("suggested_rosso");
    return (false);
  }

  if ($("#percorsoadd_periodoinizio").val() == "")
  {
    $.errorBox('Periodo validit&agrave;  obbligatorio');
    $("#percorsoadd_periodoinizio").focus();
    $("#percorsoadd_periodoinizio").addClass("sfondo_rosso");
    return (false);
  }

  if ($('#percorsoadd_orapartenza option:selected').text()=='' )
  {
    $.errorBox('Ora Partenza obbligatoria');
    $("#percorsoadd_orapartenza").addClass("sfondo_rosso");
    return (false);
  }

  if ($('#percorsoadd_oraarrivo option:selected').text()=='' )
  {
    $.errorBox('Ora Arrivo obbligatoria');
    $("#percorsoadd_oraarrivo").addClass("sfondo_rosso");
    return (false);
  }

  if (!$("input[@name='percorsoadd_ruoloutente']:checked").val())
  {
    $.errorBox('Specificare se guidatore, passeggero o emtrambi');
    return (false);
  }

  if ($("input[@name='percorsoadd_ritorno']:checked").val()=='si')
  {
      if ($('#percorsoadd_ritorno_orapartenza option:selected').text()=='' )
      {
        $.errorBox('Ora Partenza obbligatoria per il viaggio di ritorno');
        $("#percorsoadd_ritorno_orapartenza").addClass("sfondo_rosso");
        return (false);
      }

      if ($('#percorsoadd_ritorno_oraarrivo option:selected').text()=='' )
      {
        $.errorBox('Ora Arrivo obbligatoria per il viaggio di ritorno');
        $("#percorsoadd_ritorno_oraarrivo").addClass("sfondo_rosso");
        return (false);
      }
  }

  return (true);
}


function PercorsoInsertLightValidate(){

  if ($("#addlight_utente_id").length==0) //controllo se loggato
  {
    if ($("#addlight_nickname").val() == "")
    {
      $.errorBox('Nickname obbligatorio');
      $("#addlight_nickname").focus();
      $("#addlight_nickname").addClass("sfondo_rosso");
      return (false);
    }
  
    if ($("#addlight_email").length)
    {
      if ($("#addlight_email").val() == "")
      {
        $.errorBox('E-mail obbligatorio');
        $("#addlight_email").focus();
        $("#addlight_email").addClass("sfondo_rosso");
        return (false);
      }
      else
      {
      	Filtro = /^[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]@[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$/;
  
      	if (!Filtro.test($("#addlight_email").val()))
        {
        $.errorBox('Formato E-mail non valido');
        $("#addlight_email").focus();
        $("#addlight_email").addClass("sfondo_rosso");
        return false;
        }
        else
        {
  
      		if ( $("#addlight_confermaemail").val() != $("#addlight_email").val() )
          {
      		  $.errorBox("E-mail e Conferma E-mail non corrispondono");
      		  $("#addlight_confermaemail").val("");
      		  $("#addlight_confermaemail").addClass("sfondo_rosso");
      		  $("#addlight_confermaemail").focus();
      		  return false;
          }
  
        }
  
      }
    }
  
    if (!$("#addlight_privacy").is(":checked"))
    {
      $.errorBox("Dare il consenso al trattamento dei dati personali");
      return (false);
    }
  }

  return (true);
}


function MessaggioInsertValidate(){

	if ($("#testo_contattautente").val() == "")
  {
    $.errorBox('Testo messaggio obbligatorio');
    $("#testo_contattautente").focus();
    $("#testo_contattautente").addClass("sfondo_rosso");
    return (false);
  }

  return (true);

}

function FeedBackInsertValidate(toutenteid){

	if (! $("input[name='feedbackadd_positivo_" + toutenteid + "']").is(":checked") )
  {
    $.errorBox('Feedback obbligatorio');
    return (false);
  }

  return (true);

}

function LoginValidate(){

  $("#login_email").removeClass("sfondo_rosso");
  $("#login_passwd").removeClass("sfondo_rosso");

  if ($("#login_email").val() == "")
  {
    $.errorBox('E-mail obbligatorio');
    $("#login_email").focus();
    $("#login_email").addClass("sfondo_rosso");
    return (false);
  }
  else
  {
  	Filtro = /^[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]@[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$/;

		if (!Filtro.test($("#login_email").val()))
	  {
	  $.errorBox('Formato E-mail non valido');
	  $("#login_email").focus();
	  $("#login_email").addClass("sfondo_rosso");
	  return false;
	  }
  }

  if ($("#login_passwd").val() == "")
  {
    $.errorBox('Password obbligatorio');
    $("#login_passwd").focus();
    $("#login_passwd").addClass("sfondo_rosso");
    return (false);
  }

  return (true);
}

function LoginInLineValidate(){

	$("#msg_error").remove();
  $("#logininline_email").removeClass("sfondo_rosso");
  $("#logininline_passwd").removeClass("sfondo_rosso");

  if ($("#logininline_email").val() == "")
  {
    $("#msg_error").remove();
    $("#logininline_email").after('<div id="msg_error" class="error_msg">E-mail obbligatorio</div>');
    $("#logininline_email").focus();
    $("#logininline_email").addClass("sfondo_rosso");
    return (false);
  }
  else
  {
  	Filtro = /^[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]@[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$/;

		if (!Filtro.test($("#logininline_email").val()))
	  {
	  $("#msg_error").remove();
	  $("#logininline_email").after('<div id="msg_error" class="error_msg">Formato e-mail non valido</div>');
	  $("#logininline_email").focus();
	  $("#logininline_email").addClass("sfondo_rosso");
	  return false;
	  }
  }

  if ($("#logininline_passwd").val() == "")
  {
    $("#msg_error").remove();
	  $("#logininline_passwd").after('<div id="msg_error" class="error_msg">Password obbligatorio</div>');
    $("#logininline_passwd").focus();
    $("#logininline_passwd").addClass("sfondo_rosso");
    return (false);
  }

  return (true);
}

function RichiestaPassaggioValidate(){

	$("#msg_error").remove();
  $("#logininline_email").removeClass("sfondo_rosso");
  $("#logininline_passwd").removeClass("sfondo_rosso");

  if ($("#richiestapassaggio_testo").val() == "")
  {
    $("#msg_error").remove();
	  $("#richiestapassaggio_testo").after('<div id="msg_error" class="error_msg">Testo obbligatorio</div>');
    $("#richiestapassaggio_testo").focus();
    $("#richiestapassaggio_testo").addClass("sfondo_rosso");
    return (false);
  }

  return (true);
}

function UtenteInsertEditValidate(prefix)
{

  if ($("#" + prefix + "_nome").val() == "")
  {
    $.errorBox('Nome obbligatorio');
    $("#" + prefix + "_nome").focus();
    $("#" + prefix + "_nome").addClass("sfondo_rosso");
    return (false);
  }

  if ($("#" + prefix + "_cognome").val() == "")
  {
    $.errorBox('Cognome obbligatorio');
    $("#" + prefix + "_cognome").focus();
    $("#" + prefix + "_cognome").addClass("sfondo_rosso");
    return (false);
  }

  if ($("#" + prefix + "_citta").val() == "")
  {
    $.errorBox('Citt&agrave; obbligatoria');
    $("#" + prefix + "_citta").focus();
    $("#" + prefix + "_citta").addClass("sfondo_rosso");
    return (false);
  }

  if ($("#" + prefix + "_email").length)
  {
    if ($("#" + prefix + "_email").val() == "")
    {
      $.errorBox('E-mail obbligatorio');
      $("#" + prefix + "_email").focus();
      $("#" + prefix + "_email").addClass("sfondo_rosso");
      return (false);
    }
    else
    {
    	Filtro = /^[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]@[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$/;

    	if (!Filtro.test($("#" + prefix + "_email").val()))
      {
      $.errorBox('Formato E-mail non valido');
      $("#" + prefix + "_email").focus();
      $("#" + prefix + "_email").addClass("sfondo_rosso");
      return false;
      }
      else
      {

    		if ( $("#" + prefix + "_confermaemail").val() != $("#" + prefix + "_email").val() )
        {
    		  $.errorBox("E-mail e Conferma E-mail non corrispondono");
    		  $("#" + prefix + "_confermaemail").val("");
    		  $("#" + prefix + "_confermaemail").addClass("sfondo_rosso");
    		  $("#" + prefix + "_confermaemail").focus();
    		  return false;
        }

      }

    }
  }

  if ($("#" + prefix + "_passwd").length)
  {
    if ( $("#" + prefix + "_passwd").val() == "" || $("#" + prefix + "_passwd").val().length < 8 )
    {
      $.errorBox('Password obbligatorio. Inserire minimo 8 caratteri');
      $("#" + prefix + "_passwd").focus();
      $("#" + prefix + "_passwd").addClass("sfondo_rosso");
      return (false);
    }

		if ( $("#" + prefix + "_confermapasswd").val() != $("#" + prefix + "_passwd").val() )
    {
		  $.errorBox("Password e Conferma Password non corrispondono");
		  $("#" + prefix + "_confermapasswd").val("");
		  $("#" + prefix + "_confermapasswd").addClass("sfondo_rosso");
		  $("#" + prefix + "_confermapasswd").focus();
		  return false;
	  }

  }

  if ($("#" + prefix + "_nickname").val() == "")
  {
    $.errorBox('Nickname obbligatorio');
    $("#" + prefix + "_nickname").focus();
    $("#" + prefix + "_nickname").addClass("sfondo_rosso");
    return (false);
  }

  if ($("#" + prefix + "_sesso").val() == "")
  {
    $.errorBox('Sesso obbligatorio');
    $("#" + prefix + "_sesso").focus();
    $("#" + prefix + "_sesso").addClass("sfondo_rosso");
    return (false);
  }

  if ($("#" + prefix + "_datanascita").val() == "")
  {
    $.errorBox('Data di nascita obbligatoria');
    $("#" + prefix + "_datanascita").focus();
    $("#" + prefix + "_datanascita").addClass("sfondo_rosso");
    return (false);
  }
  else {
    if (!isDate($("#" + prefix + "_datanascita").val())) {
      $.errorBox('Formato Data di nascita non valido');
      $("#" + prefix + "_datanascita").focus();
      $("#" + prefix + "_datanascita").addClass("sfondo_rosso");
      return (false);
    }
  }

  if (prefix=="utenteadd") {
    if (!$("#" + prefix + "_privacy").is(":checked"))
    {
      $.errorBox("Dare il consenso al trattamento dei dati personali");
      return (false);
    }
  }

  return (true);

}

function ChangePasswordValidate()
{

  if ($("#utente_vecchiapassword").val() == "")
  {
    $.errorBox('Vecchia Password obbligatorio');
    $("#utente_vecchiapassword").focus();
    $("#utente_vecchiapassword").addClass("sfondo_rosso");
    return (false);
  }

  if ($("#utente_nuovapassword").length)
  {
    if ($("#utente_nuovapassword").val() == "" || $("#utente_nuovapassword").val().length < 8)
    {
      $.errorBox('Nuova Password obbligatorio. Inserire minimo 8 caratteri');
      $("#utente_nuovapassword").focus();
      $("#utente_nuovapassword").addClass("sfondo_rosso");
      return (false);
    }

		if ( $('#utente_nuovapassword').val() != $('#utente_ripetinuovapassword').val() )
    {
		  $.errorBox("Nuova Password e Conferma Nuova Password non corrispondono");
		  $('#utente_ripetinuovapassword').val("");
		  $('#utente_ripetinuovapassword').addClass("sfondo_rosso");
		  $('#utente_ripetinuovapassword').focus();
		  return false;
	  }

  }

  return (true);

}


function ValidaModuloContatto(theForm){

    if ($('#help_email').val() == "")
    {
      $.errorBox("Inserire un valore per il campo E-mail");
      $('#help_email').focus();
      $("#help_email").addClass("sfondo_rosso");
      return (false);
    }
    else
    {
    	Filtro = /^[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]@[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$/;

  		if (!Filtro.test($('#help_email').val()))
  	  {
  	  $.errorBox("Formato E-mail non valido");
  	  $('#help_email').focus();
  	  $("#help_email").addClass("sfondo_rosso");
  	  return false;
  	  }
    }

    if ($('#help_richiesta').val() == "")
    {
      $.errorBox("Inserire un valore per il campo Richiesta");
      $('#help_richiesta').focus();
      $("#help_richiesta").addClass("sfondo_rosso");
      return (false);
    }

    if ($('#help_codicecaptcha').val() == "")
    {
      $.errorBox("Inserire il codice di verifica visualizzato");
      $('#help_codicecaptcha').focus();
      $("#help_codicecaptcha").addClass("sfondo_rosso");
      return (false);
    }

    if (!$('#help_privacy').is(":checked"))
    {
      $.errorBox("Dare il consenso al trattamento dei dati personali");
      return (false);
    }

  return (true);
}


function isInteger(s){
	var i;
    for (i = 0; i < s.length; i++){
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    return true;
}

function stripCharsInBag(s, bag){
	var i;
    var returnString = "";
    for (i = 0; i < s.length; i++){
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

function daysInFebruary (year){
   	// February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}
function DaysArray(n) {
	for (var i = 1; i <= n; i++) {
		this[i] = 31
		if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
		if (i==2) {this[i] = 29}
   }
   return this
}

function isDate(dtStr){
  var dtCh= "/";
  var minYear=1900;
  var maxYear=2100;

	var daysInMonth = DaysArray(12)
	var pos1=dtStr.indexOf(dtCh)
	var pos2=dtStr.indexOf(dtCh,pos1+1)
	var strDay=dtStr.substring(0,pos1)
	var strMonth=dtStr.substring(pos1+1,pos2)
	var strYear=dtStr.substring(pos2+1)
	strYr=strYear
	if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1)
	if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1)
	for (var i = 1; i <= 3; i++) {
		if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1)
	}
	month=parseInt(strMonth)
	day=parseInt(strDay)
	year=parseInt(strYr)
	if (pos1==-1 || pos2==-1){
		return false
	}
	if (strMonth.length<1 || month<1 || month>12){
		return false
	}
	if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
		return false
	}
	if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
		return false
	}
	if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
		return false
	}
return true
}



function PosInArray(arr,valore) {

  for (var i = 0; i < arr.length; i++) {
    if ( arr[i]==valore ) {
      return(i);
    }
  }
  return(-1);

}

function LuogoEsistente(arr,valore) {

  for (var i = 0; i < arr.length; i++) {

	  var luogo = arr[i].toLowerCase();

    valore = trim(valore.toLowerCase());

    if ( luogo.substring(0,valore.length) == valore ) {
      return(i);
    }
  }
  return(-1);

}


// *************** Fine Funzioni di validazione form **********






// ***************  Generic error and success faceboxes ***********************

$.errorBox = function(text) {
  $.facebox('<h2 class="title icon_warning">Attenzione</h2>' + text)
}

$.successBox = function(text) {
  $.facebox('<h2 class="title icon_check">Complimenti</h2>' + text)
}

$.yesnoBox = function(title,text,yesaction) {
  $.facebox("<p style='padding:2px;font-size:1.2em;font-weight:bold;color:#8EB445;'>" + title + "</p><p style='padding:2px;'>" + text + "</p><p align='center' style='margin:10px'><a href='#' onClick=document.location.href='" + yesaction + "'><img class='png' width='85' height='33' src='/img/button/btn_conferma.png'></a>&nbsp;<a href='#' onClick='$.facebox.close();return(false);' class='annulla'>Annulla</a></p>")
}

$.confirmdeleteBox = function(title,text,confirmaction) {
  $.facebox("<p style='padding:2px;font-size:1.2em;font-weight:bold;color:#8EB445;'>" + title + "</p><p style='padding:2px;'>" + text + "</p><p align='center' style='margin:10px'><a href='#' onClick=document.location.href='" + confirmaction + "'><img class='png' width='66' height='33' src='/img/button/btn_elimina.png'></a>&nbsp;<a href='#' onClick='$.facebox.close();return(false);' class='annulla'>Annulla</a></p>")
}