var pv = [],
    pvm = [],
    line_left = {},
    line_right = {},
    line_alternativa = {},
    line_left_old = {},
    line_right_old = {},
    line_alternativa_old = {},
    pos = [],
    pos_old = [],
    Debug = {},
    timer = {},
    caducity = {},
    first = true,
    curline = 0,
    e_idle = {},
    enable_osm = false,
    fn_idle = null,
    cantidadLineas = 0,
    cant_line = 0,
    sup_line = false,
    line_old = 0;

var mantener = false;
var lineaRecargar = 0;
var lineaS;
var cargate = 0;

//servidor de de la app para los ajax
var urlServer = 'http://gpsurbana.com/';

/////////////////////
//paradas crear /////
/////////////////////
var markersArray = [];

////////////////////////////
//limpiar paradas /////////
////////////////////////////
function clearOverlays() {
    if (markersArray.length != 0) {
        var seguir = true;
        for (var i = 0; seguir == (true); i++) {
            map.removeLayer(markersArray[i]);
            if (i == markersArray.length - 1) {
                seguir = false
            }
            ;
        }
    }
    markersArray = [];
};

////////////////////////////
/////recargar la linea
////////////////////////////
var timer = {
    kill: 6000,
    o: {},
    _do: function () {
        colectivos(lineaRecargar);
        //console.log('Linea a recargar: '+lineaRecargar);
    },
    start: function () {
        try {
            this.o = setInterval(this._do, this.kill);
        } catch (ex) {
        }
    },
    end: function () {
        try {
            clearInterval(this.o);
        } catch (ex) {
        }
    }
};

////////////////////////////
/////////Limpiar las lineas
////////////////////////////
__clear = {
    array: function (x) {
        jQuery.each(x, function (k, v) {
            try {
                map.removeLayer(v);
            } catch (ex) {
                console.log(['__clear.array', ex]);
            }
        });
    },
    item: function (x) {
        try {
            map.removeLayer(x);
        } catch (ex) {
            console.log(['__clear.item', ex]);
        }
    },
    layer: function () {
        //$("#mapa").show();
    }
};

///////////////////////////
/////////rellenar la linea
///////////////////////////
__fill = {
    array: function (obj, map) {
        jQuery.each(obj, function (k, v) {
            try {
                v.bindPopup('<div id="icon_' + k + '">' + v.options.title + '</div>');
                v.addTo(map);
            } catch (ex) {
                Debug.log(['__fill.array', ex]);
            }
        });
    },
    item: function (obj, map) {
        try {
            map.addLayer(obj);
        } catch (ex) {
            Debug.log(['__fill.item', ex]);
        }
    }
};

var paradaActiva = 0;
///////////////////////////////
//funcion para las paradas ///
///////////////////////////////
function activar_paradas() {

    //clearOverlays();

    if (markersArray.length == 0) {
        var item_sel = lineaS;
        var item_sel_sub = lineaS.substring(2);

        if ((item_sel != 'sug') && (item_sel != 'pv') && (item_sel != '0')) {
            paradaActiva = 1;

            $.ajax({
                type: 'POST',
                url: urlServer + "/ajax/ebus/load_paradas/" + item_sel_sub,
                data: "",
                success: function (msg) {
                    var e = eval(msg);
                    //console.log(e);

                    for (var i in e) {
                        var myIcon = L.icon(
                            {
                                iconUrl: urlServer + '/images/mapshade/icono_parada.png'
                                /*,
                                 iconRetinaUrl: 'my-icon@2x.png',
                                 iconSize: [38, 95],
                                 iconAnchor: [22, 94],
                                 popupAnchor: [-3, -76],
                                 shadowUrl: 'my-icon-shadow.png',
                                 shadowRetinaUrl: 'my-icon-shadow@2x.png',
                                 shadowSize: [68, 95],
                                 shadowAnchor: [22, 94]
                                 */
                            });

                        if ((e[i].lat) && (e[i].lon)) {
                            var m = L.marker([e[i].lat, e[i].lon], {icon: myIcon/*, title: e[i].nro + e[i].sent*/}).addTo(map);
                            markersArray.push(m);
                        }

                    }
                }
            })

            //si es doble linea
            if (line_old) {
                $.ajax({
                    type: 'POST',
                    url: urlServer + "/ajax/ebus/load_paradas/" + line_old.substring(2),
                    data: "",
                    success: function (msg) {
                        var e = eval(msg);
                        //console.log(e);

                        for (var i in e) {
                            var myIcon = L.icon(
                                {
                                    iconUrl: urlServer + '/images/mapshade/icono_parada.png'
                                    /*,
                                     iconRetinaUrl: 'my-icon@2x.png',
                                     iconSize: [38, 95],
                                     iconAnchor: [22, 94],
                                     popupAnchor: [-3, -76],
                                     shadowUrl: 'my-icon-shadow.png',
                                     shadowRetinaUrl: 'my-icon-shadow@2x.png',
                                     shadowSize: [68, 95],
                                     shadowAnchor: [22, 94]
                                     */
                                });

                            if ((e[i].lat) && (e[i].lon)) {
                                var m = L.marker([e[i].lat, e[i].lon], {icon: myIcon/*, title: e[i].nro + e[i].sent*/}).addTo(map);
                                markersArray.push(m);
                            }

                        }
                    }
                })
            } else {

                clearOverlays();
            }

        }
        ;

    }
    else {
        clearOverlays();
        paradaActiva = 0;
    }
}

