// Navegador
//------------------------------------------------------------------------------------------------
var ie = document.all ? 1 : 0;
var ns = document.layers ? 1 : 0;

// MENU DESPLEGABLE: CORRIGE defectos de IE para mostrar el menú emergente 
// Oculta los SELECT que hay en la página y pone al li la clase over para que funcione con el evento
// -----------------------------------------------------------------------------------------------
function iniciaMenuDesplegable() {
	if (document.all && document.getElementById) {
		if (document.getElementById("menuDesplegable1")) {
			navRoot = document.getElementById("menuDesplegable1");
			for (i=0; i < navRoot.childNodes.length; i++) {
				node = navRoot.childNodes[i];
				if (node.nodeName == "LI") {
					selects = document.getElementsByTagName("select");
					node.onmouseover = function() {
						this.className += " over";
						// ocultamos los combos
						for (i = 0; i != selects.length; i++) {
							selects[i].style.visibility = "hidden";
						}
					}
					node.onmouseout = function() {
						this.className = this.className.replace(" over", "");
						// mostramos los combos
						for (i = 0; i != selects.length; i++) {
							selects[i].style.visibility = "visible";
						}
					}
				}
			}
		} 
		if (document.getElementById("menuDesplegable2")) {
			navRoot = document.getElementById("menuDesplegable2");
			for (i=0; i < navRoot.childNodes.length; i++) {
				node = navRoot.childNodes[i];
				if (node.nodeName == "LI") {
					selects = document.getElementsByTagName("select");
					node.onmouseover = function() {
						this.className += " over";
						// ocultamos los combos
						for (i = 0; i != selects.length; i++) {
							selects[i].style.visibility = "hidden";
						}
					}
					node.onmouseout = function() {
						this.className = this.className.replace(" over", "");
						// mostramos los combos
						for (i = 0; i != selects.length; i++) {
							selects[i].style.visibility = "visible";
						}
					}
				}
			}			
		} 
		if (document.getElementById("menuDesplegable3")) {
			navRoot = document.getElementById("menuDesplegable3");
			for (i=0; i < navRoot.childNodes.length; i++) {
				node = navRoot.childNodes[i];
				if (node.nodeName == "LI") {
					selects = document.getElementsByTagName("select");
					node.onmouseover = function() {
						this.className += " over";
						// ocultamos los combos
						for (i = 0; i != selects.length; i++) {
							selects[i].style.visibility = "hidden";
						}
					}
					node.onmouseout = function() {
						this.className = this.className.replace(" over", "");
						// mostramos los combos
						for (i = 0; i != selects.length; i++) {
							selects[i].style.visibility = "visible";
						}
					}
				}
			}			
		}
		
	}
}
// Popups
//------------------------------------------------------------------------------------------------
function abrePop(cual, nombre, alto, ancho, ajustable, scroll) {
	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=0, left=0');
	} 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');		
	} else {
		window.open(cual, nombre, 'left=0,top=0,width='+ancho+',height='+(alto+5)+',location=no,toolbar=no,directories=no,menubar=no,resizable='+ajustable+',scrollbars='+scroll+', status=no');
	}
}

