/*----------------------------------------------------------------*\

VALIDACIÓN DE CAMPOS DE FORMULARIOS Y CONVERSIÓN DE TIPOS DE DATOS.
===================================================================
© 2003 Centro de Cálculo Bosco S.L., All Rights Reserved
	
Funciones que contiene:
	Date ObtenerFecha(String texto)
	Date ObtenerHora(String texto)
	Date ObtenerFechaHora(String texto)
	Number ObtenerNumero(String txt)
	Boolean ObtenerBooleano(String texto)
	String FormatearFecha(Date fecha)
	String FormatearHora(Date fecha, [Boolean mostrarSegundos])
	String FormatearFechaHora(Date fecha, [Boolean mostrarSegundos])
	String FormatearNumero(Number numero, Number decimales)
	String FormatearBooleano(Boolean valor)
	Boolean ValidarNumero(Object control, Number decimales, [Boolean MostrarMensaje])
	Boolean ValidarFecha(Object control, [Boolean MostrarMensaje])
	Boolean ValidarHora(Object control, [Boolean MostrarMensaje])
	Boolean ValidarFechaHora(Object control, [Boolean MostrarMensaje])
	Boolean ValidarCodigoNumerico(Object control, [Boolean MostrarMensaje])
	Boolean ValidarCampo(Object control, [Boolean MostrarMensaje]) {
	Boolean ValidarFormulario(Object formulario) {
	void ponerComa(Object control)

Modificado:	Sergio Arroyo, 2004-03-25
	Se ha cambiado el formato de las horas de HH:MM a HH:MM:SS
	Se ha mejorado la comprobación del tipo de dato de los parámetros.
	En las funciones de validar se puede decir si el campo es obligatorio o no.
Modificado:	Sergio Arroyo, 2004-04-27
	Se han añadido las funciones:
		ValidarCodigoNumerico
		Validar/Obtener-Hora/FechaHora
		Obtener/Formatear-Booleano
Modificado: 2004-06-08
	Fallo en ObtenerNumero (había una llamada a replace() incorrecta)
Modificado: 2004-06-28
	En la funciones ValidarXXXXX se ha acambiado el último parámetro opcional por "MostrarMensaje".
	    Si MostrarMensaje == false, la función devuelve true o false
	    indicando si el valor es válido, pero no muestra ningún mensaje de aviso.
	Nuevas funciones:
	    ValidarCampo()
	    ValidarFormulario()

\*----------------------------------------------------------------*/


