<!-- // INICIO Validate.js ---------------------------------------------------

// Funciones del modulo:
//  - FiltrarCaracteres(tira)
//  - isBlank(s)
//  - Validate(theForm)
//  - isIntegerString(str)
//  - isFloatString(str)
//  - isValidEmail(str)
//  - isValidEmailAddr(str)
//  - checkMonthDays(monIndex, selDay, selYear)
//  - isValidDate(str)
//  - isStringCategory(str, categories)
//  - Trim(s)
//  - TrimTextField(field)
//  - ValidateTypedValue(type, value)
//  - TypeToString(type)
//  - GenerarMsgError(texto, sinLinea)
//  - GetPointPosition(tira)
//  - AdjustDecimal(event, el)
//  - ValidateDate(event, el)
//  - ValidateRangeDates(strFechaInicial, strFechaFinal)
//  - ValidateDecimal(event, el, negatives)
//  - ValidateInteger(event, el, negatives)
//  - ValidateNegative(event, el)
//  - ValidateIdentifier(event, el, typeIdentifier)
//  - ValidateAlphanumeric(el, event)  
//  - ultimoDiaPara(unMes, unAnno)



// Descripcion:     Funcion para validar los datos de entrada.
// Uso:             Llamar validate(<nombre_formulario>)
// Funcionalidad:   Esta funcion validara cada elemento en el formulario.  Si se
//                  detectan errores en los datos de entrada,  la descripcion de
//                  los mismos se despliega con un mensaje asociado.
// Valores de ret.: Retorna true si la validacion es exitosa,  false otro caso.
// Requisitos:      Los elementos  deberian implementar las siguientes propieda-
//                  des segun lo requieran:
//                  optional   - Un valor no es requerido en este campo.
//                  required   - Un valor es requerido en este campo.
//			        (Si cualquiera de los siguientes cuatro propiedades estan 
//                   presentes, el campo es tratado como numerico)
//			        numeric    - El campo solo admite valores numericos.
//                  integer    - El campo solo admite valores enteros positivos.
//                  min        - Valor minimo de la entrada numerica.
//                  max        - Valor maximo de la entrada numerica.
//                  email      - El campo corresponde a una direccion electronica.
//                  maxlength  - Numero maximo de caracteres para este campo.
//                  description- Descriptor del campo mostrado en caso de errores.
//                  date       - Este campo es una fecha, con formato: d/m/y
//			         category     - Una lista de posibles strings que el valor puede tener
//                               separadas por comas (Si se utiliza, tambien debe utilizarse 'categoryName')
//			         categoryName - the name of the category for the alert message
//                  error      - Cuando se sabe que hay un error, se despliega la tira


var bwrValidateIE = document.all?1:0;

var parIdioma = "es";


function FiltrarCaracteres(tira) {
    var hilera = "";
    var indice = 0, codigo, caracter;

    while (indice < tira.length) {
        codigo = tira.charCodeAt(indice);
        caracter = tira.charAt(indice);
        if (codigo == 10)
            hilera += " ";
        else
            if (caracter != '$' && caracter != '|' && caracter != '^' && codigo != 13)
                hilera += tira.substr(indice, 1);
        indice++;
    }
    return hilera;
}

function isBlank(s)
{
	for (var i = 0; i < s.length; i++) {
		var c = s.charAt(i);
		if ((c != ' ') && (c != '\n') && (c != '\t'))
			return false;
	}
	return true;
}

