var next = "puzzle1.html";
var expectedAnswer = "";
var solutionImage = null;
var expectedArrayAnswer;
var hints;
var genericSpecialAnswers =
        new Array(
        new Array("wollo", "No, there are no cheat codes. (And if there were any, they certainly wouldn't be as simple as that, it'd be something like \"d3a8ck\")"),
        new Array("d3a8ck", "You didn't honestly think that would get you anywhere, did you? As I said, there are no cheat codes"),
        new Array("", "That's not really an answer, is it?"),
        new Array("42", "While 42 may be the answer to The Ultimate Question Of Life, the Universe and Everything, it is not the answer to this puzzle"),
        new Array("help", "Getting desperate, are we? Come on, you can solve this! ... alright: if you really can't solve it, type \"give me a hint!\""),
        new Array("help me", "Getting desperate, are we? Come on, you can solve this! ... alright: if you really can't solve it, type \"give me a hint!\""),
        new Array("hint", "Getting desperate, are we? Come on, you can solve this! ... alright: if you really can't solve it, type \"give me a hint!\""),
        new Array("give me a hint!", "You didn't say please! Type \"give me a hint, please!\""),
        new Array("give me a hint, please!", "Alright, then. You'll get your hint.Just type \"If I don't get a hint now, I'll never play your stupid puzzle game again!\""),
        new Array("if i don't get a hint now, i'll never play your stupid puzzle game again!", "OK, then. Don't. See if I care.")
        );

var specialAnswers = new Array();
var imageAreas = new Array(
        new Array(4, 30, 11, 39),
        new Array(137, 173, 12, 20),
        new Array(258, 145, 16, 25),
        new Array(245, 66, 12, 11),
        new Array(195, 243, 14, 21)
        );
var duplicateImageOffset = 0;

var urlAppendix = new Array("", "gc", "al", "iao", "cin", "gss", "tm", "mic", "rew", "qtb", "enf", "mpt","rmo", "noc", "wor", "mec", "nc2", "lor", "vic", "dwk", "hdd", "xxx");
var maxLevel = 0;
var currentPuzzle = 0;

