function rebigulate(s) {
	var t = '';
	var p = s.replace(/^.+\//,'').split(' ');
	var r = 36;
	for (var i = 0; i < p.length; i++) {
		var c = parseInt(p[i], r);
		t += String.fromCharCode(c);
		r = (c % 35) + 2;
	}
	return t;
}

function randomIndex(length) {
	return Math.floor(Math.random() * length);
}

function justification(hash) {
	var factor = 137;
	if (hash) {
		var ab = hash.substring(1).split('.');
		return [parseInt(ab[0]) / factor, parseInt(ab[1])];
	} else {
		var a = randomIndex(reasons.length + 3);
		var b;
		switch (a) {
			case 0: b = randomIndex(characters.length);
			case 1: b = randomIndex(pimps.length);
			case 2: b = randomIndex(activities.length);
		}
		if (b) {
			window.location.hash = '#' + (a * factor) + '.' + b;
		} else {
			window.location.hash = '#' + (a * factor);
		}
		return [a,b];
	}
}

function why(a,b) {
	try {
		switch (a) {
			case 0: return ['Character #' + b, "you did not portray " + rebigulate(characters[b]) + " <em>truthfully<\/em>."];
			case 1: return ['Pimp #' + b, "you pimped your scene partner into " + rebigulate(pimps[b])];
			case 2: return ['Activity #' + b, "your " + rebigulate(activities[b]) + " object work was terrible."];
			default: return ['Reason #' + (a - 3), rebigulate(reasons[a - 3])];
		}
	} catch (e) {
		return ['/error/manual/' + window.location.hash.substring(1), "you are directly typing in numbers instead of finding the reasons organically."];
	}
}

function explain(hash) {
	var parts = why.apply(this, justification(hash));
	var path = parts[0];
	var cause = parts[1];
	document.getElementById('cause').innerHTML = cause;
	try {
		pageTracker._trackEvent('Justifications', 'Summon', path);
	} catch (e) {
		if (console) console.log('Trapped: ' + e);
	}
}

function initiate() {
	var c = (characters.length + pimps.length + activities.length + reasons.length);
	document.getElementById('count').innerHTML = c;
	explain(window.location.hash);
}

function heighten() {
	explain(undefined);
	return false;
}

window.onload = initiate;
