// Navegador
var ie = document.all ? 1 : 0;
var ns = document.layers ? 1 : 0;

// función GENÉRICA para cualquier formulario
//------------------------------------------------------------------------------------------------
function chekea(cual) {
var i, tipo, valor;
	if (cual.elements) {
		for (i=0; i<cual.elements.length; i++) {
			if (cual.elements[i].name != null) {
				if (cual.elements[i].name.substr(0,4) == "chk|") {
					tipo = cual.elements[i].name.split("|");
					valor = cual.elements[i].value;
					//if (valor != null) alert(valor);
					switch (tipo[2]) {
						case "str":
							// Primero veo si es obligatorio RELLENARLO
							if ((valor.length == 0) && tipo[5] == "true") {
								alert("O campo \""+tipo[6]+"\" é OBRIGATORIO");
								if (cual.elements[i].type!="hidden"){
									cual.elements[i].focus();
								}
								return false;
							}
							// Después veo si es menor que el mínimo
							if (tipo[5] == "true" && valor.length < parseInt(tipo[3],10)) {
								alert("O campo \""+tipo[6]+"\" NON pode ser menor de "+tipo[3]+" caracteres");				
								if (cual.elements[i].type!="hidden"){
									cual.elements[i].focus();
								}
								return false;
							}
							// Y por último si es mayor que el máximo
							if (valor.length > parseInt(tipo[4],10)) {
								alert("O campo \""+tipo[6]+"\" NON pode ser meirande que "+tipo[4]+" caracteres");
								if (cual.elements[i].type!="hidden"){
									cual.elements[i].focus();
								}
								return false;
							}
							break;
						case "int":
							// Primero veo si es obligatorio RELLENARLO
							if ((valor.length == 0) && tipo[5] == "true") {
								alert("O campo \""+tipo[6]+"\" é OBRIGATORIO");
								if (cual.elements[i].type!="hidden"){
									cual.elements[i].focus();
								}
								return false;
							}
							// Después compruebo que sea NUMÉRICO
							if (!(esnumerico(valor))) {
								alert("O campo \""+tipo[6]+"\" debe ser un NÚMERO");
								if (cual.elements[i].type!="hidden"){
									cual.elements[i].focus();
									cual.elements[i].select();
								}
								return false;
							}
							// Después veo si es menor que el mínimo
							if (parseInt(valor,10) < parseInt(tipo[3],10)) {
								alert("O campo \""+tipo[6]+"\" NON pode ser menor de "+tipo[3]);
								if (cual.elements[i].type!="hidden"){
									cual.elements[i].focus();
								}
								return false;
							}
							// Y por último si es mayor que el máximo
							if (parseInt(valor,10) > parseInt(tipo[4],10)) {
								alert("O campo \""+tipo[6]+"\" NON pode ser meirande de "+tipo[4]);
								if (cual.elements[i].type!="hidden"){
									cual.elements[i].focus();
									cual.elements[i].select();
								}
								return false;
							}
							break;
						case "date":
							// Primero veo si es obligatorio RELLENARLO
							if ((valor.length == 0) && tipo[5] == "true") {
								alert("O campo \""+tipo[6]+"\" é OBRIGATORIO");
								if (cual.elements[i].type!="hidden"){
									cual.elements[i].focus();
								}
								return false;
							}
							// Después compruebo que sea FECHA
							if (esfecha(valor) != "si" && valor != "") {
								alert("O campo \""+tipo[6]+"\" debe ser de tipo data.\nFormatos válidos:\ndd/mm/aa\ndd/mm/aaaa\nddmmaa\nddmmaaaa\n"+ esfecha(valor));
								if (cual.elements[i].type!="hidden"){
									cual.elements[i].focus();
								}
								return false;
							}
							// Después veo si es menor que el mínimo
							if(tipo[3] != 'x'){
								if (convierte_fecha(valor) < convierte_fecha(tipo[3])) {
									alert("O campo \""+tipo[6]+"\" NON pode ser menor que "+tipo[3]);
									if (cual.elements[i].type!="hidden"){
										cual.elements[i].focus();
									}
									return false;
								}
							}
							// Después veo si es mayor que el máximo
							if(tipo[4] != 'x'){
								if (convierte_fecha(valor) > convierte_fecha(tipo[4])) {
									alert("O campo \""+tipo[6]+"\" NON pode ser meirande que "+tipo[4]);
									if (cual.elements[i].type!="hidden"){
										cual.elements[i].focus();
									}
									return false;
								}
							}
							break;
						case "eml":	//E-mail
							// Primero veo si es obligatorio RELLENARLO
							if ((tipo[5] == "true") && (valor.length == 0)) {
								alert("O campo \""+tipo[6]+"\" é OBRIGATORIO");
								if (cual.elements[i].type!="hidden"){
									cual.elements[i].focus();
								}
								return false;
							}
							// Después compruebo que sea EMAIL válido
							if ((esMail(valor)!=true) && (valor!="")){
								alert("O campo \""+tipo[6]+"\" NON é un email válido");
								if (cual.elements[i].type!="hidden"){
									cual.elements[i].focus();
								}
								return false;
							}
							break;
						case "combo": // Combo
							// Primero veo si es obligatorio RELLENARLO
							if (tipo[5] == "true") {
								// Después comprobamos que sea válido (distinto de -1)
								if (valor == "-1"){
									alert("O campo \""+tipo[6]+"\" é OBRIGATORIO");
									if (cual.elements[i].type!="hidden"){
										cual.elements[i].focus();
									}
									return false;								
								}
							}
							break;
						case "hour":
							// Primero veo si es obligatorio RELLENARLO
							if ((valor.length == 0) && tipo[5] == "true") {
								alert("O campo \""+tipo[6]+"\" é OBRIGATORIO");
								if (cual.elements[i].type!="hidden"){
									cual.elements[i].focus();
								}
								return false;
							}
							// Después compruebo que sea HORA
							if (esHora(valor) != "si" && valor != "") {
								alert("O campo \""+tipo[6]+"\" NON é correcto. "+ esHora(valor));
								if (cual.elements[i].type!="hidden"){
									cual.elements[i].focus();
								}
								return false;
							}
							break;
						case "money":
							//Comprueba que no tenga un punto o una coma solo
							if(valor == "," || valor == "."){
								alert("O campo \""+tipo[6]+"\" debe ser un NÚMERO");
								if(cual.elements[i].type!="hidden"){
									cual.elements[i].focus();
									cual.elements[i].select();
								}
								return false;
							}
							// Primero veo si es obligatorio RELLENARLO
							if ((valor.length == 0) && tipo[5] == "true") {
								alert("O campo \""+tipo[6]+"\" é OBRIGATORIO");
								if (cual.elements[i].type!="hidden"){
									cual.elements[i].focus();
								}
								return false;
							}
							//Compruebo que el número no sea mayor
							if (!(mayorValorMoneda(valor, parseInt(tipo[4],10)))) {
								alert("O campo \""+tipo[6]+"\" é demasiado grande");
								if (cual.elements[i].type!="hidden"){
									cual.elements[i].focus();
								}
								return false;
							}
							// Después compruebo que sea NUMÉRICO, incluyendo los puntos como válidos
							if (!(esnumericomoneda(valor))) {
								alert("O campo \""+tipo[6]+"\" debe ser NUMÉRICO");
								if (cual.elements[i].type!="hidden"){
									cual.elements[i].focus();
									cual.elements[i].select();
								}
								return false;
							}
							// Compruebo que solo tenga 2 decimales
							if (numeroDecimales(valor)>2) {
								alert("O campo \""+tipo[6]+"\" NON pode ter máis de 2 decimais");
								if (cual.elements[i].type!="hidden"){
									cual.elements[i].focus();
									cual.elements[i].select();
								}
								return false;
							}
							break;
						default:
							alert("Non existen restriccións de tipo \""+tipo[2]+"\"");
							return false;
							break;
					}// switch
				}// if nombre contiene chk|
			}// if nombre es distinto de undefined
		}// for que recorre el formulario
	}// if hay elementos 
	return true;
}

