
var Menu = function(options) {

	if (!(this._element = options['element'])) return;
	
	this._list = {};
	
	this._selected = null;
	
	this._onToggle = this._toggle.bindAsEventListener(this);
	
	this._preffix = $('layout').className;
	
	if (this._closed = getCookie('fclm_' + this._preffix + '_menu_closed')) {
		
		this._closed = this._closed.split(',');
	
	} else {
	
		this._closed = [];
	
	}
	
	this._node2obj(this._list, this._element);

};

Menu.prototype = {

	_node2obj:	function(sup, node) {
	
		var subtree = node.childElements();
		
		if (subtree.length) {
		
			sup.subtree = [];
			
			subtree.each(function(subnode) {
			
				var obj = {parent: sup, node: subnode};
				
				subnode.obj = obj;
				
				if (this._closed && this._closed.include(subnode.identify())) {
				
					subnode.addClassName('closed');
					
				}
				
				if (subnode.hasClassName('selected')) {
				
					this._selected = obj;
					
					this._invoke(obj,function(obj){
					
						obj.node.removeClassName('closed');
						
						this._closed = this._closed.reject(function(id) {
						
							return obj.node.id == id;
						
						});
					
					},true);
				
				}
				
				sup.subtree.push(obj);
			
				if (subnode.down('ul')) {

					subnode.insert({top: new Element('a',{'class': 'toggeler', 'title': $_LOCALE['title_open_list']}).observe('click',this._onToggle)});
					
					this._node2obj(obj,subnode.down('ul'));
				
				}
			
			},this);
		
		}
	
	},
	
	_invoke:	function(obj,iterator,revers) {
	
		if (typeof revers == 'boolean' && revers) {
		
			if (typeof obj.parent == 'object') {
			
				iterator.call(this,obj);
			
				this._invoke(obj.parent,iterator,revers);
			
			}
		
		} else {
		
			iterator.call(this,obj);
			
			if (typeof obj.subtree == 'object' && obj.subtree.length) {
			
				obj.subtree.each(function(obj) {
				
					this._invoke(obj,iterator);
				
				},this);
			
			}
		
		}
	
	},
	
	_toggle:	function(obj) {
	
		if (typeof obj.node != 'object') {
		
			if (node = obj.findElement('li')) {
			
				obj = node.obj;
			
			}
		
		}
		
		if (obj.node.hasClassName('closed')) {
		
			if (obj.node.down('.toggeler')) {
			
				obj.node.down('.toggeler').title = $_LOCALE['title_close_list'];
			
			}
		
			this._invoke(obj,function(obj){
			
				obj.node.removeClassName('closed');
				
				this._closed = this._closed.reject(function(id) {
				
					return obj.node.id == id;
				
				});
			
			},true);
		
		} else {
		
			if (obj.node.down('.toggeler')) {
			
				obj.node.down('.toggeler').title = $_LOCALE['title_open_list'];
			
			}
		
			obj.node.addClassName('closed');
			
			this._closed.push(obj.node.id);
			
			this._closed = this._closed.uniq();
		
		}
		
		setCookie('fclm_' + this._preffix + '_menu_closed',this._closed);
	
	}

};
