
function detectar_browser(){
	var nombre = navigator.appName;
	if (nombre == "Microsoft Internet Explorer"){
	    return 0;
	    }
	else{   
	     return 1;
	  }
}

CargaNorma = function(id_norma, id_version, id_parte, url, buscar) {

	var paquete = 2500; // peso en bytes aproximado de cada paquete que envia firefox 
	var num_partes = 0;
	var peso_total_norma = "";
	var pesoActual="";  
	var porcentaje = 0; // porcentaje de descarga
	
	this.successCN = function(req){
		XML = req.responseText;
		XML = escape(XML);
        document.getElementById('status').style.display = 'none';
		document.getElementById('status').innerHTML = "";
	    creaToc();
	    
	    if (Interval_CompletarCargaTexto == -1) {
			Interval_CompletarCargaTexto = setInterval('CompletarCargaTexto()', 500);
		}
		document.close();
	    
	};
	

	this.failureCN = function(responseText, responseXML ){ 
		var msg = "Ha ocurrido un error, <a href=\"javascript:NavegarNorma('"+id_norma+"','"+id_parte+"','"+id_version+"','"+buscar+"',false);\">Favor reintentelo.</a> ";
		msg += "<br /><br />Si el problema persiste, <a href=\"javascript:enviarConsulta('46#normal#idNorma:"+id_norma+" idParte:"+id_parte+" idVersion:"+id_version+"#()');\">favor comuniquese con nosotros</a>";
		
		document.getElementById('status').innerHTML = msg;
	};
	
	this.complete = function(req) {
	};
	
	this.interactiveCN = function(req){
		var msg_peso="0%";
		
		num_partes += 1;
		if (!peso_total_norma){
			peso_total_norma = req.getResponseHeader("Content-Length");
		}
		else {
			var kilosTotal = Math.round(parseInt(peso_total_norma) / 1024);
			var kilosParte = Math.round(parseInt(num_partes*paquete) / 1024);
			var porcent = Math.round((kilosParte/kilosTotal)*100);
			if (porcent <= 100) {
				porcentaje = porcent;
			}
			msg_peso = porcentaje + "%";
		}
		
		var msg = "Descargando Norma..." + msg_peso + "<br/>";
		msg += "Tama&ntilde;o: " + parseInt(peso_total_norma/1024) + " KBytes<br/>";
		document.getElementById('status').style.zIndex = 132;
		document.getElementById('status').innerHTML = msg;
	};
	
	var params = {
		method:'get',
		onSuccess: this.successCN, 
		onFailure: this.failureCN,
		onInteractive: this.interactiveCN,
		parameters: {idNorma: id_norma, idVersion: id_version,idParte:id_parte}
	};
	this.requestCN = new Ajax.Request(url + '/scripts/getXML2', params);
};

CargaLinkModificatoria = function(idNorma, idParte, idVersion, fechaUltMod, div) {
	return true;
	/**************************/
	/** CACHE                 */
	var id_item = creaIdItemCache(idNorma,idParte,idVersion);
	if(CacheClient.existe(id_item,'ultima_modificacion')){
		var contenido = CacheClient.get(id_item,"ultima_modificacion");
		document.getElementById(div).innerHTML = contenido;
		return true;
	}
	/**************************/
	
    var url = window.parent.url;
    
    this.successCLM = function(req){
        var cont = "";
        cont = "Ultima Modificacion: ";
        if (fechaUltMod=="") {
            cont += "No tiene";
        }
        else {
            cont += '<a href="'+req.resposeText+'">'+fechaUltMod+'</a>';
        }
        document.getElementById(div).innerHTML = cont;
		CacheClient.agregar(id_item,"ultima_modificacion",cont);
    };

    this.failureCLM = function(){ 

    };
    
    var params = {
        method:'get',
        onSuccess: this.successCLM, 
        onFailure: this.failureCLM,
        parameters:  {idNorma: idNorma, idParte: idParte, idVersion: idVersion}
    };

    this.requestCLM = new Ajax.Request(url + '/scripts/linkModificatoria', params);
}


function getImagenCargando(url) {
	var html = "";
	html += '&nbsp;<span class="cargandoWhite" >&nbsp;</span>';
	return html;
}

function getImagenCargandoWhite(url) {
	var html = "";
	html += '&nbsp;<span class="cargandoWhite20" >&nbsp;</span>';
	return html;
}
function getImagenCargandoGris(url){
	var html = "";
	html += '<span class="cargandoGris" >&nbsp;</span>';
	return html;
}
    var OpcionesTemporales = new Array();
    var OpcionesOriginales = new Array();
    
