var arrayPoligoni = new Array();
var mappa;
var latMarker = new Array();
var lngMarker = new Array();

var coloreBordo = "#5b0c12";
var coloreInterno = "#e0ae31";
var dimBordo = 2;
var opacitaBordo = 1;
var opacitaInterno = 0.6;


function centraMappa()  {
	mappa.setCenter(new GLatLng(44.803056, 10.328222), 14, G_HYBRID_MAP);
	  for (var k=0; k<arrayPoligoni.length;k++) {
	    arrayPoligoni[k].setFillStyle({color:coloreInterno, opacity:opacitaInterno});
		arrayPoligoni[k].setStrokeStyle({color:coloreBordo, weight: dimBordo, opacity:opacitaBordo});	
	  }
}

function selectPoly(i)  {
	for (var k=0; k<arrayPoligoni.length;k++) {
	  arrayPoligoni[k].setFillStyle({color:coloreInterno, opacity:opacitaInterno});
	  arrayPoligoni[k].setStrokeStyle({color:coloreBordo, weight: dimBordo, opacity:opacitaBordo});	
	}
	
	mappa.setCenter(new GLatLng(latMarker[i], lngMarker[i]), 16, G_HYBRID_MAP);
	
	arrayPoligoni[i].setFillStyle({color:"#5b0c12", opacity:opacitaInterno});
	arrayPoligoni[i].setStrokeStyle({color:"#e0ae31", weight: dimBordo, opacity:opacitaBordo});	
	
	}

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...
	}

function creaMarker(coordinate, testo, index) {
	var baseIcon = new GIcon(G_DEFAULT_ICON);
		baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
		baseIcon.iconSize = new GSize(20, 34);
		baseIcon.shadowSize = new GSize(37, 34);
		baseIcon.iconAnchor = new GPoint(9, 34);
		baseIcon.infoWindowAnchor = new GPoint(9, 2);	
	// Create a lettered icon for this point using our icon class
	var letter = String.fromCharCode("A".charCodeAt(0) + index);
	var letteredIcon = new GIcon(baseIcon);
	letteredIcon.image = "images/icons/marker" + letter + ".png";// Mettere tutte le foto dei marker
	// Set up our GMarkerOptions object
	markerOptions = { icon:letteredIcon };
	var marker = new GMarker(coordinate, markerOptions);
	
	/*GEvent.addListener(marker, "click", function() {
		marker.openInfoWindowHtml(testo);
		//marker.openExtInfoWindow(mappa,testo);
	});*/
	return marker;
}

//creo istanza di XMLHttpRequest
function creaXmlHttprequest()  {
  var xmlHttp;
	try  {
		xmlHttp = new XMLHttpRequest();
	}
	catch (e)  {
	  var XmlHttpVersion = new Array('MSXML2.XMLHTTP.6.0','MSXML2.XMLHTTP.5.0','MSXML2.XMLHTTP.4.0','MSXML2.XMLHTTP.3.0','MSXML2.XMLHTTP','Microsoft.XMLHTTP');	
		for (var i=0;i<XmlHttpVersion.length && !xmlHttp; i++)  {
		  try  {xmlHttp = new ActiveXObject(XmlHttpVersion[i]);}
			catch(e) {}
		}
	}
	if (!xmlHttp) alert("Errore durante la creazione dell'oggetto");	  	
	else return xmlHttp;	  
}

