var timeout         = 500;
var closetimer		= 0;
var ddmenuitem      = 0;
var catList = new Array();
var departureOk = 0;
var destinationOk = 0;
var markersToRemove = new Array();
var markerClicked = 0;
var flag_cotral_on_map = 0;

// __MDS__
// confini della mappa

var allowedBounds = null;

// /__MDS__

$(document).ready(function() { // ON-DOM READY

	//$("a[rel='overlay']").colorbox();
	//$("a[rel='overlay']").colorbox({iframe:true, innerWidth:425, innerHeight:344});
	$(".overlay_ext").colorbox({width:"390px", height:"580px", iframe:true});
	$(".viabilita_lazio").colorbox({width:"500px", inline:true, href:"#viabilita_lazio"});
	$(".roadmap").colorbox({width:"500px", height:"500px", inline:true, href:"#roadmap"});	
	$(".chi_siamo").colorbox({width:"500px", height:"500px", inline:true, href:"#chi_siamo"});
	$(".overlay_video").colorbox({width:"390px", height:"380px", iframe:true});
	$(".overlay_audio").colorbox({width:"390px", height:"380px", iframe:true});


	$('.form_osservazione').ajaxForm(function(data) {
		if (data==1){
			$('.send_error').hide();
			$('.send_success').slideDown().delay(5000).slideUp();
			$('.form_osservazione').resetForm();
		} else if (data==2){
			$('.send_error').slideDown().delay(5000).slideUp();
		} else if (data==3){
			$('.send_error').slideDown().delay(5000).slideUp();
		}
	});
	
	$(".menu_ricerca").hover(function () {
		$(".menu_ricerca li form").toggle();
	});
	$(".menu_ricerca li").hover(function () {
		$(this).toggleClass("hover");
	});
	$(".menu_ricerca li a").click(function () {
        return false;
	});

  $.ajaxSetup({
  		type: 'GET',
  		timeout: 30000,
          	contentType:  "application/json; charset=ISO-8859-1",
  		error: function(xhr) {
  			$('#debug').append('Error: ' + xhr.status + ' ' + xhr.statusText);
  		}
  });

  $('#loading').hide();
  $('#loading').ajaxStart(function() {
		$(this).show();
	}).ajaxSend(function() {
		$(this).show();
	}).ajaxComplete(function() {
		$(this).hide();
  });

  $('#removeRoute').hide();
  $("#removeRoute").click(function(){
      map.clearOverlays();
      $('#routeDirections').html("");
      find_poi(catList);
      $("#removeRoute").hide();
      $(".come_fonti_it .htabs li.last").hide();
      $(".come_fonti_it .htabs li.first a").trigger('click');
  });

  $('.menu_ricerca input').each(function(i){this.checked=false;}); // rimuove i check da tutte le checkboxes
  $('.menu_ricerca input').click(function(){
     //checkbox_manager();
     if(this.checked){
            buildCatList("check",this.value);
        }
        else{
            markerClicked = 0;
            buildCatList("uncheck",this.value);
     }
  });

  aggiornaEventi();
  aggiornaFreetext();

	$(".menu_geocoding").tabs({cssSelected: "on"});
	$(".bollettino_avvisi").tabs({cssSelected: "on"});
	$(".come_fonti_it").tabs({cssSelected: "on"});
	$(".close_pad span").click(function () {
	    $(".menu_geocoding .htabs li.hide a").trigger('click');
		$(".menu_geocoding .absolute").hide();
		$(".menu_geocoding .htabs li a").removeClass("on");
	});

	$("#benvenuto .b_fonti").click(function () {
		$(".come_fonti_it .htabs a[href='#fonti']").trigger('click');
		return false;		
	});
	$("#benvenuto .b_contatti").click(function () {
		$(".come_fonti_it .htabs a[href='#contatti']").trigger('click');
		return false;		
	});




});


function initialize() {
  if (GBrowserIsCompatible()) {
    map = new GMap2(document.getElementById("map_canvas"));

    var mapTypeControl = new GMapTypeControl();
    var topRight = new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(10,10));
    var topRightZoom = new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(10,40));
    map.addControl(mapTypeControl, topRight);

    map.addControl(new GLargeMapControl3D(), topRightZoom);


    map.setCenter(new GLatLng(45.476277, 9.094570), 11);
    //map.setUIToDefault();



    geocoder = new GClientGeocoder();

    gdir = new GDirections(map, document.getElementById("routeDirections"));
    GEvent.addListener(gdir, "load", onGDirectionsLoad);
    GEvent.addListener(gdir, "error", handleErrors);

    map.disableScrollWheelZoom();

    baseIcon = new GIcon();
    //baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
    baseIcon.iconSize = new GSize(27, 33);
    //baseIcon.shadowSize = new GSize(37, 34);
    baseIcon.iconAnchor = new GPoint(9, 34);
    baseIcon.infoWindowAnchor = new GPoint(9, 2);
    //baseIcon.infoShadowAnchor = new GPoint(18, 25);

    eventIcon = new GIcon();
    //eventIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
    eventIcon.iconSize = new GSize(33, 33);
    //eventIcon.shadowSize = new GSize(37, 34);
    eventIcon.iconAnchor = new GPoint(9, 34);
    eventIcon.infoWindowAnchor = new GPoint(9, 2);
    //eventIcon.infoShadowAnchor = new GPoint(18, 25);