function Validate(theForm) {
	// theForm          - Formulario por validar
	// expectEverything - Todos los campos deberian ser proporcionados, excepto los que tienen 
	//                    especificada la propiedad 'optional'
	//                    En caso contrario, todos los campos son optional, excepto los que tienen
	//                    especificada la propiedad 'required'
	var msg = "";
	var emptyFields = "";
	var nonNumericFields = "";
	var emailFields = "";
	var maxLengthFields = "";
	var dateFields = "";
	var categoryFields = "";
	var errorFields = "";
	var igender = 0;
	var irelation = 0;
	var expectEverything = true;
        
	for (var i = 0; i < theForm.length; i++) {

		var e = theForm.elements[i];

		var validationRequired =
			(e.required == true) ||
			((e.type == "text" || e.type == "textarea" || e.type == "password") && !isBlank(e.value));

		var description = (e.description ? e.description : e.name);
		
		// Validacion: Campos que no pueden ser nulos
		if ((e.type == "text" || e.type == "textarea" || e.type == "password") &&
		        (e.required == true)) {
			if (isBlank(e.value))
				emptyFields += "\n        " + description;
		}

		// Validacion: Campos del tipo 'select-one'
		if ((e.type == "select-one") && (e.required == true)) {
		    if (e.value == "")
			    emptyFields += "\n        " + description;
		}

		// Validacion: Campos numericos y enteros
		if (validationRequired &&
		        (e.numeric || e.integer || (e.min != null) || (e.max != null))) {
		    var v = parseFloat(e.value);
		    if (isNaN(v) || (e.integer && !isIntegerString(e.value)) ||
		            ((e.min != null) && (v < e.min)) ||
			        ((e.max != null) && (v > e.max))) {
                                if (parIdioma == "en") {
                                    nonNumericFields += "- The field '" + description + "' must be " +
                                                        (e.integer ? "an integer" : "a number");
                                } else {
                                    nonNumericFields += "- El campo '" + description + "' debería ser " +
							(e.integer ? "un entero" : "un número");
                                }
				if (e.min != null)
                                    if (parIdioma == "en") {
                                        nonNumericFields += " that is greater than or equal to " + e.min;
                                    } else {
					nonNumericFields += " mayor o igual a " + e.min;
                                    }
				if (e.max != null && e.min != null)
                                    if (parIdioma == "en") {
                                        nonNumericFields += " and less than or equal to " + e.max;
                                    } else {
					nonNumericFields += " y menor o igual a " + e.max;
                                    }
				else if (e.max != null)
                                    if (parIdioma == "en") {
                                        nonNumericFields += " that is less than or equal to " + e.max;
                                    } else {
                                        nonNumericFields += " menor o igual a " + e.max;
                                    }
				nonNumericFields += "\n";
			}
		}
			
		// Validacion: Direcciones de correo
		if (validationRequired && 
                    (e.email && !isValidEmail(e.value))) {
                    if (parIdioma == "en") {
                        emailFields += "- The field '" + description + "' must be a valid e-mail address\n";
                    } else {
                        emailFields += "- El campo '" + description + "' debería ser una dirección de " + 
                                       "correo electrónico válida\n";
                    }
		}
                
		// Validacion: Longitud de los campos
		if (validationRequired &&
			(e.maxlength && e.maxlength != null && e.value)) {
			if (e.value.length > e.maxlength) {
                            if (parIdioma == "en") {
                                maxLengthFields += "- The field '" + description + "' can be at most " + e.maxlength +
                                                   " characters long\n";
                           } else {
				maxLengthFields += "- El campo '" + description + "' debe tener " + 
                                                   e.maxlength + " caracteres como máximo\n";
                           }
			}
		}
		
		// Validacion: Campos de tipo fecha. Formato: dd/mm/aa o dd/mm/aaaa
		if (validationRequired &&
			(e.date && !isValidDate(e.value))) {
                    if (parIdioma == "en") {
                        dateFields += "- The field '" + description + "' must be a valid date\n";
                    } else {
			dateFields += "- El campo '" + description + "' debe ser una fecha válida\n";
                    }
		}

		// Validacion: Campos categorizados
		if (validationRequired &&
                    (e.category && !isStringCategory(e.value, e.category))) {
                    if (parIdioma == "en") {
                        categoryFields += "- The field " + description + " does not belong to the " +
                                          " category " + (e.categoryName != null ? e.categoryName : e.category) + "\n";
                    } else {
			categoryFields += "- El campo '" + description + "' no pertenece a la " +
                                          " categoría '" + (e.categoryName != null ? e.categoryName : e.category) + "'\n";
                    }
		}

		if (e.error) {
			errorFields += "- " + e.error + "\n";
		}
	}

	if (!emptyFields && !nonNumericFields && !emailFields && !maxLengthFields &&
			!dateFields && !categoryFields && !errorFields)
		return true;

	if (emptyFields)
        if (parIdioma == "en") {
            msg += "- The following field(s) are blank and require a value:" + emptyFields + "\n";
        } else {
            msg += "- Los siguientes campos no fueron proporcionados:" + emptyFields + "\n";
        }
        
	msg += nonNumericFields;
	msg += emailFields;
	msg += maxLengthFields;
	msg += dateFields;
	msg += categoryFields;
	msg += errorFields;
	msg = GenerarMsgError(msg, true);
        
	alert(msg);
	return false;
}