function SeleccionaOpcionesTemporales(){
		var iframeDoc = getIframeDoc();
		if (OpcionesTemporales[0] == 1){ //ver Alertas
			iframeDoc.getElementById('ops_ver_alertas').checked = true
		}else{
			iframeDoc.getElementById('ops_ver_alertas').checked = false
		}
		if (OpcionesTemporales[1] == 1){ //ver Notas BCN
			iframeDoc.getElementById('ops_ver_notas_bcn').checked = true
		}else{
			iframeDoc.getElementById('ops_ver_notas_bcn').checked = false
		}
		if (OpcionesTemporales[2] == 1){ //ver Notas Originales
			iframeDoc.getElementById('ops_ver_notas_originales').checked = true
		}else{
			iframeDoc.getElementById('ops_ver_notas_originales').checked = false
		}
		if (OpcionesTemporales[3] == 1){ //ver Notas al Pie 
			iframeDoc.getElementById('ops_ver_notas_al_pie').checked = true
		}else{
			iframeDoc.getElementById('ops_ver_notas_al_pie').checked = false
		}
		if (OpcionesTemporales[4] == 1){ //ver partes eliminadas
			iframeDoc.getElementById('ops_ver_partes_eliminadas').checked = true
		}else{
			iframeDoc.getElementById('ops_ver_partes_eliminadas').checked = false
		}
		if (OpcionesTemporales[5] == 1){ //ver archivos binarios
			iframeDoc.getElementById('ops_ver_archivos_binarios').checked = true
		}else{
			iframeDoc.getElementById('ops_ver_archivos_binarios').checked = false
		}		
		if (OpcionesTemporales[6] == 1){ //ver HiperVínculos
			iframeDoc.getElementById('check_hipervinculos_pref').checked = true
		}else{
			iframeDoc.getElementById('check_hipervinculos_pref').checked = false
		}	
	}
	
var var_cambiaronPreferencias = false;
function cambiaronPreferencias (){
	return var_cambiaronPreferencias;
}
function CambiaValor(obj){
	if(obj.value=="true"){
		obj.value = "false";
	}else{
		obj.value = "true";
	}
}
function setOpcionesTemporales(obj,posicion){
	obj = document.getElementById(obj);
	if(obj.checked==true){
		OpcionesTemporales[posicion] = 1;
	}else{
		OpcionesTemporales[posicion] = 0;
	}
	//var_cambiaronPreferencias = true;
}
var SecargaronPreferencias = false;
function prefereciasCargadas(){
	return SecargaronPreferencias;
}

function MarcarPreferenciasCargadas(){
	SecargaronPreferencias = true;
}

var AplicaCambiosPreferencias = function (){
var checkeos = new Array("ops_ver_alertas","ops_ver_notas_bcn","ops_ver_notas_originales","ops_ver_notas_al_pie","ops_ver_partes_eliminadas","ops_ver_archivos_binarios","check_hipervinculos_pref");
if(!prefereciasCargadas()){
	for(var i=0;i < checkeos.length;i++){
		if(document.getElementById(checkeos[i]).checked==true){
			parent.OpcionesTemporales.push(1);
		}else{
			parent.OpcionesTemporales.push(0);
		}
	}
	parent.MarcarPreferenciasCargadas();
}
};

CargarAlertas = function(idNorma,idVersion,idParte){
	CargaAlertasNivelParteJS(idNorma,idParte,idVersion);
	return true;
	/**************************/
	/** CACHE                 */
	var id_item = creaIdItemCache(idNorma,idParte,idVersion);
	if(CacheClient.existe(id_item,"alertas")){
		var contenido = CacheClient.get(id_item,"alertas");
		document.getElementById('box_alertas').innerHTML = contenido;
		return true;
	}
	/**************************/
	var d = new Date();
	var time = d.getTime()+Math.random();
	var msg = '<table class="alertasNorma">';
	msg += '<tr>';
	msg += '<td class="tdalerta" style="height:24px">';
	msg += getImagenCargandoGris(url);
	msg += '</td>';
	msg += '</tr>';
	msg += '</table>';

	document.getElementById('box_alertas').innerHTML = msg;	

	this.successCAS = function(req){
		var HTML = req.responseText;
		document.getElementById('box_alertas').innerHTML = HTML;
		CacheClient.agregar(id_item,"alertas",HTML);
	};
	
	this.failureCAS = function(responseText, responseXML ){ 
		var msg = "";
		document.getElementById('box_alertas').innerHTML = msg;
		document.close();
	};
	
	var paramsCAS = {
		method:'get',
		onSuccess: this.successCAS, 
		onFailure: this.failureCAS,
		parameters: {idNorma: idNorma, idVersion: idVersion,idParte: idParte, r: time}
	};
	this.requestCAS = new Ajax.Request(url + '/resultadoAlertas', paramsCAS);
};