//COMPRUEBA que O campo sea numérico
//------------------------------------------------------------------------------------------------
function esnumerico(texto) {
    var valido 	= true; 
	var decimal	= false;
	var miles = false;
    var cadena = "1234567890";
	var i;
    for (i=0;i<texto.length;i++){

		caracter=texto.substr(i, 1);

		if(caracter==","){		// la "," es el símbolo decimal
			if(decimal==false){
				decimal=true;
			}else{
				valido=false;	// se encontro mas de una coma
				break;
			}
		}else{
			if (cadena.indexOf(caracter, 0) == -1){
				valido=false;
				break;
			}
		}
    }
    return valido;
}

//Comprueba el número máximo, excluyendo los puntos(para los de tipo moneda)
//------------------------------------------------------------------------------------------------
function mayorValorMoneda(moneda,maximo){
	//Quitamos todos los puntos de la cifra para poder comparar
	moneda = moneda.replace(/[.]/g,"");
	//Comparamos que el número no exceda del máximo
	if (parseInt(moneda,10) > maximo) {
		return false;
	}else{
		return true;
	}
}

//COMPRUEBA que O campo sea numérico, pero incluyendo los puntos
//------------------------------------------------------------------------------------------------
function esnumericomoneda(texto) {
    var valido 	= true; 
	var decimal	= false;
	var miles = false;
    var cadena = "1234567890.";
	var i;
    for (i=0;i<texto.length;i++){

		caracter=texto.substr(i, 1);
		
		if(caracter==","){		// la "," es el símbolo decimal
			if(decimal==false){
				decimal=true;
			}else{
				valido=false;	// se encontro mas de una coma
				break;
			}
		}else{
			if (cadena.indexOf(caracter, 0) == -1){
				valido=false;
				break;
			}
		}
    }
	if(texto.substr(0,1) == "."){
		valido=false;
	}
	if(texto.substr(0,1) == "," && texto.substr(1,1) == "."){
		valido=false;
	}
    return valido;
}