function isIntegerString(str) {
    
    if (null == str || "undefined" == str || "" == str)	// 6299
        return false;
    x = parseInt(new Number(str));
    if (isNaN(x))
        return false;
    if (str.indexOf(".") != -1)
        return false;
    return true;
    // return (parseFloat(str) % 1) == 0 && parseInt(str, 10) >= 0 && parseInt(str, 10) == (str - 0);
}


function isFloatString(str) {
	x = parseFloat(new Number(str));
	if (isNaN(x))
		return false;
	return true;
}

function validateEmail(element)
{
    var email = isValidEmail(element.value);
    if(element.value == "")
    {}
    else
    {
        if (!email)
        {
            alert('El formato de correo esta incorrecto.');
            element.value="";
        }
    }
}

function isValidEmail(str) {
	// email can be in one of the following formats:
	// address
	// address (comment)
	// comment <address>
	// comment [address]
	// <address> comment
	// [address] comment
	// address, address
	var allAddrs = str.split(',');
	if (allAddrs.length == 0) return false;
	if (str.charAt(str.length - 1) == ',') return false;
	for (var i = 0; i < allAddrs.length; i++) {
		current = allAddrs[i];
		var index = current.indexOf('(');
		if (index != -1) {
			var head = current.substring(0, index-1);
			index = current.indexOf(')');
			if (index == -1) return false;
			var tail = Trim(current.substring(index + 1, current.length));
			if (tail != "") return false;
			current = head;
		} else if ((index = current.indexOf('<')) != -1) {
			var index2 = current.indexOf('>');
			if (index2 == -1) return false;
			current = current.substring(index + 1, index2);
		} else if ((index = current.indexOf('[')) != -1) {
			var index2 = current.indexOf(']');
			if (index2 == -1) return false;
			current = current.substring(index + 1, index2);
		}
		if (!isValidEmailAddr(Trim(current))) return false;
	}
	return true;
}


function isValidEmailAddr(str) {
	if (str.indexOf(' ') != -1) return false;
        
	var a = str.split("@");
		
	if (a.length != 2 || str.charAt(str.length-1) == '@') return false;
		
	var b = a[1].split(".");
		
	if (b.length < 2) return false;
		
	return true;
}


function checkMonthDays(monIndex, selDay, selYear) {
//Validacion de la fecha seleccionada

    // Validacion para el mes de Febrero
    if (monIndex == 2) {
        if ((parseInt(selYear) % 4) != 0) {
            if (parseInt(selDay) > 28)
                return false;
            else
                return true;
        } else if ((parseInt(selYear) % 400) == 0) {
            if (parseInt(selDay) > 29)
                return false;
            else
                return true;
        } else if ((parseInt(selYear) % 100) == 0) {
            if (parseInt(selDay) > 28)
                return false;
            else
                return true;
        } else {
            if (parseInt(selDay) > 29)
                return false;
            else
                return true;
        }
    }


    // Verificacion de los meses con 30 dias
    if (monIndex == 4 || monIndex == 6 || monIndex== 9 || monIndex == 11) {
            if (parseInt(selDay) > 30) {
                    return false;
            } else {
                    return true;
            }
    } else {
            if (parseInt(selDay) > 31) {
                    return false;
            } else {
                    return true;
            }
    }

}
	

