/*
 * Copyright 2019-2020 - All rights reserved.
 * Rodrigo Tapia-McClung
 *
 * August 2019 - June 2020
 */

/* global Promise, omnivore, JSZip, map, layerControl, intervals, odClick, am4core*/
/* exported, odData, makeBaseMap, baseLayerPromises */

let baseLayerPromises = [],
    od, flowMapsArray = [],
    odData = {};

const compare = (el1, el2, index) => {
    return el1[index] == el2[index] ? 0 : (el1[index] < el2[index] ? -1 : 1);
}

// function to read compressed json and create a leaflet layer
const zip2Lyr = (zipFile, layerName, layerTemplate) => {
    baseLayerPromises.push(
        new Promise((resolve, reject) => {
            fetch(zipFile) // 1) fetch the url
                .then(response => { // 2) filter on 200 OK
                    if (response.status === 200 || response.status === 0) {
                        return Promise.resolve(response.blob());
                    } else {
                        return Promise.reject(new Error(response.statusText));
                    }
                })
                .then(JSZip.loadAsync) // 3) chain with the zip promise
                .then(zip => {
                    let filename = Object.keys(zip.files)[0];
                    let filetype = filename.split(".").pop();
                    return [zip.file(filename), filetype]; // 4) chain with the text content promise
                })
                .then(([file, type]) => {
                    file.async("string").then(
                        function success(text) { // 5) display the result
                            if (type == "json") {
                                layerTemplate.addData(JSON.parse(text));
                            } else if (type == "topojson") {
                                layerName = omnivore.topojson.parse(text, null, layerTemplate);
                            }
                            resolve("done");
                        },
                        function error(e) {
                            console.log(e);
                            reject("error");
                        }
                    );
                });
        })
    );
}

const createPane = (layerPane, zIndex) => {
    map.createPane(layerPane);
    map.getPane(layerPane).style.zIndex = zIndex;
    map.getPane(layerPane).style["mix-blend-mode"] = "normal";
}

const getCentrosColor = s => {
    return s == "Primario" ? "#ff5500" :
        s == "Secundario" ? "#8e1973" :
            "#d1ff73";
}

const getHaciaColor = s => {
    return s > 32000 ? "#00451c" :
        s > 6000 ? "#218542" :
        s > 2000 ? "#4bc44f" :
        s > 1000 ? "#b4d787" :
        "#e3fcd9";
}

const getDesdeColor = s => {
    return s > 6000 ? "#b30000" :
        s > 2000 ? "#fc7f44" :
        s > 1000 ? "#ffaa00" :
        "#ffebbf";
}

const getHaciaPOICColor = s => {
    return s > 4000 ? "#00451c" :
        s > 2000 ? "#218542" :
        s > 1000 ? "#4bc44f" :
        s > 500 ? "#b4d787" :
        "#e3fcd9";
}

const getDesdePOICColor = s => {
    return s > 1000 ? "#fc7f44" :
        s > 500 ? "#ffaa00" :
        "#ffebbf";
}

let munis_contexto, lim_zms, zms, conurbaciones, agebs2005, agebs2010, agebs2015, auto2010, auto2014, auto2018, tecnologia2010, tecnologia2014, tecnologia2018, centros, hacia, desde, centrosPOIC, haciaPOIC, desdePOIC;

//  *** WMS INEGI ***
//Límite geoestadístico estatal
let layer_limiteEstatal = new L.tileLayer.wms("http://gaia.inegi.org.mx/NLB/tunnel/wms/wms61?", {
    layers: "c100", //Límite geoestadístico estatal
    format: "image/svg+xml",
    transparent: true,
    pane: "pane_estatal",
    attribution: "INEGI 2019"
});
//RED NACIONAL DE CAMINOS
let layer_RedNacionalCaminos = new L.tileLayer.wms("http://gaia.inegi.org.mx/NLB/tunnel/wms/wms61?", {
    layers: "RNC", //Red nacional de caminos
    format: "image/svg+xml",
    transparent: true,
    pane: "pane_carreteras",
    attribution: "INEGI 2019"
});

//LOCALIDAD URBANA
let layer_locUrban = new L.tileLayer.wms("http://gaia.inegi.org.mx/NLB/tunnel/wms/wms61?", {
    layers: "c102",
    format: "image/svg+xml",
    transparent: true,
    pane: "pane_locs",
    attribution: "INEGI 2019"
});
//Límite geoestadístico municipal
let layer_limiteMunicipal = new L.tileLayer.wms("http://gaia.inegi.org.mx/NLB/tunnel/wms/wms61?", {
    layers: "c101", //Límite geoestadístico municipal
    format: "image/svg+xml",
    transparent: true,
    pane: "pane_munis",
    attribution: "INEGI 2019",
    minZoom: 9
});

