var keys_pressed = new Array();
var kcode = new Array(38,38,40,40,37,39,37,39,66,65);
// random store
var char_list = new Array();
// hide all divs
$(document).ready(function(){
	mindfuck("#header");
	// listen for konami code
	$(document).keydown(function(e){
		switch(e.keyCode){
			case 38: // up
			case 40: // down
			case 37: // left
			case 39: // right
			case 66: // b
			case 65: // a
				keys_pressed.push(e.keyCode);
				if(keys_pressed.length > 10) keys_pressed.shift();
				break;
			default:
				keys_pressed = new Array();
		}
		if(keys_pressed.length == 10){
			for(var i = 0; i < kcode.length; i++){
				if(kcode[i] != keys_pressed[i]) return;
				jam();
			}
		}
	});
});
// Scramble random letters, then call unfuck to slowly change them back
function mindfuck(id) {
	var list = new Array();
	var jid = $(id);
	var html = jid.html();
	var editable = true;
	for(var i = 0; i < html.length; i++){
		if(html.charAt(i) == ">") editable = true;
		if(html.charAt(i) == "<") editable = false;
		if(Math.random() > 0.3){
			if(editable && html.charAt(i).search(/[A-Za-z]/) > -1){
				var old = new Object();
				old.index = i;
				old.char = html.charAt(i);
				list.push(old);
				html = setCharAt(html, i, createRandomLowerCaseLetter());
			}
		}
	}
	list = shuffle(list);
	jid.html(html);
	setTimeout(function() {unfuck(jid, html, list)}, 1500);
}
// Incremental recursive fixing of the mindfuck function
function unfuck(jid, html, list){
	if(list.length > 0){
		html = setCharAt(html, list[list.length-1].index, list[list.length-1].char);
		list.pop();
		jid.html(html);
	}
	if(list.length > 0){
		setTimeout(function() {unfuck(jid, html, list)}, 20 + Math.random() * 20);
	}
}
// curiously missing from javascript
function setCharAt(str,index,chr) {
	if(index > str.length-1) return str;
	return str.substr(0,index) + chr + str.substr(index+1);
}
function createRandomLowerCaseLetter(){
	return String.fromCharCode(97 + Math.round(Math.random() * 25));
}
// Replaces all words (non html) with the word jam in both frames
// called via konami code.
// I'm hopeful this frivolous session of dicking around will come in useful in future
// probably not though.
function jam(){
	var jbody = $("body");
	var html = jbody.html();
	html = html.replace(/\b\w+\b(?![^<>]*>)(?!;)/g, "jam");
	jbody.html(html);
}
//+ Jonas Raoni Soares Silva
//@ http://jsfromhell.com/array/shuffle [rev. #1]
function shuffle(v){
	for(var j, x, i = v.length; i; j = parseInt(Math.random() * i), x = v[--i], v[i] = v[j], v[j] = x);
	return v;
};