// __MDS__
//LIMTAZIONE DELLO ZOOM

	map.setMapType(G_NORMAL_MAP);
	G_NORMAL_MAP.getMinimumResolution = function()
 	{
	 	return dMIN_ZOOM;
	};

 	G_NORMAL_MAP.getMaximumResolution = function()
 	{
	 	return dMAX_ZOOM;
	}; 



	
 allowedBounds = new GLatLngBounds(new GLatLng(dMIN_LAT,dMIN_LON), new GLatLng(dMAX_LAT,dMAX_LON));

 // If the map position is out of range, move it back
// Add a move listener to restrict the bounds range


    GEvent.addListener(map, "move",function(){
		
		checkBounds();	
 	});

 // /__MDS__


    GEvent.addListener(map, "zoomend", function() {

          markerClicked = 0;
          getReport();
          if(catList.length > 0) find_poi(catList);
    });

    GEvent.addListener(map, "moveend", function() {
		
          getReport();
          if(catList.length > 0) find_poi(catList);
		
    });

    GEvent.addListener(map, 'infowindowclose', function() {
          flag_cotral_on_map = 0;
    });


    /*
    for (i=0; i<pointTitle.length; i++){
       var marker = createMarker(i, new GPoint(pointLon[i],pointLat[i]), pointTitle[i] + '<br/>' + pointInfo[i]);
       map.addOverlay(marker);
    }
    */


    getReport();

    /*

    var roma = new GLatLng(41.934922, 12.500813);
    panoramaOptions = { latlng:roma };
    myPano = new GStreetviewPanorama(document.getElementById("street_view"), panoramaOptions);
    GEvent.addListener(myPano, "error", handleNoFlash);
    */


  }
}

// __MDS__
// Contolla l'uscita fuori dai bordi della massima bounding box ammesssa
	function checkBounds()
 	{
	//alert ('check bounds');
 	// Perform the check and return if OK
	 if (allowedBounds.contains(map.getCenter()))
	 {
	 	return;
	 }
	  // It`s not OK, so find the nearest allowed point and move there
	 var C = map.getCenter();
	 var X = C.lng();
	 var Y = C.lat();

	 var AmaxX = allowedBounds.getNorthEast().lng();
	 var AmaxY = allowedBounds.getNorthEast().lat();
	 var AminX = allowedBounds.getSouthWest().lng();
	 var AminY = allowedBounds.getSouthWest().lat();

	 if (X < AminX) {X = AminX;}
	 if (X > AmaxX) {X = AmaxX;}
	 if (Y < AminY) {Y = AminY;}
	 if (Y > AmaxY) {Y = AmaxY;}
	 //alert ("Restricting "+Y+" "+X);
	 map.setCenter(new GLatLng(Y,X));
 } 

// /__MDS__
/*
function handleNoFlash(errorCode) {
      if (errorCode == FLASH_UNAVAILABLE) {
        alert("Error: Flash doesn't appear to be supported by your browser");
        return;
      }
}
*/


function onGDirectionsLoad(){

    $("#removeRoute").show();
    $(".come_fonti_it .htabs li.last").show();
    $(".come_fonti_it .htabs li.last a").trigger('click');

    $('#itinerario').show();
    departureOk = 0;
    destinationOk = 0;


}