//  *** FIN WMS INEGI ***
let layer_auto2010 = new L.geoJson(null, {
    attribution: "",
    pane: "pane_auto2010",
    pointToLayer: (feature, latlng) => {
        let autoMarker = L.BeautifyIcon.icon({
            icon: "desechos",
            iconSize: [0, 0],
            iconAnchor: [7, 10],
            iconShape: "", //"circle",
            popupAnchor: [0, 0],
            innerIconStyle: "font-size: 15px;",
            html: "<span class=\"fa-stack\"><i class=\"fas fa-desechos fa-stack-1x\" style=\"color:rgba(0,121,159,0.3);font-size: 8px;\"></i></span>",
            borderWidth: 0,
            borderColor: "transparent",
            backgroundColor: "transparent"
        });
        return new L.Marker(latlng, {
            icon: autoMarker
        });
    }
});

let layer_auto2014 = new L.geoJson(null, {
    attribution: "",
    pane: "pane_auto2014",
    pointToLayer: (feature, latlng) => {
        let autoMarker = L.BeautifyIcon.icon({
            icon: "desechos",
            iconSize: [0, 0],
            iconAnchor: [7, 10],
            iconShape: "", //"circle",
            popupAnchor: [0, 0],
            innerIconStyle: "font-size: 15px;",
            html: "<span class=\"fa-stack\"><i class=\"fas fa-desechos fa-stack-1x\" style=\"color:rgba(60,75,175,0.3);font-size: 8px;\"></i></span>",
            borderWidth: 0,
            borderColor: "transparent",
            backgroundColor: "transparent"
        });
        return new L.Marker(latlng, {
            icon: autoMarker
        });
    }
});

let layer_auto2018 = new L.geoJson(null, {
    attribution: "",
    pane: "pane_auto2018",
    pointToLayer: (feature, latlng) => {
        let autoMarker = L.BeautifyIcon.icon({
            icon: "desechos",
            iconSize: [0, 0],
            iconAnchor: [7, 10],
            iconShape: "",
            popupAnchor: [0, 0],
            innerIconStyle: "font-size: 15px;",
            html: "<span class=\"fa-stack\"><i class=\"fas fa-desechos fa-stack-1x\" style=\"color:rgba(35,53,249,0.3);font-size: 8px;\"></i></span>",
            borderWidth: 0,
            borderColor: "transparent",
            backgroundColor: "transparent"
        });
        return new L.Marker(latlng, {
            icon: autoMarker
        });
    }
});

let layer_tecnologia2010 = new L.geoJson(null, {
    attribution: "",
    pane: "pane_tecnologia2010",
    pointToLayer: (feature, latlng) => {
        let autoMarker = L.BeautifyIcon.icon({
            icon: "desechos",
            iconSize: [0, 0],
            iconAnchor: [7, 10],
            iconShape: "",
            popupAnchor: [0, 0],
            innerIconStyle: "font-size: 12px;",
            html: "<span class=\"fa-stack\"><i class=\"fas fa-desechos fa-stack-1x\" style=\"color:rgba(88,24,69,0.3);font-size: 8px;\"></i></span>",
            borderWidth: 0,
            borderColor: "transparent",
            backgroundColor: "transparent"
        });
        return new L.Marker(latlng, {
            icon: autoMarker
        });
    }
});

let layer_tecnologia2014 = new L.geoJson(null, {
    attribution: "",
    pane: "pane_tecnologia2014",
    pointToLayer: (feature, latlng) => {
        let autoMarker = L.BeautifyIcon.icon({
            icon: "desechos",
            iconSize: [0, 0],
            iconAnchor: [7, 10],
            iconShape: "",
            popupAnchor: [0, 0],
            innerIconStyle: "font-size: 8px;",
            html: "<span class=\"fa-stack\"><i class=\"fas fa-desechos fa-stack-1x\" style=\"color:rgba(144,12,63,0.3);font-size: 8px;\"></i></span>",
            borderWidth: 0,
            borderColor: "transparent",
            backgroundColor: "transparent"
        });
        return new L.Marker(latlng, {
            icon: autoMarker
        });
    }
});

let layer_tecnologia2018 = new L.geoJson(null, {
    attribution: "",
    pane: "pane_tecnologia2018",
    pointToLayer: (feature, latlng) => {
        let autoMarker = L.BeautifyIcon.icon({
            icon: "desechos",
            iconSize: [0, 0],
            iconAnchor: [7, 10],
            iconShape: "",
            popupAnchor: [0, 0],
            innerIconStyle: "font-size: 8px;",
            html: "<span class=\"fa-stack\"><i class=\"fas fa-desechos fa-stack-1x\" style=\"color:rgba(199,0,57,0.3);font-size: 8px;\"></i></span>",
            borderWidth: 0,
            borderColor: "transparent",
            backgroundColor: "transparent"
        });
        return new L.Marker(latlng, {
            icon: autoMarker
        });
    }
});

const style_munis_contexto = () => {
    return {
        pane: "pane_munis_contexto",
        opacity: 1,
        color: "rgba(110,110,110,0.4)",
        lineCap: "butt",
        lineJoin: "miter",
        weight: 1.0,
        fill: true,
        fillOpacity: 1,
        fillColor: "rgba(255,255,212,0.4)"
    }
}
let layer_munis_contexto = new L.geoJson(null, {
    attribution: "",
    pane: "pane_munis_contexto",
    style: style_munis_contexto
});

