/*
 * Menu expander
 * Version 0.1
 * Last revision: 22.04.2010
 * chvatal@ccss.cz
 */

/*
 * Required steps:
 * 1) identify and collapse all menus
 * 2) add image to positions where the expand is possible
 * 3) switch between expand/collapse image based on submenu state
 * 4) expand the menu itself
 */

window.addEventListener ? window.addEventListener('load', menuCollapse, false) : window.attachEvent('onload', menuCollapse);

/**
 * Hide all elements with specified ids
 * @return void
 */
function menuCollapse() {
	$('a.aexpand').click(function(){
		switchItem(this.id.substring(7));
	})
	// this is some li element
	var el = $('div.active');
	var li_el = el.parent();
	// expand back the active menu
	if (li_el.length>0 && li_el.attr('class') != 'topli')
		expandActive(li_el);
	if (el.children('div.expand').length>0){
		ul_el = li_el.children('ul')
		ul_el.show(function(){
			menuItemSetHeight(ul_el);
		});
		ctrl_el = ($('#'+ul_el.attr('id').replace('fold','expand')));
		ctrl_el.removeClass().addClass('afold');
	}
}

/**
 * Hide or display element
 * @param string datastore path
 * @param int section
 * @return void
 */
function switchItem(section) {
	el = $('#fold_'+section);
	ctrl_el = $('#expand_'+section);
	if (el.is(':hidden')) {
		// display submenu
		el.show(function(){
			menuItemSetHeight(el);
		});
		// change icon for expand/collapse
		ctrl_el.removeClass().addClass('afold');

	} else {
		// hide submenu
		el.hide();
		// change icon for expand/collapse
		ctrl_el.removeClass().addClass('aexpand');
	}

}

/**
 * Expand to currently active menu
 * @param object object whos parent we expand from
 * @return void
 */
function expandActive(el) {
	// set display
	ul_el = el.closest('ul');
	li_el = ul_el.closest('li');
	ul_el.show(function(){
		menuItemSetHeight(ul_el);
	});
	// switch css style for expand/collapse icon
	ctrl_el = ($('#'+ul_el.attr('id').replace('fold','expand')));
	ctrl_el.removeClass().addClass('afold');
	// run the recursion back to the top menu block
	if (li_el.attr('class') != 'topli')
		expandActive(li_el);
}