function setPuzzle(puzzle){
    currentPuzzle = puzzle;
    maxLevel = getCookie("maxLevel");
    if (maxLevel == null || maxLevel < puzzle){
        var year = new Date();
        year.setTime(year.getTime() + (365 * 24 * 60 * 60 * 1000));
        document.cookie = "maxLevel=" + puzzle + "; expires=" + year.toGMTString();
        maxLevel = puzzle;
    }
    next = "puzzle" + (puzzle + 1) + "_" + urlAppendix[puzzle] + ".html";

    switch (puzzle){
        case 1:
            expectedAnswer = "Goblin Commando";
            solutionImage = "resources/goblin_commando.png";
            break;
        case 2:
            expectedAnswer = "Annul";
            solutionImage = "resources/artist_mix_annul.jpg";
            expectedArrayAnswers = new Array(
                    new Array("Pete Venters", "Venters", "P. Venters"),
                    new Array("John Avon", "Avon", "J. Avon"),
                    new Array("Michael Sutfin", "Sutfin", "M. Sutfin"),
                    new Array("John Bolton", "Bolton", "J. Bolton"),
                    new Array("Brom")
                    );
            hints = new Array(
                    "The first letter is the third one in the name of Pete Venters' card.",
                    "The second letter is the last one in the name of John Avon's card.",
                    "The third letter is the fifth one in the name of Michael Sutfin's card.",
                    "The fourth letter is the first one in the name of John Bolton's card.",
                    "The fifth letter is the last one in the name of Brom's card."
                    );
            specialAnswers = new Array(
                    new Array("Thran Quarry", "The question is, \"Whodunit?\""),
                    new Array("Artist's Crusade", "The question is, \"Whodunit?\""),
                    new Array("Decree of Annihilation", "The question is, \"Whodunit?\""),
                    new Array("Uyo, Silent Prophet", "The question is, \"Whodunit?\""),
                    new Array("Desolation Angel", "The question is, \"Whodunit?\"")
                    );
            break;
        case 3:
            expectedAnswer = "Iname as One";
            solutionImage = "resources/iname.png";
            specialAnswers = new Array(
                    new Array("Anagram", "Of course, you need an anagram! Now find the card that the phrase is an anagram of!")
                    );
            break;
        case 4:
            expectedAnswer = "Master Decoy";
            solutionImage = "resources/puzzle4.jpg";
            specialAnswers = new Array(
                    new Array("hell's caretaker", "Don't be silly. It couldn't be THAT easy!")
                    );
            imageAreas = new Array(
                    new Array(4, 30, 11, 39),
                    new Array(137, 173, 12, 20),
                    new Array(258, 145, 16, 25),
                    new Array(245, 66, 12, 11),
                    new Array(195, 243, 14, 21)
                    );
            duplicateImageOffset = 431;
            hints = new Array(
                    "Hint 1: The first number is the number of letters in the artist's first name.",
                    "Hint 2: The second number is the number of letters in the artist's last name.",
                    "Hint 3: The third number is the number of letters in the last word of this card's name.",
                    "Hint 4: Subtract the first number from the second one, then multiply by the third number.",
                    "Hint 5: Find the card with that number in Ninth Edition."
                    );
            break;
        case 5:
            expectedAnswer = "Glissa Sunseeker";
            solutionImage = "resources/glissa.jpg";
            break;
        case 6:
            expectedAnswer = "TM";
            solutionImage = "resources/card_back_tm.jpg";
            specialAnswers = new Array(
                    new Array("Trademark", "Why such a lengthy answer?"),
                    new Array("Trademark sign", "Why such a lengthy answer?"),
                    new Array("TM sign", "Why such a lengthy answer?"),
                    new Array("Deckmaster TM", "Why such a lengthy answer?"),
                    new Array("Deckmaster", "And what's wrong about it?"),
                    new Array("Deckmaster logo", "And what's wrong about it?")
                    );
            break;
        case 7:
            expectedAnswer = "Mirrodin's Core";
            solutionImage = "resources/puzzle7_mic.jpg";
            specialAnswers = new Array(
                    new Array("Mirodinscore", "Nearly. Check the card name. It's spelled differently."),
                    new Array("Mir odin score", "Nearly. Check the card name. It's spelled differently."),
                    new Array("Mirodin's core", "Nearly. Check the card name. It's spelled differently.")
                    );
            break;
        case 8:
            expectedAnswer = "Rewind";
            solutionImage = "resources/power9_rew.jpg";
            specialAnswers = new Array(
                    new Array("Power Nine", "That's right. These are the power Nine. So what?"),
                    new Array("Power 9", "That's right. These are the power Nine. So what?")
                    );
            imageAreas = new Array(
                    new Array(104, 221, 10, 12),
                    new Array(212, 160, 35, 12),
                    new Array(419, 22, 164, 135),
                    new Array(16, 444, 57, 12),
                    new Array(226, 509, 31, 12),
                    new Array(491, 462, 22, 15),
                    new Array(13, 834, 121, 14),
                    new Array(218, 592, 164, 135),
                    new Array(419, 592, 164, 135)
                    );
            duplicateImageOffset = 0;
            hints = new Array(
                    "Hint 1: The card has the same casting cost as ...",
                    "Hint 2: ... Ancestral Recall ...",
                    "Hint 3: ... and Timetwister added up.",
                    "Hint 4: Its card type is the same as ...",
                    "Hint 5: ... Ancestral Recall.",
                    "Hint 6: It lets you ...",
                    "Hint 7: ... untap ...",
                    "Hint 8: ... lands ...",
                    "Hint 9: ... as a side effect."
                    );
            break;
        case 9:
            expectedAnswer = "Quirion Trailblazer";
            solutionImage = "resources/puzzle9_trb.jpg";
            specialAnswers = new Array(
                    new Array("All that matters is the path ahead", "That's what it says up there. So far, so good. But I'm looking for a card."),
                    new Array("Allthatmattersisthepathahead", "That's what it says up there. So far, so good. But I'm looking for a card.")
                    );
            break;
        case 10:
            expectedAnswer = "Energy Flux";
            solutionImage = "resources/puzzle10_enf.jpg";
            expectedArrayAnswers = new Array(
                    new Array("Baron Sengir"),
                    new Array("Tornado Elemental"),
                    new Array("Look at Me, I'm the DCI"),
                    new Array("Boomerang"),
                    new Array("Atogatog"),
                    new Array("Abyssal Nocturnus"),
                    new Array("Lord of the Pit"),
                    new Array("Sliver Queen"),
                    new Array("Dune-Brood Nephilim", "Dunebrood Nephilim"),
                    new Array("Phyrexian Dreadnought")
                    );
            hints = new Array(
                    "Baron Sngir",
                    "Torado Elemental",
                    "Look at M, I'm the DCI",
                    "Boomeang",
                    "Atoatog",
                    "Abssal Nocturnus",
                    "Lord o the Pit",
                    "Siver Queen",
                    "Dne-Brood Nephilim",
                    "Phyreian Dreadnought"
                    );
            specialAnswers = new Array(
                    new Array("energyflux", "Nearly. Give me some SPACE!"),
                    new Array("Baron Sengir", "Enter those in the first textbox!"),
                    new Array("Tornado Elemental", "Enter those in the first textbox!"),
                    new Array("Look at Me, I'm the DCI", "Enter those in the first textbox!"),
                    new Array("Boomerang", "Enter those in the first textbox!"),
                    new Array("Atogatog", "Enter those in the first textbox!"),
                    new Array("Abyssal Nocturnus", "Enter those in the first textbox!"),
                    new Array("Lord of the Pit", "Enter those in the first textbox!"),
                    new Array("Sliver Queen", "Enter those in the first textbox!"),
                    new Array("Dune-Brood Nephilim", "Dunebrood Nephilim", "Enter those in the first textbox!"),
                    new Array("Phyrexian Dreadnought", "Enter those in the first textbox!"),
                    new Array("energy flux", "Enter your solution in the second textbox!")
                    );
            break;
        case 11:
            expectedAnswer = "Merfolk of the Pearl Trident";
            solutionImage = "resources/puzzle11_mpt.jpg";
            expectedArrayAnswers = new Array(
                    new Array("Metalworker"),
                    new Array("Equilibrium"),
                    new Array("Rancor"),
                    new Array("Frogmite"),
                    new Array("Opalescence"),
                    new Array("Lobotomy"),
                    new Array("Karstoderm"),
                    new Array("Obliterate"),
                    new Array("Firestorm"),
                    new Array("Taiga"),
                    new Array("Heartseeker"),
                    new Array("Execute"),
                    new Array("Phelddagrif"),
                    new Array("Entomb"),
                    new Array("Abomination"),
                    new Array("Resuscitate"),
                    new Array("Lifetap"),
                    new Array("Tetravus"),
                    new Array("Repercussion"),
                    new Array("Island"),
                    new Array("Dodecapod"),
                    new Array("Enfeeblement"),
                    new Array("Necropolis"),
                    new Array("Tinker")
                    );
            hints = new Array(
                    "Metalworker",
                    "Equilibrium",
                    "Rancor",
                    "Frogmite",
                    "Opalescence",
                    "Lobotomy",
                    "Karstoderm",
                    "Obliterate",
                    "Firestorm",
                    "Taiga",
                    "Heartseeker",
                    "Execute",
                    "Phelddagrif",
                    "Entomb",
                    "Abomination",
                    "Resuscitate",
                    "Lifetap",
                    "Tetravus",
                    "Repercussion",
                    "Island",
                    "Dodecapod",
                    "Enfeeblement",
                    "Necropolis",
                    "Tinker"                );
            specialAnswers = new Array(
                    new Array("energyflux", "Nearly. Give me some SPACE!"),
                    new Array("Baron Sengir", "Enter those in the first textbox!"),
                    new Array("Tornado Elemental", "Enter those in the first textbox!"),
                    new Array("Look at Me, I'm the DCI", "Enter those in the first textbox!"),
                    new Array("Boomerang", "Enter those in the first textbox!"),
                    new Array("Atogatog", "Enter those in the first textbox!"),
                    new Array("Abyssal Nocturnus", "Enter those in the first textbox!"),
                    new Array("Lord of the Pit", "Enter those in the first textbox!"),
                    new Array("Sliver Queen", "Enter those in the first textbox!"),
                    new Array("Dune-Brood Nephilim", "Dunebrood Nephilim", "Enter those in the first textbox!"),
                    new Array("Phyrexian Dreadnought", "Enter those in the first textbox!"),
                    new Array("energy flux", "Enter your solution in the second textbox!")
                    );
            break;
        case 12:
            expectedAnswer = "Rustmouth Ogre";
            solutionImage = "resources/puzzle12_rmo.jpg";
            break;
        case 13:
            expectedAnswer = "2;4;3;8;0;5;1;7;9;6";
            break;
        case 14:
            expectedAnswer = "Worship";
            solutionImage = "resources/puzzle14_wor.jpg";
            break;
        case 15:
            expectedAnswer = "Memory Crystal";
            solutionImage = "resources/puzzle15_mec.jpg";
            break;
        case 16:
            expectedAnswer = "4;1;9;8;7;10;3;6;2;5";
            break;
        case 17:
            expectedAnswer = "Lady Orca";
            solutionImage = "resources/puzzle17_lor.jpg";
            expectedArrayAnswers = new Array(
                    new Array("Ronin Warclub"),
                    new Array("Slagwurm Armor"),
                    new Array("Lightning Greaves"),
                    new Array("Healer's Headdress"),
                    new Array("Shield of Kaldra")
                    );
            hints = new Array(
                    "1. Take Barbie's power.",
                    "2. Multiply it by her toughness.",
                    "3. Calculate the sum of the digits.",
                    "4. Subtract the casting cost of Healer's Headdress.",
                    "5. Name the first creature ever to have that value as its power, but not as its toughness."
                    );
            specialAnswers = new Array(
                    new Array("ladyorca", "Nearly. Give me some SPACE!"),
                    new Array("Ronin Warclub", "Enter those in the first textbox!"),
                    new Array("Slagwurm Armor", "Enter those in the first textbox!"),
                    new Array("Lightning Greaves", "Enter those in the first textbox!"),
                    new Array("Healer's Headdress", "Enter those in the first textbox!"),
                    new Array("Shield of Kaldra", "Enter those in the first textbox!"),
                    new Array("Lady Orca", "Enter your solution in the second textbox!")
                    );
            break;
        case 18:
            expectedAnswer = "Victimize";
            solutionImage = "resources/puzzle18_vic.jpg";
            break;
        case 19:
            expectedAnswer = "Distorting Wake";
            expectedArrayAnswers = new Array(
                    new Array("Arrogant Vampire"),
                    new Array("Dream Prowler"),
                    new Array("Echoing Truth"),
                    new Array("Giant Trap Door Spider"),
                    new Array("Inner Calm, Outer Strength"),
                    new Array("Iron Tusk Elephant"),
                    new Array("Keeper of the Nine Gales"),
                    new Array("Need for Speed"),
                    new Array("Order of the White Shield"),
                    new Array("Raven Guild Initiate"),
                    new Array("Spring of Eternal Peace"),
                    new Array("Tar Pit Warrior"),
                    new Array("Toils of Night and Day"),
                    new Array("Wurmskin Forger")
                    );
            hints = new Array(
                    "Arrogant Vampire",
                    "Dream Prowler",
                    "Echoing Truth",
                    "Giant Trap Door Spider",
                    "Inner Calm, Outer Strength",
                    "Iron Tusk Elephant",
                    "Keeper of the Nine Gales",
                    "Need for Speed",
                    "Order of the White Shield",
                    "Raven Guild Initiate",
                    "Spring of Eternal Peace",
                    "Tar Pit Warrior",
                    "Toils of Night and Day",
                    "Wurmskin Forger"
                    );
            break;
        case 20:
            expectedAnswer = "Hokori, Dust Drinker";
            expectedArrayAnswers = new Array(
                    new Array("Rakdos Augermage"),
                    new Array("Crater Hellion"),
                    new Array("Urza's Incubator"),
                    new Array("Symbiotic Wurm"),
                    new Array("Xenic Poltergeist")
                    );
            hints = new Array(
                    "The card you're looking for is a white ...",
                    "... legendary ...",
                    "... creature ...",
                    "... from the Kamigawa block ...",
                    "... that messes with lands."
                    );
            solutionImage = "resources/puzzle20_hdd.jpg";
                next = "congas.html";
            break;
    }
}