const style_limZMs = () => {
    return {
        pane: "pane_limZMs",
        opacity: 1,
        color: "rgba(168,0,0,1)",
        dashArray: "",
        lineCap: "butt",
        lineJoin: "miter",
        weight: 1.0,
        fillOpacity: 0
    }
}

let layer_limZMs = new L.geoJson(null, {
    attribution: "",
    pane: "pane_limZMs",
    style: style_limZMs
});

const style_ZMs = () => {
    return {
        pane: "pane_ZMs",
        opacity: 1,
        color: "rgba(110,110,100,1)",
        dashArray: "",
        lineCap: "butt",
        lineJoin: "miter",
        weight: 1.0,
        fillOpacity: 1,
        fillColor: "rgba(255,170,0,1)"
    }
}

let layer_ZMs = new L.geoJson(null, {
    attribution: "",
    pane: "pane_ZMs",
    style: style_ZMs
});

const style_conurbaciones_rurbana = () => {
    return {
        pane: "pane_conurbaciones",
        opacity: 1,
        color: "rgba(35,35,35,0.1)",
        dashArray: "",
        lineCap: "butt",
        lineJoin: "miter",
        weight: 1.0,
        fillOpacity: 1,
        fillColor: "rgba(255,0,0,0.1)"
    }
}

let layer_conurbaciones_rurbana = new L.geoJson(null, {
    attribution: "",
    pane: "pane_conurbaciones",
    style: style_conurbaciones_rurbana
});

const style_agebs2005 = () => {
    return {
        opacity: .9,
        color: "#d6c996",
        lineCap: "butt",
        lineJoin: "miter",
        weight: 0.5, //1.0,
        fill: true,
        fillOpacity: 0.9, //1,
        fillColor: "#ffffb3"
    }
}

let layer_agebs2005 = new L.geoJson(null, {
    attribution: "",
    style: style_agebs2005,
    interactive: false
});

const style_agebs2010 = () => {
    return {
        opacity: 1,
        color: "#ffaa00",
        lineCap: "butt",
        lineJoin: "miter",
        weight: 0.5, //1.0,
        fill: true,
        fillOpacity: 1,
        fillColor: "#ffaa00"
    }
}

let layer_agebs2010 = new L.geoJson(null, {
    attribution: "",
    style: style_agebs2010,
    interactive: false
});

const style_agebs2015 = () => {
    return {
        opacity: 1,
        color: "#730000",
        lineCap: "butt",
        lineJoin: "miter",
        weight: 1.0,
        fill: true,
        fillOpacity: 1,
        fillColor: "#730000"
    }
}

let layer_agebs2015 = new L.geoJson(null, {
    attribution: "",
    style: style_agebs2015,
    interactive: false
});

let crecimiento_urbano = new L.layerGroup([layer_agebs2005, layer_agebs2010, layer_agebs2015], {
    pane: "pane_agebs"
});

const style_centros = feature => {
    return {
        pane: "pane_centros",
        opacity: 1,
        color: "rgba(110,100,110,0.7)",
        lineCap: "butt",
        lineJoin: "miter",
        weight: 0.5, //1.0,
        fill: true,
        fillOpacity: .4,
        fillColor: getCentrosColor(feature.properties["OCUPADOS"]),
        fillPattern: "stripes"
    }
}

let layer_centros = new L.geoJson(null, {
    attribution: "",
    pane: "pane_centros",
    style: style_centros,
    interactive: false
});

const style_hacia = feature => {
    return {
        pane: "pane_hacia",
        opacity: 1,
        color: "rgba(110,110,110,0.7)",
        lineCap: "butt",
        lineJoin: "miter",
        weight: 0.5, //1.0,
        fill: true,
        fillOpacity: 0.5,
        fillColor: getHaciaColor(feature.properties["PERSONAS"])
    }
}

let layer_hacia = new L.geoJson(null, {
    attribution: "",
    pane: "pane_hacia",
    style: style_hacia
});

const style_desde = feature => {
    return {
        pane: "pane_desde",
        opacity: 1,
        color: "rgba(110,110,110,0.7)",
        lineCap: "butt",
        lineJoin: "miter",
        weight: 0.5, //1.0,
        fill: true,
        fillOpacity: 0.5,
        fillColor: getDesdeColor(feature.properties["PERSONAS"])
    }
}

let layer_desde = new L.geoJson(null, {
    attribution: "",
    pane: "pane_desde",
    style: style_desde
});

const style_centrosPOIC = feature => {
    return {
        pane: "pane_centrosPOIC",
        opacity: 1,
        color: "rgba(110,100,110,0.7)",
        lineCap: "butt",
        lineJoin: "miter",
        weight: 0.5, //1.0,
        fill: true,
        fillOpacity: .4,
        fillColor: getCentrosColor(feature.properties["POIC"])
    }
}

let layer_centrosPOIC = new L.geoJson(null, {
    attribution: "",
    pane: "pane_centrosPOIC",
    style: style_centrosPOIC
});