// 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 && 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 "mce":	// editor MCE
						valor = tinyMCE.getContent();
						// Primero veo si é OBRIGATORIO RELLENARLO
						if ((valor.length == 0) && tipo[5] == "true") {
							alert("O campo \""+tipo[6]+"\" é OBRIGATORIO");
							tinyMCE.execCommand("mceFocus", cual.elements[i].name);// ERROR: NON sitúa el cursor
							return false;
						}
						// Después veo si é 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 é 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 "str":	// alfanumérico
						// Primero veo si é OBRIGATORIO 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 é 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 é 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":	// numerico
						// Primero veo si é OBRIGATORIO 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 NUMÉRICO");
							if (cual.elements[i].type!="hidden"){
								cual.elements[i].focus();
								cual.elements[i].select();
							}
							return false;
						}
						// Después veo si é menor que el mínimo
						if (parseInt(valor,10) < parseInt(tipo[3],10)) {
							alert("O campo \""+tipo[6]+"\" NON pode ser menor que "+tipo[3]);
							if (cual.elements[i].type!="hidden"){
								cual.elements[i].focus();
							}
							return false;
						}
						// Y por último si é mayor que el máximo
						if (parseInt(valor,10) > parseInt(tipo[4],10)) {
							alert("O campo \""+tipo[6]+"\" NON pode ser meirande que "+tipo[4]);
							if (cual.elements[i].type!="hidden"){
								cual.elements[i].focus();
								cual.elements[i].select();
							}
							return false;
						}
						break;
					case "date":	// fecha
						// Primero veo si é OBRIGATORIO 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 (validaFecha(valor) != "ok" && valor != "") {
							alert("O campo \""+tipo[6]+"\" debe ser de tipo data: DD/MM/AAAA\n"+validaFecha(valor));
							if (cual.elements[i].type!="hidden"){
								cual.elements[i].focus();
							}
							return false;
						}
						// Después veo si é menor que el mínimo
						if (convierteFecha(valor) < convierteFecha(tipo[3])) {
							alert("O campo \""+tipo[6]+"\" NON pode ser menor de "+tipo[3]);
							if (cual.elements[i].type!="hidden"){
								cual.elements[i].focus();
							}
							return false;
						}
						// Después veo si é mayor que el máximo
						if (convierteFecha(valor) > convierteFecha(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 "fechaCad":	// fecha caducidad
						// Primero veo si é OBRIGATORIO 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 (validaFecha(valor) != "ok" && valor != "") {
							alert("O campo \""+tipo[6]+"\" debe ser de tipo data: DD/MM/AAAA\n"+validaFecha(valor));
							if (cual.elements[i].type!="hidden"){
								cual.elements[i].focus();
							}
							return false;
						}
						// Después compruebo que sea mayor que la actual
						if (convierteFecha(valor) < convierteFecha(devuelveFechaActual())){
							alert("O campo \""+tipo[6]+"\" NON pode ser menor que a data actual.");
							if (cual.elements[i].type!="hidden"){
								cual.elements[i].focus();
							}
							return false;
						}

						// Después veo si é menor que el mínimo
						if (convierteFecha(valor) < convierteFecha(tipo[3])) {
							alert("O campo \""+tipo[6]+"\" NON pode ser menor de "+tipo[3]);
							if (cual.elements[i].type!="hidden"){
								cual.elements[i].focus();
							}
							return false;
						}
						// Después veo si é mayor que el máximo
						if (convierteFecha(valor) > convierteFecha(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 é OBRIGATORIO 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]+"\" debe ser unha dirección de correo válida");
							if (cual.elements[i].type!="hidden"){
								cual.elements[i].focus();
							}
							return false;
						}
						break;
					case "alf": // solo números o letras
						// Primero veo si es obligatorio RELLENARLO
						if ((valor.length == 0) && tipo[5] == "true") {
							alert("El campo \""+tipo[6]+"\" es OBLIGATORIO");
							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("El campo \""+tipo[6]+"\" NO puede 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("El campo \""+tipo[6]+"\" NO puede ser mayor de "+tipo[4]+" caracteres");
							if (cual.elements[i].type!="hidden"){
								cual.elements[i].focus();
							}
							return false;
						}
						// Después compruebo que sea alfanumerico
						if ((esAlfanumerico(valor)!=true) && (valor!="")){
							alert("El campo \""+tipo[6]+"\" debe estar formado por letras y numeros");
							if (cual.elements[i].type!="hidden"){
								cual.elements[i].focus();
							}
							return false;
						}
						break;
					case "file":	// archivo
						// Primero veo si é OBRIGATORIO RELLENARLO

						if ((valor == "") && tipo[5] == "true") {
							alert("O campo \""+tipo[6]+"\" é OBRIGATORIO");
							if (cual.elements[i].type!="hidden"){
								cual.elements[i].focus();
							}
							return false;
						}		

						break;
					case "fechahora":	// fecha hora
						// Primero veo si é OBRIGATORIO 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 HORA
						if (validaFechaHora(valor) != "ok" && valor != "") {
							alert("O campo \""+tipo[6]+"\" debe ser de tipo data: DD/MM/AAAA hh:mm\n"+validaFechaHora(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
						valor=valor.replace(/[.]/g,",");	// se interpreta igual un "." o una "," (es decimal)
						if(valor == "," || valor == "."){
							alert("El campo \""+tipo[6]+"\" debe ser NUMÉRICO");
							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("El campo \""+tipo[6]+"\" es OBLIGATORIO");
							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("El campo \""+tipo[6]+"\" es 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("El 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 4 decimales
						if (numeroDecimales(valor)>4) {
							alert("El campo \""+tipo[6]+"\" no puede tener mas de 4 DECIMALES");
							if (cual.elements[i].type!="hidden"){
								cual.elements[i].focus();
								cual.elements[i].select();
							}
							return false;
						}
						cual.elements[i].value=valor;
						break;
					default:
						alert("NON existen restriccións de tipo \""+tipo[2]+"\"");
						return false;
						break;
				}
			}
		}
	}
	return true;
}