////////////////////
//función ver linea
//////////////////
function colectivos(linea, parq) {
    //poner el nombre de la linea
    lineaNombre(linea);
    //la linea a recargar
    lineaRecargar = linea;
    __clear.array(pvm);

    /////////////////////
    //puesto de recarga
    ////////////////////
    switch (linea) {

        //puestos de recarga
        case 'pv':
            cargate = 0;
            $('#parquimetroOpciones').hide();
            __clear.array(pvm);
            __clear.item(line_right);
            __clear.item(line_left);
            __clear.array(pos);
            __clear.item(line_alternativa);

            __clear.array(pos_old);
            __clear.item(line_left_old);
            __clear.item(line_right_old);
            __clear.item(line_alternativa_old);

            clearOverlays();

            timer.end();
            $.ajax({
                type: 'POST',
                url: urlServer + "/ajax/ebus_dev/pv_serialize/",
                data: "",
                beforeSend: function () {
                    cargando();
                },

                success: function (msg) {
                    cargandoQuit();
                    //$('#cargas').hide();
                    var pv = eval('(' + msg + ')');
                    console.log(msg);

                    //console.log(pv);
                    var myIcon = L.icon({
                        iconUrl: 'css/icon/carga-puesto.png',
                        iconSize: [28, 28],
                        iconRetinaUrl: 'css/icon/carga-puesto.png'
                    });

                    pvm = [];


                    for (var i in pv) {
                        var tmp = L.marker([pv[i].lat, pv[i].lon], {
                            icon: myIcon,
                            title: pv[i].ad
                        }).addTo(map);
                        pvm.push(tmp);
                        tmp.bindPopup('<div id="pv_icon_' + pv[i].lat + '">' + pv[i].ad + '</div>');
                    }
                }
            });

            break;

        ///////////////////////////////////////////
        //////////parquimetros //////////////
        case 'prk':
            cargate = 0;
            //mostrar el boton de las opciones del parquimetro
            //$('#parquimetroOpciones').show();
            __clear.array(pvm);
            __clear.item(line_right);
            __clear.item(line_left);
            __clear.array(pos);
            __clear.item(line_alternativa);

            __clear.array(pos_old);
            __clear.item(line_left_old);
            __clear.item(line_right_old);
            __clear.item(line_alternativa_old);

            clearOverlays();

            timer.end();
            $.ajax({
                type: 'POST',
                //url: "http://www.gpssumo.com/ajax/ebus_dev/prk_serialize/",
                url: urlServer + "/movimientos_park/prk_serialize",
                data: "",
                beforeSend: function () {
                    cargando();
                },
                success: function (msg) {
                    cargandoQuit();

                    var pv = eval('(' + msg + ')');
                    console.log(pv);

                    //////////////////////
                    ///iconos de zonas////
                    //////////////////////
                    var myIconA = L.icon({
                        iconUrl: 'img/parq-icons/zona-a.png',
                        iconSize: [25, 25],
                        iconRetinaUrl: 'img/parq-icons/zona-a.png'
                    });

                    var myIconB = L.icon({
                        iconUrl: 'img/parq-icons/zona-b.png',
                        iconSize: [25, 25],
                        iconRetinaUrl: 'img/parq-icons/zona-b.png'
                    });

                    var myIconC = L.icon({
                        iconUrl: 'img/parq-icons/zona-c.png',
                        iconSize: [25, 25],
                        iconRetinaUrl: 'img/parq-icons/zona-c.png'
                    });


                    //////////////////////
                    ///iconos de zonas////
                    //////////////////////
                    var myIcon0 = L.icon({
                        iconUrl: 'img/parq-icons/dis-00.png',
                        iconSize: [25, 25],
                        iconRetinaUrl: 'img/parq-icons/dis-00.png'
                    });

                    var myIcon1 = L.icon({
                        iconUrl: 'img/parq-icons/dis-01.png',
                        iconSize: [25, 25],
                        iconRetinaUrl: 'img/parq-icons/dis-01.png'
                    });

                    var myIcon3 = L.icon({
                        iconUrl: 'img/parq-icons/dis-02.png',
                        iconSize: [25, 25],
                        iconRetinaUrl: 'img/parq-icons/dis-02.png'
                    });

                    var myIcon5 = L.icon({
                        iconUrl: 'img/parq-icons/dis-03.png',
                        iconSize: [25, 25],
                        iconRetinaUrl: 'img/parq-icons/dis-03.png'
                    });

                    var myIconError = L.icon({
                        iconUrl: 'img/parq-icons/zona-c.png',
                        iconSize: [25, 25],
                        iconRetinaUrl: 'css/icon/black/SVG/twitter.png'
                    });


                    pvm = [];

                    ////////////////////
                    //recorrer los datos
                    ////////////////////

                    for (var i in pv) {

                        if (parq == 'tarifa') {
                            ///////////////
                            //por tarifas
                            ///////////////
                            if (pv[i].zona == 'A') {
                                var iconFinal = myIconA;
                            }
                            if (pv[i].zona == 'B') {
                                var iconFinal = myIconB;
                            }
                            if (pv[i].zona == 'C') {
                                var iconFinal = myIconC;
                            }
                        }

                        if (parq == 'disponibilidad') {
                            /////////////////////
                            //por disponibilidad
                            /////////////////////
                            if (pv[i].disponibilidad == 0) {
                                var iconFinal = myIcon0;
                            }

                            if (pv[i].disponibilidad == 1) {
                                var iconFinal = myIcon1;
                            }
                            if (pv[i].disponibilidad > 1 && pv[i].disponibilidad < 5) {
                                var iconFinal = myIcon3;
                            }

                            if (pv[i].disponibilidad >= 5) {
                                var iconFinal = myIcon5;
                            }

                            if (pv[i].disponibilidad < 0) {
                                var iconFinal = myIconError;
                            }

                        }

                        var tmp = L.marker([pv[i].lat, pv[i].lon], {
                            icon: iconFinal,//cambiar aca
                            title: pv[i].ad
                        }).addTo(map);
                        pvm.push(tmp);
                        tmp.bindPopup('<div id="pv_icon_' + pv[i].lat + '">' + pv[i].ad + '</div>');
                    }
                }
            });

            break;

        //residuos
        case 'residuos':
            __clear.array(pvm);
            __clear.item(line_right);
            __clear.item(line_left);
            __clear.array(pos);
            __clear.item(line_alternativa);

            __clear.array(pos_old);
            __clear.item(line_left_old);
            __clear.item(line_right_old);
            __clear.item(line_alternativa_old);

            clearOverlays();

            timer.end();

            $.ajax({
                type: 'POST',
                url: "https://www.e-track.com/open/gobierno/app_ambiental",
                data: "",
                beforeSend: function () {
                    cargando();
                },
                success: function (msg) {
                    cargandoQuit();

                    var pvR = eval('(' + msg + ')');
                    console.log(pvR);

                    //////////////////////
                    ///iconos de zonas////
                    //////////////////////


                    pvm = [];

                    ////////////////////
                    //recorrer los datos
                    ////////////////////
                    var iconoURL;
                    for (var c in pvR) {

                        switch (pvR[c].sen) {
                            case 'N':
                                iconoURL = 'img/icons/residuos/ic_N.png';
                                break;

                            case 'S':
                                iconoURL = 'img/icons/residuos/ic_S.png';
                                break;

                            case 'E':
                                iconoURL = 'img/icons/residuos/ic_E.png';
                                break;

                            case 'O':
                                iconoURL = 'img/icons/residuos/ic_O.png';
                                break;

                            case 'NO':
                                iconoURL = 'img/icons/residuos/ic_NO.png';
                                break;

                            case 'SO':
                                iconoURL = 'img/icons/residuos/ic_SO.png';
                                break;

                            case 'NE':
                                iconoURL = 'img/icons/residuos/ic_NE.png';
                                break;

                            case 'SE':
                                iconoURL = 'img/icons/residuos/ic_SE.png';
                                break;


                        }


                        var icono = L.icon({
                            iconUrl: iconoURL,
                            iconSize: [30, 30],
                            iconRetinaUrl: iconoURL
                        });

                        var tmp = L.marker([pvR[c].lat, pvR[c].lon], {
                            icon: icono,//cambiar aca
                            title: pvR[c].pa
                        }).addTo(map);

                        pvm.push(tmp);
                        tmp.bindPopup('<div id="pv_icon_' + pvR[c].lat + '">' + pvR[c].pa + '</div>');
                    }
                }
            });

            break;

        //////////////////////////////////////
        ////////////lineas de colectivo//////
        //////////////////////////////////////
        default:
            //borrar paradas si es diferente
            if (lineaS != linea) {
                clearOverlays();
                cargate = 0;
            }

            lineaS = linea;
            $('#parquimetroOpciones').hide();
            ///////////////////////////////////
            /// linea multiple /////////////////
            ///////////////////////////////////
            var rl = 0;

            if (curline != linea) {
                rl = 1;
                line_old = curline;
                cant_line = cant_line + 1;
            }

            if (cant_line > 2) {
                console.log(['cant_line', cant_line]);
                cant_line = 1;
                //line_old = 0;
                /*sup_line = false;  Creo que acá debe ir esta linea, ademas de en el boton. Lo tenemos que probar.          */
                sup_line = false;

                __clear.array(pos);
                __clear.item(line_left);
                __clear.item(line_right);
                __clear.item(line_alternativa);

                __clear.array(pos_old);
                __clear.item(line_left_old);
                __clear.item(line_right_old);
                __clear.item(line_alternativa_old);
            }

            $.ajax(
                {
                    type: 'POST',
                    url: urlServer + "/ajax/ebus_dev/get_app/" + (+new Date()) + "/" + rl,
                    data: "r=" + linea + "&t=0",
                    beforeSend: function () {
                        cargando();
                        cargate = 1;
                    },
                    success: function (msg) {
                        cargandoQuit();
                        timer.end();
                        timer.start();

                        var e = eval('(' + msg + ')');
                        //console.log(msg);
                        //var e = eval(msg);

                        if (e == false) {
                            return false;
                        }

                        __clear.array(pos);
                        __clear.item(line_left);
                        __clear.item(line_right);
                        __clear.item(line_alternativa);

                        line_left = new L.Polyline(e[0][0], {color: '#FF0000', weight: 4, opacity: 0.5, smoothFactor: 1});
                        line_right = new L.Polyline(e[0][1], {color: '#0000FF', weight: 4, opacity: 0.5, smoothFactor: 1});

                        if (e[0].length > 2) {
                            line_alternativa = new L.Polyline(e[0][2], {color: '#28F014', weight: 4, opacity: 0.5, smoothFactor: 1});
                            __fill.item(line_alternativa, map);
                        }

                        pos = e[1];

                        __fill.item(line_left, map);
                        __fill.item(line_right, map);
                        __fill.array(pos, map);
                    }
                });
            /***********************************************************************************************************************/
            if ((sup_line) && (cant_line > 1) && (cant_line < 3)) {
                $.ajax(
                    {
                        type: 'POST',
                        url: urlServer + "/ajax/ebus_dev/get_app/" + (+new Date()) + "/" + rl,
                        data: "r=" + line_old + "&t=0",
                        success: function (msg) {

                            /*timer.end();
                             timer.start(); */

                            try {
                                var e = eval('(' + msg + ')');


                                //console.log(msg);

                                if (e == false) {
                                    return false;
                                }

                                __clear.array(pos_old);
                                __clear.item(line_left_old);
                                __clear.item(line_right_old);
                                __clear.item(line_alternativa_old);

                                //line_left_old     = new L.Polyline(e[0][0] , {color: '#FF0000',weight: 4,    opacity: 0.5, smoothFactor: 1});
                                //line_right_old     = new L.Polyline(e[0][1] , {color: '#0000FF',weight: 4,    opacity: 0.5, smoothFactor: 1});

                                line_left_old = new L.Polyline(e[0][0], {color: '#258209', weight: 4, opacity: 0.7, smoothFactor: 1});
                                line_right_old = new L.Polyline(e[0][1], {color: '#ff9000', weight: 4, opacity: 0.7, smoothFactor: 1});

                                if (e[0].length > 2) {
                                    line_alternativa_old = new L.Polyline(e[0][2], {color: '#28F014', weight: 4, opacity: 0.5, smoothFactor: 1});
                                    __fill.item(line_alternativa_old, map);
                                }

                                pos_old = e[1];

                                __fill.item(line_left_old, map);
                                __fill.item(line_right_old, map);
                                __fill.array(pos_old, map);
                            }
                            catch (ex) {
                                Debug.log(['default case success 2', ex]);
                            }
                        }
                    });
            }
            /***********************************************************************************************************************/
            curline = linea;
            ///////////////////////////////////
            ///linea multiples /////////////////
            ///////////////////////////////////
            break;
    }
}