function aggiornaEventi(){

    var eventiHTML="";

    $.ajax({
    		type: "GET",
            url: servicesUrl+"/bollettinoEventi.php?start=0&items=90",
    		dataType: "jsonp",
    		jsonp: "jsonp_callback",
    		success: function(jsonp) {
                try{

        			$.each(jsonp, function(entryIndex, entry) {
			              var bInsideMaxBoundingBox = entry.puntomediano.lat>dMIN_LAT && entry.puntomediano.lat<dMAX_LAT && entry.puntomediano.long>dMIN_LON && entry.puntomediano.long<dMAX_LON;
//__MDS__	

				if (bInsideMaxBoundingBox )
				{
                            	//eventiHTML += "<div class='eventi_titolo'>"+entry.titolo+"</div><div class='eventi_desc'>"+entry.descrizione+"</div>";
	                            eventiHTML += "<div class='evento' title='Vedi sulla mappa' lat='"+entry.puntomediano.lat+"' lon ='"+entry.puntomediano.long+"'><img src='./images/icone/"+entry.cause[0].icon+".gif' /><div><p><span>"+entry.data+"</span></p><h2>"+entry.titolo+"</h2><p>"+entry.descrizione+"</p></div></div>";
				}
				else
				{
					eventiHTML += "<div class='evento evento_no_geo' title='Evento non georeferenziato' lat='"+entry.puntomediano.lat+"' lon ='"+entry.puntomediano.long+"'><img src='./images/icone/"+entry.cause[0].icon+".gif' /><div><p><span>"+entry.data+"</span></p><h2>"+entry.titolo+"</h2><p class='info_evento_non_geo hide'>Evento non georeferenziato</p><p>"+entry.descrizione+"</p></div></div>";

				}
// /__MDS__

                    });
                    $(".eventi").html(eventiHTML);
					$(".evento").hover(function () {
						$(this).toggleClass("evento_on");
					});
                    $('.evento').click(function(){
			   
                          //console.log($(this).attr('lat'));
                          var latEvento = $(this).attr('lat');
                          var longEvento = $(this).attr('lon')-0.06;

			     var bInsideMaxBoundingBox = latEvento >dMIN_LAT && latEvento <dMAX_LAT && longEvento >dMIN_LON && longEvento <dMAX_LON;
//__MDS__			    				
			     if (bInsideMaxBoundingBox)
			     {
                          	map.setCenter(new GLatLng(latEvento, longEvento),12);
			     }

			     else
			     {
				/*
				L'evento ha coordinate 0, 0 
				*/
				;
			     }
// /__MDS__
                          //var lat = $('.evento')
                          //map.setCenter(latEvento, longEvento);

                    });

			$(".evento_no_geo").click(function(){
// __SS__
			if ($(".info_evento_non_geo", this).is(":hidden")) {
				$(".info_evento_non_geo", this).slideDown("fast").delay(5000).slideUp("fast");
			} 
			
			// $(".info_evento_non_geo", this).slideDown("fast").delay(5000).slideUp("fast");
// /__SS__
		});

                }
                catch(error){

                }
    		}
    });


}

function aggiornaFreetext(){      // http://infomob-20.svi.local

        var freetextHTML="";
        $.ajax({
    		type: "GET",
            //url: "http://infomob-20.svi.local/bollettinoFreetext.php?start=0&items=90",
            url: servicesUrl+"/bollettinoFreetext.php?start=0&items=90",
    		dataType: "jsonp",
    		jsonp: "jsonp_callback",
    		success: function(jsonp) {
                try{
        			$.each(jsonp, function(entryIndex, entry) {


                        
                        if (entry.content!=""){
                            freetextHTML += "<div class='freetext_titolo'>"+entry.titolo+"</div><div class='freetext_desc'><p>"+entry.descrizione+"</p><p class='visualizza_estesa' style='cursor:pointer' onclick='$(this).next().next().toggle(); $(this).next().toggle(); $(this).hide()'><a>Leggi tutto</a></p><p class='chiudi_estesa' style='cursor:pointer' onclick='$(this).next().toggle(); $(this).prev().toggle(); $(this).hide()'><a>Nascondi</a></p><p class='freetext_estesa'>"+entry.content+"</p></div>";
                        }
                        else{
                            freetextHTML += "<div class='freetext_titolo'>"+entry.titolo+"</div><div class='freetext_desc'><p>"+entry.descrizione+"</p></div>";
                        }



                    });
                    $(".freetext").html(freetextHTML);
                    $(".freetext_estesa").hide();
                    $(".chiudi_estesa").hide();
                }
                catch(error){

                }
    		}
        });


}


function buildCatList(action, catCode){

        if(action=="uncheck"){

				catList = $.grep(catList, function(a) {
					return (a != catCode);
	            });
		}
		else{
				catList.push(catCode);
		}
        find_poi(catList);
}
/*
function removeAllMarkers(){
    var marker = map.getFirstMarker();
	while (marker != null )
    {
		marker.remove();
		marker = map.getFirstMarker();
    }
}
*/
function removeAllMarkers(){

  var marker = map.getFirstMarker();

  //console.log(map.getMarkerCount());

  markersToRemove = [];

  while (marker != null)
  {
    //console.log(marker.getUserData2()+" @@ "+(marker.getUserData2() == ""));
  	if(marker.getId() != markerClicked){


        if(marker.getUserData2() == "") markersToRemove.push(marker.getId());
  	}
    else{
      //console.log("Marker da salvare "+marker.getId());
    }
  	marker = map.getNextMarker();
  }

  deleteSelectedMarkers();
  //console.log(markersToRemove.length);

}

