var state=0;
var running=0;
var sound=0;
var parts=new Array;
var word;

parts[1]="head";
parts[2]="torso";
parts[3]="Larm";
parts[4]="Rarm";
parts[5]="Lleg";
parts[6]="Rleg";
parts[7]="dick";

var used=new Array;
var used_index;
var charsleft;
var browser;

// Set up our browser name now
findBrowser();

var wordlist=new Array(
"abrasion","access","accessory","accurately","acknowledgments","adaptable",
"adapted","addiction","adhesive","adjacent","adjustable","adultery",
"advantage","advice","affixed","against","allure","alluring",
"alternative","amused","anchor","animals","ankle","ankles",
"appealing","appearance","applications","apply","arrangement","asylum",
"attaching","attention","attraction","attractive","barrier","bastinado",
"bathroom","bearing","beginners","behind","believe","belts","bewildering",
"beyond","binding","blanket","blindfold","blindfolds","blood",
"bodily","bondage","boots","bottom","bought","branding",
"breathing","buckle","buttocks","buttplug","cages","caress",
"carnality","casual","ceiling","centimetre","chafing","chain",
"chair","chamber","chastity","choke","choose","circulation","circumcise",
"circumstances","classic","climax","clips","clitorilingus","closet",
"cocksucking","collar","compounded","compromise","concise","conditions",
"conjunction","consensual","consequences","consequently","consist",
"contact","contents","continue","convenient","conventional","coprophilia",
"cramp","creation","cuffs","cupboard","cutting","cylindrical","damage",
"dangerous","decent","dehydration","depending","depletion","detail",
"deteriorate","determined","deviants","device","dexterity","diameter",
"difficult","dimensions","disadvantage","disappear","discrete",
"discretion","discussed","disposables","dividing","domestic","dominatrix",
"effective","elaborate","elbow","embarass","emergency","entertainment",
"enthusiasts","entice","equipment","erotic","essential","estimate",
"evoke","examine","excruciation","exercise","exotica","experience",
"expose","exposes","extending","extreme","extremities","failure",
"fainting","fastener","fetish","fisting","fixed","fixtures","flexible",
"flicker","flogger","flogging","fluctuations","fondle","forcing",
"fornication","frisk","fur","genitals","gloves","handcuffs",
"handles","harness","heavenly","heels","helplessly","hobble",
"hoods","humane","humble","illegal","immobility","imprisoned",
"improvise","impurity","indispensable","intense","irons","jerking",
"jockstrap","kinks","kneeling","knife","knots","leather","licentiousness",
"limber","limits","lockable","locks","malacca","manacles","masking",
"massage","master","modifications","money","mummification","neoprene",
"nibble","noose","nylon","obedience","occupy","package","packing",
"padded","padding","paddle","padlocks","painful","panic","parachute",
"partner","pervert","pleasure","plentiful","position","posture",
"powerful","pressure","prevent","punishments","purpose","queening",
"quiver","refrain","resistant","restrain","restraint","restrict",
"rigid","rimjob","rings","risque","ropes","rubber","rugged","screw",
"screwing","security","seductive","sensitive","serve","sever",
"sexuality","shackle","slave","snatch","spaghetti","spanking",
"spasm","stable","sticky","straitjackets","strands","struggle",
"sublimation","submissive","suckle","suffocation","suspension","switch",
"symbol","technique","tempest","temptress","tension","tethering",
"thumb","torture","training","twisted","tying","vanilla","warped",
"whipping","whore","wrapped","wrestle");

function randint(n) {
	return(Math.floor(Math.random() * (n - 0.5)));
}

// play a sound, this might depend no browser some day
function playSound(s) {
	if(sound == 0 || browser == "unknown") {
		return;
	}

	if(browser == "ie") {
		eval("document.all.music.src='" + s + "'");
	} else if(browser == "netscape") {
		window.location = s;
	}
}

function playRandomSound(name, count) {
	var	i;

	i = randint(count) + 1;
	playSound("sounds/" + name + i + ".wav");
}

function findBrowser() {
	if (navigator.userAgent.indexOf("Mozilla/3.0") != -1)
		browser = "netscape";
	else if (navigator.userAgent.indexOf("MSIE") != -1)
		browser = "ie";
	else if (navigator.userAgent.indexOf("Mozilla/2.0") != -1)
		browser = "netscape";
	else if (navigator.userAgent.indexOf("Mozilla") != -1)
		browser = "netscape";
	else
		browser = "unknown";

}