function residuos() {
    __clear.array(pvm);
    __clear.item(line_right);
    __clear.item(line_left);
    __clear.array(pos);
    __clear.item(line_alternativa);

    __clear.array(pos_old);
    __clear.item(line_left_old);
    __clear.item(line_right_old);
    __clear.item(line_alternativa_old);

    clearOverlays();

    timer.end();

    $.ajax({
        type: 'POST',
        url: "https://www.e-track.com/open/gobierno/app_ambiental",
        data: "",
        beforeSend: function () {
            cargando();
        },
        success: function (msg) {
            cargandoQuit();

            var pvR = eval('(' + msg + ')');
            console.log(pvR);

            //////////////////////
            ///iconos de zonas////
            //////////////////////


            pvm = [];

            ////////////////////
            //recorrer los datos
            ////////////////////
            var iconoURL;
            for (var c in pvR) {

                switch (pvR[c].sen) {
                    case 'N':
                        iconoURL = 'img/icons/residuos/ic_N.png';
                        break;

                    case 'S':
                        iconoURL = 'img/icons/residuos/ic_S.png';
                        break;

                    case 'E':
                        iconoURL = 'img/icons/residuos/ic_E.png';
                        break;

                    case 'O':
                        iconoURL = 'img/icons/residuos/ic_O.png';
                        break;

                    case 'NO':
                        iconoURL = 'img/icons/residuos/ic_NO.png';
                        break;

                    case 'SO':
                        iconoURL = 'img/icons/residuos/ic_SO.png';
                        break;

                    case 'NE':
                        iconoURL = 'img/icons/residuos/ic_NE.png';
                        break;

                    case 'SE':
                        iconoURL = 'img/icons/residuos/ic_SE.png';
                        break;


                }


                var icono = L.icon({
                    iconUrl: iconoURL,
                    iconSize: [30, 30],
                    iconRetinaUrl: iconoURL
                });

                var tmp = L.marker([pvR[c].lat, pvR[c].lon], {
                    icon: icono,//cambiar aca
                    title: pvR[c].pa
                }).addTo(map);

                pvm.push(tmp);
                tmp.bindPopup('<div id="pv_icon_' + pvR[c].lat + '">' + pvR[c].pa + '</div>');
            }
        }
    });
}