// change to 'wplf-expanded' if you want directories expanded on page load
var wplfCurrentState = 'wplf-collapsed';
// text for "expand/collapse all" link
var linkText = 'Expand/Collapse All';
// counter
var count = 0;

/**
 * Initialization function
 *
 * @return void
 */
function wplfInit()
{
	// collapse all directories on page load and count them
	wplfToggleAll();

	// only when there's more than one directory
	if(count > 1)
	{
		// and only if there are any lists
		var lists = document.getElementsByTagName('ul');
		if(lists)
		{
			// create "expand/collapse all" links
			var pBefore = document.createElement('p');
			var a = document.createElement('a');
			var text = document.createTextNode(linkText);
			pBefore.className = 'small';
			pBefore.appendChild(a);
			a.href = 'javascript:wplfToggleAll()';
			a.appendChild(text);
			var pAfter = pBefore.cloneNode(true);
			pAfter.style.marginTop = '10px';

			// insert the links before and after the list
			var divs = document.getElementsByTagName('div');
			var dirList;
			for(var i = 0; i < divs.length; i++)
				if(divs[i].className == 'wplf-list-container')
				{
					dirList = divs[i].firstChild;
					divs[i].insertBefore(pBefore, dirList);
					divs[i].appendChild(pAfter);
				}
		}
	}
}

/**
 * Collapses or expands all directories
 *
 * @return void
 */
function wplfToggleAll()
{
	// get all items in the page and set the new state
	var items = document.getElementsByTagName('li');

	// apply the new state to all items with class "dir"
	for(var i = 0; i < items.length; i++)
		if(items[i].className.slice(0, 8) == 'wplf-dir')
		{

			items[i].className = 'wplf-dir ' + wplfCurrentState;
			count++;
		}
	wplfCurrentState = (wplfCurrentState == 'wplf-collapsed') ? 'wplf-expanded' : 'wplf-collapsed';
}

/**
 * Collapses or expands the given directory
 *
 * @param integer id ID of the directory to toggle
 * @return void
 */
function wplfToggleDir(id)
{
	var item = document.getElementById('wplf-item-' + id);

	// if item has class "dir", toggle it
	if(item && item.className.slice(0, 8) == 'wplf-dir')
		item.className = (item.className == 'wplf-dir wplf-expanded') ? 'wplf-dir wplf-collapsed' :
			'wplf-dir wplf-expanded';
}