function deleteSelectedMarkers(){

    $.each(markersToRemove, function(entryIndex, entry){
        var markerToDelete = map.getMarkerById(markersToRemove[entryIndex]);
        markerToDelete.remove();
        //console.log("Id del Marker da cancellare "+markerToDelete.getId());
    });


}
function find_poi(cat){


    $('#search_results').children('.poilist').html("");


    if(!flag_cotral_on_map) removeAllMarkers();


       // setDirections(document.forms["directionsForm"].from.value, document.forms["directionsForm"].to.value, "it");



    //getReport();

    if(typeof(singleSearchMarker) != "undefined") map.addOverlay(singleSearchMarker);

    var formattedCatList = "";
    var flagCotral = 0;

	for(n=0;n<cat.length;n++){
	    if(cat[n] == "COTRAL"){

            flagCotral = 1;
	    }
        else{
		    formattedCatList += "&cat[]="+cat[n];
        }
    }

    var bounds = map.getBounds();
    var zoom = map.getZoom();
    var Min_Lon = bounds.getSouthWest().lng();
    var Min_Lat = bounds.getSouthWest().lat();
    var Max_Lon = bounds.getNorthEast().lng();
    var Max_Lat = bounds.getNorthEast().lat();
    //alert(servicesUrl-sa:8184/getPoi.php?x_min="+Min_Lon+"&y_min="+Min_Lat+"&x_max="+Max_Lon+"&y_max="+Max_Lat+"&cat="+cat+"");
    //exit();


    $.ajax({
    		type: "GET",
            url: servicesUrl+"/getPoi.php?z="+zoom+"&x_min="+Min_Lon+"&y_min="+Min_Lat+"&x_max="+Max_Lon+"&y_max="+Max_Lat+""+formattedCatList+"",
    		dataType: "jsonp",
    		jsonp: "jsonp_callback",
    		success: function(jsonp) {
                try{
        			$.each(jsonp, function(entryIndex, entry) {

                            var latlng = new GLatLng(entry.POI_N_LATITUDINE, entry.POI_N_LONGITUDINE);
                            var poi_marker = createMarker("", latlng, entry.CATEGORIA_T_CODICE, entry.POI_T_NOME, entry.POI_T_SITE, entry.POI_LOGICO, "",  entry.CATEGORIA_T_NOME);
                            map.addOverlay(poi_marker);
                            /*
                            if(entry.POI_LOGICO != "T"){
                                $('#'+entry.CATEGORIA_T_CODICE+'').append("<p>"+entry.POI_T_NOME+" "+entry.POI_T_SITE+"</p>");
                            }
                            */

                    });

                }
                catch(error){

                }
    		}
    });

    if(flagCotral){

          $.ajax({
        		type: "GET",
                url: servicesUrl+"/getFermateCotral.php?z="+zoom+"&x_min="+Min_Lon+"&y_min="+Min_Lat+"&x_max="+Max_Lon+"&y_max="+Max_Lat+"",
        		dataType: "jsonp",
        		jsonp: "jsonp_callback",
        		success: function(jsonp) {
                    try{
            			$.each(jsonp, function(entryIndex, entry) {


                                  var latlng = new GLatLng(entry.LATITUDINE, entry.LONGITUDINE);
                                  var poi_marker = createMarker("", latlng, "COTRAL", entry.NOME, entry.PALINA, entry.POI_LOGICO, "",  "Fermata Cotral", entry.DESCRIZIONECOMUNE, entry.SIGLAPROVINCIA);
                                  map.addOverlay(poi_marker);
                                  //$('#COTRAL').append("<p>"+entry.NOME+"</p>");



                        });
                    }
                    catch(error){

                    }
        		}
          });
    }

}

function getReport(){

    var htmlEventiTraffico = "";
    var bounds = map.getBounds();

    var Min_Lon = bounds.getSouthWest().lng();
    var Min_Lat = bounds.getSouthWest().lat();
    var Max_Lon = bounds.getNorthEast().lng();
    var Max_Lat = bounds.getNorthEast().lat();
    //console.log(servicesUrl+"/findReport.php?x_min="+Min_Lon+"&y_min="+Min_Lat+"&x_max="+Max_Lon+"&y_max="+Max_Lat+"&anas=1&entilocali=1&forzedipolizia=1&gestoriautostrade=1&lt=1&st=1&los=1&urb=1&exurb=1");


    $.ajax({
    		type: "GET",
            url: servicesUrl+"/findReport.php?x_min="+Min_Lon+"&y_min="+Min_Lat+"&x_max="+Max_Lon+"&y_max="+Max_Lat+"&anas=1&entilocali=1&forzedipolizia=1&gestoriautostrade=1&lt=1&st=1&los=1&urb=1&exurb=1",
    		dataType: "jsonp",
    		jsonp: "jsonp_callback",
    		success: function(jsonp) {
               try{
        			$.each(jsonp, function(entryIndex, entry) {
                        for(k=0;k<entry.locations.length;k++){
                            var latlng = new GLatLng(entry.locations[k].lat, entry.locations[k].long);
                            var marker = createMarker(entry.id, latlng, entry.cause[0].icon, entry.descrizione, entry.titolo, "", entry.data);
                            map.addOverlay(marker);
                        }
                        htmlEventiTraffico += "<p>"+entry.descrizione+"</p>";


                    });


                    //$('#eventi_traffico').html(htmlEventiTraffico);
               }
               catch(error){

               }
    		}
    });
}

