window.addEvent('domready', function() {
    if (GBrowserIsCompatible()) {
        var map = new GMap2(document.getElementById("map"));
        map.addMapType(G_NORMAL_MAP); 
        map.setCenter(new GLatLng(-36.845699697257494, 174.76275655661198), 10, G_NORMAL_MAP);
        map.setUIToDefault();

        var customUI = map.getDefaultUI();
        customUI.zoom.scrollwheel = false;
        map.setUI(customUI);
    }

    var request = new Request.JSON({
        url: "/hospitals.aspx?altTemplate=JSON-hospitals",
        onSuccess: function (response) {
            var locations = $H();

            response['hospitals'].each(
                function (hospital) {
                    var point = hospital['location'],
                        pre = (locations.get(point) || "");

                    locations.set(point, pre + buildHTML(hospital));
                });

            locations.each(addMarker);
        }
    }).get();

    function addMarker(html, coord) {
        var location = coord.split(','),
            x = location[0], y = location[1],
            point = new GLatLng(x, y),
            marker = new GMarker(point);

        map.addOverlay(marker);

        GEvent.addListener(marker, "click", function() {
            map.openInfoWindow(point, html);
        });
    }

    function buildHTML(hospital) {
        return ("<h3><a href=\"{link}\"/>{name}</a></h3>"
        +       "<ul>"
        +       (hospital.phone == "" ? "" : "<li>Phone: {phone}</li>")
        +       (hospital.email == "" ? "" : "<li>Email: {email}</li>")
        +       "</ul>"
        ).substitute(hospital);
    }
});

