var server = "http://www.provincia.milano.it/mappe2/"
var key = "ABQIAAAAUFrppv2oMiwmfR8jhoAHFRQCecenUwhGiRVk6bsTp8zLS8a7BRQQ9NXNSf0cGXW3xhh7-hbVXQ6w9Q";
if (document.domain == "provincia.milano.it" || document.domain == "www.provincia.milano.it") {
	key = "ABQIAAAAUFrppv2oMiwmfR8jhoAHFRQSgGqvl6RUhz24lZYNzdSOobPOeBTidyniuMrfdCPZ024wL4WnoBUAFg";
} else if (document.domain == "provincia.mi.it" || document.domain == "www.provincia.mi.it") {
	key = "ABQIAAAAUFrppv2oMiwmfR8jhoAHFRQMB_pfS2156CQn7Nn7BQhMMt_V3RSrfu79APc4z-wk7uy3-JU-CpgnyA";
}
document.write('<' + 'script src="http://maps.google.com/maps?file=api&amp;v=2.x&amp;key=' + key + '"' +' type="text/javascript"><' + '/script>');

var map;
var geocoder;
var markerArray = new Array;
var visualizza = {
	 "milano":					{"url" : server+"KMZ/confini_provincia_milano.kmz"},
	 "comuni":					{"url" : server+"KMZ/confini_comuni_milano.kmz"}
}

function loadxml() {
  map = new GMap2(document.getElementById("map"),{draggableCursor: 'crosshair', draggingCursor: 'move'});
  setMapCenter()
  map.addControl(new GLargeMapControl3D());
  map.addControl(new GOverviewMapControl());
  map.addControl(new GScaleControl());
  map.addControl(new GMapTypeControl());
  map.enableScrollWheelZoom();
  map.enableDoubleClickZoom();
  map.enableContinuousZoom();
  geocoder = new GClientGeocoder();
  map.addMapType(G_SATELLITE_3D_MAP);
  // GoogleEarth
  var mapControl = new GMapTypeControl();
  map.addControl(mapControl);
  // Fine GoogleEarth
				query="/mappe2/sedi.xml?nocache="+Math.random();
				jQuery.get(query, function(data){		   
					$(data).find("Categorie").each(function() {
						var cat=$(this);
						$("#ricercapunti").append("<h4>"+cat.find("Name").text()+"</h4>")
							cat.find("Markers").each(function(){
							var markers = $(this);
							var title = markers.find("title").text();
							var myid = markers.find("id").text()
							var ico = markers.find("ico").text()
							var info = markers.find("info").text();
							var uffici = markers.find("uffici").text();
							var lat = markers.find("lat").text();
							var lng = markers.find("lon").text();	
							var point = new GLatLng(parseFloat(lat),
													parseFloat(lng)
						);
							$("#ricercapunti").append("<a href=\"javascript:lightMarker('"+myid+"')\">&raquo; "+title+"</a><br />");
		
					var marker = createMarker(point, title, myid, ico, info, uffici);
												
					map.addOverlay(marker);
					markerArray[myid]=marker;
					marker.hide();
						})
					})
					// GOOGLE STREET 
					GEvent.addListener(map.getInfoWindow(), "maximizeend", function(){
						var node = document.getElementById("myPano");
						var latlng = map.getInfoWindow().getPoint();
						var pano = new GStreetviewPanorama(node);
						GEvent.addListener(pano, 'error', function(errorCode) {
							if (errorCode == 603) {
								node.innerHTML = 'StreetView necessita del flash plugin. Clicca <a href="http://get.adobe.com/flashplayer/" target="_blank"> qui</a> per scaricarlo';
							}
							if (errorCode == 600) {
								node.innerHTML = 'StreetView non disponibile per il punto selezionato.';
							}
						});
						pano.setLocationAndPOV(latlng);
						node.pano = pano;													  
					})
					// FINE GOOGLE STREET 
					var pageId = getUrlVars()["id"];
					if(pageId!=undefined && markerArray[pageId]){
						markerArray[pageId].show();
						GEvent.trigger(markerArray[pageId], 'click');
					}	
			  });
}

