var BuscadorEntradaAjax = new Class({
	initialize: function(nombreCampoTexto){
		this.campoTexto = $(nombreCampoTexto);
		this.campoTexto.addEvent("keydown",function(e){
			if (e.key=="enter"){
				e.stop();
				this.buscarEntradas();
			}
		}.bind(this));
		this.campoOculto = new Element("input", {"type": "hidden","name": "id" + nombreCampoTexto});
		this.campoOculto.inject(this.campoTexto, "after");
		this.campoTexto.addClass("cargatipgrande");
		this.campoTexto.store("tip:title", "Buscar una entrada");
		this.campoTexto.store("tip:text",  "Debes escribir al menos 2 letras de la entrada que desees buscar (no es necesario que sean las iniciales) y pulsar el enlace del lado.");
		var tipsGrande2 = new Tips('.cargatipgrande', {"showDelay": 300, "hideDelay": 150, "offsets": {'x': 15, 'y': 10}, "className": "tipgrande"});
		this.enlaceBuscar = new Element("a", {"html": "Buscar entrada", "class": "fuente8", "style": "margin-left: 10px;", "href": "#"});
		this.enlaceBuscar.inject(this.campoTexto, "after");
		this.resultadosBusqueda = new Element("div",{"class": "resultadosbuscarentrada"});
		this.resultadosBusqueda.inject(this.enlaceBuscar, "after");
		
		this.enlaceBuscar.addEvent("click", function(e){
			e.stop()
			this.buscarEntradas();
		}.bind(this));
		
	},
	
	buscarEntradas: function(){
		if (this.campoTexto.value.length < 2){
			this.resultadosBusqueda.set("html", "Debes escribir por lo menos 2 caracteres en el campo de texto");
			this.muestraResultados();
		}else{
			this.resultadosBusqueda.setStyle("display", "none");
			this.muestraCargando()
			var solicitud = new Request.HTML({
				update: this.resultadosBusqueda,
				url: "/wiki/includes/buscar_entradas_caracteres.php",
				onSuccess: function(){
					this.ocultaCargando();
					this.resultadosBusqueda.setStyle("display", "block");
					$$(".buscaentradaencontrada").each(function(elemento){
						elemento.addEvent("click", function(e){
							e.stop();
							this.guardaEntrada(elemento.get("html"), elemento.get("href"));
						}.bind(this));
					}, this);
					this.muestraResultados();
				}.bind(this)
			});
			solicitud.send("texto=" + this.campoTexto.value);
		}
	},
	guardaEntrada: function(textoMostrar, idOculto){
		this.enlaceBuscar.setStyle("display", "none");
		this.muestraSeleccion = new Element("span", {"html": textoMostrar, "style": "font-weight: bold;"});
		this.muestraSeleccion.inject(this.campoTexto, "after");
		this.enlaceCancelar = new Element("a", {"class": "fuente8", "html": "Cancelar", "style": "margin-left: 10px;", "href": "#"});
		this.enlaceCancelar.inject(this.muestraSeleccion, "after");
		this.enlaceCancelar.addEvent("click", function(e){
			e.stop();
			this.campoTexto.setStyle("display", "inline");
			this.campoOculto.value = "";
			this.enlaceBuscar.setStyle("display", "inline");
			this.enlaceCancelar.destroy();
			this.muestraSeleccion.destroy();
		}.bind(this));
		this.campoOculto.value = idOculto;
		this.resultadosBusqueda.setStyle("display", "none");
		this.campoTexto.setStyle("display", "none");
	},
	muestraResultados: function(){
		this.resultadosBusqueda.setStyle("display", "block");
	},
	muestraCargando: function(){
		this.capaCargando = new Element("div", {"class": "cargandocontenido", "style": "width: 130px; height: 30px;"});
		this.capaCargando.inject(this.enlaceBuscar, "after");
	},
	ocultaCargando: function(){
		this.capaCargando.destroy();
	}
});