// A couple of functions to manage the display.
function displayNext() {
	state++;
	if(state < 1 || state > 7) {
		alert("Internal error!");
		return;
	}
	eval("window.document.hangman.h"+state+".src='images/"
		+parts[state]+".gif'");

	eval("window.document.hangman.sidebar.src='images/side"+
		state+".gif'");
}

function clearPiece(n) {
	eval("window.document.hangman.h"+n+".src='images/transparent.gif'");
}

// Pick a new word for play

function chooseWord() {
	i = Math.round((Math.random()*10000) % (wordlist.length-0.5));
	word=wordlist[i];

	charsleft=0;

	document.lettergrid.word.value = "";
	for(i = 0; i < word.length; i++) {
		if(word.charAt(i) == " ") {
			document.lettergrid.word.value += "  ";
		} else {
			document.lettergrid.word.value += "_ ";
			charsleft++;
		}
	}
}

function newgame() {
	for(i = 1; i < 8; i++) {
		clearPiece(i);
	}

	eval("window.document.hangman.sidebar.src='images/transparent.gif'");
	document.lettergrid.tried.value = "";
	document.lettergrid.word.value = "";
	// document.lettergrid.test.value = "init";
	used_index=1;
	state=0;
	window.document.hangman.hintbutton.disabled=false;
	window.document.hangman.giveupbutton.disabled=false;
	window.document.hangman.newbutton.disabled=true;
	running=1;

	chooseWord();
}

function hint() {
	if(!running) {
		return;
	}

	// Find a letter in the word that's not in use..
	// Start at a random offset in the word, and wrap.
	pos = Math.round((Math.random()*10000) % (word.length-0.5));
	for(i = 0; i < word.length; i++) {
		if(pos >= word.length) {
			pos=0;
		}
		c = word.charAt(pos);
		if(c == " ") {
			pos++;
			continue;
		}
		hintable=1;
		for(j = 1; j < used_index; j++) {
			if(used[j].toLowerCase() == c.toLowerCase()) {
				hintable=0;
				break;
			}
		}

		if(hintable) {
			seek(c.toUpperCase());
			return;
		}
		pos++;
	}
}

function revealit() {
	if(!running) {
		return;
	}

	document.lettergrid.word.value="";
	tmp="";
	for(i = 0; i < word.length; i++) {
		tmp+=word.charAt(i).toUpperCase()+" ";
	}
	document.lettergrid.word.value=tmp;

	while(state != 7) {
		displayNext();
	}
}

function soundToggle() {
	if(sound) {
		document.hangman.soundButton.value="Sound On";
		sound=0;
	} else {
		document.hangman.soundButton.value="Sound Off";
		sound=1;
	}
}

function giveUp() {
	if(!running) {
		return;
	}

	playRandomSound("giveup", 2);
	revealit();
	window.document.hangman.hintbutton.disabled=true;
	window.document.hangman.giveupbutton.disabled=true;
	window.document.hangman.newbutton.disabled=false;
	running=0;
}

function seek(letter) {

	if(!running) {
		return;
	}

	for(i = 0; i < used_index; i++) {
		if(used[i] == letter.toLowerCase()) {
			alert("Letter "+letter+" is already in use!");
			return;
		}
	}

	used[used_index]=letter.toLowerCase();
	used_index++;

	// Try to find all instances of the letter in the word

	word_idx=0;
	tmpword="";
	currentword=document.lettergrid.word.value;
	ok=0;

	for(i = 0; i < word.length; i++) {
		if(letter.toLowerCase() == word.charAt(i).toLowerCase()) {
			tmpword += letter+" ";
			ok=1;
			charsleft--;
		} else {
			tmpword += currentword.charAt(word_idx);
			tmpword += " ";
		}
		word_idx += 2;
	}
	document.lettergrid.word.value=tmpword;
	document.lettergrid.tried.value += letter;

	if(!ok) {
		displayNext();
	}

	// document.lettergrid.test.value = charsleft+" "+state;
	if(charsleft == 0) {
		win();
		window.document.hangman.hintbutton.disabled=true;
		window.document.hangman.giveupbutton.disabled=true;
		window.document.hangman.newbutton.disabled=false;
		running=0;
	} else if(state == 7) {
		revealit();
		lose();
		window.document.hangman.hintbutton.disabled=true;
		window.document.hangman.giveupbutton.disabled=true;
		window.document.hangman.newbutton.disabled=false;
		running=0;
	}

}

function win() {
	alert("Yay! You won!");
	if(sound) {
		playRandomSound("win", 8);
	}
}

function lose() {
	if(sound) {
		playRandomSound("lose", 5);
	}
}