function closeOtherBalloons(marker_id){

   var marker = map.getFirstMarker();
    while (marker != null)
    {

    	if(marker.getId() != marker_id){
            PdMarkerClose(marker.getId());

    	}
    	marker = map.getNextMarker();
    }

}


function hilightGroup(group_id){

    var marker = map.getFirstMarker();
    while (marker != null)
    {
        //console.log(marker.getUserData2());
    	if(marker.getUserData() == group_id){
            marker.setImage("./images/icone/on_"+marker.getUserData2()+".png"); // change graphic
	        marker.topMarkerZIndex(); // bring marker to top

    	}
    	marker = map.getNextMarker();
    }
}

function  resetGroup(group_id){

    var marker = map.getFirstMarker();
    while (marker != null)
    {

    	if(marker.getUserData() == group_id){
            marker.restoreImage();
	        marker.restoreMarkerZIndex();

    	}
    	marker = map.getNextMarker();
    }
}

function getLineeCotral(palina){

        var htmlLineeCotral = "";

        $.ajax({
    		type: "GET",

    		url: servicesUrl+"/getLineeCotral.php?palina="+palina+"",
    		dataType: "jsonp",
    		jsonp: "jsonp_callback",
    		success: function(jsonp) {
    		  try{
                 htmlLineeCotral += "<ul>";
    		     $.each(jsonp, function(entryIndex, entry) {
                    htmlLineeCotral += ("<li><a onclick=\"javascript:hilightLineaCotral('"+entry.linea+"');\">"+entry.NOMEESTESO+"</a></li>");
                    //htmlLineeCotral += ("<a onclick=\"javascript:hilightLineaCotral('"+entry.linea+"');\">"+entry.NOMEESTESO+"</a>");
                 });
                 htmlLineeCotral += "</ul>";
              }catch(error){}

              $(".lineeCotral").addClass('hilightLinea').html(htmlLineeCotral);
              var infoWindow = map.getInfoWindow();
              var point = infoWindow.getPoint();
              infoWindow.reset(point, null, new GSize($('#lista_linee').width(),$('#lista_linee').height()));
              map.panBy(new GSize(0,70));

    		}
    	});

        /*
        $("#message").appendTo(map.getPane(G_MAP_FLOAT_SHADOW_PANE));
        //map.panTo(marker.getPoint());
        var markerOffset = map.fromLatLngToDivPixel(marker.getPoint());
        $("#message").show().css({ top:markerOffset.y, left:markerOffset.x });
        */
}

function centerMap(lat, lng){
    map.setCenter(new GLatLng(lat, lng),13);
    //map.setZoom(11);
}

function centerMap(lat, lng, iZoom){
    map.setCenter(new GLatLng(lat, lng),13);
    map.setZoom(iZoom);
}

function hilightLineaCotral(LineId){

    $.ajax({
    		type: "GET",
            url: servicesUrl+"/getLineaCotral.php?idLinea="+LineId+"",
    		dataType: "jsonp",
    		jsonp: "jsonp_callback",
    		success: function(jsonp) {
    		//removeAllMarkers();
            find_poi(catList);
                try{
        			$.each(jsonp, function(entryIndex, entry) {

                            var latlng = new GLatLng(entry.LATITUDINE, entry.LONGITUDINE);
                            var poi_marker = createMarker("", latlng, "COTRAL_HILIGHT", entry.NOME, entry.PALINA, "F", "", "Fermate Cotral" );
                            map.addOverlay(poi_marker);

                    });
                    flag_cotral_on_map = 1;
                }
                catch(error){

                }
    		}
    });

    /*
    var marker = map.getFirstMarker();
    while (marker != null)
    {

    	if(marker.getUserData() == LineId){
    	  alert("Ciao");
            marker.setImage("http://www.google.com/mapfiles/marker.png"); // change graphic
	        marker.topMarkerZIndex(); // bring marker to top

    	}
    	marker = map.getNextMarker();
    }
    */

}