function isValidDate(str) {
	var a = str.split("/");
		
	// Deben existir tres elementos
	if (a.length != 3) return false;
		
	// Todos los elementos deben ser enteros
	for (var i = 0; i < 3; i++) {
		if (!isIntegerString(a[i])) return false;
	}
		
	// Seccionamos la fecha
	var day   = parseInt(a[0], 10);
	var month = parseInt(a[1], 10);
	var year  = parseInt(a[2], 10);
		
	// El rango para el dia es de 1 a 31
	if (day < 1 || day > 31) return false;
		
	// El rango para el mes es de 1 a 12
	if (month < 1 || month > 12) return false;

	// El rango para el anno es de 1950 a 4000
	if (year < 1950 || year > 4000) return false;

	// La cantidad de caracteres para el anno es de 2 o 4
	if (a[2].length != 2 && a[2].length != 4) return false;

	// Cuando el anno es de 2 digitos se asume que se encuentran en el rango 1970-2069
	if (a[2].length == 2) {
		year += (year < 70 ? 2000 : 1900);
	}
		
	// Verificamos que el dia sea valido segun el mes al que pertenece
	if (checkMonthDays(month, day, year) == false) {
		return false;
	} else {
		// No hubieron errores
		return true;
	}
}


function isStringCategory(str, categories) {
	var a = categories.split(",");
		
	for (var i = 0; i < a.length; i++) {
		if (str == a[i]) return true;
	}
	return false;
}


function Trim(s) {
//  Elimina los espacios en blanco al inicio de una tira
    var start = s.length;
    var end   = 0;
    var c     = "";

	for (var i = 0; i < s.length; i++) {
		c = s.substring(i, i+1);
		if (" " != c && "\t" != c && "\n" != c && "\r" != c) {
			if (i < start)
				start = i;
			else
				if (i > end)
					end = i;
		}
    }
    return s.substring(start, end+1);
}


function TrimTextField(field) {
//  Le aplica la funcin 'Trim' a un campo de texto de un formulario
	field.value = Trim(field.value);
}


/*****************************************************************************
 *****************************************************************************/
function ValidateTypedValue(type, value) {
	//	Los tipos estan definidos en remote/kcKanaFieldInterface.java
	//	1 = text field
	//	2 = date field
	//	3 = integer
	//	4 = decimal
	//	5 = boolean
	//  6 = message
	//  7 = contactType
	var retString = "Debe proporcionar un valor de tipo '" + TypeToString(type) + "' válido para el criterio";
	if (type == 1)		//	text
		return "";
	else if (type == 2)	//	date
	{
		if (isValidDate(value) == true) return "";
	}
	else if (type == 3) // integer
	{
		if (isIntegerString(value) == true)
		{
			if (value < 1000000000)
			{
				return "";
			}
			else
			{
				retString = "El valor '" + value + "' es muy grande. Por favor, utilice un entero menor a 1,000,000,000.";
			}
		}
	}
	else if (type == 4)	//	decimal
	{
		if (isFloatString(value) == true) return "";
	}
	else if (type == 5)	//	boolean
		return "";
	else if (type == 6)	//	message
		return "";
	else if (type == 7) // contactType
		return "";
	return retString;
}


function TypeToString(type) {
	if (type == 1)		//	text
		return "text";
	else if (type == 2)	//	date
		return "date";
	else if (type == 3)	//	integer
		return "integer";
	else if (type == 4)	//	decimal
		return "decimal";
	else if (type == 5)	//	boolean
		return "boolean";
	return "undefined";
}


