$('.row.header.fixed').click(function (e) {
    sortMode = e.target.id
    switch (sortMode){
        case "species":
            sortTablebySimple("name")
            break;
        case "dexno":
            sortTablebySimple("id");
            break;
        case "tier":
            sortTablebySimple("tier");
            break;
        case "HP":
            sortTablebySimple("highHP");
            break;
        case "att":
            sortTablebySimple("highAtt");
            break;
        case "def":
            sortTablebySimple("highDef");
            break;
        case "spatt":
            sortTablebySimple("highSpAtt");
            break;
        case "spdef":
            sortTablebySimple("highSpDef");
            break;
        case "speed":
            sortTablebySimple("highSpeed");
            break;
        case "release":
            sortTablebySimple("unreleased");
            break;
    }
});

var tiers = {
    AG: 8,
    Uber: 7,
    OU: 6,
    UU: 5,
    RU: 4,
    NU: 3,
    PU: 2,
    LC: 1,
    PA: 0,
    Unsorted: -1
}
var autoReverse= [ "tier", "highHP", "highAtt", "highDef","highSpAtt","highSpDef","highSpeed" ]

function sortTablebySimple(input) {
    table = $('.table.list')[0]
    //species = table.find('.species')
    sortFunc(obj, input, false, function (newObj) {
        populateTable(newObj);
    })
}

function populateTierFilter() {
    selectBox = $('#tierFilter')[0];
    for (var key in tiers) {
        var opt = document.createElement('option');
        opt.value = key;
        opt.innerHTML = key;
        selectBox.appendChild(opt);
    }
}

function filterTier(e) {
    var val = e.value
    if (val == "Filter Tier") {
        populateTable(obj);
        currentFilter = undefined;
        return
    }
    filterFunc(obj, val, false, function (newObj) {
        populateTable(newObj);
    })
}

function sortFunc(objectinput, input, isFilter, next) {
    if (typeof currentFilter != 'undefined' && isFilter == false) {
        filterFunc(objectinput, currentFilter, true, function (filteredObj) {
            if (typeof currentsort == "undefined" || currentsort != input) {
                obj2 = _.sortBy(filteredObj, input);
            }
            if (((typeof currentsort != "undefined" && currentsort == input) || ((typeof currentsort == "undefined" || currentsort != input) && _.contains(autoReverse, input)))) {
                obj2 = _.sortBy(filteredObj, input);
                obj2.reverse()
            }
            currentsort = input
            next(obj2);
        })
    }
    else {
        var obj2 = _.sortBy(objectinput, input);
        if (_.contains(autoReverse, input)) {
            obj2.reverse()
        }
        if (typeof currentsort != "undefined" && currentsort == input) {
            if(typeof toggleSort == "undefined"){ toggleSort = true; }
            else if (!isFilter) { toggleSort = !toggleSort }
            if (toggleSort && !isFilter){
                obj2.reverse()
            }
        }
        currentsort = input
        next(obj2);
    }
}

function filterFunc(object, input, isSort, next) {
    if ((typeof currentsort != "undefined") && !isSort) {
        if (typeof currentFilter != "undefined" && currentFilter != input) {
            var object = obj;
        }
        var objectToSort = object;
        sortFunc(objectToSort, currentsort, true, function (sortedObject) {
            var newobj = _.filter(sortedObject, function (thing) { return thing.tier == tiers[input] })
            currentFilter = input;
            next(newobj);
        })
    }
    else {
        if (typeof currentFilter != "undefined" && currentFilter != input) { var object = obj }
        var newobj = _.filter(object, function (thing) { return thing.tier == tiers[input] })

        currentFilter = input;
        next(newobj)
    }
}


function makeObject(next) {
    obj = []
    for (var key in species_data) {
        var pokeObj = {};
        pokeObj.name = key;
        var id = species_data[key].id.toString();
        if (id.length == 1) { id = "00" + id; }
        else if (id.length == 2) { id = "0" + id; }
        pokeObj.id = id;

        pokeObj.tier = -1;
        pokeObj.highHP = -1;
        pokeObj.highAtt = -1;
        pokeObj.highDef = -1;
        pokeObj.highSpAtt = -1;
        pokeObj.highSpDef = -1;
        pokeObj.highSpeed = -1;
        pokeObj.unreleased = false;

        formes = formes_data[key];
        pokeObj.formes = {}
        for (var formeName in formes) {
            var formeObj = {}
            var forme = formes[formeName]

            if (tiers[forme.tier] > pokeObj.tier) { pokeObj.tier = tiers[forme.tier] }
            if (forme.stats.hp > pokeObj.highHP) { pokeObj.highHP = forme.stats.hp }
            if (forme.stats.attack > pokeObj.highAtt) { pokeObj.highAtt = forme.stats.attack }
            if (forme.stats.defense > pokeObj.highDef) { pokeObj.highDef = forme.stats.defense }
            if (forme.stats.specialAttack > pokeObj.highSpAtt) { pokeObj.highSpAtt = forme.stats.specialAttack }
            if (forme.stats.specialDefense > pokeObj.highSpDef) { pokeObj.highSpDef = forme.stats.specialDefense }
            if (forme.stats.speed > pokeObj.highSpeed) { pokeObj.highSpeed = forme.stats.speed }
            if (forme.unreleased) { pokeObj.unreleased = true; }

            if (forme.tier) { formeObj.tier = forme.tier[0]; }
            else { formeObj.tier = "Unsorted" }
            formeObj.types = forme.types;
            formeObj.Abilities = forme.abilities;
            if (forme.hiddenAbility) { formeObj.HA = forme.hiddenAbility; }
            else { formeObj.HA = "" }
            formeObj.stats = forme.stats;
            formeObj.unreleased = forme.unreleased;
            pokeObj.formes[formeName] = formeObj
        }
        obj.push(pokeObj)
    }
    next(obj);
}

