Nixian / Nixian Expedition Tracker

// ==UserScript==
// @name         Nixian Expedition Tracker
// @namespace    http://tampermonkey.net/
// @description  Expedition Tracker for Ogame
// @author       Nixian
// @match        http://*/*
// @grant        none
// @include *.ogame.gameforge.com/game/*
// @version 1.0.0.5
// @license MIT
// @updateURL https://openuserjs.org/meta/Nixian/Nixian_Expedition_Tracker.meta.js
// @downloadURL https://openuserjs.org/install/Nixian/Nixian_Expedition_Tracker.user.js
// ==/UserScript==

(function() {
    'use strict';
     //Initialize DB
    var localExpeditionDB;
    if(localStorage.getItem('NET_profitDB')==null){
        var expeditionDB = {"expID":{"Timestamp":"0","Coordinates":"","Result":"","Metal":"0","Crystal":"0","Deuterium":"0","DM":"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('NET_profitDB', JSON.stringify(expeditionDB));
    }
    localExpeditionDB = JSON.parse(localStorage.getItem('NET_profitDB'));
    cleanDB(744);
    createButton();
    var depletion = {"Entry from the communications officers logbook: It seems that no human has been in this part of the galaxy before.":0,"Logbook addition of the communication officer: We nearly had a collision with another expedition fleet. I did not believe that there would be others around here.":1,"Extrait du journal de bord d`un officier de communication : C`est un sentiment assez unique de se savoir le premier à explorer ce coin perdu de la galaxie.":0,"Entry from the communications officers logbook: It feels great to be the first ones traveling through an unexplored sector.":0,"Entry from the communications officers logbook: It seems that this part of the universe has not been explored yet.":0,"Entry from the communications officers logbook: We found debris of ancient space ships. We are not the first ones here.":1,"Extrait du journal de bord d`un officier de communication : Cette partie de l`univers n`a apparemment encore jamais été explorée.":0};
    var messages= {"Bien, nous savons désormais que les anomalies de classe 5 ne causent pas seulement un chaos total dans les systèmes de vos vaisseaux, mais qu`elles ont aussi un effet hallucinogène sur l`équipage. En dehors de cette constatation, cette expédition ne nous a pas apporté grand chose.":"Nothing","Votre module de navigation semble avoir quelques soucis, malgré une phase de test approfondie, il reste un certain nombre de bugs inexplicables et inexpliqués. Non seulement le saut spatial a eu lieu dans la mauvaise direction, mais tout le deutérium a été consommé, et votre flotte n`est arrivée que peu derrière la lune de la planète de départ. Les réservoirs étant vides, la flotte va devoir rentrer avec l`aide des générateurs de secours, causant ainsi un retard important par rapport à la date de retour initialement prévue.":"Delay","Nous avons rencontré un alien assez bizarre qui voyageait à bord d`un petit vaisseau. En échange de quelques simples calculs mathématiques, il nous a cédé un récipient contenant de l`antimatière.":"DM","Un de vos vaisseaux est entré en collision avec un vaisseau inconnu qui a foncé dans votre convoi sans aucune raison apparente. Le vaisseau inconnu a explosé, causant de sérieux dommages à vos vaisseaux. Dès les réparations d`urgence achevées, votre flotte fera demi-tour, l`expédition ne pouvant être continuée avec des vaisseaux dans cet état.":"Delay","Your expedition took gorgeous pictures of a super nova. Nothing new could be obtained from the expedition, but at least there is  good chance to win that \"Best Picture Of The Universe\" competition in next months issue of OGame magazine.":"Nothing","Nous avons dû nous défendre contre des pirates, heureusement qu`ils n`étaient pas trop nombreux.":"Pirate","Votre expédition a découvert des ressources en quantité importantes sur une lune possédant sa propre atmosphère. Vos équipes au sol sont en train de récupérer ces trésors de la nature.":"Resource","Votre expédition a suivi la trace de signaux bizarres. Apparemment, ces signaux provenaient d`une très vielle sonde lancée dans l`espace il y a plusieurs générations pour envoyer un message à des espèces inconnues. La sonde a été récupérée, plusieurs musées de la planète-mère sont déjà intéressés pour l`exposer.":"Nothing","Sur cette planète complètement isolée, nos chercheurs ont découvert des champs de ressources facilement exploitables et ont pû collecter un nombre non négligeable de matières premières.":"Resource", "Notre flotte a découvert un précieux artefact.":"Item", "Notre expédition a découvert une planète que des guerres interminables ont plus ou moins complètement détruite. Nous avons découvert beaucoup d`épaves de vaisseaux dans l`orbite de cette planète. Nos techniciens essaient d`en réparer quelques-unes. Peut-être saurons nous ainsi ce qui s`est passé ici.":"Fleet", "Votre expédition a découvert un champ d`astéroides duquel elle a pû extraire un certain nombre de ressources.":"Resource", "Votre expédition a réussi à collecter de l`antimatière et à la conserver.":"DM", "Le vent solaire causé par une supernova a complètement faussé le saut spatial de votre expédition, il a donc fallu plus de temps pour effectuer les calculs nécessaires au saut pour rentrer à domicile. Cette fausse route est d`ailleurs le seul résultat notable de votre expédition.":"Delay", "Notre expédition a rencontré un vaisseau fantôme qui transportait un peu d`antimatière. Nous ne savons pas ce qui est arrivé à l`équipage de ce vaisseau, mais nous avons réussi à récupérer l`antimatière qui se trouvait à bord.":"DM", "Nous avons découvert une base de pirates abandonnée. Il y a encore des vaisseaux dans les hangars. Nos techniciens sont en train de vérifier si nous pouvons en utiliser certains à nos fins.":"Fleet", "Nous avons retrouvé les restes d`une armada. Les techniciens se sont immédiatement rendus sur les vaisseaux les mieux conservés et essaient de les remettre en état.":"Fleet", "Nous avons trouvé l’épave d’un vaisseau extra-terrestre avec à son bord un récipient contenant de l’antimatière !":"DM", "Une flotte a pris la fuite à notre arrivée. Elle a laissé un objet derrière elle pour faire diversion.":"Item", "Votre flotte d`expédition a eu chaud, elle s`est en effet retrouvée dans le champ de gravité d`une étoile à neutrons et a mis beaucoup de temps à s`en libérer. Ceci a coûté énormément de deutérium et la flotte d`expédition revient donc sans aucun résultat.":"Nothing", "Nous avons retrouvé les restes d`une expédition précédente. Nos techniciens sont en train de vérifier si nous pouvons sauver quelques vaisseaux.":"Fleet", "Nous sommes tombés dans un piège tendu par des pirates de l`espace ! Le combat n`a pû être évité.":"Pirate", "Votre expédition a dû faire face à plusieurs vents de particule. Du coup, les systèmes d`énergie ont surchauffé, causant des pannes importantes sur les systèmes principaux de vos vaisseaux. Les mécaniciens ont pu éviter le pire, cependant votre flotte reviendra avec un retard assez conséquent.":"Delay", "Quelques pirates, apparemment complètement désespérés, ont tenté d`attaquer notre flotte d`expédition.":"Pirate", "Quelqu`un a installé un jeu de stratégie sur les ordinateurs de bord de votre expédition. Du coup, la flotte a fait un long voyage, mais sans résultat aucun.":"Nothing", "La flotte d`expédition a eu une rencontre peu amicale avec une espèce inconnue.":"Alien", "Pour une raison inconnue, le saut spatial a complètement raté, l`expédition a failli se retrouver au centre d`un soleil, ce qui aurait entraîné sa perte. Heureusement, elle s`est retrouvée dans un système solaire connu, mais le voyage du retour dure plus longtemps qu`initialement prévu.":"Delay", "Votre nouveau commandant de bord étant assez courageux, il a utilisé une irrégularité dans l`espace pour accélérer son retour. Il a réussi, mais pour le reste, l`expédition rentre bredouille.":"Speedup", "Votre expédition ne signale aucune particularité dans le secteur exploré. Au retour, votre flotte a été poussée par un vent solaire, lui permettant ainsi de rentrer à bon port avec un peu d`avance.":"Speedup", "Des vaisseaux inconnus ont attaqué la flotte d`expédition, sans avertissement et sans raison !":"Alien", "L`expédition a été attirée par des signaux bizarres et a découvert un astéroïde, dont le noyau contenait de l`antimatière. L`astéroïde se trouve désormais à bord de notre vaisseau et nos chercheurs sont en train d`essayer d`en extraire l`antimatière.":"DM", "Une erreur de calcul de votre officier de navigation vous a fait faire un saut vers une destination complètement erronée, retardant ainsi le retour de votre flotte.":"Delay", "Nous avons capté des messages provenant de pirates fortement alcoolisés. Apparemment, ils veulent nous détrousser.":"Pirate", "Notre expédition a été attaquée par un petit groupe de vaisseaux inconnus !":"Alien", "Un virus informatique a fait planter votre système de navigation peu après que vous ayez quitté votre système solaire. Du coup, votre flotte a tourné en rond, inutile de préciser que cette expédition n`a donc fourni aucun résultat intéressant.":"Nothing", "Votre expédition a trouvé un vieux convoi de transporteurs abandonnés remplis de ressources. Elle a pu en récupérer une partie.":"Resource", "Mis à part quelques petits animaux provenant d`une planète marécageuse jusque là inconnue, votre expédition ne ramène rien de spécial.":"Nothing", "Des barbares primitifs nous attaquent avec des vaisseaux qui n`ont même pas mérité le nom \"vaisseau\", tellement ils sont ridicules. Si ces attaques continuent, nous nous verrons obligés de riposter.":"Pirate", "Votre expédition a fait de superbes images d`une supernova. Mis à part, aucune information vraiment passionnante, mais votre photographe a de bonnes chances de remporter le Prix Meilleur Image de l`univers de l`année.":"Nothing", "Votre expédition a découvert une forteresse stellaire, qui doit être abandonnée depuis très longtemps. Les techniciens ont découvert quelques vaisseaux dans les hangars et essaient de les remettre en marche.":"Fleet", "Votre expédition a découvert... le vide. Pas de météorite, aucune radiation, aucune particule, il n`y avait rien qui aurait pu être utile pour votre expédition.":"Nothing", "Nous n`aurions peut-être pas dû fêter l`anniversaire du capitaine sur cette planète isolée. L`équipage a contracté une espèce de paludisme qui a envoyé une bonne partie de l`équipage à l`infirmerie. Ce manque de personnel inattendu à fait échouer la mission.":"Nothing", "Une irrégularité momentanée dans l`hyperespace a permis à votre expédition de collecter une grande quantité d`antimatière !":"DM", "Un problème de réacteur a failli détruire toute l`expédition. Heureusement que les techniciens ont fait du bon travail et ont pu éviter le pire. La réparation a cependant pris beaucoup de temps et l`expédition revient donc sans résultat aucun.":"Nothing", "Une forme de vie composée d`énergie pure a plongé pendant des jours tous les membres de votre expédition dans une hypnose profonde en diffusant un motif hypnotique sur les écrans des ordinateurs de bord. Lorsque la plupart d`entre eux sont enfin sortis de cet état second, les réserves de deutérium étaient si basses que l`expédition a dû être interrompue.":"Nothing", "Un petit défaut dans les réacteurs de votre flotte l`a fait voyager à une vitesse supérieure à la vitesse normale, ce qui fait que votre flotte rentre avec un peu d`avance sur ce qui était initialement prévu. A part cela, vos chercheurs n`ont rien découvert de spécial.":"Speedup", "Votre flotte d`expédition a fait une rencontre fort peu agréable avec des pirates de l`espace.":"Pirate", "Well, now we know that those red, class 5 anomalies do not only have chaotic effects on the ships navigation systems but also generate massive hallucination on the crew. The expedition didn`t bring anything back.":"Nothing", "Your expedition nearly ran into a neutron stars gravitation field and needed some time to free itself. Because of that a lot of Deuterium was consumed and the expedition fleet had to come back without any results.":"Nothing", "Your expedition discovered a small asteroid from which some resources could be harvested.":"Resource", "A failure in the flagships reactor core nearly destroys the entire expedition fleet. Fortunately the technicians were more than competent and could avoid the worst. The repairs took quite some time and forced the expedition to return without having accomplished its goal.":"Nothing", "A fleeing fleet left an item behind, in order to distract us in aid of their escape.":"Item", "An unexpected back coupling in the energy spools of the engines hastened the expeditions return, it returns home earlier than expected. First reports tell they do not have anything thrilling to account for.":"Speedup", "We found a deserted pirate station. There are some old ships lying in the hangar. Our technicians are figuring out whether some of them are still useful or not.":"Fleet", "Besides some quaint, small pets from a unknown marsh planet, this expedition brings nothing thrilling back from the trip.":"Nothing", "Your navigator made a grave error in his computations that caused the expeditions jump to be miscalculated. Not only did the fleet miss the target completely, but the return trip will take a lot more time than originally planned.":"Delay", "We found the remains of an alien ship. We found a little container with some Dark Matter on a shelf in the cargo hold!":"DM", "On an isolated planetoid we found some easily accessible resources fields and harvested some successfully.":"Resource", "The new and daring commander successfully traveled through an unstable wormhole to shorten the flight back! However, the expedition itself didn`t bring anything new.":"Speedup", "Your expedition fleet followed odd signals for some time. At the end they noticed that those signals where being sent from an old probe which was sent out generations ago to greet foreign species. The probe was saved and some museums of your home planet already voiced their interest.":"Nothing", "Our fleet managed to secure an item from an unmanned craft.":"Item", "Our expedition took over a ghost ship which was transporting a small amount of Dark Matter. We didn`t find any hints of what happened to the original crew of the ship, but our technicians where able to rescue the Dark Matter.":"DM", "Our expedition team came across a strange colony that had been abandoned eons ago. After landing, our crew started to suffer from a high fever caused by an alien virus. It has been learned that this virus wiped out the entire civilization on the planet. Our expedition team is heading home to treat the sickened crew members. Unfortunately we had to abort the mission and we come home empty handed.":"Nothing", "We met an odd alien on the shelf of a small ship who gave us a case with Dark Matter in exchange for some simple mathematical calculations.":"DM", "We came across the remains of a previous expedition! Our technicians will try to get some of the ships to work again.":"Fleet", "Your expedition ran into the shipyards of a colony that was deserted eons ago. In the shipyards hangar they discover some ships that could be salvaged. The technicians are trying to get some of them to fly again.":"Fleet", "Your expedition fleet seems to have flown into territory that belongs to an unknown but really aggressive and warlike alien race.":"Alien", "The expedition was able to capture and store some Dark Matter.":"DM", "Despite the first, very promising scans of this sector, we unfortunately returned empty handed.":"Nothing", "Your expedition took gorgeous pictures of a super nova. Nothing new could be obtained from the expedition, but at least there is good chance to win that \"Best Picture Of The Universe\" competition in next months issue of OGame magazine.":"Nothing", "The expedition reports tough battles against unidentified pirate ships!":"Pirate", "For unknown reasons the expeditions jump went totally wrong. It nearly landed in the heart of a sun. Fortunately it landed in a known system, but the jump back is going to take longer than thought.":"Delay", "A strange computer virus attacked the navigation system shortly after parting our home system. This caused the expedition fleet to fly in circles. Needless to say that the expedition wasn`t really successful.":"Nothing", "We caught some radio transmissions from some drunk pirates. Seems like we will be under attack soon.":"Pirate", "A living being made out of pure energy came aboard and induced all the expedition members into some strange trance, causing them to only gazed at the hypnotizing patterns on the computer screens. When most of them finally snapped out of the hypnotic-like state, the expedition mission needed to be aborted as they had way too little Deuterium.":"Nothing", "Your expeditions doesn`t report any anomalies in the explored sector. But the fleet ran into some solar wind while returning. This resulted in the return trip being expedited. Your expedition returns home a bit earlier.":"Speedup", "Your expedition fleet made contact with a friendly alien race. They announced that they would send a representative with goods to trade to your worlds.":"Merchant", "Your expedition has learnt about the extensive emptiness of space. There was not even one small asteroid or radiation or particle that could have made this expedition interesting.":"Nothing", "We needed to fight some pirates which were, fortunately, only a few.":"Pirate", "Due to a failure in the central computers of the flagship, the expedition mission had to be aborted. Unfortunately as a result of the computer malfunction, the fleet returns home empty handed.":"Nothing", "Some primitive barbarians are attacking us with spaceships that can`t even be named as such. If the fire gets serious we will be forced to fire back.":"Pirate", "Some really desperate space pirates tried to capture our expedition fleet.":"Pirate", "The new navigation module is still buggy. The expeditions jump not only lead them in the wrong direction, but it used all the Deuterium fuel. Fortunately the fleets jump got them close to the departure planets moon. A bit disappointed the expedition now returns without impulse power. The return trip will take longer than expected.":"Delay", "Our expedition was attacked by a small group of unknown ships!":"Alien", "Our fleet has found a valuable artefact.":"Item", "The last transmission we received from the expedition fleet was this magnificent picture of the opening of a black hole.":"Expedition loss", "A core meltdown of the lead ship leads to a chain reaction, which destroys the entire expedition fleet in a spectacular explosion.":"Expedition loss", "Contact with the expedition fleet was suddenly lost. Our scientists are still trying to establish contact, but it seems the fleet is lost forever.":"Expedition loss", "The only thing left from the expedition was the following radio transmission: Zzzrrt Oh no! Krrrzzzzt That zrrrtrzt looks krgzzzz like .. AHH! Krzzzzzzzztzzzz... Transmission terminated":"Expedition loss", "Your expedition picked up an emergency signal during the mission. A mega cargo vessel was caught by a powerful gravitation field generated by a planetoid. After the vessel and cargo was successfully freed, the captain announced that the person who saved them would be their favorite and exclusive client.":"Merchant", "The solar wind of a red giant ruined the expeditions jump and it will take quite some time to calculate the return jump. There was nothing besides the emptiness of space between the stars in that sector. The fleet will return later than expected.":"Delay", "Your expedition went into a sector full of particle storms. This set the energy stores to overload and most of the ships main systems crashed. Your mechanics where able to avoid the worst, but the expedition is going to return with a big delay.":"Delay", "The expedition`s flagship collided with a foreign ship when it jumped into the fleet without any warning. The foreign ship exploded and the damage to the flagship was substantial. The expedition cannot continue in these conditions, and so the fleet will begin to make its way back once the needed repairs have been carried out.":"Delay", "Your expedition ran into an alien invasion fleet and reports heavy fighting!":"Alien", "The recorded signals didn`t come from a foreign being but from a secret pirate base! They were not really surprised by our presence in their sector.":"Pirate", "An unknown species is attacking our expedition!":"Alien", "The connection to our expedition fleet was interrupted for a short time. We could decrypt their last message. They are under heavy attack, the aggressors could not be identified.":"Alien", "That emergency signal that the expedition team followed was in reality an ambush set up by some Star Buccaneers. A fight could not be avoided.":"Pirate", "We had a bit of difficulty pronouncing the dialect of the alien race correctly. Our diplomat accidentally called `Fire!` instead of `Peace!`.":"Alien", "Your expedition had an unpleasant rendezvous with some space pirates.":"Pirate", "Your expedition fleet had an unfriendly first contact with an unknown species.":"Alien", "Some exotic looking ships attacked the expedition fleet without warning!":"Alien", "We ran straight into an ambush set by some Star Buccaneers! A fight couldn`t be avoided.":"Pirate", "Our expedition found a planet which was almost destroyed during a certain chain of wars. There are different ships floating around in the orbit. The technicians are trying to repair some of them. Maybe we will also get information about what happened here.":"Fleet", "On a tiny moon with its own atmosphere your expedition found some huge raw resources storage. The crew on the ground is trying to lift and load that natural treasure.":"Resource", "Your expedition found an ancient, fully loaded but deserted freighter convoy. Some of the resources could be rescued.":"Resource"};
    var localisation = {"Métal":"Metal", "Cristal":"Crystal", "Deutérium":"Deuterium", "Petit transporteur":"Small Cargo", "Grand transporteur":"Large Cargo", "Chasseur léger":"Light Fighter", "Chasseur lourd":"Heavy Fighter", "Croiseur":"Cruiser", "Vaisseau de bataille":"Battleship", "Sonde d`espionnage":"Espionage Probe", "Traqueur":"Battlecruiser", "Éclaireur":"Pathfinder", "Bombardier":"Bomber", "Destructeur":"Destroyer", "Faucheur":"Reaper", "Metal":"Metal", "Crystal":"Crystal", "Deuterium":"Deuterium", "Small Cargo":"Small Cargo", "Large Cargo":"Large Cargo", "Light Fighter":"Light Fighter", "Heavy Fighter":"Heavy Fighter", "Cruiser":"Cruiser", "Battleship":"Battleship", "Espionage Probe":"Espionage Probe", "Battlecruiser":"Battlecruiser", "Pathfinder":"Pathfinder", "Bomber":"Bomber", "Destroyer":"Destroyer", "Reaper":"Reaper"};
    //all the functions to make the script work
    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("Résultat de l`expédition") !== -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(x[i].getElementsByClassName("msg_content")[0].innerHTML.indexOf("Entry") !== -1){depletionlevel=depletion["Entry "+x[i].getElementsByClassName("msg_content")[0].innerHTML.split("Entry")[1].trim()];}
                        if(x[i].getElementsByClassName("msg_content")[0].innerHTML.indexOf("Extrait") !== -1){depletionlevel=depletion["Extrait "+x[i].getElementsByClassName("msg_content")[0].innerHTML.split("Extrait")[1].trim()];}
                        if(x[i].getElementsByClassName("msg_content")[0].innerHTML.indexOf("Logbook") !== -1){depletionlevel=depletion["Logbook "+x[i].getElementsByClassName("msg_content")[0].innerHTML.split("Logbook")[1].trim()];}
console.log("Logbook "+x[i].getElementsByClassName("msg_content")[0].innerHTML.split("Logbook")[1].trim());*/
                        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 "Nothing":
                                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","DM":"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('NET_profitDB', JSON.stringify(localExpeditionDB));
                                reports++;
                                break;
                            case "Fleet":
                                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","DM":"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, '')]]=x[i].getElementsByClassName("msg_content")[0].innerHTML.split("<br>")[split].split(": ")[1];
                                                  }
                                }
                                localStorage.setItem('NET_profitDB', JSON.stringify(localExpeditionDB));
                                reports++;
                                break;
                            case "Resource":
                                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])){
                                       var resource = localisation[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","DM":"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('NET_profitDB', JSON.stringify(localExpeditionDB));
                                reports++;
                                break;
                            case "DM":
                                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];
                                var DMvalue = x[i].getElementsByClassName("msg_content")[0].innerHTML.split("<br>")[2].trim().split(" ")[2];
                                localExpeditionDB[id] = {"Timestamp":time,"Coordinates":coordinates,"Result":result,"Metal":"0","Crystal":"0","Deuterium":"0","DM":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","Item":"Null","Depletion":depletionlevel};
                                localStorage.setItem('NET_profitDB', JSON.stringify(localExpeditionDB));
                                reports++;
                                break;
                            case "Merchant":
                                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","DM":"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('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","DM":"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":itemfind,"Depletion":depletionlevel};
                                localStorage.setItem('NET_profitDB', JSON.stringify(localExpeditionDB));
                                reports++;
                                break;
                            case "Speedup":
                                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","DM":"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('NET_profitDB', JSON.stringify(localExpeditionDB));
                                reports++;
                                break;
                            case "Delay":
                                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","DM":"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('NET_profitDB', JSON.stringify(localExpeditionDB));
                                reports++;
                                break;
                            case "Expedition loss":
                                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","DM":"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('NET_profitDB', JSON.stringify(localExpeditionDB));
                                reports++;
                                break;
                            case "Alien":
                                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","DM":"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('NET_profitDB', JSON.stringify(localExpeditionDB));
                                reports++;
                                break;
                            case "Pirate":
                                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","DM":"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('NET_profitDB', JSON.stringify(localExpeditionDB));
                                reports++;
                                break;
                            default:
                                x[i].getElementsByClassName("msg_content")[0].innerHTML +="<!--ExpoValue --><br><span style='color:rgb(212, 54, 53)'> Unable to match message</span>";
                                console.log("The following result was not known:\n"+x[i].getElementsByClassName("msg_content")[0].innerHTML.split("<br>")[0].trim());
                                noreports++;
                        }
                    }
                }
            }
            document.getElementById('ERAdded').innerHTML=reports;
            document.getElementById('ERTotal').innerHTML=reports+noreports;
            updateFiles();

        }
    }
    function createButton(){
        if (/page=messages/.test(location.href))
        {
            var listElement = document.createElement("li");
            listElement.style="margin:5px;list-style:none;";
//            listElement.innerHTML = '<a class="btn_blue" style="min-width:25px">Exp<span></span></a><div style="text-align:right;position:relative;top:-20px"><span id="" style="font-size:0.8em;color:#00DD00;"><span id="ERAdded">0</span>/<span id="ERTotal">0</span> ER</span> <br/> <span id="" style="font-size:0.8em;color:#ffff00;"></span></div>';
            listElement.innerHTML = '<a class="btn_blue" >Track Expeditions<span></span></a><div style="position:relative;top:-20px;left:150px;"><span id="" style="font-size:0.8em;color:#00DD00;"><span id="ERAdded">0</span>/<span id="ERTotal">0</span> Expedition Reports Tracked</span> <br/> <span id="" style="font-size:0.8em;color:#ffff00;"></span></div>';

            listElement.id = "ExpeditionCheck";
            document.getElementById('buttonz').getElementsByClassName("content")[0].insertBefore(listElement,document.getElementById('buttonz').getElementsByClassName("content")[0].getElementsByTagName("div")[0]);
            //document.getElementById("tabs-nfFavorites").parentNode.insertBefore(listElement,document.getElementById("tabs-nfFavorites").nextSibling)
            document.getElementById('ExpeditionCheck').addEventListener("click", function (event)
                                                                        {
                reportExpeditions();

            }, true);

        }
        //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">NET Export</span></a>';
        menulistElement.id="NETExport";
        document.getElementById('menuTableTools').appendChild(menulistElement);
        //Add attach data to the links
        updateFiles();
        var resultdata = document.createElement("span");
        resultdata.innerHTML = "<h2 style = 'font-size:12px;'>Expedition Stats:</h2>"+processStats()
        resultdata.style="font-size:10px;color:#6f9fc8;text-align:center;position: relative;top: 10px;white-space: nowrap;";
        document.getElementById('myPlanets').appendChild(resultdata);
    }
    function cleanDB(time){
        for (var entryID in localExpeditionDB){
            if(entryID !="expID"){
                if(localExpeditionDB[entryID].timestamp<((new Date().getTime()/1000)- (60 * 60 * time))){
                    deleteExpeditionDBElement(entryID);
                }
            }
            else{

                            if(Object.keys(localExpeditionDB).length>1){
                    deleteExpeditionDBElement(entryID);
                }
            }
        }
    }
    function deleteExpeditionDBElement(id){
        delete localExpeditionDB[id];
        localStorage.setItem('NET_profitDB', JSON.stringify(localExpeditionDB));
    }
    function updateFiles(){
        var dataStr = "data:text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(localExpeditionDB));
        var dlAnchorElem = document.getElementById('downloadAnchorElem');
        dlAnchorElem.setAttribute("href",dataStr);
        dlAnchorElem.setAttribute("download", "ExpeditionExport.json");
        var dataStr2 = "data:text/json;charset=utf-8," + encodeURIComponent(convertCSV(localExpeditionDB));
        var dlAnchorElem2 = document.getElementById('downloadAnchorElem2');
        dlAnchorElem2.setAttribute("href",dataStr2);
        dlAnchorElem2.setAttribute("download", "ExpeditionExport.csv");
    }
    function convertCSV(jsondb){
        var fields;
        var data = "";
        for(var item in jsondb){
            if(fields==null){fields = "Name,"+Object.keys(jsondb[item]);}
            data+=item+","+jsondb[item].Timestamp+","+jsondb[item].Coordinates+","+jsondb[item].Result+","+jsondb[item].Metal+","+jsondb[item].Crystal+","+jsondb[item].Deuterium+","+jsondb[item].DM+","+jsondb[item]['Light Fighter']+","+jsondb[item]['Heavy Fighter']+","+jsondb[item].Cruiser+","+jsondb[item].Battleship+","+jsondb[item].Battlecruiser+","+jsondb[item].Bomber+","+jsondb[item].Destroyer+","+jsondb[item].Reaper+","+jsondb[item]['Espionage Probe']+","+jsondb[item]['Small Cargo']+","+jsondb[item]['Large Cargo']+","+jsondb[item].Pathfinder+","+jsondb[item].Item+","+jsondb[item].Depletion+"\r\n";
        }
        var csv = fields+"\r\n"+data;
        return csv;
    }
    function processStats(){
    var stats = {"Delay":0,"Nothing":0,"Alien":0,"Item":0,"Pirate":0,"DM":0,"Resource":0,"Fleet":0,"Speedup":0,"Merchant":0,"Expedition loss":0};
        var total = 0;

        for (var entry in JSON.parse(localStorage.getItem('NET_profitDB'))){
            //console.log(JSON.parse(localStorage.getItem('NET_profitDB'))[entry].Result);
            stats[JSON.parse(localStorage.getItem('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;

    }
})();