/*****************************************************************************
 * LAS SIGUIENTES FUNCIONES FUERON MODIFICADAS PARA QUE PUDIERAN MOSTRARSE   *
 * LOS MENSAJES EN VARIOS IDIOMAS.                                           *
 *****************************************************************************/
function GenerarMsgError(texto, sinLinea) {
	var msg = ""
	
        if (parIdioma == "en") {
            msg += "The form could not be submitted due to the following errors.\n\n";
            msg += texto + (sinLinea ? "" : "\n");
            msg += "\nPlease correct and re-submit.";
        } else {
            msg += "Los datos de entrada no fueron procesados debido a los siguientes errores.\n\n";
            msg += texto + (sinLinea ? "" : "\n");
            msg += "\nSeleccione OK para retornar a la ventana y modificar los datos.";
        }
	return msg;
}


// Funciones asociadas a la validacion de las teclas digitadas en los campos de la aplicacion
function GetPointPosition(tira) {
    // Retornamos la posicion del punto
    var i = 0
    var posPunto = -1
    var pointASCII = 46
    
    while ((i < tira.length) && (posPunto == -1)) {
        if (tira.charAt(i) == String.fromCharCode(pointASCII))
            posPunto = i;
        i++;
    }
    return posPunto;
}


function AdjustDecimal(event, el) {
    // El objetivo de esta funcion es agregar o no un cero segun la posicion del punto
    var posPunto = 0
    var minusASCII = 45
    var pointASCII = 46
    
    posPunto = GetPointPosition(el.value);
    switch (posPunto) {
        case -1: // No hay punto
            if (el.value == "-")
                el.value = "0";
            break;
        case 0:
            if (el.value.length == 1)
                el.value = "0";
            else
                el.value = "0" + el.value;
            break;
        default:
            if ((el.value.search(String.fromCharCode(minusASCII)) == 0) && (posPunto == 1)) { // Si se presenta la combinacion -.*
                if (el.value.length == 2) // El string solo se compone de: "-."
                    el.value = "0";
                else
                    el.value = el.value.replace("-.", "-0.");
            } else {
                if (posPunto == (el.value.length - 1))
                    el.value = el.value + "0";
            }
            break;
    }
    if (bwrValidateIE)
        event.returnValue = true;
    else
        return true;
}


function ValidateDate(event, el) {
    // Validamos que los caracteres proporcionados sean validos para la tira
    var i = 0
    var source = ""
    var result = ""
    
    source = el.value;
    while (source.search("/") != -1) {
        source = source.replace("/", "");
    }
    event.returnValue = true;
    if (source.length == 8) {
        while (i < 8) {
            result = result + source.charAt(i);
            // Agregamos el slash, si aplica
            switch (i) {
                case 1:
                    result = result + "/";
                    break;
                case 3:
                    result = result + "/";
                    break;
                default:
                    break;
            }
            i++;
        }
        el.value = result;
        if (!isValidDate(el.value)) {
            if (parIdioma == "en")
                alert("The value must be a valid date.");
            else
                alert("La fecha proporcionada es inválida.");
            el.value = "";
        }
    } else {
        if (source.length != 0) {
            if (parIdioma == "en")
                alert("The date format must be 'ddmmaaaa'.");
            else
                alert("El formato de la fecha debe ser 'ddmmaaaa'.");
            el.value = "";
        }
    }
}


