/* Show results using Google Earth API
 *
 * Tree widget using the Dojo framework is based on demo "KML DOM Tree", 
 * R. Nurik (Google), http://code.google.com/apis/earth/documentation/demogallery.html
 *
*/

djConfig = { parseOnLoad: true };
google.load('dojo', '1.2.3');

google.load('maps', '2');
google.load("earth", "1");
google.load("prototype", "1.6.0.3");

var g_ge, g_kmlObject, g_treeIdObjectMap, g_retry_cnt = 0;

google.setOnLoadCallback(function() {
    dojo.require('dijit.layout.BorderContainer');
    dojo.require('dijit.layout.SplitContainer');
    dojo.require('dijit.layout.ContentPane');
    dojo.require("dijit.layout.TabContainer");
    dojo.require('dijit.Tree');
    dojo.require("dijit.form.CheckBox");
    dojo.require('dijit.form.Button');
    dojo.require('dijit.form.TextBox');
    
    dojo.require('dojo.data.ItemFileWriteStore');
    
    dojo.require('dojo.parser');
    dojo.require('dojo.cookie');
    dojo.require('dojo.fx');
    
    dojo.addOnLoad(function() { 
	var scpt = document.createElement('script');
	scpt.src = '/amisG/lib/external/google/dijit.CheckboxTree.js';
	h = document.getElementsByTagName("head").length ? 
	    document.getElementsByTagName("head")[0] : 
	   document.body;
	h.appendChild(scpt);
	google.earth.createInstance(
	    'map',
	    function(ge) {
		g_ge = ge;
		g_ge.getWindow().setVisibility(true);
		g_ge.getNavigationControl().setVisibility(g_ge.VISIBILITY_AUTO);
		g_ge.getLayerRoot().enableLayerById(g_ge.LAYER_BORDERS, true);
		g_ge.getLayerRoot().enableLayerById(g_ge.LAYER_BUILDINGS, true);
		
		// Alaska
		var la = g_ge.createLookAt('');
		la.set(59.5,-152, 400000, g_ge.ALTITUDE_RELATIVE_TO_GROUND, 0, 5, 99.99);
		g_ge.getView().setAbstractView(la);
		loadKml();
	    },
	    function(object) {
		//alert('create fail'); //console.log('Failed to create Google Earth instance');
	    }
	);
    });
});

function buildTreeUI(kmlObject) {
  delete g_treeIdObjectMap;
  g_treeIdObjectMap = {};
  
  var treeData = {
    identifier: 'id',
    label: 'name',
    items: []
  };
  
  // walk the loaded KML object DOM
  walkKmlDom(kmlObject, function(context) {
    // generate a random, unique ID for this node (Dojo requires a unique ID
    // per each node)
    var nodeId = Number(new Date()).toString() + Math.round(Math.random() * 99999).toString();
    g_treeIdObjectMap[nodeId] = this;
    
    // create the tree node for this item
    var treeNodeData = {
      id: nodeId,
      name: (this.getName() ? this.getName() : '<' + this.getType() + '>'),
      type: this.getType(),
      checked: this.getVisibility(),
      children: []
    };
    if (treeNodeData.name != 'tile' && treeNodeData.name != 'overlay' && treeNodeData.name != 'layer' && treeNodeData.name != 'logo') {
	// add the tree node to the tree data hierarchy 
	context.current.push(treeNodeData);
	
	// all actual KML child nodes will be added to this tree node's
	// children list
	context.child = treeNodeData.children;
    }
  }, { rootContext: treeData.items });

  if (dijit.byId('tree'))
    dijit.byId('tree').destroy();
  
  // create the Dojo tree widget
  // and set its data to the hierarchy we just
  // built using walkKmlDom
  var treeDiv = document.createElement('div');
  treeDiv.style.height = '100%';
  $('mapMenu').innerHTML = '';
  dojo.byId('mapMenu').appendChild(treeDiv);
  var store = new dojo.data.ItemFileWriteStore({ data: treeData });
  var model = new dijit.tree.CheckboxForestStoreModel({
    store: store,
    labelAttr: 'name',
    typeAttr: 'type'
  });
  
  var tree = new dijit.CheckboxTree({
    id: 'tree',
    model: model
  }, treeDiv);
  if ($('mapMenu').down('div',1) == null) {
      $('mapMenu').addClassName('errorMsg').innerHTML = 'Error loading layers<br/>Try reopening this page in a new window (Ctrl+N)';
  }

  // watch for changes in the 'checked' attribute and update feature visibility
  // accordingly
  dojo.connect(store, 'onSet', function(item, attribute, oldValue, newValue) {
    if (oldValue != newValue &&
        attribute == 'checked') {
      var kmlObject = g_treeIdObjectMap[store.getValue(item, 'id')];
      if (!kmlObject)
        return;
      
      kmlObject.setVisibility(newValue);
      
      if (newValue == true) {
        var c = kmlObject;
        while (c && 'setVisibility' in c) {
          c.setVisibility(newValue);
          c = c.getParentNode();
          //store.setValue(item, 'checked' 
        }
      }
    }
  });
  
  // when clicking a tree item, fly to it
  dojo.connect(tree, 'onClick', function(item) {
    if (item) {
      var kmlObject = g_treeIdObjectMap[store.getValue(item, 'id')];
      if (!kmlObject)
        return;
      
      flyToFeature(kmlObject);
    }
  });
  
  var oldGetIconClass = tree.getIconClass;
  tree.getIconClass = function(item, opened) {
    var cls = '';
    if (item) {
      var kmlObject = g_treeIdObjectMap[store.getValue(item, 'id')];
      if (kmlObject) {
        if ('getGeometry' in kmlObject && kmlObject.getGeometry()) {
          cls = kmlObject.getGeometry().getType();
        } else {
          cls = kmlObject.getType();
        }
      }
    }
    
    return cls + ' ' + oldGetIconClass.apply(tree, [item, opened]);
  };
  
  tree.getLabelClass = function(item, opened) {
    if (item && tree.model.mayHaveChildren(item)) {
      return 'folder';
    }
    
    return '';
  };
  
  //expandTree();
}


function expandTree() {
  var tree = dijit.byId('tree');
  
  function expandChildNode(node) {
    dojo.forEach(node.getChildren(), function(c) { 
      tree._expandNode(c);
      expandChildNode(c);
    }, this);
  }
  
  expandChildNode(tree.rootNode);
}

function loadKml() {
    var now = new Date();
    var url = 'http://ak.aoos.org/cgi-bin/cookG_ws.py?time='+now.getTime();
    google.earth.fetchKml(g_ge, url, function(kmlObject) {
	if (!kmlObject) {
	    // show error
	    setTimeout(function() {
		alert('Error loading KML.');
	    }, 0);
	    return;
	}
	if (g_kmlObject)
	    g_ge.getFeatures().removeChild(g_kmlObject);
	
	g_kmlObject = kmlObject;
	g_ge.getFeatures().appendChild(g_kmlObject);
	//flyToFeature(g_kmlObject);
	buildTreeUI(g_kmlObject);
    });
}

function flyToFeature(kmlFeature) {
    var aspectRatio, lookAt, tilt;
    
    aspectRatio = dojo.coords('mapContainer').w * 1.0 / dojo.coords('mapContainer').h;
    tilt = 30;
    lookAt = computeFitLookAt(g_ge, kmlFeature, aspectRatio, tilt);
    if (lookAt) {
	g_ge.getView().setAbstractView(lookAt);
    }
}
