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

/* global Promise, omnivore, JSZip, map, glmap, layerControl, updateCharts, baseUrl */
/* exported makeBaseMap, baseLayerPromises, drawnItems */

let baseLayerPromises = [],
    drawnItems;

// 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 getSchoolColor = s => {
    return s == "Básico" ? "#409400" :
        s == "Medio superior" ? "#df6400" :
        "#c0d1e5";
}

const getCommerceColor = s => {
    return s == "Comercio al por menor en supermercados" ? "#9e4244" :
        s == "Comercio al por menor en tiendas departamentales" ? "#fc464e" :
        "#c0d1e5";
}

const getPoblacionColor = s => {
    return s > 6000 ? "#6b0601" :
        s > 4000 ? "#9e4410" :
        s > 2500 ? "#d68522" :
        s > 1000 ? "#f7ba3e" :
        s > 0 ? "#fcdd5d" :
        "#ffffff";
}

const getDensidadColor = s => {
    return s > 16000 ? "#633096" :
        s > 11500 ? "#8c6fbd" :
        s > 7000 ? "#a6a2eb" :
        s > 2400 ? "#d2d3fa" :
        s > 0 ? "#f1f0fc" :
        "#ffffff";
}

const getCuencasColor = s => {
    return s == "Bajo Grijalva o Grijalva-Villahermosa" ? "rgba(255,255,190,0.3)" :
        s == "Medio Grijalva o Grijalva-Tuxtla Gutiérrez" ? "rgba(255,170,0,0.3)" :
        "rgba(168,56,0,0.3)";
}

let pistasaereas, autobuses, supermercados, bancos, agebsbypop, agebsbydens, escuelas, hospitales, hoteles, subcuencas, tuxtlaVH, zms;

//  *** WMS INEGI ***
// AEROPUERTOS
let layer_aeropuertos = new L.tileLayer.wms("http://gaia.inegi.org.mx/NLB/tunnel/wms/wms61?", {
    layers: "c201",
    format: "image/svg+xml",
    transparent: true,
    attribution: "INEGI 2019",
    minZoom: 9
});
// VIAS FERREAS
let layer_vferreas = new L.tileLayer.wms("http://gaia.inegi.org.mx/NLB/tunnel/wms/wms61?", {
    layers: "c202",
    format: "image/svg+xml",
    transparent: true,
    pane: "pane_vferreas",
    attribution: "INEGI 2019"
});
//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"
});
// NOMBRES DE CUERPOS DE AGUA
let layer_nombresWB = new L.tileLayer.wms("http://gaia.inegi.org.mx/NLB/tunnel/wms/wms61?", {
    layers: "t311",
    format: "image/svg+xml",
    transparent: true,
    attribution: "INEGI 2019",
    minZoom: 9,
    pane: "pane_wbnames"
});
//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"
});
//MANZANAS
let layer_manzanaswms = new L.tileLayer.wms("http://gaia.inegi.org.mx/NLB/tunnel/wms/wms61?", {
    layers: "c104",
    format: "image/svg+xml",
    transparent: true,
    pane: "pane_manzanas",
    attribution: "INEGI 2019",
    minZoom: 13,
    maxZoom: 18
});
//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_pistasaereas = new L.geoJson(null, {
    attribution: "",
    minZoom: 9,
    pointToLayer: (_feature, latlng) => {
        let avionMarker = L.BeautifyIcon.icon({
            icon: "plane",
            iconSize: [0, 0],
            iconAnchor: [7, 10],
            iconShape: "", 
            popupAnchor: [0, 0],
            innerIconStyle: "font-size: 15px;",
            html: "<span class=\"fa-stack\"><i class=\"fas fa-plane fa-stack-1x\" style=\"color:#fada5e;\"></i></span>",
            borderWidth: 0,
            borderColor: "transparent",
            backgroundColor: "transparent",
        });
        return new L.Marker(latlng, {
            icon: avionMarker
        });
    }
});

