DIO-TOOLS

DIO-Tools is a small extension for the browser game Grepolis. (counter, displays, smilies, trade options, changes to the layout)

Per 29-08-2015. Zie de nieuwste versie.

// ==UserScript==
// @name		DIO-TOOLS
// @namespace	DIO
// @version		2.35
// @author		Diony
// @description DIO-Tools is a small extension for the browser game Grepolis. (counter, displays, smilies, trade options, changes to the layout)
// @include		https://de.grepolis.com/game*
// @include		http://*.grepolis.com/game*
// @include		https://*.grepolis.com/game*
// @include		https://*forum.*.grepolis.com/*.php*
// @include		http://diotools.pf-control.de/*
// @require		http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js
// @icon		http://s7.directupload.net/images/140128/vqchpigi.gif
// @icon64		http://diotools.pf-control.de/images/icon_dio_64x64.png
// @copyright	2013+, DIONY
// @grant		GM_info
// @grant		GM_setValue
// @grant		GM_getValue
// @grant		GM_deleteValue
// @grant		GM_xmlhttpRequest
// ==/UserScript==

var version = '2.35';

//if(unsafeWindow.DM) console.dir(unsafeWindow.DM.status('l10n'));
//console.dir(DM.status('templates'));

//http://s7.directupload.net/images/140128/vqchpigi.gif - DIO-Tools-Smiley

//http://de44.grepolis.com/cache/js/libs/jquery-1.10.2.min.js


//console.log(JSON.stringify(DM.getl10n()));

/*******************************************************************************************************************************
 * Changes
 * ----------------------------------------------------------------------------------------------------------------------------
 * | ● ...
 * | ● ...
 * | ● ...
 * | ● ...
 * ----------------------------------------------------------------------------------------------------------------------------
 *******************************************************************************************************************************/

/*******************************************************************************************************************************
 * Bugs / TODOs
 * ----------------------------------------------------------------------------------------------------------------------------
 * | ● Aktivitätsbox für Angriffe blendet nicht aus
 * | ● Smileys verschwinden manchmal? -> bisher nicht reproduzierbar
 * | ● Performanceeinbruch nach dem Switchen des WW-Fensters
 * | ● keine Smileys im Grepoforum mit Safari (fehlendes jQuery)
 * ----------------------------------------------------------------------------------------------------------------------------
 *******************************************************************************************************************************/

/*******************************************************************************************************************************
 * Global stuff
 *******************************************************************************************************************************/
var uw = unsafeWindow || window, $ = uw.jQuery || jQuery, DATA, GM;

// GM-API?
GM = (typeof GM_info === 'object') ? true : false;

// LOAD DATA
if(GM && (uw.location.pathname === "/game/index")){
    var WID = uw.Game.world_id, MID = uw.Game.market_id, AID = uw.Game.alliance_id;

    DATA = { 
        // GLOBAL
        options : JSON.parse(GM_getValue("options", "{}")),

        user : JSON.parse(GM_getValue("dio_user", "{}")),
        count: JSON.parse(GM_getValue("dio_count", "[]")),

        notification : GM_getValue('notification', 0), 

        error: JSON.parse(GM_getValue('error', '{}')),

        spellbox  :	JSON.parse(GM_getValue("spellbox", '{ "top":"23%", "left": "-150%", "show": false }')),
        commandbox: JSON.parse(GM_getValue("commandbox" , '{ "top":55, "left": 250 }')),
        tradebox  :	JSON.parse(GM_getValue("tradebox", '{ "top":55, "left": 450 }')),   

        // WORLD
        townTypes : JSON.parse(GM_getValue(WID + "_townTypes", GM_getValue("town_types", "{}"))),
        sentUnits : JSON.parse(GM_getValue(WID + "_sentUnits", GM_getValue(WID + "_sentUnitsArray", '{ "attack": {}, "support": {} }'))),
        biremes   : JSON.parse(GM_getValue(WID + "_biremes", GM_getValue(WID + "_biri_data", "{}"))),      

        worldWonder : JSON.parse(GM_getValue(WID + "_wonder", '{ "ratio": {}, "storage": {}, "map": {} }')),

        // MARKET
        worldWonderTypes : JSON.parse(GM_getValue(MID + "_wonderTypes", '{}'))
    };

    if(!DATA.worldWonder.map) {
        DATA.worldWonder.map = {};
    }

    // Temporary:
    if(GM_getValue(WID + "_ww_res")){
        DATA.worldWonder.ratio[AID] = parseInt(GM_getValue(WID + "_ratio", -1), 10);
        DATA.worldWonder.storage[AID] = JSON.parse(GM_getValue(WID + "_ww_res", "{}"));

        GM_deleteValue(WID + "_ratio");
        GM_deleteValue(WID + "_ww_res");
    }
    //console.log(DATA.worldWonder);

    GM_deleteValue("movebox");
    GM_deleteValue(WID + "_sentUnitsArray");
    GM_deleteValue(WID + "_biri_data");
    GM_deleteValue("town_types");
    GM_deleteValue('DIO-Notification');
}

// GM: EXPORT FUNCTIONS
uw.saveValueGM = function(name, val){
    setTimeout(function(){
        GM_setValue(name, val);

        // Reload after saving settings
        if(name == "options") {
            window.location.reload();
        }
    }, 0);
};

uw.deleteValueGM = function(name){
    setTimeout(function(){
        GM_deleteValue(name);
    },0, name);
};

uw.chatUserRequest = function(){
    setTimeout(function(){
        GM_xmlhttpRequest({
            method: "GET",
            url: "http://api.relay-chat.de/compteur_js.php?chan="+ (uw.Game.market_id === "de" ? "Grepolis" + uw.Game.market_id.toUpperCase() : "GREPO"),
            onload: function(text){
                $('.nui_main_menu .chat .indicator').get(0).innerHTML = text.response.split("'")[1];
                $('.nui_main_menu .chat .indicator').get(0).style.display = 'block';
            },
            onerror: function(){
                $('.nui_main_menu .chat .indicator').get(0).style.display = 'none';
            }
        }); 
    }, 0);
};

if(typeof exportFunction == 'function'){
    // Firefox > 30
    uw.DATA = cloneInto(DATA, unsafeWindow);
    exportFunction(uw.saveValueGM, unsafeWindow, {defineAs: "saveValueGM"});
    exportFunction(uw.deleteValueGM, unsafeWindow, {defineAs: "deleteValueGM"});
    exportFunction(uw.chatUserRequest, unsafeWindow, {defineAs: "chatUserRequest"});
} else {
    // Firefox < 30, Chrome, Opera, ...
    uw.DATA = DATA; 
}

var time_a, time_b;

// APPEND SCRIPT
function appendScript(){
    //console.log("GM-API: " + gm_bool);
    if(document.getElementsByTagName('body')[0]){
        var dioscript = document.createElement('script');
        dioscript.type ='text/javascript';
        dioscript.id = 'diotools';

        time_a = uw.Timestamp.client();
        dioscript.textContent = DIO_GAME.toString().replace(/uw\./g, "") + "\n DIO_GAME("+ version +", "+ GM +", "+ time_a +", "+ $ +");";
        document.body.appendChild(dioscript);
    } else {
        setTimeout(function(){
            appendScript();
        }, 500);
    }
}

if(location.host === "diotools.pf-control.de"){
    // PAGE
    DIO_PAGE();
} else {
    if((location.pathname !== "/game/index") && GM){
        // FORUM
        DIO_GAME(version); 
    } else {
        // GAME
        appendScript(); 
    }
} 