function ValidateRangeDates(strFechaInicial, strFechaFinal) {
    // El formato de la fecha es ddmmaaaa
    var dia = 0
    var mes = 1
    var anno = 2
    // Fechas
    var fechaInicial = strFechaInicial.split("/")
    var fechaFinal = strFechaFinal.split("/")
    // Errores
    var error

    if ((fechaFinal[anno] * 1) > (fechaInicial[anno] * 1)) {
        error = false;
    } else {
        if ((fechaFinal[anno] * 1) == (fechaInicial[anno] * 1)) {
            if ((fechaFinal[mes] * 1) > (fechaInicial[mes] * 1)) {
                error = false;
            } else {
                if ((fechaFinal[mes] * 1) == (fechaInicial[mes] * 1)) {
                    if ((fechaFinal[dia] * 1) > (fechaInicial[dia] * 1)) {
                        error = false;
                    } else {
                        if ((fechaFinal[dia] * 1) == (fechaInicial[dia] * 1)) {
                            error = false;
                        } else {
                            error = true;
                        }
                    }
                } else {
                    error = true;
                }
            }
        } else {
            error = true;
        }
    }
    // Retornamos el resultado
    return (!error);
}


function ValidateDecimal(event, el, negatives) {
    //Validamos que el caracter proporcionado sea valido para la tira
    var minusASCII = 45
    var pointASCII = 46
    // Variables generales para facilitar le manejo según el navegador
    var tecla, valRetorno

    // Valor de retorno
    valRetorno = true;
    // Tecla presionada
    if (bwrValidateIE)
        tecla = event.keyCode;
    else
        tecla = event.which;
    if (tecla == minusASCII && negatives == true) { // Es un menos y permite negativos
        if (el.value.length > 0) { // Validamos que no haya otro menos en la tira
            valRetorno = false;
            if (el.value.search(String.fromCharCode(minusASCII)) == -1) // No hay un menos en el numero
                el.value = "-" + el.value;
        }
    } else {
        if (tecla == pointASCII) { // Validamos que no haya otro punto en la tira
            if (el.value.length > 0)
                if (GetPointPosition(el.value) != -1) // Ya hay un punto en el numero
                    valRetorno = false;
        } else {
            if (tecla != 0 && tecla != 8)
                if (tecla < 48 || tecla > 57) // Si el caracter no se encuentra en el rango de numeros
                    valRetorno = false;
        }
    }
    if (bwrValidateIE)
        event.returnValue = valRetorno;
    else
        return valRetorno;
}


function ValidateInteger(event, el, negatives) {
    // Validamos que el caracter proporcionado sea valido para la tira
    var minusASCII = 45
    // Variables generales para facilitar le manejo según el navegador
    var tecla, valRetorno

    // Valor de retorno
    valRetorno = true;
    // Tecla presionada
    if (bwrValidateIE)
        tecla = event.keyCode;
    else
        tecla = event.which;
    // Validamos la tecla
    if ((tecla == minusASCII) && (negatives == true)) { // Es un menos y permite negativos
        if (el.value.length > 0) { // Validamos que no haya otro menos en la tira
            valRetorno = false;
            if (el.value.search(String.fromCharCode(minusASCII)) == -1) // No hay un menos en el numero
                el.value = "-" + el.value;;
        }
    } else {
        if (tecla != 0 && tecla != 8) // Es diferente a un caracter de control y al backspace
            if (tecla < 48 || tecla > 57) // Si el caracter no se encuentra en el rango de numeros
                valRetorno = false;
    }
    // ¿Aplicar el evento?
    if (bwrValidateIE)
        event.returnValue = valRetorno;
    else
        return valRetorno;
}


function ValidateNegative(event, el) {
    // Validamos que cualquier menos aparezca solo al inicio de la tira
    var minusASCII = 45
    var valRetorno;

    valRetorno = true;
    switch (el.value.search(String.fromCharCode(minusASCII))) {
        case -1: // Si no hay menos
            break;
        case 0: // Si es el primer caracter
            if (el.value.length == 1)
                el.value = "0";
            break;
        default:
            valRetorno = false;
            alert('El número proporcionado no es válido.');
            break;
    }
    // ¿Aplicar el evento?
    if (bwrValidateIE)
        event.returnValue = valRetorno;
    else
        return valRetorno;
} 