function checkAnswer(giveHint){
    guess = document.getElementById("guess").value.toLowerCase();
    document.getElementById("guess").select();
    if (guess == expectedAnswer.toLowerCase()){
        if (giveHint){
            giveHint();
        }
        else{
            solved();
        }
        return;
    }
    if (!checkForSpecialAnswer(guess)){
        printMessage("No, that's not it!");
    }
};

function checkArrayAnswer(giveHint){
    guess = document.getElementById("array_guess").value.toLowerCase();
    document.getElementById("array_guess").select();
    for (i = 0; i < expectedArrayAnswers.length; i++){
        for (alternative = 0; alternative < expectedArrayAnswers[i].length; alternative++){
            if (guess == expectedArrayAnswers[i][alternative].toLowerCase()){
                if (giveHint){
                    giveArrayHint(i);
                }
                else{
                    solved();
                }
                return;
            }
        }
    }
    if (!checkForSpecialAnswer(guess)){
        printMessage("No, that's not it!");
    }
};


function giveHint(){
    document.getElementById("hint").innerHTML = hint;
    printMessage("Correct! You've received a hint");
};

function giveArrayHint(index){
    document.getElementById("hint_" + index).innerHTML = hints[index];
    printMessage("Correct! You've received hint no. " + (index + 1));
};

