var geocoder = null;
var mapBlocks = null;
var markerNull = null;
var last_n = null;
var existingMarkers = {};
var zoomIniziale = null; // zoom iniziale della mappa
var normalProj = G_NORMAL_MAP.getProjection();	
if (pg == "sh"){
			  if (regione != "italia") zoomIniziale = 9;
			  if (regione == "italia") zoomIniziale = 6;
			  }
if (pg == "shc" || pg == "spectra" || pg == "smoothspectra_ntc" || pg == "smoothspectraprogetto_ntc"){
			  zoomIniziale = 6;
			  }

var metodo = 4; //1=overlay; 2.marker; 3.markermanager; 4.tileOverlay;
function newMap(div) {	
	if (GBrowserIsCompatible()){
		var map = new GMap2(document.getElementById(div));
		map.addControl(new GLargeMapControl3D());
		map.addControl(new GMapTypeControl());
		map.addControl(new GScaleControl());
		map.addControl(new HtmlControl("<img src='img/legenda.png' />")); 
		map.setCenter(new GLatLng(lat, lon), zoomIniziale);
		map.addMapType(G_PHYSICAL_MAP);
		map.setMapType(G_PHYSICAL_MAP);
		map.enableContinuousZoom();
		map.enableDoubleClickZoom();
		if (pg == "sh" || pg == "shc" || pg == "spectra"){// Creo un marker single che serve per ev. a video il hand cursor...
		  var baseIcon = new GIcon(G_DEFAULT_ICON) ;
		  baseIcon.iconSize = new GSize(20,20) ;
		  baseIcon.iconAnchor = new GPoint(10,10) ;
		  baseIcon.shadow = null ;
		  baseIcon.image = null ;
		  markerNull = createMarkerNull(new GLatLng(35,-90), baseIcon, 'start') ;
		  markerNull.hide() ;
		  map.addOverlay(markerNull) ;
			
		  }
		// Watch mouse movement to detect when over a data point...
  		//GEvent.addListener(map,"mousemove", mouseMove ) ;
		// create a local search control and add it to your map
		//var	lsc = new google.maps.LocalSearch(); 
		//map.addControl(new google.maps.LocalSearch());
		if (metodo == 3) window.setTimeout(setupMarkers, 0); //3. quando si usa markermanager
		//map.enableScrollWheelZoom();
		return map;
		}
		
		}

// 4. quando si usa TILEOVERLAY
function metodoTile() {
	//Create the tile layer object
	var detailLayer = new GTileLayer(new GCopyrightCollection(''));
	 
	//Method to retrieve the URL of the tile
	detailLayer.getTileUrl = function(tile, zoom){
	//pass the x and y position as wel as the zoom
	var tileURL = "server.php?x="+tile.x+"&y="+tile.y+"&zoom="+zoom+"&key=tile&pg="+pg;
	
	//log the URL for testing
    //GLog.writeUrl(tileURL);
	return tileURL;
	};
	 
	detailLayer.isPng = function() {
	//The example uses GIF's
	return false;
	}
	 
	//add your tiles to the normal map projection
	detailMapLayers = G_NORMAL_MAP.getTileLayers();
	detailMapLayers.push(detailLayer);
	 
	//add your tiles to the satellite map projection
	detailMapLayers = G_SATELLITE_MAP.getTileLayers();
	detailMapLayers.push(detailLayer);
	
		//add your tiles to the physical map projection
	detailMapLayers = G_PHYSICAL_MAP.getTileLayers();
	detailMapLayers.push(detailLayer);
	
	//add your tiles to the hybrid map projection
	detailMapLayers = G_HYBRID_MAP.getTileLayers();
	detailMapLayers.push(detailLayer);
    }
// FINE - quando si usa TILEOVERLAY
// 4. quando si usa TILEOVERLAY
function deleteMarkers() {
	
	mapBlocks.clearOverlays();
}