// Obtiene una fecha de una cadena con formato "DD/MM/AAAA".
// Devuelve NULL si no es una fecha o si no tiene el formato correcto.
function ObtenerFecha(texto) {
	var d, m, a, i, j, v;
	// Se asegura de obtener un texto
	if (texto == null || texto == "") {
		return null;
	}
	else if (texto instanceof Date) {
		texto = FormatearHora(texto);
	}
	else if (typeof(texto) != "string") {
		texto = String(texto);
	}
	// Trocea la cadena.
texto = texto.replace(/-/g, "/");
	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 (a == "" || 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 (m == "" || isNaN(m)) {
		return null;
	}
	m = ObtenerNumero(m);
	if (m < 1 || m > 12) {
		return null;
	}
	// Valida el día.
	if (d == "" || 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 bisiesto, 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 (typeof(fecha) == "string") {
		fecha = ObtenerFecha(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;
}

// Obtiene una fecha de una cadena con formato "HH:MM:SS".
// Devuelve NULL si no es una fecha o si no tiene el formato correcto.
function ObtenerHora(texto) {
	var v;
	// Se asegura de obtener un texto
	if (texto == null || texto == "") {
		return null;
	}
	if (texto instanceof Date) {
		texto = FormatearHora(texto);
	}
	else if (typeof(texto) != "string") {
		texto = String(texto);
	}
	// Trocea la cadena.
	v = texto.split(":");
	if (v.length < 1 || v.length > 3)
		return null;
	// Obtiene la hora.
	var h, m, s;
	h = v[0];
	// Obtiene el minuto.
	if (v.length >= 2)
		m = v[1];
	else
		m = "0";
	// Obtiene el segundo.
	if (v.length >= 3)
		s = v[2];
	else
		s = "0";
	// Valida la hora
	if (h == "" || isNaN(h)) {
		return null;
	}
	h = ObtenerNumero(h);
	if (h < 0 || h >= 24)
		return null;
	// Valida el minuto
	if (m == "" || isNaN(m)) {
		return null;
	}
	m = ObtenerNumero(m);
	if (m < 0 || m >= 60)
		return null;
	// Valida el segundo
	if (s == "" || isNaN(s)) {
		return null;
	}
	s = ObtenerNumero(s);
	if (s < 0 || s >= 60)
		return null;
	// Ok. Devuelve la hora.
	return new Date(1899, 12, 30, h, m, s);
}

// Formatea una hora como "HH:MM:SS"
// Devuelve "" si no se está pasando una dato de tipo fecha.
function FormatearHora(fecha, mostrarSegundos) {
	if (typeof(fecha) == "string") {
		fecha = ObtenerHora(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);
	if (mostrarSegundos || mostrarSegundos == null) {
		aux = "00" + f.getSeconds();
		texto += ":" + aux.substring(aux.length - 2);
	}
	return texto;
}

// Obtiene fecha y hora de una cadena con formato "DD/MM/AAAA HH:MM:SS".
// Devuelve NULL si no es una fecha o si no tiene el formato correcto.
function ObtenerFechaHora(texto) {
	var v;
	// Se asegura de obtener un texto
	if (texto == null || texto == "") {
		return null;
	}
	if (texto instanceof Date) {
		texto = FormatearHora(texto);
	}
	else if (typeof(texto) != "string") {
		texto = String(texto);
	}
	// Trocea la cadena.
	texto = texto.replace(/ +/g, " ");
	v = texto.split(" ");
	if (v.length < 1 || v.length > 2)
		return null;
	// Obtiene la fecha
	var f, h;
	f = ObtenerFecha(v[0]);
	if (f == null)
		return null;
	// Obtiene la hora,
	if (v.length > 1) {
		h = ObtenerHora(v[1]);
		if (h == null)
			return null;
		f = new Date(f.getYear(), f.getMonth(), f.getDate(), h.getHours(), h.getMinutes(), h.getSeconds());
	}
	// devuelve la fecha.
	return f;
}

// 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, mostrarSegundos) {
	if (typeof(fecha) == "string") {
		fecha = ObtenerFechaHora(fecha);
	}
	if (fecha == null || (typeof(fecha) != "object" && typeof(fecha) != "date"))
		return "";
	return FormatearFecha(fecha) + " " + FormatearHora(fecha, mostrarSegundos);
}

// Obtiene 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) {
	if (typeof(txt) == "number") {
		return txt;
	}
	var x = "" + txt;
	x = x.replace(/\./g, "");
	x = x.replace(/,/g, ".");
	if (x == "" || 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) == "string") {
		numero = ObtenerNumero(numero);
	}
	if (numero == null || typeof(numero) != "number" || isNaN(numero)) {
		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;
		ret = x.substring(x.length - 3) + ret;
		x = x.substring(0, x.length - 3);
	}
	ret = x + ret;
	return ret;
}

//=================================================================================
//
//	VALIDACIONES.
//
//	Ejemplo:
//		<input type="text" name="txtNumero" value="" onblur="ValidarNumero(this, 2)">
//
//=================================================================================

// Validar número.
function ValidarNumero(control, decimales, MostrarMensaje) {
	var x = control.value;
	if (x == "")
		return true;
	x = ObtenerNumero(x);
	if (x == null) {
		if (MostrarMensaje != false)
			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, obligatorio) {
	var x = control.value;
	if (x == "" && (!obligatorio || obligatorio == null))
		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 fecha.
function ValidarHora(control, obligatorio) {
	var x = control.value;
	if (x == "" && (!obligatorio || obligatorio == null))
		return true;
	x = ObtenerHora(x);
	if (x == null) {
		alert("Debe introducir una hora válida.");
		control.focus();
		return false;
	}
	else {
		control.value = FormatearHora(x);
		return true;
	}
}

// Validar fecha-hora.
function ValidarFechaHora(control, MostrarMensaje) {
	var x = control.value;
	if (x == "")
		return true;
	x = ObtenerFechaHora(x);
	if (x == null) {
		if (MostrarMensaje != false) {
			alert("Debe introducir una fecha válida.");
		}
		control.focus();
		return false;
	}
	else {
		control.value = FormatearFechaHora(x);
		return true;
	}
}

// Validar un código numérico (toma la longitud del atributo SIZE del control).
function ValidarCodigoNumerico(control, obligatorio) {
	var i;
	var x = jsLTrim(jsRTrim(control.value));
	if (x == "" && (!obligatorio || obligatorio == null))
		return true;
	for (i=0; i<x.length; i++) {
		if (isNaN(x.charAt(i))) {
			x = null;
			break;
		}
	}
	if (x == null) {
		alert("Debe introducir un código numérico.");
		control.focus();
		return false;
	}
	else {
		if (x.length < control.maxLength) {
			// Añade ceros a la izquierda, hasta completar el campo.
			for (i = x.length; i < control.maxLength; i++) {
				x = '0' + x;
			}
			control.value = x;
		}
		return true;
	}
}
function jsLTrim(texto) {
	var i = 0;
	while (i < texto.length && texto.charAt(i) == ' ')
		i++;
	return texto.substring(i, texto.length);
}
function jsRTrim(texto) {
	var i = texto.length;
	while (i > 0 && texto.charAt(i - 1) == ' ')
		i--;
	return texto.substring(0, i);
}


function ValidarCampo(campo, MostrarMensaje) {
	var d;
	switch (campo.formato) {
		case "N":
			d = campo.decimales;
			if (isNaN(d)) {
				d = 0;
			}
			else {
				d = parseInt(d);
			}
			return ValidarNumero(campo, d, MostrarMensaje);
		case "F":
			return ValidarFecha(campo, MostrarMensaje);
		case "H":
			return ValidarHora(campo, MostrarMensaje);
		case "FH":
			return ValidarFechaHora(campo, MostrarMensaje);
		case "COD":
			return ValidarCodigoNumerico(campo, MostrarMensaje);
		default:
			return true;
	}
}
			
function ValidarFormulario(frm) {
	var i;
	for (i=0; i<frm.length; i++) {
		if (frm[i].formato != null) {
			if (!ValidarCampo(frm[i], false)) {
				return false;
			}
		}
		if (
			frm[i].obligatorio != null
			&& String(frm[i].obligatorio).toUpperCase() != "NO"
			&& frm[i].value == ""
		) {
			var t;
			t = frm[i].title;
			if (t == null || t == "") {
				alert("Debe rellenar el campo obligatorio");
			}
			else {
				alert("Debe rellenar el campo " + t);
			}
			frm[i].focus();
			return false;
		}
	}
	return true;
}


// Función para obtener un booleano a partir de una cadena de texto.
function ObtenerBooleano(texto) {
	if (texto == null || texto == "") {
		return false;
	}
	if (typeof(texto) != "string") {
		texto = FormatearBooleano(texto);
	}
	if (texto.toUpperCase() != "NO" && texto != "0") {
		return true;
	}
	else {
		return false;
	}
}

// Devuelve una cadena de texto con "SI" o "NO".
function FormatearBooleano(valor) {
	if (typeof(valor) == "string") {
		valor = ObtenerBooleano(valor);
	}
	if (valor == null || valor == false || valor == 0) {
		return "NO";
	}
	else {
		return "SI";
	}
}

// Funcion que cambia el "." por "," (usarla en el onkeypress de un input-text.)
// Sólo funciona con IE.
function ponerComa(control) {
	if (navigator.appName == "Microsoft Internet Explorer") {
		var tecla = window.event.keyCode;
		if (tecla == 46 || tecla == 44) {
			if (control.value.indexOf(",") != -1 )
				event.keyCode = 0;
			else
				event.keyCode = 44;
		}
	}
}

/**
 * Devuelve el codigo de tecla segun el navegador
 * Navegadores controlados: IE, FireFox
 * @param {Object} e = Evento
 */
function getCodigoTecla(e)
{
	/* IE */
	if ((document.all) ? true : false){
		return e.keyCode;
	}/* FireFox */
	else{
		if (e.which == 0){
			return e.keyCode;
		}else{
			return e.which;	
		}
		
	}
}

/**
 * Funcion que solo permite insertar letras maysuculas o minusculas
 * @param {Object} e = Evento
 * @param {Object} obj = Objeto HTML donde se produce el evento
 */
function fControlLetra(e,obj)
{
	//	alert("KeyCode: " + e.keyCode + ", charCode: " + e.charCode);
	var tecla = getCodigoTecla(e);
	if( (tecla >= 65 && tecla <= 90) || 
		(tecla >= 97 && tecla <= 122) || 
		(tecla >= 160 && tecla <= 163) ||
		tecla == 130 ||
		tecla == 193 ||
		tecla == 201 ||
		tecla == 205 ||
		tecla == 211 ||
		tecla == 218 )
	{
		return true;
	}else{
		return false;
	}
}

/**
 * Funcion que solo permite insertar números
 * @param {Object} e = Evento
 * @param {Object} obj = Objeto HTML donde se produce el evento
 */
function fControlNumerico(e,obj)
{
	var tecla = getCodigoTecla(e);
	if (tecla == 8 || 
		tecla == 9 || 
		tecla == 13 ||
		(tecla >= 48 && tecla <= 57))
	{
		return true;
	}else{
		return false;
	}
}