//COMPRUEBA que el dato sea fecha
//------------------------------------------------------------------------------------------------
function esfecha(dato) {
	
	if (dato != ""){
		var i;
		var tdia, tmes, tano;
		var fecha_split = dato.split('/');
		
		if(fecha_split.length == 3) {
		// FORMATO DE BARRAS: 28/02/1997 ó 28/02/97
			// Comprobamos que sean 3 elementos distintos de 0
			for (i=0; i < fecha_split.length; i++) {
				if (parseInt(fecha_split[i],10) == 0) return "Non existe a data: 0";
			}
			tdia = fecha_split[0];
			tmes = fecha_split[1];
			tano = fecha_split[2];
			
			if ( (tdia.length != 2) || (!esNumeroEstricto(tdia)) ) {return "O día non é correcto";}
			if ( (tmes.length != 2) || (!esNumeroEstricto(tmes)) ) {return "O mes non é correcto";}
			if ( ((tano.length != 4) && (tano.length != 2)) || (!esNumeroEstricto(tano)) ) {return "O ano non é correcto";}
			
		}else if (dato.length == 6 || dato.length == 8){
		// FORMATO sin barras: 28021997 ó 280297
			tdia = dato.substr(0, 2);
			tmes = dato.substr(2, 2);
			tano = dato.substr(4, dato.length);
		}else{
			return "O formato non é correcto";
		}
		
		// AÑADIMOS las 2 primeras cifras al año si le faltan
		if (tano.length == 2){
			if (tano > 20){	// a partir de 21 el año se considera como 1921
				tano = "19"+ tano;	// 1900
			}else{			// hasta 20 el año se considera 2020
				tano = "20"+ tano;	//2000
			}
		}
		
		//SI EL AÑO es menor que 1753 devolvemos error :: 2009/11/12 DETECTAMOS FALLO
		if(tano < 1753){
			return "O ano non é correcto";
		}
		
		// Comprobamos que sea dia/mes/año: 28/02/1997 ó 28/02/97
		var f = convierte_fecha(tdia +"/"+ tmes +"/"+ tano);
		if(f.getDate() != tdia) return "O día non é correcto";
		if(f.getMonth() != (tmes-1)) return "O mes non é correcto";
		if(f.getFullYear() != tano && f.getYear() != tano) return "O ano non é correcto";

		return "si"; //fecha correcta
	}
}


