/* ==================================================
   wdckyoto_stations.js
   last update: 2009-09-16 11:33:57 daiki
   ================================================== */
google.load("earth", "1");
google.load("maps", "2");

var ge = null;
var geocoder;

var kmlObjectList = [];
var kmlListHtml = ''
var kmlListHtmlArray = [];
var laMaster, laSlave;
var camMaster, camSlave;

function fitLongitude(lon) {
  while (lon < 0)
    lon += 360;

  lon = lon % 360;

  return (lon > 180) ? lon - 360 : lon;
}

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

function init() {
  geocoder = new GClientGeocoder();
  google.earth.createInstance('ge', initCB, failureCB);
  var syncActive = false;
}

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

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, 0, ge.ALTITUDE_RELATIVE_TO_GROUND, 
               100, 0, 1000000);
        ge.getView().setAbstractView(la);
    }
  );
}


// ==================================================
var currentKmlObject = null;
    
function fetchKmlFromInput() {
// remove the old KML object if it exists
//  if (currentKmlObject) {
//    ge.getFeatures().removeChild(currentKmlObject);
//    currentKmlObject = null;
//  }
    
//  var kmlUrlBox = document.getElementById('kml-url');
//  var kmlUrl = kmlUrlBox.value;
  var kmlUrl = el('kml-url').value;

  google.earth.fetchKml(ge, kmlUrl, finishFetchKml);
}
    
function finishFetchKml(kmlObject) {
  // check if the KML was fetched properly
  if (kmlObject) {
    // add the fetched KML to Earth
    currentKmlObject = kmlObject;
    ge.getFeatures().appendChild(currentKmlObject);
    createCheckbox(kmlObjectList.length);
    kmlObjectList.push(currentKmlObject);
  } 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.');
    }, 0);
  }
}


// ==================================================
function showHideKml() {
  if (currentKmlObject) {
//    alert(currentKmlObject);
    currentKmlObject.setVisibility(!currentKmlObject.getVisibility());
  }
//  kmlObject.setVisibility(!kmlObject.getVisibility());
}

function updateVisibility(num) {
  id = 'kml' + num;
  if (kmlObjectList[num]) {
    kmlObjectList[num].setVisibility(el(id).checked);
  }
}

function createCheckbox(num) {
  var currentId = 'kml' + num;
  var boxHtml = '<form><input type=\"checkbox\" onclick=\"updateVisibility('
  + num + ')\" id=\"' + currentId + '\" />'
  + currentKmlObject.getName()
  + ' &nbsp; <a href=\"javascript:void(0)\" onclick=\"removeCheckbox('
  + num + ');return(false);\" alt=\"remove item\">[x]</a></form>';
  kmlListHtmlArray.push(boxHtml);
  kmlListHtml = kmlListHtml + boxHtml;
  el('kmlObjectList').innerHTML = kmlListHtml;
  el(currentId).checked = true;
  updateKmlListHtml();
}

function createCheckboxWDC(num, kmlObject) {
  var currentId = 'kml' + num;
  var boxHtml = '<form><input type=\"checkbox\" onclick=\"updateVisibility('
  + num + ')\" id=\"' + currentId + '\" />'
  + kmlObject.getName()
  + '</form>';
  kmlListHtmlArray.push(boxHtml);
  kmlListHtml = kmlListHtml + boxHtml;
  el('kmlObjectList').innerHTML = kmlListHtml;
  el(currentId).checked = true;
  updateKmlListHtml();
}


function removeCheckbox(num) {
  if (kmlObjectList[num]) {
    ge.getFeatures().removeChild(kmlObjectList[num]);
    kmlObjectList[num] = null;
    kmlListHtml = '';
    for (var i = 0; i < kmlObjectList.length; i++) {
      if (kmlObjectList[i]) {
        kmlListHtml = kmlListHtml + kmlListHtmlArray[i];
      }
    }
    el('kmlObjectList').innerHTML = kmlListHtml;
    updateKmlListHtml();
  }
}

function updateKmlListHtml() {
  for (var i = 0; i < kmlObjectList.length; i++) {
     if (kmlObjectList[i]) {
       el('kml' + i).checked = kmlObjectList[i].getVisibility();
     }
  }
}

function updateOptVisibility(id) {
  if (id == 'optSun') {
    ge.getSun().setVisibility(el(id).checked);
  }
  else if (id == 'optAtomosphere') {
    ge.getOptions().setAtmosphereVisibility(el(id).checked);
  }
  else if (id == 'optGrid') {
    ge.getOptions().setGridVisibility(el(id).checked);
  }
  else if (id == 'optBorders') {
    layerId = 'LAYER_BORDERS'
    ge.getLayerRoot().enableLayerById(ge[layerId], el(id).checked);

  }
}

function updateOptVisibilityCheckbox() {
  el('optSun').checked = ge.getSun().getVisibility();
  el('optAtomosphere').checked = ge.getOptions().getAtmosphereVisibility();
  el('optGrid').checked = ge.getOptions().getGridVisibility()

  layerId = 'LAYER_BORDERS'
  el('optBorders').checked = ge.getLayerRoot().getLayerById(ge[layerId]).getVisibility();
}


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);

    // for stations
//    createCheckboxWDC(kmlObjectList.length, stations);
//    kmlObjectList.push(stations);
    
    for (var i = 0; i < stations.getFeatures().getChildNodes().getLength(); i++) {
	tmpKmlObject = stations.getFeatures().getChildNodes().item(i);
	createCheckboxWDC(kmlObjectList.length, tmpKmlObject);
	kmlObjectList.push(tmpKmlObject);
    }

    // turn off items
    var off = [1];
    for (var i = 0; i < off.length ; i++) {
	stations.getFeatures().getChildNodes().item(off[i]).setVisibility(false);
    }

    updateKmlListHtml();
}




// ================================================== 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);
}