// FINE - quando si usa TILEOVERLAY
//funzione PRINCIPALE CHE CARICA LA MAPPA
function load(){
if (metodo == 4) metodoTile(); //4. quando si usano i tilesOverlay
mapBlocks = newMap('map');
//ADSENSE-----------------
// Note: replace this publisher ID with your own.
var publisherID = 'ca-pub-9251745453348745';
var adsManagerOptions = {
mode: "experimental",
maxAdsOnMap : 2,
style: 'adunit',
position: new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(3,270)),
// The channel field is optional - replace this field with a channel number 
// of your own for Google AdSense tracking
channel: '4156046542'  
};

adsManager = new GAdsManager(mapBlocks, publisherID, adsManagerOptions);
adsManager.enable();
//ADSENSE-----------------
if (metodo == 1) aggiungiOverlay(); //1. quando si usano gli Overlay
if (metodo == 2) aggiungiMarker(); //2. quando si usano i Marker
if (metodo == 4){
			//updateMarkers();
	if (pg == "smoothspectraprogetto_ntc" || pg == "smoothspectra_ntc"){
				var zonaZoom = 0; // 0 -> zoom <= 9; 1 -> zoom > 9
			GEvent.addListener(mapBlocks,'zoomend',function() {
				if (mapBlocks.getZoom() <= 9) {
				deleteMarkers();
				document.getElementById("table2").style.display = "none";
				var printTitle = document.getElementById("printTitle");
				printTitle.innerHTML = "";	
			    var printSLat = document.getElementById("printSLat");
				printSLat.innerHTML ="";
				var printSLng = document.getElementById("printSLng");
				printSLng.innerHTML = "";
				var printHazardNTC = document.getElementById("printHazardNTC");
				printHazardNTC.innerHTML = "";
				var container = document.getElementById("GChart");
				container.innerHTML = "";
				document.getElementById('img').src = "icone/spaziatore.gif";
				zonaZoom = 0;
				}
				if (mapBlocks.getZoom() > 9 && zonaZoom == 0) {
				var point = new GLatLng(mapBlocks.getCenter().y.toFixed(6)*1,mapBlocks.getCenter().x.toFixed(6)*1);
				main1(point,mapBlocks.getZoom());
				zonaZoom = 1;
				}	
			});
			GEvent.addListener(mapBlocks,'moveend',function() {
				if (mapBlocks.getZoom() <= 9) deleteMarkers();
			});
			//GEvent.addListener(mapBlocks,'mousemove',function() {
				//if (mapBlocks.getZoom() > 9) {
					//var point = new GLatLng(mapBlocks.getCenter().y.toFixed(6),mapBlocks.getCenter().x.toFixed(6));
					//main1(point,mapBlocks.getZoom());
					//}
			//});
	}
	if (pg == "sh" || pg == "shc" || pg == "spectra"){
		    var zoomStart = 12;
			GEvent.addListener(mapBlocks,'zoomend',function() {
			if (mapBlocks.getZoom() >= zoomStart) generaPoints();
			});
			GEvent.addListener(mapBlocks,'moveend',function() {
			if (mapBlocks.getZoom() >= zoomStart) generaPoints();
			});
			GEvent.addListener(mapBlocks,'mousemove',function(mouseLatLng) {
				if (mapBlocks.getZoom() >= zoomStart) mouseMoveNull(mouseLatLng);
			});
			var cliccaControllo = new HtmlControl("<img src='img/clicca.png' />");
			var Right = new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(7,320));
			GEvent.addListener(mapBlocks,'mousemove',function() {
				if (mapBlocks.getZoom() >= zoomStart) mapBlocks.addControl(cliccaControllo, Right);
				if (mapBlocks.getZoom() < zoomStart) mapBlocks.removeControl(cliccaControllo);
			});
	}
}
geocoder = new GClientGeocoder();
GEvent.addListener(mapBlocks, "moveend", moveEnd);
GEvent.addListener(mapBlocks, 'mousemove', mouseMove);
moveEnd();
}