function DIO_PAGE(){
    if(typeof GM_info == 'object') {
        setTimeout(function() {
            dio_user = JSON.parse(GM_getValue("dio_user", ""));
            console.log(dio_user);
            uw.dio_version = parseFloat(version);
        }, 0);
    } else {
        dio_user = localStorage.getItem("dio_user") || "";

        dio_version = parseFloat(version); 
    }
}
function DIO_FORUM(){
    if($(".editor_textbox_container").get(0)){
        loadSmileys(); 
        changeForumEditorLayout();
        addSmileyBoxForum();
    }
}
function DIO_GAME(version, gm, time_a){
    var MutationObserver = uw.MutationObserver || window.MutationObserver,

        WID, MID, AID, PID, LID,

        dio_sprite = "http://abload.de/img/dio_spritejmqxp.png"; // http://img1.myimg.de/DIOSPRITEe9708.png -> Forbidden!?

    if(uw.location.pathname === "/game/index"){
        WID = uw.Game.world_id; 
        MID = uw.Game.market_id;
        AID = uw.Game.alliance_id;
        PID = uw.Game.player_id;
        LID = uw.Game.locale_lang.split("_")[0]; // LID ="es";

        // World with Artemis ??
        Game.hasArtemis = Game.constants.gods.length == 6;
    }

    // jQuery Stuff:
    $.prototype.reverseList = [].reverse;
    
    $.fn.toggleClick = function() {
        var methods = arguments;    // Store the passed arguments for future reference
        var count = methods.length; // Cache the number of methods 

        // Use return this to maintain jQuery chainability
        // For each element you bind to
        return this.each(function(i, item){
            // Create a local counter for that element
            var index = 0;

            // Bind a click handler to that element
            $(item).on('click', function() {
                // That when called will apply the 'index'th method to that element
                // the index % count means that we constrain our iterator between 0
                // and (count-1)
                return methods[index++ % count].apply(this, arguments);
            });
        });
    };

    // LOAD DATA for Safari:
    if((typeof DATA === 'undefined') && (uw.location.pathname === "/game/index")){

        DATA = { 
            //GLOBAL
            options : JSON.parse(localStorage.getItem("options") || "{}"),

            user : JSON.parse(localStorage.getItem("dio_user") || "{}"),
            count: JSON.parse(localStorage.getItem("dio_count") || "[]"),

            notification : localStorage.getItem('notification') || localStorage.getItem('DIO-Notification') || 0, 

            error: JSON.parse(localStorage.getItem('error') || '{}'),

            spellbox  :	JSON.parse(localStorage.getItem("spellbox") || '{ "top":"23%", "left": "-150%", "show": false }' ),
            commandbox: JSON.parse(localStorage.getItem("commandbox") || '{ "top":55, "left": 250 }' ),
            tradebox  :	JSON.parse(localStorage.getItem("tradebox") || '{ "top":55, "left": 450 }' ),   

            //WORLD
            townTypes : JSON.parse(localStorage.getItem(WID + "_townTypes") || localStorage.getItem("town_types") || "{}" ),
            sentUnits : JSON.parse(localStorage.getItem(WID + "_sentUnits") || localStorage.getItem(WID + "_sentUnitsArray") || '{ "attack": {}, "support": {} }' ),
            biremes   : JSON.parse(localStorage.getItem(WID + "_biremes") || localStorage.getItem(WID + "_biri_data") || "{}" ),      

            worldWonder : JSON.parse(localStorage.getItem(WID + "_wonder") || '{ "ratio": {}, "storage": {}, "map": {} }'),

            // MARKET
            worldWonderTypes : JSON.parse(localStorage.getItem(MID + "_wonderTypes") || '{}')
        };

        if(!DATA.worldWonder.map) {
            DATA.worldWonder.map = {};
        }

        // Temporary:
        if(GM_getValue(WID + "_ww_res")){
            DATA.worldWonder.ratio[AID] = parseInt((localStorage.getItem(WID + "_ratio") || -1), 10);
            DATA.worldWonder.storage[AID] = JSON.parse(localStorage.getItem(WID + "_ww_res") || "{}");

            localStorage.removeItem(WID + "_ratio");
            localStorage.removeItem(WID + "_ww_res");
        }

    }

    function saveValue(name, val){
        if(gm){
            saveValueGM(name, val);
        } else {
            localStorage.setItem(name, val);
        }
    }

    function deleteValue(name){
        if(gm){
            deleteValueGM(name);
        } else {
            localStorage.removeItem(name);
        } 
    }

    /*******************************************************************************************************************************
	* Graphic filters
	*******************************************************************************************************************************/
    if(uw.location.pathname === "/game/index"){
        $('<svg width="0%" height="0%">'+
          '<filter id="GrayScale">'+
          '<feColorMatrix type="matrix" values="0.2126 0.7152 0.0722 0 0 0.2126 0.7152 0.0722 0 0 0.2126 0.7152 0.0722 0 0 0 0 0 1 0">'+
          '</filter>'+
          '<filter id="Sepia">'+
          '<feColorMatrix type="matrix" values="0.343 0.669 0.119 0 0 0.249 0.626 0.130 0 0 0.172 0.334 0.111 0 0 0.000 0.000 0.000 1 0">'+
          '</filter>'+
          '<filter id="Saturation"><feColorMatrix type="saturate" values="0.2"></filter>'+
          '<filter id="Saturation1"><feColorMatrix type="saturate" values="1"></filter>'+
          '<filter id="Saturation2"><feColorMatrix type="saturate" values="2"></filter>'+
          '<filter id="Hue1"><feColorMatrix type="hueRotate" values= "65"></filter>'+
          '<filter id="Hue2"><feColorMatrix type="hueRotate" values="150"></filter>'+
          '<filter id="Hue3"><feColorMatrix type="hueRotate" values="-65"></filter>'+
          '<filter id="Brightness15">'+
          '<feComponentTransfer>'+
          '<feFuncR type="linear" slope="1.5"/><feFuncG type="linear" slope="1.5"/><feFuncB type="linear" slope="1.5"/>'+
          '</feComponentTransfer>'+
          '</filter>'+
          '<filter id="Brightness12">'+
          '<feComponentTransfer>'+
          '<feFuncR type="linear" slope="1.2"/><feFuncG type="linear" slope="1.2"/><feFuncB type="linear" slope="1.2"/>'+
          '</feComponentTransfer>'+
          '</filter>'+
          '<filter id="Brightness11">'+
          '<feComponentTransfer>'+
          '<feFuncR type="linear" slope="1.1"/><feFuncG type="linear" slope="1.1"/><feFuncB type="linear" slope="1.1"/>'+
          '</feComponentTransfer>'+
          '</filter>'+
          '<filter id="Brightness10">'+
          '<feComponentTransfer>'+
          '<feFuncR type="linear" slope="1.0"/><feFuncG type="linear" slope="1.0"/><feFuncB type="linear" slope="1.0"/>'+
          '</feComponentTransfer>'+
          '</filter>'+
          '</svg>').appendTo('#ui_box');
    }

    /*******************************************************************************************************************************
     * Language versions: german, english, french, russian, polish, spanish
     *******************************************************************************************************************************/
    var LANG = {
        de : {
            settings : {
                dsc: "DIO-Tools bietet unter anderem einige Anzeigen, eine Smileyauswahlbox,<br>Handelsoptionen und einige Veränderungen des Layouts.",
                act: "Funktionen der Toolsammlung aktivieren/deaktivieren:",
                prv: "Vorschau einzelner Funktionen:"
            },
            options : {
                bir: [ "Biremenzähler",		"Zählt die jeweiligen Biremen einer Stadt und summiert diese. (Anzeige im Minimap-Bullauge links oben)" ],
                sml: [ "Smileys",			"Erweitert die BBCode-Leiste um eine Smileybox" ],
                str: [ "Einheitenstärke",	"Fügt mehrere Einheitenstärketabellen in verschiedenen Bereichen hinzu" ],
                trd: [ "Handel",			"Erweitert das Handelsfenster um einen Prozentualer Handel, einen Rekrutierungshandel und Limitmarker für Stadtfeste" ],
                cnt: [ "EO-Zähler",			"Zählt die ATT/UT-Anzahl im EO-Fenster (bisher nur bei eigenen Eroberungen)" ],
                way: [ "Laufzeit",			"Zeigt im ATT/UT-Fenster die Laufzeit bei Verbesserter Truppenbewegung an" ],
                wwc: [ "Weltwunder",		"Anteilsrechner & Rohstoffzähler + Vor- & Zurück-Buttons bei fertiggestellten WW's (momentan nicht deaktivierbar!)" ],
                sim: [ "Simulator",			"Anpassung des Simulatorlayouts & permanente Anzeige der Erweiterten Modifikatorbox" ],
                spl: [ "Zauberbox",			"Komprimierte verschiebbare & magnetische Zauberbox (Positionsspeicherung)" ],
                mov: [ "Aktivitätsboxen",	"Verbesserte Anzeige der Handels- und Truppenaktivitätsboxen (Positionsspeicherung)" ],
                pop: [ "Popup",				'Ändert Gunst-Popup' ],
                tsk: [ "Taskleiste",		'Vergrößert die Taskleiste und minimiert das "Tägliche Belohnung"-Fenster beim Start' ],
                irc: [ "Chat",				"Ersetzt den Allianzchat durch einen IRC-Chat" ],
                bbc: [ "DEF-Formular",		"Erweitert die BBCode-Leiste um ein automatisches DEF-Formular" ],
                com: [ "Einheitenvergleich","Fügt Einheitenvergleichstabellen hinzu" ],
                twn: [ "Stadticons",		"Fügt Stadttyp-Icons zur Stadtliste hinzu" ],
                con: [ "Kontextmenu",		'Vertauscht "Stadt selektieren" und "Stadtübersicht" im Kontextmenu'],
                sen: [ "Abgeschickte Einheiten",	'Zeigt im Angriffs-/Unterstützungsfenster abgeschickte Einheiten an'],
                tov: [ "Stadtübersicht",	'Ersetzt die neue Stadtansicht mit der alten Fensteransicht'],
                scr: [ "Mausrad",			'Man kann mit dem Mausrad die Übersichten wechseln'],

                err: [ "Automatische Fehlerberichte senden", "Wenn du diese Option aktivierst, kannst du dabei helfen Fehler zu identifizieren." ],
                her: [ "Eventkarte", "Verkleinerung von Eventkarten (50%)." ]
            },
            labels: {
                uni : "Verfügbare Einheiten",
                con : "Selektieren",
                // Smileys
                std: "Standard", gre: "Grepolis", nat: "Natur", ppl: "Leute", oth: "Sonstige",
                // Defense form
                ttl: "Übersicht: Stadtverteidigung", inf: "Informationen zur Stadt:", dev: "Abweichung",
                det: "Detailierte Landeinheiten", prm: "Premiumboni", sil: "Silberstand", mov: "Truppenbewegungen:",
                // WW
                leg: "WW-Anteil", stg: "Stufe", tot: "Gesamt",
                // Simulator
                str: "Einheitenstärke", los: "Verluste", mod: "ohne Modifikatoreinfluss",
                // Comparison box
                dsc: "Einheitenvergleich", hck: "Schlag", prc: "Stich", dst: "Distanz", sea: "See", att: "Angriff", def: "Verteidigung", spd: "Geschwindigkeit", 
                bty: "Beute (Rohstoffe)", cap: "Transportkapazität", res: "Baukosten (Rohstoffe)", fav: "Gunst", tim: "Bauzeit (s)",
                // Trade
                rat: "Ressourcenverhältnis eines Einheitentyps", shr: "Anteil an der Lagerkapazität der Zielstadt", per: "Prozentualer Handel",
                // Sent units box
                lab: "Abgeschickt",
                improved_movement: "Verbesserte Truppenbewegung"
            },
            buttons: {
                sav: "Speichern", ins: "Einfügen", res: "Zurücksetzen"
            },
        },
        en : {
            settings : {
                dsc: "DIO-Tools offers, among other things, some displays, a smiley box,<br>trade options and some changes to the layout.",
                act: "Activate/deactivate features of the toolset:",
                prv: "Preview of several features:"
            },
            options : {
                bir: [ "Bireme counter",	"Counts the biremes of a city and sums these" ],
                sml: [ "Smilies",			"Extends the bbcode bar by a smiley box" ],
                str: [ "Unit strength",		"Adds unit strength tables in various areas" ],
                trd: [ "Trade",				"Extends the trade window by a percentage trade, a recruitment trade and limit markers for city festivals" ],
                cnt: [ "Conquests",			"Counts the attacks/supports in the conquest window (only own conquests yet)" ],
                way: [ "Troop speed",		"Displays improved troop speed in the attack/support window" ],
                wwc: [ "World wonder",		"Share calculation & resources counter + previous & next buttons on finished world wonders (currently not deactivatable!)" ],
                sim: [ "Simulator",			"Adaptation of the simulator layout & permanent display of the extended modifier box" ],
                spl: [ "Spell box",			"Compressed movable & magnetic spell box (position memory)" ],
                mov: [ "Activity boxes",	"Improved display of trade and troop activity boxes (position memory)" ],
                pop: [ "Popup",				"Changes the favor popup" ],
                tsk: [ "Taskbar",			"Increases the taskbar and minimizes the daily reward window on startup" ],
                irc: [ "Chat",				'Replaced the alliance chat by an irc chat. (FlashPlayer required)' ],
                bbc: [ "Defense form",		"Extends the bbcode bar by an automatic defense form" ],
                com: [ "Unit Comparison",	"Adds unit comparison tables" ],
                twn: [ "Town icons",		"Adds town type icons to the town list" ],
                con: [ "Context menu",		'Swaps "Select town" and "City overview" in the context menu'],
                sen: [ "Sent units",		'Shows sent units in the attack/support window'],
                tov: [ "Town overview",		'Replaces the new town overview with the old window style'],
                scr: [ "Mouse wheel",		'You can change the views with the mouse wheel'],

                err: [ "Send bug reports automatically", "If you activate this option, you can help identify bugs." ],
                her: [ "Event map", "Downsizing of event maps (50%)." ]
            },
            labels: {
                uni : "Available Units",
                con : "Select town",
                // Smileys
                std: "Standard", gre: "Grepolis", nat: "Nature", ppl: "People", oth: "Other",
                // Defense form
                ttl: "Overview: Town defense", inf: "Town information:", dev: "Deviation",
                det: "Detailed land units", prm: "Premium bonuses", sil: "Silver volume", mov: "Troop movements:",
                // WW
                leg: "WW Share", stg: "Stage", tot: "Total",
                // Simulator
                str: "Unit strength", los: "Loss", mod: "without modificator influence",
                // Comparison box
                dsc: "Unit comparison", 
                hck: "Blunt", prc: "Sharp", dst: "Distance", sea: "Sea", 
                att: "Offensive", def: "Defensive", spd: "Speed", bty: "Booty (resources)", 
                cap: "Transport capacity", res: "Costs (resources)", fav: "Favor", tim: "Recruiting time (s)",
                // Trade
                rat: "Resource ratio of an unit type", shr: "Share of the storage capacity of the target city", per: "Percentage trade",
                // Sent units box
                lab: "Sent units",
                improved_movement: "Improved troop movement"
            },
            buttons: {
                sav: "Save", ins: "Insert", res: "Reset"
            },
        },
        ///////////////////////////////////
        // French Translation by eclat49 //
        ///////////////////////////////////
        fr : {  
            settings: {  
                dsc: "DIO-Tools offres certains écrans, une boîte de smiley, les options <br>commerciales, des changements à la mise en page et d'autres choses.",  
                act: "Activation/Désactivation des fonctions:",  
                prv: "Aperçu des fonctions séparées:"
            },  
            options : {
                bir: [ "Compteur de birèmes ",	"Totalise l'ensemble des birèmes présentent en villes et les résume. (Remplace la mini carte dans le cadran)" ],  
                sml: [ "Smileys",				"Rajoutes une boite de smilies à la boite de bbcode" ],  
                str: [ "Force unitaire",		"Ajoutes des tableaux de force unitaire dans les différentes armes" ],  
                trd: [ "Commerce",				"Ajout d'une option par pourcentage, par troupes pour le commerce, ainsi qu'un affichage des limites pour les festivals" ],  
                cnt: [ "Compteur conquête",		"Comptabilise le nombre d'attaque et de soutien dans la fenêtre de conquête (valable que pour ses propre conquêtes)" ],  
                way: [ "Vitesse des troupes ",	"Rajoutes le temps de trajet avec le bonus accélération" ],  
                wwc: [ "Merveille du monde",	"Compteur de ressource et calcul d'envoi + bouton précédent et suivant sur les merveilles finies(ne peut être désactivé pour le moment)" ],  
                sim: [ "Simulateur",			"Modification de la présentation du simulateur et affichage permanent des options premium" ],  
                spl: [ "Boîte de magie",		"Boîte de sort cliquable et positionnable" ],  
                mov: [ "Boîte d'activité",		"Présentation améliorée du commerce et des mouvement de troupes (mémoire de position)" ],  
                pop: [ "Popup",					'Change la popup de faveur' ],  
                tsk: [ "Barre de tâches ",		"La barre de tâches augmente et minimise le fenêtre de bonus journalier" ],  
                irc: [ "Chat",					"Remplace le chat de l'alliance à travers un chat IRC. (FlashPlayer requis)" ],  
                bbc: [ "Formulaire de défense",	"Ajout d'un bouton dans la barre BBCode pour un formulaire de défense automatique" ],  
                com: [ "Comparaison des unités","Ajoutes des tableaux de comparaison des unités" ],  
                twn: [ "Icônes des villes",		"Ajoutes desicônes de type de ville à la liste de ville" ],  
                con: [ "Menu contextuel",		'Swaps "Sélectionner ville" et "Aperçu de la ville" dans le menu contextuel'],
                sen: [ "Unités envoyées",		'Affiche unités envoyées dans la fenêtre attaque/support'],
                tov: [ "Aperçu de ville",		"Remplace la nouvelle aperçu de la ville avec l'ancien style de fenêtre"],
                scr: [ "Molette de la souris",	'Avec la molette de la souris vous pouvez changer les vues'],

                err: [ "Envoyer des rapports de bogues automatiquement", "Si vous activez cette option, vous pouvez aider à identifier les bugs." ]
            },
            labels: {
                uni : "Unités disponibles",
                con : "Sélectionner",
                // Smileys
                std: "Standard", gre: "Grepolis", nat: "Nature", ppl: "Gens", oth: "Autres",
                // Defense form
                ttl: "Aperçu: Défense de ville", inf: "Renseignements sur la ville:", dev: "Différence",
                det: "Unités terrestres détaillées", prm: "Bonus premium", sil: "Remplissage de la grotte", mov: "Mouvements de troupes:",  
                // WW
                leg: "Participation", stg: "Niveau", tot: "Total",
                // Simulator
                str: "Force unitaire", los: "Pertes", mod: "sans influence de modificateur",
                // Comparison box
                dsc: "Comparaison des unités", hck: "Contond.", prc: "Blanche", dst: "Jet", sea: "Navale", att: "Attaque", def: "Défense", spd: "Vitesse",   
                bty: "Butin", cap: "Capacité de transport", res: "Coût de construction", fav: "Faveur", tim: "Temps de construction (s)",
                // Trade
                rat: "Ratio des ressources d'un type d'unité", shr: "Part de la capacité de stockage de la ville cible", per: "Commerce de pourcentage",
                // Sent units box
                lab: "Envoyée",
                improved_movement: "Mouvement des troupes amélioré"
            },
            buttons: {
                sav: "Sauver", ins: "Insertion", res: "Remettre"
            },
        },
        ///////////////////////////////////
        // Russian Translation by MrBobr //
        ///////////////////////////////////
        ru : {
            settings : {
                dsc: "DIO-Tools изменяет некоторые окна, добавляет новые смайлы, отчёты,<br>улучшеные варианты торговли и другие функции.",
                act: "Включение/выключение функций:",
                prv: "Примеры внесённых изменений:"
            },
            options : {
                bir: [ "Счётчик бирем",		"Показывает число бирем во всех городах" ],
                sml: [ "Смайлы",			"Добавляет кнопку для вставки смайлов в сообщения" ],
                str: [ "Сила отряда",		"Добавляет таблицу общей силы отряда в некоторых окнах" ],
                trd: [ "Торговля",	        "Добавляет маркеры и отправку недостающих ресурсов, необходимых для фестиваля. Инструменты для долевой торговли" ],
                cnt: [ "Завоевания",	    "Отображение общего числа атак/подкреплений в окне завоевания города (only own conquests yet)" ],
                way: [ "30% ускорение",		"Отображает примерное время движения отряда с 30% бонусом" ],
                wwc: [ "Чудо света",	    "Share calculation & resources counter + previous & next buttons on finished world wonders (currently not deactivatable!)" ],
                sim: [ "Симулятор",		    "Изменение интерфейса симулятора, добавление новых функций" ],
                spl: [ "Заклинания",		"Изменяет положение окна заклинаний" ],
                mov: [ "Перемещения",		"Показывает окна пересылки ресурсов и перемещения войск" ],
                pop: [ "Благосклонность",	"Отображение окна с уровнем благосклонности богов" ],
                tsk: [ "Таскбар",			"Увеличение ширины таскбара и сворачивание окна ежедневной награды при входе в игру" ],
                irc: [ "Чат",				'Замена чата игры на irc-чат' ],
                bbc: [ "Форма обороны",		"Добавляет кнопку для вставки в сообщение отчёта о городе" ], // Beschreibung passt nicht ganz
                com: [ "Сравнение юнитов",	"Добавляет окно сравнения юнитов" ],
                twn: [ "Типы городов",		"Добавляет иконку к городу в списке" ],
                //con: [ "Context menu",	'Swaps "Select town" and "City overview" in the context menu'],
                //sen: [ "Sent units",		'Shows sent units in the attack/support window'],
                tov: [ "Обзор Город",		'Заменяет новый обзор города с старом стиле окна'],  // ?
                scr: [ "Колесо мыши",		'С помощью колеса мыши вы можете изменить взгляды'], // ? 

                err: [ "Отправить сообщения об ошибках автоматически", "Если вы включите эту опцию, вы можете помочь идентифицировать ошибки"]
            },

            labels: {
                uni : "Доступные войска",
                con : "выбирать",
                // Smileys
                std: "", gre: "", nat: "", ppl: "", oth: "",
                // Defense form
                ttl: "Обзор: Отчёт о городе", inf: "Информация о войсках и постройках:", dev: "Отклонение",
                det: "Детальный отчёт",   prm: "Премиум-бонусы", sil: "Серебро в пещере", mov: "Перемещения",
                // WW
                leg: "", stg: "", tot: "",
                // Simulator
                str: "Сила войск", los: "Потери", mod: "без учёта заклинаний, бонусов, исследований",
                // Comparison box
                dsc: "Сравнение юнитов", hck: "Ударное", prc: "Колющее", dst: "Дальнего боя", sea: "Морские", att: "Атака", def: "Защита", spd: "Скорость", 
                bty: "Добыча (ресурсы)", cap: "Вместимость транспортов", res: "Стоимость (ресурсы)", fav: "Благосклонность", tim: "Время найма (с)",
                // Trade
                rat: "", shr: "", per: "",
                // Sent units box
                lab: "Отправлено",
                improved_movement: "Улучшенная перемещение войск"
            },

            buttons: {
                sav: "Сохраниить", ins: "Вставка", res: "Сброс"
            },
        },
        ////////////////////////////////
        // Polish Translation by anpu //
        ////////////////////////////////
        pl : {
            settings: {
                dsc: "DIO-Tools oferuje (między innymi) poprawione widoki, nowe uśmieszki,<br>opcje handlu i zmiany w wyglądzie.",
                act: "Włącz/wyłącz funkcje skryptu:",
                prv: "podgląd poszczególnych opcji:"
            },
            options : {
                bir: [ "Licznik birem",		"Zlicza i sumuje biremy z miast" ],
                sml: [ "Emotki",			"Dodaje dodatkowe (zielone) emotikonki" ],
                str: [ "Siła jednostek",	"dodaje tabelki z siłą jednostek w różnych miejscach gry" ],
                trd: [ "Handel",			"Rozszerza okno handlu o handel procentowy, proporcje surowców wg jednostek, dodaje znaczniki dla festynów" ],
                cnt: [ "Podboje",			"Zlicza wsparcia/ataki w oknie podboju (tylko własne podboje)" ],
                way: [ "Prędkość wojsk",	"Wyświetla dodatkowo czas jednostek dla bonusu przyspieszone ruchy wojsk" ],
                wwc: [ "Cuda Świata",		"Liczy udział w budowie oraz ilość wysłanych surowców na budowę Cudu Świata oraz dodaje przyciski do szybkiego przełączania między cudami (obecnie nie możliwe do wyłączenia)" ],
                sim: [ "Symulator",			"Dostosowanie wyglądu symulatora oraz dodanie szybkich pól wyboru" ],
                spl: [ "Ramka czarów",		"Kompaktowa pływająca ramka z czarami (można umieścić w dowolnym miejscu ekranu. Zapamiętuje położenie.)" ],
                mov: [ "Ramki aktywności",	"Ulepszony podgląd ruchów wojsk i handlu (można umieścić w dowolnym miejscu ekranu. Zapamiętuje położenie.)" ],
                pop: [ "Łaski",				"Zmienia wygląd ramki informacyjnej o ilości produkowanych łask" ],
                tsk: [ "Pasek skrótów",		"Powiększa pasek skrótów i minimalizuje okienko z bonusem dziennym" ],
                irc: [ "Czat",				'Zastępuje standardowy Chat chatem IRC (wymagany FlashPlayer)' ],
                bbc: [ "Raportów obronnych","Rozszerza pasek skrótów BBcode o generator raportów obronnych" ],
                com: [ "Porównianie",		"Dodaje tabelki z porównaniem jednostek" ],
                twn: [ "Oznaczanie miast",	"Możliwość oznaczania ikonami miast na liście" ],
                con: [ "menu kontekstowe",	'Zamiemia miejcami przycisk "wybierz miasto" z przyciskiem "podgląd miasta" po kliknięciu miasta na mapie'],
                sen: [ "Wysłane jednostki",	'Pokaż wysłane jednostki w oknie wysyłania ataków/wsparć'],
                tov: [ "Podgląd miasta",	'Zastępuje nowy podgląd miasta starym'],
                scr: [ "Zoom",				'Możesz zmienić poziom przybliżenia mapy kółkiem myszy'],

                err: [ "Automatycznie wysyłać raporty o błędach", "Jeśli włączysz tę opcję, możesz pomóc zidentyfikować błędy"]

            },
            labels: {
                uni : "Dostępne jednostki",
                con : "Wybierz miasto",
                // Smileys
                std: "Standard" /* "Standardowe" */, gre: "Grepolis", nat: "Przyroda", ppl: "Ludzie", oth: "Inne",
                // Defense form
                ttl: "Podgląd: Obrona miasta", inf: "Informacje o mieście:", dev: "Ochyłka",
                det: "jednostki lądowe",  prm: "opcje Premium", sil: "Ilość srebra", mov: "Ruchy wojsk",
                // WW
                leg: "Udział w Cudzie", stg: "Poziom", tot: "Łącznie",
                // Simulator
                str: "Siła jednostek", los: "Straty", mod: "bez modyfikatorów",
                // Comparison box
                dsc: "Porównianie jednostek", hck: "Obuchowa", prc: "Tnąca", dst: "Dystansowa", sea: "Morskie", att: "Offensywne", def: "Defensywne", spd: "Prędkość", 
                bty: "Łup (surowce)", cap: "Pojemność transportu", res: "Koszta (surowce)", fav: "Łaski", tim: "Czas rekrutacji (s)",
                // Trade
                rat: "Stosunek surowców dla wybranej jednostki", shr: "procent zapełnienia magazynu w docelowym mieście", per: "Handel procentowy",
                // Sent units box
                lab: "Wysłane jednostki",
                improved_movement: "Przyspieszone ruchy wojsk‎"
            },
            buttons: {
                sav: "Zapisz", ins: "Wstaw", res: "Anuluj"
            },
        },
        ////////////////////////////////////
        // Dutch Translation by MusicVibe //
        ////////////////////////////////////
        nl : {
            settings : {
                dsc: "DIO-Tools bied onder andere een aantal displays, een smiley box, uitgebreide handels optiesen veranderingen aan de layout.",
                act: "Activeer/Deavtiveer functies van de toolset:",
                prv: "voorbeeld van een aantal functies:"
            },
            options : {
                bir: [ "Bireem teller",			"Telt het aantal biremen van een stad en telt ze bij elkaar op" ],
                sml: [ "smileys",				"Voegt een extra BBvode knop toe die een aantal smileys" ],
                str: [ "Eenheden sterkte",		"voegt een aantal tabellen toe die eenheden sterkte weergeven" ],
                trd: [ "Handel",				"Breid het handel scherm uit met een percentage trade, recruitment trade en markers voor stad feesten" ],
                cnt: [ "Veroveringen",			"Telt het aantal inkomende aanvallen/ondersteuningen in het veroveringsscherm" ],
                way: [ "Eenheden snelheid",		"Laat de versnelde eenheden snelheid zien in het aanval/ondersteuning scherm" ],
                wwc: [ "Wereld wonder",			"Aandeel berekening, grondstoffen teller, Vorige en Volgende knoppen bij voltooide wereld wonderen" ],
                sim: [ "Simulator",				"Aanpassing van de simulator layout en permanent uitgeklapte gevechtsbonussen" ],
                spl: [ "Spreuken scherm",		"Ingekorte, verplaatsbare spreuken scherm" ],
                mov: [ "Activiteiten scherm",	"Verbeterde weergave van handel en troepen bewegingen" ],
                pop: [ "Popup",					"Verandert de gunsten popup" ],
                tsk: [ "Taakbalk",				"Breid de taakbalk uit en minimaliseerd het dagelijkse beloning scherm als je inlogt" ],
                irc: [ "Chat",					'Vervang the alliantie chat met een irc chat. (FlashPlayer vereist)' ],
                bbc: [ "Verdedigings formulier","Een extra BBcode knop die een overzicht genereert van de verdediging van je stad" ],
                com: [ "Eenheden vergelijking",	"Voegt eenheden vergelijking schermen toe" ],
                twn: [ "Stad iconen",			"Voegt stad iconen toe aan de stedenlijst" ],
                con: [ "Context menu",			'Ruilt "Selecteer stad" en "Stadsoverzicht" in het context menu'],
                sen: [ "Verstuurde eenheden",	'Weergeeft verstuurde eenheden in de aanval/ondersteuning schermen'],
                tov: [ "Stadsoverzicht",		'verruild het nieuwe stadsoverzicht met het stadsoverzicht uit de oude stijl'],
                scr: [ "Muis wiel",				'Je kunt de weergave veranderen door met je muis wiel te scrollen'],
                err: [ "Verstuur bug reports automatisch", "Hiermee help je het identificeren van bugs." ],
                her: [ "Trojaanse verovering", 	"verkleining van de Trojaanse veroveringen kaart." ]
            },
            labels: {
                uni : "Beschikbare eenheden",
                con : "Selecteer stad",
                // Smileys
                std: "Standaard", gre: "Grepolis", nat: "Natuur", ppl: "Mensen", oth: "Overig",
                // Defense form
                ttl: "Overzicht: Stad verdediging", inf: "Stad informatie:", dev: "Afwijking",
                det: "Gedetaileerde land eenheden", prm: "Premium bonussen", sil: "Hoeveelheid zilver", mov: "Troepen verplaatsingen:",
                // WW
                leg: "WW Aandeel", stg: "Level", tot: "Totaal",
                // Simulator
                str: "Eenheden sterkte", los: "Verlies", mod: "Zonder modificatie invloed",
                // Comparison box
                dsc: "Eenheden vergelijking", 
                hck: "Slag", prc: "Steek", dst: "Afstand", sea: "Zee", 
                att: "Offensief", def: "Defensief", spd: "Snelheid", bty: "Buit (grondstoffen)", 
                cap: "Transport capaceit", res: "Kosten (grondstoffen)", fav: "Gunst", tim: "Bouwtijd (s)",
                // Trade
                rat: "Grondstoffen ratio van een bepaalde eenheid", shr: "Gedeelte van de opslag capaciteit van de ontvangende stad", per: "Percentage handel",
                // Sent units box
                lab: "Verstuurde eenheden",
                improved_movement: "Versnelde troepen beweging"
            },
            buttons: {
                sav: "Opslaan", ins: "Invoegen", res: "Reset"
            },
        },
        //////////////////////////////////////////////
        // Spanish Translation by Juana de Castilla //
        //////////////////////////////////////////////
        es : {
            settings : {
                dsc: "DIO-Tools ofrece, entre otras cosas, varias pantallas, ventana de <br>emoticones, opciones de comercio y algunos cambios en el diseño.",
                act: "Activar/desactivar características de las herramientas:",
                prv: "Vista previa de varias características:"
            },
            options : {
                bir: [ "Contador de birremes",		"Cuenta los birremes de una ciudad y los suma" ],
                sml: [ "Emoticones",				"Código BB para emoticones" ],
                str: [ "Fortaleza de la Unidad",	"Añade tabla de fortalezas de cada unidad en varias zonas" ],
                trd: [ "Comercio",					"Añade en la pestaña de comercio un porcentaje de comercio y reclutamiento y limitadores de Mercado por cada ciudad" ],
                cnt: [ "Conquistas",				"contador de ataques y refuerzos en la pestaña de conquista" ],
                way: [ "Velocidad de tropas",		"Muestra movimiento de tropas mejorado en la ventana de ataque/refuerzo" ],
                wwc: [ "Maravillas",				"Calcula participación & contador de recursos + antes y después teclas de maravillas terminadas (no desactibable ahora!)" ],
                sim: [ "Simulador",					"Adaptación de la ventana del simulador incluyendo recuadro de modificadores" ],
                spl: [ "Ventana de hechizos",		"Ventana deslizante y comprimida de los hechizos (memoria posicional)"],
                mov: [ "Ventana de actividad",		"Mejora las ventanas de comercio y movimiento de tropas (memoria posicional)" ],
                pop: [ "Popup",						"Cambia el popup de favores" ],
                tsk: [ "Barra de tareas",			"aumenta la barra de tareas y minimice la recompensa al aparecer" ],
                irc: [ "Chat",						'Sustituye el chat de la alianza con un irc chat. (require FlashPlayer)' ],
                bbc: [ "Formulario de defensa",		"Añade en la barra de códigos bb un formulario de defensa" ],
                com: [ "Comparación",				"añade ventana de comparación de unidades" ],
                twn: [ "Iconos de la ciudad",		"Añade iconos de tipo de ciudad en el listado de ciudades" ],
                con: [ "menú contextual",			'Cambia "Elegir ciudad" y "vista de la ciudad" en el menú contextual '],
                sen: [ "Unidades enviadas",			'Muestra las unidades enviadas en la ventana de ataque/refuerzos'],
                tov: [ "Información de la ciudad",	'sustituye la vista nueva de ciudad por la ventana antigua'],
                scr: [ "Rueda raton",				'Puede cambiar las vistas con la rueda del raton'],

                err: [ "Enviar informes de errores automáticamente", "Si se activa esta opción, puede ayudar a identificar errores." ]
            },
            labels: {
                uni : "Unidades disponibles",
                con : "Escoger ciudad",
                // Smileys
                std: "Standard", gre: "Grepolis", nat: "Natura", ppl: "Gente", oth: "Otros",
                // Defense form
                ttl: "Vista general: Defensa de la ciudad", inf: "Información de la ciudad:", dev: "Desviación",
                det: "Unidades de tierra detalladas", prm: "Bonos Premium", sil: "Volumen de plata", mov: "Movimientos de tropas:",
                // WW
                leg: "WW cuota", stg: "Nivel", tot: "Total",
                // Simulator
                str: "Fortaleza de la Unidad", los: "Perdida", mod: "sin influencia del modificador",
                // Comparison box
                dsc: "Comparación de Unidades", 
                hck: "Contundente", prc: "Punzante", dst: "Distancia", sea: "Mar",
                att: "Ataque", def: "Defensa", spd: "Velocidad", bty: "Botín (recursos)", 
                cap: "Capacidad de transporte", res: "Costes (recursos)", fav: "Favor", tim: "Tiempo de reclutamiento (s)",
                // Trade
                rat: "Proporción de recursos de un tipo de unidad", shr: "Porcentaje de la capacidad de almacenamiento de la ciudad destino", per: "Porcentaje de comercio",
                // Sent units box
                lab: "Unidades enviadas",
                improved_movement: "Movimiento de tropas mejorados"
            },
            buttons: {
                sav: "Guardar", ins: "Insertar", res: "Reinicio"
            }
        },
        ar : {}
    };

    LANG.ar = LANG.es;

    // Create JSON
    // console.log(JSON.stringify(LANG.en));

    /*******************************************************************************************************************************
     * Settings
     *******************************************************************************************************************************/

    // (De)activation of the features
    var options_def = {
        bir	: true, // Biremes counter
        sml	: true, // Smileys
        str	: true, // Unit strength
        trd	: true, // Trade options
        way	: true, // Troop speed
        cnt	: true, // Attack/support counter
        sim	: true, // Simulator
        spl	: true, // Spell box
        mov	: false,// Activity boxes
        tsk	: true, // Task bar
        irc : true, // IRC-Chat
        pop	: true, // Favor popup
        wwc	: true, // World wonder
        bbc : true, // BBCode bar
        com : true, // Unit comparison
        twn : true, // Town icons
        con : true, // Context menu
        sen : true, // Sent units
        tov : false,// Town overview
        scr : true, // Mausrad,

        err : false,
        her : true	// Thrakische Eroberung
    };
    if(uw.location.pathname === "/game/index"){
        for(var opt in options_def){
            if(options_def.hasOwnProperty(opt)){
                if(DATA.options[opt] == undefined) { 
                    DATA.options[opt] = options_def[opt];
                }
            }
        }
    }

    // Add DIO-Tools to grepo settings
    function settings() {
        var wid = $(".settings-menu").get(0).parentNode.id;

        if(!$("#dio_tools").get(0)){
            $(".settings-menu ul:last").append('<li id="dio_li"><img id="dio_icon" src="http://www.greensmilies.com/smile/smiley_emoticons_smile.gif"></div> <a id="dio_tools" href="#"> DIO-Tools</a></li>');
        }

        $(".settings-link").click(function () {
            $('.section').each(function(){
                $(this).get(0).style.display = "block";
            });
            $('.settings-container').removeClass("dio_overflow");

            $('#dio_bg_medusa').css({ display: "none" });

            if($('#dio_settings').get(0)) { $('#dio_settings').get(0).style.display = "none"; }
        });

        $("#dio_tools").click(function () { 
            if($('.email').get(0)) { $('.settings-container').removeClass("email"); }

            $('.settings-container').addClass("dio_overflow");

            $('#dio_bg_medusa').css({ display: "block" });

            if(!$('#dio_settings').get(0)){
                $('.settings-container').append(
                    '<div id="dio_settings" class="player_settings section"><div id="dio_bg_medusa"></div>'+
                    '<div class="game_header bold"><a href="#" target="_blank" style="color:white">DIO-Tools (v'+ version +')</a></div>'+
                    '<p>'	+ getText("settings", "dsc") + '</p>'+
                    '<p class="bold"><u>'+ getText("settings", "act") + '</u></p>'+
                    '<table width="100%" style=" font-size: 0.8em;"><tr><td width="24%">'+
                    '<div id="bir" class="checkbox_new"><div class="cbx_icon"></div><div class="cbx_caption">'+ getText("options", "bir")[0] +'</div></div><br><br>'+
                    '<div id="sml" class="checkbox_new"><div class="cbx_icon"></div><div class="cbx_caption">'+ getText("options", "sml")[0] +'</div></div><br><br>'+
                    '<div id="str" class="checkbox_new"><div class="cbx_icon"></div><div class="cbx_caption">'+ getText("options", "str")[0] +'</div></div><br><br>'+
                    '<div id="bbc" class="checkbox_new"><div class="cbx_icon"></div><div class="cbx_caption">'+ getText("options", "bbc")[0] +'</div></div><br><br>'+
                    '<div id="con" class="checkbox_new"><div class="cbx_icon"></div><div class="cbx_caption">'+ getText("options", "con")[0] +'</div></div><br><br>'+
                    '</td><td width="21%">'+
                    '<div id="trd" class="checkbox_new"><div class="cbx_icon"></div><div class="cbx_caption">'+ getText("options", "trd")[0] +'</div></div><br><br>'+
                    '<div id="cnt" class="checkbox_new"><div class="cbx_icon"></div><div class="cbx_caption">'+ getText("options", "cnt")[0] +'</div></div><br><br>'+
                    '<div id="way" class="checkbox_new"><div class="cbx_icon"></div><div class="cbx_caption">'+ getText("options", "way")[0] +'</div></div><br><br>'+
                    '<div id="wwc" class="checkbox_new disabled"><div class="cbx_icon"></div><div class="cbx_caption">'+ getText("options", "wwc")[0] +'</div></div><br><br>'+
                    '<div id="sen" class="checkbox_new"><div class="cbx_icon"></div><div class="cbx_caption">'+ getText("options", "sen")[0] +'</div></div><br><br>'+
                    '</td><td width="20%">'+
                    '<div id="sim" class="checkbox_new"><div class="cbx_icon"></div><div class="cbx_caption">'+ getText("options", "sim")[0] +'</div></div><br><br>'+
                    '<div id="spl" class="checkbox_new"><div class="cbx_icon"></div><div class="cbx_caption">'+ getText("options", "spl")[0] +'</div></div><br><br>'+
                    '<div id="tsk" class="checkbox_new"><div class="cbx_icon"></div><div class="cbx_caption">'+ getText("options", "tsk")[0] +'</div></div><br><br>'+
                    '<div id="twn" class="checkbox_new"><div class="cbx_icon"></div><div class="cbx_caption">'+ getText("options", "twn")[0] +'</div></div><br><br>'+
                    '<div id="tov" class="checkbox_new"><div class="cbx_icon"></div><div class="cbx_caption">'+ getText("options", "tov")[0] +'</div></div><br><br>'+
                    '</td><td>'+
                    '<div id="com" class="checkbox_new"><div class="cbx_icon"></div><div class="cbx_caption">'+ getText("options", "com")[0] +'</div></div><br><br>'+
                    '<div id="mov" class="checkbox_new"><div class="cbx_icon"></div><div class="cbx_caption">'+ getText("options", "mov")[0] +'</div></div><br><br>'+
                    '<div id="pop" class="checkbox_new"><div class="cbx_icon"></div><div class="cbx_caption">'+ getText("options", "pop")[0] +'</div></div><br><br>'+
                    '<div id="irc" class="checkbox_new"><div class="cbx_icon"></div><div class="cbx_caption">'+ getText("options", "irc")[0] +'</div></div><br><br>'+
                    '<div id="scr" class="checkbox_new"><div class="cbx_icon"></div><div class="cbx_caption">'+ getText("options", "scr")[0] +'</div></div><br><br>'+
                    '</td></tr><tr><td colspan="4">'+
                    '<div id="err" class="checkbox_new" style="float:left"><div class="cbx_icon"></div><div class="cbx_caption">'+ getText("options", "err")[0] +'</div></div>'+
                    '<div id="her" class="checkbox_new" style="float:left"><div class="cbx_icon"></div><div class="cbx_caption">'+ getText("options", "her")[0] +'</div></div><br><br>'+
                    '</td></tr>'+
                    '</table>'+
                    '<div><a class="button" id="dio_save" href="#">'+
                    '<span class="left"><span class="right"><span class="middle"><small>' + getText("buttons", "sav") + '</small></span></span></span><span></span>'+
                    '</a></div>'+
                    '<div style="position:absolute; left: 495px;top: 40px;"><a href="https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=3EWUQUTMC5VKS" target="_blank">'+
                    '<img alt="Donate" src="' + (LID === "de" ? "http://s7.directupload.net/images/140131/ctahnu2q.png" : "https://www.paypal.com/en_US/i/btn/btn_donate_LG.gif") + '"></a></div>'+
                    //'<p class="bold"><u>'+ getText("settings", "prv") + '</u></p>'+
                    '<br /><table><tr>'+
                    '<td><img id="bi_img" src="http://i.imgur.com/94m7Gg8.png"></td>'+
                    '<td><img id="sm_img" src="http://i.imgur.com/Y3BsENb.png"></td>'+
                    '<td><img id="un_img" src="http://i.imgur.com/LXkSxsS.png"></td>'+
                    '</tr></table></div></div>');

                $('.checkbox_new .cbx_caption').css({
                    whiteSpace: 'nowrap',
                    marginRight: '10px'
                });

                // Thrakische Eroberung
                if(!$('#happening_large_icon.hercules2014').get(0)){
                    $('#her').css({ display: "none" });
                }

                $("#bi_img").tooltip(getText("options", "bir")[0]); $("#sm_img").tooltip(getText("options", "sml")[0]); $("#un_img").tooltip(getText("options", "str")[0]);

                $("#bir").tooltip(getText("options", "bir")[1]); $("#sml").tooltip(getText("options", "sml")[1] + "<br><br><img src='http://666kb.com/i/ckajscggscw4s2u60.gif'>");
                $("#str").tooltip(getText("options", "str")[1]); $("#bbc").tooltip(getText("options", "bbc")[1]);
                $("#con").tooltip(getText("options", "con")[1]);

                $("#trd").tooltip(getText("options", "trd")[1]); $("#cnt").tooltip(getText("options", "cnt")[1]); $("#way").tooltip(getText("options", "way")[1]); 
                $("#wwc").tooltip(getText("options", "wwc")[1]); $("#sen").tooltip(getText("options", "sen")[1]);

                $("#sim").tooltip(getText("options", "sim")[1]); $("#spl").tooltip(getText("options", "spl")[1]); $("#mov").tooltip(getText("options", "mov")[1]); 
                $("#com").tooltip(getText("options", "com")[1]); $("#tov").tooltip(getText("options", "tov")[1]);

                $("#pop").tooltip(getText("options", "pop")[1]); $("#tsk").tooltip(getText("options", "tsk")[1]); $("#irc").tooltip(getText("options", "irc")[1]); 
                $("#twn").tooltip(getText("options", "twn")[1]); $("#scr").tooltip(getText("options", "scr")[1]);

                $("#err").tooltip(getText("options", "err")[1]); $("#her").tooltip(getText("options", "her")[1]);

                if(!uw.Layout.wnd.TYPE_TOWNINDEX){
                    $('#tov').addClass("disabled");
                    $('#tov .cbx_caption').get(0).style.color = "red";
                    $("#tov").tooltip('<span style="color:red">This feature was unfortunately prevented by the Grepolis developers on purpose. They call it "code cleanup". Sorry...</span>');
                }

                $("#dio_settings .checkbox_new").click(function () {
                    $(this).toggleClass("checked");
                });
                for(var e in DATA.options) {
                    if(DATA.options.hasOwnProperty(e)){
                        if (DATA.options[e] == true) {
                            $("#" + e).addClass("checked");
                        }
                    }
                }

                $('#dio_save').click(function(){
                    $('#dio_settings .checkbox_new').each(function(){
                        var act = false;
                        if ($("#" + this.id).hasClass("checked")) {
                            act = true;
                        }
                        DATA.options[this.id] = act;
                    });
                    saveValue("options", JSON.stringify(DATA.options));
                });
            }
            $('.section').each(function(){
                $(this).get(0).style.display = "none";
            });
            $('#dio_settings').get(0).style.display = "block";
        });  
    }


    function addSettingsButton(){
        $('<div class="btn_settings circle_button dio_settings"><div class="dio_icon js-caption"></div></div>').appendTo(".gods_area");
        $('.dio_settings').css({
            top: '95px',
            right: '103px',
            zIndex: '10'
        });
        $('.dio_settings .dio_icon').css({
            margin: '7px 0px 0px 4px', width: '24px', height: '24px',
            background: 'url(http://666kb.com/i/cifvfsu3e2sdiipn0.gif) no-repeat 0px 0px',
            backgroundSize: "100%"
        });
        $('.dio_settings').on('mouseup', function(){
            $('.dio_icon').get(0).style.marginTop = "7px";
        });
        $('.dio_settings').on('mousedown', function(){
            $('.dio_icon').get(0).style.marginTop = "8px";
        });
        $('.dio_settings').tooltip("DIO-Tools: " + DM.getl10n("layout", "config_buttons").settings);

        $('.dio_settings').click(function(){
            clickDioSettings();
        });   
    }

    var diosettings = false;
    function clickDioSettings(){
        if(!uw.GPWindowMgr.getOpenFirst(uw.Layout.wnd.TYPE_PLAYER_SETTINGS)){
            diosettings = true;
        }
        uw.Layout.wnd.Create(uw.GPWindowMgr.TYPE_PLAYER_SETTINGS,'Settings');
    }


    // Forum: Choose language
    if(!(uw.location.pathname === "/game/index")){
        LID = uw.location.host.split(".")[1];
    }

    // Translation GET
    function getText(category, name){
        var txt = "???";
        if(LANG[LID]){
            if(LANG[LID][category]){
                if(LANG[LID][category][name]){
                    txt = LANG[LID][category][name];
                } else { if(LANG.en[category]){ if(LANG.en[category][name]){
                    txt = LANG.en[category][name];
                }}}
            } else { 
                if(LANG.en[category]){ if(LANG.en[category][name]){
                    txt = LANG.en[category][name];
                }}
            }
        } else {
            if(LANG.en[category]){ if(LANG.en[category][name]){
                txt = LANG.en[category][name];
            }}
        }
        return txt;
    }

    var exc = false, sum = 0, ch = ["FBADAF", "IGCCJB"], alpha = 'ABCDEFGHIJ';

    function a(){
        var pA = PID.toString(), pB = "";

        for(var c in pA){ if(pA.hasOwnProperty(c)){ pB += alpha[pA[parseInt(c, 10)]];}}

        sum = 0;
        for(var b in ch){
            if(ch.hasOwnProperty(b)){
                if(!(pB === ch[b])){exc = true;} else {exc = false; return;}
                for(var s in ch[b]){if(ch[b].hasOwnProperty(s)){sum += alpha.indexOf(ch[b][s]); }}
            }
        }
    }

    var autoTownTypes, manuTownTypes, population, sentUnitsArray, biriArray, spellbox, commandbox, tradebox, wonder, wonderTypes;


    function setStyle(){
        // Settings
        $('<style type="text/css">'+
          '#dio_bg_medusa { background:url('+ dio_sprite +') -160px -43px no-repeat; height: 510px; width: 260px; right: -10px; z-index: -1; position: absolute;} '+
          '.dio_overflow  { overflow: hidden; } '+
          '#dio_icon  { width:15px; vertical-align:middle; margin-top:-2px; } '+
          '#quackicon { width:15px !important; vertical-align:middle !important; margin-top:-2px; height:12px !important; } '+
          '</style>').appendTo('head');

        // Tutorial-Quest Container
        $('<style type="text/css"> #tutorial_quest_container { top: 130px } </style>').appendTo('head');

        // Ranking
        $('<style type="text/css"> .wonder_ranking { display: none; } </style>').appendTo('head');

        // Velerios
        $('<style id="dio_velerios" type="text/css"> #ph_trader_image { background-image: url(http://s14.directupload.net/images/140826/mh8k8nyw.jpg); } </style>').appendTo('head');
        // http://s7.directupload.net/images/140826/bgqlsdrf.jpg

        // Specific player wishes
        if(PID == 1212083){
            $('<style id="dio_whishes" type="text/css"> #world_end_info { display: none; } </style>').appendTo('head');
        }

    }
    if(uw.location.pathname === "/game/index"){
        setStyle();
    }

    function loadFeatures(){
        if(typeof(ITowns) !== "undefined"){

            autoTownTypes = {}; manuTownTypes = DATA.townTypes; population	= {};

            sentUnitsArray = DATA.sentUnits; biriArray	= DATA.biremes;

            spellbox	= DATA.spellbox; commandbox	= DATA.commandbox; tradebox	= DATA.tradebox;

            wonder		= DATA.worldWonder; wonderTypes = DATA.worldWonderTypes;


            var DIO_USER = { 'name': uw.Game.player_name, 'market': MID };
            saveValue("dio_user", JSON.stringify(DIO_USER));

            $.Observer(uw.GameEvents.game.load).subscribe('DIO_START', function(e,data){
                // check if city overview window exists
                if(!uw.Layout.wnd.TYPE_TOWNINDEX){
                    DATA.options.tov = false;
                }
                // replace start city overview with the window style
                if(DATA.options.tov){
                    if($('#ui_box').hasClass("city-overview-enabled") && uw.Layout.wnd.TYPE_TOWNINDEX) {
                        $.Observer(uw.GameEvents.ui.bull_eye.radiobutton.island_view.click).publish({});
                        uw.GPWindowMgr.Create(uw.Layout.wnd.TYPE_TOWNINDEX, uw.DM.getl10n('town_index').window_title +" - "+ uw.ITowns.getTown(uw.Game.townId).name);
                    }
                }
                minimizeDailyReward();

                a();

                // English => default language
                if(!LANG[LID]){ LID = "en"; }

                if((ch.length == 2) && exc && (sum == 42)){
                    addFunctionToITowns();

                    if(DATA.options.tsk) {scaleTaskbar(); hideNavElements();}

                    if(DATA.options.com) {addComparisonButton();}
                    addSettingsButton();
                    addAvailableUnitsBox();
                    addAvailableUnitsButton();

                    //addStatsButton();

                    fixUnitValues();
                    if(DATA.options.bir) {initBiri();}

                    getAllUnits();
                    setInterval(function(){
                        getAllUnits();
                    },1800000);

                    if(DATA.options.pop) {unbindFavorPopup();}
                    if(DATA.options.spl) {catchSpellBox(); initSpellBox();}
                    imageSelectionProtection();

                    if(DATA.options.con) {changeContextMenu();}

                    /*
                    $.Observer(uw.GameEvents.menu.click).subscribe('DIO_MENU', function(e,data){
                        //console.log(data.option_id);
                    });
                    $.Observer(uw.GameEvents.attack.incoming).subscribe('DIO_ATTACK', function(e,data){
                        //console.log(data.count);
                    });
                    $.Observer(uw.GameEvents.town.units.change).subscribe('DIO_UNITCHANGE', function(e,data){
                        //console.log(data.count);
                    });
                    */

                    //Notification
                    uw.NotificationType.DIO_TOOLS = "diotools";
                    $('<style type="text/css"> #notification_area .diotools .icon { background: url(http://666kb.com/i/cifvfsu3e2sdiipn0.gif) 4px 7px no-repeat !important; -webkit-filter: hue-rotate(100deg);filter: url(#Hue3); } </style>').appendTo('head');

                    var notif = DATA.notification;
                    if(notif <= 10){
                        //newFeatureNotification(1, 'Swap context menu buttons ("Select town" and "City overview")');
                        //newFeatureNotification(2, 'Town overview (old window mode)');
                        //newFeatureNotification(3, 'Mouse wheel: You can change the views with the mouse wheel');
                        //newFeatureNotification(4, 'Town icons on the strategic map');
                        //newFeatureNotification(5, 'Percentual unit population in the town list');
                        //newFeatureNotification(6, 'New world wonder ranking');
                        //newFeatureNotification(7, 'World wonder icons on the strategic map');
                        petitionNotification(8);
                        $('.diotools .icon').each(function(){
                            $(this).click(function(){
                                clickDioSettings();
                                $(this).parent().find(".close").click();
                            });
                        });
                        $('.diotools').css({
                            cursor: "pointer"
                        });
                        saveValue('notification', ++notif);
                    }

                    if(DATA.options.mov){showActivityBoxes();}
                    if(DATA.options.str){addStrengthMenu(); setStrengthMenu();}

                    if(DATA.options.twn){setTownList(); addTownIcon(); setTownIconsOnMap();}

                    if(DATA.options.com){addComparisonBox();}
                    if(DATA.options.sml){loadSmileys();}
                    if(DATA.options.irc){initChatUser();}

                    if(DATA.options.tov){setCityWindowButton();}

                    if(DATA.options.scr){scrollViews();}
                    if(DATA.options.sen){getSentUnits();}


                    setTimeout(function(){
                        counter(uw.Timestamp.server());
                        setInterval(function(){ 
                            counter(uw.Timestamp.server());
                        }, 21600000);
                    }, 60000);

                    // AJAX-EVENTS
                    ajaxObserver();

                    // Execute once to get the world wonder types and coordinates
                    setTimeout(function(){
                        if(!wonderTypes.great_pyramid_of_giza){
                            getWorldWonderTypes();
                        }
                        if(wonderTypes.great_pyramid_of_giza){
                            setTimeout(function(){
                                if(!wonder.map.mausoleum_of_halicarnassus){
                                    getWorldWonders();
                                } else {
                                    setWonderIconsOnMap();
                                }
                            }, 2000);
                        }
                    }, 3000);

                    // Execute once to get alliance ratio
                    if (wonder.ratio[AID] == -1 || !$.isNumeric(wonder.ratio[AID])){ 
                        setTimeout(function(){
                            getPointRatioFromAllianceProfile();
                        }, 5000);
                    }

                }
                time_b = uw.Timestamp.client();
                //console.log("Gebrauchte Zeit:" + (time_b - time_a));
            });  
        } else {
            setTimeout(function(){
                loadFeatures();
            }, 100);
        }
    }
    if(uw.location.pathname === "/game/index"){
        loadFeatures();
    }

    /*******************************************************************************************************************************
     * HTTP-Requests
     * *****************************************************************************************************************************/
    function ajaxObserver(){
        $(document).ajaxComplete(function (e, xhr, opt) {
            var url = opt.url.split("?"),
                action = url[0].substr(5) + "/" + url[1].split(/&/)[1].substr(7);
            if(PID == 84367 || PID == 104769){
                console.log(action);
                console.log((JSON.parse(xhr.responseText).json));
            }
            setTimeout(function(){
                switch (action) {
                    case "/frontend_bridge/fetch": // Daily Reward

                        // Event map
                        if(DATA.options.her){
                            if($('.js-hercules2014-dragdrop.dragdrop').get(0)){
                                $('.js-hercules2014-dragdrop.dragdrop').css({ 
                                    "transform": "translate(0px, 0px)"
                                });
                            }
                            
                            if(!$('#dio_hercules').get(0) && $('.hercules_map').get(0)){
                                var map_width = parseInt(getComputedStyle($('.hercules_map').get(0)).width, 10) / 2;
                                var map_height = parseInt(getComputedStyle($('.hercules_map').get(0)).height, 10) / 2;

                                $('<style id="dio_hercules" type="text/css"> .hercules_map .stages { -webkit-transform: scale(0.5) translate(0px, 0px); transform: scale(0.5) translate(0px, 0px); margin-left: -33%; } '+
                                  '.hercules2014_map .dragdrop, .hercules2014_map .hercules_map { width: '+ map_width +'px !important; height: '+ map_height +'px !important; } '+
                                  '.hercules_map { background-size: 100% !important; } '+
                                  '</style>').appendTo('head');
                            }
                        }

                        //console.log("done");
                        //$('.daily_login').find(".minimize").click();
                        break;
                    case "/player/index":
                        settings();
                        if(diosettings){ $('#dio_tools').click(); diosettings = false; }
                        break;
                    case "/index/switch_town":

                        if(DATA.options.str)	{setStrengthMenu();}
                        if(DATA.options.bir)	{getBiri();}
                        if(DATA.options.twn)	{changeTownIcon();}

                        // Update city window
                        if(uw.Layout.wnd.TYPE_TOWNINDEX){ // check if the window type exists
                            if(uw.GPWindowMgr.getOpenFirst(uw.Layout.wnd.TYPE_TOWNINDEX)){
                                uw.GPWindowMgr.getOpenFirst(uw.Layout.wnd.TYPE_TOWNINDEX).setTitle(uw.DM.getl10n('town_index').window_title +" - "+ uw.ITowns.getTown(uw.Game.townId).name);
                                uw.GPWindowMgr.getOpenFirst(uw.Layout.wnd.TYPE_TOWNINDEX).reloadContent();
                            }
                        }
                        break;
                    case "/building_docks/index":
                        if(DATA.options.bir)	{getBiriDocks();}
                        break;
                    case "/building_place/units_beyond":
                        if(DATA.options.bir)	{getBiriAgora();}
                        //addTransporterBackButtons();
                        break;
                    case "/building_place/simulator":
                        if(DATA.options.sim)	{changeSimulatorLayout(); }
                        break;
                    case "/building_place/simulate":
                        if(DATA.options.sim)	{afterSimulation(); }
                        break;

                    case "/alliance_forum/forum": case "/message/new": case "/message/forward": case "/message/view": case "/player_memo/load_memo_content":
                        if(DATA.options.sml){addSmileyBox(action); }
                        if(DATA.options.bbc){addForm(action); }
                        break;
                    case "/wonders/index":
                        if(DATA.options.trd){WWTradeHandler(); }
                        getResWW();
                        break;
                    case "/wonders/send_resources":
                        getResWW();
                        break;
                    case "/ranking/alliance": 
                        getPointRatioFromAllianceRanking();
                        break;
                    case "/ranking/wonder_alliance":
                        getPointRatioFromAllianceRanking();
                        changeWWRanking(JSON.parse(xhr.responseText).plain.html);
                        setWonderIconsOnMap();
                        break;
                    case "/alliance/members_show":
                        getPointRatioFromAllianceMembers();
                        break;
                    case "/town_info/trading":
                        if(DATA.options.trd){addTradeMarks(15, 18, 15, "red"); TownTabHandler(action.split("/")[2]); }
                        break;
                    case "/farm_town_overviews/get_farm_towns_for_town":
                        changeResColor();
                        break;
                    case "/command_info/conquest_info":
                        if(DATA.options.str)	{addStrengthConquest();}
                        break;
                    case "/command_info/conquest_movements": case "/conquest_info/getinfo":
                        if(DATA.options.cnt)	{countMovements();}
                        break;
                    case "/building_barracks/index": case "/building_barracks/build":
                        if(DATA.options.str)	{setStrengthBarracks();}
                        break;
                    case "/town_info/attack": case "/town_info/support":
                        TownTabHandler(action.split("/")[2]);
                        break;
                    case "/report/index":
                        changeDropDownButton();
                        loadFilter();
                        saveFilter();
                        //removeReports();
                        break;
                    case "/message/default": case "/message/index":
                        break;
                    case "/chat/init":
                        if(DATA.options.irc)	{modifyChat();}
                        break;
                    case "/town_info/go_to_town":
                        /*
                        //console.log(uw.Layout.wnd);
                        var windo = uw.GPWindowMgr.getOpenFirst(uw.Layout.wnd.TYPE_TOWNINDEX).getID();
                        //console.log(uw.GPWindowMgr.getOpenFirst(uw.Layout.wnd.TYPE_TOWNINDEX));
                        uw.GPWindowMgr.getOpenFirst(uw.Layout.wnd.TYPE_TOWNINDEX).setPosition([100,400]);
                        //console.log(windo);
                        //console.log(uw.GPWindowMgr.getOpenFirst(uw.Layout.wnd.TYPE_TOWNINDEX).getPosition());
                        */

                        break;
                } 
            },0);

        });
    }

    function test(){
        //http://gpde.innogamescdn.com/images/game/temp/island.png

        //console.log(uw.WMap);
        //console.log(uw.WMap.getSea(uw.WMap.getXCoord(), uw.WMap.getYCoord()));

        //console.log(uw.GameControllers.LayoutToolbarActivitiesController().prototype.getActivityTypes());
        //console.log(uw.GameViews);
        //console.log(uw.GameViews.BarracksUnitDetails());

        //console.log(uw.ITowns.getTown(uw.Game.townId).unitsOuter().sword);
        //console.log(uw.ITowns.getCurrentTown().unitsOuter().sword);

        //console.log(uw.ITowns.getTown(uw.Game.townId).researches().attributes);
        //console.log(uw.ITowns.getTown(uw.Game.townId).hasConqueror());
        //console.log(uw.ITowns.getTown(uw.Game.townId).allUnits());
        //console.log(uw.ITowns.all_units.fragments[uw.Game.townId]._byId);
        //console.log("Zeus: " + uw.ITowns.player_gods.zeus_favor_delta_property.lastTriggeredVirtualPropertyValue);
        //console.log(uw.ITowns.player_gods.attributes);

        //console.log(uw.ITowns.getTown('5813').createTownLink());
        //console.log(uw.ITowns.getTown(5813).unitsOuterTown);

        //console.log(uw.ITowns.getTown(uw.Game.townId).getLinkFragment());

        //console.log(uw.ITowns.getTown(uw.Game.townId).allGodsFavors());
    }

    /*******************************************************************************************************************************
     * Helping functions
     * ----------------------------------------------------------------------------------------------------------------------------
     * | ● fixUnitValues: Get unit values and overwrite some wrong values
     * | ● getMaxZIndex: Get the highest z-index of "ui-dialog"-class elements
     * ----------------------------------------------------------------------------------------------------------------------------
     *******************************************************************************************************************************/

    // Fix buggy grepolis values
    function fixUnitValues(){
        uw.GameData.units.small_transporter.attack = uw.GameData.units.big_transporter.attack = uw.GameData.units.demolition_ship.attack = uw.GameData.units.militia.attack = 0;
        uw.GameData.units.small_transporter.defense = uw.GameData.units.big_transporter.defense = uw.GameData.units.demolition_ship.defense = uw.GameData.units.colonize_ship.defense = 0;
        uw.GameData.units.militia.resources = { wood: 0, stone: 0, iron: 0 };
    }

    function getMaxZIndex(){
        var maxZ = Math.max.apply(null,$.map($("div[class^='ui-dialog']"), function(e,n){
            if($(e).css('position')=='absolute'){
                return parseInt($(e).css('z-index'), 10) || 1000;
            }
        }));
        return (maxZ !== -Infinity)? maxZ + 1 : 1000;
    }

    function getBrowser(){
        var ua = navigator.userAgent, tem, 
            M = ua.match(/(opera|maxthon|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
        if(/trident/i.test(M[1])){
            tem =  /\brv[ :]+(\d+)/g.exec(ua) || [];
            M[1] = 'IE';
            M[2] = tem[1] || '';
        }
        if(M[1] === 'Chrome'){
            tem = ua.match(/\bOPR\/(\d+)/);
            if(tem != null){ 
                M[1] = 'Opera';
                M[2] = tem[1];
            }
        }
        M = M[2]? [M[1], M[2]]: [navigator.appName, navigator.appVersion, '-?'];
        if((tem = ua.match(/version\/(\d+)/i))!= null) M.splice(1, 1, tem[1]);

        return M.join(' ');
    }

    // Error Handling / Remote diagnosis / Automatic bug reports
    function errorHandling(e, fn){
        if(PID == 84367 || PID == 104769){
            HumanMessage.error("DIO-TOOLS("+ version +")-ERROR: " + e.message);
            console.log(e.stack);
        } else {
            if(!DATA.error[version]){
                DATA.error[version] = {};
            }

            if(DATA.options.err && !DATA.error[version][fn]){
                $.ajax({
                    type: "POST",
                    url: "https://diotools.pf-control.de/game/error.php",
                    data: { error: e.stack.replace(/'/g,'"') , "function": fn, browser: getBrowser(), version: version },
                    success: function (text) {
                        DATA.error[version][fn] = true;
                        saveValue("error", JSON.stringify(DATA.error));
                    }
                });
            }
        }
    }

    // Notification
    function newFeatureNotification(nid, feature){
        var Notification = new NotificationHandler();
        Notification.notify($('#notification_area>.notification').length+1, uw.NotificationType.DIO_TOOLS,
                            "<span style='color:rgb(8, 207, 0)'><b><u>New Feature!</u></b></span>"+ feature + "<span class='small notification_date'>DIO-Tools: v"+ version +"</span>");
    }
    
    // Petition notification
    function petitionNotification(nid){
        var Notification = new NotificationHandler();
        
        var link = "", headline = "";
        
        switch(LID){
            case "de":
                headline = 'Petition gegen "Warfare Packages"';
                link = "http://forum.de.grepolis.com/showthread.php?32155";
                break;
            case "nl":
                headline = 'Petitie tegen "Warfare Packages"';
                link = "http://forum.nl.grepolis.com/showthread.php?32350";
                break;
            case "us":
                headline = 'Petition to Stop "Warfare Packages"';
                link = "http://forum.us.grepolis.com/showthread.php?9082";
            default:
                headline = 'Petition to Stop "Warfare Packages"';
                link = "http://forum.en.grepolis.com/showthread.php?55775";
                break;
        }
        Notification.notify($('#notification_area>.notification').length+1, uw.NotificationType.DIO_TOOLS,
                            '<span style="color:rgb(8, 207, 0)"><b><u>'+ headline +'</u></b></span><a href="'+ link +'" target="_blank">'+ link +'</a><span class="small notification_date">DIO-Tools: v'+ version +'</span>');
    }

    /*******************************************************************************************************************************
     * Mousewheel Zoom
     *******************************************************************************************************************************/

    // Scroll trough the 2-3 views
    function scrollViews(){
        try {
            var scroll = 2;
            $('#main_area, .ui_city_overview').bind('mousewheel', function(e){
                if($('.island_view').hasClass('checked')){
                    scroll = 2;
                } else if($('.strategic_map').hasClass('checked')){
                    scroll = 1;
                } else {
                    scroll = 3;
                }
                var delta = 0;
                if (e.originalEvent.wheelDelta) {
                    if(e.originalEvent.wheelDelta < 0) { delta = -1;} else { delta = 1; }
                }
                if (e.originalEvent.detail) {
                    if(e.originalEvent.detail < 0) { delta = 1;} else { delta = -1; }
                }

                if(delta < 0) {
                    scroll -= 1;
                    if(scroll < 1) { scroll = 1; }
                }else {
                    scroll += 1;
                    if(scroll > 2 && DATA.options.tov) { scroll = 2; }
                    if(scroll > 3) { scroll = 3; }
                }

                switch(scroll){
                    case 1: $('.strategic_map').click(); $('#popup_div').css('display', 'none'); break;
                    case 2: $('.island_view').click(); break;
                    case 3: $('.city_overview').click(); break;
                }
                //prevent page from scrolling
                return false;
            });
        } catch(error){
            errorHandling(error, "scrollViews");
        }
    }


    /*******************************************************************************************************************************
     * Statistics
     * ----------------------------------------------------------------------------------------------------------------------------
     * | ● Expansion of towns?
     * | ● Occupancy of the farms?
     * | ● Mouseclick-Counter?
     * | ● Resource distribution (%)?
     * | ● Building level counter ?
     * ----------------------------------------------------------------------------------------------------------------------------
     *******************************************************************************************************************************/

    function addStatsButton(){
        $('<div class="btn_statistics circle_button"><div class="ico_statistics js-caption"></div></div>').appendTo(".gods_area");
        $('.btn_statistics').css({
            top: '56px',
            left: '-4px',
            zIndex: '10',
            position: 'absolute'
        });
        $('.btn_statistics .ico_statistics').css({
            margin: '7px 0px 0px 8px', width: '17px', height: '17px',
            background: 'url(http://s1.directupload.net/images/140408/pltgqlaw.png) no-repeat 0px 0px', // http://s14.directupload.net/images/140408/k4wikrlq.png // http://s7.directupload.net/images/140408/ahfr8227.png
            backgroundSize: "100%",
            //WebkitFilter: 'hue-rotate(100deg)',
            //filter: 'url(#Hue3)'
        });

        mouseclickCounter();

        $('.btn_statistics').on('mousedown', function(){
            $('.ico_statistics').get(0).style.marginTop = "8px";
        });
        $('.btn_statistics').toggleClick(function(){
            $('.btn_statistics').addClass("checked");
            $('.ico_statistics').get(0).style.marginTop = "8px";
            //console.log(click_cnt);
            $('#statistics_box').get(0).style.display = "block"; 
            $('#statistics_box').get(0).style.zIndex = getMaxZIndex() + 1;
        }, function(){
            $('.btn_statistics').removeClass("checked");
            $('.ico_statistics').get(0).style.marginTop = "7px";
            $('#statistics_box').get(0).style.display = "none";
        });
        $('.btn_statistics').tooltip(getText("labels", "uni"));
    }

    var click_cnt = 0;
    function mouseclickCounter(){
        // TODO: start date and reset button
        $('body').click(function(){
            click_cnt++;
        });
    }

    /*******************************************************************************************************************************
     * Body Handler
     * ----------------------------------------------------------------------------------------------------------------------------
     * | ● Town icon
     * | ● Town list: Adds town type to the town list
     * | ● Swap Context Icons
     * | ● City overview
     * ----------------------------------------------------------------------------------------------------------------------------
     *******************************************************************************************************************************/

    var townTypeIcon = {
        // Automatic Icons
        lo: 0, ld: 3, so: 6, sd: 7, fo: 10, fd: 9, bu: 14, /* Building */ po: 22, no: 12,

        // Manual Icons
        fa: 20, /* Favor */ re: 15, /* Resources */ di: 2, /* Distance */ sh: 1, /* Pierce */ lu: 13, /* ?? */ dp: 11, /* Diplomacy */ ha: 15, /* ? */ si: 18, /* Silber */ ra: 17, ch: 19, /* Research */ ti: 23, /* Time */ un: 5,
        wd: 16, /* Wood */ wo: 24, /* World */ bo: 13, /* Booty */ gr: 21, /* Lorbeer */ st: 17, /* Stone */ is: 26, /* ?? */ he: 4, /* Helmet */ ko: 8 /* Kolo */
    },
        townTypeIcon2 = {
            lo: "http://s14.directupload.net/images/140129/gvctb3i5.png",	// red:		http://s7.directupload.net/images/140129/mn4m2vhx.png kreuz: http://s1.directupload.net/images/140129/rdvuhlmc.png
            ld: "http://s7.directupload.net/images/140129/zwts6zz8.png",	// blue:	http://s1.directupload.net/images/140129/oua87w9q.png
            so: "http://s7.directupload.net/images/140129/674supp9.png",	// smaller: http://s14.directupload.net/images/140129/x7jv2kc9.png
            sd: "http://s14.directupload.net/images/140129/aseivxpl.png",
            fo: "http://s14.directupload.net/images/140129/j9mwfuu4.png",	// bright:	http://s1.directupload.net/images/140129/7ueia7ja.png
            fd: "http://s7.directupload.net/images/140129/lwtlj9ej.png",	// bright:	http://s1.directupload.net/images/140129/4an4dhr7.png

            bu: "http://s1.directupload.net/images/140129/y3d6znpg.png", // http://s14.directupload.net/images/140129/wb9w9odq.png,	// build2: http://s1.directupload.net/images/140129/qzj2vem6.png  bbcode: http://s7.directupload.net/images/140129/d39yg9zj.png
            po: "http://gpde.innogamescdn.com/images/game/res/pop.png",
            no: "http://s7.directupload.net/images/140129/t8tjs543.png", // green: http://s7.directupload.net/images/140129/zneb6f3m.png
            // brown: http://s14.directupload.net/images/140129/fhlanrua.png   http://s14.directupload.net/images/140129/9m4xtmys.png      http://s7.directupload.net/images/140129/9hflkab3.png

            // Manual Icons
            fa: "http://s7.directupload.net/images/140404/xt839us6.png", // "http://s7.directupload.net/images/140404/xifwkdqy.png",
            re: "http://s14.directupload.net/images/140404/b4n3tyjh.png",
            di: "http://s14.directupload.net/images/140404/nvqxx5j7.png",
            sh: "http://s1.directupload.net/images/140404/mbvpptpg.png",
            lu: "http://s1.directupload.net/images/140404/38n97lp5.png",
            // ro: "http://s14.directupload.net/images/140404/9o22obra.png",
            dp: "http://s1.directupload.net/images/140404/95cgvzcp.png",
            ha: "http://s1.directupload.net/images/140404/9om7bf4m.png",
            si: "http://s1.directupload.net/images/140404/b5eumrw7.png",
            ra: "http://s14.directupload.net/images/140404/3qofe863.png",
            ch: "http://s7.directupload.net/images/140404/jrthehnw.png",
            ti: "http://s7.directupload.net/images/140404/u2a5x7as.png", // "http://s1.directupload.net/images/140404/ceubhq4f.png",
            un: "http://s1.directupload.net/images/140404/x3um2uvt.png", //"http://s14.directupload.net/images/140404/ib4w63he.png", //"http://s7.directupload.net/images/140404/ltegir8t.png", //"http://s1.directupload.net/images/140404/88ljrpvt.png",

            wd: "http://s7.directupload.net/images/140404/te9zldjx.png",
            wo: "http://s1.directupload.net/images/140404/cxbjhapw.png",
            bo: "http://s14.directupload.net/images/140404/ki4gwd7x.png",
            gr: "http://s14.directupload.net/images/140404/n7bq4ixc.png",
            st: "http://s1.directupload.net/images/140404/zwc8ctqh.png",
            is: "http://s1.directupload.net/images/140404/48nlm7xd.png",
            he: "http://s7.directupload.net/images/140404/uldko8rb.png",


            ko: "http://s7.directupload.net/images/140404/r8kikv5d.png", // "http://s7.directupload.net/images/140404/qpawnrwd.png" // "http://s1.directupload.net/images/140404/icuao2mf.png" // 
        },
        worldWonderIcon = {
            colossus_of_rhodes:				"url(http://gpde.innogamescdn.com/images/game/map/wonder_colossus_of_rhodes.png) 38px -1px;",
            great_pyramid_of_giza:			"url(http://gpde.innogamescdn.com/images/game/map/wonder_great_pyramid_of_giza.png) 34px -6px;",
            hanging_gardens_of_babylon:		"url(http://gpde.innogamescdn.com/images/game/map/wonder_hanging_gardens_of_babylon.png) 34px -5px;",
            lighthouse_of_alexandria:		"url(http://gpde.innogamescdn.com/images/game/map/wonder_lighthouse_of_alexandria.png) 37px -1px;",
            mausoleum_of_halicarnassus:		"url(http://gpde.innogamescdn.com/images/game/map/wonder_mausoleum_of_halicarnassus.png) 37px -4px;",
            statue_of_zeus_at_olympia:		"url(http://gpde.innogamescdn.com/images/game/map/wonder_statue_of_zeus_at_olympia.png) 36px -3px;",
            temple_of_artemis_at_ephesus:	"url(http://gpde.innogamescdn.com/images/game/map/wonder_temple_of_artemis_at_ephesus.png) 34px -5px;"
        };

    function setWonderIconsOnMap(){
        try {
            if(!$('#wondericons_map').get(0)){
                var color = "orange";

                // style for world wonder icons
                var style_str = "<style id='wondericons_map' type='text/css'>";
                for(var ww_type in wonder.map){
                    if(wonder.map.hasOwnProperty(ww_type)){
                        for(var ww in wonder.map[ww_type]){
                            if(wonder.map[ww_type].hasOwnProperty(ww)){
                                /*
                                if(wonder.map[ww_type][ww] !== AID){
                                    color = "rgb(192, 109, 54)";
                                } else {
                                    color = "orange";
                                }
                                */
                                style_str += "#mini_i" + ww + ":before {"+
                                    "content: '';"+
                                    "background:"+ color + " " + worldWonderIcon[ww_type] +
                                    "background-size: auto 97%;"+
                                    "padding: 8px 16px;"+
                                    "top: 50px;"+
                                    "position: relative;"+
                                    "border-radius: 40px;"+
                                    "z-index: 200;"+
                                    "cursor: pointer;"+
                                    "box-shadow: 1px 1px 0px rgba(0, 0, 0, 0.5);"+
                                    "border: 2px solid green; } "+
                                    "#mini_i" + ww + ":hover:before { z-index: 201; "+
                                    "filter: url(#Brightness12);"+
                                    "-webkit-filter: brightness(1.2);} ";
                            }
                        }
                    }
                }
                $(style_str + "</style>").appendTo('head');

                // Context menu on mouseclick
                $('#minimap_islands_layer').on('click', '.m_island', function(e){
                    var ww_coords = this.id.split("i")[3].split("_");
                    uw.Layout.contextMenu(e, 'wonder', {ix: ww_coords[0], iy: ww_coords[1]});
                });


            }
        } catch(error) {
            errorHandling(error, "setWonderIconsOnMap");
        }
    }

    function setTownIconsOnMap(){
        try {
            // if town icon changed 
            if($('#townicons_map').get(0)){ $('#townicons_map').remove(); }

            // style for own towns (town icons)
            var start = (new Date()).getTime(), end, style_str = "<style id='townicons_map' type='text/css'>";
            for(var e in autoTownTypes){
                if(autoTownTypes.hasOwnProperty(e)){
                    style_str += "#mini_t"+ e +" { height: 19px;"+
                        "width:19px;"+
                        "border-radius: 11px;"+
                        "border: 2px solid rgb(16, 133, 0);"+
                        "margin: -4px;"+
                        //"background: rgb(255, 187, 0) url(http://s7.directupload.net/images/140404/xt839us6.png) repeat;"+ 
                        "background: rgb(255, 187, 0) url("+ dio_sprite +") "+ (townTypeIcon[(manuTownTypes[e] || autoTownTypes[e])]*-25) +"px -27px repeat;"+
                        "z-index: 100;"+
                        "font-size: 0em;"+
                        "cursor: pointer;"+
                        "box-shadow: 1px 1px 0px rgba(0, 0, 0, 0.5);} "+
                        "#mini_t"+ e +":hover { z-index: 101; "+
                        "filter: url(#Brightness12);" +
                        "-webkit-filter: brightness(1.2);} "; 
                } 
            }

            // Context menu on mouseclick
            $('#minimap_islands_layer').on('click', '.m_town', function(z){
                var id = parseInt($(this).get(0).id.substring(6), 10);
                uw.Layout.contextMenu(z, 'determine', {"id": id, "name": uw.ITowns.getTown(id).name });

                z.stopPropagation(); // prevent parent world wonder event
            });

            // Style for foreign cities (shadow)
            style_str += ".m_town { text-shadow: 1px 1px 0px rgba(0, 0, 0, 0.7); } "; 

            style_str += "</style>";
            $(style_str).appendTo('head');
            /*
            setTimeout(function(){
                uw.MapTiles.createTownDiv_old = uw.MapTiles.createTownDiv;

                uw.MapTiles.createTownDiv = function(town, player_current_town) {
                    var ret = uw.MapTiles.createTownDiv_old(town, player_current_town);

                    if(!isNaN(town.id) && town.player_id == PID) {

                        //setIconMap(town.id);
                        console.log(town.id);
                        console.log(player_current_town);
                    }
                    return ret;
                };
            },2000);
            */
        } catch(error) {
            errorHandling(error, "setTownIconsOnMap");
        }
    }

    // Style for town icons
    var style_str = '<style id="townicons" type="text/css">';
    for(var s in townTypeIcon){
        if(townTypeIcon.hasOwnProperty(s)){
            style_str += '.townicon_'+ s +' { background:url('+ dio_sprite +') '+ (townTypeIcon[s]*-25) +'px -26px repeat;float:left;} ';
        }
    }
    style_str += '</style>';
    $(style_str).appendTo('head');


    // City overview
    function setCityWindowContext(){
        // $.each($("#goToTown").data("events"), function(i, e) { //console.log(i); });
        if(uw.Layout.wnd.TYPE_TOWNINDEX){
            $('#goToTown').unbind("mousedown");
            $('#goToTown').on("mousedown", function(){
                uw.GPWindowMgr.Create(uw.Layout.wnd.TYPE_TOWNINDEX, uw.DM.getl10n('town_index').window_title +" - "+ uw.ITowns.getTown(uw.Game.townId).name);
                if($('#select_town').get(0)) {$('#select_town').mousedown(); }
                var town = setInterval(function(){
                    if($('#town_background').get(0)){
                        document.getSelection().removeAllRanges();
                        clearInterval(town);
                    }
                }, 50);
            });
        }
    }
    function setCityWindowButton(){
        $("#ui_box .bull_eye_buttons .city_overview").appendTo('#ui_box .bull_eye_buttons');
        $("#ui_box .bull_eye_buttons .city_overview").css({
            left: '18px',
            top: '3px'
        });
        if(uw.Layout.wnd.TYPE_TOWNINDEX){
            $('.bull_eye_buttons .city_overview').on("click", function(){
                uw.GPWindowMgr.Create(uw.Layout.wnd.TYPE_TOWNINDEX, uw.DM.getl10n('town_index').window_title +" - "+ uw.ITowns.getTown(uw.Game.townId).name);
            });
        }
    }

    function changeContextMenu(){
        // Set context menu event handler
        $.Observer(uw.GameEvents.map.context_menu.click).subscribe('DIO_CONTEXT', function(e,data){
            if(DATA.options.con && $('#context_menu').children().length == 4){
                // Clear animation
                $('#context_menu div#goToTown').css({
                    left: '0px', 
                    top: '0px',
                    WebkitAnimation: 'none', //'A 0s linear',
                    animation: 'none' //'B 0s linear'
                });
            }
            // Set 'goToTown' button
            if(DATA.options.tov && $('#goToTown').get(0)){
                setCityWindowContext();
            }
            // Replace german label of 'select town' button
            if(LID === "de" && $('#select_town').get(0)){
                $("#select_town .caption").get(0).innerHTML = "Selektieren";
            }
        });

        // Set context menu animation
        if(!$('#select_town').get(0) && !$('#espionage').get(0)){
            var ani_duration = 0;
            // set fixed position of 'select town' button
            $('<style type="text/css"> #select_town { left: 0px !important; top: 0px !important; z-index: 6} </style>').appendTo('head'); //-webkit-filter: hue-rotate(65deg);filter: url(#Hue1);

            // set animation of 'goToTown' button
            $('<style id="dio_context" type="text/css"> #context_menu div#goToTown { left: 30px; top: -51px; '+
              '-webkit-animation: A 0.115s linear; animation: B 0.2s;} '+
              '@-webkit-keyframes A { from {left: 0px; top: 0px;} to {left: 30px; top: -51px;} }'+
              '@keyframes B { from {left: 0px; top: 0px;} to {left: 30px; top: -51px;} }'+
              '</style>').appendTo('head');
        }
    }

    function imageSelectionProtection(){
        $('<style type="text/css"> img { -moz-user-select: -moz-none; -khtml-user-select: none; -webkit-user-select: none;} </style>').appendTo('head'); 
    }

    function setTownList(){
        // TODO: rewrite in one style tag

        // Town list
        $('<style type="text/css"> #town_groups_list .item { text-align: left; padding-left:35px;} </style>').appendTo('head');
        //$('<style type="text/css"> #town_groups_list .inner_column { width: 172px !important; float:left; margin-bottom:20px; position:relative !important; left:0px !important; top:0px !important} </style>').appendTo('head');
        $('<style type="text/css"> #town_groups_list .inner_column { border: 1px solid rgba(100, 100, 0, 0.3);margin: -2px 0px 0px 2px;} </style>').appendTo('head');
        $('<style type="text/css"> .town_groups_list .island_quest_icon { background-size: 90%; position: absolute; right: 37px; top: 4px;} </style>').appendTo('head');

        // Quacks Zentrier-Button verschieben
        $('<style type="text/css"> #town_groups_list .jump_town { right: 37px !important;} </style>').appendTo('head');

        // Population percentage
        $('<style type="text/css"> #town_groups_list .pop_percent { position: absolute; right: 7px; font-size: 0.7em;} '+
          '#town_groups_list .full { color: green; }'+
          '#town_groups_list .threequarter { color: darkgoldenrod; }'+
          '#town_groups_list .half { color: darkred; }'+
          '#town_groups_list .quarter { color: red; }'+
          '</style>').appendTo('head');

        // Town Icons
        $('<style type="text/css"> .icon_small { height:20px;padding-left:25px;margin-left:-25px; background-clip:padding-box;} </style>').appendTo('head');


        // Open town list: hook to grepolis function render()
        if(DATA.options.twn){
            var i = 0; 
            while(uw.layout_main_controller.sub_controllers[i].name != 'town_name_area'){ i++; }

            uw.layout_main_controller.sub_controllers[i].controller.town_groups_list_view.render_old = uw.layout_main_controller.sub_controllers[i].controller.town_groups_list_view.render;

            uw.layout_main_controller.sub_controllers[i].controller.town_groups_list_view.render = function() {
                uw.layout_main_controller.sub_controllers[i].controller.town_groups_list_view.render_old();
                changeTownList();
            };
        }
    }

    function changeTownList(){
        $("#town_groups_list .town_group_town").each(function() {
            try {
                var town_id = $(this).attr('name'), str = $(this).get(0).innerHTML, townicon_str, percent_str = "", percent = -1,
                    space = "full";

                if(population[town_id]){
                    percent = population[town_id].percent;
                }

                if(percent < 75){ space = "threequarter"; } 
                if(percent < 50){ space = "half"; }
                if(percent < 25){ space = "quarter"; }

                if (!(str.indexOf("townicon") >= 0)){
                    townicon_str= '<div class="icon_small townicon_'+ (manuTownTypes[town_id] || autoTownTypes[town_id] || "no") +'"></div>';
                    // TODO: Notlösung...
                    if(percent != -1){
                        percent_str	= '<div class="pop_percent '+ space +'">' + percent + '%</div>';
                    }

                    $(this).get(0).innerHTML = townicon_str + percent_str + str;
                }

                // opening context menu
                /*
                $(this).click(function(e){
                    console.log(e);
                    uw.Layout.contextMenu(e, 'determine', {"id": town_id,"name": uw.ITowns[town_id].getName()});
                });
                */

            } catch(error){
                errorHandling(error, "changeTownList");   
            }
        });

        $("#town_groups_list .town_group_town").hover(function(){
            $(this).find('.island_quest_icon').css({
                display: "none"
            });
        }, function(){
            $(this).find('.island_quest_icon').css({
                display: "block"
            });   
        });

        // Add change town list event handler
        $.Observer(uw.GameEvents.town.town_switch).unsubscribe('DIO_SWITCH_TOWN');
        $.Observer(uw.GameEvents.town.town_switch).subscribe('DIO_SWITCH_TOWN', function () {
            changeTownList();
        });
    }

    function addTownIcon(){
        try {
            // Quickbar modification 
            $('.ui_quickbar .left, .ui_quickbar .right').css({ width: '46%' });

            $('<div id="town_icon"><div class="town_icon_bg"><div class="icon_big townicon_'+ 
              (manuTownTypes[uw.Game.townId] || ((autoTownTypes[uw.Game.townId] || "no") + " auto")) + '"></div></div></div>').appendTo('.town_name_area');


            $('.town_name_area').css({ zIndex: 11, left: '52%' }); // because of Kapsonfires Script and Beta Worlds bug report bar
            $('.town_name_area .left').css({
                zIndex: 20,
                left: '-39px'
            });

            // Town Icon Style
            $('#town_icon .icon_big').css({
                backgroundPosition: townTypeIcon[(manuTownTypes[uw.Game.townId] || ((autoTownTypes[uw.Game.townId] || "no")))]*-25 + 'px 0px'
            });

            $('<style type="text/css">'+
              '#town_icon { background:url('+ dio_sprite +') 0 -125px no-repeat; position:absolute; width:69px; height:61px; left:-47px; top:0px; z-index: 10; } '+
              '#town_icon .town_icon_bg { background:url('+ dio_sprite +') -76px -129px no-repeat; width:43px; height:43px; left:25px; top:4px; cursor:pointer; position: relative; } '+
              '#town_icon .town_icon_bg:hover { filter:url(#Brightness11); -webkit-filter:brightness(1.1); box-shadow: 0px 0px 15px rgb(1, 197, 33); } '+
              '#town_icon .icon_big	{ position:absolute; left:9px; top:9px; height:25px; width:25px; } '+
              '</style>').appendTo('head');


            var icoArray = ['ld', 'lo', 'sh', 'di', 'un', 
                            'sd', 'so', 'ko', 'ti', 'gr',
                            'fd', 'fo', 'dp', 'no', 'po',
                            're', 'wd', 'st', 'si', 'bu', 
                            'he', 'ch', 'bo', 'fa', 'wo'];

            // Fill select box with town icons
            $('<div class="select_town_icon dropdown-list default active"><div class="item-list"></div></div>').appendTo("#town_icon");
            for(var i in icoArray){
                if(icoArray.hasOwnProperty(i)){
                    $('.select_town_icon .item-list').append('<div class="option_s icon_small townicon_'+ icoArray[i] +'" name="'+ icoArray[i] +'"></div>');
                }
            }
            $('<hr><div class="option_s auto_s" name="auto"><b>Auto</b></div>').appendTo('.select_town_icon .item-list');

            // Styles
            $('#town_icon .select_town_icon').css({
                position: 'absolute',
                top: '47px',
                left: '23px',
                width: '145px',
                display: "none",
                padding: '2px',
                border: '3px inset rgb(7, 99, 12)',
                boxShadow: 'rgba(0, 0, 0, 0.5) 4px 4px 6px',
                borderRadius: '0px 10px 10px 10px',
                background: "url(https://gpde.innogamescdn.com/images/game/popup/middle_middle.png)"
            });
            $('#town_icon .item-list').css({ maxHeight: '400px', maxWidth: '200px', align: "right", overflowX: 'hidden' });

            $('<style type="text/css">'+
              '#town_icon .option_s { cursor:pointer; width:20px; height:20px; margin:0px; padding:2px 2px 3px 3px; border:2px solid rgba(0,0,0,0); border-radius:5px; background-origin:content-box; background-clip:content-box;} '+
              '#town_icon .option_s:hover { border: 2px solid rgb(59, 121, 81) !important;-webkit-filter: brightness(1.3); } '+
              '#town_icon .sel { border: 2px solid rgb(202, 176, 109); } '+
              '#town_icon hr { width:145px; margin:0px 0px 7px 0px; position:relative; top:3px; border:0px; border-top:2px dotted #000; float:left} '+
              '#town_icon .auto_s { width:136px; height:16px; float:left} '+
              '</style>').appendTo('head'); 

            $('#town_icon .option_s').click(function(){
                $("#town_icon .sel").removeClass("sel"); $(this).addClass("sel");

                if($(this).attr("name") === "auto"){
                    delete manuTownTypes[uw.Game.townId];
                } else {
                    manuTownTypes[uw.Game.townId] = $(this).attr("name");
                }
                changeTownIcon();
                saveValue(WID + "_townTypes", JSON.stringify(manuTownTypes));
            });

            // Show & hide drop menus on click
            $('#town_icon .town_icon_bg').click(function(){
                var el = $('#town_icon .select_town_icon').get(0);
                if( el.style.display === "none"){
                    el.style.display = "block";
                } else {
                    el.style.display = "none";
                }
            });

            $('#town_icon .select_town_icon [name="'+ (manuTownTypes[uw.Game.townId] || (autoTownTypes[uw.Game.townId] ? "auto" :"" )) +'"]').addClass("sel");

        } catch(error){
            errorHandling(error, "addTownIcon");
        }
    }

    function changeTownIcon(){
        var townType = (manuTownTypes[uw.Game.townId] || ((autoTownTypes[uw.Game.townId] || "no")));
        $('#town_icon .icon_big').removeClass().addClass('icon_big townicon_'+ townType + " auto");
        $('#town_icon .sel').removeClass("sel");
        $('#town_icon .select_town_icon [name="'+ (manuTownTypes[uw.Game.townId] || (autoTownTypes[uw.Game.townId] ? "auto" :"" )) +'"]').addClass("sel");

        $('#town_icon .icon_big').css({
            backgroundPosition: townTypeIcon[townType]*-25 + 'px 0px'
        });

        $('#town_icon .select_town_icon').get(0).style.display = "none";

        // update town icons on the map
        setTownIconsOnMap();
    }

    /*******************************************************************************************************************************
     * Available units
     * ----------------------------------------------------------------------------------------------------------------------------
     * | ● Shows all available units
     * ----------------------------------------------------------------------------------------------------------------------------
     *******************************************************************************************************************************/
    function addAvailableUnitsButton(){
        var default_title = DM.getl10n("place", "support_overview").options.troop_count + " ("+ DM.getl10n("hercules2014", "available")+")";

        $('<div class="btn_available_units circle_button"><div class="ico_available_units js-caption"></div></div>').appendTo(".bull_eye_buttons");
        $('.btn_available_units').css({
            top: '86px',
            left: '119px',
            zIndex: '10',
            position: 'absolute'
        });
        $('.btn_available_units .ico_available_units').css({
            margin: '5px 0px 0px 4px', width: '24px', height: '24px',
            background: 'url(http://s1.directupload.net/images/140323/w4ekrw8b.png) no-repeat 0px 0px', //http://gpde.innogamescdn.com/images/game/res/unit.png
            backgroundSize: "100%",
            filter: 'url(#Hue1)',
            WebkitFilter: 'hue-rotate(100deg)'

        });
        $('.btn_available_units').on('mousedown', function(){
            $('.ico_available_units').get(0).style.marginTop = "6px";
        });
        $('.btn_available_units').toggleClick(function(){
            $('#available_units_box').get(0).style.display = "block"; 
            $('#available_units_box').get(0).style.zIndex = getMaxZIndex() + 1;
            $('.btn_available_units').addClass("checked");
            $('.ico_available_units').get(0).style.marginTop = "6px";
        }, function(){
            $('#available_units_box').get(0).style.display = "none";
            $('.btn_available_units').removeClass("checked");
            $('.ico_available_units').get(0).style.marginTop = "5px";
        });
        $('.btn_available_units').tooltip(LANG.hasOwnProperty(LID) ? getText("labels", "uni") : default_title);
    }

    /*******************************************************************************************************************************
     * Comparison
     * ----------------------------------------------------------------------------------------------------------------------------
     * | ● Compares the units of each unit type
     * ----------------------------------------------------------------------------------------------------------------------------
     *******************************************************************************************************************************/
    function addComparisonButton(){
        $('<div class="btn_comparison circle_button"><div class="ico_comparison js-caption"></div></div>').appendTo(".bull_eye_buttons"); 
        $('.btn_comparison').css({
            top: '51px',
            left: '120px',
            zIndex: '10',
            position: 'absolute'
        });
        $('.btn_comparison .ico_comparison').css({
            margin: '5px 0px 0px 4px', width: '24px', height: '24px',
            background: 'url(http://666kb.com/i/cjq6cxia4ms8mn95r.png) no-repeat 0px 0px',
            backgroundSize: "100%",
            filter: 'url(#Hue1)',
            WebkitFilter: 'hue-rotate(60deg)'
        });
        $('.btn_comparison').on('mousedown', function(){
            $('.ico_comparison').get(0).style.marginTop = "6px";
        });
        $('.btn_comparison').toggleClick(function(){
            $('#unit_box').get(0).style.display = "block"; 
            $('#unit_box').get(0).style.zIndex = getMaxZIndex() + 1;
            $('.btn_comparison').addClass("checked");
            $('.ico_comparison').get(0).style.marginTop = "6px";
        }, function(){
            $('#unit_box').get(0).style.display = "none";
            $('.btn_comparison').removeClass("checked");
            $('.ico_comparison').get(0).style.marginTop = "5px";
        });
        $('.btn_comparison').tooltip(getText("labels", "dsc"));
    }

    function addComparisonBox(){
        var pos = {
            att: { hack: "36%",	pierce: "27%",	distance: "45.5%",	ship: "72.5%" }, 
            def: { hack: "18%",	pierce: "18%",	distance: "18%",	ship: "81.5%" }
        };

        var unitIMG = "https://gpall.innogamescdn.com/images/game/units/units_info_sprite2.51.png";
        $('<div id="unit_box" class="ui-dialog">'+
          '<div class="bbcode_box middle_center"><div class="bbcode_box middle_right"></div><div class="bbcode_box middle_left"></div>'+
          '<div class="bbcode_box top_left"></div><div class="bbcode_box top_right"></div><div class="bbcode_box top_center"></div>'+
          '<div class="bbcode_box bottom_center"></div><div class="bbcode_box bottom_right"></div><div class="bbcode_box bottom_left"></div>'+
          '<div style="height:20px; margin-left:35px;">'+
          '<a class="hack" href="#" style="background: url('+ unitIMG +'); background-position: 0% '+ pos.att.hack +';">'+
          '<span style="margin-left:20px">'+ getText("labels", "hck") +'</span></a>'+
          '<a class="pierce" href="#" style="background: url('+ unitIMG +'); background-position: 0% '+ pos.att.pierce +';">'+
          '<span style="margin-left:20px">'+ getText("labels", "prc") +'</span></a>'+
          '<a class="distance" href="#" style="background: url('+ unitIMG +'); background-position: 0% '+ pos.att.distance +';">'+
          '<span style="margin-left:20px">'+ getText("labels", "dst") +'</span></a>'+
          '<a class="ship" href="#" style="background: url('+ unitIMG +'); background-position: 0% '+ pos.att.ship +';">'+
          '<span style="margin-left:20px">'+ getText("labels", "sea") +'</span></a>'+
          '</div><hr>'+
          '<div class="box_content"></div></div>').appendTo('body');

        $('#unit_box a').css({
            float: 'left',
            backgroundRepeat: 'no-repeat',
            backgroundSize: '25px',
            lineHeight: '2',
            marginRight:'10px'
        });
        $('#unit_box span').css({
            marginLeft: '27px',
        });
        $('#unit_box').draggable({ 
            containment: "body",
            snap: "body",
        });
        $('#unit_box').css({
            position: 'absolute',
            top: '100px',
            left: '200px',
            zIndex: getMaxZIndex() + 1,
            display: 'none'
        });
        $('#unit_box .box_content').css({
            background: 'url(http://s1.directupload.net/images/140206/8jd9d3ec.png) 94% 94% no-repeat',
            backgroundSize: '140px'
        });

        $('#unit_box').bind("mousedown",function(){
            $(this).get(0).style.zIndex = getMaxZIndex() + 1;
        });

        addComparisonTable("hack");
        addComparisonTable("pierce");
        addComparisonTable("distance");
        addComparisonTable("ship");

        $('#unit_box .t_hack').get(0).style.display = "block";

        // Tooltips
        /*
        var labelArray = DM.getl10n("common", "barracks_and_docs"), 
            labelAttack = DM.getl10n("context_menu", "titles").attack, 
            labelDefense = DM.getl10n("place", "tabs")[0];

        $('.tr_att').tooltip(labelAttack);
        $('.tr_def').tooltip(labelDefense + " (Ø)"); 
        $('.tr_def_ship').tooltip(labelDefense);
        $('.tr_spd').tooltip(labelArray.tooltips.speed);
        $('.tr_bty').tooltip(labelArray.tooltips.booty.title); 
        $('.tr_bty_ship').tooltip(labelArray.tooltips.ship_transport.title);
        $('.tr_res').tooltip(labelArray.costs + " (" + 
                             labelArray.cost_details.wood + " + " + 
                             labelArray.cost_details.stone + " + " + 
                             labelArray.cost_details.iron + ")"
                            );
        $('.tr_fav').tooltip(labelArray.costs + " (" + labelArray.cost_details.favor + ")");
        $('.tr_tim').tooltip(labelArray.cost_details.buildtime_barracks + " (s)"); 
        $('.tr_tim_ship').tooltip(labelArray.cost_details.buildtime_docks + " (s)");
        */
        switchComparisonTables();

        $('#unit_box hr').css({ border: '1px solid', color: '#804000', float:'none' });
    }

    function switchComparisonTables(){
        $('#unit_box .hack, #unit_box .pierce, #unit_box .distance, #unit_box .ship').click(function(){
            $('#unit_box [class^="t_"]').css({ display : "none" });
            $('#unit_box .t_'+this.className).get(0).style.display = "block";
        });
    }

    var ttpArray = [], t = 0;
    function addComparisonTable(type){
        var pos = {
            att: { hack: "36%",	pierce: "27%",	distance: "45.5%",	ship: "72.5%" }, 
            def: { hack: "18%",	pierce: "18%",	distance: "18%",	ship: "81.5%" }
        };
        var unitIMG = "https://gpall.innogamescdn.com/images/game/units/units_info_sprite2.51.png";
        var strArray = [
            "<td></td>",
            '<td><div class="bla" style="background: url('+ unitIMG +'); background-position: 0% '+ pos.att[type] +';"></div></td>',
            '<td><div class="bla" style="background: url('+ unitIMG +'); background-position: 0% '+ pos.def[type] +';"></div></td>',
            '<td><div class="bla" style="background: url('+ unitIMG +'); background-position: 0% 63%;"></div></td>',
            (type !== "ship") ? '<td><div class="booty"></div></td>' : '<td><div class="bla" style="background-image: url('+ unitIMG +'); background-position: 0% 91%;"></div></td>',
            '<td><div class="bla" style="background: url('+ unitIMG +'); background-position: 0% 54%;"></div></td>',
            '<td><div class="bla" style="background: url(https://gpall.innogamescdn.com/images/game/res/favor.png)"></div></td>',
            '<td><div class="bla" style="background: url(https://gpall.innogamescdn.com/images/game/res/time.png);"></div></td>'
        ];

        for(var e in uw.GameData.units){
            if(uw.GameData.units.hasOwnProperty(e)){
                var valArray = [];

                if(type === (uw.GameData.units[e].attack_type || "ship") && (e !== "militia")) {
                    valArray.att	= Math.round(uw.GameData.units[e].attack*10 / uw.GameData.units[e].population) / 10;
                    valArray.def	= Math.round(((uw.GameData.units[e].def_hack + uw.GameData.units[e].def_pierce + uw.GameData.units[e].def_distance)*10)/(3*uw.GameData.units[e].population)) / 10;
                    valArray.def	= valArray.def || Math.round(uw.GameData.units[e].defense*10/uw.GameData.units[e].population) / 10;
                    valArray.speed	= uw.GameData.units[e].speed;
                    valArray.booty	= Math.round(((uw.GameData.units[e].booty)*10) / uw.GameData.units[e].population) / 10;
                    valArray.booty	= valArray.booty || Math.round(((uw.GameData.units[e].capacity ? uw.GameData.units[e].capacity + 6 : 0)*10) / uw.GameData.units[e].population) / 10;
                    valArray.favor	= Math.round((uw.GameData.units[e].favor *10)/ uw.GameData.units[e].population) / 10;
                    valArray.res	= Math.round((uw.GameData.units[e].resources.wood + uw.GameData.units[e].resources.stone + uw.GameData.units[e].resources.iron)/(uw.GameData.units[e].population));
                    valArray.time	= Math.round(uw.GameData.units[e].build_time / uw.GameData.units[e].population);

                    valArray.heroStyle		= ""; valArray.heroStyleIMG	= "";

                    // World without Artemis? -> grey griffin and boar
                    if(!uw.Game.hasArtemis && ((e === "griffin") || (e === "calydonian_boar"))){
                        valArray.heroStyle		= "color:black;opacity: 0.4;";
                        valArray.heroStyleIMG	= "filter: url(#GrayScale); -webkit-filter:grayscale(100%); ";
                    }

                    strArray[0] += '<td class="un'+ (t) +'"><div class="unit index_unit unit_icon40x40 ' + e + '" style="'+ valArray.heroStyle + valArray.heroStyleIMG +'"></div></td>';
                    strArray[1] += '<td class="bold" style="color:'+ ((valArray.att>19)?'green;':((valArray.att<10 && valArray.att!=0 )?'red;':'black;')) + valArray.heroStyle +';">'+ valArray.att	+'</td>';
                    strArray[2] += '<td class="bold" style="color:'+ ((valArray.def>19)?'green;':((valArray.def<10 && valArray.def!=0 )?'red;':'black;')) + valArray.heroStyle +';">'+ valArray.def	+'</td>'; 
                    strArray[3] += '<td class="bold" style="'+ valArray.heroStyle +'">'+ valArray.speed	+'</td>'; 
                    strArray[4] += '<td class="bold" style="'+ valArray.heroStyle +'">'+ valArray.booty	+'</td>'; 
                    strArray[5] += '<td class="bold" style="'+ valArray.heroStyle +'">'+ valArray.res	+'</td>'; 
                    strArray[6] += '<td class="bold" style="color:'+ ((valArray.favor>0)?'rgb(0, 0, 214);':'black;') + valArray.heroStyle +';">'+ valArray.favor	+'</td>'; 
                    strArray[7] += '<td class="bold" style="'+ valArray.heroStyle +'">'+ valArray.time	+'</td>'; 

                    ttpArray[t] = uw.GameData.units[e].name; t++;
                }
            }
        }

        $('<table class="t_'+ type +'" cellpadding="1px" style="display:none">'+
          '<tr>'+ strArray[0] +'</tr>'+
          '<tr class="tr_att">'+ strArray[1] +'</tr><tr class="tr_def'+ (type == "ship" ? "_ship" : "") +'">'+ strArray[2] +'</tr>'+
          '<tr class="tr_spd">'+ strArray[3] +'</tr><tr class="tr_bty'+ (type == "ship" ? "_ship" : "") +'">'+ strArray[4] +'</tr>'+
          '<tr class="tr_res">'+ strArray[5] +'</tr><tr class="tr_fav">'+ strArray[6] +'</tr><tr class="tr_tim'+ (type == "ship" ? "_ship" : "") +'">'+ strArray[7] +'</tr>'+
          '</table>').appendTo('#unit_box .box_content');

        for(var i = 0; i <= t; i++){
            $('.un'+i).tooltip(ttpArray[i]);
        }


        //$('#unit_box .box_content').css({ position: 'relative' });
        $('#unit_box .bla').css({
            height: '25px',
            width: '25px',
            backgroundSize: '100%',
            float: 'left'
        });
        $('#unit_box .booty').css({
            width: '26px',
            height: '25px',
            background: 'url(http://s14.directupload.net/images/140404/ki4gwd7x.png)',
            backgroundSize: '95%'
        });
    }

    /*******************************************************************************************************************************
     * Reports and Messages
     * ----------------------------------------------------------------------------------------------------------------------------
     * | ● Storage of the selected filter (only in German Grepolis yet)
     * ----------------------------------------------------------------------------------------------------------------------------
     *******************************************************************************************************************************/

    var filter = "all";
    function saveFilter(){
        $('#dd_filter_type_list .item-list div').each(function(){
            $(this).click(function(){
                filter = $(this).attr("name");
            });
        });
        /*
        var i = 0;
        $("#report_list a").each(function () {
            //console.log((i++) +" = " + $(this).attr('data-reportid'));
        });
        */
    }

    function loadFilter(){
        if(!($('#dd_filter_type_list .selected').attr("name") === filter)){
            $('#dd_filter_type .caption').click();
            $('#dd_filter_type_list .item-list div[name='+ filter +']').click();
        }
    }

    function removeReports(){
        $("#report_list li:contains('spioniert')").each(function () {
            //$(this).remove();
        });
    }

    var zut = 0;
    var messageArray = {};
    function filterPlayer(){
        if(!$('#message_filter_list').get(0)) {
            $('<div id="message_filter_list" style="height:300px;overflow-y:scroll; width: 790px;"></div>').appendTo('#folder_container');
            $("#message_list").get(0).style.display = "none";
        }
        if(zut < parseInt($('.es_last_page').get(0).value, 10)-1){
            $('.es_page_input').get(0).value = zut++;
            $('.jump_button').click();
            $("#message_list li:contains('')").each(function () {
                $(this).appendTo('#message_filter_list');
            });
        } else {
            zut = 1;
        }
    }


    /*******************************************************************************************************************************
	 * World Wonder Ranking - Change
	 *******************************************************************************************************************************/

    function getWorldWonderTypes(){
        $.ajax({
            type: "GET",
            url: 
            "/game/alliance?town_id="+ uw.Game.town_id + "&action=world_wonders&h="+ uw.Game.csrfToken + "&json=%7B%22town_id%22%3A"+ uw.Game.town_id +"%2C%22nlreq_id%22%3A"+ uw.Game.notification_last_requested_id + 
            "%7D&_="+ uw.Game.server_time,
            success: function(text) {
                try {
                    //console.log(JSON.parse(text));
                    temp = JSON.parse(text).json.data.world_wonders;
                    for(var t in temp){
                        if(temp.hasOwnProperty(t)){
                            wonderTypes[temp[t].wonder_type] = temp[t].full_name;
                        }
                    }
                    temp = JSON.parse(text).json.data.buildable_wonders;
                    for(var x in temp){
                        if(temp.hasOwnProperty(x)){
                            wonderTypes[x] = temp[x].name;
                        }
                    }
                    saveValue(MID + "_wonderTypes", JSON.stringify(wonderTypes));
                } catch(error){
                    errorHandling(error, "getWorldWonderTypes");
                }
            }
        });
    }

    function getWorldWonders(){
        $.ajax({
            type: "GET",
            url: "/game/ranking?town_id="+ uw.Game.town_id +"&action=wonder_alliance&h="+ uw.Game.csrfToken + "&json=%7B%22type%22%3A%22all%22%2C%22town_id%22%3A"+ uw.Game.town_id +"%2C%22nlreq_id%22%3A3"+ uw.Game.notification_last_requested_id + 
            "%7D&_="+ uw.Game.server_time
        });
    }


    function changeWWRanking(html){
        if($('#ranking_inner tr', html)[0].children.length !== 1){ // world wonders existing?
            try {
                var ranking = {}, temp_ally, temp_ally_id, temp_ally_link;

                // Save world wonder ranking into array
                $('#ranking_inner tr', html).each(function(){
                    try {
                        if(this.children[0].innerHTML){
                            temp_ally = this.children[1].children[0].innerHTML; // das hier

                            temp_ally_id = this.children[1].children[0].onclick.toString();
                            temp_ally_id = temp_ally_id.substring(temp_ally_id.indexOf(",") + 1);
                            temp_ally_id = temp_ally_id.substring(0, temp_ally_id.indexOf(")"));

                            temp_ally_link = this.children[1].innerHTML;

                        } else {
                            //World wonder name
                            var wonder_name = this.children[3].children[0].innerHTML;

                            for(var w in wonderTypes){
                                if(wonderTypes.hasOwnProperty(w)){
                                    if(wonder_name == wonderTypes[w]){
                                        var level = this.children[4].innerHTML, // world wonder level
                                            ww_data = JSON.parse(atob(this.children[3].children[0].href.split("#")[1])), wonder_link;
                                        //console.log(ww_data);

                                        if(!ranking.hasOwnProperty(level)) {
                                            // add wonder types
                                            ranking[level] = {
                                                colossus_of_rhodes : {},
                                                great_pyramid_of_giza : {},
                                                hanging_gardens_of_babylon : {},
                                                lighthouse_of_alexandria : {},
                                                mausoleum_of_halicarnassus : {},
                                                statue_of_zeus_at_olympia : {},
                                                temple_of_artemis_at_ephesus : {}
                                            };
                                        }

                                        if(!ranking[level][w].hasOwnProperty(temp_ally_id)) {
                                            ranking[level][w][temp_ally_id] = {}; // add alliance array
                                        }
                                        // island coordinates of the world wonder:
                                        ranking[level][w][temp_ally_id].ix = ww_data.ix;
                                        ranking[level][w][temp_ally_id].iy = ww_data.iy;
                                        ranking[level][w][temp_ally_id].sea = this.children[5].innerHTML; // world wonder sea

                                        wonder_link = this.children[3].innerHTML;
                                        if(temp_ally.length > 15){
                                            temp_ally = temp_ally.substring(0,15) + '.';
                                        }
                                        wonder_link = wonder_link.substr(0, wonder_link.indexOf(">")+1) + temp_ally +'</a>';

                                        ranking[level][w][temp_ally_id].ww_link = wonder_link;

                                        // other data of the world wonder
                                        ranking[level][w][temp_ally_id].ally_link = temp_ally_link;
                                        ranking[level][w][temp_ally_id].ally_name = temp_ally; // alliance name
                                        ranking[level][w][temp_ally_id].name = wonder_name; // world wonder name

                                        // Save wonder coordinates for wonder icons on map
                                        if(!wonder.map[w]){ 
                                            wonder.map[w] = {};
                                        }
                                        wonder.map[w][ww_data.ix + "_" + ww_data.iy] = level;
                                        saveValue(WID + "_wonder", JSON.stringify(wonder));

                                    }
                                }
                            }
                        }
                    } catch(error){
                        errorHandling(error, "changeWWRankingEachFunction");
                    }
                });
                //console.log(wonder.map);
                //console.log(ranking);
                if($('#ranking_table_wrapper').get(0)){
                    $('#ranking_fixed_table_header').get(0).innerHTML = '<tr>'+
                        '<td style="width:10px">#</td>'+
                        '<td>Colossus</td>'+
                        '<td>Pyramid</td>'+
                        '<td>Garden</td>'+
                        '<td>Lighthouse</td>'+
                        '<td>Mausoleum</td>'+
                        '<td>Statue</td>'+
                        '<td>Temple</td>'+
                        '</tr>';

                    $('#ranking_fixed_table_header').css({
                        tableLayout: 'fixed',
                        width: '100%',
                        //paddingLeft: '0px',
                        paddingRight: '15px'
                    });

                    var ranking_substr = '', z = 0;
                    for(var level = 10; level >= 1; level--){
                        if(ranking.hasOwnProperty(level)){
                            var complete = "";
                            if(level == 10) { complete = "background: rgba(255, 236, 108, 0.36);"; }

                            // Alternate table background color
                            if(z == 0){
                                ranking_substr += '<tr class="game_table_odd" style="'+ complete +'"><td style="border-right: 1px solid #d0be97;">'+ level +'</td>'; z = 1;
                            } else {
                                ranking_substr += '<tr class="game_table_even" style="'+ complete +'"><td style="border-right: 1px solid #d0be97;">'+ level +'</td>'; z = 0;
                            }
                            for(var w in ranking[level]){
                                if(ranking[level].hasOwnProperty(w)){
                                    ranking_substr += '<td>';

                                    for(var a in ranking[level][w]){
                                        if(ranking[level][w].hasOwnProperty(a)){
                                            ranking_substr += '<nobr>' + ranking[level][w][a].ww_link + '</nobr><br />'; // ww link
                                        }
                                    }
                                    ranking_substr += '</td>';
                                }
                            }
                            ranking_substr += '</tr>';
                        }
                    }

                    var ranking_str = '<table id="ranking_endless_scroll" class="game_table" cellspacing="0"><tr>'+
                        '<td style="width:10px;border-right: 1px solid #d0be97;"></td>'+
                        '<td><div class="dio_wonder" style="background:'+ worldWonderIcon.colossus_of_rhodes			+';margin-left:26px"></div></td>'+	// Colossus
                        '<td><div class="dio_wonder" style="background:'+ worldWonderIcon.great_pyramid_of_giza			+';margin-left:19px"></div></td>'+	// Pyramid
                        '<td><div class="dio_wonder" style="background:'+ worldWonderIcon.hanging_gardens_of_babylon	+';margin-left:19px"></div></td>'+	// Garden 
                        '<td><div class="dio_wonder" style="background:'+ worldWonderIcon.lighthouse_of_alexandria		+';margin-left:24px"></div></td>'+	// Lighthouse 
                        '<td><div class="dio_wonder" style="background:'+ worldWonderIcon.mausoleum_of_halicarnassus	+';margin-left:25px"></div></td>'+	// Mausoleum
                        '<td><div class="dio_wonder" style="background:'+ worldWonderIcon.statue_of_zeus_at_olympia		+';margin-left:25px"></div></td>'+	// Statue
                        '<td><div class="dio_wonder" style="background:'+ worldWonderIcon.temple_of_artemis_at_ephesus	+';margin-left:22px"></div></td>'+	// Temple
                        '</tr>'+ ranking_substr + '</table>';

                    $('#ranking_table_wrapper').get(0).innerHTML = ranking_str;

                    $('#ranking_endless_scroll .dio_wonder').css({
                        width: "65px", height: "60px",
                        backgroundSize: "auto 100%",
                        backgroundPosition: "64px 0px"
                    });

                    $('#ranking_endless_scroll').css({
                        tableLayout: 'fixed',
                        width: '100%',
                        overflowY: 'auto',
                        overflowX: 'hidden',
                        fontSize: '0.7em',
                        lineHeight: '2'
                    });
                    $('#ranking_endless_scroll tbody').css({
                        verticalAlign: 'text-top'
                    });

                    $('#ranking_table_wrapper img').css({
                        width: "60px"
                    });
                    $('#ranking_table_wrapper').css({
                        overflowY: 'scroll'
                    });
                }
            } catch(error){
                errorHandling(error, "changeWWRanking");
            }
        }
        if($('.wonder_ranking').get(0)) {
            $('.wonder_ranking').get(0).style.display = "block";
        }
    }


    /*******************************************************************************************************************************
	 * World Wonder
	 * ----------------------------------------------------------------------------------------------------------------------------
	 * | ● click adjustment
	 * | ● Share calculation (= ratio of player points to alliance points)
	 * | ● Resources calculation & counter (stores amount)
	 * | ● Adds missing previous & next buttons on finished world wonders (better browsing through world wonders)
	 * ----------------------------------------------------------------------------------------------------------------------------
	 *******************************************************************************************************************************/

    // getPointRatio: Default
    function getPointRatioFromAllianceProfile(){
        if(AID){
            $.ajax({
                type: "GET",
                url: '/game/alliance?town_id='+ uw.Game.townId + '&action=profile&h='+ uw.Game.csrfToken + '&json=%7B%22alliance_id%22%3A'+ AID + '%2C%22town_id%22%3A'+ uw.Game.townId +
                '%2C%22nlreq_id%22%3A'+ uw.Game.notification_last_requested_id + '%7D&_='+ uw.Game.server_time,
                success: function(text) {
                    try {
                        text = text.substr(text.indexOf("/li")+14).substr(0, text.indexOf("\ "));
                        var AP = parseInt(text, 10);
                        wonder.ratio[AID] = 100 / AP * uw.Game.player_points;
                        saveValue(WID + "_wonder", JSON.stringify(wonder));
                    } catch(error){
                        errorHandling(error, "getPointRatioFromAllianceProfile");
                    }
                }
            });
        } else {
            wonder.ratio[AID] = -1;
            saveValue(WID + "_wonder", JSON.stringify(wonder));
        }
    }

    function getPointRatioFromAllianceRanking(){
        try {
            if(AID && $('.current_player .r_points').get(0)){
                wonder.ratio[AID] = 100 / parseInt($('.current_player .r_points').get(0).innerHTML, 10) * uw.Game.player_points;
                saveValue(WID + "_wonder", JSON.stringify(wonder));
            }
        } catch(error){
            errorHandling(error, "getPointRatioFromAllianceRaking");
        }
    }

    function getPointRatioFromAllianceMembers(){
        try {
            var ally_points = 0;
            $('#ally_members_body tr').each(function(){
                ally_points += parseInt($(this).children().eq(2).text(), 10) || 0;
            });
            wonder.ratio[AID] = 100 / ally_points * uw.Game.player_points;
            saveValue(WID + "_wonder", JSON.stringify(wonder));
        } catch(error){
            errorHandling(error, "getPointRatioFromAllianceMembers");
        }
    }

    // TODO: Split function...
    function getResWW(){ 
        try {
            var wndArray = uw.GPWindowMgr.getOpen(uw.Layout.wnd.TYPE_WONDERS);

            for(var e in wndArray){
                if(wndArray.hasOwnProperty(e)){
                    var wndID = "#gpwnd_" + wndArray[e].getID() + " ";

                    if($(wndID + '.wonder_progress').get(0)){
                        var res = 0,
                            ww_share = {total: {share:0, sum:0}, stage: {share:0, sum:0}},
                            ww_type = $(wndID + '.finished_image_small').attr('src').split("/")[6].split("_")[0], // Which world wonder?
                            res_stages = [ 2, 4, 6, 10, 16, 28, 48, 82, 140, 238], // Rohstoffmenge pro Rohstofftyp in 100.000 Einheiten
                            stage = parseInt($(wndID + '.wonder_expansion_stage span').get(0).innerHTML.split("/")[0], 10) + 1, // Derzeitige Füllstufe
                            speed = uw.Game.game_speed;

                        wonder.storage[AID] = wonder.storage[AID] || {};

                        wonder.storage[AID][ww_type] = wonder.storage[AID][ww_type] || {};

                        wonder.storage[AID][ww_type][stage] = wonder.storage[AID][ww_type][stage] || 0;

                        if(!$(wndID + '.ww_ratio').get(0)) {
                            $('<fieldset class="ww_ratio"></fieldset>').appendTo(wndID + '.wonder_res_container .trade'); 
                            $(wndID + '.wonder_header').prependTo(wndID + '.wonder_progress');
                            $(wndID + '.wonder_res_container .send_res').insertBefore(wndID + '.wonder_res_container .next_level_res');
                        }

                        $(wndID + '.wonder_progress').css({
                            margin: '0 auto 5px'
                        });
                        $(wndID + '.wonder_header').css({
                            textAlign: 'left',
                            margin: '10px -8px 12px 3px'
                        });
                        $(wndID + '.build_wonder_icon').css({
                            top: '25px',
                        });
                        $(wndID + '.wonder_progress_bar').css({
                            top: '54px',
                        });
                        $(wndID + '.wonder_controls').css({
                            height: '380px',
                        });

                        $(wndID + '.trade fieldset').css({
                            float: 'right',
                        });

                        $(wndID + '.wonder_res_container').css({
                            right: '29px'
                        });

                        $(wndID + '.ww_ratio').css({
                            position: 'relative',
                            height: 'auto'
                        });
                        $(wndID + 'fieldset').css({
                            height: 'auto'
                        });
                        $(wndID + '.town-capacity-indicator').css({
                            marginTop: '0px'
                        });

                        for(var d in res_stages){
                            if(res_stages.hasOwnProperty(d)){
                                ww_share.total.sum += res_stages[d];
                            }
                        }

                        ww_share.total.sum *= speed * 300000;

                        ww_share.total.share = parseInt(wonder.ratio[AID] * (ww_share.total.sum / 100), 10);

                        ww_share.stage.sum = speed * res_stages[stage-1] * 300000;

                        ww_share.stage.share = parseInt(wonder.ratio[AID] * (ww_share.stage.sum / 100), 10); // ( 3000 = 3 Rohstofftypen * 100000 Rohstoffe / 100 Prozent)
                        setResWW(stage, ww_type, ww_share, wndID);


                        $(wndID + '.wonder_res_container .send_resources_btn').click(function(e){
                            try {
                                wonder.storage[AID][ww_type][stage] += parseInt($(wndID + '#ww_trade_type_wood input:text').get(0).value, 10);
                                wonder.storage[AID][ww_type][stage] += parseInt($(wndID + '#ww_trade_type_stone input:text').get(0).value, 10);
                                wonder.storage[AID][ww_type][stage] += parseInt($(wndID + '#ww_trade_type_iron input:text').get(0).value, 10);

                                setResWW(stage, ww_type, ww_share, wndID);
                                saveValue(WID + "_wonder", JSON.stringify(wonder));
                            } catch(error){
                                errorHandling(error, "getResWW_Click");
                            }
                        });

                    } else {
                        $('<div class="prev_ww pos_Y"></div><div class="next_ww pos_Y"></div>').appendTo(wndID + '.wonder_controls');

                        $(wndID + '.wonder_finished').css({ width: '100%' });

                        $(wndID + '.pos_Y').css({
                            top: '-266px',
                        });

                    }
                }
            }
        } catch(error){
            errorHandling(error, "getResWW");
        }
    }

    function setResWW(stage, ww_type, ww_share, wndID){
        try {
            var width_stage, width_total, res_total = 0, disp_stage = "none", disp_total = "none";

            for(var z in wonder.storage[AID][ww_type]){
                if(wonder.storage[AID][ww_type].hasOwnProperty(z)){
                    res_total += wonder.storage[AID][ww_type][z];
                }
            }

            if(ww_share.stage.share > wonder.storage[AID][ww_type][stage]){
                width_stage = (242 / ww_share.stage.share) * wonder.storage[AID][ww_type][stage];
            } else {
                width_stage = 0;
                disp_stage = "block";
            }
            if(ww_share.total.share > res_total){
                width_total = (242 / ww_share.total.share) * res_total;
            } else {
                width_total = 0;
                disp_total = "block";
            }

            $(wndID + '.ww_ratio').get(0).innerHTML = "";
            $(wndID + '.ww_ratio').append('<legend>'+ getText("labels", "leg") +' (<span style="color:#090">'+ (Math.round(wonder.ratio[AID] * 100) / 100) +'%</span>):</legend>'+
                                          '<div class="town-capacity-indicator">'+
                                          '<div class="icon all_res"></div>'+
                                          '<div id="ww_town_capacity_stadium" class="tripple-progress-progressbar">'+
                                          '<div class="border_l"></div><div class="border_r"></div><div class="body"></div>'+
                                          '<div class="progress overloaded">'+
                                          '<div class="indicator3" style="left: 0px; width:'+ width_stage +'px"></div>'+
                                          '<span class="ww_perc">' + Math.round(wonder.storage[AID][ww_type][stage]/ww_share.stage.share*100) + '%</span>'+
                                          '<div class="indicator4" style="left: 0px; display:'+ disp_stage +'"></div>'+
                                          '</div>'+
                                          '<div class="amounts">'+ getText("labels", "stg") +': <span class="curr">'+ pointNumber(wonder.storage[AID][ww_type][stage]) +'</span> / '+
                                          '<span class="max">'+ pointNumber(Math.round(ww_share.stage.share / 1000) * 1000) +'</span></div>'+
                                          '</div></div>'+
                                          '<div class="town-capacity-indicator">'+
                                          '<div class="icon all_res"></div>'+
                                          '<div id="ww_town_capacity_total" class="tripple-progress-progressbar">'+
                                          '<div class="border_l"></div><div class="border_r"></div><div class="body"></div>'+
                                          '<div class="progress overloaded">'+
                                          '<div class="indicator3" style="left: 0px; width:'+ width_total +'px;"></div>'+
                                          '<span class="ww_perc">'+ Math.round(res_total/ww_share.total.share*100) +'%</span>'+
                                          '<div class="indicator4" style="left: 0px; display:'+ disp_total +'"></div>'+
                                          '</div>'+
                                          '<div class="amounts">'+ getText("labels", "tot") +': <span class="curr">'+ pointNumber(res_total) +'</span> / '+
                                          '<span class="max">'+ pointNumber((Math.round(ww_share.total.share / 1000) * 1000)) +'</span></div>'+
                                          '</div></div>');

            $('.ww_ratio .progress').css({
                lineHeight: '1',
                color: 'white',
                fontSize: '0.8em'
            });

            $(wndID + '.ww_perc').css({
                position:'absolute',
                width:'242px',
                textAlign: 'center'
            });

            $(wndID + '.indicator4').css({
                background: 'url(https://gpall.innogamescdn.com/images/game/layout/progressbars-sprite_2.70_compressed.png) no-repeat 0 0',
                backgroundPosition: '0px -355px',
                height: '10px',
                zIndex: '13000',
                width: '242px'
            });
            $(wndID + '.all_res').css({
                background: 'url(https://gpall.innogamescdn.com/images/game/layout/resources.png) no-repeat 0 -90px',
                width: '30px',
                height: '30px',
                margin: '0 auto',
                marginLeft: '5px'
            });
            $(wndID + '.town-capacity-indicator').css({
                marginTop: '0px'
            });

            $(wndID + '.ww_ratio').tooltip("<table style='border-spacing:0px; text-align:right' cellpadding='5px'><tr>"+
                                           "<td align='right' style='border-right: 1px solid;border-bottom: 1px solid'></td>"+
                                           "<td style='border-right: 1px solid; border-bottom: 1px solid'><span class='bbcodes_player bold'>("+ (Math.round((wonder.ratio[AID]) * 100) / 100) +"%)</span></td>"+
                                           "<td style='border-bottom: 1px solid'><span class='bbcodes_ally bold'>(100%)</span></td></tr>"+
                                           "<tr><td class='bold' style='border-right:1px solid;text-align:center'>"+ getText("labels", "stg") + "&nbsp;" + stage +"</td>"+
                                           "<td style='border-right: 1px solid'>"+ pointNumber(Math.round(ww_share.stage.share / 1000) * 1000) +"</td>"+
                                           "<td>" + pointNumber(Math.round(ww_share.stage.sum / 1000) * 1000) + "</td></tr>"+
                                           "<tr><td class='bold' style='border-right:1px solid;text-align:center'>"+ getText("labels", "tot") +"</td>"+
                                           "<td style='border-right: 1px solid'>"+ pointNumber(Math.round(ww_share.total.share / 1000) * 1000) +"</td>"+
                                           "<td>"+ pointNumber(Math.round(ww_share.total.sum / 1000) * 1000) +"</td>"+
                                           "</tr></table>");
        } catch(error){
            errorHandling(error, "setResWW");
        }
    }

    // Adds points to numbers
    function pointNumber(number) {
        var sep; if(LID === "de"){ sep = "."; } else { sep = ",";}

        number = number.toString();
        if (number.length > 3) { 
            var mod = number.length % 3; 
            var output = (mod > 0 ? (number.substring(0,mod)) : '');

            for (var i=0 ; i < Math.floor(number.length / 3); i++) { 
                if ((mod == 0) && (i == 0)) {
                    output += number.substring(mod+ 3 * i, mod + 3 * i + 3); 
                } else {
                    output+= sep + number.substring(mod + 3 * i, mod + 3 * i + 3); 
                }
            } 
            number = output;
        }
        return number;
    }

    /*******************************************************************************************************************************
     * Farming Village Overview
     * ----------------------------------------------------------------------------------------------------------------------------
     * | ● Color change on possibility of city festivals
     * ----------------------------------------------------------------------------------------------------------------------------
     * *****************************************************************************************************************************/

    function changeResColor(){
        var res, res_min, i = 0;
        $('#fto_town_list .fto_resource_count :last-child').reverseList().each(function(){
            if($(this).parent().hasClass("stone")){
                res_min = 18000;
            } else { 
                res_min = 15000;
            }
            res = parseInt($(this).get(0).innerHTML, 10);
            if((res >= res_min) && !($(this).hasClass("town_storage_full"))){
                $(this).get(0).style.color = '#0A0';
            }
            if(res < res_min){
                $(this).get(0).style.color = '#000';
            }
        });
    }

    /********************************************************************************************************************************
     * Conquest Info
     * -----------------------------------------------------------------------------------------------------------------------------
     * | ● Amount of supports und attacks in the conquest window
     * | ● Layout adjustment (for reasons of clarity)
     * | - TODO: conquest window of own cities
     * -----------------------------------------------------------------------------------------------------------------------------
     * ******************************************************************************************************************************/

    function countMovements(){
        var i = 0, a = 0;
        $('#unit_movements .support').each(function(){
            i++;
        });
        $('#unit_movements .attack_land, #unit_movements .attack_sea, #unit_movements .attack_takeover').each(function(){
            a++;
        });

        var str = "<div style='position: absolute;width: 100px;margin-top: -16px;left: 40%;'><div style='float:left;margin-right:5px;'></div>"+
            "<div class='troops' id='count_def'></div>"+
            "<div class='troops' style='color:green;'> " + i + "</div>"+
            "<div class='troops' id='count_off'> </div>"+
            "<div style='color:red;'> " + a + "</div></div>"+
            "<hr class='move_hr'>";

        if($('.gpwindow_content .tab_content .bold').get(0)){
            $('.gpwindow_content .tab_content .bold').append(str);
        } else {
            $('.gpwindow_content h4:eq(1)').append(str);

            // TODO: set player link ?
            /*
            $('#unit_movements li div').each(function(){

                //console.log($(this).get(0).innerHTML);
            });
            */
        }
        $('.move_hr').css({
            margin: '7px 0px 0px 0px',
            backgroundColor: '#5F5242',
            height: '2px',
            border: '0px solid'
        });

        // smaller movements
        $('#unit_movements').css({
            fontSize: '0.80em'
        });
        $('.incoming').css({
            width: '150px',
            height: '45px',
            float: 'left'
        });
        $('#unit_movements div').each(function(){
            if($(this).attr('class') === "unit_movements_arrow"){
                // delete placeholder for arrow of outgoing movements (there are no outgoing movements) 
                if(!$(this).get(0).style.background) { $(this).get(0).remove(); }
            } else {
                // realign texts
                $(this).css({
                    margin: '3px',
                    paddingLeft: '3px'
                });
            }
        });

        $('.troops').css({
            float: 'left',
            margin: '0px 5px 0px 0px',
            height:'18px', 
            width:'18px',
            position: 'relative'
        });
        $('#count_def').css({
            background: 'url(https://gpall.innogamescdn.com/images/game/place/losts.png)',
            backgroundPosition: '0 -36px'
        });
        $('#count_off').css({
            background: 'url(https://gpall.innogamescdn.com/images/game/place/losts.png)',
            backgroundPosition: '0 0px' 
        });
    }

    /*******************************************************************************************************************************
	 * Town window
	 * ----------------------------------------------------------------------------------------------------------------------------
	 * | ● TownTabHandler (trade, attack, support,...)
	 * | ● Sent units box
	 * | ● Short duration: Display of 30% troop speed improvement in attack/support tab
	 * | ● Trade options:
	 * |	- Ressource marks on possibility of city festivals
	 * |	- Percentual Trade: Trade button
	 * |	- Recruiting Trade: Selection boxes (ressource ratio of unit type + share of the warehouse capacity of the target town)
	 * ----------------------------------------------------------------------------------------------------------------------------
	 *******************************************************************************************************************************/
    var arrival_interval = {};
    // TODO: Change both functions in MultipleWindowHandler()
    function TownTabHandler(action){
        var wndArray, wndID, wndA;
        wndArray = Layout.wnd.getOpen(uw.Layout.wnd.TYPE_TOWN);
        //console.log(wndArray);
        for(var e in wndArray){
            if(wndArray.hasOwnProperty(e)){
                //console.log(wndArray[e].getHandler());
                wndA = wndArray[e].getAction(); wndID = "#gpwnd_" + wndArray[e].getID() + " ";
                if(!$(wndID).get(0)) {
                    wndID = "#gpwnd_" + (wndArray[e].getID() + 1) + " ";

                }
                //console.log(wndID);
                if(wndA === action){
                    switch(action){
                        case "trading": 
                            if($(wndID + '#trade_tab').get(0)){
                                if(!$(wndID + '.rec_trade').get(0)){
                                    addRecTrade(wndID);
                                }
                                if(!($(wndID + '.btn_trade').get(0))){
                                    addPercentTrade(wndID, false);
                                }
                            }
                            //addTradeMarks(wndID, 15, 18, 15, "red"); // town festival
                            break;
                        case "support": case "attack":
                            //if(!arrival_interval[wndID]){
                            if(DATA.options.way && !($('.js-casted-powers-viewport .unit_movement_boost').get(0) || $(wndID + '.short_duration').get(0))){
                                //if(arrival_interval[wndID]) console.log("add " + wndID);
                                addShortDuration(wndID);
                            }
                            if(DATA.options.sen){
                                addSentUnitsBox(wndID, action);
                            }
                            //}
                            break;
                        case "rec_mark":
                            //addTradeMarks(wndID, 15, 18, 15, "lime");
                            break;
                    }
                }
            } 
        }
    }

    function WWTradeHandler(){
        var wndArray, wndID, wndA;
        wndArray = uw.GPWindowMgr.getOpen(uw.GPWindowMgr.TYPE_WONDERS);
        for(var e in wndArray){
            if(wndArray.hasOwnProperty(e)){
                wndID = "#gpwnd_" + wndArray[e].getID() + " ";
                if(!($(wndID + '.btn_trade').get(0) || $(wndID +'.next_building_phase').get(0) || $(wndID +'#ww_time_progressbar').get(0))){
                    addPercentTrade(wndID, true);
                }
            }
        }
    }

    /*******************************************************************************************************************************
	 * ● Sent units box
	 *******************************************************************************************************************************/
    function addSentUnitsBox(wndID, action){
        if(!$(wndID + '.sent_units_box').get(0)){
            $('<div class="game_inner_box sent_units_box '+ action +'"><div class="game_border ">'+
              '<div class="game_border_top"></div><div class="game_border_bottom"></div><div class="game_border_left"></div><div class="game_border_right"></div>'+
              '<div class="game_border_corner corner1"></div><div class="game_border_corner corner2"></div><div class="game_border_corner corner3"></div><div class="game_border_corner corner4"></div>'+
              '<div class="game_header bold">'+
              '<div class="icon_sent townicon_'+ (action == "attack" ? "lo" : "ld") +'"></div><span>'+ getText("labels", "lab") +' ('+ (action == "attack" ? "OFF" : "DEF") +')</span>'+
              '</div>'+
              '<div class="troops"><div class="units_list"></div><hr style="width: 172px;border: 1px solid rgb(185, 142, 93);margin: 3px 0px 2px -1px;">'+
              '<div id="btn_sent_units_reset" class="button_new">'+
              '<div class="left"></div>'+
              '<div class="right"></div>'+
              '<div class="caption js-caption">'+ getText("buttons", "res") +'<div class="effect js-effect"></div></div>'+
              '</div>'+
              '</div></div>').appendTo(wndID + '.attack_support_window');

            updateSentUnitsBox(action);

            $(wndID + '.icon_sent').css({
                height: '20px',
                marginTop: '-2px',
                width: '20px',
                backgroundPositionY: '-26px',
                paddingLeft: '0px',
                marginLeft: '0px'
            });

            $(wndID + '.sent_units_box').css({
                position: 'absolute',
                right: '0px',
                bottom: '16px',
                width: '192px',
                //border: '2px solid green',
                //borderRadius: '5px',
                //padding: '5px'
            });
            $(wndID + '.troops').css({ padding: '6px 0px 6px 6px' });

            $(wndID + '#btn_sent_units_reset').click(function(){
                // Overwrite old array
                sentUnitsArray[action] = {}; updateSentUnitsBox(action);
            });
        }
    }

    function getSentUnits(){
        $.Observer(uw.GameEvents.command.send_unit).subscribe('DIO_SEND_UNITS', function(e,data){
            try {
                for(var z in data.params){
                    if(data.params.hasOwnProperty(z) && (data.sending_type !== "")){
                        if(uw.GameData.units[z]){
                            sentUnitsArray[data.sending_type][z] = (sentUnitsArray[data.sending_type][z] == undefined ? 0 : sentUnitsArray[data.sending_type][z]);
                            sentUnitsArray[data.sending_type][z] += data.params[z];
                        }
                    }
                }
                //updateSentUnitsBox(data.sending_type);
            } catch(error){
                errorHandling(error, "getSentUnits");
            }
        });
    }

    function updateSentUnitsBox(action){
        try {
            // Remove old unit list
            $('.sent_units_box.'+ action +' .units_list').each(function(){
                $(this).get(0).innerHTML = "";
            });

            // Add new unit list
            for(var x in sentUnitsArray[action]){
                if(sentUnitsArray[action].hasOwnProperty(x)){
                    if((sentUnitsArray[action][x] || 0) > 0){
                        $('.sent_units_box.'+ action +' .units_list').each(function(){
                            $(this).append('<div class="unit_icon25x25 '+ x + 
                                           (sentUnitsArray[action][x] >= 1000  ? (sentUnitsArray[action][x] >= 10000  ? " five_digit_number" : " four_digit_number") : "") +'">'+
                                           '<span class="count text_shadow">'+ sentUnitsArray[action][x] +'</span>'+
                                           '</div>');
                        });
                    }
                }
            }
            saveValue(WID +"_sentUnits", JSON.stringify(sentUnitsArray));
        } catch(error){
            errorHandling(error, "updateSentUnitsBox");
        }
    }

    /*******************************************************************************************************************************
	 * ● Short duration
	 *******************************************************************************************************************************/

    function addShortDuration(wndID){
        //console.log($(wndID + ".duration_container").get(0));
        try {
            //var tooltip = (LANG.hasOwnProperty(LID) ? getText("labels", "improved_movement") : "") + " (+30% "+ DM.getl10n("common", "barracks_and_docs").tooltips.speed.trim() + ")";
            var tooltip = (LANG.hasOwnProperty(LID) ? getText("labels", "improved_movement") : "") + " (+30%)";

            $('<table class="dio_duration">'+
              '<tr><td class="way_icon"></td><td class="dio_way"></td><td class="arrival_icon"></td><td class="dio_arrival"></td><td colspan="2" class="dio_night"></td></tr>'+
              '<tr class="short_duration_row" style="color:darkgreen">'+
              '<td>&nbsp;╚&gt;&nbsp;</td><td><span class="short_duration">~0:00:00</span></td>'+
              '<td>&nbsp;&nbsp;&nbsp;╚&gt;</td><td><span class="short_arrival">~00:00:00</span></td>'+
              '<td class="short_icon"></td><td></td></tr>'+
              '</table>').prependTo(wndID + ".duration_container");


            $(wndID + ".nightbonus").appendTo(wndID + ".dio_night");
            $(wndID + '.way_duration').appendTo(wndID + ".dio_way");
            $(wndID + ".arrival_time").appendTo(wndID + ".dio_arrival");


            // Style
            $(wndID + '.duration_container').css({
                width:'auto'
            });
            $(wndID + '.dio_duration').css({
                borderSpacing: '0px',
                marginBottom: '2px',
                textAlign: 'right'
            });
            $(wndID + '.dio_way span,'+ wndID + '.dio_arrival span').css({
                padding: '0px 0px 0px 0px',
                background: 'none'
            });
            $(wndID + '.short_icon').css({
                padding: '20px 0px 0px 30px',
                background: 'url(http://666kb.com/i/ck2c7eohpyfa3yczt.png) 11px -1px / 21px no-repeat',
                WebkitFilter: 'hue-rotate(50deg)'
            });
            $(wndID + '.way_icon').css({
                padding: '30px 0px 0px 30px',
                background: 'transparent url(https://gpall.innogamescdn.com/images/game/towninfo/traveltime.png) no-repeat 0 0'
            });
            $(wndID + '.arrival_icon').css({
                padding: '30px 0px 0px 30px',
                background: 'transparent url(https://gpall.innogamescdn.com/images/game/towninfo/arrival.png) no-repeat 0 0'
            });
            $(wndID + '.max_booty').css({
                padding: '0px 0px 0px 30px',
                margin: '3px 0 4px 4px',
                width: 'auto'
            });
            $(wndID + '.fast_boats_needed').css({
                background: 'transparent url(http://s7.directupload.net/images/140724/4pvfuch8.png) no-repeat 0 0',
                padding: '2px 10px 7px 24px',
                margin: '0px 0px 0px 6px'
            });
            $(wndID + '.slow_boats_needed').css({
                background: 'transparent url(http://s1.directupload.net/images/140724/b5xl8nmj.png) no-repeat 0 0',
                padding: '2px 10px 7px 24px',
                margin: '0px 0px 0px 6px'
            });

            // Tooltip
            $(wndID + '.short_duration_row').tooltip(tooltip);

            // Detection of changes
            changeShortDuration(wndID);
            /*
            $(wndID + '.way_duration').bind('DOMSubtreeModified', function(e) { console.log(e); }); // Alternative
            */



        } catch(error){
            errorHandling(error, "addShortDuration");
        }
    }

    function changeShortDuration(wndID){
        var duration = new MutationObserver(function(mutations) {
            mutations.forEach(function(mutation) {
                if(mutation.addedNodes[0]){
                    //console.log(mutation);
                    calcShortDuration(wndID);
                }
            });    
        });
        if($(wndID + '.way_duration').get(0)){
            duration.observe($(wndID + '.way_duration').get(0), { attributes: false, childList: true, characterData: false});
        }
    }

    //$('<style> .duration_container { display: block !important } </style>').appendTo("head");

    function calcShortDuration(wndID){
        //console.log(wndID);
        //console.log($(wndID + '.duration_container .way_duration').get(0));
        try {
            var setup_time = 900/uw.Game.game_speed,
                duration_time = $(wndID + '.duration_container .way_duration').get(0).innerHTML.replace("~","").split(":"), 
                // TODO: hier tritt manchmal Fehler auf TypeError: Cannot read property "innerHTML" of undefined at calcShortDuration (<anonymous>:3073:86) 
                arrival_time,
                h,m,s,
                atalanta_factor = 0;

            // Atalanta aktiviert?
            if($(wndID + '.unit_container.heroes_pickup .atalanta').get(0)){
                if($(wndID + '.cbx_include_hero').hasClass("checked")) {
                    // Beschleunigung hängt vom Level ab, Level 1 = 11%, Level 20 = 30%
                    var atalanta_level = MM.getCollections().PlayerHero[0].models[1].attributes.level;

                    atalanta_factor = (atalanta_level + 10) / 100;
                }
            }

            // Sekunden, Minuten und Stunden zusammenrechnen (-> in Sekunden)
            duration_time = ((parseInt(duration_time[0], 10)*60 + parseInt(duration_time[1], 10))*60 + parseInt(duration_time[2], 10));

            // Verkürzte Laufzeit berechnen
            duration_time = ((duration_time - setup_time) * (1 + atalanta_factor)) / (1 + 0.3 + atalanta_factor) + setup_time;

            h = Math.floor(duration_time/3600);
            m = Math.floor((duration_time - h*3600)/60);
            s = Math.floor(duration_time - h*3600 - m*60);

            if(m < 10) { m = "0" + m; }
            if(s < 10) { s = "0" + s; }

            $(wndID + '.short_duration').get(0).innerHTML = "~"+ h +":" + m + ":" + s;

            arrival_time = Math.round((Timestamp.server() + Game.server_gmt_offset)) + duration_time;

            h = Math.floor(arrival_time/3600);
            m = Math.floor((arrival_time - h*3600)/60);
            s = Math.floor(arrival_time - h*3600 - m*60);

            h %= 24;

            if(m < 10) { m = "0" + m; }
            if(s < 10) { s = "0" + s; }

            $(wndID + '.short_arrival').get(0).innerHTML = "~" + h + ":" + m + ":" + s;

            clearInterval(arrival_interval[wndID]);
            arrival_interval[wndID] = setInterval(function(){
                arrival_time += 1;

                h = Math.floor(arrival_time/3600);
                m = Math.floor((arrival_time - h*3600)/60);
                s = Math.floor(arrival_time - h*3600 - m*60);

                h %= 24;

                if(m < 10) { m = "0" + m; }
                if(s < 10) { s = "0" + s; }

                if($(wndID + '.short_arrival').get(0)){
                    $(wndID + '.short_arrival').get(0).innerHTML = "~" + h + ":" + m + ":" + s;
                } else {
                    clearInterval(arrival_interval[wndID]);
                }
            }, 1000);

        } catch(error){
            errorHandling(error, "calcShortDuration");
        }
    }

    /*******************************************************************************************************************************
	 * ● Dropdown menu
	 *******************************************************************************************************************************/

    // Preload images for drop down arrow buttons
    var drop_over = new Image(); drop_over.src = "http://s7.directupload.net/images/140107/hna95u8a.png";
    var drop_out = new Image(); drop_out.src = "http://s14.directupload.net/images/140107/ppsz5mxk.png";

    function changeDropDownButton(){
        /*
        $('<style type="text/css">' +
          '#dd_filter_type .arrow, .select_rec_unit .arrow {' + 
          'width: 18px !important; height: 17px !important; background: url("http://s14.directupload.net/images/140107/ppsz5mxk.png") no-repeat 0px -1px !important;' + 
          'position: absolute; top: 2px !important; right: 3px;' +
          '</style>').appendTo('head');	
        */


        $('.arrow').css({
            width: '18px',
            height: '17px',
            background: 'url('+ drop_out.src +') no-repeat -1px -1px',
            position: 'absolute',
            top: '2px',
            right: '3px'
        });
    }

    var o = 1; // ????????????????????????????

    /*******************************************************************************************************************************
     * ● Recruiting Trade
     * *****************************************************************************************************************************/
    var trade_count = 0, unit = "FS", percent = "0.0"; // Recruiting Trade

    function addRecTrade(wndID){
        var max_amount;

        $('<div class="rec_trade">'+
          // DropDown-Button for unit
          '<div class="drop_rec_unit dropdown default">'+
          '<div class="border-left"></div>'+
          '<div class="border-right"></div>'+
          '<div class="caption" name="'+ unit +'">'+ unit +'</div>'+
          '<div class="arrow"></div>'+
          '</div>'+
          '<div class="drop_rec_perc dropdown default">'+
          // DropDown-Button for ratio
          '<div class="border-left"></div>'+
          '<div class="border-right"></div>'+
          '<div class="caption" name="'+ percent +'">'+ Math.round(percent * 100)+'%</div>'+
          '<div class="arrow"></div>'+
          '</div></div><span class="rec_count" style="top:30px">('+ trade_count +')</span>').appendTo(wndID + ".content");

        // Select boxes for unit and ratio
        $('<div class="select_rec_unit dropdown-list default active">'+
          '<div class="item-list">'+
          '<div class="option_s unit index_unit unit_icon40x40 attack_ship" name="FS"></div>'+
          '<div class="option_s unit index_unit unit_icon40x40 bireme" name="BI"></div>'+
          '<div class="option_s unit index_unit unit_icon40x40 sword" name="SK"></div>'+
          '<div class="option_s unit index_unit unit_icon40x40 slinger" name="SL"></div>'+
          '<div class="option_s unit index_unit unit_icon40x40 archer" name="BS"></div>'+
          '<div class="option_s unit index_unit unit_icon40x40 hoplite" name="HO"></div>'+
          '<div class="option_s unit index_unit unit_icon40x40 rider" name="RE"></div>'+
          '<div class="option_s unit index_unit unit_icon40x40 chariot" name="SW"></div>'+
          '</div></div>').appendTo(wndID + ".rec_trade");
        $('<div class="select_rec_perc dropdown-list default inactive">'+
          '<div class="item-list">'+
          '<div class="option sel" name="0.0">&nbsp;&nbsp;0%</div>'+
          '<div class="option" name="0.05">&nbsp;&nbsp;5%</div>'+
          '<div class="option" name="0.1">10%</div>'+
          '<div class="option" name="0.16666">17%</div>'+
          '<div class="option" name="0.2">20%</div>'+
          '<div class="option" name="0.25">25%</div>'+
          '<div class="option" name="0.33">33%</div>'+
          '<div class="option" name="0.5">50%</div>'+
          '</div></div>').appendTo(wndID + ".rec_trade");

        $(wndID + ".rec_trade [name='"+ unit +"']").toggleClass("sel");

        // Styles
        $(wndID + '.rec_trade').css({ position: 'absolute', left: '30px', top: '70px' });
        $(wndID + '.select_rec_unit').css({
            position: 'absolute',
            top: '20px',
            width: '84px',
            display: "none"
        });
        $(wndID + '.select_rec_perc').css({
            position: 'absolute',
            left: '50px',
            top: '20px',
            width: '50px',
            display: "none"
        });
        $(wndID + '.item-list').css({ maxHeight: '400px', maxWidth: '200px', align: "right" });

        $(wndID + '.arrow').css({
            width: '18px',
            height: '18px',
            background: 'url('+ drop_out.src +') no-repeat -1px -1px',
            position: 'absolute',
        });

        $(wndID + '.option_s').css({
            filter: "url(#GrayScale)",
            WebkitFilter: "grayscale(100%)",
            cursor: 'pointer',
            color: 'black',
            lineHeight: '14px',
            float: 'left',

            position: 'relative',
            width: '40px',
            margin: '0px',
            padding: '0px'
        });

        $('.select_rec_unit .sel').css({"filter": "url(#Sepia)", "-webkit-filter" : "sepia(100%)"});

        // hover effects of the elements in the drop menus
        $(wndID + '.option_s').hover(
            function(){
                //console.log(this.className); 
                $(this).css({ "filter": "none", "-webkit-filter" : "grayscale(0%) sepia(0%)"});
                if(!($(this).hasClass("sel"))){ 
                    $('.option_s .sel').css({"filter": "url(#Sepia)", "-webkit-filter" : "grayscale(0%) sepia(100%)" });
                }
            },
            function(){
                $('.select_rec_unit .option_s').css({ "filter": "url(#GrayScale)", "-webkit-filter" : "grayscale(100%) sepia(0%)" });
                $('.select_rec_unit .sel').css({ "filter": "url(#Sepia)", "-webkit-filter" : "grayscale(0%) sepia(100%)" });
            }
        );
        $(wndID + '.option').hover(
            function(){ $(this).css({color: '#fff', background: "#328BF1"}); },
            function(){ $(this).css({color: '#000', background: "#FFEEC7"}); }
        );

        // click events of the drop menu
        $(wndID + ' .select_rec_unit .option_s').each(function(){
            $(this).click(function(e){
                $(".select_rec_unit .sel").toggleClass("sel");
                $("." + this.className.split(" ")[4]).toggleClass("sel");

                unit = $(this).attr("name");
                $('.drop_rec_unit .caption').attr("name", unit);
                $('.drop_rec_unit .caption').each(function(){
                    $(this).get(0).innerHTML = unit;
                });
                $(this).parent().parent().get(0).style.display = "none";
                $('.drop_rec_unit .caption').change();
            });
        });
        $(wndID + ' .select_rec_perc .option').each(function(){
            $(this).click(function(e){
                $(this).parent().find(".sel").toggleClass("sel");
                $(this).toggleClass("sel");

                percent = $(this).attr("name");
                $('.drop_rec_perc .caption').attr("name", percent);
                $('.drop_rec_perc .caption').each(function(){
                    $(this).get(0).innerHTML = Math.round(percent * 100)+"%";
                });
                $(this).parent().parent().get(0).style.display = "none";
                $('.drop_rec_perc .caption').change();
            });
        });

        // show & hide drop menus on click
        $(wndID + '.drop_rec_perc').click(function(e){
            if($(e.target)[0].parentNode.parentNode.childNodes[3].style.display === "none"){
                $(e.target)[0].parentNode.parentNode.childNodes[3].style.display = "block";
                $(e.target)[0].parentNode.parentNode.childNodes[2].style.display = "none";
            } else {
                $(e.target)[0].parentNode.parentNode.childNodes[3].style.display = "none";
            }
        });
        $(wndID + '.drop_rec_unit').click(function(e){
            if($(e.target)[0].parentNode.parentNode.childNodes[2].style.display === "none"){
                $(e.target)[0].parentNode.parentNode.childNodes[2].style.display = "block";
                $(e.target)[0].parentNode.parentNode.childNodes[3].style.display = "none";
            } else {
                $(e.target)[0].parentNode.parentNode.childNodes[2].style.display = "none";
            }
        });

        $(wndID).click(function(e){
            var clicked = $(e.target), element = $('#' + this.id + ' .select_rec_unit').get(0);
            if(!(clicked[0].parentNode.className.split(" ")[1] === "dropdown") && element){
                element.style.display = "none";
            }
        });

        // hover arrow change
        $(wndID + '.dropdown').hover(function(e){
            $(e.target)[0].parentNode.childNodes[3].style.background = "url('"+ drop_over.src +"') no-repeat -1px -1px";
        }, function(e){
            $(e.target)[0].parentNode.childNodes[3].style.background = "url('"+ drop_out.src +"') no-repeat -1px -1px";
        });

        $(wndID + ".drop_rec_unit .caption").attr("name", unit);
        $(wndID + ".drop_rec_perc .caption").attr("name",percent);

        $(wndID + '.drop_rec_unit').tooltip(getText("labels", "rat"));
        $(wndID + '.drop_rec_perc').tooltip(getText("labels", "shr"));

        var ratio = {NO: {w:0,		s: 0,		i: 0		}, 
                     FS: {w:1,		s: 0.2308,	i: 0.6154	}, 
                     BI: {w:1,		s: 0.8750,	i: 0.2250	}, 
                     SL: {w:0.55,	s: 1,		i: 0.4		}, 
                     RE: {w:0.6666, s: 0.3333,	i: 1		}, 
                     SK: {w:1,		s: 0,		i: 0.8947	},  
                     HO: {w:0,		s: 0.5,		i: 1		}, 
                     BS: {w:1,		s: 0,		i: 0.6250	},  
                     SW: {w:0.4545, s: 1,		i: 0.7273	}
                    };


        if($('#town_capacity_wood .max').get(0)){
            max_amount = parseInt($('#town_capacity_wood .max').get(0).innerHTML, 10); 
        } else {
            max_amount = 25500;
        }

        $(wndID + '.caption').change(function(e){
            //console.log($(this).attr('name') + ", " + unit + "; " + percent);
            if(!(($(this).attr('name') === unit) || ($(this).attr('name') === percent))){
                //trade_count = 0;
                $('.rec_count').get(0).innerHTML = "(" + trade_count + ")";
            }

            var tmp = $(this).attr('name');

            if($(this).parent().attr('class').split(" ")[0] === "drop_rec_unit"){
                unit = tmp;
            } else {
                percent = tmp;
            }
            var max = (max_amount - 100)/1000;
            addTradeMarks(max * ratio[unit].w, max * ratio[unit].s, max * ratio[unit].i, "lime");

            var part = (max_amount - 1000) * parseFloat(percent); // -1000 als Puffer (sonst Überlauf wegen Restressies, die nicht eingesetzt werden können, vorallem bei FS und Biremen)
            var rArray = uw.ITowns.getTown(uw.Game.townId).getCurrentResources();
            var tradeCapacity = uw.ITowns.getTown(uw.Game.townId).getAvailableTradeCapacity();

            var wood = ratio[unit].w * part;
            var stone= ratio[unit].s * part;
            var iron = ratio[unit].i * part;

            if((wood > rArray.wood) || (stone > rArray.stone) || (iron > rArray.iron) || ( (wood + stone + iron) > tradeCapacity)) { 
                wood = stone = iron = 0;
                $('.drop_rec_perc .caption').css({color:'#f00'}); 
                //$('.' + e.target.parentNode.parentNode.className + ' .select_rec_perc .sel').css({color:'#f00'});
                //$('.select_rec_perc .sel').css({color:'#f00'});
            } else {
                $('.' + e.target.parentNode.parentNode.className + ' .drop_rec_perc .caption').css({color:'#000'});
            }
            $("#trade_type_wood [type='text']").select().val(wood).blur();
            $("#trade_type_stone [type='text']").select().val(stone).blur();
            $("#trade_type_iron [type='text']").select().val(iron).blur();
        });

        $('#trade_button').click(function(){
            trade_count++;
            $('.rec_count').get(0).innerHTML = "(" + trade_count + ")";

        });

        $(wndID + '.rec_count').css({
            position: 'absolute',
            display: 'block',
            left: '33px',
            top: '95px',
            width: '20px'
        });
        $(wndID + '.drop_rec_unit').css({
            position: 'absolute',
            display: 'block',
            width: '50px',
            overflow: 'visible'
        });
        $(wndID + '.drop_rec_perc').css({
            position: 'absolute',
            display: 'block',
            left: '49px',
            width: '55px',
            color:'#000'
        });
        $(wndID + '.drop_rec_perc .caption').change();
    }
    /*******************************************************************************************************************************
	 * ● Ressources marks
	 *******************************************************************************************************************************/
    function addTradeMarks(woodmark, stonemark, ironmark, color){
        var max_amount, limit, wndArray = uw.GPWindowMgr.getOpen(uw.Layout.wnd.TYPE_TOWN), wndID;
        for(var e in wndArray){
            if(wndArray.hasOwnProperty(e)){ 
                wndID = "#gpwnd_" + wndArray[e].getID() + " ";
                if($(wndID + '.town-capacity-indicator').get(0)){

                    max_amount = $(wndID + '.amounts .max').get(0).innerHTML;

                    $('#trade_tab .c_'+ color).each(function(){
                        $(this).get(0).remove();
                    });
                    $('#trade_tab .progress').each(function(){
                        if($("p", this).length < 3) {
                            if($(this).parent().get(0).id != "big_progressbar"){
                                limit = 1000 * (242 / parseInt(max_amount, 10));

                                switch($(this).parent().get(0).id.split("_")[2]){
                                    case "wood":	limit = limit * woodmark; break;
                                    case "stone":	limit = limit * stonemark; break;
                                    case "iron":	limit = limit * ironmark; break;
                                }
                                $('<p class="c_'+ color +'"style="position:absolute;left: '+ limit +'px; background:'+ color +';width:2px;height:100%;margin:0px"></p>').appendTo(this);
                            }
                        }  
                    });
                }
            }
        }
    }

    /*******************************************************************************************************************************
	 * ● Percentual Trade
	 *******************************************************************************************************************************/
    var rest_count = 0;

    function addPercentTrade(wndID, ww){

        var a = ""; var content = wndID + ".content";
        if(ww) {
            a = "ww_";
            content = wndID + '.trade .send_res';
        }
        $('<div class="btn btn_trade"><a class="button" href="#">'+
          '<span class="left"><span class="right">'+
          '<span class="middle mid">'+
          '<span class="img_trade"></span></span></span></span>'+
          '<span style="clear:both;"></span>'+
          '</a></div>').prependTo(content);

        $(wndID + '.btn_trade').tooltip(getText("labels", "per"));

        setPercentTrade(wndID, ww);

        // Style
        $(wndID + '.btn').css({ width: '20px', overflow: 'visible', position: 'absolute', display: 'block' });

        if(!ww){ $(wndID + '.content').css({ height: '320px' }); }

        if(ww){
            $(wndID + '.btn_trade').css({ left: '678px', top: '154px' });
        } else {
            $(wndID + '.btn_trade').css({ left: '336px', top: '135px' });
        }

        $(wndID + '.mid').css({ minWidth: '26px' });

        $(wndID + '.img_trade').css({
            width: '27px',
            height: '27px',
            top: '-3px',
            float: 'left',
            position: 'relative',
            background: 'url("http://666kb.com/i/cjq6d72qk521ig1zz.png") no-repeat'
        });

    }

    var res = {};
    function setPercentTrade(wndID, ww){
        var a = ww ? "ww_" : "", own_town = $(wndID + '.town_info').get(0) ? true : false; 

        $(wndID + '.btn_trade').toggleClick(
            function(){
                res.wood = {}; res.stone = {}; res.iron = {}; res.sum = {};

                res.sum.amount = 0;
                // Set amount of resources to 0
                setAmount(true, a, wndID);
                // Total amount of resources // TODO: ITowns.getTown(Game.townId).getCurrentResources(); ?
                for(var e in res){
                    if(res.hasOwnProperty(e) && e != "sum") {
                        res[e].rest = false;
                        res[e].amount = parseInt($('.ui_resources_bar .'+ e +' .amount').get(0).innerHTML, 10);
                        res.sum.amount += res[e].amount;
                    }
                }
                // Percentage of total resources
                res.wood.percent = 100/res.sum.amount * res.wood.amount;
                res.stone.percent = 100/res.sum.amount * res.stone.amount;
                res.iron.percent = 100/res.sum.amount * res.iron.amount;

                // Total trading capacity
                res.sum.cur = parseInt($(wndID + '#' + a + 'big_progressbar .caption .curr').get(0).innerHTML, 10);
                //res.sum.max = parseInt($(wndID + '#' + a + 'big_progressbar .caption .max').get(0).innerHTML, 10) - res.sum.cur;

                // Amount of resources on the percentage of trading capacity (%)
                res.wood.part =  parseInt(res.sum.cur/100 * res.wood.percent, 10);
                res.stone.part =  parseInt(res.sum.cur/100 * res.stone.percent, 10);
                res.iron.part =  parseInt(res.sum.cur/100 * res.iron.percent, 10);

                // Get rest warehouse capacity of each resource type
                for(var f in res){
                    if(res.hasOwnProperty(f) && f != "sum") {
                        if(!ww && own_town){ // Own town
                            var curr	= parseInt($(wndID + '#town_capacity_'+ f +' .amounts .curr').get(0).innerHTML.replace('+', '').trim(), 10) || 0,
                                curr2	= parseInt($(wndID + '#town_capacity_'+ f +' .amounts .curr2').get(0).innerHTML.replace('+', '').trim(), 10) || 0,
                                max		= parseInt($(wndID + '#town_capacity_'+ f +' .amounts .max').get(0).innerHTML.replace('+', '').trim(), 10) || 0;

                            res[f].cur = curr + curr2;
                            res[f].max = max  - res[f].cur;

                            if(res[f].max < 0) { res[f].max = 0; }

                        } else { // World wonder or foreign town
                            res[f].max = 30000;
                        }
                    }
                } 
                // Rest of fraction (0-2 units) add to stone amount
                res.stone.part += res.sum.cur - (res.wood.part + res.stone.part + res.iron.part);

                res.sum.rest = 0;
                rest_count = 0;
                calcRestAmount();
                setAmount(false, a, wndID);
            }, 
            function(){
                setAmount(true, a, wndID);
            }
        );
    }

    function calcRestAmount(){
        // Subdivide rest
        if(res.sum.rest > 0){
            for(var e in res){
                if(res.hasOwnProperty(e) && e != "sum" && res[e].rest != true) {
                    res[e].part += res.sum.rest/(3 - rest_count);
                }
            }
            res.sum.rest = 0;
        }
        // Calculate new rest
        for(var f in res){
            if(res.hasOwnProperty(f) && f != "sum" && res[f].rest != true) {
                if(res[f].max <= res[f].part) {
                    res[f].rest = true;
                    res.sum.rest += res[f].part - res[f].max;
                    rest_count += 1;
                    res[f].part = res[f].max;
                }
            }
        }
        // Recursion
        if(res.sum.rest > 0 && rest_count < 3){
            calcRestAmount();
        }
    }

    function setAmount(clear, a, wndID){
        for(var e in res){
            if(res.hasOwnProperty(e) && e !== "sum") {
                if(clear == true) { res[e].part = 0; }
                $(wndID + "#" + a + "trade_type_" + e + ' [type="text"]').select().val(res[e].part).blur();
            }
        }
    }

    /* ******************************************************************************************************************************
     * Unit strength (blunt/sharp/distance) and Transport Capacity
     * ----------------------------------------------------------------------------------------------------------------------------
     * | ● Unit strength: Unit menu
     * |	- Switching of def/off display with buttons
     * |	- Possible Selection of certain unit types
     * | ● Unit strength: Siege
     * | ● Unit strength: Barracks
     * | ● Transport capacity: Unit menu
     * |	- Switching of transporter speed (+/- big transporter)
     * ----------------------------------------------------------------------------------------------------------------------------
     * ******************************************************************************************************************************/

    var def = true, blunt = 0, sharp = 0, dist = 0, shipsize = false;

    function getSelectedUnitsMenu(){
        var units = [];
        if($(".units_land .units_wrapper .selected").length > 0){
            $(".units_land .units_wrapper .selected").each(function(){
                units[$(this).get(0).className.split(" ")[1]] = $(this).get(0).children[0].innerHTML;
            });
        } else {
            $(".units_land .units_wrapper .unit").each(function(){
                units[$(this).get(0).className.split(" ")[1]] = $(this).get(0).children[0].innerHTML;
            });
        }
        return units;
    }

    // Calculate defensive strength
    function calcDef(units){
        var e; blunt = sharp = dist = 0;
        for(e in units) {
            if(units.hasOwnProperty(e)) {
                blunt += units[e] * uw.GameData.units[e].def_hack;
                sharp += units[e] * uw.GameData.units[e].def_pierce;
                dist  += units[e] * uw.GameData.units[e].def_distance;
            }
        }
    }
    // Calculate offensive strength
    function calcOff(units, selectedUnits){
        var e; blunt = sharp = dist = 0;
        for(e in selectedUnits) {
            if(selectedUnits.hasOwnProperty(e)) {
                var attack = (units[e] || 0) * uw.GameData.units[e].attack;
                switch(uw.GameData.units[e].attack_type){
                    case 'hack':	blunt += attack;	break;
                    case 'pierce':	sharp += attack;	break;
                    case 'distance':dist  += attack;	break;
                }
            }
        }
    }

    /*******************************************************************************************************************************
	 * ● Unit strength: Unit menu
	 *******************************************************************************************************************************/
    function setStrengthMenu() {
        try{
            var unitsIn = uw.ITowns.getTown(uw.Game.townId).units(),
                e, units = getSelectedUnitsMenu();

            // Calculation
            if(def==true){
                calcDef(units);
            } else {
                calcOff(unitsIn, units);
            }
            $('#blunt').get(0).innerHTML = blunt;
            $('#sharp').get(0).innerHTML = sharp;
            $('#dist').get(0).innerHTML = dist;

            setTransportCapacity(units);
        }catch(e){
            handleError(e, "setStrengthMenu");
        }
    }


    function addStrengthMenu(){
        $('<hr><div id="strength" class="cont_left"><span id="str_font" class="bold text_shadow" style="color:#FFCC66;font-size: 0.8em;">'+
          '<table style="margin:0px;">'+
          '<tr><td><div class="ico units_info_sprite img_hack"></td><td id="blunt">0</td></tr>'+
          '<tr><td><div class="ico units_info_sprite img_pierce"></td><td id="sharp">0</td></tr>'+
          '<tr><td><div class="ico units_info_sprite img_dist"></td><td id="dist">0</td></tr>'+
          '</table>'+
          '</span></div>'+
          '<div class="cont_right">'+
          '<img id="def" class="img" src="https://gpall.innogamescdn.com/images/game/unit_overview/support.png">'+
          '<img id="off" class="img" src="https://gpall.innogamescdn.com/images/game/unit_overview/attack.png">'+
          '</div>').appendTo('.units_land .content');

        // transporter display
        $('<div id="transporter" class="cont" style="height:25px;">'+
          '<table style=" margin:0px;"><tr align="center" >'+
          '<td><img id="ship_img" class="ico" src="http://s7.directupload.net/images/140724/4pvfuch8.png"></td>'+
          '<td><span id="ship" class="bold text_shadow" style="color:#FFCC66;font-size: 10px;"></span></td>'+
          '</tr></table>'+
          '</div>').appendTo('.units_naval .content');

        // Styles
        $('.ico').css({
            height: '20px',
            width: '20px'
        });
        $('.units_info_sprite').css({
            background: 'url(https://gpall.innogamescdn.com/images/game/units/units_info_sprite2.51.png)',
            backgroundSize: '100%'
        });
        $('.img_pierce').css({ backgroundPosition: '0px -20px' });
        $('.img_dist').css({ backgroundPosition: '0px -40px' });
        $('hr').css({
            margin: '0px',
            backgroundColor: '#5F5242',
            height: '2px',
            border: '0px solid'
        });
        $('.cont_left').css({
            background: 'url(https://gpall.innogamescdn.com/images/game/layout/layout_units_nav_bg.png)',
            width:'65%', 
            display: 'table-cell'
        });
        $('.cont').css({
            background: 'url(https://gpall.innogamescdn.com/images/game/layout/layout_units_nav_bg.png)'
        });
        $('.cont_right').css({
            background:'url(https://gpall.innogamescdn.com/images/game/layout/layout_units_nav_bg.png)',
            width:'30%',
            display: 'table-cell',
            verticalAlign:'middle'
        });
        $('.img').css({
            float:'right', 
            background:'none', 
            margin:'2px 8px 2px 0px'
        });

        $('.units_land .units_wrapper, .btn_gods_spells .checked').click(function(){
            setTimeout(function(){
                setStrengthMenu();
            }, 100);
        });

        $('#off').css({"filter": "url(#GrayScale)", "-webkit-filter" : "grayscale(80%)" });

        // Buttons
        $('#off').click(function(){
            $('#strength .img_hack').get(0).style.backgroundPosition = '0% 36%';
            $('#strength .img_pierce').get(0).style.backgroundPosition = '0% 27%';
            $('#strength .img_dist').get(0).style.backgroundPosition = '0% 45%';

            $('#str_font').get(0).style.color = "#edb";

            // TODO: doesn't work in FF yet
            $(this).css({ "filter": "none", "-webkit-filter" : "grayscale(0%)" });

            $('#def').css({"filter": "url(#GrayScale)", "-webkit-filter" : "grayscale(80%)" });
            def = false;
            setStrengthMenu();
        });
        $('#def').click(function(){
            $('#strength .img_hack').get(0).style.backgroundPosition = '0% 0%';
            $('#strength .img_pierce').get(0).style.backgroundPosition = '0% 9%';
            $('#strength .img_dist').get(0).style.backgroundPosition = '0% 18%';

            $('#str_font').get(0).style.color = "#fc6";

            $(this).css({"filter": "none", "-webkit-filter" : "grayscale(0%)" });
            $('#off').css({"filter": "url(#GrayScale)", "-webkit-filter" : "grayscale(80%)" });
            def = true;
            setStrengthMenu();
        });
        $('#def,#off,#transporter').hover(function() {   
            $(this).css('cursor','pointer');
        });
        $('#transporter').toggleClick(
            function(){
                $('#ship_img').get(0).src = "http://s1.directupload.net/images/140724/b5xl8nmj.png";
                shipsize = !shipsize;
                setStrengthMenu();
            }, 
            function(){
                $('#ship_img').get(0).src = "http://s7.directupload.net/images/140724/4pvfuch8.png";
                shipsize = !shipsize;  
                setStrengthMenu();
            }
        );
    }

    /*******************************************************************************************************************************
	 * ● Unit strength: Siege
	 *******************************************************************************************************************************/
    function addStrengthConquest(){
        var units = [], str;

        // units of the siege
        $('#conqueror_units_in_town .unit').each(function(){
            str = $(this).attr("class").split(" ")[4];
            if(!uw.GameData.units[str].is_naval){
                units[str] = parseInt($(this).get(0).children[0].innerHTML, 10);
                //console.log($(this).attr("class").split(" ")[4]);
            }
        });
        // calculation
        calcDef(units);

        $('<div id="strength_eo" class="game_border" style="width:90px; margin: 20px; align:center;">'+
          '<div class="game_border_top"></div><div class="game_border_bottom"></div>'+
          '<div class="game_border_left"></div><div class="game_border_right"></div>'+
          '<div class="game_border_corner corner1"></div><div class="game_border_corner corner2"></div>'+
          '<div class="game_border_corner corner3"></div><div class="game_border_corner corner4"></div>'+
          '<span class="bold" style="color:#000;font-size: 0.8em;"><table style="margin:0px;background:#f7dca2;width:100%;align:center;">'+
          '<tr><td width="1%"><div class="ico units_info_sprite img_hack"></div></td><td id="bl" align="center" width="100%">0</td></tr>'+
          '<tr><td><div class="ico units_info_sprite img_pierce"></div></td><td id="sh" align="center">0</td></tr>'+
          '<tr><td><div class="ico units_info_sprite img_dist"></div></td><td id="di" align="center">0</td></tr>'+
          '</table></span>'+
          '</div>').appendTo('#conqueror_units_in_town');

        $('#strength_eo').tooltip('Gesamteinheitenstärke der Belagerungstruppen');

        $('#strength_eo .ico').css({
            height: '20px',
            width: '20px'
        });
        $('#strength_eo .units_info_sprite').css({
            background: 'url(https://gpall.innogamescdn.com/images/game/units/units_info_sprite2.51.png)',
            backgroundSize: '100%'
        });
        $('#strength_eo .img_pierce').css({ backgroundPosition: '0% 9%' });
        $('#strength_eo .img_dist').css({ backgroundPosition: '0% 18%' });


        $('#bl').get(0).innerHTML = blunt;
        $('#sh').get(0).innerHTML = sharp;
        $('#di').get(0).innerHTML = dist;
    }

    /*******************************************************************************************************************************
	 * ● Unit strength: Barracks
	 *******************************************************************************************************************************/
    function setStrengthBarracks(){
        if(!$('#strength_baracks').get(0)){
            var units = [], pop = 0;

            // whole units of the town
            $('#units .unit_order_total').each(function(){
                units[$(this).parent().parent().attr("id")] = $(this).get(0).innerHTML;
            });
            // calculation
            calcDef(units);

            // population space of the units
            for(var e in units) {
                if(units.hasOwnProperty(e)) {
                    pop += units[e] * uw.GameData.units[e].population;
                }
            }
            $('<div id="strength_baracks" class="game_border" style="float:right; width:70px; align:center;">'+
              '<div class="game_border_top"></div><div class="game_border_bottom"></div>'+
              '<div class="game_border_left"></div><div class="game_border_right"></div>'+
              '<div class="game_border_corner corner1"></div><div class="game_border_corner corner2"></div>'+
              '<div class="game_border_corner corner3"></div><div class="game_border_corner corner4"></div>'+
              '<span class="bold" style="color:#000;font-size: 0.8em;"><table style="margin:0px;background:#f7dca2;width:100%;align:center;">'+
              '<tr><td width="1%"><div class="ico units_info_sprite img_hack"></div></td><td id="b" align="center" width="100%">0</td></tr>'+
              '<tr><td><div class="ico units_info_sprite img_pierce"></div></td><td id="s" align="center">0</td></tr>'+
              '<tr><td><div class="ico units_info_sprite img_dist"></div></td><td id="d" align="center">0</td></tr>'+
              '</table></span>'+
              '</div>').appendTo('.ui-dialog #units');

            $('<div id="pop_baracks" class="game_border" style="float:right; width:60px; align:center;">'+
              '<div class="game_border_top"></div><div class="game_border_bottom"></div>'+
              '<div class="game_border_left"></div><div class="game_border_right"></div>'+
              '<div class="game_border_corner corner1"></div><div class="game_border_corner corner2"></div>'+
              '<div class="game_border_corner corner3"></div><div class="game_border_corner corner4"></div>'+
              '<span class="bold" style="color:#000;font-size: 0.8em;"><table style="margin:0px;background:#f7dca2;width:100%;align:center;">'+
              '<tr><td width="1%"><img class="ico" src="https://gpall.innogamescdn.com/images/game/res/pop.png"></td><td id="p" align="center" width="100%">0</td></tr>'+
              '</table></span>'+
              '</div>').appendTo('.ui-dialog #units');

            $('.ui-dialog #units .ico').css({
                height: '20px',
                width: '20px'
            });
            $('.ui-dialog #units .units_info_sprite').css({
                background: 'url(https://gpall.innogamescdn.com/images/game/units/units_info_sprite2.51.png)',
                backgroundSize: '100%'
            });
            $('.ui-dialog #units .img_pierce').css({ backgroundPosition: '0% 9%' });
            $('.ui-dialog #units .img_dist').css({ backgroundPosition: '0% 18%' });

            //$('#pop_baracks').tooltip('Bevölkerungszahl aller Landeinheiten der Stadt');
            //$('#strength_baracks').tooltip('Gesamteinheitenstärke stadteigener Truppen');

            $('#b').get(0).innerHTML = blunt;
            $('#s').get(0).innerHTML = sharp;
            $('#d').get(0).innerHTML = dist;
            $('#p').get(0).innerHTML = pop;
        }
    }

    /*******************************************************************************************************************************
	 * ● Transporter capacity
	 *******************************************************************************************************************************/
    function setTransportCapacity(){
        var bigTransp = 0, smallTransp = 0, pop = 0, ship = 0, unit, berth, units = [];
        // Ship space (available)
        smallTransp = parseInt(uw.ITowns.getTown(parseInt(uw.Game.townId, 10)).units().small_transporter, 10);
        if(isNaN(smallTransp)) smallTransp = 0;
        if(shipsize){
            bigTransp = parseInt(uw.ITowns.getTown(parseInt(uw.Game.townId, 10)).units().big_transporter, 10);
            if(isNaN(bigTransp)) bigTransp = 0;
        }

        // Checking: Research berth
        berth = 0;
        if(uw.ITowns.getTown(uw.Game.townId).researches().hasBerth()){
            berth = 6;
        }
        ship = bigTransp*(20 + berth) + smallTransp*(10 + berth);

        units = uw.ITowns.getTown(uw.Game.townId).units();

        // Ship space (required)
        for(var e in units) {
            if(units.hasOwnProperty(e)) {
                if(uw.GameData.units[e]){ // without Heroes
                    if(!(uw.GameData.units[e].is_naval || uw.GameData.units[e].flying)){
                        pop += units[e] * uw.GameData.units[e].population;
                    }
                }
            }
        }
        $('#ship').get(0).innerHTML = pop + "/" + ship; 
    }


    /*******************************************************************************************************************************
     * Simulator
     * ----------------------------------------------------------------------------------------------------------------------------
     * | ● Layout adjustment
     * | ● Permanent display of the extended modifier box
     * | ● Unit strength for entered units (without modificator influence yet)
     * ----------------------------------------------------------------------------------------------------------------------------
     *******************************************************************************************************************************/

    function changeSimulatorLayoutNew(){
        if(!$('#dio_simulator').get(0)){
            $('<style id="dio_simulator" type="text/css">'+

              '#place_simulator { overflow: hidden !important} '+
              '#place_simulator .game_body { height: 457px !important} '+

              // Bonus container
              '.place_sim_wrap_mods {position: absolute !important; right: -17px !important} '+ 
              '.place_sim_wrap_mods .place_simulator_table :eq(1) { width: 300px;} '+ ////////////// genauer!
              '.place_sim_wrap_mods > .place_simulator_table { width: 272px;} '+ ////////////// genauer!



              // Extended modifier box
              '.place_sim_wrap_mods_extended { display: table !important; position: relative !important; width: 272px !important; padding-top: 3px !important; opacity: 1 !important; left: 0px; top: 0px} '+
              '.place_sim_wrap_mods_extended table { table-layout: fixed !important; width: 100% !important} '+
              '.place_sim_wrap_mods_extended table tr td:eq(0) { width: 18px !important } '+
              '.place_image { width: 20px !important; height:20px !important; background-size: 100% !important; margin: auto !important} '+
              '.place_cross { height: 19px !important}'+
              
              '.place_image.pa_commander { background-image: url(https://gpde.innogamescdn.com/images/game/place/simulator/sprite.png); } '+

              '.top_border td { border-top: 2px solid #BFA978 !important; padding-top: 3px !important} '+

              // Unit container
              '#simulator_body .unit_container { height: 50px !important; width: 50px !important; margin: 0px 3px 0px 1px !important} '+
              '.place_simulator_odd, .place_simulator_even { text-align: center !important} '+
              '.place_insert_field { margin: 0px !important}  '+

              // Sea unit box
              '.place_sim_sea_wrap h4 { float: left !important} '+
              '.place_sim_select_strategies select { width: 95px !important} '+
              '.place_sim_select_strategies { margin-left: 99px !important} '+

              // Land unit box
              '#place_sim_wrap_units { position: absolute !important; bottom: 35px !important} '+
              '#place_sim_wrap_units h4 { float: left !important}  '+

              // Select boxes
              '.place_sim_select_gods { width: 105px !important} '+
              '.place_sim_select_gods select { width: 80px !important} '+
              '.place_sim_select_gods_wrap { padding: 0px !important} '+
              '#select_insert_units { width: 130px !important} '+

              '.place_sim_select_gods_wrap .place_symbol, .place_sim_select_strategies .place_symbol { margin: 0px 2px 0px 5px !important} '+
              '.place_sim_insert_units .place_symbol { background: url(https://gpall.innogamescdn.com/images/game/towninfo/traveltime.png) !important; background-size: 140% !important; background-position-y: -4px !important} '+
              '.place_attack { float: left !important} '+
              '#simulator_body .att { margin-left: 19px !important} '+

              // Hero box
              '.place_sim_heroes_container { position: absolute !important; right: 26px !important; padding-top: 3px !important; z-index: 1 !important} '+
              '.place_sim_hero_container { width: 45px !important; height: 25px !important} '+
              // - Hero container
              '.place_sim_hero_choose, .place_sim_hero_unit_container { height: 26px !important; width: 30px !important} '+
              '#hero_defense_icon, #hero_attack_icon { height: 25px !important; width: 25px !important; margin: 0px !important} '+
              '#hero_defense_dd, #hero_attack_dd { height: 25px !important; width: 25px !important; margin: 1px !important} '+
              '.place_sim_hero_attack, .place_sim_hero_defense { margin-left: 3px !important} '+
              '#hero_attack_text, #hero_defense_text { font-size: 11px !important; bottom: 0px !important} '+
              '.place_sim_heroes_container .plus { left: 2px; top: 2px !important} '+
              // - Hero spinner
              '.place_sim_hero_spinner { height: 25px !important; width: 40px !important } '+
              '.place_sim_heroes_container td:eq(0) { height: 30px !important} '+
              '.hero_spinner { height: 24px !important;position:absolute !important; width:12px !important; left:29px !important, background:url(https://gpall.innogamescdn.com/images/game/border/odd.png) repeat !important; border: 1px solid rgb(107, 107, 107) !important} '+
              '.place_sim_hero_spinner .button_down, .place_sim_hero_spinner .button_up { bottom: 2px !important; cursor: pointer !important} '+

              // Quack
              '#q_place_sim_lost_res { display: none; } '+
              '</style>').appendTo('head');
        }

        /////////////////////////////////////


        $('.place_sim_bonuses_heroes h4').prependTo('.place_sim_wrap_mods');

        $('.place_sim_bonuses_more_confirm').parent().get(0).style.display = "none";
        $('.place_sim_showhide').remove();

        // Wall loss
        $('.place_sim_wrap_mods tr:eq(1) td:eq(5)').html('<span id="building_place_def_losses_wall_level" class="place_losses bold"></span');
        $('.place_sim_wrap_mods tr:last-child').remove();
        // AutoFillIn
        $('.place_insert_field[name="sim[mods][att][luck]"]').get(0).value = 0;

        // Extended modificator box
        //$('.place_sim_wrap_mods_extended').removeClass().addClass("place_sim_wrap_mods_extend");
        $('.place_sim_wrap_mods_extended').appendTo('.place_sim_wrap_mods');
        $('.place_sim_wrap_mods_extended .place_simulator_table').appendTo('.place_sim_wrap_mods_extended');
        if($('.place_sim_wrap_mods_extended .game_border').get(0)) { $('.place_sim_wrap_mods_extended .game_border').remove(); } // TODO: css!

        $('.place_sim_wrap_mods_extended .place_image').each(function(){
            var s = parseInt($(this).css('backgroundPosition').replace("px", "").split(" ")[1], 10)/2;
            $(this).get(0).style.backgroundPosition = '0px '+s+'px';
        });
        $('.place_sim_wrap_mods_extended .power').each(function(){
            $(this).removeClass("power_icon45x45").addClass("power_icon16x16");
        });
        $('.place_sim_wrap_mods_extended td:nth-child(even)').each(function(){
            $(this).addClass("left_border place_simulator_odd");
        });
        $('.place_sim_wrap_mods_extended td:nth-child(odd)').each(function(){
            $(this).addClass("left_border place_simulator_even");
        });

        // Beta only yet
        //if($('.place_sim_wrap_mods_extend tr').length == 5){
        $('.place_sim_wrap_mods_extended tr:eq(2)').each(function(){
            $(this).addClass("top_border");
        });
        $('.place_sim_wrap_mods_extended tr:last-child').remove();
        //}

        $('.place_sim_wrap_mods_extend td:first-child').each(function(){
            $(this).removeClass("left_border");
        });
        // -> update percentage each time
        $('.place_checkbox_field').each(function(){
            $(this).click(function(){
                uw.FightSimulator.closeModsExtended();
                //$('.place_sim_bonuses_more_confirm').get(0).click();
            });
        });


        // Sea unit box

        $('.place_sim_select_strategies').prependTo('.place_sim_sea_wrap');
        $('.place_sim_sea_wrap h4').prependTo('.place_sim_sea_wrap');

        // Land unit box
        $('<div id="place_sim_wrap_units"></div>').appendTo('#simulator_body');

        $('#place_simulator h4:last, .place_sim_select_gods_wrap').appendTo('#place_sim_wrap_units');
        $('#place_sim_ground_units').appendTo('#place_sim_wrap_units');
        $('#place_sim_wrap_units h4').prependTo('.place_sim_select_gods_wrap');


        // Hero world ?
        if(uw.Game.hasArtemis){
            $('.place_sim_wrap_mods_extend tr').each(function(){
                $(this).get(0).children[1].style.borderLeft = "none";
                $(this).get(0).children[0].remove();
            });
        }

        // Hero box ?
        if($('.place_sim_heroes_container').get(0)){
            $('.place_sim_heroes_container').appendTo(".place_sim_wrap_mods");

            $('#place_simulator h4:eq(2)').remove(); // Delete heroes title

            $('.hero_unit').each(function(){
                $(this).removeClass('unit_icon40x40').addClass('unit_icon25x25');
            });

            // hero spinner
            $('.place_sim_hero_spinner').each(function(){
                $(this).removeClass('place_sim_hero_spinner').addClass('hero_spinner');
            });
            $('.hero_spinner .border_l').remove();
            $('.hero_spinner .border_r').remove();
            $('.hero_spinner .body').remove();
        }

        setStrengthSimulator();
    }

    function changeSimulatorLayout(){
        
        if(!$('#dio_simulator').get(0)){
            $('<style id="dio_simulator" type="text/css">'+
              '.place_image { background-image: url(https://gpde.innogamescdn.com/images/game/place/simulator/sprite.png) !important; } '+
              '.place_image.pa_captain { background-position: 0px -120px !important; } '+
              '.place_image.pa_commander { background-position: 0px -140px !important; } '+
              '.place_image.pa_priest { background-position: 0px -160px !important; } '+
              '</style>').appendTo('head');
        }
              

        $('#place_simulator').css({
            overflow: 'hidden'
        });
        $('#place_simulator .game_body').css({
            height: '457px'
        });

        // Bonus container
        $('.place_sim_bonuses_heroes h4').prependTo('.place_sim_wrap_mods');
        $('.place_sim_wrap_mods').css({
            position: 'absolute',
            right: '-17px'
        });
        $('.place_sim_wrap_mods .place_simulator_table .left_border').css({
            width: '47px'
        });
        // Wall loss
        $('.place_sim_wrap_mods tr:eq(1) td:eq(5)').html('<span id="building_place_def_losses_wall_level" class="place_losses bold"></span');
        $('.place_sim_wrap_mods tr:last-child').remove();
        // AutoFillIn
        $('.place_insert_field[name="sim[mods][att][luck]"]').get(0).value = 0;
        //$('.place_insert_field[name="sim[mods][att][morale]"]').get(0).value = 100;


        // Extended modificator box
        $('.place_sim_wrap_mods_extended').removeClass().addClass("place_sim_wrap_mods_extend");
        $('.place_sim_wrap_mods_extend').appendTo('.place_sim_wrap_mods');
        $('.place_sim_wrap_mods_extend .place_simulator_table').appendTo('.place_sim_wrap_mods_extend');
        if($('.place_sim_wrap_mods_extend .game_border').get(0)) { $('.place_sim_wrap_mods_extend .game_border').remove(); }
        $('.place_sim_wrap_mods_extend').css({
            display: 'table',
            position: 'relative',
            width: '272px',
            paddingTop: '3px'
        });
        $('.place_sim_wrap_mods_extend table').css({
            tableLayout: 'fixed',
            width: '100%'
        });
        $('.place_sim_wrap_mods_extend table tr td:eq(0)').css({
            width: '18px'
        });
        $('.place_sim_bonuses_more_confirm').parent().get(0).style.display = "none";
        $('.place_sim_showhide').remove();
        $('.place_image').css({
            width: '20px',
            height:'20px',
            backgroundSize: '100%',
            margin: 'auto'
        });
        $('.place_cross').css({
            height: '19px'
        });
        $('.place_sim_wrap_mods_extend .place_image').each(function(){
            var s = parseInt($(this).css('backgroundPosition').replace("px", "").split(" ")[1], 10)/2;
            $(this).get(0).style.backgroundPosition = '0px '+s+'px';
        });
        $('.place_sim_wrap_mods_extend .power').each(function(){
            $(this).removeClass("power_icon45x45").addClass("power_icon16x16");
        });
        $('.place_sim_wrap_mods_extend td:nth-child(even)').each(function(){
            $(this).addClass("left_border place_simulator_odd");
        });
        $('.place_sim_wrap_mods_extend td:nth-child(odd)').each(function(){
            $(this).addClass("left_border place_simulator_even");
        });

        // Beta only yet
        if($('.place_sim_wrap_mods_extend tr').length == 5){
            $('.place_sim_wrap_mods_extend tr:eq(2)').each(function(){
                $(this).addClass("top_border");
            });
            $('.place_sim_wrap_mods_extend tr:last-child').remove();
        }
        $('.top_border td').css({
            borderTop: '2px solid #BFA978',
            paddingTop: '3px'
        });
        $('.place_sim_wrap_mods_extend td:first-child').each(function(){
            $(this).removeClass("left_border");
        });
        // -> update percentage each time
        $('.place_checkbox_field').each(function(){
            $(this).click(function(){
                uw.FightSimulator.closeModsExtended();
                //$('.place_sim_bonuses_more_confirm').get(0).click();
            });
        });


        // unit container
        $('#simulator_body .unit_container').css({
            height: '50px',
            width: '50px',
            margin: '0px 3px 0px 1px'
        });
        $('.place_simulator_odd, .place_simulator_even').css({
            textAlign: 'center'
        });
        $('.place_insert_field').css({
            margin: '0px'
        });

        // Sea unit box
        $('.place_sim_sea_wrap h4').css({
            float: 'left'
        });
        $('.place_sim_select_strategies').prependTo('.place_sim_sea_wrap');
        $('.place_sim_select_strategies select').css({
            width: '95px'
        });
        $('.place_sim_sea_wrap h4').prependTo('.place_sim_sea_wrap');
        $('.place_sim_select_strategies').css({
            marginLeft: '99px'
        });

        // Land unit box
        $('<div id="place_sim_wrap_units"></div>').appendTo('#simulator_body');
        $('#place_sim_wrap_units').css({
            position: 'absolute',
            bottom: '35px'
        });
        $('#place_simulator h4:last, .place_sim_select_gods_wrap').appendTo('#place_sim_wrap_units');
        $('#place_sim_ground_units').appendTo('#place_sim_wrap_units');
        $('#place_sim_wrap_units h4').prependTo('.place_sim_select_gods_wrap');
        $('#place_sim_wrap_units h4').css({
            float: 'left'
        });

        // Select boxes
        $('.place_sim_select_gods').css({
            width: '105px'
        });
        $('.place_sim_select_gods select').css({
            width: '80px'
        });  
        $('.place_sim_select_gods_wrap').css({
            padding: '0px'
        });
        $('#select_insert_units').css({
            width: '130px'
        });  

        $('.place_sim_select_gods_wrap .place_symbol, .place_sim_select_strategies .place_symbol').css({
            margin: '0px 2px 0px 5px'
        });
        $('.place_sim_insert_units .place_symbol').css({
            background: 'url(https://gpall.innogamescdn.com/images/game/towninfo/traveltime.png)',
            backgroundSize: '140%',
            backgroundPositionY: '-4px'
        });
        $('.place_attack').css({
            float: 'left'
        });
        $('#simulator_body .att').css({
            marginLeft: '19px'
        });


        // Hero world ?
        if(uw.Game.hasArtemis){
            $('.place_sim_wrap_mods_extend tr').each(function(){
                $(this).get(0).children[1].style.borderLeft = "none";
                $(this).get(0).children[0].remove();
            });
        }


        // Hero box ?
        if($('.place_sim_heroes_container').get(0)){
            $('.place_sim_heroes_container').appendTo(".place_sim_wrap_mods");

            $('#place_simulator h4:eq(2)').remove(); // Delete heroes title

            $('.place_sim_heroes_container').css({
                position: 'absolute',
                right: '26px',
                paddingTop: '3px',
                zIndex: '1'
            });

            $('.place_sim_hero_container').css({
                width: '45px', height: '25px'
            });

            // hero container
            $('.place_sim_hero_choose, .place_sim_hero_unit_container').css({
                height: '26px',
                width: '30px'
            });

            $('#hero_defense_icon, #hero_attack_icon').css({
                height: '25px',
                width: '25px',
                margin: '0px'
            });
            $('#hero_defense_dd, #hero_attack_dd').css({
                height: '25px',
                width: '25px',
                margin: '1px'
            });

            $('.place_sim_hero_attack, .place_sim_hero_defense').css({
                marginLeft: '3px'
            });
            $('#hero_attack_text, #hero_defense_text').css({
                fontSize: '11px',
                bottom: '0px'
            });
            $('.place_sim_heroes_container .plus').css({
                left: '2px', top: '2px'
            });

            $('.hero_unit').each(function(){
                $(this).removeClass('unit_icon40x40').addClass('unit_icon25x25');
            });



            // hero spinner
            $('.place_sim_hero_spinner').css({
                height: '25px', width: '40px'
            });
            $('.place_sim_hero_spinner').each(function(){
                $(this).removeClass('place_sim_hero_spinner').addClass('hero_spinner');
            });
            $('.hero_spinner .border_l').remove();
            $('.hero_spinner .border_r').remove();
            $('.hero_spinner .body').remove();

            $('.place_sim_heroes_container td:eq(0)').css({ height: '30px' });

            $('.hero_spinner').css({
                height: '24px',
                position: 'absolute',
                width: '12px',
                left: '29px',
                background: 'url(https://gpall.innogamescdn.com/images/game/border/odd.png) repeat',
                border: '1px solid rgb(107, 107, 107)'
            });
            $('.place_sim_hero_spinner .button_down, .place_sim_hero_spinner .button_up').css({
                bottom: '2px',
                cursor: 'pointer'
            });
        }

        $('<style type="text/css"> #q_place_sim_lost_res { display: none; } </style>').appendTo('head');	

        setStrengthSimulator();
    }

    function afterSimulation(){
        var lossArray = { att : { res: 0, fav: 0, pop: 0 }, def : { res: 0, fav: 0, pop: 0 } }, 
            wall_level = parseInt($('.place_sim_wrap_mods .place_insert_field[name="sim[mods][def][wall_level]"]').val(), 10), 
            wall_damage = parseInt($('#building_place_def_losses_wall_level').get(0).innerHTML, 10),
            wall_iron = [ 0, 200, 429, 670, 919, 1175, 1435, 1701, 1970, 2242, 2518, 2796, 3077, 3360, 3646, 3933, 4222, 4514, 4807, 5101, 5397, 5695, 5994, 6294, 6596, 6899 ];

        // Calculate unit losses
        $('#place_sim_wrap_units .place_losses, #place_sim_naval_units .place_losses').each(function(){
            var loss = parseInt($(this).get(0).innerHTML, 10) || 0;
            if(loss > 0){
                var unit = this.id.substring(26);
                var side = this.id.split("_")[2]; // att / def
                lossArray[side].res += loss *(uw.GameData.units[unit].resources.wood + uw.GameData.units[unit].resources.stone + uw.GameData.units[unit].resources.iron);
                lossArray[side].fav += loss * uw.GameData.units[unit].favor;
                lossArray[side].pop += loss * uw.GameData.units[unit].population;
            }
        });
        // Calculate wall resource losses
        for(var w = wall_level; w > wall_level - wall_damage; w--){
            lossArray.def.res += 400 + w * 350 + wall_iron[w]; // wood amount is constant, stone amount is multiplicative and iron amount is irregular for wall levels
        }

        // Insert losses into table
        for(var x in lossArray){
            if(lossArray.hasOwnProperty(x)){
                for(var z in lossArray[x]){
                    if(lossArray[x].hasOwnProperty(z)){
                        $("#"+ x +"_"+ z).get(0).innerHTML = ((z === "res") && (lossArray[x][z] > 10000))? (Math.round(lossArray[x][z]/1000)+"k"):lossArray[x][z];
                    }
                }
            }
        }
    }

    // Stärkeanzeige: Simulator
    var unitsGround = { att: {}, def: {} }, unitsNaval = { att: {}, def: {} }, name ="";

    function setStrengthSimulator() {
        $('<div id="simu_table" style="position:relative; align:center;font-size: 0.8em; margin-top:6px; margin-right:39%;">'+
          '<div style="float:left; margin-right:12px;"><h4>'+ getText("labels", "str") +'</h4>'+
          '<table class="place_simulator_table strength" cellpadding="0px" cellspacing="0px" style="align:center;">'+
          '<tr>'+
          '<td class="place_simulator_even"></td>'+
          '<td class="left_border place_simulator_odd"><div class="ico units_info_sprite img_hack"></div></td>'+
          '<td class="left_border place_simulator_even"><div class="ico units_info_sprite img_pierce"></div></td>'+
          '<td class="left_border place_simulator_odd"><div class="ico units_info_sprite img_dist"></div></td>'+
          '<td class="left_border place_simulator_even"><div class="ico units_info_sprite img_ship"></div></td>'+
          '</tr><tr>'+
          '<td class="place_simulator_even"><div class="place_symbol place_att"></div></td>'+
          '<td class="left_border place_simulator_odd" id="att_b">0</td>'+
          '<td class="left_border place_simulator_even" id="att_s">0</td>'+
          '<td class="left_border place_simulator_odd" id="att_d">0</td>'+
          '<td class="left_border place_simulator_even" id="att_ship">0</td>'+
          '</tr><tr>'+
          '<td class="place_simulator_even"><div class="place_symbol place_def"></div></td>'+
          '<td class="left_border place_simulator_odd" id="def_b">0</td>'+
          '<td class="left_border place_simulator_even" id="def_s">0</td>'+
          '<td class="left_border place_simulator_odd" id="def_d">0</td>'+
          '<td class="left_border place_simulator_even" id="def_ship">0</td>'+
          '</tr>'+
          '</table>'+
          '</div><div><h4>'+ getText("labels", "los") +'</h4>'+
          '<table class="place_simulator_table loss" cellpadding="0px" cellspacing="0px" style="align:center;">'+
          '<tr>'+
          '<td class="place_simulator_even"></td>'+
          '<td class="left_border place_simulator_odd"><div class="ico units_info_sprite img_res"></div></td>'+
          '<td class="left_border place_simulator_even"><div class="ico units_info_sprite img_fav"></div></td>'+
          '<td class="left_border place_simulator_odd"><div class="ico units_info_sprite img_pop"></div></td>'+
          '</tr><tr>'+
          '<td class="place_simulator_even"><div class="place_symbol place_att"></div></td>'+
          '<td class="left_border place_simulator_odd" id="att_res">0</td>'+
          '<td class="left_border place_simulator_even" id="att_fav">0</td>'+
          '<td class="left_border place_simulator_odd" id="att_pop">0</td>'+
          '</tr><tr>'+
          '<td class="place_simulator_even"><div class="place_symbol place_def"></div></td>'+
          '<td class="left_border place_simulator_odd" id="def_res">0</td>'+
          '<td class="left_border place_simulator_even" id="def_fav">0</td>'+
          '<td class="left_border place_simulator_odd" id="def_pop">0</td>'+
          '</tr>'+
          '</table>'+
          '</div></div>').appendTo('#simulator_body');

        $('#simu_table .ico').css({
            height: '20px',
            width: '20px'
        });
        $('#simu_table .units_info_sprite').css({
            background: 'url(https://gpall.innogamescdn.com/images/game/units/units_info_sprite2.51.png)',
            backgroundSize: '100%'
        });
        $('#simu_table .img_hack').css({	backgroundPosition: '0% 36%' });
        $('#simu_table .img_pierce').css({	backgroundPosition: '0% 27%' });
        $('#simu_table .img_dist').css({	backgroundPosition: '0% 45%' });
        $('#simu_table .img_ship').css({	backgroundPosition: '0% 72%' });

        $('#simu_table .img_fav').css({ background: 'url(https://gpall.innogamescdn.com/images/game/res/favor.png)', backgroundSize: '100%' });
        $('#simu_table .img_res').css({ background: 'url(https://gpall.innogamescdn.com/images/game/units/units_info_sprite2.51.png) 0% 54%', backgroundSize: '100%' });
        $('#simu_table .img_pop').css({ background: 'url(https://gpall.innogamescdn.com/images/game/res/pop.png)', backgroundSize: '100%' });

        $('#simu_table .left_border').css({
            width: '54px'
        });
        $('#simu_table .left_border').each(function(){
            $(this)[0].align = 'center';
        });

        $('#simu_table .strength').tooltip(getText("labels", "str") + " (" + getText("labels", "mod") +")");
        $('#simu_table .loss').tooltip(getText("labels", "los"));

        // Klick auf Einheitenbild
        $('.index_unit').click(function(){
            var type = $(this).attr('class').split(" ")[4];
            $('.place_insert_field[name="sim[units][att]['+type+']"]').change();
        });

        $('#place_sim_ground_units .place_insert_field, #place_sim_naval_units .place_insert_field').on('input change', function(){
            name = $(this).attr("name").replace(/\]/g, "").split("[");
            var str = this;
            //console.log(str);
            setTimeout(function(){
                var unit_type = $(str).closest('.place_simulator_table').attr("id").split("_")[2],
                    val, e;

                val = parseInt($(str).val(), 10);
                val = val || 0;

                if(unit_type == "ground"){
                    unitsGround[name[2]][name[3]] = val;

                    if(name[2] == "def"){
                        calcDef(unitsGround.def);
                    } else {
                        calcOff(unitsGround.att, unitsGround.att);
                    }
                    $('#' + name[2] + '_b').get(0).innerHTML = blunt;
                    $('#' + name[2] + '_s').get(0).innerHTML = sharp;
                    $('#' + name[2] + '_d').get(0).innerHTML = dist;

                } else {
                    var att = 0, def = 0;
                    unitsNaval[name[2]][name[3]] = val;

                    if(name[2] == "def"){
                        for(e in unitsNaval.def) {
                            if(unitsNaval.def.hasOwnProperty(e)) {
                                def += unitsNaval.def[e] * uw.GameData.units[e].defense;
                            }
                        }
                        $('#def_ship').get(0).innerHTML = def;
                    } else {
                        for(e in unitsNaval.att) {
                            if(unitsNaval.att.hasOwnProperty(e)) {
                                att += unitsNaval.att[e] * uw.GameData.units[e].attack;
                            }
                        }
                        $('#att_ship').get(0).innerHTML = att;
                    }
                }
            }, 100); 
        });

        // Abfrage wegen eventueller Spionageweiterleitung 
        getUnitInputs();
        setTimeout(function(){
            setChangeUnitInputs("def");
        }, 100);

        $('#select_insert_units').change(function(){
            var side = $(this).find('option:selected').val();
            setTimeout(function(){
                getUnitInputs();
                if(side === "att" || side === "def"){
                    setChangeUnitInputs(side);  
                }
            }, 200);
        });
    }

    function getUnitInputs(){
        $('#place_sim_ground_units .place_insert_field, #place_sim_naval_units .place_insert_field').each(function(){
            name = $(this).attr("name").replace(/\]/g, "").split("[");
            var str = this;
            var unit_type = $(str).closest('.place_simulator_table').attr("id").split("_")[2],
                val, e;
            val = parseInt($(str).val(), 10);
            val = val || 0;
            if(unit_type === "ground"){
                unitsGround[name[2]][name[3]] = val;
            } else {
                var att = 0, def = 0;
                unitsNaval[name[2]][name[3]] = val;
            }
        });
    }

    function setChangeUnitInputs(side){
        $('.place_insert_field[name="sim[units][' + side + '][godsent]"]').change();
        setTimeout(function(){
            $('.place_insert_field[name="sim[units][' + side + '][colonize_ship]"]').change();
        }, 100);
    }

    /*******************************************************************************************************************************
     * Defense form
     * ----------------------------------------------------------------------------------------------------------------------------
     * | ● Adds a defense form to the bbcode bar
     * ----------------------------------------------------------------------------------------------------------------------------
     *******************************************************************************************************************************/

    // Funktion aufteilen...
    function addForm(e){
        var textareaId = "", bbcodeBarId = "";

        switch (e) {
            case "/alliance_forum/forum": 
                textareaId = "#forum_post_textarea";
                bbcodeBarId = "#forum";
                break;
            case "/message/forward":
                textareaId = "#message_message";
                bbcodeBarId = "#message_bbcodes";
                break;
            case "/message/new":
                textareaId = "#message_new_message";
                bbcodeBarId = "#message_bbcodes";
                break;
            case "/message/view":
                textareaId = "#message_reply_message";
                bbcodeBarId = "#message_bbcodes";
                break;
            case "/player_memo/load_memo_content":
                textareaId = "#memo_text_area";
                bbcodeBarId = "#memo_edit";
                break;   
        }

        $('<a title="Verteidigungsformular" href="#" class="dio_bbcode_option def_form" name="def_form"></a>').appendTo(bbcodeBarId + ' .bb_button_wrapper');

        $('.def_form_button').css({
            cursor: 'pointer',
            marginTop:'3px'
        });

        $(bbcodeBarId + ' .dio_bbcode_option').css({
            background: 'url("http://s14.directupload.net/images/140126/lt3hyb8j.png")',
            display: 'block',
            float: 'left',
            width: '22px',
            height: '23px',
            margin: '0 3px 0 0',
            position: 'relative',
        });
        $(bbcodeBarId + ' .def_form').css({
            backgroundPosition: '-89px 0px'
        });
        var imgArray = { 
            wall:	'https://gpall.innogamescdn.com/images/game/main/wall.png',
            tower:	'https://gpall.innogamescdn.com/images/game/main/tower.png',
            hide:	'https://gpall.innogamescdn.com/images/game/main/hide.png',

            spy:	'http://s7.directupload.net/images/140114/yr993xwc.png',
            pop:	'http://s7.directupload.net/images/140114/4d6xktxm.png',

            rev1:	'http://s7.directupload.net/images/140115/9cv6otiu.png',
            rev0:	'http://s7.directupload.net/images/140115/aue4rg6i.png',
            eo1:	'http://s1.directupload.net/images/140115/fkzlipyh.png',
            eo0:	'http://s1.directupload.net/images/140115/hs2kg59c.png',
            att:	'http://s1.directupload.net/images/140115/3t6uy4te.png',
            sup:	'http://s7.directupload.net/images/140115/ty6szerx.png',

            zeus:		'http://s1.directupload.net/images/140114/cdxecrpu.png',
            hera:		'http://s1.directupload.net/images/140114/mve54v2o.png',
            athena:		'http://s14.directupload.net/images/140114/kyqyedhe.png',
            poseidon:	'http://s7.directupload.net/images/140114/tusr9oyi.png',
            hades:		'http://s7.directupload.net/images/140114/huins2gn.png',
            artemis:	'http://s7.directupload.net/images/140114/kghjhko8.png',
            nogod:		'http://s1.directupload.net/images/140114/e7vmvfap.png',

            captain:	'http://s14.directupload.net/images/140114/88gg75rc.png',
            commander:	'http://s14.directupload.net/images/140114/slbst52o.png',
            priest:		'http://s1.directupload.net/images/140114/glptekkx.png',

            phalanx:	'http://s7.directupload.net/images/140114/e97wby6z.png',
            ram:		'http://s7.directupload.net/images/140114/s854ds3w.png',

            militia:	'http://wiki.en.grepolis.com/images/9/9b/Militia_40x40.png',
            sword:		'http://wiki.en.grepolis.com/images/9/9c/Sword_40x40.png',
            slinger:	'http://wiki.en.grepolis.com/images/d/dc/Slinger_40x40.png',
            archer:		'http://wiki.en.grepolis.com/images/1/1a/Archer_40x40.png',
            hoplite:	'http://wiki.en.grepolis.com/images/b/bd/Hoplite_40x40.png',
            rider:		'http://wiki.en.grepolis.com/images/e/e9/Rider_40x40.png',
            chariot:	'http://wiki.en.grepolis.com/images/b/b8/Chariot_40x40.png',
            catapult:	'http://wiki.en.grepolis.com/images/f/f0/Catapult_40x40.png',
            godsent:	'http://wiki.de.grepolis.com/images/6/6e/Grepolis_Wiki_225.png',

            def_sum:	'http://s14.directupload.net/images/140127/6cxnis9r.png',

            minotaur:	'http://wiki.de.grepolis.com/images/7/70/Minotaur_40x40.png',
            manticore:	'http://wiki.de.grepolis.com/images/5/5e/Manticore_40x40.png',
            zyclop:		'http://wiki.de.grepolis.com/images/6/66/Zyklop_40x40.png',
            sea_monster:'http://wiki.de.grepolis.com/images/7/70/Sea_monster_40x40.png',
            harpy:		'http://wiki.de.grepolis.com/images/8/80/Harpy_40x40.png',
            medusa:		'http://wiki.de.grepolis.com/images/d/db/Medusa_40x40.png',
            centaur:	'http://wiki.de.grepolis.com/images/5/53/Centaur_40x40.png',
            pegasus:	'http://wiki.de.grepolis.com/images/5/54/Pegasus_40x40.png',
            cerberus:	'http://wiki.de.grepolis.com/images/6/67/Zerberus_40x40.png',
            fury:		'http://wiki.de.grepolis.com/images/6/67/Erinys_40x40.png',
            griffin:	'http://wiki.de.grepolis.com/images/d/d1/Unit_greif.png',
            calydonian_boar:	'http://wiki.de.grepolis.com/images/9/93/Unit_eber.png',

            big_transporter:	'http://wiki.en.grepolis.com/images/0/04/Big_transporter_40x40.png',
            bireme:				'http://wiki.en.grepolis.com/images/4/44/Bireme_40x40.png',
            attack_ship:		'http://wiki.en.grepolis.com/images/e/e6/Attack_ship_40x40.png',
            demolition_ship:	'http://wiki.en.grepolis.com/images/e/ec/Demolition_ship_40x40.png',
            small_transporter:	'http://wiki.en.grepolis.com/images/8/85/Small_transporter_40x40.png',
            trireme:			'http://wiki.en.grepolis.com/images/a/ad/Trireme_40x40.png',
            colonize_ship:		'http://wiki.en.grepolis.com/images/d/d1/Colonize_ship_40x40.png',

            move_icon:	'http://de.cdn.grepolis.com/images/game/unit_overview/',

            bordure: 'http://s1.directupload.net/images/140126/8y6pmetk.png'
        };

        $('<div class="bb_def_chooser">'+
          '<div class="bbcode_box middle_center">'+
          '<div class="bbcode_box top_left"></div><div class="bbcode_box top_right"></div>'+
          '<div class="bbcode_box top_center"></div><div class="bbcode_box bottom_center"></div>'+
          '<div class="bbcode_box bottom_right"></div><div class="bbcode_box bottom_left"></div>'+
          '<div class="bbcode_box middle_left"></div><div class="bbcode_box middle_right"></div>'+
          '<div class="bbcode_box content clearfix" style="padding:5px">'+
          '<div id="f_uni" class="checkbox_new checked"><div class="cbx_icon"></div><div class="cbx_caption">'+ getText("labels", "det") +'</div></div><br><br>'+
          '<div id="f_prm" class="checkbox_new checked"><div class="cbx_icon"></div><div class="cbx_caption">'+ getText("labels", "prm") +'</div></div><br><br>'+
          '<div id="f_sil" class="checkbox_new checked"><div class="cbx_icon"></div><div class="cbx_caption">'+ getText("labels", "sil") +'</div></div><br><br>'+
          '<div id="f_mov" class="checkbox_new checked"><div class="cbx_icon"></div><div class="cbx_caption">'+ getText("labels", "mov") +'</div></div><br><br>'+
          '<div><a class="button" id="dio_insert" href="#"><span class="left"><span class="right"><span class="middle"><small>'+ getText("buttons", "ins") +'</small></span></span></span><span></span></a></div>'+
          '</div></div></div>').appendTo(bbcodeBarId + ' .bb_button_wrapper');

        $('.bb_def_chooser').css({
            display: 'none',
            top: '38px',
            left: '510px',
            position: 'absolute',
            width: '190px',
            zIndex: 10000
        });

        $(bbcodeBarId + " .bb_def_chooser .checkbox_new").click(function () {
            $(this).toggleClass("checked");
        });

        $(bbcodeBarId + ' .def_form').toggleClick(function(){
            $(this).parent().find(".bb_def_chooser").get(0).style.display = "block";
        }, function(){
            $(this).parent().find(".bb_def_chooser").get(0).style.display = "none";
        });

        $(bbcodeBarId + ' #dio_insert').click(function(){
            var textarea = $(textareaId).get(0), text = $(textarea).val(), troop_table = "", troop_img = "", troop_count = "", separator = "", move_table = "", landunit_sum = 0;

            $('.def_form').click();

            if($('#f_uni').hasClass("checked")){
                $('.units_land .unit, .units_naval .unit').each(function(){
                    troop_img	+= separator + '[img]'		+ imgArray[this.className.split(" ")[1]]	+ '[/img]';
                    troop_count += separator + '[center]'	+ $(this).find(".value").get(0).innerHTML	+ '[/center]';
                    separator = "[||]";
                });
            } else {
                $('.units_land .unit').each(function(){
                    var a = this.className.split(" ")[1], def = (uw.GameData.units[a].def_hack + uw.GameData.units[a].def_pierce + uw.GameData.units[a].def_distance)/(3 * uw.GameData.units[a].population);
                    if(def > 10){
                        landunit_sum += parseInt($(this).find(".value").get(0).innerHTML, 10) * uw.GameData.units[a].population * ((def > 20) ? 2 : 1); 
                    }
                });
                landunit_sum = (landunit_sum > 10000) ? ((Math.round(landunit_sum / 100))/10) + "k" : landunit_sum;

                troop_img	+= '[img]'+ imgArray.def_sum +'[/img]';
                troop_count += '[center]'+ landunit_sum	+'[/center]';
                separator = "[||]";
                $('.units_naval .unit').each(function(){
                    troop_img	+= separator + '[img]'		+ imgArray[this.className.split(" ")[1]]	+ '[/img]';
                    troop_count += separator + '[center]'	+ $(this).find(".value").get(0).innerHTML	+ '[/center]';
                });
            }
            if(troop_img !== ""){ troop_table = "\n[table][**]" + troop_img + "[/**][**]" + troop_count + "[/**][/table]\n"; }

            var str = '[img]'+ imgArray.bordure + '[/img]'+
                '\n\n[color=#006B00][size=12][u][b]'+ getText("labels", "ttl") +' ([url="http://adf.ly/eDM1y"]©DIO-Tools[/url])[/b][/u][/size][/color]\n\n'+
                //'[table][**][img]'+ imgArray.sup +'[/img][||]'+
                '[size=12][town]' + uw.ITowns.getTown(uw.Game.townId).getId() + '[/town] ([player]'+ uw.Game.player_name +'[/player])[/size]'+
                //'[||][img]'+ imgArray['rev' + (uw.ITowns.getTown(uw.Game.townId).hasConqueror()?1:0)] +'[/img][/**][/table]'+
                '\n\n[i][b]'+ getText("labels", "inf") +'[/b][/i]' + troop_table +
                '[table][*]'+
                '[img]'+ imgArray.wall		+'[/img][|]\n'+
                '[img]'+ imgArray.tower		+'[/img][|]\n'+
                '[img]'+ imgArray.phalanx	+'[/img][|]\n'+
                '[img]'+ imgArray.ram		+'[/img][|]\n'+
                ($('#f_prm').hasClass("checked") ? '[img]'+ imgArray.commander	+'[/img][|]\n' : ' ')+
                ($('#f_prm').hasClass("checked") ? '[img]'+ imgArray.captain	+'[/img][|]\n' : ' ')+
                ($('#f_prm').hasClass("checked") ? '[img]'+ imgArray.priest	+'[/img][|]\n' : ' ')+
                ($('#f_sil').hasClass("checked") ? '[center][img]'+imgArray.spy+'[/img][/center][|]\n' : ' ')+
                '[img]'+ imgArray.pop		+'[/img][|]\n'+
                '[img]'+ imgArray[(uw.ITowns.getTown(uw.Game.townId).god() || "nogod")]	+'[/img][/*]\n'+
                '[**][center]' + uw.ITowns.getTown(uw.Game.townId).buildings().getBuildingLevel("wall")+ '[/center][||]'+
                '[center]' + uw.ITowns.getTown(uw.Game.townId).buildings().getBuildingLevel("tower")+ '[/center][||]'+
                '[center]' + (uw.ITowns.getTown(uw.Game.townId).researches().attributes.phalanx? '+' : '-') + '[/center][||]'+
                '[center]' + (uw.ITowns.getTown(uw.Game.townId).researches().attributes.ram? '+' : '-')+ '[/center][||]'+
                ($('#f_prm').hasClass("checked") ? '[center]' + ((uw.Game.premium_features.commander >= uw.Timestamp.now())? '+' : '-') + '[/center][||]' : ' ')+
                ($('#f_prm').hasClass("checked") ? '[center]' + ((uw.Game.premium_features.captain >= uw.Timestamp.now())? '+' : '-')+ '[/center][||]' : ' ')+
                ($('#f_prm').hasClass("checked") ? '[center]' + ((uw.Game.premium_features.priest >= uw.Timestamp.now())? '+' : '-') + '[/center][||]' : ' ')+
                ($('#f_sil').hasClass("checked") ? '[center]' + Math.round(uw.ITowns.getTown(uw.Game.townId).getEspionageStorage()/1000) + 'k[/center][||]': ' ')+
                '[center]' + uw.ITowns.getTown(uw.Game.townId).getAvailablePopulation() + '[/center][||]'+
                '[center]' + $('.gods_favor_amount').get(0).innerHTML + '[/center]'+
                '[/**][/table]';

            var bb_count_str = parseInt(str.match(/\[/g).length, 10), bb_count_move = 0;

            var i = 0;
            if($('#f_mov').hasClass("checked")){ 
                move_table += '\n[i][b]'+ getText("labels", "mov") +'[/b][/i]\n[table]';

                $('#toolbar_activity_commands').mouseover();

                $('#toolbar_activity_commands_list .content .command').each(function(){
                    var cl = $(this).children()[0].className.split(" ");
                    if((cl[cl.length-1] === "returning" || cl[cl.length-1] === "revolt_arising" || cl[cl.length-1] === "revolt_running") && ((bb_count_str + bb_count_move) < 480)) {
                        move_table += (i%1) ? "" : "[**]";
                        i++;
                        move_table += "[img]" + imgArray.move_icon + cl[2] + ".png[/img][||]";
                        move_table += getArrivalTime($(this).children()[1].innerHTML) + (uw.Game.market_id === "de" ? " Uhr[||]" : " [||]");
                        move_table += "[town]" + JSON.parse(atob($(this).children()[2].firstChild.href.split("#")[1])).id + "[/town]";
                        move_table += (i%1) ? "[||]" : "[/**]";
                    }
                    bb_count_move = parseInt(move_table.match(/\[/g).length, 10);
                });
                if((bb_count_str + bb_count_move) > 480){
                    move_table += '[**]...[/**]';
                }

                $('#toolbar_activity_commands').mouseout();

                //console.log((bb_count_str + bb_count_move));
                move_table += (i%1) ? "[/**]" : "";
                move_table += "[*][|][color=#800000][size=6][i] ("+ getText("labels", "dev") +": ±1s)[/i][/size][/color][/*][/table]\n";
            }

            str += move_table + '[img]'+ imgArray.bordure + '[/img]';



            $(textarea).val(text.substring(0, $(textarea).get(0).selectionStart) + str + text.substring($(textarea).get(0).selectionEnd));
        });
    }

    function getArrivalTime(duration_time){
        /*
        var server_time = new Date((uw.Timestamp.server() + 7200) * 1000);

        duration_time = duration_time.split(":");

        s = server_time.getUTCSeconds() + parseInt(duration_time[2], 10);
        m = server_time.getUTCMinutes() + parseInt(duration_time[1], 10) + ((s>=60)? 1 : 0);
        h = server_time.getUTCHours() + parseInt(duration_time[0], 10) + ((m>=60)? 1 : 0);
        */

        var server_time = $('.server_time_area').get(0).innerHTML.split(" ")[0].split(":"), arrival_time, s, m, h;
        duration_time = duration_time.split(":");

        s = parseInt(server_time[2], 10) + parseInt(duration_time[2], 10);
        m = parseInt(server_time[1], 10) + parseInt(duration_time[1], 10) + ((s>=60)? 1 : 0);
        h = parseInt(server_time[0], 10) + parseInt(duration_time[0], 10) + ((m>=60)? 1 : 0);

        s = s%60; m = m%60; h = h%24;

        s = ((s<10) ? "0" : "") + s;
        m = ((m<10) ? "0" : "") + m;
        h = ((h<10) ? "0" : "") + h;

        arrival_time = h + ":" + m + ":" + s;

        return arrival_time;
    }


    /*******************************************************************************************************************************
 * Smiley box
 * ----------------------------------------------------------------------------------------------------------------------------
 * | ● Display of a smiley selection box for text input fields (forum, messages, notes):
 * | ● Used smileys: http://www.greensmilies.com/smilie-album/
 * | + Own Grepolis smileys
 * ----------------------------------------------------------------------------------------------------------------------------
 *******************************************************************************************************************************/

    var smileyArray =  { "standard": {}, "nature": {}, "grepolis": {}, "people": {}, "other":{} };

    // smiley categories
    smileyArray.button = [ "rollsmiliey", "smile" ];

    smileyArray.standard = [ 
        "smilenew", "i/cnfy7elqh8dotnsdp", "lol", "neutral_new", "afraid", "freddus_pacman", "auslachen2", "kolobok-sanduhr", "bussi2", "winken4", "flucht2", "panik4", "ins-auge-stechen", 
        "seb_zunge", "fluch4_GREEN", "baby_junge2", "blush-reloaded6", "frown", "verlegen", "blush-pfeif", "stevieh_rolleyes", "daumendreh2", "baby_taptap", 
        "sadnew", "hust", "confusednew", "idea2", "irre", "irre4", "sleep", "candle", "nicken", "no_sad", 
        "thumbs-up_new", "thumbs-down_new", "bravo2", "oh-no2", "kaffee2", "drunk", "saufen", "freu-dance", "hecheln", "headstand", "rollsmiliey", "eazy_cool01", "motz", "cuinlove", "biggrin"
    ];
    smileyArray.nature = [
        "dinosaurier07", "flu-super-gau", "ben_cat", "schwein", "hundeleine01", "blume", "ben_sharky", "ben_cow", "charly_bissig", "gehirnschnecke_confused", "mttao_fische", "mttao_angler", 
        "insel", "fliegeschnappen", "i/cifohy0y1cl7nckzw", /* Spinne */ "i/cifogx34asrswrcjw", /* Schiffbrüchiger */ "plapperhase", "ben_dumbo"  
    ];
    smileyArray.grepolis = [
        "mttao_wassermann", "i/cigrmpfofys5xtiks", /* Hera */ "i/cifvfsu3e2sdiipn0", /* Medusa */ "i/cigmv8wnffb3v0ifg", /* Mantikor */ "i/cigrqlp2odi2kqo24", /* Zyklop */
        "i/cj1l9gndtu3nduyvi", /* Minotaurus */ "i/cj2byjendffymp88t", /* Pegasus */ "i/cj2ccmi2x8mhcoikd", /* Hydra */
        "silvester_cuinlove", "mttao_schuetze", "kleeblatt2", "wallbash", /* "glaskugel4", */ "musketiere_fechtend", /* "krone-hoch",*/ "i/cifojb85jytq5h07g", // Wikinger
        "mttao_waage2", "steckenpferd", /* "kinggrin_anbeten2", */ "i/cifohielywpedbyh8", /* Grepo Love */ "skullhaufen", "pferdehaufen" // "i/ckajscggscw4s2u60"
    ];
    smileyArray.people = [ 
        "seb_hut5", "opa_boese2", "star-wars-yoda1-gruen", "hexefliegend", "snob", "seb_detektiv_ani", "seb_cowboy", "devil", "segen", "pirat5", "borg", "hexe3b", 
        "i/cifoqe3geok0jco5o", // Ägypter
        "i/ciforgs313z0ae1cc", // Hippie
        "eazy_polizei", "stars_elvis", "mttao_chefkoch", "nikolaus", "pirate3_biggrin", "batman_skeptisch", "tubbie1", "tubbie2", "tubbie3", "tubbie4" 
    ];
    smileyArray.other = [ 
        "steinwerfen", "herzen02", "scream-if-you-can", "kolobok", "headbash", "liebeskummer", "bussi", "brautpaar-reis", "grab-schaufler2", "boxen2", "aufsmaul", 
        "sauf", "mttao_kehren", "sm", "weckruf", "klugscheisser2", "karte2_rot", "dagegen", "party","dafuer", "outofthebox", "pokal_gold", "koepfler", "transformer"
    ];

    // Forum: extra smiley
    if($(".editor_textbox_container").get(0)){
        smileyArray.grepolis.push("i/ckajscggscw4s2u60"); // Pacman
        smileyArray.grepolis.push("i/cowqyl57t5o255zli"); // Bugpolis
        smileyArray.grepolis.push("i/cowquq2foog1qrbee"); // Inno
    }

    var id = 0, error_count = 0;

    var er = false;
    // preload images
    function loadSmileys(){
        // Replace german sign smilies
        if(LID !== "de"){
            smileyArray.other[17] = "dagegen2";
            smileyArray.other[19] = "dafuer2";
        }

        for(var e in smileyArray){
            if(smileyArray.hasOwnProperty(e)) {
                for(var f in smileyArray[e]){
                    if(smileyArray[e].hasOwnProperty(f)) {
                        var src = smileyArray[e][f]; 
                        smileyArray[e][f] = new Image();
                        smileyArray[e][f].className = "smiley" + (id++);
                        smileyArray[e][f].style.margin = '3px';
                        smileyArray[e][f].style.maxHeight = '35px';
                        smileyArray[e][f].style.cursor = 'pointer';
                        if(src.substring(0,2) == "i/" ) {
                            smileyArray[e][f].src = "http://666kb.com/" + src + ".gif";
                        } else {
                            if(er == false){
                                smileyArray[e][f].src = "http://www.greensmilies.com/smile/smiley_emoticons_" + src + ".gif";
                            } else {
                                smileyArray[e][f].src = 'http://s1.directupload.net/images/140128/93x3p4co.gif';
                            }
                        }
                        smileyArray[e][f].onerror = function () {
                            this.src = 'http://s1.directupload.net/images/140128/93x3p4co.gif';
                        };
                    }
                }
            }
        }
    }

    // Forum smilies


    function changeForumEditorLayout(){
        $('.blockrow').css({ border: "none" });

        // Subject/Title
        $($('.section div label[for="title"]').parent()).css({ float:"left", width:"36%", marginRight: "20px"});
        $($('.section div label[for="subject"]').parent()).css({ float:"left", width:"36%", marginRight: "20px"});

        $('.section div input').eq(0).css({ marginBottom: "-10px", marginTop: "10px"});
        $('#display_posticon').remove();

        // Posticons
        $('.posticons table').css({ width: "50%", /*marginTop: "-16px"*/});
        $('.posticons').css({ marginBottom: "-16px" });
        $('.posticons').insertAfter($('.section div label[for="title"]').parent());
        $('.posticons').insertAfter($('.section div label[for="subject"]').parent());
        // Posticons hint
        $('.posticons p').remove();
        // Posticons: No Icon - radio button
        $(".posticons [colspan='14']").parent().replaceWith($(".posticons [colspan='14']"));
        $(".posticons [colspan='14']").children().wrap("<nobr></nobr>");
        $(".posticons [colspan='14']").appendTo('.posticons tr:eq(0)');
        $(".posticons [colspan='4']").remove();
    }

    function addSmileyBoxForum(){
        $('<div class="smiley_box"><div>'+
          '<div align="center" style="float:left">'+
          '<a class="group" name="standard">'+	getText("labels", "std")	+' </a>'+
          '<a class="group" name="grepolis">'+	getText("labels", "gre")	+' </a>'+
          '<a class="group" name="nature">'+	getText("labels", "nat")	+' </a>'+
          '<a class="group" name="people">'+	getText("labels", "ppl")	+' </a>'+
          '<a class="group" name="other">'+		getText("labels", "oth")	+' </a>'+
          '</div><div align="right" style="margin-top:2px;"><a class="smiley_link" href="http://adf.ly/eDbBl" target="_blank">WWW.GREENSMILIES.COM</a></div>'+
          '<hr class="smiley_hr">'+
          '<div class="smiley_box_cont" style="overflow: hidden;"><hr class="smiley_hr"></div>'+
          '</div></div><br>').insertAfter(".texteditor");

        addSmileys("standard", "");    

        $('.smiley_hr').css({ margin: '3px 0px 0px 0px', color:	'#086b18', border: '1px solid' });
        $('.smiley_link').css({ color: '#0c450c' });
        $('.smiley_link').hover(
            function(){$(this).css({ color: '#14999E' });}, 
            function(){$(this).css({ color: '#0c450c' });}
        );
        $('.smiley_box').css({ maxHeight: '90px', marginLeft: "5px", width: "99%", minHeight:"10px" });
        $('.smiley_box_cont').css({ overflow: 'overlay', minHeight: '70px', marginBottom: '10px' });

        $('.group').css({ color:'#0c450c', marginRight: '10px', cursor:"pointer"}); $('.group[name="standard"]').css({ color:'#089421' });

        $('.group').click(function(){
            $('.group').each(function(){
                $(this).get(0).style.color = '#0c450c'; 
            });
            $(this).get(0).style.color = '#089421';
            // change smiley group
            addSmileys($(this).get(0).name, "");
        }); 
    }

    // add smiley box
    function addSmileyBox(e){
        var bbcodeBarId = "";
        switch (e) {
            case "/alliance_forum/forum":	bbcodeBarId = "#forum"; 
                break;
            case "/message/forward":	bbcodeBarId = "#message_bbcodes";
                break;
            case "/message/new":		bbcodeBarId = "#message_bbcodes";
                break;
            case "/message/view":		bbcodeBarId = "#message_bbcodes";
                break;
            case "/player_memo/load_memo_content":	bbcodeBarId = "#memo_edit";
                break;   
        }
        if(($(bbcodeBarId + ' #emots_popup_7').get(0) || $(bbcodeBarId + ' #emots_popup_15').get(0)) && PID == 84367){
            $(bbcodeBarId + " .bb_button_wrapper").get(0).lastChild.remove();
        }
        $('<img class="smiley_button" src="http://www.greensmilies.com/smile/smiley_emoticons_smile.gif">').appendTo(bbcodeBarId + ' .bb_button_wrapper');

        $('<div class="smiley_box">'+
          '<div class="bbcode_box middle_center"><div class="bbcode_box middle_right"></div><div class="bbcode_box middle_left"></div>'+
          '<div class="bbcode_box top_left"></div><div class="bbcode_box top_right"></div><div class="bbcode_box top_center"></div>'+
          '<div class="bbcode_box bottom_center"></div><div class="bbcode_box bottom_right"></div><div class="bbcode_box bottom_left"></div>'+
          '<div align="center" style="width:100%;">'+
          '<a class="group" name="standard" href="">'+	getText("labels", "std") +' </a>'+
          '<a class="group" name="grepolis" href="">'+	getText("labels", "gre") +' </a>'+
          '<a class="group" name="nature" href="">'+	getText("labels", "nat") +' </a>'+
          '<a class="group" name="people" href="">'+	getText("labels", "ppl") +' </a>'+
          '<a class="group" name="other" href="">'+		getText("labels", "oth") +' </a>'+
          '</div>'+
          '<hr class="smiley_hr">'+
          '<div class="smiley_box_cont" style="overflow: hidden;"></div>'+
          '<hr class="smiley_hr">'+
          '<div align="center" style="margin-top:2px;"><a href="http://www.greensmilies.com/smilie-album/" target="_blank"><span class="smiley_link">WWW.GREENSMILIES.COM</span></a></div>'+
          '</div>').appendTo(bbcodeBarId + ' .bb_button_wrapper');

        $(bbcodeBarId + ' .smiley_button').css({
            cursor: 'pointer',
            margin:'3px 2px 2px 2px'
        });
        $(bbcodeBarId + ' .smiley_box').css({
            zIndex: '5000', 
            position: 'absolute', 
            top: '27px', 
            left: '430px',
            width: '300px',
            display: 'none'
        });
        $(bbcodeBarId + ' .smiley_link').css({
            color: '#086b18',
            fontSize: '0.6em'
        });
        $(bbcodeBarId + ' .smiley_hr').css({
            margin:	'3px 0px 0px 0px',
            color:	'#086b18',
            border:	'1px solid'
        });
        $(bbcodeBarId + ' .group').css({
            color:'#0c450c'
        });
        $(bbcodeBarId + ' .group[name="standard"]').css({
            color:'#089421'
        });
        $(bbcodeBarId + ' .group').click(function(){
            $("#"+ $(this).closest('.bb_button_wrapper').parent().get(0).id +' .group').each(function(){
                $(this).get(0).style.color = '#0c450c';
            });
            $(this).get(0).style.color = '#089421';
            // change smiley group
            addSmileys($(this).get(0).name, "#"+ $(this).closest('.bb_button_wrapper').parent().get(0).id);
        });

        addSmileys("standard", bbcodeBarId);

        // smiley box toggle
        $(bbcodeBarId + " .smiley_button").toggleClick(
            function(){
                $(this).get(0).src = smileyArray.button[0].src;
                $(this).closest('.bb_button_wrapper').find(".smiley_box").get(0).style.display = "block";   
            }, 
            function(){
                $(this).get(0).src = smileyArray.button[1].src;
                $(this).closest('.bb_button_wrapper').find(".smiley_box").get(0).style.display = "none";  
            }
        );
    }

    if($(".editor_textbox_container").get(0)){
        loadSmileys(); 
        changeForumEditorLayout();
        addSmileyBoxForum();
    }


    // insert smileys from arrays into smiley box
    function addSmileys(type, bbcodeBarId){
        // reset smilies
        if($(bbcodeBarId + " .smiley_box_cont").get(0)) {$(bbcodeBarId + " .smiley_box_cont").get(0).innerHTML='';}
        // add smilies
        for(var e in smileyArray[type]){
            if(smileyArray[type].hasOwnProperty(e)) {
                //$(smileyArray[type][e]).clone();
                $('<img src="' + smileyArray[type][e].src + '" class="smiley">').appendTo(bbcodeBarId + " .smiley_box_cont");
            }
        }
        $('.smiley').css({ margin:'3px', maxHeight:'35px', cursor:'pointer' });

        $(bbcodeBarId + " .smiley_box_cont .smiley").click(function(){
            var textarea;
            if(uw.location.pathname === "/game/index"){
                // hide smiley box
                $(this).closest('.bb_button_wrapper').find(".smiley_button").click();
                // find textarea
                textarea = $(this).closest('.gpwindow_content').find("textarea").get(0);
            } else {

                if($('.editor_textbox_container').get(0)) {
                    textarea = $('.editor_textbox_container .cke_contents textarea').get(0);
                } else {
                    $(this).appendTo('iframe .forum');
                }
                //$(textarea).val(text.substring(0, $(textarea).get(0).selectionStart) + "[img]"+ $(this).get(0).src + "[/img]" + text.substring($(textarea).get(0).selectionEnd));
            }
            var text = $(textarea).val();
            $(textarea).val(text.substring(0, $(textarea).get(0).selectionStart) + "[img]"+ $(this).get(0).src + "[/img]" + text.substring($(textarea).get(0).selectionEnd));
        });
    }


    /*******************************************************************************************************************************
     * Biremes counter
     * ----------------------------------------------------------------------------------------------------------------------------
     * | ● Incremental update when calling a city (experimental, especially intended for siege worlds)
     * ----------------------------------------------------------------------------------------------------------------------------
     * *****************************************************************************************************************************/
    var count, townId;

    function updateBiriCount(){
        var sum =0, e;
        for(e in biriArray) {
            if(biriArray.hasOwnProperty(e)) {
                if(!uw.ITowns.getTown(e)) { // town is no longer in possession of user
                    delete biriArray[e]; 
                    saveBiri();
                } else {
                    sum += parseInt(biriArray[e], 10);
                }
            }
        }
        if(DATA.options.bir){
            sum = sum.toString();
            var str ="", fsize = ['1.4em', '1.2em', '1.15em', '1.1em', '1.0em'], i;

            for(i = 0; i<sum.length; i++){
                str += "<span style='font-size:" + fsize[i] + "'>" + sum[i] + "</span>";
            }
            $('#bi_count').get(0).innerHTML = "<b>" + str + "</b>";
        }
    }

    function getBiri(){
        var biremeIn = parseInt(uw.ITowns.getTown(uw.Game.townId).units().bireme, 10),
            biremeOut = parseInt(uw.ITowns.getTown(uw.Game.townId).unitsOuter().bireme, 10);
        if(isNaN(biremeIn)) biremeIn = 0;
        if(isNaN(biremeOut)) biremeOut = 0;
        if(!biriArray[uw.Game.townId] || biriArray[uw.Game.townId] < (biremeIn + biremeOut)) {
            biriArray[uw.Game.townId] = biremeIn;
        }
        updateBiriCount();
        saveBiri();
    }

    function getBiriDocks(){
        var windowID = uw.BuildingWindowFactory.getWnd().getID(),
            biremeTotal = parseInt($('#gpwnd_' + windowID + ' #unit_order_tab_bireme .unit_order_total').get(0).innerHTML, 10);

        if(!isNaN(biremeTotal)) biriArray[uw.Game.townId] = biremeTotal;
        updateBiriCount();
        saveBiri();
    }

    function getBiriAgora(){
        var biremeTotal = parseInt(uw.ITowns.getTown(parseInt(uw.Game.townId, 10)).units().bireme, 10);
        if(isNaN(biremeTotal)) biremeTotal = 0;

        $('#units_beyond_list .bireme').each(function(){
            biremeTotal += parseInt($(this).get(0).children[0].innerHTML, 10);
        });
        biriArray[uw.Game.townId] = biremeTotal;
        updateBiriCount();
        saveBiri();
    }

    function saveBiri(){
        saveValue(WID + "_biremes", JSON.stringify(biriArray));
    }

    function initBiri() {
        $(".picomap_container").prepend("<div id='unit_count'><div id='bi_count'></div></div>");

        updateBiriCount();

        $('#unit_count').css({
            background: 'url(https://gpall.innogamescdn.com/images/game/units/units_sprite_90x90_compressed.jpg)',
            height: '90px',
            width: '90px',
            position: 'relative',
            margin: '5px 28px 0px 28px',
            backgroundPosition: '-270px 0px'
        });        
        $('#bi_count').css({
            color: '#826021', 
            position: 'relative',
            top: '28px',
            fontStyle: 'italic',
            width: '79px'
        });    
        $('.picomap_overlayer').tooltip(getText("options", "bir")[0]);

        // Set Sea-ID beside the bull eye
        $('#sea_id').prependTo('#ui_box');
        $('#sea_id').css({
            background: 'none',
            fontSize: '25px',
            cursor: 'default',
            height: '50px',
            width: '50px',
            position: 'absolute',
            top:  '70px',
            left: '157px',
            zIndex: 30
        });

    }

    /*******************************************************************************************************************************
     * Popups
     * ----------------------------------------------------------------------------------------------------------------------------
     * | ● Available units (no supporting or outer units)
     * | ● Improved favor
     * | ● getTownTypes
     * ----------------------------------------------------------------------------------------------------------------------------
     *******************************************************************************************************************************/
    var groupUnitArray = {};
    // TODO: split Function (getUnits, calcUnitsSum, availableUnits, countBiremes, getTownTypes)?
    function getAllUnits(){
        try {
            var townArray = uw.ITowns.getTowns(), groupArray = uw.ITowns.townGroups.getGroupsDIO(),

                unitArray = {"sword":0, "archer":0, "hoplite":0, "chariot":0, "godsent":0, "rider":0, "slinger":0, "catapult":0, "small_transporter":0, "big_transporter":0,
                             "manticore":0, "harpy":0, "pegasus":0, "cerberus":0, "minotaur":0, "medusa":0, "zyklop":0, "centaur":0, "fury":0, "sea_monster":0 },

                unitArraySea = {"bireme":0, "trireme":0, "attack_ship":0, "demolition_ship":0, "colonize_ship":0 };

            if(uw.Game.hasArtemis){
                unitArray = $.extend(unitArray, {"griffin":0, "calydonian_boar":0});
            }
            unitArray = $.extend(unitArray, unitArraySea);

            for(var group in groupArray){
                if(groupArray.hasOwnProperty(group)){
                    // clone Object "unitArray"
                    groupUnitArray[group] = Object.create(unitArray);

                    for(var town in groupArray[group].towns){
                        if(groupArray[group].towns.hasOwnProperty(town)){
                            var type = { lo: 0, ld: 0, so: 0, sd: 0, fo: 0, fd: 0 }; // Type for TownList

                            for(var unit in unitArray){
                                if(unitArray.hasOwnProperty(unit)){
                                    // All Groups: Available units
                                    var tmp = parseInt(uw.ITowns.getTown(town).units()[unit], 10);
                                    groupUnitArray[group][unit] +=  tmp || 0;
                                    // Only for group "All"
                                    if(group == -1){
                                        //Bireme counter
                                        if( unit === "bireme" && ((biriArray[townArray[town].id] || 0) < (tmp || 0))) {
                                            biriArray[townArray[town].id] = tmp;    
                                        }
                                        //TownTypes
                                        if(!uw.GameData.units[unit].is_naval){
                                            if(uw.GameData.units[unit].flying){
                                                type.fd += ((uw.GameData.units[unit].def_hack + uw.GameData.units[unit].def_pierce + uw.GameData.units[unit].def_distance)/3 * (tmp || 0));
                                                type.fo += (uw.GameData.units[unit].attack * (tmp || 0));
                                            } else {
                                                type.ld += ((uw.GameData.units[unit].def_hack + uw.GameData.units[unit].def_pierce + uw.GameData.units[unit].def_distance)/3 * (tmp || 0));
                                                type.lo += (uw.GameData.units[unit].attack * (tmp || 0));
                                            }
                                        } else {
                                            type.sd += (uw.GameData.units[unit].defense * (tmp || 0));
                                            type.so += (uw.GameData.units[unit].attack * (tmp || 0));
                                        }
                                    }
                                }
                            }
                            // Only for group "All"
                            if(group == -1){
                                // Icon: DEF or OFF?
                                var z = ((type.sd + type.ld + type.fd) <= (type.so + type.lo + type.fo)) ? "o" : "d",
                                    temp = 0;

                                for(var t in type){
                                    if(type.hasOwnProperty(t)){
                                        // Icon: Land/Sea/Fly (t[0]) + OFF/DEF (z)
                                        if(temp < type[t]){
                                            autoTownTypes[townArray[town].id] = t[0] + z;
                                            temp = type[t];
                                        }
                                        // Icon: Troops Outside (overwrite)
                                        if(temp < 1000){
                                            autoTownTypes[townArray[town].id] = "no";
                                        }
                                    }
                                }
                                // Icon: Empty Town (overwrite)
                                var popBuilding = 0, buildVal = uw.GameData.buildings, buildingLevelArray = townArray[town].buildings().getLevels(),
                                    popMax = Math.floor(buildVal.farm.farm_factor * Math.pow(townArray[town].buildings().getBuildingLevel("farm"), buildVal.farm.farm_pow)), // Population from farm level
                                    popPlow = townArray[town].researches().attributes.plow ? 200 : 0,
                                    popFactor = townArray[town].buildings().getBuildingLevel("thermal") ? 1.1 : 1.0, // Thermal
                                    popExtra = townArray[town].getPopulationExtra();

                                for(var b in buildingLevelArray){
                                    if(buildingLevelArray.hasOwnProperty(b)){
                                        popBuilding += Math.round(buildVal[b].pop * Math.pow(buildingLevelArray[b], buildVal[b].pop_factor));
                                    }
                                }
                                population[town] = {};

                                population[town].max = popMax * popFactor + popPlow + popExtra;
                                population[town].buildings = popBuilding;
                                population[town].units = parseInt((population[town].max - (popBuilding + townArray[town].getAvailablePopulation()) ), 10);

                                if(population[town].units < 300){
                                    autoTownTypes[townArray[town].id] = "po";
                                }

                                population[town].percent = Math.round(100/(population[town].max - popBuilding) * population[town].units);
                            }
                        }
                    }
                }
            }
            updateBiriCount();
            saveBiri();
            updateAvailableUnitsBox(groupUnitArray[-1]);
        } catch(error){
            errorHandling(error, "getAllUnits"); // TODO: Eventueller Fehler in Funktion
        }
    }

    function addFunctionToITowns(){
        // Copy function and prevent an error
        uw.ITowns.townGroups.getGroupsDIO = function(){
            var town_groups_towns, town_groups, groups = {};

            // #Grepolis-Fix: 2.75 -> 2.76
            if(MM.collections){
                town_groups_towns = MM.collections.TownGroupTown[0];
                town_groups = MM.collections.TownGroup[0];
            } else {
                town_groups_towns = MM.getCollections().TownGroupTown[0];
                town_groups = MM.getCollections().TownGroup[0];
            }

            town_groups_towns.each(function(town_group_town){
                var gid=town_group_town.getGroupId(),
                    group=groups[gid],
                    town_id=town_group_town.getTownId();

                if(!group){
                    groups[gid] = group = {
                        id:gid,
                        //name: town_groups.get(gid).getName(), // hier tritt manchmal ein Fehler auf: TypeError: Cannot read property "getName" of undefined at http://_.grepolis.com/cache/js/merged/game.js?1407322916:8298:525
                        towns:{}
                    };
                }

                group.towns[town_id]={id:town_id};
                //groups[gid].towns[town_id]={id:town_id};
            });
            //console.log(groups);
            return groups;
        };
    }


    function addAvailableUnitsBox(){
        try {
            var groupArray = uw.ITowns.townGroups.getGroupsDIO(),
                default_title = DM.getl10n("place", "support_overview").options.troop_count + " ("+ DM.getl10n("hercules2014", "available")+")";

            if(default_title.length >= 20){ 
                default_title = default_title.substr(0, default_title.indexOf("("));
            }

            $('<div id="available_units_box" class="ui-dialog">'+
              '<div class="bbcode_box middle_center"><div class="bbcode_box middle_right"></div><div class="bbcode_box middle_left"></div>'+
              '<div class="bbcode_box top_left"></div><div class="bbcode_box top_right"></div><div class="bbcode_box top_center"></div>'+
              '<div class="bbcode_box bottom_center"></div><div class="bbcode_box bottom_right"></div><div class="bbcode_box bottom_left"></div>'+
              '<h4><nobr>'+ (LANG.hasOwnProperty(LID) ? getText("labels", "uni") : default_title) + '</nobr></h4>'+
              '<div class="drop_box">'+
              '<div class="drop_group dropdown default">'+
              '<div class="border-left"></div><div class="border-right"></div>'+
              '<div class="caption" name="'+ groupArray[-1].id +'">'+ ITowns.town_groups._byId[groupArray[-1].id].attributes.name +'</div>'+
              '<div class="arrow"></div>'+
              '</div>'+
              '<div class="select_group dropdown-list default active"><div class="item-list"></div></div>'+
              '</div><hr>'+
              '<div class="box_content"></div>'+
              '</div>').appendTo('body');

            for(var group in groupArray){
                if(groupArray.hasOwnProperty(group)){
                    var group_name = ITowns.town_groups._byId[group].attributes.name;
                    $('<div class="option'+ (group == -1 ? " sel" : "") +'" name="'+ group +'">'+ group_name +'</div>').appendTo('#available_units_box .item-list');
                }
            }

            // Styles
            $('#available_units_box .drop_box').css({
                float: 'left',
                position: 'absolute',
                top: '1px',
                right: '0px',
                width: '90px',
                zIndex: '1'
            });
            $('#available_units_box h4').css({
                color: 'rgb(128, 64, 0)',
                width: '10px', 
                height: '25px', 
                marginLeft: '4px', 
                lineHeight: '1.9'
            });
            $('#available_units_box .drop_group').css({
                width: '84px'
            });
            $('#available_units_box .select_group').css({
                position: 'absolute',
                width: '80px',
                display: "none",
                right: '3px'
            });
            //$('#available_units_box .item-list').css({ maxHeight: '400px', maxWidth: '200px', align: "right" });

            $('#available_units_box .arrow').css({
                width: '18px',
                height: '18px',
                background: 'url('+ drop_out.src +') no-repeat -1px -1px',
                position: 'absolute'
            });

            // hover effects of the elements in the drop menu
            $('#available_units_box .option').hover(
                function(){ $(this).css({color: '#fff', background: "#328BF1"}); },
                function(){ $(this).css({color: '#000', background: "#FFEEC7"}); }
            );

            // click events of the drop menu
            $('#available_units_box .select_group .option').each(function(){
                $(this).click(function(e){
                    $(this).parent().find(".sel").toggleClass("sel");
                    $(this).toggleClass("sel");

                    $('#available_units_box .drop_group .caption').attr("name", $(this).attr("name"));
                    $('#available_units_box .drop_group .caption').get(0).innerHTML = $(this).get(0).innerHTML;
                    $('#available_units_box .select_group')[0].style.display = "none";

                    updateAvailableUnitsBox(groupUnitArray[$(this).attr("name")]);
                    //$('#available_units_box .drop_group .caption').change();
                });
            });
            // show & hide drop menu on click
            $('#available_units_box .drop_group').click(function(){
                if($('#available_units_box .select_group')[0].style.display === "none"){
                    $('#available_units_box .select_group')[0].style.display = "block";
                } else {
                    $('#available_units_box .select_group')[0].style.display = "none";
                }
            });

            $('#available_units_box').click(function(e){
                var clicked = $(e.target);
                if(!(clicked[0].parentNode.className.split(" ")[1] === "dropdown")){
                    $('#available_units_box .select_group').get(0).style.display = "none";
                }
            });

            // hover arrow change
            $('#available_units_box .dropdown').hover(function(e){
                $(e.target)[0].parentNode.childNodes[3].style.background = "url('"+ drop_over.src +"') no-repeat -1px -1px";
            }, function(e){
                $(e.target)[0].parentNode.childNodes[3].style.background = "url('"+ drop_out.src +"') no-repeat -1px -1px";
            });

            //$("#available_units_box .drop_group .caption").attr("name", "All");
            //$('#available_units_box .drop_group').tooltip();

            $('#available_units_box').draggable({ 
                containment: "body",
                snap: "body",
            });
            $('#available_units_box').css({
                color: 'rgb(12, 69, 12)',
                position: 'absolute',
                top: '100px',
                left: '200px',
                zIndex: getMaxZIndex() + 1,
                display: 'none'
            });
            $('#available_units_box .box_content').css({
                background: 'url(http://s1.directupload.net/images/140206/8jd9d3ec.png) 94% 94% no-repeat',
                backgroundSize: '140px'
            });

            $('#available_units_box').bind("mousedown",function(){
                $(this).get(0).style.zIndex = getMaxZIndex() + 1;
            });

            $('#available_units_box hr').css({ margin: '3px 0px 0px', border: '1px solid', color: 'rgb(128, 64, 0)'});
        } catch(error){
            errorHandling(error, "addAvailableUnitsBox");
        }
    }

    function updateAvailableUnitsBox(unitArray){
        var i = 0, content = '<table><tr><td>', ttpArray = {};
        for(var u in unitArray){
            if(unitArray.hasOwnProperty(u)){
                if(((i%5 == 0) && (i!== 25)) || u == "bireme") { 
                    content += "</td></tr><tr><td>"; 
                }
                content += '<div class="unit index_unit bold unit_icon40x40 ' + u + ' " ><span style="font-size:0.9em">' + unitArray[u] + '</span></div> ';
                ttpArray[u] = GameData.units[u].name;
                i++;
            }
        }
        content += '</td></tr></table>';
        $('#available_units_box .box_content').get(0).innerHTML = "";
        $('#available_units_box .box_content').append(content);


        // Unit name tooltips
        for(var o in ttpArray){
            if(ttpArray.hasOwnProperty(o)){
                $("#available_units_box ."+ o).tooltip(ttpArray[o]);
            }
        }
    }

    function unbindFavorPopup(){
        //$('.gods_favor_button_area, #favor_circular_progress').mouseover();
        //$('.gods_favor_button_area, #favor_circular_progress').mouseout();

        $('.gods_favor_button_area, #favor_circular_progress').bind('mouseover mouseout', function(){
            return false;
        });
        $('.gods_area').bind('mouseover', function(){
            setFavorPopup();
        });
    }

    var godArray = {
        zeus:		'   0px', //'http://s1.directupload.net/images/140116/mkhzwush.png',
        hera:		'-152px', //'http://s1.directupload.net/images/140116/58ob8z82.png',
        poseidon:	'-101px', //'http://s1.directupload.net/images/140116/dkfxrw2f.png',
        athena:		' -50px', //'http://s14.directupload.net/images/140116/iprgopak.png',
        hades:		'-203px', //'http://s14.directupload.net/images/140116/c9juk95y.png',
        artemis:	'-305px', //'http://s14.directupload.net/images/140116/pdc8vxe2.png'
    };

    var godImg = new Image(); godImg.src = "https://diotools.pf-control.de/images/game/gods.png";

    function setFavorPopup(){
        var pic_row = "",
            fav_row	= "", 
            prod_row = "";

        for(var g in godArray){
            if(godArray.hasOwnProperty(g)){
                if(uw.ITowns.player_gods.attributes.temples_for_gods[g]){
                    pic_row += '<td><div style="width:50px;height:51px;background:url('+ godImg.src +');background-position: 0px '+ godArray[g] +';"></td>';
                    fav_row += '<td class="bold" style="color:blue">'+ uw.ITowns.player_gods.attributes[g + "_favor"] +'</td>';
                    prod_row += '<td class="bold">'+ uw.ITowns.player_gods.attributes.production_overview[g].production +'</td>';
                }
            }
        }
        var tool_element = $('<table><tr><td></td>'+ pic_row +'</tr>'+
                             '<tr align="center"><td><img src="https://gpall.innogamescdn.com/images/game/res/favor.png"></td>'+ fav_row +'</tr>'+
                             '<tr align="center"><td>+</td>'+ prod_row +'</tr>'+
                             '</table>');

        $('.gods_favor_button_area, #favor_circular_progress').tooltip(tool_element);
    }


    /*******************************************************************************************************************************
     * GUI Optimization
     * ----------------------------------------------------------------------------------------------------------------------------
     * | ● Modified spell box (smaller, moveable & position memory)
     * | ● Larger taskbar and minimize daily reward-window on startup
     * | ● Modify chat
     * | ● Improved display of troops and trade activity boxes (movable with position memory on startup)
     * ----------------------------------------------------------------------------------------------------------------------------
     *******************************************************************************************************************************/

    // Spell box
    function catchSpellBox(){
        $.Observer(uw.GameEvents.ui.layout_gods_spells.rendered).subscribe('DIO_SPELLBOX_CHANGE_OPEN', function () {
            if(spellbox.show == false) {
                spellbox.show = true;
                saveValue("spellbox", JSON.stringify(spellbox));
            }

            changeSpellBox();
        });
        $.Observer(uw.GameEvents.ui.layout_gods_spells.state_changed).subscribe('DIO_SPELLBOX_CLOSE', function () {
            spellbox.show = false;
            saveValue("spellbox", JSON.stringify(spellbox));
        });
    }

    function initSpellBox(){
        try {
            $('<style type="text/css">'+
              '.gods_spells_active .nui_right_box {'+ 
              'overflow: visible !important;'+
              '</style>').appendTo('head');

            $(".gods_spells_menu").css({
                width: "134px"
            });

            $("#ui_box .gods_area .gods_spells_menu .content").css({
                background: "url(https://gpall.innogamescdn.com/images/game/layout/power_tile.png) 1px 4px",
                overflow: "auto",
                margin: "0 0 0px 0px",
                border: "3px inset rgb(16, 87, 19)",
                borderRadius: "10px"
            });

            $('.nui_units_box').css({
                display: 'block',
                marginTop: '-8px',
                position: 'relative'
            });
            $('.nui_units_box .bottom_ornament').css({
                marginTop: '-28px',
                position: 'relative'
            });

            $('.gods_area').css({
                height: '150px'
            });

            if($(".gods_spells_menu .left").get(0)){
                $(".gods_spells_menu .left").remove(); $(".gods_spells_menu .right").remove();
                $(".gods_spells_menu .top").remove(); $(".gods_spells_menu .bottom").remove();
            }

            $(".gods_spells_menu").draggable({ 
                containment: "body",  
                distance: 10 , 
                snap: "body, .gods_area, .nui_units_box, .ui_quickbar, .nui_main_menu, .minimized_windows_area, #island_quests_overview", 
                opacity: 0.7,
                stop : function(){
                    spellbox.top = this.style.top;
                    spellbox.left = this.style.left;

                    saveValue("spellbox", JSON.stringify(spellbox));
                }
            });
            $(".gods_area .gods_spells_menu").before($('.nui_units_box'));


            // Position
            $('.gods_spells_menu').css({
                position:	'absolute',
                left:		spellbox.left,
                top:		spellbox.top,
                zIndex:		'5000',
                padding:	'30px 0px 0px -4px'
            });

            // Active at game start?
            if(spellbox.show) {
                $('.btn_gods_spells').click();
            } 
        } catch(error){
            errorHandling(error, "initSpellBox");
        } 

    }

    function changeSpellBox(){
        try {
            $(".gods_spells_menu").css({
                //height: "300px"
                //height: $(".nui_units_box").height() + "px"
            });
            //console.log($(".nui_units_box").height());

            $('.god_container[data-god_id="zeus"]').css({
                //float: 'left'
            });
            $('.powers_container').css({
                background: 'none'
            });
            $('.god_container').css({
                float: 'left'
            });
            $('.god_container[data-god_id="zeus"], .god_container[data-god_id="athena"]').css({
                float: 'none'
            });
            $('.content .title').each(function(){
                $(this).get(0).style.display = "none";
            });

            $('.god_container[data-god_id="poseidon"]').prependTo('.gods_spells_menu .content');
            $('.god_container[data-god_id="athena"]').appendTo('.gods_spells_menu .content');
            $('.god_container[data-god_id="artemis"]').appendTo('.gods_spells_menu .content');

            if($('.bolt').get(0))		{ $('.bolt').remove(); }
            if($('.earthquake').get(0)) { $('.earthquake').remove(); }
            if($('.pest').get(0))		{ $('.pest').remove(); }
        } catch(error){
            errorHandling(error, "changeSpellBox");
        }
    }

    // Minimize Daily reward window on startup
    function minimizeDailyReward(){
        /*
        $.Observer(uw.GameEvents.window.open).subscribe('DIO_WINDOW', function(u,dato){});
        $.Observer(uw.GameEvents.window.reload).subscribe('DIO_WINDOW2', function(f){});
        */
        if(MutationObserver) {
            var startup = new MutationObserver(function(mutations) {
                mutations.forEach(function(mutation) {
                    if(mutation.addedNodes[0]){
                        if($('.daily_login').get(0)){ //  && !uw.GPWindowMgr.getOpenFirst(uw.Layout.wnd.TYPE_SHOW_ON_LOGIN).isMinimized()
                            $('.daily_login').find(".minimize").click();
                            //uw.GPWindowMgr.getOpenFirst(uw.Layout.wnd.TYPE_SHOW_ON_LOGIN).minimize();
                        }
                    }
                });    
            });
            startup.observe($('body').get(0), { attributes: false, childList: true, characterData: false});

            setTimeout(function(){ startup.disconnect();}, 3000);
        }
    }

    // Larger taskbar
    function scaleTaskbar(){
        $('.minimized_windows_area').get(0).style.width= "150%";
        $('.minimized_windows_area').get(0).style.left= "-25%";
    }
    // hide fade out buttons => only for myself
    function hideNavElements() {
        if(uw.Game.premium_features.curator<=uw.Timestamp.now()){
            $('.nav').each(function() {
                $(this).get(0).style.display = "none";
            });
        }
    }

    /*******************************************************************************************************************************
     * Modify Chat
     *******************************************************************************************************************************/
    function popupChatUser(){ // not used yet
        setTimeout(function(){
            GM_xmlhttpRequest({
                method: "POST",
                url: "http://wwwapi.iz-smart.net/modules.php?name=Chaninfo&file=nicks&chan=Grepolis"+ uw.Game.market_id.toUpperCase(),
                onload: function(response) {
                    //$('.nui_main_menu .chat .indicator').get(0).innerHTML = 
                    //console.log(response.responseText);
                    //$('.nui_main_menu .chat .indicator').get(0).style.display = 'inline';
                }
            }); 
        }, 0);
    }

    function initChatUser(){
        $('.nui_main_menu .chat .button, .nui_main_menu .chat .name_wrapper').css({
            filter: 'url(#Hue1)',
            WebkitFilter: 'hue-rotate(65deg)'
        });
        updateChatUser();
        setInterval(function(){ updateChatUser(); }, 300000);
        $('.nui_main_menu .chat').mouseover(function(){
            //popupChatUser();
        });
        if($('.nui_main_menu .chat').hasClass('disabled')){ $('.nui_main_menu .chat').removeClass('disabled');}
    }

    function updateChatUser(){
        var market = uw.Game.market_id;
        if(gm){
            // GM-BROWSER:
            chatUserRequest();
        } else {
            // SAFARI:
            $.ajax({
                url:"https://diotools.pf-control.de/game/chatuser_count.php?chan=Grepo"+ (market === "de" ? "lisDE" : ""),
                dataType : 'text',
                success: function(text) {
                    $('.nui_main_menu .chat .indicator').get(0).innerHTML = text;
                    $('.nui_main_menu .chat .indicator').get(0).style.display = 'block';
                },
                error: function (xhr, ajaxOptions, thrownError) {
                    $('.nui_main_menu .chat .indicator').get(0).style.display = 'none';
                }
            });
        }
    }


    $('<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/swfobject/2.2/swfobject.js"></script>').appendTo('head');

    // Modify chat window
    function modifyChat() {
        var host = { fr: 'irc.quakenet.org', def: 'flash.afterworkchat.de'}, 
            market = uw.Game.market_id, select_nick = false, chatwnd_id,
            nickname = uw.Game.player_name;

        setTimeout(function(){ updateChatUser(); }, 10000); setTimeout(function(){ updateChatUser(); }, 30000);

        //uw.GPWindowMgr.Create(uw.Layout.wnd.TYPE_CHAT);

        //uw.GPWindowMgr.getOpenFirst(uw.Layout.wnd.TYPE_CHAT).setWidth(600);
        //uw.GPWindowMgr.getOpenFirst(uw.Layout.wnd.TYPE_CHAT).setHeight(300);
        //uw.GPWindowMgr.getOpenFirst(uw.Layout.wnd.TYPE_CHAT).setPosition([0,'bottom']);

        //console.log(uw.GPWindowMgr.getOpenFirst(uw.Layout.wnd.TYPE_CHAT));

        chatwnd_id = '#gpwnd_' + uw.GPWindowMgr.getOpenFirst(uw.Layout.wnd.TYPE_CHAT).getID();

        $('#chat').get(0).innerHTML = "";
        //$(chatwnd_id).parent().children('.gpwindow_left').remove();
        //$(chatwnd_id).parent().children('.gpwindow_right').remove();
        //$(chatwnd_id).parent().children('.gpwindow_top').remove();
        //$(chatwnd_id).parent().children('.gpwindow_bottom').remove();
        //$(chatwnd_id).parent().parent().children('.ui-dialog-titlebar').remove();

        var replaceArray = {
            // Russian:
            "Ё":"YO","Й":"I","Ц":"TS","У":"U","К":"K","Е":"E","Н":"N","Г":"G","Ш":"SH","Щ":"SCH","З":"Z","Х":"H","Ъ":"'",
            "ё":"yo","й":"i","ц":"ts","у":"u","к":"k","е":"e","н":"n","г":"g","ш":"sh","щ":"sch","з":"z","х":"h","ъ":"'",
            "Ф":"F","Ы":"I","В":"V","А":"a","П":"P","Р":"R","О":"O","Л":"L","Д":"D","Ж":"ZH","Э":"E",
            "ф":"f","ы":"i","в":"v","а":"a","п":"p","р":"r","о":"o","л":"l","д":"d","ж":"zh","э":"e",
            "Я":"Ya","Ч":"CH","С":"S","М":"M","И":"I","Т":"T","Ь":"'","Б":"B","Ю":"YU",
            "я":"ya","ч":"ch","с":"s","м":"m","и":"i","т":"t","ь":"'","б":"b","ю":"yu",

            // Greek:
            'Α':'A','Β':'B','Γ':'G','Δ':'D','Ε':'E','Ζ':'Z','Η':'H','Θ':'Th','Ι':'I','Κ':'K','Λ':'L','Μ':'M','Ν':'N','Ξ':'J','Ο':'O','Π':'P','Ρ':'R','Σ':'S',
            'Τ':'T','Υ':'U','Φ':'F','Χ':'Ch','Ψ':'Ps','Ω':'W','Ά':'A','Έ':'E','Ή':'H','Ί':'I','Ό':'O','Ύ':'U','Ώ':'W','Ϊ':'I',
            'α':'a','β':'b','γ':'g','δ':'d','ε':'e','ζ':'z','η':'h','θ':'th','ι':'i','κ':'k','λ':'l','μ':'m','ν':'n','ξ':'j','ο':'o','π':'p','ρ':'r','ς':'s',
            'σ':'s','τ':'t','υ':'u','φ':'f','χ':'ch','ψ':'ps','ω':'w','ά':'a','έ':'e','ή':'h','ί':'i','ό':'o','ύ':'u','ώ':'w','ϊ':'i','ΐ':'i'
        };

        function replaceNick(word){
            var temp = "", temp2 = "";
            // Step 1: Replace Special and some german chars
            word = word.replace(/[.,:,+,*]/g,"").replace(/[=,\ ,\-]/g,"_").replace(/ö/gi,"oe").replace(/ä/gi,"ae").replace(/ü/gi,"ue").replace(/ß/g,"ss");
            // Step 2: Replace russian and greek chars
            if(!word.match(/^[a-zA-Z0-9_]+$/)){
                temp = word.split('').map(function (char) { 
                    var ch = "";
                    ch = replaceArray[char] || char; 
                    return ch;
                }).join("");
                // Step 3: Delete all other special chars
                if(!temp.match(/^[a-zA-Z0-9_]+$/)){
                    for(var c = 0; c < temp.length; c++){
                        if(temp[c].match(/^[a-zA-Z0-9_]+$/)){
                            temp2 += temp[c];
                        }
                    }
                    select_nick = true;
                    temp = temp2;
                }
                word = temp;
            } 
            return word;
        }
        //nickname = "kνnmδενεί-ναισυνδεδ*εμένος_Ιππέας"; // greek test nickname
        nickname = replaceNick(nickname);

        if(PID == 84367){ nickname = "DionY_"; }

        $('<iframe src="https://diotools.pf-control.de/chat/lightIRC.swf'+ //'+ //http://flash.afterworkchat.de/1.0/FlashChat.swf
          '?host=irc.todochat.org'+//irc.lightirc.com'+ //flash.afterworkchat.de'+
          //'?languagePath=http://flash.afterworkchat.de/1.0/language/'+
          '&port=6667'+
          '&ssl=true'+          
          '&policyPort=8002'+
          '&styleURL=https://diotools.pf-control.de/css/green3.css'+
          '&emoticonPath=https://diotools.pf-control.de/chat/emoticons/'+
          '&emoticonList='+
          ':)->smile.png,:(->sad.png,:O->baby.swf,:D->biggrin.png,~D->coffee.swf,:P->tongue.swf,8)->cool.png,:|->neutral.png,X)->drunk.swf,%5e%5e->grins.png,:{->cry.swf,:S->verlegen.png,'+
          ':$->blush.swf,:]->lol.swf,:*->bussi.swf,:[->fluch.swf'+
          //'&accessKey=54a2846a460ae1703ac690d21551b997'+
          '&nick='+ nickname +
          '&nickAlternate='+ nickname +'_'+
          '&autojoin=%23GREPO,%23Grepolis'+ market.toUpperCase() +
          '&showNickSelection='+ select_nick +
          '&showNavigation=true'+
          '&navigationPosition=top'+
          '&showNickSelection=false'+
          '&showIdentifySelection=false'+
          '&language='+ LID +
          '&quitMessage=CYA'+
          '&showChannelHeader=false'+
          //'&useUserListIcons=true'+
          '&userListWidth=100'+
          '&soundAlerts=true'+
          '&soundOnNewChannelMessage=true'+
          '&showServerWindow=false'+
          '&fontSize=9'+
          '&showJoinPartMessages=false'+
          '&showMenuButton=false'+
          '&showTranslationButton=false'+
          '&showTimestamps=true'+
          //'&showInfoMessages=false'+
          '&showRegisterNicknameButton=false'+
          '&showRichTextControls=false'+
          //'&useUserListIcons=true'+
          '&showUserListInformationPopup=false'+
          '&showNickChangeButton=false'+
          '&showChannelCentral=false'+
          '&showOptionsButton=false'+
          '&showEmoticonsButton=true'+
          '&rememberNickname=false'+
          '" style="width:518px; height:357px; border:0px;"></iframe>').appendTo("#chat");

        /*
        $('<html><body><div id="lightIRC"><p><a href="http://www.adobe.com/go/getflashplayer"><img src="http://www.adobe.com/images/shared/download_buttons/get_flash_player.gif" alt="Get Adobe Flash player" /></a></p></div>'+
          '<script type="text/javascript">'+
          'var params = {};'+
          'params.languagePath			= "http://flash.afterworkchat.de/1.0/language/";'+
          'params.host					= "flash.afterworkchat.de";'+
          'params.port					= 6667;'+
          'params.policyPort			= 9000;'+
          //'params.accessKey			= "54a2846a460ae1703ac690d21551b997";'+
          'params.styleURL				= "http://diotools.pf-control.de/css/green2.css";'+
          'params.emoticonPath			= "http://diotools.pf-control.de/chat/emoticons/";'+
          'params.emoticonList			= ":)->smile.png,:(->sad.png,:O->baby.swf,:D->biggrin.png,~D->coffee.swf,:P->tongue.swf,8)->cool.png,:|->neutral.png,X)->drunk.swf,%5e%5e->grins.png,:{->cry.swf,:S->verlegen.png,'+
          ':$->blush.swf,:]->lol.swf,:*->bussi.swf,:[->fluch.swf";'+
          'params.nick					= "'+ nickname + '";' +
          'params.autojoin				= "%23GREPO,%23Grepolis'+ market.toUpperCase() + '";' +
          'params.showNickSelection		= ' + select_nick + ';'+
          'params.showIdentifySelection = false;'+
          'params.language				= "'+ LID +'";'+
          'params.soundAlerts			= true;'+
          'params.fontSize				= "10";'+
          'params.navigationPosition	= "top";'+
          'params.showJoinPartMessages	= false;'+
          'params.showTimestamps		= true;'+
          'params.showRegisterNicknameButton = false;'+
          'params.showNickChangeButton	= true;'+
          'params.showOptionsButton		= true;'+
          'params.showServerWindow		= false;'+
          'params.showOptionsButton		= false;'+
          'params.showMenuButton		= false;'+
          'params.showTranslationButton	= false;'+
          'params.showRichTextControls	= false;'+
          'params.showChannelHeader		= false;'+
          'params.rememberNickname		= false;'+
          'params.userListWidth			= 100;' +
          'params.soundAlerts			= true;'+
          'params.soundOnNewChannelMessage = false;'+
          'swfobject.embedSWF("http://flash.afterworkchat.de/1.0/FlashChat.swf", "lightIRC", "100%", "100%", "10.0.0", "http://flash.afterworkchat.de/expressinstall.swf", params, {wmode:"transparent"});'+
          '</script></body></html>').appendTo("#chat"); 
          */
    }

    /*******************************************************************************************************************************
 * Activity boxes
 * ----------------------------------------------------------------------------------------------------------------------------
 * | ● Show troops and trade activity boxes
 * | ● Boxes are magnetic & movable (position memory)
 * ----------------------------------------------------------------------------------------------------------------------------
 *******************************************************************************************************************************/
    var mut_toolbar, mut_command, mut_trade;
    function checkToolbarAtStart(){
        if(parseInt($('.toolbar_activities .commands .count').get(0).innerHTML, 10) > 0){
            $('#toolbar_activity_commands_list').get(0).style.display = "block";
        } else {
            $('#toolbar_activity_commands_list').get(0).style.display = "none";
        }
        if(parseInt($('.toolbar_activities .trades .count').get(0).innerHTML, 10) > 0){
            $('#toolbar_activity_trades_list').get(0).style.display = "block";
        } else {
            $('#toolbar_activity_trades_list').get(0).style.display = "none";
        }
    }

    function catchToolbarEvents(){
        mut_toolbar = new MutationObserver(function(mutations) {
            mutations.forEach(function(mutation) {
                if(mutation.addedNodes[0]){
                    //console.log(mutation);
                    if(mutation.target.id === "toolbar_activity_trades_list"){
                        draggableTradeBox();
                    } else {
                        draggableCommandBox();
                    }
                    mutation.addedNodes[0].remove();
                }
            });    
        });
        mut_command = new MutationObserver(function(mutations) {
            mutations.forEach(function(mutation) {
                if(mutation.addedNodes[0]){
                    if(mutation.addedNodes[0].nodeValue > 0){
                        $('#toolbar_activity_commands_list').get(0).style.display = "block";
                    } else {
                        $('#toolbar_activity_commands_list').get(0).style.display = "none";
                    }
                }
            });    
        });
        mut_trade = new MutationObserver(function(mutations) {
            mutations.forEach(function(mutation) {
                if(mutation.addedNodes[0]){
                    if(mutation.addedNodes[0].nodeValue > 0){
                        $('#toolbar_activity_trades_list').get(0).style.display = "block";
                    } else {
                        $('#toolbar_activity_trades_list').get(0).style.display = "none";
                    }
                }
            });    
        });
    }
    // moveable boxes
    function draggableTradeBox(){
        $("#toolbar_activity_trades_list").draggable({ 
            containment: "body",
            distance: 20,
            snap: "body, .gods_area, .nui_units_box, .ui_quickbar, .nui_main_menu, .minimized_windows_area, .nui_left_box", 
            opacity: 0.7,
            start : function () {
                $("#fix_trade").remove();
            },
            stop : function () {
                var pos = $('#toolbar_activity_trades_list').position();
                tradebox.left = pos.left;

                saveValue("tradebox", JSON.stringify(tradebox));


                $('<style id="fix_trade" type="text/css">'+
                  '#toolbar_activity_trades_list {'+
                  'left:' + tradebox.left	+ 'px !important;'+
                  'top: ' + tradebox.top	+ 'px !important}'+
                  '</style>').appendTo('head');	
            }
        });
    }

    function draggableCommandBox(){
        $("#toolbar_activity_commands_list").draggable({ 
            containment: "body",
            distance: 20,
            snap: "body, .gods_area, .nui_units_box, .ui_quickbar, .nui_main_menu, .minimized_windows_area, .nui_left_box", 
            opacity: 0.7,
            stop : function () {
                var pos = $('#toolbar_activity_commands_list').position();
                commandbox.left = pos.left;
                commandbox.top = pos.top;

                saveValue("commandbox", JSON.stringify(commandbox));
            }
        });
    }

    function showActivityBoxes(){
        var observe_options = { attributes: false, childList: true, characterData: false};

        catchToolbarEvents();

        mut_toolbar.observe($('#toolbar_activity_commands_list').get(0), observe_options );
        mut_toolbar.observe($('#toolbar_activity_trades_list').get(0), observe_options );

        mut_command.observe($('.toolbar_activities .commands .count').get(0), observe_options );
        mut_trade.observe($('.toolbar_activities .trades .count').get(0), observe_options );

        $('#toolbar_activity_commands').mouseover();
        $('#toolbar_activity_trades').mouseover();
        $('#toolbar_activity_commands, #toolbar_activity_trades').unbind("mouseover");
        $('#toolbar_activity_commands, #toolbar_activity_commands_list, #toolbar_activity_trades, #toolbar_activity_trades_list').unbind("mouseout");
        $('#toolbar_activity_trades_list').unbind("click");

        checkToolbarAtStart();

        $('#toolbar_activity_commands_list').css({
            left:	commandbox.left	+ "px",
            top:	commandbox.top	+ "px"
        });

        $('<style id="fix_lists" type="text/css">'+
          '#toolbar_activity_commands_list, #toolbar_activity_trades_list { width: 160px}'+
          '.dropdown-list .content { max-height: 329px}'+
          '</style>'+
          '<style id="fix_trade" type="text/css">'+
          '#toolbar_activity_trades_list {'+
          'left:' + tradebox.left	+ 'px !important;'+
          'top: ' + tradebox.top	+ 'px !important}'+
          '</style>').appendTo('head');

        draggableCommandBox();
        draggableTradeBox();

        $('.toolbar_activities .commands').mouseover(function(){
            $('#toolbar_activity_commands_list').get(0).style.display = "block";
        });
        $('.toolbar_activities .trades').mouseover(function(){
            $('#toolbar_activity_trades_list').get(0).style.display = "block";
        });
    }

    /*******************************************************************************************************************************
     * Other stuff
     *******************************************************************************************************************************/

    function counter(time){
        var type = "", today, counted, year, month, day;
        if(uw.Game.market_id !== "zz"){
            counted = DATA.count;
            today = new Date((time + 7200) * 1000);
            year = today.getUTCFullYear();
            month = ((today.getUTCMonth()+1) < 10 ? "0" : "") + (today.getUTCMonth()+1);
            day = (today.getUTCDate() < 10 ? "0" : "") + today.getUTCDate();
            today = year + month + day;
            //console.log(today);
            if(counted[0] !== today){type += "d"; }
            if(counted[1] == false){ type += "t"; }
            if((counted[2] == undefined) || (counted[2] == false)){ type += "b"; }
            if(type !== ""){
                $.ajax({
                    type: "GET",
                    url: "https://diotools.pf-control.de/game/count.php?type="+ type + "&market="+ uw.Game.market_id + "&date="+ today + "&browser="+ getBrowser(),
                    dataType : 'text',
                    success: function (text) {
                        if(text.indexOf("dly") > -1){
                            counted[0] = today;
                        }
                        if(text.indexOf("tot") > -1){
                            counted[1] = true; 
                        }
                        if(text.indexOf("bro") > -1){
                            counted[2] = true; 
                        }
                        saveValue("dio_count", JSON.stringify(counted));
                    }
                });
            }

        }
    }

    /*
    function xmas(){
        $('<a href="http://www.greensmilies.com/smilie-album/" target="_blank"><div id="xmas"></div></a>').appendTo('#ui_box');
        $('#xmas').css({
            background: 'url("http://www.greensmilies.com/smile/smiley_emoticons_weihnachtsmann_nordpol.gif") no-repeat',
            height: '51px',
            width: '61px',
            position:'absolute',
            bottom:'10px',
            left:'60px',
            zIndex:'2000'
        });
        $('#xmas').tooltip("HO HO HO, Frohe Weihnachten!");  
    }

    function silvester(){
        $('<a href="http://www.greensmilies.com/smilie-album/" target="_blank"><div id="silv">'+
          '<img src="http://www.greensmilies.com/smile/sign2_2.gif">'+
          '<img src="http://www.greensmilies.com/smile/sign2_0.gif">'+
          '<img src="http://www.greensmilies.com/smile/sign2_1.gif">'+
          '<img src="http://www.greensmilies.com/smile/sign2_4.gif">'+
          '</div></a>').appendTo('#ui_box');
        $('#silv').css({
            //background: 'url("http://www.greensmilies.com/smile/buchstaben_0.gif") no-repeat',
            //height: '57px',
            //width: '34px',
            position:'absolute',
            bottom:'10px',
            left:'70px',
            zIndex:'10'
        });
        $('#silv').tooltip("Frohes Neues!");  
    }

    function joke(){
        setTimeout(function(){
            if($('#grcgrc').get(0)){
                $('<a href="http://www.greensmilies.com/smilie-album/" target="_blank"><div id="fight"></div></a>').appendTo('#ui_box');
                $('#fight').css({
                    background: 'url("http://www.greensmilies.com/smile/smiley_emoticons_hoplit_speer4.gif") no-repeat',
                    height: '51px',
                    width: '61px',
                    position:'absolute',
                    bottom:'10px',
                    left:'39px',
                    zIndex:'2000'
                });
                $('#fight').tooltip("WWW.GREENSMILIES.COM");
            }
        }, 5000);
    }
*/

}