Mishin870 / TO War plugin

// ==UserScript==
// @name         TO War plugin
// @include    https://war.tankionline.com/*
// @version      0.5
// @description  No description
// @author       Mishin870
// @match        https://tampermonkey.net/installed.php?version=4.7&ext=dhdg&updated=true
// @require http://code.jquery.com/jquery-1.12.4.min.js
// @license      MIT
// ==/UserScript==

var zoneDefs = {
    "ru": ["Оса","Трибьют","Соликамск","Колхоз","Холм","Подземка","РедАлерт","СтолицаМедведей","Дюссельдорф","Монте-Карло","Перекрёсток","Пустыня","Бойня","Форест","Остров","Молотов","Осада","Перевал","Гравити","Полигон","Кураж","Арена","Атра","Рио","Парма","Новэл","Пинг-Понг","Фабрика","Год2042","Барда","Берлин","Зона","Долина","Волна","Палуба9","Бобруйск","Жаворонки","Магистраль","Лагерь","Иран","Кунгур","Гардер","Мосты","Эспланада","Эдинбург","Дуалити","СтолицаЛьвов","Губаха","Брест","Кёльн","Простор","СтолицаВолков","Ферма","Плато","Дуэль","Бумбокс","Каньон","Ущелье","ФортНокс","Стадион","Станция","Магадан","Тишина","Сандал","Шоссе","Серпухов","Чернобыль","Будущее","Песочница"],
    "en": ["Osa","Tribute","Solikamsk","Kolhoz","Hill","Subway","RedAlert","BearsCapital","Dusseldorf","MonteCarlo","Cross","Desert","Massacre","Forest","Island","Molotov","Siege","Pass","Gravity","Polygon","Courage","Arena","Atra","Rio","Parma","Novel","Ping-Pong","Factory","Year2042","Barda","Berlin","Zone","Valley","Wave","Deck-9","Bobruisk","Skylark","Magistral","Camp","Iran","Kungur","Garder","Bridges","Esplanade","Edinburgh","Duality","LionsCapital","Gubakha","Brest","Cologne","Scope","WolvesCapital","Farm","Highland","Duel","Boombox","Canyon","Rift","FortKnox","Stadium","Station","Magadan","Silence","Sandal","Highways","Serpuhov","Chernobyl","Future","Sandbox"],
    "de": ["Osa","Tribut","Solikamsk","Kolchose","Erdhügel","U-Bahn","RedAlert","HauptstadtderBären","Düsseldorf","Monte-Carlo","Kreuzung","Wüste","Massaker","Forest","Insel","Molotow","Belagerung","Pass","Gravity","Schießplatz","Courage","Arena","Atra","Rio","Parma","Novel","Ping-Pong","Fabrik","Jahr2042","Barda","Berlin","Zone","Doline","Welle","Deck9","Bobruisk","Lerchen","Magistrale","Lager","Iran","Kungur","Garder","Brücken","Esplanade","Edinburgh","Duality","HauptstadtderLöwen","Gubacha","Brest","Köln","Weite","HauptstadtderWölfe","Bauernhof","Hochebene","Duell","Boombox","Canyon","Kluft","FortKnox","Stadion","Station","Magadan","Stille","Sandal","Highway","Serpuchow","Tschernobyl","Zukunft","Sandkasten"],
    "pl": ["Osa","Trybut","Solikamsk","Kołchoz","Wzgórze","Metro","RedAlert","StolicaNiedźwiedzi","Düsseldorf","MonteCarlo","Krzyż","Pustynia","Rzeź","Las","Wyspa","Mołotow","Oblężenie","Przełęcz","Grawitacja","Poligon","Odwaga","Arena","Atra","Rio","Parma","Novel","Ping-Pong","Fabryka","Rok2042","Barda","Berlin","Strefa","Dolina","Fala","Pokład9","Bobruisk","Skylark","Magistrala","Obóz","Iran","Kungur","Garder","Mosty","Esplanada","Edynburg","Dwoistość","StolicaLwów","Gubakha","Brest","Kolonia","Scope","StolicaWilków","Farma","Góry","Pojedynek","Boombox","Kanion","Wyłom","FortKnox","Stadion","Stacja","Magadan","Cisza","Sandał","Autostrady","Serpuhov","Czarnobyl","Przyszłość","Sandbox"],
};
var mapName = {
    "ru": ["Карта", "Карта (будущее)"],
    "en": ["Map", "Map (future)"],
    "de": ["Karte", "Karte (zukunft)"],
    "pl": ["Mapa", "Mapa (przyszłość)"],
};
var futureButtonName = {
    "ru": ["В будущее", "Назад"],
    "en": ["To the future", "Back"],
    "de": ["In der Zukunft", "Zurück"],
    "pl": ["W przyszłości", "Wróć"],
};
var oldZones = {};
var newZones = {};
var oldPoints = {};
var newPoints = {};
var wolvesPoints = null;
var bearsPoints = null;
var lionsPoints = null;
var future = false;
var initialized = false;
var lang = "ru";