function createMarker(point, title, myid, ico, info, uffici){
	var icon = new GIcon();
    icon.image = ico;
    icon.iconSize = new GSize(25, 25);
    icon.iconAnchor = new GPoint(13, 35);
    icon.infoWindowAnchor = new GPoint(15, 5);
      var marker = new GMarker(point, icon);
		var infoTabs = [
			new GInfoWindowTab("Info", "<div class=\"fumetto\"><h3>"+title+"</h3><div class=\"tabint\">"+info+"</div></div>"),
			new GInfoWindowTab("Uffici", "<div class=\"fumetto\"><h3>"+title+"</h3><div class=\"text\">" + uffici + "</div></div>"),
			new GInfoWindowTab("Percorso", "<div class=\"fumetto\"><h3 id=\"tit\">Seleziona il punto di partenza:</h3><form id=\"formperc\"action=\"javascript:getDirections()\"><br /><a class=\"on\" href=\"javascript:daquiaqui('aqui')\" >A quì</a> | <a href=\"javascript:daquiaqui('daqui')\" >Da quì</a><br /><br />Indirizzo (ad es. 'Via Vivaio 1, Milano')<br /><br /><input type=\"text\" size=\"50\" maxlength=\"50\" name=\"daddr\" id=\"daddr\" value=\"\" /><input type=\"hidden\" value=\"aqui\" id=\"daa\"><input type=\"hidden\" id=\"saddr\" value=\""+point.lat()+","+point.lng()+"\"><input type=\"submit\" value=\"Calcola\" class=\"invia\"></form></div>")
		];
      GEvent.addListener(marker, 'click', function(){
	  		marker.openInfoWindowTabsHtml(infoTabs, {
			maxTitle: 'Google Street',
			maxContent: '<div id="myPano" style="height:360px; width:660px; text-align:left;"></div>'
			});
      });
      return marker;
}

// Evento CLICK dalla colonna DX
function lightMarker(x){
		if(x=='all'){
			map.closeInfoWindow()
			showAll()
		}else{
			for(i in markerArray){markerArray[i].hide()};
			markerArray[x].show();
			map.setZoom(16)
			GEvent.trigger(markerArray[x], 'click');
		}
}
// Funzioncina per prendere i parametri dell'URL
function getUrlVars(){
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++){
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    return vars;
}
// CANCELLA TUTTO
function hideAll(){
	setMapCenter()
	map.closeInfoWindow()
	for(i in markerArray){markerArray[i].hide()};

        $("#tabbed a:eq(0)").trigger('click')
	$("#tabbed a:eq(1)").hide();
	$("#strade").html('');
	if(gdir){gdir.clear()}
}
// MOSTRA TUTTO
function showAll(){
	setMapCenter()
	for(i in markerArray){markerArray[i].show()};
}
// CENTRAMENTO 
function setMapCenter(){
	map.setCenter(new GLatLng(45.4636889, 9.1881408), 12);
}
// ------ Confini
function toggleGeoXML(id, checked, layers) {
	if (checked) {
		if(!layers[id].geoXml){
  			var geoXml = new GGeoXml(layers[id].url);
			layers[id].geoXml = geoXml;
			map.addOverlay(geoXml);
		}
	} 
	else if (layers[id].geoXml) {
		map.removeOverlay(layers[id].geoXml);
		layers[id].geoXml=false
	}
}
// ------ Geocode del Cerca indirizzo
function showLocation() {
      var address = document.getElementById('address_input').value;
      geocoder.getLocations(address, addAddressToMap);
    }
