PageSourceSearch

https://inegi.org.mx/componentes/mapad3/js/mapa-d3.js

js inegi.org.mx collected 2026-09-24 09:08:05 UTC 110,347 bytes, 2,643 lines download raw bytes

1let urlApiEnti_D3 = 'llamado/API.svc/CatalogoAreaGeografica/entMap/munMap/3/json/tokenMap';
2/// apiIndicadores
3let urlApiIndi_D3 = 'llamado/API.svc/ValoresDesgloseIndicador/indicaMp/entMap/ln/oport/json/tokenMap';
4let urlApiIndi_tm = 'llamado/API.svc/ValoresDesgloseIndicador/indicaMp/entMap/ln/oport/tm/json/tokenMap';
5//apimetadatos
6let urlApiMeta_D3 = 'llamado/API.svc/MetadatoIndicador/ln/indicaMp/0/periodoMp/periodoMp/oport/json/tokenMap';
7let urlApiMeta_tm = 'llamado/API.svc/MetadatoIndicador/ln/indicaMp/0/periodoMp/periodoMp/oport/tm/json/tokenMap';
8let coloresIniciales_D3 = new Array('#3288bd','#64a276', '#b36e02', '#a07fc2', '#ff5465', '#999421', '#599fae' ,'#db290d', '#fc8d59', '#525252', '#4f7d76', '#d419a5');
9let mapasTemObj_D3 = [];
10let inicializa2D_D3 = false;
11let dataEstraFija_D3 = new Array();
12let tituloIndicadores_D3 = false;
13
14
15let rangecolores = []; 
16let paramPeriodoVacio= false; //bandera para conocer si el parametro periodo viene vacio
17let paramUndefined=false; //bandera para saber cuando no mandaron parametros
18let servicio_ocupado=false;
19
20let paleta1= new Array('#d53e4f','#fc8d59','#c5890f','#518a22','#4da46f','#3288bd');
21let paleta2= new Array('#b30019','#ff4847','#8f5c4a','#959595','#737373','#525252');
22let paleta3= new Array('#989861','#9e843b','#c5890f','#db290d','#bd1f24','#97001c');
23let paleta4= new Array('#9f9741','#839d61','#46a491','#327eb8','#3146bd','#383199');
24
25
26const crearMapaTematicoD3 = (paramobj) => {
27    /* 
28    id=id contenedor
29    indica=indicador
30    dato_f=datos fijos
31    ageo=área geografica
32    muv=mostrar último valor 
33    mum= mostrar unidad de medida
34    mum_f= mostrar unidad de medida fija
35    pf=periodo final
36    mup=mostrar el periodo definido
37    mup_f=mostrar el periodo definido fijo
38    mn=mostrar notas
39    mn_f =fuentes  fijas
40    mf=nostrar fuente
41    mf_f =fuentes  fijas
42    mimpr= mostrar boton imprimir 
43    mxls=mostrar boton de descarga xls
44    estra=escala o estratificacion
45    mestra=mostrar radio buttons de estratos
46    estra_f=estratos fijos
47    paleta=paleta de colores o colores fijos
48    mpaleta=mostrar paletas de colores
49    mcompara=mostrar comparación de países
50    cobertura=est/mun/pais
51    etiqueta=fija/over
52    tm
53    */
54
55
56 
57
58    let D3parametros={}; //parametros que enviare a crearmapad3
59    let parametrosOrig={}; //parametros que recibo en la función crearmapaTematicoD3
60    //validamos si se mando parámetros
61    if (paramobj !== undefined) {
62        paramUndefined=false;
63        if(paramobj.etiqueta!=undefined){
64            D3parametros.etiqueta=paramobj.etiqueta;
65        }
66        else
67            D3parametros.etiqueta='over';
68        //validamos si sera un mapa mundi
69        if(paramobj.cobertura!=undefined && paramobj.cobertura==='pais'){
70            try {
71 
72                parametrosOrig=paramobj;
73                // revisar despues en ie no me dejo parametrosOrig={...paramobj};
74                $('#'+paramobj.id).empty();
75                //validacion para indefinidos de tipo boolean
76                parametrosOrig.muv=paramobj.muv;
77                parametrosOrig.mum=paramobj.mum;
78                parametrosOrig.mup=paramobj.mup;
79                parametrosOrig.mn=paramobj.mn;
80                parametrosOrig.mf=paramobj.mf;
81                parametrosOrig.mimpr=paramobj.mimpr;
82                parametrosOrig.mxls=paramobj.mxls;
83                parametrosOrig.mestra=paramobj.mestra;
84                parametrosOrig.mpaleta=paramobj.mpaleta;
85                parametrosOrig.mcompara=paramobj.mcompara;
86                D3parametros.mcompara=paramobj.mcompara;
87                parametrosOrig.tm=paramobj.tm;
88                verificaUndefined(parametrosOrig);
89        
90
91        
92                //validacion para undefined
93                    
94                if(paramobj.mf_f!=undefined)
95                    D3parametros.fuentesAdd=paramobj.mf_f;
96                else
97                    D3parametros.fuentesAdd="";
98
99                if(paramobj.mn_f!=undefined)
100                    D3parametros.notasAdd=paramobj.mn_f;
101                else
102                    D3parametros.notasAdd="";
103        
104                //validamos si nos mandaron estratos fijos, al no ser así se toma los que se envio o en caso la opción por default
105                if(paramobj.estra_f!=undefined){
106                    D3parametros.estratoslim=paramobj.estra_f;
107                    paramobj.estra='fijos';
108                    parametrosOrig.estra='fijos';
109                    parametrosOrig.mestra=false;
110                    D3parametros.estra="1";
111                }else{
112                    if(paramobj.estra!=undefined)
113                        D3parametros.estra=paramobj.estra;
114                    else{
115                        paramobj.estra="3";
116                        D3parametros.estra="3";
117                    }
118                }
119            
120
121
122                //validamos el parámetro paleta
123                if(paramobj.paleta!=undefined){
124                    D3parametros.colores=paramobj.paleta;
125                }
126                else{
127                    D3parametros.colores=['#24a55b'];
128                }
129                    
130        
131                if (paramobj.pf==undefined){
132                    paramPeriodoVacio=false;
133                    paramobj.pf=0;
134                }
135                else if(paramobj.pf!=0||paramobj.pf!='0'){
136                    paramobj.pf;
137                }
138                else{
139                    paramPeriodoVacio=false;
140                    paramobj.pf=0;
141                }
142
143                if(paramobj.mup_f!=undefined){
144                    parametrosOrig.mup_f =paramobj.mup_f;  
145                }
146                else{
147                    parametrosOrig.mup_f='';
148                }
149
150                if(paramobj.mum_f!=undefined){
151                    parametrosOrig.mum_f=paramobj.mum_f;   
152                }
153                else{
154                    parametrosOrig.mum_f='';
155                }
156
157                
158                if(paramobj.cobertura!=undefined){
159                    parametrosOrig.cobertura=paramobj.cobertura;  
160                    D3parametros.cobertura=paramobj.cobertura; 
161                }
162                else{
163                    parametrosOrig.cobertura='est';
164                    D3parametros.cobertura='est';
165                }
166                
167                
168                } catch (error) {
169                    console.log("mapamundi" +error);
170                }
171                let mapDemanda = document.getElementById(paramobj.id);
172                mapDemanda.innerHTML = '';
173                mapDemanda.innerHTML = '<div id="cargaMapa_' + paramobj.id + '" style="width:100%;height:100%;text-align: center;"><img alt="Cargando información..." title="Cargando información..." src="/img/cargando.gif" style="top: 50%;left:50%;position: absolute;"></div>';
174
175                mapDemanda.setAttribute("data-informacion", paramobj.dato_f);
176                mapDemanda.setAttribute('data-ageo', paramobj.ageo);
177                mapDemanda.setAttribute('data-tipoestratos', paramobj.estra);
178                mapDemanda.setAttribute('data-periodo', paramobj.pf);
179                mapDemanda.setAttribute('data-mestra', paramobj.mestra);
180                mapDemanda.setAttribute('data-mpaleta', paramobj.mpaleta);
181                mapDemanda.setAttribute('data-mcompara', paramobj.mcompara);
182                mapDemanda.setAttribute('data-mimpr', paramobj.mimpr);
183                mapDemanda.setAttribute('data-mxls', paramobj.mxls);
184            
185            
186    
187                $(mapDemanda).data('setUnidadM_D3', paramobj.mum == undefined ? false : paramobj.mum);
188                $(mapDemanda).data('setValorM_D3',paramobj.muv == undefined ? false : paramobj.muv);
189                $(mapDemanda).data('NotasM', paramobj.mn == undefined ? false : paramobj.mn);
190                $(mapDemanda).data('setFuentesM', paramobj.mf == undefined ? false : paramobj.mf);
191        //aqui empieza todo con la llamada a setMapasDocD3
192                $(mapDemanda).each(function () { 
193                    setMapasDocD3(this,parametrosOrig,D3parametros) 
194                });
195                document.getElementById('spanUnidad_' + paramobj.id).innerHTML=paramobj.mum_f;
196                document.getElementById('spanPer_' + paramobj.id).innerHTML =parametrosOrig.mup_f;
197                iniciaMapD3(D3parametros,'normal');
198                quitarloading(D3parametros.objeto);
199        }
200        else{
201            if (paramobj.id !== undefined && paramobj.indica !== undefined && paramobj.ageo !== undefined) {
202                    try {
203                            parametrosOrig=paramobj;
204                            // revisar despues en ie no me dejo parametrosOrig={...paramobj};
205                        $('#'+paramobj.id).empty();
206                        //validacion para indefinidos de tipo boolean
207                        parametrosOrig.muv=paramobj.muv;
208                        parametrosOrig.mum=paramobj.mum;
209                        parametrosOrig.mup=paramobj.mup;
210                        parametrosOrig.mn=paramobj.mn;
211                        parametrosOrig.mf=paramobj.mf;
212                        parametrosOrig.mimpr=paramobj.mimpr;
213                        parametrosOrig.mxls=paramobj.mxls;
214                        parametrosOrig.mestra=paramobj.mestra;
215                        parametrosOrig.mpaleta=paramobj.mpaleta;
216                        verificaUndefined(parametrosOrig);
217                
218
219                
220                        //validacion para undefined
221                        if(paramobj.mf_f!=undefined)
222                            D3parametros.fuentesAdd=paramobj.mf_f;
223                        else
224                            D3parametros.fuentesAdd="";
225
226                        if(paramobj.mn_f!=undefined)
227                            D3parametros.notasAdd=paramobj.mn_f;
228                        else
229                            D3parametros.notasAdd="";
230                
231                        //validamos si nos mandaron estratos fijos, al no ser así se toma los que se envio o en caso la opción por default
232                        if(paramobj.estra_f!=undefined){
233                            D3parametros.estratoslim=paramobj.estra_f;
234                            paramobj.estra='fijos';
235                            parametrosOrig.estra='fijos';
236                            parametrosOrig.mestra=false;
237                            D3parametros.estra="1";
238                        }else{
239                            if(paramobj.estra!=undefined)
240                                D3parametros.estra=paramobj.estra;
241                            else{
242                                paramobj.estra="3";
243                                D3parametros.estra="3";
244                            }
245                        }
246                        
247
248
249                        if(paramobj.dato_f!=undefined && paramobj.pf==undefined){
250                            paramobj.mn=false;
251                            paramobj.mf=false;
252                            paramobj.mum=false;
253                        }
254                    
255                        //validamos el parámetro paleta
256                        if(paramobj.paleta!=undefined){
257                            switch (paramobj.paleta) {
258                                case '1':
259                                    parametrosOrig.colorfijo=false;
260                                    D3parametros.paleta=paleta1;
261                                    break;
262                                case '2':
263                                    parametrosOrig.colorfijo=false;
264                                    D3parametros.paleta=paleta2;
265                                    break;
266                                case '3':
267                                    parametrosOrig.colorfijo=false;
268                                    D3parametros.paleta=paleta3;
269                                    break;
270                                case '4':
271                                    parametrosOrig.colorfijo=false;
272                                    D3parametros.paleta=paleta4;
273                                    break;
274                                case '5':
275                                    parametrosOrig.colorfijo=false;
276                                    D3parametros.paleta=paleta5;
277                                    break;
278                                default:
279                                    D3parametros.paleta=paramobj.paleta;
280                                    parametrosOrig.colorfijo=true;
281                                    parametrosOrig.mpaleta=false;
282                                    paramobj.mpaleta=false;
283                                    break;
284                            }
285                        }
286                    else{
287                            D3parametros.paleta="";
288                        }
289                            
290                
291                        if (paramobj.pf==undefined){
292                            paramPeriodoVacio=false;
293                            paramobj.pf=0;
294                        }
295                        else if(paramobj.pf!=0||paramobj.pf!='0'){
296                            paramobj.pf;
297                        }
298                        else{
299                            paramPeriodoVacio=false;
300                            paramobj.pf=0;
301                        }
302
303                        if(paramobj.mup_f!=undefined){
304                            parametrosOrig.mup_f=paramobj.mup_f;   
305                        }
306                        else{
307                            parametrosOrig.mup_f='';
308                        }
309
310                        if(paramobj.mum_f!=undefined){
311                            parametrosOrig.mum_f=paramobj.mum_f;   
312                        }
313                        else{
314                            parametrosOrig.mum_f='';
315                        }
316
317                        
318                        if(paramobj.cobertura!=undefined){
319                            parametrosOrig.cobertura=paramobj.cobertura;  
320                            D3parametros.cobertura=paramobj.cobertura; 
321                        }
322                        else{
323                            parametrosOrig.cobertura='est';
324                            D3parametros.cobertura='est';
325                        }
326                        
327                        
328                    } catch (error) {
329                        console.log("crearMapaTematicoD3undefinned" +error);
330                    }
331                    inicializa2D_D3 = false;
332                    //aquí hay un error porque busco el array pero no hago nada con el
333                    mapasTemObj_D3 = $.grep(mapasTemObj_D3, function (value) {
334                        return value.id != paramobj.id;
335                    });
336                    let mapDemanda = document.getElementById(paramobj.id);
337                    mapDemanda.innerHTML = '';
338                    mapDemanda.innerHTML = '<div id="cargaMapa_' + paramobj.id + '" style="width:100%;height:100%;text-align: center;"><img alt="Cargando información..." title="Cargando información..." src="/img/cargando.gif" style="top: 50%;left:50%;position: absolute;"></div>';
339
340                    mapDemanda.setAttribute("data-informacion", paramobj.dato_f);
341                    mapDemanda.setAttribute('data-indicador', paramobj.indica);
342                    mapDemanda.setAttribute('data-ageo', paramobj.ageo);
343                    mapDemanda.setAttribute('data-tipoestratos', paramobj.estra);
344                    mapDemanda.setAttribute('data-periodo', paramobj.pf);
345                    mapDemanda.setAttribute('data-mestra', paramobj.mestra);
346                    mapDemanda.setAttribute('data-mpaleta', paramobj.mpaleta);
347                    mapDemanda.setAttribute('data-mimpr', paramobj.mimpr);
348                    mapDemanda.setAttribute('data-mxls', paramobj.mxls);
349                
350                    
351            
352                    $(mapDemanda).data('setUnidadM_D3', paramobj.mum == undefined ? false : paramobj.mum);
353                    $(mapDemanda).data('setValorM_D3',paramobj.muv == undefined ? false : paramobj.muv);
354                    $(mapDemanda).data('setPeriodoM_D3', paramobj.mup == undefined ? false : paramobj.mup);
355                    $(mapDemanda).data('NotasM', paramobj.mn == undefined ? false : paramobj.mn);
356                    $(mapDemanda).data('setFuentesM', paramobj.mf == undefined ? false : paramobj.mf);
357            //aqui empieza todo con la llamada a setMapasDocD3
358                    $(mapDemanda).each(function () { 
359                        setMapasDocD3(this,parametrosOrig,D3parametros) 
360                    });
361            }
362            else{
363                    //caso de Directorio pero con parámetros
364                    contm = "<div class='col-md-12 text-right'>";
365                    contm += "<div class='row'>";
366                    contm += "</div>";
367                    contm += "</div>";
368                    contm += "<div id='mapaTematico'  class='mapTem'  data-ageo='" +paramobj.ageo + "' data-tipoEstratos='" + paramobj.estra + "' >";
369                    document.getElementById(paramobj.id ).innerHTML = contm;
370                    document.getElementById("mapaTematico").setAttribute("data-informacion", paramobj.dato_f);
371                    paramobj.id='mapaTematico';
372                    let objTematico; 
373                    if ($('div.mapTem').length > 0) {
374                        $('div.mapTem').each(function () { objTematico=this;});
375                    }
376                
377                    try {
378                        parametrosOrig=paramobj;
379                        //validacion para indefinidos de tipo boolean
380                        parametrosOrig.muv=paramobj.muv;
381                        parametrosOrig.mum=paramobj.mum;
382                        parametrosOrig.mup=paramobj.mup;
383                        parametrosOrig.mn=paramobj.mn;
384                        parametrosOrig.mf=paramobj.mf;
385                        parametrosOrig.mimpr=paramobj.mimpr;
386                        parametrosOrig.mxls=paramobj.mxls;
387                        parametrosOrig.mestra=paramobj.mestra;
388                        parametrosOrig.mpaleta=paramobj.mpaleta;
389                        verificaUndefined(parametrosOrig);
390                
391
392                
393                        //validacion para undefined
394                        if(paramobj.mf_f!=undefined)
395                            D3parametros.fuentesAdd=paramobj.mf_f;
396                        else
397                            D3parametros.fuentesAdd="";
398                        
399                        if(paramobj.mn_f!=undefined)
400                            D3parametros.notasAdd=paramobj.mn_f;
401                        else
402                            D3parametros.notasAdd="";
403
404                        //validamos si nos mandaron estratos fijos, al no ser así se toma los que se envio o en caso la opción por default
405                        if(paramobj.estra_f!=undefined){
406                            D3parametros.estratoslim=paramobj.estra_f;
407                            paramobj.estra='fijos';
408                            parametrosOrig.estra='fijos';
409                            parametrosOrig.mestra=false;
410                            D3parametros.estra="1";
411                        }else{
412                            if(paramobj.estra!=undefined)
413                                D3parametros.estra=paramobj.estra;
414                            else{
415                                paramobj.estra="3";
416                                D3parametros.estra="3";
417                            }
418                        }
419                
420                        if(paramobj.paleta!=undefined){
421                            switch (paramobj.paleta) {
422                                case '1':
423                                    parametrosOrig.colorfijo=false;
424                                    D3parametros.paleta=paleta1;
425                                    break;
426                                case '2':
427                                    parametrosOrig.colorfijo=false;
428                                    D3parametros.paleta=paleta2;
429                                    break;
430                                case '3':
431                                    parametrosOrig.colorfijo=false;
432                                    D3parametros.paleta=paleta3;
433                                    break;
434                                case '4':
435                                    parametrosOrig.colorfijo=false;
436                                    D3parametros.paleta=paleta4;
437                                    break;
438                                case '5':
439                                    parametrosOrig.colorfijo=false;
440                                    D3parametros.paleta=paleta5;
441                                    break;
442                                default:
443                                    D3parametros.paleta=paramobj.paleta;
444                                    parametrosOrig.colorfijo=true;
445                                    parametrosOrig.mpaleta=false;
446                                    paramobj.mpaleta=false;
447                                    break;
448                            }
449                        
450                        }
451                    else{
452                            D3parametros.paleta="";
453                        }
454                        
455
456
457                        //validamos si nos mandan dato pero no periodo final, no se mostraria notas, fuentes y unidad de medida porque no se podria consultar el api de metadatos
458                        if(paramobj.dato_f!=undefined && paramobj.pf==undefined){
459                            paramobj.mn=false;
460                            paramobj.mf=false;
461                            paramobj.mum=false;
462                        }
463                
464                        if (paramobj.pf==undefined){
465                            paramPeriodoVacio=true;
466                            paramobj.pf=0;
467                        }
468                        else if(paramobj.pf!=0||paramobj.pf!='0'){
469                            paramobj.pf;
470                        }
471                        else{
472                            paramPeriodoVacio=true;
473                            paramobj.pf=0;
474                        }
475
476                        if(paramobj.mup_f!=undefined){
477                            parametrosOrig.mup_f=paramobj.mup_f;   
478                        }
479                        else{
480                            parametrosOrig.mup_f='';
481                        }
482
483                        if(paramobj.mum_f!=undefined){
484                            parametrosOrig.mum_f=paramobj.mum_f;   
485                        }
486                        else{
487                            parametrosOrig.mum_f='';
488                        }
489
490                        if(paramobj.cobertura!=undefined){
491                            parametrosOrig.cobertura=paramobj.cobertura;  
492                            D3parametros.cobertura=paramobj.cobertura; 
493                        }
494                        else{
495                            parametrosOrig.cobertura='est';
496                            D3parametros.cobertura='est';
497                        }
498                        
499                        
500                    } catch (error) {
501                        console.log("crearMapaTematicoD3undefinned" +error);
502                    }
503                    inicializa2D_D3 = false;
504        
505                    let mapDemanda = document.getElementById(objTematico.id);
506                    mapDemanda.innerHTML = '';
507                    mapDemanda.innerHTML = '<div id="cargaMapa_' + objTematico.id + '" style="width:100%;height:100%;text-align: center;"><img alt="Cargando información..." title="Cargando información..." src="/img/cargando.gif" style="top: 50%;left:50%;position: absolute;"></div>';
508
509                    mapDemanda.setAttribute("data-informacion", paramobj.dato_f);
510                    mapDemanda.setAttribute('data-tipoestratos', paramobj.estra);
511                    mapDemanda.setAttribute('data-periodo', paramobj.pf);
512                    mapDemanda.setAttribute('data-mimpr', paramobj.mimpr);
513                    mapDemanda.setAttribute('data-mxls', paramobj.mxls);
514                    if(paramobj.mestra!=undefined)
515                        do
515cument.getElementById("mapaTematico").setAttribute('data-mestra', paramobj.mestra);
516                    if(paramobj.mpaleta!=undefined)
517                        document.getElementById("mapaTematico").setAttribute('data-mpaleta', paramobj.mpaleta);
518
519                    
520            
521                    $(mapDemanda).data('setUnidadM_D3', paramobj.mum == undefined ? true : paramobj.mum);
522                    $(mapDemanda).data('setValorM_D3',paramobj.muv == undefined ? true : paramobj.muv);
523                    $(mapDemanda).data('setPeriodoM_D3', paramobj.mup == undefined ? true : paramobj.mup);
524                    $(mapDemanda).data('NotasM', paramobj.mn == undefined ? true : paramobj.mn);
525                    $(mapDemanda).data('setFuentesM', paramobj.mf == undefined ? true : paramobj.mf);
526                    if ($('div.mapTem').length > 0) {
527                        $('div.mapTem').each(function () { setMapasDocD3(this,parametrosOrig,D3parametros) });
528                    }
529            }
530        } 
531    } 
532    else {
533        //caso de Directorio sin parámetros
534        paramUndefined=true;
535        D3parametros.estra="3";
536        D3parametros.fuentesAdd="";
537        if ($('div.mapTem').length > 0) {
538            $('div.mapTem').each(function () { setMapasDocD3(this,parametrosOrig,D3parametros) });
539        }
540    }
541    let conCss = cr_elem_D3('link', '', { 'href': '/componentes/mapaTematico/css/mapaTematico.css', 'rel': 'stylesheet' }, ''); 
542
543    document.getElementsByTagName('head')[0].appendChild(conCss);
544   
545};
546
547const verificaUndefined =(parametros) => {
548    for (let property in parametros) {
549        parametros[property] = (parametros[property]!=undefined) ? parametros[property] : false;
550       // console.log(`${property}: ${parametros[property]}`);
551      }
552};
553
554const cambiollamaApi_D3 = () => {
555    let C_direccionServicio = '';
556    if (C_direccionServicio_V == '' || API_V == '') {
557        C_direccionServicio = "/app/api/indicadores/interna_v1_1";
558    }
559    else {
560        C_direccionServicio = C_direccionServicio_V + '_' + API_V;
561    }
562    return C_direccionServicio;
563};
564
565//constructores
566function mapTematico_D3(id, idAgeo) {
567    this.id = id;
568    this.titulo = '';
569    this.total = '';
570    this.periodo = '';
571    this.idEntidad = idAgeo.substring(0, 2);
572    this.nombre = '';
573    this.municipios = new Array();
574    this.indicador = '';
575    this.oportuno = 1;
576    this.anio = '';
577    this.tipoEstratifica = '1';
578    this.unidadMedida = '';
579    this.unidadMedidaM = true;
580    this.valorM = true;
581    this.periodoM = true;
582    this.cobertura='est';
583    //parámetros que ocupo del API, aún no están disponibles
584    this.fuentesM = false;
585    this.notasM = false;
586    this.fuentes = '';
587    this.notas = '';
588}
589
590function paises_D3( nombre, valor, color) {
591    this.nombre = nombre;
592    this.valor = valor;
593    this.coordenadas = new Array();
594    this.color = color;
595    this.mapa;
596}
597
598function municpio_D3(idMunicipio, nombre, valor, color) {
599    this.municipio = idMunicipio;
600    this.nombre = nombre;
601    this.valor = valor;
602    this.coordenadas = new Array();
603    this.estrato = '';
604    this.color = color;
605    this.mapa;
606}
607//elemento para método externo
608function munEnt_D3(idMunicipio, nombre, valor, color,periodoApi) {
609    this.id = idMunicipio;
610    this.nombre = nombre;
611    this.valor = valor;
612    this.estrato = '';
613    this.color = color;
614    this.periodo=periodoApi;
615}
616function arrayfuente (nombrefuente, urlproyecto) {
617    this.nombreFuente = nombrefuente;
618    this.urlProyecto = urlproyecto;
619}
620
621//Prototype mapas
622mapTematico_D3.prototype = {
623    constructor: mapTematico_D3,
624    crearMapaSvg: function (obj) {
625        let divMapaTem = document.getElementById(obj.id);
626        let divTitulo = cr_elem_D3('div', '', { 'class': 'col-md-12', 'style': 'font-size: 16px; text-align: right;' }, obj.titulo + '');
627        divTitulo.appendChild(cr_elem_D3('span', obj.total, { 'id': 'spanTotal_' + obj.id, 'style': 'font-size: 16px;color: #337ab7;font-weight: bold;' }, ''));
628        divTitulo.appendChild(cr_elem_D3('span', obj.total, { 'id': 'spanUnidad_' + obj.id, 'style': 'font-size: 16px;color:#337ab7;' }, ''));
629        let divSpPer = cr_elem_D3('div', '', { 'class': 'col-md-12' }, '');
630        divSpPer.appendChild(cr_elem_D3('span', obj.periodo, { 'id': 'spanPer_' + obj.id, 'style': 'font-size: 12px;float: right;' }, ''));
631        divMapaTem.appendChild(divTitulo);
632        divMapaTem.appendChild(divSpPer);
633        divSpMapE = cr_elem_D3('div', '', {'id': 'divobj_' +obj.id, 'class': 'col-md-12' }, '');
634        let elmObja = cr_elem_D3('a', '', { 'id': 'link', 'href': '#','style':'display:none' }, '');
635        divMapaTem.appendChild(divSpMapE);
636        divMapaTem.appendChild(elmObja);
637
638
639        let cont= document.getElementById(obj.id);
640        let mimp = cont.getAttribute('data-mimpr');
641        let mxls = cont.getAttribute('data-mxls');
642        if(mimp==='true')
643            cr_btnImp_D3(obj.id, divSpMapE);
644        if(mxls==='true')
645            cr_btnExcel_D3(obj.id, divSpMapE,obj.cobertura);
646
647          
648        let tipoVis = divMapaTem.getAttribute('data-tipovisual');
649
650        if (tipoVis == '2') {
651            elmObj.style.display = 'none';
652            divTitulo.style.display = 'none';
653            divSpPer.style.display = 'none';
654        }
655
656
657        if (tipoVis == '2') {
658            //divMapaTem.appendChild(cr_elem_D3('div', '', { 'id': 'pantwhi_' + obj.id, 'style': 'width: 100%;height: ' + divMapaTem.style.height + ';position: absolute;background-color: #fff;' }, ''));
659            divMapaTem.appendChild(cr_elem_D3('div', '', { 'id': 'pantwhi_' + obj.id, 'style': 'width: 100%;height: ' + divMapaTem.style.height + ';position: absolute;' }, ''));
660
661        }
662        //divMapaTem.appendChild(elmObj);
663       
664
665
666
667    },
668    setValoresD3: function (obj, elm,parametrosOrig,D3parametros) {
669        let  elmObjmapa; //guardo la informacion de cada mapa
670        let tkm = '9f161bde-19af-31b0-e4fe-aee373b1df89';
671        let tenti = '';
672
673        let v = $(obj).data('informacion');
674        elmObjmapa= v;
675        if (v !== 'undefined') {
676            D3parametros.informacion=elmObjmapa;
677            if(D3parametros.cobertura!='pais'){
678                   
679                let munMap = 'null';
680                if (elm.idEntidad == 0) {
681                    tenti = 'null';
682                }
683                else {
684                    tenti = elm.idEntidad;
685                }
686                let urlApi = urlApiEnti_D3.replace('entMap', tenti).replace('munMap', munMap).replace('tokenMap', tkm).replace('llamado', cambiollamaApi_D3());
687                //aquí llamar al Api
688                $.support.cors = true;
689                $.ajax({
690                    dataType: "jsonp",
691                    url: urlApi,
692                    data: "",
693                    cache: false,
694                    success: function (dataEnti) {
695                        elm.datosfijos=true;
696                        setMunicipiosDatosFijos(parametrosOrig,dataEnti, elm, v,D3parametros);
697                    },
698                    error: function (e) {
699                        console.log('setValoresD3, llamadaApi:'+urlApi+' '+e);
700                        iniciaMapD3(D3parametros,'simplect');////CREARA UN MAPA GRIS AL NO HABER INFORMACION pero con tooltips
701                        quitarloading(elm);
702                    }
703                });
704            }
705            else{
706                for (let i = 0; i < elmObjmapa.valores.length; i++) {
707
708                    elm.municipios.push(new paises_D3(elmObjmapa.valores[i].id, elmObjmapa.valores[i].val, ''));
709                }
710                D3parametros.idioma=encDomIng;
711 
712            }
713            
714        }
715        else {
716
717            if(parametrosOrig.estra==='fijos'){
718                fetchingDataInfo(parametrosOrig,parametrosOrig.estra,fetchingDataMeta,elm,D3parametros);
719            }
720            else{
721                  //validacion para saber si se usara la estratificacion 3 que corresponden a las del componente, y si no es necesario mandar un 1
722                if(parametrosOrig.estra!='3'){
723
724                    fetchingDataInfo(parametrosOrig,parametrosOrig.estra,fetchingDataMeta,elm,D3parametros);
725                    
726                }
727                else{
728                    fetchingDataInfo(parametrosOrig,'1',fetchingDataMeta,elm,D3parametros);
729                    
730                }
731            }
732          
733        }
734            elm.colorfijo=parametrosOrig.colorfijo;
735    }
736};
737
738const  setMapasDocD3 = (obj,parametrosOrig,D3parametros) => {
739
740    if ($(obj).height() < 100) {
741        let divMapaTem = document.getElementById(obj.id);
742            $(obj).css('min-height', '500px');
743    }
744
745    let elm = new mapTematico_D3(obj.id, getAgeo_D3(obj));
746    elm.titulo = getTitulo_D3(obj);
747    elm.total = getTotal_D3(obj);
748    elm.indicador = getIndicador_D3(obj);
749    elm.tm=parametrosOrig.tm;
750    elm.periodo = getPeriodo_D3(obj);
751    elm.oportuno = getOportuno_D3(obj);
752    elm.unidadMedidaM = setUnidadM_D3(obj);
753    elm.valorM = setValorM_D3(obj);
754    elm.periodoM = setPeriodoM_D3(obj);
755    elm.cobertura=parametrosOrig.cobertura;
756    elm.fuentesM = setFuentesM_D3(obj);
757    elm.notasM = setNotasM_D3(obj);
758    elm.tipoEstratifica = getTipoEstrat_D3(obj);
759    elm.datosfijos=false;
760    elm.colorfijo=false;
761    elm.anio = getAnio_D3(obj);
762    elm.setValoresD3(obj, elm,parametrosOrig,D3parametros);
763    D3parametros.objeto=elm;
764    elm.crearMapaSvg(elm);
765    mapasTemObj_D3.push(elm);
766
767    if(D3parametros.cobertura==='pais'){
768        if(parametrosOrig.mcompara){
769            let divobj=document.getElementById('divobj_' +elm.id);  
770            let divContenedor=cr_btnGear(elm, divobj);
771            cr_divcompara(divContenedor,elm.id);
772        }
773    }
774};
775
776const setMunicipiosDatosFijos = (parametrosOrig,dataEnti, elm, valM,D3parametros) => {
777    try {
778        elm.nombre = dataEnti[0].Nombre_Entidad;
779        elm.titulo = dataEnti[0].Nombre_Indicador;
780    
781        if (elm.valorM) {
782            let dtot = document.getElementById('spanTotal_' + elm.id);
783            dtot.innerHTML = valM.valores[0].val;
784        }else{
785            document.getElementById('spanTotal_' + elm.id).style.display = 'none';
786        }
787    
788        if (elm.idEntidad != 0) {
789            for (let i = 0; i < dataEnti[0].Municipio.length; i++) {
790                let valMun = $.grep(valM.valores, function (ex) { return pad_D3(ex.id, 3) == dataEnti[0].Municipio[i].Municipio; });
791                let valo = '0';
792                if (valMun[0]) {
793                    valo = valMun[0].val
794                }
795                elm.municipios.push(new munEnt_D3(dataEnti[0].Municipio[i].Municipio, dataEnti[0].Municipio[i].Nombre, valo, ''));
796            }
797        }
798        else {
799            for (let i = 0; i < dataEnti.length; i++) {
800                let valMun = $.grep(valM.valores, function (ex) { return pad_D3(ex.id, 2) == dataEnti[i].Entidad; });
801                elm.municipios.push(new munEnt_D3(dataEnti[i].Entidad, dataEnti[i].Nombre, valMun[0].val, ''));
802            }
803        }
804            getEstratificarDatosFijos(parametrosOrig,elm,D3parametros);
805    } catch (error) {
806        console.log("setMunicipiosDatosFijos"+error);
807        iniciaMapD3(D3parametros,'simplegris'); //crea un mapa gris al haber un error
808    }
809   
810};
811const pad_D3 = (n, width, z) => {
812    z = z || '0';
813    n = n + '';
814    return n.length >= width ? n : new Array(width - n.length + 1).join(z) + n;
815};
816
817const getEstratificarDatosFijos = (parametrosOrig,elm,D3parametros) => {
818    try {
819        let decimales = 0;
820        let vctKD = new Array();
821        for (let i = 1; i < elm.municipios.length; i++) {
822            if (elm.municipios[i].valor != '')
823                if (!isNaN((elm.municipios[i].valor).replace(/,/g, ''))) {
824                    decimales = getDecimales_D3(elm.municipios[i].valor, decimales);
825                    vctKD.push(parseFloat((elm.municipios[i].valor).replace(/,/g, '')));
826                }
827        }
828        webApiEstratificaDatosFijos(parametrosOrig,elm, vctKD, decimales,D3parametros);
829    } catch (error) {
830        console.log("getEstratificarDatosFijos"+error);
831        iniciaMapD3(D3parametros,'simplegris'); //crea un mapa gris al haber un error
832    }
833};
834
835const webApiEstratificaDatosFijos = (parametrosOrig,elm, vctKD, decimales,D3parametros) => {
836    let valorEstra = {
837        valores: vctKD,
838        tipoEstra: elm.tipoEstratifica
839    };
840    let siestra = $.grep(dataEstraFija_D3, function (ex) { return ex.id == elm.id; });
841
842    try {
843        if (siestra[0].tipo == 1) {
844
845            if (elm.municipios[0].valor < 0) {
846                //Estrato uno
847                siestra[0].estratos[0].limInferior = '?';
848                siestra[0].estratos[0].limSuperior = 'V{00}';
849                //Estrato dos
850                siestra[0].estratos[1].limInferior = 'V{00}';
851                siestra[0].estratos[1].limSuperior = '0';
852                //Estrato tres
853                siestra[0].estratos[2].limInferior = '0';
854                siestra[0].estratos[2].limSuperior = '?';
855            } else {
856                //Estrato uno
857                siestra[0].estratos[0].limInferior = 'V{00}';
858                siestra[0].estratos[0].limSuperior = '?';
859                //Estrato dos
860                siestra[0].estratos[1].limInferior = '0';
861                siestra[0].estratos[1].limSuperior = 'V{00}';
862                //Estrato tres
863                siestra[0].estratos[2].limInferior = '?';
864                siestra[0].estratos[2].limSuperior = '0';
865            }
866
867
868        }
869    }
870    catch (x) {
871        //console.log('No se ha definido el tipo de mapa');
872    }
873
874
875
876    if (siestra.length > 0) {
877        //coloresIniciales_D3 = ('#fff,' + siestra[0].colores).split(',');
878
879        for (let z = 0; z < siestra[0].estratos.length; z++) {
880            if (siestra[0].estratos[z].limInferior == '?') {
881                //siestra[0].estratos[z].limInferior = Math.min.apply(null, vctKD);
882                siestra[0].estratos[z].limInferior = (/[$]/i.test(siestra[0].estratos[z].limInferior.toString())) ? '$' + Math.min.apply(null, vctKD) : Math.min.apply(null, vctKD); 
883            }
884
885            if (siestra[0].estratos[z].limSuperior == '?') {
886                //siestra[0].estratos[z].limSuperior = Math.max.apply(null, vctKD);
887                siestra[0].estratos[z].limSuperior = (/[$]/i.test(siestra[0].estratos[z].limSuperior.toString())) ? '$' + Math.max.apply(null, vctKD) : Math.max.apply(null, vctKD); 
888            }
889
890        }
891
892        for (let x = 0; x < siestra[0].estratos.length; x++) {
893            siestra[0].estratos[x].limInferior = formatear_D3(siestra[0].estratos[x].limInferior.toString(), elm);
894            siestra[0].estratos[x].limSuperior = formatear_D3(siestra[0].estratos[x].limSuperior.toString(), elm);
895        }
896
897
898        webApiClasificaDatosFijos(parametrosOrig,siestra[0].estratos, elm, decimales, siestra[0].colores,D3parametros);
899    }
900    else {
901
902        if(parametrosOrig.estra!='fijos'){
903            $.ajax({
904                contentType: "application/json",
905                dataType: "json",
906                method: "POST",
907                url: "/app/api/mapatematico/mapaTem/obtenerEntidad",
908                data: JSON.stringify(valorEstra),
909                cache: false,
910                success: function (dataEstra) {
911                   console.log(dataEstra);
912                   if(elm.periodo!='')
913                        registraApiMeta(elm,parametrosOrig);
914                        webApiClasificaDatosFijos(parametrosOrig,dataEstra, elm, decimales,'',D3parametros);
915                        iniciaMapD3(D3parametros,'normal');//llama al camponente d3
916                        quitarloading(elm);
917                },
918                error: function (qXHR, textStatus, errorThrown) {
919                    // throw new Error(errorThrown + ' ' + this.url + ' ' + JSON.stringify(this.data));
920                    iniciaMapD3(D3parametros,'simplect');////CREARA UN MAPA GRIS AL NO HABER INFORMACION pero con tooltips
921                     quitarloading(elm);
922                     }
923            });
924        }
925        else{
926            registraApiMeta(elm,parametrosOrig);
927            webApiClasificaDatosFijos(parametrosOrig,D3parametros.estratoslim, elm, decimales,'',D3parametros);
928            iniciaMapD3(D3parametros,'normal');//llama al camponente d3
929            quitarloading(elm);
930        }
931        
932    }
933};
934
935const webApiClasificaDatosFijos = (parametrosOrig,dataEstra, elm, decimales, colores,D3parametros) => {
936    try {
937        let txt_periodof='';
938        if (elm.periodoM) {
939            if(elm.periodo!=''&& elm.periodo!='0'){
940                txt_periodof=elm.periodo ;
941            }
942            else{
943                document.getElementById('spanPer_' + elm.id).style.display = 'none';
944            }
945        }
946        else{
947            document.getElementById('spanPer_' + elm.id).style.display = 'none';
948        }
949    
950        if(parametrosOrig.mup_f!=''){
951            txt_periodof=txt_periodof+' '+parametrosOrig.mup_f;
952            document.getElementById('spanPer_' + elm.id).innerHTML =txt_periodof;
953            document.getElementById('spanPer_' + elm.id).style.display = 'block';
954        }
955        else{
956            document.getElementById('spanPer_' + elm.id).innerHTML =txt_periodof;
957        }
958    
959        generaColoresD3(dataEstra,D3parametros);
960        let coloresInicialesInt = coloresIniciales_D3;
961        //validación para colores fijos (se agregó el parámetro colores)
962        if (colores) {
963            coloresInicialesInt = ('#fff,' + colores).split(',');
964        }
965    
966    let coloInit;
967        for (let j = 1; j < elm.municipios.length; j++) {
968            for (let i = 0; i < dataEstra.length; i++) {
969                if(elm.tipoEstratifica=='fijos'){
970    
971                    if (condicionPersonalizada(dataEstra[i].limSuperior, dataEstra[i].limInferior, (elm.municipios[j].valor).replace(/,/g, ''),dataEstra[i].operadorS,dataEstra[i].operadorI)) {
972                        elm.municipios[j].estrato = dataEstra[i].nestrato;
973                        try {
974                            coloInit = coloresInicialesInt[dataEstra[i].nestrato];
975                        } catch (error) {
976                            coloInit='#fff';
977                        }
978                       
979                        if (dataEstra[i].nestrato == 'extremosar') {
980                            coloInit = coloresInicialesInt[(11)];
981                        }
982                        if (dataEstra[i].nestrato == 'extremosab') {
983                            coloInit = coloresInicialesInt[(10)];
984                        }
985                        if (dataEstra[i].nestrato == 'ceros') {
986                            coloInit = coloresInicialesInt[(9)];
987                        }
988                        elm.municipios[j].color = coloInit;
989                        break;
990                    }
991                }
992                else{
993                    if (entre_D3(dataEstra[i].limSuperior, dataEstra[i].limInferior, (elm.municipios[j].valor).replace(/,/g, ''))) {
994                        elm.municipios[j].estrato = dataEstra[i].nestrato;
995                        let coloInit = coloresInicialesInt[dataEstra[i].nestrato];
996                        if (dataEstra[i].nestrato == 'extremosar') {
997                            coloInit = coloresInicialesInt[(11)];
998                        }
999                        if (dataEstra[i].nestrato == 'extremosab') {
1000                            coloInit = coloresInicialesInt[(10)];
1001                        }
1002                        if (dataEstra[i].nestrato == 'ceros') {
1003                            coloInit = coloresInicialesInt[(9)];
1004                        }
1005                        elm.municipios[j].color = coloInit;
1006                        break;
1007                    }
1008                }
1009               
1010            }
1011        }
1012        let cont= document.getElementById(elm.id);
1013        let mesc =  cont.getAttribute('data-mestra');
1014        let mpal =  cont.getAttribute('data-mpaleta');
1015        let divobj=document.getElementById('divobj_' +elm.id);
1016               if(mesc==='true'||mpal==='true'){
1017                let divContenedor=cr_btnGear(elm, divobj);
1018                //valida el parámetro para mostrar las opciones de estratos y ademas valida que no se manden estratos fijos
1019                if(mesc==='true' && elm.tipoEstratifica!='fijos')
1020                     cr_radiobtn(divContenedor,parametrosOrig);
1021                if(mpal==='true')
1022                    cr_paletacolores(divContenedor,elm.id);
1023            }
1024    } catch (error) {
1025        console.log("webApiClasificaDatosFijos"+error);
1026        iniciaMapD3(D3parametros,'simplegris'); //crea un mapa gris al haber un error
1027    }
1028
1029};
1030
1031const getDecimales_D3 = (valor, anterior) => {
1032    try {
1033        let decimales = 0;
1034        if (valor.indexOf('.') > 0) {
1035            decimales = (valor.substring(valor.indexOf('.') + 1, valor.length)).length;
1036        }
1037    
1038        if (decimales > anterior) {
1039            return decimales;
1040        }
1041        else {
1042            return anterior;
1043        }
1044        
1045    } catch (error) {
1046        console.log("getDecimales_D3"+error);
1047    } 
1048};
1049
1050const formatear_D3 = (texto, elm) => {
1051    let txtf = texto;
1052
1053    for (let j = 0; j < elm.municipios.length; j++) {
1054
1055        let vvalor = 'V\\{' + elm.municipios[j].municipio + '\\}';
1056        let nnombre = 'N\\{' + elm.municipios[j].municipio + '\\}';
1057
1058        let reg1 = new RegExp(vvalor, 'gi');
1059        let reg2 = new RegExp(nnombre, 'gi');
1060
1061        txtf = txtf.replace(reg1, elm.municipios[j].valor);
1062        txtf = txtf.replace(reg2, elm.municipios[j].nombre);
1063    }
1064    return txtf;
1065};
1066
1067const  fetchingDataMeta = async (dataAll,elm,parametrosOrig,D3parametros,elmObjmapa) => {
1068    let dataFuentes=[];
1069     try {
1070        let txt_unidadMedida='';
1071         const resp =await setMetadatosD3(elm);
1072         if(resp["NOTAS"]!=null){
1073            if(resp["NOTAS"].length!=0){
1074                if(resp["NOTAS"].length>1){
1075                    for(let n=0;n<resp["NOTAS"].length;n++){
1076                        elm.notas=elm.notas+ resp["NOTAS"][n].NOTA+'</br>';
1077                    }
1078                }
1079                else
1080                elm.notas = resp["NOTAS"][0].NOTA;
1081            }
1082        }
1083        if(elm.unidadMedidaM){
1084            if(resp.NOMBRE_UNIDAD!=null){
1085                if( resp.NOMBRE_UNIDAD!="Es nulo"){
1086                    if( resp.NOMBRE_UNIDAD!=""){
1087                        if(resp.FACTOR!=null){
1088                            elm.unidadMedida = resp.FACTOR+' de '+resp.NOMBRE_UNIDAD;
1089                            txt_unidadMedida = ' ' + resp.FACTOR+' de '+resp.NOMBRE_UNIDAD;
1090                        }else{
1091                            elm.unidadMedida = resp.NOMBRE_UNIDAD;
1092                            txt_unidadMedida = ' ' + resp.NOMBRE_UNIDAD;
1093                        }                  
1094                    }
1095                }
1096            }
1097        }
1098      
1099        if(resp["FUENTES"]!=null){
1100            if(resp["FUENTES"].length>1){
1101                for(let f=0;f<resp["FUENTES"].length;f++){
1102                    dataFuentes.push(new arrayfuente(resp["FUENTES"][f].NOMBRE_FUENTE,resp["FUENTES"][f].URL_PROYECTO));
1103                }
1104            }
1105            else{
1106                dataFuentes.push(new arrayfuente(resp["FUENTES"][0].NOMBRE_FUENTE,resp["FUENTES"][0].URL_PROYECTO));
1107            }
1108            elm.fuentes= dataFuentes;
1109        }
1110        if(parametrosOrig.mum_f!=''){
1111            txt_unidadMedida=txt_unidadMedida+' '+parametrosOrig.mum_f;
1112            document.getElementById('spanUnidad_' + elm.id).innerHTML =txt_unidadMedida;
1113            document.getElementById('spanUnidad_' + elm.id).style.display = 'inline';
1114        }
1115        else{
1116            document.getElementById('spanUnidad_' + elm.id).innerHTML =txt_unidadMedida;
1117        }
1118
1119        RevisaInfo(dataAll,elm,parametrosOrig,D3parametros,elmObjmapa);
1120     } catch (error) {
1121         console.log("fetchingDataMeta"+error);
1122         iniciaMapD3(D3parametros,'simplegris'); //crea un mapa gris al haber un error
1123     }
1124};
1125
1126const  setMunicipiosAllD3 = (dataAll,elm,parametrosOrig,D3parametros,elmObjmapa) => {
1127    try {
1128            let txt_periodof='';
1129            generaColoresD3(dataAll.estratos,D3parametros);
1130            
1131            elm.municipios=dataAll.elementos;
1132            elm.nombre = dataAll.elementos[0].Nombre_Entidad;
1133        
1134            for (let i = 0; i < dataAll.elementos.length; i++) {
1135                let valOp = '';
1136                if (elm.oportuno === 1) {
1137                    valOp = dataAll.elementos[i].valor;
1138                    if (i == 0) {
1139                        if (elm.periodoM) {
1140                            txt_periodof = dataAll.elementos[1].periodo;
1141                        }
1142                        else{
1143                            document.getElementById('spanPer_' + elm.id).style.display = 'none';
1144                        }
1145                        if (elm.valorM) {
1146                            let dtot = document.getElementById('spanTotal_' + elm.id);
1147                            dtot.innerHTML = dataAll.elementos[0].valor;
1148                        }else{
1149                            document.getElementById('spanTotal_' + elm.id).style.display = 'none';
1150                        }
1151                        if (elm.unidadMedidaM||parametrosOrig.mum_f!='') {
1152                            document.getElementById('spanUnidad_' + elm.id).style.display = 'inline';
1153                        }else{
1154                            document.getElementById('spanUnidad_' + elm.id).style.display = 'none';
1155                        }
1156                        
1157                    }
1158                }
1159                else {
1160                    let objOp = $.grep(dataEnti[i].Valores, function (ex) { return ex.Periodo == elm.anio; });
1161                    
1162                    if (objOp.length > 0) {
1163                        valOp = objOp[0].Valor;
1164                    }
1165                    else {
1166                        valOp = 'No existe información para mostrar';
1167                    }
1168                }
1169        
1170            }
1171            if(parametrosOrig.mup_f!=''){
1172                txt_periodof=txt_periodof+' '+parametrosOrig.mup_f;
1173                document.getElementById('spanPer_' + elm.id).innerHTML =txt_periodof;
1174                document.getElementById('spanPer_' + elm.id).style.display = 'block';
1175            }
1176            else{
1177                document.getElementById('spanPer_' + elm.id).innerHTML =txt_periodof;
1178            }
1179
1180            D3parametros.informacion=elmObjmapa;
1181            let cont= document.getElementById(elm.id);
1182            let mesc = cont.getAttribute('data-mestra');
1183            let mpal = cont.getAttribute('data-mpaleta');
1184            let divobj=document.getElementById('divobj_' +elm.id);
1185            if(mesc==='true'||mpal==='true'){
1186                let divContenedor=cr_btnGear(elm, divobj);
1187                if(mesc==='true' && elm.tipoEstratifica!='fijos')
1188                    cr_radiobtn(divContenedor,parametrosOrig);
1189                if(mpal==='true')
1190                    cr_paletacolores(divContenedor,elm.id);
1191            }
1192            
1193                iniciaMapD3(D3parametros,'normal');//llama al camponente d3
1194                quitarloading(elm);
1195                
1196    } catch (error) {
1197        console.log("setMunicipiosAllD3"+error);
1198        iniciaMapD3(D3parametros,'simplegris'); //crea un mapa gris al haber un error
1199    }
1200    
1201};
1202
1203const  RevisaInfo= (dataAll,elm,parametrosOrig,D3parametros,elmObjmapa) => {
1204    try {
1205        if(dataAll.elementos.length==undefined){
1206            iniciaMapD3(D3parametros,'simplegris');//CREARA UN MAPA GRIS AL NO HABER INFORMACION
1207            quitarloading(elm);
1208        }
1209        else{
1210            if(paramPeriodoVacio)
1211                setMunicipiosAllD3(dataAll,elm,parametrosOrig,D3parametros,elmObjmapa);
1212            else{
1213                 //Validamos que la informacion sea del Periodo solicitado
1214                let objValores = $.grep(dataAll.elementos, function (ex) { 
1215                    return ex.periodo == parametrosOrig.pf.toString(); });
1216                if(objValores.length>0){
1217                    setMunicipiosAllD3(dataAll, elm,parametrosOrig,D3parametros,elmObjmapa);}
1218                else{
1219                    if(elm.periodo=='')
1220                        elm.periodo = dataAll.elementos[0].periodo;
1221                        iniciaMapD3(D3parametros,'simplegris');//CREARA UN MAPA GRIS AL NO HABER INFORMACION DEL PERIODO
1222                        quitarloading(elm);}
1223            }
1224           
1225        }
1226    } catch (error) {
1227        console.log("RevisaInfo"+error);
1228        iniciaMapD3(D3parametros,'simplegris'); //crea un mapa gris al haber un error
1229    }
1230};
1231
1232
1233const registraApiMeta = async (elm,parametrosOrig) => {
1234    let dataFuentes=[];
1235    let txt_unidadMedida='';
1236    try {
1237        const resp =await setMetadatosD3(elm);
1238        if(resp["NOTAS"]!=null){
1239            if(resp["NOTAS"].length!=0){
1240                if(resp["NOTAS"].length>1){
1241                    for(let n=0;n<resp["NOTAS"].length;n++){
1242                        elm.notas=elm.notas+ resp["NOTAS"][n].NOTA+'</br>';
1243                    }
1244                }
1245                else
1246                elm.notas = resp["NOTAS"][0].NOTA;
1247            }
1248        }
1249        if(elm.unidadMedidaM){
1250            if(resp.NOMBRE_UNIDAD!=null){
1251                if( resp.NOMBRE_UNIDAD!="Es nulo"){
1252                    if( resp.NOMBRE_UNIDAD!=""){
1253                        if(resp.FACTOR!=null){
1254                            elm.unidadMedida = resp.FACTOR+' de '+resp.NOMBRE_UNIDAD;
1255                            txt_unidadMedida = ' ' + resp.FACTOR+' de '+resp.NOMBRE_UNIDAD;
1256                        }
1257                        else{
1258                            elm.unidadMedida = resp.NOMBRE_UNIDAD;
1259                            txt_unidadMedida = ' ' + resp.NOMBRE_UNIDAD;
1260                        }
1261
1262                    }
1263                }    
1264            }
1265        }
1266      
1267        if(resp["FUENTES"]!=null){
1268            if(resp["FUENTES"].length>1){
1269                for(let f=0;f<resp["FUENTES"].length;f++){
1270                    dataFuentes.push(new arrayfuente(resp["FUENTES"][f].NOMBRE_FUENTE,resp["FUENTES"][f].URL_PROYECTO));
1271                }
1272            }
1273            else{
1274                dataFuentes.push(new arrayfuente(resp["FUENTES"][0].NOMBRE_FUENTE,resp["FUENTES"][0].URL_PROYECTO));
1275            }
1276            elm.fuentes= dataFuentes;
1277        }
1278        if(parametrosOrig.mum_f!=''){
1279            txt_unidadMedida=txt_unidadMedida+' '+parametrosOrig.mum_f;
1280            document.getElementById('spanUnidad_' + elm.id).innerHTML =txt_unidadMedida;
1281            document.getElementById('spanUnidad_' + elm.id).style.display = 'inline';
1282        }
1283        else{
1284            document.getElementById('spanUnidad_' + elm.id).innerHTML =txt_unidadMedida;
1285        }
1286
1287    } catch (error) {
1288        console.log("registraApiMeta"+error);
1289        iniciaMapD3(D3parametros,'simplegris'); //crea un mapa gris al haber un error
1290    }
1291   
1292};
1293
1294const fetchingDataInfo = async (parametrosOrig,estrato,callback,elm,D3parametros) => {
1295    let  elmObjmapa;
1296    let dataEnti=[];
1297    let dataMun=[];
1298    let resultData=[];
1299    try {
1300        if(D3parametros.cobertura==='mun'){
1301            for(let i=1;i<33;i++){
1302                if(i<10){
1303                    parametrosOrig.ageo='0'+i;
1304                    resultData= await getApiIndicadores(parametrosOrig);
1305                }            
1306                else{
1307                    parametrosOrig.ageo=i;
1308                    resultData= await getApiIndicadores(parametrosOrig);
1309                }
1310                for(let x=0;x<resultData.length;x++){
1311                    if(resultData[x].Municipio!='0')
1312                        dataMun.push(resultData[x]);
1313                }
1314            }
1315        }
1316        D3parametros.dataMun=dataMun;
1317        parametrosOrig.ageo="00";
1318        dataEnti= await getApiIndicadores(parametrosOrig);
1319        
1320        
1321        
1322            //validamos si se mando el parámetro pf, al no mandarse se le asigna el último periodo 
1323            if(elm.periodo=='0'||elm.periodo==0||elm.periodo==''){
1324                let ultperiodo;
1325                if(dataEnti[0].Valores.length>1){
1326                    for(let p=0;p>dataEnti[0].Valores.length;p++){
1327                        if(p==0){
1328                            ultperiodo=dataEnti[0].Valores[p].Perio
1328do;
1329                        }
1330                        else{
1331                            if(ultperiodo<dataEnti[0].Valores[p].Periodo){
1332                                ultperiodo=dataEnti[0].Valores[p].Periodo;
1333                            }
1334                        }
1335                        
1336                    }
1337                    parametrosOrig.pf=ultperiodo;
1338                    elm.periodo = ultperiodo;
1339                }
1340                parametrosOrig.pf=dataEnti[0].Valores[0].Periodo;
1341                elm.periodo = dataEnti[0].Valores[0].Periodo;
1342            }
1343            elmObjmapa=dataEnti;
1344            acomodo_D3(parametrosOrig, estrato,dataEnti, callback,elm,D3parametros,elmObjmapa);
1345    } 
1346    catch (error) {
1347        iniciaMapD3(D3parametros,'simplegris'); //crea un mapa gris al haber un error
1348        console.log ("fetchingDataInfo"+error)
1349    }
1350};
1351
1352const  getApiIndicadores = (parametrosOrig) => {
1353
1354    let entidad=parametrosOrig.ageo;
1355    let indicador=parametrosOrig.indica;
1356    let oportuno = 1;
1357    let tkm = '9f161bde-19af-31b0-e4fe-aee373b1df89';
1358
1359    sitioIng = window.location.host.match(/en.\w+[inegi.org.mx]+/gi);
1360    tituloIndicadores_D3 = true;
1361    let urlApiIndix;
1362    if (parametrosOrig.tm===undefined)
1363        urlApiIndix = urlApiIndi_D3.replace('entMap', entidad).replace('indicaMp', indicador).replace('oport', oportuno).replace('tokenMap', tkm).replace('llamado', cambiollamaApi_D3().replace('ln', (sitioIng) ? 'en' : 'es'));
1364    else
1365        urlApiIndix = urlApiIndi_tm.replace('entMap', entidad).replace('indicaMp', indicador).replace('oport', oportuno).replace('tm',parametrosOrig.tm).replace('tokenMap', tkm).replace('llamado', cambiollamaApi_D3().replace('ln', (sitioIng) ? 'en' : 'es'));
1366    
1367        $.support.cors = true;
1368    return new Promise((resolve, reject)=>{
1369        $.ajax({
1370            dataType: "jsonp",
1371            url: urlApiIndix,
1372            data: "",
1373            cache: false,
1374            success(datosEnti){
1375               resolve(datosEnti);
1376            }
1377        });
1378    }) ;     
1379};
1380
1381const acomodo_D3 = (parametrosOrig, estrato,dataEnti,  callback,elm,D3parametros,elmObjmapa) => {
1382    let vctKD = new Array();
1383    for (let i = 1; i < dataEnti.length; i++) {
1384        if (!isNaN((dataEnti[i].Valores[0].Valor).replace(/,/g, ''))) {
1385            vctKD.push(parseFloat((dataEnti[i].Valores[0].Valor).replace(/,/g, '')));
1386        }
1387    }
1388    fetchingDataEstrato(parametrosOrig, estrato,dataEnti, vctKD,  callback,elm,D3parametros,elmObjmapa);
1389};
1390
1391const fetchingDataEstrato = async (parametrosOrig, estrato,dataEnti, vctKD,  callback,elm,D3parametros,elmObjmapa) => {
1392    try {
1393        if(elm.tipoEstratifica==='fijos'){
1394            const dataEstra= parametrosOrig.estra_f;
1395            generaJson_D3(parametrosOrig, dataEnti, dataEstra, callback,elm,D3parametros,elmObjmapa);
1396        }else{
1397            const dataEstra= await getJsonEstratoo( estrato,vctKD,  elm);
1398            generaJson_D3(parametrosOrig, dataEnti, dataEstra, callback,elm,D3parametros,elmObjmapa);
1399        }
1400     
1401    } catch (error) {
1402        console.log("fetchingDataEstrato"+error);
1403        iniciaMapD3(D3parametros,'simplegris'); //crea un mapa gris al haber un error
1404    }
1405};
1406
1407const getJsonEstratoo =( estrato, vctKD, elm) =>{
1408    let tipo=estrato;
1409    let valorEstra = {
1410        valores: vctKD,
1411        tipoEstra: tipo
1412    };
1413    return new Promise ((resolve,reject)=>{
1414        $.ajax({
1415            contentType: "application/json",
1416            dataType: "json",
1417            method: "POST",
1418            url: "/app/api/mapaTematico/mapaTem/obtenerEntidad",
1419            data: JSON.stringify(valorEstra),
1420            cache: false,
1421            success: function (datosEstra) {
1422               resolve(datosEstra);
1423            },
1424            error: function (e) {
1425                iniciaMapD3(D3parametros,'simplect');////CREARA UN MAPA GRIS AL NO HABER INFORMACION pero con tooltips
1426                quitarloading(elm);
1427                throw e; 
1428            }
1429        });
1430    });
1431       
1432};
1433
1434const generaJson_D3 = (parametrosOrig, dataEnti, dataEstra, callback,elm,D3parametros,elmObjmapa) => {
1435    try {
1436        let entidad=parametrosOrig.ageo;
1437        let lstMunEnt = new Array();
1438        
1439        //validación para los casos donde no hay dato Nacional
1440        if(dataEnti[0].Entidad != '00' && dataEnti[0].Entidad != '0')
1441            lstMunEnt.push(new munEnt_D3('', '','', '','')); 
1442    
1443        for (let x = 0; x < dataEnti.length; x++) {
1444            if (entidad === "00") {
1445                lstMunEnt.push(new munEnt_D3(dataEnti[x].Entidad, dataEnti[x].Nombre_Entidad, dataEnti[x].Valores[0].Valor, '',dataEnti[x].Valores[0].Periodo));
1446            }
1447            else {
1448                lstMunEnt.push(new munEnt_D3(dataEnti[x].Municipio, dataEnti[x].Nombre_Municipio, dataEnti[x].Valores[0].Valor, '',dataEnti[x].Valores[0].Periodo));
1449            }
1450        }
1451        for (let j = 1; j < lstMunEnt.length; j++) {
1452            for (let i = 0; i < dataEstra.length; i++) {
1453                if(elm.tipoEstratifica=='fijos'){
1454                    if (condicionPersonalizada(dataEstra[i].limSuperior, dataEstra[i].limInferior, (lstMunEnt[j].valor).replace(/,/g, ''),dataEstra[i].operadorS,dataEstra[i].operadorI)) {
1455                        lstMunEnt[j].estrato = dataEstra[i].nestrato;
1456                        let coloInit = coloresIniciales_D3[dataEstra[i].nestrato];
1457                        if (dataEstra[i].nestrato == 'extremosar') {
1458                            coloInit = coloresIniciales_D3[(11)];
1459                        }
1460                        if (dataEstra[i].nestrato == 'extremosab') {
1461                            coloInit = coloresIniciales_D3[(10)];
1462                        }
1463                        if (dataEstra[i].nestrato == 'ceros') {
1464                            coloInit = coloresIniciales_D3[(9)];
1465                        }
1466                        lstMunEnt[j].color = coloInit;
1467                        break;
1468                    }
1469                }
1470                else{
1471                    if (entre_D3(dataEstra[i].limSuperior, dataEstra[i].limInferior, (lstMunEnt[j].valor).replace(/,/g, ''))) {
1472                        lstMunEnt[j].estrato = dataEstra[i].nestrato;
1473                        let coloInit = coloresIniciales_D3[dataEstra[i].nestrato];
1474                        if (dataEstra[i].nestrato == 'extremosar') {
1475                            coloInit = coloresIniciales_D3[(11)];
1476                        }
1477                        if (dataEstra[i].nestrato == 'extremosab') {
1478                            coloInit = coloresIniciales_D3[(10)];
1479                        }
1480                        if (dataEstra[i].nestrato == 'ceros') {
1481                            coloInit = coloresIniciales_D3[9];
1482                        }
1483                        lstMunEnt[j].color = coloInit;
1484                        break;
1485                    }
1486                }
1487    
1488            }
1489        }
1490            length=lstMunEnt.length-1;
1491            if(lstMunEnt.length!=33){
1492                lstMunEnt[length+1]={'Entidad':'9'};
1493            }
1494        
1495       
1496        let jsonRes = {
1497            estratos: dataEstra,
1498            elementos: lstMunEnt
1499        };
1500        callback(jsonRes,elm,parametrosOrig,D3parametros,elmObjmapa);
1501    } catch (error) {
1502        console.log("generaJson_D3"+error);
1503        iniciaMapD3(D3parametros,'simplegris'); //crea un mapa gris al haber un error
1504    }
1505 
1506};
1507
1508const getJsonEstratoMun=( estrato, vctKD) =>{
1509    let tipo=estrato;
1510
1511    let valorEstra = {
1512        valores: vctKD,
1513        tipoEstra: tipo
1514    };
1515    return new Promise ((resolve,reject)=>{
1516        $.ajax({
1517            contentType: "application/json",
1518            dataType: "json",
1519            method: "POST",
1520            url: "/app/api/mapaTematico/mapaTem/obtenerEntidad",
1521            data: JSON.stringify(valorEstra),
1522            cache: false,
1523            success: function (datosEstra) {
1524                console.log("Estratosmun " + JSON.stringify(datosEstra));
1525                resolve(datosEstra);
1526            },
1527            error: function (e) {
1528               console.log("getJsonEstratoMun"+e);
1529                throw e; 
1530            }
1531        });
1532    });
1533       
1534};
1535
1536//LLAMADO AL API DE METADATOINDICADOR
1537const setMetadatosD3=(elm)=> {
1538    
1539    let tkm = '9f161bde-19af-31b0-e4fe-aee373b1df89';
1540    sitioIng = window.location.host.match(/en.\w+[inegi.org.mx]+/gi);
1541    let urlApiIndix ;
1542    if (elm.tm===undefined)
1543        urlApiIndix = urlApiMeta_D3.replace('indicaMp', elm.indicador).replace('oport', elm.oportuno).replace('periodoMp', elm.periodo).replace('periodoMp', elm.periodo).replace('tokenMap', tkm).replace('llamado', cambiollamaApi_D3()).replace('ln', (sitioIng) ? 'en' : 'es');
1544    else
1545        urlApiIndix = urlApiMeta_tm.replace('indicaMp', elm.indicador).replace('oport', elm.oportuno).replace('tm',elm.tm).replace('periodoMp', elm.periodo).replace('periodoMp', elm.periodo).replace('tokenMap', tkm).replace('llamado', cambiollamaApi_D3()).replace('ln', (sitioIng) ? 'en' : 'es');
1546        // $.getJSON("http://www.inegi.org.mx/app/api/indicadores/interna_v1_1/API.svc/MetadatoIndicador/es/"+elm.indicador+"/00000/"+ elm.periodo+"/"+ elm.periodo+"/1/json/563cbaa8-58bb-fef8-6763-1f1dae318f99", function (resp) { 
1547   return new Promise((resolve,reject)=>{
1548        $.getJSON(urlApiIndix , function (respuesta) { 
1549            resolve(respuesta);
1550        });
1551   });
1552};
1553
1554const generaColoresD3 = (dataEstra,D3parametros) => { 
1555    try {
1556        let coloInit= [];
1557        let ulInfo = cr_elem_D3('ul', '', '', '');
1558        rangecolores=[];
1559        let extremos = '';
1560        let coloresInicialesInt = coloresIniciales_D3;
1561    
1562    
1563        if (dataEstra[0].etiqueta !== undefined && dataEstra[0].etiqueta !== '') {
1564    
1565            for (let i = 0; i < dataEstra.length; i++) {
1566                let coloInit = coloresInicialesInt[dataEstra[i].nestrato];
1567                rangecolores.push(coloInit);
1568            }
1569    
1570        }
1571        else {
1572            
1573            for (let i = 0; i < dataEstra.length; i++) {
1574                if (dataEstra[i].nestrato == 'ceros') {
1575                    dataEstra[i].nestrato = 0;
1576                    coloInit = coloresInicialesInt[(9)];
1577                    rangecolores.push(coloInit);
1578                }
1579                else if (dataEstra[i].nestrato == 'extremosar') {
1580                    coloInit = coloresInicialesInt[(11)];
1581                    extremos = '*';
1582                    rangecolores.push(coloInit);
1583                }
1584                else if (dataEstra[i].nestrato == 'extremosab') {
1585                    coloInit = coloresInicialesInt[(10)];
1586                    extremos = '*';
1587                    rangecolores.push(coloInit);
1588                }else{
1589                    coloInit = coloresInicialesInt[dataEstra[i].nestrato];
1590                    rangecolores.push(coloInit);
1591                }
1592            }
1593        }
1594        if (extremos == '*') {
1595            let txin;
1596            if (encDomIng) {
1597                txin = ['', 'See more']
1598            } else {
1599                txin = ['*Unidades geográficas con valores que se alejan del resto.', 'Ver más']
1600            }
1601    
1602            ulInfo.appendChild(cr_elem_D3('div', '', { 'class': 'clearfix' }, ''));
1603            ulInfo.appendChild(cr_elem_D3('div', '', { 'style': 'text-align: left;', 'class': 'col-md-12' }, '' + txin[0] + ' <a href="/componentes/mapaTematico/doc/nota_cug.pdf" target="_blank">' + txin[1] + '</a>'));
1604        }
1605        D3parametros.idioma=encDomIng;
1606        D3parametros.estratoslim=dataEstra;
1607        if(paramUndefined)
1608            D3parametros.colores=rangecolores;
1609        else{
1610            if(D3parametros.paleta.length!=0||D3parametros.paleta!='')
1611            D3parametros.colores=D3parametros.paleta;
1612        else
1613            D3parametros.colores=rangecolores;
1614        }
1615    } catch (error) {
1616        console.log("setMunicipiosAllD3"+error);
1617        iniciaMapD3(generaColoresD3,'simplegris'); //crea un mapa gris al haber un error
1618    }
1619};
1620
1621const quitarloading = (elm) =>{
1622    try {
1623        let elesperar = document.getElementById('cargaMapa_' + elm.id);
1624        if (elesperar) {
1625            elesperar.style.display = 'none';
1626        }
1627        
1628    } catch (error) {
1629        console.log(error);
1630    }
1631};
1632
1633const importarScript_Callback = (nombre, callback) => {
1634    let s = document.createElement("script");
1635    s.onload = callback;
1636    s.src = nombre;
1637    document.querySelector("head").appendChild(s);
1638};
1639
1640const importarScript = (nombre) => {
1641    let s = document.createElement("script");
1642    s.src = nombre;
1643    document.querySelector("head").appendChild(s);
1644};
1645
1646//recibe limSup, limInf,Valor, OperadorSup,OperadorInf
1647const condicionPersonalizada = (a, b, x, w, z) => {
1648    //console.log(x+z+b+'&&'+x+w+a);
1649    if (x == '') { return false; }
1650    else{
1651        let CS = true, CI = true;
1652        let infS = false, infI = false;
1653
1654        //revisamos si el limSup trae el signo ?, que significa infinito
1655        if (/[?]/i.test(a.toString())) {
1656            a = a.toString().replace(/[?]/i, '');
1657            infS = true;
1658        }
1659
1660        //revisamos si el limInf trae el signo ?, que significa infinito
1661        if (/[?]/i.test(b.toString())) {
1662            b = b.toString().replace(/[?]/i, '');
1663            infI = true;
1664        }
1665
1666        let min = Math.min(a, b),
1667            max = Math.max(a, b);
1668
1669        if(!infI){
1670                switch (z) {
1671                    case '>':
1672                        CI=parseFloat(x)>min;
1673                     
1674                    break;
1675                    case '>=':
1676                        CI=parseFloat(x)>=min;
1677                    break;
1678                    case '<':
1679                        CI=parseFloat(x)<min;
1680                     
1681                    break;
1682                    case '<=':
1683                        CI=parseFloat(x)<=min;
1684                    break;
1685                    case '==':
1686                        CI= min==parseFloat(x);
1687                    break;
1688                    default:
1689                        break;
1690                }
1691            }
1692    if(!infS){
1693        switch (w) {
1694            case '<':
1695                CS=parseFloat(x)<max;
1696                break;
1697            case '<=':
1698                CS=parseFloat(x)<=max;
1699            break;
1700            case '>':
1701                CS=parseFloat(x)>max;
1702                break;
1703            case '>=':
1704                CS=parseFloat(x)>=max;
1705            break;
1706            case '==':
1707                if(parseFloat(x)==max)
1708                    CS=true;
1709                else
1710                    CS=false;
1711                break;
1712            default:
1713                break;
1714        }
1715    }
1716
1717    let t=CI && CS;
1718    return  t;
1719    }
1720};
1721
1722const entre_D3 = (a, b, x) => {
1723    if (x == '') { return false; }
1724
1725    let CS = true, CI = true;
1726
1727    if (/[$]/i.test(a.toString())) {
1728        a = a.toString().replace(/[$]/i, '');
1729        CS = !CS;
1730    }
1731
1732    if (/[$]/i.test(b.toString())) {
1733        b = b.toString().replace(/[$]/i, '');
1734        CI = !CI;
1735    }
1736
1737    let min = Math.min(a, b),
1738        max = Math.max(a, b);
1739
1740    let decimin = 0;
1741    let decimax = 0;
1742
1743    if (min.toString().indexOf('.') > -1) {
1744        decimin = min.toString().split('.')[1].length;
1745    }
1746
1747    if (max.toString().indexOf('.') > -1) {
1748        decimax = max.toString().split('.')[1].length;
1749    }
1750
1751    if (x.toString().indexOf('.') > -1) {
1752        if (decimax == 0)
1753            decimax = x.toString().split('.')[1].length;
1754        if (decimin == 0)
1755            decimin = x.toString().split('.')[1].length;
1756    }
1757
1758    if (CS && CI) {
1759        //return parseFloat(x).toFixed(decimin) >= min && parseFloat(x).toFixed(decimax) <= max;
1760        return parseFloat(x) >= min && parseFloat(x) <= max;
1761    }
1762
1763    if (CS && !CI) {
1764        //return parseFloat(x).toFixed(decimin) > min && parseFloat(x).toFixed(decimax) <= max;
1765        return parseFloat(x) > min && parseFloat(x) <= max;
1766    }
1767
1768    if (!CS && CI) {
1769        //return parseFloat(x).toFixed(decimin) >= min && parseFloat(x).toFixed(decimax) < max;
1770        return parseFloat(x) >= min && parseFloat(x) < max;
1771    }
1772
1773    if (!CS && !CI) {
1774        //return parseFloat(x).toFixed(decimin) > min && parseFloat(x).toFixed(decimax) < max;
1775        return parseFloat(x) > min && parseFloat(x) < max;
1776    }
1777};
1778
1779const cr_elem_D3 = (a, b, e, z) => {
1780    let elem = document.createElement(a);
1781    if (e != '') {
1782        for (x in e) {
1783            elem.setAttribute(x, e[x]);
1784        }
1785    }
1786    elem.innerHTML = z;
1787    let textnode = document.createTextNode(b);
1788    elem.appendChild(textnode);
1789    return elem;
1790};
1791
1792//creacion de elementos para configurar el mapa
1793const cr_btnGear = (elm, row) => {
1794    try {
1795        if(elm=='mapaTematico'){
1796            elm.id='mapaTematico';
1797        }
1798        let objelm=JSON.stringify(elm);
1799        let  sitioIng = window.location.host.match(/en.\w+[inegi.org.mx]+/gi);
1800        let gp = document.createElement("div");
1801        gp.setAttribute('id', 'divGear'+elm.id);
1802        //gp.setAttribute('style', 'top:23px;');
1803        gp.setAttribute('class', 'btn-group menubuttons');
1804    
1805        let inputs = document.createElement("button");
1806        inputs.setAttribute('type', 'button');
1807        inputs.setAttribute('id', 'btnGearMap'+elm.id);
1808        inputs.setAttribute('class', 'btn btn-default btn-md btnGearMap');
1809        inputs.setAttribute('title', (sitioIng) ? 'Setting' : 'Configuración del mapa');
1810        inputs.setAttribute('aria-controls','contentP');
1811        inputs.setAttribute('data-target','#contentP'+elm.id);
1812        inputs.setAttribute('style', 'font-size:15pt;');
1813        inputs.setAttribute('onclick', 'configOpen('+objelm+')');
1814    
1815        let sp = document.createElement("span");
1816        sp.setAttribute('class', 'glyphicon glyphicon-cog');
1817        sp.setAttribute('aria-hidden', 'true');
1818        sp.setAttribute('style', 'color:black !important');
1819    
1820        gp.appendChild(inputs);
1821        inputs.appendChild(sp);
1822        row.appendChild(gp);
1823    
1824       // $('#btnGearMap'+elm.id).tooltip();
1825    
1826        let divCon = document.createElement("div");
1827        divCon.setAttribute('id', 'contentP'+elm.id);
1828        divCon.setAttribute('style', 'text-align:left');
1829        divCon.setAttribute('class', 'sidepanel contentP');
1830        let divP=document.createElement("div");
1831        divP.setAttribute('id', 'contentConfig'+elm.id);
1832    
1833        divP.setAttribute('style', 'opacity:0;height:100%');
1834    
1835        let cont= document.getElementById(elm.id);
1836        let mesc =  cont.getAttribute('data-mestra');
1837        let mpal =  cont.getAttribute('data-mpaleta');
1838        if(mesc==='true' && !mpal==='true')
1839            divP.setAttribute('style', 'opacity:0;height:100%;margin-top:10px');
1840        if(mpal==='true' && !mesc==='true')
1841        divP.setAttribute('style', 'opacity:0;height:100%;margin-top:10px');
1842    
1843        if(mesc==='true'){
1844            let labelR=document.createElement("label");
1845            if (encDomIng) 
1846                labelR.innerHTML="Select a stratification method:";
1847            else
1848                labelR.innerHTML="Seleccione un método de estratificación:";
1849            labelR.setAttribute('style', 'display:block !important;margin-left: 8px;');
1850            divP.appendChild(labelR);
1851        }
1852        
1853    
1854        divCon.appendChild(divP);
1855    
1856        row.appendChild(divCon);
1857        return divP;
1858        
1859    } catch (error) {
1860        console.log("cr_btnGear: "+error)
1861        
1862    }
1863   
1864};
1865const cr_radiobtn = (row,parametrosOrig) => { 
1866    let objparam=JSON.stringify(parametrosOrig);
1867    let input2 = document.createElement("input");
1868    input2.setAttribute('type', 'radio');
1869    input2.setAttribute('id', 'rbscaleQuantile'+parametrosOrig.id);
1870    input2.setAttribute('class', 'form-check-input');
1871    input2.setAttribute('name', 'scaleradio'+parametrosOrig.id);
1872    if(parametrosOrig.estra==undefined||parametrosOrig.estra=='3')
1873        input2.setAttribute('checked', 'true');
1874    input2.setAttribute('style', 'margin: 3px 3px 0px 5px;');
1875    input2.setAttribute('value', '3');
1876    input2.setAttribute('onclick','clicRadio(' +objparam+ ')');
1877
1878
1879    let sp2 = document.createElement("label");
1880    sp2.setAttribute('class', 'form-check-label');
1881    sp2.setAttribute('style', 'font-weight: normal;');
1882    sp2.innerHTML="Cuantil";
1883    row.appendChild(input2);
1884    row.appendChild(sp2);
1885
1886    /*let input1 = document.createElement("input");
1887    input1.setAttribute('type', 'radio');
1888    input1.setAttribute('id', 'rbscaleQuantize');
1889    input1.setAttribute('class', 'form-check-input');
1890    input1.setAttribute('name', 'scaleradio');
1891    if(parametrosOrig.estra=='3')
1892        input1.setAttribute('checked', 'true');
1893    input1.setAttribute('style', 'margin: 3px 3px 0px 5px;');
1894    input1.setAttribute('value', '3');
1895    input1.setAttribute('onclick', 'clicRadio()');
1896    
1897 
1898
1899    let sp1 = document.createElement("label");
1900    sp1.setAttribute('class', 'form-check-label');
1901    sp1.setAttribute('style', 'font-weight: normal;');
1902    sp1.innerHTML="Cuantizar";
1903
1904    row.appendChild(input1);
1905    row.appendChild(sp1);*/
1906  
1907
1908
1909    let input3 = document.createElement("input");
1910    input3.setAttribute('type', 'radio');
1911    input3.setAttribute('id', 'rbscalekmedias'+parametrosOrig.id);
1912    input3.setAttribute('class', 'form-check-input');
1913    input3.setAttribute('name', 'scaleradio'+parametrosOrig.id);
1914    if(parametrosOrig.estra=='1')
1915        input3.setAttribute('checked', 'true');
1916    input3.setAttribute('style', 'margin: 3px 3px 0px 5px;');
1917    input3.setAttribute('value', '1');
1918    input3.setAttribute('onclick','clicRadio(' +objparam+ ')');
1919
1920    let sp3 = document.createElement("label");
1921    sp3.setAttribute('class', 'form-check-label');
1922    sp3.setAttribute('style', 'font-weight: normal;');
1923    sp3.innerHTML="K-medias";
1924    row.appendChild(input3);
1925    row.appendChild(sp3);
1926
1927    let input4 = document.createElement("input");
1928    input4.setAttribute('type', 'radio');
1929    input4.setAttribute('id', 'rbscaleDalenius'+parametrosOrig.id);
1930    input4.setAttribute('class', 'form-check-input');
1931    input4.setAttribute('name', 'scaleradio'+parametrosOrig.id);
1932    if(parametrosOrig.estra=='2')
1933        input4.setAttribute('checked', 'true');
1934    input4.setAttribute('style', 'margin: 3px 3px 0px 5px;');
1935    input4.setAttribute('value', '2');
1936    input4.setAttribute('onclick', 'clicRadio(' +objparam+ ')');
1937
1938    let sp4 = document.createElement("label");
1939    sp4.setAttribute('class', 'form-check-label');
1940    sp4.setAttribute('style', 'font-weight: normal;');
1941    sp4.innerHTML="Dalenius";
1942    row.appendChild(input4);
1943    row.appendChild(sp4);
1944
1945};
1946const  cr_paletacolores = (row,idp) => {
1947    let rb = document.createElement("div");
1948    rb.setAttribute('id', 'paletas'+idp);
1949    rb.setAttribute('class', 'paletas');
1950    rb.setAttribute('style','margin-left: 8px;margin-top: 10px;');
1951    let label=document.createElement("label");
1952    label.setAttribute('style', 'display:block !important;');
1953    if (encDomIng) 
1954        label.innerHTML="Select a color palette:";
1955    else
1956        label.innerHTML="Seleccione una paleta de colores:";
1957    rb.appendChild(label);
1958    row.appendChild(rb);
1959};
1960const cr_btnExcel_D3 = (id, row,cobertura) => {
1961    //let row = document.getElementById('mapa_trauma_divbtns_' + idExcel);
1962    let ExcelPr = document.createElement("div");
1963    ExcelPr.setAttribute('id', 'btnExcel');
1964    ExcelPr.setAttribute('class', 'btn-group menubuttons');
1965    ExcelPr.setAttribute('style', 'right: 5px;position: absolute;','display: block;');
1966    
1967    let input = document.createElement("input");
1968    input.setAttribute('type', 'image');
1969    input.setAttribute('src','/img/ico/ico_xls.png');
1970    input.setAttribute('class','btn btn-link btn-xs');
1971    input.setAttribute('style','cursor: pointer');
1972    input.setAttribute('style','float:right;');
1973    input.setAttribute('onclick', 'genTabled3("' + id + '",true,"'+cobertura+'")');
1974    //input.setAttribute('style','top:10px;'); 
1975
1976    let ExcelMap = document.createElement("span");
1977    ExcelMap.setAttribute('aria-hidden', 'true');
1978  
1979    ExcelPr.appendChild(input);
1980    input.appendChild(ExcelMap);
1981    row.appendChild(ExcelPr);
1982};
1983const cr_btnImp_D3 = (id, row) => {
1984    let inputs, sitioIng = window.location.host.match(/en.\w+[inegi.org.mx]+/gi);
1985    let gp = document.createElement("div");
1986    gp.setAttribute('id', 'btngImp');
1987    gp.setAttribute('class', 'btn-group menubuttons');
1988    gp.setAttribute('style', 'top: 25px; right: 5px;position: absolute; display: block;');
1989
1990    inputs = document.createElement("button");
1991    inputs.setAttribute('type', 'button');
1992    inputs.setAttribute('id', 'btnImpMap');
1993    inputs.setAttribute('class', 'btn btn-default btn-md');
1994    inputs.setAttribute('title', (sitioIng) ? 'Print map' : 'Imprimir mapa');
1995    inputs.setAttribute('data-toggle', 'tooltip');
1996    inputs.setAttribute('style', 'float:right;');
1997    inputs.setAttribute('onclick', 'clonDuplicadod3("' + id + '")');
1998    //inputs.setAttribute('style', 'top:35px;');
1999
2000    let sp = document.createElement("span");
2001    sp.setAttribute('class', 'inegi-imprimir');
2002    sp.setAttribute('aria-hidden', 'true');
2003    sp.setAttribute('style', 'font-size:18pt;');
2004
2005    gp.appendChild(inputs);
2006    inputs.appendChild(sp);
2007    row.appendChild(gp);
2008
2009    $('#btnImpMap').tooltip();
2010
2011};
2012const cr_divcompara = (row,idp) => {
2013    let divP= document.createElement("div");
2014    divP.setAttribute("class","row"); 
2015    divP.innerHTML='<div class="col-md-4"> <div class="col-md-12" style="text-align: center;"><br /> <select id="select-pais-base"><option value="0">-- Selecciona el pais base --</option> </select></div></div>'+
2016    '<div class="col-md-4" style="margin-top: 50px;"><div class="col-md-12" style="text-align: center;"><br /><button id="btnCompara" type="button" onClick="calculoComapara('+idp+')" class="btn btn-default">Comparar</button></div></div>'+
2017    '<div class="col-md-4"><div class="col-md-12" style="text-align: center;"><br /><select id="select-pais" multiple=""><option value="0">-- Selecciona el pais o los paises --</option></select></div></div>';
2018    row.appendChild(divP);
2019};
2020const clicRadio = (parametrosOrig) =>{
2021    let rtipo= $('input:radio[name=scaleradio'+parametrosOrig.id+']:checked').val();
2022    let cont= document.getElementById(parametrosOrig.id);
2023    let colorSelect = cont.getAttribute('data-colorchange');
2024    parametrosOrig.estra=rtipo;
2025    if(colorSelect!='' && colorSelect!=null)
2026        parametrosOrig.paleta=colorSelect;
2027    $('#Capa_1'+parametrosOrig.id).empty();
2028    $('#estMapa_'+parametrosOrig.id).empty();
2029    $('#legTitle'+parametrosOrig.id).empty();
2030    switch (rtipo) {
2031     case "1":
2032         crearMapaTematicoD3(parametrosOrig);
2033       break;
2034     case "3":
2035         crearMapaTematicoD3(parametrosOrig);
2036       break;
2037     case "4":
2038         crearMapaTematicoD3(parametrosOrig);
2039       break;
2040       case "2":
2041         crearMapaTematicoD3(parametrosOrig);
2042       break;
2043   }
2044   setTimeout(function(){
2045    paletaSelect(colorSelect,parametrosOrig);
2046}, 1000);
2047  
2048};
2049
2050const configOpen = (elm) => {
2051    let objelm=JSON.stringify(elm);
2052        let cont= document.getElementById(elm.id);
2053        let mesc =  cont.getAttribute('data-mestra');
2054        let mpal =  cont.getAttribute('data-mpaleta');
2055        let mcom =  cont.getAttribute('data-mcompara');
2056     
2057    let heightdiv;
2058    if(mesc==='true'&&mpal==='true')
2059        heightdiv=165;
2060    else {
2061        if(mesc==='true')
2062            heightdiv=80;
2063        if(mpal==='true')
2064            heightdiv=100;
2065    }
2066    if (mcom){
2067        heightdiv=135;
2068    }
2069    if (screen.width <= 460){
2070        heightdiv=heightdiv+80;
2071    }
2072        
2073
2074    $('[data-toggle="tooltip"]').tooltip();
2075     let widthP=contentPWidth(elm);
2076    document.getElementById("contentP"+elm.id).style.width = widthP+'%';
2077    document.getElementById("contentP"+elm.id).style.height = heightdiv+'px';
2078    document.getElementById("contentP"+elm.id).style.border = "1px solid #ddd";
2079    document.getElementById("contentP"+elm.id).style.boxShadow= "rgb(245 245 245) 4px 5px";
2080    document.getElementById("contentConfig"+elm.id).style.opacity = "1";
2081    let btn=document.getElementById('btnGearMap'+elm.id);
2082    btn.setAttribute('onclick', 'configClose('+objelm+')');
2083
2084 };
2085
2086const configClose = (elm) => {
2087    let objelm=JSON.stringify(elm);
2088    document.getElementById("contentP"+elm.id).style.width = "0";
2089    let btn=document.getElementById('btnGearMap'+elm.id);
2090    btn.setAttribute('onclick', 'configOpen('+objelm+')');
2091
2092    setTimeout(function(){
2093        document.getElementById("contentP"+elm.id).style.border = "1px solid transparent"; 
2094        document.getElementById("contentP"+elm.id).style.boxShadow= "transparent 4px 5px";
2095        document.getElementById("contentConfig"+elm.id).style.opacity = "0";
2096        document.getElementById("contentP"+elm.id).style.height = '10px';
2097    }, 200);
2098        
2099};
2100
2101const updateMun = (dataMun,dataEstra,elm) => {
2102    try {
2103        let lstMunEnt = new Array();
2104        let coloresDef= new Array();
2105        let paletaColores;
2106        let paletSelect=document.getElementById(elm.id).getAttribute('data-colorchange');
2107        if(paletSelect!=null){
2108            switch (paletSelect) {
2109              case "1":
2110                paletaColores=paleta1;
2111              break;
2112              case "2":
2113                paletaColores=paleta2;
2114              break;
2115              case "3":
2116                paletaColores=paleta3;
2117              break;
2118              case "4":
2119                paletaColores=paleta4;
2120              break;
2121            }
2122        }
2123        else{
2124            paletaColores=coloresIniciales_D3;
2125        }
2126     for (let x = 0; x < dataMun.length; x++) {
2127                lstMunEnt.push(new municpio_D3(dataMun[x].Municipio, dataMun[x].Nombre_Municipio, dataMun[x].Valores[0].Valor, '',dataMun[x].Valores[0].Periodo));
2128        }
2129    
2130        for (let i = 0; i < dataEstra.length; i++) {
2131            if (dataEstra[i].nestrato == 'extremosar'){
2132                coloresDef.push(coloresIniciales_D3[11]);
2133            }
2134            else if (dataEstra[i].nestrato == 'extremosab'){
2135                coloresDef.push(coloresIniciales_D3[10]);
2136            }
2137            else if  (dataEstra[i].nestrato == 'ceros'){
2138                coloresDef.push(coloresIniciales_D3[9]);
2139            }
2140            else
2141                coloresDef.push(paletaColores[dataEstra[i].nestrato-1]);
2142    }
2143    for (let j = 0; j < lstMunEnt.length; j++) {
2144            for (let i = 0; i < dataEstra.length; i++) {
2145                   if (entre_D3(dataEstra[i].limSuperior, dataEstra[i].limInferior, (lstMunEnt[j].valor).replace(/,/g, ''))) {
2146                        lstMunEnt[j].estrato = dataEstra[i].nestrato;
2147                        let coloInit = paletaColores[dataEstra[i].nestrato-1];
2148                        if (dataEstra[i].nestrato == 'extremosar') {
2149                            coloInit = coloresIniciales_D3[(11)];
2150                        }
2151                        if (dataEstra[i].nestrato == 'extremosab') {
2152                            coloInit = coloresIniciales_D3[(10)];
2153                        }
2154                        if (dataEstra[i].nestrato == 'ceros'){
2155                            coloInit = coloresIniciales_D3[9];
2156                        }
2157                        lstMunEnt[j].color = coloInit;
2158                        break;
2159                    }
2160    
2161        }
2162    }
2163    
2164        let jsonRes = {
2165            estratos: dataEstra,
2166            elementos: lstMunEnt,
2167            coloresMun: coloresDef
2168        }
2169        elm.municipiosR=jsonRes.elementos;
2170        return jsonRes;
2171    } catch (error) {
2172        console.log("updateMun"+error);
2173    }
2174  
2175};
2176
2177//para imprimir mapa y descargar xls
2178const clonDuplicadod3 = (e) => {
2179    let t = document.getElementById("contenedorMapaPrint");
2180    t && document.body.removeChild(t);
2181    let a = document.createElement("div");
2182    a.setAttribute("id", "contenedorMapaPrint"), document.body.appendChild(a), mostrarHora(a), imagendiv(a), textodiv(a), nomTituloTem(e);
2183    document.getElementById("mapitaClon");
2184    if (document.getElementById("objMapa_" + e)) {
2185        let n = document.querySelector("#objMapa_" + e+" >#Capa_1"+e).cloneNode("true");
2186        n.setAttribute("id", "mapitaClon"), document.createElement("div").innerHTML = "duplicado", n.classList.add("mapClonado"), a.appendChild(n);
2187
2188        let i = window.location.host.match(/en.\w+[inegi.org.mx]+/gi),
2189            o = document.getElementById((i ? "cont_K-means_" : "cont_K-medias_") + e);
2190        if (o) o.classList.contains("active") || (o = document.getElementById("cont_Dalenius_" + e));
2191        else o = document.getElementById("estMapa_" + e);
2192        let d = o.cloneNode("true");
2193        d.setAttribute("id", d.id + "2"), d.classList.add("tablitaClonada"), $(d).find("table").attr("id", "tblEstra_" + e + "_dalTable"), a.appendChild(d), genTable(e, false), setTimeout(function () {
2194            let e = window.navigator.userAgent;
2195            /Edge/.test(e) ? impIE() : window.print();
2196        })
2197    } else alert("Solo se puede imprimir el mapa Temático, favor de seleccionarlo.");
2198};
2199const genTabled3 = (e, isExport,cobertura) => {
2200    let filen;
2201    let t = document.getElementById("contenedorMapaPrint");
2202    if (t == undefined) {
2203        t = document.createElement("div");
2204        t.setAttribute("id", "contenedorMapaPrint");
2205        document.body.appendChild(t);
2206    }
2207    mapasTemObjImp = $.grep(mapasTemObj_D3, function (j) {
2208        return j.id == e;
2209    });
2210
2211
2212    if (document.querySelector('#tblTemTbl')) {
2213        t.removeChild(t.querySelector('#tblTemTbl'));
2214    }
2215    
2216    
2217
2218    let a3 = document.createElement("table");
2219    a3.setAttribute("id", "tblTemTbl", e);
2220
2221
2222    if (isExport) {
2223
2224        let a = new Date,
2225            n = a.getDate(),
2226            i = a.getMonth() + 1,
2227            o = a.getFullYear(),
2228            d = a.getHours(),
2229            m = a.getMinutes(),
2230            s= a.getSeconds();
2231
2232        let trExcelPr = document.createElement("tr");
2233        trExcelPr.className = "tr-excel-tr";
2234        let textExcel = document.createElement("td");
2235        textExcel.className = "td-excel-text";
2236        textExcel.setAttribute('colspan', '3');
2237        textExcel.setAttribute('style', 'font-weight: bold;font-size:12pt; font-family: Arial;');
2238        textExcel.innerHTML = "Instituto Nacional de Estadística y Geografía (INEGI)";
2239        trExcelPr.appendChild(textExcel);
2240        a3.appendChild(trExcelPr);
2241
2242        let trExcelsub = document.createElement("tr");
2243        trExcelsub.className = "tr-excel-tr";
2244        let textExcelsub = document.createElement("td");
2245        textExcelsub.className = "td-excel-text";
2246        textExcelsub.setAttribute('colspan', '3');
2247        textExcelsub.setAttribute('style', 'font-weight: bold;font-size:11pt;font-family: Arial;');
2248        let nExcelsub = window.location.host.match(/en.\w+[inegi.org.mx]+/gi);
2249        if(nExcelsub)
2250            textExcelsub.innerHTML = "Distribution of establishments";
2251        else
2252            textExcelsub.innerHTML = "Distribución de establecimientos";
2253        trExcelsub.appendChild(textExcelsub);
2254        //a3.appendChild(trExcelsub);
2255
2256        let textBan = document.createElement("tr");
2257        textBan.className = "tr-excel-Ban";
2258        let textBanEx = document.createElement("td");
2259        if (textBanEx.className = "td-excel-ban", "00" == mapasTemObjImp[0].idEntidad) {
2260            let nExcelBan = window.location.host.match(/en.\w+[inegi.org.mx]+/gi);
2261            if(tituloIndicadores_D3 == true){
2262                textBanEx.innerHTML = nExcelBan ? "Bank Indicators" : "Banco de Indicadores";
2263            }
2264            else{
2265                textBanEx.innerHTML = '';
2266            }
2267            textBanEx.setAttribute('style', 'font-weight: bold;');
2268        } else
2269            textBanEx.innerHTML = mapasTemObjImp[0].nombre;
2270        textBanEx.setAttribute('colspan', '3');
2271        textBan.appendChild(textBanEx);
2272        a3.appendChild(textBan);
2273
2274        let textNac = document.createElement("tr");
2275        textNac.className = "tr-excel-Nac";
2276        let textNacEx = document.createElement("td");
2277        if (textNacEx.className = "td-excel-nac", "00" == mapasTemObjImp[0].idEntidad) {
2278            let nExcel = window.location.host.match(/en.\w+[inegi.org.mx]+/gi);
2279            textNacEx.innerHTML = nExcel ? "United Mexican States" : "Estados Unidos Mexicanos";
2280            textNacEx.setAttribute('style', 'font-weight: bold;')
2281        } else
2282            textNacEx.innerHTML = mapasTemObjImp[0].nombre;
2283        textNacEx.setAttribute('colspan', '3');
2284        textNac.appendChild(textNacEx);
2285        //a3.appendChild(textNac);
2286
2287        let titlExcel = document.createElement("tr");
2288        titlExcel.className = "tr-title-ex";
2289        let tiExceltd = document.createElement("td");
2290        tiExceltd.className = "nom-Tit-Med";
2291        let oMed = "";
2292        null != mapasTemObjImp[0].unidadMedida && "" != mapasTemObjImp[0].unidadMedida && (oMed = " (" + mapasTemObjImp[0].unidadMedida + "), ");
2293        let dMed = "";
2294        null != mapasTemObjImp[0].titulo && (dMed = mapasTemObjImp[0].titulo);
2295        let mUni = "";
2296        null != mapasTemObjImp[0].periodo && (mUni = " " + mapasTemObjImp[0].periodo), tiExceltd.innerHTML = dMed + oMed + mUni;
2297        tiExceltd.setAttribute('colspan', '3'),
2298        tiExceltd.setAttribute('style', 'font-weight: bold;');
2299        titlExcel.appendChild(tiExceltd);
2300        if(dMed=='')
2301            a3.appendChild(textExcelsub);
2302        else
2303            a3.appendChild(titlExcel);
2304
2305        let trExcelPr2 = document.createElement("tr");
2306        trExcelPr2.className = "tr-excel-tr";
2307        let horsExcel = document.createElement("td");
2308        let nExcelhors = window.location.host.match(/en.\w+[inegi.org.mx]+/gi);
2309        horsExcel.className = "td-excel-text";
2310        horsExcel.setAttribute('colspan', '3');
2311        horsExcel.setAttribute('style', 'font-size:9pt;font-family: Arial;');
2312        if(nExcelhors)
2313            horsExcel.innerHTML = "Date: "+ n + "/" + i + "/" + o + " -" + d + ":" + m;
2314        else
2315            horsExcel.innerHTML = "Fecha de consulta: "+ n + "/" + i + "/" + o + " -" + d + ":" + m;
2316        filen='mapa'+o+i+n+d+m+s;
2317        trExcelPr2.appendChild(horsExcel);
2318        a3.appendChild(trExcelPr2);
2319
2320    }
2321
2322
2323    let n = document.createElement("thead");
2324    n.className = "tTemTbl", a3.appendChild(n);
2325    let i = document.createElement("tr");
2326    i.className = "tr-color-tr";
2327    let o = document.createElement("td");
2328    o.className = "td-Nombre-td";
2329    o.setAttribute('style', 'font-weight: bold;background-color:#c8c8c8;border: 1px solid black;font-size:10pt;font-family: Arial;');
2330    o.innerText="Estrato";
2331    let d = document.createElement("td");
2332    d.setAttribute('style', 'font-weight: bold;background-color:#c8c8c8;border: 1px solid black;font-size:10pt;font-family: Arial;');
2333    if (d.className = "td-Nombre-td", "00" == mapasTemObjImp[0].idEntidad) {
2334        let m = window.location.host.match(/en.\w+[inegi.org.mx]+/gi);
2335        if(cobertura=='est'){
2336            d.innerText = m ? "Geographic Region" : "Entidad federativa";
2337        }
2338         else if(cobertura==='mun'){
2339            d.innerText = m ? "Geographic Region" : "Región geográfica";
2340        }
2341         else{
2342            d.innerText = m ? "Country" : "País";
2343         }
2344    } else {
2345        m = window.location.host.match(/en.\w+[inegi.org.mx]+/gi);
2346        d.innerText = m ? "Geographic Region" : "Municipios"
2347    }
2348    let r = document.createElement("td");
2349    r.className = "td-Valor-td";
2350    r.setAttribute('style', 'font-weight: bold;background-color:#c8c8c8;border: 1px solid black;font-size:10pt;font-family: Arial;');
2351    m = window.location.host.match(/en.\w+[inegi.org.mx]+/gi);
2352    r.innerText = m ? "Value" : "Valor", i.appendChild(o), i.appendChild(d), i.appendChild(r), n.appendChild(i);
2353    let l = document.createElement("tbody");
2354    a3.appendChild(l);
2355    for (let c = 0; c < mapasTemObjImp[0].municipios.length; c++) {
2356        let p = document.createElement("tr"),
2357            s = document.createElement("td"),
2358            u = document.createElement("td"),
2359            g = document.createElement("td");
2360        s.setAttribute("style", "border: 1px solid black; background-color: " + mapasTemObjImp[0].municipios[c].color + " !important;"), u.className = "mt-txt-align-l", u.innerText = mapasTemObjImp[0].municipios[c].nombre, u.setAttribute("style", "padding-left: 1em !important;border: 1px solid black;"), g.setAttribute('style', 'border: 1px solid black;'),g.className = "mt-txt-align-r", g.innerText = mapasTemObjImp[0].municipios[c].valor, l.appendChild(p), p.appendChild(s), p.appendChild(u), p.appendChild(g);
2361    }
2362    for (let c = 0; c < mapasTemObjImp[0].municipiosR.length; c++) {
2363        let p = document.createElement("tr"),
2364            s = document.createElement("td"),
2365            u = document.createElement("td"),
2366            g = document.createElement("td");
2367        s.setAttribute("style", "border: 1px solid black; background-color: " + mapasTemObjImp[0].municipiosR[c].color + " !important;"), u.className = "mt-txt-align-l", u.innerText = mapasTemObjImp[0].municipiosR[c].nombre, u.setAttribute("style", "padding-left: 1em !important;border: 1px solid black;"), g.setAttribute('style', 'border: 1px solid black;'),g.className = "mt-txt-align-r", g.innerText = mapasTemObjImp[0].municipiosR[c].valor, l.appendChild(p), p.appendChild(s), p.appendChild(u), p.appendChild(g);
2368    }
2369    let nExcelfue = window.location.host.match(/en.\w+[inegi.org.mx]+/gi);
2370    let trExcelf = document.createElement("tr");
2371    let textoFuente="Fuente: ";
2372    if(mapasTemObjImp[0].fuentes.length!=0){
2373      for(let fs=0; fs<mapasTemObjImp[0].fuentes.length;fs++){
2374          if(fs==0)
2375            textoFuente=textoFuente+mapasTemObjImp[0].fuentes[fs].nombreFuente;
2376            else{
2377               if(mapasTemObjImp[0].fuentes[fs].nombreFuente!=mapasTemObjImp[0].fuentes[fs-1].nombreFuente)
2378                textoFuente=textoFuente+'</br>'+mapasTemObjImp[0].fuentes[fs].nombreFuente;}
2379      }
2380    }
2381    else{
2382        if(nExcelfue)
2383        textoFuente = "INEGI. Directorio Estadístico Nacional de Unidades Económicas";
2384    else
2385        textoFuente = "INEGI. Directorio Estadístico Nacional de Unidades Económicas";
2386        
2387    }
2388    trExcelfclassName = "tr-excel-tr";
2389    let fExcel = document.createElement("td");
2390    fExcel.className = "td-excel-hors";
2391    fExcel.setAttribute('colspan', '3');
2392    fExcel.innerHTML = textoFuente;
2393    trExcelf.appendChild(fExcel);
2394    a3.appendChild(trExcelf);
2395  
2396    t.appendChild(a3);
2397    if (isExport) {
2398        tablesToExceld3('tblTemTbl',filen,e,cobertura);
2399    }
2400}
2401const tablesToExceld3 = (idtb, e,id,cobertura) => {
2402    esperaExceld3(idtb, e);
2403    document.querySelector("#objMapa_" + id+ ">#Capa_1"+id).style.height = '500px';
2404    if(cobertura!='pais')
2405         $("#estMapa_"+ id ).height(150);
2406};
2407const esperaExceld3 = (idtb, e) => {
2408    let exportador = {
2409        _fallbacktoCSV: true,
2410        toXLS: function toExcel(tableId, filename) {
2411            this._filename = (typeof filename == 'undefined') ? tableId : filename;
2412            //let ieVersion = this._getMsieVersion();
2413            //Fallback to CSV for IE & Edge
2414            if ((this._getMsieVersion() || this._isFirefox()) && this._fallbacktoCSV) {
2415                console.log('Explorer o Mozilla');
2416                return this.toCSV(tableId);
2417            } else if (this._getMsieVersion() || this._isFirefox()) {
2418                alert("Not supported browser");
2419            }
2420            //Other Browser can download xls
2421            let htmltable = document.getElementById(tableId);
2422            let html = htmltable.outerHTML;
2423        },
2424        toCSV: function (tableId, filename) {
2425            this._filename = (typeof filename === 'undefined') ? tableId : filename;
2426            // Generate our CSV string from out HTML Table
2427            let csv = html;
2428            // Create a CSV Blob
2429            let blob = new Blob([csv], { type: "data:application/vnd.ms-excel" });
2430            // Determine which approach to take for the download
2431            // Works for Internet Explorer and Microsoft Edge
2432            if (navigator.msSaveOrOpenBlob) {
2433                navigator.msSaveOrOpenBlob(blob, this._filename + ".xls");
2434            } else {
2435                this._downloadAnchor(URL.createObjectURL(blob), 'xls');
2436            }
2437        },
2438        _getMsieVersion: function () {
2439            let ua = window.navigator.userAgent;
2440            let msie = ua.indexOf("MSIE ");
2441            if (msie > 0) {
2442                // IE 10 or older => return version number
2443                return parseInt(ua.substring(msie + 5, ua.indexOf(".", msie)), 10);
2444            }
2445            let trident = ua.indexOf("Trident/");
2446            if (trident > 0) {
2447                // IE 11 => return version number
2448                let rv = ua.indexOf("rv:");
2449                return parseInt(ua.substring(rv + 3, ua.indexOf(".", rv)), 10);
2450            }
2451            let edge = ua.indexOf("Edge/");
2452            if (edge > 0) {
2453                // Edge (IE 12+) => return version number
2454                return parseInt(ua.substring(edge + 5, ua.indexOf(".", edge)), 10);
2455            }
2456            // other browser
2457            return false;
2458        },
2459        _isFirefox: function () {
2460            if (navigator.userAgent.indexOf("Firefox") > 0) {
2461                return 1;
2462            }
2463            return 0;
2464        },
2465        _downloadAnchor: function (content, ext) {
2466            let anchor = document.createElement("a");
2467            anchor.style = "display:none !important";
2468            anchor.id = "downloadanchor";
2469            document.body.appendChild(anchor);
2470            // If the [download] attribute is supported, try to use it
2471            if ("download" in anchor) {
2472                anchor.download = this._filename + "." + ext;
2473            }
2474            anchor.href = content;
2475            anchor.click();
2476            anchor.remove();
2477        },
2478        _tableToCSV: function (table) {
2479            // We'll be co-opting `slice` to create arrays
2480            let slice = Array.prototype.slice;
2481            return table;
2482        }
2483    };
2484
2485    let tab_text = document.getElementById(idtb);
2486    let ua = window.navigator.userAgent;
2487    let msie = ua.indexOf("MSIE ");
2488    console.log('tab_text');
2489
2490    let html = tab_text.outerHTML;
2491    while (html.indexOf('á') != -1) html = html.replace('á', '&aacute;');
2492    while (html.indexOf('Á') != -1) html = html.replace('Á', '&Aacute;');
2493    while (html.indexOf('é') != -1) html = html.replace('é', '&eacute;');
2494    while (html.indexOf('É') != -1) html = html.replace('É', '&Eacute;');
2495    while (html.indexOf('í') != -1) html = html.replace('í', '&iacute;');
2496    while (html.indexOf('Í') != -1) html = html.replace('Í', '&Iacute;');
2497    while (html.indexOf('ó') != -1) html = html.replace('ó', '&oacute;');
2498    while (html.indexOf('Ó') != -1) html = html.replace('Ó', '&Oacute;');
2499    while (html.indexOf('ú') != -1) html = html.replace('ú', '&uacute;');
2500    while (html.indexOf('Ú') != -1) html = html.replace('Ú', '&Uacute;');
2501    while (html.indexOf('º') != -1) html = html.replace('º', '&ordm;');
2502    while (html.indexOf('ñ') != -1) html = html.replace('ñ', '&ntilde;');
2503    while (html.indexOf('Ñ') != -1) html = html.replace('Ñ', '&Ntilde;');
2504    tab_text.innerHTML = html;
2505
2506    let link = document.getElementById('link');
2507    
2508    link.href='data:application/vnd.ms-excel,' + encodeURIComponent(html);
2509    link.download=e;
2510    link.click();
2511    if ((exportador._getMsieVersion() || exportador._isFirefox()) && exportador._fallbacktoCSV) {
2512        console.log('Explorer o Mozilla');
2513        //exportador.toCSV(html, 'SVG');
2514
2515    }
2516    else                 //other browser not tested on IE 11
2517    {
2518       // window.open('data:application/vnd.ms-excel,' + encodeURIComponent(html));
2519
2520    }
2521
2522};
2523
2524const contentPWidth = (elm) => {
2525    let cont= document.getElementById(elm.id);
2526    let mesc =  cont.getAttribute('data-mestra');
2527    let mpal =  cont.getAttribute('data-mpaleta');
2528    let mimp = cont.getAttribute('data-mimpr');
2529
2530     
2531    const totalWidth=$('#'+elm.id).width();
2532    let espaciobtn=0;
2533    let calculoPor=0;
2534
2535    if(mimp==='true')
2536        espaciobtn=espaciobtn+$('#btngImp').width();
2537    if(mesc==='true' || mpal==='true')
2538        espaciobtn=espaciobtn+$('#divGear'+elm.id).width();
2539    if(elm.periodoM )
2540        espaciobtn=espaciobtn+$('#spanPer_'+elm.id).width()+10;
2541
2542    calculoPor=(espaciobtn*100)/totalWidth;
2543    return (100-calculoPor)-1;
2544};
2545
2546
2547
2548//get y set
2549const getAgeo_D3 = (obj) => {
2550    let ag = obj.getAttribute('data-ageo');
2551    //let ag = $(obj).data('ageo');//$(obj).attr('data-ageo');
2552    if (ag !== undefined)
2553        return ag;
2554    else
2555        return '00';
2556};
2557const getOportuno_D3 = (obj) => {
2558    let op = obj.getAttribute('data-oportuno');
2559    if (op !== undefined && op !==null)
2560        return op;
2561    else
2562        return 1;
2563};
2564const getTipoEstrat_D3 = (obj) => {
2565    let op = obj.getAttribute('data-tipoestratos');
2566    if (op !== undefined)
2567        return op;
2568    else
2569        return 1;
2570};
2571const getIndicador_D3 = (obj) => {
2572    let ind = obj.getAttribute('data-indicador');
2573    if (ind !== undefined)
2574        return ind;
2575    else
2576        return '';
2577};
2578const getTitulo_D3 = (obj) => {
2579    let tit = obj.getAttribute('data-titulo');
2580    if (tit !== undefined && tit !==null)
2581        return tit;
2582    else
2583        return '';
2584};
2585const getTotal_D3 = (obj) => {
2586    let tot = obj.getAttribute('data-total');
2587    if (tot !== undefined && tot !==null)
2588        return tot;
2589    else
2590        return '';
2591};
2592const getPeriodo_D3 = (obj) => {
2593    let per = obj.getAttribute('data-periodo');
2594    if (per !== undefined && per !==null)
2595        return per;
2596    else
2597        return '';
2598};
2599const getAnio_D3 = (obj) => {
2600    let anio = obj.getAttribute('data-anio');
2601    if (anio !== undefined)
2602        return anio;
2603    else
2604        return '';
2605};
2606const setUnidadM_D3 = (obj) => {
2607    let UnidadM = $(obj).data('setUnidadM_D3');
2608    if (UnidadM !== undefined)
2609        return UnidadM;
2610    else
2611        return true;
2612};
2613const setValorM_D3 = (obj) => {
2614    let ValorM = $(obj).data('setValorM_D3');
2615    if (ValorM !== undefined)
2616        return ValorM;
2617    else
2618        return true;
2619};
2620const setPeriodoM_D3 = (obj) => {
2621    let PeriodoM = $(obj).data('setPeriodoM_D3');
2622    if (PeriodoM !== undefined)
2623        return PeriodoM;
2624    else
2625        return true;
2626};
2627const setFuentesM_D3 = (obj) => {
2628    let FuentesM = $(obj).data('setFuentesM_D3');
2629    if (FuentesM !== undefined)
2630        return FuentesM;
2631    else
2632        return true;
2633};
2634const setNotasM_D3 = (obj) => {
2635    let NotasM = $(obj).data('NotasM');
2636    if (NotasM !== undefined)
2637        return NotasM;
2638    else
2639        return true;
2640};
2641
2642
2643

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.