function createMarker(group_id, point, icon_code, desc, desc2, flag_logico, data_evento, categoria_poi, comune, provincia) {

  /*
  •	AER  -> AEROPORTI
  •	MET -> METROPOLITANE
  •	FS -> STAZIONI FERROVIARIE
  •	PARK -> PARKING – GARAGE
  •	TAXI -> TAXI
  •	TRAGH -> TRAGHETTI
  •	DIST -> DISTRIBUTORI CARBURANTE
  */

  var marker;

   if(group_id != ""){
      //console.log("desc: "+desc+" desc2: "+desc2+" icon_code: "+icon_code);
      //console.log("./images/icone/"+icon_code+".gif");
      eventIcon.image = "./images/icone/"+icon_code+".png";

      marker = new PdMarker(point, eventIcon);
      marker.setCursor("help");

      marker.setUserData(group_id);
      marker.setUserData2(icon_code);

      GEvent.addListener(marker, "mouseover", function() {
            hilightGroup(marker.getUserData());
      });

      GEvent.addListener(marker, "mouseout", function() {
            resetGroup(marker.getUserData());
      });

      GEvent.addListener(marker, "click", function() {
        //$(this).trigger("mouseout");
        var html = "<div class='contFloat balloon'><img src='./images/icone/"+icon_code+".png' /><div><p><span>"+data_evento+"</span></p><h2>"+desc2+"</h2><p>"+desc+"</p></div></div>";
        //marker.setDetailWinHTML(html);
		markerClicked = marker.getId();
		marker.openInfoWindowHtml(html);
        //closeOtherBalloons(marker.getId());
            //openBalloon(marker, group_id);
      });


   }
   else{

       if(flag_logico == "T"){ // **** GESTIONE POI LOGICI ****

        switch (icon_code){


         case "COTRAL":
              baseIcon.image = "./images/icone/l_cotral.png";
         break;

         case "TRLOC":
              baseIcon.image = "./images/icone/l_trasporti_locali.png";
         break;

         case "AER":
              baseIcon.image = "./images/icone/l_aereo_civili.png";
         break;

         case "AERAL":
              baseIcon.image = "./images/icone/l_aereo_altro.png";
         break;

         case "AERMI":
              baseIcon.image = "./images/icone/l_aero_militari.png";
         break;

         case "MET":
              baseIcon.image = "./images/icone/l_metro.png";
         break;

         case "FS":
              baseIcon.image = "./images/icone/l_ferrovie.png";
         break;

         case "PARK":
              baseIcon.image = "./images/icone/l_parking.png";
         break;

         case "TAXI":
              baseIcon.image = "./images/icone/l_taxi.png";
         break;

         case "POCOM":
              baseIcon.image = "./images/icone/l_porti_commerciali.png";
         break;

         case "POMIL":
              baseIcon.image = "./images/icone/l_porti_militari.png";
         break;

         case "POAL":
              baseIcon.image = "./images/icone/l_porti_altro.png";
         break;

         case "TRAGH":
              baseIcon.image = "./images/icone/l_traghetti.png";
         break;

         case "DIST":
              baseIcon.image = "./images/icone/l_fuel.png";
         break;

         default:
              baseIcon.image = "http://www.google.com/mapfiles/marker_yellow.png";
         break;

       }

  }
  else{                   // **** GESTIONE POI FISICI ****


        switch (icon_code){


         case "COTRAL":
              baseIcon.image = "./images/icone/cotral.png";
         break;

         case "COTRAL_HILIGHT":
              baseIcon.image = "./images/icone/on_cotral.png";
         break;

         case "TRLOC":
              baseIcon.image = "./images/icone/trasporti_locali.png";
         break;

         case "AER":
              baseIcon.image = "./images/icone/aereo_civili.png";
         break;

         case "AERAL":
              baseIcon.image = "./images/icone/aereo_altro.png";
         break;

         case "AERMI":
              baseIcon.image = "./images/icone/aero_militari.png";
         break;

         case "MET":
              baseIcon.image = "./images/icone/metro.png";
         break;

         case "FS":
              baseIcon.image = "./images/icone/ferrovie.png";
         break;

         case "PARK":
              baseIcon.image = "./images/icone/parking.png";
         break;

         case "TAXI":
              baseIcon.image = "./images/icone/taxi.png";
         break;

         case "POCOM":
              baseIcon.image = "./images/icone/porti_commerciali.png";
         break;

         case "POMIL":
              baseIcon.image = "./images/icone/porti_militari.png";
         break;

         case "POAL":
              baseIcon.image = "./images/icone/porti_altro.png";
         break;

         case "TRAGH":
              baseIcon.image = "./images/icone/traghetti.png";
         break;

         case "DIST":
              baseIcon.image = "./images/icone/fuel.png";
         break;

         default:
              baseIcon.image = "http://www.google.com/mapfiles/marker_yellow.png";
         break;

       }

    }

    marker = new PdMarker(point, baseIcon);



    //marker.setHoverImage("http://www.google.com/mapfiles/dd-start.png");
    marker.setCursor("help"); // http://www.quirksmode.org/css/cursor.html
    //marker.setTitle(pointTitle[i]);
    if(icon_code.lastIndexOf("COTRAL") == -1){    // ******poi non cotral*****

        if(flag_logico == "T"){
            var htmlPoiLogico = "<div class='contFloat balloon'><img src='"+baseIcon.image+"' /><div><h2>"+desc+"</h2><p>"+desc+" in questa zona</p><p class='more_info'>Fare click <a onClick=\"javascript:$(this).parent().hide(); centerMap("+point.lat()+","+point.lng()+")\">qui</a> per espandere la visuale ad un maggior dettaglio</div></div>";
          //marker.setDetailWinHTML(htmlPoiLogico);

			GEvent.addListener(marker, "click", function() {
			    markerClicked = marker.getId();
				marker.openInfoWindowHtml(htmlPoiLogico);
			});

        }
        else{

            var testo_link = "";
            //console.log("desc: "+desc+" desc2: "+desc2);
            if(desc2 != null){
                if(icon_code == "TRLOC"){
                    testo_link = "E' possibile ottenere maggiori informazioni sul trasporto locale facendo click ";
                }
                else if(icon_code == "MET"){
                    testo_link = "E' possibile ottenere maggiori informazioni sulla metropolitana facendo click ";
                }
                else{
                    testo_link = "Per informazioni fare click ";
                }
                var html = "<div class='contFloat balloon'><img src='"+baseIcon.image+"' /><div><h2>"+categoria_poi+"</h2><p>"+desc+"</p><p class='more_info'>"+testo_link+" <a href='"+desc2+"' target='_blank'>qui</a></p></p></div></div>";
            }
            else{
                var html = "<div class='contFloat balloon'><img src='"+baseIcon.image+"' /><div><h2>"+categoria_poi+"</h2><p>"+desc+"</p></div></div>";
            }

            //marker.setDetailWinHTML(html);
			GEvent.addListener(marker, "click", function() {
                markerClicked = marker.getId();
                marker.openInfoWindowHtml(html);
			});


            //alert(marker.getId());
        }


    }
    else{                  // ******* POI COTRAL! ******

        if(icon_code == "COTRAL" && flag_logico == "T"){

          GEvent.addListener(marker, "click", function() {
            //console.log(desc+" "+desc2);
            markerClicked = marker.getId();
            var htmlCotralLogico = "<div class='contFloat balloon'><img src='"+baseIcon.image+"' /><div><h2>"+desc+"</h2><p>"+desc+" in questa zona</p><p class='more_info'>Fare click <a onClick=\"javascript:$(this).parent().hide(); centerMap("+point.lat()+","+point.lng()+")\">qui</a> per espandere la visuale ad un maggior dettaglio</p></div></div>";
            marker.openInfoWindowHtml(htmlCotralLogico);
            //marker.setDetailWinHTML(htmlCotralLogico);
            //closeOtherBalloons(marker.getId());
            //openBalloonPoiLogico(marker, desc, point);
          });
        }
        else if(icon_code == "COTRAL_HILIGHT"){
            var htmlCotralFisico = "<div class='contFloat balloon'><img src='"+baseIcon.image+"' /><div><h2>"+categoria_poi+"</h2><p>"+desc+"</p><div class='lineeCotral'></div></div></div>";
            GEvent.addListener(marker, "click", function(){
                marker.openInfoWindowHtml(htmlCotralFisico);
            });
          //marker.setDetailWinHTML(htmlCotralFisico);
        }
        else{

          var htmlCotralFisico = "<div id = 'lista_linee' class='contFloat balloon'><img src='"+baseIcon.image+"' /><div><h2>"+categoria_poi+"</h2><p>"+desc+" "+comune+" "+provincia+"</p><p class='more_info'>E' possibile consultare i percorsi che comprendono questa fermata facendo click <a onClick=\"javascript:$(this).parent().hide(); getLineeCotral('"+desc2+"')\">qui</a></p><p class='lineeCotral'></p></div></div>";

          //marker.setDetailWinHTML(htmlCotralFisico);

          GEvent.addListener(marker, "click", function() {
             markerClicked = marker.getId();
             marker.openInfoWindowHtml(htmlCotralFisico);
            //marker.setDetailWinHTML(htmlCotralFisico);
          });


        }
        /*
        var html = "<div class='pad balloon'><div class='nome_stazione'>"+desc+"</div><div class='palina_cotral'>"+desc2+"</div></div>";

        marker.setDetailWinHTML(html);
        */
    }

  }
  /*
   else
   {
   if (pointDetail[i].length > 0)
     marker.setDetailWinHTML(pointDetail[i]);
     marker.setHoverImage("images/markeryellow.png");

   if (i == 3) // marker D. show time, switch class on click
   {
     GEvent.addListener(marker, "mouseover", function() {
     marker.setTooltip(getTheTime());
   });

   GEvent.addListener(marker, "click", function() {
   if (marker.getTooltipHiding())
   {
     marker.setTooltipHiding(false);
     marker.setOpacity(100);
     marker.setTooltipClass("markerTooltipAlternate");
   }
   else
   {
     marker.setTooltipHiding(true);
     marker.setOpacity(70);
     marker.resetTooltipClass();

     // mouseout disabled when switching classes
     marker.restoreImage();
     marker.hideTooltip();
   }
   });
   }
   }

   */
   return marker;
}


