/* the scrambler! by Chip Black
 * makes your webpage unintelligible
 *
 * the scrambler! is public domain.
 * Use. Modify. Destroy.
 */

/* permute(str)
 * 
 * Randomly swaps adjacent pairs of characters in a string.
 * Returns the modified string.
 */
function permute(str) {
	var rstr = '';

	if (str.length == 0)
		return str;

	for (var i=0; i < str.length; i++) {
		if (Math.random() > 0.6 && i < str.length - 1) {
			rstr += str[i+1] + str[i];
			i++;
		} else {
			rstr += str[i];
		}
	}
	return rstr;
}

/* scramble(node)
 *
 * recursively scan a Element tree rooted at node, running permute on
 * found text nodes
 * Returns nothing.
 */
function scramble(node) {
	var n = node.childNodes.length;
	for (var i=0; i < n; i++) {
		if (node.childNodes[i].nodeType == Node.TEXT_NODE &&
		    node.childNodes[i].nodeValue != '') {
			newnode = document.createTextNode(permute(node.childNodes[i].nodeValue));
			try {
				node.replaceChild(newnode,node.childNodes[i]);
			} catch (e) {
			}
		} else if (node.childNodes[i].nodeType == Node.ELEMENT_NODE) {
			scramble(node.childNodes[i]);
		}
	}
}

var tsn = null;

/* start_scramble(node)
 *
 * Start the auto-scrambling timer, scrambling the Element tree rooted at node.
 * Returns nothing.
 */
function start_scramble(node) {
	tsn = node;
	tscrambler();
}

/* stop_scramble()
 *
 * Stop the scrambler.
 * Returns nothing. (OF COURSE IT RETURNS NOTHING. LOOK AT IT! IT /IS/ NOTHING!)
 */
function stop_scramble() {
	tsn = null;
}

/* toggle_scramble()
 *
 * Single function entry point to start/stop scrambling (useful for links)
 */
function toggle_scramble() {
	if (tsn)
		stop_scramble();
	else
		start_scramble(document.body);
}

/* print_scramblethingy()
 *
 * Print out a checkbox with a funny quip. When the checkbox is checked,
 * The auto-scrambling code is activated. When it is unchecked, the
 * auto-scrambling ceases. This is meant to be inserted in a webpage.
 */
function print_scramblethingy() {
	var tagline = '';
	var n = Math.floor(Math.random()*8);
	switch (n) {
	case 0:
		tagline = "shake it up";
		break;
	case 1:
		tagline = "EARTHQUAKE!";
		break;
	case 2:
		tagline = "shaken, not stirred";
		break;
	case 3:
		tagline = "UNDER NO CIRCUMSTANCES ENABLE THIS CHECKBOX!";
		break;
	case 4:
		tagline = "scrambled";
		break;
	case 5:
		tagline = "Instant Cthulu";
		break;
	case 6:
		tagline = "There is a very small but non-zero probability that checking this will make this blog <i>worse</i>";
		break;
	case 7:
		tagline = "DOUSSELBARF!";
	}
	document.write('<form><input type="checkbox" onClick="if (this.checked) start_scramble(document.body); else stop_scramble();">' + tagline + '</form>');
}

/* tscrambler()
 *
 * Scrambling thread. Don't call this directly.
 */
function tscrambler() {
	if (tsn == null)
		return;
	scramble(tsn);
	setTimeout('tscrambler()',500);
}