function load() {
	if (GBrowserIsCompatible()) {
		mappa = new GMap2(document.getElementById("mappa"));
		mappa.setCenter(new GLatLng(44.803056, 10.328222), 14, G_SATELLITE_MAP);//coordinate Hotel Torino
		//mappa.addControl(new GSmallMapControl());
		mappa.addControl(new GLargeMapControl());
    mappa.enableScrollWheelZoom();
        var mapControl = new GMapTypeControl();
        mappa.addControl(mapControl);

		var xmlHttp = creaXmlHttprequest();
		var URL = "xml/";
		
		if (xmlHttp)  {
			try  {
				xmlHttp.open("GET",URL + "googleMarker.xml", true);
				xmlHttp.onreadystatechange = function() {
					// in case of network errors this might not give reliable results
					if ((xmlHttp.readyState == 4) && (xmlHttp.status == 200))  {
						try  { 
							var xmlResponse = xmlHttp.responseXML;
							if (!xmlResponse || !xmlResponse.documentElement)
								throw ("Struttura XML non valida:\n" + this.responseText);
							var rootNode = xmlResponse.documentElement.nodeName;
							if (rootNode == "parsererror")
								throw ("Struttura XML non valida");
					    
							//pesco tutti i marker dal googleXml
							markerArray = xmlResponse.getElementsByTagName("marker");
							
							for (var i=0; i<(markerArray.length); i++)  {
								testo = markerArray[i].getElementsByTagName("testo")[0].childNodes[0].nodeValue;
								latMarker[i] = parseFloat(markerArray[i].getElementsByTagName("lat")[0].childNodes[0].nodeValue);
								lngMarker[i] = parseFloat(markerArray[i].getElementsByTagName("lon")[0].childNodes[0].nodeValue);
								mappa.addOverlay(creaMarker(new GLatLng(latMarker[i],lngMarker[i]),testo,i));
								
								//Preparo i poligoni
								lat1 = parseFloat(markerArray[i].getElementsByTagName("lat1")[0].childNodes[0].nodeValue);
								lat2 = parseFloat(markerArray[i].getElementsByTagName("lat2")[0].childNodes[0].nodeValue);
								lat3 = parseFloat(markerArray[i].getElementsByTagName("lat3")[0].childNodes[0].nodeValue);
								lat4 = parseFloat(markerArray[i].getElementsByTagName("lat4")[0].childNodes[0].nodeValue);
								lon1 = parseFloat(markerArray[i].getElementsByTagName("lon1")[0].childNodes[0].nodeValue);
								lon2 = parseFloat(markerArray[i].getElementsByTagName("lon2")[0].childNodes[0].nodeValue);
								lon3 = parseFloat(markerArray[i].getElementsByTagName("lon3")[0].childNodes[0].nodeValue);
								lon4 = parseFloat(markerArray[i].getElementsByTagName("lon4")[0].childNodes[0].nodeValue);
								
								arrayPoligoni[i] = new GPolygon([
																		new GLatLng(lat1, lon1),
																		new GLatLng(lat2, lon2),
																		new GLatLng(lat3, lon3),
																		new GLatLng(lat4, lon4),
																		new GLatLng(lat1, lon1)], 
																		coloreBordo, dimBordo, opacitaBordo, coloreInterno, opacitaInterno);
								}
							
							for (var i=0; i<(markerArray.length); i++)
							  mappa.addOverlay(arrayPoligoni[i]);
								
							
							//marker dell'hotel
							var hotelIcon = new GIcon(G_DEFAULT_ICON);
							hotelIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
							hotelIcon.iconSize = new GSize(44, 42);
							hotelIcon.shadowSize = new GSize(37, 34);
							hotelIcon.iconAnchor = new GPoint(9, 34);
							hotelIcon.infoWindowAnchor = new GPoint(9, 2);	
							var hotelTorinoIcon = new GIcon(hotelIcon);
							hotelTorinoIcon.image = "images/icons/markerHT.png"
							markerHotelOptions = { icon:hotelTorinoIcon };
							
							var markerHotel = new GMarker(new GLatLng(44.803078, 10.328219), markerHotelOptions);
							mappa.addOverlay(markerHotel);
							
							GEvent.addListener(markerHotel, "click", function() {
								markerHotel.openInfoWindowHtml("Hotel Torino");
							});
							
							/* impostazione per direzione*/
							gdir = new GDirections(mappa, document.getElementById("directions"));
							GEvent.addListener(gdir, "load", onGDirectionsLoad);
							GEvent.addListener(gdir, "error", handleErrors);

							
						}
					catch (e)  { 
						alert ("Errore durante la lettura della risposta: " + e.toString() );
						}
					}	
				}
				xmlHttp.send(null);
			}
			catch (e)  {
				alert("Impossibile collegarsi al server:\n" + e.toString());
			} 
		}
	}
}