var BuscadorPadre = new Class({
	Extends: BuscadorEntradaAjax,
	initialize: function(nombreCampoTexto,idCategoriaOriginal){
		this.parent(nombreCampoTexto);
		
		this.idCategoriaOriginal = idCategoriaOriginal;
	},
	guardaEntrada: function(textoMostrar,idOculto){
		solicitud = new Request({
			url: "/wiki/includes/cambiar_padre.php",
			onSuccess: function(responseText, responseXML){
				this.resultadosBusqueda.removeClass("cargandocontenido");
				var respuesta = JSON.decode.attempt(responseText);
				if (respuesta) {
					this.resultadosBusqueda.set("html", respuesta.mensaje);
					
				}else{
					this.resultadosBusqueda.set("html", "He recibido una respuesta incorrecta del servidor");	
				}
			}.bind(this),
			onRequest: function(){
				this.resultadosBusqueda.addClass("cargandocontenido");
			}.bind(this)
		});
		
		solicitud.send("id_categoria=" + this.idCategoriaOriginal + "&hijo_de=" + idOculto);
	}
});

var BuscadorPadreDiscusion = new Class({
	Extends: BuscadorEntradaAjax,
	initialize: function(nombreCampoTexto,idCategoriaOriginal,idWikiDiscusion){
		this.parent(nombreCampoTexto);
		this.idWikiDiscusion = idWikiDiscusion;
		this.idCategoriaOriginal = idCategoriaOriginal;
	},
	guardaEntrada: function(textoMostrar,idOculto){
		solicitud = new Request({
			url: "/wiki/includes/cambiar_padre_discusion.php",
			onSuccess: function(responseText, responseXML){
				this.resultadosBusqueda.removeClass("cargandocontenido");
				var respuesta = JSON.decode.attempt(responseText);
				if (respuesta) {
					this.resultadosBusqueda.set("html", respuesta.mensaje);
					
				}else{
					this.resultadosBusqueda.set("html", "He recibido una respuesta incorrecta del servidor");	
				}
			}.bind(this),
			onRequest: function(){
				this.resultadosBusqueda.addClass("cargandocontenido");
			}.bind(this)
		});
		
		solicitud.send("id_wiki_discusion=" + this.idWikiDiscusion + "&id_categoria_original=" + this.idCategoriaOriginal + "&id_wiki_categoria=" + idOculto);
	}
});

var BuscadorEntradaRelacionar = new Class({
	Extends: BuscadorEntradaAjax,
	initialize: function(nombreCampoTexto,objetoListado,idCategoriaOriginal){
		this.parent(nombreCampoTexto);
		this.objetoListado = objetoListado;
		this.idCategoriaOriginal = idCategoriaOriginal;
	},
	guardaEntrada: function(textoMostrar, idOculto){
		solicitud = new Request({
			url: "/wiki/includes/crear_relacion_entrada.php",
			onSuccess: function(responseText, responseXML){
				this.resultadosBusqueda.removeClass("cargandocontenido");
				var respuesta = JSON.decode.attempt(responseText);
				if (respuesta) {
					this.resultadosBusqueda.set("html", respuesta.mensaje);
					if (respuesta.valido == "1") {
						this.objetoListado.actualizarListado();
					}
				}else{
					this.resultadosBusqueda.set("html", "He recibido una respuesta incorrecta del servidor");	
				}
			}.bind(this),
			onRequest: function(){
				this.resultadosBusqueda.addClass("cargandocontenido");
			}.bind(this)
		});
		solicitud.send("id_categoria=" + this.idCategoriaOriginal + "&id_categoria_relacionar=" + idOculto);
	}
});