function solved(){
    if (document.getElementById("img") != null && solutionImage != null){
        document.getElementById("img").src = solutionImage;
    }
    printMessage("Correct! You may proceed to the next level.", next);
    //window.location.href = next;
};

function checkForSpecialAnswer(guess){
    for (i = 0; i < specialAnswers.length; i++){
        if (guess == specialAnswers[i][0].toLowerCase()){
            printMessage(specialAnswers[i][1]);
            return true;
        }
    }
    for (i = 0; i < genericSpecialAnswers.length; i++){
        if (guess == genericSpecialAnswers[i][0].toLowerCase()){
            printMessage(genericSpecialAnswers[i][1]);
            return true;
        }
    }
    return false;
}

function makeImageMap(){
    map = document.getElementById("img_map");
    for (i = 0; i < imageAreas.length; i++){
        area = document.createElement("area");
        area.shape = "rect";
        area.coords = imageAreas[i][0] + ", " + imageAreas[i][1] + ", " + (imageAreas[i][0] + imageAreas[i][2]) + ", " + (imageAreas[i][1] + imageAreas[i][3]);
        //area.setAttribute("onclick", "javascript:processMapClick(" + i + ")");
        area.alt = "";
        area.href = "javascript:processMapClick(" + i + ");";
        area.setAttribute("onmouseover", "javascript: window.status = 'x'; return true;");
        map.appendChild(area);
    }
    if (duplicateImageOffset > 0){
        for (i = 0; i < imageAreas.length; i++){
            area = document.createElement("area");
            area.shape = "rect";
            area.coords = (duplicateImageOffset + imageAreas[i][0]) + ", " + imageAreas[i][1] + ", " + (duplicateImageOffset + imageAreas[i][0] + imageAreas[i][2]) + ", " + (imageAreas[i][1] + imageAreas[i][3]);
            //area.setAttribute("onclick", "javascript:printMessage(" + i + ")");
            area.alt = "";
            area.href = "javascript:processMapClick(" + i + ")";
            area.setAttribute("onmouseover", "javascript: window.status = 'x'; return true;");
            map.appendChild(area);
        }
    }

}

