var map = null;
var markers = [];
var centerLatitude = 30;
var centerLongitude = -98;
var zoom = 2;
var geocoder = null;
var markerManager  = null;

function geocodeCallback(point) {
	if (!point) {
		alert(address + " not found");
	} else {
		centerLatitude = point.lat();
		centerLongitude = point.lng();
		zoom = 5;
		map.setCenter(new GLatLng(centerLatitude, centerLongitude), zoom);
		document.input.location.value = "";
	}
}

function geocodeAddress(theForm) {
	var address = theForm.location.value;
	var returnVal = true;
	geocoder.getLatLng(address, geocodeCallback );
	return false;
}	

function showAddress(address) {
	geocoder.getLatLng(
		address,
		function(point) {
			if (!point) {
				alert(address + " not found");
			} else {
				map.setCenter(point, 13);
			}
		}
	);
}

function showGoogleMap(address) {
	window.open("http://maps.google.com/maps?f=q&q=" + address);
}

function initialize() {
	if (GBrowserIsCompatible()) {
		map = new GMap2(document.getElementById("map_canvas"));
		map.addControl(new GLargeMapControl());
		map.setCenter(new GLatLng(centerLatitude, centerLongitude), zoom);
		map.enableDoubleClickZoom();
		map.setUIToDefault();
		
		geocoder = new GClientGeocoder();

		for (var i = 0; i < data.station.length; ++i) {
			var latlng = new GLatLng(data.station[i].latitude, data.station[i].longitude);
			markers.push(createMarker(latlng, data.station[i].name, data.station[i].address));
		}
		
		markerManager = new MarkerManager(map);
		markerManager.addMarkers(markers, 3);
		markerManager.refresh();
	}
}

function createMarker(latlng, name, address) {
	var icon = new GIcon(); 
    icon.image = 'http://labs.google.com/ridefinder/images/mm_20_red.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 marker = new GMarker(latlng, {icon: icon, title: address});

	var html = "<b>" + name + "</b><br/>";
	html += "<a href=\"javascript:showGoogleMap('" + encodeURIComponent(address) + "')\">" + address + "</a>";
	
	GEvent.addListener(marker, "click", function() {
		//if (map.getZoom() < 13) {
		//	showAddress(address);
		//} else {
		marker.openInfoWindowHtml(html);
		//}
	});
	
	//GEvent.addListener(marker, 'mouseover', function(){
	//	this.tooltip.show();
	//});
	
	//GEvent.addListener(marker, 'mouseout', function(){
	//	this.tooltip.hide();
	//});
	
	return marker;
}