var ListadoEntradasRelacionadas = new Class({
	urlBuscar: "/wiki/includes/buscar_entradas_relacionadas.php",
	classEnlacesQuitar: "enlacedeletecategoriarelacionada",
	
	initialize: function(idDestino,idCategoria){
		this.destino = $(idDestino);
		this.idCategoriaBuscar = idCategoria;
		this.actualizarListado();
	},
	actualizarListado: function(){
		this.destino.empty();
		new Element("div", {"style": "height: 30px; width: 300px;", "class":"cargandocontenido"}).inject(this.destino);
		solicitud = new Request.HTML({
			update: this.destino,
			url: this.urlBuscar,
			onSuccess: function(){
				$$("a." + this.classEnlacesQuitar).each(function(enlace){
					enlace.addEvent("click", function(e){
						e.stop();
						solicitud = new Request({
							url: enlace.get("href"),
							onRequest: function(){
								var elemLista = enlace.getParent();
								elemLista.setStyle("background-image", "url(/images/ajax-loader-mini.gif)");
								enlace.empty();
							},
							onSuccess: function(responseText, responseXML){
								var elemLista = enlace.getParent();
								elemLista.set("html",responseText);
								elemLista.setStyle("background-image", "url(/images/iconos/arrow_right.png)");
							}
						}).send();
					});
				});
			}.bind(this)
		});
		solicitud.send("id_categoria=" + this.idCategoriaBuscar);
	}
});

var ListadoEtiquetasRelacionadas = new Class({
	Extends: ListadoEntradasRelacionadas,
	
	urlBuscar: "/wiki/includes/buscar_etiquetas_relacionadas.php",
	classEnlacesQuitar: "enlacedeleteetiquetarelacionada"
});






var BuscadorEtiquetaAjax = new Class({
	initialize: function(nombreCampoTexto){
		this.campoTexto = $(nombreCampoTexto);
		this.campoTexto.addEvent("keydown",function(e){
			if (e.key=="enter"){
				e.stop();
				this.buscarEtiquetas();
			}
		}.bind(this));
		this.campoOculto = new Element("input", {"type": "hidden","name": "id" + nombreCampoTexto});
		this.campoOculto.inject(this.campoTexto, "after");
		this.campoTexto.addClass("cargatipgrande");
		this.campoTexto.store("tip:title", "Buscar una Etiqueta");
		this.campoTexto.store("tip:text",  "Debes escribir al menos 2 letras de la Etiqueta que desees buscar (no es necesario que sean las iniciales) y pulsar el enlace del lado.");
		var tipsGrande2 = new Tips('.cargatipgrande', {"showDelay": 300, "hideDelay": 150, "offsets": {'x': 15, 'y': 10}, "className": "tipgrande"});
		this.enlaceBuscar = new Element("a", {"html": "Buscar Etiqueta", "class": "fuente8", "style": "margin-left: 10px;", "href": "#"});
		this.enlaceBuscar.inject(this.campoTexto, "after");
		this.resultadosBusqueda = new Element("div",{"class": "resultadosbuscaretiqueta"});
		this.resultadosBusqueda.inject(this.enlaceBuscar, "after");
		
		this.enlaceBuscar.addEvent("click", function(e){
			e.stop()
			this.buscarEtiquetas();
		}.bind(this));
		
	},
	
	buscarEtiquetas: function(){
		if (this.campoTexto.value.length < 2){
			this.resultadosBusqueda.set("html", "Debes escribir por lo menos 2 caracteres en el campo de texto");
			this.muestraResultados();
		}else{
			this.resultadosBusqueda.setStyle("display", "none");
			this.muestraCargando()
			var solicitud = new Request.HTML({
				update: this.resultadosBusqueda,
				url: "/wiki/includes/buscar_etiquetas_caracteres.php",
				onSuccess: function(){
					this.ocultaCargando();
					this.resultadosBusqueda.setStyle("display", "block");
					$$(".buscaetiquetaencontrada").each(function(elemento){
						elemento.addEvent("click", function(e){
							e.stop();
							this.guardaEtiqueta(elemento.get("html"), elemento.get("href"));
						}.bind(this));
					}, this);
					this.muestraResultados();
				}.bind(this)
			});
			solicitud.send("texto=" + this.campoTexto.value);
		}
	},
	guardaEtiqueta: function(textoMostrar, idOculto){
		this.enlaceBuscar.setStyle("display", "none");
		this.muestraSeleccion = new Element("span", {"html": textoMostrar, "style": "font-weight: bold;"});
		this.muestraSeleccion.inject(this.campoTexto, "after");
		this.enlaceCancelar = new Element("a", {"class": "fuente8", "html": "Cancelar", "style": "margin-left: 10px;", "href": "#"});
		this.enlaceCancelar.inject(this.muestraSeleccion, "after");
		this.enlaceCancelar.addEvent("click", function(e){
			e.stop();
			this.campoTexto.setStyle("display", "inline");
			this.campoOculto.value = "";
			this.enlaceBuscar.setStyle("display", "inline");
			this.enlaceCancelar.destroy();
			this.muestraSeleccion.destroy();
		}.bind(this));
		this.campoOculto.value = idOculto;
		this.resultadosBusqueda.setStyle("display", "none");
		this.campoTexto.setStyle("display", "none");
	},
	muestraResultados: function(){
		this.resultadosBusqueda.setStyle("display", "block");
	},
	muestraCargando: function(){
		this.capaCargando = new Element("div", {"class": "cargandocontenido", "style": "width: 130px; height: 30px;"});
		this.capaCargando.inject(this.enlaceBuscar, "after");
	},
	ocultaCargando: function(){
		this.capaCargando.destroy();
	}
});

