/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
// JavaScript Document
google.load("maps", "2.x");
var myPano;
var panoramaOptions;

var map;
var directions;
var gdir;
    var geocoder = null;
    var addressMarker;
var punto_sede;

var address;
var letteredIcon;
  // Create a base icon for all of our markers that specifies the
// shadow, icon dimensions, etc.
var baseIcon ;
var marker;
var markerOptions;
//baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";

// Creates a marker whose info window displays the letter corresponding
// to the given index.
var svClient;
var esistenza_pano=false;
var start ;
var pano;
var tipo_schermo="form_ricerca";
var indirizzo_iniziale = 'test';
var zoom_area=5;
 var advanceTimer = null;
 var selectedStep = null;

 /**
    * The GRoute we are following extracted from the directions response.
    */
    var route;

   /**
    * It turns out that the polyline generated for a driving directions
    * route normally has a lot of repeated vertices. This causes problems
    * when trying to determine how close we are to the next vertex, so it's
    * better to collapse these duplicated vertices out.
    *
    * The array of route vertices with duplicates removed.
    */
    var vertices;

   /**
    * Array that maps the polyline vertex indices to the
    * index of the same point in the vertices array.
    *
    * For example, if the polyline vertices are
    * [a, a, b, c, d, d, e], the vertices array will be
    * [ a, b, c, d, e ] and the vertexMap array will be
    * [ 1, 1, 2, 3, 4, 4, 5 ].
    */
    var vertexMap;

   /**
    * Array that contains the index in the vertices array of
    * the point at the start of the n'th step in the route
    */
    var stepToVertex;

   /**
    * An array that gives the route step number that each
    * point in the vertices array is part of.
    */
    var stepMap;

   /**
    * The current position of the panorama and vehicle marker.
    */
    var currentLatLng;

   /**
    * Metadata for the current panorama including the list of
    * available links, loaded using GStreetviewClient.
    */
    var panoMetaData;

   /**
    * boolean flag set when we are so close to the next vertex that we should
    * check links in the panoramas we load for the next turning we need.
    */
    var close = false;

   /**
    * The direction in degrees from our current location to the next
    * vertex on the route. Used to select the most suitable link to follow.
    */
    var bearing;

   /**
    * The direction from the next vertex on the route to the vertex
    * after that. Used when we are close to a vertex and are looking
    * for links that represent the next turn we need to make.
    */
    var nextBearing;

   /**
    * The index of the vertex we are heading towards on the route in the
    * vertices array.
    */
    var nextVertexId;

   /**
    * GLatLng of the vertex we are heading towards on the route.
    */
    var nextVertex;

   /**
    * An array that at any time contains the GLatLng of each vertex
    * from the start of the current route step to the next vertex
    * ahead of our current position. This is used to work out how
    * far we are along the current step.
    */
    var progressArray;

   /**
    * The distance in meters covered by traversing the points in the
    * progressArray. By subtracting the distance from our current location
    * to the next vertex from this value we find how far along the step
    * we are, and use this to update the progress bar.
    */
    var progressDistance;

   /**
    * Index of the route step we are currently on.
    */
    var currentStep;

   /**
    * The marker on our map that shows the current location. For IE6 this
    * is a standard red maps pushpin. For all other browsers it is a
    * directional arrow.
    */
    var carMarker;

   /**
    * A copy of the current step index used to unhighlight the previously
    * highlighted step in the textual driving directions when the
    * current step changes.
    */
    var selectedStep = null;

   /**
    * boolean flag indicating whether we are currently driving (automatically
    * following) links, or are stationary.
    */
    var driving = false;

  /**
   * Id of the timer that adds a delay between following each link to give the
   * panorama time to load. We need this to cancel the timer if the user clicks
   * Stop while we are waiting to follow the next link.
   */
    var advanceTimer = null;

  /**
   * Delay in seconds between following each link.
   */
    var advanceDelay = 0;

   /**
    * Set up the initial view and register the various event listeners.
    */
   var    filtro_sedi=null;
   var  filtro_regione=null;
   var  filtro_provincia=null;
   var filtro_citta=null;
    var filtro_indirizzo=null;