CargarMetadatos = function(idNorma,idVersion,idParte){
	//cargarMetadatosJS();
	//return true;
	
	if (typeof(idNorma) == 'undefined') {
		var idNorma = $F('idNorma_interna');
		var idParte = $F('idParte_interna');
		var idVersion = $F('idVersion_interna');
	}else{
		if (!(document.getElementById('info_datos').style.display == "block")) {
			return true;	
		}
	}

	var mensajeAbierto = false;
	if (document.getElementById('mensaje_carga').style.display != "") {
		document.getElementById('mensaje_carga').innerHTML = "Cargando... espere un momento..." + getImagenCargando("");
		document.getElementById('mensaje_carga').style.display = "";
		mensajeAbierto = true;
	}
	/**************************/
	/** CACHE                 */
	var id_item = creaIdItemCache(idNorma,idParte,idVersion);
	if(CacheClient.existe(id_item,"datos")){
		var contenido = CacheClient.get(id_item,"datos");
		document.getElementById('_box_metadatos_').innerHTML = contenido;
		ajustarTam('norma','iframeContenido_norma');
		if(mensajeAbierto){
			document.getElementById('mensaje_carga').style.display = "none";
			document.getElementById('mensaje_carga').innerHTML = "";
		}
		return true;
	}
	/**************************/
	var d = new Date();
	var time = d.getTime()+Math.random();
	var msg = '<table class="metadatosNorma">';
	msg += '<tr>';
	msg += '<td class="titTabla">';
	msg += 'Datos /';
	msg += getImagenCargandoGris(url);
	msg += '</td>';
	msg += '</tr>';		
	msg += '</table>';		
	document.getElementById('_box_metadatos_').innerHTML = msg;	

	this.successCMS = function(req){
		var HTML = req.responseText;
		document.getElementById('_box_metadatos_').innerHTML = HTML;
		ajustarTam('norma','iframeContenido_norma');
		CacheClient.agregar(id_item,"datos",HTML);
		if(mensajeAbierto){
			document.getElementById('mensaje_carga').style.display = "none";
			document.getElementById('mensaje_carga').innerHTML = "";
		}
	};
	
	this.failureCMS = function(responseText, responseXML ){ 
		var msg = "";
		document.getElementById('_box_metadatos_').innerHTML = msg;
		if(mensajeAbierto){
			document.getElementById('mensaje_carga').style.display = "none";
			document.getElementById('mensaje_carga').innerHTML = "";
		}
		document.close();
	};
	
	var paramsCMS = {
		method:'get',
		onSuccess: this.successCMS, 
		onFailure: this.failureCMS,
		parameters: {idNorma: idNorma, idVersion: idVersion,idParte: idParte, r: time}
	};
	this.requestCMS = new Ajax.Request(url + '/resultadoDatosNorma', paramsCMS);
};

CargarLinkModificatoria = function(idNorma,idVersion,idParte){
	/**************************/
	/** CACHE                 */
	var id_item = creaIdItemCache(idNorma,idParte,idVersion);
	if(CacheClient.existe(id_item,"ultima_modificacion")){
		var contenido = CacheClient.get(id_item,"ultima_modificacion");
		document.getElementById('_box_modificatoria_').innerHTML = contenido;
		parent.construyePath();
		return true;
	}
	/**************************/

	var arrParte = getArregloByIdParte(idParte);
	
	if (!arrParte) {
		alert("No se ha encontrado la parte con ID = " + idParte)
		return false;
	}
	var metadatos 		= arrParte[2];
	var cantidades 		= metadatos.getCantidadesVinculaciones();
	var encontroModif   = false;
	for (var i = 0; i < cantidades.length; i++) {
		if (cantidades[i].tipo == "MODIFICACION") {
			encontroModif = true;
			break;	
		}
	}
	if(!encontroModif){
		CacheClient.agregar(id_item, "ultima_modificacion", '');
		document.getElementById('_box_modificatoria_').innerHTML = '';
		return true;
	}
	
	var idTipoParte  	 	= metadatos.getTipoParteID();
	if(!(idTipoParte in oc(["0","170","6","10","11"]))){
		var listaIdsVinc  	= metadatos.getListaIdsVinc();
		listaIdsVinc 		= listaIdsVinc.join(",");
	}else{
		listaIdsVinc		= "";	
	}
	
	
	var d = new Date();
	var time = d.getTime()+Math.random();
	var msg = getImagenCargandoGris(url);
	document.getElementById('_box_modificatoria_').innerHTML = msg;	

	this.successCRLM = function(req){
		var HTML = req.responseText;
		document.getElementById('_box_modificatoria_').innerHTML = HTML;
		//document.getElementById('mensaje_carga').style.display = "none";
		parent.construyePath();
		CacheClient.agregar(id_item,"ultima_modificacion",HTML);
	};
	
	
	this.failureCRLM = function(responseText, responseXML ){ 
		var msg = "";
		document.getElementById('_box_modificatoria_').innerHTML = msg;
		//document.getElementById('mensaje_carga').style.display = "none";
		parent.construyePath();
		document.close();
	};
	
	var paramsCRLM = {
		method:'get',
		onSuccess: this.successCRLM, 
		onFailure: this.failureCRLM,
		parameters: {idNorma: 		idNorma, 
					 idVersion: 	idVersion,
					 idParte: 		idParte, 
					 listaIdsVinc:	listaIdsVinc,
					 r: 			time}
	};
	this.requestCRLM = new Ajax.Request(url + '/resultadoModificatoria', paramsCRLM);
};

