function ValidaCIF(pFormulario)
{

  var v1 = new Array(0,2,4,6,8,1,3,5,7,9);
  var temp = 0;
  var temp1;

  if (
      (pFormulario.cif.value.length==0) && (pFormulario.dni.value.length==0)
     )
  {
          alert("Introduzca el DNI o el CIF.");
          return (false);
  }

  if (
      (pFormulario.cif.value.length>0) && (pFormulario.dni.value.length>0)
     )
  {
          alert("Introduzca el DNI o el CIF, pero no los dos.");
          return (false);
  }

  if (
      (pFormulario.cif.value.length==0) && (pFormulario.dni.value.length>0)
     )
     return (true);


  //en caso de tener sólo metido el CIF, lo verificamos
  var sCIF = pFormulario.cif.value.toUpperCase();
  pFormulario.cif.value=sCIF;

  var resul = false;
  var temp = sCIF; // pasar a mayúsculas

  if (!/^[A-Za-z0-9]{9}$/.test(temp)) // Son 9 dígitos?

    alert ("Longitud incorrecta, un CIF consta de 9 dígitos");

  else if (!/^[ABCDEFGHKLMNPQS]{1}[0-9]{7}[ABCDEFGHIJ0-9]{1}$/.test(temp)) // Es una letra de las admitidas ?

    alert("El formato del CIF es incorrecto.");

  else

    resul = true;

  //borramos la letra del NIF, que no se usa
  pFormulario.letra.value ="";

  return resul;
}


function calcularletraNIF (sDni)
{
        var cadena = 'TRWAGMYFPDXBNJZSQVHLCKET';
        var posicion = parseInt(sDni) % 23;
        return (cadena.charAt(posicion));
}


function DNIValido(pFormulario)
{
         //alert(pFormulario.dni.value.length + " " +parseInt(pFormulario.dni.value) + " " + pFormulario.cif.value.length);

         if ((pFormulario.dni.value.length)>0 && (pFormulario.cif.value.length)==0)
         {
                  if (
                      ((pFormulario.dni.value.length)==8) && (parseInt(pFormulario.dni.value)>0)
                     )
                  {
                       pFormulario.letra.value = calcularletraNIF(pFormulario.dni.value);
                       //alert(calcularletraNIF(pFormulario.dni.value));
                       return (true);
                  }
                  else
                  {
                           alert("Corrija el DNI introducido. Recuerde que sólo debe indicar NIF o CIF, pero no ambos.");
                           pFormulario.dni.focus();
                           return (false);
                  }
         }
         return (true);
}


function emailCheck (emailStr)
{
       /* Verificar si el email tiene el formato user@dominio. */
       var emailPat=/^(.+)@(.+)$/

       /* Verificar la existencia de caracteres. ( ) < > @ , ; : \ " . [ ] */
       var specialChars="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]"

       /* Verifica los caracteres que son válidos en una dirección de email */
       var validChars="\[^\\s" + specialChars + "\]"

       var quotedUser="(\"[^\"]*\")"

       /* Verifica si la dirección de email está representada con una dirección IP Válida */


       var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/


       /* Verificar caracteres inválidos */

       var atom=validChars + '+'
       var word="(" + atom + "|" + quotedUser + ")"
       var userPat=new RegExp("^" + word + "(\\." + word + ")*$")
       /* domain, as opposed to ipDomainPat, shown above. */
       var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$")


       var matchArray=emailStr.match(emailPat)
       if (matchArray==null) {
       alert("El email parece incorrecto. Compruebe la @ y los puntos.")
       return (false)
       }
       var user=matchArray[1]
       var domain=matchArray[2]

       // Si el user "user" es valido
       if (user.match(userPat)==null) {
       // Si no
       alert("El nombre de usuario no es válido.")
       return (false)
       }

       /* Si la dirección IP es válida */
       var IPArray=domain.match(ipDomainPat)
       if (IPArray!=null) {
       for (var i=1;i<=4;i++) {
       if (IPArray[i]>255) {
       alert("IP de destino inválida.")
       return (false)
       }
       }
       return true
       }

       var domainArray=domain.match(domainPat)
       if (domainArray==null) {
       alert("El dominio parece no ser válido.")
       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>3)
       {
       alert('La dirección debe tener 3 letras si es ."com" o 2 si es de algún país.')
       return (false);
       }

       if (len<2) {
       var errStr="La dirección es errónea."
       alert(errStr)
       return (false)
       }

       // La dirección de email ingresada es Válida
       return true;
}

function litrosValidos(pFormulario,aLitros,aDesc)
{
         var iSuma = 0;
         var i=0;
         for (i=0; i<3; i++)
         {
              iSuma +=aLitros[i];
              //alert(aDesc[i]+ ": " +aLitros[i]);
              if (!((aLitros[i]>=0) && (aLitros[i]<=30000)))
              {
                     alert("La cantidad de litros de " + aDesc[i] + " es errónea.");
                     switch (i)
                     {
                     case 1: pFormulario.gasoleo_a.focus(); break;
                     case 2: pFormulario.gasoleo_b.focus(); break;
                     case 3: pFormulario.gasoleo_c.focus(); break;
                     }
                     return (false);
              }
         }

         if (iSuma<=0)
         {
             alert("La cantidad total de litros de gasóleo ha de estar entre 0 y 30000.");
             pFormulario.gasoleo_a.focus();
             return (false);
         }

         return (true);
}

function fnDatosValidos(pFormulario)
{
         //nombre y/o empresa
         if ( (pFormulario.nombre.value=="" && pFormulario.empresa.value=="") ||
               (pFormulario.nombre.value=="" && pFormulario.empresa.value!="") )
         {
               alert("Revise su nombre y el de su empresa o comunidad.");
               pFormulario.nombre.focus();
               return (false);
         }

         if (!DNIValido(pFormulario))
         {
                 pFormulario.dni.focus();
                 return (false);
         }

         if (!ValidaCIF(pFormulario))
         {
                 pFormulario.cif.focus();
                 return (false);
         }

         if (!emailCheck(pFormulario.email.value))
         {
              pFormulario.email.focus();
              return (false);
         }

         if (pFormulario.tfno.value=="")
         {
             alert("Revise su teléfono.");
             pFormulario.tfno.focus();
             return (false);
         }

         //alert("1:" + pFormulario.gasoleo_a.value);

         var zLitros =new Array(pFormulario.gasoleo_a.value,pFormulario.gasoleo_b.value,pFormulario.gasoleo_c.value);
         var zDesc =new Array("gasóleo A","gasóleo B","gasóleo C");
         if (!litrosValidos(pFormulario,zLitros,zDesc))
         {
              //alert("2");
              return (false);
         }


         //window.alert("Fin de validación.");
         //return (false);
         return (true);
}
