 $(document).ready(function(){
 
   $.datepicker.setDefaults({ changeYear: true, yearRange: '-80:0' }); 
   $("#arr_Fechamatriculacion").datepicker($.datepicker.regional['es']);   
   $("#arr_Fechainspeccion").datepicker($.datepicker.regional['es']);
   $("#arr_Fecharec").datepicker($.datepicker.regional['es']);
   $("#arr_Fechaent").datepicker($.datepicker.regional['es']);
   
   //$("#arr_fechamatriculacion").blur(function() { $("#arr_fechamatriculacion").val('pppp') }) ;  
   $("#arr_Fechamatriculacion").livequery('blur', function() {
      validarFechas();
   }); 
   
   $("#arr_Fechainspeccion").livequery('blur', function() {
      validarFechas();
   });
   
   /*$("#arr_Matricula").livequery('blur', function() {
      validarMatricula();
   });   */
   
   $("#arr_Horarec").livequery('change', function() {
      validarHora();
   });
   
   $("#arr_Horaent").livequery('change', function() {
      validarHora();
   });    
      
   $.validator.addMethod(
        'IsEmpty',          
        function(v) {                 
            return  ((v == null) || (v.length == 0));         
        },
             
        '' 
    );     
    
    $.validator.addMethod( 
        "letrasnum",          
        function(v) {                  
          return jQuery.validator.methods.IsEmpty(v) || /^[a-zA-Z0-9]+$/i.test(v);
          //alert(v);          
        },          
       "Ingresa solo letras y numeros." 
    );
    
    $.validator.addMethod( 
        "verbco",          
        function() {
          if (!jQuery.validator.methods.IsEmpty($("input[name^=bco]").val()) && /^[0-9]+$/i.test($("input[name^=bco]").val())) {        
            return true; 
          } else {
            $("input[name^=bco]").addClass("error");
            return false;
          }
         //})                           
        },          
       "Todos los campos con números." 
    );
    
    $.validator.addMethod( 
        "fecharec",          
        function() {
          frec = $('#arr_Fecharec').val();               
          hoy = new Date();
          frec = frec.split("/");
          frec_comp = new Date(parseInt(frec[2],10), parseInt(frec[1],10)-1, parseInt(frec[0],10));
          diffecha = frec_comp.getTime() - hoy.getTime();
          if (diffecha <= 172800000) {      //48hs antes
            $(this).val('');
            return false;
          } else {
            return true
          }                            
        },          
       "Esta fecha debe ser 48hs. antes." 
    ); 
    
    $.validator.addMethod( 
        "finderec",          
        function() {
          frec = $('#arr_Fecharec').val();               
          frec = frec.split("/");
          fecha_comp = new Date(parseInt(frec[2],10), parseInt(frec[1],10)-1, parseInt(frec[0],10));
          dia = fecha_comp.getDay();
          if (dia==0 || dia == 6) {      //48hs antes
            $(this).val('');
            return false;
          } else {
            return true
          }                            
        },          
       "El servicio es de lunes a viernes." 
    );
    
    $.validator.addMethod( 
        "findeent",          
        function() {
          frec = $('#arr_Fechaent').val();               
          frec = frec.split("/");
          fecha_comp = new Date(parseInt(frec[2],10), parseInt(frec[1],10)-1, parseInt(frec[0],10));
          dia = fecha_comp.getDay();
          if (dia==0 || dia == 6) {      //48hs antes
            $(this).val('');
            return false;
          } else {
            return true
          }                            
        },          
       "El servicio es de lunes a viernes." 
    ); 
    
    $.validator.addMethod( 
        "matricula",          
        function() {
          matricula = $("#arr_Matricula").val();
          strMatr="(^[a-z,A-Z]{1,2}[\-][0-9][0-9][0-9][0-9][\-][a-z,A-Z][a-z,A-Z]$)|(^[a-z,A-Z]{1,2}[0-9][0-9][0-9][0-9][a-z,A-Z][a-z,A-Z]$)|(^[0-9][0-9][0-9][0-9][a-z,A-Z][a-z,A-Z][a-z,A-Z]$)|(^[0-9][0-9][0-9][0-9][\-][a-z,A-Z][a-z,A-Z][a-z,A-Z]$)";
         // if( matricula.length < 7 ) {
         //   return false;
         // } else {   
            if (matricula.match(strMatr)==null) {
              //$("#arr_Matricula").val('');
              return false;
            } else {
              return true
            }
          //}                         
        },          
       "Esta matrícula no es válida." 
    );  
    
    var validator = $("#itv").validate({
        rules: {
          "arr[Idprovincia]": {
             required: true
          },
          "arr[Idciudad]": {
             required: true
          }
        }
     });   
     
    $("input").keypress(function() {
        $(".errorcaptcha").text('');
    });
    
    $("#arr_Idprovincia")     //Provincia 1
       .livequery('change', function() {
       var idProv = $(this).val();
       $("#selciudad").load("/ajax/ciudad", 'idprov='+idProv+'&obj=arr[Idciudad]' );       
    });
    
    $("#selciudad").load(function() {
       var idProv = $("#arr_Idprovincia").val();
       $(this).load("/ajax/ciudad", 'idprov='+idProv+'&obj=arr[Idciudad]' );       
    });
    
    $("input[name^=misma]").change(function() {
       $("#togl").toggle("slow");
    });
    
    if($("input[name^=misma]").val() == 1) {
      $("#togl").show("slow");
    };
 
 
 function validarFechas() {
   matric = $('#arr_Fechamatriculacion').val();
   inspec = $('#arr_Fechainspeccion').val();
    if (matric != "") {
      hoy1=new Date();
      fhmatric = new String(matric);
      fhmatric = fhmatric.split("/");
      fhmatricfinal = new Date(parseInt(fhmatric[2],10), parseInt(fhmatric[1],10)-1, parseInt(fhmatric[0],10));
      diffecha = hoy1.getTime() - fhmatricfinal.getTime();
      if (diffecha < 0) {
        alert ("La fecha de primera matriculación no puede ser mayor a la actual");
        $('#arr_Fechamatriculacion').val('');
        return false;
      }     
    }

    if (inspec != "") {
      fmatric = new String(matric);
      fmatric = fmatric.split("/");
      finspec = new String(inspec);
      finspec = finspec.split("/");
      fmatric = fmatric[1] + "/" + fmatric[0] + "/" + fmatric[2];
      finspec = finspec[1] + "/" + finspec[0] + "/" + finspec[2];       
      newfmatric = new Date(fmatric);
      newfinspec = new Date(finspec);       
      if (newfmatric > newfinspec) {
        alert("La fecha de última inspección no puede ser menor a la de matriculación")
        $('#arr_Fechainspeccion').val(''); 
        return false;
      }
    }
    return true;  
  };
  
 /* function validarMatricula() {
   matricula = $("#arr_Matricula").val();
   strMatr="(^[a-z,A-Z]{1,2}[\-][0-9][0-9][0-9][0-9][\-][a-z,A-Z][a-z,A-Z]$)|(^[a-z,A-Z]{1,2}[0-9][0-9][0-9][0-9][a-z,A-Z][a-z,A-Z]$)|(^[0-9][0-9][0-9][0-9][a-z,A-Z][a-z,A-Z][a-z,A-Z]$)|(^[0-9][0-9][0-9][0-9][\-][a-z,A-Z][a-z,A-Z][a-z,A-Z]$)";
   if (matricula.match(strMatr)==null) {
     alert('Esta matrícula no es válida, introduzca una matricula correcta');
     $("#arr_Matricula").val('');
   }
  }
  
  function validarFecharec() {
    frec = $('#arr_Fecharec').val();               
    hoy = new Date();
    frec = frec.split("/");
    frec_comp = new Date(parseInt(frec[2],10), parseInt(frec[1],10)-1, parseInt(frec[0],10));
    diffecha = frec_comp.getTime() - hoy.getTime();
    if (diffecha > 172800000) {      //48hs antes
      alert ("Solo podemos dar servicios solicitados 48hs antes.\n Por favor corrija la fecha");
      $('#arr_Fecharec').val('');
      return false;
    }
    //alert(diffecha);     
  }             */
  
  
  function validarHora () {    
    frec    = $('arr_Fecharec').val();
    fent    = $('arr_Fechaent').val();
    horarec = $('arr_Horarec').val();
    horaent = $('arr_Horaent').val();
    if (frec <= fent) {
      horarec = new String(hrec);
      horaent = new String(hent);
      horarec = horarec.split(":");
      horaent = horaent.split(":");
      hrecfinal=3600 * parseInt(horarec[0]) + 60 * parseInt(horarec[1]);
      hentfinal=3600 * parseInt(horaent[0]) + 60 * parseInt(horaent[1]);
      diff2 = hentfinal - hrecfinal;
      if (diff2 < 14400) {
        return true;
      }
    }
  }

     
  })