CargarVinculaciones = function(idNorma,idVersion,idParte,indice_parte_cargada){
	cargaVinculacionesJS();
	return true;
	/**************************/
	/** CACHE                 */
	var id_item = creaIdItemCache(idNorma,idParte,idVersion);
	if(CacheClient.existe(id_item,"vinculaciones")){
		var contenido = CacheClient.get(id_item,"vinculaciones");
		document.getElementById('box_vinculaciones').innerHTML = contenido;
		document.getElementById('box_vinculaciones2').innerHTML = contenido;
		return true;
	}
	/**************************/
	var d = new Date();
	var time = d.getTime()+Math.random();
	msg = getImagenCargandoGris(url);
	document.getElementById('box_vinculaciones').innerHTML = msg;	
	document.getElementById('box_vinculaciones2').innerHTML = msg;
	var nodo = arregloPartes[indice_parte_cargada][2];
	var tipoParte = nodo.getTipoParteID();
	
	this.successCVS = function(req){
		var HTML = req.responseText;
		document.getElementById('box_vinculaciones').innerHTML = HTML;
		document.getElementById('box_vinculaciones2').innerHTML = HTML;
		CacheClient.agregar(id_item,"vinculaciones",HTML);
	};
	
	this.failureCVS = function(responseText, responseXML ){ 
		var msg = "";
		document.getElementById('box_vinculaciones').innerHTML = msg;
		document.close();
	};
	
	var paramsCVS = {
		method:'get',
		onSuccess: this.successCVS, 
		onFailure: this.failureCVS,
		parameters: {idNorma: idNorma, idVersion: idVersion,idParte: idParte,tipoParte: tipoParte, r: time}
	};
	this.requestCVS = new Ajax.Request(url + '/resultadoVinculaciones', paramsCVS);
};


CargarContenidoAjax = function(idNorma,idVersion,idParte,buscar,indice_parte_cargada){
	var d = new Date();
	var time = d.getTime()+Math.random();

	var paquete = 4096; // peso en bytes aproximado de cada paquete que envia firefox 
	var num_partes = 0;
	var peso_total_norma = "";
	var pesoActual="";  
	var porcentaje = 0; // porcentaje de descarga
	var HTML = "";

	this.successCCA = function(req){
		HTML = req.responseText;
		
		//document.getElementById('mensaje_carga').style.display = "none";
		//document.getElementById('mensaje_carga').innerHTML = "";
		document.getElementById('iframeContenido_norma').innerHTML = HTML;
		parent.FndocumentoCargado();
		parent.AplicaCambiosPreferencias();
		parent.SeleccionaOpcionesTemporales();
		
		parent.cargarVersionesAjax(idNorma,idVersion,idParte,indice_parte_cargada);
		setTimeout(function(){
			parent.CargarLinkModificatoria(idNorma,idVersion,idParte);
		},100)

		setTimeout(function(){
			parent.CargarMetadatos(idNorma,idVersion,idParte);
		},500)
	
		setTimeout(function(){
			parent.CargarVinculaciones(idNorma,idVersion,idParte,indice_parte_cargada);
		},1000)

		setTimeout(function(){
			parent.CargarAlertas(idNorma,idVersion,idParte);
		},1500)
		
		document.close();
	};
	
	this.loadingCCA = function(req){
		var msg = __mensaje_carga__;
		//msg += getImagenCargando(url);
		document.getElementById('mensaje_carga').style.display = "";	
		document.getElementById('mensaje_carga').innerHTML = msg;	
	};
	
	this.failureCCA = function(responseText, responseXML ){ 
		var msg = "Error al cargar Contenido Ajax  !!...";
		document.getElementById('mensaje_carga').innerHTML = msg;
		document.close();
	};
	
	this.completeCCA = function(req) {
		//document.getElementById('mensaje_carga').style.display = "none";	
		//document.getElementById('mensaje_carga').innerHTML = "";
	};
	
	this.interactiveCCA = function(req){
		var msg_peso="0";
		
		num_partes += 1;
		if (!peso_total_norma){
			peso_total_norma = req.getResponseHeader("Content-Length");
		}
		else {
			var kilosTotal = Math.round(parseInt(peso_total_norma) / 1024);
			var kilosParte = Math.round(parseInt(num_partes*paquete) / 1024);
			var porcent = Math.round((kilosParte/kilosTotal)*100);
			if (porcent <= 99) {
				porcentaje = porcent;
			}
			msg_peso = porcentaje + "%";
		}
		
		//var msg = "Descargando Norma..." + msg_peso;
		//document.getElementById('mensaje_carga').innerHTML = msg;
	};
	
	var paramsCCA = {
		method:'get',
		onSuccess: this.successCCA, 
		onFailure: this.failureCCA,
		onLoading: this.loadingCCA,
		onInteractive: this.interactive,
		parameters: {idNorma: idNorma, idVersion: idVersion,idParte: idParte, buscar: buscar, r: time }
	};
	//prompt("s",url + '/contenido_norma');
	//prompt("s2",paramsCCA);
	this.requestCCA = new Ajax.Request(url + '/contenido_norma', paramsCCA);
		
	};

