(function (){
    "use strict";

    var geoProcessCMD = {};
    var mymap         = null;
    var _layer        = null;

    // -----------------------------------------------------------

    var sendMessage = function (msg) {
        // Make sure you are sending a string, and to stringify JSON
        window.parent.postMessage(msg + "", '*');
    };

    // -----------------------------------------------------------

    window.addEventListener("message", function (e){
        if (e.data && e.data.name === "mychatGeoCoords"){
            var _coords   = e.data.coords;
            var _markers  = [];
            var _polyline = [];

            _layer && mymap.removeLayer(_layer);

            if (_coords.length && _coords[_coords.length - 1] && _coords[_coords.length - 1].coords){
                _coords.forEach(function (item){
                    _markers.push(L.marker(item.coords).bindPopup(item.title));
                    _polyline.push(item.coords);
                });

                var polyline = L.polyline(_polyline, {color: 'blue'});

                _layer = L
                .layerGroup(_markers)
                 .addLayer(polyline)
                 .addLayer(L.circleMarker(_coords[_coords.length - 1].coords, {
                    radius: 30,
                    color : 'green',
                    weight: 1,
                    fillOpacity: 0.07,
                }))
                 .addTo(mymap);

                // .addTo(mymap);

                mymap.setView(L.marker(_coords[_coords.length - 1].coords).getLatLng(), 16);
            }
        }
    }, false);

    // -----------------------------------------------------------

    mymap = L.map('_mapRenderView_').setView([0, 0], 4);

    L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
        maxZoom: 18,
    }).addTo(mymap);

    sendMessage("geo_ready");

    var allLinks = document.getElementsByTagName("a");

    for (var i = 0; i < allLinks.length; i++){
        if (allLinks[i].href.indexOf("http") === 0) {
            allLinks[i].onclick = function (e){
                e.preventDefault();
            }
        }
    }

    document.body.onclick = function (){
        sendMessage("geo_anyClick");
    }
})()
