var letters = {};
var firstpass = /(\d+)(\D)/g;
var secondpass = /\d+\D(\D+)$/;
var divshow = 0;
var dolist = false;
var checkListVar = [];
var wordList = [];
var wordPool = [];

var hintlist = {
    "11letter": { "description":"11-letter words", "count":0, "max": 1, "maxcolor": "#FF0000" },
    "8letter": { "description":"8-letter words", "count":0, "max": 1, "maxcolor": "#BBBB00" },
    "punctuation": { "description":":,!! in order", "pass":true },
    "startswithi": { "description":"Starts with I","pass":true },
    "has!!": { "description":"Contains !!", "pass":true },
    "sidebyside": { "description":"8 and 11 letter words adjacent", "pass":true },
    "validwords": { "description":"All words are valid", "pass":true },
    "validletters": { "description":"All letters are valid", "pass":true }
};

var errorlist = {
    "notinlist":{"description":"Word is not in list!","iserr":false},
    "doesntmatch":{"description":"Sentence doesn't match the Anacryptogram!","iserr":false},
    "badlength":{"description":"Word is an invalid length (must be 1-8 or 11 letters)","iserr":false}
};


function shufflepool() {
    mypool = document.getElementById('pool');
    char_arr = mypool.innerHTML.split('');
    char_arr.sort(function(){return Math.random()<0.5?-1:1});
    mypool.innerHTML = char_arr.join('');
}

function cloneObj(o) {
     if(typeof(o) != 'object') return o;
     if(o == null) return o;

     var newO = new Object();

     for(var i in o) newO[i] = cloneObj(o[i]);
      return newO;
 }

function getimage() {
    document.getElementById('thepic').src = document.getElementById('picsrc').value;
}

function updatepool(event) {
    errorlist['notinlist'].iserr = false;
    errorlist['doesntmatch'].iserr = false;
    errorlist['badlength'].iserr = false;

    var charup = getChar(event);
    if(charup > 13 && charup <= 40 && charup != 32) {
        //Don't update for control keys, except for spacebar.
        return;
    }

    var sentelm = document.getElementById('sentence');
    var dosuggest = document.getElementById('suggest').checked;

    sent = sentelm.value;
    //Check to see if they match the anacryptogram
    validity = checkValid(sent, letters, true);
    templet = validity['letters'];
    if(validity['fail']) { errorlist['doesntmatch'].iserr = true; }

    if(charup==13) {
        sentelm.value = sentelm.value.replace(/[\n\r]+/, '');
        shufflepool();
        document.getElementById('suggestions').innerHTML = genSuggest(templet);
        return;
    }

    var suggestions = '';
    var badwords = '';
    if(dolist) {
        //If we're using the list, go ahead and check and generate suggestions
        badwords = checkList(sent, templet);
        if(dosuggest) {
            suggestions = genSuggest(templet);
        }
    } else {
        //Do a poor man's length check
        var regex = /\b[A-Za-z]{9,}\b/g;
        while(match = regex.exec(sent)) {
            if(match[0].length != 11) {
                badwords = badwords + match[0] + ' ';
                errorlist['badlength'].iserr = true;
            }
        }
    }

    var succeeded = true;
    var pool = '';
    var missedpool = '';
    var list = '';
    for(i in templet) {
        var letcount = templet[i];

        if(letcount > 0) { classname = 'pos'; }
        else if(letcount < 0) { classname = 'neg'; }
        else { classname = 'zero'; }
        list += '<span class="letcount ' + classname + '">' + i + ': ' + letcount + '</span>';

        for(r=0;r<letcount;r++) {
            pool += i;
        }
        if(letcount < 0) {
            for(r=0;r<(-letcount);r++) {
                missedpool += i;
            }
        }
        if(letcount != 0) {
            succeeded = false;
        }
    }
    var errlist = [];
    for(e in errorlist) {
        if(errorlist[e].iserr) { errlist.push(errorlist[e].description); }
    }

    updateHints(sent);  //Update the hints
    //Copy over error conditions to hintslist
    hintlist['validwords'].pass = !errorlist['notinlist'].iserr;
    hintlist['validletters'].pass = !errorlist['doesntmatch'].iserr;

    var hints = '<table><tr><th style="width:100px;text-align:left;"></th><th style="width:20px;text-align:right;"></th></tr>';
    var altrow = true;
    for(h in hintlist) {
        hints += '<tr' + (altrow ? ' class="altrow"' : '') + '><td>' + hintlist[h].description + '</td><td>';
        if(typeof(hintlist[h].count) != 'undefined') {
            if(hintlist[h].count == 0) {
                numcolor = "#FF0000";
                succeeded = false;
            } else if(hintlist[h].count > hintlist[h].max) {
                numcolor = hintlist[h].maxcolor;
                if(hintlist[h].maxcolor == '#FF0000') {
                    succeeded = false; 
                }
            } else {
                numcolor = "#006600";
            }
            hints += '<span class="hint" style="color:' + numcolor + '">' + hintlist[h].count + '</span>';
        } else if(typeof(hintlist[h].pass) != 'undefined') {
            if(hintlist[h].pass) {
                hints += '<span class="hint" style="color:#006600">Pass</span>';
            } else {
                hints += '<span class="hint" style="color:#FF0000">Fail</span>';
                succeeded = false;
            }
        }
        hints += '</td></tr>';
        altrow = !altrow;
    }

    if(errlist.length == 0) { 
        if(succeeded) { msg = '<span style="color:green;">Match found!</span>'; }
        else { msg = 'Keep going...'; } 
    }
    else { msg = '<span style="color:red;font-size:80%;">' + errlist.join('<br/>') + '</span>'; }

    document.getElementById('missedpool').innerHTML = missedpool;
    document.getElementById('pool').innerHTML = pool;
    document.getElementById('list').innerHTML = list;
    document.getElementById('badwords').innerHTML = badwords;
    document.getElementById('suggestions').innerHTML = suggestions;
    document.getElementById('result').innerHTML = msg;
    document.getElementById('hints').innerHTML = hints;
}