function cargaVinculacionesVersionesAjax(idNorma, idParte, fechasVersiones, listaIdsVinc, fechasFinVigencia, mensajeAbierto, movido_a, movido_de, texto_refundido){
	this.successCVVA = function(req){
		try{
			setearVinculacionesVersiones(req.responseText);
		}catch(e){
			alert(e);
		}
		if(mensajeAbierto){
			document.getElementById('mensaje_carga').style.display = "none";
			document.getElementById('mensaje_carga').innerHTML = "";
		}
	};
	
	this.failureCVVA = function(req, responseXML ){ 
		try{
			setearVinculacionesVersiones("{'vinculaciones':[],'refundidos':[]}");
		}catch(e){
			alert(e);
		}
		if(mensajeAbierto){
			document.getElementById('mensaje_carga').style.display = "none";
			document.getElementById('mensaje_carga').innerHTML = "";
		}
	};

	this.paramsCVVA = {
						method:'post',
						onSuccess: this.successCVVA, 
						onFailure: this.failureCVVA,
						parameters: {idNorma: 			idNorma,
									 fechasVersiones: 	fechasVersiones,
									 idParte: 			idParte,
									 listaIdsVinc:		listaIdsVinc,
									 fechasFinVigencia:	fechasFinVigencia,
									 movido_a:			movido_a,
									 movido_de:			movido_de,
									 texto_refundido:	texto_refundido,
									 r: 				time}
				
					};

	var d = new Date();
	var time = d.getTime()+Math.random();

	this.requestCVVA = new Ajax.Request(url + '/resultadoVersiones', this.paramsCVVA);

};
cargarVersionesAjax = function (idNorma, idVersion, idParte,indice_parte_cargada){
	if (document.getElementById('info_version').style.display == "block") {
		cargarVersionesJs();
	}
	__VERSIONES_CARGADAS__ = true;
	return true;
	
	__VERSIONES_CARGADAS__ = false;
	if (typeof(indice_parte_cargada)=='undefined'){
		indice_parte_cargada = id_parte_cargada;
	}
	/**************************/
	/** CACHE                 */
	var id_item = creaIdItemCache(idNorma,idParte,idVersion);
	if(CacheClient.existe(id_item,"version")){
		var contenido = CacheClient.get(id_item,"version");
		document.getElementById('box_versiones').innerHTML = contenido;
		//Esta funcion y valor de la variable estan definidos en resultadoVersiones.pt
        var objMostrarFechaDerogacion = document.getElementById("mostrarFechaDerogacion");
		if (objMostrarFechaDerogacion) {
			var mostrarFechaDerogacion = objMostrarFechaDerogacion.getAttribute("value");
			FnMostrarFechaDerogacion(mostrarFechaDerogacion);
		}
		__VERSIONES_CARGADAS__ = true;
		return true;
	}
	/**************************/
	var d = new Date();
	var time = d.getTime()+Math.random();

	var paquete = 4096; // peso en bytes aproximado de cada paquete que envia firefox 
	var num_partes = 0;
	var peso_total_norma = "";
	var pesoActual="";  
	var porcentaje = 0; // porcentaje de descarga
	var HTML = "";
	var statusVersiones = document.getElementById("statusVersiones");

	var msg = "<div style='height:20px;'>Preparando Versiones. (Espere un momento...)";
	msg += getImagenCargandoWhite(url);
	msg += "</div>";
	document.getElementById('box_versiones').style.display = "";	
	document.getElementById('box_versiones').innerHTML = msg;

	msg = "<div style='height:20px;'>Preparando Versiones. (Espere un momento...)";
	msg += getImagenCargando(url);
	msg += "</div>";
	statusVersiones.style.display = "none";
	statusVersiones.innerHTML = msg;

	
	this.successCVA = function(req){
		var HTML = req.responseText;
		if (indice_parte_cargada == id_parte_cargada) {
			document.getElementById('box_versiones').innerHTML = HTML;
			
			//Esta funcion y valor de la variable estan definidos en resultadoVersiones.pt
			var objMostrarFechaDerogacion = document.getElementById("mostrarFechaDerogacion");
			if (objMostrarFechaDerogacion) {
				var mostrarFechaDerogacion = objMostrarFechaDerogacion.getAttribute("value");
				FnMostrarFechaDerogacion(mostrarFechaDerogacion);
			}
			
			document.close();
			parent.ajustarTam('norma', 'iframeContenido_norma');
			statusVersiones.style.display = "none";
			statusVersiones.innerHTML = "";
			__VERSIONES_CARGADAS__ = true;
		}
		CacheClient.agregar(id_item,"version",HTML);
	};
	
	this.failureCVA = function(responseText, responseXML ){ 
		if (indice_parte_cargada == id_parte_cargada) {
			var msg = "No se pudo obtener las versiones ...";
			document.getElementById('box_versiones').innerHTML = msg;
			statusVersiones.innerHTML = msg;
			setTimeut(function(){
				statusVersiones.style.display = "none";
				statusVersiones.innerHTML = "";
			}, 1000);
			document.close();
			__VERSIONES_CARGADAS__ = false;
		}
	};
	
	this.interactiveCVA = function(req){
		if (indice_parte_cargada == id_parte_cargada) {
			var msg_peso = "0%";
			
			num_partes += 1;
			if (!peso_total_norma) {
				peso_total_norma = req.getResponseHeader("Content-Length");
			}
			else {
				var kilosTotal = Math.round(parseInt(peso_total_norma) / 1024);
				var kilosParte = Math.round(parseInt(num_partes * paquete) / 1024);
				var porcent = Math.round((kilosParte / kilosTotal) * 100);
				if (porcent <= 99) {
					porcentaje = porcent;
				}
				msg_peso = porcentaje + "%";
			}
			
			var msg = "Cargando Versiones..." + msg_peso;
			msg += getImagenCargandoWhite(url);
			document.getElementById('box_versiones').innerHTML = msg;
		}
	};
	
	var paramsCVA = {
		method:'get',
		onSuccess: this.successCVA, 
		onFailure: this.failureCVA,
		onInteractive: this.interactiveCVA,
		parameters: {idNorma: idNorma, idVersion: idVersion,idParte: idParte, r: time}
	};
	this.requestCVA = new Ajax.Request(url + '/resultadoVersiones', paramsCVA);
	};

	function RegistraPuntajeNavegar(idNorma,idParte,idVersion){
		var url = parent.urlServidor+"/../Navegar/puntajeNavegar?idNorma="+idNorma+"&idParte="+idParte+"&idVersion="+idVersion+"";
		llamadaAjaxTraza(url);
	}
	
