﻿/*
FUNCTION initialize()
Inizializes Google Maps
*/
var geocoder;
var map;
var infowindow;
var elevator;
var mapBounds;
var regionevalida;

function initialize() {
  geocoder = new google.maps.Geocoder();
  infowindow = new google.maps.InfoWindow();
  // Create an ElevationService
  elevator = new google.maps.ElevationService(); 
  var myLatlng = new google.maps.LatLng(43, 11);
  var myOptions = {
  zoom: 6, //Questo è solo uno zoom di default che viene poi personalizzato nello switch (dominio)
  center: myLatlng,
  draggableCursor: 'pointer', // trasforma il cursore in indicatore
  mapTypeId: google.maps.MapTypeId.TERRAIN,
  mapTypeControl: true,
  mapTypeControlOptions: { style: google.maps.MapTypeControlStyle.DROPDOWN_MENU },
  navigationControlOptions: { style: google.maps.NavigationControlStyle.SMALL }     
  }

  map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);  

  var uvLayer = TMSloader("UV", "CAMPANIA");

  map.overlayMapTypes.push(uvLayer); // Carico di default il layer AVG

  google.maps.event.addListener(map, 'click', queryLocation);

  //definisco alcune variabili globali in funzione dell'URL del sito
  
  // Estraggo dall'URL il dominio di TERZO livello (se esiste), altrimenti il PRIMO livello
  url = location.host.split('.');  
  if (url.length >= 3)
    dominio = url[url.length - 3];
  else
  //Caso dominio di PRIMO livello: posso essere in questo caso quando ad esempio 
  //sono in debug in locale (http://localhost:1550/...)
    dominio = url[0]; 
  
  switch (dominio) {
    case "fondazionepascale":
    case "istitutotumori":
      regionevalida = "Campania";
      minZoom = 8;
      maxZoom = 10;
      minLatLng = new google.maps.LatLng(39, 13);
      maxLatLng = new google.maps.LatLng(42, 16);
      map.setCenter(new google.maps.LatLng(41, 14.5));
      map.setZoom(8);
      break;

    default:
      regionevalida = "all";
      minZoom = 6;
      maxZoom = 6;
      minLatLng = new google.maps.LatLng(36.33918, 12.1333);
      maxLatLng = new google.maps.LatLng(41.94085, 28.01953);
      map.setCenter(new google.maps.LatLng(40, 18));
  }

  mapBounds = new google.maps.LatLngBounds(minLatLng, maxLatLng);
  
  // Add a move listener to restrict the Zoom range
  restrictZoom(minZoom, maxZoom);
}

/*
FUNCTION restrictZoom(minZoom, maxZoom)
Add a move listener to restrict the Zoom range
*/
function restrictZoom(minZoom, maxZoom) {
  google.maps.event.addListener(map, 'zoom_changed', function() {
    if (map.getZoom() > maxZoom) {
      map.setZoom(maxZoom);
    }
    if (map.getZoom() < minZoom) {
      map.setZoom(minZoom);
    }
  });
}  

/*
FUNCTION TMSloader(layerID, locationID)
Constructs an ImageMapType using the provided layerID and locationID 
*/
function TMSloader(layerID, locationID) {
  var Layer = new google.maps.ImageMapType({
    getTileUrl: function(coord, zoom) {
      var ymax = 1 << zoom;
      var y = ymax - coord.y - 1;
      //var currentTime = new Date();
      //currentTime = currentTime.getTime();
      //return "tiles/" + zoom + "/" + coord.x + "/" + y + ".png?"; //+ currentTime;
      //TODO: correggere con il path definitivo
      return "http://www.happysun.it/tiles/" + zoom + "/" + coord.x + "/" + y + ".png?"; //+ currentTime;
    },
    tileSize: new google.maps.Size(256, 256),
    isPng: true,
    maxZoom: 9,
    minZoom: 6,
    opacity: 0.7
  });
  return Layer;
}

///*
//FUNCTION codeAddress()
//Find a location on the map
//*/
function codeAddress() {
  var address = document.getElementById('ctl00_PageContent_address').value;
  if (geocoder) {
    geocoder.geocode({ 'address': address }, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        map.setCenter(results[0].geometry.location);
        map.setZoom(14);
        //TODO: Il marker per ora è nascosto. E' necessario gestire i click sui marker generati dai due tipi
        //di eventi: quelli generato dalla barra di localizzazione (funzione codeAddress())
        //e quelli generati dal click sulla mappa (funzione queryLocation()).
        var marker = new google.maps.Marker({
          //map: map,
          position: results[0].geometry.location,
          title: address
        });
        google.maps.event.addListener(marker, 'click', function(event) {
          map.setZoom(8);
          var infowindow = new google.maps.InfoWindow({
            content: marker.title
          });
          infowindow.open(map, marker);
        });
        //markersArray.push(marker);
      } else {
        alert("Geocode was not successful for the following reason: " + status);
      }
    });
  }
}