// addAddressToMap() is called when the geocoder returns an
// answer.  It adds a marker to the map with an open info window
// showing the nicely formatted version of the address and the country code.







function addAddressToMap(response) {

    //map.clearOverlays();
  if (!response || response.Status.code != 200) {
    alert("Impossibile risolvere l'indirizzo immesso");
  } else if(response.Placemark.length == 1) {

        showAddress(response.Placemark[0].address);
  }
  else{

    var place = response.Placemark;
    /*
    point = new GLatLng(place.Point.coordinates[1],
                        place.Point.coordinates[0]);
    marker = new GMarker(point);
    map.addOverlay(marker);
    marker.openInfoWindowHtml(place.address + '<br>' +
      '<b>Country code:</b> ' + place.AddressDetails.Country.CountryNameCode);
    */

    $.each(place, function(entryIndex, entry) {
        $('.ricerca_singolo').append("<p onclick='javascript:showAddress($(this).text());$(this).parent().hide();'>"+entry.address+"</p>");


    });
  }
}

function disambiguaPartenza(response){

    var place = response.Placemark;

    if (!response || response.Status.code != 200) {
      alert("Errore, impossibile risolvere l'indirizzo immesso");
    }
    else if(response.Placemark.length == 1) {

        document.forms["directionsForm"].from.value = response.Placemark[0].address;
        departureOk = 1;

    }
    else{
        departureOk = 0;
        $.each(place, function(entryIndex, entry) {

            $('.disambigua_partenza').append("<p onclick='javascript:document.forms[\"directionsForm\"].from.value=$(this).text();$(this).parent().hide(); departureOk = 1'>"+entry.address+"</p>");

        });
    }

}

