/*
 * autore: Federico Luciani, federico.luciani@cheiron.com
 */

var centerLat=45.657443;
var centerLng=13.807433;
var centerZoom=16;

var map;
var marker;
var gdir;
var contextmenu;

//load and unload the map
GEvent.addDomListener(window,'load',loadMap);
GEvent.addDomListener(window,'unload',GUnload);

//check for google maps compatibility, if so, create map
function loadMap(){
  if(!GBrowserIsCompatible()){
    alert('Sorry, the Google Maps API is not compatible with this browser.');
    return;
  }else{
    initMap();
  }
}

//create map icon and sidebar
function initMap() {
  map = new GMap2(document.getElementById('mapContainer'));
  map.setCenter(new GLatLng(centerLat,centerLng),centerZoom);
  var extLargeMapControl = new ExtLargeMapControl();
  map.addControl(extLargeMapControl);  
//  map.addControl(new GLargeMapControl());
  map.addControl(new GMenuMapTypeControl(false,false));
  map.addControl(new GScaleControl());
  var OverviewMapControl = new GOverviewMapControl(new GSize(160,160));
  map.addControl(OverviewMapControl);
  OverviewMapControl.hide(true);   
  map.addMapType(G_PHYSICAL_MAP);
  map.setMapType(G_NORMAL_MAP);  

  contextmenu = document.createElement("div");
  contextmenu.id = 'context-menu';
  contextmenu.style.visibility="hidden";
  contextmenu.style.background="#ffffff";
  contextmenu.style.border="1px #aaa solid";

  contextmenu.innerHTML = '<a href="javascript:zoomIn();"><div class="context-menu">&nbsp;Zoom avanti</div></a>'
                        + '<a href="javascript:zoomOut();"><div class="context-menu" style="border-bottom:1px #aaa solid">&nbsp;Zoom indietro</div></a>'
                        + '<a href="javascript:zoomInHere();"><div class="context-menu">&nbsp;Zoom avanti qui</div></a>'
                        + '<a href="javascript:zoomOutHere();"><div class="context-menu" style="border-bottom:1px #aaa solid">&nbsp;Zoom indietro qui</div></a>'
                        + '<a href="javascript:centreMapHere();"><div class="context-menu">&nbsp;Centra qui</div></a>'
                        + '<a href="javascript:centreMapMarker();"><div class="context-menu">&nbsp;Centra il marker</div></a>';

  map.getContainer().appendChild(contextmenu);
  GEvent.addListener(map,"singlerightclick",function(pixel,tile) {
    clickedPixel = pixel;
    var x=pixel.x;
    var y=pixel.y;
    if (x > map.getSize().width - 150) { x = map.getSize().width - 150 }
    if (y > map.getSize().height - 100) { y = map.getSize().height - 100 }
    var pos = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(x,y));
    pos.apply(contextmenu);
    contextmenu.style.visibility = "visible";
  });

  GEvent.addListener(map, "click", function() {
    contextmenu.style.visibility="hidden";
  });

  gdir = new GDirections(map);
  GEvent.addListener(gdir, "load", onGDirectionsLoad);
  GEvent.addListener(gdir, "error", handleErrors);
 
  createMap();
}

