var ge;

// store the object loaded for the given file... initially none of the objects
// are loaded, so initialize these to null
var currentKmlObjects = {
  'marengo1000': null,
  'marengo1700': null,
  'marengophotos': null
};

google.load("earth", "1");

function loadMap() {
  google.earth.createInstance('map3d', initCallback, failureCallback);
}

function initCallback(instance) {
  ge = instance;
  ge.getWindow().setVisibility(true);

  // add a navigation control
  ge.getNavigationControl().setVisibility(ge.VISIBILITY_AUTO);

  // add some layers
  ge.getLayerRoot().enableLayerById(ge.LAYER_BORDERS, true);
  //ge.getLayerRoot().enableLayerById(ge.LAYER_ROADS, true);

  // fly to Santa Cruz
  var la = ge.createLookAt('');
  la.set(44.906795, 8.728419,
    0, // altitude
    ge.ALTITUDE_RELATIVE_TO_GROUND,
    0, // heading
    0, // straight-down tilt
    18256 // range (inverse of zoom)
    );
  ge.getView().setAbstractView(la);

  // if the page loaded with checkboxes checked, load the appropriate
  // KML files
  if (document.getElementById('radiomarengo1000').checked)
	{
    loadKml('marengo1000');
	}

  if (document.getElementById('radiomarengo1700').checked)
	{
    loadKml('marengo1700');
	}

  if (document.getElementById('radiomarengophotos').checked)
	{
    loadKml('marengophotos');
	}

  //document.getElementById('installed-plugin-version').innerHTML =
  //  ge.getPluginVersion().toString();
}

function failureCallback(errorCode) {
}

function removeAll(){
	for(i in currentKmlObjects)
	{
		if(currentKmlObjects[i] != null)
		{
			ge.getFeatures().removeChild(currentKmlObjects[i]);
			currentKmlObjects[i] = null;
		}
	}
}

function radioChange(file) {
	removeAll();

  // if the checkbox is checked, fetch the KML and show it on Earth
  var kmlCheckbox = document.getElementById('radio' + file);
  if (kmlCheckbox.checked)
    loadKml(file);
}

function loadKml(file) {
  var kmlUrl = 'http://www.virtualarc.com/static/kml/' + file + '.kmz';
//var kmlUrl = '/static/kml/' + file + '.kml';

  // fetch the KML
  google.earth.fetchKml(ge, kmlUrl, function(kmlObject) {
    // NOTE: we still have access to the 'file' variable (via JS closures)

    if (kmlObject) {
      // show it on Earth
      currentKmlObjects[file] = kmlObject;
      ge.getFeatures().appendChild(kmlObject);
    } else {
      // bad KML
      currentKmlObjects[file] = null;

      // wrap alerts in API callbacks and event handlers
      // in a setTimeout to prevent deadlock in some browsers
      setTimeout(function() {
        alert('Bad or null KML.');
      }, 0);

      // uncheck the box
      document.getElementById('radio' + file).checked = '';
    }
  });
}