var BuscadorEtiquetaRelacionar = new Class({
	Extends: BuscadorEtiquetaAjax,
	initialize: function(nombreCampoTexto,objetoListado,idCategoriaOriginal){
		this.parent(nombreCampoTexto);
		this.objetoListado = objetoListado;
		this.idCategoriaOriginal = idCategoriaOriginal;
	},
	guardaEtiqueta: function(textoMostrar, idOculto){
		solicitud = new Request({
			url: "/wiki/includes/crear_relacion_etiqueta.php",
			onSuccess: function(responseText, responseXML){
				this.resultadosBusqueda.removeClass("cargandocontenido");
				var respuesta = JSON.decode.attempt(responseText);
				if (respuesta) {
					this.resultadosBusqueda.set("html", respuesta.mensaje);
					if (respuesta.valido == "1") {
						this.objetoListado.actualizarListado();
					}
				}else{
					this.resultadosBusqueda.set("html", "He recibido una respuesta incorrecta del servidor");	
				}
			}.bind(this),
			onRequest: function(){
				this.resultadosBusqueda.addClass("cargandocontenido");
			}.bind(this)
		});
		
		solicitud.send("id_categoria=" + this.idCategoriaOriginal + "&id_etiqueta_relacionar=" + idOculto);
	}
});

var ArbolDHTML = new Class({
	initialize: function(destino, arbolInicial){
		this.destino = $(destino);
		this.nodoRaiz = new NodoArbolDHTML(arbolInicial.raiz, "raiz", null, false);
		this.nodoRaiz.divNodo.inject(this.destino);
	}
});

