$(document).ready(function() {
    var options = {
        controls: [],
        numZoomLevels: 10
    };
    var map = new OpenLayers.Map('solar_map', options);

    // Show a map of slopes.
    var wms = new OpenLayers.Layer.WMS("Terrain Flatness",
        "http://insolation.mesaac.com/mapserv.cgi",
        {
            layers: "etopo1_raster"
        },
        {
            projection: "EPSG:4326"
        });
      
    var worldpoli = new OpenLayers.Layer.WMS("Political Boundaries",
        "http://insolation.mesaac.com/mapserv.cgi",
        {
            layers: "world,states_line"
        },
        {
            isBaseLayer: false
        });
    worldpoli.setOpacity(0.25);
    
    var insol = new OpenLayers.Layer.WMS("Insolation",
        "http://insolation.mesaac.com/mapserv.cgi",
        {
            layers: "annual_avg_insolation"
        },
        {
            isBaseLayer: false,
            projection: "EPSG:4326"
        });
    insol.setOpacity(0.5);

    map.addLayers([wms, worldpoli, insol]);

    var switcherControl = new OpenLayers.Control.LayerSwitcher();
    map.addControl(switcherControl);
    switcherControl.maximizeControl();
    map.addControl(new OpenLayers.Control.PanZoomBar());
    map.addControl(new OpenLayers.Control.MouseDefaults());
    map.addControl(new OpenLayers.Control.KeyboardDefaults());
    
    //=============================================================
    // Latitude/longitude field mgmt
    //-------------------------------------------------------------
    var latField = $('#latitude_field');
    var lonField = $('#longitude_field');
    var zoomBtn = $('#zoom_btn');
    var geviewLink = $('#geview_link');
    var userOpenedGEView = false;
    
    var currLat = null, currLon = null;
    
    var lalo = $('#latitude_field,#longitude_field');
    
    function openGEView() {
        userOpenedGEView = true;
        try {
            window.open(geviewLink.attr('href'), "geview");
        } catch (e) {}
    };
    
    geviewLink.click(function() {
        openGEView();
        return false;
    });
    
    function zoomGoogleEarth(lat, lon) {
        var url = ("/ge.html?lat=" + lat + "&lon=" + lon);
        geviewLink.attr("href", url);
        if (userOpenedGEView) {
            openGEView();
        }
    };

    function showCenter() {
        var lonlat = map.getCenter();
        if (lonlat != null) {
            latField.val(lonlat.lat.toFixed(6));
            currLat = lonlat.lat;
            lonField.val(lonlat.lon.toFixed(6));
            currLon = lonlat.lon;
            lalo.removeClass("Changed");

            zoomGoogleEarth(currLat, currLon);
        }
    };
        

    function zoomMap() {
        var lat = parseFloat(latField.val());
        var lon = parseFloat(lonField.val());
        
        if (!(isNaN(lat) || isNaN(lon))) {
            var zoomLevel = map.getNumZoomLevels() - 1;
            map.setCenter(
                new OpenLayers.LonLat(parseFloat(lon), parseFloat(lat)),
                zoomLevel
            );
            currLat = lat;
            currLon = lon;
            lalo.removeClass("Changed");
        }
    };
    
    // Zoom only if the user hits return.
    $('#lat_lon').submit(function() {
        zoomMap();
        return false;
    });
    // Prevent the map from responding to arrow events inside the 
    // lat/lon fields.
    lalo.keydown(function(e) {
        // Propagate carriage returns to the containing form.  Absorb
        // everything else.
        if (e.keyCode == 13) {
            $('#lat_lon').submit();
        } else {
            e.stopPropagation();
        }
    });
    
    // TODO:  Use map.getCenter() to detect unapplied field values.
    latField.change(function() {
        latField.toggleClass("Changed", (latField.val() != currLat));
    });
    lonField.change(function() {
        lonField.toggleClass("Changed", (lonField.val() != currLon));
    });
    
    zoomBtn.click(zoomMap);
    
    function moved() {
        showCenter();
    };
    map.events.register("moveend", this, moved);
    
    //-------------------------------------------------------------

    function resize() {
        // Get the jQuery map element, not to be confused with the
        // OpenLayers map object.
        var solarMap = $("#solar_map");
        var wPix = $('body').width() - 10;
        var hPix = Math.floor(0.5 * wPix);
        // Try to avoid scrolling
        var hWin = $(window).height();
        var headerBottom = $('#header').offset().top + $('#header').height();
        var hMax = hWin - headerBottom - 128;
        hMax = (hMax > 0) ? hMax : 480;
        hPix = (hPix > hMax) ? hMax : hPix;
        
        solarMap.width(wPix).height(hPix);
        if (map.updateSize) { 
            map.updateSize();
        };
    };

    $(window).resize(resize);

    resize();
    map.zoomToMaxExtent();
    showCenter();
    latField.focus();
});