var GoogleEarth = function(elID) {
    var that = this;
    var _ge = null;
    var _view = null;
    var coords = {
        lat: 0.0, lon: 0.0, alt: 1000,
        heading: 180.0, tilt: 75.0, range: 1000
    };

    // Public methods
    this.zoomTo = function(newCoords) {
        if (_ge != null) {
            var v = _getView();
            if (v != null) {
                coords = $.extend(coords, newCoords);
                v.set(coords.lat, coords.lon, coords.alt,
                      _ge.ALTITUDE_CLAMP_TO_GROUND,
                      coords.heading, coords.tilt, coords.range);
                _ge.getView().setAbstractView(v);
            }
        } else {
            coords = $.extend(coords, newCoords);
        }
    };

    function _getView() {
        var result = _view;
        if ((result == null) && (_ge != null)) {
            result = _view = _ge.getView().copyAsLookAt(
                _ge.ALTITUDE_CLAMP_TO_GROUND);
        }
        return result;
    };

    function _showFailure(msg) {
        // Avoid overwriting the default Google Earth plugin error message.
        return;
    };

    function _initCB(pluginInstance) {
        _ge = pluginInstance;
        _ge.getWindow().setVisibility(true);
        // add a navigation control
        _ge.getNavigationControl().setVisibility(_ge.VISIBILITY_AUTO);
        that.zoomTo(coords);
    };

    function _failCB(errorCode) {
        _showFailure("Couldn't create Google Earth instance: " + errorCode);
    };

    function _earthLoaded() {
        if (google && google.earth && google.earth.createInstance) {
            google.earth.setLanguage("en");
            google.earth.createInstance(elID, _initCB, _failCB);
        } else {
            showFailure("Cannot create Google Earth instance -- google earth not properly loaded.");
        }
    };

    google.load("earth", "1", {"callback": _earthLoaded});
    return this;
};

$(document).ready(function() {
    var ge = new GoogleEarth('ge_view');
    var coords = {
        lat: 0.0,
        lon: 0.0,
        alt: 5000
    };
    // See if the URL includes view coordinates.
    var s = location.search;
    if (s) {
        var params = s.substring(1).split("&");
        for (var i = 0; i != params.length; i++) {
            var parts = params[i].split('=');
            if (parts.length == 2) {
                coords[parts[0]] = parseFloat(parts[1]);
            }
        }
    }

    function resize() {
        var wPix = $('body').width() - 8;
        var hPix = Math.floor(0.75 * wPix);
        var header = $('#header');
        var hBottom = header.offset().top + header.height();
        var footer = $('#footer');
        var fTop = footer.offset().top;
        var hMax = (fTop - hBottom) - 16;
        if ((hMax > 0) && (hMax < hPix)) {
            hPix = hMax;
        }
        $('#ge_view').width(wPix).height(hPix);
    };

    $(window).resize(resize);
    resize();
    ge && ge.zoomTo(coords);
});