function disambiguaArrivo(response){

    var place = response.Placemark;

    if (!response || response.Status.code != 200) {
    alert("Errore, impossibile risolvere l'indirizzo immesso");
    } else if(response.Placemark.length == 1) {

        document.forms["directionsForm"].to.value = response.Placemark[0].address;
        destinationOk = 1;
        if(departureOk == 1) setDirections(document.forms["directionsForm"].from.value, document.forms["directionsForm"].to.value, "it");

    }
    else{



      $.each(place, function(entryIndex, entry) {
          $('.disambigua_arrivo').append("<p onclick='javascript:document.forms[\"directionsForm\"].to.value=$(this).text();$(this).parent().hide(); destinationOk = 1;  '>"+entry.address+"</p>");


      });
    }

}

function setDirections(fromAddress, toAddress, locale) {
    //console.log(departureOk+" "+destinationOk);
   try{
        $('.disambigua_partenza').hide();
        $('.disambigua_arrivo').hide();
        gdir.load("from: " + fromAddress + " to: " + toAddress,
                { "locale": locale });
   }
   catch(errore){


   }


}


function showLocation() {

    $('.ricerca_singolo').html("");
    $('.ricerca_singolo').show();
    var address = document.forms["geocodeForm"].indirizzo.value;
    geocoder.getLocations(address, addAddressToMap);

}

function searchStartLocation(){
   if(document.forms["directionsForm"].from.value != ""){
      $('.disambigua_partenza').html("");
      $('.disambigua_partenza').show();
      var address = document.forms["directionsForm"].from.value;
      geocoder.getLocations(address, disambiguaPartenza);
   }
}

function searchEndLocation(){
   if(document.forms["directionsForm"].to.value != ""){
      $('.disambigua_arrivo').html("");
      $('.disambigua_arrivo').show();
      var address = document.forms["directionsForm"].to.value;
      geocoder.getLocations(address, disambiguaArrivo);
    }
}



function showAddress(address) {

      if (geocoder) {
        geocoder.getLatLng(
          address,
          function(point) {
            if (!point) {
              alert(address + " non trovato");
            } else {
              find_poi(catList);
              map.setCenter(point, 13);
              //var marker = new GMarker(point);
              singleSearchMarker = new PdMarker(point);
              map.addOverlay(singleSearchMarker);
              markerClicked = singleSearchMarker.getId();
              GEvent.addListener(singleSearchMarker, "click", function() {
                    singleSearchMarker.openInfoWindowHtml("<div class='contFloat balloon'><h2>"+address+"</h2></div>");
                    markerClicked = singleSearchMarker.getId();
              });
              singleSearchMarker.openInfoWindowHtml("<div class='contFloat balloon'><h2>"+address+"</h2></div>");
              //singleSearchMarker.setDetailWinHTML("<div class='contFloat balloon'><h2>"+address+"</h2></div>");
            }
          });
      }
}

function handleErrors(){
	   if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
	     alert("Non e' stato possibile trovare una corrispondenza geografica con l'indirizzo immesso.");
	   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.");

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

}


