// Make the selected word global
var secretWord = hangmanWords();

// c variable keeps a tally on how many letters have been revealed and triggers win if all are revealed
var c = 0;

// Randomly choose a word from the array
function hangmanWords() {
	var hWords = new Array ("ACCLAIM", "AGILE", "ALIAS", "CURT", "DISDAIN", "FABRICATE", "GOAD", "INNATE");
	
	// Randomly pick one of the words from the hWords array
	var ranNum = Math.ceil(-1 + hWords.length*Math.random());
	var myWord = hWords[ranNum];
	
	// Create array of word letters
	var myWordArray = myWord.split("");
	return myWordArray;	
}

function myDate() {
	var today = new Date();
	var hour = today.getHours();
	var minute = today.getMinutes();
	var ampm = (hour < 12) ? " am" : " pm";
	hour = (hour > 12) ? hour - 12 : hour;
	hour = (hour == 0) ? 12 : hour;
	minute = (minute < 10) ? "0"+minute : minute;
	document.write(hour+":"+minute+ampm);
}

function myInputs() {
	//var myWordArray = hangmanWords();
	var wordLength = secretWord.length;
	
	// while loop to create underscore
	document.write('<div id="dash">');
	var l = 0;
	while (l < wordLength) {
		document.write('<span id="under'+l+'" >' + '<img src="images/underScore.jpg" alt"underscore" />' + '</span>');
		l++;
	}
	document.write('</div>');
	
	// Create a single letter input field for each letter in the word
	document.write('<div id="word">');
	for (var i=0; i < wordLength; i++) {
		document.write('<span id="letter'+i+'">'+ secretWord[i] + '</span>');
	}
	document.write('</div>');
}

// Find cookie function
function findCookie(cookieName) {
    var value = null;
    var findVal = cookieName + "=";
    var dc = document.cookie;
    if (dc.length > 0) {
        var start = dc.indexOf(findVal);
        if (start >= 0) {
            start += findVal.length;
            lastVal = dc.indexOf(";", start);
            if (lastVal == -1) {
                lastVal = dc.length;
            }
            value = dc.substring(start, lastVal);
        }
    }
    return value;
}

function removeCookie() {
	// Remove cookie
	document.cookie = "wrongLetters= ;expires=Saturday, 05-Dec-09 00:00:01 GMT;";
}

// Display win or lose div
function myResult(id) {
	var display = document.getElementById(id);
	display.style.visibility = "visible";
}

// Cookie to keep a tally of wins and loses
function score(win) {
	var cScore = findCookie("score");
	
	// Write cookie after first round
	if (cScore == null) {
		if (win == 1) {
			document.cookie = "score=1-0";
		} else {
			document.cookie = "score=0-1";
		}
	} else {
		if (win == 1) {
			if (cScore[2] == "-") {		
				var nWin = parseInt(cScore[0]+cScore[1]) + 1;
				var nLose = cScore[3];
				if (cScore[4] == true) {
					var nWin = parseInt(cScore[0]+cScore[1]) + 1;
					var nLose = cScore[3] + cScore[4]
				}
			} else if ((cScore[1] == "-") && (cScore[3] == true)) {
				var nWin = parseInt(cScore[0]) + 1;
				var nLose = cScore[2] + cScore[3];
			} else {
				var nWin = parseInt(cScore[0]) + 1;
				var nLose = cScore[2];
			}
		} else {
			if (cScore[2] == "-") {
				var nWin = cScore[0] + cScore[1];
				var nLose = parseInt(cScore[3]) + 1;
				if (cScore[4] == true) {
					var nWin = cScore[0] + cScore[1];
					var nLose = parseInt(cScore[3] + cScore[4]) + 1;
				}
			} else if ((cScore[1] == "-") && (cScore[3] == true)) {
				var nWin = cScore[0];
				var nLose = parseInt(cScore[2] +cScore[3]) + 1;
			} else {
				var nWin = cScore[0];
				var nLose = parseInt(cScore[2]) + 1;
			}
		}
		var sUpdate = nWin + "-" + nLose;
		document.cookie = "score="+sUpdate;
	}
}

