﻿function getDivMap() {
    var mapDiv = null;
    mapDiv = document.getElementById(mapCanvas);
    mapDiv.parentNode.style.display = "block";
    return mapDiv;
}
 
function loadGoogleMap() {
    var map = null;
    var mapDiv = null;
    if (GBrowserIsCompatible()) {
        mapDiv = getDivMap();
        map = new google.maps.Map2(mapDiv);
    }
    return map;
}

function getGDir(map,divPrint,mostraPercorsoTestuale) {
    if(divPrint == "")
    {
        var gdir=new google.maps.Directions();
        setGDirProperty(gdir, false);
    }
    else
    {
      pathDiv = document.getElementById(divPrint); 
      var gdir=new google.maps.Directions(map, pathDiv);
      setGDirProperty(gdir, mostraPercorsoTestuale);
     }
      return gdir;
}

 /* La seguente funzione aggiunge funzionalità alla GoogleMap,quali: zoom in-out, pan, etc. */
function addFunctionMapOnClick(isLocked, controllo3D, labelNav, abilitaClick){
    if (!isLocked) {
        if(controllo3D)
                map.addControl(new google.maps.SmallZoomControl3D());

        if(labelNav) {
                map.addControl(new GNavLabelControl());
                var position = new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(7, 30));
                map.addControl(new GMenuMapTypeControl(), position);
        } else
            map.addControl(new GMenuMapTypeControl());
            
	    if(abilitaClick) {
	        map.enableDoubleClickZoom(); 
	        map.enableContinuousZoom();
	    } else
              map.disableDragging();
            
	    google.maps.Event.addListener(map, "click", function(overlay,point) {
          if (!overlay)
            map.setCenter(point);
        });
    }
}//end addFunctionMap

function setGDirProperty(gdir, mostraPercorsoTestuale) {//mostraPercorsoTestuale=true--> se si deve stampare anche il percorso testuale nella opportuna div
      var reasons=[]; 
      reasons[G_GEO_SUCCESS]            = msg_g_geo_success;
      reasons[G_GEO_MISSING_ADDRESS]    = msg_g_geo_missing_address; 
      reasons[G_GEO_UNKNOWN_ADDRESS]    = msg_g_geo_unknown_address; 
      reasons[G_GEO_UNAVAILABLE_ADDRESS]= msg_geo_unvailable_address; 
      reasons[G_GEO_BAD_KEY]            = msg_geo_bad_key; 
      reasons[G_GEO_TOO_MANY_QUERIES]   = msg_g_geo_too_many_queries; 
      reasons[G_GEO_SERVER_ERROR]       = msg_g_geo_server_error; 
      reasons[G_GEO_BAD_REQUEST]        = msg_g_geo_bad_request; 
      reasons[G_GEO_MISSING_QUERY]      = msg_g_geo_missing_query; 
      reasons[G_GEO_UNKNOWN_DIRECTIONS] = msg_g_geo_unknown_directions; 
      google.maps.Event.addListener(gdir,"error", function() {
          var code = gdir.getStatus().code;
          var reason=msg_code + " " + code;
          if (reasons[code])
            reason = reason + " : " + reasons[code];
          alert(msg_failed_directions + ", " + reason);
          if(mostraPercorsoTestuale) {
            HideDiv(divMap_text);//nel caso di errore viene nascosta la div contenente il percorso testuale
          }
      });
      google.maps.Event.addListener(gdir,"load",function() { 
        layerP = this.getPolyline();
        map.addOverlay(layerP);
        if(mostraPercorsoTestuale)
            ShowDiv(divMap_text);
      });
}



function verifyMarker(address) {
    var geocoder = new google.maps.ClientGeocoder();
    if (geocoder){
        geocoder.getLatLng(address, function(point){
            if(!point)
                alert(address + " " + address_not_found);
        });
    }
}

function ShowDiv(ID){
    document.getElementById(ID).style.display='';
}//end ShowHideDiv

function HideDiv(ID) {
    document.getElementById(ID).style.display='none';
}//end HideDiv

function ShowHideDiv(ID){
	if(document.getElementById(ID).style.display==''){
		document.getElementById(ID).style.display='none';
	}else{
		document.getElementById(ID).style.display='';
	}
}//end ShowHideDiv

function centraMappaCoo(x, y, fattoreZoom) {
     map.setCenter(new google.maps.LatLng(y, x));
     map.setZoom(fattoreZoom);
}

