Well, first of all, you're going to need some way of indicating which nodes are visible. I've been going through your code and for the life of me I can't figure out where you check for anything like that. It looks to me the only output you have is not conditional at all - it is the first statement of a for loop.
What I think you need:
- A place in each node which indicates if it's visible or not.
- A recursive subroutine that will, given the node and the root, climb up the tree, marking all the parents of the newly visible node as visible.(Called when a child node becomes visible)
- Another rescursive subroutine, called when a node is made invisible, which climbs the tree, and checks which of the parents still has visible children - any parent that doesn't, should be marked not visible. (Called when a child node becomes invisible).
- A way of displaying only visible elements. You can do that either by redrawing the whole page each time (outputing only the visible tree nodes), or through some javascript & div magic. (Setting the visibility of specific divs to off and on).