/*global $ */
/*jslint undef: true, eqeqeq: true, browser: true */
/* Above lines are for JSLint, the JavaScript vefifier.  http://jslint.com/ */

var RFXMailAddressEncoder = {};

/* It's a shame that JavaScript doesn't have a transliterate function. */

RFXMailAddressEncoder.encode = function (s) {
	s = s.replace(/[A-Z]/g, function (c) {
		return String.fromCharCode(
			((c.charCodeAt(0) - 65 /* 'A' */) + 5) % 26 + 65);
	});
	s = s.replace(/[a-z]/g, function (c) {
		return String.fromCharCode(
			((c.charCodeAt(0) - 97 /* 'a' */) + 5) % 26 + 97);
	});
	s = s.replace(/[0-9]/g, function (c) {
		return String.fromCharCode(
			((c.charCodeAt(0) - 48 /* '0' */) + 3) % 10 + 48);
	});
	s = s.replace(/[\@\.]/g, function (c) {
		return (c === "@" ? "." : "@");
	});
	return s;
};

RFXMailAddressEncoder.decode = function (s) {
	s = s.replace(/[A-Z]/g, function (c) {
		return String.fromCharCode(
			((c.charCodeAt(0) - 65 /* 'A' */) + 21) % 26 + 65);
	});
	s = s.replace(/[a-z]/g, function (c) {
		return String.fromCharCode(
			((c.charCodeAt(0) - 97 /* 'a' */) + 21) % 26 + 97);
	});
	s = s.replace(/[0-9]/g, function (c) {
		return String.fromCharCode(
			((c.charCodeAt(0) - 48 /* '0' */) + 7) % 10 + 48);
	});
	s = s.replace(/[\@\.]/g, function (c) {
		return (c === "@" ? "." : "@");
	});
	return s;
};

/* converts /contact.php?to=...&subject=...&cc=...&bcc=...&hash=... back
   to mailto:...?subject=...&cc=...&bcc=... */
RFXMailAddressEncoder.decodeLink = function (u) {
	var pathname, search, pairs, i, pair, name, value;
	var outpairs, email, result, temp;
	if (!/\?/.test(u)) {
		return u;
	}
	pathname = RegExp.leftContext;
	search = RegExp.rightContext;
	if (pathname !== "/shared_lib/email_obfuscator/contact.php") {
		return u;
	}
	pairs = search.split(/\&/);
	outpairs = [];
	for (i = 0; i < pairs.length; i += 1) {
		pair = pairs[i].replace(/\+/g, '%20');
		if (/^hash=/.test(pair)) {
			/* ignore */
		}
		else if (/^(to|cc|bcc)=/.test(pair)) {
			name = RegExp.$1;
			value = decodeURIComponent(RegExp.rightContext);
			value = RFXMailAddressEncoder.decode(value);
			if (name === "to") {
				email = value;
			}
			else {
				outpairs.push(name + "=" +
					      encodeURIComponent(value));
			}
		}
		else {
			outpairs.push(pair);
		}
	}
	if (email === undefined) {
		return u;
	}
	result = "mailto:" + email;
	if (outpairs.length) {
		result += "?" + outpairs.join("&");
	}
	return result;
};

if ("$" in this && 
    !/KEEP_EMAIL_LINKS/.test(document.location.search)) {
	$(document).ready(function () {
		var links = $(document).find("a[href^='/shared_lib/email_obfuscator/contact.php?']");
		links.each(function (i, elt) {
			var href, newhref;
			href = $(elt).attr("href");
			newhref = RFXMailAddressEncoder.decodeLink(href);
			$(elt).attr("href", newhref);
			$(elt).removeAttr("target");
		});
	});
}


