
// CORRIGE defectos de IE para mostrar el menú emergente
// -----------------------------------------------------------------------------------------------
function iniciaMenuDesplegable() {
	if (document.all && document.getElementById) {
		if (document.getElementById("menuDesplegable")) {
			navRoot = document.getElementById("menuDesplegable");
			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";
						}
					}
				}
			}
		}
	}
}


// Navegador
//------------------------------------------------------------------------------------------------
var ie = document.all ? 1 : 0;
var ns = document.layers ? 1 : 0;


// Popups
//------------------------------------------------------------------------------------------------
function abrePop(cual, nombre, alto, ancho, ajustable, scroll) {
	var ventana;
	var donde_x, donde_y;
	donde_x = (screen.width - ancho) / 2;
	donde_y = (screen.height - alto) / 2;
	if (ie) {
		ventana = 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) {
		ventana = window.open(cual, nombre, 'width='+ ancho +', height='+ alto +', location=no,toolbar=no, directories=no, menubar=no, resizable='+ajustable+', scrollbars='+ scroll +', status=no, top='+donde_y+', left='+donde_x+'');
	} else {
		ventana = window.open(cual, nombre, 'left='+ donde_x +', top='+ donde_y +', width='+ ancho +', height='+ (alto+5) +', location=no, toolbar=no, directories=no, resizable='+ ajustable +', scrollbars='+ scroll +', status=no');
	}
	ventana.focus();
}


// 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 && 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 es obligatorio RELLENARLO
						if ((valor.length == 0) && tipo[5] == "true") {
							alert("El campo \""+tipo[6]+"\" es OBLIGATORIO");
							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("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;
						}
						break;
					case "str":	// 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;
						}
						break;
					case "int":	// numerico
						// 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 compruebo que sea NUMÉRICO
						if (!(esnumerico(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;
						}
						// Después veo si es menor que el mínimo
						if (parseInt(valor,10) < parseInt(tipo[3],10)) {
							alert("El campo \""+tipo[6]+"\" NO puede ser menor que "+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("El campo \""+tipo[6]+"\" NO puede ser mayor 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 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 compruebo que sea FECHA
						if (validaFecha(valor) != "ok" && valor != "") {
							alert("El campo \""+tipo[6]+"\" debe ser de tipo fecha: DD/MM/AAAA\n"+validaFecha(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("El campo \""+tipo[6]+"\" NO puede 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("El campo \""+tipo[6]+"\" NO puede ser mayor de "+tipo[4]);
							if (cual.elements[i].type!="hidden"){
								cual.elements[i].focus();
							}
							return false;
						}
						break;
					case "fechaCad":	// fecha caducidad
						// 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 compruebo que sea FECHA
						if (validaFecha(valor) != "ok" && valor != "") {
							alert("El campo \""+tipo[6]+"\" debe ser de tipo fecha: 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("El campo \""+tipo[6]+"\" NO puede ser menor que la fecha actual.");
							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("El campo \""+tipo[6]+"\" NO puede 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("El campo \""+tipo[6]+"\" NO puede ser mayor 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("El campo \""+tipo[6]+"\" es OBLIGATORIO");
							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("El campo \""+tipo[6]+"\" debe ser una dirección de correo válida");
							if (cual.elements[i].type!="hidden"){
								cual.elements[i].focus();
							}
							return false;
						}
						break;
					case "file":	// archivo
						// Primero veo si es obligatorio RELLENARLO

						if ((valor == "") && tipo[5] == "true") {
							alert("El campo \""+tipo[6]+"\" es OBLIGATORIO");
							if (cual.elements[i].type!="hidden"){
								cual.elements[i].focus();
							}
							return false;
						}		

						break;
					case "fechahora":	// fecha hora
						// 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 compruebo que sea FECHA HORA
						if (validaFechaHora(valor) != "ok" && valor != "") {
							alert("El campo \""+tipo[6]+"\" debe ser de tipo fecha: DD/MM/AAAA hh:mm\n"+validaFechaHora(valor));
							if (cual.elements[i].type!="hidden"){
								cual.elements[i].focus();
							}
							return false;
						}
						
						break;
					default:
						alert("No existen restricciones 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);
	ano 	= 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 es 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="El día no es correcto";
		}else if(fecha.getMonth() != (mes-1)){
			 aux="El mes no es correcto";
		}else if(fecha.getFullYear() != ano){
			aux="El año no es correcto";
		}else{
			aux="ok"; // la fecha es 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);
	tano = 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;
}
// 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:"100%",
//	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 : ""
	});
}
// 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();
}
// 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, aux;
	
	mes = document.getElementById("comboMesCalendario").value;
	ano = document.getElementById("comboAnoCalendario").value;
	
	fechaIni = "01/"+ numDosCifras(mes) +"/"+ ano;
	fechaFin = nDiasMes(ano, mes) +"/"+ numDosCifras(mes) +"/"+ ano;

	if(destino.indexOf("?") == -1){
		aux = "?";
	}else{
		aux = "&";
	}
		
//	enviamos el mes y año del calendario para posicionarlo en esa posicion al recargar la página
	window.location.href = destino + aux +"anoCalendario="+ ano +"&mesCalendario="+ mes;
}
