﻿
function ShowMapEditPage()
 {
    if (document.getElementById(ew.Controls['Longitude']).value != "0.00000000000000")
    {   
        var zoom = document.getElementById(ew.Controls['Zoom']).value;
        document.getElementById("showmap_yes").checked = true; //cancella il valore di zoom
        showHideMapForm();
        document.getElementById(ew.Controls['Zoom']).value = zoom;
//        point =  new GLatLng(document.getElementById(ew.Controls['Latitude']).value, document.getElementById(ew.Controls['Longitude']).value);
        centerOnCoords();
        showPin();
    }
 }

function LoadMap_ViewPage()
{
    var lati = document.getElementById(ew.Controls['Latitude']).value.replace(/,/,".");
    var longi = document.getElementById(ew.Controls['Longitude']).value.replace(/,/,".");

    if (lati != "0.00000000000000")
    {   
        //Initialize
        if (GBrowserIsCompatible()) {
            window.onunload = GUnload;
            map = new GMap2(document.getElementById("spazio_mappa"));
            map.addControl(new GLargeMapControl());
	        pinIcon = new GIcon();
            pinIcon.image = "http://www.lecceannunci.it/images/Pin_Google.gif";
            pinIcon.shadow = "http://www.lecceannunci.it/images/Pin_Google_Shadow.gif";
            pinIcon.iconSize = new GSize(48, 50);
            pinIcon.shadowSize = new GSize(48, 50);
            pinIcon.iconAnchor = new GPoint(45, 47);
            pinIcon.infoWindowAnchor = new GPoint(50, 35);
        }
        else {
            alert("<strong>Attenzione, il browser che stai usando non permette la visualizzazione della mappa.</strong>");
        }
    
        //Centra
        point = new GLatLng(lati, longi, true);
        map.setCenter(point, document.getElementById(ew.Controls['Zoom']).value ? parseInt(document.getElementById(ew.Controls['Zoom']).value) : DEFAULT_ZOOM);

        //Mostra Pin
        mOptions = {"clickable":false,"draggable":false,"icon":pinIcon};
        pin_map = new GMarker(new GLatLng(lati, longi,  true), mOptions);
        map.addOverlay(pin_map);        
    }
    else{
        document.getElementById('spazio_mappa').style.display = 'none';
    }
}


function mapInitialize(){
  if (GBrowserIsCompatible()) {
    document.getElementById("spazio_mappa").style.display='block';
    window.onunload = GUnload;
    map = new GMap2(document.getElementById("spazio_mappa"));
    map.addControl(new GLargeMapControl());
	
	
    pinIcon = new GIcon();
    pinIcon.image = "images/Pin_Google.gif";
    pinIcon.shadow = "images/Pin_Google_Shadow.gif";
    pinIcon.iconSize = new GSize(48, 50);
    pinIcon.shadowSize = new GSize(48, 50);
    pinIcon.iconAnchor = new GPoint(45, 47);
    pinIcon.infoWindowAnchor = new GPoint(50, 35);

    GEvent.addListener(map, "dragend", function() {
        point = map.getCenter();
        document.getElementById(ew.Controls['Latitude']).value=point.lat();
        document.getElementById(ew.Controls['Longitude']).value=point.lng();
        showPin();
		});

    GEvent.addListener(map, "zoomend", function() {
        document.getElementById(ew.Controls['Zoom']).value = map.getZoom();
        });

    mapInitialized = true;
	
  }
  else{
    alert("<strong>Attenzione, il browser che stai usando non permette la visualizzazione della mappa.</strong>");
  }
}

function removeTownFromAddress(address, town){
    address = address.toLowerCase();
    firstCityWord = town.split(' ')[0];
    firstCityWord = firstCityWord.replace(/^\s+|\s+$/, '');
    pos = address.indexOf(firstCityWord.toLowerCase());
    if (pos>-1){
        tokens = address.substr(0,pos).split(' ');
        lastword = tokens[tokens.length-2];
        if (lastword && lastword.match('/via|viale|piazza|corso|vicolo/')>-1)
            return address;
        else
            return address.substr(0,pos);
    }
    else
        return address;
}

