
//=================================================================
//		VALIDACIÓN DE CAMPOS DE FORMULARIOS
//		  Y CONVERSIÓN DE TIPOS DE DATOS.
//=================================================================


// Obtiene una fecha de una cadena con formato "dia/mes/año".
// Devuelve NULL si no es una fecha o si no tiene el formato correcto.
function ObtenerFecha(texto) {
	var d, m, a, i, j, v;
	// Si no es una cadena, devuelve nulo.
	if (typeof(texto) != "string") {
		return null;
	}
	// Trocea la cadena.
	v = texto.split("/");
	// Si no tiene 3 trozos (0, 1 y 2), prueba con otro separador.
	if (v.length != 3) {
		v = texto.split("-");
	}
	// Si no tiene 3 trozos (0, 1 y 2), devuelve nulo.
	if (v.length != 3) {
		return null;
	}
	// Obtiene día, mes y año.
	d = v[0];
	m = v[1];
	a = v[2];
	// Valida el año.
	if (isNaN(a)) {
		return null;
	}
	a = ObtenerNumero(a);
	// ¿Sólo dos cifras?
	if (a < 100) {
		// Considera años de 1930 a 2029.
		if (a >= 30)
			a += 1900;
		else
			a += 2000;
	}
	// Valida el mes.
	if (isNaN(m)) {
		return null;
	}
	m = ObtenerNumero(m);
	if (m < 1 || m > 12) {
		return null;
	}
	// Valida el día.
	if (isNaN(d)) {
		return null;
	}
	d = ObtenerNumero(d);
	// Días que tiene cada mes.
	var dias;
	dias = new Array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
	if (a % 4 == 0) {
		// Si es año visiesto, cambia los días de febrero.
		dias[1] = 29;
	}
	if (d < 1 || d > dias[m - 1]) {
		// El número de día no es válido.
		return null;
	}
	// Ok. Fecha válida.
	return new Date(a, m - 1, d);
}

// Formatea una fecha como "DD/MM/AAAA"
// Devuelve "" si no se está pasando una dato de tipo fecha.
function FormatearFecha(fecha) {
	if (fecha == null || (typeof(fecha) != "object" && typeof(fecha) != "date"))
		return "";
	var f = new Date(fecha);
	var texto = "";
	var aux;
	aux = "00" + f.getDate();
	texto += aux.substring(aux.length - 2);
	aux = "00" + (f.getMonth() + 1);
	texto += "/" + aux.substring(aux.length - 2);
	aux = f.getYear();
	if (aux < 1000)
		aux += 1900;
	texto += "/" + aux;
	return texto;
}

// Formatea una hora como "HH:MM"
// Devuelve "" si no se está pasando una dato de tipo fecha.
function FormatearHora(fecha) {
	if (fecha == null || (typeof(fecha) != "object" && typeof(fecha) != "date"))
		return "";
	var f = new Date(fecha);
	var texto = "";
	var aux;
	aux = "00" + f.getHours();
	texto += aux.substring(aux.length - 2);
	aux = "00" + f.getMinutes();
	texto += ":" + aux.substring(aux.length - 2);
	return texto;
}

// Formatea una fecha y hora como "DD/MM/AAAA HH:MM"
// Devuelve "" si no se está pasando una dato de tipo fecha.
function FormatearFechaHora(fecha) {
	if (fecha == null || (typeof(fecha) != "object" && typeof(fecha) != "date"))
		return "";
	return FormatearFecha(fecha) + " " + FormatearHora(fecha);
}

// Formatea un número a partir de una cadena con formato "5.167,45".
// Devuelve NULL si no es un número válido.
function ObtenerNumero(txt) {
	var x = "" + txt;
	x = x.replace(".", "");
	x = x.replace(",", ".");
	if (isNaN(x)) {
		return null;
	}
	else {
		while (x.length > 1 && x.charAt(0) == '0') {
			x = x.substring(1)
		}
		if (x.indexOf(".") != -1)
			return parseFloat(x);
		else
			return parseInt(x);
	}
}

// Formatea un número con formato "5.167,45"
// Devuelve "" si no se está pasando una dato de tipo número.
function FormatearNumero(numero, decimales) {
	if (typeof(numero) != "number") {
		return null;
	}
	var ret = "";
	var x = String(Math.round(numero * Math.pow(10, decimales)));
	if (decimales > 0) {
		var aux = "0000000000" + x;
		ret = "," + (aux).substring(aux.length - decimales);
		if (x.length <= decimales) {
			return "0" + ret;
		}
		else {
			x = x.substring(0, x.length - decimales);
		}
	}
	while (x.length >= 4) {
		ret = "." + x.substring(x.length - 3) + ret;
		x = x.substring(0, x.length - 3);
	}
	ret = x + ret;
	return ret;
}

// Validar número.
function ValidarNumero(control, decimales) {
	var x = control.value;
	if (x == "")
		return true;
	x = ObtenerNumero(x);
	if (x == null) {
		alert("Debe introducir un número válido.");
		control.focus();
		return false;
	}
	else {
		control.value = FormatearNumero(x, decimales);
		return true;
	}
}

// Validar fecha.
function ValidarFecha(control) {
	var x = control.value;
	if (x == "")
		return true;
	x = ObtenerFecha(x);
	if (x == null) {
		alert("Debe introducir una fecha válida.");
		control.focus();
		return false;
	}
	else {
		control.value = FormatearFecha(x);
		return true;
	}
}

// Validar un NIF
function ValidarNIF(control){
	var numero, letra, letraOK;
	
	// Separa el número y la letra.
	numero = control.value;
	if (numero == "")
		return true;
	letra = "";
	if (numero.length >= 1) {
		letra = numero.charAt(numero.length - 1).toUpperCase();
		if (letra >= "A" && letra <= "Z")
			numero = numero.substring(0, numero.length - 1)
		else
			letra = "";
	}

	// Verifica que el campo es numérico.
	if (isNaN(numero)) {
		alert("Debe introducir un número de NIF");
		control.focus();
		return false;
	}
	// Verifica que no se introducen más de 8 dígitos.
	if (numero.length != 8) {
		alert("El NIF debe tener 8 dígitos.");
		control.focus();
		return false;
	}
	
	// Obtiene la letra correcta.
	letraOK = "TRWAGMYFPDXBNJZSQVHLCKE".charAt(parseInt(numero) % 23);
	
	// Comprueba que la letra está bien puesta.
	if (letra != letraOK) {
		alert("La letra que le corresponde a este NIF es: " + letraOK);
	}
	
	control.value = numero + letra;
	return true;
}
