<!--

// Validación de campos text: se espera que el campo a validar defina un
// atributo "validacion" con el nombre del tipo y opcionalmente otro
// "descripcion" con el nombre de campo que aparecerá en los errores.
// Si además tiene un atributo "requerido" el campo no podrá estar en blanco.

// En el onSubmit del formulario hay que poner una llamada a return validarCampos(form);

// También hay que poner una llamada a la función inicializarForm al final del formulario

// Validator Object
var valid = new Object();

// Texto (para validar que esté relleno, espacios aparte)
valid.texto = new Object();
valid.texto.error0 = "El campo de texto";

// Números naturales (sin signo)
valid.numero = new Object();
valid.numero.expresion = /^(\d)*$/;
valid.numero.onkeypress = teclasNumero;
valid.numero.error0 = "El número";
valid.numero.error = " no es válido";

function teclasNumero(event)
{
    return filtrarTecla (event, "0123456789");
}

// Fechas (DD/MM/YY DD/MM/YYYY DD-MM-YY DD-MM-YYYY)
valid.fecha = new Object();
valid.fecha.expresion = /^(\d{1,2})(\/|-)(\d{1,2})\2(\d{2,4})$/;
valid.fecha.normalizacion = normalizarFecha;
valid.fecha.validacion = validarFecha;
valid.fecha.longitud = 10;
valid.fecha.onkeypress = teclasFecha;
valid.fecha.error0 = "La fecha";
valid.fecha.error = " no es correcta, debe introducirla en el formato dd/mm/aaaa";
valid.fecha.formateoSubmit = formatearFechaEv;
valid.fecha.desformateoSubmit = desformatearFechaEv;

var meses = new Array ("Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre");

function validarFecha (campo, matchArray, descrip)
{
	month = matchArray[3]; // parse date into variables 
	day = matchArray[1]; 
	year = matchArray[4]; 
	if (month < 1 || month > 12) { // check month range
		alert("Sólo son válidos los meses con valor del 1 al 12.");
		return false;
	}
	if (day < 1 || day > 31) {
		alert("Sólo son válidos los días entre 1 y 31.");
		return false; 
	} 
	if ((month==4 || month==6 || month==9 || month==11) && day==31) {
		alert ("Fecha inválida: " + meses[month-1]+" tiene sólo 30 días") 
		return false;
	} 
	if (month == 2) { // check for february 29th 
		var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)); 
		if (day>29 || (day==29 && !isleap)) { 
			alert("Fecha inválida: Febrero del año " + year + " no tiene " + day + " días");
			return false;
		} 
	} 

	return true; // date is valid 
}

function normalizarFecha (campo, matchArray)
{
	if (campo.value != "") {
	    if (matchArray != null) {
    		month = matchArray[3];
    		day = matchArray[1];
	    	year = matchArray[4];
    	
    		if (day.length == 1)  day = "0" + day;
    		if (month.length == 1)  month = "0" + month;
	     	year = year4 (year);
    		campo.value = day + "/" + month + "/" + year;
    	}
	}
}

function formatearFechaEv (campo)
{
    campo.value = formatearFecha (campo.value, getAtributo (campo, "submitFormat"));
}

function desformatearFechaEv (campo)
{
    campo.value = desformatearFecha (campo.value, getAtributo (campo, "submitFormat"));
}

function formatearFecha (valorNorm, formato)
{
    if (formato == "ddMMyyyy") {
        return valorNorm.substring (0,2) + valorNorm.substring (3,5) + valorNorm.substring (6,10);
    } else if (formato == "yyyyMMdd") {
        return valorNorm.substring (6,10) + valorNorm.substring (3,5) + valorNorm.substring (0,2);
    } else {
        return valorNorm;
    }
}

function desformatearFecha (valorNorm, formato)
{
    if (formato == "ddMMyyyy") {
        if (valorNorm.length == 8)
            return valorNorm.substring (0,2) + "/" + valorNorm.substring (2,4) + "/" + valorNorm.substring (4,8);
    } else if (formato == "yyyyMMdd") {
        if (valorNorm.length == 8)
            return valorNorm.substring (6,8) + "/" + valorNorm.substring (4,6) + "/" + valorNorm.substring (0,4);
    }
    return valorNorm;
}

function year4 (year)
{
   	if (year.length == 1)  year = "0" + year;
    if (year.length == 2) {
        var current = (new Date()).getYear();
        var decada = parseInt(current / 100);
        if (parseInt (current % 100) < parseInt(year) - 5)  decada--;
        year = "" + decada + year;
    }
    if (year.length == 3)  year = "0" + year;
    return year;
}

function teclasFecha(event)
{
    return filtrarTecla (event, "0123456789/-");
}


// Horas (matches 5:04 or 12:34 but not 75:83)
valid.hora = new Object();
valid.hora.expresion = /^([1-9]|1[0-2]):[0-5]\d$/;
valid.hora.longitud = 5;


// E-mail
valid.email = new Object();
valid.email.expresion = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
valid.email.error0 = "El campo con la dirección de correo";


