var map = null;
var geocoder = null;
var locationsMap = {};
var locationsInfo = {};

function initializeMap() {
  if (GBrowserIsCompatible()) {
    map = new GMap2(document.getElementById("map_canvas"));
    map.addControl(new GLargeMapControl());
    map.addControl(new GMapTypeControl());
    //map.setCenter(new GLatLng(37.4419, -122.1419), 13);
    geocoder = new GClientGeocoder();
  }
}

function focusLocation(regionId, regionName) {
	if (!locationsMap[regionId]) 
	{ 
		addLocationToMap(regionId, regionName, function(point) {
			geocoderCallBack(regionId, regionName)(point);
		    map.setCenter(locationsMap[regionId].point, 4);
		    locationsMap[regionId].marker.openInfoWindow(
		    	document.getElementById('region'+regionId+'Details').innerHTML);
		}
		); 
	}
	else {
	    map.setCenter(locationsMap[regionId].point, 4);
	    locationsMap[regionId].marker.openInfoWindowHtml(
	    	document.getElementById('region'+regionId+'Details').innerHTML);
	}
}

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);

function createMarker(point) {
  // Create a lettered icon for this point using our icon class
  var letteredIcon = new GIcon(baseIcon);
  letteredIcon.image = "http://musing-dev.metaware.it/maps/images/marker.png";
  // Set up our GMarkerOptions object
  markerOptions = { icon:letteredIcon };
  var marker = new GMarker(point, markerOptions);
  return marker;
}

function geocoderCallBack(regionId, regionName) {
	return function(point) {
	  if (!point) {
	    alert(regionName + " not found");
	  } else {
	    map.setCenter(point, 3);
	    var marker = createMarker(point);
	    marker.bindInfoWindow(document.getElementById("region"+regionId+"Details").innerHTML);
	    map.addOverlay(marker);
	    locationsMap[regionId] = {};
	    locationsMap[regionId].marker = marker;
	    locationsMap[regionId].point = point;
	  }
  }
}


function addLocationToMap(regionId, regionName, callback) {
  if (geocoder) {
    geocoder.getLatLng(
      regionName,
      callback
    );
  }
}

function fetchRegionDetails(regionId) {
	
}


function toggleBox(ddId, toggleId) {
	var box = document.getElementById(ddId);
	if (box.className == 'shown') 
		box.className = 'notshown';
	else 
		box.className = 'shown';
	if (toggleId != undefined) {
		var toggle = document.getElementById(toggleId);
		toggle.className = 'box'+box.className;
	}
};

var fetched = {};

function fetchRegionDetails(regionId) {
	toggleBox('region'+regionId+'DetailsFetch', 'region'+regionId+'DetailsToggle');
	if (!fetched[regionId]) {
		$('#region'+regionId+'DetailsFetch').load('getRegionDetails.html?regionId='+regionId);;
		fetched[regionId] = true;
	}
};