let aeropuertosypistasaereas = new L.layerGroup([layer_aeropuertos, layer_pistasaereas], {
    pane: "pane_aeropuertosypistas",
    minZoom: 9
});

let layer_autobuses = new L.geoJson(null, {
    attribution: "",
    pane: "pane_autobuses",
    pointToLayer: (_feature, latlng) => {
        let busMarker = L.BeautifyIcon.icon({
            icon: "bus1",
            iconSize: [0, 0],
            iconAnchor: [7, 10],
            iconShape: "",
            popupAnchor: [0, 0],
            innerIconStyle: "font-size: 8px;",
            html: "<span class=\"fa-stack\"><i class=\"fas fa-bus1 fa-stack-1x\" style=\"color:#fda50f;\"></i></span>",
            borderWidth: 0,
            borderColor: "transparent",
            backgroundColor: "transparent"
        });
        return new L.Marker(latlng, {
            icon: busMarker
        });
    }
});

let layer_supermercados = new L.geoJson(null, {
    attribution: "",
    pane: "pane_supermercados",
    pointToLayer: (feature, latlng) => {
        let shoppingMarker = L.BeautifyIcon.icon({
            icon: "shopping-cart",
            iconSize: [0, 0],
            iconAnchor: [7, 10],
            iconShape: "circle",
            popupAnchor: [0, 0],
            innerIconStyle: "font-size: 15px;",
            borderWidth: 0,
            borderColor: "transparent",
            backgroundColor: "transparent",
            textColor: getCommerceColor(feature.properties["nombre_act"])
        });
        return new L.Marker(latlng, {
            icon: shoppingMarker
        });
    }
});

let layer_bancos = new L.geoJson(null, {
    attribution: "",
    pane: "pane_bancos",
    pointToLayer: (_feature, latlng) => {
        let bancosMarker = 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:#05ac72;\"></i><i class =\"fas fa-dollar fa-stack-1x fa-inverse\"></i></span>",
            borderWidth: 0,
            borderColor: "transparent",
            backgroundColor: "transparent",
            textColor: "#C0C0C0"
        });
        return new L.Marker(latlng, {
            icon: bancosMarker
        });
    }
});

let layer_escuelas = new L.geoJson(null, {
    attribution: "",
    pane: "pane_escuelas",
    pointToLayer: (feature, latlng) => {
        let escuelaMarker = L.BeautifyIcon.icon({
            icon: "escuela",
            iconSize: [0, 0],
            iconAnchor: [7, 10],
            iconShape: "circle",
            popupAnchor: [0, 0],
            innerIconStyle: "font-size: 15px;",
            borderWidth: 0,
            borderColor: "transparent",
            backgroundColor: "transparent",
            textColor: getSchoolColor(feature.properties["Nivel"])
        });
        return new L.Marker(latlng, {
            icon: escuelaMarker
        });
    }
});

let layer_hospitales = new L.geoJson(null, {
    attribution: "",
    pane: "pane_hospitales",
    pointToLayer: (_feature, latlng) => {
        let hospitalMarker = L.BeautifyIcon.icon({
            icon: "desechos",
            iconSize: [0, 0],
            iconAnchor: [7, 10],
            iconShape: "circle",
            popupAnchor: [0, 0],
            innerIconStyle: "font-size: 13px;",
            html: "<span class=\"fa-stack\"><i class=\"fas fa-desechos fa-stack-1x\" style=\"color:#ff0000;\"></i><i class =\"fas fa-plus-circle fa-stack-1x fa-inverse\"></i></span>",
            borderWidth: 0,
            borderColor: "transparent",
            backgroundColor: "transparent",
            textColor: "#C0C0C0"
        });
        return new L.Marker(latlng, {
            icon: hospitalMarker
        });
    }
});