// COMPRUEBA que O campo sea hora (formato HH:MM)
// ------------------------------------------------------------------------------------------------
function esHora(dato) {
var hora_split;
var i;
var thora, tminutos;
	hora_split = dato.split(':');
	
	if(hora_split.length != 2) {return "Debe ter HH:MM";}
	
	thora = parseInt(hora_split[0],10);
	tminutos = parseInt(hora_split[1],10);
	
	if ( (hora_split[0].length != 2) || (!esNumeroEstricto(hora_split[0])) ) {return "A hora non é correcta";}
	if ( (hora_split[1].length != 2) || (!esNumeroEstricto(hora_split[1])) ) {return "Os minutos non son correctos";}

	// Comprobamos si son correctos
	if ((thora) < 0 || (thora > 23)) return "A hora non é correcta";
	if ((tminutos < 0) || (tminutos > 59)) return "Os minutos non son correctos";

	return "si";
}


// DEVUELVE una FECHA
// ------------------------------------------------------------------------------------------------
function convierte_fecha(quien) {
	var fecha_split;	
	var tdia, tmes, tano;
	fecha_split = quien.split('/');
	tdia = parseInt(fecha_split[0],10);
	tmes = parseInt(fecha_split[1],10);
	tano = parseInt(fecha_split[2],10);
	return date = new Date(tano,tmes-1,tdia);
}


// COMPRUEBA que el dato sea un número
// ------------------------------------------------------------------------------------------------
function esNumeroEstricto(dato){
	var i;
	for(i=0;i<dato.length;i++){
		if (dato.charAt(i)>'9' || dato.charAt(i)<'0') { return false;}
	}
	return true;
}


// AÑADE un 0 a la izda de un nº de una cifra
// ------------------------------------------------------------------------------------------------
function numDosCifras(num){
	var aux =num;
	if (num < 10){
		aux = "0" + aux;
	}
	return aux;
}


// VALIDA un email
//------------------------------------------------------------------------------------------------
function esMail(texto){
    var valido = true;             
    var cadena = "abcdefghijklmnñopqrstuvwxyzABCDEFGHIJKLMNÑOPQRSTUVWXYZ1234567890@._-";
    var arroba = texto.indexOf("@", 0);
    if ((texto.lastIndexOf("@")) != arroba) arroba = -1;
    var punto = texto.lastIndexOf(".");
	var i;
    for (i=0 ;i<texto.length;i++){
		if (cadena.indexOf(texto.substr(i, 1),0) == -1){
			valido = false;
			break;
    	}
    }
	if ((arroba > 1) && (arroba + 1 < punto) && (punto + 1 < (texto.length)) && (valido == true) && (texto.indexOf("..",0) == -1)){
    	valido = true;
	}else{
		valido = false;
	}
    return valido;
}


// PIDE confirmación para enviar los ids de varios checkbox de un listado
// -----------------------------------------------------------------------------------------------
function chekeaLstCheckbox(destino, frm, txtAccion){
	var seguir;
	var ids;
	var pregunta;
	
	ids = "";
	seguir = false;
  	for(i=0;i<document.forms[frm].elements.length;i++){
		var e = document.forms[frm].elements[i];
	 	if ((e.type=='checkbox') && (e.checked==true) && (e.name=="borrar")) {
			ids+=e.value+',';
			seguir = true;
		}
	}

	if(seguir==false){
		alert("Debe seleccionar polo menos un rexistro");
	}else{
		pregunta = "¿Desexa "+ txtAccion +" os rexistros seleccionados?";
/*
		if(destino.indexOf("cEmpresasNotificarInscripcion.asp")) {
			pregunta = txtAccion;
		}
*/
		if(confirm(pregunta)==true){
			document.location.href=destino+"&ids="+ids.substr(0, ids.length-1);
		}
	}
}


// CAMBIA el nº de registros por página
// ------------------------------------------------------------------------------------------------
function cambiaPagina(destino, varIndice, pagNumRs){
	if ((isNaN(pagNumRs)==false && pagNumRs!="")){
		if (destino.indexOf("?")== -1){
			document.location.href = destino +"?"+ varIndice +"="+ pagNumRs;
		}else{
			document.location.href = destino +"&"+ varIndice +"="+ pagNumRs;
		}
	}
}