/* gestione mappa */

var descrizione_finale=null;

function createMarker(point,descrizione,not) {
  // Create a lettered icon for this point using our icon class
baseIcon = new GIcon(G_DEFAULT_ICON);
baseIcon.iconSize = new GSize(25, 25);
baseIcon.shadowSize = new GSize(26, 26);
baseIcon.iconAnchor = new GPoint(20, 20);
baseIcon.infoWindowAnchor = new GPoint(20,20);

  letteredIcon = new GIcon(baseIcon);

  letteredIcon.image = "./images/blue-dot.png";
  //letteredIcon.image = "http://www.google.com/mapfiles/markerA.png";

  // Set up our GMarkerOptions object
  markerOptions = { icon:letteredIcon };
  marker = new GMarker(point, markerOptions);




GEvent.addListener(marker, "click", function() {

	var stringa = descrizione
    var splitted = stringa.split(",");
    var aux="";
    for (i in splitted) {
        aux += splitted[i] + ",";
        if(i==1)
            {
                aux +="<br>";
            }

    }
    var nota_sostituita="";
    //!r! e !fr!
   nota_sostitutiva=new String(not);
   nota_sostitutiva = nota_sostitutiva.replace("!fr!","</span>");
    nota_sostitutiva = nota_sostitutiva.replace("!r!","<span style=color:red>");
   map.openInfoWindowHtml(point,"<b>"+ aux + "</b>" + "<br>" + nota_sostitutiva);


    //setToMap(marker);
    //initialize2(latlng);
    //cambiapannello();
  });
  return marker;
}
function allerta(response)
{
    var point = false;
     if (!response || response.Status.code != 200) {
        alert("Sorry, we were unable to geocode that address");
      } else {
	  // Retrieve the object
      place = response.Placemark[0];

      // Retrieve the latitude and longitude
      point = new GLatLng(place.Point.coordinates[1],
                          place.Point.coordinates[0]);
      }
      return point;
}
 function initialize_streetview()
 {

      pano = new GStreetviewPanorama(document.getElementById("schermo"));
       //svOverlay = new GStreetviewOverlay();
        //map.addOverlay(svOverlay);
       street_view=true;
      var fenwayPOV = {yaw:370.64659986187695,pitch:-20};


    pano.setLocationAndPOV(punto_sede, fenwayPOV);
      GEvent.addListener(pano, "error", handleNoFlash);
      GEvent.addListener(map,"click", function(overlay,latlng) {
          pano.setLocationAndPOV(latlng);
        });
/*
var fenwayPark = new GLatLng(42.345573,-71.098326);
      var fenwayPOV = {yaw:370.64659986187695,pitch:-20};
      alert(fenwayPark);
      pano.setLocationAndPOV(geocoder.getLocations(address, allerta), fenwayPOV);
       
      GEvent.addListener(pano, "error", handleNoFlash);
      GEvent.addListener(map,"click", function(overlay,latlng) {
          pano.setLocationAndPOV(latlng);
        });
*/
     
    }

    function handleNoFlash(errorCode) {
      if (errorCode == 603) {
        alert("Errore: PlugIn Flash non installato");
        return;
      }
      else if (errorCode == 600)
     {
              alert('Non esiste immagine del punto vendita');
              //VisualizzaRicerca();

      }
      else
      {
                  alert("Errore");
       }
    }
function initialize_mappe(indirizzo)
{

    var filtro=null;

    map = new google.maps.Map2(document.getElementById("cartina_info"));
    gdir = new GDirections(map,document.getElementById("directions"));
    
    
    map.checkResize();
    address = indirizzo;

	geocoder = new GClientGeocoder();
    
	geocoder.getLocations(address, addToMap);
    if(filtro_sedi==null)
    {
        filtro="sedi_xml.php";
    }
    else
    {
        filtro="sedi_xml.php?" + filtro_sedi;
    }
  
    GDownloadUrl(filtro, function(data) {
          var xml = GXml.parse(data);
          var markers = xml.documentElement.getElementsByTagName("marker");
          for (var i = 0; i < markers.length; i++) {
              var desc = markers[i].getAttribute("desc");
              var nota = markers[i].getAttribute("nota");
            var latlng = new GLatLng(parseFloat(markers[i].getAttribute("lat")),
                                    parseFloat(markers[i].getAttribute("lng")));

             map.addOverlay(createMarker(latlng,desc,nota));


          }
        });
        /*
	map.removeMapType(G_SATELLITE_MAP);
	map.addControl(new GSmallZoomControl3D());
    */
   

    var customUI = map.getDefaultUI();
        customUI.controls.maptypecontrol = false;
        customUI.controls.menumaptypecontrol = true;
        customUI.controls.scalecontrol=true;
        customUI.controls.maptypecontrol = false;
        
        map.setUI(customUI);


   // initialize_streetview();
  
  }

