// JavaScript for lists

/*
	LISTS
	
	Functions to deal with lists.
*/

function setupLists() {
	// Run various initialization functions.
	setupColumns();
	continueLists();
}

function continueLists() {
	/*
		Runs onload. 
		Looks for ordered lists with a "continue" attribute. 
		If this attribute is the ID of another (presumed prior) list in the page, 
		the numbering is continued from the end of the referenced list.
		Multiple continued lists may be strung together.
	*/
	
	var ols = document.getElementsByTagName('OL');
	for( i=0; i<ols.length; i++ ) {
		var nItems = 0;
		var newList = ols[i];
		while( prevListId = newList.getAttribute('continue') ) {
			if( prevList = document.getElementById(prevListId) ) {
				var lis = prevList.getElementsByTagName('LI');
				nItems += lis.length;
				newList = prevList;
			}
			else break;
		}
		ols[i].setAttribute('start',nItems + 1);
	}
}

function setupColumns() {
	/*
		Runs onload.
		Looks for lists (ordered or unordered) with class="columns"
		and a second optional numeric class specifying number of columns (the default is 2) 
		then divides the lists into separate lists, wrapped in divs for styling.
		If an ordered lists, connects them with "continue" attributes (see above).
	*/
	
	var uls = document.getElementsByTagName('UL');
	for( i=0; i<uls.length; i++ ) {
		if( elementHasClassName(uls[i],'columns') ) {
			buildColumns(uls[i],false);
		}
	}
	
	var ols = document.getElementsByTagName('OL');
	for( i=0; i<ols.length; i++ ) {
		if( elementHasClassName(ols[i],'columns') ) {
			buildColumns(ols[i],true);
		}
	}
	
	
}

function buildColumns(list,isOrdered) {
	var nCols = findNumericClassName(list);
	if( nCols === null ) nCols = 2;
			
	var items = list.getElementsByTagName('LI');
	var colLength = Math.ceil(items.length/nCols);
	
	var listId = (list.id == '') ? ('columnList' + '-' + i) : list.id;
	
	var newLists = Array();
	for( j=0; j<nCols; j++ ) {
		newLists[j] = (isOrdered) ? document.createElement('OL') : document.createElement('UL');
		newLists[j].id = listId + '-' + (j+1);
		if( isOrdered && j>0 ) newLists[j].setAttribute('continue',listId + '-' + j);
		newLists[j].style.width = (Math.floor(100/nCols) - 8) + '%';
		
		k=0;
		while( k<colLength && items.length>0 ) {
			var moveItem = items[0];
			list.removeChild(moveItem);
			newLists[j].appendChild(moveItem);
			k++;
		}
	}
	for( j=0; j<nCols; j++ ) {
		// Do this after we've stripped all the LIs so that the count doesn't get screwed up
		list.appendChild(newLists[j]);
	}
}