// MARCA todos los check al pulsar uno
// frm es el nombre del formulario que contiene los checkbox
// -----------------------------------------------------------------------------------------------
function marcaCheckbox(frm){
	var e;
  	for(i=0;i<document.forms[frm].elements.length;i++){
		e = document.forms[frm].elements[i];
	 	if ((e.name != 'marcaTodosCheckbox') && (e.type=='checkbox') && (!e.disabled)) {
			e.checked = document.forms[frm].marcaTodosCheckbox.checked;
		}
	}
}

// Popup
// -----------------------------------------------------------------------------------------------
function abrePop(cual, nombre, alto, ancho, ajustable, scroll) {
	var donde_x, donde_y;
	donde_x = (screen.width - ancho) / 2;
	donde_y = (screen.height - alto) / 2;
	abrePopPosicion(cual, nombre, alto, ancho, ajustable, scroll, donde_x, donde_y)
}
function abrePopPosicion(cual, nombre, alto, ancho, ajustable, scroll, donde_x, donde_y) {
	var ventana;
	if (ie) {
		window.open(cual, nombre, 'toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars='+scroll+', resizable='+ajustable+', copyhistory=no, width='+ancho+', height='+alto+', top='+donde_y+', left='+donde_x+'');
	} else if (ns) {
		window.open(cual, nombre,'width=740,height=500,location=no,toolbar=no,directories=no,menubar=no,resizable='+ajustable+',scrollbars=yes,status=no, top='+donde_y+', left='+donde_x+'');		
	} else {
		window.open(cual, nombre, 'left=0,top=0,width='+ancho+',height='+alto+',location=no,toolbar=no,directories=no,menubar=no,resizable='+ajustable+',scrollbars='+scroll+',status=no, top='+donde_y+', left='+donde_x+'');		
	}
}

// Redirige pa pagina de documentos para guardarlo
// -----------------------------------------------------------------------------------------------
function eliminaArchivoDocumento(formulario){
	if(confirm("¿Está seguro de querer eliminar o arquivo?")){
		formulario.eliminarArchivo.value = "si";
		formulario.submit();
	}
}

// DEVUELVE el nº de elementos seleccionados en un combo
// -----------------------------------------------------------------------------------------------
function dameNumSel(objetoSelect){
	var seleccionadas = 0 ;
	for (var i=0; i < objetoSelect.options.length; i++){
		if (objetoSelect.options[i].selected){
			seleccionadas ++;
		}
	}
	return seleccionadas; 
}

// MUEVE los elementos de un combo a otro
// -----------------------------------------------------------------------------------------------
function traspasaElementosCombos(comboFuente, comboDestino){
	var nuevoElementoDestino;
	var arrayElementosTraspasados = new Array();
	var i;
	
	if (dameNumSel(comboFuente) == 0){
		// comprobamos si hay elementos seleccionados
		alert("Debe seleccionar polo menos un rexistro");
		comboFuente.focus();
	}else{
		// movemos los seleccionamos
		for (i=0; i < comboFuente.options.length; i++){ 
			if (comboFuente.options[i].selected){
				nuevoElementoDestino = new Option(comboFuente.options[i].text, comboFuente.options[i].value);
				comboDestino.options[comboDestino.options.length] = nuevoElementoDestino;
				arrayElementosTraspasados[arrayElementosTraspasados.length] = i;
			}
		}
		// borramos los traspasados del combo fuente
		arrayElementosTraspasados.reverse(); // le damos la vuelta para borrar correctamente
		for (i=0; i < arrayElementosTraspasados.length; i++){
			comboFuente.options[arrayElementosTraspasados[i]] = null;
		}
	}
}


// VUELCA la información de un combo a un campo de texto
// -----------------------------------------------------------------------------------------------
function vuelcaElementosCombo(combo, campoIds){
	// almacenamos los menús seleccionados en O campo oculto
	for (i=0; i < combo.options.length; i++){
		campoIds.value += combo.options[i].value+",";
	}
}


// COMPARA 2 campos de claves, para ver que son iguales.
// -----------------------------------------------------------------------------------------------
function chekeaClaves(clave1, clave2) {
	var valor1 = clave1.value; 
	var valor2 = clave2.value;
	if (valor1 != valor2) {
		alert("As chaves non coinciden.");
		return false;
	}else{
		return true;
	}
}