// REGEX Elements
/*
    // matches zip codes
    valid.zipCode.expresion = /\d{5}(-\d{4})?/;

    // matches $17.23 or $14,281,545.45 or ...
    valid.Currency.expresion = /\$\d{1,3}(,\d{3})*\.\d{2}/;

    // matches 5:04 or 12:34 but not 75:83
    valid.hora.expresion = /^([1-9]|1[0-2]):[0-5]\d$/;

    //matches email
    valid.emailAddress.expresion = /^.+\@(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,3}|[0-9]{1,3})(\]?)$/;

    // matches phone ###-###-####
    valid.phoneNumber.expresion = /^\(?\d{3}\)?\s|-\d{3}-\d{4}$/;

    // International Phone Number
    valid.phoneNumberInternational = /^\d(\d|-){7,20}/;

    // IP Address
    valid.ipAddress = /^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;

    // Date xx/xx/xxxx
    valid.Date = /^\d{1,2}(\-|\/|\.)\d{1,2}\1\d{4}$/;
			/^(\d{1,2})(\/|-)(\d{1,2})\2(\d{2})$/
    // State Abbreviation
    valid.State = /^(AK|AL|AR|AZ|CA|CO|CT|DC|DE|FL|GA|HI|IA|ID|IL|IN|KS|KY|LA|MA|MD|ME|MI|MN|MO|MS|MT|NB|NC|ND|NH|NJ|NM|NV|NY|OH|OK|OR|PA|RI|SC|SD|TN|TX|UT|VA|VT|WA|WI|WV|WY)$/i;

    // Social Security Number
    valid.SSN = /^\d{3}\-\d{2}\-\d{4}$/;
*/

// Funciones genéricas

function inicializarForm (theForm, campoFoco)
{
    inicializarCampos (theForm);
    campoFoco.focus();
}

function inicializarCampos (theForm)
{
	var elArr = theForm.elements; 
	for(var i = 0; i < elArr.length; i++) {
		var campo = elArr[i];
		var v = valid [getAtributo (campo, "validacion")];
		if(!v) continue;
		if (v.longitud)  campo.maxLength = v.longitud;
		if (v.onkeypress)  campo.onkeypress = v.onkeypress;
		if (v.onkeyup)  campo.onkeyup = v.onkeyup;
		if (v.onkeydown)  campo.onkeydown = v.onkeydown;
		if (v.normalizacion) {
		    campo.onblur = normalizarCampoEv;
		    if (campo.value) {
                if (v.desformateoSubmit)  v.desformateoSubmit (campo);
		        normalizarCampo (campo);
		    }
		}
    }
}

function getAtributo (campo, nombre)
{
    if (campo.getAttribute(nombre))
        return campo.getAttribute(nombre);
    else
        return null;
}

function validarCampos (theForm)
{
	var elArr = theForm.elements; 
	for(var i = 0; i < elArr.length; i++) {
		var campo = elArr[i];
		var v = valid [getAtributo (campo, "validacion")];
		if(!v) continue;
		var descripCampo;
		if (getAtributo (campo, "descripcion")) {
			descripCampo = getAtributo (campo, "descripcion");
		} else {
			descripCampo = "El campo " + campo.name;
		}
		
		var defErr;
		if (v.error) {
		    if (!getAtributo (campo, "descripcion") && v.error0) {
    			defErr = v.error0 + v.error;
    		} else {
    			defErr = descripCampo + v.error;
		    }
		} else {
			defErr = descripCampo + " no es válido";
		}
		
		var ok = true;
		var requerido = getAtributo (campo, "requerido");
		if (requerido)  requerido = (requerido.toLowerCase() != "no");
		var vacio = isEmpty (campo.value);
		if (vacio && requerido) {
			ok = false;
			alert ("Debe rellenar " + minuscPrimera(descripCampo));
		} else if (vacio) {
			campo.value = "";
		} else {
			var patron = v.expresion;
			var valores = null;
			if (patron) {
			    valores = campo.value.match (patron);
			    ok = (valores != null);
			}
			if (!ok) {
				alert (defErr);
			}
	
			if (ok && v.validacion) {
				ok = v.validacion (campo, valores, descripCampo);
			}
		}
			
		if (!ok){
			if (elArr[i].select)  elArr[i].select();
			elArr[i].focus();
			return false;

		} else if (v.normalizacion) {
		    v.normalizacion (campo, valores);
		}
		
		if (ok && v.formateoSubmit)  v.formateoSubmit (campo);
	}
	return true;
}

function normalizarCampo (campo)
{
	var v = valid [getAtributo (campo, "validacion")];
	if (!v || !v.normalizacion) return;
	
	var patron = v.expresion;
	var valores = null;
	if (patron) {
	    valores = campo.value.match (patron);
	}
	if (v.normalizacion) {
	    v.normalizacion (campo, valores);
	}
}


function normalizarCampoEv()
{
    var campo = this;
    normalizarCampo (campo);
}

function filtrarTecla (event, caracteresValidos)
{
  var key, keychar;

  if (window.event)
    key = window.event.keyCode;
  else if (event)
    key = event.which;
  else
    return true;

  keychar = String.fromCharCode(key);

  if ((key==null) || (key==0) || (key==8) || (key==9) || (key==13) || (key==27))
    return true;
  else if (((caracteresValidos).indexOf(keychar) > -1))
    return true;
  else
    return false;
}

function minuscPrimera (texto)
{
	if ((texto == null) || (texto.length < 2))
		return texto;
	else
		return texto.substring(0,1).toLowerCase() + texto.substring(1);
}

function isEmpty(str){
	if (str == null)
		return true;
	else
		return (strip(" \n\r\t",str).length == 0);
}

function strip(filter,str){
   var i,curChar;
   var retStr = '';
   var len = str.length;
   for(i=0; i<len; i++){
      curChar = str.charAt(i);
      if(filter.indexOf(curChar)<0) 
         retStr += curChar;
   }
   return retStr;
}

//-->
