var map;
var geocoder;
var map_cur_layer;

registerPloneFunction(function () {
    if (GBrowserIsCompatible()) {
        map = new GMap2(document.getElementById('providers-map'));
        // http://maps.google.com/?ie=UTF8&ll=39.740986,-96.723633&spn=23.398378,73.828125&z=5
        // Oregon focus:
        // map.setCenter(new GLatLng(45.5,-122.5), 9);
        // National focus:
        map.setCenter(new GLatLng(39.740986,-96.723633), 3);
        map.addControl(new GLargeMapControl());
        map.addControl(new GMapTypeControl());
        map.enableScrollWheelZoom();
        
        // prevent zooming in too much
        GEvent.addListener(map, 'zoomend', function(oldZoomLevel, newZoomLevel) {
           if(newZoomLevel > 9) {
             map.setZoom(Math.min(oldZoomLevel, 9));
           }
        });
        
        geocoder = new GClientGeocoder();
        
        // load the initial map layer
        loadKML('childcare-providers.kml', true);
    }
});

function loadKML(kml_url, nozoom) {
    if (nozoom == null) {
        nozoom = false;
    }
    var Icon = new GIcon();
    Icon.iconSize = new GSize(10, 16);
    Icon.iconAnchor = new GPoint(5, 16);
    Icon.infoWindowAnchor = new GPoint(5, 4);
    if (map_cur_layer) {
        map_cur_layer.removeOverlay();
    }
    map_cur_layer = new EGeoXml('map_cur_layer', map, kml_url, {nozoom: nozoom, baseicon:Icon});
    map_cur_layer.parse();
}

// Remove Overlays
EGeoXml.prototype.removeOverlay = function (){
    if(this.gmarkers.length != 0) {
        for(i=0;i<this.gmarkers.length;i++) {
            map.removeOverlay(this.gmarkers[i]);
            //clusterer.RemoveMarker(this.gmarkers[i]);
        }
    }
    if(this.gpolylines.length != 0) {
        for(i=0;i<this.gpolylines.length;i++) {
            map.removeOverlay(this.gpolylines[i]);
        }
    }
    if(this.gpolygons.length != 0) {
        for(i=0;i<this.gpolygons.length;i++) {
            map.removeOverlay(this.gpolygons[i]);
        }
    }
};

//This function zooms map to the selected address
function showAddress(address, zoom) {
    //console.log(address);
    
    if (zoom == null) {
        zoom = 9;
    }
    if (geocoder) {
        geocoder.getLatLng(address, function(point) {
            if (!point) {
                alert(address + " not found");
            } else {
                map.setCenter(point, zoom);
            }
        });
    }
}