function addAddressToMap(response) {
      map.clearOverlays();
      if (!response || response.Status.code != 200) {
        alert("Sorry, we were unable to geocode that address");
      } else {
        place = response.Placemark[0];
        point = new GLatLng(place.Point.coordinates[1], place.Point.coordinates[0]);
		map.setCenter(point, 13);
        marker = new GMarker(point);
        map.addOverlay(marker);
        marker.openInfoWindowHtml(place.address + '<!-- <br>' + '<b>Stato:</b> ' + place.AddressDetails.Country.CountryNameCode + "-->");
      }
    }
// ----------------------
var gdir


function getDirections(){
	if(document.getElementById("daa").value=='daqui'){
		var saddr= document.getElementById("saddr").value;
		var daddr = document.getElementById("daddr").value;
	}
	else if(document.getElementById("daa").value=='aqui'){
		var daddr= document.getElementById("saddr").value;
		var saddr = document.getElementById("daddr").value;
		}
	gdir = new GDirections(map, document.getElementById("strade"));
	gdir.load("from: "+saddr+" to: "+daddr);
	$("#strade").html('');
	$("#tabbed a:eq(1)").show();
	tabLight($("#tabbed a:eq(1)"), "#strade");
      // === Array for decoding the failure codes ===
      var reasons=[];
      reasons[G_GEO_SUCCESS]            = "Success";
      reasons[G_GEO_MISSING_ADDRESS]    = "Missing Address: The address was either missing or had no value.";
      reasons[G_GEO_UNKNOWN_ADDRESS]    = "Unknown Address:  No corresponding geographic location could be found for the specified address.";
      reasons[G_GEO_UNAVAILABLE_ADDRESS]= "Unavailable Address:  The geocode for the given address cannot be returned due to legal or contractual reasons.";
      reasons[G_GEO_BAD_KEY]            = "Bad Key: The API key is either invalid or does not match the domain for which it was given";
      reasons[G_GEO_TOO_MANY_QUERIES]   = "Too Many Queries: The daily geocoding quota for this site has been exceeded.";
      reasons[G_GEO_SERVER_ERROR]       = "Server error: The geocoding request could not be successfully processed.";
      reasons[G_GEO_BAD_REQUEST]        = "A directions request could not be successfully parsed.";
      reasons[G_GEO_MISSING_QUERY]      = "No query was specified in the input.";
      reasons[G_GEO_UNKNOWN_DIRECTIONS] = "The GDirections object could not compute directions between the points.";
      // === catch Directions errors ===
      GEvent.addListener(gdir, "error", function() {
        var code = gdir.getStatus().code;
        var reason="Code "+code;
        if (reasons[code]) {
          reason = reasons[code]
        } 
        alert("Failed to obtain directions, "+reason);
	}); 
}

function daquiaqui(dove){
	$("#formperc a").removeClass("on")
	if(dove=='aqui'){
		$('#daa').value='aqui'; 
		$('#tit').html('Seleziona il punto di partenza:');
		$("#formperc a:eq(0)").addClass("on")
	}
	else if(dove=='daqui'){
		$('#daa').value='daqui'; 
		$('#tit').html('Seleziona il punto di arrivo:');
		$("#formperc a:eq(1)").addClass("on")
	}
}

/*#.- .-.. . .. ... .- -. -.. .-. --- -.-. .- .. -- ..#*/
/* ]======[]======[      LAYOUT      ]======[]======[  */
/*#.- .-.. . .. ... .- -. -.. .-. --- -.-. .- .. -- ..#*/
$(document).ready(function(){
	$("#tabbed a:eq(1)").hide();
	resize()
	$(window).resize(function(){
			resize()				
	})
	loadxml();		   
	$("#address_submit").click(function(){
		showLocation()			
	})
	$("#tabbed a").click(function(){
		area = $(this).attr('href');
		tabLight($(this), area)
	})
})
function resize(){
	$("#map").height($(window).height()-190);
	$("#rightcol .text").height($(window).height()-190);
}
function tabLight(This, area){
		$("#tabbed a").removeClass("on");
		$("#rightcol .text > div").hide();
		This.addClass("on");
		$(area).show();
}
