// we need to expose the map
var G_Map;
var change_point_provider;

(function(){
    var map;
    var point_provider = "X-POINT-PROVIDER-X";
    var app = new GoogleMapApp();
    var gm = google.maps;
    var kml_layer = null;

    $(document).ready(function(){
        var init_lat  = parseFloat($.cookie("GoogleMapLat")) || X-DEFAULT-LAT-X;
        var init_lon  = parseFloat($.cookie("GoogleMapLon")) || X-DEFAULT-LON-X;
        var init_zoom = parseFloat($.cookie("GoogleMapZoom")) || X-DEFAULT-ZOOM-X;
        var init_type = $.cookie("GoogleMapMapTypeId") || google.maps.MapTypeId.HYBRID;

        map = app.generateMap($(".GoogleMap").get(0), init_lat, init_lon,
                              {"zoom": init_zoom, "mapTypeId": init_type } );

        // Save stuff when the user changes things:
        gm.event.addListener( map, 'center_changed', function(){
            $.cookie("GoogleMapLat", map.getCenter().lat(), {expires: 7});
            $.cookie("GoogleMapLon", map.getCenter().lng(), {expires: 7});
        });
        gm.event.addListener( map, 'zoom_changed', function(){
            $.cookie("GoogleMapZoom", map.getZoom(), {expires: 7});
        });
        google.maps.event.addListener(map, "maptypeid_changed", function(){
            $.cookie("GoogleMapMapTypeId", map.getMapTypeId(), {"expires": 7});
        });

        // expose the map
        G_Map = map;

        draw_kml();
    });

    function draw_kml(){
        var url =
            "X-BASE-URL-X" +
            "index.php?P=P_GoogleMaps_GetKML" +
            "&PP="+point_provider +
            "&DP=X-DETAIL-PROVIDER-X" ;

        var myKml = new gm.KmlLayer( url,
                                     {map: map,
                                      preserveViewport: true });

        if (kml_layer !== null) {
            kml_layer.setMap(null);
        }
        kml_layer = myKml;
    }

    change_point_provider = function(new_pp){
        point_provider = new_pp;
        draw_kml();
    }
})();