// COMPRUEBA que una fecha sea correcta
//------------------------------------------------------------------------------------------------
function validaFecha(dato){
	var fecha, dia, mes, ano, aux, formato;

	dia 	= dato.substr(0, 2);
	mes 	= dato.substr(3, 2);
	aNON 	= dato.substr(6, 4);

	aux		= "DD"+dato.substr(2, 1)+"MM"+dato.substr(5, 1)+"AAAA";
	formato	= "DD/MM/AAAA";	// formato de fecha y hora
	
//	comprobamos si el formato recibido é el correcto
	if(isNaN(dia+mes+ano)==false && aux==formato && dato.length==formato.length){
		fecha=new Date(ano, mes-1, dia);
		
		if(fecha.getDate() != dia){
			aux="O día NON é correcto";
		}else if(fecha.getMonth() != (mes-1)){
			 aux="O mes NON é correcto";
		}else if(fecha.getFullYear() != ano){
			aux="O ano NON é correcto";
		}else{
			aux="ok"; // la fecha é correcta
		}
	}else{
		aux="'"+dato+"'";
	}
	return aux;
}

// CONVIERTE una FECHA
// -----------------------------------------------------------------------------------------------
function convierteFecha(quien) {
	var fecha_split;	
	var tdia, tmes, tano;
	fecha_split = quien.split('/');
	tdia = parseInt(fecha_split[0],10);
	tmes = parseInt(fecha_split[1],10);
	taNON = parseInt(fecha_split[2],10);
	return date = new Date(tano,tmes-1,tdia);
}

// 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;
}

// CAMBIA el valor de una variable de nº de registros
// -----------------------------------------------------------------------------------------------
function cambiaNumRs(todo, varQuery, varQueryValor) {
	window.location = ""+todo+"&"+varQuery+"="+varQueryValor;
}

// 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 texto de tipo alfanumerico
// -----------------------------------------------------------------------------------------------
function esAlfanumerico(texto){
    var valido = true;             
    var cadena = "abcdefghijklmnñopqrstuvwxyzABCDEFGHIJKLMNÑOPQRSTUVWXYZ1234567890";
	var i;
    for (i=0 ;i<texto.length;i++){
		if (cadena.indexOf(texto.substr(i, 1),0) == -1){
			valido = false;
			break;
    	}
    }
    return valido;
}

//COMPRUEBA que el 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 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;
	}
}

// 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;
	}
}

// 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;
}

// DEVUELVE la consulta realizada con ajax a una función que pasamos como parámetro
// -------------------------------------------------------------------------------------------
function consultaAjax(destino, funcion) {
	var devolver;
	devolver = "";
	var xmlHttp = GetXmlHttpObject();
	if (xmlHttp==null) {
		alert ("Browser does not support HTTP Request");
		//return;
	}
	xmlHttp.onreadystatechange = function(){
			if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete") {
				if (xmlHttp.responseText == -1000){ // id incorrecto
					devolver = "";
				}else{	// id correcto
					devolver = xmlHttp.responseText;
				}
				eval(funcion)(devolver);
			}
		};
		xmlHttp.open("GET", "consultaAjax.php"+ destino , true);
		xmlHttp.send(null);
}
