gameTime = 0;
gameSpeed = 1;
refreshInterval = 10;

firstNum = 0;
secondNum = 0;

startTime = null;
lastTime = null;

jitterUntil = null;

gameInProgress = false;

consecutiveCorrectAnswers = 0;
maxMultiple = 10;

gameScore = 0;
collectingScore = false;

highScoreName = "";

loadingGame = false;

function startGame() {
    gameInProgress = true;
    loadingGame = true;
    startTime = new Date();
    lastTime = startTime;
    gameTime = 0;
    gameSpeed = 1;
    firstNum = 0;
    secondNum = 0;
    consecutiveCorrectAnswers = 0;
    maxMultiple = 10;
    gameScore = 0;
    jitterUntil = null;
    $('controls').hide();
    $('gameOver').hide();
    $('highScore').hide();
    $('instructions').hide();
    $('highScoreSubmit').hide();
    $('answerBox').value = "";
    $('puzzle').show();
    $('timer').show();
    setTimeout("incrementGameTime()", refreshInterval);
    setTimeout("activateEnterKey()", 500);
    choosePuzzle();
}

function activateEnterKey() {
    loadingGame = false;
}

function incrementGameTime() {
    var currentTime = new Date();
    var timeDiff = currentTime.valueOf() - lastTime.valueOf();
    lastTime = currentTime;
    gameTime += (gameSpeed * timeDiff);
    var timer = $("timer");
    var timerText = document.createTextNode("" + (gameTime / 1000).toFixed(2));
    if (timer.firstChild != null) {
        timer.replaceChild(timerText, timer.firstChild);
    } else {
        timer.appendChild(timerText);
    }

    var red = gameSpeed *  255.0;
    var blue = (1 - gameSpeed) * 255.0;

    
    $('timer').style.color = "rgb(" + red.toFixed(0) + ",0," + blue.toFixed(0) + ")";
    if (gameSpeed == 0) {
        gameSpeed = 0.005;
    } else if (gameSpeed < 1) {
        var multiplier = 0.0035 * (timeDiff / refreshInterval);
        multiplier += 1;
        gameSpeed = Math.min(gameSpeed * multiplier, 1);
    }

    var main = $('main');
    if (jitterUntil != null) {
        var now = new Date();
        if (jitterUntil > now.valueOf()) {
            main.style.marginTop = "" + randomize(30) + "px";
        } else {
            main.style.marginTop = "";
            jitterUntil = null;
        }
    }
    
    if (gameTime >= 10000) {
        gameOver();
    }
    else {
        setTimeout("incrementGameTime()", refreshInterval);
    }
}

function gameOver() {
    gameInProgress = false;
    gameTimer = 0;
    gameSpeed = 1;
    $('answer').hide()
    $('puzzle').hide();
    $('timer').hide();
    var main = $('main');
    main.style.marginTop = "";
    var endTime = new Date();

    var timeDiff = endTime.valueOf() - startTime.valueOf();
    var timeDiffInSec = (timeDiff / 1000).toFixed(2);
    gameScore = timeDiffInSec;

    var gameOverText = document.createTextNode("Your 10sec lasted for " + timeDiffInSec + "sec");
    var gameOver = $('gameOver');
    if (gameOver.firstChild != null) {
        gameOver.replaceChild(gameOverText, gameOver.firstChild);
    } else {
        gameOver.appendChild(gameOverText);
    }

    gameOver.show();
    $('play').value = "play again";
    $('controls').show();
    $('highScore').show();
    setTimeout("focusPlayButton()", 800);
}

function focusPlayButton() {
    $('play').focus();
}

function randomGameNumber() {
    return randomize(maxMultiple);   
}

function randomize(maxNum) {
    return Math.floor(Math.random() * maxNum + 1);
}

function choosePuzzle() {
    firstNum = randomGameNumber();
    secondNum = randomGameNumber();

    var puzzle = $("puzzle");
    var puzzleText = document.createTextNode("" + firstNum + " x " + secondNum);
    if (puzzle.firstChild != null) {
        puzzle.replaceChild(puzzleText, puzzle.firstChild);
    } else {
        puzzle.appendChild(puzzleText);
    }

    $("answer").show();
    $("answerBox").focus();
}

function submitAnswer(event) {
    if (!gameInProgress) {
        return;
    }
    
    if (parseInt($F("answerBox")) == (firstNum * secondNum)) {
        gameSpeed *= 0.5;
        consecutiveCorrectAnswers++;
        if (consecutiveCorrectAnswers % 3 == 0 && consecutiveCorrectAnswers != 0) {
            maxMultiple++;
        }
    } else {
        gameSpeed *= 1.1;
        var now = new Date();
        jitterUntil = now.valueOf() + 500;
        consecutiveCorrectAnswers = 0;
    }

    $("answerBox").setValue("");
    choosePuzzle();
}

function collectScore() {
    var name = "enter your name";
    if (highScoreName != "") {
        name = highScoreName;
    }
    $("answerBox").setValue(name);
    $("answer").style.width = "100%";
    $("play").setValue("send score");
    $("highScore").hide();
    collectingScore = true;
    Effect.BlindDown("answer");
    $("answerBox").focus();
    $("answerBox").select();
}

/****
 * NOTE TO THE CURIOUS/DEVIOUS
 *
 * I have made no attempt whatsoever to encrypt, obfuscate or otherwise secure this high score submission system.
 * If you want to cheat it would be easy to do so, though it will make things less interesting for the non-cheats.
 * Up to you!
 */
function submitScore() {
    highScoreName = $F("answerBox");
    Effect.BlindUp("answer");
    $("play").setValue("play again");
    collectingScore = false;
    var url = "http://kamikazemouse.com/time_factor/scoring/sendHighScore.php";
    var params = "player_name=" + escape(highScoreName) + "&elapsed_time=" + escape(gameScore);
    new Ajax.Request(url, {
        parameters: params,
        onSuccess: function(response) {
            var responses = response.responseText.split(":")
            if (responses[0] == "success") {
                var highScoreSubmit = $("highScoreSubmit");
                var highScoreSubmitLink = document.createElement("a");
                highScoreSubmitLink.setAttribute("href", "http://kamikazemouse.com/time_factor/scoring/highScores.php?score_id=" + responses[1]);
                var highScoreSubmitText = document.createTextNode("View your score");
                highScoreSubmitLink.appendChild(highScoreSubmitText)
                if (highScoreSubmit.firstChild != null) {
                    highScoreSubmit.replaceChild(highScoreSubmitLink, highScoreSubmit.firstChild);
                } else {
                    highScoreSubmit.appendChild(highScoreSubmitLink);
                }
                $("answer").style.width = "50%";
                Effect.BlindDown("highScoreSubmit", { queue: "end" });
            }
        }
    });
}

function handleButtonClick() {
    if (collectingScore) {
        submitScore();
    } else {
        startGame();
    }
}

