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

Element.implement({getSelectedText:function(){if(Browser.Engine.trident)return document.selection.createRange().text;return this.get('value').substring(this.selectionStart,this.selectionEnd);},replaceSelectedText:function(newtext,isLast){var isLast=(isLast==null)?true:isLast;var scroll_top=this.scrollTop;if(Browser.Engine.trident){this.focus();var range=document.selection.createRange();range.text=newtext;if(isLast){range.select();this.scrollTop=scroll_top;}}
else{originalStart=this.selectionStart;originalEnd=this.selectionEnd;this.value=this.get('value').substring(0,originalStart)+newtext+this.get('value').substring(originalEnd);if(isLast==false){this.setSelectionRange(originalStart,originalStart+newtext.length);}
else{this.setSelectionRange(originalStart+newtext.length,originalStart+newtext.length);this.scrollTop=scroll_top;}
this.focus();}}});var nawte=new Class({Implements:Options,options:{displatchChangeEvent:false,changeEventDelay:200,interceptTabs:true},initialize:function(element,list,options){this.el=$(element);this.setOptions(options);if(this.options.dispatchChangeEvent){this.el.addEvents({'focus':function(){this.timer=this.watchChange.periodical(this.options.changeEventDelay,this);}.bind(this),'blur':function(){this.timer=$clear(this.timer);}.bind(this)});}
if(this.options.interceptTabs){this.el.addEvent('keypress',function(event){var event=new Event(event);if(event.key=="tab"){event.preventDefault();this.replaceSelection("\t");}}.bind(this));}
if(!$defined(list)||list==""){list=new Element('li');list.inject(this.el,'before');this.list=list;}
else{this.list=$(list);}
this.oldContent=this.el.get('value');},watchChange:function(){if(this.oldContent!=this.el.get('value')){this.oldContent=this.el.get('value');this.el.fireEvent('change');}},getSelection:function(){return this.el.getSelectedText();},wrapSelection:function(wrapper,isLast){var isLast=(isLast==null)?true:isLast;this.el.replaceSelectedText(wrapper+this.el.getSelectedText()+wrapper,isLast);},insert:function(insertText,where,isLast){var isLast=(isLast==null)?true:isLast;where=(where=="")?'after':where;var newText=(where=="before")?insertText+this.el.getSelectedText():this.el.getSelectedText()+insertText;this.el.replaceSelectedText(newText,isLast);},replaceSelection:function(newText,isLast){var isLast=(isLast==null)?true:isLast;this.el.replaceSelectedText(newText,isLast);},processEachLine:function(callback,isLast){var isLast=(isLast==null)?true:isLast;var lines=this.el.getSelectedText().split("\n");var newlines=[];lines.each(function(line){if(line!="")
newlines.push(callback.attempt(line,this));else
newlines.push("");}.bind(this));this.el.replaceSelectedText(newlines.join("\n"),isLast);},getValue:function(){return this.el.get('value');},setValue:function(text){this.el.set('value',text);this.el.focus();},addFunction:function(name,callback,args){var item=new Element('li');var itemlink=new Element('a',{'events':{'click':function(e){new Event(e).stop();callback.attempt(null,this);}.bind(this)},'href':'#'});itemlink.set('html','<span>'+name+'</span>');itemlink.setProperties(args||{});itemlink.inject(item,'bottom');item.injectInside(this.list);}});





var EditorSubtitular = new Class({
	Extends: nawte,
	
	initialize: function(element, list, options){
		this.parent(element, list, options);
		this.addFunction('<img src="/images/iconos/text_bold.png" width="16" height="16" alt="Negrita" class="cargatipgrande" id="botoneditornegrita">', function() {
			selection = this.getSelection();
			if (selection == "") {
				this.replaceSelection("<b></b>");
			}
			else {
				this.insert("<b>", "before", false); 
				this.insert("</b>", "after", true); //now isLast is set to true, because it is the last one!
			}
		});
		this.addFunction('<img src="/images/iconos/text_italic.png" width="16" height="16" alt="It&aacute;lica" class="cargatipgrande" id="botoneditoritalica">', function() {
			selection = this.getSelection();
			if (selection == "") {
				this.replaceSelection("<i></i>");
			}
			else {
				this.insert("<i>", "before", false); 
				this.insert("</i>", "after", true); 
			}
		});
		this.addFunction('<img src="/images/iconos/text_underline.png" width="16" height="16" alt="Underline" class="cargatipgrande" id="botoneditorsubrayado">', function() {
			selection = this.getSelection();
			if (selection == "") {
				this.replaceSelection("<u></u>");
			}
			else {
				this.insert("<u>", "before", false); 
				this.insert("</u>", "after", true); 
			}
		});
		this.addFunction('<img src="/images/iconos/tag.png" width="16" height="16" alt="Convertir entidades &lt;, &gt; y &amp;" class="cargatipgrande" id="botoneditorentidades">', function() {
			selection = this.getSelection();
			selection = selection.replace(/&/g, "&amp;")
			selection = selection.replace(/</g, "&lt;");
			selection = selection.replace(/>/g, "&gt;")
			this.replaceSelection(selection);
		});
		this.addFunction('<img src="/images/iconos/script.png" width="16" height="16" alt="C&oacute;digo" class="cargatipgrande" id="botoneditorcodigo">', function() {
			selection = this.getSelection();
			if (selection == "") {
				this.replaceSelection("<pre class=\"codigo\">\n</pre>");
			}
			else {
				this.insert("<pre class=\"codigo\">\n", "before", false); 
				this.insert("\n</pre>", "after", true); 
			}
		});
		$("botoneditornegrita").store("tip:title", "Negrita");
		$("botoneditornegrita").store("tip:text",  "Escribir en negrita");
		$("botoneditoritalica").store("tip:title", "Itálica");
		$("botoneditoritalica").store("tip:text",  "Escribir en cursiva");
		$("botoneditorsubrayado").store("tip:title", "Subrayado");
		$("botoneditorsubrayado").store("tip:text",  "Escribir con texto subrayado");
		$("botoneditorentidades").store("tip:title", "Convertir entidades");
		$("botoneditorentidades").store("tip:text",  "Convertir a caracteres especiales las entidades &lt;, &gt; y &amp;");
		$("botoneditorcodigo").store("tip:title", "Código");
		$("botoneditorcodigo").store("tip:text",  "Escribir un pedazo de código");
		var tipsGrande3 = new Tips('.cargatipgrande', {"showDelay": 300, "hideDelay": 150, "offsets": {'x': 15, 'y': 10}, "className": "tipgrande"});
	}
});

