var map;  
var baseIcon;

function mapLoad()
{
	/*
	 * Load in Google Maps API
	 */
	google.load("maps", "2", {"callback": buildMap});
	$('document').unload(function() {google.maps.Unload();});
}

function buildMap()
{
	/*
	 * Set up the template Marker
	 */
	 baseIcon = new google.maps.Icon(G_DEFAULT_ICON);
	baseIcon.iconSize = new google.maps.Size(20,34);
	baseIcon.iconAnchor = new google.maps.Point(10,34)
	baseIcon.image = "/wp-content/themes/preDevCamp/images/mapIcon_pre.png";
	
	/*
	 * Retrieve the name of the city
	 */
	 var cityName = $("h2#cityName").text();
	 map = new google.maps.Map2(document.getElementById("locationInfo"));
	 if(cityName == "Orange County")
	 {
	  /*
	   * getLatLng doesn't like Orange County
	   */
	  map.setCenter(new google.maps.LatLng(33.8,-117.816667), 10);		   
	 }
	 else if(cityName != "preDevCamp")
	 {
	  var geocoder = new google.maps.ClientGeocoder();
	  geocoder.getLatLng(cityName,function(point){map.setCenter(point, 10);});
	 }
	 else
	 {
	  // This is the main page
	  map.setCenter(new google.maps.LatLng(0,0), 0);
	  $.getJSON('/cgi-bin/getCityInfo.pl',showCities);	
	 }
}

function showCities(response)
{
		jQuery.each(response.cityInfo,function()
	  {
		 var city = this;
		 addMarker(new google.maps.LatLng(city.lat,city.long),city.name,city.domainName);		  
	  }
	);
	
}

function getMarker(cityName,cityLink)
{
	if(cityName.indexOf("Orange County") != -1)
	{
		/*
		 * getLatLng doesn't like Orange County
		 */
		addMarker(new google.maps.LatLng(33.8,-117.816667), cityName,cityLink);		   
	}
	else
	{
		var geocoder = new google.maps.ClientGeocoder();
		geocoder.getLatLng(cityName,function(point){addMarker(point,cityName,cityLink);});
	}
}


function addMarker(point,cityName,cityLink)
{
	cityName.replace(/\s*$/, "");
	if(point != null)
	{
		var preIcon = new google.maps.Icon(baseIcon);
		var markerOptions = {icon:preIcon,title:cityName};
		var marker = new google.maps.Marker(point, markerOptions);
		map.addOverlay(marker);
		google.maps.Event.addListener(marker, "click", function()
		{
			parent.location.href='http://'+cityLink;											
		});
	}
}

$('document').ready(mapLoad);