(function($) {

    /**
     * Contains google map instance.
     */
    var MAP;

    /**
     * Contains an array of map markers.
     */
    var MANAGERS = {};

    /**
     * Contains the default latlng coordinates for the map to center on nz.
     */
    var NZ = new GLatLng(-40.900557, 174.885971);

    $(document).ready(function() {
        /**
         * Create a new google map object.
         */
        MAP = new GMap2($('#theMap').get(0));
        MAP.setCenter(NZ, 5);
        MAP.setUIToDefault();
        MAP.disableDoubleClickZoom();

        /**
         * Create a new MarkerManager object
         */
        MANAGER = new MarkerManager(MAP);

        /**
         * Event handler when map is double clicked, zoom in, center on that point and display the
         * "Please select service type" box.
         */
        GEvent.addListener(MAP, 'click', function(overlay, point) {
            MAP.setCenter(point);
            MAP.setZoom(10);
            load_map_features();
            $('#stage1').css('display', 'none');
            $('#stage3').css('display', 'block');
        });

        /**
         * Get the map features when the map is zoomed.
         */
        GEvent.addListener(MAP, 'zoomend', function() {
            if (10 <= MAP.getZoom()) {
                load_map_features();
                $('#stage1').css('display', 'none');
                $('#stage3').css('display', 'block');
            } else {
                $('#stage3').css('display', 'none');
                $('#stage1').css('display', 'block');
            }
        });

        /**
         * Add event listeners to input and select fields in "Select service type" menu to get the
         * map features when a service type is changed.
         */
        $('input[name=RadioGroup1], select[name=DayCareRes]').click(function() {
            load_map_features();
        });
    });

    /**
     * Support method to query the json api and retrieve the points to display on the google map.
     */
    var load_map_features = function()
    {
        //var bounds = MAP.getBounds();
        //var southwest = bounds.getSouthWest();
        //var northwest = bounds.getNorthEast();

        var selected = $('input[name=RadioGroup1]:checked').val();
        if ('DayCare' == selected) {
            selected = $('select[name=DayCareRes] option:selected').val();
        }

        var data = {
            'StID': selected
            //'MinX': southwest.lng(),
            //'MaxX': northwest.lng(),
            //'MinY': northwest.lat(),
            //'MaxY': southwest.lat()
        };

        if (undefined == MANAGERS[selected]) {
            MANAGERS[selected] = new MarkerManager(MAP);

            $.getJSON('/map/ajax/', data, function(data) {
                $.each(data, function(i, item) {
                    var latlng = new GLatLng(item['y'], item['x']);
                    var marker_options = {icon: get_icon(item), title: item['name']};
                    var marker = new GMarker(latlng, marker_options);
                    GEvent.addListener(marker, 'click', function(point) {
                        window.location = '/Facilities/Service/DisplayService/FromMap/1/FaStID/'+item['id'];
                    });
                    MANAGERS[selected].addMarker(marker, 10);
                });
            });
        }

        for (manager in MANAGERS) {
            MANAGERS[manager].hide();
        }
        MANAGERS[selected].show();
    };

    /**
     * Support method for creating a GIcon object for a Marker to display on the map.
     */
    var get_icon = function(data)
    {
        if (data.subscriber) {
            var icon = new GIcon(G_DEFAULT_ICON,
                '/IM_Custom/Classes/EldernetFacilityAsset/Templates/Images/key-1.png');
        } else {
            var icon = new GIcon(G_DEFAULT_ICON,
                '/IM_Custom/Classes/EldernetFacilityAsset/Templates/Images/key-2.png');
        }

        icon.iconSize = new GSize(10, 10);
        icon.iconAnchor = new GPoint(0, 0);
        icon.shadow = null;

        return icon;
    };

})(jQuery);

