/* ==================================================
   wdckyoto.js
   last update: 2009-09-15 19:05:28 daiki
   ================================================== */

google.load("earth", "1");
google.load("maps", "2.99");  // JS ジオコーダ

var ge = null;
var geocoder;

function el(e) { return document.getElementById(e); }

function init() {
  geocoder = new GClientGeocoder();
  google.earth.createInstance("map3d", initCB, failureCB);
}

function initCB(object) {
  ge = object;
  ge.getNavigationControl().setVisibility(ge.VISIBILITY_AUTO);
  ge.getLayerRoot().enableLayerById(ge.LAYER_BORDERS, true);
  ge.getLayerRoot().enableLayerById(ge.LAYER_BUILDINGS, false);
  ge.getOptions().setAtmosphereVisibility(true);
  fetchKmlFromWDCKyoto();
  ge.getWindow().setVisibility(true);
}

function failureCB(object) {
  alert('読み込みに失敗しました');
}

function submitLocation() {
  var address = el('address').value;
  geocoder.getLatLng(
    address, 
    function(point) {
      if (point && ge != null) {
        var la = ge.createLookAt('');     
        la.set(point.y, point.x, 100, ge.ALTITUDE_RELATIVE_TO_GROUND, 
               0, 0, 4000);
        ge.getView().setAbstractView(la);
      }
    }
  );
}

function fetchKmlFromWDCKyoto() {
  var kmlUrl = 'http://wdc.kugi.kyoto-u.ac.jp/gglearth/stations.kmz'
  google.earth.fetchKml(ge, kmlUrl, finishFetchKmlWDCKyoto);
}
    
function finishFetchKmlWDCKyoto(kmlObject) {
  // check if the KML was fetched properly
  if (kmlObject) {
    // add the fetched KML to Earth
    currentKmlObject = kmlObject;
    ge.getFeatures().appendChild(currentKmlObject);
      resetVisibilityWDCKyoto();
  } else {
    // wrap alerts in API callbacks and event handlers
    // in a setTimeout to prevent deadlock in some browsers
    setTimeout(function() {
//      alert('Bad or null KML.');
	alert('cannot load kml from WDC Kyoto.');
    }, 0);
  }
}


function resetVisibilityWDCKyoto() {
    stations = ge.getFeatures().getLastChild();
    //traceKmlNode(stations);
    
    // turn off
    var off = [1, 3];
    for (var i = 0; i < off.length ; i++) {
	stations.getFeatures().getChildNodes().item(off[i]).setVisibility(false);
    }

    // navigation control auto
    ge.getNavigationControl().setVisibility(ge.VISIBILITY_AUTO);
    ge.getNavigationControl().setVisibility(ge.VISIBILITY_AUTO);
    ge.getLayerRoot().enableLayerById(ge.LAYER_BORDERS, false);
    ge.getLayerRoot().enableLayerById(ge.LAYER_BUILDINGS, false);
}



// ================================================== debug
var str = ''
function traceKmlNode(node) {
    var childNodes = node.getFeatures().getChildNodes();
    for (var i = 0; i < childNodes.getLength(); i++) { 
	str = str + '[' + i + '] ' + childNodes.item(i).getName() + '<br>';
    } 
    alert(str);
}

