// Navegador
var ie = document.all ? 1 : 0;
var ns = document.layers ? 1 : 0;
// 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 != 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 "editor":
							valor = tinyMCE.getContent();
							// Primero veo si es obligatorio RELLENARLO
							if ((valor.length == 0) && tipo[5] == "true") {
								alert("O campo \""+tipo[6]+"\" é obrigatorio");
								tinyMCE.execCommand("mceFocus", cual.elements[i].name);// ERROR: no sitúa el cursor
								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 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("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":
							// 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 puede 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: DD.MM.AAAA\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 (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 es mayor que el máximo
							if (convierteFecha(valor) > convierteFecha(tipo[4])) {
								alert("O campo \""+tipo[6]+"\" non pode ser meirande de "+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]+"\" debe ser unha dirección de correo válida");
								if (cual.elements[i].type!="hidden"){
									cual.elements[i].focus();
								}
								return false;
							}
							break;
						case "alf": // Es el tipo alfanumérico
							// 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;
						default:
							alert("Non existen restriccións de tipo \""+tipo[2]+"\"");
							return false;
							break;
					}
				}
			}
		}
	}
	return true;
}


//COMPRUEBA las fechas de un buscadores
//------------------------------------------------------------------------------------------------
function chekeaFrmBsq(cual, mensaje){

	var seguir=true;
	var valor = cual.elements["bsqFechaDesde"].value;
	if (esfecha(valor) != "si" && valor != "") {
		alert(mensaje);
		cual.elements["bsqFechaDesde"].focus();
		seguir = false;
	}

	valor = cual.elements["bsqFechaHasta"].value;
	if (esfecha(valor) != "si" && valor != "" && seguir==true) {
		alert(mensaje);
		cual.elements["bsqFechaHasta"].focus();
		seguir = false;
	}

	return seguir;
}


//COMPRUEBA que el campo sea fecha
//------------------------------------------------------------------------------------------------
function esfecha(dato) {
	var fecha_split;
	var i;
	var tdia, tmes, tano;

	fecha_split = dato.split('.');

	if(fecha_split.length != 3) {return "Debe ter DD.MM.AAAA";}
	
	tdia = parseInt(fecha_split[0],10);
	tmes = parseInt(fecha_split[1],10);
	tano = parseInt(fecha_split[2],10);

	if ((fecha_split[0].length!=2) || (!esNumeroEstricto(fecha_split[0])) ) {return "O día non é correcto. Formato: DD.MM.AAAA";}
	if ((fecha_split[1].length!=2) || (!esNumeroEstricto(fecha_split[1])) ) {return "O mes non é correcto. Formato: DD.MM.AAAA";}
	if ((fecha_split[2].length!=4) || (!esNumeroEstricto(fecha_split[2])) ) {return "O ano non é correcto. Formato: DD.MM.AAAA";}

	// Comprobamos que sean 3 elementos
		// Comprobamos que no sean ceros
		for (i=0; i<fecha_split.length; i++) {
			if (parseInt(fecha_split[i],10) == 0) return "Non existe a data: 0";
		}
		// Comprobamos que el AÑO tenga 4 dígitos
		//if(fecha_split[2].length != 4) aux="El año debe tener 4 dígitos: AAAA";
		// Comprobamos que sea dia/mes/año: 28/02/1997
		var f = convierteFecha(dato);
		if(f.getDate() != tdia) return "O día non é correcto";
		if(f.getMonth() != (tmes-1)) return "O mes non é correcto";
		if(f.getFullYear() != tano) return "O ano non é correcto";

	return "si";
}


//DEVUELVE 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);
	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;
}

// Recarga la página añadiendo una variable al querystring
// -----------------------------------------------------------------------------------------------
function recargaPagina(todo, varQuery, varQueryValor) {
	window.location = ""+todo+"&"+varQuery+"="+varQueryValor;
}

// MUESTRA o no una capa mediante la propiedad display
// ------------------------------------------------------------------------------------------------
function abrirCerrarCapa(capa){
	if(document.getElementById(capa).style.display=='none'){
		document.getElementById(capa).style.display='block';
		if(document.getElementById("btnAbrirCerrar")){
			document.getElementById("btnAbrirCerrar").src="img/btnFlechaAr.gif";
		}
	}else{
		document.getElementById(capa).style.display='none';
		if(document.getElementById("btnAbrirCerrar")){
			document.getElementById("btnAbrirCerrar").src="img/btnFlechaAb.gif";
		}
	}
}

// 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;
}


// REDIRIGE un banner
//------------------------------------------------------------------------------------------------
function abreBanner(enlace){
	window.open(enlace);
//	window.location = enlace;
}

