// Comprueba la validez del formato del email
// Comrpueba la existencia de una "@" y un "." tras ésta.
// Retorna false si no detecta ninguno de los anteriores caracteres
function emailValido(valorFormulario) {
  var idx_at = valorFormulario.value.indexOf('@');
  if (idx_at == -1 || idx_at == 0) return false;
  var idx_dot = valorFormulario.value.indexOf('.', (idx_at + 2));
  if (idx_dot == -1 ) return false;
  return true;
}

// Retorna true en caso de que el objeto pasado sea nulo o esté vacío
function estaVacio(campo) {
  if ( campo.value <= 0 || campo.value.length==0 || campo.value==null ) {
	campo.focus();
	return true;
  }
  else return false;
}

// Comrpueba si el valor pasado es numérico
function esNumerico(theFormtxtNombre)
{
  valor = theFormtxtNombre.value;
  if (isNaN(valor))
  {       	      
    theFormtxtNombre.focus();
    return false;
  }
  return true;
}

// Comprueba que el teléfono introducido tenga 9 dígitos
function validarLongitudTelefono(theFormtxtNombre)
{
  if (theFormtxtNombre.value.length != 9) {
    theFormtxtNombre.focus();
    return false;
  }
  return true;
}

// Comprueba que el codigo postal introducido tenga 9 dígitos
function validarLongitudCPostal(theFormtxtNombre)
{
  if (theFormtxtNombre.value.length != 5) {
    theFormtxtNombre.focus();
    return false;
  }
  return true;
}



function validaNumerico(theFormtxtNombre)
{
  var checkOK = "0123456789";
  var checkStr = theFormtxtNombre.value;
  var allValid = true;
  for (i = 0;  i < checkStr.length;  i++)
  {
    ch = checkStr.charAt(i);
    for (j = 0;  j < checkOK.length;  j++)
      if (ch == checkOK.charAt(j))
        break;
    if (j == checkOK.length)
    {
      allValid = false;
      break;
    }
  }
  if (!allValid)
  {
    alert("Escriba únicamente caracteres NUMÉRICOS en el campo de texto.");
    theFormtxtNombre.focus();
    return (false);
  }
  return (true);
}

//******************************************************************
/*
/* Comprobación de la validez de una fecha mediante las funciones:
/* "validarFecha()". Dos funciones auxiliares "y2k()" y "esFecha()".
/*
*******************************************************************/
// Funciones auxiliares para el cálculo de la fecha
function y2k(numero) {return (numero<1000) ? numero+1900:numero;}

// El mes pasado debe estar entre 1 y 12 y el año en formato yyyyy
function esFecha (dia,mes,ano) {
  if (mes==0)
    return false;
  var hoy = new Date();
  ano = ((!ano) ? y2k(hoy.getYear()):ano);
  mes = ((!mes) ? hoy.getMonth():mes-1);
  if (!dia) 
    return false;
  var test = new Date(ano,mes,dia);
  if ( (y2k(test.getYear()) == ano) && (mes == test.getMonth()) && (dia == test.getDate()) )         
    return true;
  else
    return false;
}