function toggle() {
    if (!initialized) {
        init();
        return;
    }
    future = !future;
    var zones = future ? newZones : oldZones;
    $(".map-territory").each(function() {
        var obj = $(this);
        var name = obj.text().replace(/\s/g, '');
        obj.removeClass("bears");
        obj.removeClass("lions");
        obj.removeClass("wolves");
        if (zones[name] == 0) {
            obj.addClass("bears");
        } else if (zones[name] == 1) {
            obj.addClass("lions");
        } else if (zones[name] == 2) {
            obj.addClass("wolves");
        }
    });
    $(".screen-switcher > .button-tab.active").html(future ? mapName[lang][1] : mapName[lang][0]);
    $(".screen-map").css("background-image", future ? "none" : "url(/assets/images/bg_map.jpg)");
    $(".screen-map").css("background-color", future ? "#000000" : "#63635b");

    var points = future ? newPoints : oldPoints;
    $(".faction-points > .faction.wolves").parent().find("span").html(points["wolves"] + '<span class="max"> / 300');
    $(".faction-points > .faction.bears").parent().find("span").html(points["bears"] + '<span class="max"> / 300');
    $(".faction-points > .faction.lions").parent().find("span").html(points["lions"] + '<span class="max"> / 300');

    $("#futureButton").html(futureButtonName[lang][future ? 1 : 0]);
}

$('body').on('click', '.button-tab', function (){
    if ($(this).is(':last-child') && !$(this).hasClass("active")) {
        initialized = false;
        preInit();
    }
});

if (getLastUrlPart() == "map") {
    $(document).ready(preInit);
}

function getLastUrlPart() {
    var url = window.location.href;
    var parts = url.split("/");
    return (url.lastIndexOf('/') !== url.length - 1
       ? parts[parts.length - 1]
       : parts[parts.length - 2]);
}

function realPreInit() {
    if (getLastUrlPart() != "map") {
        return;
    }
    $("nav > .screen-switcher").prepend("<a id='futureButton' class='button-tab' href='javascript:void(0)'></a>");
    $("#futureButton").html(futureButtonName[lang][0]);
    $("#futureButton").click(toggle);
}

function preInit() {
    if ($('nav > .screen-switcher').is(':visible')) {
        setTimeout(realPreInit, 3000);
    } else {
        setTimeout(preInit, 50);
    }
}

function init() {
    lang = $("html").attr("lang");

    $.ajax({
        'method': 'GET',
        'url': 'https://war.tankionline.com/api/data',
        'success': function(data) {
            var json = JSON.parse(data).response;
            var zones = {};
            var attacks = [json.attackFractionA, json.attackFractionB, json.attackFractionC];
            var defends = [json.defendFractionA, json.defendFractionB, json.defendFractionC];
            var i;
            for (i = 0; i < attacks.length; i++) {
                Object.keys(attacks[i]).forEach(function(key) {
                    if (!(key in zones)) {
                        var obj = [0, 0, 0];
                        zones[key] = obj;
                    }
                    zones[key][i] += attacks[i][key].countPoints;
                });
            }
            for (i = 0; i < defends.length; i++) {
                Object.keys(defends[i]).forEach(function(key) {
                    if (!(key in zones)) {
                        var obj = [0, 0, 0];
                        zones[key] = obj;
                    }
                    zones[key][i] += defends[i][key].countPoints;
                });
            }
            wolvesPoints = $(".faction-points > .faction.wolves").parent().find("span");
            bearsPoints = $(".faction-points > .faction.bears").parent().find("span");
            lionsPoints = $(".faction-points > .faction.lions").parent().find("span");
            oldPoints["wolves"] = parseInt(wolvesPoints.html().split('<span class="max">')[0]);
            oldPoints["bears"] = parseInt(bearsPoints.html().split('<span class="max">')[0]);
            oldPoints["lions"] = parseInt(lionsPoints.html().split('<span class="max">')[0]);

            newPoints["wolves"] = 0;
            newPoints["bears"] = 0;
            newPoints["lions"] = 0;

            console.log(wolvesPoints.html().split('<span class="max">'));

            $(".map-territory").each(function() {
                var obj = $(this);

                var name = obj.text().replace(/\s/g, '');
                if (zoneDefs[lang].indexOf(name) == -1) {
                    alert("Зона не найдена: " + name);
                }

                var level = obj.hasClass("level-1") ? 1 : (
                    obj.hasClass("level-2") ? 2 : (
                        obj.hasClass("level-3") ? 3 : -1
                    )
                );
                if (level == -1) {
                    alert("Неизвестный уровень зоны у: " + name);
                }
                var zonePoints = 0;
                if (level == 1) {
                    zonePoints = 1;
                } else if (level == 2) {
                    zonePoints = 3;
                } else if (level == 3) {
                    zonePoints = 5;
                }

                var index = zoneDefs[lang].indexOf(name);
                var points = zones[index + 1];

                if (obj.hasClass("lions")) {
                    oldZones[name] = 1;
                    newPoints["lions"] += zonePoints;
                } else if (obj.hasClass("bears")) {
                    oldZones[name] = 0;
                    newPoints["bears"] += zonePoints;
                } else if (obj.hasClass("wolves")) {
                    oldZones[name] = 2;
                    newPoints["wolves"] += zonePoints;
                }

                if (points[0] > points[1]) {
                    if (points[0] > points[2]) {
                        newZones[name] = 0;
                    } else {
                        newZones[name] = 2;
                    }
                } else {
                    if (points[1] > points[2]) {
                        newZones[name] = 1;
                    } else {
                        newZones[name] = 2;
                    }
                }
            });
            newPoints["bears"] += oldPoints["bears"];
            newPoints["lions"] += oldPoints["lions"];
            newPoints["wolves"] += oldPoints["wolves"];
            initialized = true;
            toggle();
        }
    });
}