Texto = function(nodo) {
    this.estado = 'inicial'; // estados posibles: 'inicial', 'en proceso', 'completo' 
    this.cargando = false; // indica si se esta cargando texto 
    this.indice_cuerpos = 0;
    this.indice_cuerpo = 0;
    this.textoFinal = "";
    this.con_notas_bcn = false;
    this.con_notas_al_pie = false;
    this.con_notas_originales = false;
    this.nodo = nodo;
    this.writerObj = null; // writerObj es un objeto que implementa el metodo innerHTML
    this.labelPercent = null; // Objeto para desplegar el porcentaje de carga  
    this.labelCargando = null; // Objeto para desplegar mensaje de cargando
    this.Bytes_carga = 50; // Nodos TEXTOS que se cargan por vez
    this.Bytes_carga_inicial = 200; // Nodos TEXTOS que se cargan en la primera iteracion
//    this.Bytes_carga = 20000; // Bytes a cargar en cada intervalo
//    this.Bytes_carga_inicial = 10000; // Bytes que se carga en la primera iteracion
    this.interval = -1;
    this.cuerpos_cargados = 0; // cantidad de cuerpos cargados 
    this.IdsNotasPie = new Array();
    this.muestra_archivos_binarios = false;
    this.muestra_hipervinculos = 0;
    this.TienePartesEliminadas = false;
	this.DivMensaje = null; //Div que muestra el porcentaje de carga del texto
	this.ConDobleArticulado = null; //Se ocupa para no calcular 2 veces si es con Doble articulado
	this.idObjeto = null; //Este id se usa para poder guardar el texto parseado del nodo (CACHE)
	this.tieneNodosHijos = true; //Se usa para saber si se pueden borrar los nodos textos, cuando ya no se usaran.-
	this.id_de_cuerpo = 1000;
    this.iframe = window.document;
    
	this.setIdObjeto  = function (id){
		this.idObjeto = id;
	}
	this.getIdObjeto = function(){
		if (this.idObjeto){
			return this.idObjeto;
		}else{
			alert("El id debe ser seteado al crearse el Objeto, usando 'setIdObjeto(id)'")
		}
	}
	
	this.borrarNodosTextos = function(){
		if (this.estado == "completo" && this.TienePartesEliminadas == false){
			this.nodo = null;
		}
	}
	
    // Realiza la carga de un trozo de texto 
    this.cargar = function() {
        if (this.estado == "completo" || this.cargando == true) {
			return;
		}
        this.parsea();
    };
    
    this.setWriterObj = function(writer) {
    	this.writerObj = writer;
    };
    
    this.setLabelPercent = function(label) {
    	this.labelPercent = label;
    };
	this.resetLabelPercent = function(){
    	var tmp_obj = document.getElementById("porcentaje_carga");
		this.labelPercent = tmp_obj;
	};
    this.setLabelCargando = function(label) {
    	this.labelCargando = label;
    };
    
    this.setDivMensaje = function(div){
    	this.DivMensaje = div;
    };

    
    // Detiene la carga del texto
    this.detenerCarga = function() {
        clearInterval(this.interval);
        this.interval = -1;
		reiniciarMoverMenuLateral();
    };



// #################################################################################
// Ajustes para el nuevo esquema v.10
// #################################################################################

    this.extraeElementosTexto = function(cuerpo) {
        var j=0;
        var arreglo_nodos=new Array();
        var s = new XMLSerializer();  // para convertir a string el nodo
        var nodo_relacion = cuerpo.selectSingleNode('../../ELEMENTOS_DEL_TEXTO').getElementsByTagName("REF_RELACION");
        var nodo_nota = cuerpo.selectSingleNode('../../ELEMENTOS_DEL_TEXTO').getElementsByTagName("NOTA");
        var nodo_nota_al_pie = cuerpo.selectSingleNode('../../ELEMENTOS_DEL_TEXTO').getElementsByTagName("REF_NOTA_AL_PIE");
        var nodo_archivo = cuerpo.selectSingleNode('../../ELEMENTOS_DEL_TEXTO').getElementsByTagName("REF_ARCHIVO_BINARIO");
        if (nodo_nota.length>0 || nodo_nota_al_pie.length>0 || nodo_relacion.length>0 || nodo_archivo.length>0) {
            if (nodo_nota) {
                for (var i=0; i<nodo_nota.length; i++) {
                    var arreglo = new Array(4);
                    arreglo[0] = "NOTA";
                    arreglo[1] = nodo_nota[i].getAttribute('offset');
                    arreglo[2] = nodo_nota[i].getAttribute('offset_end');
                    arreglo[3] = s.serializeToString(nodo_nota[i]);
                    arreglo_nodos.push(arreglo);
                }
            } 
            if (nodo_nota_al_pie) {
                for (var i=0; i<nodo_nota_al_pie.length; i++) {
                    var arreglo = new Array(4);
                    arreglo[0] = "REF_NOTA_AL_PIE";
                    arreglo[1] = nodo_nota_al_pie[i].getAttribute('offset');
                    arreglo[2] = nodo_nota_al_pie[i].getAttribute('offset_end');
                    arreglo[3] = s.serializeToString(nodo_nota_al_pie[i]);
                    arreglo_nodos.push(arreglo);
                }
            }
            if (nodo_relacion) { 
                for (var i=0; i<nodo_relacion.length; i++) {
                    var arreglo = new Array(5);
                    arreglo[0] = "REF_RELACION";
                    arreglo[1] = nodo_relacion[i].getAttribute('offset');
                    arreglo[2] = nodo_relacion[i].getAttribute('offset_end');
                    arreglo[3] = s.serializeToString(nodo_relacion[i]);
                    arreglo[4] = nodo_relacion[i].getAttribute('id_relacion');
                    arreglo_nodos.push(arreglo);
                }
            }
            if (nodo_archivo) {
                for (var i=0; i<nodo_archivo.length; i++) {
                    var arreglo = new Array(4);
                    arreglo[0] = "REF_ARCHIVO_BINARIO";
                    arreglo[1] = nodo_archivo[i].getAttribute('offset');
                    arreglo[2] = nodo_archivo[i].getAttribute('offset_end');
                    arreglo[3] = s.serializeToString(nodo_archivo[i]);
                    arreglo_nodos.push(arreglo);
                }
            }
            // ordena por offset de menor a mayor
            arreglo_nodos = arreglo_nodos.sort(function(a,b){return a[2] - b[2]});
        }
        return arreglo_nodos;
    };
	
    this.ocurrenciasTextoEntreOffsets = function(texto,offset_inicio,offset_termino,textoAContar){
		var ocurrencias = 0;
		//var index = texto.indexOf(textoAContar,offset_inicio);
		var index = texto.indexOf(textoAContar,0);
		while(index != -1 && index < (offset_termino+(ocurrencias*textoAContar.length))){
			ocurrencias++;
			index = texto.indexOf(textoAContar,index+textoAContar.length);
		}
		return ocurrencias;
	};
	
    this.parseaElementosTexto = function(cuerpo) {
        var offset_inicio=0, offset_termino=0, nota_offset=0, nota_offset_end=0;
        var txt_final="", txt_bloque="", txt_resto="", nota_texto="";
        
        var arreglo = this.extraeElementosTexto(cuerpo); // arma arreglo con los elementos del texto
        var texto = cuerpo.childNodes[0].nodeValue;
        texto = replace(texto,"&amp;","&");
        texto = replace(texto,"&","&amp;");
        texto = replace(texto,"<","&lt;");
        texto = replace(texto,">","&gt;");
		
        for (var i=0; i<arreglo.length; i++) {
            nota_offset = parseInt(arreglo[i][1]);
            nota_offset_end = parseInt(arreglo[i][2]);
            nota_texto = arreglo[i][3];
            if (offset_inicio == 0) {
				offset_termino = nota_offset;
			}
			else {
				offset_termino = nota_offset;
			}
			
			var tmp_borrar = offset_termino;
			
			//descuenta las ocurrencias del texto "Que no Existe" para el calculo del offset
			var nro_ocurrencias = this.ocurrenciasTextoEntreOffsets(texto, offset_inicio, offset_termino, cadenaSaltosObligados);
			offset_termino = offset_termino + (nro_ocurrencias*cadenaSaltosObligados.length);
            
			
			// extrae texto antes de la nota
			txt_bloque = texto.slice(offset_inicio,offset_termino);
			//alert("antes "+tmp_borrar+"\ndespues "+offset_termino+"\n"+txt_bloque);
			
			offset_inicio = offset_termino;
            
            if(arreglo[i][0]=="REF_RELACION") {
				nro_ocurrencias = this.ocurrenciasTextoEntreOffsets(texto, 0, nota_offset, cadenaSaltosObligados);
				var l_nota_offset = nota_offset + (nro_ocurrencias*cadenaSaltosObligados.length);
				
				nro_ocurrencias = this.ocurrenciasTextoEntreOffsets(texto, 0, nota_offset_end, cadenaSaltosObligados);
				var l_nota_offset_end = nota_offset_end + (nro_ocurrencias*cadenaSaltosObligados.length);
                
				var txt_hipervinculo = texto.slice(l_nota_offset, l_nota_offset_end);
                txt_final = txt_final + txt_bloque + "<REF_RELACION id_relacion='" + arreglo[i][4] + "'>" + txt_hipervinculo + "</REF_RELACION>";
                txt_resto = texto.slice(l_nota_offset_end);
                offset_inicio = l_nota_offset_end;
            } else {
                txt_resto = texto.slice(offset_termino);
	            if(texto.slice(offset_inicio,offset_inicio+1) == '\n'){
	                txt_final = txt_final + txt_bloque + nota_texto+' ';
				}else{
	                txt_final = txt_final + txt_bloque + nota_texto;
				}
            }
        }
        txt_final = txt_final + txt_resto;  // le agrega el resto del texto
        if (txt_final == "") {
            return cuerpo;  // retorna el nodo porque no tenia elementos del texto 
        }
        else
        {
            txt_final = "<NODO>" + txt_final + "</NODO>";
			//alert(txt_final);
            var cuerpo_con_elementos = Sarissa.getDomDocument();
            cuerpo_con_elementos = (new DOMParser()).parseFromString(txt_final, "text/xml").documentElement;
            cuerpo_con_elementos.normalize(); // junta los nodos de texto adyacentes
            return cuerpo_con_elementos;
        }
    };
    
    // concatena si hay nodos TEXTO seguidos y retorna el num de nodos para incrementar el indice j
    this.concatenaVariosTexto = function(arr_cuerpo) {
        if(arr_cuerpo.nextSibling) {
            var cont = -1;
            var ultimo_texto="";
            var nodos_texto = arr_cuerpo.selectSingleNode('../../TEXTOS').getElementsByTagName("TEXTO");
            var num_texto = nodos_texto.length;
            for (var y=0;y<num_texto;y++) {
                nodos_texto[y].normalize();
                ultimo_texto = ultimo_texto + nodos_texto[y].childNodes[0].nodeValue;
            }
            arr_cuerpo.childNodes[0].nodeValue = ultimo_texto;
            
            // elimina nodos TEXTO sobrantes
            nodo_textos = arr_cuerpo.selectSingleNode('../../TEXTOS');
            for (var j=0;j<num_texto-1;j++) {
                nodo_textos.removeChild(nodo_textos.childNodes[1]); 
            }
            return num_texto; 
        }
        else
        {
            arr_cuerpo.normalize();
            return 0;
        }
    };

// #################################################################################
// FIN Ajustes para el nuevo esquema v.10
// #################################################################################

    // Parsea un elemento cuerpo y retorna el texto procesado
    this.parseaCuerpo = function(cuerpo,nodoXml, objPadre) {
		if(typeof(nodoXml) == 'undefined'){
			nodoXml = null;
		}
		if(typeof(objPadre) == 'undefined'){
			objPadre = this.writerObj;
		}
		var d = document;
    	// reemplaza el cuerpo por el nuevo cuerpo con los elementos del texto incluidos
        var cuerpo_original = cuerpo;
        
		var idParte = cuerpo_original.parentNode.parentNode.parentNode.getAttribute('id_parte');
		if (!idParte){
			alert(cuerpo.parentNode.parentNode.parentNode.tagName);
		}
		this.id_de_cuerpo = idParte;
		
        var cuerpo  = this.parseaElementosTexto(cuerpo);
        
		
        
        var html = "";
		var hijoscuerpo = cuerpo.childNodes;
        for (var z=0;z<hijoscuerpo.length;z++)
        {
            if (hijoscuerpo[z].nodeType==3 || hijoscuerpo[z].nodeName=='REF_RELACION') 
            {
                var textomasrelacion = this.buscaRelacion(hijoscuerpo[z], z, cuerpo_original, 0, objPadre);
                //html =  html + textomasrelacion[1];
                z = textomasrelacion[0]-1;
            }
            else if (hijoscuerpo[z].nodeName=='NOTA' || hijoscuerpo[z].nodeName=='REF_NOTA_AL_PIE')
            {
				var offset = hijoscuerpo[z].getAttribute("offset");
				var offset_end = hijoscuerpo[z].getAttribute("offset_end");
				try{
                	var nota = hijoscuerpo[z].childNodes[0].nodeValue;
                }catch(e){
					var nota = "¡¡NOTA AL PIE revisar XML!!";
				}
				var div = d.createElement("div");
				div.setAttribute("onMouseOver","onMouseOverNotas(this);");
				div.setAttribute("onMouseOut","onMouseOutNotas(this);");
				div.setAttribute("offset",offset);
				div.setAttribute("offset_end",offset_end);
				div.setAttribute("id_de_cuerpo",this.id_de_cuerpo);
				div.setAttribute("onMouseOut","onMouseOutNotas(this);");
				div.className = "colordeFondo";
				div.style.display = "none";
				div.style.position = "absolute";
				div.style.width = "200px";
				 
				if (hijoscuerpo[z].nodeName=='REF_NOTA_AL_PIE') {
					div.setAttribute("name","notas_al_pie");
                }
                else {
                    var tipo_nota = hijoscuerpo[z].getAttribute('tipo_nota');
                    if (tipo_nota && tipo_nota=='0') { 
						div.setAttribute("name","notas_bcn");
                    }
                    else if(tipo_nota && tipo_nota=='1') {
						div.setAttribute("name","notas_originales");
                    }else{
						div.setAttribute("name","");
					}
                }
				objPadre.appendChild(div);
				
				var pre = d.createElement("pre");
				pre.className = "topPre";
				pre.setAttribute("id_de_cuerpo",this.id_de_cuerpo);
				pre.setAttribute("width", '28');
                div.appendChild(pre);
				
                if (hijoscuerpo[z].nodeName=='NOTA') {
				/***********************
					Si viene solo el id de la parte, se navega en forma interna con la funcion buscaIdParte,
					si no
					se navega a la norma con la funcion NavegarNorma
				**********************/
                    this.con_notas_bcn=true;
                    if (hijoscuerpo[z].selectSingleNode('../NOTA/@id_norma') && hijoscuerpo[z].selectSingleNode('../NOTA/@id_version')) {
                        var id_norma = hijoscuerpo[z].getAttribute('id_norma');
                        var id_version = hijoscuerpo[z].getAttribute('id_version');
                        var id_parte = hijoscuerpo[z].getAttribute('id_parte');
                        if(!id_parte){
                        	id_parte = '';
                        }
                        var url = '';
                        if (id_norma && id_norma != '' && id_version && id_version != '') {
							var id_version_formateado = id_version.substring(0, 4) + "-" + id_version.substring(4, 6) + "-" + id_version.substring(6, 8);

							var a = d.createElement("a");
							a.setAttribute("href","javascript:window.parent.NavegarNorma(\"" + id_norma + "\",\"" + id_parte + "\",\"" + id_version_formateado + "\",\"" + buscar + "\",false,\"_blank\")");
							a.appendChild(d.createTextNode(nota.replace(/^\s*/, "")));

							pre.appendChild(a);
						}
						else 
							if (id_parte && id_parte != '') {
								var a = d.createElement("a");
								a.setAttribute("href","javascript:buscaIdParte(\"" + id_parte + "\");");
								a.appendChild(d.createTextNode(nota.replace(/^\s*/, "")));

								pre.appendChild(a);
							}
							else {
								pre.appendChild(d.createTextNode(nota.replace(/^\s*/, "")));
							}
                    }
                    else 
					{
						var span = d.createElement("span");
						span.setAttribute("name","noname");
						span.appendChild(d.createTextNode(nota.replace(/^\s*/, "")));
						pre.appendChild(span);
                    }
                }
                else if (hijoscuerpo[z].nodeName=='REF_NOTA_AL_PIE') {
                    this.con_notas_al_pie=true;
                    var id_nota = hijoscuerpo[z].getAttribute('id_nota');
                    if (id_nota && id_nota!='') {
						var a = d.createElement("a");
						a.setAttribute("href","javascript:void(0);");
						a.setAttribute("onclick","javascript:buscaNotaPieDesdeParte("+id_nota+",this);");
						a.setAttribute("id_nota_al_pie",id_nota);
						a.setAttribute("name","link_ref_nota_pie");
						a.appendChild(d.createTextNode(nota.replace( /^\s*/, "" )));
                    	pre.appendChild(a);
					}
                }
                
                
                var texto_sig_nota = hijoscuerpo[z].nextSibling;
                if (texto_sig_nota && texto_sig_nota.nodeType==3) {
      
	  				if (nodoXml) {
						//comprobar si esta eliminado o no
						var res = this.muestraEstaEliminado(nodoXml);
						if (res[0]) {
							var estaEliminada = "true";
						}else{
							var estaEliminada = "false";
						}
					}else{
						var estaEliminada = "false";
					}
					
					var div_texto = d.createElement("div");
					objPadre.appendChild(div_texto);
					div_texto.setAttribute("name","texto");
					div_texto.style.wihth = width_texto;
					div_texto.style.margin = "0px";
                    
					var pre = d.createElement("pre");
					pre.setAttribute("eliminado",estaEliminada);
					pre.setAttribute("id_de_cuerpo",this.id_de_cuerpo);
					pre.setAttribute("name",'pre_texto');
					pre.style.width="100%";
					
                    var textomasrelacion = this.buscaRelacion(texto_sig_nota, z+1, cuerpo_original, 1, pre);

                    z = textomasrelacion[0]-1;

                    div_texto.appendChild(pre);

                }
            }
        }
        return html;
    };
    this.muestraEstaEliminado = function (cuerpo){
		var metadatosNodo = getMetadatos(cuerpo.parentNode.parentNode);
		try{
			var estaEliminada = metadatosNodo.estaEliminada();
        }catch(e){
			var estaEliminada = false;
		}
		if(estaEliminada){
        	this.TienePartesEliminadas = true;
		}

		return new Array(estaEliminada,'');
		/*
        if (estaEliminada && !this.iframe.getElementById('ops_ver_partes_eliminadas').checked) {
        	display = 'none';
        }else if(estaEliminada){
			display = '';
		}else{
			display = 'none';
		}
		return new Array(estaEliminada,display);
		*/
	};
	
    // Parsea el texto
    this.parsea = function() {
    	if(this.cargando) 
        	return;
			
		if(this.estado == 'inicial'){
			if (detectar_browser()) {// => cualquier excepto IE
				var style_width = '98%';
			}
			else {//=> CASO IE
				var winW = 630, winH = 460;
				if (parseInt(navigator.appVersion) > 3) {
					if (navigator.appName.indexOf("Microsoft") != -1) {
						winW = document.body.offsetWidth;
					}
				}
				var ancho = winW - 300;
				var style_width = ancho + 'px';
			}

			var div = document.createElement("div");

			div.setAttribute("id","div_general");
			div.style.width = style_width;

			this.writerObj.innerHTML = "";
			this.writerObj.appendChild(div);
		}
		var objPadre 	= $('div_general'); 
		this.cargando 	= true;
		this.estado 	= "en proceso";
        var texto 		= "";
		var d 			= document;
        // chequea si esta marcada la opcion de muestra archivos binarios y actualiza variable global
        this.muestra_archivos_binarios = parent.document.getElementById("ops_ver_archivos_binarios").checked;

        // chequea si esta marcada la opcion de muestra hipervinculos y actualiza variable global
        this.muestra_hipervinculos = parent.document.getElementById("check_hipervinculos_pref").checked;
        

        var cargo_texto = false;
        var ult_i = this.indice_cuerpos;
        var ult_j = this.indice_cuerpo;
        var bytes;
		
		////////////////////////////////////////////////////////////////////
		// nuevo codigo 10-01-2008
		var arr_cuerpos = new Array();
		var var_isArticuloConDobleArticulado = null;
		if(this.ConDobleArticulado != null){
			var_isArticuloConDobleArticulado = this.ConDobleArticulado;
		}else{
			var_isArticuloConDobleArticulado = this.isArticuloConDobleArticulado()
		} 
		if(var_isArticuloConDobleArticulado){
			 // solo si es doble articulado se toma solo el primer nodo TEXTOS
			 arr_cuerpos[0] = this.nodo.getElementsByTagName("TEXTOS")[0];
		}
		else 
		{
		     arr_cuerpos = this.nodo.getElementsByTagName("TEXTOS");
		}
		////////////////////////////////////////////////////////////////////
        var iteraciones = -1;
		var total_cuerpos = arr_cuerpos.length;
		for(var i=ult_i; i<arr_cuerpos.length; i++) {
			iteraciones++; 
			if (this.muestra_texto(arr_cuerpos[i]))
            {
                var arr_cuerpo = arr_cuerpos[i].getElementsByTagName("TEXTO");
                for(var j=ult_j; (j<arr_cuerpo.length && cargo_texto==false); j++) 
                {
                    // concatena varios TEXTO seguidos si los hay e incrementa indice j
                    var result_concatena = this.concatenaVariosTexto(arr_cuerpo[j]);
                    
					
					this.parseaCuerpo(arr_cuerpo[j],arr_cuerpos[i], objPadre);
                    j=j+result_concatena;
                    
                    //texto += this.parseaCuerpo(arr_cuerpo[j]);
                    if (this.estado == "inicial") {
						bytes = this.Bytes_carga_inicial;
					}
					else {
						bytes = this.Bytes_carga;
					}
                    if( iteraciones >= bytes) {
                        cargo_texto = true;
                    }
                    this.indice_cuerpo = j+1;
                }
            
                if (this.indice_cuerpo < arr_cuerpo.length) // Aun no terminan cuerpo
                {
                    this.indice_cuerpos = i;
                    ult_i = i;
                }
                else 
                {
                    this.cuerpos_cargados++;
                    this.indice_cuerpos = i+1;
                    this.indice_cuerpo = 0;
                    ult_j = 0;
                    this.muestraArchivoBinario(arr_cuerpos[i], objPadre);
                    this.muestraNotasAlPie(arr_cuerpos[i], objPadre);
				}
                if (cargo_texto == true) {
					break;
				}
            }
            else {
                this.indice_cuerpos=i+1;
                this.cuerpos_cargados++;
            } 
        }

        if(this.indice_cuerpos==arr_cuerpos.length) // Si se completo toda la carga del texto
        {
            this.estado="completo";
            this.detenerCarga();
			var pre = d.createElement("pre");
			pre.setAttribute("name","pre_texto");
			pre.style.display = "none";
			pre.appendChild(d.createElement("br"));
			pre.appendChild(d.createElement("br"));
			objPadre.appendChild(pre);
			objPadre.appendChild(d.createElement("br"));
            //texto += "<pre name='pre_texto' style='display:none'><br /> <br /></pre><br />";
            
			this.muestraArchivoBinarioNivelNorma(this.nodo, objPadre);
			
			this.borrarNodosTextos();
			
			try{eval(onEndCargaTexto);}catch(e){alert("En Texto.js: "+e);}
        }
        else {
            this.estado = "en proceso";
        }

        // si se completo toda la carga del texto
        if(this.indice_cuerpos==arr_cuerpos.length) {
        	this.print("");
			respaldo_norma_texto = "";
            parent.despliega_notas();
            
            // busca y destaca el texto de busqueda en la norma/parte completa
			//mostrarBusquedaCNotas();
        }
        
        this.ver_progreso(total_cuerpos);
        this.cargando = false;
    };
	
	///////////////////////////////////////////////////////////////////////////////////
	//  nueva funcion 10-01-2008
	//Retorna verdadero si el nodo actual es un articulo y además uno de sus hijos es "Doble Articulado"
	this.isArticuloConDobleArticulado = function(){
		// Se modifica funcion, porque se retira la excepcion para los Dobles Articulados, 
		// Ahora se comportan como un agrupador normal.-
		return false;
		
		var tipo = this.nodo.selectSingleNode('@tipo_parte');
		if (tipo && tipo.nodeValue == "6") {
			var EstructFuncionales = this.nodo.getElementsByTagName("ESTRUCTURAS_FUNCIONALES");
			
			for (var l = 0; l < EstructFuncionales.length; l++) {
				var EstructFuncional = EstructFuncionales[l].getElementsByTagName("ESTRUCTURA_FUNCIONAL");
				for (var m = 0; m < EstructFuncional.length; m++) {
					var tipo_hijo = EstructFuncional[m].selectSingleNode('@tipo_parte');
					if (tipo_hijo && tipo_hijo.nodeValue == "13") {
						return true;
					}
				}
			}
		}
			
		return false;
	};
	/////////////////////////////////////////////////////////////////////////////////////
	this.ver_progreso = function(total_cuerpos) {
		var carga = 0;
		if(total_cuerpos > 0) {
			carga = parseInt((this.cuerpos_cargados/total_cuerpos)*100);
		}
		try {
			this.labelPercent.innerHTML = carga + "%";
		} 
		catch (e) {
			try {
				this.DivMensaje.innerHTML = __mensaje_carga__;
				this.resetLabelPercent();
				this.labelPercent.innerHTML = carga + "%";
			}catch(e){
				alert(this.labelPercent);
			}
		}
		parent.ajustarTam('norma','iframeContenido_norma');
		if(carga < 100){
			this.DivMensaje.style.display = "";
		}else{
			this.DivMensaje.style.display="none";
		}
		
		if (this.estado == "completo") {
			try {
				//guardarCacheNormaParte(this.getIdObjeto(), $('div_general').innerHTML);
			} 
			catch (e) {
				alert("En guardarCacheNormaParte:" + e);
			}
		}
	};
	
    this.muestra_texto = function(nodo_cuerpos) {
        var p = nodo_cuerpos.selectSingleNode('../..');
        var tiene_hijos = p.selectSingleNode('./ESTRUCTURAS_FUNCIONALES/ESTRUCTURA_FUNCIONAL');
        // Comprobar si tiene hijos
        if(tiene_hijos) 
        {
            var tipo= p.selectSingleNode('./@tipo_parte');
            // Comprobar que no sea un doble articulado
            if(tipo && tiposEF.getItem(tipo.nodeValue)!="Articulo") 
            {
                var ingresado_por = p.selectSingleNode('./@ingresado_por');
                
                // Si fue ingresado en el proceso de migracion
                // esto debe ser cambiado para que se compare con todo el largo del string
                // que seria "Proceso Migracion Legis II"
                if (ingresado_por && ingresado_por.nodeValue.substr(0, 7) == "Proceso") {
					//return false;
					/*
					 * Esta linea se comento porque existia un error anteriormente en la exportaacion,
					 * y ahora se supone que se arreglo, 
					 * lo que pasaba es que en el agrupador y en el primer nodo hijo aparecia el titulo
					 * del agrupador, ahora el titulo debiese estar solamente en en nodo TEXTO del agrupador.
					 */
					//return true
				}
                
            }
        }
      //comprobar si esta eliminado o no
        var metadatosNodo = getMetadatos(p);
/*		try{
			var estaEliminada = metadatosNodo.estaEliminada();
        }catch(e){
			var estaEliminada = false;
		}
		if(estaEliminada){
        	this.TienePartesEliminadas = true;
        }
        if (estaEliminada && !this.iframe.getElementById('ops_ver_partes_eliminadas').checked) {
        	return false;
        }
*/
        //Comprobar si esta movido
        try{
			if(metadatosNodo.estaMovida()){
	        	return false;
	        }
		}catch(e){
			
		}	
        return true;
    };
    
    // Limpia el texto
    this.limpiar= function() {
        this.estado = "inicial";
        this.textoFinal = "";
        this.writerObj.innerHTML = "";
        this.indice_cuerpos = 0;
        this.indice_cuerpo = 0;
    };
    
    this.print = function(texto) {
        this.textoFinal += texto;
		if (detectar_browser()) {// => cualquier excepto IE
			var style_width = '98%';
		}
		else {//=> CASO IE
			var winW = 630, winH = 460;
			if (parseInt(navigator.appVersion) > 3) {
				if (navigator.appName.indexOf("Microsoft") != -1) {
					winW = document.body.offsetWidth;
				}
			}
			var ancho = winW - 300;
			var style_width = ancho + 'px';
		}

		if (this.textoFinal != "") {
			this.writerObj.innerHTML = "<div id='div_general' style='width:" + style_width + ";'>" + this.textoFinal + "</div>";
			parent.ajustarTam('norma','iframeContenido_norma');
		}
		if (this.estado == "completo") {
			var inHTML = this.writerObj.innerHTML;
			this.iframe.getElementById('old_div').innerHTML = inHTML;
			if (this.textoFinal == "") {
				this.textoFinal = $('div_general').innerHTML;
			}
		}else {
			this.iframe.getElementById('old_div').innerHTML = "";
		}
    };
    
    this.muestraNotasAlPie = function(nodo,objPadre) 
    {
        var d = document;
	    var nota_al_pie = nodo.selectSingleNode('../NOTAS_AL_PIE').getElementsByTagName("NOTA_AL_PIE");
        for (var i=0; i<nota_al_pie.length; i++) {
            
            if (nota_al_pie[i].childNodes[0]) {
                var titulo = nota_al_pie[i].getAttribute('titulo');
                var id_nota = nota_al_pie[i].getAttribute('id_nota');
                var texto = nota_al_pie[i].childNodes[0].nodeValue;
				texto = replace(texto,cadenaSaltosObligados,"\n");
				
				var div = d.createElement("div");
				div.setAttribute("onMouseOver","onMouseOverNotas(this);");
				div.setAttribute("onMouseOut","onMouseOutNotas(this);");
				div.setAttribute("id_de_cuerpo",this.id_de_cuerpo);
				div.setAttribute("name","notas_al_pie");
				div.setAttribute("tipo","nota_al_pie");
				div.className 	   = "colordeFondo";
				div.style.display  = "none";
				div.style.width    = width_texto;
				objPadre.appendChild(div);
                
				var a = d.createElement("a");
				a.setAttribute("id","es_nota_al_pie");
				a.setAttribute("href","javascript:void(0);");
				a.setAttribute("onclick","buscaRefANotaPie("+id_nota+");");
				
				a.setAttribute("name","idnota_" + id_nota);
				div.appendChild(a);
                
				var pre = d.createElement("pre");
				pre.setAttribute("name","pre_nota");
				pre.setAttribute("id_de_cuerpo",this.id_de_cuerpo);
				pre.className  = "topPre";
				pre.style.width = "100%";
				a.appendChild(pre);
                
                // extrae titulo
                if (titulo && titulo.nodeValue!='') {
                    titulo = titulo;
                } else { titulo = "NOTA:"; }
                
                // extrae datos del hipervinculo
				/***********************
					Si viene solo el id de la parte, se navega en forma interna con la funcion buscaIdParte,
					si no
					se navega a la norma con la funcion NavegarNorma
				**********************/
                var id_norma = nota_al_pie[i].getAttribute('id_norma');
                var id_version = nota_al_pie[i].getAttribute('id_version');
                var id_parte = nota_al_pie[i].getAttribute('id_parte');
                var url = '';
                if(!id_parte) id_parte = '';
                if (id_norma && id_norma!='' && id_version && id_version!='') {
                    var id_version_formateado = id_version.substring(0,4) + "-" + id_version.substring(4,6) + "-" + id_version.substring(6,8);
                    var a = d.createElement("a");
					a.setAttribute("href","javascript:NavegarNorma(\"" + id_norma  + "\",\""+id_parte+"\",\"" + id_version_formateado+"\",\""+buscar+"\");");
					a.appendChild(d.createTextNode(titulo));
					a.appendChild(d.createElement("br"));
					a.appendChild(d.createTextNode(texto));
					
                    pre.appendChild(a);
                }else if(id_parte && id_parte != ''){
					var a = d.createElement("a");
					a.setAttribute("href","javascript:buscaIdParte(\"" + id_parte  + "\");");
					a.appendChild(d.createTextNode(titulo));
					a.appendChild(d.createElement("br"));
					a.appendChild(d.createTextNode(texto));
					
					pre.appendChild(a);
				}
                else {
					var span = d.createElement("span");
					span.setAttribute("name","noname");
					span.appendChild(d.createTextNode(titulo));
					span.appendChild(d.createElement("br"));
					span.appendChild(d.createTextNode(texto));

					pre.appendChild(span);
                }
            }
        }
    };
    
    this.buscaRelacion = function(nodo, indice, nodo_original, viene_de, objPadre) {
        var html2 = '';
		var d = document;
        if(viene_de==0) {  // 0:antes de una nota ; 1:despues de una nota
            var div = d.createElement("div");
			div.setAttribute("id","texto");
			div.setAttribute("name","texto");
			div.style.width = width_texto;
			div.style.margin = '0px';
			objPadre.appendChild(div);
			
						
			var pre = d.createElement("pre");
			pre.setAttribute("id_de_cuerpo",this.id_de_cuerpo);
			pre.setAttribute("name",'pre_texto');
			pre.style.width = '100%';
			div.appendChild(pre);
			
			objPadre = pre;
        }
	
	    var resultado = new Array(2);
	    var i=indice;
	    while (nodo) 
	    {
	        if (nodo.nodeName=='REF_ARCHIVO_BINARIO' && this.muestra_archivos_binarios==true) {  
	            var id_archivo = nodo.getAttribute('id_archivo');
	            var visible = nodo.getAttribute('visible');
                var archivo_binario = nodo_original.selectSingleNode('//ARCHIVOS_BINARIOS/ARCHIVO_BINARIO[@id_archivo="'+id_archivo+'"]');
//                var archivo_binario = nodo_original.selectSingleNode('../../../ARCHIVOS_BINARIOS/ARCHIVO_BINARIO[@id_archivo="'+id_archivo+'"]');
	            if (archivo_binario) {
	                var nombre_old = archivo_binario.getAttribute('nombre');
	                var formato = archivo_binario.getAttribute('formato');
	                var tamano = archivo_binario.getAttribute('tamano');
					try{
						var nombre = archivo_binario.childNodes[0].nodeValue;
					}catch(e){
						var nombre = "";
					}
					if (!nombre){nombre=nombre_old;}

					
					var span = d.createElement("span");
					span.setAttribute("name","archivos_binarios");
					objPadre.appendChild(span);
                    var br = d.createElement("br");span.appendChild(br);
					
	                if (formato == 'JPEG' || formato == 'JPG') {
						var a  = d.createElement("a");
						a.setAttribute("href","javascript:verArchivo(" + id_archivo + ", \"" + formato + "\")");
						span.appendChild(a);
						var br = d.createElement("br");span.appendChild(br);
						var br = d.createElement("br");span.appendChild(br);

						var img = d.createElement("img");
						img.setAttribute("border",'0');
						//img.setAttribute("width",'300px');
						img.setAttribute("onload",'revisarDimensionesImagen(this);')
						img.setAttribute("src","archivobinario?id=" + id_archivo + "&formato=" + formato + "");
						img.style.border = "1px solid #666666";
						a.appendChild(img);

						var span = d.createElement("span");
						var br = d.createElement("br");span.appendChild(br);
						span.setAttribute("name","archivos_binarios_caption");
						span.style.display="none";
						objPadre.appendChild(span);
						var a  = d.createElement("a");
						span.appendChild(a);
						var href = "document.getElementById('ops_ver_archivos_binarios').checked = true;";
						href += "muestra_oculta_archivos_binarios('archivos_binarios','ops_ver_archivos_binarios', true);";
						href += "parent.setOpcionesTemporales('ops_ver_archivos_binarios',5);";
						
						a.setAttribute("onclick","javascript:"+href+"");
						a.setAttribute("href","javascript:void(0);");
						a.appendChild(document.createTextNode(nombre));
						var br = d.createElement("br");span.appendChild(br);
						var br = d.createElement("br");span.appendChild(br);
					}
	                if (formato == 'PDF') {
						//var br = d.createElement("br");span.appendChild(br);
						//var br = d.createElement("br");span.appendChild(br);
						span.appendChild(document.createTextNode("Ver archivo adjunto: "));

						var button = d.createElement("button");span.appendChild(button);
						button.setAttribute("id","bot_pdf");

						var a  = d.createElement("a");
						a.setAttribute("href","javascript:verArchivo(" + id_archivo + ", \"" + formato + "\")");
						a.appendChild(document.createTextNode(nombre + " (" + formato + ", " + tamano + " Bytes)"));
						span.appendChild(a);
						var br = d.createElement("br");span.appendChild(br);
						var br = d.createElement("br");span.appendChild(br);
	                }
	            }
	        }
            if (nodo.nodeName=='REF_RELACION') {
	            var id_relacion = nodo.getAttribute('id_relacion');
	            var texto_ref_relacion = nodo.childNodes[0].nodeValue;
	            //var relacion = nodo.selectSingleNode('../../../../RELACIONES/RELACION[@id_relacion="'+id_relacion+'"]');
	            var relacion = nodo_original.selectSingleNode('../../../RELACIONES/RELACION[@id_relacion="'+id_relacion+'"]');

				// si NO se quiere mostrar el hipervinculo
				var display_hipervinculo_normal = ""; 
				var display_hipervinculo_link = "none"; 
                // si se quiere mostrar el hipervinculo
				if(this.muestra_hipervinculos){
					display_hipervinculo_normal = "none"; 
					display_hipervinculo_link = ""; 
				}
				
	            var span_relacion = d.createElement("span");
				span_relacion.setAttribute("name","hipervinculo_link");
				span_relacion.setAttribute("id","hipervinculo_link_"+id_relacion+"");
				span_relacion.style.display = display_hipervinculo_link;
				
				var span_relacion_normal = d.createElement("span");
				span_relacion_normal.setAttribute("name","hipervinculo_normal");
				span_relacion_normal.setAttribute("id","hipervinculo_normal_"+id_relacion+"");
				span_relacion_normal.style.display = display_hipervinculo_normal;
				
				//Se crea el HTML para el link al hipervinculo
				if (relacion) {
	                var tipo_hipervinculo = relacion.selectSingleNode('./HIPERVINCULO/@tipo');
	                if(tipo_hipervinculo) {
	                    if (tipo_hipervinculo.nodeValue == "0") // hipervinculo externo http
	                    {
	                        var enlace = relacion.selectSingleNode("./HIPERVINCULO/ENLACE/text()");
	                        if (enlace) {
								var a = d.createElement("a");
								a.setAttribute("href",enlace.nodeValue);
								a.setAttribute("target","_blank");
	                            a.appendChild(d.createTextNode(texto_ref_relacion));
								span_relacion.appendChild(a);
	                        }
	                    }
	                    if (tipo_hipervinculo.nodeValue == "2" || tipo_hipervinculo.nodeValue == "3") // hipervinculos internos (2 Dentro de la misma norma), (3 a otra norma)
	                    {
	                          var id_norma = relacion.selectSingleNode('./HIPERVINCULO/PARAMETROS/PARAMETRO[@nombre="id_norma"]/text()');
	                          var id_version = relacion.selectSingleNode('./HIPERVINCULO/PARAMETROS/PARAMETRO[@nombre="id_version"]/text()');
	                          var tipo_parte = relacion.selectSingleNode('./HIPERVINCULO/PARAMETROS/PARAMETRO[@nombre="tipo_parte"]/text()');
	                          var id_parte = relacion.selectSingleNode('./HIPERVINCULO/PARAMETROS/PARAMETRO[@nombre="parte"]/text()');
   						  	  var a = d.createElement("a");
							  /**
							   * Falta considerar el Tipo HiperVinculo == 1 ?> Websevice
							   */
							  
	                          if (id_norma && id_norma.nodeValue!='' && id_version && id_version.nodeValue!='') {
	                              if (id_parte && id_parte.nodeValue!='') {
	                                  var local_id_Parte = id_parte.nodeValue;
	                              } 
                                  else {
	                                  var local_id_Parte = '';
	                              }
                                  if (tipo_hipervinculo.nodeValue=="3") {
	                              	  a.setAttribute("href","javascript:window.parent.NavegarNorma(\""+id_norma.nodeValue+"\",\""+local_id_Parte+"\",\""+id_version.nodeValue+"\",\""+buscar+"\");");
                                  }
                                  else if (tipo_hipervinculo.nodeValue=="2") {
	                              	  a.setAttribute("href","javascript:parent.buscaIdParte("+id_parte.nodeValue+");");
                                  } 
                                  a.appendChild(d.createTextNode(texto_ref_relacion));
	                          }
	                          span_relacion.appendChild(a);
	                    }
	                }
					objPadre.appendChild(span_relacion);
	            }
				//Se crea el HTML para el texto sin hipervinculo
                if (relacion) {
					span_relacion_normal.appendChild(d.createTextNode(texto_ref_relacion));
					objPadre.appendChild(span_relacion_normal);
                }
	        }
	        else if (nodo.nodeType == 3) {
				if (nodo.nodeValue.indexOf("&#160;") > -1) {
					objPadre.appendChild(d.createTextNode(replace(nodo.nodeValue,"#160;","")));
				}
				else {
					objPadre.appendChild(d.createTextNode(nodo.nodeValue));
				}
			}
			else {
				break;
			}
	        i++;
	        nodo = nodo.nextSibling;
	    }
	    resultado[0]= i;
	    resultado[1]= "";
	    return resultado
	};
    
    this.muestraArchivoBinarioNivelNorma = function(nodo, objPadre) {  // muestra archivos binarios solo a nivel de NORMA
        var d = document;
		//var link = "";
        if (nodo.selectSingleNode("/NORMA/ARCHIVOS_BINARIOS"))// && verifica_parte == 0)
        {
            var archivo_binario = nodo.selectSingleNode("/NORMA/ARCHIVOS_BINARIOS").getElementsByTagName("ARCHIVO_BINARIO");
            if (archivo_binario) {
                for (var i=0; i<archivo_binario.length; i++) {
                    var id_archivo = archivo_binario[i].getAttribute('id_archivo');
                    var nombre_old = archivo_binario[i].getAttribute('nombre');
					try{
						var nombre = archivo_binario[i].childNodes[0].nodeValue;
					}catch(e){
						var nombre = "";
					}
					
					if (!nombre){nombre=nombre_old;}
                    var formato = archivo_binario[i].getAttribute('formato');
                    var tamano = archivo_binario[i].getAttribute('tamano'); 
					
					var pre = d.createElement("pre");
					pre.setAttribute("name","pre_texto");
					objPadre.appendChild(pre);
                    
					if (formato == 'JPEG' || formato == 'JPG') {
						var span = d.createElement("span");
						span.setAttribute("name","archivos_binarios_hidd");
						span.style.display = "none";
						pre.appendChild(span);
                       
					    __global__con_binarios_imagenes = true;
                       
					    var a = d.createElement("a");
						a.setAttribute("href","#");
						a.setAttribute("id_archivo",id_archivo);
						a.setAttribute("formato",formato);
						span.appendChild(a);
					}
                    else{
						var span = d.createElement("span");
						span.setAttribute("name","archivos_binarios_hidd");
						pre.appendChild(span);
						
						var id_formato = "bot_txt";
						switch(formato.toUpperCase()){
							case "PDF":
								id_formato = "bot_pdf";
								break;
							case "WORD":
								id_formato = "bot_word";
								break;
							case "TXT":
								id_formato = "bot_txt";
								break;
							case "CSV":
								id_formato = "bot_txt";
								break;
						}
                        var a = d.createElement("a");
						a.setAttribute("href","javascript:verArchivo(" + id_archivo + ", \"" + formato + "\")");
						span.appendChild(a);
						var button = d.createElement("button");
						button.setAttribute("id",id_formato);
						a.appendChild(button);
						a.appendChild(d.createTextNode("Descargar " + nombre + " (" + formato + ", " + tamano + " Bytes)"));
						var br = d.createElement("br");
						pre.appendChild(br);
                    }
                }
            }
        }
    };
    
    this.muestraArchivoBinario = function(nodo, objPadre) {
		if(typeof(objPadre)=='undefined'){
			objPadre = null;
		}
		var d = document;
        var link = "";
        if(nodo.selectSingleNode("../../ARCHIVOS_BINARIOS/ARCHIVO_BINARIO"))
		{
			var archivo_binario = nodo.selectSingleNode("../../ARCHIVOS_BINARIOS").getElementsByTagName("ARCHIVO_BINARIO");
            if (archivo_binario) {
                for (var i=0; i<archivo_binario.length; i++) {
                    var id_archivo = archivo_binario[i].getAttribute('id_archivo');
                    var nombre_old = archivo_binario[i].getAttribute('nombre');
					try{
						var nombre = archivo_binario[i].childNodes[0].nodeValue;
					}catch(e){
						var nombre = "";
					}
					if (!nombre){nombre=nombre_old;}
                    var formato = archivo_binario[i].getAttribute('formato');
                    var tamano = archivo_binario[i].getAttribute('tamano'); 
                    var pre = d.createElement("pre");
					pre.setAttribute("name","pre_texto");
					objPadre.appendChild(pre);

                    
					if (formato == 'JPEG' || formato == 'JPG') {
						var span = d.createElement("span");
						span.setAttribute("name","archivos_binarios_hidd");
						span.style.display = "none";
						pre.appendChild(span);

                        __global__con_binarios_imagenes = true;
						var a = d.createElement("a");
						a.setAttribute("href","#");
						a.setAttribute("id_archivo",id_archivo);
						a.setAttribute("formato",formato);
						span.appendChild(a);
                    }
                    else{
						var span = d.createElement("span");
						span.setAttribute("name",'archivos_binarios_hidd');
						pre.appendChild(span);

						var id_formato = "bot_pdf";
						switch(formato.toUpperCase()){
							case "PDF":
								id_formato = "bot_pdf";
								break;
							case "WORD":
								id_formato = "bot_word";
								break;
							case "TXT":
								id_formato = "bot_txt";
								break;
							case "CSV":
								id_formato = "bot_txt";
								break;
						}
						var a = d.createElement("a");
						a.setAttribute("href","javascript:verArchivo(" + id_archivo + ", \"" + formato + "\")");
						span.appendChild(a);
						var button = d.createElement("button");
						button.setAttribute("id",id_formato);
						a.appendChild(button);
						a.appendChild(d.createTextNode(" Descargar " + nombre + " (" + formato + ", " + tamano + " Bytes)"));
	                    var br = d.createElement("br");
						pre.appendChild(br);
                    }
                }
            }
        }
    };
}