function ValidateIdentifier(event, el, typeIdentifier) {
    // Validamos que los caracteres proporcionados sean validos para la tira
    var i = 0
    var source = ""
    var result = ""
    var valRetorno;
    
    // Eliminamos de la tira fuente los guiones
    source = el.value;
    while (source.search("-") != -1) {
        source = source.replace("-", "");
    }
    // Validacion segun el tipo de identificador
    valRetorno = true;
    if (source != "") {
        switch (eval(typeIdentifier)) {
            case 0: // Cedula Juridica
                if (source.length == 12) {
                    i = 0;
                    while (i < 12) {
                        result = result + source.charAt(i);
                        // Agregamos el guion, si aplica
                        switch (i) {// Ejemplo: 1-231-231232-31
                            case 0: 
                                result = result + "-";
                                break;
                            case 3: 
                                result = result + "-";
                                break;
                            case 9: 
                                result = result + "-";
                                break;
                            default:
                                break;
                        }
                        i++;
                    }
                } else {
                    result = source;
                    el.focus(); // Nos posicionamos en el mismo campo
                    alert("Largo de la identificación incorrecto");
                }
                break;
            case 1: // Cedula de Identidad
                if (source.length == 9) {
                    i = 0;				
                    while (i < 9) {
                        result = result + source.charAt(i);
                        // Agregamos el guion, si aplica
                        switch (i) {// Ejemplo: 1-0123-0456
                            case 0: 
                                result = result + "-";
                                break;
                            case 4: 
                                result = result + "-";
                                break;
                            default:
                                break;
                        }
                        i++;
                    }
                } else {
                    result = source;
                    el.focus(); // Nos posicionamos en el mismo campo
                    alert("Largo de la identificación incorrecto");
                }
                break;
            default: // Cualquier otro tipo de identificador
                result = source;
                break;
        }
    }
    el.value = result;
}

// Verifica si la tecla recibida es una vocal tildada o una eñe

function esCaracterEspannol(tecla){
    /*if( tecla == 225 || tecla == 233 || tecla == 237 || tecla == 243 || tecla == 250 || 
        tecla == 193 || tecla == 201 || tecla == 205 || tecla == 211 || tecla == 218 || 
        tecla == 241 || tecla == 209)/
        return true;
    /*else
        return false;*/
}

/**
 * Usado para validar que se reciban solo caracteres alfanumericos.
 * Valida que la tecla recibida sea solo numero o  letra
 * @param el elemento que hay que validar.
 * @param event evento que dispara la valición.
 * @return true si es valido o false si es invalido.
 */
