google.load("earth", "1");

var ge = null;
var imgOverlayKml = null;

function init() {
  google.earth.createInstance("map3d", initCallback, failureCallback);
}

function initCallback(object) {
  ge = object;
  ge.getWindow().setVisibility(true);
  ge.getNavigationControl().setVisibility(ge.VISIBILITY_AUTO);
  var options = ge.getOptions();
  options.setStatusBarVisibility(true);
}

function failureCallback(object) {
  alert('Failed To Load GE Plug-in');
}

function showImgOverlay(val) {
  if (val == "none") {
    if (imgOverlayKml) {
      ge.getFeatures().removeChild(imgOverlayKml);
      imgOverlayKml = null;
    }
  }
  else if (val == "Poster"){
    if (imgOverlayKml) {
      ge.getFeatures().removeChild(imgOverlayKml);
      imgOverlayKml = null;
    }
    imgOverlayKml = ge.parseKml(
      '<kml xmlns="http://earth.google.com/kml/2.1">' +
      '  <GroundOverlay>' +
      '      <name>DMSP Nighttime Lights</name>' +
      '      <visibility>1</visibility>' +
      '<Icon>' +
      '              <href>http://www.ngdc.noaa.gov/eog/maps/cgi-bin/public/ms/poster?service=WMS&amp;request=getMap&amp;layers=nighttime_lights_f152003&amp;format=image/jpeg&amp;srs=EPSG:4326&amp;version=1.1.1&amp;WIDTH=2000&amp;HEIGHT=2000</href>' +
      '              <viewRefreshMode>onStop</viewRefreshMode>' +
      '              <viewBoundScale>1</viewBoundScale>' +
      '      </Icon>' +
      '      <LatLonBox>' +
      '              <north>90</north>' +
      '              <south>-90</south>' +
      '              <east>-180</east>' +
      '              <west>180</west>' +
      '      </LatLonBox>' +
      ' </GroundOverlay>' +
      '</kml>');
    ge.getFeatures().appendChild(imgOverlayKml);
  }
  else {
    if (imgOverlayKml) {
      ge.getFeatures().removeChild(imgOverlayKml);
      imgOverlayKml = null;
    }
    imgOverlayKml = ge.parseKml(
      '<kml xmlns="http://earth.google.com/kml/2.1">' +
      '  <GroundOverlay>' +
      '      <name>DMSP Nighttime Lights</name>' +
      '      <visibility>1</visibility>' +
      '<Icon>' +
      '              <href>http://www.ngdc.noaa.gov/eog/maps/cgi-bin/public/ms/gcv2?service=WMS&amp;request=getMap&amp;layers=' +
      val + '_v2_stable_lights_avg_vis&amp;format=image/jpeg&amp;srs=EPSG:4326&amp;version=1.1.1&amp;WIDTH=2000&amp;HEIGHT=2000</href>' +
      '              <viewRefreshMode>onStop</viewRefreshMode>' +
      '              <viewBoundScale>1</viewBoundScale>' +
      '      </Icon>' +
      '      <LatLonBox>' +
      '              <north>90</north>' +
      '              <south>-90</south>' +
      '              <east>-180</east>' +
      '              <west>180</west>' +
      '      </LatLonBox>' +
      ' </GroundOverlay>' +
      '</kml>');
    ge.getFeatures().appendChild(imgOverlayKml);
  }
}