function addToMap(response)
   {

	    if (!response || response.Status.code != 200) {
        alert("Sorry, we were unable to geocode that address");
      } else {
	  // Retrieve the object
      place = response.Placemark[0];
   
      // Retrieve the latitude and longitude
      point = new GLatLng(place.Point.coordinates[1],
                          place.Point.coordinates[0]);
      indirizzo_iniziale = point;
      map.checkResize();
      // Center the map on this point
      map.setCenter(point, zoom_area);

      // Create a marker
      //marker = new GMarker(point);

      // Add the marker to map
      map.addOverlay(marker);
      punto_sede = point;
	  }
      // Add address information to marker
      //marker.openInfoWindowHtml(place.address);
   }
   function setToMap(spot)
   {


        var zoomsize=map.getZoom();
        map.checkResize();
        if(zoomsize!=16)
        {map.setZoom(16);}
        else
       {
           //alert(zoomsize);
           //GestioneProvince(filtra_provincia);

        }
   }
   function ZommaArea(area)
  {

          var zoom_value;
      if(area=='italia')
          {
              zoom_value=5;
          }
          else if (area=='regione')
          {
              zoom_value=6;
          }
          else if (area=='provincia')
          {
              zoom_value=7;
          }
      geocoder.getLatLng(area, function(point)
      {
            if (!point)
            {
            	alert(area + " non trovato");
            }
            else
            {
            // Center the map on this point

               map.setCenter(point, zoom_value);
            }
        }
	)
  }

       // GEvent.addListener(gdir, "load", onGDirectionsLoad);
       //  GEvent.addListener(gdir, "error", handleErrors);

   function setDirections(fromAddress, toAddress, locale) {
      gdir.load("from: " + fromAddress + " to: " + toAddress,
                { "locale": locale });
    }
 function handleErrors(){
	   if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
	     alert("No corresponding geographic location could be found for one of the specified addresses. This may be due to the fact that the address is relatively new, or it may be incorrect.\nError code: " + gdir.getStatus().code);
	   else if (gdir.getStatus().code == G_GEO_SERVER_ERROR)
	     alert("A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known.\n Error code: " + gdir.getStatus().code);

	   else if (gdir.getStatus().code == G_GEO_MISSING_QUERY)
	     alert("The HTTP q parameter was either missing or had no value. For geocoder requests, this means that an empty address was specified as input. For directions requests, this means that no query was specified in the input.\n Error code: " + gdir.getStatus().code);

	//   else if (gdir.getStatus().code == G_UNAVAILABLE_ADDRESS)  <--- Doc bug... this is either not defined, or Doc is wrong
	//     alert("The geocode for the given address or the route for the given directions query cannot be returned due to legal or contractual reasons.\n Error code: " + gdir.getStatus().code);

	   else if (gdir.getStatus().code == G_GEO_BAD_KEY)
	     alert("The given key is either invalid or does not match the domain for which it was given. \n Error code: " + gdir.getStatus().code);

	   else if (gdir.getStatus().code == G_GEO_BAD_REQUEST)
	     alert("A directions request could not be successfully parsed.\n Error code: " + gdir.getStatus().code);

	   else alert("An unknown error occurred.");

	}
	function onGDirectionsLoad(){
      // Use this function to access information about the latest load()
      // results.

      // e.g.
      // document.getElementById("getStatus").innerHTML = gdir.getStatus().code;
	  // and yada yada yada...
	}
  
