
var Tree = Class.create();

Tree.prototype = {

	initialize : function(element) {

		this.element = $(element);
		if(!this.element) return false;
        
		this.anchor = $A($$('.handle'));
		this.anchor.each(this.setup.bind(this));
	},

	setup : function(elm) {

		Event.observe(elm,'click',this.click.bindAsEventListener(this),false);
	},

	toggle :  function(elm) {

        this.close(elm);

		if(elm.next().next().next()) {
			elm.next().next().next().toggle();
			elm.hasClassName('closed') ? elm.toggleClassName('opened') : elm.toggleClassName('closed');
		}
	},

	click :  function(event) {

        var element = Event.element(event);

		if(element)
			this.toggle(element);
	},
    
    close :  function(elm) {
    
        var parent = elm.up();
    
        var siblings = parent.siblings();
        siblings.each(function(item) {

            var childs = item.childElements();
            childs.each(function(child) {
            
                if(child.hasClassName('handle'))
                    child.className = 'handle closed';
            
                if(child.hasClassName('list'))
                    child.hide();
            });
        
        });
    
    }
}

Event.observe(window, 'load', function(){ new Tree('menu'); }, false);
