RELIGIONIZER = {

	religions: [],

	done: false,

	current_religion: null,

	weighted_religions: [],
		
	init: function(){
		new Ajax.Request(script_url, {
			method: 'POST',
			parameters: 'init=true',
			onSuccess: function(response) {
				var r = eval(response.responseText);
				RELIGIONIZER.religions = r;

				for (var i=0; i<RELIGIONIZER.religions.length; i++) {
					var preload = new Image();
					preload.src = RELIGIONIZER.religions[i].image;

					for (var j=0; j<RELIGIONIZER.religions[i].weight; j++)
						RELIGIONIZER.weighted_religions.push(i);

					for (j=0; j<RELIGIONIZER.religions[i].jokes.length; j++) {			
						for (var k=0; k<RELIGIONIZER.religions[i].jokes[j].weight; k++) {
							RELIGIONIZER.religions[i].weighted_jokes.push(j);
						}
					}
				}
			}
		});
	},

	swap: function(idx) {
		var religion = this.religions[idx]
		this.current_religion = religion;
		$('imgMain').src = religion.image;
		$("txtMain").innerHTML = religion.name;
		$("txtChooseMsg").innerHTML = "Choose "+religion.name;
		$("txtMsg").innerHTML = "Convert Again";
	},

	getjoke: function(religion) {
		var random_number = Math.floor(Math.random()*religion.weighted_jokes.length);
		var chosen_joke = religion.weighted_jokes[random_number];
		return religion.jokes[chosen_joke].text;
	},

	getreligion: function() {
		var random_number = Math.floor(Math.random()*this.weighted_religions.length);
		var chosen_religion = this.weighted_religions[random_number];
		this.swap(chosen_religion);
	},
	
	save: function() {
		new Ajax.Request(script_url, {
			method: 'POST',
			parameters: 'save=true&img='+encodeURIComponent(RELIGIONIZER.current_religion.image)+'&name='+encodeURIComponent(RELIGIONIZER.current_religion.name),
			onSuccess: function(response) {
				RELIGIONIZER.done = true;
				$("txtMsg").innerHTML = 'Congratulations!';
				window.setTimeout(function(){
					var profileurl;
					if (loggedin) profileurl = '/heroes/'+username;
					else profileurl = '/heroes/login/';
					window.location.href=profileurl;
				}, 2000);
			}
		});
	}
	
}
RELIGIONIZER.init();

function shuffler() {
	if (!RELIGIONIZER.done) {
		$('choose_button').style.display='none';
		$('txtJoke').innerHTML = '';
		var myInterval = window.setInterval(function(){RELIGIONIZER.getreligion();},100);
		window.setTimeout(function(){
			clearInterval(myInterval);
			$("txtJoke").innerHTML = RELIGIONIZER.getjoke(RELIGIONIZER.current_religion);
			if (RELIGIONIZER.current_religion.isfinal)
				RELIGIONIZER.save();
			else
				$('choose_button').style.display='block';
		},2000*Math.random()+1000);
	}
}