// Comprueba si la fecha pasada es válida
function validarFecha(theFormtxtNombre)
{
  var checkOK = "0123456789/- \t\r\n\f";
  var checkStr = theFormtxtNombre.value;
  var allValid = true;
  for (i = 0;  i < checkStr.length;  i++)
  {
    ch = checkStr.charAt(i);
    for (j = 0;  j < checkOK.length;  j++)
      if (ch == checkOK.charAt(j))
        break;
    if (j == checkOK.length)
    {
      allValid = false;
      break;
    }
  }//fin del for (i = 0;  i < checkStr.length;  i++)

  if (!allValid)
  {
    alert("Por favor, escriba caracteres NUMÉRICOS, la barra / o el - para separar los dias de los meses y años. Gracias");
    theFormtxtNombre.focus();
    return (false);
  }//fin del if (!allValid)

  var x = theFormtxtNombre.value;
  theFormtxtNombre.value = (x.replace('-','/')).replace('-','/');

  var contador=0;

  for(i=0;i<theFormtxtNombre.value.length;i++)
  {
    if(theFormtxtNombre.value.charAt(i)=='/')
    {
      contador++;
    }
    if(theFormtxtNombre.value.charAt(i)==' ')
    {
      alert("Por favor, no escriba espacios en blanco en medio del campo de texto.");
      theFormtxtNombre.focus();
      return(false);
    }
  }//fin del 	for(i=0;i<theFormtxtNombre.value.length;i++)

  if (contador != 2)
  {
    alert("Debe introducir DOS barras separadoras para los meses y años /.");
    theFormtxtNombre.focus();
    return false;
  }

  var aux = theFormtxtNombre.value;
  var arraySplits = aux.split("/",3);
  var Dia = arraySplits[0];
  var Mes = arraySplits[1];
  var Ano = arraySplits[2];

  if ((arraySplits[0].length==1))
  {
    Dia='0'+Dia; 
  }
  if ((arraySplits[2].length==0))
  {
    alert('Debe introducir un año comprendido entre 2000 y 2300');
	return false;
  }

  if ((arraySplits[0].length > 2) || (arraySplits[1].length > 2) || (arraySplits[2].length > 4))
  {
    alert('Por favor, introduzca la fecha en el siguiente formato dd/mm/aaaa.');
    theFormtxtNombre.focus();
    return false;
  }
  if ((arraySplits[1].length==1))
  {
    Mes='0'+Mes; 
  }

  var intDia = parseInt(Dia,10);
  var intMes = parseInt(Mes,10);
  var intAnio = parseInt(Ano,10);
  
  if ((intDia>31) || (intDia<1))
  {
    alert('Introduzca un día que esté comprendido entre 1 y 31.');
    theFormtxtNombre.focus();
    return (false);
  }

  if ((intMes>12) || (intMes<1))
  {
    alert('Introduzca un mes que esté comprendido entre 1 y 12.');
    theFormtxtNombre.focus();
    return (false);
  }
    
  if ((intAnio<2000) || (intAnio>2300))
  {
    alert('Introduzca un año que esté comprendido entre el 2000 y el 2300.');
    theFormtxtNombre.focus();
    return (false); 
  }

  //compruebo que el formato de la fecha sea correcto
  if (esFecha(intDia,intMes,intAnio))
  {
    return (true);
  }
  else
  {
    alert('Debe introducir una fecha correcta. Gracias.');
    theFormtxtNombre.focus();
    return (false);
  }
  return true;
}//fin de la function validarFecha(theFormtxtNombre)

/******* Validacion de un numero flotante con un formato determinado *********/
// txtCampoFlotante: objeto
// total: número de carácteres
// decimales: número de decimales
function validarFloatRango(txtCampoFlotante,total,decimales)
{
  var valor = eval(txtCampoFlotante);
  if(valor.value !='' && valor.value!=' ')
  {
    var reempla = valor.value;
    reempla = reempla.replace(',','.');
    valor.value = reempla;
    if(isNaN(valor.value)==true)
    {
      alert('El valor introducido no es correcto.');
      valor.focus();
      valor.value='';
      return false;
    }
    var numero = parseFloat(valor.value);

    /* Compongo el número que quiero que sea el máximo */
    var entero = parseInt(Number(total) - Number(decimales));
    entero = Math.pow(10,entero) - 1;

    /*Genero el número decimal mas grande que puedo introducir*/
    var parteDecimal = (Math.pow(10,decimales)-1)/(Math.pow(10,decimales));
    entero =  entero + parteDecimal;

    if(numero<1 || numero>entero)
    {
      alert('El interés deber estar comprendido entre 1 y '+entero+'.');
      valor.focus();
      valor.value='';
      return false;
    }

    if(isNaN(numero)==true)
    {
      alert('Se produjo un error al pasar la cadena a decimal.');
      valor.focus();
      valor.value='';
      return false;

    }
  }// if blanco
  return true;
}


