var map;
var mapSugestao;
var geocoderPopup;
var G_LAT_LNG_DEFAULT; // guardar obj de lat/lgn
var t_info_mapSugestao;

var imagem_n = './wp-content/themes/caronainterativa/imagens/marker_atual.png';
var imagem_v = './wp-content/themes/caronainterativa/imagens/marker_visitados.png';
var imagem_e = './wp-content/themes/caronainterativa/imagens/marker_carona.png';

var last_exp = null;

function initializeMap() {
    if (GBrowserIsCompatible()) {
        G_LAT_LNG_DEFAULT = new GLatLng(-18.479609,-46.450195);

        map = new GMap2(document.getElementById("mapaPrincipal"));
        var terr_ = new GMapType(G_PHYSICAL_MAP.getTileLayers(),G_PHYSICAL_MAP.getProjection(),"Relevo");
        map.addMapType(terr_);
        map.addControl(new GMenuMapTypeControl());
        // map.addControl(new GLargeMapControl());
        map.addControl(new G_ZoomControl()); // controle com as lupas
        map.addControl(new GScaleControl());
        map.setCenter(G_LAT_LNG_DEFAULT, 5);
        map.enableDoubleClickZoom();
        map.setMapType(G_PHYSICAL_MAP);

        // pontos_map_n -> pontos não visitados
        // pontos_map_v -> pontos visitados
        // pontos_map_e -> excursão

        if (pontos_map_n && pontos_map_v && pontos_map_e) {
            for(var i=0; i < pontos_map_n.length; i++) { map.addOverlay( createMarker(pontos_map_n[i], imagem_n) ); }
            for(var i=0; i < pontos_map_v.length; i++) { map.addOverlay( createMarker(pontos_map_v[i], imagem_v) ); }
            for(var i=0; i < pontos_map_e.length; i++) { map.addOverlay( createMarker(pontos_map_e[i], imagem_e) ); }

            if (pontos_map_e.length > 0) {
                var p = pontos_map_e[pontos_map_e.length-1];
                last_exp = new GLatLng(p.latitude, p.longitude);
                centralizarLastExp();
            }
        }
    }
}
function inicializeMapPopUp() {
    if (GBrowserIsCompatible()) {
        mapSugestao = new GMap2(document.getElementById("mapaSugestao"));
        var terr = new GMapType(G_PHYSICAL_MAP.getTileLayers(),G_PHYSICAL_MAP.getProjection(),"Relevo");
        mapSugestao.addMapType(terr);
        mapSugestao.addControl(new GMenuMapTypeControl());
        //mapSugestao.addControl(new GSmallZoomControl());
        mapSugestao.addControl(new G_ZoomControl()); // controle com as lupas
        mapSugestao.setCenter(G_LAT_LNG_DEFAULT, 3);
        mapSugestao.enableDoubleClickZoom();

        geocoderPopup = new GClientGeocoder();
    }
}
function searchPoint() {
    if (GBrowserIsCompatible()) {
        var estado  = $('select#estado').val();
        var address = $('input#country').val()+','+ 
                      ((estado) ? estado+',' : '')+
                      $('input#cidade').val() +','+
                      $('input#endereco').val();
        geocoderPopup.getLocations(address, addAddressToMap);
    }
}
function addAddressToMap(response) {
    var nivel;
    var txt_mapSugestao;
    var setAddressAndZoom = function(place) {
        //
        txt_mapSugestao = '';
        nivel = 4
        //
        var country = state = city = address = postalCode = '';
        //
        if (place && place.AddressDetails) {
            if (place.AddressDetails.Country) {
                txt_mapSugestao += '<strong>País:</strong>&nbsp;';
                if (place.AddressDetails.Country.CountryName) { 
                    country = place.AddressDetails.Country.CountryName;
                    txt_mapSugestao += country;
                }
                if (place.AddressDetails.Country.CountryNameCode) {
                    if (country == '') country = place.AddressDetails.Country.CountryNameCode;
                    txt_mapSugestao += '&nbsp;('+ place.AddressDetails.Country.CountryNameCode +')<br/>';
                }
                if (place.AddressDetails.Country.AdministrativeArea) {
                    if (place.AddressDetails.Country.AdministrativeArea.AdministrativeAreaName) {
                        nivel = 6;
                        state = place.AddressDetails.Country.AdministrativeArea.AdministrativeAreaName;
                        txt_mapSugestao += '<strong>Estado:</strong>&nbsp;' + state + '<br/>';
                    } 
                    if (place.AddressDetails.Country.AdministrativeArea.Locality) {
                        if (place.AddressDetails.Country.AdministrativeArea.Locality.LocalityName) {
                            nivel = 13;
                            city = place.AddressDetails.Country.AdministrativeArea.Locality.LocalityName;
                            txt_mapSugestao += '<strong>Cidade:</strong>&nbsp;' + city +'<br/>';
                        }
                        if (place.AddressDetails.Country.AdministrativeArea.Locality.Thoroughfare) {
                            nivel = 16;
                            address = place.AddressDetails.Country.AdministrativeArea.Locality.Thoroughfare.ThoroughfareName;
                            txt_mapSugestao += '<strong>Endereço:</strong>&nbsp;' + address +'<br/>';   
                        }
                        if (place.AddressDetails.Country.AdministrativeArea.Locality.PostalCode) {
                            nivel = 16;
                            postalCode = place.AddressDetails.Country.AdministrativeArea.Locality.PostalCode.PostalCodeNumber;
                            txt_mapSugestao += '<strong>Código postal:</strong>&nbsp;' + postalCode;
                        }
                    }
                }
            }
        }// place...
        $('input#country').val( country );
        $('select#estado').val( state );
        $('input#cidade').val( city );
        $('input#endereco').val( address += ((postalCode != '') ? ', '+postalCode : '') );
        //
        disableEnableUF( country );
    };
    var setPoint = function(marker) {
        if (marker) {
            marker.openInfoWindowHtml(txt_mapSugestao);
            
            jQuery("#latitude").attr("value", marker.getLatLng().lat());
            jQuery("#longitude").attr("value", marker.getLatLng().lng());
        } else {
            jQuery("#latitude").attr("value", "");
            jQuery("#longitude").attr("value", "");
        }
    };
    mapSugestao.clearOverlays();
    if (!response || response.Status.code != 200) {
        mapSugestao.setCenter(G_LAT_LNG_DEFAULT, 3);

        setAddressAndZoom(null);
        setPoint(null);

        alert('Não foi possível localizar o endereço informado!');
    } 
    else {
        var place = response.Placemark[0];
        var point = new GLatLng(place.Point.coordinates[1], place.Point.coordinates[0]);
        var marker = new GMarker(point, {draggable:true});
        
        GEvent.addListener(marker, "infowindowopen", function(){
            clearTimeout(t_info_mapSugestao);
            t_info_mapSugestao = setTimeout(function(){ marker.closeInfoWindow() }, 2000);
        });
        GEvent.addListener(marker, "closewindowopen", function(){ clearTimeout(t_info_mapSugestao) });
        GEvent.addListener(marker, "dragstart", function(){ marker.closeInfoWindow() });
        GEvent.addListener(marker, "dragend", function(){ geocoderPopup.getLocations(marker.getLatLng(), addAddressToMap) });
        GEvent.addListener(marker, "click", function(){ geocoderPopup.getLocations(marker.getLatLng(), addAddressToMap) });

        setAddressAndZoom(place);

        mapSugestao.setZoom(nivel);
        mapSugestao.addOverlay(marker);

        setPoint(marker);
    }
}
function createMarker(ponto, imagem) {
    var icon = new GIcon(G_DEFAULT_ICON);
    icon.iconSize = new GSize(20,34);
    icon.image = imagem;

    var point = new GLatLng(ponto.latitude, ponto.longitude);
    var marker = new GMarker(point, {icon:icon,zIndexProcess:function(marker,b){ return 1 }});

    // GEvent.addListener(marker, 'infowindowclose', function() { map.returnToSavedPosition() });
    GEvent.addListener(marker, 'click', function() {
        // map.savePosition();
        marker.openInfoWindow('carregando...');
        GDownloadUrl("./wp-content/themes/caronainterativa/detalhesComentario.php?idPoint="+ ponto.codigo, function(data) {
            marker.openInfoWindowHtml(data,{ autoScroll:true,limitSizeToMap:true,maxWidth:580 });
            // if (map.getZoom() < 13)
            //  map.setZoom(15);
            // {zoomLevel:15, autoScroll:true, limitSizeToMap:true, buttons:{close:{height:16,width:5}} }
        });
    });
    return marker;
}
