RookieOne / OGame v7: Ganancias de Batallas y Expediciones

// ==UserScript==
// @name         OGame v7: Ganancias de Batallas y Expediciones
// @namespace    https://openuserjs.org/users/RookieOne
// @version      1.2.1
// @description  Seguimiento de Batallas y Expediciones
// @author       RookieOne
// @license      MIT
// @copyright    2020, RookieOne
// @match        https://*.ogame.gameforge.com/game/*
// @include      https://*.ogame.*
// @updateURL    https://openuserjs.org/meta/RookieOne/OGame_v7_Ganancias_de_Batallas_y_Expediciones.meta.js
// @downloadURL  https://openuserjs.org/src/scripts/RookieOne/OGame_v7_Ganancias_de_Batallas_y_Expediciones.user.js
// @grant        GM_xmlhttpRequest
// @icon         https://gf3.geo.gfsrv.net/cdnb8/e4122bc5585ef4c18c6e13bca5d65d.png
// @require      https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js
// @require      https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js
// @require      https://cdn.datatables.net/1.10.2/js/jquery.dataTables.min.js
// @require      https://canvasjs.com/assets/script/canvasjs.min.js
// ==/UserScript==

"use strict";
(function() {

    var SCRIPT_VERSION = "1.2.1";

    var shipdata={204:{"name":"LF","metal":3000,"crystal":1000,"deuterium":0},
                  205:{"name":"HF","metal":6000,"crystal":4000,"deuterium":0},
                  206:{"name":"Cru","metal":20000,"crystal":7000,"deuterium":2000},
                  207:{"name":"BS","metal":45000,"crystal":15000,"deuterium":0},
                  215:{"name":"BC","metal":30000,"crystal":40000,"deuterium":15000},
                  211:{"name":"BO","metal":50000,"crystal":25000,"deuterium":15000},
                  213:{"name":"DE","metal":60000,"crystal":50000,"deuterium":15000},
                  214:{"name":"DS","metal":5000000,"crystal":4000000,"deuterium":1000000},
                  202:{"name":"SC","metal":2000,"crystal":2000,"deuterium":0},
                  203:{"name":"LC","metal":6000,"crystal":6000,"deuterium":0},
                  208:{"name":"CS","metal":10000,"crystal":20000,"deuterium":10000},
                  209:{"name":"RC","metal":10000,"crystal":6000,"deuterium":2000},
                  210:{"name":"ES","metal":0,"crystal":1000,"deuterium":0},
                  212:{"name":"SA","metal":0,"crystal":2000,"deuterium":500},
                  217:{"name":"Cra","metal":2000,"crystal":2000,"deuterium":1000},
                  218:{"name":"RP","metal":85000,"crystal":55000,"deuterium":20000},
                  219:{"name":"PF","metal":8000,"crystal":15000,"deuterium":8000},
                  401:{"name":"RL","metal":2000,"crystal":0,"deuterium":0},
                  402:{"name":"LL","metal":1500,"crystal":500,"deuterium":0},
                  403:{"name":"HL","metal":6000,"crystal":2000,"deuterium":0},
                  404:{"name":"GC","metal":20000,"crystal":15000,"deuterium":2000},
                  405:{"name":"IC","metal":5000,"crystal":3000,"deuterium":0},
                  406:{"name":"PT","metal":50000,"crystal":50000,"deuterium":30000},
                  407:{"name":"SS","metal":10000,"crystal":10000,"deuterium":0},
                  408:{"name":"LS","metal":50000,"crystal":50000,"deuterium":0}};
    var depletion = {"Znaleźliśmy dowód wskazujący na obecność wielu innych flot ekspedycyjnych.":2, "Registro añadido de la comunicación oficial: Encontramos antiguos signos de naves espaciales. No somos los primeros.":1 ,"Registro añadido de la comunicación oficial: Parece como si esta parte del universo no hubiera sido explorada hasta ahora.":0, "Registro añadido de la comunicación oficial: Es una gran sensación ser el primero en un sector inexplorado.":0, "Registro añadido de la comunicación oficial: Parece como si ningún humano hubiera estado antes en esta parte de la galaxia.":0, "Registro añadido de la comunicación oficial: Casi tuvimos chocamos con otra flota de expedición. No pensé que también otros se acercaran por acá.":1, };
    var messages= {"El contacto con nuestra expedición fue interrumpido por un corto tiempo. Podemos descifrar su último mensaje. Están bajo ataque, el agresor no pudo ser identificado." : "Aliens" ,"Encontramos un planeta con restos de una civilización. Somos capaces de ver una estación espacial gigante orbitando. Algunos de tus técnicos y pilotos fueron a la superficie en busca de algunas naves que se todavia se puedan usar.":"Naves","Nuestra expedición encontró una estación espacial oxidada, la cual parece haber estado flotando sin control por el espacio exterior durante mucho tiempo. La estación por si misma era totalmente inútil, sin embargo, había algo de Materia Oscura almacenada en su reactor. Nuestros técnicos están intentando juntar tanto como pueden." : "MO" , "¡Una espontanea deformación en el hiperespacio permitió a tu expedición recolectar grandes cantidades de Materia Oscura!":"MO","Lo único que quedó de la expedición fue el siguiente mensaje de radio: Zzzrrt Mierda! Krrrzzzzt Eso zrrrtrzt parece krgzzzz como Krzzzzzzzztzzzz...":"Flota Perdida","Tu expedición tuvo un desagradable encuentro con algunos piratas espaciales." : "Piratas" , "Tuvimos dificultades para pronunciar correctamente el dialecto de una raza alienígena. Nuestro diplomático gritó \"¡Fuego!\" en lugar de \"¡Paz!\"." : "Aliens" , "Encontramos un enorme cementerio de naves espaciales. Algunos de los técnicos de la expedición consiguieron volver a hacer funcionar algunas naves y nos las llevamos." : "Naves" , "Tu expedición informa del descubrimiento de una nave alien gigante averiada y abandonada. No fueron capaces de aprender de sus tecnologías, pero fueron capaces de dividir la nave en sus componentes básicos y hacer algunos recursos útiles de ella." : "Recursos" , "¡Caimos en una emboscada organizada por algunos bucaneros estelares! La batalla no se pudo evitar." : "Piratas" , "Nuestra expedición hizo un primer contacto con una raza especial. Parecían como unas criaturas de energía, se llamaban a si mismos Legorianos, fluyeron a través de las naves de la expedición y decidieron ayudar a nuestra especie poco desarrollada. ¡Un recipiente que contenía Materia Oscura fue materializada en el puente de la nave!" : "MO" , "Nuestra expedición informa de un espectacular y extraño fenómeno. La acumulación de Materia Oscura en los almacenes de energía de los escudos de la nave. Nuestros técnicos intentan almacenar tanta Materia Oscura como pueden mientras dura el fenómeno." : "MO" , "Un cinturón de minerales alrededor de un planeta desconocido contiene incontables recursos. ¡Las naves de la expedición están de vuelta y sus almacenes están llenos!" : "Recursos" , "Tu expedición parece haber entrado en un territorio que pertenece a una raza alien desconocida pero realmente agresiva y belical." : "Aliens" , "El nuevo módulo de navegación está aún lleno de errores. El salto de la expedición fue en una dirección totalmente errónea pero el deuterio fue usado igualmente. Afortunadamente el salto de la flota los dejó cerca de la luna del planeta de inicio." : "Retraso" , "Tu expedición no hizo un primer contacto amigable con una especie desconocida." : "Aliens" , "¡Una especie desconocida ataca nuestra expedición!" : "Aliens" , "¡Algunas naves de apariencia exótica atacaron la expedición sin previo aviso!" : "Aliens" , "Nuestra expedición se encontró con un antiguo hangar automático. Algunas de las naves se encuentran todavía en la fase de producción y nuestros técnicos están tratando de reactivar los generadores de energía." : "Naves" , "El viento de una estrella gigante roja arruinó los saltos de la expedición, esta necesitara algo de tiempo para calcular el salto de retorno. No había nada aparte del vacío entre las estrellas en ese sector. La flota volverá más tarde de lo previsto." : "Retraso" , "La nave principal de la expedición colisionó con una nave extranjera cuando esta saltó sobre la flota sin ningún aviso. La nave extranjera explotó y los daños a la nave principal fueron sustanciales. Tan pronto como las reparaciones necesarias sean realizadas la flota empezará el viaje de vuelta ya que la expedición no puede continuar en estas condiciones." : "Retraso" , "Tu expedición aprendió acerca del extenso vacío del espacio. No hubo ni un pequeño asteroide, radiación o partícula que pudiera haber hecho esta expedición interesante." : "Nada" , "Nuestra flota ha encontrado un valioso artefacto." : "Item" , "Alguien instaló un viejo juego de estrategia en todos los ordenadores de la nave. La flota de la expedición estuvo ausente por un largo tiempo, pero no fue realmente productiva a causa de ello." : "Nada" , "En una pequeña luna con su propia atmósfera, tu expedición encontró una cantidad enorme de recursos sin explotar. La tripulación en el terreno está tratando de levantar y cargar el tesoro natural." : "Recursos" , "Un fallo en los motores de la nave insignia estuvo cerca de destruir la flota entera en expedición. Afortunadamente los técnicos,que eran más que competentes, evitaron lo peor. Las reparaciones llevaron algo de tiempo y la expedición se vio forzada a volver sin haber logrado nada." : "Nada" , "Probablemente la celebración del cumpleaños del capitán no debió hacerse en ese planeta desierto. Una fiebre terrible y desconocida causó que la gran mayoría de la tripulación de la expedición tuvieran que estar en la enfermería durante el resto de la expedición. Debido a la escasez de personal la expedición fracasó." : "Nada" , "La expedición siguió algunas señales fuera de lo común hasta un asteroide. En el núcleo del asteroide se encontró una pequeña cantidad de Materia Oscura. El asteroide fue tomado y los exploradores intentan extraer la Materia Oscura." : "MO" , "Además de algunos pintorescos, pequeños animales de compañía de un desconocido planeta, esta expedición no trae nada emocionante a su regreso del viaje." : "Nada" , "La flota en expedición no saltó de vuelta al vecindario. Nuestros académicos están aún intentando encontrar que pasó, pero parece que la flota se perdió para siempre.":"Flota Perdida" , "Necesitamos luchar con algunos piratas que eran, por suerte, solo unos pocos." : "Piratas" , "A causa de razones desconocidas el salto de la expedición fue totalmente erróneo. Estuvo a punto de aterrizar en el corazón de un planeta. Afortunadamente esta aterrizó en un sistema conocido, el salto de vuelta va a llevar más tiempo del esperado." : "Retraso" , "Tu expedición no informa de ninguna anomalía en el sector explorado. Pero la flota entro en algún viento solar mientras volvía. A causa de esto la vuelta de la flota se aceleró mucho. Tu expedición vuelve a casa un poco antes." : "Vuelta Rapida" , "Tu expedición casi entra en el campo gravitacional de una estrella de neutrones y necesito algún tiempo para librarse ella misma. A causa de esto mucho Deuterio fue consumido y la flota en expedición tuvo que volver sin ningún resultado." : "Nada" , "Una flota en proceso de huida ha dejado caer un objeto para distraer nuestra atención de su evasión." : "Item" , "A pesar de los resultados iniciales, escaneos del sector muy prometedores, volvimos, desafortunadamente, con las manos vacías." : "Nada" , "Tu expedición entró en un sector lleno de tormentas de partículas. Esto provocó que los almacenes de energía se sobrecargaran y la mayoría de los sistemas principales de las naves se averiaron. Tus mecánicos fueron capaces de evitar lo peor pero la flota va a volver con un gran retraso." : "Retraso" , "Tu expedición hizo magníficas fotos de una super nova. No se obtuvo nada de la expedición pero al menos hay muchas posibilidades de ganar el concurso \"Mejor Foto del Universo\" este año." : "Nada" , "Un inesperado acoplamiento de energía en los motores aceleró la vuelta de la expedición, vuelve a casa antes de lo esperado. Los primeros informes dicen que no tienen nada emocionante a tener en cuenta." : "Vuelta Rapida" , "Algunos bárbaros primitivos están atacándonos con naves espaciales que no deberían ser llamadas así. Si nos disparan en serio nos veremos forzados a devolver el fuego." : "Piratas" , "Encontramos los restos de una armada. Los técnicos fueron directamente a las naves casi intactas para intentar ponerlas en funcionamiento de nuevo." : "Naves" , "Algunos piratas realmente desesperados intentaron capturar nuestra expedición." : "Piratas" , "Un extraño virus informático atacó el sistema de navegación al poco de salir de nuestro sistema solar. Esto causó que la expedición volara en círculos. No hace falta decir que la expedición no fue realmente satisfactoria." : "Nada" , "¡El nuevo, y un poco atrevido, comandante viajó con éxito a través de un inestable agujero de gusano para acortar el vuelo de regreso! Sin embargo, la expedición en sí no trajo nada nuevo." : "Vuelta Rapida" , "La señal de emergencia que la expedición siguió resultó ser un montaje de algunos bucaneros estelares. La batalla no se pudo evitar." : "Piratas" , "Tu flota en expedición tuvo un corto contacto con una raza de aliens un poco vergonzosa. Estos anunciaron que van a enviar a un representante con bienes de comercio a tus mundos." : "Mercader" , "Capturamos algunos mensajes de radio de algunos piratas borrachos. Parece que vamos a estar bajo ataque pronto." : "Piratas" , "Tu expedición captura un grito de ayuda. Era una gran nave de carga que fue capturada por un potente campo gravitacional de un planetoide. Después de que la nave de carga fuese liberada con éxito, el capitán de celebración anunció que va a poner a su liberador en su libro negro como cliente exclusivo preferido." : "Nada" , "Un ser de pura energía se aseguró que todos los miembros de la expedición solo miraran el hipnotizante patrón de los monitores. Cuando la mayoría de ellos se despejaron de nuevo, la expedición debía ser abortada ya que quedaba poco Deuterio." : "Nada" , "Tu expedición encontró un antiguo, pero desierto convoy de carga. Algunos de los recursos podrían ser rescatados." : "Recursos" , "Nuestra expedición se encontró con una nave fantasma que transportaba una pequeña cantidad de Materia Oscura. No encontramos ningún indicio de que le pasó a la tripulación original de la nave pero nuestros técnicos fueron capaces de rescatar la Materia Oscura." : "MO" , "Nuestra expedición encontró un planeta que estuvo cerca de ser completamente destruido en continuas guerras. Hay naves diversas flotando alrededor de la órbita. Los técnicos intentan reparar algunas de ellas. Quizá con ello también conseguiremos información de lo que pasó aquí." : "Naves" , "Encontramos los restos de una nave alienígena. En sus estanterías había un pequeño contenedor con algo de Materia Oscura." : "MO" , "La expedición fue capaz de capturar y almacenar algo de Materia Oscura." : "MO" , "Una fusión del núcleo de la nave insignia produce una reacción en cadena que destruye de una forma bastante espectacular la flota entera en expedición.": "Flota Perdida", "Nuestra expedición logro un experimento único. Fueron capaces de reciclar Materia Oscura de la desaparición de una estrella." : "MO", "Tu expedición volvió a través de una vieja estrella fortaleza que está desierta desde hace años. En el hangar de la fortaleza encontraron algunas naves. Los técnicos intentan poner algunas a flote de nuevo." : "Naves" , "Nos encontramos un extraño alien en una estantería en una pequeña nave, nos dio una maleta con Materia Oscura a cambio de unos simples cálculos matemáticos." : "MO" , "¡Atravesamos los restos de una expedición previa! Nuestros técnicos intentarán conseguir que algunas de las naves funcionen de nuevo." : "Naves", "Encontramos una estación pirata desierta. Hay estacionadas algunas viejas naves en el hangar. Nuestros técnicos están mirando si algunas de ellas son aún útiles.": "Naves", "¡Nuestra expedición fue atacada por un pequeño grupo de naves sin identificar!":"Aliens", "Tu expedición descubrió un pequeño asteroide en el cual se pueden reciclar algunos recursos." : "Recursos", "En un planetoide abandonado encontramos algunas zonas de recursos fácilmente accesibles y recolectamos algunos satisfactoriamente." : "Recursos" , "Bueno, ahora sabemos que esas 5 anomalías rojas no solo tienen efectos caóticos en los sistemas de navegación de la nave sino que también generan alucinaciones masivas en la tripulación. La expedición no trajo nada de vuelta.": "Nada", "Tu flota en expedición siguió señales fuera de lo común algún tiempo. Al final ellos se percataron que esas señales estaban siendo emitidas desde una vieja sonda que fue lanzada tiempo atrás para dar la bienvenida a especies desconocidas. La sonda fue guardada y algunos museos de tu planeta base ya han manifestado su interés." : "Nada" , "Nuestra flota ha podido guardar un objeto en una nave sin tripulación.": "Item", "El líder de la navegación tuvo un mal día y esto causó que el salto de la expedición fuera mal calculado. No solo la flota aterrizó en algún lugar completamente diferente, sino que ahora el camino de vuelta necesita mucho más tiempo." : "Retraso"};
    var localisation = {"Nave pequeña de carga":"Small Cargo", "Nave grande de carga":"Large Cargo", "Cazador ligero":"Light fighter", "Cazador Pesado":"Heavy Fighter", "Crucero":"Cruiser", "Nave de Batalla":"Battleship", "Sonda de Espionaje":"Espionage Probe", "Acorazado":"Battlecruiser", "Bombardero":"Bomber", "Destructor":"Destroyer", "Metal":"Metal", "Cristal":"Crystal", "Deuterio":"Deuterium", "Explorador": "Pathfinder", "Segador": "Reaper"};
    var localprofitDB;
    var localdfDB;
    var localExpeditionDB;
    var offset;
    initiate();
    checkRisk();
    function initiate(){
        if(localStorage.getItem('NRT_options')==null){
            try{
            $.ajax({
                type:     'GET',
                url:      'https://' + window.location.host + '/api/serverData.xml',
                dataType: 'xml',
                global:   false,
                async:    false,
                error:    function(jqXHR, exception) {
                    console.log("Error getting HTML data - check errorlog");
                },
                success:  function(data) {
                    //Try parse the xml data
                    //console.log(data);
                    try{
                        var localoffset = data.childNodes.item(0).childNodes.item(4).textContent;
                        var options = {"offset":localoffset};
        localStorage.setItem('NRT_options', JSON.stringify(options));
                        offset=options.offset;
                    }
                    catch(ex){
                        console.log('Error on parsing inner xml: ' + ex);
                    }
                }
            }); }
        catch(ex){
                        console.log('Error getting xml: ' + ex);
                    };
    }
        else{
        var options = JSON.parse(localStorage.getItem('NRT_options'));
            offset = options.offset;
        }
        //Sort css
        var css = document.createElement("style");
        css.type = "text/css";
        css.innerHTML = "input#RaidHours[type=number]::-webkit-inner-spin-button, input[type=number]::-webkit-outer-spin-button {  -webkit-appearance: none;  margin: 0;}input#RaidHours{text-align:center;} #table1_length{display: none;}#table1_wrapper{min-height:351px;}#table1_paginate{background:black;}#table1_paginate a{cursor: pointer;color:#FFFFFF;margin:5px;}#table1_paginate a:hover{color:#DCDCDC;margin:5px;}#table1{min-height:351px; text-align:center;}#table1 thead{color:rgb(255, 215, 0);}";
        document.head.appendChild(css);
        //Initialize DB
        if(localStorage.getItem('Prueba1_profitDB')==null){
            var profitDB = {"crID":{"timestamp":"0","attackerid":"","defenderid":"","coordinates":"","loot":"","df":"","attackerloss":"","defenderloss":"","repaired":"","wreckfield":""}};
            localStorage.setItem('Prueba1_profitDB', JSON.stringify(profitDB));
        }
        if(localStorage.getItem('Prueba1_dfDB')==null){
            var dfDB = {"dfID":{"timestamp":"0","coordinates":"","metal":"","crystal":""}};
            localStorage.setItem('Prueba1_dfDB', JSON.stringify(dfDB));
        }
    if(localStorage.getItem('Prueba1_NET_profitDB')==null){
        var expeditionDB = {"expID":{"Timestamp":"0","Coordinates":"","Result":"","Metal":"0","Crystal":"0","Deuterium":"0","MO":"0","Light Fighter":"0","Heavy Fighter":"0","Cruiser":"0","Battleship":"0","Battlecruiser":"0","Bomber":"0","Destroyer":"0","Reaper":"0","Espionage Probe":"0","Small Cargo":"0","Large Cargo":"0","Pathfinder":"0","Item":"Null","Depletion":"0"}};
        localStorage.setItem('Prueba1_NET_profitDB', JSON.stringify(expeditionDB));
    }
        localExpeditionDB = JSON.parse(localStorage.getItem('Prueba1_NET_profitDB'));
        localprofitDB = JSON.parse(localStorage.getItem('Prueba1_profitDB'));
        localdfDB = JSON.parse(localStorage.getItem('Prueba1_dfDB'));
        cleanDB(744);
        //Initialise table and message button
        createProfitTable();
        createExportMenuItems();
        updateProfits();
        console.log(window.location.search);
        if(window.location.search.indexOf("?page=messages")!==-1){
                createButton();
        }


    }
    //Function used on button to check which tab is active and parse the messages on that page
    function getMsgs() {
        var logged = 0;
        if(document.getElementById("subtabs-nfFleet21").getAttribute("tabindex")==0){
            logged = 0;
            //console.log("logging CR");
            var crMessages = document.getElementById("ui-id-18");
            var crReports = "";
            crReports = crMessages.getElementsByTagName("li");
            for (var i = 0; i < crReports.length; ++i) {
                if(crReports[i].getAttribute('data-msg-id')!==null&&crReports[i].innerHTML.search("CrLogged")<0){
                    var time = null;
                    if(crReports[i].getElementsByClassName("msg_date fright")[0].hasAttribute("original")){time = crReports[i].getElementsByClassName("msg_date fright")[0].getAttribute("original").split(".");}
                    else{time = crReports[i].getElementsByClassName("msg_date fright")[0].innerHTML.split(".");}
                            var day = time[0];
                    var month = time[1]-1;
                    var year = time[2].split(" ")[0];
                    var hours = time[2].split(" ")[1].split(":")[0];
                    var minutes = time[2].split(" ")[1].split(":")[1];
                    var seconds = time[2].split(" ")[1].split(":")[2];
                    //create date that is in unix time
                    let localoffset = parseInt(offset.replace("+","").split(":")[0])*60+parseInt(offset.replace("+","").split(":")[1]);
                    time = new Date(year, month, day, hours, minutes, seconds,0).getTime()/1000-(new Date().getTimezoneOffset()+localoffset)*60;
                    if(localprofitDB.hasOwnProperty(crReports[i].innerHTML.substring(crReports[i].innerHTML.search("input value='")+13,crReports[i].innerHTML.search("' readonly")))||localprofitDB.hasOwnProperty(crReports[i].getAttribute('data-msg-id')+time+crReports[i].getElementsByClassName("msg_title blue_txt")[0].getElementsByTagName("a")[0].innerHTML.replace(/\[/g, '').replace(/\]/g, ''))){
                                            crReports[i].getElementsByClassName('msg_content')[0].innerHTML+="<!--CrLogged--><span style='width:100%;float:left;color:rgb(0, 176, 0)'>Mensaje ya registrado</span>";
                    }
                    else if(crReports[i].getElementsByClassName("msg_actions clearfix")[0].innerHTML.length<300){ crReports[i].getElementsByClassName('msg_content')[0].innerHTML+="<!--CrLogged--><span style='width:100%;float:left;color:rgb(0, 176, 0)'>Nada to log</span>";}
                    else{
                    parseCR(crReports[i].getAttribute('data-msg-id'));
                    crReports[i].getElementsByClassName('msg_content')[0].innerHTML+="<!--CrLogged--><span style='width:100%;float:left;color:rgb(0, 176, 0)'>Mensaje registrado</span>";
                    logged++;
                    }
                }
            }
        }
        else if(document.getElementById("subtabs-nfFleet24").getAttribute("tabindex")==0){
            logged = 0;
            //console.log("logging DF");
            var dfMessages = document.getElementById("ui-id-24");
            var dfReports = "";
            dfReports = dfMessages.getElementsByTagName("li");
            for (var j = 0; j < dfReports.length; ++j) {
                if((dfReports[j].className =="msg "||dfReports[j].className =="msg msg_new")&dfReports[j].innerHTML.search("DFLogged")<0){
                    if(dfReports[j].innerHTML.search("icon_apikey")>0){
                        parseDF(dfReports[j]);
                        dfReports[j].getElementsByClassName('msg_content')[0].innerHTML+="<!--DFLogged--><br/><span style='color:rgb(0, 176, 0)'>Mensaje registrado</span>";
                        logged++;
                    }
                }
            }
        }
        else if(document.getElementById("subtabs-nfFleet22").getAttribute("tabindex")==0){
           // console.log(localExpeditionDB);
            logged=reportExpeditions();
        }

        else{
            console.log("Message Tab not identified - nothing logged");
        }
        document.getElementById("MsgParseResults").innerHTML=logged+" Mensajes Registrados";
    }
    //parse DF message based on HTML element
    function parseDF(msg){
        var content = msg.getElementsByClassName('msg_content')[0].innerHTML.substring(msg.getElementsByClassName('msg_content')[0].innerHTML.search("]</a>"),msg.getElementsByClassName('msg_content')[0].innerHTML.length);
        var apiKey = msg.innerHTML.substring(msg.innerHTML.search("input value='")+13,msg.innerHTML.search("' readonly"));
        var numbers = content.match(/((\d)*(\.)*(\d))+/g);
        var crystal = parseInt(numbers[numbers.length-1].replace(/\./g,""));
        var metal = parseInt(numbers[numbers.length-2].replace(/\./g,""));
        var date;
         if(msg.getElementsByClassName("msg_date fright")[0].hasAttribute("original")){date = msg.getElementsByClassName("msg_date fright")[0].getAttribute("original").split(".");}
                    else{date =msg.getElementsByClassName('msg_date fright')[0].innerHTML.split(".");}
        var day = date[0];
        var month = date[1]-1;
        var year = date[2].split(" ")[0];
        var hours = date[2].split(" ")[1].split(":")[0];
        var minutes = date[2].split(" ")[1].split(":")[1];
        var seconds = date[2].split(" ")[1].split(":")[2];
        //create date that is in unix time
        date = new Date(year, month, day, hours, minutes, seconds,0).getTime()/1000;
        var coords = msg.getElementsByClassName('txt_link')[0].innerHTML.replace("[","").replace("]","");
        //Store data locally if metal or crystal are not both 0
        if((metal+crystal)>0){
            localdfDB[apiKey] = {"timestamp":date,"coordinates":coords,"metal":metal,"crystal":crystal};
            localStorage.setItem('Prueba1_dfDB', JSON.stringify(localdfDB));
        }
    }
    //Parse combat report based on message ID
    function parseCR(id){
        //Try get the html data from the detailed window
        try{
            $.ajax({
                type:     'GET',
                url:      'index.php?page=messages',
                data:     'messageId='+id+'&tabid=21&ajax=1',
                dataType: 'html',
                context:  document.body,
                global:   false,
                async:    true,
                error:    function(jqXHR, exception) {
                    console.log("Error getting HTML data - check errorlog");
                },
                success:  function(data) {
                    //Try parse the html data
                    try{
                        var div = document.createElement('div');
                        div.id = "workspace";
                        div.style.visibility="hidden";
                        document.body.appendChild(div);
                        if (div){
                            div.innerHTML = data;
                            var combatreport = div.getElementsByClassName('detail_msg')[0];
                            if (combatreport){
                                //If probe loss - we can't parse this
                                if(combatreport.getElementsByClassName("msg_actions clearfix")[0].innerHTML.length>300){
                                    //find fight details
                                    var json = JSON.parse(combatreport.innerHTML.substring((combatreport.innerHTML.search("var combatData")+35),(combatreport.innerHTML.search("var attackerJson")-12)));
                                    var coordinates = json.coordinates;
                                    var loot = json.loot;
                                    var df = json.debris;
                                    var repair = json.repairedDefense
                                    var combatId = json.combatId;
                                    var attackerid = "";
                                    var defenderid = "";
                                    var wreckfield = {};
                                    var attackerloss ={204:0,205:0,206:0,207:0,215:0,211:0,213:0,214:0,202:0,203:0,208:0,209:0,210:0,212:0,217:0,218:0,219:0,401:0,402:0,403:0,404:0,405:0,406:0,407:0,408:0};
                                    var defenderloss = {204:0,205:0,206:0,207:0,215:0,211:0,213:0,214:0,202:0,203:0,208:0,209:0,210:0,212:0,217:0,218:0,219:0,401:0,402:0,403:0,404:0,405:0,406:0,407:0,408:0};
                                    if(json.wreckfield){
                                        wreckfield = json.wreckfield.ships;
                                    }
                                    var timestamp = json.event_timestamp;
                                                                        if(localprofitDB.hasOwnProperty(combatId)){
                            deleteExpeditionDBElement(combatId);
                        };
                                    combatId = combatreport.getAttribute('data-msg-id')+timestamp+coordinates.galaxy+":"+coordinates.system+":"+coordinates.position;
                                    combatId.replace(/ /g, '');
                                    //Avoid looking for attackerID on expeditions - then set attacker and defender ID
                                    if(coordinates.position!=16){
                                        //For each attacker - add the ships lost to losses
                                        for (var akey in json.attackerJSON.combatRounds[json.attackerJSON.combatRounds.length-1].losses){
                                            if(typeof(json.attackerJSON.combatRounds[json.attackerJSON.combatRounds.length-1].losses[akey])!="undefined"){
                                                for(var shiploss in json.attackerJSON.combatRounds[json.attackerJSON.combatRounds.length-1].losses[akey]){
                                                    if(json.attackerJSON.combatRounds[json.attackerJSON.combatRounds.length-1].losses[akey][shiploss]!="undefined"){
                                                        attackerloss[shiploss]+=parseInt(json.attackerJSON.combatRounds[json.attackerJSON.combatRounds.length-1].losses[akey][shiploss]);
                                                    }
                                                }
                                            }
                                        }
                                        //For each attacker - add their ID to attackerID
                                        for (var attkey in json.attacker){
                                            attackerid += json.attacker[attkey].ownerID+",";
                                        }
                                        //For each defender - add the ships/defense lost to losses
                                        for (var dkey in json.defenderJSON.combatRounds[json.defenderJSON.combatRounds.length-1].losses) {
                                            if(typeof(json.defenderJSON.combatRounds[json.defenderJSON.combatRounds.length-1].losses[dkey])!="undefined"){
                                                for(var dshiploss in json.defenderJSON.combatRounds[json.defenderJSON.combatRounds.length-1].losses[dkey]){
                                                    if(json.defenderJSON.combatRounds[json.defenderJSON.combatRounds.length-1].losses[dkey][dshiploss]!="undefined"){
                                                        defenderloss[dshiploss]+=parseInt(json.defenderJSON.combatRounds[json.defenderJSON.combatRounds.length-1].losses[dkey][dshiploss]);
                                                    }
                                                }
                                            }
                                        }
                                        //For each defender - add their ID to defender list
                                        for (var defkey in json.defender){
                                            defenderid += json.defender[defkey].ownerID+",";
                                        }
                                        var CRapiKey = combatreport.getElementsByClassName("msg_actions clearfix")[0].innerHTML.substring(combatreport.getElementsByClassName("msg_actions clearfix")[0].innerHTML.search("<br/><input value='")+19,combatreport.getElementsByClassName("msg_actions clearfix")[0].innerHTML.search("' readonly"));
                                        combatId=CRapiKey;
                                    }
                                    //If expedition, set attackerID to expo and set defenderID
                                    else{
                                        //console.log(json.defenderJSON.combatRounds[json.defenderJSON.combatRounds.length-1].losses);
                                        attackerid = "expo";
                                        for (var defkeys in json.defender){
                                            defenderid += json.defender[defkeys].ownerID+",";
                                        }
                                                                                for (var dkey2 in json.defenderJSON.combatRounds[json.defenderJSON.combatRounds.length-1].losses) {
                                            if(typeof(json.defenderJSON.combatRounds[json.defenderJSON.combatRounds.length-1].losses[dkey2])!="undefined"){
                                                for(var dshiploss2 in json.defenderJSON.combatRounds[json.defenderJSON.combatRounds.length-1].losses[dkey2]){
                                                    if(json.defenderJSON.combatRounds[json.defenderJSON.combatRounds.length-1].losses[dkey2][dshiploss2]!="undefined"){
                                                        defenderloss[dshiploss2]+=parseInt(json.defenderJSON.combatRounds[json.defenderJSON.combatRounds.length-1].losses[dkey2][dshiploss2]);
                                                    }
                                                }
                                            }
                                        }
                                    }
                                    //If no losses - create empty arrays
                                    if(typeof(defenderloss)=="undefined"){defenderloss={};}
                                    if(typeof(attackerloss)=="undefined"){attackerloss={};}
                                    //Store data locally
                                    localprofitDB[combatId] = {"timestamp":timestamp,"attackerid":attackerid,"defenderid":defenderid,"coordinates":coordinates,"loot":loot,"df":df,"attackerloss":attackerloss,"defenderloss":defenderloss,"repaired":repair,"wreckfield":wreckfield};
                                    localStorage.setItem('Prueba1_profitDB', JSON.stringify(localprofitDB));
                                }
                            }
                            //clean up between each message parsed

                            div.parentElement.removeChild(div);
                        }
                        else{
                            console.log('div "workspace" not found');
                        }
                    }
                    catch(ex){
                        console.log('Error on parsing inner: ' + ex);
                    }
                }
            });
        }
        catch (ex){
            console.log('Error on parsing outer: ' + ex);
        }
    }
    function reportExpeditions(){
        if(document.getElementById("subtabs-nfFleet22").getAttribute("tabindex")==0){
            var x = document.getElementsByClassName("msg");
            var reports = 0;
            var noreports = 0;
            for (var i = 0; i < x.length; ++i) {
                if(x[i].getElementsByClassName("msg_title blue_txt")[0].innerHTML.indexOf("Expedition Result") !== -1||x[i].getElementsByClassName("msg_title blue_txt")[0].innerHTML.indexOf("Resultado de la Expedición") !== -1){
                    var time = null;
                    if(x[i].getElementsByClassName("msg_date fright")[0].hasAttribute("original")){time = x[i].getElementsByClassName("msg_date fright")[0].getAttribute("original");}
                    else{time = x[i].getElementsByClassName("msg_date fright")[0].innerHTML;}
                    var coordinates = x[i].getElementsByClassName("msg_title blue_txt")[0].getElementsByTagName("a")[0].innerHTML.replace('[', '').replace(']', '');
                    if(x[i].getElementsByClassName("msg_content")[0].innerHTML.indexOf("ExpoValue") !== -1){}
                    else{
                        var result = messages[x[i].getElementsByClassName("msg_content")[0].innerHTML.split("<br>")[0].trim()];
                        var depletionlevel = "Not found";
                        var id = time+coordinates;
                        id = id.replace(/ /g, '');
                        if(localExpeditionDB.hasOwnProperty(id)){
                            deleteExpeditionDBElement(id);
                        };
                        id=x[i].getAttribute('data-msg-id')+time+coordinates;
                        id = id.replace(/ /g, '');
                        if(depletion.hasOwnProperty(x[i].getElementsByClassName("msg_content")[0].innerHTML.split("<br>")[x[i].getElementsByClassName("msg_content")[0].innerHTML.split("<br>").length-1].trim())){
                        depletionlevel=depletion[x[i].getElementsByClassName("msg_content")[0].innerHTML.split("<br>")[x[i].getElementsByClassName("msg_content")[0].innerHTML.split("<br>").length-1].trim()];
                    }
                        else{
                            console.log("The following depletion level was not known:\n"+x[i].getElementsByClassName("msg_content")[0].innerHTML.split("<br>")[x[i].getElementsByClassName("msg_content")[0].innerHTML.split("<br>").length-1].trim());
                        }
                        switch(result) {
                            case "Nada":
                                x[i].getElementsByClassName("msg_content")[0].innerHTML +="<!--ExpoValue --><br><span style='color:#6f9fc8'>"+result+"</span>";
                                localExpeditionDB[id] = {"Timestamp":time,"Coordinates":coordinates,"Result":result,"Metal":"0","Crystal":"0","Deuterium":"0","MO":"0","Light Fighter":"0","Heavy Fighter":"0","Cruiser":"0","Battleship":"0","Battlecruiser":"0","Bomber":"0","Destroyer":"0","Reaper":"0","Espionage Probe":"0","Small Cargo":"0","Large Cargo":"0","Pathfinder":"0","Item":"Null","Depletion":depletionlevel};
                                localStorage.setItem('Prueba1_NET_profitDB', JSON.stringify(localExpeditionDB));
                                reports++;
                                break;
                            case "Naves":
                                x[i].getElementsByClassName("msg_content")[0].innerHTML +="<!--ExpoValue --><br><span style='color:rgb(0, 176, 0)'>"+result+"</span>";
                                localExpeditionDB[id] = {"Timestamp":time,"Coordinates":coordinates,"Result":result,"Metal":"0","Crystal":"0","Deuterium":"0","MO":"0","Light Fighter":"0","Heavy Fighter":"0","Cruiser":"0","Battleship":"0","Battlecruiser":"0","Bomber":"0","Destroyer":"0","Reaper":"0","Espionage Probe":"0","Small Cargo":"0","Large Cargo":"0","Pathfinder":"0","Item":"Null","Depletion":depletionlevel};
                                for (var split = 0; split < x[i].getElementsByClassName("msg_content")[0].innerHTML.split("<br>").length; ++split) {
                                                   if(localisation.hasOwnProperty(x[i].getElementsByClassName("msg_content")[0].innerHTML.split("<br>")[split].split(": ")[0].replace(/\:/g, ''))){
                                                      localExpeditionDB[id][localisation[x[i].getElementsByClassName("msg_content")[0].innerHTML.split("<br>")[split].split(": ")[0].replace(/\:/g, '')]]=parseInt(x[i].getElementsByClassName("msg_content")[0].innerHTML.split("<br>")[split].split(": ")[1]);
                                                  }
                                }
                                localStorage.setItem('Prueba1_NET_profitDB', JSON.stringify(localExpeditionDB));
                                reports++;
                                break;
                            case "Recursos":
                                x[i].getElementsByClassName("msg_content")[0].innerHTML +="<!--ExpoValue --><br><span style='color:rgb(0, 176, 0)'>"+result+"</span>";
                                for (split = 0; split < x[i].getElementsByClassName("msg_content")[0].innerHTML.split("<br>")[2].trim().split(" ").length; ++split) {
                                    if(Number.isInteger(parseInt(x[i].getElementsByClassName("msg_content")[0].innerHTML.split("<br>")[2].trim().split(" ")[split]))){
                                        var resourcevalue = x[i].getElementsByClassName("msg_content")[0].innerHTML.split("<br>")[2].trim().split(" ")[split];
                                    }
                                    if(localisation.hasOwnProperty(x[i].getElementsByClassName("msg_content")[0].innerHTML.split("<br>")[2].trim().split(" ")[split].replace(/\./g, ''))){
                                       var resource = localisation[x[i].getElementsByClassName("msg_content")[0].innerHTML.split("<br>")[2].trim().split(" ")[split].replace(/\./g, '')];

                                       }
                                    console.log(x[i].getElementsByClassName("msg_content")[0].innerHTML.split("<br>")[2].trim().split(" ")[split]);
                                }

                                //var resource = x[i].getElementsByClassName("msg_content")[0].innerHTML.split("<br>")[2].trim().split(" ")[0];
                                //var resourcevalue = x[i].getElementsByClassName("msg_content")[0].innerHTML.split("<br>")[2].trim().split(" ")[1];
                                localExpeditionDB[id] = {"Timestamp":time,"Coordinates":coordinates,"Result":result,"Metal":"0","Crystal":"0","Deuterium":"0","MO":"0","Light Fighter":"0","Heavy Fighter":"0","Cruiser":"0","Battleship":"0","Battlecruiser":"0","Bomber":"0","Destroyer":"0","Reaper":"0","Espionage Probe":"0","Small Cargo":"0","Large Cargo":"0","Pathfinder":"0","Item":"Null","Depletion":depletionlevel};
                                localExpeditionDB[id][resource] = resourcevalue.replace(/\./g, '');
                                localStorage.setItem('Prueba1_NET_profitDB', JSON.stringify(localExpeditionDB));
                                reports++;
                                break;
                            case "MO":
                                x[i].getElementsByClassName("msg_content")[0].innerHTML +="<!--ExpoValue --><br><span style='color:rgb(0, 176, 0)'>"+result+"</span>";
                                //var DM = x[i].getElementsByClassName("msg_content")[0].innerHTML.split("<br>")[2].trim().split(" ")[0]+" "+x[i].getElementsByClassName("msg_content")[0].innerHTML.split("<br>")[2].trim().split(" ")[1];
                                                                for (split = 0; split < x[i].getElementsByClassName("msg_content")[0].innerHTML.split("<br>")[2].trim().split(" ").length; ++split) {
                                    if(Number.isInteger(parseInt(x[i].getElementsByClassName("msg_content")[0].innerHTML.split("<br>")[2].trim().split(" ")[split]))){
                                        var DMvalue = x[i].getElementsByClassName("msg_content")[0].innerHTML.split("<br>")[2].trim().split(" ")[split];
                                    }
                                                                }
                                localExpeditionDB[id] = {"Timestamp":time,"Coordinates":coordinates,"Result":result,"Metal":"0","Crystal":"0","Deuterium":"0","MO":DMvalue.replace(/\./g, ''),"Light Fighter":"0","Heavy Fighter":"0","Cruiser":"0","Battleship":"0","Battlecruiser":"0","Bomber":"0","Destroyer":"0","Reaper":"0","Espionage Probe":"0","Small Cargo":"0","Large Cargo":"0","Pathfinder":"0","Deathstar":"0", "Colonyship":"0", "Recycler":"0", "Satelite":"0", "Crawler":"0", "Rocket Launcher":"0", "Light Laser":"0", "Heavy Laser":"0", "Gaus Cannon":"0", "Ion Cannon":"0", "Plasma Turret":"0", "Small Shield":"0", "Large Shield":"0","Item":"Null","Depletion":depletionlevel};
                                localStorage.setItem('Prueba1_NET_profitDB', JSON.stringify(localExpeditionDB));
                                reports++;
                                break;
                            case "Mercader":
                                x[i].getElementsByClassName("msg_content")[0].innerHTML +="<!--ExpoValue --><br><span style='color:rgb(0, 176, 0)'>"+result+"</span>";
                                localExpeditionDB[id] = {"Timestamp":time,"Coordinates":coordinates,"Result":result,"Metal":"0","Crystal":"0","Deuterium":"0","MO":"0","Light Fighter":"0","Heavy Fighter":"0","Cruiser":"0","Battleship":"0","Battlecruiser":"0","Bomber":"0","Destroyer":"0","Reaper":"0","Espionage Probe":"0","Small Cargo":"0","Large Cargo":"0","Pathfinder":"0","Deathstar":"0", "Colonyship":"0", "Recycler":"0", "Satelite":"0", "Crawler":"0", "Rocket Launcher":"0", "Light Laser":"0", "Heavy Laser":"0", "Gaus Cannon":"0", "Ion Cannon":"0", "Plasma Turret":"0", "Small Shield":"0", "Large Shield":"0","Item":"Null","Depletion":depletionlevel};
                                localStorage.setItem('Prueba1_NET_profitDB', JSON.stringify(localExpeditionDB));
                                reports++;
                                break;
                            case "Item":
                                x[i].getElementsByClassName("msg_content")[0].innerHTML +="<!--ExpoValue --><br><span style='color:rgb(0, 176, 0)'>"+result+"</span>";
                                var itemfind = x[i].getElementsByClassName("msg_content")[0].getElementsByTagName("a")[0].innerHTML;
                                localExpeditionDB[id] = {"Timestamp":time,"Coordinates":coordinates,"Result":result,"Metal":"0","Crystal":"0","Deuterium":"0","MO":"0","Light Fighter":"0","Heavy Fighter":"0","Cruiser":"0","Battleship":"0","Battlecruiser":"0","Bomber":"0","Destroyer":"0","Reaper":"0","Espionage Probe":"0","Small Cargo":"0","Large Cargo":"0","Pathfinder":"0","Deathstar":"0", "Colonyship":"0", "Recycler":"0", "Satelite":"0", "Crawler":"0", "Rocket Launcher":"0", "Light Laser":"0", "Heavy Laser":"0", "Gaus Cannon":"0", "Ion Cannon":"0", "Plasma Turret":"0", "Small Shield":"0", "Large Shield":"0","Item":itemfind,"Depletion":depletionlevel};
                                localStorage.setItem('Prueba1_NET_profitDB', JSON.stringify(localExpeditionDB));
                                reports++;
                                break;
                            case "Vuelta Rapida":
                                x[i].getElementsByClassName("msg_content")[0].innerHTML +="<!--ExpoValue --><br><span style='color:rgb(0, 176, 0)'>"+result+"</span>";
                                localExpeditionDB[id] = {"Timestamp":time,"Coordinates":coordinates,"Result":result,"Metal":"0","Crystal":"0","Deuterium":"0","MO":"0","Light Fighter":"0","Heavy Fighter":"0","Cruiser":"0","Battleship":"0","Battlecruiser":"0","Bomber":"0","Destroyer":"0","Reaper":"0","Espionage Probe":"0","Small Cargo":"0","Large Cargo":"0","Pathfinder":"0","Deathstar":"0", "Colonyship":"0", "Recycler":"0", "Satelite":"0", "Crawler":"0", "Rocket Launcher":"0", "Light Laser":"0", "Heavy Laser":"0", "Gaus Cannon":"0", "Ion Cannon":"0", "Plasma Turret":"0", "Small Shield":"0", "Large Shield":"0","Item":"Null","Depletion":depletionlevel};
                                localStorage.setItem('Prueba1_NET_profitDB', JSON.stringify(localExpeditionDB));
                                reports++;
                                break;
                            case "Retraso":
                                x[i].getElementsByClassName("msg_content")[0].innerHTML +="<!--ExpoValue --><br><span style='color:rgb(212, 54, 53)'>"+result+"</span>";
                                localExpeditionDB[id] = {"Timestamp":time,"Coordinates":coordinates,"Result":result,"Metal":"0","Crystal":"0","Deuterium":"0","MO":"0","Light Fighter":"0","Heavy Fighter":"0","Cruiser":"0","Battleship":"0","Battlecruiser":"0","Bomber":"0","Destroyer":"0","Reaper":"0","Espionage Probe":"0","Small Cargo":"0","Large Cargo":"0","Pathfinder":"0","Deathstar":"0", "Colonyship":"0", "Recycler":"0", "Satelite":"0", "Crawler":"0", "Rocket Launcher":"0", "Light Laser":"0", "Heavy Laser":"0", "Gaus Cannon":"0", "Ion Cannon":"0", "Plasma Turret":"0", "Small Shield":"0", "Large Shield":"0","Item":"Null","Depletion":depletionlevel};
                                localStorage.setItem('Prueba1_NET_profitDB', JSON.stringify(localExpeditionDB));
                                reports++;
                                break;
                            case "Flota Perdida":
                                x[i].getElementsByClassName("msg_content")[0].innerHTML +="<!--ExpoValue --><br><span style='color:rgb(212, 54, 53)'>"+result+"</span>";
                                localExpeditionDB[id] = {"Timestamp":time,"Coordinates":coordinates,"Result":result,"Metal":"0","Crystal":"0","Deuterium":"0","MO":"0","Light Fighter":"0","Heavy Fighter":"0","Cruiser":"0","Battleship":"0","Battlecruiser":"0","Bomber":"0","Destroyer":"0","Reaper":"0","Espionage Probe":"0","Small Cargo":"0","Large Cargo":"0","Pathfinder":"0","Deathstar":"0", "Colonyship":"0", "Recycler":"0", "Satelite":"0", "Crawler":"0", "Rocket Launcher":"0", "Light Laser":"0", "Heavy Laser":"0", "Gaus Cannon":"0", "Ion Cannon":"0", "Plasma Turret":"0", "Small Shield":"0", "Large Shield":"0","Item":"Null","Depletion":depletionlevel};
                                localStorage.setItem('Prueba1_NET_profitDB', JSON.stringify(localExpeditionDB));
                                reports++;
                                break;
                            case "Aliens":
                                x[i].getElementsByClassName("msg_content")[0].innerHTML +="<!--ExpoValue --><br><span style='color:#ffd700'>"+result+"</span>";
                                localExpeditionDB[id] = {"Timestamp":time,"Coordinates":coordinates,"Result":result,"Metal":"0","Crystal":"0","Deuterium":"0","MO":"0","Light Fighter":"0","Heavy Fighter":"0","Cruiser":"0","Battleship":"0","Battlecruiser":"0","Bomber":"0","Destroyer":"0","Reaper":"0","Espionage Probe":"0","Small Cargo":"0","Large Cargo":"0","Pathfinder":"0","Deathstar":"0", "Colonyship":"0", "Recycler":"0", "Satelite":"0", "Crawler":"0", "Rocket Launcher":"0", "Light Laser":"0", "Heavy Laser":"0", "Gaus Cannon":"0", "Ion Cannon":"0", "Plasma Turret":"0", "Small Shield":"0", "Large Shield":"0","Item":"Null","Depletion":depletionlevel};
                                localStorage.setItem('Prueba1_NET_profitDB', JSON.stringify(localExpeditionDB));
                                reports++;
                                break;
                            case "Piratas":
                                x[i].getElementsByClassName("msg_content")[0].innerHTML +="<!--ExpoValue --><br><span style='color:#ffd700'>"+result+"</span>";
                                localExpeditionDB[id] = {"Timestamp":time,"Coordinates":coordinates,"Result":result,"Metal":"0","Crystal":"0","Deuterium":"0","MO":"0","Light Fighter":"0","Heavy Fighter":"0","Cruiser":"0","Battleship":"0","Battlecruiser":"0","Bomber":"0","Destroyer":"0","Reaper":"0","Espionage Probe":"0","Small Cargo":"0","Large Cargo":"0","Pathfinder":"0","Deathstar":"0", "Colonyship":"0", "Recycler":"0", "Satelite":"0", "Crawler":"0", "Rocket Launcher":"0", "Light Laser":"0", "Heavy Laser":"0", "Gaus Cannon":"0", "Ion Cannon":"0", "Plasma Turret":"0", "Small Shield":"0", "Large Shield":"0","Item":"Null","Depletion":depletionlevel};
                                localStorage.setItem('Prueba1_NET_profitDB', JSON.stringify(localExpeditionDB));
                                reports++;
                                break;
                            default:
                                x[i].getElementsByClassName("msg_content")[0].innerHTML +="<!--ExpoValue --><br><span style='color:rgb(212, 54, 53)'> No se reconoce el mensaje (Copialo y mandaselo a RookieOne para que lo agregue)</span>";
                                console.log("The following result was not known:\n"+x[i].getElementsByClassName("msg_content")[0].innerHTML.split("<br>")[0].trim());
                                noreports++;
                        }
                        var depletionmessage = "";
                        switch(depletionlevel){
                            case 0:
                                depletionmessage+="<span style='color:rgb(0, 176, 0)'>"
                        break;
                                                            case 1:
                                                                depletionmessage+="<span style='color:#ffd700'>";

                        break;
                                                            case 2:
                                depletionmessage+="<span style='color:rgb(212, 54, 53)'>";
                        break;
                                  case "Not Found":
                                depletionmessage+="<span style='color:rgb(212, 54, 53)'>";
                        break;
                            default:
                        }
                        depletionmessage+="<br/>Nivel de Agotamiento: "+depletionlevel+"</span>";
                        x[i].getElementsByClassName("msg_content")[0].innerHTML +=depletionmessage;
                    }
                }
            }
            //document.getElementById('ERAdded').innerHTML=reports;
            //document.getElementById('ERTotal').innerHTML=reports+noreports;
            updateFiles();
        }
                    return reports;

    }
    //Create a button to gather reports in messages
    function createButton(){
        var listElement = document.createElement("li");
        listElement.style="margin:5px;list-style:none;";
        listElement.innerHTML = '<a class="btn_blue" >Registrar Mensajes<span></span></a><div style="position:relative;top:-20px;left:150px;"><span id="MsgParseResults" style="font-size:0.8em;color:#00DD00;">0 Mensajes Registrados</span></div>';
        listElement.id = "ExpeditionCheck";
        document.getElementById('buttonz').getElementsByClassName("content")[0].insertBefore(listElement,document.getElementById('buttonz').getElementsByClassName("content")[0].getElementsByTagName("div")[0]);
        document.getElementById('ExpeditionCheck').addEventListener("click", function (event)
{
                getMsgs();

            }, true);
        /*var raidintel = document.createElement('div');
        raidintel.addEventListener('click', function(){ getMsgs() ;}, false);
        var button = document.createElement('a');
        button.id = "AddCrRaids";
        button.innerHTML="<span class='textlabel'>Check messages</span>";
        button.classList.add("btn_blue");
        raidintel.appendChild(button);
        raidintel.innerHTML+="<br/><span id=MsgParseResults></span>";
        raidintel.style="text-align:center;";
        //var menu = document.getElementById('ExpeditionCheck');
        document.getElementById('buttonz').getElementsByClassName("content")[0].insertBefore(raidintel,document.getElementById('buttonz').getElementsByClassName("content")[0].getElementsByTagName("div")[0]);

        //menu.appendChild(raidintel);*/
    }
    //Create a table to display profits under planet list
    function createProfitTable(){
        var menuList = document.getElementById("toolbarcomponent");
        if (menuList == null){
     menuList = document.getElementById("leftMenu");
        }
        var table = document.createElement('div');
        var table2 = document.createElement('div');
        if(document.getElementById('banner_skyscraper')!=null){
        //    console.log(document.getElementById('right').getBoundingClientRect().top);
        document.getElementById('banner_skyscraper').style.top="auto";
            document.getElementById('banner_skyscraper').style.bottom="250px";
        }
        menuList.style.paddingBottom="30px";

        table2.style="display:block;float:center;z-index:99999;";
        //table2.innerHTML="<h1 id='header' style='font-size: 10px;color: #ff5700;font-weight: bold;background: black;border: 1px solid #383838;border-radius: 1px;padding: 1px;text-align: center;display: block'>version 1.0.5</h1>";
        table2.innerHTML="<h1 id='header' style='font-size: 10px;color: #ff5700;font-weight: bold;background: black;border: 1px solid #383838;border-radius: 1px;padding: 5px;text-align: center;display: block'><div id='prueba1'><span style='display:block;'>version <span  id='version'>0</span></div></h1>";
        //table2.innerHTML+="<div style='font-size:10px;color:#6f9fc8;display:block;background:black;' id='prueba1'><span style='display:block;'>version: <span  id='version'>0</span></div>";

        table.style="display:block;float:left;z-index:99999;";

        table.innerHTML="<h1 id='header' style='font-size: 14px;color: #ff5700;font-weight: bold;background: black;border: 1px solid #383838;border-radius: 4px;padding: 4px;text-align: center;display: block'>Ganancias B&E</h1>";

        //table.innerHTML+="<h2 style='font-size: 12px;color: #ff5700;font-weight: bold;background: black;padding: 1px; display: block'>----------------------------</h2>";
        //table.innerHTML+="<h2 style='font-size: 10px;color: #ff5700;font-weight: bold;background: black;padding: 1px; text-align: center;display: block'>Relativa</h2>";
        //table.innerHTML+="<h2 style='font-size: 12px;color: #555555;font-weight: bold;background: black;padding: 1px; display: block'>----------------------------</h2>";
        //table.innerHTML+="<h2 style='font-size: 12px;color: #555555;font-weight: bold;background: black;padding: 1px; display: block'>----------------------------</h2>";
        //table.innerHTML+="<h2 style='font-size: 12px;color: #555555;font-weight: bold;background: black;padding: 1px; display: block'><br></h2>";

        table.innerHTML+="<h2 style='font-size: 12px;color: #ffd700;font-weight: bold;background: black;padding: 1px; display: block'>Ultima(s\) <input type='number' style='-webkit-outer-spin-button {-webkit-appearance: none;margin: 0;}text-align:center;background:black;color:#ffd700;border: 1px solid #383838;border-radius: 4px;padding: 1px; width:30px;' id='RaidHours' min='1' value='1'></input> hora\(s\):</h2><div style='font-size:10px;color:#6f9fc8;display:block;background:black;' id='weekly'><span style='display:block;'>Metal: <span  id='HourlyMetal'>0</span></span><span style='display:block;'>Cristal: <span id='HourlyCrystal'>0</span><span style='display:block;'>Deuterio: <span id='HourlyDeut'>0</span></span><span style='font-size: 11px;font-weight: bold;background: black;border: 1px solid #5c2203;border-radius: 4px;padding: 1px;text-align: left;display: block'>Total: <span id='HourlyTotal'>0</span></span></div>";
        //table.innerHTML+="<h2 style='font-size: 12px;color: #555555;font-weight: bold;background: black;padding: 1px; display: block'>----------------------------</h2>";
        //table.innerHTML+="<h2 style='font-size: 12px;color: #555555;font-weight: bold;background: black;padding: 1px; display: block'><br></h2>";

        table.innerHTML+="<h2 style='font-size: 12px;color: #ffd700;font-weight: bold;background: black;padding: 1px; display: block'>Ultimas 24 horas:</h2><div style='font-size:10px;color:#6f9fc8;display:block;background:black;' id='daily'><span style='display:block;'>Metal: <span  id='DailyMetal'>0</span></span><span style='display:block;'>Cristal: <span style='text-align:right;' id='DailyCrystal'>0</span><span style='display:block;'>Deuterio: <span id='DailyDeut'>0</span></span><span style='font-size: 11px;font-weight: bold;background: black;border: 1px solid #5c2203;border-radius: 4px;padding: 1px;text-align: left;display: block'>Total: <span id='DailyTotal'>0</span></span></div>";
        //table.innerHTML+="<h2 style='font-size: 12px;color: #555555;font-weight: bold;background: black;padding: 1px; display: block'>----------------------------</h2>";
        //table.innerHTML+="<h2 style='font-size: 12px;color: #555555;font-weight: bold;background: black;padding: 1px; display: block'><br></h2>";

        table.innerHTML+="<h2 style='font-size: 12px;color: #ffd700;font-weight: bold;background: black;padding: 1px; display: block'>Ultimos 7 dias:</h2><div style='font-size:10px;color:#6f9fc8;display:block;background:black;' id='weekly'><span style='display:block;'>Metal: <span  id='WeeklyMetal'>0</span></span><span style='display:block;'>Cristal: <span style='text-align:right;' id='WeeklyCrystal'>0</span><span style='display:block;'>Deuterio: <span id='WeeklyDeut'>0</span></span><span style='font-size: 11px;font-weight: bold;background: black;border: 1px solid #5c2203;border-radius: 4px;padding: 1px;text-align: left;display: block'>Total: <span id='WeeklyTotal'>0</span></span></div>";
        //table.innerHTML+="<h2 style='font-size: 12px;color: #555555;font-weight: bold;background: black;padding: 1px; display: block'>----------------------------</h2>";
        table.innerHTML+="<h2 style='font-size: 12px;color: #555555;font-weight: bold;background: black;padding: 1px; display: block'><br></h2>";

        //table.innerHTML+="<h2 style='font-size: 12px;color: #555555;font-weight: bold;background: black;padding: 1px; display: block'>----------------------------</h2>";
        table.innerHTML+="<h2 style='font-size: 12px;color: #ff5700;font-weight: bold;background: black;padding: 1px; display: block'>Hoy:</h2><div style='font-size:10px;color:#6f9fc8;display:block;background:black;' id='today'><span style='display:block;'>Metal: <span  id='TodayMetal'>0</span></span><span style='display:block;'>Cristal: <span style='text-align:right;' id='TodayCrystal'>0</span><span style='display:block;'>Deuterio: <span id='TodayDeut'>0</span></span><span style='font-size: 11px;font-weight: bold;background: black;border: 1px solid #5c2203;border-radius: 4px;padding: 1px;text-align: left;display: block'>Total: <span id='TodayTotal'>0</span></span></div>";
        //table.innerHTML+="<h2 style='font-size: 12px;color: #555555;font-weight: bold;background: black;padding: 1px; display: block'>----------------------------</h2>";
        table.innerHTML+="<h2 style='font-size: 12px;color: #555555;font-weight: bold;background: black;padding: 1px; display: block'><br></h2>";

        table.innerHTML+="<h2 style='font-size: 12px;color: #ffd700;font-weight: bold;background: black;padding: 1px; text-align:left; display: block'>Promedio 7 dias:</h2><div style='font-size:10px;color:#6f9fc8;display:block;background:black;' id='yesterday'><span style='display:block;'>Metal: <span  id='YesterdayMetal'>0</span></span><span style='display:block;'>Cristal: <span style='text-align:right;' id='YesterdayCrystal'>0</span><span style='display:block;'>Deuterio: <span id='YesterdayDeut'>0</span></span><span style='font-size: 11px;font-weight: bold;background: black;border: 1px solid #5c2203;border-radius: 4px;padding: 1px;text-align: left;display: block'>Total: <span id='YesterdayTotal'>0</span></span></div>";
        //table.innerHTML+="<h2 style='font-size: 12px;color: #555555;font-weight: bold;background: black;padding: 1px; display: block'>----------------------------</h2>";
        //table.innerHTML+="<h2 style='font-size: 12px;color: #555555;font-weight: bold;background: black;padding: 1px; display: block'><br></h2>";

        table.innerHTML+="<h2 style='font-size: 12px;color: #ffd700;font-weight: bold;background: black;padding: 1px; text-align:left; display: block'>Diferencia:</h2><div style='font-size:10px;color:#6f9fc8;display:block;background:black;' id='versus'><span style='display:block;'>Metal: <span  id='VersusMetal'>0</span></span><span style='display:block;'>Cristal: <span style='text-align:right;' id='VersusCrystal'>0</span><span style='display:block;'>Deuterio: <span id='VersusDeut'>0</span></span><span style='font-size: 11px;font-weight: bold;background: black;border: 1px solid #5c2203;border-radius: 4px;padding: 1px;text-align: left;display: block'>Total: <span id='VersusTotal'>0</span></span></div>";
        //table.innerHTML+="<h2 style='font-size: 12px;color: #555555;font-weight: bold;background: black;padding: 1px; display: block'>----------------------------</h2>";
        table.innerHTML+="<h2 style='font-size: 12px;color: #555555;font-weight: bold;background: black;padding: 1px; display: block'><br></h2>";

        table.innerHTML+="<div style='font-size:10px;color:#6f9fc8;display:none;background:black;' text-align:center; id='bash'><h2 style='font-size: 12px;color: #ffd700;font-weight: bold;background: black;padding: 1px;display: block'>Bash Risk:</h2><span style='width:100%;display:block;' id='bashlist'></div>";

        var buttonWrapper = document.createElement('div');
        buttonWrapper.style.background="black";
        var button = document.createElement('input');
        button.id="toggleTable";
        button.type="button";
        button.value="[Bat./Rec.]";
        button.className="btn_blue";
        button.style="min-width: 65px;margin-top:10px;width:50%;height:20px;text-align:center;padding:0;";
        button.onclick=function() {toggleProfitOverviewTable()};
        buttonWrapper.appendChild(button);
        var buttonWrapper2 = document.createElement('div');
        var button2 = document.createElement('input');
        button2.id="toggleExpeditions";
        button2.type="button";
        button2.value="[Expe.]";
        button2.className="btn_blue";
        button2.style="min-width: 65px;margin-top:10px;width:50%;height:20px;text-align:center;padding:0;";
        button2.onclick=function() {toggleExpeditionOverviewTable()};
        buttonWrapper.appendChild(button2);
        table.appendChild(buttonWrapper);
        table.appendChild(table2);
        //console.log(document.getElementsByClassName('uv-idletimer-toggle uv-element')[0]!=null);
        /*if(document.getElementsByClassName('uv-idletimer-toggle uv-element')[0]!=null){
        document.getElementsByClassName('uv-idletimer-toggle uv-element')[0].getElementsByTagName("span")[0].innerHTML="Activity Timer";
        document.getElementsByClassName('uv-idletimer-toggle uv-element')[0].style="Margin:0;";
        document.getElementsByClassName('uv-idletimer-toggle uv-element')[0].getElementsByTagName("span")[0].style="margin-top:5px;";
        //menuList.insertBefore(table,document.getElementsByClassName('uv-idletimer-toggle uv-element')[0]);
        }*/
        menuList.appendChild(table);
        var profitOverviewTable = document.createElement('div');
        profitOverviewTable.style="width:800px; display:block;  position: absolute;  z-index: 999;top: 140px; left: 174px;visibility:hidden;min-height:351px;";
        profitOverviewTable.id="profitOverviewTable";

        menuList.appendChild(profitOverviewTable);
        var expeditionOverviewTable = document.createElement('div');
        expeditionOverviewTable.style="background-color:#000000; width:510px; display:block;  position: absolute;  z-index: 999;top: 140px; left: 174px;;visibility:hidden;min-height:450px;";
        expeditionOverviewTable.id="expeditionOverviewTable";
        menuList.appendChild(expeditionOverviewTable);
        document.getElementById('RaidHours').addEventListener("change",function(){updateHourly(parseInt(document.getElementById('RaidHours').value));});
        dragElement(table);
        dragElement(profitOverviewTable);
        dragElement(expeditionOverviewTable);
        //table.innerHTML+="<h2 style='font-size: 10px;color: #ff5700;font-weight: bold;background: black;border: 1px solid #383838;border-radius: 4px;padding: 1px;text-align: center;display: block'>versión 1.0.3</h2>";
    }

    //Creates profit list based on time specified (hours) returns a profit list with metal, crystal, deut, total
    function processLocalDB(time){
        if(typeof(time)=="number"){
            var localID = document.getElementsByName('ogame-player-id')[0].getAttribute('content');
            var currentTime = document.getElementsByName('ogame-timestamp')[0].getAttribute('content');
            var timeZone = document.getElementsByName('ogame-language')[0].getAttribute('content');
            //console.log(currentTime);
            //console.log((new Date().getTime()/1000));
            var mprofit =0;
            var cprofit =0;
            var dprofit =0;
            var tprofit =0;
            var mloss = 0;
            var closs = 0;
            var dloss = 0;
            if(localStorage.getItem('Prueba1_profitDB')!=null){
                var localprofitDB = JSON.parse(localStorage.getItem('Prueba1_profitDB'));
                for (var entryID in localprofitDB){
                    if(localprofitDB[entryID].timestamp>(currentTime- (60 * 60 * time))){
                        if(localprofitDB[entryID].attackerid.includes(localID)){
                            //console.log("You were the attacker");
                            mloss = 0;
                            closs = 0;
                            dloss = 0;
                            for(var alosses in localprofitDB[entryID].attackerloss){
                                mloss += localprofitDB[entryID].attackerloss[alosses]*shipdata[alosses].metal;
                                closs += localprofitDB[entryID].attackerloss[alosses]*shipdata[alosses].crystal;
                                dloss += localprofitDB[entryID].attackerloss[alosses]*shipdata[alosses].deuterium;
                            }
                            mprofit+=localprofitDB[entryID].loot.metal-mloss;
                            cprofit+=localprofitDB[entryID].loot.crystal-closs;
                            dprofit+=localprofitDB[entryID].loot.deuterium-dloss;
                        }
                        else if(localprofitDB[entryID].defenderid.includes(localID)){
                            //console.log("You were the defender");
                            mloss = 0;
                            closs = 0;
                            dloss = 0;
                            for(var dlosses in localprofitDB[entryID].defenderloss){
                                if(localprofitDB[entryID].repaired.hasOwnProperty(dlosses)){
                                    mloss += (localprofitDB[entryID].defenderloss[dlosses]-localprofitDB[entryID].repaired[dlosses])*shipdata[dlosses].metal;
                                    closs += (localprofitDB[entryID].defenderloss[dlosses]-localprofitDB[entryID].repaired[dlosses])*shipdata[dlosses].crystal;
                                    dloss += (localprofitDB[entryID].defenderloss[dlosses]-localprofitDB[entryID].repaired[dlosses])*shipdata[dlosses].deuterium;
                                }
                                else if(localprofitDB[entryID].wreckfield.hasOwnProperty(dlosses)){
                                    mloss += (localprofitDB[entryID].defenderloss[dlosses]-localprofitDB[entryID].wreckfield[dlosses])*shipdata[dlosses].metal;
                                    closs += (localprofitDB[entryID].defenderloss[dlosses]-localprofitDB[entryID].wreckfield[dlosses])*shipdata[dlosses].crystal;
                                    dloss += (localprofitDB[entryID].defenderloss[dlosses]-localprofitDB[entryID].wreckfield[dlosses])*shipdata[dlosses].deuterium;
                                }
                                else{
                                    mloss += localprofitDB[entryID].defenderloss[dlosses]*shipdata[dlosses].metal;
                                    closs += localprofitDB[entryID].defenderloss[dlosses]*shipdata[dlosses].crystal;
                                    dloss += localprofitDB[entryID].defenderloss[dlosses]*shipdata[dlosses].deuterium;
                                }
                            }
                            mprofit+=0-mloss-localprofitDB[entryID].loot.metal;
                            cprofit+=0-closs-localprofitDB[entryID].loot.crystal;
                            dprofit+=0-dloss-localprofitDB[entryID].loot.deuterium;
                        }
                        else{
                            //console.log("You were not involved");
                        }
                    }
                }
                if(localStorage.getItem('Prueba1_dfDB')!=null){
                    var localdfDB = JSON.parse(localStorage.getItem('Prueba1_dfDB'));
                    for (var dfentryID in localdfDB){
                        var timestring3;
                        if(document.getElementById("ago_clock_server")!== null){
                        timestring3 = document.getElementById("ago_clock_server").innerHTML.split(".");
                        timestring3[1] =document.getElementById("ago_clock_server").innerHTML.split(".")[0];
                        timestring3[0] =document.getElementById("ago_clock_server").innerHTML.split(".")[1];
                        }
                        else{
                        timestring3 = document.getElementsByClassName("OGameClock")[0].innerHTML.replace(/\//g, '').replace(/<span>/g, '').split(".");
                        timestring3[1] =document.getElementsByClassName("OGameClock")[0].innerHTML.replace(/\//g, '').replace(/<span>/g, '').split(".")[0];
                        timestring3[0] =document.getElementsByClassName("OGameClock")[0].innerHTML.replace(/\//g, '').replace(/<span>/g, '').split(".")[1];
                        }
                        //console.log(localdfDB[dfentryID].timestamp);
                        //console.log(new Date(timestring3.toString().replace(/,/g, '.')).getTime()-60 * 60 * time*1000);
                        if(localdfDB[dfentryID].timestamp*1000>(new Date(timestring3.toString().replace(/,/g, '.')).getTime()-60 * 60 * time*1000)){
                            //Add DF profits
                            mprofit+=localdfDB[dfentryID].metal;
                            cprofit+=localdfDB[dfentryID].crystal;
                        }
                    }
                }
                    if(localStorage.getItem('Prueba1_NET_profitDB')!=null){
                    var localExpDB = JSON.parse(localStorage.getItem('Prueba1_NET_profitDB'));
                    for (var ExpentryID in localExpDB){
                        var timestring = localExpDB[ExpentryID].Timestamp.split(".")
                        timestring[1] =localExpDB[ExpentryID].Timestamp.split(".")[0];
                        timestring[0] =localExpDB[ExpentryID].Timestamp.split(".")[1];
                        var timestring2;
                        if(document.getElementById("ago_clock_server")!== null){
                        timestring2 = document.getElementById("ago_clock_server").innerHTML.split(".");
                        timestring2[1] =document.getElementById("ago_clock_server").innerHTML.split(".")[0];
                        timestring2[0] =document.getElementById("ago_clock_server").innerHTML.split(".")[1];
                        }
                        else{
                        timestring2 = document.getElementsByClassName("OGameClock")[0].innerHTML.replace(/\//g, '').replace(/<span>/g, '').split(".");
                        timestring2[1] =document.getElementsByClassName("OGameClock")[0].innerHTML.replace(/\//g, '').replace(/<span>/g, '').split(".")[0];
                        timestring2[0] =document.getElementsByClassName("OGameClock")[0].innerHTML.replace(/\//g, '').replace(/<span>/g, '').split(".")[1];
                        }
                        if(new Date(timestring.toString().replace(/,/g, '.')).getTime()>(new Date(timestring2.toString().replace(/,/g, '.')).getTime()-60 * 60 * time*1000)){
                            //Add Exp profits
                            mprofit+=parseInt(localExpDB[ExpentryID].Metal);
                            cprofit+=parseInt(localExpDB[ExpentryID].Crystal);
                            dprofit+=parseInt(localExpDB[ExpentryID].Deuterium);
                            mprofit+=parseInt(localExpDB[ExpentryID]['Small Cargo'])*shipdata[202].metal;
                            cprofit+=parseInt(localExpDB[ExpentryID]['Small Cargo'])*shipdata[202].crystal;
                            mprofit+=parseInt(localExpDB[ExpentryID]['Large Cargo'])*shipdata[203].metal;
                            cprofit+=parseInt(localExpDB[ExpentryID]['Large Cargo'])*shipdata[203].crystal;
                            mprofit+=parseInt(localExpDB[ExpentryID]['Light Fighter'])*shipdata[204].metal;
                            cprofit+=parseInt(localExpDB[ExpentryID]['Light Fighter'])*shipdata[204].crystal;
                            mprofit+=parseInt(localExpDB[ExpentryID]['Heavy Fighter'])*shipdata[205].metal;
                            cprofit+=parseInt(localExpDB[ExpentryID]['Heavy Fighter'])*shipdata[205].crystal;
                            mprofit+=parseInt(localExpDB[ExpentryID]['Cruiser'])*shipdata[206].metal;
                            cprofit+=parseInt(localExpDB[ExpentryID]['Cruiser'])*shipdata[206].crystal;
                            dprofit+=parseInt(localExpDB[ExpentryID]['Cruiser'])*shipdata[206].deuterium;
                            mprofit+=parseInt(localExpDB[ExpentryID]['Battleship'])*shipdata[207].metal;
                            cprofit+=parseInt(localExpDB[ExpentryID]['Battleship'])*shipdata[207].crystal;
                            cprofit+=parseInt(localExpDB[ExpentryID]['Espionage Probe'])*shipdata[210].crystal;
                            mprofit+=parseInt(localExpDB[ExpentryID]['Bomber'])*shipdata[211].metal;
                            cprofit+=parseInt(localExpDB[ExpentryID]['Bomber'])*shipdata[211].crystal;
                            dprofit+=parseInt(localExpDB[ExpentryID]['Bomber'])*shipdata[211].deuterium;
                            mprofit+=parseInt(localExpDB[ExpentryID]['Destroyer'])*shipdata[213].metal;
                            cprofit+=parseInt(localExpDB[ExpentryID]['Destroyer'])*shipdata[213].crystal;
                            dprofit+=parseInt(localExpDB[ExpentryID]['Destroyer'])*shipdata[213].deuterium;
                            mprofit+=parseInt(localExpDB[ExpentryID]['Battlecruiser'])*shipdata[215].metal;
                            cprofit+=parseInt(localExpDB[ExpentryID]['Battlecruiser'])*shipdata[215].crystal;
                            dprofit+=parseInt(localExpDB[ExpentryID]['Battlecruiser'])*shipdata[215].deuterium;
                            mprofit+=parseInt(localExpDB[ExpentryID]['Reaper'])*shipdata[218].metal;
                            cprofit+=parseInt(localExpDB[ExpentryID]['Reaper'])*shipdata[218].crystal;
                            dprofit+=parseInt(localExpDB[ExpentryID]['Reaper'])*shipdata[218].deuterium;
                            mprofit+=parseInt(localExpDB[ExpentryID]['Pathfinder'])*shipdata[219].metal;
                            cprofit+=parseInt(localExpDB[ExpentryID]['Pathfinder'])*shipdata[219].crystal;
                            dprofit+=parseInt(localExpDB[ExpentryID]['Pathfinder'])*shipdata[219].deuterium;
                        }
                    }

                    tprofit = mprofit+cprofit+dprofit;
                    return {"total":tprofit,"metal":mprofit,"crystal":cprofit,"deut":dprofit};
                }
                else{
                    return {"total":"nan","metal":"nan","crystal":"nan","deut":"nan"};
                }
            }
            else{
                return {"total":"nan","metal":"nan","crystal":"nan","deut":"nan"};
            }
        }
    }

    function processLocalDB_Hoy(){
            var localID = document.getElementsByName('ogame-player-id')[0].getAttribute('content');
            var currentTime = document.getElementsByName('ogame-timestamp')[0].getAttribute('content');
            var timeZone = document.getElementsByName('ogame-language')[0].getAttribute('content');
            var now = new Date();
            var startOfDay = new Date(now.getFullYear(), now.getMonth(), now.getDate());
            var timestamp_Hoy_Inicio = startOfDay / 1000;
            var timestamp_Hoy_Fin = timestamp_Hoy_Inicio + 86400;
            var mprofit =0;
            var cprofit =0;
            var dprofit =0;
            var tprofit =0;
            var mloss = 0;
            var closs = 0;
            var dloss = 0;

            //var now = new Date();
            //var startOfDay = new Date(now.getFullYear(), now.getMonth(), now.getDate());
            //var timestamp = startOfDay / 1000;

        if(localStorage.getItem('Prueba1_profitDB')!=null){
                var localprofitDB = JSON.parse(localStorage.getItem('Prueba1_profitDB'));
                for (var entryID in localprofitDB){
                    if((localprofitDB[entryID].timestamp>timestamp_Hoy_Inicio) && (localprofitDB[entryID].timestamp<timestamp_Hoy_Fin)){
                        if(localprofitDB[entryID].attackerid.includes(localID)){
                            //console.log("You were the attacker");
                            mloss = 0;
                            closs = 0;
                            dloss = 0;
                            for(var alosses in localprofitDB[entryID].attackerloss){
                                mloss += localprofitDB[entryID].attackerloss[alosses]*shipdata[alosses].metal;
                                closs += localprofitDB[entryID].attackerloss[alosses]*shipdata[alosses].crystal;
                                dloss += localprofitDB[entryID].attackerloss[alosses]*shipdata[alosses].deuterium;
                            }
                            mprofit+=localprofitDB[entryID].loot.metal-mloss;
                            cprofit+=localprofitDB[entryID].loot.crystal-closs;
                            dprofit+=localprofitDB[entryID].loot.deuterium-dloss;
                        }
                        else if(localprofitDB[entryID].defenderid.includes(localID)){
                            //console.log("You were the defender");
                            mloss = 0;
                            closs = 0;
                            dloss = 0;
                            for(var dlosses in localprofitDB[entryID].defenderloss){
                                if(localprofitDB[entryID].repaired.hasOwnProperty(dlosses)){
                                    mloss += (localprofitDB[entryID].defenderloss[dlosses]-localprofitDB[entryID].repaired[dlosses])*shipdata[dlosses].metal;
                                    closs += (localprofitDB[entryID].defenderloss[dlosses]-localprofitDB[entryID].repaired[dlosses])*shipdata[dlosses].crystal;
                                    dloss += (localprofitDB[entryID].defenderloss[dlosses]-localprofitDB[entryID].repaired[dlosses])*shipdata[dlosses].deuterium;
                                }
                                else if(localprofitDB[entryID].wreckfield.hasOwnProperty(dlosses)){
                                    mloss += (localprofitDB[entryID].defenderloss[dlosses]-localprofitDB[entryID].wreckfield[dlosses])*shipdata[dlosses].metal;
                                    closs += (localprofitDB[entryID].defenderloss[dlosses]-localprofitDB[entryID].wreckfield[dlosses])*shipdata[dlosses].crystal;
                                    dloss += (localprofitDB[entryID].defenderloss[dlosses]-localprofitDB[entryID].wreckfield[dlosses])*shipdata[dlosses].deuterium;
                                }
                                else{
                                    mloss += localprofitDB[entryID].defenderloss[dlosses]*shipdata[dlosses].metal;
                                    closs += localprofitDB[entryID].defenderloss[dlosses]*shipdata[dlosses].crystal;
                                    dloss += localprofitDB[entryID].defenderloss[dlosses]*shipdata[dlosses].deuterium;
                                }
                            }
                            mprofit+=0-mloss-localprofitDB[entryID].loot.metal;
                            cprofit+=0-closs-localprofitDB[entryID].loot.crystal;
                            dprofit+=0-dloss-localprofitDB[entryID].loot.deuterium;
                        }
                        else{
                            //console.log("You were not involved");
                        }
                    }
                }
                if(localStorage.getItem('Prueba1_dfDB')!=null){
                    var localdfDB = JSON.parse(localStorage.getItem('Prueba1_dfDB'));
                    for (var dfentryID in localdfDB){
                        if((localdfDB[dfentryID].timestamp>timestamp_Hoy_Inicio) && (localdfDB[dfentryID].timestamp<timestamp_Hoy_Fin)){
                            //Add DF profits
                            mprofit+=localdfDB[dfentryID].metal;
                            cprofit+=localdfDB[dfentryID].crystal;
                        }
                    }
                }
                    if(localStorage.getItem('Prueba1_NET_profitDB')!=null){
                    var localExpDB = JSON.parse(localStorage.getItem('Prueba1_NET_profitDB'));
                    for (var ExpentryID in localExpDB){
                        var timestring = localExpDB[ExpentryID].Timestamp.split(".")
                        timestring[1] =localExpDB[ExpentryID].Timestamp.split(".")[0];
                        timestring[0] =localExpDB[ExpentryID].Timestamp.split(".")[1];
                        var timestring2;
                        if(document.getElementById("ago_clock_server")!== null){
                        timestring2 = document.getElementById("ago_clock_server").innerHTML.split(".");
                        timestring2[1] =document.getElementById("ago_clock_server").innerHTML.split(".")[0];
                        timestring2[0] =document.getElementById("ago_clock_server").innerHTML.split(".")[1];
                        }
                        else{
                        timestring2 = document.getElementsByClassName("OGameClock")[0].innerHTML.replace(/\//g, '').replace(/<span>/g, '').split(".");
                        timestring2[1] =document.getElementsByClassName("OGameClock")[0].innerHTML.replace(/\//g, '').replace(/<span>/g, '').split(".")[0];
                        timestring2[0] =document.getElementsByClassName("OGameClock")[0].innerHTML.replace(/\//g, '').replace(/<span>/g, '').split(".")[1];
                        }
                        //if((new Date(timestring.toString().replace(/,/g, '.')).getTime()>(new Date(timestring2.toString().replace(/,/g, '.')).getTime()-60 * 60 * time*1000)) && 1 == 0){
                        if(((new Date(timestring.toString().replace(/,/g, '.')).getTime()/1000)>timestamp_Hoy_Inicio) && ((new Date(timestring.toString().replace(/,/g, '.')).getTime()/1000)<timestamp_Hoy_Fin)){
                            //Add Exp profits
                            mprofit+=parseInt(localExpDB[ExpentryID].Metal);
                            cprofit+=parseInt(localExpDB[ExpentryID].Crystal);
                            dprofit+=parseInt(localExpDB[ExpentryID].Deuterium);
                            mprofit+=parseInt(localExpDB[ExpentryID]['Small Cargo'])*shipdata[202].metal;
                            cprofit+=parseInt(localExpDB[ExpentryID]['Small Cargo'])*shipdata[202].crystal;
                            mprofit+=parseInt(localExpDB[ExpentryID]['Large Cargo'])*shipdata[203].metal;
                            cprofit+=parseInt(localExpDB[ExpentryID]['Large Cargo'])*shipdata[203].crystal;
                            mprofit+=parseInt(localExpDB[ExpentryID]['Light Fighter'])*shipdata[204].metal;
                            cprofit+=parseInt(localExpDB[ExpentryID]['Light Fighter'])*shipdata[204].crystal;
                            mprofit+=parseInt(localExpDB[ExpentryID]['Heavy Fighter'])*shipdata[205].metal;
                            cprofit+=parseInt(localExpDB[ExpentryID]['Heavy Fighter'])*shipdata[205].crystal;
                            mprofit+=parseInt(localExpDB[ExpentryID]['Cruiser'])*shipdata[206].metal;
                            cprofit+=parseInt(localExpDB[ExpentryID]['Cruiser'])*shipdata[206].crystal;
                            dprofit+=parseInt(localExpDB[ExpentryID]['Cruiser'])*shipdata[206].deuterium;
                            mprofit+=parseInt(localExpDB[ExpentryID]['Battleship'])*shipdata[207].metal;
                            cprofit+=parseInt(localExpDB[ExpentryID]['Battleship'])*shipdata[207].crystal;
                            cprofit+=parseInt(localExpDB[ExpentryID]['Espionage Probe'])*shipdata[210].crystal;
                            mprofit+=parseInt(localExpDB[ExpentryID]['Bomber'])*shipdata[211].metal;
                            cprofit+=parseInt(localExpDB[ExpentryID]['Bomber'])*shipdata[211].crystal;
                            dprofit+=parseInt(localExpDB[ExpentryID]['Bomber'])*shipdata[211].deuterium;
                            mprofit+=parseInt(localExpDB[ExpentryID]['Destroyer'])*shipdata[213].metal;
                            cprofit+=parseInt(localExpDB[ExpentryID]['Destroyer'])*shipdata[213].crystal;
                            dprofit+=parseInt(localExpDB[ExpentryID]['Destroyer'])*shipdata[213].deuterium;
                            mprofit+=parseInt(localExpDB[ExpentryID]['Battlecruiser'])*shipdata[215].metal;
                            cprofit+=parseInt(localExpDB[ExpentryID]['Battlecruiser'])*shipdata[215].crystal;
                            dprofit+=parseInt(localExpDB[ExpentryID]['Battlecruiser'])*shipdata[215].deuterium;
                            mprofit+=parseInt(localExpDB[ExpentryID]['Reaper'])*shipdata[218].metal;
                            cprofit+=parseInt(localExpDB[ExpentryID]['Reaper'])*shipdata[218].crystal;
                            dprofit+=parseInt(localExpDB[ExpentryID]['Reaper'])*shipdata[218].deuterium;
                            mprofit+=parseInt(localExpDB[ExpentryID]['Pathfinder'])*shipdata[219].metal;
                            cprofit+=parseInt(localExpDB[ExpentryID]['Pathfinder'])*shipdata[219].crystal;
                            dprofit+=parseInt(localExpDB[ExpentryID]['Pathfinder'])*shipdata[219].deuterium;
                        }
                    }

                    tprofit = mprofit+cprofit+dprofit;
                    return {"total":tprofit,"metal":mprofit,"crystal":cprofit,"deut":dprofit};
                }
                else{
                    return {"total":"nan","metal":"nan","crystal":"nan","deut":"nan"};
                }
            }
            else{
                return {"total":"nan","metal":"nan","crystal":"nan","deut":"nan"};
            }
    }

    function processLocalDB_Ayer(){
            var localID = document.getElementsByName('ogame-player-id')[0].getAttribute('content');
            var currentTime = document.getElementsByName('ogame-timestamp')[0].getAttribute('content');
            var timeZone = document.getElementsByName('ogame-language')[0].getAttribute('content');
            var now = new Date();
            var startOfDay = new Date(now.getFullYear(), now.getMonth(), now.getDate());
            var timestamp_Ayer_Inicio = (startOfDay / 1000) - 86400;
            var timestamp_Ayer_Fin = timestamp_Ayer_Inicio + 86400;
            var mprofit =0;
            var cprofit =0;
            var dprofit =0;
            var tprofit =0;
            var mloss = 0;
            var closs = 0;
            var dloss = 0;
            if(localStorage.getItem('Prueba1_profitDB')!=null){
                var localprofitDB = JSON.parse(localStorage.getItem('Prueba1_profitDB'));
                for (var entryID in localprofitDB){
                    if((localprofitDB[entryID].timestamp>timestamp_Ayer_Inicio) && (localprofitDB[entryID].timestamp<timestamp_Ayer_Fin)){
                        if(localprofitDB[entryID].attackerid.includes(localID)){
                            //console.log("You were the attacker");
                            mloss = 0;
                            closs = 0;
                            dloss = 0;
                            for(var alosses in localprofitDB[entryID].attackerloss){
                                mloss += localprofitDB[entryID].attackerloss[alosses]*shipdata[alosses].metal;
                                closs += localprofitDB[entryID].attackerloss[alosses]*shipdata[alosses].crystal;
                                dloss += localprofitDB[entryID].attackerloss[alosses]*shipdata[alosses].deuterium;
                            }
                            mprofit+=localprofitDB[entryID].loot.metal-mloss;
                            cprofit+=localprofitDB[entryID].loot.crystal-closs;
                            dprofit+=localprofitDB[entryID].loot.deuterium-dloss;
                        }
                        else if(localprofitDB[entryID].defenderid.includes(localID)){
                            //console.log("You were the defender");
                            mloss = 0;
                            closs = 0;
                            dloss = 0;
                            for(var dlosses in localprofitDB[entryID].defenderloss){
                                if(localprofitDB[entryID].repaired.hasOwnProperty(dlosses)){
                                    mloss += (localprofitDB[entryID].defenderloss[dlosses]-localprofitDB[entryID].repaired[dlosses])*shipdata[dlosses].metal;
                                    closs += (localprofitDB[entryID].defenderloss[dlosses]-localprofitDB[entryID].repaired[dlosses])*shipdata[dlosses].crystal;
                                    dloss += (localprofitDB[entryID].defenderloss[dlosses]-localprofitDB[entryID].repaired[dlosses])*shipdata[dlosses].deuterium;
                                }
                                else if(localprofitDB[entryID].wreckfield.hasOwnProperty(dlosses)){
                                    mloss += (localprofitDB[entryID].defenderloss[dlosses]-localprofitDB[entryID].wreckfield[dlosses])*shipdata[dlosses].metal;
                                    closs += (localprofitDB[entryID].defenderloss[dlosses]-localprofitDB[entryID].wreckfield[dlosses])*shipdata[dlosses].crystal;
                                    dloss += (localprofitDB[entryID].defenderloss[dlosses]-localprofitDB[entryID].wreckfield[dlosses])*shipdata[dlosses].deuterium;
                                }
                                else{
                                    mloss += localprofitDB[entryID].defenderloss[dlosses]*shipdata[dlosses].metal;
                                    closs += localprofitDB[entryID].defenderloss[dlosses]*shipdata[dlosses].crystal;
                                    dloss += localprofitDB[entryID].defenderloss[dlosses]*shipdata[dlosses].deuterium;
                                }
                            }
                            mprofit+=0-mloss-localprofitDB[entryID].loot.metal;
                            cprofit+=0-closs-localprofitDB[entryID].loot.crystal;
                            dprofit+=0-dloss-localprofitDB[entryID].loot.deuterium;
                        }
                        else{
                            //console.log("You were not involved");
                        }
                    }
                }
                if(localStorage.getItem('Prueba1_dfDB')!=null){
                    var localdfDB = JSON.parse(localStorage.getItem('Prueba1_dfDB'));
                    for (var dfentryID in localdfDB){
                        if((localdfDB[dfentryID].timestamp>timestamp_Ayer_Inicio) && (localdfDB[dfentryID].timestamp<timestamp_Ayer_Fin)){
                            //Add DF profits
                            mprofit+=localdfDB[dfentryID].metal;
                            cprofit+=localdfDB[dfentryID].crystal;
                        }
                    }
                }
                    if(localStorage.getItem('Prueba1_NET_profitDB')!=null){
                    var localExpDB = JSON.parse(localStorage.getItem('Prueba1_NET_profitDB'));
                    for (var ExpentryID in localExpDB){
                        var timestring = localExpDB[ExpentryID].Timestamp.split(".")
                        timestring[1] =localExpDB[ExpentryID].Timestamp.split(".")[0];
                        timestring[0] =localExpDB[ExpentryID].Timestamp.split(".")[1];
                        var timestring2;
                        if(document.getElementById("ago_clock_server")!== null){
                        timestring2 = document.getElementById("ago_clock_server").innerHTML.split(".");
                        timestring2[1] =document.getElementById("ago_clock_server").innerHTML.split(".")[0];
                        timestring2[0] =document.getElementById("ago_clock_server").innerHTML.split(".")[1];
                        }
                        else{
                        timestring2 = document.getElementsByClassName("OGameClock")[0].innerHTML.replace(/\//g, '').replace(/<span>/g, '').split(".");
                        timestring2[1] =document.getElementsByClassName("OGameClock")[0].innerHTML.replace(/\//g, '').replace(/<span>/g, '').split(".")[0];
                        timestring2[0] =document.getElementsByClassName("OGameClock")[0].innerHTML.replace(/\//g, '').replace(/<span>/g, '').split(".")[1];
                        }
                        //if((new Date(timestring.toString().replace(/,/g, '.')).getTime()>(new Date(timestring2.toString().replace(/,/g, '.')).getTime()-60 * 60 * time*1000)) && 1 == 0){
                        if(((new Date(timestring.toString().replace(/,/g, '.')).getTime()/1000)>timestamp_Ayer_Inicio) && ((new Date(timestring.toString().replace(/,/g, '.')).getTime()/1000)<timestamp_Ayer_Fin)){
                            //Add Exp profits
                            mprofit+=parseInt(localExpDB[ExpentryID].Metal);
                            cprofit+=parseInt(localExpDB[ExpentryID].Crystal);
                            dprofit+=parseInt(localExpDB[ExpentryID].Deuterium);
                            mprofit+=parseInt(localExpDB[ExpentryID]['Small Cargo'])*shipdata[202].metal;
                            cprofit+=parseInt(localExpDB[ExpentryID]['Small Cargo'])*shipdata[202].crystal;
                            mprofit+=parseInt(localExpDB[ExpentryID]['Large Cargo'])*shipdata[203].metal;
                            cprofit+=parseInt(localExpDB[ExpentryID]['Large Cargo'])*shipdata[203].crystal;
                            mprofit+=parseInt(localExpDB[ExpentryID]['Light Fighter'])*shipdata[204].metal;
                            cprofit+=parseInt(localExpDB[ExpentryID]['Light Fighter'])*shipdata[204].crystal;
                            mprofit+=parseInt(localExpDB[ExpentryID]['Heavy Fighter'])*shipdata[205].metal;
                            cprofit+=parseInt(localExpDB[ExpentryID]['Heavy Fighter'])*shipdata[205].crystal;
                            mprofit+=parseInt(localExpDB[ExpentryID]['Cruiser'])*shipdata[206].metal;
                            cprofit+=parseInt(localExpDB[ExpentryID]['Cruiser'])*shipdata[206].crystal;
                            dprofit+=parseInt(localExpDB[ExpentryID]['Cruiser'])*shipdata[206].deuterium;
                            mprofit+=parseInt(localExpDB[ExpentryID]['Battleship'])*shipdata[207].metal;
                            cprofit+=parseInt(localExpDB[ExpentryID]['Battleship'])*shipdata[207].crystal;
                            cprofit+=parseInt(localExpDB[ExpentryID]['Espionage Probe'])*shipdata[210].crystal;
                            mprofit+=parseInt(localExpDB[ExpentryID]['Bomber'])*shipdata[211].metal;
                            cprofit+=parseInt(localExpDB[ExpentryID]['Bomber'])*shipdata[211].crystal;
                            dprofit+=parseInt(localExpDB[ExpentryID]['Bomber'])*shipdata[211].deuterium;
                            mprofit+=parseInt(localExpDB[ExpentryID]['Destroyer'])*shipdata[213].metal;
                            cprofit+=parseInt(localExpDB[ExpentryID]['Destroyer'])*shipdata[213].crystal;
                            dprofit+=parseInt(localExpDB[ExpentryID]['Destroyer'])*shipdata[213].deuterium;
                            mprofit+=parseInt(localExpDB[ExpentryID]['Battlecruiser'])*shipdata[215].metal;
                            cprofit+=parseInt(localExpDB[ExpentryID]['Battlecruiser'])*shipdata[215].crystal;
                            dprofit+=parseInt(localExpDB[ExpentryID]['Battlecruiser'])*shipdata[215].deuterium;
                            mprofit+=parseInt(localExpDB[ExpentryID]['Reaper'])*shipdata[218].metal;
                            cprofit+=parseInt(localExpDB[ExpentryID]['Reaper'])*shipdata[218].crystal;
                            dprofit+=parseInt(localExpDB[ExpentryID]['Reaper'])*shipdata[218].deuterium;
                            mprofit+=parseInt(localExpDB[ExpentryID]['Pathfinder'])*shipdata[219].metal;
                            cprofit+=parseInt(localExpDB[ExpentryID]['Pathfinder'])*shipdata[219].crystal;
                            dprofit+=parseInt(localExpDB[ExpentryID]['Pathfinder'])*shipdata[219].deuterium;
                        }
                    }

                    tprofit = mprofit+cprofit+dprofit;
                    return {"total":tprofit,"metal":mprofit,"crystal":cprofit,"deut":dprofit};
                }
                else{
                    return {"total":"nan","metal":"nan","crystal":"nan","deut":"nan"};
                }
            }
            else{
                return {"total":"nan","metal":"nan","crystal":"nan","deut":"nan"};
            }
    }


    //Update profits overviewtable
    function updateProfits(){
        // 7 días
        var wDeut = document.getElementById('WeeklyDeut');
        var wCrystal = document.getElementById('WeeklyCrystal');
        var wMetal = document.getElementById('WeeklyMetal');
        var wTotal = document.getElementById('WeeklyTotal');
        // 24hs
        var dDeut = document.getElementById('DailyDeut');
        var dCrystal = document.getElementById('DailyCrystal');
        var dMetal = document.getElementById('DailyMetal');
        var dTotal = document.getElementById('DailyTotal');
        // Hoy
        var tDeut = document.getElementById('TodayDeut');
        var tCrystal = document.getElementById('TodayCrystal');
        var tMetal = document.getElementById('TodayMetal');
        var tTotal = document.getElementById('TodayTotal');
        // Ayer
        var yDeut = document.getElementById('YesterdayDeut');
        var yCrystal = document.getElementById('YesterdayCrystal');
        var yMetal = document.getElementById('YesterdayMetal');
        var yTotal = document.getElementById('YesterdayTotal');
        // Promedio
        var pDeut = document.getElementById('PromedioDeut');
        var pCrystal = document.getElementById('PromedioCristal');
        var pMetal = document.getElementById('PromedioMetal');
        var pTotal = document.getElementById('PromedioTotal');
        // Hoy versus Ayer
        var vDeut = document.getElementById('VersusDeut');
        var vCrystal = document.getElementById('VersusCrystal');
        var vMetal = document.getElementById('VersusMetal');
        var vTotal = document.getElementById('VersusTotal');
        // Hoy versus Promedio
        var vpDeut = document.getElementById('VersusPromedioDeut');
        var vpCrystal = document.getElementById('VersusPromedioCristal');
        var vpMetal = document.getElementById('VersusPromedioMetal');
        var vpTotal = document.getElementById('VersusPromedioTotal');
        // Versión Script
        var nroversion = document.getElementById('version');
        nroversion.innerHTML=SCRIPT_VERSION;
        //update Hourly
        updateHourly(parseInt(document.getElementById('RaidHours').value));
        //update weekly
        var weeklyprofit = processLocalDB(168);
        wMetal.innerHTML=weeklyprofit.metal.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ".");
        if(weeklyprofit.metal>=0){wMetal.style="color:#00b000;";}else{wMetal.style="color:#d43635;";}
        wCrystal.innerHTML=weeklyprofit.crystal.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ".");
        if(weeklyprofit.crystal>=0){wCrystal.style="color:#00b000;";}else{wCrystal.style="color:#d43635;";}
        wDeut.innerHTML=weeklyprofit.deut.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ".");
        if(weeklyprofit.deut>=0){wDeut.style="color:#00b000;";}else{wDeut.style="color:#d43635;";}
        wTotal.innerHTML=weeklyprofit.total.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ".");
        if(weeklyprofit.total>=0){wTotal.style="color:#00b000;";}else{wTotal.style="color:#d43635;";}
        //update daily
        var dailyprofit= processLocalDB(24);
        dMetal.innerHTML=dailyprofit.metal.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ".");
        if(dailyprofit.metal>=0){dMetal.style="color:#00b000;";}else{dMetal.style="color:#d43635;";}
        dCrystal.innerHTML=dailyprofit.crystal.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ".");
        if(dailyprofit.crystal>=0){dCrystal.style="color:#00b000;";}else{dCrystal.style="color:#d43635;";}
        dDeut.innerHTML=dailyprofit.deut.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ".");
        if(dailyprofit.deut>=0){dDeut.style="color:#00b000;";}else{dDeut.style="color:#d43635;";}
        dTotal.innerHTML=dailyprofit.total.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ".");
        if(dailyprofit.total>=0){dTotal.style="color:#00b000;";}else{dTotal.style="color:#d43635;";}
        //update Hoy
        var todayprofit= processLocalDB_Hoy();
        tMetal.innerHTML=todayprofit.metal.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ".");
        if(todayprofit.metal>=0){tMetal.style="color:#00b000;";}else{tMetal.style="color:#d43635;";}
        tCrystal.innerHTML=todayprofit.crystal.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ".");
        if(todayprofit.crystal>=0){tCrystal.style="color:#00b000;";}else{tCrystal.style="color:#d43635;";}
        tDeut.innerHTML=todayprofit.deut.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ".");
        if(todayprofit.deut>=0){tDeut.style="color:#00b000;";}else{tDeut.style="color:#d43635;";}
        tTotal.innerHTML=todayprofit.total.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ".");
        if(todayprofit.total>=0){tTotal.style="color:#00b000;";}else{tTotal.style="color:#d43635;";}
        //update promedio
        var yesterdayprofit= weeklyprofit; //processLocalDB(168);
        yMetal.innerHTML=Math.round(yesterdayprofit.metal/7).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ".");
        if(yesterdayprofit.metal>=0){yMetal.style="color:#00b000;";}else{yMetal.style="color:#d43635;";}
        yCrystal.innerHTML=Math.round(yesterdayprofit.crystal/7).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ".");
        if(yesterdayprofit.crystal>=0){yCrystal.style="color:#00b000;";}else{yCrystal.style="color:#d43635;";}
        yDeut.innerHTML=Math.round(yesterdayprofit.deut/7).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ".");
        if(yesterdayprofit.deut>=0){yDeut.style="color:#00b000;";}else{yDeut.style="color:#d43635;";}
        yTotal.innerHTML=Math.round(yesterdayprofit.total/7).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ".");
        if(yesterdayprofit.total>=0){yTotal.style="color:#00b000;";}else{yTotal.style="color:#d43635;";}
        //update versus
        //var versusprofit= processLocalDB_Ayer();

        vMetal.innerHTML = Math.round((todayprofit.metal-(yesterdayprofit.metal/7))).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ".");
        if((todayprofit.metal-(yesterdayprofit.metal/7))>=0){vMetal.style="color:#00b000;";}else{vMetal.style="color:#d43635;";}
        vCrystal.innerHTML = Math.round((todayprofit.crystal-(yesterdayprofit.crystal/7))).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ".");
        if((todayprofit.crystal-(yesterdayprofit.crystal/7))>=0){vCrystal.style="color:#00b000;";}else{vCrystal.style="color:#d43635;";}
        vDeut.innerHTML = Math.round((todayprofit.deut-(yesterdayprofit.deut/7))).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ".");
        if((todayprofit.deut-(yesterdayprofit.deut/7))>=0){vDeut.style="color:#00b000;";}else{vDeut.style="color:#d43635;";}
        vTotal.innerHTML = Math.round((todayprofit.total-(yesterdayprofit.total/7))).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ".");
        if((todayprofit.total-(yesterdayprofit.total/7))>=0){vTotal.style="color:#00b000;";}else{vTotal.style="color:#d43635;";}

    }
    //Updates the hourly profits on profits overviewtable
    function updateHourly(hours){
        if(hours<1){document.getElementById('RaidHours').value=1;hours=1;}
        var hDeut = document.getElementById('HourlyDeut');
        var hCrystal = document.getElementById('HourlyCrystal');
        var hMetal = document.getElementById('HourlyMetal');
        var hTotal = document.getElementById('HourlyTotal');
        var hourlyprofit= processLocalDB(hours);
        hMetal.innerHTML=hourlyprofit.metal.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ".");
        if(hourlyprofit.metal>=0){hMetal.style="color:#00b000;";}else{hMetal.style="color:#d43635;";}
        hCrystal.innerHTML=hourlyprofit.crystal.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ".");
        if(hourlyprofit.crystal>=0){hCrystal.style="color:#00b000;";}else{hCrystal.style="color:#d43635;";}
        hDeut.innerHTML=hourlyprofit.deut.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ".");
        if(hourlyprofit.deut>=0){hDeut.style="color:#00b000;";}else{hDeut.style="color:#d43635;";}
        hTotal.innerHTML=hourlyprofit.total.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ".");
        if(hourlyprofit.total>=0){hTotal.style="color:#00b000;";}else{hTotal.style="color:#d43635;";}
    }
    //Makes an element dragable - credit to https://www.w3schools.com/howto/howto_js_draggable.asp
    function dragElement(elmnt) {
        var pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0;
        if (document.getElementById(elmnt.id + "header")) {
            // if present, the header is where you move the DIV from:
            document.getElementById(elmnt.id + "header").onmousedown = dragMouseDown;
        } else {
            // otherwise, move the DIV from anywhere inside the DIV:
            elmnt.onmousedown = dragMouseDown;
        }

        function dragMouseDown(e) {
            e = e || window.event;
            e.preventDefault();
            // get the mouse cursor position at startup:
            pos3 = e.clientX;
            pos4 = e.clientY;
            document.onmouseup = closeDragElement;
            // call a function whenever the cursor moves:
            document.onmousemove = elementDrag;
        }

        function elementDrag(e) {
            if(elmnt.style.position!="Absolute"){
                    if(document.getElementById('banner_skyscraper')!=null){
        document.getElementById('banner_skyscraper').style.top="auto";
            document.getElementById('banner_skyscraper').style.bottom="0px";
        }
            }
            e = e || window.event;
            e.preventDefault();
            // calculate the new cursor position:
            pos1 = pos3 - e.clientX;
            pos2 = pos4 - e.clientY;
            pos3 = e.clientX;
            pos4 = e.clientY;
            // set the element's new position:
            elmnt.style.top = (elmnt.offsetTop - pos2) + "px";
            elmnt.style.left = (elmnt.offsetLeft - pos1) + "px";
            elmnt.style.position="absolute";
        }

        function closeDragElement() {
            // stop moving when mouse button is released:
            document.onmouseup = null;
            document.onmousemove = null;
        }
    }
    function createExpeditionOverviewTable(){
        var expeditionOverviewTable = document.getElementById("expeditionOverviewTable");
        //expeditionOverviewTable.style="width:250px;height:500px;";
               var closeExpeditionStats = document.createElement('div');
        closeExpeditionStats.id = "closeExpeditionStats";
        closeExpeditionStats.className = "close-tooltip";
        closeExpeditionStats.style = "right:2px;top:2px;";
        closeExpeditionStats.onclick=function() {toggleExpeditionOverviewTable()};
        expeditionOverviewTable.appendChild(closeExpeditionStats);
        var expeditionStatsHeader = document.createElement('h1');
        expeditionStatsHeader.id='header';
        expeditionStatsHeader.style="font-size: 14px;color: #ff5700;font-weight: bold;background: black;border: 1px solid #383838;border-radius: 4px;padding: 1px;text-align: center;display: block;margin-bottom:5px";
        expeditionStatsHeader.innerHTML="Estadística de Expediciones";
        expeditionOverviewTable.appendChild(expeditionStatsHeader);
        /*var expeditionStats = document.createElement('span');
        expeditionStats.id="expeditionStats";
        expeditionStats.style="color:#6f9fc8;";
        expeditionStats.innerHTML=processStats();
                expeditionOverviewTable.appendChild(expeditionStats);*/
        var chart = document.createElement('span');
        chart.id="chart-container";
        chart.style="width:250px;height:250px;";
        expeditionOverviewTable.appendChild(chart);
        //createChart();

    }
    //Creates the raid table with full details
    function createProfitOverviewTable(){
        var localID = document.getElementsByName('ogame-player-id')[0].getAttribute('content');
        var table = document.createElement('table');
        table.style="width:800px;opacity:1;background:black;";
        table.className="table table-bordered table-striped";
        table.id="table1";
        // EXTRACT VALUE FOR HTML HEADER.
        var col = ["Tipo","Coord.","Fecha y Hora"," Metal "," Cristal "," Deuterio "," CE de Metal "," CE de Cristal ","Borrar"];
        var headers = document.createElement("thead");
        var row = document.createElement("tr");
        for (var j = 0; j < col.length; j++) {
            var th = document.createElement("th");
            th.innerHTML = col[j];
            row.appendChild(th);
        }
        headers.appendChild(row);
        table.appendChild(headers);
        var tbody = document.createElement("tbody");
        // ADD CR JSON DATA TO THE TABLE AS ROWS.
        for (var key in localprofitDB) {
            if(key!="crID"){
                var tr = document.createElement("tr");
                var type = document.createElement("td");
                type.className="type";
                var coord = document.createElement("td");
                coord.className="coord";
                var timestamp = document.createElement("td");
                timestamp.className="timestamp";
                var lootm = document.createElement("td");
                lootm.className="ploot";
                var lootc = document.createElement("td");
                lootc.className="ploot";
                var lootd = document.createElement("td");
                lootd.className="ploot";
                var dfm = document.createElement("td");
                dfm.className="pdf";
                var dfc = document.createElement("td");
                dfc.className="pdf";
                var deleteCR = document.createElement("td");
                deleteCR.style = "color:red;cursor: pointer;"
                deleteCR.innerHTML = "X";
                deleteCR.id=key;
                deleteCR.addEventListener('click', function(){if (confirm("Estas seguro de querer borrar esta entrada?")) {
                    delete localprofitDB[this.id];
                    localStorage.setItem('Prueba1_profitDB', JSON.stringify(localprofitDB));
                } else {
                    //Don't delete DB entry
                } ;}, false);
                for (var data in localprofitDB[key]) {
                    switch(data) {
                        case "coordinates":
                            var target = "";
                            if(localprofitDB[key][data].planetType==3){target = "m";}
                            coord.innerHTML = localprofitDB[key][data].galaxy+":"+localprofitDB[key][data].system+":"+localprofitDB[key][data].position+target;
                            break;
                        case "loot":
                            if(localprofitDB[key].attackerid.includes(localID)){
                                lootm.innerHTML =localprofitDB[key][data].metal;
                                lootm.style="color: rgb(0, 176, 0);";
                                lootc.innerHTML =localprofitDB[key][data].crystal;
                                lootc.style="color: rgb(0, 176, 0);";
                                lootd.innerHTML =localprofitDB[key][data].deuterium;
                                lootd.style="color: rgb(0, 176, 0);";
                            }
                            else{
                                lootm.innerHTML =-localprofitDB[key][data].metal;
                                if(localprofitDB[key][data].metal>0){lootm.style="color: rgb(212, 54, 53);";} else{lootm.style="color: rgb(0, 176, 0);";}
                                lootc.innerHTML =-localprofitDB[key][data].crystal;
                                if(localprofitDB[key][data].crystal>0){lootc.style="color: rgb(212, 54, 53);";} else{lootc.style="color: rgb(0, 176, 0);";}
                                lootd.innerHTML =-localprofitDB[key][data].deuterium;
                                if(localprofitDB[key][data].deuterium>0){lootd.style="color: rgb(212, 54, 53);";} else{lootd.style="color: rgb(0, 176, 0);";}
                            }
                            break;
                        case "df":
                            dfm.innerHTML =localprofitDB[key][data].metal;
                            dfc.innerHTML =localprofitDB[key][data].crystal;
                            break;
                        case "timestamp":
                            var date = new Date(parseInt(localprofitDB[key].timestamp)*1000);
                            timestamp.innerHTML = ("0"+date.getDate()).slice(-2)+"-"+("0"+(date.getMonth()+1)).slice(-2)+"-"+date.getFullYear()+" "+("0"+date.getHours()).slice(-2)+":"+("0" + date.getMinutes()).slice(-2);
                            break;
                        default:
                            // do nothing
                    }
                    type.innerHTML="CR";
                    tr.appendChild(type);
                    tr.appendChild(coord);
                    tr.appendChild(timestamp);
                    lootm.innerHTML = lootm.innerHTML.replace(/\B(?=(\d{3})+(?!\d))/g, ".")
                    tr.appendChild(lootm);
                    lootc.innerHTML = lootc.innerHTML.replace(/\B(?=(\d{3})+(?!\d))/g, ".")
                    tr.appendChild(lootc);
                    lootd.innerHTML = lootd.innerHTML.replace(/\B(?=(\d{3})+(?!\d))/g, ".")
                    tr.appendChild(lootd);
                    dfm.innerHTML = dfm.innerHTML.replace(/\B(?=(\d{3})+(?!\d))/g, ".")
                    tr.appendChild(dfm);
                    dfc.innerHTML = dfc.innerHTML.replace(/\B(?=(\d{3})+(?!\d))/g, ".")
                    tr.appendChild(dfc);
                    tr.appendChild(deleteCR);
                }
                tbody.appendChild(tr);
            }
        }
        // ADD DF JSON DATA TO THE TABLE AS ROWS.
        for (var dfkey in localdfDB) {
            if(dfkey!="dfID"){
                var dftr = document.createElement("tr");
                var dftype = document.createElement("td");
                dftype.className="type";
                var dfcoord = document.createElement("td");
                dfcoord.className="coord";
                var dftimestamp = document.createElement("td");
                dftimestamp.className="timestamp";
                var dflootm = document.createElement("td");
                dflootm.className="ploot";
                var dflootc = document.createElement("td");
                dflootc.className="ploot";
                var dflootd = document.createElement("td");
                dflootd.className="ploot";
                var dfdfm = document.createElement("td");
                dfdfm.className="pdf";
                var dfdfc = document.createElement("td");
                dfdfc.className="pdf";
                var deleteDF = document.createElement("td");
                deleteDF.style = "color:red;cursor: pointer;"
                deleteDF.innerHTML = "X";
                deleteDF.id=dfkey;
                deleteDF.addEventListener('click', function(){if (confirm("Estas seguro de querer borrar esta entrada?")) {
                    delete localdfDB[this.id];
                    localStorage.setItem('Prueba1_dfDB', JSON.stringify(localdfDB));
                }else {
                    //Don't delete DB entry
                } ;}, false);
                //deleteDF.addEventListener('click', function(){deleteHarvestDBElement(dfkey) ;}, false);
                dftype.innerHTML="HR";
                dftr.appendChild(dftype);
                for (var dfdata in localdfDB[dfkey]) {
                    switch(dfdata) {
                        case "coordinates":
                            dfcoord.innerHTML = localdfDB[dfkey][dfdata];
                            break;
                        case "metal":
                            dfdfm.innerHTML =localdfDB[dfkey][dfdata];
                            if(parseInt(localdfDB[dfkey][dfdata])>=0){dfdfm.style="color: rgb(0, 176, 0);";}else{dfdfm.style="color: rgb(212, 54, 53);";}
                            break;
                        case "crystal":
                            dfdfc.innerHTML =localdfDB[dfkey][dfdata];
                            if(parseInt(localdfDB[dfkey][dfdata])>=0){dfdfc.style="color: rgb(0, 176, 0);";}else{dfdfc.style="color: rgb(212, 54, 53);";}
                            break;
                        case "timestamp":
                            var dfdate = new Date(parseInt(localdfDB[dfkey][dfdata])*1000-new Date().getTimezoneOffset()*60*1000);
                            dftimestamp.innerHTML = ("0"+dfdate.getDate()).slice(-2)+"-"+("0"+(dfdate.getMonth()+1)).slice(-2)+"-"+dfdate.getFullYear()+" "+("0"+dfdate.getHours()).slice(-2)+":"+("0" + dfdate.getMinutes()).slice(-2);
                            break;
                        default:
                            //do nothing
                    }
                    dftr.appendChild(dfcoord);
                    dftr.appendChild(dftimestamp);
                    dflootm.innerHTML = "0";
                    dftr.appendChild(dflootm);
                    dflootc.innerHTML = "0";
                    dftr.appendChild(dflootc);
                    dflootd.innerHTML = "0";
                    dftr.appendChild(dflootd);
                    dfdfm.innerHTML = ""+dfdfm.innerHTML.replace(/\B(?=(\d{3})+(?!\d))/g, ".")
                    dftr.appendChild(dfdfm);
                    dfdfc.innerHTML = ""+dfdfc.innerHTML.replace(/\B(?=(\d{3})+(?!\d))/g, ".")
                    dftr.appendChild(dfdfc);
                    dftr.appendChild(deleteDF);
                }
                tbody.appendChild(dftr);
            }
            table.appendChild(tbody);
        }
                var closeProfitOverviewTable = document.createElement('div');
        closeProfitOverviewTable.id = "closeProfitOverviewTable";
        closeProfitOverviewTable.className = "close-tooltip";
        closeProfitOverviewTable.style = "top:2px;right:5px;";
        closeProfitOverviewTable.onclick=function() {toggleProfitOverviewTable()};
        document.getElementById("profitOverviewTable").appendChild(closeProfitOverviewTable);
        var header = document.createElement("h1");
        header.innerHTML="Resumen de Batallas";
        header.id="header";
        header.style="float:left;width:80%;font-size: 14px;color: #ff5700;font-weight: bold;background: black;border: 1px solid #383838;border-radius: 4px;padding: 1px;text-align: center;display: block";
        document.getElementById("profitOverviewTable").appendChild(header);
        var deleteDiv = document.createElement("span");
        deleteDiv.innerHTML="Reiniciar BD";
        deleteDiv.style="cursor: pointer;float:left;width:16%;font-size: 14px;color: red;font-weight: bold;background: black;border: 1px solid #383838;border-radius: 4px;padding: 1px;text-align: center;display: block";
        deleteDiv.addEventListener('click', function(){if (confirm("CUIDADO!! Se borra la Base de Datos y se reinician todos los calculos, estas seguro?")) {
            localStorage.removeItem("Prueba1_dfDB");
            localStorage.removeItem("Prueba1_profitDB");
            localStorage.removeItem("Prueba1_NET_profitDB");
        } else {
            //Don't delete DB
        } ;}, false);
        document.getElementById("profitOverviewTable").appendChild(deleteDiv);
        document.getElementById("profitOverviewTable").appendChild(table);
        $('#table1').dataTable({
            "iDisplayLength": 20,
            "searching": false,
            "info":     false,
            "language": {
                "decimal": ",",
                "thousands": ".",
            },
            "order": [[ 2, "desc" ]]

        });
    }
    //Toggles the raid table with full details
    function toggleProfitOverviewTable(){
        var profitOverviewTable = document.getElementById('profitOverviewTable');
        if(profitOverviewTable.style.visibility=="hidden"){
            createProfitOverviewTable();
            profitOverviewTable.style.visibility="visible";
        }
        else{
            profitOverviewTable.innerHTML ="";
            profitOverviewTable.style.visibility="hidden";
        }
    }
    function toggleExpeditionOverviewTable(){
        var expeditionOverviewTable = document.getElementById('expeditionOverviewTable');
        if(expeditionOverviewTable.style.visibility=="hidden"){
            createExpeditionOverviewTable();
            createChart();
            let coverUp = document.createElement('div');
            coverUp.style="width:100px;height:10px;position:absolute;background-color: white; top: 412px;left: 5px;";
            expeditionOverviewTable.appendChild(coverUp);
            expeditionOverviewTable.style.visibility="visible";
        }
        else{
            expeditionOverviewTable.innerHTML ="";
            expeditionOverviewTable.style.visibility="hidden";
        }
    }
    function checkRisk(){
        var localID = document.getElementsByName('ogame-player-id')[0].getAttribute('content');
        var attackList={};
        if(localStorage.getItem('Prueba1_profitDB')!=null){
            var localprofitDB = JSON.parse(localStorage.getItem('Prueba1_profitDB'));
            for (var entryID in localprofitDB){
                if(localprofitDB[entryID].timestamp>((new Date().getTime()/1000)- (60 * 60 * 24))){
                    if(localprofitDB[entryID].attackerid==localID){
                        var target = "";
                        if(localprofitDB[entryID].coordinates.planetType==3){target = "m";}
                        var coord = localprofitDB[entryID].coordinates.galaxy+":"+localprofitDB[entryID].coordinates.system+":"+localprofitDB[entryID].coordinates.position+target;
                        if(attackList.hasOwnProperty(coord)){
                            attackList[coord]+=1;
                        }
                        else{
                            attackList[coord]=1;
                        }
                    }
                }
            }
        }
        var sixAttacks = document.createElement('div');
        var fiveAttacks = document.createElement('div');
        var fourAttacks = document.createElement('div');
        for (var targets in attackList){
            var moonIcon = '<figure style="width:13px;height:13px;"   class="planetIcon moon tooltip js_hideTipOnMobile" title=""></figure>';
            //var planetIcon = '<figure class="menuImage overview " title=""></figure>';

            if(attackList[targets]>=4){
                var riskMeter ="color: rgb(212, 54, 53);";
                if(attackList[targets]==4){
                    riskMeter ="color: rgb(0, 176, 0);";
                    if(targets.search("m")<0){
                        fourAttacks.innerHTML+="<div style='font-size:11px;"+riskMeter+"'><img width='13px' height='13px' style='display:inline-block;vertical-align:middle;'src='"+document.getElementsByClassName("planetPic")[Math.floor(Math.random() *document.getElementsByClassName("planetPic").length)].src+"'></img><span style='display:inline-block;'>["+targets+"]</span> <span style='display:inline-block;'>- "+attackList[targets]+"</span></div>";
                    }
                    else{
                        fourAttacks.innerHTML+="<div style='font-size:11px;"+riskMeter+"'>"+moonIcon+"["+targets.replace("m","")+"] - <span>"+attackList[targets]+"</span></div>";
                    }
                }
                else if(attackList[targets]==5){
                    riskMeter ="color:#ffd700;";
                    if(targets.search("m")<0){
                        fiveAttacks.innerHTML+="<div style='font-size:11px;"+riskMeter+"'><img width='13px' height='13px' style='display:inline-block;vertical-align:middle;'src='"+document.getElementsByClassName("planetPic")[Math.floor(Math.random() *document.getElementsByClassName("planetPic").length)].src+"'></img><span style='display:inline-block;'>["+targets+"]</span> <span style='display:inline-block;'>- "+attackList[targets]+"</span></div>";
                    }
                    else{
                        fiveAttacks.innerHTML+="<div style='font-size:11px;"+riskMeter+"'>"+moonIcon+"["+targets.replace("m","")+"] - <span>"+attackList[targets]+"</span></div>";
                    }
                }
                else{
                    if(targets.search("m")<0){
                        sixAttacks.innerHTML+="<div style='font-size:11px;"+riskMeter+"'><img width='13px' height='13px' style='display:inline-block;vertical-align:middle;'src='"+document.getElementsByClassName("planetPic")[Math.floor(Math.random() *document.getElementsByClassName("planetPic").length)].src+"'></img><span style='display:inline-block;'>["+targets+"]</span> <span style='display:inline-block;'>- "+attackList[targets]+"</span></div>";
                    }
                    else{
                        sixAttacks.innerHTML+="<div style='font-size:11px;"+riskMeter+"'>"+moonIcon+"["+targets.replace("m","")+"] - <span>"+attackList[targets]+"</span></div>";
                    }
                    document.getElementById('bashlist').appendChild(sixAttacks);
                    document.getElementById('bashlist').appendChild(fiveAttacks);
                    document.getElementById('bashlist').appendChild(fourAttacks);
                }
            }
        }
        if(sixAttacks.innerHTML.length+fiveAttacks.innerHTML.length+fourAttacks.innerHTML.length>0){document.getElementById('bash').style.display="block";}
    }
    function cleanDB(time){
        for (var entryID in localprofitDB){
            if(entryID !="crID"){
                if(localprofitDB[entryID].timestamp<((new Date().getTime()/1000)- (60 * 60 * time))){
                    deleteProfitDBElement(entryID);
                }
            }
        }
        for (var DFentryID in localdfDB){
            if(DFentryID !="dfID"){
                if(localdfDB[DFentryID].timestamp<((new Date().getTime()/1000)- (60 * 60 * time))){
                    deleteProfitDBElement(DFentryID);
                }
            }
        }
        for (var ExpentryID in localExpeditionDB){
            if(ExpentryID !="expID"){
                if(localExpeditionDB[ExpentryID].timestamp<((new Date().getTime()/1000)- (60 * 60 * time))){
                    deleteExpeditionDBElement(ExpentryID);
                }
            }
            else{

                            if(Object.keys(localExpeditionDB).length>1){
                    deleteExpeditionDBElement(ExpentryID);
                }
            }
        }
    }
    function deleteProfitDBElement(id){
        delete localprofitDB[id];
        localStorage.setItem('Prueba1_profitDB', JSON.stringify(localprofitDB));
    }
    function deleteHarvestDBElement(id){
        delete localdfDB[id];
        localStorage.setItem('Prueba1_dfDB', JSON.stringify(localdfDB));
    }
        function deleteExpeditionDBElement(id){
        delete localExpeditionDB[id];
        localStorage.setItem('Prueba1_NET_profitDB', JSON.stringify(localExpeditionDB));
    }
    function processStats(){
    var stats = {"Recursos":0,"Naves":0,"MO":0,"Item":0,"Mercader":0,"Nada":0,"Aliens":0,"Piratas":0,"Retraso":0,"Vuelta Rapida":0,"Flota Perdida":0};
        var total = 0;

        for (var entry in JSON.parse(localStorage.getItem('Prueba1_NET_profitDB'))){
            //console.log(JSON.parse(localStorage.getItem('Prueba1_NET_profitDB'))[entry].Result);
            stats[JSON.parse(localStorage.getItem('Prueba1_NET_profitDB'))[entry].Result]++;
            total++;
        }
        var output="";
        for (var result in stats){
        output+=result+": "+stats[result]+"/"+total+" - "+((stats[result]/total)*100).toFixed(2)+"%<br/>";
        }
            return output;

    }
    function createExportMenuItems(){
        //Create menu items
        var menulistElement = document.createElement("li");
        menulistElement.innerHTML = '<span class="menu_icon"><a id="downloadAnchorElem" href="#"><div class="menuImage premium  " style="text-align:center;">JS</div></a></span><a id="downloadAnchorElem2" class="menubutton " href="#"><span class="textlabel">Exportar B&E</span></a>';
        menulistElement.id="NETExport";
        document.getElementById('menuTableTools').appendChild(menulistElement);
        //Add attach data to the links
        updateFiles();
        }
    function updateFiles(){
        var dataStr = "data:text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(localExpeditionDB))+"\r\n"+ encodeURIComponent(JSON.stringify(localprofitDB))+"\r\n"+ encodeURIComponent(JSON.stringify(localdfDB));
        var dlAnchorElem = document.getElementById('downloadAnchorElem');
        dlAnchorElem.setAttribute("href",dataStr);
        dlAnchorElem.setAttribute("download", "ExpeditionExport.json");
        var dataStr2 = "data:text/json;charset=utf-8," + encodeURIComponent(convertCSV());
        var dlAnchorElem2 = document.getElementById('downloadAnchorElem2');
        dlAnchorElem2.setAttribute("href",dataStr2);
        dlAnchorElem2.setAttribute("download", "ExpeditionExport.csv");
    }
    function convertCSV(){
        let localoffset = parseInt(offset.replace("+","").split(":")[0])*60+parseInt(offset.replace("+","").split(":")[1]);
        var fields;
        var data = "";
        for(let item in localExpeditionDB){
            if(localExpeditionDB[item].hasOwnProperty("Deathstar")){
            if(fields==null){fields = "ID,"+Object.keys(localExpeditionDB[item]);}
            data+=item+","+localExpeditionDB[item].Timestamp+","+localExpeditionDB[item].Coordinates+","+localExpeditionDB[item].Result+","+localExpeditionDB[item].Metal+","+localExpeditionDB[item].Crystal+","+localExpeditionDB[item].Deuterium+","+localExpeditionDB[item].DM+","+localExpeditionDB[item]['Light Fighter']+","+localExpeditionDB[item]['Heavy Fighter']+","+localExpeditionDB[item].Cruiser+","+localExpeditionDB[item].Battleship+","+localExpeditionDB[item].Battlecruiser+","+localExpeditionDB[item].Bomber+","+localExpeditionDB[item].Destroyer+","+localExpeditionDB[item].Reaper+","+localExpeditionDB[item]['Espionage Probe']+","+localExpeditionDB[item]['Small Cargo']+","+localExpeditionDB[item]['Large Cargo']+","+localExpeditionDB[item].Pathfinder+","+localExpeditionDB[item]['Deathstar']+","+localExpeditionDB[item]['Colonyship']+","+localExpeditionDB[item]['Recycler']+","+localExpeditionDB[item]['Satelite']+","+localExpeditionDB[item]['Crawler']+","+localExpeditionDB[item]['Rocket Launcher']+","+localExpeditionDB[item]['Light Laser']+","+localExpeditionDB[item]['Heavy Laser']+","+localExpeditionDB[item]['Gaus Cannon']+","+localExpeditionDB[item]['Ion Cannon'] +","+localExpeditionDB[item]['Plasma Turret'] +","+localExpeditionDB[item]['Small Shield'] +","+localExpeditionDB[item]['Large Shield']+","+localExpeditionDB[item].Item+","+localExpeditionDB[item].Depletion+"\r\n";
        }
            else{
            data+=item+","+localExpeditionDB[item].Timestamp+","+localExpeditionDB[item].Coordinates+","+localExpeditionDB[item].Result+","+localExpeditionDB[item].Metal+","+localExpeditionDB[item].Crystal+","+localExpeditionDB[item].Deuterium+","+localExpeditionDB[item].DM+","+localExpeditionDB[item]['Light Fighter']+","+localExpeditionDB[item]['Heavy Fighter']+","+localExpeditionDB[item].Cruiser+","+localExpeditionDB[item].Battleship+","+localExpeditionDB[item].Battlecruiser+","+localExpeditionDB[item].Bomber+","+localExpeditionDB[item].Destroyer+","+localExpeditionDB[item].Reaper+","+localExpeditionDB[item]['Espionage Probe']+","+localExpeditionDB[item]['Small Cargo']+","+localExpeditionDB[item]['Large Cargo']+","+localExpeditionDB[item].Pathfinder+",0,0,0,0,0,0,0,0,0,0,0,0,0,"+localExpeditionDB[item].Item+","+localExpeditionDB[item].Depletion+"\r\n";
            }
        }
        for(let item in localdfDB){
            if(item !="dfID"){
                let date =new Date(parseInt(localdfDB[item].timestamp)*1000);
                let timestamp = ("0"+date.getDate()).slice(-2)+"."+("0"+(date.getMonth()+1)).slice(-2)+"."+date.getFullYear()+" "+("0"+date.getHours()).slice(-2)+":"+("0" + date.getMinutes()).slice(-2)+":"+("0" + date.getSeconds()).slice(-2);
            data+=item+","+timestamp+","+localdfDB[item].coordinates+",Harvest,"+localdfDB[item].metal+","+localdfDB[item].crystal+",0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,Null,Null\r\n";
            }
        }
        for(let item in localprofitDB){
            if(item !="crID"){

                var moon="";
                let localID = document.getElementsByName('ogame-player-id')[0].getAttribute('content');
                let date =new Date(parseInt(localprofitDB[item].timestamp)*1000+(new Date().getTimezoneOffset()+localoffset)*60*1000);
                let timestamp = ("0"+date.getDate()).slice(-2)+"."+("0"+(date.getMonth()+1)).slice(-2)+"."+date.getFullYear()+" "+("0"+date.getHours()).slice(-2)+":"+("0" + date.getMinutes()).slice(-2)+":"+("0" + date.getSeconds()).slice(-2);
                if(localprofitDB[item].coordinates.planetType==3){moon="m";}
            if(localprofitDB[item].attackerid.includes(localID)){
            data+=item+","+timestamp+","+localprofitDB[item].coordinates.galaxy+":"+localprofitDB[item].coordinates.system+":"+localprofitDB[item].coordinates.position+moon+",Combat,"+localprofitDB[item].loot.metal+","+localprofitDB[item].loot.crystal+","+localprofitDB[item].loot.deuterium+",0,"+-localprofitDB[item].attackerloss['204']+","+-localprofitDB[item].attackerloss['205']+","+-localprofitDB[item].attackerloss['206']+","+-localprofitDB[item].attackerloss['207']+","+-localprofitDB[item].attackerloss['215']+","+-localprofitDB[item].attackerloss['211']+","+-localprofitDB[item].attackerloss['213']+","+-localprofitDB[item].attackerloss['218']+","+-localprofitDB[item].attackerloss['210']+","+-localprofitDB[item].attackerloss['202']+","+-localprofitDB[item].attackerloss['203']+","+-localprofitDB[item].attackerloss['219']+","+-localprofitDB[item].attackerloss['214']+","+-localprofitDB[item].attackerloss['208']+","+-localprofitDB[item].attackerloss['209']+",0,0,0,0,0,0,0,0,0,0,Null,Null\r\n";
            }
            else if(localprofitDB[item].defenderid.includes(localID)){
                for(var dlosses in localprofitDB[item].defenderloss){
                    if(localprofitDB[item].repaired.hasOwnProperty(dlosses)){
                        localprofitDB[item][dlosses] -= localprofitDB[item].repaired[dlosses];
                    }
                    else if(localprofitDB[item].wreckfield.hasOwnProperty(dlosses)){
                        localprofitDB[item][dlosses] -= localprofitDB[item].wreckfield[dlosses];
                    }
                    else{
                    }
                }
                data+=item+","+timestamp+","+localprofitDB[item].coordinates.galaxy+":"+localprofitDB[item].coordinates.system+":"+localprofitDB[item].coordinates.position+moon+",Combat,"+-localprofitDB[item].loot.metal+","+-localprofitDB[item].loot.crystal+","+-localprofitDB[item].loot.deuterium+",0,"+-localprofitDB[item].defenderloss['204']+","+-localprofitDB[item].defenderloss['205']+","+-localprofitDB[item].defenderloss['206']+","+-localprofitDB[item].defenderloss['207']+","+-localprofitDB[item].defenderloss['215']+","+-localprofitDB[item].defenderloss['211']+","+-localprofitDB[item].defenderloss['213']+","+-localprofitDB[item].defenderloss['218']+","+-localprofitDB[item].defenderloss['210']+","+-localprofitDB[item].defenderloss['202']+","+-localprofitDB[item].defenderloss['203']+","+-localprofitDB[item].defenderloss['219']+","+-localprofitDB[item].defenderloss['214']+","+-localprofitDB[item].defenderloss['208']+","+-localprofitDB[item].defenderloss['209']+","+-localprofitDB[item].defenderloss['212']+","+-localprofitDB[item].defenderloss['217']+","+-localprofitDB[item].defenderloss['401']+","+-localprofitDB[item].defenderloss['402']+","+-localprofitDB[item].defenderloss['403']+","+-localprofitDB[item].defenderloss['404']+","+-localprofitDB[item].defenderloss['405']+","+-localprofitDB[item].defenderloss['406']+","+-localprofitDB[item].defenderloss['407']+","+-localprofitDB[item].defenderloss['408']+",Null,Null\r\n";
            }
            else{
            console.log("No csv entry created due to you not being involved.");
            }
        }
        }
        var csv = fields+"\r\n"+data;
        return csv;
                   }

    function createChart(){
        var stats = {"Recursos":0,"Naves":0,"MO":0,"Item":0,"Mercader":0,"Nada":0,"Aliens":0,"Piratas":0,"Retraso":0,"Vuelta Rapida":0,"Flota Perdida":0};
        var total = 0;

        for (var entry in JSON.parse(localStorage.getItem('Prueba1_NET_profitDB'))){
            //console.log(JSON.parse(localStorage.getItem('Prueba1_NET_profitDB'))[entry].Result);
            stats[JSON.parse(localStorage.getItem('Prueba1_NET_profitDB'))[entry].Result]++;
            total++;
        }
        var chart = new CanvasJS.Chart("chart-container", {
            animationEnabled: false,
            toolTipContent: "{label}({z})/"+total+": <strong>{y}%</strong>",
            title: {
                text: ""
            },
            data: [{
                type: "pie",
                startAngle: 240,
                radius: 90,
                indexLabelFontSize: 12,
                yValueFormatString: "##0.00\"%\"",
                indexLabel: "{label}({z}/"+total+"): {y}",
                dataPoints: [
                    {y: stats['Recursos']/total*100, label: "Recursos",z:stats['Recursos']},
                    {y: stats['Naves']/total*100, label: "Naves",z:stats['Naves']},
                    {y: stats['MO']/total*100, label: "MO",z:stats['MO']},
                    {y: stats['Item']/total*100, label: "Item",z:stats['Item']},
                    {y: stats['Mercader']/total*100, label: "Mercader",z:stats['Mercader']},
                    {y: stats['Nada']/total*100, label: "Nada",z:stats['Nada']},
                    {y: stats['Aliens']/total*100, label: "Aliens",z:stats['Aliens']},
                    {y: stats['Piratas']/total*100, label: "Piratas",z:stats['Piratas']},
                    {y: stats['Retraso']/total*100, label: "Retraso",z:stats['Retraso']},
                    {y: stats['Vuelta Rapida']/total*100, label: "Vuelta Rapida",z:stats['Vuelta Rapida']},
                    {y: stats['Flota Perdida']/total*100, label: "Flota Perdida",z:stats['Flota Perdida']}
                ]
            }]
        });
        chart.render();
        document.getElementsByClassName('canvasjs-chart-credit')[0].style='display: none;';
        document.getElementsByClassName('canvasjs-chart-canvas')[0].style='margin-left:5px;';

    }

})();