Valmone / Make Looting Great Again

// ==UserScript==
// @name        Make Looting Great Again
// @namespace   https://openuserjs.org/user/Valmone
// @description Récapitulatif de rentabilité pillage/raide/expedition Ogame
// @copyright   2018, Valmone (https://openuserjs.org/users/Valmone)
// @license    	MIT
// @include     *.ogame*gameforge.com/game/*
// @version    	1.6.2
// @grant       GM_addStyle
// @grant       GM_setValue
// @grant       GM_getValue
// @grant       GM_deleteValue
// @updateURL   https://openuserjs.org/meta/Valmone/Make_Looting_Great_Again.meta.js
// @downloadURL https://openuserjs.org/install/Valmone/Make_Looting_Great_Again.user.js
// ==/UserScript==

// ==OpenUserJS==
// @author       Valmone
// @testeur      Kate, Sospyne, Galoup
// ==/OpenUserJS==

(function() {
    'use strict';

    function importOldData() {
        function transfertID(arg, entry) {
            for(var i = 0; i < arg.length; i++) {
                entry.push(arg[i]);
            }
            return entry;
        }
        function transfertREPORT(arg, entry, type) {
            for(var i = 0; i < arg.length; i++) {
                if (type == "localStorage")
                	entry.push(arg[i]);
                else {
                	if (type != "combat") {
	                    var damage = 0,
	                        loose = 0;
	                } else {
	                    var damage = arg[i].degats,
	                        loose = arg[i].pertes;
	                }
	                entry.push(new report(null, type, arg[i].metal, arg[i].cristal, arg[i].deut, damage, loose, arg[i].date));
                }
            }
            return entry;
        }

        var newData = new DATA(),
            oldData;
        if (GM_getValue("conteneur"+ serverNAME)) {
            oldData = GM_getValue("conteneur"+ serverNAME);
            newData.ids = transfertID(oldData.api_rc, newData.ids);
            newData.ids = transfertID(oldData.api_expe, newData.ids);

            newData.reports = transfertREPORT(oldData.combats, newData.reports, "combat");
            newData.reports = transfertREPORT(oldData.expedition, newData.reports, "expedition");
        }

        if (localStorage.getItem("MLGA"+ serverNAME)) {
        	newData.ids = transfertID(JSON.parse(localStorage.getItem("MLGA"+ serverNAME)).ids, newData.ids);
        	newData.reports = transfertREPORT(JSON.parse(localStorage.getItem("MLGA"+ serverNAME)).reports, newData.reports, "localStorage");
        	localStorage.removeItem("MLGA"+ serverNAME);
        }

        GM_setValue("MLGA"+ serverNAME, JSON.stringify(newData));
    }

    function timeout(ms) {
        return new Promise(resolve => setTimeout(resolve, ms));
    }

    function DATA() {
        this.ids = new Array();
        this.reports = new Array();
    }

    function report(id, type, metal, crystal, deut, damage, loose, date ) {
        this.id = id;
        this.loose = loose;
        this.metal = metal;
        this.type = type;
        this.crystal = crystal;
        this.damage = damage;
        this.date = date;
        this.deut = deut;
        this.loose = loose;
        this.metal = metal;
    }

    function addMenuButton() {
        var img = `<span class="menu_icon">
		       <div class="menuImage shipyard"></div>
			</span>`,
            aff_option = `
        <span class="menu_icon">` +
            img +
            `</span>
        <a class="menubutton" href="#" accesskey="" target="_self">
            <span class="textlabel">
                Make Looting
            </span>
        </a>`;

        var tableau = document.createElement("li");
        tableau.innerHTML = aff_option;
        tableau.id = 'AffichageRcMLGA';
        document.getElementById('menuTable').appendChild(tableau);
    }

    function searchMSG() {
        var waitForMessages = setInterval(async function() {
            if (!$(".ajax_load_shadow.clearfix").is(':visible')) {
                clearInterval(waitForMessages);
                await timeout(300);
                var msgs = $(".msg"),
                    dataSAVED = GM_getValue("MLGA"+ serverNAME) ? JSON.parse(GM_getValue("MLGA"+ serverNAME)) : new DATA();
                for (var indexMsgs = 0; indexMsgs < msgs.length; indexMsgs++) {
                    var msgsContent = $(msgs[indexMsgs]).children(".msg_content");
                    if (msgsContent.children().length > 0) {
                        if (msgsContent.children(".espionageDefText")[0]) {
                            //console.log("spy subit:  ", msgsContent.children(".espionageDefText")[0]);
                        } else if (msgsContent.children(".compacting")[0]) {
                            //console.log("spy inflige:  ", msgsContent.children(".compacting")[0]);
                        } else if (msgsContent.children(".combatLeftSide")[0]) {
                            //console.log("combat:  ", msgsContent.children(".combatLeftSide")[0]);
                            dataSAVED = send_combat($(msgs[indexMsgs])[0], dataSAVED);
                        } else if ((msgsContent[0].innerText.search(regexRessourcesFindExpe[0]) > -1) || (msgsContent[0].innerText.search(regexRessourcesFindExpe[1]) > -1) || (msgsContent[0].innerText.search(regexRessourcesFindExpe[2]) > -1)) {
                            //console.log("expe:  ", msgsContent[0]);
                            dataSAVED = send_expedition($(msgs[indexMsgs])[0], dataSAVED);
                        } else if (msgsContent.children(".planetIcon")[0]) {
                            //console.log("cdr:  ", msgsContent.children(".planetIcon")[0]);
                            dataSAVED = send_debrisfield($(msgs[indexMsgs])[0], dataSAVED);
                        }
                    }
                }
                //console.log("FINAL ->    ", dataSAVED);
                GM_setValue("MLGA"+ serverNAME, JSON.stringify(dataSAVED));
                $("#AffichageRcMLGA").find("span.textlabel").css("color", "rgb(0, 200, 0)");
                await timeout(1000);
                $("#AffichageRcMLGA").find("span.textlabel").css("color", "rgb(119, 150, 177)");
            }
        }, 10);
    }

    function send_combat(msg, arg) {

        function invertLoot(name, arg) {
            name != playerNAME ? arg = parseInt(arg)*-1 : arg = parseInt(arg);
            return arg;
        }

        msg = $(msg);
        var idMsg = parseInt(msg.attr("data-msg-id")),
            type = "combat",
            date = msg.find(".msg_date").attr("data-datezone").replace(" ", ""),
            arrayIDs = arg.ids,
            arrayREPORTs = arg.reports;

        if (arrayIDs.indexOf(idMsg) < 0) {
            msg = msg.children(".msg_content");
            var attacker = msg.children(".combatLeftSide"),
                attackerNAME = attacker.children(".msg_ctn").eq(0).text(),
                attackerNAME = /\(([^\)]+)\)/.test(attackerNAME) ? /\(([^\)]+)\)/.exec(attackerNAME)[1] : null,
                loose = attacker.children(".msg_ctn").eq(0).attr("data-title").replace(/[^0-9]/g, ''),
                looting = attacker.children(".msg_ctn").eq(1).attr("data-title").split(':');

            var defender = msg.children(".combatRightSide"),
                defenderNAME = defender.children(".msg_ctn").eq(0).text(),
                defenderNAME = /\(([^\)]+)\)/.test(defenderNAME) ? /\(([^\)]+)\)/.exec(defenderNAME)[1] : null,
                damage = defender.children(".msg_ctn").eq(0).attr("data-title").replace(/[^0-9]/g, '');

            if (attackerNAME != playerNAME) {
                let tmp = damage;
                damage = loose;
                loose = tmp;
            }

            var rslt = new report(idMsg, type, invertLoot(attackerNAME, looting[1].replace(/[^0-9]/g, '')), invertLoot(attackerNAME, looting[2].replace(/[^0-9]/g, '')), invertLoot(attackerNAME, looting[3].replace(/[^0-9]/g, '')), parseInt(damage), parseInt(loose), date);
            //console.log(rslt);
            arrayIDs.push(idMsg);
            arrayREPORTs.push(rslt);
            arg.ids = arrayIDs;
            arg.reports = arrayREPORTs;
        }
        return arg;
    }

    function send_expedition(msg, arg) {
        msg = $(msg);
        var idMsg = parseInt(msg.attr("data-msg-id")),
            type = "expedition",
            date = msg.find(".msg_date").attr("data-datezone").replace(" ", ""),
            arrayIDs = arg.ids,
            arrayREPORTs = arg.reports;

        if (arrayIDs.indexOf(idMsg) < 0) {
            msg = msg.children(".msg_content");
            var value = parseInt(msg[0].innerText.replace(/[^0-9]/g, '')),
                metal = msg[0].innerText.search(regexRessourcesFindExpe[0]) > -1 ? value : 0,
                crystal = msg[0].innerText.search(regexRessourcesFindExpe[1]) > -1 ? value : 0,
                deuterium = msg[0].innerText.search(regexRessourcesFindExpe[2]) > -1 ? value : 0;

            var rslt = new report(idMsg, type, metal, crystal, deuterium, 0, 0, date);
            arrayIDs.push(idMsg);
            arrayREPORTs.push(rslt);
            arg.ids = arrayIDs;
            arg.reports = arrayREPORTs;
        }
        return arg;
    }

    function send_debrisfield(msg, arg) {
        msg = $(msg);
        var idMsg = parseInt(msg.attr("data-msg-id")),
            type = "debrisfield",
            date = msg.find(".msg_date").attr("data-datezone").replace(" ", ""),
            arrayIDs = arg.ids,
            arrayREPORTs = arg.reports;

        if (arrayIDs.indexOf(idMsg) < 0) {
            msg = msg.children(".msg_content");
            var values = msg[0].innerText.match(/((\d)*(\.)*(\d))+/g),
                metal = parseInt(values[values.length-3].replace(/[^0-9]/g, '')),
                crystal = parseInt(values[values.length-2].replace(/[^0-9]/g, '')),
                deuterium = parseInt(values[values.length-1].replace(/[^0-9]/g, ''));


            var rslt = new report(idMsg, type, metal, crystal, deuterium, 0, 0, date);
            arrayIDs.push(idMsg);
            arg.ids = arrayIDs;
            (metal == 0) && (crystal == 0) && (deuterium == 0) ? null : arrayREPORTs.push(rslt);
            arg.reports = arrayREPORTs;
        }
        return arg;
    }

    function showMLGA() {
        function resetMLGA() {
            confirm("Attention, vous perdrez tous les rapports enregistrés dans Make Looting Great Again !!") ? GM_setValue("MLGA"+ serverNAME, JSON.stringify(new DATA())) : null;
            mlga_all_time();
        }

        function createHTML() {
            const style = "border-bottom-color:rgb(241, 241, 241);border-bottom-style:none;border-bottom-width:0px;border-image-outset:0px;border-image-repeat:stretch;border-image-slice:100%;border-image-source:none;border-image-width:1;border-left-color:rgb(241, 241, 241);border-left-style:none;border-left-width:0px;border-right-color:rgb(241, 241, 241);border-right-style:none;border-right-width:0px;border-top-color:rgb(241, 241, 241);border-top-style:none;border-top-width:0px;color:rgb(241, 241, 241);display:block;float:left;font-famil:Verdana, Arial, SunSans-Regular, sans-serif;font-size:12px;font-style:normal;font-weight:400;height:1202px;margin-bottom:0px;margin-left:0px;margin-right:0px;margin-top:0px;outline-color:rgb(241, 241, 241);outline-style:none;outline-width:0px;overflow-x:visible;overflow-y:visible;padding-bottom:0px;padding-left:0px;padding-right:0px;padding-top:0px;position:relative;text-align:left;width:670px;";
            var sp1 = document.createElement("div");
            sp1.id = "newSpan";				// lui donne un attribut id appelé 'newSpan'
            sp1.style = style;
            var sp1_content = document.createTextNode("new replacement span element.");		// crée un contenu pour le nouvel élément.
            sp1.appendChild(sp1_content);		// applique ce contenu au nouvel élément
            if ($("#middle")[0]) {
                var sp2 = $("#middle")[0];				// construit une référence au noeud existant devant être remplacé
            } else {
                var sp2 = $("#contentWrapper")[0];
            }
            //var sp2 = document.getElementById("inhalt");			// construit une référence au noeud existant devant être remplacé
            var parentDiv = sp2.parentNode;
            parentDiv.insertBefore(sp1, sp2);		// remplace le noeud existant sp2 avec le nouvel élément span sp1
            // puis on inverse sp1 et sp2
            var html,
                style_nbr_rc = `<span id="version">`+ scriptVERSION +`</span><div class="panel" id="resources-summary" style="visibility: visible; background-color:rgb(13, 16, 20);border-bottom-color:rgb(43, 56, 72);border-bottom-style:solid;border-bottom-width:0.989583px;border-image-outset:0px;border-image-repeat:stretch;border-image-slice:100%;border-image-source:none;border-image-width:1;border-left-color:rgb(43, 56, 72);border-left-style:solid;border-left-width:0.989583px;border-right-color:rgb(43, 56, 72);border-right-style:solid;border-right-width:0.989583px;border-top-color:rgb(43, 56, 72);border-top-style:solid;border-top-width:3.99306px;color:rgb(241, 241, 241);display:block;font-family:Verdana, Arial, SunSans-Regular, sans-serif;font-size:12px;font-style:normal;font-weight:400;height:40px;margin-bottom:20px;margin-left:6px;margin-right:6px;margin-top:10px;outline-color:rgb(241, 241, 41);outline-style:none;outline-width:0px;padding-bottom:6px;padding-left:6px;padding-right:6px;padding-top:6px;text-align:left;width:644.063px;"><h1 style="visibility: visible; font: 14.4px; text-align: center; font-weight: bold; font-size: 30px; color: orange;">Make Looting Great Again</h1></div>`,
                style_ressources_total = `<div class="panel" id="resources-summary" style="visibility: visible; background-color:rgb(13, 16, 20);border-bottom-color:rgb(43, 56, 72);border-bottom-style:solid;border-bottom-width:0.989583px;border-image-outset:0px;border-image-repeat:stretch;border-image-slice:100%;border-image-source:none;border-image-width:1;border-left-color:rgb(43, 56, 72);border-left-style:solid;border-left-width:0.989583px;border-right-color:rgb(43, 56, 72);border-right-style:solid;border-right-width:0.989583px;border-top-color:rgb(43, 56, 72);border-top-style:solid;border-top-width:3.99306px;color:rgb(241, 241, 241);display:block;font-family:Verdana, Arial, SunSans-Regular, sans-serif;font-size:12px;font-style:normal;font-weight:400;height:165px;margin-bottom:20px;margin-left:6px;margin-right:6px;margin-top:10px;outline-color:rgb(241, 241, 41);outline-style:none;outline-width:0px;padding-bottom:6px;padding-left:6px;padding-right:6px;padding-top:6px;text-align:left;width:644.063px;">
										<table class="ogi" style="width: 100%;">
											<thead>
											<tr>
												<th>&nbsp;</th>
												<th width="120" style="visibility: visible; padding: 4px;">
													<div class="resourceIcon metal" style="visibility: visible; float: right;"></div>
												</th>
												<th width="120" style="visibility: visible; padding: 4px;">
													<div class="resourceIcon crystal" style="visibility: visible; float: right;"></div>
												</th>
												<th width="120" style="visibility: visible; padding: 4px;">
													<div class="resourceIcon deuterium" style="visibility: visible; float: right;"></div>
												</th>
												<th width="1"></th>
											</tr>
										</thead>
										<tbody>
											<tr class="summary alt">
												<td>
													<span class="label bold-hard" style="visibility: visible; text-align: left; color: grey; font-weight: 800;">`+ all_pillage +`</span>
													<span class="mlga_totalrapportcombat" style="font-size: 10px; font-weight: 800; color: grey;"></span>
												</td>
												<td class="bold">
													<span id="mlga_metalcombat" style="visibility: visible; color: #c6556c; font: 12px; float: right;"></span>
												</td>
												<td class="bold">
													<span id="mlga_crystalcombat" style="visibility: visible; color: #00bfff; font: 12px; float: right;"></span>
												</td>
												<td class="bold">
													<span id="mlga_deuteriumcombat" style="visibility: visible; color: #6495e2; font: 12px; float: right;"></span>
												</td>
												<td class="bold"></td>
											</tr>
											<tr>
												<td class="label" style="visibility: visible; text-align: left;">&nbsp;</td>
												<td>&nbsp;</td>
												<td>&nbsp;</td>
												<td>&nbsp;</td>
											</tr>
											<tr class="summary alt">
												<td>
													<span class="label bold-hard" style="visibility: visible; text-align: left; color: grey; font-weight: 800;">`+ all_recyclage +`</span>
													<span class="mlga_totalrapportdebrisfield" style="font-size: 10px; font-weight: 800; color: grey;"></span>
												</td>
												<td class="bold">
													<span id="mlga_metaldebrisfield" style="visibility: visible; color: #c6556c; font: 12px; float: right;"></span>
												</td>
												<td class="bold">
													<span id="mlga_crystaldebrisfield" style="visibility: visible; color: #00bfff; font: 12px; float: right;"></span>
												</td>
												<td class="bold">
													<span id="mlga_deuteriumdebrisfield" style="visibility: visible; color: #6495e2; font: 12px; float: right;"></span>
												</td>
												<td class="bold"></td>
											</tr>
											<tr>
												<td class="label" style="visibility: visible; text-align: left;">&nbsp;</td>
												<td>&nbsp;</td>
												<td>&nbsp;</td>
												<td>&nbsp;</td>
											</tr>
											<tr class="summary alt">
												<td>
													<span class="label bold-hard" style="visibility: visible; text-align: left; color: grey; font-weight: 800;">`+ all_expedition +`</span>
													<span class="mlga_totalrapportexpedition" style="font-size: 10px; font-weight: 800; color: grey;"></span>
												</td>
												<td class="bold">
													<span id="mlga_metalexpedition" style="visibility: visible; color: #c6556c; font: 12px; float: right;"></span>
												</td>
												<td class="bold">
													<span id="mlga_crystalexpedition" style="visibility: visible; color: #00bfff; font: 12px; float: right;"></span>
												</td>
												<td class="bold">
													<span id="mlga_deuteriumexpedition" style="visibility: visible; color: #6495e2; font: 12px; float: right;"></span>
												</td>
												<td class="bold"></td>
											</tr>
											<tr>
												<td class="label" style="visibility: visible; text-align: left;">&nbsp;</td>
												<td>&nbsp;</td>
												<td>&nbsp;</td>
												<td>&nbsp;</td>
											</tr>
											<tr class="summary alt">
												<td class="label bold-hard" style="visibility: visible; text-align: left; color: grey; font-size: 15px; font-weight: 800;">`+ somme_total +`</td>
												<td class="bold">&nbsp;</td>
												<td class="bold">&nbsp;</td>
												<td class="bold">
													<span id="mlga_sommetotal" style="visibility: visible; color: green; font: 12px; font-size: 15px; float: right;"></span>
												</td>
												<td class="bold"></td>
											</tr>
											<tr>
												<td class="label" style="visibility: visible; text-align: left;">&nbsp;</td>
												<td>&nbsp;</td>
												<td>&nbsp;</td>
												<td>&nbsp;</td>
												<td class="bold">
												</td>
												<!--
													<td>
														<span id="somme total simpli" style="visibility: visible; text-align: right; color: orange; font-weight: 800;"></span>
													</td>
												-->
											</tr>
										</tbody></table></div>`,
                style_autre = `<div class="panel" id="resources-summary" style="visibility: visible; background-color:rgb(13, 16, 20);border-bottom-color:rgb(43, 56, 72);border-bottom-style:solid;border-bottom-width:0.989583px;border-image-outset:0px;border-image-repeat:stretch;border-image-slice:100%;border-image-source:none;border-image-width:1;border-left-color:rgb(43, 56, 72);border-left-style:solid;border-left-width:0.989583px;border-right-color:rgb(43, 56, 72);border-right-style:solid;border-right-width:0.989583px;border-top-color:rgb(43, 56, 72);border-top-style:solid;border-top-width:3.99306px;color:rgb(241, 241, 241);display:block;font-family:Verdana, Arial, SunSans-Regular, sans-serif;font-size:12px;font-style:normal;font-weight:400;height:116px;margin-bottom:20px;margin-left:6px;margin-right:6px;margin-top:10px;outline-color:rgb(241, 241, 41);outline-style:none;outline-width:0px;padding-bottom:6px;padding-left:6px;padding-right:6px;padding-top:6px;text-align:left;width:644.063px;">
								<table class="ogi" style="width: 100%;">
									<thead>
										<tr>
											<th>&nbsp;</th>
											<th width="120" style="visibility: visible; padding: 4px;">
												<div class="resourceIcoon metal" style="visibility: visible; float: right;"></div>
											</th>
											<th width="120" style="visibility: visible; padding: 4px;">
												<div class="resourceIcoon crystal" style="visibility: visible; float: right;"></div>
											</th>
											<th width="120" style="visibility: visible; padding: 4px;">
												<div class="resourceIcoon deuterium" style="visibility: visible; float: right;"></div>
											</th>
											<th width="1"></th>
										</tr>
									</thead>
									<tbody>
										<tr class="summary alt">
											<td class="label bold-hard" style="visibility: visible; text-align: left; color: grey; font-size: 15px; font-weight: 800;">`+ moyenne_par_rc +`</td>
											<td class="bold">&nbsp;</td>
											<td class="bold">
												<span id="mlga_average" style="visibility: visible; color: none; font: 12px; font-size: 15px; float: right;"></span>
											</td>
											<td class="bold">&nbsp;</td>
											<td class="bold"></td>
										</tr>
										<tr>
											<td class="label" style="visibility: visible; text-align: left;">&nbsp;</td>
											<td>&nbsp;</td>
											<td>&nbsp;</td>
											<td>&nbsp;</td>
										</tr>
										<tr>
											<td class="label bold-hard" style="visibility: visible; text-align: left; color: grey; font-size: 15px; font-weight: 800;">`+ degat_realise +`</td>
											<td class="bold">&nbsp;</td>
											<td class="bold">
												<span id="mlga_damagegiven" style="visibility: visible; color: green; font: 12px; font-size: 15px; float: right;"></span>
											</td>
											<td class="bold">&nbsp;</td>
											<td class="bold"></td>
										</tr>
										<tr>
											<td class="label" style="visibility: visible; text-align: left;">&nbsp;</td>
											<td>&nbsp;</td>
											<td>&nbsp;</td>
											<td>&nbsp;</td>
										</tr>
										<tr class="summary alt">
											<td class="label bold-hard" style="visibility: visible; text-align: left; color: grey; font-size: 15px; font-weight: 800;">`+ pertes_subit +`</td>
											<td class="bold">&nbsp;</td>
											<td class="bold">
												<span id="mlga_damagetaken" style="visibility: visible; color: red; font: 12px; font-size: 15px; float: right;"></span>
											</td>
											<td class="bold">&nbsp;</td>
											<td class="bold"></td>
										</tr>
										</tbody></table></div>`,
                style_conclusion = `<div class="panel" id="resources-summary" style="visibility: visible; background-color:rgb(13, 16, 20);border-bottom-color:rgb(43, 56, 72);border-bottom-style:solid;border-bottom-width:0.989583px;border-image-outset:0px;border-image-repeat:stretch;border-image-slice:100%;border-image-source:none;border-image-width:1;border-left-color:rgb(43, 56, 72);border-left-style:solid;border-left-width:0.989583px;border-right-color:rgb(43, 56, 72);border-right-style:solid;border-right-width:0.989583px;border-top-color:rgb(43, 56, 72);border-top-style:solid;border-top-width:3.99306px;color:rgb(241, 241, 241);display:block;font-family:Verdana, Arial, SunSans-Regular, sans-serif;font-size:12px;font-style:normal;font-weight:400;height:30px;margin-bottom:20px;margin-left:6px;margin-right:6px;margin-top:10px;outline-color:rgb(241, 241, 41);outline-style:none;outline-width:0px;padding-bottom:6px;padding-left:6px;padding-right:6px;padding-top:6px;text-align:left;width:644.063px;">
									<table class="ogi" style="width: 100%;">
										<thead>
											<tr>
												<th>
													<h1 style="visibility: visible; font: 14.4px; text-align: right; font-weight: bold; font-size: 20px; color: orange;">`+ benefices_totaux +`</h1>
												</th>
												<th width="120">&nbsp;</th>
												<th width="120">
													<h1 id="mlga_finalprofit" style="visibility: visible; font: 14.4px; text-align: right; font-weight: bold; font-size: 20px;"></h1>
												</th>
												<th width="120">&nbsp;</th>
												<th width="1"></th>
											</tr>
										</thead></table></div>`,
                style_choix = `<div style="text-align: center; margin-right: 10%;">
								<button style="width: 40px; height: 40px; border-radius: 50%;" id="mlga_choix_24h">
									24h
								</button>
								<button style="width: 40px; height: 40px; border-radius: 50%;" id="mlga_choix_7j">
									7j
								</button>
								<button style="width: 40px; height: 40px; border-radius: 50%;" id="mlga_choix_1m">
									1m
								</button></div>`,
                style_reset = `<span id="mlga_resetRC" class="btn_blue btn_trash ui-tabs-anchor" role="presentation" tabindex="-1" style="visibility: visible; margin: 10px; margin-right: 50%;">Reset</span>`;
            html = ``+ style_nbr_rc +""+ style_ressources_total +""+ style_autre +""+ style_conclusion +""+ style_choix +""+ style_reset +"";
            document.getElementById("newSpan").innerHTML = html;
        }

        function formatage_value(x){
            var result = 0,
                round = 0,
                y = x;
            y < 0 ? x = x *(-1) : null;
            for (var i = 0; x >= 1000 ; i++) {
                var z = (x/1000);				//	1928.302
                z = Math.floor(z);				//	1928
                z = z *1000;					//	1928000
                z = x-z;						//	302
                if (z < 1) {
                    z = "000";
                } else if (z < 10) {
                    z = "00"+ z;
                } else if (z < 100) {
                    z = "0"+ z;
                } else {}
                if (round > 0) {
                    result = z +"."+ result;
                } else {
                    result = z;
                    round++;
                }
                //console.log(z);
                x = (x-z) /1000;				//	1928
            }
            z = (x/1000);				//	1928.302
            z = Math.floor(z);				//	1928
            z = z *1000;					//	1928000
            z = x-z;
            if (round > 0) {
                result = z +"."+ result;
            } else {
                result = z;
                round++;
            }
            y < 0 ? result = "-"+ result : null;
            //console.log("resultat: "+ result);
            return result;
        }

        function check_time(arg, date) {
            function create_date(j, m, a) {
                let result = new Date(parseInt(a), parseInt(m)-1, parseInt(j));
                return result;
            }
            var today = $(".OGameClock").text().split(" ")[0],
                today2 = today;
            //"2023-04-20 16:21:38"
            date = date.split(" ")[0];
            if (arg == "day") {
                if ((date.split(".")[0] == today.split(".")[0]) && (date.split(".")[1] == today.split(".")[1]) && (date.split(".")[2] == today.split(".")[2]))
                    null;
                else
                    return false;
            }
            if (arg == "week") {
                today = create_date(today.split(".")[0], today.split(".")[1], today.split(".")[2]);
                today2 = create_date(today2.split(".")[0]-7, parseInt(today2.split(".")[1]), today2.split(".")[2]);
                date = create_date(date.split(".")[0], date.split(".")[1], date.split(".")[2]);
                if ((today >= date) && (today2 <= date))
                    null;
                else
                    return false;
            }
            if (arg == "month") {
                today = create_date(today.split(".")[0], today.split(".")[1], today.split(".")[2]);
                today2 = create_date(today2.split(".")[0], parseInt(today2.split(".")[1])-1, today2.split(".")[2]);
                date = create_date(date.split(".")[0], date.split(".")[1], date.split(".")[2]);
                if ((today >= date) && (today2 <= date))
                    null;
                else
                    return false;
            }
            return true;
        }

        function mlga_all_time(arg) {
            var data = JSON.parse(GM_getValue("MLGA"+ serverNAME)),
                mlgaCombat = new report(0, "mlgaCombat", 0, 0, 0, 0, 0, 0),
                mlgaDebrisfield = new report(0, "mlgaDebrisfield", 0, 0, 0, 0, 0, 0),
                mlgaExpedition = new report(0, "mlgaExpedition", 0, 0, 0, 0, 0, 0);
            data = data.reports;

            for (var i = data.length - 1; i >= 0; i--) {
                if (data[i].type == "combat" && check_time(arg, data[i].date)) {
                    mlgaCombat.id++;
                    mlgaCombat.metal += data[i].metal;
                    mlgaCombat.crystal += data[i].crystal;
                    mlgaCombat.deut += data[i].deut;
                    mlgaCombat.damage += data[i].damage;
                    mlgaCombat.loose += data[i].loose;
                    mlgaCombat.date += data[i].metal + data[i].crystal + data[i].deut;
                }
                if (data[i].type == "debrisfield" && check_time(arg, data[i].date)) {
                    mlgaDebrisfield.id++;
                    mlgaDebrisfield.metal += data[i].metal;
                    mlgaDebrisfield.crystal += data[i].crystal;
                    mlgaDebrisfield.deut += data[i].deut;
                    mlgaDebrisfield.date += data[i].metal + data[i].crystal + data[i].deut;
                }
                if (data[i].type == "expedition" && check_time(arg, data[i].date)) {
                    mlgaExpedition.id++;
                    mlgaExpedition.metal += data[i].metal;
                    mlgaExpedition.crystal += data[i].crystal;
                    mlgaExpedition.deut += data[i].deut;
                    mlgaExpedition.date += data[i].metal + data[i].crystal + data[i].deut;
                }
            }

            $(".mlga_totalrapportcombat").html("&nbsp;&nbsp;("+ formatage_value(mlgaCombat.id) +")");
            $("#mlga_metalcombat").text(formatage_value(mlgaCombat.metal));
            $("#mlga_crystalcombat").text(formatage_value(mlgaCombat.crystal));
            $("#mlga_deuteriumcombat").text(formatage_value(mlgaCombat.deut));

            $(".mlga_totalrapportdebrisfield").html("&nbsp;&nbsp;("+ formatage_value(mlgaDebrisfield.id) +")");
            $("#mlga_metaldebrisfield").text(formatage_value(mlgaDebrisfield.metal));
            $("#mlga_crystaldebrisfield").text(formatage_value(mlgaDebrisfield.crystal));
            $("#mlga_deuteriumdebrisfield").text(formatage_value(mlgaDebrisfield.deut));

            $(".mlga_totalrapportexpedition").html("&nbsp;&nbsp;("+ formatage_value(mlgaExpedition.id) +")");
            $("#mlga_metalexpedition").text(formatage_value(mlgaExpedition.metal));
            $("#mlga_crystalexpedition").text(formatage_value(mlgaExpedition.crystal));
            $("#mlga_deuteriumexpedition").text(formatage_value(mlgaExpedition.deut));

            $("#mlga_sommetotal").text(formatage_value(mlgaCombat.date + mlgaDebrisfield.date + mlgaExpedition.date));
            $("#mlga_average").text(formatage_value(Math.round((mlgaCombat.date + mlgaDebrisfield.date + mlgaExpedition.date - mlgaCombat.loose) / ((mlgaCombat.id + mlgaDebrisfield.id + mlgaExpedition.id) == 0 ? 1 : (mlgaCombat.id + mlgaDebrisfield.id + mlgaExpedition.id)))));
            $("#mlga_damagegiven").text(formatage_value(mlgaCombat.damage));
            $("#mlga_damagetaken").text("-" +formatage_value(mlgaCombat.loose));
            $("#mlga_finalprofit").text(formatage_value(mlgaCombat.date + mlgaDebrisfield.date + mlgaExpedition.date - mlgaCombat.loose));
        }


        if (document.getElementById("newSpan")) {
            var el = document.getElementById("newSpan");
            el.parentNode.removeChild(el);
        } else {
            createHTML();
            mlga_all_time();

            $("button").mouseenter(function() {$("#"+this.id).css("background-color", "#90A0A8");});
            $("button").mouseleave(function() {$("#"+this.id).css("background-color", "");});
            document.getElementById('mlga_choix_24h').addEventListener("click", function(event) {mlga_all_time("day");}, true);
            document.getElementById('mlga_choix_7j').addEventListener("click", function(event) {mlga_all_time("week");}, true);
            document.getElementById('mlga_choix_1m').addEventListener("click", function(event) {mlga_all_time("month");}, true);
            document.getElementById('mlga_resetRC').addEventListener("click", resetMLGA);
        }
    }

    const scriptVERSION = "1.5.0",
          serverLNG = $("meta[name='ogame-language']").attr("content"),
          serverNAME = $("meta[name='ogame-universe-name']").attr("content"),
          playerNAME = $("meta[name='ogame-player-name'").attr("content"),
          url = window.location.href,
          regexRessourcesFindExpe = new Array("L`attaquant obtient Métal", "L`attaquant obtient Cristal", "L`attaquant obtient Deutérium");

    const chargement = "Patientez",
          fini = "Terminé",
          recuperer = "Récupérer",
          reset_rc = "Validé",
          nbr_de_rc = "Nombre de RC",
          all_pillage = "Total Pillages",
          all_recyclage = "Total Recyclage",
          all_expedition = "Total Expedition",
          somme_total = "Σ Total",
          moyenne_par_rc = "Moyenne",
          moyenne_par_expe = "Moyenne par Expedition",
          degat_realise = "Dégâts",
          pertes_subit = "Pertes",
          benefices_totaux = "Bénéfices Totaux",
          mauvais_menu_messages = "Pas d'API ici";


    !GM_getValue("MLGA"+ serverNAME) ? importOldData() : null;
    localStorage.getItem("MLGA"+ serverNAME) ? importOldData() : null;

    addMenuButton();

    document.getElementById("AffichageRcMLGA").addEventListener("click", showMLGA);

    if (url.search("messages") >= 0) {
        var waitForMenuMessages = setInterval(function() {
            if ($("#subtabs-nfFleet21") && $("#subtabs-nfFleet22") && $("#subtabs-nfFleet24")) {
                clearInterval(waitForMenuMessages);
		        document.getElementById("subtabs-nfFleet21").addEventListener("click", searchMSG);
		        document.getElementById("subtabs-nfFleet22").addEventListener("click", searchMSG);
		        document.getElementById("subtabs-nfFleet24").addEventListener("click", searchMSG);
		        var waitForSubMenuMessages = setInterval(function() {
		            if ($("#ui-id-16") && $("#ui-id-18") && $("#ui-id-22")) {
		                clearInterval(waitForSubMenuMessages);
				        document.getElementById("ui-id-16").addEventListener("click", searchMSG);
				        document.getElementById("ui-id-18").addEventListener("click", searchMSG);
				        document.getElementById("ui-id-22").addEventListener("click", searchMSG);
		            }
		        }, 10);
            }
        }, 10);
    }
})();