// AUTOR: Enric Cappellani
// Modificado ligeramente por Daniel Rodriguez
// Adaptado a .js Raúl Ivorra
// Modificado por Lázaro S.M.

// Variables Globales
var swOK=0;
var nEle=0;
var sError='';

// valida EL FORMULARIO
//===================================
function valida(nelementos) 
{
  var nTot=0;
  var nPas=0;
  var nTorna=0;  
  var sNom;
  var sOne;
  var sTwo;
  sError="Lista de errores:"+"";
  
  for (var j=0; j<nelementos; j++)
  {
    nEle=j;

    // AVERIGUA LOS TIPOS
    sNom = document.forms[0].elements[j].name;
	if (sNom != null) {
		sOne = sNom.substring(0,1);
		sTwo = sNom.substring(1,2);
	
		// CORREO OBLIGATORIO
		if (sOne=='e' && sTwo=='r') 
		{
		   CaracterNoValid(document.forms[0].elements[j].value,'Er');
		   nTot+=swOK;
		}
		else
		   if (sOne=='e' && document.forms[0].elements[nEle].value!='') 
		   {
			   CaracterNoValid(document.forms[0].elements[j].value,'Eo');
			   nTot+=swOK;
		   }
	
	
		// NUMERICO Y OBLIGATORIO else NUMERICO NO OBLIGATORIO PERO INFORMADO
		if (sOne=='n' && sTwo=='r') 
		{
		   CaracterNoValid(document.forms[0].elements[j].value,'Nr');
		   nTot+=swOK;
		}
		else
		   if (sOne=='n' && document.forms[0].elements[nEle].value!='') 
		   {
			   CaracterNoValid(document.forms[0].elements[j].value,'No');
			   nTot+=swOK;
		   }
	
	
		//numero de tarjeta y obligatirio
		if (sOne=='t' && sTwo=='r')
		{
		   CaracterNoValid(document.forms[0].elements[j].value,'Tr');
		   nTot+=swOK;
		}
		else
		   if (sOne=='t' && document.forms[0].elements[nEle].value!='') 
		   {
			   CaracterNoValid(document.forms[0].elements[j].value,'To');
			   nTot+=swOK;
		   }
		// CADENA Y OBLIGATORIA
		if (sOne=='s' && sTwo=='r') 
		{
		   CaracterNoValid(document.forms[0].elements[j].value,'Sr');
		   nTot+=swOK;
		}
		// LISTA DE ERRORES
		if (nPas==0 && nTot>0) 
		{
		  document.forms[0].elements[nEle].focus();
		  nPas=1;
		}
	}//Fin If
	
  } // Fin For

  if (nTot>0)
    {
		alert(sError);
	}
  else
    {
		document.forms[0].submit();
	}
}

