/* ----------------------------------------------------------------------------------------
Graceful E-Mail Obfuscation - JavaScript function (decodes e-mail addresses)
Originally written by Roel Van Gils 7/31/07 (http://www.alistapart.com/articles/gracefulemailobfuscation)
Updated to work with BWR publication by Ed Wagner 12/5/07
---------------------------------------------------------------------------------------- */

window.onload = function () {
    geo();
}

function geo() {
    if (!document.getElementsByTagName) // Check for browser support
	return false;
    var map = rot13init(); 
    var tooltip_js_on = "Send e-mail";
    var tooltip_js_off = "To reveal this e-mail address, you will need to answer a simple question";
    var links = document.getElementsByTagName('a'); // Get all anchors
    function geo_decode(anchor) { // function to recompose the orginal address
	var href = anchor.getAttribute('href');
	var address = href.replace(/\/decode\/email\/([a-z0-9._%-]+)\+([a-z0-9._%-]+)\+([a-z.]+)/i, '$1' + '@' + '$2' + '.' + '$3');
	var linktext = anchor.innerHTML; // IE Fix
	if (href != address) {
	    anchor.setAttribute('href','mailto:' + str_rot13(address,map)); // Add mailto link
	    anchor.innerHTML = linktext; // IE Fix
	}
    }
    for (var l = 0 ; l < links.length ; l++) { // Loop through the anchors
	var href = links[l].getAttribute('href');
	if (href && href.indexOf("/decode/email/") == 0) { // Only change links that are encoded email addresses
	    links[l].onclick = function() { // Decode links when clicked
		geo_decode(this);
	    }
	    links[l].onmouseover = function() { // Display tooltip when links are hovered
		if (this.getAttribute('title') == tooltip_js_off) { // Set custom tooltip if specified
		    this.setAttribute('title',tooltip_js_on);
		    geo_decode(this); // Decode links when hovered (so that the address appears correctly in the browser's status bar)
		}
	    }
	}
    }
}

function rot13init() {
    var map = new Array();
    var s = "abcdefghijklmnopqrstuvwxyz";
    for (var i = 0 ; i < s.length ; i++)
	map[s.charAt(i)] = s.charAt((i+13)%26);
    for (var i = 0 ; i < s.length ; i++)
	map[s.charAt(i).toUpperCase()] = s.charAt((i+13)%26).toUpperCase();
    return map;
}

function str_rot13(a,map) {
    var s = "";
    for (var i = 0 ; i < a.length ; i++) {
	var b = a.charAt(i);
	s += (b>='A' && b<='Z' || b>='a' && b<='z' ? map[b] : b);
    }
    return s;
}