function centraMappa(coo, fattoreZoom) {
     map.setCenter(new google.maps.LatLng(coo[0][0], coo[0][1]));
     map.setZoom(fattoreZoom);
}

 /*
    * aggiungiPuntiInteresse permette di aggiungere alla mappa 1 o più punti
    * di interesse rappresentati da marker.
    * Restituisce il numero di punti aggiunti alla mappa
  */
function aggiungiPuntiInteresseSuMappa(coo, pathIcona, notClickable) {
       var contatore = 0;
       for (i=0; i<coo.length; i++) {
            var point = new google.maps.LatLng(coo[i][0], coo[i][1]);
            var nomeIcona = coo[i][2];
            var iconaTipo = createIconaTipo(nomeIcona, pathIcona);
            var marker = createMarker(point, iconaTipo, coo[i][5], coo[i][3], coo[i][2], coo[i][4], notClickable, coo[i][6]);
            map.addOverlay(marker);
            contatore++;
        }//end for
      return contatore;
}//end addPuntiInteresse

/*
    * CreateMarker permette di creare un marker da applicare sulla mappa.
    * Inoltre vengono settati opportunamente i parametri contenuti
    * nell'openInfoWindowHtml mediante il valore contenuto in html
  */
function createMarker(point, icona, iid, html, cat, inPerc, clic, tooltip){//OK
        var opts = {clickable: clic, icon: icona, title:tooltip}; 
        var marker = new google.maps.Marker(point, opts);
        marker.iid = iid;
        marker.categoria = cat;
        marker.inPercorso = inPerc;
        if (html != "" && html != undefined){
            google.maps.Event.addListener(marker, "click", function(){
                marker.openInfoWindowHtml(html);
            });
        }
        gmarkers.push(marker);
        return marker;
}//end createMarker


function createIconaTipo (nameIcon, pathIcona) {
    var iconaTipo = null;
    if (nameIcon != "") {
        iconaTipo = new google.maps.Icon();
        iconaTipo.image = pathIcona + nameIcon;
        iconaTipo.iconAnchor = new google.maps.Point(12, 15);
        iconaTipo.infoWindowAnchor = new google.maps.Point(8,1);
    }
    else {
        var mylabel = {"url":"overlay.png",
                      "anchor":new google.maps.Point(4,4),
                      "size":new google.maps.Size(12,12)};
        iconaTipo = new google.maps.Icon(G_DEFAULT_ICON);
    }

    return iconaTipo;
}

function costruisciPercorso(coo){//OK
  var strRoute = "";     
  for (i=0; i<coo.length; i++) {
        if(coo[i][4] == 1){
            if (strRoute == "")
                strRoute += "from: ";
            else
                strRoute += " to: ";
        }
        if(coo[i][4] == 1) //se il punto appartiene al percorso allora lo aggiungiamo
            strRoute += coo[i][0] + ", " + coo[i][1];
  }//end for
  return strRoute;
}//end caricaPercorso

function buildPath(coo){
    var routeArray = new Array(); 
    for(i=0; i<coo.length; i++){
        if(coo[i][4] == 1)
        {
            var point = new google.maps.LatLng(coo[i][0], coo[i][1]);
            routeArray.push(point);
        }
    }
    return routeArray;
}

function creaPercorsoDuePunti(from,to,percorsoDrivingWalking,evitaHighways) {
     var evitaAutostrade; 
     var modalitàViaggio; 
     verifyMarker(from);
     verifyMarker(to);
     if(percorsoDrivingWalking == "0")
        modalitàViaggio = G_TRAVEL_MODE_DRIVING; 
     else
        modalitàViaggio = G_TRAVEL_MODE_WALKING;
     if (evitaHighways == "0")
        evitaAutostrade = false;
     else
        evitaAutostrade = true;
     gdir.loadFromWaypoints([from,to],{ getSteps:true, getPolyline:true,"locale": locale,avoidHighways:evitaAutostrade,travelMode:modalitàViaggio});
}//end creaPercorsoDuePunti

function creaPercorsoNPunti(arrayRoute, percorsoDrivingWalking, evitaHighways){
    var evitaAutostrade; 
    var modalitàViaggio; 
    if(percorsoDrivingWalking == "0")
        modalitàViaggio = G_TRAVEL_MODE_DRIVING;
    else
        modalitàViaggio = G_TRAVEL_MODE_WALKING;
    if (evitaHighways == "0")
        evitaAutostrade = false;
    else
        evitaAutostrade = true;
    gdir.loadFromWaypoints(arrayRoute,{ getSteps:true, getPolyline:true,"locale": locale,avoidHighways:evitaAutostrade,travelMode:modalitàViaggio});
}//creaPercorsoNPunti