function validateAlphanumeric(el, event) 
{ 
    //Validamos que el caracter proporcionado sea valido para la tira
    var temp = ""
    //var el = event.srcElement // Obtenemos el elemento fuente

    var tecla, valRetorno;

    if (bwrValidateIE)
    tecla = event.keyCode;
    else
    tecla = event.which; 

    varRetorno = true; // Inicialmente, consideramos que todo esta bien

    if 
    (
        // Caracteres especiales.
        tecla == 0 || tecla == 8 || tecla == 32 || tecla == 58 
        // Letras.
        || (tecla >= 65 && tecla <= 90) || (tecla >= 97 && tecla <= 122)
        // Numeros.
        || (tecla >= 48 && tecla <= 57)  
        // Vocales tildadas y ñ.      
        || tecla == 193 || tecla == 225 || (tecla >= 192 && tecla <= 197) || (tecla >= 224 && tecla <= 229) // A, a 
        || tecla == 211 || tecla == 243 || (tecla >= 210 && tecla <= 214) || (tecla >= 242 && tecla <= 246) // O, o
        || tecla == 201 || tecla == 233 || (tecla >= 200 && tecla <= 203) || (tecla >= 232 && tecla <= 235) // E, e
        || tecla == 205 || tecla == 237 || (tecla >= 204 && tecla <= 207) || (tecla >= 236 && tecla <= 239) // I, i
        || tecla == 218 || tecla == 250 || (tecla >= 217 && tecla <= 220) || (tecla >= 249 && tecla <= 252) // U, u
        || tecla == 209 || tecla == 241 // Ñ, ñ
        // Otros caracteres.
        || tecla == 33 || tecla == 191 || (tecla >= 35 && tecla <= 38)
        || (tecla >= 40 && tecla <= 47)
        || (tecla >= 59 && tecla <= 64)
        || (tecla >= 91 && tecla <= 96)
        || (tecla >= 123 && tecla <= 161)        
    )
    {
        valRetorno = true;
    }
    else
    {
        valRetorno = false;
    }
    
    /*
    if (tecla == 0 || tecla == 8 || tecla == 32 || (tecla >= 44 && tecla >= 46) || tecla == 95 || tecla == 58 || tecla == 59 ) 
    valRetorno = true;
    else
    {
        if ((tecla >= 65 && tecla <= 90) || (tecla >= 97 && tecla <= 122) || (tecla >= 48 && tecla <= 57) 
        || esCaracterEspannol(tecla))
        valRetorno = true;
        else
        {
            if ((tecla >= 160 && tecla <= 165) || (tecla == 130))
            valRetorno = true;
            else
            valRetorno = false;
        }
    }
    */

    // ¿Aplicar el evento?
    if (bwrValidateIE) 
    {
        event.returnValue = valRetorno;
        return valRetorno;
    }
    else
    {
        return valRetorno; 
    }
}

function validateAlphanumericStrict(el, event) 
{
    //Validamos que el caracter proporcionado sea valido para la tira 

    var temp = ""
    //var el = event.srcElement // Obtenemos el elemento fuente

    var tecla, valRetorno;

    if (bwrValidateIE)
    tecla = event.keyCode;
    else 
    tecla = event.which; 

    varRetorno = true; // Inicialmente, consideramos que todo esta bien

    if (tecla == 0 || tecla == 8 || tecla == 32)
    valRetorno = true;
    else 
    {
        if ((tecla >= 65 && tecla <= 90) || (tecla >= 97 && tecla <= 122) || (tecla >= 48 && tecla <= 57) 
        || esCaracterEspannol(tecla))
        valRetorno = true; 
        else
        valRetorno = false;
    }

    // ¿Aplicar el evento?
    if (bwrValidateIE)
    {
        event.returnValue = valRetorno;
        return valRetorno; 
    }
    else
    {
        return valRetorno; 
    }
}

/**
 * Retorna la fecha valida para el período proporcionado con el formato dd/mm/aaaa ó dd/mm/aa.
 * @param unMes mes para que se genera la fecha.
 * @param unAnno año para que se genera la fecha.
 * @return la fecha respectiva si los parámetros son correctos, una hilera vacía en caso contrario.
 */
function ultimoDiaPara(unMes, unAnno) {
    var unDia;
    var unaFecha;
    
    // Generación para el mes de febrero
    if (unMes == 2) {
        if((unAnno % 4) != 0) {
            unDia = 28;
        } else {
            if((unAnno % 400) == 0) {
                unDia = 29; 
            } else {
                if((unAnno % 100) == 0) {
                    unDia = 28;
                } else {
                    unDia = 29;
                }
            }
        }
    } else {
        // Generación para los meses con 30 dias
        if (unMes == 4 || unMes == 6 || unMes == 9 || unMes == 11) {
            unDia = 30;
        } else {
            // Generación para los meses con 31 dias
            unDia = 31;
        }
    }
    
    // Construimos la fecha por retornar
    unaFecha  = (unDia < 10 ? "0" : "") + unDia + "/";
    unaFecha += (unMes < 10 ? "0" : "") + unMes + "/";
    unaFecha += unAnno;
    
    // Fecha válida
    return unaFecha;
}


// FINAL Validate.js ----------------------------------------------------------->