//--- INICIO --- Función que devuelve si un valor es numérico
function IsNumeric(valor){ 
	var log=valor.length;
	var sw="S"; 
	for (x=0; x<log; x++) {
		v1=valor.substr(x,1); 
		v2 = parseInt(v1); 
		//Compruebo si es un valor numérico 
		if (isNaN(v2)) { sw= "N";} 
	} 
	if (sw=="S") {return true;} else {return false; } 
} 
//--- FIN ---


//--- INICIO --- Función para seleccionar el texto de un campo Input
function seleccionarTexto(obj) { 
    var valor_input = obj.value; 
    var longitud = valor_input.length; 

    if (obj.setSelectionRange) { 
        obj.focus(); 
        obj.setSelectionRange (0, longitud); 
    } 
    else if (obj.createTextRange) { 
        var range = obj.createTextRange() ; 
        range.collapse(true); 
        range.moveEnd('character', longitud); 
        range.moveStart('character', 0); 
        range.select(); 
    } 
} 
//--- FIN ---


//--- INICIO --- Funciones para cambiar el color del elemento que tiene el foco
// Dentro de la etiqueta FORM incluir: onKeyUp="highlight(event)" onClick="highlight(event)"
var highlightcolor="#FFFFDD"

var ns6=document.getElementById&&!document.all
var previous=''
var eventobj

var intended=/INPUT|TEXTAREA|SELECT|OPTION/

function checkel(which){
	if (which.style&&intended.test(which.tagName)){
		if (ns6&&eventobj.nodeType==3)
			eventobj=eventobj.parentNode.parentNode
			return true
	}
	else
		return false
}

function highlight(e){
	eventobj=ns6? e.target : event.srcElement
	if (previous!=''){
		if (checkel(previous))
			if (previous.type != "radio" && eventobj.disabled == false) { previous.style.backgroundColor='' }
			previous=eventobj
		//if (checkel(eventobj))
			//if (eventobj.type != "radio" && eventobj.disabled == false) { eventobj.style.backgroundColor=highlightcolor }
	}else{
		if (checkel(eventobj))
			if (eventobj.type != "radio" && eventobj.disabled == false) { eventobj.style.backgroundColor=highlightcolor }
			previous=eventobj
			//if (eventobj.type == "text") { eventobj.select() }
		}
}
//--- FIN ---


//--- INICIO --- Función genérica de validación de formularios
/* Incluir dentro de la página antes de la declaración de la función
	var camposObligatorios = Array("sNombre", "sApellidos");
	var nombreCampos = Array("Nombre", "Apellidos");
*/
function validarCampos(formulario){
	var mensaje = "\nDebe completar los siguientes campos:      \n\n";
	var longMensaje = mensaje.length;
	
	for (var i = 0; i < camposObligatorios.length; i++){
		var obj = formulario.elements[camposObligatorios[i]];
		if (obj){
			switch(obj.type){
			case "select-one":
				if (obj.selectedIndex == -1 || obj.options[obj.selectedIndex].value == ""){
					mensaje += "   - " + nombreCampos[i] + "\n";
				}
				break;
			case "select-multiple":
				if (obj.selectedIndex == -1){
					mensaje += "   - " + nombreCampos[i] + "\n";
				}
				break;
			case "text":
			case "password":
			case "textarea":
				if (obj.value == "" || obj.value == null){
					mensaje += "  -  " + nombreCampos[i] + "\n";
				}
				break;
			default:
			}
			if (obj.type == undefined){
				var blnchecked = false;
				for (var j = 0; j < obj.length; j++){
					if (obj[j].checked){
						blnchecked = true;
					}
				}
				if (!blnchecked){
					mensaje += "   - " + nombreCampos[i] + "\n";
				}
			}
		}
	}
	if (mensaje.length == longMensaje){
		return true;
	}else{
		alert(mensaje);
		return false;
	}
}
//--- FIN ---