//funzione per inserire una legenda nella mappa
function HtmlControl(html) { this.html = html } 
HtmlControl.prototype = new GControl(); 
HtmlControl.prototype.initialize = function(map) { 
  var container = document.createElement("div"); 
  var extra = document.createElement("div"); 
  extra.className = "legend"; 
  extra.innerHTML = this.html; 
  container.appendChild(extra); 
  map.getContainer().appendChild(container); 
  return container; 
} 
HtmlControl.prototype.getDefaultPosition = function() { 
return new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(7, 30)); 
} 

//funzioni per gestire il marker nelle mappe sh, shc, spectra
function mouseMoveNull(mouseLatLng) // Watch mouse movement for proximity to a data point...
{
	var threshold = 10; //pixels;
	var zoom = mapBlocks.getZoom() ;
	var mousePx = G_NORMAL_MAP.getProjection().fromLatLngToPixel(mouseLatLng, zoom) ;	
	var bounds = mapBlocks.getBounds();
	var SW = bounds.getSouthWest();
	var NE = bounds.getNorthEast();
		for (n in points)
		{
			if (points[n].lat <= NE.y.toFixed(6) && points[n].lat >= SW.y.toFixed(6) && points[n].lng <= NE.x.toFixed(6) && points[n].lng >= SW.x.toFixed(6)) {
			var LatLngPoint = new GLatLng(points[n].lat,points[n].lng);
			var PixelPoint = G_NORMAL_MAP.getProjection().fromLatLngToPixel(LatLngPoint, zoom) ;
			var d = Math.sqrt(Math.pow((mousePx.x - PixelPoint.x),2) + Math.pow((mousePx.y - PixelPoint.y),2))
				if (d < threshold)
				{
					if (last_n != n) {
						activateMarker(points,n);		// Activate the hand
						last_n = n;
						return;
					} else {
						return;
					}
				}
			}
		}
	//markerNull.hide() ;
}
// Activate a marker...
function activateMarker(points, n)
{
	var LatLngPoint = new GLatLng(points[n].lat,points[n].lng);
	//var latlng = G_NORMAL_MAP.getProjection().fromPixelToLatLng(LatLngPoint, map.getZoom());
	markerNull.setLatLng(LatLngPoint);
	if (pg == "shc" || pg == "spectra"  || pg == "sh"){
				  if (pg == "shc") titolo = "Curve di hazard INGV-DPC 2004/2006 (Progetto S1, Deliverable D2)";
				  if (pg == "spectra") titolo = "Spettri INGV-DPC 2004/2006 (Progetto S1, Deliverable D3)";
				  if (pg == "sh") titolo = "Pericolosit&agrave; OPCM 3519";
			  	  markerNull.bindInfoWindowHtml(htmlLink(titolo,points[n].ID_tab,points[n].lat,points[n].lng,points[n].ag,pg));
			  }
	markerNull.show() ;
}
function createMarkerNull(point, iconName, html) 
{
	var marker = new GMarker(point,{icon:iconName});
		GEvent.addListener(marker, "click", function()
		{
		marker.openInfoWindowHtml(html);
		});
	return marker;
}

function generaPoints() {

    //create the boundry for the data to provide
    //initial filtering
	var loader = new HtmlControl("<img src='img/ajaxloader/ajax-loader.gif' />");
	var Right = new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(190,340));
	mapBlocks.addControl(loader, Right);	
    var bounds = mapBlocks.getBounds();
    var southWest = bounds.getSouthWest();
    var northEast = bounds.getNorthEast();
    var getVars = 'ne=' + northEast.toUrlValue()
    + '&sw=' + southWest.toUrlValue()
	+ '&pg=' + pg;

    //log the URL for testing
    //GLog.writeUrl('data_sh.php?'+getVars);

    //retrieve the points
    var request = GXmlHttp.create();
    request.open('GET', 'data_sh.php?'+getVars, true);
    request.onreadystatechange = function() {
         if (request.readyState == 4) {
              var jscript = request.responseText;
              eval(jscript);
			  //var prova = document.getElementById("prova");
			  //prova.innerHTML = points[2].lat;
			  mouseMoveNull(mouseLatLng);
			  mapBlocks.removeControl(loader);
         }
    }
    request.send(null);
}