function processMapClick(index){
    giveArrayHint(index);
}

function printMessage(text, link){
    div = document.getElementById("linkDiv");
    while (div.hasChildNodes()){
        div.removeChild(div.firstChild);
    }
    text = document.createTextNode(text);
    if (link != null){
        a = document.createElement("a");
        a.href = link;
        a.appendChild(text);
        div.appendChild(a);
    }else{
        div.appendChild(text);
    }
}

function show(id){
    document.getElementById(id).style.visibility = 'visible';
}

function hide(id){
    document.getElementById(id).style.visibility = 'hidden';
}

function remove(id){
    document.getElementById(id).parentNode.removeChild(document.getElementById(id));
}

function getCookie(name) {
    var dc = document.cookie;
    var prefix = name + "=";
    var begin = dc.indexOf("; " + prefix);
    if (begin == -1) {
        begin = dc.indexOf(prefix);
        if (begin != 0) return null;
    } else
        begin += 2;
    var end = document.cookie.indexOf(";", begin);
    if (end == -1)
        end = dc.length;
    return unescape(dc.substring(begin + prefix.length, end));
}

function getJumpBar(){
    s = "Jump to Puzzle: ";
    for (i = 1; i <= maxLevel; i++){
        s += "<a href=puzzle" + i + (urlAppendix[i-1] == "" ? "" : ("_" + urlAppendix[i-1])) + ".html>" + i + "</a> ";
    }
    return s

}