ObtenerPermisosIntemediasUsuario = function(idNorma,idParte){
	var d = new Date();
	var time = d.getTime()+Math.random();
	__USUARIO_PUEDE_VER_INTERMEDIAS__ = false;
	__TERMINO_AJAX_USUARIO_INTERMEDIA__ = false;
	
	this.successOPI = function(req){
		var resultado = req.responseText;

		__USUARIO_PUEDE_VER_INTERMEDIAS__ = true;

		if (trim(resultado) == "0"){
			__USUARIO_PUEDE_VER_INTERMEDIAS__ = false;
		}

		__TERMINO_AJAX_USUARIO_INTERMEDIA__ = true;
	};
	
	this.failureOPI = function(req, responseXML ){ 
		__TERMINO_AJAX_USUARIO_INTERMEDIA__ = true;
		__USUARIO_PUEDE_VER_INTERMEDIAS__ = false;
		document.close();
	};
	
	var paramsOPI = {
		method:'post',
		onSuccess: this.successOPI, 
		onFailure: this.failureOPI,
		parameters: {idNorma: idNorma, idParte: idParte, r: time}
	};
	this.requestOPI = new Ajax.Request(url + '/scripts/fechaVigenciaOriginal', paramsOPI);
};

var objetoDeTextosCacheados = new Object();
var __CACHE_CARGADO__ = false;
var __CACHE_NOT_FOUND_C_N_ = false;
var __CACHE_CARGADO__C_NOTAS_ = false;
var partesCacheadasYCargadas = new Array();
var objetoDeTextosCacheadosCNotas = new Object();

obtenerTextosCacheados = function(idNorma, inicioVigencia, idParte, conNotas){
	if(!considerarCache()){
		__CACHE_CARGADO__ = true;
		__CACHE_CARGADO__C_NOTAS_ = true;
		return;
	}
	
	if (!idParte) {
		idParte = 0;
	}
	if(typeof(conNotas) == 'undefined'){
		conNotas  = false;
	}
	if (!((esNormaCacheable != false) && (idParte in oc(esNormaCacheable[idNorma]['idsParte'])))) {
		__CACHE_CARGADO__ = true;
		__CACHE_CARGADO__C_NOTAS_ = true;
		return;
	}
	var Key1 = idNorma + "_" + idParte + "_" + inicioVigencia+"_"+conNotas;
	var Key = idNorma + "_" + idParte + "_" + inicioVigencia;
	if (Key1 in oc(partesCacheadasYCargadas)) {
		if (!conNotas) {
			__CACHE_CARGADO__ = true;
		}else{
			__CACHE_CARGADO__C_NOTAS_ = true;
		}
		return;
	}

	var paquete = 4096; // peso en bytes aproximado de cada paquete que envia firefox 
	var num_partes = 0;
	var peso_total_norma = "";
	var pesoActual="";  
	var porcentaje = 0; // porcentaje de descarga
	var d = new Date();
	var time = d.getTime() + Math.random();
	if (typeof(idParte) == 'undefined') {
		idParte = 0;
	}
	this.successOTC = function(req){
		if (req.responseText.indexOf("|!|NOT FOUND|!|") > -1) {
			if (!conNotas) {
				__CACHE_CARGADO__ = true;
			}else{
				__CACHE_CARGADO__C_NOTAS_ = true;
				__CACHE_NOT_FOUND_C_N_ = true;
				
			}
			partesCacheadasYCargadas.push(Key1);
		}
		else {
			try {
				if (!conNotas) {
					objetoDeTextosCacheados = eval("(" + req.responseText + ")");
					CacheClient.agregar(Key, 'texto_sin_notas', objetoDeTextosCacheados[Key]);
					objetoDeTextosCacheados[Key] = null;
					__CACHE_CARGADO__ = true;
				}else{
					objetoDeTextosCacheadosCNotas = eval("(" + req.responseText + ")");
					__CACHE_CARGADO__C_NOTAS_ = true;
				}
				partesCacheadasYCargadas.push(Key1);
			} 
			catch (e) {
				alert(e);
				if (!conNotas) {
					__CACHE_CARGADO__ = true;
				}else{
					__CACHE_CARGADO__C_NOTAS_ = true;
				}
				partesCacheadasYCargadas.push(Key1);
			}
		}
		document.getElementById('mensaje_carga').style.display = "none";
	};
	
	this.failureOTC = function(req, responseXML){
		if (!conNotas) {
			__CACHE_CARGADO__ = true;
		}
		else {
			__CACHE_CARGADO__C_NOTAS_ = true;
		}
		//document.getElementById('mensaje_carga').style.display = "none";
	};
	
	this.interactiveOTC = function(req){

		var msg_peso = "0%";
		
		num_partes += 1;
		if (!peso_total_norma) {
			peso_total_norma = req.getResponseHeader("Content-Length");
		}
		else {
			var kilosTotal = Math.round(parseInt(peso_total_norma) / 1024);
			var kilosParte = Math.round(parseInt(num_partes * paquete) / 1024);
			var porcent = Math.round((kilosParte / kilosTotal) * 100);
			if (porcent <= 99) {
				porcentaje = porcent;
			}
			msg_peso = porcentaje + "%";
		}
		
		var msg = "Cargando texto..." + msg_peso;
		document.getElementById('mensaje_carga').innerHTML     = msg;
		document.getElementById('mensaje_carga').style.display = "";
	};
	var paramsOTC = {
		method		 : 'post',
		onSuccess	 : this.successOTC,
		onFailure	 : this.failureOTC,
		onInteractive: this.interactiveOTC,
		parameters	 : {
				idNorma		  : idNorma,
				inicioVigencia: inicioVigencia,
				idParte		  : idParte,
				conNotas	  : conNotas,
				r			  : time
		}
	};
	this.requestOTC = new Ajax.Request(url + '/scripts/getTextosPrecalculados', paramsOTC);
};