// Display the total score tally onsubmit
function writeScore() {
	var score = findCookie("score");	
		if (score[2] == "-") {
			var win = score[0] + score[1];
			var lose = score[3];
			if (score[4] == false) {
				var win = score[0] + score[1];
				var lose = score[3] + score[4];
			}
		} else if ((score[1] == "-") && (score[3] == "")) {
			var win = score[0];
			var lose = score[2] + score[3];
		} else {
			var win = score[0];
			var lose = score[2];
		}
	alert("Won: "+win+"  "+"Lost: "+lose);
}

// Compare the letter guess to the word
function checkWord() {
	var myLetter = document.getElementById('yourGuess').value;
	var myLetter = myLetter.toUpperCase();
	
	// Loop through myWord and check if it contains myLetter
	var stringWord = secretWord.join("");
  	var match = new Array();
	//var lettersLeft = stringWord.length;
	
	for (i = 0; i < secretWord.length; i++) {
        myChar = stringWord.charAt(i);
        
        //Penalize if wrong word is entered
        if ((myLetter.length > 1) && (myLetter != stringWord)) {
        	match[i] = "z";
        } else if (myLetter.indexOf(myChar) == 0) {
        	
        	c++;
			var reveal = document.getElementById('under'+i);
			reveal.style.visibility = "hidden";  
			match[i] = "a";
			if (c == stringWord.length) {
				// Remove guess button and change to try again
	  			var removeGuess = document.getElementById('Guess');
	  			removeGuess.style.visibility = "hidden";
	  		
	  			var tryAgain = document.getElementById('tryAgain');
	  			tryAgain.style.display = "inline";
	  			
	  			removeCookie();
				myResult('notice');
				score(1);
			}
  		} 
	}
	
		var hMatch = match.sort();
		if (myLetter == stringWord) {
			var cScore = findCookie("score");
		
  	  		// Remove guess button and change to try again
	  		var removeGuess = document.getElementById('Guess');
	  		removeGuess.style.visibility = "hidden";
	  		
	  		var tryAgain = document.getElementById('tryAgain');
	  		tryAgain.style.display = "inline";
	  		
	  		// Reveal word
	  		var showWord = document.getElementById('dash');
			showWord.style.visibility = "hidden";
			
			removeCookie();
			myResult('notice');
			score(1);
			
  	  	} else if (hMatch[0] != "a") {
  	  		var cName = findCookie("wrongLetters");
  	  		
  	  		
  	  		// if the "wrongLetters" cookie doesn't exist, add it to collect guessed letters
  			if ((myLetter.length == 1) && (cName == null)) {
  				document.cookie = "wrongLetters="+myLetter;
  				document.getElementById('myTry').innerHTML = myLetter;
  				
  			//add the last guess to the cookie string	
  			} else if ((myLetter.length == 1) && (cName.length >= 1)) {
  				var fLetter = new Array();
  				
				for (i=0; i<cName.length; i++) {
  					var usedChar = cName.charAt(i);
					if (usedChar == myLetter) {
  						fLetter[i]="a";
  					} else {
  						fLetter[i]="z";
					}
			 	 }
			  
				var foundLetter = fLetter.sort();
				if (foundLetter[0] == "a") {
					document.getElementById('myTry').innerHTML = cName;
					alert("You already guessed that letter");
					return false;
				} else {
				  	var newValue = cName + myLetter;
  					document.cookie = "wrongLetters=" + newValue;
  				  	document.getElementById('myTry').innerHTML = newValue;
				} 
			}
			//document.getElementById('myTry').innerHTML = myLetter;
			var myNoose = document.getElementById('noose');
			var myHead = document.getElementById('head');
			var myBody = document.getElementById('body');
			var myLeftArm = document.getElementById('leftArm');
			var myRightArm = document.getElementById('rightArm');
			var myLeftLeg = document.getElementById('leftLeg');
			var myRightLeg = document.getElementById('rightLeg');
			if (usedChar == myLetter) {
				alert("You already guessed that letter");
			} else {
			if (myNoose.style.left == "-30px") {
				hNoose();
			} else if ((myNoose.style.left > "0") && (myHead.style.left == "-30px")) {
				hHead(); 
	  		} else if ((myHead.style.left > "0") && (myBody.style.left == "-30px")) {
	  			hBody();
	  		} else if ((myBody.style.left > "0") && (myLeftArm.style.left == "-30px")) {
	  			hLeftArm();
	 		} else if ((myLeftArm.style.left > "0") && (myRightArm.style.left == "-30px")) {
	  			hRightArm();
	  		} else if ((myRightArm.style.left > "0") && (myLeftLeg.style.left == "-30px")) {
	  			hLeftLeg();
	  		} else if ((myLeftLeg.style.left > "0") && (myRightLeg.style.left == "-30px")) {
	  			hRightLeg();
			}
		}
	} 
}

