/* Minification failed. Returning unminified contents.
(65,48-49): run-time error JS1195: Expected expression: >
(84,67-68): run-time error JS1195: Expected expression: >
(156,10-11): run-time error JS1195: Expected expression: )
(169,6-7): run-time error JS1195: Expected expression: )
(191,43-44): run-time error JS1195: Expected expression: >
(203,6-7): run-time error JS1195: Expected expression: )
(211,39-40): run-time error JS1195: Expected expression: >
(213,6-7): run-time error JS1195: Expected expression: )
 */
var dictMaps = new Object();
var dictMarkers = new Object();
let getMap = false;
let downloadMapPromise;

function showAddress(address, mapId, postalCode, country) {
    $("#ew_item_" + mapId + "_address_streetAddress").val(address);
    $("#ew_item_" + mapId + "_address_countryName").val(country);
    $("#ew_item_" + mapId + "_address_postalCode").val(postalCode);
}

function showCoordinates(lat, lng, eval, mapId) {
    $("#ew_item_" + mapId + "_location_latitude").val(lat);
    $("#ew_item_" + mapId + "_location_longitude").val(lng);
    $("#ew_item_" + mapId + "_location_elevation").val(eval);
}

function restorePosition(_el, index) {
    var markers = dictMarkers[index];
    var map = dictMaps[index];

    let lat = _el.latitude;
    let lng = _el.longitude;

    var latlng = {
        lat: parseFloat(lat),
        lng: parseFloat(lng),
    };

    // Restore marker after page load.
    var marker = new google.maps.Marker({
        position: latlng,
        map: map,
        title: ''
    });

    marker.setIcon('http://maps.google.com/mapfiles/ms/icons/red-dot.png');

    map.setCenter({
        lat: parseFloat(lat),
        lng: parseFloat(lng),
    })

    markers.push(marker);
}

function initMap(index, el) {
    var Kiev = new google.maps.LatLng(50.45119, 30.45463);

    var markers = [];
    dictMarkers[index] = markers;

    var map = new google.maps.Map(document.getElementById("map_" + index), {
        zoom: 6,
        center: Kiev
    });

    dictMaps[index] = map;

    if (el != undefined && el.longitude != "" && el.latitude != "") {
        restorePosition(el, index);
    }

    // Configure the click listener.
    map.addListener("click", (mapsMouseEvent) => {
        // Delete markers.
        deleteMarkers(index);

        var latLngStr = JSON.stringify(mapsMouseEvent.latLng.toJSON(), null, 2);
        var latLng = JSON.parse(latLngStr);
        // Zoom.
        var zoom = map.getZoom();

        var lat = latLng.lat;
        var lng = latLng.lng;

        const geocoder = new google.maps.Geocoder();
        const latlng = {
            lat: parseFloat(lat),
            lng: parseFloat(lng),
        };

        // Get geocode.
        geocoder.geocode({ location: latlng }, (results, status) => {
            if (status === "OK") {
                // Get postal code.
                var postalCode = "";
                for (i = 0; i < results.length; i++) {
                    for (var j = 0; j < results[i].address_components.length; j++) {
                        for (var k = 0; k < results[i].address_components[j].types.length; k++) {
                            if (results[i].address_components[j].types[k] == "postal_code") {
                                postalCode = results[i].address_components[j].short_name;
                            }
                        }
                    }
                }

                // Get coutnry.
                var country = null, countryCode = null, city = null, cityAlt = null, political = null;
                var c, lc, component;
                for (var r = 0, rl = results.length; r < rl; r += 1) {
                    var result = results[r];

                    if (!city && result.types[0] === 'locality') {
                        for (c = 0, lc = result.address_components.length; c < lc; c += 1) {
                            component = result.address_components[c];

                            if (component.types[0] === 'locality') {
                                city = component.long_name;
                                break;
                            }
                        }
                    }
                    else if (!city && !cityAlt && result.types[0] === 'administrative_area_level_1') {
                        for (c = 0, lc = result.address_components.length; c < lc; c += 1) {
                            component = result.address_components[c];

                            if (component.types[0] === 'administrative_area_level_1') {
                                cityAlt = component.long_name;
                                break;
                            }
                        }
                    } else if (!country && result.types[0] === 'country') {
                        country = result.address_components[0].long_name;
                        countryCode = result.address_components[0].short_name;
                    }

                    if (city && country) {
                        break;
                    }
                } // End For

                if (results[0]) {
                    let fullAddress = results[0].formatted_address;
                    var partOfAddress = "";
                    for (var i = 0; i < results[0].address_components.length; i++) {
                        var type = results[0].address_components[i].types[0];
                        if (type == "plus_code" || type == "country" || type == "postal_code" || type == "administrative_area_level_1") {
                            continue;
                        }

                        if (i == 0) {
                            partOfAddress = partOfAddress + results[0].address_components[i].long_name;
                        } else {
                            partOfAddress = partOfAddress + ", " + results[0].address_components[i].long_name;
                        }
                    }

                    showAddress(partOfAddress, index, postalCode, country);
                } else {
                    showAddress("Address not loaded.", index, "", "");
                }
            } else {
                window.alert("Error: " + status);
            }
        });

        showCoordinates(latLng.lat, latLng.lng, zoom, index);

        var marker = new google.maps.Marker({
            position: mapsMouseEvent.latLng,
            map: map,
            title: ''
        });

        marker.setIcon('http://maps.google.com/mapfiles/ms/icons/red-dot.png');

        dictMarkers[index].push(marker);
    });
}

// Sets the map on all markers in the array.
function setMapOnAll(map, markers) {
    for (let i = 0; i < markers.length; i++) {
        markers[i].setMap(map);
    }
}

// Removes the markers from the map, but keeps them in the array.
function clearMarkers(markers) {
    setMapOnAll(null, markers);
}

function deleteMarkers(mapId) {
    var markers = dictMarkers[mapId];
    clearMarkers(markers);
    dictMarkers[mapId] = [];
}

function downloadMap() {
    return new Promise((resolve, reject) => {
        let url = "https://maps.googleapis.com/maps/api/js?libraries=geometry&sensor=false&key=AIzaSyDN78Gt3__vv1N2uCgeNUSQLRdVlrpHTww&language=uk";

        $.getScript(url)
            .done(function () {
                resolve("Success!");
            })
            .fail(function (jqxhr, settings, exception) {
                console.log(exception);
                reject(exception);
            });
        getMap = true;
    });
}

function checkGetMap(index, el_loc) {
    if (!getMap) {
        downloadMapPromise = downloadMap();
    }

    downloadMapPromise.then((result) => {
        initMap(index, el_loc);
    });
};