const style_haciaPOIC = feature => {
    return {
        pane: "pane_haciaPOIC",
        opacity: 1,
        color: "rgba(110,110,110,0.7)",
        lineCap: "butt",
        lineJoin: "miter",
        weight: 0.5, //1.0,
        fill: true,
        fillOpacity: 0.5,
        fillColor: getHaciaPOICColor(feature.properties["PERSONAS"])
    }
}

let layer_haciaPOIC = new L.geoJson(null, {
    attribution: "",
    pane: "pane_haciaPOIC",
    style: style_haciaPOIC
});

const style_desdePOIC = feature => {
    return {
        pane: "pane_desdePOIC",
        opacity: 1,
        color: "rgba(110,110,110,0.7)",
        lineCap: "butt",
        lineJoin: "miter",
        weight: 0.5, //1.0,
        fill: true,
        fillOpacity: 0.5,
        fillColor: getDesdePOICColor(feature.properties["PERSONAS"])
    }
}

let layer_desdePOIC = new L.geoJson(null, {
    attribution: "",
    pane: "pane_desdePOIC",
    style: style_desdePOIC
});

let canvasPointRenderer = L.canvas({ pane: "pane_flujos" });

const createFlowLayer = (geojson, type, addOnCreate) => {
    return new Promise(resolve => {
        let canvasBezierStyle = [],
            animatedCanvasBezierStyle = [];

        // define styles based on properties and values
        intervals[type].values.forEach((val, idx) => {
            canvasBezierStyle.push({
                classMinValue: idx == 0 ? 0 : intervals[type].values[idx - 1] + 1,
                classMaxValue: val,
                symbol: {
                    strokeStyle: intervals[type].colors[idx],
                    lineWidth: intervals[type].thickness[idx],
                    lineCap: "round",
                    shadowColor: intervals[type].colors[idx],
                    shadowBlur: 1.5
                }
            });

            animatedCanvasBezierStyle.push({
                classMinValue: idx == 0 ? 0 : intervals[type].values[idx - 1] + 1,
                classMaxValue: val,
                symbol: {
                    strokeStyle: intervals[type].colors[idx],
                    lineWidth: intervals[type].animThickness[idx],
                    lineDashOffsetSize: 4,
                    lineCap: "round",
                    shadowColor: intervals[type].colors[idx],
                    shadowBlur: 1.5
                }
            });
        });

        $.getJSON(geojson, data => {
            // build data array from geojson to be used in amchart
            let source = data.features;
            let newData = [];
            source.forEach(o => newData.push({ "xVar": o.properties.muni_origen, "yVar": o.properties.muni_destino, "flowCount": o.properties.viajes }));

            let origins = [],
                destinations = [];

            newData.forEach(data => {
                origins.push(data.xVar); // all origins
                destinations.push(data.yVar) // all destinations
            });
            origins = origins.filter((v, i, a) => a.indexOf(v) === i); // get unique ones
            destinations = destinations.filter((v, i, a) => a.indexOf(v) === i); // get unique ones

            // add missing combinations with 0 trips
            origins.forEach((o) => {
                destinations.forEach((d) => {
                    if (!newData.some(data => data.xVar === o && data.yVar === d)) {
                        newData.push({ "xVar": o, "yVar": d, "flowCount": 0 });
                    }
                });
            });

            // sort array by origins and then by destinations
            newData.sort((el1, el2) => {
                let compared = compare(el1, el2, "xVar");
                return compared == 0 ? compare(el1, el2, "yVar") : compared;
            });

            odData[type] = newData; // push to chart data object to reuse
            // TODO: add heatColors to each data array

            let flowMapLayer = L.canvasFlowmapLayer(data, {
                // Define origins and destination from json values
                originAndDestinationFieldIds: {
                    originUniqueIdField: "id_origen",
                    originGeometry: {
                        x: "xo",
                        y: "yo"
                    },
                    destinationUniqueIdField: "id_destino",
                    destinationGeometry: {
                        x: "xd",
                        y: "yd"
                    }
                },
                // Line styles
                canvasBezierStyle: {
                    type: "classBreaks",
                    field: "viajes",
                    classBreakInfos: canvasBezierStyle
                },
                // Animated line styles
                animatedCanvasBezierStyle: {
                    type: "classBreaks",
                    field: "viajes",
                    classBreakInfos: animatedCanvasBezierStyle
                },

                // dot styles
                style: geoJsonFeature => {
                    if (geoJsonFeature.properties.isOrigin) {
                        return {
                            renderer: canvasPointRenderer,
                            radius: 5,
                            weight: 1,
                            color: "rgb(195, 255, 62)",
                            fillColor: "rgba(195, 255, 62, 0.6)",
                            fillOpacity: 0.6
                        };
                    } else {
                        return {
                            renderer: canvasPointRenderer,
                            radius: 2.5,
                            weight: 0.25,
                            color: "rgb(17, 142, 170)",
                            fillColor: "rgb(17, 142, 170)",
                            fillOpacity: 0.7
                        };
                    }
                },
                // some custom options
                pathDisplayMode: "all",
                animationStarted: true,
                //animationEasingFamily: "Cubic",
                //animationEasingType: "In",
                animationEasingFamily: "Linear",
                animationEasingType: "None",
                animationDuration: 2000,
                customLayerId: type,
                pane: "pane_flujos"
            }).bindTooltip(layer => { // what to display on hover
                let coords = layer.getLatLng();
                let label = od.features.filter(f => f.properties.lng == coords.lng && f.properties.lat == coords.lat);
                return label[0].properties.nombre;
            });

            // if layer is to be added on creation, add click funcionality and populate chart
            if (addOnCreate) {
                flowMapLayer.addTo(map).on("click", odClick);
                let odChart = am4core.registry.baseSprites.find(c => c.htmlContainer.id === "topLeftChart");
                odChart.data = newData;

                let chordChart = am4core.registry.baseSprites.find(c => c.htmlContainer.id === "bottomLeftChart");
                chordChart.data = newData;
                chordChart.data = chordChart.data.filter( e => e.flowCount > 0 );
            }
            flowMapsArray.push(flowMapLayer);
            resolve(flowMapsArray);
        });
    });
}