function mostraInfoWindow(){
if(typeof arr_messaggi != 'undefined'){
     coo = arr_messaggi;
     for(var i = 0; i < coo.length; i++) {
          if (gmarkers[i].iid == iid)
             google.maps.Event.trigger(gmarkers[i], "click");
     }//end for
 }
}//mostraInfoWindow

/*
    * La seguente funzione permette di calcolare il baricentro
    * con il relativo zoom di una mappa, in base ai punti di 
    * interesse massati nel parametro (array di array) denominato
    * cooRoute
*/
function baricentroMap(map, cooRoute) {
    // *** Calcolo per ottenere il baricentro e i limiti di mappa ***
	    var S0 = cooRoute[0][0];
	    var N0 = cooRoute[0][0];
	    var W0 = cooRoute[0][1];
	    var E0 = cooRoute[0][1];
	    var x0 = 0;
	    var y0 = 0;
		
	    for (i = 0;i < cooRoute.length; i++) {
		    S0 = Math.min(cooRoute[i][0], S0);
		    N0 = Math.max(cooRoute[i][0], N0);
		    W0 = Math.min(cooRoute[i][1], W0);
		    E0 = Math.max(cooRoute[i][1], E0);
	    }

	    // Calcolo le medie
	    x0 = (E0 + W0) / 2;
	    y0 = (N0 + S0) / 2;

	    var Alt0 = Math.abs(N0 - S0);
	    var Lar0 = Math.abs(E0 - W0);

	    map.setCenter(new google.maps.LatLng(y0, x0));
        var rectBounds = new google.maps.LatLngBounds(new GLatLng(S0,W0), new google.maps.LatLng(N0,E0));
	    map.setZoom(map.getBoundsZoomLevel(rectBounds));
}// end baricentroMap


function boxclick(box,category) {
  if (box.checked)
      showNotInPercorso(category);
  else
      hideNotInPercorso(category);
}


/*
     * La seguente funzione mostra sulla mappa, i marker 
     * indicati in category
*/      
function showNotInPercorso(category){//
    for (var i=0; i<gmarkers.length; i++){
        if(gmarkers[i].inPercorso == "0")
            if(gmarkers[i].categoria == category)
                gmarkers[i].show();
    }//end for
}//end show


/*
    * La seguente funzione nasconde sulla mappa, i marker 
    * indicati in category
*/
function hideNotInPercorso(category) {
    for (var i=0; i<gmarkers.length; i++){
        if(gmarkers[i].inPercorso == "0")
            if(gmarkers[i].categoria == category)
                gmarkers[i].hide();
    }//end for
    map.closeInfoWindow();
}//end hide


function disegnaCerchio(center, radius, nodes, liColor, liWidth, liOpa, fillColor, fillOpa)
    {
	//trasforma km/gradi
	var latConv = center.distanceFrom(new GLatLng(center.lat()+0.1, center.lng()))/100;
	var lngConv = center.distanceFrom(new GLatLng(center.lat(), center.lng()+0.1))/100;
	//Loop 
	var points = [];
	var step = parseInt(360/nodes)||10;
	for(var i=0; i<=360; i+=step)
	{
	      var pint = new GLatLng(center.lat() + (radius/latConv * Math.cos(i * Math.PI/180)), center.lng() + (radius/lngConv * Math.sin(i * Math.PI/ 180)));
          points.push(pint); 
	}
	points.push(points[0]); 
	liWidth = liWidth||2;
	var poly = new GPolygon(points,liColor,liWidth,liOpa,fillColor,fillOpa);
	bounds = poly.getBounds();
	map.addOverlay(poly);
	map.setZoom(map.getBoundsZoomLevel(bounds));
	map.setCenter(center);
    }


function stampa_div(div_id)
{
    var prt_content = document.getElementById(div_id);
    var win_print = window.open('','','width=1,height=100,left=0,top=0,toolbar=no,scrollbars=yes,status=no,location=no,menubar=no,resizable=no');
    win_print.document.write(prt_content.innerHTML);
    win_print.document.close();
    win_print.focus();
    win_print.print();
    win_print.close();
}