function checkValid(sent, letters, clone) {
    var returnval = {'letters':0,'fail':0}
    if(clone) { myletters = cloneObj(letters); }
    else { myletters = letters; }

    var failboat = false;
    for(i=0;i<sent.length;i++) {
        var curchar = sent.charAt(i);
        if(curchar != ' ') {
            if(myletters[curchar]) {
                myletters[curchar]--;
                if(myletters[curchar] < 0) { failboat = true; }
            } else {
                myletters[curchar] = -1;
                failboat = true;
            }
        }
    }

    returnval['letters'] = myletters;
    returnval['fail'] = failboat;
    return returnval;
}

function genletters() {
    letters = {};
    var input = document.getElementById('anacryptogram').value;
    while(match = firstpass.exec(input)) {
        letters[match[2]] = match[1];
    }
    if(match = secondpass.exec(input)) {
        var tail = match[1].split('');
        for(i=0;i<tail.length;i++) {
            if(letters[tail[i]]) {
                letters[tail[i]]++;
            } else {
                letters[tail[i]] = 1;
            }
        }

    }
    updatepool();
}

function getChar(e){
    var characterCode;

    try {
        if(e && e.which){
            e = e;
            characterCode = e.which; //character code is contained in NN4's which property
        } else {
            e = event;
            characterCode = e.keyCode; //character code is contained in IE's keyCode property
        }

        return characterCode;
    }
    catch(err) {
        return null;
    }
}

function toggleDiv(name, link) {
    var div = document.getElementById(name);
    var linky = document.getElementById(link);
    if(divshow) {
        div.style.display='none';
        linky.innerHTML = 'Show old updates'; 
        divshow=0;
    }
    else {
        div.style.display='';
        linky.innerHTML = 'Hide old updates'; 
        divshow=1;
    }
}

function toggleList(chk) {
    var div = document.getElementById('listopts');
    if(chk.checked) {
        div.style.display='';
        dolist = true;
        getWordlist('check');
    }
    else {
        div.style.display='none';
        dolist = false;
    }
}

function maybeSort(chk) {
    if(!chk.checked) {
        wordPool.sort();
    }
}