function populateTable(arr) {
    table = $('.table.list')[0];

    while(table.rows.length > 0) {
        table.deleteRow(0);
    }

    for (var i in arr) {
        var pokeObj = arr[i];
        var row = table.insertRow(-1);
        row.className += "row pokemonRow"
        row.id = pokeObj.name
        // Sets dexNo
        var dexcell = row.insertCell(0);
        dexcell.innerHTML = pokeObj.id;
        // sets Icon
        var img = document.createElement("div");
        img.className += "iconplace"
        img.style.background = "URL(/Sprites/Icons/icon" + pokeObj.id + ".png";
        dexcell.appendChild(img);
        // Sets name
        var namecell = row.insertCell(1);
        namecell.innerHTML = pokeObj.name;
        namecell.className += "cell species"
        //Handles multiple formes
        for (var j in pokeObj.formes) {
            var formeTable = document.createElement('table');
            formeTable.className += "formeTable"
            var forme = pokeObj.formes[j];
            var formeRow = formeTable.insertRow(-1);
            formeRow.className += "row inherit"
            //Sets formename
            var formenamecell = formeRow.insertCell(0);
            formenamecell.className += "formeName"
            formenamecell.innerHTML = j;
            //Sets forme tier
            var formetiercell = formeRow.insertCell(1);
            formetiercell.className += "tier"
            formetiercell.innerHTML = forme.tier;
            if (forme.types[1]) {
                //type 1
                var type1cell = formeRow.insertCell(2);
                type1cell.className += forme.types[0]
                type1cell.innerHTML = forme.types[0]
                //type 2
                var type2cell = formeRow.insertCell(3);
                type2cell.className += forme.types[1]
                type2cell.innerHTML = forme.types[1]
            }
            else {
                //hax for single type
                var type1cell = formeRow.insertCell(2);
                type1cell.className += forme.types[0] + " singletypeleft"
                type1cell.innerHTML = forme.types[0]
                var type2cell = formeRow.insertCell(3);
                type2cell.className += "singeltyperight"
            }
            type1cell.className += " type";
            type2cell.className += " type";
            //set abilities
            var abils = forme.Abilities.join('<br>');
            var abilcell = formeRow.insertCell(4);
            abilcell.className += "abilities";
            abilcell.innerHTML = abils;
            //hidden ability
            var haCell = formeRow.insertCell(5);
            haCell.className += "abilities";
            haCell.innerHTML = forme.HA
            //stats
            //hp
            var hpcell = formeRow.insertCell(6);
            hpcell.className += "allstats";
            hpcell.innerHTML = forme.stats.hp;
            //att
            var attcell = formeRow.insertCell(7);
            attcell.className += "allstats";
            attcell.innerHTML = forme.stats.attack;
            //def
            var defcell = formeRow.insertCell(8);
            defcell.className += "allstats";
            defcell.innerHTML = forme.stats.defense;
            //spatt
            var spattcell = formeRow.insertCell(9);
            spattcell.className += "allstats";
            spattcell.innerHTML = forme.stats.specialAttack;
            //def
            var spdefcell = formeRow.insertCell(10);
            spdefcell.className += "allstats";
            spdefcell.innerHTML = forme.stats.specialDefense;
            //speed
            var speedcell = formeRow.insertCell(11);
            speedcell.className += "allstats";
            speedcell.innerHTML = forme.stats.speed;
            //released
            releasecell = formeRow.insertCell(12)
            if ((forme.unreleased == false || typeof forme.unreleased == 'undefined') && pokeObj.formes.default.unreleased != true) {
                releasecell.className += "release released"
                releasecell.innerHTML = "✔"
            }
            else {
                releasecell.className += "release unreleased"
                releasecell.innerHTML = "✖"
            }
            row.appendChild(formeTable);

        }

    }

}

function openTab(pkmn) {
    pkmn = pkmn.replace(" ", "_")
    url= "/pokemon/" + pkmn
    window.open(url, '_blank');
}

$("table.table.list").click(function (e) {
    target = e.target;
    var search = target;
    var searching = true;
    while (searching) {
        upNode = search.parentElement;
        if (upNode.localName == "body") {
            searching = false;
            return;
        }
        if (upNode.className == "row pokemonRow") {
            searching = false;
            openTab(upNode.id)
        }
        else {
            search = upNode;
        }
    }

})


$(document).ready(function () {
    makeObject(function (arr) {
        populateTierFilter()
        if (window.location.hash) {
            tr = window.location.hash
            tr = tr.replace("#", "")
            filterFunc(arr, tr, false, function (newObj) {
                populateTable(newObj);
            })
        }
        else {
            populateTable(arr)
        }
    })
});