var map = {
    settings: {
        healthFacilityAjax : '',
        patient_autocomplete_url: '',
        city_autocomplete_url: '',
        postalCode_autocomplete_url: ''
    },
    geoMap: null,
    markers: [],
    hfMarkers: [],
    patientMarkers: [],
    init: function() {
        this.initMap();
        this.initAutocomplete();
        this.removeParams();
    },
    initAutocomplete: function() {
        global.autocomplete.bind(map.settings.patient_autocomplete_url, '#filter-patient-fullName', '#filter-patient-id', {
            onSelect: function (d) {
                if((d.geoLat === null && d.geoLat === '') || (d.geoLong === null || d.geoLong === '')){
                    map.doGeocodePatient(d);
                }else{
                    for(let i = 0; i<map.patientMarkers.length; i++) {
                        map.patientMarkers[i].setMap(null);
                    }

                    map.patientMarkers = [];
                    const marker = new google.maps.Marker({
                        map: map.geoMap,
                        position : new google.maps.LatLng(d.geoLat,d.geoLong)
                    });
                    const infoWin = new google.maps.InfoWindow({
                        content: "Full Name: " + d.data + "<br />" +
                            "Address: " + d.address + "<br />"
                    });

                    (function (geoMap, marker, infoWin) {
                        marker.addListener('click', function(){
                            infoWin.open(geoMap, marker);
                        });
                    })(map.geoMap, marker, infoWin);
                    map.patientMarkers.push(marker);
                }
            }
        });
        global.autocomplete.bind(map.settings.city_autocomplete_url, '#filter-city-desc', '#filter-city-id', {
            onSelect: function (d) {
                var params = {
                    city_id : jQ('#filter-city-id').val() !== '' ? jQ('#filter-city-id').val() : '',
                };
                var patientDetails = d.patientDetails.split('|');
                for(let i = 0 ; i < patientDetails.length ; i++){
                    var patientDetail = patientDetails[i].split(';');
                    if(patientDetail[3] && patientDetail[4]){
                        const marker = new google.maps.Marker({
                            map: map.geoMap,
                            position : new google.maps.LatLng(patientDetail[3],patientDetail[4])
                        });
                        const infoWin = new google.maps.InfoWindow({
                            content: "Full Name: " + patientDetail[1] + "<br />" +
                                "Address: " + patientDetail[2] + "<br />"
                        });
                        (function (geoMap, marker, infoWin) {
                            marker.addListener('click', function(){
                                infoWin.open(geoMap, marker);
                            });
                        })(map.geoMap, marker, infoWin);
                        map.patientMarkers.push(marker);
                    }else{
                        map.doGeocode(patientDetail);
                    }
                }
                jQ('#filter-postalCode-desc').devbridgeAutocomplete('setOptions', {params: params});
            }
        });
        global.autocomplete.bind(map.settings.postalCode_autocomplete_url, '#filter-postalCode-desc', '#filter-postalCode-id', {
            onSelect: function (d) {
                var params = {
                    postalCode_id : jQ('#filter-postalCode-id').val() !== '' ? jQ('#filter-postalCode-id').val() : '',
                };
                console.log(d);
                var patientDetails = d.patientDetails.split('|');
                for(let i = 0 ; i < patientDetails.length ; i++){
                    var patientDetail = patientDetails[i].split(';');
                    if(patientDetail[3] && patientDetail[4]){
                        const marker = new google.maps.Marker({
                            map: map.geoMap,
                            position : new google.maps.LatLng(patientDetail[3],patientDetail[4])
                        });
                        const infoWin = new google.maps.InfoWindow({
                            content: "Full Name: " + patientDetail[1] + "<br />" +
                                "Address: " + patientDetail[2] + "<br />"
                        });
                        (function (geoMap, marker, infoWin) {
                            marker.addListener('click', function(){
                                infoWin.open(geoMap, marker);
                            });
                        })(map.geoMap, marker, infoWin);
                        map.patientMarkers.push(marker);
                    }else{
                        map.doGeocode(patientDetail);
                    }
                }
                jQ('#filter-city-desc').devbridgeAutocomplete('setOptions', {params: params});

                map.doGeocode(d.data);
            }
        });
    },
    removeParams: function () {
        jQ('#filter-city-desc').unbind('keyup').bind('keyup', function () {
            var params = {
                city_id : ''
            };
            jQ('#filter-postalCode-desc').devbridgeAutocomplete('setOptions', {params: params});
        });

        jQ('#filter-postalCode-desc').unbind('keyup').bind('keyup', function () {
            var params = {
                postalCode_id : ''
            };
            jQ('#filter-city-desc').devbridgeAutocomplete('setOptions', {params: params});
        });
    },
    initMap: function() {
        if(jQ('#map-canvas').length) {

            var latLong = new google.maps.LatLng(53.5564402,-113.7368218); // Edmonton, Canada
            map.geoMap  = new google.maps.Map(document.getElementById('map-canvas'), {
                center: latLong,
                zoom: 6,
                gestureHandling: 'greedy',
                //scaleControl: false,
                streetViewControl: false,
                //rotateControl: false,
                fullscreenControl: false,
                // mapTypeControl: false,
                controlSize: 26,
                mapTypeControlOptions: {
                    mapTypeIds: ['roadmap', 'satellite', 'hybrid', 'terrain']
                }
            });
            //var input = document.getElementById('address');
            //var submitButton = document.getElementById('submitGeoCode');
            //map.geoMap.controls[google.maps.ControlPosition.TOP_LEFT].push(submitButton);
            //map.geoMap.controls[google.maps.ControlPosition.TOP_RIGHT].push(input);

            map.geoMap.addListener('idle', function(){
                map.getHealthFacilities();
            });
        }
    },
    doGeocode: function (patientDetail) {
        for(let i = 0; i<map.patientMarkers.length; i++) {
            map.patientMarkers[i].setMap(null);
        }

        map.patientMarkers = [];
        const geocoder = new google.maps.Geocoder(),
            geoMap = map.geoMap;
        geocoder.geocode(
            {
                'address': patientDetail[2],
                'country': 'CA'
            }, function (results, status) {
                if (status === google.maps.GeocoderStatus.OK) {
                    geoMap.setCenter(results[0].geometry.location);
                   const marker = new google.maps.Marker({
                        map: geoMap,
                        position: results[0].geometry.location
                    });
                    const infoWin = new google.maps.InfoWindow({
                        content: "Full Name: " + patientDetail[1] + "<br />" +
                            "Address: " + patientDetail[2] + "<br />"
                    });

                    (function (geoMap, marker, infoWin) {
                        marker.addListener('click', function(){
                            infoWin.open(geoMap, marker);
                        });
                    })(map.geoMap, marker, infoWin);
                    map.patientMarkers.push(marker);
                } else {
                    if (status === google.maps.GeocoderStatus.OVER_QUERY_LIMIT) {
                        wait = true;
                        setTimeout("wait = true", 2000);
                    }else{
                        //Error handling
                        alert('Geocode was not successful for the following reason: ' + status);
                    }
                }
            });
    },

    doGeocodePatient: function (patient) {
        for(let i = 0; i<map.patientMarkers.length; i++) {
            map.patientMarkers[i].setMap(null);
        }

        map.patientMarkers = [];
        const geocoder = new google.maps.Geocoder(),
            geoMap = map.geoMap;
        geocoder.geocode(
            {
                'address': patient.address,
                'country': 'CA'
            }, function (results, status) {
                if (status === google.maps.GeocoderStatus.OK) {
                    geoMap.setCenter(results[0].geometry.location);
                    const marker = new google.maps.Marker({
                        map: geoMap,
                        position: results[0].geometry.location
                    });
                    const infoWin = new google.maps.InfoWindow({
                        content: "Full Name: " + patient.data + "<br />" +
                            "Address: " + patient.address + "<br />"
                    });

                    (function (geoMap, marker, infoWin) {
                        marker.addListener('click', function(){
                            infoWin.open(geoMap, marker);
                        });
                    })(map.geoMap, marker, infoWin);
                    map.patientMarkers.push(marker);
                } else {
                    if (status === google.maps.GeocoderStatus.OVER_QUERY_LIMIT) {
                        wait = true;
                        setTimeout("wait = true", 2000);
                    }else{
                        //Error handling
                        alert('Geocode was not successful for the following reason: ' + status);
                    }
                }
            });
    },

    getHealthFacilities: function () {
      global.ajax({
          'url': map.settings.healthFacilityAjax,
          'type': 'GET',
          success: function (data) {
              let healthFacilities = data['healthFacilities'];
              console.log(healthFacilities);

              for(var i=0; i<healthFacilities.length; i++){
                  const marker = new google.maps.Marker({
                      map: map.geoMap,
                      position : new google.maps.LatLng(healthFacilities[i]['geoLat'],healthFacilities[i]['geoLong']),
                      icon:'/bundles/rxconnexion/admin/images/map-icon/HF.png'
                  });
                  const infoWin = new google.maps.InfoWindow({
                      content: "Address: " + healthFacilities[i]['address'] + "<br />" +
                                "Health Facility: " + healthFacilities[i]['description']
                  });
                  (function (geoMap, marker, infoWin) {
                      marker.addListener('click', function(){
                          infoWin.open(geoMap, marker);
                      });
                  })(map.geoMap, marker, infoWin);

                  map.hfMarkers.push(marker);
              }
          }
      })
    }
};