dojo.provide("examples.TutorialGraphListener");

dojo.require("yfiles.client.tiles.HitTest");
dojo.require("yfiles.client.tiles.widget.GraphCanvas");

dojo.declare("examples.TutorialGraphListener", null, {
  _canvas : null,

  constructor : function(/*yfiles.client.tiles.GraphCanvas*/ canvas) {
    this._canvas = canvas;
    this._initializeGraph();
    dojo.connect(this._canvas, 'onClickNodeLabel', this, 'onClickNodeLabel');
  },

  // ------------------------------------------------------------------------------- //
  // graph event handling
  // ------------------------------------------------------------------------------- //
  onClickNodeLabel : function (/*String*/ nodeLabelId) {
    var info = this._canvas.getHitTest().getLabelInfo(nodeLabelId);
    if(info && info.labelIndex == 1) {
      this._toggleNode(info.mainElementId);
    }
  },

  // ------------------------------------------------------------------------------- //
  // internal functions
  // ------------------------------------------------------------------------------- //
  _toggleNode : function (nodeId) {
    var self = this;
    dojo.xhrPost({
      url: this._canvas.baseURL + '/TreeCollapser/toggleNode',
      content : { path : 'CollapsibleTree', id : nodeId, layout : 'tree' },
      load: function(boundsAndShift, ioargs) {
        self._canvas.refresh(boundsAndShift.bounds, boundsAndShift.shift);
      },
      handleAs: 'json'
    });
  },

  _initializeGraph : function () {
    var self = this;
    dojo.xhrPost({
      url : this._canvas.baseURL + '/TreeCollapser/initialize',
      content : { layout : 'tree' },
      load: function(result, ioargs) {
        self._canvas.setPath('CollapsibleTree');
      }
    });
  }
});