// Make sure the characters entered are letters
function validLetters(yourGuess) {
	var realLetter = new RegExp(/[a-zA-Z]/g);
	return realLetter.test(yourGuess);
}

// Validate that the character entered is a letter
function vGuess() {
	if (document.hangman.yourGuess.value.length == 0)
		{alert("Please guess a letter");
		return false;}
	else if (validLetters(document.hangman.yourGuess.value) == false)
		{alert("You must enter a letter");
		return false;}
	checkWord();
}



// Returns the x coordinate of the id element
function xCoord(id) {
    if (document.getElementById) {
        var obj = document.getElementById(id);
        xc = parseInt(obj.style.left);
        return xc;
    }
}
// Returns the y coordinate of the id element
function yCoord(id) {
    if (document.getElementById) {
        var obj = document.getElementById(id);
        yc = parseInt(obj.style.top);
        return yc;
    }
}
// Moves object by dx (horizontal) and dy (vertical) 
function shiftIt(id, dx, dy) {
    if (document.getElementById) {
        var obj = document.getElementById(id);
        obj.style.left = xCoord(id) + dx + "px";
        obj.style.top = yCoord(id) + dy + "px";
    }
}

function hNoose() {
	var hAnimate = 2;
	var x = xCoord("noose");
    if (x < 540) {
        shiftIt("noose", 10, 0);
        setTimeout("hNoose()", 20);
    } 
}
function hHead() {
	var hAnimate = 2;
	var x = xCoord("head");
    if (x < 530) {
        shiftIt("head", 10, 0);
        setTimeout("hHead()", 20);
    } 
}
function hBody() {
	var hAnimate = 3;
	var x = xCoord("body");
    if (x < 540) {
        shiftIt("body", 10, 0);
        setTimeout("hBody()", 20);
    } 
}
function hLeftArm() {
	var hAnimate = 3;
	var x = xCoord("leftArm");
    if (x < 530) {
        shiftIt("leftArm", 10, 0);
        setTimeout("hLeftArm()", 20);
    } 
}
function hRightArm() {
	var hAnimate = 3;
	var x = xCoord("rightArm");
    if (x < 550) {
        shiftIt("rightArm", 10, 0);
        setTimeout("hRightArm()", 20);
    } 
}
function hLeftLeg() {
	var hAnimate = 3;
	var x = xCoord("leftLeg");
    if (x < 530) {
        shiftIt("leftLeg", 10, 0);
        setTimeout("hLeftLeg()", 20);
    } 
}
function hRightLeg() {
	var hAnimate = 3;
	var x = xCoord("rightLeg");
    if (x < 550) {
        shiftIt("rightLeg", 10, 0);
        setTimeout("hRightLeg()", 5);
    } else {
	  		// Remove guess button and change to try again
	  		var removeGuess = document.getElementById('Guess');
	  		removeGuess.style.visibility = "hidden";
	  		
	  		var tryAgain = document.getElementById('tryAgain');
	  		tryAgain.style.display = "inline";
	  		
	  		// Reveal word
	  		var showWord = document.getElementById('dash');
			showWord.style.visibility = "hidden";
			
			//Remove wrong letter cookie
			removeCookie();
			myResult('noticeLose');
			
			// Add 1 to lose tally
			score(0);
	}
}