function createMap() {
	var icon=new GIcon();
  icon.image = "Images/Map/center.png";
  icon.shadow = "Images/Map/center_shadow.png";
//	icon.image = "Images/Map/home.png";
//	icon.shadow = "Images/Map/home_shadow.png";
	icon.iconSize = new GSize(32.0, 32.0);
	icon.shadowSize = new GSize(49.0, 32.0);
	icon.iconAnchor = new GPoint(16.0, 16.0);
	icon.infoWindowAnchor = new GPoint(16.0, 16.0);
	
	var point = new GLatLng(45.656790,13.810624);
	//var point = new GLatLng(45.65714,13.81038); //GPS
	//var point = new GLatLng(45.65721,13.81061); //GPS 55
	//var point = new GLatLng(45.657205,13.810629); //Google
	
	var html = '<div class=\'map_infowindow\'><ul><li><h2>Gravità  Zero</h2></li></ul><h3>Palestra d\'arrampicata sportiva</h3><p class=\'map_infowindow_details\'>Via alle Cave 55 (zona San Giovanni)<br />Trieste (TS)<br /><br /></p></div>';
	var marker = createMarker(map, point, html, 'Gravità  Zero', icon, null);
	map.addOverlay(marker);
	marker.openInfoWindowHtml(html);

	var icon=new GIcon();
	icon.image = "Images/Map/bus.png";
	icon.shadow = "Images/Map/bus_shadow.png";
	icon.iconSize = new GSize(32.0, 32.0);
	icon.shadowSize = new GSize(49.0, 32.0);
	icon.iconAnchor = new GPoint(16.0, 16.0);
	icon.infoWindowAnchor = new GPoint(16.0, 16.0);  
	
	var point = new GLatLng(45.656264,13.805817);
	var marker = createMarker(map, point, null, 'Capolinea Piazzale Gioberti', icon, null);
	map.addOverlay(marker);

	var icon=new GIcon();
	icon.image = "Images/Map/parking.png";
	icon.shadow = "Images/Map/parking_shadow.png";
	icon.iconSize = new GSize(32.0, 32.0);
	icon.shadowSize = new GSize(49.0, 32.0);
	icon.iconAnchor = new GPoint(16.0, 16.0);
	icon.infoWindowAnchor = new GPoint(16.0, 16.0);

	var point = new GLatLng(45.656723,13.805609);
	var marker = createMarker(map, point, null, 'Parcheggio Chiesa San Giovanni', icon, null);
	map.addOverlay(marker);

	var point = new GLatLng(45.655823,13.807411);
	var marker = createMarker(map, point, null, 'Parcheggio Via alle Cave', icon, null);
	map.addOverlay(marker);

}

function createMarker(map, point, html, toolTip, icon, linkId) {
	var marker = new GMarker(point, {icon:icon, title:toolTip});
	if (html != null) {
		GEvent.addListener(marker, "click", function() {
      marker.openInfoWindowHtml(html);
//				var z = map.getZoom();
//				var lt = map.getCenter().lat().toFixed(6);
//				var lg = map.getCenter().lng().toFixed(6);
//				marker.openInfoWindowHtml(html+'<div>'+ z + ' ' + lt + ' ' + lg + '</div>');
		});
	}
	if (toolTip != null) {
	}
	if (linkId != null) {
		document.getElementById(linkId).onmouseover = function() { marker.openInfoWindowHtml(html); };
		document.getElementById(linkId).onmouseout = function() { map.closeInfoWindow(); };
	}
	return marker;
}


function fix6ToString(n) {
  return n.toFixed(6).toString();
}


function zoomIn() {
  map.zoomIn();
  contextmenu.style.visibility="hidden";
}
function zoomOut() {
  map.zoomOut();
  contextmenu.style.visibility="hidden";
}
function zoomInHere() {
  var point = map.fromContainerPixelToLatLng(clickedPixel)
  map.zoomIn(point,true);
  contextmenu.style.visibility="hidden";
}
function zoomOutHere() {
  var point = map.fromContainerPixelToLatLng(clickedPixel)
  map.setCenter(point,map.getZoom()-1);
  contextmenu.style.visibility="hidden";
}
function centreMapHere() {
  var point = map.fromContainerPixelToLatLng(clickedPixel)
  map.setCenter(point);
  contextmenu.style.visibility="hidden";
}
function centreMapMarker() {
  var point = map.fromContainerPixelToLatLng(clickedPixel)
  map.setCenter(marker.getPoint());
  contextmenu.style.visibility="hidden";
}

function setDirections() {
  map.closeInfoWindow();
  //gdir.load("from: " + document.getElementById('ctl00_col2_txtFrom').value + " to: Via alle cave 55 Trieste", {locale:"it_IT"});
  gdir.load("from: " + document.getElementById('ctl00_col2_txtFrom').value + " to: G0@45.65714,13.81038", {locale:"it_IT"});
}

function onGDirectionsLoad(){
  document.getElementById('ctl00_col2_lblStatus').innerHTML='Distanza: ' + gdir.getDistance().html + ' - Durata: ' + gdir.getDuration().html;
}

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.");
}