/*
FUNCTION queryLocation(event)
Interroga un punto effettuando un reverse geocoding e visualizzando una InfoWindow.
*/
function queryLocation(event) {

  var locations = [];
  var elevation;

  // Retrieve the clicked location and push it on the array
  var clickedLocation = event.latLng;
  locations.push(clickedLocation);

  // Create a LocationElevationRequest object using the array's one value
  var positionalRequest = {
    'locations': locations
  }
  
  if (geocoder) {
      geocoder.geocode({ 'latLng': clickedLocation }, function(results, status) {
//          if (status == google.maps.GeocoderStatus.OK) {
//              if (results[0]) {

                  var localita = findGeocName(results, "locality");
                  var provincia = findGeocName(results, "administrative_area_level_2");
                  var regione = findGeocName(results, "administrative_area_level_1");

                  map.setCenter(clickedLocation);
                  //TODO: Il marker per ora è nascosto. E' necessario gestire i click sui marker generati dai due tipi
                  //di eventi: quelli generato dalla barra di localizzazione (funzione codeAddress())
                  //e quelli generati dal click sulla mappa (funzione queryLocation()).
                  marker = new google.maps.Marker({
                      //map: map,
                      position: clickedLocation
                  });

                  if (elevator) {
                      elevator.getElevationForLocations(positionalRequest, function(results_ELE, status_ELE) {
                          if (status_ELE == google.maps.ElevationStatus.OK) {

                              // Retrieve the first result
                              if (results_ELE[0]) {
                                  elevation = results_ELE[0].elevation;
                              } else {
                                  alert("No elevation results found");
                              }
                          } else {
                              alert("Elevation service failed due to: " + status_ELE);
                          }

                          //Costruisco l'InfoWindow
                          var lat = roundTo(clickedLocation.lat(), 3);
                          var lon = roundTo(clickedLocation.lng(), 3);
                                                   
                          //Se la regione è valida costruisco il corretto infowindow, altrimenti visualizzo un messaggio
                          if ((mapBounds.contains(clickedLocation)) && ((regione == regionevalida) || (regione == '') || regionevalida == 'all')) {

                              /* nell'infowindow ho 2 div, uno con l'immagine di caricamento e uno con l'iframe, al caricamento dell'iframe il loader viene nascosto via javascript */
                              /* per non far comparire scrollbar ho un div che racchiude gli altri 2 con altezza pari all'infowindow e overflow=hidden */
                              var contentstring = '<div style="height:340px; overflow:hidden"><div id="loading_img" style="overflow:auto;"><table width="100%" height="320px" style="vertical-align:middle"><tr><td align="center"><img src="Images/Icone/ajax-loader.gif"/></td></tr></table></div>'
                              + '<div id="iframe" style="width: 440px; height: 320px; float: left; overflow:auto;"><iframe width="440" height="320" frameborder="0" scrolling="no" '
                              + 'src="UVTabs.aspx?LON=' + lon + '&LAT=' + lat + '&ELEV=' + elevation + '&PROV=' + provincia
                              + '&LOC=' + localita + '&REAG=' + regione + '" onload="loadTabs()"></div></div>';

                            } else {
                              //TODO: Spostare il testo della seguente contentstring in una pagina asp (con iframe?) in modo
                              //da gestire facilmente il multilingua. 
                              var contentstring = "Servizio non disponibile per l'area selezionata.";
                            }               
                              infowindow.setContent(contentstring);
                              infowindow.open(map, marker); // apro la infowindow con i risultati
                          }); // end elevator.getElevationForLocations
                  } // end if (elevator)
//              } // end if (results[0])
//          } // end if (status == google.maps.ElevationStatus.OK)
//          else {
//              alert("Geocoder failed due to: " + status);
//          }
      });     //end geocoder.geocode
 } // end  if (geocoder)
}

//funzione per arrotondare il numero di decimali di un numero
function roundTo(value, decimalpositions) {
  var i = value * Math.pow(10, decimalpositions);
  i = Math.round(i);
  return i / Math.pow(10, decimalpositions);
}


/*
FUNCTION findGeocName(results, type)
Cerca il tipo di indirizzo di interesse (es. provincia, regione...)
tra i risultati ottenuti con il reverse geocoding
*/
function findGeocName(results, type) {
  for (var i = 0; i < results.length; i++) {
    if (results[i].types[0] == type) {
      return results[i].address_components[0].long_name;
    }
  }
  return '';
}


