/*
Context-links.js

Tim Stackhouse

Pulls all links from the context of a page into a ul for use in a sidebar

source can be any element
target must be a UL

*/

function pullLinks(source_id, target_id) {
	//get the DOM elements of the source and target for our links
	var elem = document.getElementById(source_id);
	var target = document.getElementById(target_id);
	//getElementsByTagName returns an HTML collection
	//make it an array so we can do more with it
	var links = collectionToArray(elem.getElementsByTagName("a"));
	//preserve any elements in the list already
	var linkList = target.innerHTML;
	//tally any links we're putting in
	var linkCount = 0;
	for (var i = 0; i < links.length; i++) {
		//Make all links in the body have a class the same as the value of their rel
		links[i].className = links[i].rel;
	}
	//put external links at the bottom of the list
	//links.sort(sortExternal);
	for (var i = 0; i < links.length; i++) {
		//if it's marked as important, process it
		if(links[i].rel.match("important")) {
			//the actual text of the link
			var text = "";
			if(links[i].title != "") {
				text = links[i].title;
			}
			else{
				text = links[i].innerHTML;
			}
			//make the first letter uppercase (just to make it look better)
			//make sure it's not a www link
			if(text.indexOf("www") != 0) {
				text = text.charAt(0).toUpperCase() + text.substring(1,text.length);
			}
			//append this link to the string of list elements
			linkList = linkList + "<li class=\"" + links[i].rel + "\"><a href='" + links[i] + "'>" + text + "</a></li>";
			//tally this link
			linkCount++;
		}
	}
	//if we don't have any links, blow away what's there
	// otherwise put the links where they belong
	if (linkCount == 0){
		target.innerHTML = "";
	}
	else {
		target.innerHTML = linkList;
	}
}

//simple sorting to put externals to the bottom
function sortExternal(a, b) {
	if(a.rel.match("external")) {
		return 1;
	}
	else if(b.rel.match("external")) {
		return -1;
	}
	else {
		return 0;
	}
}

//convert an HTMLCollection to a JavaScript array
function collectionToArray(col) {
	a = new Array();
	for (i = 0; i < col.length; i++)
		a[a.length] = col[i];
	return a;
}