let layer_hoteles = new L.geoJson(null, {
    attribution: "",
    pane: "pane_hoteles",
    pointToLayer: (_feature, latlng) => {
        let hotelMarker = L.BeautifyIcon.icon({
            icon: "bed",
            iconSize: [0, 0],
            iconAnchor: [7, 10],
            iconShape: "circle",
            popupAnchor: [0, 0],
            innerIconStyle: "font-size: 12px;",
            borderWidth: 0,
            borderColor: "transparent",
            backgroundColor: "transparent",
            textColor: "#808080"
        });
        return new L.Marker(latlng, {
            icon: hotelMarker
        });
    }
});

const style_cuencas = feature => {
    return {
        pane: "pane_agebsbydens",
        opacity: 1,
        color: "rgba(168,0,0,0.3)",
        lineCap: "butt",
        lineJoin: "miter",
        weight: 1.0,
        fill: true,
        fillOpacity: 1,
        fillColor: getCuencasColor(feature.properties["Subregion"])
    }
}
let layer_cuencas = new L.geoJson(null, {
    attribution: "",
    pane: "pane_cuencas",
    style: style_cuencas
});

const style_limZMs = () => {
    return {
        pane: "pane_limZMs",
        opacity: 1,
        color: "rgba(101,43,0,0.6)",
        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 = feature => {
    switch (String(feature.properties["ZM_NOMBRE"])) {
    case "Tuxtla Gutiérrez":
        return {
            pane: "pane_ZMs",
            opacity: 1,
            color: "rgba(139,47,0,0.6)",
            dashArray: "",
            lineCap: "butt",
            lineJoin: "miter",
            weight: 1.0,
            fill: true,
            fillOpacity: 1,
            fillColor: "rgba(139,60,0,0.6)"
        }
    case "Villahermosa":
        return {
            pane: "pane_ZMs",
            opacity: 1,
            color: "rgba(139,47,0,0.6)",
            dashArray: "",
            lineCap: "butt",
            lineJoin: "miter",
            weight: 1.0,
            fill: true,
            fillOpacity: 1,
            fillColor: "rgba(207,152,62,0.6)"
        }
    }
}

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

const style_agebsbypop = feature => {
    return {
        pane: "pane_agebsbypop",
        opacity: .6,
        color: "#4d4d4d",
        lineCap: "butt",
        lineJoin: "miter",
        weight: 0.5, //1.0,
        fill: true,
        fillOpacity: 0.7, //1,
        fillColor: getPoblacionColor(feature.properties["POBTOT"])
    }
}

let layer_agebsbypop = new L.geoJson(null, {
    attribution: "",
    pane: "pane_agebsbypop",
    style: style_agebsbypop
});

const style_agebsbydens = feature => {
    return {
        pane: "pane_agebsbydens",
        opacity: .6,
        color: "#4d4d4d",
        lineCap: "butt",
        lineJoin: "miter",
        weight: 0.5, //1.0,
        fill: true,
        fillOpacity: 0.5, //1,
        fillColor: getDensidadColor(feature.properties["DENPOB_KM2"]) //"rgba(0,240,2,0.05)"
    }
}

let layer_agebsbydens = new L.geoJson(null, {
    attribution: "",
    pane: "pane_agebsbydens",
    style: style_agebsbydens
});

let layer_agricolapv_fake = new L.geoJson(null, {}),
    layer_agricolaoi_fake = new L.geoJson(null, {});

let layer_agricolapv = {
    id: "agricola_pv",
    source: {
        type: "vector",
        tiles: [`${baseUrl}/agricola_pv/mvt/{z}/{x}/{y}?geom_column=geom&columns=cultivo`],
        maxzoom: 19,
        minzoom: 6
    },
    "source-layer": "agricola_pv", // source has to match postgis table name
    type: "fill",
    paint: {
        "fill-opacity": 0,
        "fill-color": [
            "match", ["get", "cultivo"],
            "Sorgo grano", "#ff5500",
            "Frijol", "#8e1973",
            "#d1ff73"
        ],
        "fill-outline-color": [
            "match", ["get", "cultivo"],
            "Sorgo grano", "#e60000",
            "Frijol", "#a80084",
            "#aaff00"
        ]
    }
}

let layer_agricolaoi = {
    id: "agricola_oi",
    source: {
        type: "vector",
        tiles: [`${baseUrl}/agricola_oi/mvt/{z}/{x}/{y}?geom_column=geom&columns=cultivo`],
        maxzoom: 19,
        minzoom: 6
    },
    "source-layer": "agricola_oi", // source has to match postgis table name
    type: "fill",
    paint: {
        "fill-opacity": 0,
        "fill-color": [
            "match", ["get", "cultivo"],
            "Sorgo grano", "#ff5500",
            "Frijol", "#8e1973",
            "#d1ff73"
        ],
        "fill-outline-color": [
            "match", ["get", "cultivo"],
            "Sorgo grano", "#e60000",
            "Frijol", "#a80084",
            "#aaff00"
        ]
    }
}

let layer_retorno2 = L.imageOverlay(
        "data/inunda_002rt.png", [[18.8249, -94.4231], [15.0813, -91.5209]],
        {opacity: 0.5}
    ),
    layer_retorno5 = L.imageOverlay(
        "data/inunda_005rt.png", [[18.8249, -94.4231], [15.0813, -91.5209]],
        {opacity: 0.5}
    ),
    layer_retorno10 = L.imageOverlay(
        "data/inunda_010rt.png", [[18.8249, -94.4231], [15.0813, -91.5209]],
        {opacity: 0.5}
    ),
    layer_retorno50 = L.imageOverlay(
        "data/inunda_050rt.png", [[18.8249, -94.4231], [15.0813, -91.5209]],
        {opacity: 0.5}
    ),
    layer_retorno100 = L.imageOverlay(
        "data/inunda_100rt.png", [[18.8249, -94.4231], [15.0813, -91.5209]],
        {opacity: 0.5}
    );

const styleDrawnItems = () => {
    let currentId = 0;
    drawnItems.eachLayer(l => {
        l.feature.properties.id = currentId;
        l.feature.properties.color = d3.schemeCategory10[currentId];

        l.setStyle({
            fillColor: d3.schemeCategory10[currentId],
            opacity: 0.5,
            fillOpacity: 0.2,
            color: d3.schemeCategory10[currentId],
            weight: 4
        });
        currentId++;
    });
}

const toggleButtons = () => {
    let buttons = [];
    buttons.push(document.getElementsByClassName("leaflet-draw-draw-polyline")[0]);
    buttons.push(document.getElementsByClassName("leaflet-draw-draw-polygon")[0]);
    buttons.push(document.getElementsByClassName("leaflet-draw-draw-rectangle")[0]);

    buttons.forEach(b => {
        // disable buttons if there are 10 drawn items
        if (drawnItems.getLayers().length >= 10) {
            b.onClick = "preventEventDefault(); return false";
            b.classList.add("draw-control-disabled");
            // enable buttons if there are less than 10 drawn items
        } else if (drawnItems.getLayers().length < 10) {
            b.onClick = null;
            b.classList.remove("draw-control-disabled");
        }
    })
}

const makeBaseMap = () => {
    createPane("pane_munis", 402);
    createPane("pane_ZMs", 403);
    createPane("pane_limZMs", 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_wbnames", 421);
    createPane("pane_aeropuertosypistas", 411);
    createPane("pane_autobuses", 412);
    createPane("pane_escuelas", 413);
    createPane("pane_hoteles", 414);
    createPane("pane_hospitales", 415);
    createPane("pane_supermercados", 416);
    createPane("pane_bancos", 417);
    createPane("pane_vferreas", 418);
    createPane("pane_agricolaoi", 419);
    createPane("pane_agricolapv", 420);
    createPane("pane_agebsbypop", 421);
    createPane("pane_agebsbydens", 422);

    layerControl.addOverlay(layer_nombresWB, "Nombres cuerpos de agua");
    zip2Lyr("../grijalva/data/escuelas.zip", escuelas, layer_escuelas);
    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("../riesgos/data/Aeropuertos y pistas aereas.zip", pistasaereas, layer_pistasaereas);
    layerControl.addOverlay(aeropuertosypistasaereas, "Aeropuertos y pistas<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=c201&format=image/png&STYLE=default\" alt=\"Aeropuertos\"/></i> <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<i class=\"fa fa-plane\" style=\"color:#fada5e;margin-top:3px; margin-left:0px;font-size: 15px;\"></i> &nbsp;&nbsp; &nbsp;&nbsp;Pistas aéreas");
    zip2Lyr("../riesgos/data/Central de autobuses.zip", autobuses, layer_autobuses);
    layerControl.addOverlay(layer_autobuses, "<i class=\"fa fa-bus1\" style=\"color:#fda50f;margin-top:3px; margin-left:0px;font-size: 13px;\"></i> Central de autobuses");
    layerControl.addOverlay(layer_escuelas, "Escuelas con 50 personas ocupadas o más<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<i class=\"fa fa-escuela\" style=\"color:#409400;margin-top:3px; margin-left:0px;font-size: 13px;\"></i> Básico<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<i class=\"fa fa-escuela\" style=\"color:#df6400;margin-top:3px; margin-left:0px;font-size: 13px;\"></i> Medio superior<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<i class=\"fa fa-escuela\" style=\"color:#c0d1e5;margin-top:3px; margin-left:0px;font-size: 13px;\"></i> Otras escuelas");
    zip2Lyr("../grijalva/data/hospitales.zip", hospitales, layer_hospitales);
    layerControl.addOverlay(layer_hospitales, "<span class=\"fa fa-stack\" style=\"padding-top: 6px;\"><i class=\"fas fa-desechos fa-stack-1x\" style=\"color:#ff0000;\"></i><i class=\"fas fa-plus-circle fa-stack-1x fa-inverse\"></i></span>Hospitales con 50 personas ocupadas o más");
    zip2Lyr("../grijalva/data/hoteles.zip", hoteles, layer_hoteles);
    layerControl.addOverlay(layer_hoteles, "&nbsp; <i class=\"fas fa-bed style=\"color:#808080;\"></i> Hoteles principales");
    zip2Lyr("../riesgos/data/Supermercados y tiendas departamentales.zip", supermercados, layer_supermercados);
    layerControl.addOverlay(layer_supermercados, "Supermercados y tiendas departamentales<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<i class=\"fa fa-shopping-cart\" style=\"color:#9e4244 ;margin-top:3px; margin-left:0px;font-size: 13px;\"></i> Supermercados<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<i class=\"fa fa-shopping-cart\" style=\"color:#fc464e;margin-top:3px; margin-left:0px;font-size: 13px;\"></i> Tiendas Departamentales");
    zip2Lyr("../riesgos/data/Bancos.zip", bancos, layer_bancos);
    layerControl.addOverlay(layer_bancos, "<span class = \"fa fa-stack\" style=\"padding-top: 6px;\"><i class=\"fas fa-desechos fa-stack-1x\" style=\"color:#05ac72;\"></i><i class=\"fas fa-dollar fa-stack-1x fa-inverse\"></i></span>Bancos");
    layerControl.addOverlay(layer_vferreas, "<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=c202\" alt=\"Vías Férreas\"/>");

    // add agriculture tiles to map and add fake overlay to control their opacity
    glmap.getMapboxMap().addLayer(layer_agricolaoi);
    layerControl.addOverlay(layer_agricolaoi_fake, "Ciclo agrícola (Otoño-Invierno), SIAP-SADER 2017-2018 <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> Maíz grano<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> Frijol<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> Sorgo grano");
    glmap.getMapboxMap().addLayer(layer_agricolapv);
    layerControl.addOverlay(layer_agricolapv_fake, "Ciclo agrícola (Primavera-Verano), SIAP-SADER 2017 <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> Maíz grano<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> Frijol<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> Sorgo grano");

    layerControl.addOverlay(layer_retorno2, "Periodo de retorno a 2 años");
    layerControl.addOverlay(layer_retorno5, "Periodo de retorno a 5 años");
    layerControl.addOverlay(layer_retorno10, "Periodo de retorno a 10 años");
    layerControl.addOverlay(layer_retorno50, "Periodo de retorno a 50 años");
    layerControl.addOverlay(layer_retorno100, "Periodo de retorno a 100 años");

    zip2Lyr("../riesgos/data/poblacionAGEB.zip", agebsbydens, layer_agebsbydens);
    layerControl.addOverlay(layer_agebsbydens, "Densidad de población total por AGEB <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=\"#ffffff\"   stroke=\"rgba(0,0,0,0.6)\" stroke-dasharray=\" \"></rect></svg> Sin Población<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=\"#f1f0fc\" stroke = \"rgba(0,0,0,0.6)\" stroke-dasharray=\" \"></rect></svg> 1 - 2400 <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=\"#d2d3fa\" stroke = \"rgba(0,0,0,0.6)\" stroke-dasharray=\" \"></rect></svg> 2401 - 7000 <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=\"#a6a2eb\" stroke=\"rgba(0,0,0,0.6)\" stroke-dasharray=\" \"></rect></svg> 7001 - 11500 <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=\"#8c6fbd\" stroke=\"rgba(0,0,0,0.6)\" stroke-dasharray=\" \"></rect></svg> 11501 - 16000 <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=\"#633096\" stroke=\"rgba(0,0,0,0.6)\" stroke-dasharray=\" \"></rect></svg> 16001 - 67000");
    zip2Lyr("../riesgos/data/poblacionAGEB.zip", agebsbypop, layer_agebsbypop);
    layerControl.addOverlay(layer_agebsbypop, "Población total por AGEB <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=\"#ffffff\"   stroke=\"rgba(0,0,0,0.6)\" stroke-dasharray=\" \"></rect></svg> Sin Población<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=\"#fcdd5d\" stroke = \"rgba(0,0,0,0.6)\" 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=\"#f7ba3e\" stroke = \"rgba(0,0,0,0.6)\" stroke-dasharray=\" \"></rect></svg> 1001 - 2500 <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=\"#d68522\" stroke=\"rgba(0,0,0,0.6)\" stroke-dasharray=\" \"></rect></svg> 2501 - 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=\"#9e4410\" stroke=\"rgba(0,0,0,0.6)\" stroke-dasharray=\" \"></rect></svg> 4001 - 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=\"#6b0601\" stroke=\"rgba(0,0,0,0.6)\" stroke-dasharray=\" \"></rect></svg> 6001 - 18600");
    layerControl.addOverlay(layer_manzanaswms, "<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=c102m\" alt=\"Manzanas\"/>");
    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\"/>");
    zip2Lyr("../grijalva/data/limites_TG_V.zip", tuxtlaVH, 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(101,43,0,0.6)\" stroke-dasharray=\" \"></rect></svg> Límites de zonas metropolitanas");
    zip2Lyr("../grijalva/data/limitesZM.zip", zms, layer_ZMs);
    layerControl.addOverlay(layer_ZMs, "Zonas metropolitanas<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=\"rgba(139,60,0,0.8)\" stroke=\"rgba(139,47,0,0.6)\" stroke-dasharray=\" \"></rect></svg> Tuxtla Gutiérrez<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=\"rgba(207,152,62,0.8)\" stroke=\"rgba(139,47,0,0.6)\" stroke-dasharray=\" \"></rect></svg> Villahermosa");
    zip2Lyr("../grijalva/data/cuencas.zip", subcuencas, layer_cuencas);
    layerControl.addOverlay(layer_cuencas, "Cuenca y subcuencas del Grijalva, CONAGUA 2017<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=\"rgba(255,255,190,0.3)\" stroke=\"rgba(168, 0,00,0.3)\" stroke-dasharray=\" \"></rect></svg> Bajo Grijalva o Grijalva-Villahermosa<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=\"rgba(255,170,0,0.3)\" stroke=\"rgba(168,0,0,0.3)\" stroke-dasharray=\" \"></rect></svg>  Medio Grijalva o Grijalva-Tuxtla-Gutiérrez<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=\"rgba(168,56,0,0.3)\" stroke=\"rgba(168,0,0,0.3)\" stroke-dasharray=\" \"></rect></svg>  Alto Grijalva o Grijalva-La Concordia");
    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\"/>");

    // set agriculture tiles' opacity to 0 or 1 depending on the case
    map.on("overlayadd", event => {
        if (event.name.includes("Primavera-Verano")) {
            glmap.getMapboxMap().setPaintProperty("agricola_pv", "fill-opacity", 1);
        }
        if (event.name.includes("Otoño-Invierno")) {
            glmap.getMapboxMap().setPaintProperty("agricola_oi", "fill-opacity", 1);
        }
    }).on("overlayremove", event => {
        if (event.name.includes("Primavera-Verano")) {
            glmap.getMapboxMap().setPaintProperty("agricola_pv", "fill-opacity", 0);
        }
        if (event.name.includes("Otoño-Invierno")) {
            glmap.getMapboxMap().setPaintProperty("agricola_oi", "fill-opacity", 0);
        }
    });

    // show loader only first time PNG overlays are loaded
    layer_retorno2.once("add", () => $(".loader").css("display", "block"))
        .on("load", () => $(".loader").hide("fade", 750));
    layer_retorno5.once("add", () => $(".loader").css("display", "block"))
        .on("load", () => $(".loader").hide("fade", 750));
    layer_retorno10.once("add", () => $(".loader").css("display", "block"))
        .on("load", () => $(".loader").hide("fade", 750));
    layer_retorno50.once("add", () => $(".loader").css("display", "block"))
        .on("load", () => $(".loader").hide("fade", 750));
    layer_retorno100.once("add", () => $(".loader").css("display", "block"))
        .on("load", () => $(".loader").hide("fade", 750));

    // Localize Leaflet.Draw texts
    L.drawLocal = {
        draw: {
            toolbar: {
                actions: {
                    title: "Cancelar dibujo",
                    text: "Cancelar"
                },
                finish: {
                    title: "Terminar dibujo",
                    text: "Terminar"
                },
                undo: {
                    title: "Eliminar último punto dibujado",
                    text: "Eliminar último punto"
                },
                buttons: {
                    polyline: "Dibujar una polilínea",
                    polygon: "Dibujar un polígono",
                    rectangle: "Dibujar un rectángulo",
                    circle: "Dibujar un círculo",
                    marker: "Dibujar un marcador",
                    circlemarker: "Dibujar un marcador circular"
                }
            },
            handlers: {
                circle: {
                    tooltip: {
                        start: "Haz click y arrastra para dibujar un círculo"
                    },
                    radius: "Radio"
                },
                circlemarker: {
                    tooltip: {
                        start: "Haz click en el mapa para ubicar el marcador circular"
                    }
                },
                marker: {
                    tooltip: {
                        start: "Haz click en el mapa para ubicar el marcador"
                    }
                },
                polygon: {
                    error: "<strong>Error:</strong>",
                    tooltip: {
                        start: "Haz click para empezar a dibujar la figura",
                        cont: "Haz click para continuar dibujando la figura",
                        end: "Haz click en el primer punto para cerrar la figura"
                    }
                },
                polyline: {
                    error: "<strong>Error:</strong> las líneas no deben cruzarse",
                    tooltip: {
                        start: "Haz click para empezar a dibujar la línea",
                        cont: "Haz click para continuar dibujando la línea",
                        end: "Haz click en el último punto para terminar la línea"
                    }
                },
                rectangle: {
                    tooltip: {
                        start: "Haz click y arrastra para dibujar un rectángulo"
                    }
                },
                simpleshape: {
                    tooltip: {
                        end: "Suelta el ratón para terminar de dibujar"
                    }
                }
            }
        },
        edit: {
            toolbar: {
                actions: {
                    save: {
                        title: "Guardar los cambios",
                        text: "Guardar"
                    },
                    cancel: {
                        title: "Cancelar la edición, descarta todos los cambios",
                        text: "Cancelar"
                    },
                    clearAll: {
                        title: "Limpiar todas las capas",
                        text: "Limpiar todo"
                    }
                },
                buttons: {
                    edit: "Editar capas",
                    editDisabled: "No hay capas que editar",
                    remove: "Eliminar capas",
                    removeDisabled: "No hay capas que eliminar"
                }
            },
            handlers: {
                edit: {
                    tooltip: {
                        text: "Arrastra el marcador para editar la figura",
                        subtext: "Haz click en cancelar para deshacer los cambios"
                    }
                },
                remove: {
                    tooltip: {
                        text: "Haz click en una figura para eliminarla"
                    }
                }
            }
        }
    }
    // leaflet draw control
    drawnItems = L.featureGroup().addTo(map);

    let drawControl = new L.Control.Draw({
        draw: {
            polygon: {
                showArea: true,
                //allowIntersection: false, // Restricts shapes to simple polygons
                //drawError: {
                //color: "#f9a800",
                //message: "<strong>you can't draw that!" // Message that will show when intersect
                //},
                shapeOptions: {
                    color: "#42ffc3"
                }
            },
            // disable toolbar item by setting it to false
            polyline: {
                //allowIntersection:false,
                shapeOptions: {
                    color: "#42ffc3"
                }
            },
            rectangle: {
                shapeOptions: {
                    color: "#42ffc3"
                }
            },
            marker: false,
            circlemarker: false,
            circle: false // Turns off this drawing tool
        },
        edit: {
            featureGroup: drawnItems,
            //remove: false
        }
    });
    map.addControl(drawControl);

    // set z-index of panes so actions can be done on drawnItems when editing/deleting
    map.on(L.Draw.Event.CREATED, event => {
        $("#mexmap .leaflet-pane.leaflet-overlay-pane").css("z-index", "400");
        let layer = event.layer,
            feature = layer.feature = layer.feature || {}; // Initialize feature

        feature.type = feature.type || "Feature"; // Initialize feature.type
        feature.properties = feature.properties || {}; // Initialize feature.properties

        drawnItems.addLayer(layer); // whatever you want to do with the created layer

        // give each drawn item an id and color from an array
        styleDrawnItems();
        // disable buttons if there are 10 drawn items
        toggleButtons();

        // after drawing shape, update chart with data for polygons contained inside it
        updateCharts();
    });

    map.on(L.Draw.Event.DELETESTART, () => {
        // before deleting shape, bring pane up
        $("#mexmap .leaflet-pane.leaflet-overlay-pane").css("z-index", "451");
    });

    map.on(L.Draw.Event.DELETED, () => {
        // after deleting a drawn item, refresh the list of ids and colors
        styleDrawnItems();
        // enable buttons if there are less than 10 drawn items
        toggleButtons();

        // after deleting shape, send pane down
        $("#mexmap .leaflet-pane.leaflet-overlay-pane").css("z-index", "400");
        // and update chart with data:
        // if there are drawnItems, use them. If not, use original data
        updateCharts();
    });

    map.on(L.Draw.Event.EDITSTART, () => {
        $("#mexmap .leaflet-pane.leaflet-overlay-pane").css("z-index", "451");
        // before  editing shape, bring pane up
    });

    map.on(L.Draw.Event.EDITSTOP, () => {
        $("#mexmap .leaflet-pane.leaflet-overlay-pane").css("z-index", "400");
        // before  editing shape, bring pane up
    });

    map.on(L.Draw.Event.EDITED, () => {
        // before  editing shape, send pane down
        $("#mexmap .leaflet-pane.leaflet-overlay-pane").css("z-index", "400");
        // after editing shape, update chart with data for polygons contained inside it
        updateCharts();
    });
}