//--- INICIO --- Función para cambiar el foco pulsando Enter
// Dentro de cada campo incluir: onkeypress="return controlarEnter(this, event)"
function controlarEnter (field, event) {
	var keyCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
	if (keyCode == 13) {
		var i;
		for (i = 0; i < field.form.elements.length; i++)
			if (field == field.form.elements[i])
				break;
				i = (i + 1) % field.form.elements.length;
				field.form.elements[i].focus();
				return false;
	} 
	else
		return true;
}      
//--- FIN ---


//--- INICIO --- Funciones para restrigir el tipo de caracteres que se pueden introducir en un campo
// Dentro del campo en cuestion incluir: onKeyPress="soloNumeros()"  o  onKeyPress="soloNumerosLetras()"
function soloNumerosLetras(){
	var key=window.event.keyCode;
	if (key<48 || (key>57 && key < 65) || (key > 90 && key<97) || key>122){
		window.event.keyCode=0;
	}
}
function soloNumeros(){
	var key=window.event.keyCode;
	if (key<48 || key>57){
		window.event.keyCode=0;
	}
}
function soloLetras(){
	var key=window.event.keyCode;
	if (key<57 || (key>57 && key < 65) || (key > 90 && key<97) || key>122){
		window.event.keyCode=0;
	}
}
function soloNumerosDecimales(){
	var key=window.event.keyCode;
	if (key<48 || key>57){
		window.event.keyCode=0;
	}
	if (key==46 || key==44){
		if (document.getElementById(window.event.srcElement.id).value.indexOf(",") == -1){
			window.event.keyCode=44;
		}else{
			window.event.keyCode=0;
		}
	}
}
function soloCaracteres(sCaracteres){ // Solo permite escribir los caracteres pasados por parámetros
	var key=window.event.keyCode;
	var nLongitud = sCaracteres.length;
	var bValido = false;
	for(var i=0; i<nLongitud; i++){
		if(sCaracteres.charCodeAt(i) == key){
			bValido = true;
			break;
		}
	}
	if(!bValido){window.event.keyCode=0}
}
function bloquearCaracteres(sCaracteres){ // Permite escribir cualquier caracter excepto los pasados por parámetros
	var key=window.event.keyCode;
	var nLongitud = sCaracteres.length;
	var bValido = true;
	for(var i=0; i<nLongitud; i++){
		if(sCaracteres.charCodeAt(i) == key){
			bValido = false;
			break;
		}
	}
	if(!bValido){window.event.keyCode=0}
}
//--- FIN ---


//--- INICIO --- Función para calcular la letra del DNI
function letraDNI(nif){
	var cadena = 'TRWAGMYFPDXBNJZSQVHLCKE';
	var nifnum = parseInt(nif, 10);
	var posicion = nifnum % 23;
	return cadena.charAt(posicion);
}
//--- FIN ---


//--- INICIO --- Función que comprueba si un año es bisiesto
function esBisiesto(anno){
	if (anno%4 == 0){
			if (anno%100 == 0 && anno%400 != 0){
				return false;
			}else{
				return true;
			}
	}else{
		return false;
	}
}
//--- FIN ---


//--- INICIO --- Función que comprueba si una dirección email tiene un formato válido (xxxxxxx@xxxxxx.xxx)
function validarEmail(email) {
	if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(email)){
		return (true)
	} else {
		return (false);
	}
}
//--- FIN ---