// ANALIZA CAMPO A CAMPO SI SON NUMERICOS
//=========================================
function CaracterNoValid(pCaracter,pType)
{
	swOK=0;
	// E-MAIL OBLIGATORIO
	if (pType=='Er') 
	{
 		swOK=2;
 		for (var i=0;i<pCaracter.length;i++)
 		{
			var sByte=pCaracter.substring(i,i+1);
 			if (sByte=="@" || sByte==".") 
 			{
 				swOK=swOK-1;
 			}
		}
	}
	if (swOK>0)
	{
		sError+=" Campo "+ document.forms[0].elements[nEle].name.substr(2)+ " ha de ser e-mail y es obligatorio" +".";
		return;
 	}

  	// NUMERICO OBLIGATORIO
  	if (pType=='Nr')
	{
    	swOK=0;
    	if (pCaracter=='')
		{
      		swOK=1;
      		sError+=" Campo "+ document.forms[0].elements[nEle].name.substr(2)+ " ha de ser numérico y es obligatorio" +".";
			return;
    	}
		for (var i=0;i<pCaracter.length;i++)
   		{
			var sByte=pCaracter.charAt(i);
			if (sByte<"0" || sByte>"9")
			{
        		sError+=" Campo "+ document.forms[0].elements[nEle].name.substr(2)+ " ha de ser numérico y es obligatorio" +".";
				swOK=1;
				return;
      		}
		}
	}
	
  // NUMERICO INFORMADO
	if (pType=='No')
  	{
		swOK=0;
    	if (pCaracter=='')
		{
			swOK=1;
			sError+=" Campo "+ document.forms[0].elements[nEle].name.substr(2)+ " ha de ser numérico y NO es obligatorio" +".";
			return;
		}
    	for (var i=0;i<pCaracter.length;i++)
    	{
	  		var sByte=pCaracter.charAt(i);
			if (sByte<"0" || sByte>"9")
			{
        		sError+=" Campo "+ document.forms[0].elements[nEle].name.substr(2)+ " ha de ser numérico y NO es obligatorio" +".";
				swOK=1;
				return;
			}
    	}
	}
	//tarjeta y obligatorio
	if (pType=='Tr' )
	{
    	swOK=0;
    	if (pCaracter=='')
		{
      		swOK=1;
      		sError+=" Campo "+ document.forms[0].elements[nEle].name.substr(2)+ " ha de ser Número de tarjeta (15 a 20 dígitos) y es obligatorio" +".";
			return;
    	}
		for (var i=0;i<pCaracter.length;i++)
   		{
			var sByte=pCaracter.charAt(i);
			if (sByte<"0" || sByte>"9")
			{
        		sError+=" Campo "+ document.forms[0].elements[nEle].name.substr(2)+ " ha de ser Número de tarjeta (15 a 20 dígitos) y es obligatorio" +".";
				swOK=1;
				return;
      		}
			else if ( pCaracter.length <15 || pCaracter.length >20 )
				{
				sError+=" Campo "+ document.forms[0].elements[nEle].name.substr(2)+ " ha de ser Número de tarjeta (15 a 20 dígitos) y es obligatorio" +"."+" Número de digitos erròneo.";
				swOK=1;
				return;
				}
			if(luhn(pCaracter) == -1)
			{
				sError+=" Campo "+ document.forms[0].elements[nEle].name.substr(2)+ " ha de ser Número de tarjeta (15 a 20 dígitos) y es obligatorio" +"."+" LUHN incorrecto";
				swOK=1;
				return;
			}
		}
	}
	//tarjeta y Opional
	if (pType=='To')
	{
    	swOK=0;
    	if (pCaracter=='')
		{
      		swOK=1;
      		sError+=" Campo "+ document.forms[0].elements[nEle].name.substr(2)+ " ha de ser Número de tarjeta (15 a 20 dígitos) y NO es obligatorio" +".";
			return;
    	}
		for (var i=0;i<pCaracter.length;i++)
   		{
			var sByte=pCaracter.charAt(i);
			if (sByte<"0" || sByte>"9")
			{
        		sError+=" Campo "+ document.forms[0].elements[nEle].name.substr(2)+ " ha de ser Número de tarjeta (15 a 20 dígitos) y NO es obligatorio" +".";
				swOK=1;
				return;
      		}
			else if ( pCaracter.length <15 || pCaracter.length >20 )
				{
				sError+=" Campo "+ document.forms[0].elements[nEle].name.substr(2)+ " ha de ser Número de tarjeta (15 a 20 dígitos) y NO es obligatorio" +"."+" Número de digitos erròneo.";
				swOK=1;
				return;
				}
			if(luhn(pCaracter) == -1)
			{
				sError+=" Campo "+ document.forms[0].elements[nEle].name.substr(2)+ " ha de ser Número de tarjeta (15 a 20 dígitos) y NO es obligatorio" +"."+" LUHN incorrecto";
				swOK=1;
				return;
			}
		}
	}

  // CADENA
	if (pType=='Sr')
	{
    	if (pCaracter=='')
		{
			sError+=" Campo "+ document.forms[0].elements[nEle].name.substr(2)+ " ha de ser texto y es obligatorio"+".";
			swOK=1;
			return;
		}
	}
}
function luhn(entrada)
{ 
	var numero = new Array(entrada.length);
	var i = 0
	var total = 0
	for (i = 0; i < entrada.length; ++i)
	{
		//convierto los caracteres en numeros
		numero[i] = parseInt(entrada.charAt(i))
	}
	for (i = numero.length -2; i >= 0; i-=2)
	{  
		//multiplico las posiciones pares desde atras por 2
		numero[i] *= 2;							 
		// Si tienen 2 digitos sumo los digitos
		if (numero[i] > 9) numero[i]-=9;			 
	}										 
	for (i = 0; i < numero.length; ++i)
	{
		//sumo el array
		total += numero[i];						 
	}	
	if ((total%10)!=0)
	{
		// no cumple la restriccion
		return -1;
	}
	// si cumple
	else return 1;
}
function es_fecha(dia,mes,anyo)
{
	var d,m,a;
	d=parseInt(dia.value);
	m=parseInt(mes.value);
	a=parseInt(anyo.value);
	//alert(dia.value+" "+mes.value+" "+anyo.value);
	//alert(parseInt(dia.value)+" "+parseInt(mes.value)+" "+" "+parseInt(anyo.value) );
	switch(parseInt(mes.value))
	{
		case 2:
			// si es bisiesto
			if ( (parseInt(anyo.value) % 4)==0)
			{
				if(parseInt(dia.value)>29)
				{
					alert("Número de dias "+parseInt(dia.value)+" incorrecto para mes "+parseInt(mes.value)+" en año bisiesto.");
					return false;
				}
			}
			else
			{
					if(parseInt(dia.value)>28)
					{
						alert("Número de dias "+parseInt(dia.value)+" incorrecto para mes "+parseInt(mes.value)+" en NO año bisiesto.");
						return false;
					}
			}
			break;
		case 1,3,5,7,8,10,12:
			if(parseInt(dia.value)>31)
			{
				alert("Número de dias "+parseInt(dia.value)+" incorrecto para mes "+parseInt(mes.value));
				return false;
			}
			break;
		case 4,6,9,11:
			if(parseInt(dia.value)>30)
			{
				alert("Número de dias "+parseInt(dia.value)+" incorrecto para mes "+parseInt(mes.value));
				return false;
			}
			break;
	}
	return true;
}
function es_mayor(diaini,mesini,anyoini,diafin,mesfin,anyofin)
{
var inicial =0;
var final =0;
inicial = parseInt(anyoini.value)*10000+parseInt(mesini.value)*100+parseInt(diaini.value);
//alert("Inicial "+inicial);
final = parseInt(anyofin.value)*10000+parseInt(mesfin.value)*100+parseInt(diafin.value);
//alert("Final "+final);
if (inicial > final)
{
	alert("La Fecha Inicial ha de ser menor que la Fecha Final");
	return true;
}
else
{
	return false;
}
}