function searchAddress(address){
  if (!geocoder)
    geocoder = new GClientGeocoder();

  address = address.replace(tip,'');

  if (document.getElementById('town').selectedIndex > 0){
      address = removeTownFromAddress(address,document.getElementById('town').options[document.getElementById('town').selectedIndex].text);
      address = address + ' ' + document.getElementById('town').options[document.getElementById('town').selectedIndex].text;
      if (document.getElementById('city').selectedIndex > 0){
          address = address + ', ' + document.getElementById('city').options[document.getElementById('city').selectedIndex].text;
      }
  }

geocoder.getLocations(
          address,
          function(response){
            if (!response || response.Status.code != 200) {
              help = document.getElementById("help_mappa");
              help.innerHTML="<div class=\"warning\">L'indirizzo non è stato trovato. Si prega di riprovare</div><br>";
              help.style.display='block';
              document.getElementById("spazio_mappa").style.display='none';
            } else {
              if (response.Placemark.length==1){
                help = document.getElementById("help_mappa");
                if (response.Placemark[0].AddressDetails.Accuracy<6){
                  help.innerHTML="<div class=\"warning\">Non è stato trovato l'indirizzo esatto. Assicurarsi di aver digitato correttamente l'indirizzo. In alternativa, spostare la puntina.</div><br>";
                  help.style.display='block';
                }else{
                  help.style.display='none';
                }
                if (!mapInitialized)
                  mapInitialize();
                point =  new GLatLng(response.Placemark[0].Point.coordinates[1], response.Placemark[0].Point.coordinates[0]);
                document.getElementById(ew.Controls['Latitude']).value = point.lat();
                document.getElementById(ew.Controls['Longitude']).value = point.lng();
                if (document.getElementById("spazio_mappa").style.display=='none');{
                  document.getElementById("spazio_mappa").style.display='block';
                }
                centerOnCoords();
                showPin();
                showInfoWindow();
              }else{
                document.getElementById("spazio_mappa").style.display='none';
                help = document.getElementById("help_mappa");
                help.style.display='block';
                help.innerHTML="<div><span class=\"warning\">Sono stati trovati pi&ugrave; risultati. Seleziona l'indirizzo dall'elenco oppure inserisci maggiroi dettagli nel campo di ricerca (CAP, provincia).</span><br><ul>";
                for (i=0;i<response.Placemark.length;i++){
                  help.innerHTML += "<li class=\"list\" style='margin-left:15px'><a href='#' onclick=\"document.getElementById('spazio_mappa').style.display='block';document.getElementById(ew.Controls['Longitude']).value='" + response.Placemark[i].Point.coordinates[0] + "';document.getElementById(ew.Controls['Latitude']).value='" + response.Placemark[i].Point.coordinates[1] + "';centerOnCoords();showPin();document.getElementById('help_mappa').style.display='none';return false;\">" + response.Placemark[i].address + "</a></li>";
                }
                help.innerHTML += "</ul></div>";
              }
            }
          }
        );
}

function centerOnCoords(panning){
  if (!mapInitialized)
    mapInitialize();
  point = new GLatLng(document.getElementById(ew.Controls['Latitude']).value, document.getElementById(ew.Controls['Longitude']).value, true);
  if (panning){
    map.setZoom(document.getElementById(ew.Controls['Zoom']).value ? parseInt(document.getElementById(ew.Controls['Zoom']).value) : DEFAULT_ZOOM);
    map.panTo(point);
  } else
    map.setCenter(point, document.getElementById(ew.Controls['Zoom']).value ? parseInt(document.getElementById(ew.Controls['Zoom']).value) : DEFAULT_ZOOM);
}

function removePin(){
  if (pin_map){
    map.removeOverlay(pin_map);
  }
  
}

function showPin()
{
  removePin();

  mOptions = {"clickable":false,"title":"Trascina la puntina nel punto desiderato","draggable":true,"icon":pinIcon};
  pin_map = new GMarker(new GLatLng(document.getElementById(ew.Controls['Latitude']).value,  document.getElementById(ew.Controls['Longitude']).value,  true), mOptions);

  GEvent.addListener(pin_map,"dragstart",
          function (){
            pin_map.closeInfoWindow();
          }
  );
  GEvent.addListener(pin_map,"dragend",
          function (){
            point = pin_map.getPoint();
            document.getElementById(ew.Controls['Latitude']).value = point.lat();
            document.getElementById(ew.Controls['Longitude']).value = point.lng();
            centerOnCoords(true);
          }
  );

  map.addOverlay(pin_map);        
}

function showInfoWindow(){
  var tipNode = document.createElement('div');
  tipNode.style.width = '200px';
  tipNode.style.height = '30px';
  tipNode.id = 'tip';
  tipNode.innerHTML='Se vuoi, puoi trascinare la puntina nella posizione desiderata.';
  pin_map.openInfoWindowHtml(tipNode);
}

function showHideMapForm(){
  if (document.getElementById("showmap_yes").checked){
    document.getElementById("inputmap").style.display='block';
    document.getElementById(ew.Controls['Zoom']).value='16';
  }
  else{
    document.getElementById(ew.Controls['Latitude']).value='0';
    document.getElementById(ew.Controls['Longitude']).value='0';
    document.getElementById(ew.Controls['Zoom']).value='16';
    document.getElementById("spazio_mappa").style.display='none';
    document.getElementById("inputmap").style.display='none';
    document.getElementById("help_mappa").style.display='none';
    document.getElementById('map_search').value=tip;
  }
}

////////////////////////////////////// FINE MAPPA