function crearArregloTXTJSON(txtJSON){
	txtJSON = String(txtJSON);
	var largoTexto = txtJSON.length;
	var tamano = 3000;
	var iteraciones = Math.ceil(largoTexto / tamano);
	var arreglo = new Array();
	
	for (var i =0;i<iteraciones;i++){
		var start = (i * tamano);
		var start = (i*tamano);
		var stop = start + tamano;
		arreglo.push(txtJSON.substring(start,stop));	
	}
	return arreglo;
}
function validarCacheoNorma(idNorma, inicioVigencia, vez, total){

	var msg = "Validando...";
	document.getElementById('mensaje_carga').innerHTML = msg;
	document.getElementById('mensaje_carga').style.display = "";

	if (typeof(vez) == 'undefined') {
		vez = 0;
	}
	
	if (vez > 10) {
		alert("No se pudo guardar, favor intentelo nuevamente, si el problema persiste, avise al webmaster");
		document.getElementById('mensaje_carga').style.display = "none";
		document.getElementById('mensaje_carga').innerHTML = "";
		return;
	}
	this.succesVCN = function(req){
		alert("operacion realizada con exito");
		document.getElementById('mensaje_carga').style.display = "none";
		document.getElementById('mensaje_carga').innerHTML = "";
	};
	this.failureVCN = function(req){
		setTimeout(function(){
			validarCacheoNorma(idNorma, inicioVigencia, vez + 1,total);
		}, 5000);
	};
	
	var paramsVCN = {
		method: 'post',
		onSuccess: this.succesVCN,
		onFailure: this.failureVCN,
		parameters: {
			idNorma: idNorma,
			inicioVigencia: inicioVigencia,
			total: total
		}
	};
	this.requestVCN = new Ajax.Request(url + '/scripts/SC_validarCacheoNorma', paramsVCN);
	
}

