﻿angular.module('dispatch', [])
    .directive('uppercase', function () {
        return {
            restrict: "A",
            require: "?ngModel",
            link: function (scope, element, attrs, ngModel) {
                ngModel.$parsers.push(function (input) { return input ? input.toUpperCase() : ""; });
                element.css("text-transform", "uppercase");
            }
        };
    })
    .controller('dispatchCtrl', ['$scope', '$http', 'growl', 'DispatchServics', '$interval', '$location', "driverService", "$sce", "ChatService", function ($scope, $http, growl, DispatchServics, $interval, $location, driverService, $sce, ChatService) {

        $scope.OpInfo = JSON.parse(localStorage.getItem("_Op"));
        $scope.CityName = $scope.OpInfo.City;
        $scope.IdCity = $scope.OpInfo.IdCity;

        var platform = new H.service.Platform({
            apikey:'HVp2lS8N0_RI_I0KTqEGSTcSvGGSmg2WhR4E3wWTmRs'
        });


        $scope.TypeReport = 1;
        $scope.chats = ChatService;
        $scope.IsDisabled = true;
        $scope.CityName = '';
        $scope.Phone = '';// '3103680445';
        $scope.ValeFisico = null;
        $scope.IsBusiness = false;
        $scope.UserFixedsEnd = [];
        $scope.ListGeoZonas = [];
        $scope.Servicio = null;
        $scope.UserFixeds = {
              Id: ''
            , IdCity: ''
            , IdZona: ''
            , IdUser: ''
            , IdBusinesse: ''
            , IdTypeServics: 0
            , IdTypeCapacity: 0
            , IdTypePago: 0
            , Name: ''
            , Referen: ''
            , Phone: ''
            , Td1: ''
            , Td2: ''
            , Td3: ''
            , Td4: ''
            , Td5: ''
            , Tn1: ''
            , Tn2: ''
            , Tn3: ''
            , Tn4: ''
            , Address: ''
            , NumberHouse: ''
            , Barrio: ''
            , CreateDate: ''
            , Latitud: 0
            , Longitud: 0


        };


        if ($scope.Role === "Business") {
            $scope.IsBusiness = true;
            $scope.BusinessInfo = JSON.parse(localStorage.getItem("_BusinessInfo"));
        }


        var mDate = new Date();
       
        var markers = [];

        var circle;
        var autocomplete;
      


        var mapOpen;

        $scope.IsTrakingDriver = false;

        $scope.data = {
            availableOptions: [
                { id: '0', name: 'TAXI' },
                { id: '1', name: 'DOMICILIOS' },
                { id: '2', name: 'A-TRANSPORTE' }

            ],
            selectedOption: { id: '0', name: 'TAXI' }
        };
        $scope.Td1s = {
            model: null,
            availableOptions: [
                { id: 'CL', name: 'CL' },
                { id: 'Cra', name: 'Cra' },
                { id: 'AV', name: 'AV' },
                { id: 'AC', name: 'AC' },
                { id: 'AK', name: 'AK' },
                { id: 'AP', name: 'AP' },
                { id: 'DG', name: 'DG' },
                { id: 'MZ', name: 'MZ' },
                { id: 'Tv', name: 'Tv' },
            ],
            selectedOption: { id: 'CL', name: 'CL' }
        };
        $scope.Td3s = {
            model: null,
            availableOptions: [
                { id: '', name: '' },
                { id: 'A', name: 'A' },
                { id: 'B', name: 'B' },
                { id: 'C', name: 'C' },
                { id: 'D', name: 'D' },
                { id: 'E', name: 'E' },
                { id: 'F', name: 'F' },
                { id: 'G', name: 'G' },
                { id: 'H', name: 'H' },
                { id: 'I', name: 'I' },
                { id: 'J', name: 'J' },
                { id: 'K', name: 'K' },
                { id: 'L', name: 'L' },
                { id: 'M', name: 'M' },
                { id: 'N', name: 'N' },
                { id: 'O', name: 'O' },
                { id: 'P', name: 'P' },
                { id: 'Q', name: 'Q' },
                { id: 'R', name: 'R' },
                { id: 'S', name: 'S' },
                { id: 'T', name: 'T' },
                { id: 'U', name: 'U' },
                { id: 'V', name: 'V' },
                { id: 'W', name: 'W' },
                { id: 'X', name: 'X' },
                { id: 'Y', name: 'Y' },
                { id: 'Z', name: 'Z' },
            ],
            selectedOption: { id: 'A', name: 'A' }
        };
        $scope.Td4s = {
            model: null,
            availableOptions: [
                { id: '', name: '' },
                { id: 'BIS', name: 'BIS' },
                { id: 'BIS A', name: 'BIS A' },
                { id: 'BIS B', name: 'BIS B' },
                { id: 'BIS C', name: 'BIS C' },
                { id: 'BIS D', name: 'BIS D' },
                { id: 'BIS E', name: 'BIS E' }
            ],
            selectedOption: { id: 'BIS A', name: 'BIS A' }
        };
        $scope.Td5s = {
            model: null,
            availableOptions: [
                { id: '', name: '' },
                { id: 'NORTE', name: 'NORTE' },
                { id: 'SUR', name: 'SUR' },
                { id: 'ESTE', name: 'ESTE' },
                { id: 'OESTE', name: 'OESTE' }
            ]

        };
        $scope.dataTiempo = {
            availableOptions: [
                { id: '0', name: 'INMEDIATO' },
                { id: '5', name: 'RESERVA' }
            ],
            selectedOption: { id: '0', name: 'INMEDIATO' }
        };

        $scope.ListZonas = {
            availableOptions: [],
            selectedOption: {}

        };


        /********************************/

        $scope.showTab1 = function () {

            $('#tab1').toggleClass('active');
            $('#tab1').show();
            $('#tab2').hide();
            $('#tab3').hide();
        };

        $scope.showTab2 = function () {
            $('#tab2').toggleClass('active');
            $('#tab2').show();
            $('#tab1').hide();
            $('#tab3').hide();
        };

        $scope.showTab3 = function () {
            $('#tab3').toggleClass('active');
            $('#tab3').show();
            $('#tab1').hide();
            $('#tab2').hide();
        };

        $scope.supported = false;

        $scope.success = function () {
            console.log('Copied!');
        };

        $scope.fail = function (err) {
            console.error('Error!', err);
        };

        $scope.gettextToCopy = function (id) {
            return+'http://'+ window.location.hostname+ '/home/IndexView/' + id;
        };

        $scope.fancyTimeFormat = function (time) {
            if (time <= 0) {
                time = time * -1;
            }

            // Hours, minutes and seconds
            var hrs = ~~(time / 3600);
            var mins = ~~((time % 3600) / 60);
            var secs = ~~time % 60;

            // Output like "1:01" or "4:03:59" or "123:03:59"
            var ret = "";

            if (hrs > 0) {
                ret += "" + hrs + ":" + (mins < 10 ? "0" : "");
            }

            ret += "" + mins + ":" + (secs < 10 ? "0" : "");
            ret += "" + secs;
            return ret;
        };

        $scope.UpdateTempo = function () {

            if ($scope.dataTiempo.selectedOption.id == 5) return;
            mDate = new Date();
            $scope.Fecha = mDate;
            $scope.Hora = mDate;
            $scope.MaxFecha = mDate;
            $scope.MaxHora = mDate;
        };

        $scope.UpdateTempo();

        $scope.updateAddress = function () {

            $scope.UserFixeds.Address = $scope.UserFixeds.Td1 + ' ';
            $scope.UserFixeds.Address = $scope.UserFixeds.Address + ($scope.UserFixeds.Td2 == null ? '' : $scope.UserFixeds.Td2);
            $scope.UserFixeds.Address = $scope.UserFixeds.Address + ($scope.UserFixeds.Td3 == null ? '' : $scope.UserFixeds.Td3) + ' ';
            $scope.UserFixeds.Address = $scope.UserFixeds.Address + ($scope.UserFixeds.Td4 == null ? '' : $scope.UserFixeds.Td4) + ' ';
            $scope.UserFixeds.Address = $scope.UserFixeds.Address + ($scope.UserFixeds.Td5 == null ? '' : $scope.UserFixeds.Td5) + ' ';
            $scope.UserFixeds.Address = $scope.UserFixeds.Address + '#';
            $scope.UserFixeds.Address = $scope.UserFixeds.Address + ($scope.UserFixeds.Tn1 == null ? '' : $scope.UserFixeds.Tn1);
            $scope.UserFixeds.Address = $scope.UserFixeds.Address + ($scope.UserFixeds.Tn2 == null ? '' : $scope.UserFixeds.Tn2) + ' ';
            $scope.UserFixeds.Address = $scope.UserFixeds.Address + ($scope.UserFixeds.Tn3 == null ? '' : $scope.UserFixeds.Tn3) + ' ';
            $scope.UserFixeds.Address = $scope.UserFixeds.Address + ($scope.UserFixeds.Tn4 == null ? '' : $scope.UserFixeds.Tn4) + ' ';
            let addres = $scope.UserFixeds.Address + ($scope.UserFixeds.NumberHouse == '' ? '' : '-' + $scope.UserFixeds.NumberHouse)
            geocodeHere(addres);
            return $scope.UserFixeds.Address;

        };
        $scope.updateAddressZona = function () {
            let addres = $scope.UserFixeds.Address + ($scope.UserFixeds.NumberHouse == '' ? '' : '-' + $scope.UserFixeds.NumberHouse)
            geocodeHere(addres);
            return addres;

        };



        $scope.SetAddress = function (url, IdUserApp) {

            $scope.UserFixeds.Phone = $scope.Phone;
            $scope.UserFixeds.IdCity = $scope.IdCity;
            $scope.UserFixeds.Id = createUUID();
            // $scope.UserFixeds.IdUser = IdUserApp;
            $scope.UserFixeds.Address = $scope.UserFixeds.Address;

            if (confirm("DESEA GUARDAR LA DIRECCION?")) {
                console.log($scope.UserFixeds);
                $http.post('/api/Dispatch/SetAddress', $scope.UserFixeds).success(function (data, status, headers, config) {
                    if (data != null) {
                        $("#myAddAddress").hide();
                        $("#myAddress").show();
                        $scope.BuscarAddress();
                    }
                }).error(function (data, status, headers, config) { console.log(data); });

            }

        };

        $scope.SendFrecuencia = function (Id) {


            var res = DispatchServics.SendFrecuencia(Id).then(function (pl) {

                if (pl.data === 0) {
                    growl.warning("Servicio Ya fue asignado ó cancelado ", { title: 'warning!' });
                    $scope.GetServicioPublicados();

                } else if (pl.data >= 1) {
                    growl.success("Servicio re-direccionado a el modulo de frecuencias satisfactiamente.", { title: 'Succes!' });
                    $scope.GetServicioPublicados();
                } else if (pl.data === -1) {
                    growl.warning("No hay frecuencias activas ", { title: 'warning!' });
                    $scope.GetServicioPublicados();
                } else if (pl.data === -2) {
                    growl.warning("Este servicio ya fue pasado por frecuencias", { title: 'warning!' });
                    $scope.GetServicioPublicados();
                } else {
                    growl.warning("Servicio NO FUE re-direccionado a el modulo de frecuencias.", { title: 'warning!' });
                    $scope.GetServicioPublicados();
                }
            }, function (errorPl) {
                growl.error(errorPl.data, { title: 'Error!' });
            });
        };

        $scope.GetServicioPublicados = function () {
            var res = DispatchServics.getServicioPublicados().then(function (pl) {
                var data = pl.data;
                console.log(data);
                $scope.ListServicios = [];
                $scope.ListServiciosPositivos = [];
                $scope.ListServiciosReservas = [];

                $.each(data, function (key, value) {
                    if (value.State === 0 || value.State === 1 || value.State === 2 || value.State === 3 || value.State === 4) {
                        if (!value.IsPositive) {
                            $scope.ListServicios.push(value);
                        }
                    }
                    if (value.State >4) {
                        // console.log(value);
                        $scope.ListServiciosPositivos.push(value);
                    }

                    if (value.State === 5) {
                        $scope.ListServiciosReservas.push(value);
                    }
                });

                //console.log($scope.Servicio);
                if ($scope.Servicio !== null) {
                    $.each(data, function (key, value) {
                        if ($scope.Servicio.Id === value.Id) {
                            $scope.ModalTrakingDriverRefresh(value);
                        }

                    });
                }

            }, function (errorPl) {
                growl.error(errorPl.data, { title: 'Error!' });
                $scope.loggedIn = false;
                localStorage.setItem("_LoggedIn", $scope.loggedIn);
                window.location = '#/signin';
            });
        };

        $scope.getListEmpresas = function () {

            var res = DispatchServics.getLisEmpresas().then(function (pl) {
                var data = pl.data;
                $scope.ListEmpresas = data;
            }, function (errorPl) {
                growl.error(errorPl.data, { title: 'Error!' });
            });

        };

        $scope.GetCentroCostosByBusiness = function (IdBusiness) {
            var res = DispatchServics.GetCentroCostosByBusiness(IdBusiness).then(function (pl) {
                var data = pl.data;
                $scope.ListCentroCostos = data;
            }, function (errorPl) {
                growl.error(errorPl.data, { title: 'Error!' });
            });
        };

        $scope.GeoZonaChange = function (v) {
            $scope.UserFixeds.Referen = v.Name;
            $scope.UserFixeds.IdZona = v.Id;
            deleteMarkers();
            setMarkersDireccionCenter(mapOpen, v.Latitud, v.Longitud);
        }

        $scope.GetAllZonas = function () {
            var CurrentDay = new Date();
            var GeoZonas = "Gz_"+CurrentDay.getDay()+"_"+ $scope.IdCity;

            if (localStorage.getItem(GeoZonas) == null) {
                var res = DispatchServics.getGetAllZonas($scope.IdCity).then(function (pl) {
                    var data = pl.data;
                    localStorage.setItem(GeoZonas, JSON.stringify(data));
                    $scope.ListZonas.availableOptions = data;
                }, function (errorPl) {
                    growl.error(errorPl.data, { title: 'Error!' });
                });
            } else {
                $scope.ListZonas.availableOptions = JSON.parse(localStorage.getItem(GeoZonas));
            }
        };

        $scope.GetAllZonas();

        $scope.GetServicioPublicados();

        $scope.BuscarAddress = function () {
            $scope.UpdateTempo();
            if ($scope.Phone == null || $scope.Phone == '') {
                growl.warning('Digita un numero de telefono!', { title: 'Warning!' });
                $("#Phone").focus();
                return;
            }
            $scope.getAllAddressByPhone();

        };
        $scope.ModalHide = function () {
            $("#myAddress").hide();
            $("body").css("overflow", "scroll");
        };
        $scope.ModalAddHide = function () {
            $("#myAddAddress").hide();
            $("#myAddress").show();
        };
        $scope.ModalAddHideEndAddress = function () {
            $("#myEndAddAddress").hide();
        };
        $scope.ModalTrakingDriverHide = function () {
            $scope.Servicio = null;
            $("#myTraking").hide();
        };
        $scope.ModalServicesLogHide = function () {
            $scope.Servicio = null;
            $("#myServicesLog").hide();
        };
        $scope.getAddress = function (hs) {
            $scope.UserFixeds = hs;
            $scope.Address = hs.Address + ' - ' + hs.NumberHouse;
            $("#myAddress").hide();
            $("body").css("overflow", "scroll");
        };
        $scope.ModalAddAddress = function () {
            $("#myAddAddress").show();
            $("#myAddress").hide();
            var popup = L.popup();
            $scope.setDivMapa('map');
            mapOpen.on('click', function (e) {
                popup
                    .setLatLng(e.latlng)
                    .setContent("Este es el punto Inicial " + e.latlng.toString() + "\nde la direccion")
                    .openOn(mapOpen);
                deleteMarkers();
                setMarkersDireccion(mapOpen, e.latlng.lat, e.latlng.lng);
            });


        };


        /*TRAKING AL  DRIVER*/
        $scope.ModalAllTrakingDriverHide = function () {
            $scope.IsTrakingDriver = false;
            $("#myAllTraking").hide();
        };

        $scope.BuscarPlaca = function () {
            $scope.setAllDriverLocationsByIdOp(mapOpen);
        };

        $scope.changesTypePago = function () {
            if ($scope.UserFixeds.IdTypePago == 2) {
                $scope.IsDisabled = false;
            } else {
                $scope.IsDisabled = true;
            }

        };

        $scope.ModalAllTrakingDriverShow = function () {
            $scope.IsTrakingDriver = true;
            $scope.setDivMapa('AllTrakingmap');
            $scope.setAllDriverLocationsByIdOp(mapOpen);
        };
        $scope.setDivMapa = function (value) {
            if (mapOpen != null) mapOpen.remove();
            mapOpen = L.map(document.getElementById(value)).setView([localStorage.getItem("LatitudCiti"), localStorage.getItem("LongitudCiti")], 14);



            //https://api.mapbox.com/styles/v1/{id}/tiles/{z}/{x}/{y}?access_token={accessToken}
            L.tileLayer('https://api.mapbox.com/styles/v1/{id}/tiles/{z}/{x}/{y}?access_token={accessToken}', {
                attribution: 'Map data &copy; <a href="https://www.openstreetmap.org/">OpenStreetMap</a> contributors, <a href="https://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, Imagery © <a href="https://www.mapbox.com/">Mapbox</a>',
                maxZoom: 18,
                id: 'mapbox/streets-v11',
                accessToken: 'pk.eyJ1IjoidGF4aWRyaXZlcmNvIiwiYSI6ImNsZzFld3Y5MDFnNHEzZXA2bDdiMHd6b2sifQ.OEzh_4sxJSbs2Jw731Rh-A'
            }).addTo(mapOpen);
        };
        $scope.ReasignarServicio = function (Ids) {

            var placa = prompt("DIGITE LA PLACA O EL MOVIL", "");

            if (placa != null) {

                var res = DispatchServics.reasignarServicioJosb(Ids, placa).then(function (pl) {
                    $scope.GetServicioPublicados();
                    //growl.success('Servicio re-asignado', { title: 'Success!' });
                }, function (errorPl) {
                    growl.error(errorPl.data, { title: 'Error!' });
                });

            }

        };
        ///Modal para el tracking del conductor y el  pasajero
        $scope.ModalTrakingDriver = function (hs) {
            $scope.TotalVehiculos = 0;
            $scope.Servicio = hs;
            $("#myTraking").show();
            $scope.setDivMapa('Trakingmap');

            //  console.log(hs);
            setMarkersTraking(mapOpen, hs);



        };

        $scope.GetListaDriverDistanceGPS = function (dis, map, lt, lg) {

            var res = DispatchServics.GetListaDriverDistanceGPSByOp(dis, lt, lg).then(function (pl) {
                var data = pl.data;

                // map.fitBounds([[51.5, 10], [55.5, 13]]);

                var icon = L.divIcon({
                    className: 'custom-div-icon',
                    html: "<div style='background-color:#FCC704;' class='marker-pin'></div><i class='material-icons'>local_taxi</i>",
                    iconSize: [30, 42],
                    iconAnchor: [15, 42]
                });

                //account_circle

                $.each(data, function (k, v) {
                    var markerD = new L.marker([v.Latitud, v.Longitud], {
                        icon: icon
                    });
                    map.addLayer(markerD);

                });

                var circleOptions = {
                    color: 'red',
                    fillColor: '#f03',
                    fillOpacity: 0.1
                };

                var circleCenter = [lt, lg];

                var circle = L.circle(circleCenter, dis, circleOptions);

                circle.addTo(map);

                $scope.TotalDistancia = dis;
                $scope.TotalVehiculos = data.length;


            }, function (errorPl) {
                growl.error(errorPl.data, { title: 'Error!' });
            });

        };
        $scope.ModalServicesLog = function (hs) {
            $scope.Servicio = hs;

            var res = DispatchServics.setServicioLog(hs.Id).then(function (pl) {
                var data = pl.data;
                $("#myServicesLog").show();
                $scope.ListServicesLog = data;

            }, function (errorPl) {
                growl.error(errorPl.data, { title: 'Error!' });
            });

        };
        $scope.ModalTrakingDriverRefresh = function (hs) {
            $scope.Servicio = hs;
            $scope.setDivMapa('Trakingmap');
            setMarkersTraking(mapOpen, hs);
        };
        $scope.getKilometros = function (lat1, lon1, lat2, lon2) {
            rad = function (x) { return x * Math.PI / 180; }
            var R = 6378.137; //Radio de la tierra en km
            var dLat = rad(lat2 - lat1);
            var dLong = rad(lon2 - lon1);
            var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.cos(rad(lat1)) * Math.cos(rad(lat2)) * Math.sin(dLong / 2) * Math.sin(dLong / 2);
            var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
            var d = R * c;
            return d.toFixed(3); //Retorna tres decimales
        };
        $scope.getAllAddressByPhone = function () {
            $scope.ListAddress = [];
            var res = DispatchServics.getAllAddressByPhone($scope.Phone).then(function (pl) {
                var data = pl.data;
                $("#myAddress").show();
                $("body").css("overflow", "hidden");
                if (data.length == 0) {
                    growl.warning('No hay  Registro!', { title: 'Warning!' });
                    return;
                }
                $scope.ListAddress = data;

            }, function (errorPl) {
                growl.error(errorPl.data, { title: 'Error!' });
            });


        };
        $scope.setAllDriverLocationsByIdOp = function (map) {
            deleteMarkers();
            var res = DispatchServics.setAllDriverLocationsByIdOp().then(function (pl) {
                var data = pl.data;
                $("#myAllTraking").show();

                if (data.length == 0) {
                    growl.warning('No hay  Registro!', { title: 'Warning!' });
                    return;
                }

                $scope.CountDriver = data.length;
                $.each(data, function (key, value) {
                    setMarkersTaxi(map, value);
                });

                mapOpen.invalidateSize(true);
            }, function (errorPl) {
                growl.error(errorPl.data, { title: 'Error!' });
            });
        };

        /*
        Publica los servicio a los  conductores
        */
        $scope.AdminServicesDistance = function () {

            try {
                $scope.UpdateTempo();
                if ($scope.Address == null || $scope.Address == '') {
                    growl.warning('Digita una direccion!\npara el servicio', { title: 'Warning!' });
                    $("#Phone").focus();
                    return;
                }

                $scope.UserFixeds.Id = createUUID();
                $scope.UserFixeds.IdCity = createUUID();

                $scope.Fecha.setHours($scope.Hora.getHours());
                $scope.Fecha.setMinutes($scope.Hora.getMinutes());
                $scope.Fecha.setSeconds(0);

                $scope.UserFixeds.CreateDate = $scope.Fecha;
                $scope.UserFixeds.State = $scope.dataTiempo.selectedOption.id;
                if ($scope.IsBusiness) {
                    $scope.UserFixeds.IdBusinesse = $scope.BusinessInfo.Id;
                }

                $scope.UserFixeds.IdTypeServics = $scope.data.selectedOption.id;
                $scope.UserFixeds.EndLatitud = $scope.UserFixedsEnd.Latitud === undefined ? 0 : $scope.UserFixedsEnd.Latitud;
                $scope.UserFixeds.EndLongitud = $scope.UserFixedsEnd.Longitud === undefined ? 0 : $scope.UserFixedsEnd.Longitud;

                //   $scope.UserFixeds.EndAddress

                if (confirm("PUBLICAR EL SERVICIO")) {

                    $http.post('/api/Dispatch/AdminServicesDistance', $scope.UserFixeds).success(function (data, status, headers, config) {
                        if (data !== null) {
                            $scope.UserFixedsEnd = [];
                            $scope.GetServicioPublicados();
                        }
                    }).error(function (data, status, headers, config) {
                        growl.error(data, { title: 'Error!' });
                    });

                    $("#Phone").focus();
                    $("#Phone").select();
                }
            }
            catch (e) {
                alert(e);
            }
        };
        $scope.CancelServices = function (Id) {
            var params = {
                Ids: Id
            };
            console.log(Id);
            if (confirm("CANCELAR EL SERVICIO")) {

                var res = DispatchServics.CancelServices(Id).then(function (pl) {
                    var data = pl.data;
                    if (data == 1) {
                        growl.info("SERVICIO CANCELADO", { title: 'Info!' });
                    }
                }, function (errorPl) {
                    growl.error(errorPl.data, { title: 'Error!' });
                });

            }

        };
        $scope.EliminarServices = function (Id) {

            if (confirm("ELIMINAR EL SERVICIO")) {

                var res = DispatchServics.EliminarServices(Id).then(function (pl) {
                    var data = pl.data;
                    if (data == 1) {
                        growl.info("SERVICIO ELIMINADO", { title: 'Info!' });
                        $scope.GetServicioPublicados();
                    }
                }, function (errorPl) {
                    growl.error(errorPl.data, { title: 'Error!' });
                });

            }
        };
        $scope.setNoAtendido = function (Id) {
            if (confirm("¿NO SE HA ATENDIDO EL SERVICIO?")) {
                var res = DispatchServics.setNoAtendido(Id).then(function (pl) {
                    var data = pl.data;
                    if (data == 1) {
                        growl.success("SERVICIO CAMBIADO DE ESTADO CORRECTAMENTE", { title: 'OK!' });
                        $scope.GetServicioPublicados();
                    }
                }, function (errorPl) {
                    growl.error(errorPl.data, { title: 'Error!' });
                });
            }
        };




        /***ENVIA MENSAJES A LOS CONDUCTORES***/
        $scope.ModalGMessageShow = function () {
            $("#ModalGMessage").show();
        };
        $scope.ModalGMessageHide = function () {
            $("#ModalGMessage").hide();
        };
        $scope.enviarNotification = function () {
            var res = DispatchServics.EnviarNotification($scope.Servicio.Placa, $scope.Msg).then(function (pl) {
                var data = pl.data;
                if (data === 1) {
                    growl.info('ENVIADO', { title: 'Info!' });
                }
            }, function (errorPl) {
                growl.error(errorPl.data, { title: 'Error!' });
            });
        };
        $scope.enviarAllNotification = function () {
            if ($scope.AllPlaca === null) $scope.AllPlaca = "";
            var res = DispatchServics.EnviarNotification($scope.AllPlaca, $scope.Msg).then(function (pl) {
                var data = pl.data;
                if (data === 1) {
                    growl.info('ENVIADO', { title: 'Info!' });
                }
            }, function (errorPl) {
                growl.error(errorPl.data, { title: 'Error!' });
            });

            $scope.ModalGMessageHide();
        };

        $interval(function () {
            if (!$scope.isActive('/dispatch')) return;

            $scope.UpdateTempo();
            $scope.GetServicioPublicados();
            if ($scope.IsTrakingDriver) { $scope.setAllDriverLocationsByIdOp(map); }
            console.log($location.path());

        }, 100000);

        $scope.isActive = function (viewLocation) {
            var active = (viewLocation === $location.path());
            return active;
        };









        /***************HERE*****************************/

        function geocodeHere(address) {
            console.log(address + ',' + $scope.OpInfo.City);

            var geocoder = platform.getSearchService(),
                geocodingParameters = {
                    q: address + ',' + $scope.OpInfo.City + ', Colombia'
                };

            geocoder.geocode(
                geocodingParameters,
                onSuccess,
                onError
            );
        }


        function onSuccess(result) {
            var location = result.items;
            if (location.length > 0) {
                console.log(location);
                setMarkersDireccionCenter(mapOpen, location[0].position.lat, location[0].position.lng);
            }
        }


        function onError(error) {
            alert('Can\'t reach the remote server');
        }


        /*************************************************/

        /***************************CHAT*************************/

        $scope.chats.OnServicesPublic = function () {
            $scope.UpdateTempo();
            $scope.GetServicioPublicados();
            //  console.log("On:", $location.path());
        };

        $scope.chats.OnSetAlertaToUser = function (PServices, Alert) {
            if (PServices.TypeAlert != undefined) {
                if (PServices.TypeAlert == 2) {
                    //ANIMACION VIBRATE
                    document.getElementById("floating-button").className = "vibrateCont";
                    setTimeout(function () {
                        document.getElementById("floating-button").className = "";
                    }, 3000);

                    // SOLICITUD de CODIGO
                    var audio = new Audio('Assets/tone.mp3');
                    audio.play();

                    //BUSCAR SI YA EL CONDUCTOR ESTA EN LA LISTA
                    var indiceLista = -1;
                    for (var i = 0; i < $scope.vecMensajesDriver.length; i++) {
                        if ($scope.vecMensajesDriver[i].Name == PServices.DriverName) {
                            indiceLista = i;
                            break;
                        }
                    }

                    if (indiceLista == -1) {
                        //NO ESTA EN LA LISTA
                        //LLENAR VEC MSG
                        var vecMsg = [];
                        vecMsg.push({
                            typeMsg: "DRIVER",
                            msg: PServices.Alert,
                            fecha: new Date()
                        });
                        //LLENAR VECTOR MSG
                        var objPrin = {
                            IdDriver: PServices.IdDriver,
                            Name: PServices.DriverName,
                            Placa: PServices.DriverPlaca,
                            Nit: PServices.DriverNit,
                            contNewMsg: 1,
                            typeAlert: 2,
                            dataa: PServices,
                            Mensajes: vecMsg
                        };
                        $scope.vecMensajesDriver.push(objPrin);
                    } else {
                        //SI ESTA EN LA LISTA
                        $scope.vecMensajesDriver[indiceLista].contNewMsg++;
                        $scope.vecMensajesDriver[indiceLista].Mensajes.push({
                            typeMsg: "DRIVER",
                            msg: PServices.Alert,
                            fecha: new Date()
                        });
                    }
                }
            }
            console.log("On:OnSetAlertaToUser", PServices);

        };

        $scope.chats.OnMessageToDriver = function (Message) {
            var audio = new Audio('Assets/tone.mp3');
            audio.load();

            setTimeout(function () {
                audio.play();
            }, 0);
            //ANIMACION VIBRATE

            if (document.getElementById("floating-button") != null && document.getElementById("floating-button").className != null) {
                document.getElementById("floating-button").className = "vibrateCont";
            }

            setTimeout(function () {
                document.getElementById("floating-button").className = "";

            }, 3000);


            if ($scope.vecMsgSelect != null && $scope.vecMsgSelect.Id == Message.IdOrigen) {

                getChatByDriver(Message.IdOrigen);
                UpdateChatByDriver(Message.Id);
            } else {
                getDriverByChat();
            }
        };
/***/
        function callAtTimeout() {
            console.log("Timeout occurred");
            $scope.UpdateTempo();
            $scope.GetServicioPublicados();

            if ($scope.IsTrakingDriver) { $scope.setAllDriverLocationsByIdOp(map); }
        }


        function createUUID() {

            var s = [];
            var hexDigits = "0123456789abcdef";
            for (var i = 0; i < 36; i++) {
                s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
            }
            s[14] = "4";  // bits 12-15 of the time_hi_and_version field to 0010
            s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1);  // bits 6-7 of the clock_seq_hi_and_reserved to 01
            s[8] = s[13] = s[18] = s[23] = "-";

            var uuid = s.join("");
            return uuid;
        }

        function InitMap() {
            //https://api.mapbox.com/v4/mapbox.satellite/1/0/0@2x.jpg90?access_token={token}
            mapOpen = L.map(document.getElementById('AllTrakingmap')).setView([localStorage.getItem("LatitudCiti"), localStorage.getItem("LongitudCiti")], 14);
            L.tileLayer('https://api.mapbox.com/styles/v1/{id}/tiles/{z}/{x}/{y}?access_token={accessToken}', {
                attribution: 'Map data &copy; <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, Imagery © <a href="http://mapbox.com">Mapbox</a>',
                subdomains: ['a', 'b', 'c', 'd'],
                accessToken: 'pk.eyJ1IjoidGF4aWRyaXZlcmNvIiwiYSI6ImNsZzFld3Y5MDFnNHEzZXA2bDdiMHd6b2sifQ.OEzh_4sxJSbs2Jw731Rh-A',
                id: 'mapbox/streets-v11',

            }).addTo(mapOpen);


            //L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token={accessToken}', {
            //    attribution: 'Map data &copy; <a href="https://www.openstreetmap.org/">OpenStreetMap</a> contributors, <a href="https://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, Imagery © <a href="https://www.mapbox.com/">Mapbox</a>',
            //    maxZoom: 18,
            //    id: 'mapbox.streets',
            //    accessToken: 'pk.eyJ1IjoidGRyaXZlciIsImEiOiJjanZpbjVrcmkwMjRrM3lvYXIzbDNqY3V4In0.fbmyker0cIMNKR5UfYXGgw'
            //}).addTo(mapOpen);


        }

        InitMap();


        var componentForm = {
            street_number: 'short_name',
            route: 'long_name',
            locality: 'long_name',
            administrative_area_level_1: 'short_name',
            country: 'long_name',
            postal_code: 'short_name'
        };

       

        // initAutocomplete();




      


        function plotMatchesOnMap(results, reverse) {

            markers = new Array(results.length);
            var resultsListHtml = "";

            for (var i = 0; i < results.length; i++) {
                setMarkersDireccion(mapOpen, results[i].geometry.location.lat(), results[i].geometry.location.lng());
                break;
            }

        }

        function plotMatchesOnMapEnd(results, reverse) {

            markers = new Array(results.length);
            var resultsListHtml = "";

            for (var i = 0; i < results.length; i++) {
                setMarkersDireccionEndAddress(mapOpen, results[i].geometry.location.lat(), results[i].geometry.location.lng());
                break;
            }

        }

        function resetMap() {

            for (var i in markers) {
                markers[i].setMap(null);
            }

            if (circle != null) {
                circle.setMap(null);
            }
            markers = [];

        }

        function clearBoundsOverlays() {
            if (boundsOverlay != null) {
                boundsOverlay.setMap(null);

            }
            if (viewportOverlay != null) {
                viewportOverlay.setMap(null);

            }
        }

        function setMarkersDireccion(map, lat, lng) {

            var markerDireccion = new L.marker([lat, lng], { title: 'A qui' });
            map.addLayer(markerDireccion);
            var latLon = L.latLng([lat, lng]);
            var bounds = latLon.toBounds(500); // 500 = metres
            map.panTo(latLon).fitBounds(bounds);


            if ($scope.UserFixeds != null) {
                $scope.UserFixeds.Latitud = lat;
                $scope.UserFixeds.Longitud = lng;
            } else {
                growl.error('Primero digite una direccion\nantes de ubicar una punto', { title: 'Error!' });

            }
        }



        /*
         Coloca una marka en el mapa  por la direccion registrada
         */
        function setMarkersDireccionCenter(map, lat, lng) {

            var markerDireccion = new L.marker([lat, lng], { title: 'A qui' });
            map.addLayer(markerDireccion);
            var latLon = L.latLng([lat, lng]);
            var bounds = latLon.toBounds(500); // 500 = metres
            map.panTo(latLon).fitBounds(bounds);
            markers.push(markerDireccion);
            if ($scope.UserFixeds != null) {
                $scope.UserFixeds.Latitud = lat;
                $scope.UserFixeds.Longitud = lng;
            } else {
                growl.error('Primero digite una direccion\nantes de ubicar una punto', { title: 'Error!' });

            }
        }


        /// Recorido del veiculos en direccion al  pasajero
        function setMarkersTraking(map, hs) {

            if (hs.State != 0) {

                var iconD = L.divIcon({
                    className: 'custom-div-icon',
                    html: "<div style='background-color:#FCC704;' class='marker-pin'></div><i class='material-icons'>local_taxi</i>",
                    iconSize: [30, 42],
                    iconAnchor: [15, 42]
                });
                var markerDriver = new L.marker([hs.Latitud, hs.Longitud], { DeviceId: hs.DeviceId, title: hs.DriverName, icon: iconD });
                map.addLayer(markerDriver);
            }


            var iconP = L.divIcon({
                className: 'custom-div-icon',
                html: "<div style='background-color:#04C7FC;' class='marker-pin'></div><i class='material-icons'>account_circle</i>",
                iconSize: [30, 42],
                iconAnchor: [15, 42]
            });

            //account_circle

            var markerPasajero = new L.marker([hs.sLatitud, hs.sLongitud], { icon: iconP, title: hs.Name });
            map.addLayer(markerPasajero);



            if (hs.State == 0) {
                DispatchServics.GetOfficeSetting().then(function (pl) {
                    var data = pl.data;

                    $scope.GetListaDriverDistanceGPS(data.DistanceDespacho * 9, map, hs.Latitud, hs.Longitud);

                }, function (errorPl) {
                    growl.error(errorPl.data, { title: 'Error!' });
                });




            }


            map.setView([hs.Latitud, hs.Longitud], 19, { animation: true });


        }

        function setMarkersTaxi(map, taxi) {

            var Indexmarker = -1;
            for (i = 0; i < markers.length; i++) {
                if (markers[i].options.DeviceId === taxi.DeviceId) {
                    map.removeLayer(markers[i]);
                    Indexmarker = i;
                    break;
                }

            }

            var estadoUrl = '#42D109';

            if (taxi.State === 0) {
                estadoUrl = '#FB3A0A';
            } else if (taxi.State === 1) {

                estadoUrl = '#42D109';
            }

            var icon = L.divIcon({
                className: 'custom-div-icon',
                html: "<div style='background-color:" + estadoUrl + ";' class='marker-pin'></div><i class='material-icons'>local_taxi</i><span class='span-pin' >" + taxi.Placa + "</span>",
                iconSize: [30, 42],
                iconAnchor: [15, 42]
            });

            var markerDriver = new L.marker([taxi.Latitud, taxi.Longitud], { DeviceId: taxi.DeviceId, title: taxi.DriverName, icon: icon });

            if (Indexmarker !== -1) {
                markers[Indexmarker] = markerDriver;
            }
            else {

                markers.push(markerDriver);
            }

            if (taxi.Placa == $scope.PlacaTraking) {
                map.setView([taxi.Latitud, taxi.Longitud], 16, { animation: true });

            } else if ($scope.PlacaTraking == '') {
                map.setZoom(11);
            }



            map.addLayer(markerDriver);


        }

        function deleteMarkers() {
            for (var i = 0; i < markers.length; i++) {
                mapOpen.removeLayer(markers[i]);
            }
            markers = [];
        }

        $scope.ModalHidePregDelete = function () {
            $scope.banDelete = false;
            $("#myAddressConfirm").hide();
        };

        $scope.pregDeleteAdress = function () {
            var vecAdres = [];
            for (var i = 0; i < $scope.ListAddress.length; i++) {
                if ($scope.ListAddress[i].check) {
                    vecAdres.push($scope.ListAddress[i].Id);
                }
            }

            if (vecAdres.length == 0) {
                growl.error("Debe seleccionar al menos una dirección", { title: 'Error!' });
                return;
            }
            $scope.banDelete = true;
            $("#myAddressConfirm").show();
        };

        $scope.banDelete = false;
        $scope.deleteDirecciones = function () {

            var vecAdres = [];
            for (var i = 0; i < $scope.ListAddress.length; i++) {
                if ($scope.ListAddress[i].check) {
                    vecAdres.push($scope.ListAddress[i].Id);
                }
            }

            if (vecAdres.length == 0) {
                growl.error("Debe seleccionar al menos una dirección", { title: 'Error!' });
                return;
            }
            $scope.ModalHidePregDelete();
            $scope.banDelete = true;
            var res = DispatchServics.deleteAdress(vecAdres);
            res.then(function (pl) {
                $scope.banDelete = false;
                if (pl.data.std == 1) {
                    growl.success(pl.data.msg, { title: 'Success!' });
                    $scope.getAllAddressByPhone();
                } else {
                    growl.error(pl.data.msg, { title: 'Error!' });
                }
            }, function (errorPl) {
                $scope.banDelete = false;
                growl.error(errorPl.data, { title: 'Error!' });
            });
        }

        //NUEVO
        $('#txtMsg').keyup(function (e) {
            if (event.keyCode == 13) {
                var content = this.value;
                var caret = getCaret(this);
                if (event.shiftKey) {
                    this.value = content.substring(0, caret - 1) + "\n" + content.substring(caret, content.length);
                    event.stopPropagation();
                } else {
                    this.value = content.substring(0, caret - 1) + content.substring(caret, content.length);
                    $scope.enviarMensaje();
                }
            }
        });

        function getCaret(el) {
            if (el.selectionStart) {
                return el.selectionStart;
            } else if (document.selection) {
                el.focus();

                var r = document.selection.createRange();
                if (r == null) {
                    return 0;
                }

                var re = el.createTextRange(),
                    rc = re.duplicate();
                re.moveToBookmark(r.getBookmark());
                rc.setEndPoint('EndToStart', re);

                return rc.text.length;
            }
            return 0;
        }

        $scope.mensajeTexto = "";
        $scope.timeMicro = "00:00";
        $scope.EnviandoData = false;
        $scope.cargandoChat = false;

        getDriverByChat();


        var pressTimer;
        var segundosGrabados = 0;
        $scope.banGrabando = false;
        $scope.microCancelado = false;
        var RecordMicro = new ObjRecord();
        RecordMicro.Initialize();

        $scope.cancelarMicro = function () {
            if ($scope.banGrabando) {
                $scope.banGrabando = false;
                $scope.microCancelado = true;
                clearInterval(pressTimer);
                RecordMicro.stopRecording(function (AudioBLOB) { }, RecordMicro._AudioFormat);
                segundosGrabados = 0;
                $scope.timeMicro = "00:00";
            }
        };

        $scope.grabarMicro = function () {
            if ($scope.vecMsgSelect == null) {
                growl.error("Debe seleccionar un conductor para enviar un audio", { title: 'Error!' });
                return;
            }
            $scope.banGrabando = !$scope.banGrabando;
            if ($scope.banGrabando) {
                //GRABAR
                console.log("inicio grabacion");
                RecordMicro.startRecording();
                pressTimer = window.setInterval(function () {
                    segundosGrabados++;
                    formatTimeMicro(segundosGrabados);
                }, 1000);
            } else {
                // DETENER GRABACION
                clearInterval(pressTimer);
                console.log("se detuvo grabacion -- " + segundosGrabados);
                RecordMicro.stopRecording(function (AudioBLOB) {
                    var reader = new FileReader();
                    reader.readAsDataURL(AudioBLOB);
                    reader.onloadend = function () {
                        base64data = reader.result;
                        //MANDAR AUDIO AL SRVIDOR
                        if (segundosGrabados >= 1) {
                            enviarAudioChat(base64data);
                        } else {
                            growl.error("El audio es muy corto.", { title: 'Error!' });
                        }
                        segundosGrabados = 0;
                        $scope.timeMicro = "00:00";
                    }
                }, RecordMicro._AudioFormat);
            }
        };

        function formatTimeMicro(segundos) {
            var min = segundos / 60;
            if (min < 1) {
                $scope.timeMicro = "00:";
            } else {
                if (min < 10)
                    $scope.timeMicro = "0";
                $scope.timeMicro += Math.floor(min) + ":";
            }
            var newSegundos = segundos - (Math.floor(min) * 60);
            if (newSegundos < 10)
                $scope.timeMicro += "0";
            $scope.timeMicro += newSegundos;
            $scope.$apply();
        }

        function enviarAudioChat(base64data) {
            if ($scope.vecMsgSelect === null) {
                return;
            }
            $scope.EnviandoData = true;
            var data = {
                IdDestino: $scope.vecMsgSelect.Id,
                Message: base64data.split(",")[1],
                TypeMessage: "AUDIO"
            };

           
        }

        $scope.enviarMensaje = function () {
            if ($scope.EnviandoData) {
                return;
            }
            if ($scope.vecMsgSelect === null) {
                growl.error("Debe seleccionar un conductor para enviar un mensaje", { title: 'Error!' });
                return;
            }
            if ($scope.mensajeTexto !== "") {
                $scope.EnviandoData = true;
                var data = {
                    IdDestino: $scope.vecMsgSelect.Id,
                    Message: $scope.mensajeTexto,
                    TypeMessage: "TEXTO"
                };

                var res = $scope.chats.enviarChatOperador(data);
                res.then(function (pl) {
                    $scope.EnviandoData = false;
                    if (pl.data !== '00000000-0000-0000-0000-000000000000') {
                        $scope.vecMsgSelect.Mensajes.push({
                            Message: $scope.mensajeTexto,
                            TypeMessage: "TEXTO",
                            TypeOrigen: "OPERADOR",
                            DateCreate: new Date()
                        });

                        $scope.mensajeTexto = "";
                        $('.chat_area').animate({
                            scrollTop: $(".chat_area")[0].scrollHeight
                        }, 'slow');

                     //  getChatByDriver();
                    }
                }, function (errorPl) {
                    $scope.EnviandoData = false;
                    console.log(errorPl);
                });
            }

        };

        $scope.vecMensajesDriver = [];
        $scope.vecMsgSelect = null;
        $scope.verMsgConductores = function () {

            $('#myChatMsgDriver').show();
            getDriverByChat();
        };

        $scope.HideMsgConductores = function () {
            $scope.vecMsgSelect = null;
            $('#myChatMsgDriver').hide();

        };

        function getDriverByChat() {

            var res = driverService.getDriversByOperador();
            res.then(function (pl) {
                var listoresult = pl.data.sort(function (a, b) {
                    var dateA = new Date(a.DateCreate).getTime();
                    var dateB = new Date(b.DateCreate).getTime();
                    return dateB - dateA;
                });
                $scope.vecMensajesDriver = listoresult;
            }, function (errorPl) {
                console.log(errorPl);
            });
        }




        $scope.formtAudio = function (msg) {
            return $sce.trustAsResourceUrl("data:audio/wav;base64," + msg);
        };

        function getChatByDriver(id) {
            $scope.cargandoChat = true;
            var res = $scope.chats.getHistorialByDriver(id);
            res.then(function (pl) {
                $scope.cargandoChat = false;
                $scope.vecMsgSelect.Mensajes = pl.data;


                $('.chat_area').animate({
                    scrollTop: $(".chat_area")[0].scrollHeight
                }, 'slow');

                $.each(pl.data, function (key, values) {
                    UpdateChatByDriver(values.Id);
                });
            }, function (errorPl) {
                $scope.cargandoChat = false;
                console.log(errorPl);
            });


        }

        function UpdateChatByDriver(id) {

            var res = $scope.chats.UpdateChatByDriver(id);
            res.then(function (pl) {
                console.log(pl.data);

            }, function (errorPl) {
                $scope.cargandoChat = false;
                console.log(errorPl);
            });


        }

        $scope.formatearFecha = function (fecha) {
            return new Date(fecha);
        };

        $scope.selecDriverMsg = function (item) {

            for (var i = 0; i < $scope.vecMensajesDriver.length; i++) {
                $scope.vecMensajesDriver[i].check = false;

            }

            item.check = true;
            item.contNewMsg = 0;
            $scope.vecMsgSelect = item;
            getChatByDriver(item.Id);

        };

        $scope.evniarCodigoDirecto = function () {
            var msg = "El codigo es: " + $scope.vecMsgSelect.data.ServiceCodigo;
            var res = DispatchServics.EnviarCodigoNotification($scope.vecMsgSelect.IdDriver, msg).then(function (pl) {
                var data = pl.data;
                if (data == 1) {
                    $scope.vecMsgSelect.Mensajes.push({
                        typeMsg: "OP",
                        msg: msg,
                        fecha: new Date()
                    });
                }
            }, function (errorPl) {
                growl.error(errorPl.data, { title: 'Error!' });
            });

        };



        function setMarkersDireccionEndAddress(map, lat, lng) {
            var markerDireccion = new L.marker([lat, lng], { title: 'A qui' });

            map.addLayer(markerDireccion);
            map.setView([lat, lng], 19, { animation: true });
            map.setZoom(19);

            if ($scope.UserFixedsEnd != null) {

                $scope.UserFixedsEnd.Latitud = lat;
                $scope.UserFixedsEnd.Longitud = lng;
            } else {
                growl.error('Primero digite una direccion\nantes de ubicar una punto', { title: 'Error!' });

            }
        }

        $scope.updateEndAddress = function () {

            $scope.UserFixedsEnd.Address = $scope.UserFixedsEnd.Td1 + ' ';
            $scope.UserFixedsEnd.Address = $scope.UserFixedsEnd.Address + ($scope.UserFixedsEnd.Td2 == null ? '' : $scope.UserFixedsEnd.Td2);
            $scope.UserFixedsEnd.Address = $scope.UserFixedsEnd.Address + ($scope.UserFixedsEnd.Td3 == null ? '' : $scope.UserFixedsEnd.Td3) + ' ';
            $scope.UserFixedsEnd.Address = $scope.UserFixedsEnd.Address + ($scope.UserFixedsEnd.Td4 == null ? '' : $scope.UserFixedsEnd.Td4) + ' ';
            $scope.UserFixedsEnd.Address = $scope.UserFixedsEnd.Address + ($scope.UserFixedsEnd.Td5 == null ? '' : $scope.UserFixedsEnd.Td5) + ' ';
            $scope.UserFixedsEnd.Address = $scope.UserFixedsEnd.Address + '#';
            $scope.UserFixedsEnd.Address = $scope.UserFixedsEnd.Address + ($scope.UserFixedsEnd.Tn1 == null ? '' : $scope.UserFixedsEnd.Tn1);
            $scope.UserFixedsEnd.Address = $scope.UserFixedsEnd.Address + ($scope.UserFixedsEnd.Tn2 == null ? '' : $scope.UserFixedsEnd.Tn2) + ' ';
            $scope.UserFixedsEnd.Address = $scope.UserFixedsEnd.Address + ($scope.UserFixedsEnd.Tn3 == null ? '' : $scope.UserFixedsEnd.Tn3) + ' ';
            $scope.UserFixedsEnd.Address = $scope.UserFixedsEnd.Address + ($scope.UserFixedsEnd.Tn4 == null ? '' : $scope.UserFixedsEnd.Tn4) + ' ';
            //  $scope.UserFixedsEnd.Address = $scope.UserFixedsEnd.Address + ($scope.UserFixedsEnd.NumberHouse == null ? '' :'- '+ $scope.UserFixedsEnd.NumberHouse);
            submitQueryEnd($scope.UserFixedsEnd.Address + ($scope.UserFixedsEnd.NumberHouse == null ? '' : '- ' + $scope.UserFixedsEnd.NumberHouse));
            return $scope.UserFixedsEnd.Address;

        };

        var fila = 0;
        $scope.pulsar = function (e) {
            tab = document.getElementById('tabla');
            filas = tab.getElementsByTagName('tr');
            if (e.keyCode === 38 && fila > 0) num = -1;
            else if (e.keyCode === 40 && fila < filas.length - 1) num = 1;
            else return;
            filas[fila].style.background = 'white';
            fila += num;
            $(filas[fila]).css("background", "#efefef");
            $(filas[fila]).find("button").focus();
            window.scrollTo(0, 0);
        };

        $scope.pulsar(event);

        $scope.OpenEndAddressModal = function () {
            $("#myEndAddAddress").show();
            var popup = L.popup();
            $scope.setDivMapa('mapenddress');
            mapOpen.on('click', function (e) {
                popup
                    .setLatLng(e.latlng)
                    .setContent("Este es el punto Final " + e.latlng.toString() + "\nde la direccion")
                    .openOn(mapOpen);
                setMarkersDireccionEndAddress(mapOpen, e.latlng.lat, e.latlng.lng);
            });
        };


        $scope.addEndAddress = function () {
            $scope.UserFixeds.EndAddress = $("#Direccion1").val();
        };


        $scope.HideEstadoFrecuenciasHide = function () {
            $("#EstadoFrecuencias").hide();
        };

        $scope.OpenEstadoFrecuencias = function () {

            var res = DispatchServics.GetEstadoFrecuencias().then(function (pl) {
                console.log(pl.data);
                $scope.ListEstadoFrecuencias = pl.data;
                $("#EstadoFrecuencias").show();
            }, function (errorPl) {
                growl.error(errorPl.data, { title: 'Error!' });
            });
        };

    }])
    .controller('reportdispatchCtrl', ['$scope', '$http', 'growl', 'DispatchServics', function ($scope, $http, growl, DispatchServics) {
        var d = new Date();
        var v = new Date();
        d.setHours(0, 0, 0, 0);
        v.setTime(d.getTime());
        $scope.StartDate = v;
        $scope.EndDate = d;
        $scope.getListEmpresas = function () {

            var res = DispatchServics.getLisEmpresas().then(function (pl) {
                var data = pl.data;
                $scope.ListEmpresas = data;
            }, function (errorPl) {
                growl.error(errorPl.data, { title: 'Error!' });
            });

        };

        $scope.getReservas = function () {
            $scope.ListReservas = [];
            $scope.TotalRServis = 0;
            var res = DispatchServics.getReservasReports($scope.StartDate, $scope.EndDate).then(function (pl) {
                var data = pl.data;
                if (data.length === 0) {
                    growl.warning('No hay Resultados!', { title: 'Warning!' });
                    return;
                }


                $scope.ListReservas = data;
                $scope.TotalRServis = data.length;

            },
                function (errorPl) {
                    if (r.isArray(errorPl.data))
                        $scope.errorMessages = errorPl.data;
                    else
                        $scope.errorMessages = new Array(errorPl.data.replace(/["']{1}/gi, ""));

                    growl.error($scope.errorMessages, { title: 'Error!' });
                });

        };

        $scope.getServicios = function () {
            $scope.TotalServis = 0;
            $scope.ListTotalServicios = [];

            var res = DispatchServics.getServiciosReports($scope.TypeReport, $scope.StartDate, $scope.EndDate).then(function (pl) {
                var data = pl.data;
                if (data.length == 0) {
                    growl.warning('No hay Resultados!', { title: 'Warning!' });
                    return;
                }
                $scope.ListTotalServicios = data;
                $scope.TotalServis = data.length;
            },
                function (errorPl) {
                    growl.error($scope.errorMessages, { title: 'Error!' });
                });

        };

        $scope.getServiciosDispacher = function () {
            $scope.TotalServis = 0;
            $scope.ListTotalServicios = [];
            console.log($scope.StartDate, $scope.EndDate);

            var res = DispatchServics.getServiciosReportsByDespacher($scope.StartDate, $scope.EndDate).then(function (pl) {
                var data = pl.data;
                if (data.length == 0) {
                    growl.warning('No hay Resultados!', { title: 'Warning!' });
                    return;
                }
                $scope.ListTotalServicios = data;
                $scope.TotalServis = data.length;


            },
                function (errorPl) {
                    growl.error($scope.errorMessages, { title: 'Error!' });
                });

        };

        $scope.calcTotalPositivos = function () {
            var total = 0;

            angular.forEach($scope.ListTotalServicios, function (value) {
                total = value.TotalPositivos + total;

            });
            return total;
        };

        $scope.calcTotalCancelados = function () {
            var total = 0;

            angular.forEach($scope.ListTotalServicios, function (value) {
                total = value.TotalCancelados + total;

            });
            return total;
        };

        $scope.calcTotalPositivosF = function () {
            var Ftotal = 0;
            angular.forEach($scope.ListTotalServicios, function (value) {

                Ftotal = value.TotalPositivosF + Ftotal;
            });
            return Ftotal;
        };

        $scope.calcTotalCanceladosF = function () {

            var Ftotal = 0;
            angular.forEach($scope.ListTotalServicios, function (value) {

                Ftotal = value.TotalCanceladosF + Ftotal;
            });
            return Ftotal;
        };

        $scope.calcTotalPositivosTotal = function () {

            var Ftotal = 0;
            angular.forEach($scope.ListTotalServicios, function (value) {

                Ftotal = value.TotalPositivosTodos + Ftotal;
            });
            return Ftotal;
        };

        $scope.calcTotalNoAtendidos = function () {

            var Ftotal = 0;
            console.log(1);
            angular.forEach($scope.ListTotalServicios, function (value) {

                Ftotal = value.TotalNoAtendidos + Ftotal;
            });
            return Ftotal;
        };

        $scope.getServiciosSinTomar = function () {
            $scope.TotalServis = 0;
            $scope.ListTotalServicios = [];
            var res = DispatchServics.getServiciosReportsNoTomado($scope.StartDate, $scope.EndDate).then(function (pl) {
                var data = pl.data;
                if (data.length == 0) {
                    growl.warning('No hay Resultados!', { title: 'Warning!' });
                    return;
                }
                $scope.ListTotalServicios = data;
                $scope.TotalServis = data.length;
                console.log(data);
            },
                function (errorPl) {

                    growl.error($scope.errorMessages, { title: 'Error!' });
                });

        };

        $scope.getServiciosByDriver = function () {

            ;
            $scope.TotalServis = 0;
            $scope.ListTotalServicios = [];

            var res = DispatchServics.getServiciosReportsByDriver($scope.TypeReport, $scope.Nit, $scope.StartDate, $scope.EndDate).then(function (pl) {
                var data = pl.data;
                if (data.length == 0) {
                    growl.warning('No hay Resultados!', { title: 'Warning!' });
                    return;
                }
                $scope.ListTotalServicios = data;
                $scope.TotalServis = data.length;
            },
                function (errorPl) {

                    growl.error($scope.errorMessages, { title: 'Error!' });
                });

        };


        $scope.getServiciosByUser = function () {
            $scope.TotalServis = 0;
            $scope.ListTotalServicios = [];

            var res = DispatchServics.getServiciosReportsByUser($scope.Phone, $scope.StartDate, $scope.EndDate).then(function (pl) {
                var data = pl.data;
                if (data.length == 0) {
                    growl.warning('No hay Resultados!', { title: 'Warning!' });
                    return;
                }
                $scope.ListTotalServicios = data;
                $scope.TotalServis = data.length;
            },
                function (errorPl) {
                    growl.error($scope.errorMessages, { title: 'Error!' });
                });

        };



        $scope.getServiciosByUserPoint = function () {
            $scope.TotalServis = 0;
            $scope.ListTotalServicios = [];

            var res = DispatchServics.getServiciosReportsByUserPoint($scope.Email, $scope.StartDate, $scope.EndDate).then(function (pl) {
                var data = pl.data;
                if (data.length == 0) {
                    growl.warning('No hay Resultados!', { title: 'Warning!' });
                    return;
                }
                $scope.ListTotalServicios = data;
                $scope.TotalServis = data.length;
            },
                function (errorPl) {
                    growl.error(errorPl.data, { title: 'Error!' });
                });

        };



        $scope.SetPaymentServices = function (Hs) {

            var res = DispatchServics.SetPaymentServices(Hs.Id, Hs.IdUserApp).then(function (pl) {
                var data = pl.data;
                if (data.length == 0) {
                    growl.warning('No hay Resultados!', { title: 'Warning!' });
                    return;
                }

                $scope.getServiciosByUserPoint();

            },
                function (errorPl) {
                    growl.error(errorPl.data, { title: 'Error!' });
                });

        };


        $scope.ModalValeFisicoShow = function (value) {
            if (value.ValeFisico == null) {
                $scope.HServicio = value;
                $("#ModalAsignarValeFisico").modal('show');
                $('#TxtValeFisico').focus();
            } else {
                alert("El servicio ya tiene una VALE FISICO Asignado");
            }
        };

        $scope.ModalValeFisicoHide = function () {
            $("#ModalAsignarValeFisico").modal('hide');
        };


        $scope.setValeFisicoToDriver = function () {

            if ($scope.ValeFisico != null) {

                if (confirm("CONFIRMA LA ASIGNACION!")) {

                    var res = DispatchServics.setValeFisicoToDriver($scope.HServicio.Id, $scope.IdBusinesse, $scope.ValeFisico).then(function (pl) {
                        var data = pl.data;
                        if (data == 1) {
                            growl.info("VALE FISICO REGISTRADO", { title: 'Info!' });
                        }
                    }, function (errorPl) {
                        growl.error(errorPl.data, { title: 'Error!' });
                    });

                }
            } else {
                $('#TxtValeFisico').focus();
            }

        };
        $scope.CancelServices = function (Id) {
            var params = {
                Ids: Id,
            };
            console.log(Id);
            if (confirm("CANCELAR EL SERVICIO")) {

                var res = DispatchServics.CancelServices(Id).then(function (pl) {
                    var data = pl.data;
                    if (data == 1) {
                        growl.info("SERVICIO CANCELADO", { title: 'Info!' });
                    }
                }, function (errorPl) {
                    growl.error(errorPl.data, { title: 'Error!' });
                });

            }

        };

        $scope.EliminarServices = function (Id) {

            if (confirm("ELIMINAR EL SERVICIO - RESERVA")) {

                var res = DispatchServics.EliminarServices(Id).then(function (pl) {
                    var data = pl.data;
                    if (data == 1) {
                        growl.info("SERVICIO ELIMINADO", { title: 'Info!' });
                    }
                }, function (errorPl) {
                    growl.error(errorPl.data, { title: 'Error!' });
                });

            }
        };



    }])
    .controller('dispatchPuntosFijosCtrl', ['$scope', '$http', '$location', '$interval', 'growl', 'DispatchServics', '$interval', '$location', "driverService", "$sce", '$rootScope', '$filter', function ($scope, $http, $location, $interval, growl, DispatchServics, driverService, $sce, $rootScope, $filter) {

        //Calculo Tarifa
        var FCong = 0;
        var Banderazo = 0;
        var CostoKm = 0;
        var FCal = 0;
        var PuertaPuerta = 0;
        var RecargoAereopuerto = 0;
        var RecargosNocturno = 0;
        var CarreraMinima = 0;

        var recAreopuerto = false;
        var recPuerta = false;

        var Vf1 = 36;
        var Vc = 18;
        var b1 = 0.83;
        var b2 = 2.48;
        var c = -0.825;

        var DistanciaLimite = 600;
        var hs = {};
        //Fin

        //INICIO - VARIABLES dispatcher Puntos Fijos
        $scope.listDrivers = [];
        $scope.IdFixedSpot = '';
        $scope.listFixedSpotServices = [];
        $("#getservice").attr('disabled', 'true');
        //FIN

        var circle;
        var clickMarker = null;

        $scope.CityName = '';
        $scope.OpInfo = JSON.parse(localStorage.getItem("_Op"));
        $scope.CityName = $scope.OpInfo.City;
        var mDate = new Date();
        var myLatlng;
        var styles = [
            {
                "stylers": [
                    { "invert_lightness": true },
                    { "saturation": -100 },
                    { "lightness": -5 }
                ]
            }
        ];

        var markers = [];
        var _Latitud;
        var _Longitud;
        var ResultDireccion;
        var geoMarker = {};

        var mapOpen;

        $scope.IsTrakingDriver = false;
        $scope.FCalidad = false;
        $scope.Td1s = {
            model: null,
            availableOptions: [
                { id: 'CL', name: 'CL' },
                { id: 'KR', name: 'KR' },
                { id: 'AV', name: 'AV' },
                { id: 'AC', name: 'AC' },
                { id: 'AK', name: 'AK' },
                { id: 'AP', name: 'AP' },
                { id: 'DG', name: 'DG' },
                { id: 'MZ', name: 'MZ' },
                { id: 'Tv', name: 'Tv' },
            ],
            selectedOption: { id: 'CL', name: 'CL' }
        };
        $scope.Td3s = {
            model: null,
            availableOptions: [
                { id: '', name: '' },
                { id: 'A', name: 'A' },
                { id: 'B', name: 'B' },
                { id: 'C', name: 'C' },
                { id: 'D', name: 'D' },
                { id: 'E', name: 'E' },
                { id: 'F', name: 'F' },
                { id: 'G', name: 'G' },
                { id: 'H', name: 'H' },
                { id: 'I', name: 'I' },
                { id: 'J', name: 'J' },
                { id: 'K', name: 'K' },
                { id: 'L', name: 'L' },
                { id: 'M', name: 'M' },
                { id: 'N', name: 'N' },
                { id: 'O', name: 'O' },
                { id: 'P', name: 'P' },
                { id: 'Q', name: 'Q' },
                { id: 'R', name: 'R' },
                { id: 'S', name: 'S' },
                { id: 'T', name: 'T' },
                { id: 'U', name: 'U' },
                { id: 'V', name: 'V' },
                { id: 'W', name: 'W' },
                { id: 'X', name: 'X' },
                { id: 'Y', name: 'Y' },
                { id: 'Z', name: 'Z' },
            ],
            selectedOption: { id: 'A', name: 'A' }
        };
        $scope.Td4s = {
            model: null,
            availableOptions: [
                { id: '', name: '' },
                { id: 'BIS', name: 'BIS' },
                { id: 'BIS A', name: 'BIS A' },
                { id: 'BIS B', name: 'BIS B' },
                { id: 'BIS C', name: 'BIS C' },
                { id: 'BIS D', name: 'BIS D' },
                { id: 'BIS E', name: 'BIS E' },
            ],
            selectedOption: { id: 'BIS A', name: 'BIS A' }
        };
        $scope.Td5s = {
            model: null,
            availableOptions: [
                { id: '', name: '' },
                { id: 'NORTE', name: 'NORTE' },
                { id: 'SUR', name: 'SUR' },
                { id: 'ESTE', name: 'ESTE' },
                { id: 'OESTE', name: 'OESTE' },

            ]

        };

        clear();
        function clear() {
            for (i = 0; i < 100; i++) {
                window.clearInterval(i);
            }
        }

        getInitAddressFixedSpot();

        function getInitAddressFixedSpot() {

            try {
                var res = DispatchServics.getInitAddressFixedSpot().then(function (pl) {
                    $scope.showTab1();
                    if (pl.data.Name == "-1") {
                        $("#Phone").attr('disabled', 'true');
                        $("#Placa").attr('disabled', 'true');
                        $("#getaddress").attr('disabled', 'true');
                        $("#getservice").attr('disabled', 'true');
                        return growl.error("El usuario no tiene Puntos Fijos Parametrizados.", { title: 'Error!' });
                    }
                    else {
                        getListServicesFixed();
                        $interval(MyIntervalo, 6000);
                        $scope.Info = pl.data;
                    }
                }, function (errorPl) {
                    growl.error(errorPl.data, { title: 'Error!' });
                });
            } catch (e) {
                console.log(e);
            }
        }

        $scope.showTab1 = function () {
            $('#tab1').toggleClass('active');
            $('#tab1').show();
            $('#tab2').hide();
            $('#tab3').hide();
        };

        $scope.isActive = function (viewLocation) {
            var active = (viewLocation === $location.path());
            return active;
        };

        function MyIntervalo() {
            if ($scope.isActive('/puntosfijos')) {
                getListServicesFixed();
            }
        }

        function getListServicesFixed() {
            try {
                var res = DispatchServics.getListServicesFixed().then(function (pl) {
                    $scope.listFixedSpotServices = pl.data;
                }, function (errorPl) {
                    growl.error(errorPl.data, { title: 'Error!' });
                });
            } catch (e) {
                console.log(e);
            }
        }

        $scope.BuscarAddress = function () {
            $scope.UpdateTempo();
            if ($scope.Phone == null || $scope.Phone == '') {
                growl.warning('Digita un numero de telefono!', { title: 'Warning!' });
                $("#Phone").focus();
                return;
            }
            $scope.getAllAddressByPhone();
        };

        $scope.UpdateTempo = function () {
            if ($scope.dataTiempo.selectedOption.id == 5) return;
            mDate = new Date();
            $scope.Fecha = mDate;
            $scope.Hora = mDate;
            $scope.MaxFecha = mDate;
            $scope.MaxHora = mDate;
        };

        $scope.dataTiempo = {
            availableOptions: [
                { id: '0', name: 'INMEDIATO' },
                { id: '5', name: 'RESERVA' },

            ],
            selectedOption: { id: '0', name: 'INMEDIATO' }
        };

        $scope.ModalHide = function () {
            $("#myAddress").hide();
            $("body").css("overflow", "scroll");
        };


        $scope.OpenEndAddressModalPuntosFijos = function () {

            $("#myAddAddress").show();
            $("#myAddress").hide();

            var popup = L.popup();
            $scope.setDivMapa('mapenddressPuntosFijos');

            mapOpen.on('click', function (e) {
                popup
                    .setLatLng(e.latlng)
                    .setContent("Este es el punto Final " + e.latlng.toString() + "\nde la direccion")
                    .openOn(mapOpen);
                setMarkersDireccionEndAddress(mapOpen, e.latlng.lat, e.latlng.lng);
            });
        };

        $scope.setDivMapa = function (value) {
            if (mapOpen != null) mapOpen.remove();
            mapOpen = L.map(document.getElementById(value)).setView([localStorage.getItem("LatitudCiti"), localStorage.getItem("LongitudCiti")], 14);

            L.tileLayer.provider('OpenStreetMap.DE').addTo(mapOpen);

            //L.tileLayer('https://cartodb-basemaps-{s}.global.ssl.fastly.net/dark_all/{z}/{x}/{y}{r}.png', {
            //    attribution: '&copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a> &copy; <a href="http://cartodb.com/attributions">CartoDB</a>',
            //    subdomains: 'abcd',
            //    maxZoom: 14
            //}).addTo(mapOpen);
        };


        function resizingMap() {
            if (typeof map == "undefined") return;
            var center = map.getCenter();
            google.maps.event.trigger(map, "resize");
            map.setCenter(center);
        }



        function resetMap() {

            for (var i in markers) {
                markers[i].setMap(null);
            }

            if (circle != null) {
                circle.setMap(null);
            }
            markers = [];

        }

        $scope.getAddress = function (hs) {
            $scope.UserFixeds = hs;
            $scope.Address = hs.Address + ' - ' + hs.NumberHouse;
            $("#myAddress").hide();
            $("body").css("overflow", "scroll");
            $scope.DireccionDestino = hs.Address;
            $scope.GetConfigData($scope.FCalidad, $scope.Info, hs);

        };

        $scope.pregDeleteAdress = function () {
            var vecAdres = [];
            for (var i = 0; i < $scope.ListAddress.length; i++) {
                if ($scope.ListAddress[i].check) {
                    vecAdres.push($scope.ListAddress[i].Id);
                }
            }

            if (vecAdres.length == 0) {
                growl.error("Debe seleccionar al menos una dirección", { title: 'Error!' });
                return;
            }
            $scope.banDelete = true;
            $("#myAddressConfirm").show();
        };

        $scope.ModalHidePregDelete = function () {
            $scope.banDelete = false;
            $("#myAddressConfirm").hide();
        };

        function setMarkersDireccionEndAddress(map, lat, lng) {
            var markerDireccion = new L.marker([lat, lng], { title: 'A qui' });

            map.addLayer(markerDireccion);
            map.setView([lat, lng], 19, { animation: true });
            map.setZoom(19);

            if ($scope.UserFixeds !== null) {

                $scope.UserFixeds.Latitud = lat;
                $scope.UserFixeds.Longitud = lng;
            } else {
                growl.error('Primero digite una direccion\nantes de ubicar una punto', { title: 'Error!' });

            }
        }

        $scope.getAllAddressByPhone = function () {
            $scope.ListAddress = [];
            var res = DispatchServics.getAllAddressByPhone($scope.Phone).then(function (pl) {
                var data = pl.data;
                $("#myAddress").show();
                $("body").css("overflow", "hidden");
                if (data.length === 0) {
                    growl.warning('No hay  Registro!', { title: 'Warning!' });
                    return;
                }
                $scope.ListAddress = data;
                $scope.IdFixedSpot = $scope.ListAddress[0].Id;
            }, function (errorPl) {
                growl.error(errorPl.data, { title: 'Error!' });
            });


        };

        $scope.ModalAddHide = function () {
            $("#myAddAddress").hide();
            $("#myAddress").show();
        };

        $scope.deleteDirecciones = function () {

            var vecAdres = [];
            for (var i = 0; i < $scope.ListAddress.length; i++) {
                if ($scope.ListAddress[i].check) {
                    vecAdres.push($scope.ListAddress[i].Id);
                }
            }

            if (vecAdres.length === 0) {
                growl.error("Debe seleccionar al menos una dirección", { title: 'Error!' });
                return;
            }
            $scope.ModalHidePregDelete();
            $scope.banDelete = true;
            var res = DispatchServics.deleteAdress(vecAdres);
            res.then(function (pl) {
                $scope.banDelete = false;
                if (pl.data.std === 1) {
                    growl.success(pl.data.msg, { title: 'Success!' });
                    $scope.getAllAddressByPhone();
                } else {
                    growl.error(pl.data.msg, { title: 'Error!' });
                }
            }, function (errorPl) {
                $scope.banDelete = false;
                growl.error(errorPl.data, { title: 'Error!' });
            });
        };

       

        $scope.updateAddress = function () {

            $scope.UserFixeds.Address = $scope.UserFixeds.Td1 + ' ';
            $scope.UserFixeds.Address = $scope.UserFixeds.Address + ($scope.UserFixeds.Td2 === null ? '' : $scope.UserFixeds.Td2);
            $scope.UserFixeds.Address = $scope.UserFixeds.Address + ($scope.UserFixeds.Td3 === null ? '' : $scope.UserFixeds.Td3) + ' ';
            $scope.UserFixeds.Address = $scope.UserFixeds.Address + ($scope.UserFixeds.Td4 === null ? '' : $scope.UserFixeds.Td4) + ' ';
            $scope.UserFixeds.Address = $scope.UserFixeds.Address + ($scope.UserFixeds.Td5 === null ? '' : $scope.UserFixeds.Td5) + ' ';
            $scope.UserFixeds.Address = $scope.UserFixeds.Address + '#';
            $scope.UserFixeds.Address = $scope.UserFixeds.Address + ($scope.UserFixeds.Tn1 === null ? '' : $scope.UserFixeds.Tn1);
            $scope.UserFixeds.Address = $scope.UserFixeds.Address + ($scope.UserFixeds.Tn2 === null ? '' : $scope.UserFixeds.Tn2) + ' ';
            $scope.UserFixeds.Address = $scope.UserFixeds.Address + ($scope.UserFixeds.Tn3 === null ? '' : $scope.UserFixeds.Tn3) + ' ';
            $scope.UserFixeds.Address = $scope.UserFixeds.Address + ($scope.UserFixeds.Tn4 === null ? '' : $scope.UserFixeds.Tn4) + ' ';
            $scope.UserFixeds.Address = $scope.UserFixeds.Address + ($scope.UserFixeds.NumberHouse === null ? '' : '- ' + $scope.UserFixeds.NumberHouse);

            return $scope.UserFixeds.Address;

        };



        function plotMatchesOnMap(results, reverse) {

            markers = new Array(results.length);
            var resultsListHtml = "";

            for (var i = 0; i < results.length; i++) {
                setMarkersDireccionEndAddress(mapOpen, results[i].geometry.location.lat(), results[i].geometry.location.lng());
                break;
            }

        }

        $scope.SetAddress = function (url, IdUserApp) {
            $scope.UserFixeds.Phone = $scope.Phone;
            $scope.UserFixeds.IdCity = createUUID();
            $scope.UserFixeds.Id = createUUID();
            // $scope.UserFixeds.IdUser = IdUserApp;
            $scope.UserFixeds.Address = $scope.UserFixeds.Address;

            if (confirm("DESEA GUARDAR LA DIRECCION?")) {
                $http.post('/api/Dispatch/SetAddress', $scope.UserFixeds).success(function (data, status, headers, config) {
                    if (data !== null) {
                        $("#myAddAddress").hide();
                        $("#myAddress").show();
                        $scope.BuscarAddress();
                    }
                }).error(function (data, status, headers, config) { console.log(data); });

            }

        };

        function createUUID() {

            var s = [];
            var hexDigits = "0123456789abcdef";
            for (var i = 0; i < 36; i++) {
                s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
            }
            s[14] = "4";  // bits 12-15 of the time_hi_and_version field to 0010
            s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1);  // bits 6-7 of the clock_seq_hi_and_reserved to 01
            s[8] = s[13] = s[18] = s[23] = "-";

            var uuid = s.join("");
            return uuid;
        }

        $scope.GetConfigData = function (FCalidad, Hs, Destino) {

            var res = DispatchServics.GetConfigData();
            res.success(function (data, status, headers, config) {
                $scope.ListConfig = data;

                console.log(data);
                if (FCalidad === undefined) {
                    FCalidad = 0;
                }

                if (FCalidad) {
                    CostoKm = $scope.ListConfig.ParametriaRecargos[0].ValorPagarConFactor;
                    Banderazo = $scope.ListConfig.ParametriaRecargos[0].ValorPagarConFactor;
                    RecargoAereopuerto = $scope.ListConfig.ParametriaRecargos[0].ValorPagarConFactor;
                    RecargosNocturno = $scope.ListConfig.ParametriaRecargos[0].ValorPagarConFactor;
                    CarreraMinima = $scope.ListConfig.ParametriaRecargos[0].ValorPagarConFactor;
                    PuertaPuerta = $scope.ListConfig.ParametriaRecargos[0].ValorPagarConFactor;
                }

                CostoKm = $scope.ListConfig.ParametriaRecargos[0].ValorPagarSinFactor;
                Banderazo = $scope.ListConfig.ParametriaRecargos[0].ValorPagarSinFactor;
                RecargoAereopuerto = $scope.ListConfig.ParametriaRecargos[0].ValorPagarSinFactor;
                RecargosNocturno = $scope.ListConfig.ParametriaRecargos[0].ValorPagarSinFactor;
                CarreraMinima = $scope.ListConfig.ParametriaRecargos[0].ValorPagarSinFactor;
                PuertaPuerta = $scope.ListConfig.ParametriaRecargos[0].ValorPagarSinFactor;


                $scope.ModalTrakingDriver(Hs, Destino);

            }).error(function (data, status, headers, config) {
                growl.error(data, { title: 'Error!' });
            });
        };


        $scope.ModalTrakingDriver = function (hs, Destino) {
            $scope.Servicio = hs;
            $scope.setDivMapa('Trakingmap');
            setMarkersTraking(mapOpen, hs, Destino);
        };


        function setMarkersTraking(map, hs, Destino) {

            var estadoUrl = 'http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=pin_sleft|' + hs.Placa + '|FF0000|FFFFFF';

            if (hs.DState === 0) {
                estadoUrl = 'https://chart.googleapis.com/chart?chst=d_bubble_icon_text_small&chld=taxi|bb|' + hs.Placa + '|FFFF00|908D8D';
            }
            if (hs.DState === 1) {
                estadoUrl = 'https://chart.googleapis.com/chart?chst=d_bubble_icon_text_small&chld=taxi|bb|' + hs.Placa + '|0000FF|FFFFFF';
            }
            if (hs.DState === 3) {
                estadoUrl = 'https://chart.googleapis.com/chart?chst=d_bubble_icon_text_small&chld=taxi|bb|' + hs.Placa + '|FF0000|FFFFFF';
            }
            if (hs.DState === 2) {
                estadoUrl = 'https://chart.googleapis.com/chart?chst=d_bubble_icon_text_small&chld=taxi|bb|' + hs.Placa + '|00FF00|FFFFFF';
            }

            if (hs.DState === 4) {
                estadoUrl = 'http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=' + hs.Placa + '|FF0000|FFFFFF';
            }


            var myIcon = L.icon({
                iconUrl: estadoUrl,
            });


            var markerDriver = new L.marker([hs.Latitud, hs.Longitud], { DeviceId: hs.DeviceId, title: hs.DriverName });

            var PIcon = L.icon({
                iconUrl: 'http://maps.gstatic.com/intl/de_de/mapfiles/ms/micons/red-pushpin.png'
            });


            var markerPasajero = new L.marker([Destino.Latitud, Destino.Longitud], { icon: PIcon, title: hs.Name });


            map.addLayer(markerPasajero);
            map.addLayer(markerDriver);
            map.setView([hs.Latitud, hs.Longitud], 19, { animation: true });


        }

        function GetTarifa(distancia, tiempo, origen, destino, aplicaBaderazo) {

            var FCong = $scope.getFCong(distancia, tiempo);

            var tempBanderazo = 0;
            if (aplicaBaderazo) {
                tempBanderazo = Banderazo;
            }

            var tarifa = parseFloat(tempBanderazo) + parseFloat(((CostoKm * (parseFloat(1) + parseFloat(FCal))) * (parseFloat(1) + parseFloat(FCong)) * (distancia / 1000))) + parseFloat($scope.getRecargos(origen, destino));
            if (tarifa < CarreraMinima) {
                tarifa = CarreraMinima;
                tarifa = RoundValues(tarifa);
            }

            $scope.TotalCarrera = new Intl.NumberFormat().format(RoundValues(tarifa));
        }

        $scope.getFCong = function (distancia, tiempo) {

            var Vs = (distancia / (tiempo == 0 ? 1 : tiempo)) * 3.6;

            if (Vs >= Vf1) {
                return 0;
            }
            else if (Vs >= Vc && Vs < Vf1) {
                return ((Vf1 - Vs) / Vf1) * b1;
            }
            else if (Vs < Vc) {
                return (((Vf1 - Vs) / Vf1) * b2) + c;
            }
            else {
                return 0;
            }

        };

        $scope.getRecargos = function (origen, destino) {
            var recNocturno = false;

            var totalRecargos = 0;

            var OnlyDate = new Date();
            var WeekName = OnlyDate.toString().split(" ")[0];

            var dd = OnlyDate.getDate();
            var mm = OnlyDate.getMonth() + 1;
            var yyyy = OnlyDate.getFullYear();

            if (dd < 10) {
                dd = '0' + dd;
            }
            if (mm < 10) {
                mm = '0' + mm;
            }

            FormatDate = yyyy + '-' + mm + '-' + dd;
            FormatDateHour = yyyy + '-' + mm + '-' + dd + " " + OnlyDate.getHours() + ":" + OnlyDate.getMinutes() + ":" + OnlyDate.getSeconds();


            if (WeekName == "Sun") {
                totalRecargos += RecargosNocturno;
                recNocturno = true;
            }


            //RECARGO FESTIVO
            if (!recNocturno) {
                if (Isfestivo(FormatDate)) {
                    totalRecargos += RecargosNocturno;
                    recNocturno = true;
                }
            }

            if (!recNocturno) {
                //RECARGO NOCTURNO
                var fechaRango = GetFirtsFechaFestivo();

                if (fechaRango != null) {
                    var Fecha1 = FormatDate + " " + fechaRango.horaInicio;
                    var Fecha2 = FormatDate + " " + fechaRango.horaFinal;
                    if (FormatDateHour >= Fecha1 || FormatDateHour <= Fecha2) {
                        totalRecargos += RecargosNocturno;
                        recNocturno = true;
                    }
                }
            }

            //RECARGO AEREOPUERTO
            if (IsCercaAereopuerto(origen, destino)) {
                totalRecargos += RecargoAereopuerto;
                recAreopuerto = true;
            }

            return totalRecargos;
        };


        function GetFirtsFechaFestivo() {
            var horaInicio = 0;
            var horaFinal = 0;
            if ($scope.ListConfig.ParametriaFestivos.length > 0) {
                var firts = $scope.ListConfig.ParametriaFestivos[0];
                horaInicio = firts.HoraInicio;
                horaFinal = firts.HoraFIn;

            }
            return { horaInicio, horaFinal };
        }


        function Isfestivo(fechaActual) {
            var ban = false;
            if ($scope.ListConfig.ParametriaFestivos != null) {
                for (var i = 0; i < $scope.ListConfig.ParametriaFestivos.length; i++) {
                    var obj = $scope.ListConfig.ParametriaFestivos[i];
                    var fechaFestivo = obj.FechaFestivo.split("T")[0];

                    if (fechaFestivo == fechaActual) {
                        ban = true;
                        break;
                    }
                }
            }
            return ban;
        }


        function IsCercaAereopuerto(origen, destino) {

            var lat1 = origen.split(',')[0];
            var lon1 = origen.split(',')[1];

            var Arlt = 4.697632;
            var Arln = -74.142020;

            // generally used geo measurement function 
            var R = 6378.137;
            // Radius of earth in KM
            var dLat = Arlt * Math.PI / 180 - lat1 * Math.PI / 180;
            var dLon = Arln * Math.PI / 180 - lon1 * Math.PI / 180;
            var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.cos(lat1 * Math.PI / 180) * Math.cos(Arlt * Math.PI / 180) * Math.sin(dLon / 2) * Math.sin(dLon / 2);
            var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
            var d = R * c;
            var res1 = d * 1000; // meters



            var PArlt = 4.693296;
            var PArln = -74.134869;

            // generally used geo measurement function 
            R = 6378.137;
            // Radius of earth in KM
            dLat = PArlt * Math.PI / 180 - lat1 * Math.PI / 180;
            dLon = PArln * Math.PI / 180 - lon1 * Math.PI / 180;
            a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.cos(lat1 * Math.PI / 180) * Math.cos(PArlt * Math.PI / 180) * Math.sin(dLon / 2) * Math.sin(dLon / 2);
            c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
            d = R * c;
            res2 = d * 1000; // meters


            var lat11 = destino.split(',')[0];
            var lon11 = destino.split(',')[1];

            // generally used geo measurement function 
            R = 6378.137;
            // Radius of earth in KM
            dLat = Arlt * Math.PI / 180 - lat11 * Math.PI / 180;
            dLon = Arln * Math.PI / 180 - lon11 * Math.PI / 180;
            a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.cos(lat11 * Math.PI / 180) * Math.cos(Arlt * Math.PI / 180) * Math.sin(dLon / 2) * Math.sin(dLon / 2);
            c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
            d = R * c;
            res3 = d * 1000; // meters


            R = 6378.137;
            // Radius of earth in KM
            dLat = PArlt * Math.PI / 180 - lat11 * Math.PI / 180;
            dLon = PArln * Math.PI / 180 - lon11 * Math.PI / 180;
            a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.cos(lat11 * Math.PI / 180) * Math.cos(PArlt * Math.PI / 180) * Math.sin(dLon / 2) * Math.sin(dLon / 2);
            c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
            d = R * c;
            var res4 = d * 1000; // meters



            var distancia = 0;

            if (res1 <= DistanciaLimite) { return true; }

            else if (res2 <= DistanciaLimite) { return true; }

            else if (res3 <= DistanciaLimite) { return true; }

            else if (res4 <= DistanciaLimite) { return true; }

            else { return false; }
        }


        function RoundValues(valor) {
            var data = valor / 100;
            var newValor = Math.round(data);
            return newValor * 100;
        }

        $scope.saveService = function () {
            try {
                console.log($scope.TotalKm);
                var res = DispatchServics.saveService($scope.Info.Id, $scope.IdDriver, $scope.IdFixedSpot, $scope.Placa, $scope.Movil, $scope.TotalMin.replace(' Min', ''), $scope.TotalKm.replace(' km', ''), $scope.TotalCarrera.replace('.', ',')).then(function (pl) {

                    if (pl.data.StatusCode == 200) {
                        $scope.ServiceCode = pl.data.Code;
                        $scope.ServiceMovil = $scope.Movil;
                        $scope.ServicePlate = $scope.Placa;
                        $scope.ServiceDate = pl.data.Date;
                        $scope.ServiceTime = pl.data.Time;
                        $scope.ServiceDriver = $scope.Conductor;
                        $scope.ServiceEndAddress = $scope.DireccionDestino;
                        $scope.ServiceCost = $scope.TotalCarrera;
                        $scope.ServiceUser = '';
                        $scope.ServiceInitAddress = $scope.Info.Address;
                        return imprimir();
                    }
                },
                    function (errorPl) {
                        growl.error(errorPl.data, { title: 'Error!' });
                    });
            } catch (e) {
                console.log(e);
            }
        };

        function imprimir() {

            getListServicesFixed();

            var objeto = document.getElementById('table2export');  //obtenemos el objeto a imprimir
            var ventana = window.open("", "_blank", ""); //abrimos una ventana vacía nueva
            ventana.document.write('<html>');
            ventana.document.write('<head><title>TICKET SERVICIO</title><link href="../css/Utilidades.css" rel="stylesheet" /></head>');
            ventana.document.write('<body>');
            ventana.document.write(objeto.outerHTML.replace(/##ServiceCode/g, $scope.ServiceCode)
                .replace(/##ServiceMovil/g, $scope.ServiceMovil).replace(/##ServicePlate/g, $scope.ServicePlate)
                .replace(/##ServiceDate/g, $scope.ServiceDate).replace(/##ServiceTime/g, $scope.ServiceTime)
                .replace(/##ServiceDriver/g, $scope.ServiceDriver).replace(/##ServiceEndAddress/g, $scope.ServiceEndAddress)
                .replace(/##ServiceCost/g, $scope.ServiceCost).replace(/##ServiceUser/g, $scope.ServiceUser)
                .replace(/##ServiceInitAddress/g, $scope.ServiceInitAddress));
            ventana.document.write('</body>');
            ventana.document.write('</html>');
            ventana.document.close();  //cerramos el documento

            setTimeout(function () {
                ventana.print();  //imprimimos la ventana
                ventana.close();  //cerramos la ventana
            }, 100);

        }

        $("#Placa").on("keydown", function (event) {
            if (event.which == 9) {
                $("#divMovil").focus();
            }
        });

        $scope.getInfoDriver = function () {
            try {
                if ($scope.Placa == undefined || $scope.Placa == '' || $scope.Placa.length < 6)
                    return growl.info('No ha ingresado una placa válida.', { title: 'Info!' });
                var res = DispatchServics.getInfoDriver($scope.Placa).then(function (pl) {
                    $scope.listDrivers = pl.data;
                    if ($scope.listDrivers.length == 0) {
                        growl.info('No hay conductores asociados a esta placa.', { title: 'Info!' });
                    }
                    else if ($scope.listDrivers.length == 1) {
                        $scope.Movil = $scope.listDrivers[0].Codigo;
                        $scope.Conductor = $scope.listDrivers[0].Name;
                        $scope.IdDriver = $scope.listDrivers[0].Id;
                        $("#getservice").removeAttr('disabled');
                    }
                    else {
                        $("#listDriversModal").show();
                    }
                },
                    function (errorPl) {
                        growl.error(errorPl.data, { title: 'Error!' });
                    });

            } catch (e) {
                console.log(e);
            }
        };

        $scope.ModalHideList = function () {
            $("#listDriversModal").hide();
        };

        $scope.setInfoDriver = function (ind) {
            $scope.Movil = $scope.listDrivers[ind].Codigo;
            $scope.Conductor = $scope.listDrivers[ind].Name;
            $scope.IdDriver = $scope.listDrivers[ind].Id;
            $("#listDriversModal").hide();
            $("#getservice").removeAttr('disabled');
        };


    }])
    .controller('deliverydispatcherCtrl', ['$scope', '$http', '$location', '$interval', 'growl', 'DispatchServics', function ($scope, $http, $location, $interval, growl, DispatchServics) {


        $scope.Phone = '';
        $scope.DeliveryType = "0";
        $scope.listDeliveryTypes = [];
        $scope.listDriversDelivery = [];
        $scope.isVisibleSecond = false;
        $scope.isVisibleThird = false;
        $scope.isVisibleFirst = true;
        getDeliveryTypes();
        $scope.conteo = 0;
        $scope.Endconteo = 0;
        $scope.conteoS = 0;
        $scope.conteoT = 0;
        $scope.isVisibleAddressAd = false;
        $scope.CityName = '';
        $scope.OpInfo = JSON.parse(localStorage.getItem("_Op"));
        $scope.CityName = $scope.OpInfo.City;
        $scope.IdCity = $scope.OpInfo.IdCity;
        getDeliveryServices();
        $scope.listPublicServices = [];
        $scope.DetailsServices = [];
        var geocoder = new google.maps.Geocoder();

        var InitLatutudM1 = 0;
        var InitLongitudM1 = 0;

        var InitLatutudM2 = 0;
        var InitLongitudM2 = 0;

        var InitLatutudM3 = 0;
        var InitLongitudM3 = 0;

        $scope.showTab1 = function () {
            $('#tab1').toggleClass('active');
            $('#tab1').show();
            $('#tab2').hide();
            $('#tab3').hide();
        };

        $scope.showTab2 = function () {
            $('#tab2').toggleClass('active');
            $('#tab2').show();
            $('#tab1').hide();
            $('#tab3').hide();
        };

        $scope.showTab3 = function () {
            $('#tab3').toggleClass('active');
            $('#tab3').show();
            $('#tab1').hide();
            $('#tab2').hide();
        };

        $scope.showTab1();

        function getDeliveryServices() {
            var res = DispatchServics.getDeliveryServices().then(function (pl) {
                var data = pl.data;
                $scope.listPublicServices = [];
                $scope.listPublicServicesPositives = [];
                $scope.listPublicServicesReserves = [];

                $.each(data, function (key, value) {
                    if (value.State === 0 || value.State === 1 || value.State === 2 || value.State === 3 || value.State === 4) {
                        if (!value.IsPositive) {
                            $scope.listPublicServices.push(value);
                        }
                    }
                    if (value.IsPositive) {
                        $scope.listPublicServicesPositives.push(value);
                    }

                    if (value.State === 5) {
                        $scope.listPublicServicesReserves.push(value);
                    }
                });

                if ($scope.Servicio != null) {
                    $.each(data, function (key, value) {
                        if ($scope.Servicio.Id == value.Id) {
                            $scope.ModalTrakingDriverRefresh(value);
                        }
                    });
                }

            }, function (errorPl) {
                growl.error(errorPl.data, { title: 'Error!' });
                $scope.loggedIn = false;
                localStorage.setItem("_LoggedIn", $scope.loggedIn);
                window.location = '#/signin';
            });
        }

        var styles = [
            {
                "stylers": [
                    { "invert_lightness": true },
                    { "saturation": -100 },
                    { "lightness": -5 }
                ]
            }
        ];

        $scope.Td1s = {
            model: null,
            availableOptions: [
                { id: 'CL', name: 'CL' },
                { id: 'CRA', name: 'CRA' },
                { id: 'AV', name: 'AV' },
                { id: 'AC', name: 'AC' },
                { id: 'AK', name: 'AK' },
                { id: 'AP', name: 'AP' },
                { id: 'DG', name: 'DG' },
                { id: 'MZ', name: 'MZ' },
                { id: 'Tv', name: 'Tv' },
            ],
            selectedOption: { id: 'CL', name: 'CL' }
        };
        $scope.Td3s = {
            model: null,
            availableOptions: [
                { id: 'A', name: 'A' },
                { id: 'B', name: 'B' },
                { id: 'C', name: 'C' },
                { id: 'D', name: 'D' },
                { id: 'E', name: 'E' },
                { id: 'F', name: 'F' },
                { id: 'G', name: 'G' },
                { id: 'H', name: 'H' },
                { id: 'I', name: 'I' },
                { id: 'J', name: 'J' },
                { id: 'K', name: 'K' },
                { id: 'L', name: 'L' },
                { id: 'M', name: 'M' },
                { id: 'N', name: 'N' },
                { id: 'O', name: 'O' },
                { id: 'P', name: 'P' },
                { id: 'Q', name: 'Q' },
                { id: 'R', name: 'R' },
                { id: 'S', name: 'S' },
                { id: 'T', name: 'T' },
                { id: 'U', name: 'U' },
                { id: 'V', name: 'V' },
                { id: 'W', name: 'W' },
                { id: 'X', name: 'X' },
                { id: 'Y', name: 'Y' },
                { id: 'Z', name: 'Z' },
            ],
            selectedOption: { id: 'A', name: 'A' }
        };
        $scope.Td4s = {
            model: null,
            availableOptions: [
                { id: 'BIS', name: 'BIS' },
                { id: 'BIS A', name: 'BIS A' },
                { id: 'BIS B', name: 'BIS B' },
                { id: 'BIS C', name: 'BIS C' },
                { id: 'BIS D', name: 'BIS D' },
                { id: 'BIS E', name: 'BIS E' },
            ],
            selectedOption: { id: 'BIS A', name: 'BIS A' }
        };
        $scope.Td5s = {
            model: null,
            availableOptions: [
                { id: 'NORTE', name: 'NORTE' },
                { id: 'SUR', name: 'SUR' },
                { id: 'ESTE', name: 'ESTE' },
                { id: 'OESTE', name: 'OESTE' },

            ]

        };
        var markers = [];
        var circle;
        var clickMarker = null;
        $scope.Td1 = "0";
        $scope.Td3 = "0";
        $scope.Td4 = "0";
        $scope.Td5 = "0";
        $scope.Td6 = "0";
        $scope.Td7 = "0";
        $scope.Td8 = "0";
        $scope.EndTd1 = "0";
        $scope.EndTd3 = "0";
        $scope.EndTd4 = "0";
        $scope.EndTd5 = "0";
        $scope.EndTd6 = "0";
        $scope.EndTd7 = "0";
        $scope.EndTd8 = "0";
        $scope.disabledP1 = true;
        $scope.disabledS1 = true;
        $scope.disabledT1 = true;
        $scope.isOpenFirst = false;
        $scope.isOpenSecond = false;
        $scope.isOpenThird = false;
        $scope.listAddresses = [];
        $scope.listInfo = [];
        $scope.disabledAddP1 = false;
        $scope.disabledAddS1 = false;
        $scope.disabledAddT1 = false;
        $scope.selectedType = '0';
        $scope.selectedTypeS = '0';
        $scope.selectedTypeT = '0';
        var mapOpen;

        $scope.isActive = function (viewLocation) {
            var active = (viewLocation === $location.path());
            return active;
        };

        function MyIntervalo() {
            if ($scope.isActive('/deliverydispatch')) {
                getDeliveryServices();
            }
        }


        function getDeliveryTypes() {
            try {
                var res = DispatchServics.getDeliveryTypes().then(function (pl) {
                    $scope.listDeliveryTypes = pl.data;
                    $interval(MyIntervalo, 6000);
                }, function (errorPl) {
                    growl.error(errorPl.data, { title: 'Error!' });
                });
            } catch (e) {
                return growl.error(e.toString(), { title: 'Error!' });
            }
        }

        $scope.ModalTrakingDriver = function (hs) {
            $scope.Servicio = hs;
            console.log($scope.Servicio);
            $("#myTraking").show();
            $scope.setDivMapa('Trakingmap');
            setMarkersTraking(mapOpen, hs);
        };

        $scope.ModalTrakingDriverHide = function () {
            $scope.Servicio = null;
            $("#myTraking").hide();
        };

        $scope.ModalGMessageShow = function () {
            $("#ModalGMessage").show();
        };

        $scope.ModalGMessageHide = function () {
            $("#ModalGMessage").hide();
        };

        $scope.enviarAllNotification = function () {
            if ($scope.AllPlaca == null) $scope.AllPlaca = "";


            var res = DispatchServics.EnviarNotification($scope.AllPlaca, $scope.Msg).then(function (pl) {
                var data = pl.data;
                if (data == 1) {
                    growl.info('ENVIADO', { title: 'Info!' });
                }
            }, function (errorPl) {
                growl.error(errorPl.data, { title: 'Error!' });
            });

            $scope.ModalGMessageHide();
        };

        $scope.ModalAllTrakingDriverShow = function () {
            $scope.IsTrakingDriver = true;
            $scope.setDivMapa('AllTrakingmap');
            $scope.setAllDriverLocationsByIdOp(mapOpen);

        };

        $scope.setAllDriverLocationsByIdOp = function (map) {
            deleteMarkers();
            var res = DispatchServics.setAllDriverLocationsByIdOp().then(function (pl) {
                var data = pl.data;
                $("#myAllTraking").show();

                if (data.length == 0) {
                    growl.warning('No hay  Registro!', { title: 'Warning!' });
                    return;
                }

                $scope.CountDriver = data.length;
                $.each(data, function (key, value) {
                    setMarkersTaxi(map, value);
                });

                mapOpen.invalidateSize(true);
            }, function (errorPl) {
                growl.error(errorPl.data, { title: 'Error!' });
            });
        };


        function setMarkersTaxi(map, taxi) {
            var Indexmarker = -1;
            for (i = 0; i < markers.length; i++) {
                if (markers[i].options.DeviceId === taxi.DeviceId) {
                    map.removeLayer(markers[i]);
                    Indexmarker = i;
                    break;
                }
            }
            var estadoUrl = 'http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=pin_sleft|' + taxi.Placa + '|FF0000|FFFFFF';// 'http://labs.google.com/ridefinder/images/mm_20_yellow.png';

            if (taxi.State === 0) {
                estadoUrl = 'https://chart.googleapis.com/chart?chst=d_bubble_icon_text_small&chld=taxi|bb|' + taxi.Placa + '|FFFF00|908D8D';
            }
            if (taxi.State === 1) {
                estadoUrl = 'https://chart.googleapis.com/chart?chst=d_bubble_icon_text_small&chld=taxi|bb|' + taxi.Placa + '|0000FF|FFFFFF';
            }
            if (taxi.State === 3) {
                estadoUrl = 'https://chart.googleapis.com/chart?chst=d_bubble_icon_text_small&chld=taxi|bb|' + taxi.Placa + '|FF0000|FFFFFF';
            }
            if (taxi.State === 2) {
                estadoUrl = 'https://chart.googleapis.com/chart?chst=d_bubble_icon_text_small&chld=taxi|bb|' + taxi.Placa + '|00FF00|FFFFFF';
            }

            if (taxi.State === 4) {
                estadoUrl = 'http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=' + taxi.Placa + '|FF0000|FFFFFF';
            }

            var myIcon = L.icon({
                iconUrl: estadoUrl,
            });

            var markerDriver = new L.marker([taxi.Latitud, taxi.Longitud], { DeviceId: taxi.DeviceId, title: taxi.DriverName, icon: myIcon });

            if (Indexmarker !== -1) {
                markers[Indexmarker] = markerDriver;
            }
            else {
                markers.push(markerDriver);
            }
            if (taxi.Placa == $scope.PlacaTraking) {
                map.setView([taxi.Latitud, taxi.Longitud], 16, { animation: true });

            } else if ($scope.PlacaTraking == '') {
                map.setZoom(11);
            }
            map.addLayer(markerDriver);
        }

        function deleteMarkers() {
            for (var i = 0; i < markers.length; i++) {
                mapOpen.removeLayer(markers[i]);
            }
            markers = [];
        }

        $scope.BuscarPlaca = function () {
            $scope.setAllDriverLocationsByIdOp(mapOpen);
        };

        $scope.ModalAllTrakingDriverHide = function () {
            $scope.IsTrakingDriver = false;
            $("#myAllTraking").hide();
        };

        $scope.setDivMapa = function (value) {
            if (mapOpen != null) mapOpen.remove();
            mapOpen = L.map(document.getElementById(value)).setView([localStorage.getItem("LatitudCiti"), localStorage.getItem("LongitudCiti")], 14);

            L.tileLayer.provider('OpenStreetMap.DE').addTo(mapOpen);
        };

        /// Recorido del veiculos en direccion al  pasajero
        function setMarkersTraking(map, hs) {

            var markerDriver = new L.marker([hs.Latitud, hs.Longitud], { DeviceId: hs.DeviceId, title: hs.DriverName });

            var PIcon = L.icon({
                iconUrl: 'http://maps.gstatic.com/intl/de_de/mapfiles/ms/micons/red-pushpin.png'
            });

            var markerPasajero = new L.marker([hs.sLatitud, hs.sLongitud], { icon: PIcon, title: hs.Name });

            map.addLayer(markerPasajero);
            map.addLayer(markerDriver);
            map.setView([hs.Latitud, hs.Longitud], 19, { animation: true });


      

        }

        $scope.ReasignarServicio = function (Ids) {
            var placa = prompt("DIGITE LA PLACA O EL MOVIL", "");
            if (placa != null) {
                var res = DispatchServics.reasignarServicioJosb(Ids, placa).then(function (pl) {
                    getDeliveryServices();
                }, function (errorPl) {
                    growl.error(errorPl.data, { title: 'Error!' });
                });
            }
        };

        $scope.EliminarServices = function (Id) {

            if (confirm("ELIMINAR EL SERVICIO")) {
                var res = DispatchServics.EliminarServices(Id).then(function (pl) {
                    var data = pl.data;
                    if (data >= 1) {
                        growl.info("SERVICIO ELIMINADO", { title: 'Info!' });
                        getDeliveryServices();
                    }
                }, function (errorPl) {
                    growl.error(errorPl.data, { title: 'Error!' });
                });

            }
        };

        $scope.setNoAtendido = function (Id) {
            if (confirm("¿NO SE HA ATENDIDO EL SERVICIO?")) {
                var res = DispatchServics.setNoAtendido(Id).then(function (pl) {
                    var data = pl.data;
                    if (data >= 1) {
                        growl.success("SERVICIO CAMBIADO DE ESTADO CORRECTAMENTE", { title: 'OK!' });
                        getDeliveryServices();
                    }
                }, function (errorPl) {
                    growl.error(errorPl.data, { title: 'Error!' });
                });
            }
        };

        $scope.getDetailsDeliveryServices = function (item) {
            try {
                var res = DispatchServics.getDetailsDeliveryServices(item.Id).then(function (pl) {
                    if (pl.data.length > 0) {
                        $scope.DetailsServices = pl.data;
                        $("#divDetails").show();
                    }
                }, function (errorPl) {
                    return growl.error(errorPl.data, { title: 'Error!' });
                });
            } catch (e) {
                return growl.error(e.toString(), { title: 'Error!' });
            }
        };

        $scope.closeModalDetails = function () {
            $("#divDetails").hide();
            $scope.DetailsServices = [];
        };

        $scope.closeModalAddress = function () {
            $("#myEndAddAddress").hide();
        };

        function getInfoNameNumber() {
            try {
                var res = DispatchServics.getInfoNameNumber($("#namenumber").val(), $scope.IdCity).then(function (pl) {
                    $scope.listInfo = pl.data;
                    $(".divInfoP1").css("display", "block")
                }, function (errorPl) {
                    return growl.error(errorPl.data, { title: 'Error!' });
                });
            } catch (e) {
                return growl.error(e, { title: 'Error!' });
            }
        }

        function getInfoNameNumberFind() {
            try {
                var res = DispatchServics.getInfoNameNumber($("#namenumberFind").val(), $scope.IdCity).then(function (pl) {
                    $scope.listInfo = pl.data;
                    $(".divInfoP1Find").css("display", "block")
                }, function (errorPl) {
                    return growl.error(errorPl.data, { title: 'Error!' });
                });
            } catch (e) {
                return growl.error(e, { title: 'Error!' });
            }
        }

        function getInfoNameNumberS() {
            try {
                var res = DispatchServics.getInfoNameNumber($("#namenumberS").val(), $scope.IdCity).then(function (pl) {
                    $scope.listInfoS = pl.data;
                    $(".divInfoS1").css("display", "block")
                }, function (errorPl) {
                    return growl.error(errorPl.data, { title: 'Error!' });
                });
            } catch (e) {
                return growl.error(e, { title: 'Error!' });
            }
        }

        function getInfoNameNumberT() {
            try {
                var res = DispatchServics.getInfoNameNumber($("#namenumberT").val(), $scope.IdCity).then(function (pl) {
                    $scope.listInfoT = pl.data;
                    $(".divInfoT1").css("display", "block")
                }, function (errorPl) {
                    return growl.error(errorPl.data, { title: 'Error!' });
                });
            } catch (e) {
                return growl.error(e, { title: 'Error!' });
            }
        }

        var input = document.getElementById("namenumber"), intervalo;
        var inputFind = document.getElementById("namenumberFind"), intervalo;
        var inputS = document.getElementById("namenumberS"), intervalo;
        var inputT = document.getElementById("namenumberT"), intervalo;

        input.addEventListener("keyup", function (e) {
            var key = e.keyCode;
            $listItems = $(".np");
            if ($("#namenumber").val().length >= 3) {
                clearInterval(intervalo); //Al escribir, limpio el intervalo
                intervalo = setInterval(function () { //Y vuelve a iniciar
                    getInfoNameNumber();
                    clearInterval(intervalo); //Limpio el intervalo
                }, 200);
            }
            else {
                $(".divInfoP1").css("display", "none")
            }
        }, false);

        $("#namenumber").focusout(function () {
            setTimeout(function () {
                $(".divInfoP1").css("display", "none");
            }, 200);
        });

        $("#namenumber").click(function () {
            if ($("#namenumber").val().length >= 3) {
                $(".divInfoP1").css("display", "block");
            }
        });

        inputFind.addEventListener("keyup", function (e) {
            console.log($("#namenumberFind").val().length);
            var key = e.keyCode;
            $listItems = $(".npFind");
            if ($("#namenumberFind").val().length >= 3) {
                clearInterval(intervalo); //Al escribir, limpio el intervalo
                intervalo = setInterval(function () { //Y vuelve a iniciar
                    getInfoNameNumberFind();
                    clearInterval(intervalo); //Limpio el intervalo
                }, 200);
            }
            else {
                $(".divInfoP1Find").css("display", "none")
            }
        }, false);

        $("#namenumberFind").focusout(function () {
            setTimeout(function () {
                $(".divInfoP1Find").css("display", "none")
            }, 200);
        });

        $("#namenumberFind").click(function () {
            if ($("#namenumberFind").val().length >= 3) {
                $(".divInfoP1Find").css("display", "block");
            }
        });

        inputS.addEventListener("keyup", function (e) {
            var key = e.keyCode;
            $listItems = $(".np");
            if ($("#namenumberS").val().length >= 3) {
                try {
                    clearInterval(intervalo); //Al escribir, limpio el intervalo
                    intervalo = setInterval(function () { //Y vuelve a iniciar
                        getInfoNameNumberS();
                        clearInterval(intervalo); //Limpio el intervalo
                    }, 200);
                } catch (e) {
                    return growl.error(e, { title: 'Error!' });
                }
            }
            else {
                $(".divInfoS1").css("display", "none");
            }
        }, false);

        $("#namenumberS").focusout(function () {
            setTimeout(function () {
                $(".divInfoS1").css("display", "none");
            }, 200);
        });

        $("#namenumberS").click(function () {
            if ($("#namenumberS").val().length >= 3) {
                $(".divInfoS1").css("display", "block");
            }
        });

        inputT.addEventListener("keyup", function (e) {
            var key = e.keyCode;
            $listItems = $(".np");
            if ($("#namenumberT").val().length >= 3) {
                try {
                    clearInterval(intervalo); //Al escribir, limpio el intervalo
                    intervalo = setInterval(function () { //Y vuelve a iniciar
                        getInfoNameNumberT();
                        clearInterval(intervalo); //Limpio el intervalo
                    }, 200);
                } catch (e) {
                    return growl.error(e, { title: 'Error!' });
                }
            }
            else {
                $(".divInfoT1").css("display", "none");
            }
        }, false);

        $("#namenumberT").focusout(function () {
            setTimeout(function () {
                $(".divInfoT1").css("display", "none");
            }, 200);
        });

        $("#namenumberT").click(function () {
            if ($("#namenumberT").val().length >= 3) {
                $(".divInfoT1").css("display", "block");
            }
        });

        $scope.getDato = function (module, item) {

            $scope[("NameCel" + module)] = item.Phone + "-" + item.Name;
            $scope[("completeAddress" + module)] = item.Address;

            if (module == "P1") {
                InitLatutudM1 = item.Latitud;
                InitLongitudM1 = item.Longitud;
            } else if (module == "S1") {
                InitLatutudM2 = item.Latitud;
                InitLongitudM2 = item.Longitud;
            } else if (module == "T1") {
                InitLatutudM3 = item.Latitud;
                InitLongitudM3 = item.Longitud;
            }

            $scope[("disabled" + module)] = false;

            setTimeout(function () {
                $(".divInfo" + module).css("display", "none");
            }, 50);
        };

        // Esta función obtiene el dato seleccionado de la lista, y debe estampar en el respectivo campo de dirección, la que se seleccionó nueva.
        $scope.getDatoFind = function (module, item) {
            console.log(module);
            console.log(item.Address);

            $scope[("NameCel" + module + "Find")] = item.Phone + "-" + item.Name;
            $scope[("completeAddress" + module)] = item.Address;

            if (module == "P1") {
                InitLatutudM1 = item.Latitud;
                InitLongitudM1 = item.Longitud;
            } else if (module == "S1") {
                InitLatutudM2 = item.Latitud;
                InitLongitudM2 = item.Longitud;
            } else if (module == "T1") {
                InitLatutudM3 = item.Latitud;
                InitLongitudM3 = item.Longitud;
            }

            $scope[("disabled" + module)] = false;

            submitQuery2(item.Address);

            setTimeout(function () {
                $(".divInfo" + module).css("display", "none");
            }, 50);
        };


        $scope.openInfoModal = function () {
            $scope.isVisibleFirst = true;
            $scope.isOpenFirst = true;
            $(".prb").toggle();
        };

        $scope.CloseModal1 = function () {
            $("#modalInfo").hide();
            var elemento = document.getElementById("modalInfo");
            elemento.style.width = "500px";
            $scope.isVisibleThird = false;
            $scope.isVisibleSecond = false;
            $scope.isOpenThird = false;
            $scope.isOpenSecond = false;
            elemento.style.left = "50%";
        };

        $scope.openInfoModal1 = function () {
            if ($scope.isOpenSecond && !$scope.isOpenThird) {
                var elem = document.getElementById("modalInfo");
                var elem1 = document.getElementById("second");
                elem.style.width = "1500px";
                elem.style.left = "25%";
                elem.style.display = "flex";
                elem1.style.marginTop = "20px";
                $scope.isVisibleThird = true;
                $scope.isVisibleSecond = true;
                $scope.isOpenThird = true;
                $scope.isOpenSecond = true;
            }
            else if (!$scope.isOpenSecond && $scope.isOpenThird) {
                elem = document.getElementById("modalInfo");
                elem1 = document.getElementById("third");
                elem.style.width = "1500px";
                elem.style.left = "25%";
                elem.style.display = "flex";
                elem1.style.marginTop = "20px";
                $scope.isVisibleThird = true;
                $scope.isVisibleSecond = true;
                $scope.isOpenThird = true;
                $scope.isOpenSecond = true;
            }
            else if (!$scope.isOpenSecond && !$scope.isOpenThird) {
                elem = document.getElementById("modalInfo");
                elem1 = document.getElementById("second");
                elem.style.width = "1000px";
                elem.style.left = "40%";
                elem.style.display = "flex";
                elem1.style.marginTop = "20px";
                $scope.isVisibleSecond = true;
                $scope.isOpenSecond = true;
                $scope.isVisibleThird = false;
                $scope.isOpenThird = false;
            }
        };

        $scope.showAddress = function (module) {
            $scope.moduleName = module;

            $scope.Td1 = '0';
            $scope.st1 = '';
            $scope.Td3 = '0';
            $scope.Td4 = '0';
            $scope.Td7 = '0';
            $scope.Td8 = '0';
            $scope.st2 = '';
            $scope.Td5 = '0';
            $scope.Td6 = '0';
            $scope.st3 = '';
            $scope.NameMod = '';
            $scope.CelMod = '';
            $scope.eLatitud = undefined;
            $scope.eLongitud = undefined;

            var t = module.replace(/1/g, '').replace(/2/g, '').replace(/3/g, '');
            switch (t) {
                case 'P':
                    $scope.moduleAddress = 1;
                    break;
                case 'S':
                    $scope.moduleAddress = 2;
                    break;
                case 'T':
                    $scope.moduleAddress = 3;
                    break;
            }
            $("#myAddressAdd").show();
            var popup = L.popup();
            $scope.setDivMapa('mapdelivery');
            mapOpen.on('click', function (e) {
                popup
                    .setLatLng(e.latlng)
                    .setContent("Este es el punto Inicial " + e.latlng.toString() + "\nde la direccion")
                    .openOn(mapOpen);
                setMarkersDireccion(mapOpen, e.latlng.lat, e.latlng.lng);
            });
        };

        $scope.showAddressFind = function (module) {
            $scope.moduleName = module;

            $scope.Td1 = '0';
            $scope.st1 = '';
            $scope.Td3 = '0';
            $scope.Td4 = '0';
            $scope.Td7 = '0';
            $scope.Td8 = '0';
            $scope.st2 = '';
            $scope.Td5 = '0';
            $scope.Td6 = '0';
            $scope.st3 = '';
            $scope.NameMod = '';
            $scope.CelMod = '';
            $scope.eLatitud = undefined;
            $scope.eLongitud = undefined;

            var t = module.replace(/1/g, '').replace(/2/g, '').replace(/3/g, '');
            switch (t) {
                case 'P':
                    $scope.moduleAddress = 1;
                    break;
                case 'S':
                    $scope.moduleAddress = 2;
                    break;
                case 'T':
                    $scope.moduleAddress = 3;
                    break;
            }
            $("#myAddressAddFind").show();
            var popup = L.popup();
            $scope.setDivMapa('mapdeliveryFind');
            //mapOpen.on('click', function (e) {
            //    popup
            //        .setLatLng(e.latlng)
            //        .setContent("Este es el punto Inicial " + e.latlng.toString() + "\nde la direccion")
            //        .openOn(mapOpen);
            //    console.log("JAVIER REYES");
            //    console.log(e);
            //    setMarkersDireccion2(mapOpen, e.latlng.lat, e.latlng.lng);
            //});
        };

        $scope.setDivMapa = function (value) {
            if (mapOpen != null) mapOpen.remove();
            mapOpen = L.map(document.getElementById(value)).setView([localStorage.getItem("LatitudCiti"), localStorage.getItem("LongitudCiti")], 14);

            L.tileLayer.provider('OpenStreetMap.DE').addTo(mapOpen);

            //L.tileLayer('https://cartodb-basemaps-{s}.global.ssl.fastly.net/dark_all/{z}/{x}/{y}{r}.png', {
            //    attribution: '&copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a> &copy; <a href="http://cartodb.com/attributions">CartoDB</a>',
            //    subdomains: 'abcd',
            //    maxZoom: 14
            //}).addTo(mapOpen);
        };

        var markerDireccion = undefined;

        function setMarkersDireccion(map, lat, lng) {

            if (markerDireccion != undefined) {
                map.removeLayer(markerDireccion);
            }

            markerDireccion = new L.marker([lat, lng], { title: 'Punto' });


            map.addLayer(markerDireccion);
            map.setView([lat, lng], 8, { animation: true });
            map.setZoom(17);


            if ($scope.completeAddress != null) {

                $scope.eLatitud = lat;
                $scope.eLongitud = lng;
            } else {
                growl.error('Primero digite una direccion\nantes de ubicar una punto', { title: 'Error!' });

            }
        }

        function setMarkersDireccion1(map, lat, lng) {

            if (markerDireccion != undefined) {
                map.removeLayer(markerDireccion);
            }

            markerDireccion = new L.marker([lat, lng], { title: 'Punto' });


            map.addLayer(markerDireccion);
            map.setView([lat, lng], 8, { animation: true });
            map.setZoom(17);

            console.log($scope.completeEndAddress);

            if ($scope.completeEndAddress != null) {

                $scope.dLatitud = lat;
                $scope.dLongitud = lng;
            } else {
                growl.error('Primero digite una direccion\nantes de ubicar una punto', { title: 'Error!' });

            }
        }

        function setMarkersDireccion2(map, lat, lng) {

            if (markerDireccion != undefined) {
                map.removeLayer(markerDireccion);
            }

            markerDireccion = new L.marker([lat, lng], { title: 'Punto' });


            map.addLayer(markerDireccion);
            map.setView([lat, lng], 8, { animation: true });
            map.setZoom(17);

            //if ($scope.completeEndAddress != null) {

            $scope.eLatitud = lat;
            $scope.eLongitud = lng;

            InitLatutudM1 = lat;
            InitLongitudM1 = lng;
            //} else {
            //    growl.error('Primero digite una direccion\nantes de ubicar una punto', { title: 'Error!' });

            //}
        }

        $scope.getImagesService = function (it) {
            $("#urlImg1").attr('src', it.UrlImg1);
            $("#urlImg2").attr('src', it.UrlImg2);
            $("#urlImg3").attr('src', it.UrlImg3);
            $("#urlImg4").attr('src', it.UrlImg4);
        }

        $scope.showEndAddress = function (module) {
            $scope.moduleName = module;
            var t = module.replace(/1/g, '').replace(/2/g, '').replace(/3/g, '');
            var t1 = module.replace(/P/g, '').replace(/S/g, '').replace(/T/g, '');
            switch (t) {
                case 'P':
                    $scope.moduleAddress = 1;
                    break;
                case 'S':
                    $scope.moduleAddress = 2;
                    break;
                case 'T':
                    $scope.moduleAddress = 3;
                    break;
            }
            $("#myEndAddressAdd").show();

            var popup = L.popup();
            $scope.setDivMapa('mapdeliveryDestino');
            mapOpen.on('click', function (e) {
                popup
                    .setLatLng(e.latlng)
                    .setContent("Este es el punto Inicial " + e.latlng.toString() + "\nde la direccion")
                    .openOn(mapOpen);
                setMarkersDireccion(mapOpen, e.latlng.lat, e.latlng.lng);
            });
        };

        // En la dirección del nuevo Search, se debe agregar la Georeferenciación, y ajustar la función para que no se haga por onBlur sino, bloquear botón OK hasta que esté la dirección completa.
        $scope.setAddress = function (module, flg = 0) {

            $scope[("completeAddress" + module)] = ($scope.Td1 === undefined ? "0" : $scope.Td1) + ($scope.st1 === undefined ? "" : $scope.st1) + ($scope.Td3 === "0" ? "" : $scope.Td3) + ($scope.Td8 === "0" ? "" : $scope.Td8) + ($scope.Td4 === "0" ? "" : $scope.Td4) + " #" + ($scope.st2 === undefined ? "" : $scope.st2) + ($scope.Td5 === "0" ? "" : $scope.Td5) + ($scope.Td6 === "0" ? "" : $scope.Td6) + "-" + ($scope.st3 === undefined ? "" : $scope.st3);
            $scope.completeAddress = ($scope.Td1 === undefined ? "0" : $scope.Td1) + ($scope.st1 === undefined ? "" : $scope.st1) + ($scope.Td3 === "0" ? "" : $scope.Td3) + ($scope.Td4 === "0" ? "" : $scope.Td4) + " #" + ($scope.st2 === undefined ? "" : $scope.st2) + ($scope.Td5 === "0" ? "" : $scope.Td5) + ($scope.Td6 === "0" ? "" : $scope.Td6) + "-" + ($scope.st3 === undefined ? "" : $scope.st3);
            console.log($scope.st3);
            if ($scope.st3 != "") {
                submitQuery($scope.completeAddress);
            }
        };

     

        function plotMatchesOnMap(results, reverse) {

            markers = new Array(results.length);
            var resultsListHtml = "";

            for (var i = 0; i < results.length; i++) {
                setMarkersDireccion(mapOpen, results[i].geometry.location.lat(), results[i].geometry.location.lng());
                break;
            }

        }

        function plotMatchesOnMap1(results, reverse) {

            markers = new Array(results.length);
            var resultsListHtml = "";

            for (var i = 0; i < results.length; i++) {
                setMarkersDireccion1(mapOpen, results[i].geometry.location.lat(), results[i].geometry.location.lng());
                break;
            }

        }

        function plotMatchesOnMap2(results, reverse) {

            markers = new Array(results.length);
            var resultsListHtml = "";

            for (var i = 0; i < results.length; i++) {
                setMarkersDireccion2(mapOpen, results[i].geometry.location.lat(), results[i].geometry.location.lng());
                break;
            }

        }

        function resetMap() {

            for (var i in markers) {
                markers[i].setMap(null);
            }
            if (circle != null) {
                circle.setMap(null);
            }
            markers = [];
        }

        $scope.setEndAddress = function (module, flg = 0) {

            $scope[("completeEndAddress" + module)] = ($scope.EndTd1 === undefined ? "0" : $scope.EndTd1) + ($scope.Endst1 === undefined ? "" : $scope.Endst1) + ($scope.EndTd3 === "0" ? "" : $scope.EndTd3) + ($scope.EndTd8 === "0" ? "" : $scope.EndTd8) + ($scope.EndTd4 === "0" ? "" : $scope.EndTd4) + " #" + ($scope.Endst2 === undefined ? "" : $scope.Endst2) + ($scope.EndTd5 === "0" ? "" : $scope.EndTd5) + ($scope.EndTd6 === "0" ? "" : $scope.EndTd6) + "-" + ($scope.Endst3 === undefined ? "" : $scope.Endst3);
            $scope.completeEndAddress = ($scope.EndTd1 === undefined ? "0" : $scope.EndTd1) + ($scope.Endst1 === undefined ? "" : $scope.Endst1) + ($scope.EndTd3 === "0" ? "" : $scope.EndTd3) + ($scope.EndTd4 === "0" ? "" : $scope.EndTd4) + " #" + ($scope.Endst2 === undefined ? "" : $scope.Endst2) + ($scope.EndTd5 === "0" ? "" : $scope.EndTd5) + ($scope.EndTd6 === "0" ? "" : $scope.EndTd6) + "-" + ($scope.Endst3 === undefined ? "" : $scope.Endst3);


            if ($scope.Endst3 != undefined && $scope.Endst3 != "") {
                submitQuery1($scope.completeEndAddress);
            }
        };

        $scope.closemodal = function () {
            $("#myAddressAdd").hide();
        };

        $scope.closemodalFind = function () {
            $("#myAddressAddFind").hide();
        };

        $scope.closeModalEnd = function (type = 0) {

            $scope.EndTd1 = '0';
            $scope.Endst1 = '';
            $scope.EndTd3 = '0';
            $scope.EndTd4 = '0';
            $scope.EndTd7 = '0';
            $scope.EndTd8 = '0';
            $scope.Endst2 = '';
            $scope.EndTd5 = '0';
            $scope.EndTd6 = '0';
            $scope.Endst3 = '';
            $scope.dLatitud = undefined;
            $scope.dLongitud = undefined;
            $("#myEndAddressAdd").hide();
            $scope.completeEndAddress = '';
            $scope.Endconteo = 0;
        };

        $scope.closeModalAddressAdd = function (module, flg = 0) {

            if (flg == 1) {
                $("#myAddressAdd").hide();
            }
            else {
                if ($scope.NameMod === undefined || $scope.CelMod === undefined || $scope.NameMod === '' || $scope.CelMod === '') {
                    $scope.conteo = 0;
                    return growl.error("No ha ingresado Teléfono o Nombre de Usuario.", { title: 'Error!' });
                }

                if ($scope.completeAddress == undefined || $scope.completeAddress == "") {
                    $scope.conteo = 0;
                    return growl.error("No ha ingresado una dirección.", { title: 'Error!' });
                }

                $scope[('disabled' + module)] = false;
                $scope[('NameCel' + module)] = $scope.CelMod + '-' + $scope.NameMod;
                $("#myAddressAdd").hide();
                try {
                    $scope.UserInfo = [];
                    $scope.UserInfo.Phone = $scope.CelMod;
                    $scope.UserInfo.IdCity = createUUID();
                    $scope.UserInfo.Id = createUUID();
                    $scope.UserInfo.Name = $scope.NameMod;
                    $scope.UserInfo.Address = ($scope.Td1 === undefined ? '' : $scope.Td1) + ($scope.st1 === undefined ? '' : $scope.st1) + ($scope.Td3 === '0' ? '' : $scope.Td3) + ($scope.Td8 === '0' ? '' : $scope.Td8) + ($scope.Td4 === '0' ? '' : $scope.Td4) + " #" + ($scope.st2 === undefined ? '' : $scope.st2);
                    $scope.UserInfo.Address = $scope.UserInfo.Address + ($scope.Td5 === '0' ? '' : $scope.Td5) + "-" + ($scope.Td6 === '0' ? '' : $scope.Td6) + ($scope.st3 === undefined ? '' : $scope.st3);
                    $scope.UserInfo.Td1 = ($scope.Td1 === undefined ? '' : $scope.Td1);
                    $scope.UserInfo.Td2 = ($scope.st1 === undefined ? '' : $scope.st1);
                    $scope.UserInfo.Td3 = ($scope.Td3 === '0' ? null : $scope.Td3);
                    $scope.UserInfo.Td4 = ($scope.Td4 === '0' ? null : $scope.Td4);
                    $scope.UserInfo.Td5 = ($scope.Td8 === '0' ? null : $scope.Td8);
                    $scope.UserInfo.Tn1 = ($scope.st2 === undefined ? '' : $scope.st2);
                    $scope.UserInfo.Tn2 = ($scope.Td5 === '0' ? null : $scope.Td5);
                    $scope.UserInfo.Tn3 = ($scope.Td6 === '0' ? null : $scope.Td6);
                    $scope.UserInfo.Tn4 = null;
                    $scope.UserInfo.NumberHouse = ($scope.st3 === undefined ? '' : $scope.st3);
                    $scope.UserInfo.Latitud = $scope.eLatitud;
                    $scope.UserInfo.Longitud = $scope.eLongitud;


                    var res = DispatchServics.setAddress($scope.UserInfo).then(function (pl) {
                        if (pl.data == 1) {
                            growl.success("Dirección agregada correctamente!", { title: 'Ok!' });
                        }
                        else if (pl.data == 0) {
                            growl.info("La dirección ya se encuentra agregada.", { title: 'Info!' });
                        }

                        $scope.Td1 = '0';
                        $scope.st1 = '';
                        $scope.Td3 = '0';
                        $scope.Td4 = '0';
                        $scope.Td7 = '0';
                        $scope.Td8 = '0';
                        $scope.st2 = '';
                        $scope.Td5 = '0';
                        $scope.Td6 = '0';
                        $scope.st3 = '';
                        $scope.NameMod = '';
                        $scope.CelMod = '';
                        $scope.eLatitud = undefined;
                        $scope.eLongitud = undefined;

                    }, function (errorPl) {
                        return growl.error(errorPl.data, { title: 'Error!' });
                    });

                } catch (e) {
                    return growl.error(e.toString(), { title: 'Error!' });
                }
            }
        };

        $scope.addEndAddress = function (module, type = 0) {
            $scope[("isVisibleAddressAdd" + module)] = true;
        };

        function createUUID() {
            var s = [];
            var hexDigits = "0123456789abcdef";
            for (var i = 0; i < 36; i++) {
                s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
            }
            s[14] = "4";  // bits 12-15 of the time_hi_and_version field to 0010
            s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1);  // bits 6-7 of the clock_seq_hi_and_reserved to 01
            s[8] = s[13] = s[18] = s[23] = "-";

            var uuid = s.join("");
            return uuid;
        }

        $scope.openInfoModal1S = function () {
            if ($scope.isOpenFirst && !$scope.isOpenThird) {
                var elem = document.getElementById("modalInfo");
                var elem1 = document.getElementById("third");
                elem.style.width = "1500px";
                elem.style.left = "25%";
                elem.style.display = "flex";
                elem1.style.marginTop = "20px";
                $scope.isVisibleThird = true;
                $scope.isVisibleFirst = true;
                $scope.isOpenThird = true;
                $scope.isOpenFirst = true;
            }
            else if (!$scope.isOpenFirst && $scope.isOpenThird) {
                elem = document.getElementById("modalInfo");
                elem1 = document.getElementById("first");
                elem.style.width = "1500px";
                elem.style.left = "25%";
                elem.style.display = "flex";
                elem1.style.marginTop = "20px";
                $scope.isVisibleThird = true;
                $scope.isVisibleFirst = true;
                $scope.isOpenThird = true;
                $scope.isOpenFirst = true;
            }
            else if (!$scope.isOpenFirst && !$scope.isOpenThird) {
                elem = document.getElementById("modalInfo");
                elem1 = document.getElementById("first");
                elem.style.width = "1000px";
                elem.style.left = "40%";
                elem.style.display = "flex";
                elem1.style.marginTop = "20px";
                $scope.isOpenThird = false;
                $scope.isOpenFirst = true;
                $scope.isVisibleThird = false;
                $scope.isVisibleFirst = true;
            }
        };


        $scope.UpdateTempo = function () {
            mDate = new Date();
            $scope.Fecha = mDate;
            $scope.Hora = mDate;
            $scope.MaxFecha = mDate;
            $scope.MaxHora = mDate;
        };

        // Se organiza la Información para la Publicación del Servicio
        function setInfo(width, module, initaddress, endaddress, namecel, reference) {
            $scope.serviceToAdd = [];
            $scope.UpdateTempo();
            $scope.Fecha.setHours($scope.Hora.getHours());
            $scope.Fecha.setMinutes($scope.Hora.getMinutes());
            $scope.Fecha.setSeconds(0);
            var Info1 = namecel.split("-");
            var AddressInfo1 = initaddress.split("-");

            //var geocoder1 = new google.maps.Geocoder();
            //geocoder1.geocode({
            //    'address': endaddress + ', ' + $scope.CityName + ', Colombia'
            //}, function (results1, status1) {
            //    // Longitud y Latitud de la Dirección de Destino

            //    var lat = 0;
            //    var long = 0;

            //    console.log("Modulo " + module);

            //    if (module == 1) {
            //        lat = InitLatutudM1;
            //        long = InitLongitudM1;
            //        console.log(InitLatutudM1);
            //    } else if (module == 2) {
            //        lat = InitLatutudM2;
            //        long = InitLongitudM2;
            //    } else if (module == 3) {
            //        lat = InitLatutudM3;
            //        long = InitLongitudM3;
            //    }

            //    $scope.serviceToAdd = {};

            //    lat2 = results1[0].geometry.location.lat();
            //    lng2 = results1[0].geometry.location.lng();

            //    $scope.serviceToAdd = ({
            //        Id: createUUID()
            //        , IdCity: createUUID()
            //        , IdTypeServics: 1
            //        , CreateDate: $scope.Fecha
            //        , IdBusinesse: null
            //        , Address: initaddress
            //        , EndAddress: endaddress
            //        , Latitud: parseFloat(lat)
            //        , Longitud: parseFloat(long)
            //        , EndLatitud: parseFloat(lat2)
            //        , EndLongitud: parseFloat(lng2)
            //        , State: 0
            //        , Symbol: 'DELIVERY'
            //        , IsDispatch: 0
            //        , CountPublic: 0
            //        , Observacion: 'DELIVERY SERVICE'
            //        , Phone: Info1[0]
            //        , Referen: reference
            //        , NumberHouse: AddressInfo1[1]
            //        , Name: Info1[1]
            //    });

            //    console.log($scope.serviceToAdd);

            //    console.log("Servicio: " + $scope.serviceToAdd.Id);

            //    if (confirm("¿PUBLICAR EL SERVICIO?")) {
            //        $http.post('/api/Dispatch/SetPublicDeliveryJobs', $scope.serviceToAdd).success(function (data, status, headers, config) {
            //            if (data != null) {
            //                growl.success("Servicio publicado correctamente.", { title: 'Ok!' });
            //                $(".prb").hide();
            //                var element = document.getElementById("modalInfo");
            //                if (width === 2) {
            //                    element.style.width = "500px";
            //                    element.style.left = "50%";
            //                }
            //                else if (width === 3) {
            //                    element.style.width = "1000px";
            //                    element.style.left = "40%";
            //                }

            //                try {
            //                    $scope.listToSave[0].IdService = $scope.serviceToAdd.Id;
            //                    var res = DispatchServics.setDeliveryServices($scope.listToSave).then(function (pl) {
            //                        getDeliveryServices();
            //                    }, function (errorPl) {
            //                        console.log(errorPl);
            //                        growl.error(errorPl.data, { title: 'Error!' });
            //                    });
            //                } catch (e) {
            //                    return growl.error(e.toString(), { title: 'Error!' });
            //                }

            //                hideElements(width, module); // Se ocultan los elementos y Módulo desde el que se publicó el servicio
            //                resetVars(module); // Se llama el reset de las Variables después de publicado el servicio
            //                $scope.serviceToAdd = [];
            //            }
            //        }).error(function (data, status, headers, config) {
            //            return growl.error(data, { title: 'Error!' });
            //        });
            //    }
            //});
        }

        // Hace reset a las Variables dependiendo del Módulo que Publica el Servicio
        function resetVars(item) {
            //Info Dirección de Origen (Módulo 3)
            $scope.Td1 = '0';
            $scope.st1 = '';
            $scope.Td3 = '0';
            $scope.Td4 = '0';
            $scope.Td7 = '0';
            $scope.Td8 = '0';
            $scope.st2 = '';
            $scope.Td5 = '0';
            $scope.Td6 = '0';
            $scope.st3 = '';
            //Info Primera Dirección de Destino (Módulo 3)
            $scope.EndTd1 = "0";
            $scope.Endst1 = '';
            $scope.Endst2 = '';
            $scope.EndTd3 = "0";
            $scope.EndTd4 = "0";
            $scope.EndTd5 = "0";
            $scope.EndTd6 = "0";
            $scope.EndTd7 = "0";
            $scope.EndTd8 = "0";
            $scope.Endst3 = '';
            switch (item) {
                case 1:
                    $scope.isVisibleFirst = false;
                    $scope.NameCelP1 = '';
                    $scope.completeAddressP1 = '';
                    $scope.disabledAddP1 = false;
                    $scope.completeEndAddressP1 = '';
                    $scope.selectedType = '0';
                    $scope.ReferenceAdd = '';
                    $scope.disabledP1 = true;
                    $scope.Valor = '';
                    $scope.Details = '';
                    $scope.Details01P1 = '';
                    $scope.Details1 = '';
                    $scope.Details2 = '';
                    $scope.isVisibleAddressAddP2 = false;
                    $scope.isVisibleAddressAddP3 = false;
                    $scope.completeEndAddressP2 = '';
                    $scope.completeEndAddressP3 = '';
                    break;
                case 2:
                    $scope.isVisibleSecond = false;
                    $scope.NameCelS1 = '';
                    $scope.completeAddressS1 = '';
                    $scope.disabledAddS1 = false;
                    $scope.completeEndAddressS1 = '';
                    $scope.selectedTypeS = '0';
                    $scope.ReferenceAddS = '';
                    $scope.disabledS1 = true;
                    $scope.ValorS = '';
                    $scope.DetailsS = '';
                    $scope.Details01S1 = '';
                    $scope.DetailsS1 = '';
                    $scope.DetailsS2 = '';
                    $scope.isVisibleAddressAdS2 = false;
                    $scope.isVisibleAddressAdS3 = false;
                    $scope.completeEndAddressS2 = '';
                    $scope.completeEndAddressS3 = '';
                    break;
                case 3:
                    $scope.isVisibleThird = false;
                    $scope.NameCelT1 = '';
                    $scope.disabledT1 = true;
                    $scope.completeAddressT1 = '';
                    $scope.disabledAddT = false;
                    $scope.completeEndAddressT1 = '';
                    $scope.selectedTypeT = '0';
                    $scope.ReferenceAddT = '';
                    $scope.ValorT = '';
                    $scope.DetailsT = '';
                    $scope.Details01T1 = '';
                    $scope.DetailsT1 = '';
                    $scope.DetailsT2 = '';
                    $scope.isVisibleAddressAdT2 = false;
                    $scope.isVisibleAddressAdT3 = false;
                    $scope.completeEndAddressT2 = '';
                    $scope.completeEndAddressT3 = '';
                    break;
            }
        }

        function hideElements(width, module) {
            switch (width) {
                case 1: // Width 1 (1 Módulo Abierto)
                    $("#modalInfo").hide();
                    $scope.isVisibleFirst = false;
                    $scope.isOpenFirst = false;
                    $scope.isVisibleSecond = false;
                    $scope.isOpenSecond = false;
                    $scope.isVisibleThird = false;
                    $scope.isOpenThird = false;
                    break;
                case 2: // Width 2 (2 Módulos Abiertos)
                    if (module === 1) { // Desde donde se llama la Acción (Módulo 1)
                        $scope.isVisibleFirst = false;
                        $scope.isOpenFirst = false;
                        if ($scope.isOpenSecond) { // Se determina si es el Módulo 2 el que está abierto
                            $scope.isVisibleSecond = true;
                            $scope.isOpenSecond = true;
                            $scope.isVisibleThird = false;
                            $scope.isOpenThird = false;
                        }
                        else if ($scope.isOpenThird) { // Se determina si es el Módulo 3 el que está abierto
                            $scope.isVisibleSecond = false;
                            $scope.isVisibleThird = true;
                            $scope.isOpenSecond = false;
                            $scope.isOpenThird = true;
                        }
                    }
                    else if (module === 2) { // Desde donde se llama la Acción (Módulo 2)
                        $scope.isVisibleSecond = false;
                        $scope.isOpenSecond = false;
                        if ($scope.isOpenFirst) { // Se determina si es el Módulo 1 el que está abierto
                            $scope.isVisibleFirst = true;
                            $scope.isOpenFirst = true;
                            $scope.isVisibleThird = false;
                            $scope.isOpenThird = false;
                        }
                        else if ($scope.isOpenThird) { // Se determina si es el Módulo 3 el que está abierto
                            $scope.isVisibleFirst = false;
                            $scope.isOpenFirst = false;
                            $scope.isVisibleThird = true;
                            $scope.isOpenThird = true;
                        }
                    }
                    else if (module === 3) { // Desde donde se llama la Acción (Módulo 3)
                        $scope.isVisibleThird = false;
                        $scope.isOpenThird = false;
                        if ($scope.isOpenFirst) { // Se determina si es el Módulo 1 el que está abierto
                            $scope.isVisibleFirst = true;
                            $scope.isOpenFirst = true;
                            $scope.isVisibleSecond = false;
                            $scope.isOpenSecond = false;
                        }
                        else if ($scope.isOpenSecond) { // Se determina si es el Módulo 2 el que está abierto
                            $scope.isVisibleFirst = false;
                            $scope.isVisibleSecond = true;
                            $scope.isOpenFirst = false;
                            $scope.isOpenSecond = true;
                        }
                    }
                    break;
                case 3:
                    if (module === 1) { // Desde donde se llama la Acción (Módulo 1)              
                        $scope.isVisibleFirst = false;
                        $scope.isOpenFirst = false;
                        if ($scope.isOpenSecond && $scope.isOpenThird) { // Se cierra el Módulo 1 y se dejan abiertos los Módulos 2 y 3
                            $scope.isVisibleSecond = true;
                            $scope.isOpenSecond = true;
                            $scope.isVisibleThird = true;
                            $scope.isOpenThird = true;
                        }
                    }
                    else if (module === 2) { // Desde donde se llama la Acción (Módulo 2)
                        $scope.isVisibleSecond = false;
                        $scope.isOpenSecond = false;
                        if ($scope.isOpenFirst && $scope.isOpenThird) { // Se cierra el Módulo 2 y se dejan abiertos los Módulos 1 y 3
                            $scope.isVisibleFirst = true;
                            $scope.isOpenFirst = true;
                            $scope.isVisibleThird = true;
                            $scope.isOpenThird = true;
                        }
                    }
                    else if (module === 3) { // Desde donde se llama la Acción (Módulo 3)
                        $scope.isVisibleThird = false;
                        $scope.isOpenThird = false;
                        if ($scope.isOpenFirst && $scope.isOpenSecond) { // Se cierra el Módulo 3 y se dejan abiertos los Módulos 1 y 2
                            $scope.isVisibleFirst = true;
                            $scope.isOpenFirst = true;
                            $scope.isVisibleSecond = true;
                            $scope.isOpenSecond = true;
                        }
                    }
                    break;
            }
        }

        // Se publica el Servicio dependiendo del Módulo del que se envía y dependiendo de los Módulos que se encuentren abiertos se determina el comportamiento
        $scope.setService = function (module) {
            if (module == 1) {
                if ($scope.completeEndAddressP1 == undefined || $scope.completeEndAddressP1 == "") {
                    $scope.completeEndAddressP1 = "-";
                }
                if ($scope.ReferenceAdd == undefined || $scope.ReferenceAdd == "") {
                    $scope.ReferenceAdd = "-";
                }
                if ($scope.completeAddressP1 == undefined || $scope.completeAddressP1 == "") {
                    growl.error("Debe seleccionar una dirección de origen", { title: 'Error!' });
                    return;
                }
            };
            if (module == 2) {
                if ($scope.completeEndAddressS1 == undefined || $scope.completeEndAddressS1 == "") {
                    $scope.completeEndAddressS1 = "-";
                }
                if ($scope.ReferenceAddS == undefined || $scope.ReferenceAddS == "") {
                    $scope.ReferenceAddS = "-";
                }
                if ($scope.completeAddressS1 == undefined || $scope.completeAddressS1 == "") {
                    growl.error("Debe seleccionar una dirección de origen", { title: 'Error!' });
                    return;
                }
            };
            if (module == 3) {
                if ($scope.completeEndAddressT1 == undefined || $scope.completeEndAddressT1 == "") {
                    $scope.completeEndAddressT1 = "-";
                }
                if ($scope.ReferenceAddT == undefined || $scope.ReferenceAddT == "") {
                    $scope.ReferenceAddT = "-";
                }
                if ($scope.completeAddressT1 == undefined || $scope.completeAddressT1 == "") {
                    growl.error("Debe seleccionar una dirección de origen", { title: 'Error!' });
                    return;
                }
            };

            organizeInfoDeliveries(module);
            var element = document.getElementById("modalInfo");
            if (element.style.width == "500px") {
                if (module === 1) setInfo(1, module, $scope.completeAddressP1, $scope.completeEndAddressP1, $scope.NameCelP1, $scope.ReferenceAdd, $scope.listToSave);
                else if (module === 2) setInfo(1, module, $scope.completeAddressS1, $scope.completeEndAddressS1, $scope.NameCelS1, $scope.ReferenceAddS, $scope.listToSave);
                else if (module === 3) setInfo(1, module, $scope.completeAddressT1, $scope.completeEndAddressT1, $scope.NameCelT1, $scope.ReferenceAddT, $scope.listToSave);
            }
            else if (element.style.width == "1000px") {
                if (module === 1) setInfo(2, module, $scope.completeAddressP1, $scope.completeEndAddressP1, $scope.NameCelP1, $scope.ReferenceAdd, $scope.listToSave);
                else if (module === 2) setInfo(2, module, $scope.completeAddressS1, $scope.completeEndAddressS1, $scope.NameCelS1, $scope.ReferenceAddS, $scope.listToSave);
                else if (module === 3) setInfo(2, module, $scope.completeAddressT1, $scope.completeEndAddressT1, $scope.NameCelT1, $scope.ReferenceAddT, $scope.listToSave);
            }
            else if (element.style.width == "1500px") {
                if (module === 1) setInfo(3, module, $scope.completeAddressP1, $scope.completeEndAddressP1, $scope.NameCelP1, $scope.ReferenceAdd, $scope.listToSave);
                else if (module === 2) setInfo(3, module, $scope.completeAddressS1, $scope.completeEndAddressS1, $scope.NameCelS1, $scope.ReferenceAddS, $scope.listToSave);
                else if (module === 3) setInfo(3, module, $scope.completeAddressT1, $scope.completeEndAddressT1, $scope.NameCelT1, $scope.ReferenceAddT, $scope.listToSave);
            }
        };

        $scope.CancelServices = function (Id) {
            var params = {
                Ids: Id,
            };
            if (confirm("CANCELAR EL SERVICIO")) {

                var res = DispatchServics.CancelServices(Id).then(function (pl) {
                    var data = pl.data;
                    if (data == 1) {
                        growl.info("SERVICIO CANCELADO", { title: 'Info!' });
                        getDeliveryServices();
                    }
                }, function (errorPl) {
                    growl.error(errorPl.data, { title: 'Error!' });
                });

            }

        };

        function organizeInfoDeliveries(module) {
            $scope.listToSave = [];
            $scope.UpdateTempo();
            $scope.Fecha.setHours($scope.Hora.getHours());
            $scope.Fecha.setMinutes($scope.Hora.getMinutes());
            $scope.Fecha.setSeconds(0);
            if (module === 1) {
                $scope.listToSave.push({
                    Id: createUUID()
                    , IdService: createUUID()
                    , StartAddress: $scope.completeAddressP1
                    , EndAddress: $scope.completeEndAddressP1
                    , UrlImg1: ''
                    , UrlImg2: ''
                    , UrlImg3: ''
                    , UrlImg4: ''
                    , Description: $scope.Details01P1
                    , DescriptionF: $scope.Details
                    , DeliveryType: $scope.selectedType
                    , State: 0
                    , Valor: parseFloat($scope.Valor)
                    , Base: $scope.Base1
                    , CreateDate: $scope.Fecha
                });

                if ($scope.completeEndAddressP2 != undefined && $scope.completeEndAddressP2 != '') {
                    $scope.listToSave.push({
                        Id: createUUID()
                        , IdService: createUUID()
                        , StartAddress: $scope.completeEndAddressP1
                        , EndAddress: $scope.completeEndAddressP2
                        , UrlImg1: ''
                        , UrlImg2: ''
                        , UrlImg3: ''
                        , UrlImg4: ''
                        , Description: $scope.Details
                        , DescriptionF: $scope.Details1
                        , DeliveryType: $scope.selectedType
                        , State: 0
                        , Valor: 0.0
                        , Base: 0
                        , CreateDate: $scope.Fecha
                    });
                }

                if ($scope.completeEndAddressP3 != undefined && $scope.completeEndAddressP3 != '') {
                    $scope.listToSave.push({
                        Id: createUUID()
                        , IdService: createUUID()
                        , StartAddress: $scope.completeEndAddressP2
                        , EndAddress: $scope.completeEndAddressP3
                        , UrlImg1: ''
                        , UrlImg2: ''
                        , UrlImg3: ''
                        , UrlImg4: ''
                        , Description: $scope.Details1
                        , DescriptionF: $scope.Details2
                        , DeliveryType: $scope.selectedType
                        , State: 0
                        , Valor: 0.0
                        , Base: 0
                        , CreateDate: $scope.Fecha
                    });
                }
            }
            else if (module === 2) {
                $scope.listToSave.push({
                    Id: createUUID()
                    , IdService: createUUID()
                    , StartAddress: $scope.completeAddressS1
                    , EndAddress: $scope.completeEndAddressS1
                    , UrlImg1: ''
                    , UrlImg2: ''
                    , UrlImg3: ''
                    , UrlImg4: ''
                    , Description: $scope.Details01S1
                    , DescriptionF: $scope.DetailsS
                    , DeliveryType: $scope.selectedTypeS
                    , State: 0
                    , Valor: parseFloat($scope.ValorS)
                    , Base: $scope.Base2
                    , CreateDate: $scope.Fecha
                });

                if ($scope.completeEndAddressS2 != undefined && $scope.completeEndAddressS2 != '') {
                    $scope.listToSave.push({
                        Id: createUUID()
                        , IdService: createUUID()
                        , StartAddress: $scope.completeEndAddressS1
                        , EndAddress: $scope.completeEndAddressS2
                        , UrlImg1: ''
                        , UrlImg2: ''
                        , UrlImg3: ''
                        , UrlImg4: ''
                        , Description: $scope.DetailsS
                        , DescriptionF: $scope.DetailsS1
                        , DeliveryType: $scope.selectedTypeS
                        , State: 0
                        , Valor: 0.0
                        , Base: 0
                        , CreateDate: $scope.Fecha
                    });
                }

                if ($scope.completeEndAddressS3 != undefined && $scope.completeEndAddressS3 != '') {
                    $scope.listToSave.push({
                        Id: createUUID()
                        , IdService: createUUID()
                        , StartAddress: $scope.completeEndAddressS2
                        , EndAddress: $scope.completeEndAddressS3
                        , UrlImg1: ''
                        , UrlImg2: ''
                        , UrlImg3: ''
                        , UrlImg4: ''
                        , Description: $scope.DetailsS1
                        , DescriptionF: $scope.DetailsS2
                        , DeliveryType: $scope.selectedTypeS
                        , State: 0
                        , Valor: 0.0
                        , Base: 0
                        , CreateDate: $scope.Fecha
                    });
                }
            }
            else if (module === 3) {
                $scope.listToSave.push({
                    Id: createUUID()
                    , IdService: createUUID()
                    , StartAddress: $scope.completeAddressT1
                    , EndAddress: $scope.completeEndAddressT1
                    , UrlImg1: ''
                    , UrlImg2: ''
                    , UrlImg3: ''
                    , UrlImg4: ''
                    , Description: $scope.Details01T1
                    , DescriptionF: $scope.DetailsT
                    , DeliveryType: $scope.selectedTypeT
                    , State: 0
                    , Valor: parseFloat($scope.ValorT)
                    , Base: $scope.Base3
                    , CreateDate: $scope.Fecha
                });

                if ($scope.completeEndAddressT2 != undefined && $scope.completeEndAddressT2 != '') {
                    $scope.listToSave.push({
                        Id: createUUID()
                        , IdService: createUUID()
                        , StartAddress: $scope.completeEndAddressT1
                        , EndAddress: $scope.completeEndAddressT2
                        , UrlImg1: ''
                        , UrlImg2: ''
                        , UrlImg3: ''
                        , UrlImg4: ''
                        , Description: $scope.DetailsT
                        , DescriptionF: $scope.DetailsT1
                        , DeliveryType: $scope.selectedTypeT
                        , State: 0
                        , Valor: 0.0
                        , Base: 0
                        , CreateDate: $scope.Fecha
                    });
                }

                if ($scope.completeEndAddressT3 != undefined && $scope.completeEndAddressT3 != '') {
                    $scope.listToSave.push({
                        Id: createUUID()
                        , IdService: createUUID()
                        , StartAddress: $scope.completeEndAddressT2
                        , EndAddress: $scope.completeEndAddressT3
                        , UrlImg1: ''
                        , UrlImg2: ''
                        , UrlImg3: ''
                        , UrlImg4: ''
                        , Description: $scope.DetailsT1
                        , DescriptionF: $scope.DetailsT2
                        , DeliveryType: $scope.selectedTypeT
                        , State: 0
                        , Valor: 0.0
                        , Base: 0
                        , CreateDate: $scope.Fecha
                    });
                }
            }
        }

        $scope.test = false;

        $scope.showpanel = function () {
            if ($scope.test === false) {
                $scope.test = true;
                $("#tl").removeClass('span6');
                $("#tl").addClass('span12');

                $("#P1").css('margin-left', '3%');
                $("#P2").css('margin-left', '3%');

            } else {
                $scope.test1 = true;
                $("#dv1").removeClass("span6");
                $("#dv2").removeClass("span6");

                $("#dv1").addClass("span4");
                $("#dv2").addClass("span4");
                $("#dv3").addClass("span4");
            }
        };

        $scope.closePanel = function () {
            if ($scope.test1 === true) {
                $scope.test1 = false;

                $("#dv1").removeClass("span4");
                $("#dv2").removeClass("span4");
                $("#dv3").removeClass("span4");
                $("#dv1").addClass("span6");
                $("#dv2").addClass("span6");
                resetVars(3);
            } else if ($scope.test === true) {
                $scope.test = false;
                $("#tl").removeClass('span12');
                $("#tl").addClass('span6');
                $("#P1").css('margin-left', '27%');
                $("#P2").css('margin-left', '27%');
                resetVars(2);
            } else {
                $(".prb").hide();
                resetVars(1);
            }
        };
    }]);