const makeBaseMap = () => {
    //return new Promise( resolve=> {
    createPane("pane_munis", 402);
    createPane("pane_munis_contexto", 402);
    createPane("pane_ZMs", 403);
    createPane("pane_limZMs", 404);
    createPane("pane_conurbaciones", 404);
    createPane("pane_locs", 405);
    createPane("pane_cuencas", 406);
    createPane("pane_buffer", 407);
    createPane("pane_manzanas", 408);
    createPane("pane_estatal", 409);
    createPane("pane_carreteras", 410);
    createPane("pane_auto2010", 411);
    createPane("pane_auto2014", 411);
    createPane("pane_auto2018", 411);
    createPane("pane_tecnologia2010", 412);
    createPane("pane_tecnologia2014", 412);
    createPane("pane_tecnologia2018", 412);
    createPane("pane_centros", 420);
    createPane("pane_desde", 414);
    createPane("pane_hacia", 415);
    createPane("pane_centrosPOIC", 420);
    createPane("pane_desdePOIC", 414);
    createPane("pane_haciaPOIC", 415);
    createPane("pane_agebs", 421);
    createPane("pane_flujos", 422);

    zip2Lyr("../centropais/data/munis_contexto.zip", munis_contexto, layer_munis_contexto);
    layerControl.addOverlay(layer_munis_contexto, "&nbsp;<svg height=\"15\" width=\"15\"><path d=\"M0 0 L15 0 L15 10 L0 10 Z \" x=\"5\" y=\"5\" fill=\"rgba(255,255,212,0.4)\" stroke=\"rgba(110,100,100,0.4)\" stroke-dasharray=\" \"></rect></svg>&nbsp; Municipios para dar contexto a la región");
    zip2Lyr("../centropais/data/munis_conurbaciones_rurbana.zip", conurbaciones, layer_conurbaciones_rurbana);
    layerControl.addOverlay(layer_conurbaciones_rurbana, "&nbsp;<svg height=\"15\" width=\"15\"><path d=\"M0 0 L15 0 L15 10 L0 10 Z \" x=\"5\" y=\"5\" fill=\"rgba(255,0,0,0.1)\" stroke=\"rgba(35,35,35,0.4)\" stroke-dasharray=\" \"></rect></svg>&nbsp; Municipios que albergan las conurbaciones de la región");
    layerControl.addOverlay(layer_RedNacionalCaminos, "Red Nacional de Caminos <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<img src=\"http://gaia.inegi.org.mx/NLB/tunnel/wms/mdm6wms?map=/opt/map/mdm60/mdm61leyendaprueba.map&Request=GetLegendGraphic&format=image/png&Version=1.1.1&Service=WMS&LAYER=c200\" alt=\"Red Nacional de Caminos\"/>");
    zip2Lyr("../centropais/data/agebs_urbanos2005.zip", agebs2005, layer_agebs2005);
    zip2Lyr("../centropais/data/expansion_agebs2010.zip", agebs2010, layer_agebs2010);
    zip2Lyr("../centropais/data/expansion_agebs2015.zip", agebs2015, layer_agebs2015);
    layerControl.addOverlay(crecimiento_urbano, "Crecimiento urbano 2005-2015<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<svg height=\"15\" width=\"15\"><path d=\"M0 0 L15 0 L15 10 L0 10 Z \" x=\"5\" y=\"5\" fill=\"#730000\"   stroke=\"#730000\" stroke-dasharray=\" \"></rect></svg> Expansión del área de los AGEB's urbanos 2015<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<svg height=\"15\" width=\"15\"><path d=\"M0 0 L15 0 L15 10 L0 10 Z \" x=\"5\" y=\"5\" fill=\"#ffaa00\" stroke = \"#ffaa00\" stroke-dasharray=\" \"></rect></svg> Expansión del área de los AGEB's urbanos 2010<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<svg height = \"15\" width=\"15\"><path d=\"M0 0 L15 0 L15 10 L0 10 Z \" x=\"5\" y=\"5\" fill=\"#ffffd3\" stroke = \"#d6c996\" stroke-dasharray=\" \"></rect></svg> Área ocupada por los AGEBS's urbanos en 2005");
    crecimiento_urbano.addTo(map);
    zip2Lyr("../centropais/data/industria_automotriz_2010.zip", auto2010, layer_auto2010);
    layerControl.addOverlay(layer_auto2010, "&nbsp; <i class=\"fa fa-desechos\" style=\"color:#00799f;margin-top:3px;margin-left:0px;font-size: 8px;opacity:0.75;\"></i>&nbsp;&nbsp;Unidades económicas en la industria automotriz 2010 ");
    zip2Lyr("../centropais/data/industria_automotriz_2014.zip", auto2014, layer_auto2014);
    layerControl.addOverlay(layer_auto2014, "&nbsp; <i class=\"fa fa-desechos\" style=\"color:#3c4baf;margin-top:3px;margin-left:0px;font-size: 8px;opacity:0.75;\"></i>&nbsp;&nbsp;Unidades económicas en la industria automotriz 2014 ");
    zip2Lyr("../centropais/data/industria_automotriz_2018.zip", auto2018, layer_auto2018);
    layerControl.addOverlay(layer_auto2018, "&nbsp; <i class=\"fa fa-desechos\" style=\"color:#2335f9;margin-top:3px;margin-left:0px;font-size: 8px;opacity:0.75;\"></i>&nbsp;&nbsp;Unidades económicas en la industria automotriz 2018 ");
    zip2Lyr("../centropais/data/tecnologia_media_alta_2010.zip", tecnologia2010, layer_tecnologia2010);
    layerControl.addOverlay(layer_tecnologia2010, "&nbsp; <i class=\"fa fa-desechos\" style=\"color:#581845;margin-top:3px;margin-left:0px;font-size: 8px;opacity:0.75;\"></i>&nbsp;&nbsp;Unidades económicas en la industria de tecnología media-alta 2010 ");
    zip2Lyr("../centropais/data/tecnologia_media_alta_2014.zip", tecnologia2014, layer_tecnologia2014);
    layerControl.addOverlay(layer_tecnologia2014, "&nbsp; <i class=\"fa fa-desechos\" style=\"color:#900c3f;margin-top:3px;margin-left:0px;font-size: 8px;opacity:0.75;\"></i>&nbsp;&nbsp;Unidades económicas en la industria de tecnología media-alta 2014 ");
    zip2Lyr("../centropais/data/tecnologia_media_alta_2018.zip", tecnologia2018, layer_tecnologia2018);
    layerControl.addOverlay(layer_tecnologia2018, "&nbsp; <i class=\"fa fa-desechos\" style=\"color:#c70039;margin-top:3px;margin-left:0px;font-size: 8px;opacity:0.75;\"></i>&nbsp;&nbsp;Unidades económicas en la industria de tecnología media-alta 2018 ");
    zip2Lyr("../centropais/data/Centros_de_mercado_de_ocupados.zip", centros, layer_centros);
    layerControl.addOverlay(layer_centros, "Centros de mercado <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<svg height=\"15\" width=\"15\"><path d=\"M0 0 L15 0 L15 10 L0 10 Z \" x=\"5\" y=\"5\" fill=\"#d1ff73\"   stroke=\"#aaff00\" stroke-dasharray=\" \"></rect></svg> Terciario<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<svg height=\"15\" width=\"15\"><path d=\"M0 0 L15 0 L15 10 L0 10 Z \" x=\"5\" y=\"5\" fill=\"#8e1973\" stroke = \"#a80084\" stroke-dasharray=\" \"></rect></svg> Secundario<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<svg height = \"15\" width=\"15\"><path d=\"M0 0 L15 0 L15 10 L0 10 Z \" x=\"5\" y=\"5\" fill=\"#ff5500\" stroke = \"#e60000\" stroke-dasharray=\" \"></rect></svg> Primario");
    layer_centros.addTo(map);
    zip2Lyr("../centropais/data/hacia.zip", hacia, layer_hacia);
    layerControl.addOverlay(layer_hacia, "Número de ocupados <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<svg height=\"15\" width=\"15\"><path d=\"M0 0 L15 0 L15 10 L0 10 Z \" x=\"5\" y=\"5\" fill=\"#e3fcd9\"   stroke=\"#6e6e6e\" stroke-dasharray=\" \"></rect></svg> 0 - 1000<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<svg height=\"15\" width=\"15\"><path d=\"M0 0 L15 0 L15 10 L0 10 Z \" x=\"5\" y=\"5\" fill=\"#b4d787\" stroke = \"#6e6e6e\" stroke-dasharray=\" \"></rect></svg> 1001 - 2000<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<svg height = \"15\" width=\"15\"><path d=\"M0 0 L15 0 L15 10 L0 10 Z \" x=\"5\" y=\"5\" fill=\"#4bc44f\" stroke = \"#6e6e6e\" stroke-dasharray=\" \"></rect></svg> 2001 - 6000 <br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<svg height = \"15\" width=\"15\"><path d=\"M0 0 L15 0 L15 10 L0 10 Z \" x=\"5\" y=\"5\" fill=\"#218542\" stroke = \"#6e6e6e\" stroke-dasharray=\" \"></rect></svg> 6001 - 32000 <br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<svg height = \"15\" width=\"15\"><path d=\"M0 0 L15 0 L15 10 L0 10 Z \" x=\"5\" y=\"5\" fill=\"#00451c\" stroke = \"#6e6e6e\" stroke-dasharray=\" \"></rect></svg> 32001 - 53300");
    zip2Lyr("../centropais/data/desde.zip", desde, layer_desde);
    layerControl.addOverlay(layer_desde, "Número de ocupados <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<svg height=\"15\" width=\"15\"><path d=\"M0 0 L15 0 L15 10 L0 10 Z \" x=\"5\" y=\"5\" fill=\"#ffebbf\"   stroke=\"#6e6e6e\" stroke-dasharray=\" \"></rect></svg> Menos de 1000<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<svg height=\"15\" width=\"15\"><path d=\"M0 0 L15 0 L15 10 L0 10 Z \" x=\"5\" y=\"5\" fill=\"#ffaa00\" stroke = \"#6e6e6e\" stroke-dasharray=\" \"></rect></svg> 1001 - 2000<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<svg height = \"15\" width=\"15\"><path d=\"M0 0 L15 0 L15 10 L0 10 Z \" x=\"5\" y=\"5\" fill=\"#fc7f44\" stroke = \"#6e6e6e\" stroke-dasharray=\" \"></rect></svg> 2001- 6000 <br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<svg height = \"15\" width=\"15\"><path d=\"M0 0 L15 0 L15 10 L0 10 Z \" x=\"5\" y=\"5\" fill=\"#b30000\" stroke = \"#6e6e6e\" stroke-dasharray=\" \"></rect></svg> 6001 - 7200");
    zip2Lyr("../centropais/data/centros_de_mercado_POIC.zip", centrosPOIC, layer_centrosPOIC);
    layerControl.addOverlay(layer_centrosPOIC, "Centros de mercado POIC <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<svg height=\"15\" width=\"15\"><path d=\"M0 0 L15 0 L15 10 L0 10 Z \" x=\"5\" y=\"5\" fill=\"#d1ff73\"   stroke=\"#aaff00\" stroke-dasharray=\" \"></rect></svg> Terciario<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<svg height=\"15\" width=\"15\"><path d=\"M0 0 L15 0 L15 10 L0 10 Z \" x=\"5\" y=\"5\" fill=\"#8e1973\" stroke = \"#a80084\" stroke-dasharray=\" \"></rect></svg> Secundario<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<svg height = \"15\" width=\"15\"><path d=\"M0 0 L15 0 L15 10 L0 10 Z \" x=\"5\" y=\"5\" fill=\"#ff5500\" stroke = \"#e60000\" stroke-dasharray=\" \"></rect></svg> Primario");
    zip2Lyr("../centropais/data/hacia_POIC.zip", haciaPOIC, layer_haciaPOIC);
    layerControl.addOverlay(layer_haciaPOIC, "Número de viajes <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<svg height=\"15\" width=\"15\"><path d=\"M0 0 L15 0 L15 10 L0 10 Z \" x=\"5\" y=\"5\" fill=\"#e3fcd9\"   stroke=\"#6e6e6e\" stroke-dasharray=\" \"></rect></svg> Menos de 500<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<svg height=\"15\" width=\"15\"><path d=\"M0 0 L15 0 L15 10 L0 10 Z \" x=\"5\" y=\"5\" fill=\"#b4d787\" stroke = \"#6e6e6e\" stroke-dasharray=\" \"></rect></svg> 501 - 1000<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<svg height = \"15\" width=\"15\"><path d=\"M0 0 L15 0 L15 10 L0 10 Z \" x=\"5\" y=\"5\" fill=\"#4bc44f\" stroke = \"#6e6e6e\" stroke-dasharray=\" \"></rect></svg> 1001 - 2000 <br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<svg height = \"15\" width=\"15\"><path d=\"M0 0 L15 0 L15 10 L0 10 Z \" x=\"5\" y=\"5\" fill=\"#218542\" stroke = \"#6e6e6e\" stroke-dasharray=\" \"></rect></svg> 2001 - 4000 <br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<svg height = \"15\" width=\"15\"><path d=\"M0 0 L15 0 L15 10 L0 10 Z \" x=\"5\" y=\"5\" fill=\"#00451c\" stroke = \"#6e6e6e\" stroke-dasharray=\" \"></rect></svg> 4001 - 10612");
    zip2Lyr("../centropais/data/desde_POIC.zip", desdePOIC, layer_desdePOIC);
    layerControl.addOverlay(layer_desdePOIC, "Número de viajes <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<svg height=\"15\" width=\"15\"><path d=\"M0 0 L15 0 L15 10 L0 10 Z \" x=\"5\" y=\"5\" fill=\"#ffebbf\"   stroke=\"#6e6e6e\" stroke-dasharray=\" \"></rect></svg> Menos de 500<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<svg height=\"15\" width=\"15\"><path d=\"M0 0 L15 0 L15 10 L0 10 Z \" x=\"5\" y=\"5\" fill=\"#ffaa00\" stroke = \"#6e6e6e\" stroke-dasharray=\" \"></rect></svg> 501 - 1000<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<svg height = \"15\" width=\"15\"><path d=\"M0 0 L15 0 L15 10 L0 10 Z \" x=\"5\" y=\"5\" fill=\"#fc7f44\" stroke = \"#6e6e6e\" stroke-dasharray=\" \"></rect></svg> 1001- 2000");
    zip2Lyr("../centropais/data/limite_ZMs.zip", lim_zms, layer_limZMs);
    layerControl.addOverlay(layer_limZMs, "&nbsp; <svg height=\"15\" width=\"15\"><path d=\"M0 0 L15 0 L15 10 L0 10 Z \" x=\"5\" y=\"5\" fill=\"none\" stroke=\"rgba(168,0,0,1)\" stroke-dasharray=\" \"></rect></svg> Límites de zonas metropolitanas");
    zip2Lyr("../centropais/data/ZMs.zip", zms, layer_ZMs);
    layerControl.addOverlay(layer_ZMs, "&nbsp; <svg height=\"15\" width=\"15\"><path d=\"M0 0 L15 0 L15 10 L0 10 Z \" x=\"5\" y=\"5\" fill=\"rgba(255,170,0,1)\" stroke=\"rgba(110,100,100,1)\" stroke-dasharray=\" \"></rect></svg>&nbsp;Zonas metropolitanas");
    layerControl.addOverlay(layer_locUrban, "<img src=\"http://gaia.inegi.org.mx/NLB/tunnel/wms/mdm6wms?map=/opt/map/mdm60/mdm61leyendaprueba.map&Request=GetLegendGraphic&format=image/png&Version=1.1.1&Service=WMS&LAYER=c102\" alt=\"Localidades urbanas\"/>");
    layerControl.addOverlay(layer_limiteMunicipal, "<img src=\"http://gaia.inegi.org.mx/NLB/tunnel/wms/wms61?version=1.3.0&service=WMS&request=GetLegendGraphic&sld_version=1.1.0&layer=c101&format=image/png&STYLE=default\" alt=\"Límite municipal\"/>");
    layerControl.addOverlay(layer_limiteEstatal, "Límite estatal <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<img src=\"http://gaia.inegi.org.mx/NLB/tunnel/wms/wms61?version=1.3.0&service=WMS&request=GetLegendGraphic&sld_version=1.1.0&layer=c100&format=image/png&STYLE=default\" alt=\"Límite Estatal\"/>");


    let resetControl = L.control({
        position: "topleft"
    });

    resetControl.onAdd = () => {
        let div = L.DomUtil.create("div", "leaflet-bar leaflet-control");
        div.innerHTML = "<button type=\"button\" class=\"btn btn-sm btn-light\" id=\"resetFlows\" title=\"Reiniciar fujos\"><i class=\"fa fa-sync-alt\"></i></button>";
        return div;
    };

    resetControl.addTo(map);

    $.getJSON("data/od.geojson", data => {
        od = data;
    });

    // create one flow, then another, then another...
    // and finally set reset control funcionality
    createFlowLayer("data/viajes_ocupados_desde.geojson", "ocupadosDesde", true)
        .then(() => createFlowLayer("data/viajes_ocupados_hacia.geojson", "ocupadosHacia"))
        .then(() => createFlowLayer("data/viajes_ocupados_entre.geojson", "ocupadosEntre"))
        .then(() => createFlowLayer("data/viajes_ocupados_POIC_desde.geojson", "poicDesde"))
        .then(() => createFlowLayer("data/viajes_ocupados_POIC_hacia.geojson", "poicHacia"))
        .then(() => createFlowLayer("data/viajes_ocupados_POIC_entre.geojson", "poicEntre"))
        .then(layers => {
            // reset to all flows displayed
            $("#resetFlows").on("click", () => {
                layers.forEach(layer => {
                    if (map.hasLayer(layer)) {
                        layer.originAndDestinationGeoJsonPoints.features.forEach( feature => {
                            if (feature.properties.isOrigin === true) {
                                feature.properties._isSelectedForPathDisplay = true;
                            } else {
                                feature.properties._isSelectedForPathDisplay = false;
                            }
                        });
                        layer._resetCanvas();
                        $("#odTableRow").addClass("align-self-center");
                        $("#odCard").show();
                        $("#tblViajes").hide();
                        $("#tblViajes tbody").html("");
                    }
                });
                // TODO: reset amchart
                //let amchart = am4core.registry.baseSprites.find(c => c.htmlContainer.id === "amchartdiv");
                //amchart.data = odData.ocupadosDesde;
            });
        });
}