//	MUESTRA un banner con enlaces (se llama directamente desde el banner)
//----------------------------------------------------------------------------------------------------------------------
function muestraBannerEnlaces(enlaces){
	var aux, clase;
	aux=desordenar(enlaces);
	document.write("<table cellpadding=\"0\" cellspacing=\"0\" class=\"tblBannerEnlaces\" border=\"0\">");
	for(i=0;i<aux.length;i++){
		if(i<aux.length-1){clase="separador"}else{clase="";}
		document.write("<tr><td class=\""+clase+"\">"+aux[i]+"</td></tr>");
	}
	document.write("</table>"); 
}

//	DESORDENAR un array
//----------------------------------------------------------------------------------------------------------------------
function desordenar(array){
    var aux=array;
	var i=aux.length;
	var j;
	var tmp;
    while(i--){
        j=Math.floor( Math.random() * (i+1) );
        tmp=aux[i];
        aux[i]=aux[j];
        aux[j]=tmp;
    }
	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;
}

// INICIA el editor de textos para textareas
// -----------------------------------------------------------------------------------------------
function iniciaEditor(btnMostrar, cssMostrar, hojaCss, enlace){
	tinyMCE.init({
	mode : "textareas",							//dónde actuará
	editor_selector : "mceEditor",				//<textarea class="mceEditor"> convierte un textarea en editor
	entity_encoding : "raw", 					//para que no sustituya tildes por &...
	theme : "plexus", 							//tipo
	language : "es",							//idioma
	docs_language : "es",						//idioma de la ayuda
	convert_newlines_to_brs : false,
	force_br_newlines : false,
	popups_css : hojaCss,						//hoja de estilos que cogerán las pop-ups
	//auto_resize : true,						//el editor se redimensiona para ocupar todo el espacio del q dispone (quita el scroll)
	theme_plexus_layout_manager: "SimpleLayout",//para redimensionar
	theme_plexus_statusbar_location :"bottom",	//para redimensionar
	theme_plexus_resizing : true,				//para redimensionar
	theme_plexus_resize_horizontal : false,		//para no redimensionar horizontalmente
	theme_plexus_path : false,					//no queremos path
	content_css : hojaCss,
	theme_plexus_styles : cssMostrar,			// estilos para el combo
	theme_plexus_buttons1 : btnMostrar, 		//botones activos
	theme_enlace: enlace,
	relative_urls: false,  						// El path debe ser absoluto
	plugins : "searchreplace",					//plugins: botón de reemplazar
	height : "200",
	width:"625",
//	etiquetas válidas e inválidas
//	valid_elements : "strong/b,em/i,strike,-ul,-li"
//	invalid_elements como referencia porque el script funciona con las que que son válidas
//	invalid_elements : "-div[id|dir|class|align|style]"
	invalid_elements : ""
	});
}


// RECARGA la pagina al seleccionar un año o un mes distinto en el combo del calendario
// ---------------------------------------------------------------------------------------
function recargaCalendario(destino){
	var ano, mes, fechaIni, fechaFin;
	
	ano=document.frmCalendario.anoCalendario.value;
	mes=document.frmCalendario.mesCalendario.value;

	fechaIni="01."+numDosCifras(mes)+"."+ano;
	fechaFin=nDiasMes(ano, mes)+"."+numDosCifras(mes)+"."+ano;

//	con esta opcion enviamos tambien las fechas del primer y último día del mes seleccionado
//	window.location.href = destino+"&anoCalendario="+ano+"&mesCalendario="+mes+"&bsqFechaDesde="+fechaIni+"&bsqFechaHasta="+fechaFin;

//	con esta opcion solo enviamos el mes y año del calendario para posicionarlo en esa posicion al recargar la página
	window.location.href = destino+"&anoCalendario="+ano+"&mesCalendario="+mes;
}

// DEVUELVE el nº de días de un mes
// ---------------------------------------------------------------------------------------
function nDiasMes(ano, mes){
	var msDia, msFecha, fecha;
	msDia = 86400000;	// nº de ms de un dia
	msFecha = new Date(ano, mes, 1).getTime();// nº de ms hasta el dia 1 del mes siguiente al seleccionado
	fecha = new Date(msFecha - msDia);	// fecha del último día del mes
	return fecha.getDate();
}

// 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;
}

// AUMENTA O DISMINUYE el texto que hay dentro de un div
// ------------------------------------------------------------------------------------------------
function zoomTexto(accion,elemento){
//inicializaciones
	if(document.getElementById(elemento)){
		obj=document.getElementById(elemento);
		if (obj.style.fontSize==""){
			obj.style.fontSize="100%";
		}
	
		actual=parseInt(obj.style.fontSize); //valor actual del tamaño del texto
		incremento=10;// el valor del incremento o decremento en el tamaño
	
	//accion sobre el texto
		if(accion=="reestablecer"){
			obj.style.fontSize="100%"
		}
		if(accion=="aumentar" && actual<=150){
			valor=actual+incremento;
			obj.style.fontSize=valor+"%"
		}
		if(accion=="disminuir" && actual>=50){
			valor=actual-incremento;
			obj.style.fontSize=valor+"%"
		}
	}
}

// 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;
}
//
// -------------------------------------------------------------------------------------------
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);
}