cachearTextoJSON = function(txtJSON,idNorma,inicioVigencia,posicion,arreglo){
	var d = new Date();
	var time = d.getTime() + Math.random();
	
	if(typeof(posicion) == 'undefined'){
		posicion = 0;
	}
	if(typeof(arreglo) == 'undefined'){
		arreglo = crearArregloTXTJSON(txtJSON);
	}
	
	this.successCTJ = function(req){
		try {
			if (posicion + 1  < arreglo.length) {
				var X = Math.round((posicion * 100) / (arreglo.length));
				var msg = "Enviado " + X + "%";
				document.getElementById('mensaje_carga').style.display = "";
				document.getElementById('mensaje_carga').innerHTML = msg;
				arreglo[posicion] = "";
				if(_DETENER_CACHEO_){
					var conf = confirm("Favor confirme que desea detener el proceso de Cacheo");
					if (conf){
						_DETENER_CACHEO_ = false;
						document.getElementById('mensaje_carga').style.display = "none";
						return;
					}else{
						_DETENER_CACHEO_ = false;
					}
				}
				setTimeout(function(){
					cachearTextoJSON("", idNorma, inicioVigencia, posicion + 1, arreglo);
				},1000);
				return;
			}else{
				var strREQ = String(req.responseText);
				if(strREQ.indexOf("EXITO") >= 0){
					alert("Operacion Realizada con Exito");
				}else{
					setTimeout(function(){validarCacheoNorma(idNorma,inicioVigencia,1,arreglo.length)},1000);
				}
			}
			document.getElementById('mensaje_carga').style.display = "none";
			return;
		} 
		catch (e) {
			alert(e);
		}
	};
	
	this.failureCTJ = function(req, responseXML){ 
		alert("Ha ocurrido un error al realizar la operacion, avise al webmaster: "+req.responseText);
	};
	
	var paramsCTJ = {
		method:'post',
		onSuccess: this.successCTJ, 
		onFailure: this.failureCTJ,
		parameters: {idNorma: idNorma, 
					 inicioVigencia: inicioVigencia, 
					 txtJSON: arreglo[posicion],
					 posicion: posicion,
					 total: arreglo.length}
	};
	this.requestCTJ = new Ajax.Request(url + '/scripts/guardaTextosPrecalculados', paramsCTJ);
}

guardarXmlCompletoDeLaNorma = function(){
	this.successGXN = function(req){
		
	};
	this.failureGXN = function(req){
		
	};
	var paramsGXN = {
		method:'get',
		onSuccess: this.successGXN, 
		onFailure: this.failureGXN,
		parameters: {idNorma: idNorma}
	};
	this.requestGXN = new Ajax.Request(url + '/scripts/SC_AgregarNormaAPlone', paramsGXN);
	
};

function guardarCacheNormaParteAjax(txtJson,idNorma){
	this.successCNPA = function(req){
		alert(req.responseText);
	};
	this.failureCNPA = function(req){
		alert(req.responseText);
	};
	var paramsCNPA = {
		method:'post',
		onSuccess: this.successCNPA, 
		onFailure: this.failureCNPA,
		parameters: {
					txtJson: txtJson,
					idNorma: idNorma
					}
	};
	this.requestCNPA = new Ajax.Request(url + '/scripts/SC_GurdarNormaPartesCache', paramsCNPA);
	
};


function cargaWebServicesAjax(nombre, urlws){
	this.success = function(req){
		id_input_carga = 'input_'+nombre;
		document.getElementById(nombre).innerHTML = req.responseText;
		document.getElementById('input_'+nombre).style.display = 'block';
		document.getElementById(id_input_carga).value = 'cargado';
		ajustarTam('norma','iframeContenido_norma');
	};
	this.failure = function(req){
		document.getElementById(nombre).innerHTML = "El contenido del dictamen no se encuentra en línea.";
		ajustarTam('norma','iframeContenido_norma');
	};
	var params = {
		method:'post',
		onSuccess: this.success, 
		onFailure: this.failure,
		parameters: {urlws: urlws}
	};
	this.request = new Ajax.Request(url + '/scripts/getWebservices', params);
};



function obtenerEstadoCachePartes(idNorma,idsPartes,inicioVigencia, indicesPartes){
	
	this.successOECP = function(req){
		var idsPartesR = eval("("+req.responseText+")");
		for (var i = 0; i < idsPartes.length; i++) {
			var obj = $("sarbolTOC"+indicesPartes[i]);
			if (!obj){
				continue;	
			}
			try {
				if (!eval(idsPartesR[idsPartes[i]])) {
					obj.className = "nodeNoCache";
				}
				else {
					if (obj.className == "nodeNoCache") {
						obj.className = "node";
					}
				}
			} 
			catch (e) {
				alert(e);
				continue;
			}
		}
	};
	
	this.failureOECP = function(req){
		alert(req.responseText);
	};
	
	var paramsOECP = {
		method:'post',
		onSuccess: this.successOECP, 
		onFailure: this.failureOECP,
		parameters: {
					idNorma: idNorma,
					idsPartes: idsPartes,
					inicioVigencia: inicioVigencia
					}
	};
	
	this.requestOECP = new Ajax.Request(url + '/scripts/SC_GetEstadoCachePartes', paramsOECP);
	
};

function obtenerEsCodigoONo(idNorma){
	
	this.successOECN = function(req){
		
		if(req.responseText.indexOf("False") > -1){
			return false;
		}
		var href	= trim(req.responseText,"\n");
		href 		= trim(href," ");
//		var texto 	= "<a href='"+href+"' target='_blank'>(Texto no Oficial)</a>"
		var texto 	= "(Texto no Oficial)"

		$('spanEsCodigo').style.display="";
		$('spanEsCodigo').innerHTML = texto;
	};
	
	this.failureOECN = function(req){
		//alert(req.responseText);
	};
	
	var paramsOECN = {
		method:'post',
		onSuccess: this.successOECN, 
		onFailure: this.failureOECN,
		parameters: {idNorma: idNorma}
	};
	
	this.requestOECN = new Ajax.Request(url + '/scripts/getEsCodigo', paramsOECN);
	
};

//EOF