// Trim any sequence of one or more spaces at the beginning or end of the string:
function trim(string) {
	return string.replace(/^\s+|\s+$/g,"");
}

// Trim any sequence of one or more spaces from the beginning of the string:
function ltrim(string) {
	return string.replace(/^\s+/,"");
}

// Trim any sequence of one or more spaces from the end of the string:
function rtrim(string) {
	return string.replace(/\s+$/,"");
}

/*
	Replaces e.g.:
	
		<span class="contact">foo [at] bar.com</span>
		
	...with:
	
		<a href="mailto:foo@bar.com">foo [at] bar.com</a>
*/
function buildMailtoLinks() {
	// Initialize vars:
	var spanCollection;
	var emailSpanText;
	var emailParts;
	var mailtoLinkText;
	var mailtoHrefValue;
	var parentContainer;
	var mailtoLink;
	var contactSpanCollection = new Array;
	
	// First round up all the likely suspects:
	spanCollection = document.getElementsByTagName('span');

	// Then, lets reduce our list to the items we actually need:
	// Start by initializing a var we'll need:
	var y=0;
	// Then loop through ALL the spans:
	for (var x=0; x<spanCollection.length; x++) {
		// If we find one with the right className:		
		if (spanCollection[x].className == 'contact') {
			// Add it to our collection:
			contactSpanCollection[y] = spanCollection[x];
			// Increment the counter (must be done here):
			y++;
		}
	}
	
	/*
		Note:
		
		It would be a bit more efficient to simply loop through the original collection of spans
		ONCE, but this method is a little more explicit. Maybe we'll lean it up later.
	*/
	
	// Then loop through the smaller collection:
	for (var i=0; i<contactSpanCollection.length; i++) {
		// Get the trimmed 'email address':
		emailSpanText = trim(contactSpanCollection[i].childNodes[0].nodeValue);
		
		// Split it into three parts by spaces:
		emailParts = emailSpanText.split(' ');
		
		// Create--actually, just copy--the link text:
		mailtoLinkText = document.createTextNode(emailSpanText);
		
		// Assemble the value of the href attribute:
		mailtoHrefValue = 'mailto:' + emailParts[0] + '@' + emailParts[2]; 
					
		// Find out what the parent element is:
		parentContainer = contactSpanCollection[i].parentNode;
		
		// Create a brand new a element:
		mailtoLink = document.createElement('a');
		
		// Set the link text of the new a:
		mailtoLink.appendChild(mailtoLinkText);
		
		// Set the value of its href attribute:
		mailtoLink.href = mailtoHrefValue; 
		
		// Swap the new link for the old span:	
		parentContainer.replaceChild(mailtoLink,contactSpanCollection[i]);
	}
}