﻿var Kml =
{
    KmlMap : function (mapDivId, kmlLink, options)
    {
        var DEFAULT_ERR_INTERVAL = 20000; // 20 seconds
        var DEFAULT_MAX_RETRIES = 5; // The maximum number of times to try to reload the map
        
        var _errorTimer = null;
        var _retries = 0;
        var _map = null; 
        
        var _zoomLevel = options.ZoomLevel || 4;
        var _startLat = options.StartLat || 0;
        var _startLong = options.StartLong || 0;
        var _errorTimeout = options.ErrorTimeout || DEFAULT_ERR_INTERVAL;
        var _maxRetries = options.MaxRetries || DEFAULT_MAX_RETRIES;
        
        this.LoadMap = _loadMap;
        
        // Loads in a Google map and attempts to add an overlay for the kml. If the overlay fails
        // the error timer will attempt to load the map again until maximum number of retries is reached
        function _loadMap()
        {
            if (GBrowserIsCompatible())
            {
                var mapDiv = document.getElementById(mapDivId);
                _map = new GMap2(mapDiv);
                _map.addControl(new GSmallMapControl());
                //Remove map types
                //_map.addControl(new GMapTypeControl());
                _map.setCenter(new GLatLng(_startLat, _startLong), _zoomLevel);
                               
                // Set an error timer. If the GGeoXml doesn't load before the interval is up, clear the 
                // overlays and try to load it again. If the overlay loads, the timer will be cancelled.
                _errorTimer = setInterval(_tryAgain, _errorTimeout); 
                //_map.addOverlay(new GMarker(new GLatLng(41.9, -87.62)));
                _addOverlay();
            }
        }
        
        
        // Attempts to add the overlay and if successful clears the error timeout
        function _addOverlay()
        {        
            var kmlOverlay = new GGeoXml(kmlLink, 
                                         function (test) 
                                         { 
                                            document.getElementById(mapDivId + "-cover").style.display = "none";
                                            clearInterval(_errorTimer);
                                         });
        
            _map.addOverlay(kmlOverlay);
        }
        
        // Clears the overlays from the map and tries to load it again
        function _tryAgain()
        {
            // Only keep trying to reload if the maximum # of retries hasn't been reached
            if (_retries < _maxRetries)
            {
                _retries++;
                _map.clearOverlays();
                _addOverlay();
            }
            // Otherwise, reset the retry timer
            else
            {
                clearInterval(_errorTimer);
            }
        }
    }
}