
/* Variabili Globali */
var map = null;
var mapoverview = null;
var geocoder = null;
var gdirections = null;

/* Funzione chiamata al caricamento della pagina principale */
function initialize() {
   
    if (GBrowserIsCompatible()) {
        map = new GMap2(document.getElementById("map_canvas"));
        ip_locate(map);
        map.setUIToDefault();
        mapoverview = new GOverviewMapControl();
        map.addControl(mapoverview);
        map.addControl(new GMapTypeControl());

        
        // creo l'oggetto geocoder
        geocoder = new GClientGeocoder();
        
        // creo l'oggetto GDirections
        var e = document.getElementById("tragitto_res");
        gdirections = new GDirections(map, e);
    }
}

function compute_photo_link(photo) {
    var link = 'http://farm';
    link += photo.farm + '.static.flickr.com/';
    link += photo.server + '/';
    link += photo.id + '_' + photo.secret + '.jpg';
    return link;
}

function base58encode(num) {
    alphabet = '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ';
    base_count = alphabet.length;
    encoded = '';
    while (num >= base_count) {
        div = num/base_count;
        mod = (num - (base_count * parseInt(div)));
        encoded = alphabet[mod] + encoded;
        num = parseInt(div);
    }

    if (num) encoded = alphabet[num] + encoded;

    return encoded;
}

function showAddress(address) {
  if (geocoder) {
    geocoder.getLatLng(
      address,
      function(point) {
        if (!point) {
          alert(address + " non trovato");
        } else {
          map.setCenter(point, 16);
          var marker = new GMarker(point);
          map.addOverlay(marker);
          //marker.openInfoWindowHtml(address);
        }
      }
    );
  }
}

/* Centra la mappa sulla citta' dell'utente. Si basa in prima istanza all'ip
 * dell'utente, provando ad ottenere direttamente latitudine e longitudine.
 * Se non riesce, prova a fare il reverse geocoding sul nome della citta'.
 * Se neanche questo riesce, allora la mappa viene centrata su Roma.
 */
function ip_locate(map) {
    $.getJSON('location.php', {}, function(data){
        var lat = data.Latitude;
        var lon = data.Longitude;
        if (lat && lon) {
            map.setCenter(new GLatLng(lat, lon), 13);
        }
        else {
            // Proviamo con il nome della citta'
            var citta = data.City;
            if (citta && geocoder) {
                geocoder.getLatLng(
                    citta,
                    function(point) {
                        if (!point) {
                            map.setCenter(new GLatLng(41.8899, 12.4933), 13); //Roma
                        } else {
                            map.setCenter(point, 16);
                        }
                    }
                );
            } else
                map.setCenter(new GLatLng(41.8899, 12.4933), 13); //Roma
        }
    });
}

function bounding_box() {
    /* another bounding box drawing code
       starting from 2 points
    */
    var bbox = Array();
    var i = 0;
    var listener = GEvent.addListener(map, "click", function(overlay, latlng) {
        if (latlng) {
            bbox[i++] = latlng;
            if (i == 2) {
                var min_lat = Math.min(bbox[0].lat(), bbox[1].lat());
                var min_lng = Math.min(bbox[0].lng(), bbox[1].lng());
                var max_lat = Math.max(bbox[0].lat(), bbox[1].lat());
                var max_lng = Math.max(bbox[0].lng(), bbox[1].lng());
                
                var line1 = new GPolyline([
                        new GLatLng(min_lat, min_lng),
                        new GLatLng(min_lat, max_lng)
                    ], '#FF0000', 5);
                var line2 = new GPolyline([
                        new GLatLng(min_lat, max_lng),
                        new GLatLng(max_lat, max_lng)
                    ], '#FF0000', 5);
                var line3 = new GPolyline([
                        new GLatLng(max_lat, max_lng),
                        new GLatLng(max_lat, min_lng)
                    ], '#FF0000', 5);
                var line4 = new GPolyline([
                        new GLatLng(max_lat, min_lng),
                        new GLatLng(min_lat, min_lng)
                    ], '#FF0000', 5);
                
                map.clearOverlays();
                map.addOverlay(line1);
                map.addOverlay(line2);
                map.addOverlay(line3);
                map.addOverlay(line4);
                GEvent.removeListener(listener);
                
                $('#min_lat').text(min_lat);
                $('#max_lat').text(max_lat);
                $('#min_lng').text(min_lng);
                $('#max_lng').text(max_lng);
            }
        }
    });
}

function radial() {
    var listener = GEvent.addListener(map, "click", function(overlay, latlng) {
        if (latlng) {
            var slider_value = $('#radius_slider').slider('value');
            var lat_radius = (180 * slider_value) / 28000;
            var lng_radius = (360 * slider_value) / 40010;
            var lat_click = latlng.lat();
            var lng_click = latlng.lng();
            $('#radial_lat').text(lat_click);
            $('#radial_lng').text(lng_click);
            map.clearOverlays();
            for (var ang=0; ang<360; ang+=5) {
                var rad = (3.14 * ang) / 180;
                var rad2 = (3.14 * (ang+5)) / 180;
                var line = new GPolyline([
                    new GLatLng(lat_click + Math.sin(rad)*lat_radius, lng_click + Math.cos(rad)*lng_radius),
                    new GLatLng(lat_click + Math.sin(rad2)*lat_radius, lng_click + Math.cos(rad2)*lng_radius)
                ], '#FF0000', 5);
                map.addOverlay(line);
            }
            GEvent.removeListener(listener);
        }
    });
}

/* Removes all the overlays on the map */
function clearMap() {
    map.clearOverlays();
}

/* Cancels all listeners of the click event */
function clearListeners() {
    GEvent.clearListeners(map, "click");
}

/* Calcola il tragitto e lo visualizza sulla mappa */
function computeDirections(from, to) {
    var query_string = "from: " + from + " to: " + to;
    GEvent.clearListeners(gdirections, "error");
    GEvent.clearListeners(gdirections, "addoverlay");
    GEvent.addListener(gdirections, "error", function() {
        var errore = "";
        code = gdirections.getStatus().code;
        switch (code) {
                case 400: { errore = "Errore nella richesta"; }break;
                case 500: { errore = "Errore del server"; }break;
                case 601: { errore = "Indirizzo non specificato."; }break;
                case 602: { errore = "Indirizzo non trovato. Controlla i dati"; }break;
                case 603: { errore = "Indirizzo non disponibile"; }break;
                case 604: { errore = "Rotta non calcolabile"; }break;
                case 610: { errore = "Errore api_key"; }break;
                case 620: { errore = "Stai facendo troppe query"; }break;
        }

        alert(errore);
    });
    GEvent.addListener(gdirections, "addoverlay", function() {
        search_function();
    });
    gdirections.load(query_string,
                     { "locale": "it_IT",
                       "preserveViewPort": true });
}