//--- INICIO --- Función que comprueba si una dirección URL tiene un formato válido (http:// https// ftp://)
function validarURL(url){
	if(/(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/.test(url)){
//	if(/^(ht|f)tp(s?)\:\/\/\w+(\.\w+)*\.\w{2,3}$/.test(url)){
//	if(/^(ht|f)tps?:\/\/\w+([\.\-\w]+)?\.([a-z]{2,3}|info|mobi|aero|asia|name)(:\d{2,5})?(\/)?((\/).+)?$/i.test(url)){
		return (true)
	} else {
		return (false);
	}
}
//--- FIN ---

//--- INICIO --- Función que comprueba si una hora tiene formato hh:mm y la hora es válida
function validarHora(hora) {
	if (/((0[0-9]|1[0-9]|2[0-3]):[0-5][0-9])/.test(hora)){
		return (true)
	} else {
		return (false);
	}
}
//--- FIN ---

//--- INICIO --- Función que despliega un calendario para guardar una fecha en un campo de texto
function mostrarCalendario(campo){
	url = "../../funciones/Calendar.asp?dFecha=" + campo.value;
	ancho = 280;
	alto = 330;
	hor = (screen.width - ancho)/2;
	vert = (screen.height - alto)/2;
	propiedades = eval("'dialogHeight:" + alto + "px; dialogWidth:" + ancho + "px; dialogTop:" + vert + "px; dialogLeft:" + hor + "px; edge=raised; help=0; resizable=0; scroll=0; status=0'")
	fechaDevuelta = window.showModalDialog(url,"", propiedades);
	if (fechaDevuelta != undefined) {
		campo.value = fechaDevuelta;
	};
}
//--- FIN ---





//--- INICIO --- Función que formatea un campo de fecha mientras escribes
// Dentro de la etiqueta INPUT incluir: onKeyUp="this.value=escribeFecha(this.value);"
// También es util incluir en el INPUT:
//			onKeyPress="soloNumeros();" 	-- Para que mejorar la validación de números
//			onBlur="formateaFecha(this);"   -- Para formatear el año a 4 dígitos
function escribeFecha(fecha){ 
	var long = fecha.length; 
	var dia, mes, ano;
	var primerslap = (fecha.indexOf("/") > 0);
	var segundoslap = (fecha.indexOf("/") > 0 && fecha.indexOf("/") != fecha.lastIndexOf("/"));

	if ((long>=2) && (primerslap==false)) {
		dia=fecha.substr(0,2); 
		if ((IsNumeric(dia)==true) && (dia<=31) && (dia!="00")) {
			fecha=fecha.substr(0,2)+"/"+fecha.substr(3,7); primerslap=true;
		} else {
			fecha=""; primerslap=false;
		} 
	} else {
		dia=fecha.substr(0,1); 
		if (IsNumeric(dia)==false){fecha="";} 
		if ((long<=2) && (primerslap=true)) {fecha=fecha.substr(0,1); primerslap=false; } 
	} 

	if ((long>=5) && (segundoslap==false)){
		mes=fecha.substr(3,2); 
		if ((IsNumeric(mes)==true) && (mes<=12) && (mes!="00")){
			fecha=fecha.substr(0,5)+"/"+fecha.substr(6,4); segundoslap=true;
		} else {
			fecha=fecha.substr(0,3);; segundoslap=false;
		} 
	} else {
		if ((long<=5) && (segundoslap=true)) { fecha=fecha.substr(0,4); segundoslap=false; }
	} 

	if (long>=7){
		ano=fecha.substr(6,4); 
		if (IsNumeric(ano)==false){
			fecha=fecha.substr(0,6);
		} else {
			if (long==10){
				if ((ano==0) || (ano<1900) || (ano>2100)){
					fecha=fecha.substr(0,6);
				}
			}
		} 
	} 

	if (long>=10){ 
		fecha=fecha.substr(0,10); 
		dia=fecha.substr(0,2); 
		mes=fecha.substr(3,2); 
		ano=fecha.substr(6,4); 
		// Año no bisiesto y es febrero y el dia es mayor a 28 
		if ( (ano%4 != 0) && (mes ==02) && (dia > 28) ) { fecha=fecha.substr(0,2)+"/"; } 
	} 
	return (fecha); 
} 

function formateaFecha(obj){
	var fecha = obj.value;
	var dia = fecha.substr(0,2); 
	var mes = fecha.substr(3,2); 
	var ano = fecha.substr(6,4); 
	var sFecha;
	var oFecha = new Date();
	
	if(obj.value.length > 0){
		if(IsNumeric(dia) && IsNumeric(mes) && IsNumeric(ano) && dia.length > 0 && mes.length > 0 && ano.length > 0){
			oFecha.setFullYear(ano,mes - 1,dia);
			if(oFecha.getYear() > 99 && oFecha.getYear() < 1900){
				seleccionarTexto(obj);
				alert('Fecha no válida');
			}else{
				if(ano.length <= 2){
					anno = oFecha.getYear();
					if(anno < 50){
						anno += 2000;
					}else{
						anno += 1900;
					}
					sFecha = dia + '/' + mes + '/' + anno.toString();
					obj.value = sFecha
				}
			}
		}else{
			seleccionarTexto(obj);
			alert('Fecha no válida');	
		}
	}
}
//--- FIN ---

//--- INICIO --- Función que formatea un campo de hora mientras escribes
// Dentro de la etiqueta INPUT incluir: onKeyUp="escribeHora(this);"
// También es util incluir en el INPUT:
//			onKeyPress="soloNumeros();" 	-- Para permitir escribir sólo números
//			onBlur="formateaHora(this);"   -- Para completar y validar la hora
function escribeHora(obj){ 
	var hora = obj.value;
	var key=window.event.keyCode;
	var long = hora.length; 
	var horas; 
	var minutos;
	var dospuntos = (hora.indexOf(":") > 0);

	if (key == 190){
		if (!dospuntos){
			horas=hora.substr(0,2); 
			if ((IsNumeric(horas)==true) && (parseInt(horas,10)<=23) && (parseInt(horas,10)>=0)) {
				hora=hora.substr(0,2)+":"+hora.substr(3,2);
			} else {
				hora="";
			} 
			obj.value = hora; 
		}
	}

	if ((key>=48 && key<=57) || (key>=96 && key<=105)){
		if ((long>=2) && (dospuntos==false)) {
			horas=hora.substr(0,2); 
			if ((IsNumeric(horas)==true) && (parseInt(horas,10)<=23) && (parseInt(horas,10)>=0)) {
				hora=hora.substr(0,2)+":"+hora.substr(3,2);
			} else {
				hora="";
			} 
		} else {
			horas=hora.substr(0,1); 
			if (IsNumeric(horas)==false){hora="";} 
			if ((long<=2) && (dospuntos=true)) {hora=hora.substr(0,1); } 
		} 
		obj.value = hora; 
	}
} 

function formateaHora(obj){
	var hora = obj.value;
	var horas = '', minutos = '';
	var separador = hora.indexOf(":")
	var horaValida = false;

	if(obj.value.length > 0){
		if (separador > 0){
			horas = hora.substr(0,separador); 
			minutos = hora.substr(separador + 1,2); 
		} else {
			horas = hora;
		}
		if (minutos.length == 0) { minutos = '0' };
	
		if(IsNumeric(horas) && IsNumeric(minutos) && horas.length > 0 && minutos.length > 0 && horas.length <= 2 && minutos.length <= 2){
			if (parseInt(horas,10) <= 23 && parseInt(minutos,10) <= 59){
				horas = '0' + horas;
				minutos = '0' + minutos;
				obj.value = horas.substr(horas.length-2,2) + ':' + minutos.substr(minutos.length-2,2)
				horaValida = true;
			} else {
				seleccionarTexto(obj);
				alert('Hora no válida');	
			}
		} else {
			seleccionarTexto(obj);
			alert('Hora no válida');	
		}
	}
}
//--- FIN ---

function compararHoras(hora1, hora2) { 
    var arHora1 = hora1.split(":"); 
    var arHora2 = hora2.split(":"); 
     
    var hh1 = parseInt(arHora1[0],10); 
    var mm1 = parseInt(arHora1[1],10); 
    var hh2 = parseInt(arHora2[0],10); 
    var mm2 = parseInt(arHora2[1],10); 

    if (hh1<hh2 || (hh1==hh2 && mm1<mm2)) return "menor"; 
    else if (hh1>hh2 || (hh1==hh2 && mm1>mm2)) return "mayor"; 
    else return "igual"; 
}

function generarPassword(longitud, mayusculas, numeros, minusculas){
	mayusculas = typeof(mayusculas) != 'undefined' ? mayusculas : true;
	numeros = typeof(numeros) != 'undefined' ? numeros : true;
	minusculas = typeof(minusculas) != 'undefined' ? minusculas : true;

    if (!mayusculas && !minusculas && !numeros)	return "";

    var aux = "";
    var num;
    var repetir;
    TotalCaracteres = 26 * 2 + 10;	//26 (a-z) + 26 (A-Z) + 10 (0-9)	//a-z = 97-122	//A-Z = 65-90	//0-9 = 48-57

    for (i = 1; i <= longitud; i++)	{
        repetir = false;
        num = Math.floor(Math.random()*TotalCaracteres);

        if (num < 26)
            if (minusculas)
                aux = aux + String.fromCharCode(num + 97);
            else
                repetir = true;
        else if (num < 52)
            if (mayusculas)
                aux = aux + String.fromCharCode(num - 26 + 65);
            else
                repetir = true;
        else if (num < 62)
            if (numeros)
                aux = aux + String.fromCharCode(num - 52 + 48);
            else
                repetir = true;

        if (repetir) i--;
	}
    return aux;
}

function seleccionarElementoEnCombo(src,texto) {
   var combo = src;
   var total = src.length;
   for (i = 0; i < total; i++) {
      if (combo[i].text == texto) {
         combo[i].selected = true;
      }   
   }
}

function vaciaCombo(id, texto){
	combo = document.getElementById(id);
	combo.length=0;
	var nuevaOpcion = document.createElement("option");
	nuevaOpcion.value = "";
	nuevaOpcion.innerHTML = texto;
	combo.appendChild(nuevaOpcion);
	combo.disabled=true;
}

function cambiarImagen2Estados(src){
	sIdActivo = src.id + '(1)';
	sIdInactivo = src.id + '(0)';
	if(src.value == "0"){
		document.getElementById(sIdActivo).style.display = 'none';
		document.getElementById(sIdInactivo).style.display = 'inline';
	}else{
		document.getElementById(sIdInactivo).style.display = 'none';
		document.getElementById(sIdActivo).style.display = 'inline';
	}
}

function cambiarCombo2Estados(src){
	var sIdCombo = new String(src.id);
	sIdCombo = sIdCombo.substring(0,sIdCombo.length - 3);
	combo = document.getElementById(sIdCombo);
	if(combo.value == "0"){
		combo.value = "1";
	}else{
		combo.value = "0";
	}
	cambiarImagen2Estados(combo);
}

function cambiarImagen3Estados(src){
	sIdNada = src.id + '(0)';
	sIdInactivo = src.id + '(1)';
	sIdActivo = src.id + '(2)';
	if(src.value == "0"){
		document.getElementById(sIdNada).style.display = 'inline';
		document.getElementById(sIdActivo).style.display = 'none';
		document.getElementById(sIdInactivo).style.display = 'none';
	}
	if(src.value == "1"){
		document.getElementById(sIdNada).style.display = 'none';
		document.getElementById(sIdInactivo).style.display = 'inline';
		document.getElementById(sIdActivo).style.display = 'none';
	}
	if(src.value == "2"){
		document.getElementById(sIdNada).style.display = 'none';
		document.getElementById(sIdInactivo).style.display = 'none';
		document.getElementById(sIdActivo).style.display = 'inline';
	}
}

function cambiarCombo3Estados(src){
	var sIdCombo = new String(src.id);
	sIdCombo = sIdCombo.substring(0,sIdCombo.length - 3);
	combo = document.getElementById(sIdCombo);
	if(combo.value == "0"){
		combo.value = "1";
	}else{
		if(combo.value == "1"){
			combo.value = "2";
		}else{
			combo.value = "0";
		}
	}
	cambiarImagen3Estados(combo);
}
