//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//	FUNCIONES DE VALIDACION DE JAVASCRIPT
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

var valDebug=false;


//Averigua si un valor es numerico
function isNumeric(val)
{
	return !isNaN(val);
}

//Si es o no fecha valida.
//Basado en el isDate de royer
function isDate(val)
{
	var datePat    = /^(\d{1,2})(\/|-)(\d{1,2})(\/|-)(\d{4})$/;
	var matchArray = val.match(datePat);

  	// No es una fecha
  	if(matchArray==null)
		return false;

  	day   = matchArray[1];
  	month = matchArray[3];
  	year  = matchArray[5];

	// El mes no esta entre 1 y 12
  	if((month<1) || (month>12))
		return false;

  	// El dia no esta entre 1 y 31
  	if((day<1) || (day>31))
		return false;

	// El mes no tiene 31 dias
	if(((month==4) || (month==6) || (month==9) || (month==11)) && (day==31))
		return false;

  	// 29 Febrero
  	if(month==2)
  	{
	    var isleap=(((year%4)==0) && (((year%100)!= 0) || ((year%400)==0)));
	    if((day>29) || ((day==29) && !isleap))
			return false;
	}

	// Fecha valida
	return true;
}

//Comproibaciçon de email valido
//basado en el ejemplo de http://javascript.espaciolatino.com/ejemplos/ejemplo09.htm
function isEmail(val)
{
	//primero, averiguo que no tenga ningun caracter extraño
	//var plant = /[^\w^@^\.^-]+/gi
	var plant =/^[_A-Za-z0-9-]+(\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\.[A-Za-z0-9-]+)*$/i
	return plant.test(val);
	/*if (plant.test(val))
		return false;
	else
	{
		//ahora, compruebo el formato correcto
    	plant =/(^\w^\.+)(@{1})([\w\.-]+$)/i
     	return plant.test(val);
	}*/
}


var DNI_LETRAS=new Array("T","R","W","A","G","M","Y","F","P","D","X","B","N","J","Z","S","Q","V","H","L","C","K","E","T");

//comprueba el numero y letra del DNI
//formato correcto: 12345678-A
function isDNI(val)
{
	//primero, NO debe de existir guion, espacios, punto, etc
	if(val.indexOf("-")>=0 || val.indexOf(" ")>=0 || val.indexOf(".")>=0)
	{
		if(valDebug) alert("DEBUG: Error, contiene guion, espacio o punto");
		return false;
	}
	//segundo, el tamaño debe ser 8 numeros + letra, osea, 9
	if(val.length>9)
	{
		if(valDebug) alert("DEBUG: Error, más de 9 carácteres");
		return false;
	}

	//segundo, la primera parte todo numeros
	var dniNumber=val.substr(0, val.length-1);
	if(valDebug) alert("DEBUG: número DNI: "+dniNumber);

	if(isNaN(dniNumber))
		return false;
	var intDniNumber=parseInt(dniNumber);

	//devuelvo comprobando la letra de paso
	return (val.toUpperCase()==dniNumber+getDNILetter(dniNumber));
}

//Interno, devuelve la letra del DNI para el número dado
function getDNILetter(dniNumber)
{
	return DNI_LETRAS[dniNumber % 23];
}




//Comprueba que un numero tiene el formato de numérico de moneda 1,234.34
function isMoney(val)
{
	var debug=valDebug;

	//expersion para comprobar luego parte a parte que solo haya numeros
	var regex=/^\d+$/;

	//primero, verifico el punto decimal si lo hay
	if(val.indexOf(",")>0)
	{
		//que no haya mas de uno
		if(val.indexOf(",") != val.lastIndexOf(","))
		{
			if(debug) alert('hay más de una coma decimal');
			return false;
		}

		//que despues venga solo uno o dos caracteres
		if((val.indexOf(",")+3)<=(val.length-1))
		{
			if(debug) alert('hay más de uno o dos carácteres en el decimal (tamaño: '+val.length+', posicion del decimal: '+(val.indexOf(",")+1));
			return false
		}

		if(debug) alert("Decimales: "+val.substr(val.indexOf(",")+1));

		//y por ultimo, que esa parte decimal sea numerica
		if(!regex.test(val.substr(val.indexOf(",")+1)))
		{
			if(debug) alert('el decimal no es numérico');
			return false;
		}
	}

	//ahora, recojo la parte no decimal, si es uqe hay decimal
	var noDecs=val.indexOf(",")>=0?val.substr(0, val.indexOf(",")):val;

	if(debug) alert("parte entera: "+noDecs);

	/*
	//ahora miro cuantas comas tiene
	var startPos=noDecs.length;
	//lo primero, si no tiene, no debe haber más de 3 carácteres no decimales
	if(startPos<0)
		if(noDecs.length>3)
		{
			if(debug) alert('numero entero mayor de 3 carácteres');
			return false;
		}

	//ahora, un while hasta que no haya mas puntos
	while(startPos>=0)
	{
		var nextPos=noDecs.lastIndexOf(".", startPos-1);
		//si no hay mas comas antes, el grupo es desde 0 hasta lastPost, sino desde startPos
		var tmpGroup=noDecs.substring(nextPos+1, startPos);
		if(debug) alert('Analizando grupo '+tmpGroup);

		if(tmpGroup.length==0 || tmpGroup.length>3 || (tmpGroup.length<3 && nextPos>0) || !regex.test(tmpGroup))
		{
			if(debug) alert('grupo NO valido!!');
			return false;
		}
		startPos=nextPos;
	}*/

	//Ahora, simplemente derifico que es numerico (ya no hay separador de miles admitido)
	if(!regex.test(noDecs))
		return false;

	//si llego aqui, es que es correcto

	return true;
}