 
     found
 
+  removeFromTree: (id) ->
+    removeChild = (id, p) =>
+      [match] = (child for child in p.children() when child.id is id)
+      if match?
+        p.children.remove match
+        match
+      else
+        removed = null
+        for child in p.children()
+          removed = removeChild(id, child)
+          break if removed?
+        removed
+
+    removed = null
+    for o in @objects()
+      removed = removeChild id, o
+      break if removed?
+
+    removed
+
+  insertIntoTree: (obj) ->
+    insertChild = (o, p) =>
+      if p.id == o.parent_id
+        if o instanceof TreeNode
+          p.children.push o
+        else
+          p.children.push new TreeNode o, @, p.level+1
+        p.children.sort (l, r) -> l.id - r.id
+        true
+      else
+        added = false
+        for child in p.children()
+          added = insertChild(o, child)
+          break if added
+        added
+
+    added = false
+    for o in @objects()
+      added = insertChild obj, o
+      break if added
+
+    added
+
   findInTabs: (id) ->
     os = @tabs().map (tab) ->
       switch tab.type


  # triggered by clicking a tab's close button
  closeTab: (tab, event) =>
    remove = (restore = false) =>
      tab.restore() if restore
      tabIndex = @tabs.indexOf(tab)
      selectOther = tab.active()
      @tabs.remove(tab)
      if selectOther
        otherTab = @tabs()[tabIndex]
        if not otherTab? and tabIndex > 0
          otherTab = @tabs()[tabIndex-1]
        @selectTab(otherTab) if otherTab?

      if @tabs().length == 0
        @selectedTab null

    if tab.dirty()
      bootbox.confirm "Are you sure you want to close this #{tab.type}?  Your unsaved changes will be lost.", (close) =>
        remove(true) if close
    else
      remove()

    event.stopPropagation()


    @socket.emit 'get_tree', null, (tree) =>
      @objects tree.map (o) => new TreeNode o, @

  clearEditor: ->
    @objects []
    @tabs []
    @selectedObject null
    @selectedTab null

  findInTree: (id) ->
    find = (id, o) ->
      if o.id == id
