var word;
var answer;
var play;

function reset_game(){ $.get("wordlist.txt", setup_game); }
function setup_game(wordlist){
answer = "";
play = 0;
word = wordlist.split(/\n/)[Math.floor(Math.random() * 100001) % 1175];
$('#hangman img').attr("src", "img/0.gif");
$("#answer").html(word.replace(/./g, "_ "));
$("#character_list").html("");
for(i = 97; i <= 122; i++) {
s = String.fromCharCode(i);
$("#character_list").append("<a href=\""+s+"\" onclick=\"guess('"+s+"');return false;\">"+s+"</a> ");
}
}
function refresh_answer_list(){
answer_list = "";
for(i = 0; i < word.length; i++) {
if(answer.match(word.charAt(i))) {
answer_list += word.charAt(i) + " ";
} else {
answer_list += "_ ";
}
}
$("#answer").html(answer_list);
}
function increment_hang_man(){
$('#hangman img').attr("src", "img/"+play+".gif");
}
function check_winning() {
if($("#answer").html().match(/_/) == null){
alert("You win!");
$("#character_list a").removeAttr("href").removeAttr('onclick');
} else if(play >= 8) {
alert("Game over!");
$("#answer").html(word.replace(/(.)/g, "$1 "));
$("#character_list a").removeAttr("href").removeAttr('onclick');
}
}
function guess(chr){
if(word.match(chr) != null){
answer += chr;
refresh_answer_list();
} else {
play++;
increment_hang_man();
}
$("#character_list a[href$='"+chr+"']").removeAttr('onclick').removeAttr("href");
check_winning();
}

$(document).ready(reset_game);