var NodoArbolDHTML = new Class({
	initialize: function(datosNodo, marcadorIndice, padre, esUltimo, esRelacionado){
		this.marcadorIndice = marcadorIndice;
		this.nombre = datosNodo.nombre;
		this.idBBDD = datosNodo.id;
		this.url = datosNodo.url;
		this.padre = padre;
		this.esUltimo = esUltimo;
		this.imgCarpeta = new Element("span");
		this.expandido = true;
		if($defined(datosNodo.expandido)){
			if(!datosNodo.expandido){
				this.expandido = false;
			}
		}
		
		this.destacado = false;
		if($defined(datosNodo.destacar)){
			if(datosNodo.destacar){
				this.destacado = true;
			}
		}
		this.hijosAjax = false;
		if($defined(datosNodo.hijosAjax)){
			if(datosNodo.hijosAjax){
				this.hijosAjax = true;
			}
		}
		this.tieneHijos = false;
		if($defined(datosNodo.hijos)){
			this.tieneHijos = true;
		}
		
		this.tieneRelacionados = false;
		if($defined(datosNodo.relacionados)){
			this.tieneRelacionados = true;
		}
		this.esRelacionado = false;
		if ($defined(esRelacionado)){
			this.esRelacionado = true;
		}
		if ($defined(this.padre)){
			//es que no es el raiz
			if (this.esRelacionado){
				this.imgCarpeta.addClass('relacionada');
			}else{
				if(this.expandido && $defined(datosNodo.hijos)){
					this.imgCarpeta.addClass('carpetaabierta');
				}else{
					this.imgCarpeta.addClass('carpetacerrada');
				}
			}
			this.nivelProfundidad = this.padre.nivelProfundidad + 1;
		}else{
			this.imgCarpeta.addClass('carpetaabierta')
			//es raiz
			this.nivelProfundidad = 0;
		}
		var textoEnlaceEntrada = "<a class='";
		if (this.destacado){
			textoEnlaceEntrada += "linkdestacado";
		}else{
			textoEnlaceEntrada += "link";
		}
		textoEnlaceEntrada += "' href='" + this.url + "'>" + this.nombre + "</a>";
		this.enlace = new Element("span",{"html": textoEnlaceEntrada});
		this.divNodo = new Element("div",{
			"class": "lineaarbol"
		});
		//para cada nivel de profundidad, idento colocando un span
		for(prof=this.nivelProfundidad-1; prof>=0; prof--){
			var profundidad_actual = new Element("span");
			if (prof==0){
				if (this.esUltimo){
					profundidad_actual.addClass('finalrama');
				}else{
					profundidad_actual.addClass('rama');
				}
				if(this.tieneHijos || this.hijosAjax){
					var urlImagen = "/images/arbol/menos.gif";
					if (!this.expandido || this.hijosAjax){
						urlImagen = "/images/arbol/mas.gif";
					}
					this.imgExpandir = new Element("img", {src: urlImagen, "border": 0});
					this.enlaceImgExpandir = new Element("a",{href: "#"});
					this.imgExpandir.inject(this.enlaceImgExpandir)
					this.enlaceImgExpandir.addEvent("click", function(e){
						e.stop();
						this.expandirContraerRama();
					}.bind(this));
					this.enlaceImgExpandir.inject(profundidad_actual);
				}		
			}else{
				if (!this.padreUltimo(prof -1)){
					profundidad_actual.addClass('identadorlineavertical');
				}else{
					profundidad_actual.addClass('identadorvacio');
				}	
			}
			profundidad_actual.inject(this.divNodo);
		}
		this.imgCarpeta.inject(this.divNodo);
		this.enlace.inject(this.divNodo);
		
		this.hijos = new Hash({});
		if(this.tieneRelacionados || this.tieneHijos){
			this.divHijos = new Element("div",{
				"class": "hijosnodo"
			});
			if (!this.expandido){
				this.divHijos.setStyle("display", "none");
			}
			this.divHijos.inject(this.divNodo);
		}
		if($defined(datosNodo.hijos)){
			var hijosIni = new Hash(datosNodo.hijos);
			this.keyUltimo = hijosIni.getKeys()[hijosIni.getLength()-1];
			hijosIni.each(function(elemento, indice){
				var esElUltimo = false;
				if(this.keyUltimo==indice && !this.tieneRelacionados){
					esElUltimo = true;
				}
				this.hijos.include(indice, new NodoArbolDHTML(elemento, indice, this, esElUltimo));
				this.hijos.get(indice).divNodo.inject(this.divHijos);
			}, this);
		}
		this.relacionados = new Hash({});
		if(this.tieneRelacionados){
			var relacionadosIni = new Hash(datosNodo.relacionados);
			//console.log("RELACIONADOS INI: " ,relacionadosIni)
			this.keyUltimoRel = relacionadosIni.getKeys()[relacionadosIni.getLength()-1];
			relacionadosIni.each(function(elemento, indice){
				var esElUltimo = false;
				if(this.keyUltimoRel==indice){
					esElUltimo = true;
				}
				this.relacionados.include(indice, new NodoArbolDHTML(elemento, indice, this, esElUltimo, true));
				//console.log(this.relacionados.get(indice))
				this.relacionados.get(indice).divNodo.inject(this.divHijos);
			}, this);
		}
	},
	padreUltimo: function(nivelPadre){
		if(nivelPadre==0)
			return this.padre.esUltimo;
		else{
			nivelPadre--;
			return this.padre.padreUltimo(nivelPadre)
		}
	},
	expandirContraerRama: function(){
		if(this.hijosAjax){
			var ajaxHijosJSON = new Request.JSON({
				url: "/wiki/includes/arbol_parcial.php",
				data: "id=" + this.idBBDD,
				method: "post",
				onRequest: function(){
					this.imgCarpeta.removeClass('carpetacerrada');
					this.imgCarpeta.addClass('cargando');
				}.bind(this),
				onSuccess: function(responseJSON, responseText){
					var responseJSONRel = new Hash(responseJSON.relacionadas);
					var hayRelacionadas = false;
					if (responseJSONRel.getLength()>0){
						hayRelacionadas = true;
					}
					this.tieneHijos=true;
					this.hijosAjax=false;
					this.expandido = false;
					this.divHijos = new Element("div",{
						"class": "hijosnodo",
						"style": "display:none;"
					});
					this.divHijos.inject(this.divNodo);
					var responseJSON = new Hash(responseJSON.hijos);
					this.keyUltimo = responseJSON.getKeys()[responseJSON.getLength()-1];
					responseJSON.each(function(elemento,indice){
						var esElUltimo = false;
						if(this.keyUltimo==indice && !hayRelacionadas){
							esElUltimo = true;
						}
						//console.log("esElUltimo=", esElUltimo, " / hayRelacionadas=", hayRelacionadas, " / Indice=", indice);
						this.hijos.include(indice, new NodoArbolDHTML(elemento, indice, this, esElUltimo));
						this.hijos.get(indice).divNodo.inject(this.divHijos);
					},this);
					this.keyUltimo = responseJSONRel.getKeys()[responseJSONRel.getLength()-1];
					responseJSONRel.each(function(elemento,indice){
						var esElUltimo = false;
						if(this.keyUltimo==indice){
							esElUltimo = true;
						}
						this.hijos.include(indice, new NodoArbolDHTML(elemento, indice, this, esElUltimo, true));
						this.hijos.get(indice).divNodo.inject(this.divHijos);
					},this);
					this.imgCarpeta.addClass('carpetacerrada');
					this.imgCarpeta.removeClass('cargando');
					this.expandirContraerRama();
				}.bind(this)
			});
			ajaxHijosJSON.send();
		}else{
			if(this.expandido){
				this.divHijos.setStyle("display", "none");
				this.expandido = false;
				this.imgExpandir.set("src","/images/arbol/mas.gif");
				this.imgCarpeta.removeClass('carpetaabierta');
				this.imgCarpeta.addClass('carpetacerrada');
			}else{
				
				this.divHijos.setStyle("display", "block");
				this.expandido = true;
				this.imgExpandir.set("src","/images/arbol/menos.gif");
				this.imgCarpeta.removeClass('carpetacerrada');
				this.imgCarpeta.addClass('carpetaabierta');
			}
		}
		this.enlaceImgExpandir.blur();
	}
});