
google.load("maps", "2");
google.setOnLoadCallback(function() {
    var tooltip = $("tooltip");
    var tooltipText = $("tooltip_text");

    var geocoder = new google.maps.ClientGeocoder();
    var map = new google.maps.Map2($("google_map"));
    var bounds = new google.maps.LatLngBounds();
    map.addControl(new google.maps.SmallMapControl());

    var communityCount = 0;
    var responseCount = 0;

    function addCommunity(community, point) {
        bounds.extend(point);
        if (++communityCount == 1) {
            map.setCenter(bounds.getCenter());
            map.setZoom(10);
        }
        var marker = new google.maps.Marker(point);

        // mouseover for community icon
        google.maps.Event.addListener(marker, "mouseover", function(position) {
            if (tooltip.getStyle("visibility") != "visible") {
                var point = map.fromLatLngToContainerPixel(position);
                tooltipText.innerHTML = community.name;
                tooltip.style.left = point.x + "px";
                tooltip.style.top = (point.y - tooltip.getHeight() - 40) + "px";
                tooltip.style.visibility = "visible";
            }
        });

        // mouseout for community icon
        google.maps.Event.addListener(marker, "mouseout", function(position) {
            tooltip.style.visibility = "hidden";
        });

        // onclick for community icon
        google.maps.Event.addListener(marker, "click", function(position) {
            window.location = community.url;
        });

        map.addOverlay(marker);

        if (communityCount == Communities.length) {
            if (MapCenter) {
                map.setCenter(MapCenter);
            }
            else {
                map.setCenter(bounds.getCenter());
            }

            if (MapZoom > 0) {
                map.setZoom(MapZoom);
            }
            else {
                if (communityCount > 1) {
                    map.setZoom(map.getBoundsZoomLevel(bounds));
                    if (MapZoom == -1) map.zoomOut();
                }
            }
        }
    }

    Communities.each(function(community) {
        if (community.latitude) {
            addCommunity(community, new GLatLng(community.latitude, community.longitude));
        }
        else {
            geocoder.getLatLng(community.address,
		    function(point) {
		        if (point) { addCommunity(community, point); }
		    }
		);
        }
    });



});