// DEVUELVE el nº de decimales de un número
// -----------------------------------------------------------------------------------------------
function numeroDecimales(numero){
	if(numero.indexOf(",")>0){
		var aux = numero.split(",");
		return aux[1].length;
	}else{
		return 0;
	}
}

// formatea un texto para javascript
// -----------------------------------------------------------------------------------------------
function formatoJS(texto){
	texto = texto.replace("\n", "");	// nueva linea
	texto = texto.replace("\r", "");	// tabulador
	texto = texto.replace("\t", "");	// retorno de carro
	texto = texto.replace("\f", "");	// alimentacion de formulario
	texto = texto.replace("\b", "");	// retroceso de un espacio
	return texto;
}

// CREA un objeto para AJAX según disponibilidad del navegador
// -----------------------------------------------------------------------------------------------
function GetXmlHttpObject() {
	var objXMLHttp = null;
	if (window.XMLHttpRequest) {
		objXMLHttp = new XMLHttpRequest();
	} else if (window.ActiveXObject) {
		objXMLHttp = new ActiveXObject("Microsoft.XMLHTTP");
	}
	return objXMLHttp;
}

// EJECUTA un procedimiento con ajax y llama a la funcion correspondiente para tratar el resultado
// -----------------------------------------------------------------------------------------------
function ejecutaAjax(pagina, funcionJS) {
	var devolver, funcion;
	devolver = "";
	var xmlHttp = GetXmlHttpObject();
	if (xmlHttp==null) {
		alert ("Browser does not support HTTP Request");
		//return;
	}
	xmlHttp.onreadystatechange = function(){
//	alert(xmlHttp.responseText);
		if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete") {
			if (xmlHttp.responseText == -1000){ // id incorrecto
				devolver = "";
			}else{	// id correcto
				devolver = xmlHttp.responseText;
			}
			eval(funcionJS+"('"+formatoJS(devolver)+"');");
		}
	};
	xmlHttp.open("GET", pagina, true);
	xmlHttp.send(null);
}

// PIDE confirmación para cambiar de quenda los participantes de los equipos
// -----------------------------------------------------------------------------------------------
function confirmaCambioQuenda(destino, frm, pregunta){
	var seguir;
	var ids;
	var idQuenda = document.getElementById("idQuenda").value;

	var nombreQuenda = document.getElementById("idQuenda").options[document.getElementById("idQuenda").selectedIndex].text;
	var fechaQuenda = nombreQuenda.substring(0, 8);

	ids = "";
	seguir = false;

  	for(i=0;i<document.forms[frm].elements.length;i++){
		var e = document.forms[frm].elements[i];
	 	if ((e.type=='checkbox') && (e.checked==true) && (e.name=="borrar")) {
			ids+=e.value+',';
			seguir = true;
		}
	}

	if(seguir==false){
		alert("Debe seleccionar polo menos un rexistro");
	}else{
		if(idQuenda == "") {
			alert("Debe seleccionar a quenda á que quere cambiar os participantes");
		} else {
			pregunta = pregunta.replace("#fecha#", fechaQuenda);
			if(confirm(pregunta)==true){
				document.location.href=destino+"&idQuenda="+idQuenda+"&ids="+ids.substr(0, ids.length-1);
			}
		}
	}
}

// DESHABILITA los combos de la página
// -----------------------------------------------------------------------------------------------
function deshabilitaCombos(obj){
	switch(obj.name) {
	case "bsqIdPrograma":
		document.frmBuscador.bsqIdModalidad.disabled = true;
		document.frmBuscador.bsqIdSubCategoria.disabled = true;
		document.frmBuscador.bsqIdCategoria.disabled = true;
		break;
	case "bsqIdModalidad":
		document.frmBuscador.bsqIdCategoria.disabled = true;
		document.frmBuscador.bsqIdSubCategoria.disabled = true;
		break;
	case "bsqIdCategoria":
		document.frmBuscador.bsqIdSubCategoria.disabled = true;
		break;
	}
}

// HABILITA las cajas del formulario para edicion
// -----------------------------------------------------------------------------------------------
function habilitaCajas(obj){
	if(obj.checked == true) {
		$("caja1_"+obj.value).disabled=false;
		$("caja2_"+obj.value).disabled=false;
	}
}