function getHTTPObject() {
	var xhr = false;
	if (window.XMLHttpRequest) {
		xhr = new XMLHttpRequest();
	} else if (window.ActiveXObject) {
		try {
			xhr = new ActiveXObject("Msxml2.XMLHTTP");
		} catch(e) {
			try {
				xhr = new ActiveXObject("Microsoft.XMLHTTP");
			} catch(e) {
				xhr = false;
			}
		}
	}
	return xhr;
}

var map;
var bounds;

// Return XML
function grabMapXML(url, type) {
	$('#map-loading').show();
	var request = getHTTPObject();
	if (request) {
		request.onreadystatechange = function() {
			parseMapXMLResponse(request, type);
		};
		request.open("GET", url, true);
		request.send(null);
	}
}

function parseMapXMLResponse(request, type) {
  if (request.readyState == 4) {
    if (request.status == 200 || request.status == 304) {
		var data = request.responseXML;

		if (GBrowserIsCompatible()) {
			// Set up the map
			map = new GMap2(document.getElementById("map"));
			
			map.setCenter(new GLatLng(0,0), 0);
			bounds = new GLatLngBounds();
		
			// Create the icon
			var icon = new GIcon();
			icon.image = "http://labs.google.com/ridefinder/images/mm_20_green.png";
			icon.shadow = "http://labs.google.com/ridefinder/images/mm_20_shadow.png";
			icon.iconSize = new GSize(12, 20);
			icon.shadowSize = new GSize(22, 20);
			icon.iconAnchor = new GPoint(6, 20);
			icon.infoWindowAnchor = new GPoint(5, 1);
		
			var points = data.getElementsByTagName("location");
			var markers = [];
			var point;
			for (var i = 0; i < points.length; i++) {
				var lng = parseFloat(points[i].getElementsByTagName('longitude')[0].firstChild.nodeValue);
				var lat = parseFloat(points[i].getElementsByTagName('latitude')[0].firstChild.nodeValue);
				if(points[i].getElementsByTagName('title')[0].firstChild)
					var title = points[i].getElementsByTagName('title')[0].firstChild.nodeValue;
				else
					var title = '';
				if(points[i].getElementsByTagName('details')[0].firstChild)
					var details = points[i].getElementsByTagName('details')[0].firstChild.nodeValue;
				else
					var details = '';
				if(points[i].getElementsByTagName('slug')[0].firstChild)
					var slug = points[i].getElementsByTagName('slug')[0].firstChild.nodeValue;
				else
					var slug = '';
				if(points[i].getElementsByTagName('link')[0].firstChild)
					var link = points[i].getElementsByTagName('link')[0].firstChild.nodeValue;
				else
					var link = '';
				if(points[i].getElementsByTagName('address')[0].firstChild)
					var address = points[i].getElementsByTagName('address')[0].firstChild.nodeValue;
				else
					var address = '';
				if(points[i].getElementsByTagName('city')[0].firstChild)
					var city = points[i].getElementsByTagName('city')[0].firstChild.nodeValue;
				else
					var city = '';
				if(points[i].getElementsByTagName('province')[0].firstChild)
					var province = points[i].getElementsByTagName('province')[0].firstChild.nodeValue;
				else
					var province = '';
				if(points[i].getElementsByTagName('postal')[0].firstChild)
					var postal = points[i].getElementsByTagName('postal')[0].firstChild.nodeValue;
				else
					var postal = '';
				if(points[i].getElementsByTagName('country')[0].firstChild)
					var country = points[i].getElementsByTagName('country')[0].firstChild.nodeValue;
				else
					country = '';
				marker = createMarker(lat, lng, type, title, details, slug, link, address, city, province, postal, country);
				map.addOverlay(marker);
			}
			if(type == 'home')
				map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
			else
				map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds)-1);

			//Create accessible map controls
			$('#mapcontrols button').click(function() { return false; });				
			$('#centerButton').click(function() { map.panTo(bounds.getCenter()); });
			$('#upButton').click(function() { map.panDirection(0,0.5); });
			$('#rightButton').click(function() { map.panDirection(-0.5,0); });
			$('#downButton').click(function() { map.panDirection(0,-0.5); });
			$('#leftButton').click(function() { map.panDirection(0.5,0); });
			$('#zoomInButton').click(function() { map.zoomIn(); });
			$('#zoomOutButton').click(function() { map.zoomOut(); });
		
			$('#map-loading').animate( {opacity: 'hide' },1500);
		}
    }
  }
}

function createMarker(latitude, longitude, type, title, details, slug, link, address, city, province, postal, country) {
	// Create the icon for the marker
	var icon = new GIcon();
	icon.image = "/images/icons/marker.png";
	icon.iconSize = new GSize(21, 24);
	icon.iconAnchor = new GPoint(10, 24);
	
	point = new GLatLng(latitude,longitude);

	// Create the new mark and add an info window with the name of the ward;
	var marker = new GMarker(point,icon);
	GEvent.addListener(marker, "click", function() {
		var overlay = document.getElementById('overlay');
		if(document.getElementById('overlay')) {
			map.getPane(G_MAP_MARKER_PANE).removeChild(overlay);
		}
		var infoShell = document.createElement('div');
		infoShell.id = 'overlay';
		
		var inner = document.createElement('div');
		$(inner).addClass('inner');
		
		var close = document.createElement('a');
		close.id = 'close';
		$(close).attr('href', '#close');
		$(close).click(function(){ closeInfo(); return false; });
		$(close).text('Close');
		$(inner).append($(close));	
		$(inner).append('<h4>'+title+'</h4>');
		if(type == 'details')
			$(inner).append('<p>'+address+'<br/>'+city+', '+province+'<br/>'+country+' '+postal+'</p>');
		else if(type == 'general')
			$(inner).append('<p>'+details+'</p>');
		
		var theP = document.createElement('p');
		var theLink = document.createElement('a');
		if(type == 'details') {
			$(theLink).attr('href', link);
			$(theLink).text('View Website');
		} else {
			$(theLink).attr('href', '/directions/'+slug+'/');
			$(theLink).text('View More Details');
		}
		$(theP).append($(theLink));
		$(inner).append($(theP));
		
		$(infoShell).append($(inner));
		
		map.getPane(G_MAP_MARKER_PANE).appendChild(infoShell);
		var markerPosition = map.fromLatLngToDivPixel(marker.getPoint());
		var overlayBottom = parseInt(markerPosition.y)-(infoShell.offsetHeight+20);
		var overlayLeft = parseInt(markerPosition.x)-110;
		infoShell.style.top = overlayBottom+"px";
		infoShell.style.left = overlayLeft+"px";
		infoShell.style.visibility = "visible";
		
		if(type == 'home')
			map.panTo(map.fromDivPixelToLatLng(new GPoint(parseInt(markerPosition.x), parseInt(markerPosition.y)-($('#map').height()/2-20))));
		else
			map.panTo(map.fromDivPixelToLatLng(new GPoint(parseInt(markerPosition.x), parseInt(markerPosition.y)-($('#map').height()/2-50))));

	});
	bounds.extend(point);
  	return marker;
}

function closeInfo() { $('#overlay').remove(); }