/* ECサイトの商品カテゴリコンテナで使用
 * 3階層までしか考慮していない。
*/
var TreeMenu = Class.create();

TreeMenu.prototype = {
    initialize: function() {
		/* メニューの親子関係を保存
		 * menu[parent_id] = [element_id1, element_id2, ..]
		 */
		this.menu = {};

		/* 現在のメニューの状態を保存
		 * true: Open, false: Close
		 * show_flgs = {element_id1 => true, element_id2 => false, ..}
		 */
		this.show_flgs = {};

		/*
		 * 始めに開いておくメニューを設定する
		 */
		this.opened_ids = {};
    },

	
	setOpenId: function(ids) {
		var opened_ids = {}
		ids.each( function(opened_id) {
			opened_ids[opened_id] = true;
		});
		this.opened_ids = opened_ids;
	},

    add: function(element, parent_element) {
		if (typeof parent_element == 'undefined') {
			this.menu[element.id] = new Array();
		} else {
			if (typeof this.menu[parent_element.id] == 'undefined') {
				this.menu[parent_element.id] = [element];
			} else {
				this.menu[parent_element.id].push(element);
			}
		}

		if (typeof this.opened_ids[parent_element.id] !=  'undefined') {
			this.show_flgs[element.id] = false;
			this.openWithChildren(parent_element, this.menu[parent_element.id]);
		} else {
			this.show_flgs[element.id] = false;
		}

		Event.observe(element, 'click', (function() {
			this.toggleChildren(element)}).bindAsEventListener(this));
    },

	toggleChildren: function(element) {
		var menu = this.menu
		var show_flgs = this.show_flgs

		var children_elements = menu[element.id];
		if (children_elements) {
			//メニューが開いていたら
			if (show_flgs[element.id]) {
				this.closeWithChildren(element, children_elements);
			} else {
				this.openWithChildren(element, children_elements);
			}
		}
	},

	closeWithChildren: function(element, children_elements) {
		var menu = this.menu
		var show_flgs = this.show_flgs

		children_elements.each( function(children_element) {
			var s_children_elements = menu[children_element.id];
			if (s_children_elements) {
				s_children_elements.each( function(s_children_element) {
					s_children_element.hide();
				});
			}

			children_element.hide();

			if (children_element.style.backgroundImage) {
				children_element.style.backgroundImage = 'url(/static/images/shop/tree_menu_open.gif)';
				children_element.style.backgroundRepeat = 'no-repeat';
				children_element.style.backgroundPosition = '10px 0';
			}

			show_flgs[children_element.id] = false;
		});

		show_flgs[element.id] = false;

		if (element.style.backgroundImage) {
			element.style.backgroundImage = 'url(/static/images/shop/tree_menu_open.gif)';
			element.style.backgroundRepeat = 'no-repeat';
		}
	},

	openWithChildren: function(element, children_elements) {
		var menu = this.menu;
		var show_flgs = this.show_flgs;

		children_elements.invoke('show');
		element.style.backgroundImage = 'url(/static/images/shop/tree_menu_close.gif)';
		element.style.backgroundRepeat = 'no-repeat';

		show_flgs[element.id] = true;
	}
}
