NOTICE: By continued use of this site you understand and agree to the binding Terms of Service and Privacy Policy.
// ==UserScript== // @name OGame Fleet Tool // @namespace de.figgecrew.ogame.fleettool // @include *.ogame*gameforge.com/game/index.php?page=* // @grant GM_getValue // @grant GM_setValue // @grant GM_info // @grant GM_xmlhttpRequest // @require http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js // @description OGame Fleet Tool - Enhance your OGame for faster mining // @version 0.56 // @author the_darkman // @copyright 2010-2020, the_darkman // @license MIT // @history 0.56 refactoring transporter cargo capacity determination // @history 0.55 Tampermonkey support added // @history 0.54 research message; fix recycler not working; fix resource order // @history 0.53 refactoring and icons for chrome // @history 0.52 adapt to OGame 7.x API // @history 0.51 typo fix only // @history 0.50 show fleet times in local time (playing us server in europe) // @history 0.49 vacation mode alliance page fix // @history 0.48 some bugfixes due to new ogame socket system // @history 0.47 https support // @history 0.46 Merged languages into main extention // @history 0.45 On alliance page, on mouse over of member, show player planets // @history 0.44 intenational warriders.de links. Not working for every country // @history 0.43 small cargos as default // @history 0.42 New language detection (URL or OGame XML API based), settings via link, better chrome support // @history 0.41 Bugfix fur Scriptish (https://github.com/scriptish/scriptish/wiki) // @history 0.40 Bugfix for OGame 5.3.0, war-riders.de links in alliance page // @history 0.39 OGame 5.2.0 fix // @history 0.38 loaded resources order fix // @history 0.37 OGame 5.x fix // @history 0.36 Update box has overwritten last "normal" box, in my case the shipyard box // @history 0.35 OGame 4.0.1 ready // @history 0.34 Check for OGame version before making OGame 3.X fix // @history 0.33 OGame3.0.0 ready // @history 0.32 icon beautifying // @history 0.31 fixes icon issues // @history 0.30 fix for the poland server // @history 0.29 Menulabel could now have the homeworld coordinates as text, disableable in the options // @history 0.28 filter fix for Firefox 5 // @history 0.27 new language supported: serbian; digits grouping bug hopefully fixed // @history 0.26 new feature: select debris field as target when recycler are in fleet // @history 0.25 fixes again the "more than 999 cargos" bug. Didn't worked in 0.24 // @history 0.24 fixes more than 999 cargos bug (just replace . with nothing) // @history 0.23 "more cargoes than exist"-bug finally fixed, thanks for the hint vess! // @history 0.22 Double miningmode fixed, better calculation if resource left configured, "more cargoes than exist"-bug fixed // @history 0.21 quick fix for id change of resource input field. Should now work with both id versions // @history 0.20 back button in fleet page works now; Moonlinks should now also contain miningmode (no guarantee for that) // @history 0.19 small bugfix in the language selection // @history 0.18 External languages are now possible. Also a moon could be automatically selected as target. Small cargos could be prefered // @history 0.17 Added greek language. Some more texts are translated (Menu item, update info box). // @history 0.16 Shows the installed script version in the option header // @history 0.15 Added script update info // @history 0.14 Added button to take first planet from list as homeplanet // @history 0.13 Added check if coordinates are well formed. // @history 0.12 Complete rewritten option feature. SUpports now multi universe and multi server use. // @history 0.11 Added ne Menu-item for selecting transport or normal fleet pages // @history 0.10 Replaced mission-button click, so it is even faster // @history 0.09 Added option to preselect homeworld coords // @history 0.08 Added option to leave a special amount of each resource on the planet // @history 0.07 Option button now also visible when no fleet at planet exists. // @history 0.06 this version uses now jQuery for checking if a mission is selected. // @history 0.05 small bugfix. You know, one feature comes in, and with it a few bugs :-) // @history 0.04 Don't do something when preselection of mission was done. Config for no mission text added. // @history 0.03 Added function to select transport as default mission and take all resources. Customizable througth option button in fleet page 1 // @history 0.02 Added all universes on all server // @history 0.01 Initial release // ==/UserScript== (function() { 'use strict'; if (typeof jQuery !== "undefined") { main ($); } else { add_jQuery (main, "1.7.2"); } function add_jQuery (callbackFn, jqVersion) { var _jqVersion = jqVersion || "1.7.2"; var D = document; var targ = D.body || D.documentElement; var scriptNode = D.createElement ('script'); scriptNode.src = '//ajax.googleapis.com/ajax/libs/jquery/' + _jqVersion + '/jquery.min.js' ; scriptNode.addEventListener ("load", function () { var scriptNode = D.createElement ("script"); scriptNode.textContent = 'var gm_jQuery = jQuery.noConflict (true);\n' + '(' + callbackFn.toString () + ')(gm_jQuery);' ; targ.appendChild (scriptNode); }, false); targ.appendChild (scriptNode); } function main ($) { if(document.location.href.indexOf('page=standalone') != -1) { console.log('no valid fleet tool page'); return; } // needed since chrome does not support MetaData parsing var version="0.56"; var chrome = typeof GM_xmlhttpRequest == 'undefined'; if (chrome) { GM_getValue = function(name, defaultValue) { var value = localStorage.getItem(name); if (!value) return defaultValue; var type = value[0]; value = value.substring(1); switch (type) { case 'b': return value == 'true'; case 'n': return Number(value); default: return value; } } GM_setValue = function(name, value) { value = (typeof value)[0] + value; localStorage.setItem(name, value); } GM_xmlhttpRequest=function(obj) { var request=new XMLHttpRequest(); request.onreadystatechange=function() { if(obj.onreadystatechange) { obj.onreadystatechange(request); }; if(request.readyState==4 && obj.onload) { obj.onload(request); } } request.onerror=function() { if(obj.onerror) { obj.onerror(request); } } try { request.open(obj.method,obj.url,true); } catch(e) { if(obj.onerror) { obj.onerror( {readyState:4,responseHeaders:'',responseText:'',responseXML:'',status:403,statusText:'Forbidden'} ); }; return; } if(obj.headers) { for(var name in obj.headers) { request.setRequestHeader(name,obj.headers[name]); } } request.send(obj.data); return request; } } // getting meta data from source dom, like universe, language and ogame version var get_meta_data=function(){var domain,server,universe;var language=$('meta[name="ogame-language"]').attr('content');var version=$('meta[name="ogame-version"]').attr('content');var uni=$('meta[name="ogame-universe"]').attr('content');var session=$('meta[name="ogame-session"]').attr('content');var fields=uni.match(/([a-z0-9]*)-([a-z]{2}).ogame.gameforge.com/);if(fields){domain=fields[0];language=fields[2];var regexp=/[0-9]+/;universe=regexp.exec(fields[1])[0];server=language+universe}return{'domain':domain,'server':server,'universe':universe,'language':language,'session':session,'version':version}} // prefix build from universe number, server id and language, needed as prefix for storing preferences var uni_server_prefix = ''; var data = get_meta_data(); var lang = "EN"; if(data != undefined) { lang = data.language.toUpperCase(); if(lang === "US") lang = "EN"; uni_server_prefix = data.server + '_uni' + data.universe + '_' + data.language + '_'; } var strings = new Array(); strings = { 'DE' : { transport:"Transport", fleet_tool:"Fleet Tool", fleet_tool_settings:"Einstellungen", homeworld:"Heimatplanet Koordinaten", homeworldhelp:"Hier kannst Du die Koordinaten Deines Heimatplaneten eintragen. Diese werden dann automatisch im Transport-menü vorbelegt. Klicke auf den obigen Button um den ersten Planeten aus der rechten Liste als Deinen Heimatplaneten zu nehmen.", homeworld_btn:"Koordinaten holen", label_coords:"Koordinaten als Menülabel", moon:"Nimm den Mond des Heimatplaneten als Ziel", wrong_coords_format:"Die Koordinaten des Heimatplaneten entsprechen nicht der Form 2:123:5, bitte korrigieren.", transportasmission:"Transport Mission", useallresources:"Alle Resourcen einladen", metalleft:"Verbleibendes Metall", crystalleft:"Verbleibendes Kristall", deuteriumleft:"Verbleibendes Deuterium", prefered_small_cargo:"Kleine Transporter bevorzugen", select_debris_on_recycler:"Trümmerfeld als Ziel wenn Recycler in der Flotte sind", table_source:"Start", table_target:"Ziel", new_version_available:"Neue Version {0} verfügbar", install_tooltip:"Script aktualisieren", install_version:"Version installieren", visit_script_page:"Info Seite besuchen", alliance_links:"Links zu war-riders.de auf Allianzseite anlegen", fleet_times_local:"Flotten Zeiten in lokaler Zeit anzeigen"}, 'EN' : { transport:"Transport", fleet_tool:"Fleet tool", fleet_tool_settings:"settings", homeworld:"Homeworld coords" , homeworldhelp:"This option allows you to set the coordinates of your homeplanet. If you set this option, the coordinates are inserted automatically at the transport menu. Click the button above to take the first planet in the list on the right as your homeworld.", homeworld_btn:"Get coords", label_coords:"Homeworld coordinates are menu caption", moon:"Set moon as target on homeworld", wrong_coords_format:"The coordinates are not well formed. Should be like 2:123:5. Please try again.", transportasmission:"Transport mission", useallresources:"Use all resources", metalleft:"Metal leave", crystalleft:"Crystal leave", deuteriumleft:"Deut leave", prefered_small_cargo:"Use small cargos as prefered cargos", select_debris_on_recycler:"Select debrisfield as target if recyler is in fleet", table_source:"Source", table_target:"Target", new_version_available:"New version {0} available", install_tooltip:"Update script to new version", install_version:"install new version", visit_script_page:"view script page", alliance_links:"Create links for members on alliance page to war-riders.de", fleet_times_local:"Show fleet arrival times in local time"}, 'GR' : { transport:"Μεταφορά", fleet_tool:"Εργαλείο στόλου", fleet_tool_settings:"settings", homeworld:"Αρχικές συντεταγμένες" , homeworldhelp:"Αυτή η επιλογή σου επιτρέπει να επιλέξεις τις συντεταγμένες του αρχικού πλανήτη σου. Αν θέσεις αυτή την επιλογή, οι συντεταγμένες εισέρχονται αυτόματα στο μενού των μεταφορών. Κάνε κλικ στο παραπάνω κουμπί ώστε να ο πρώτος πλανήτης που εμφανίζεται στα δεξιά, να επιλεχθεί ως ο αρχικός σου.", homeworld_btn:"Προσθήκη συντεταγμένων", label_coords:"Homeworld coordinates are menu caption", moon:"Θέσε το φεγγάρι ως στόχο στις αρχικές συντεταγμένες", wrong_coords_format:"Οι συντεταγμένες δεν είναι σωστά διαμορφομένες. Θα έπρεπε να είναι για παράδειγμα 2:123:5. Προσπάθησε ξανά.", transportasmission:"Αποστολή μεταφοράς", useallresources:"Χρησιμοποίησε όλους τους πόρους", metalleft:"Άφησε μέταλλο", crystalleft:"Άφησε Κρύσταλλο", deuteriumleft:"Άφησε Δευτέριο", prefered_small_cargo:"Χρησιμοποίησε μικρά μεταγωγικά για τις μεταφορές", select_debris_on_recycler:"Select debrisfield as target if recyler is in fleet", table_source:"Source", table_target:"Target", new_version_available:"Η νέα έκδοση {0} είναι διαθέσιμη", install_tooltip:"Ενημέρωση του script στη νεότερη έκδοση", install_version:"Εγκατέστησε τη νέα έκδοση", visit_script_page:"Μεταφορά στη σελιδα του script", alliance_links:"Create links for members on alliance page to war-riders.de", fleet_times_local:"Show fleet arrival times in local time"}, 'BG' : { transport:"Транспорт", fleet_tool:"Fleet tool", fleet_tool_settings:"settings", homeworld:"Координати на целта" , homeworldhelp:"Тази опция Ви позволява да прочетете координатите на Родната планета. Ако изберете тази опция, координатите ще бъдат въвеждани автоматично като цел на транспорта. Цъкнете горния бутон, за да се вземат координатите на първата планета в списъка планети вдясно.", homeworld_btn:"Прочитане на координатите", label_coords:"Използване на координатите на целта като надпис на бутона", moon:"Установяване типа на целта да бъде луна", wrong_coords_format:"Неправилен формат на координатите. Трябва да е Г:ССС:П. Моля, опитайте пак.", transportasmission:"Транспортирай", useallresources:"Натоварване на всички ресурси", metalleft:"Да остане Метал", crystalleft:"Да останат Кристали", deuteriumleft:"Да остане Деутериум", prefered_small_cargo:"Да се използват предимно Малки Транспортьори вместо Големи", select_debris_on_recycler:"Избиране на поле отломки като цел, ако флотът съдържа рециклатори", table_source:"Изходна точка", table_target:"Цел", new_version_available:"Има нова версия {0}", install_tooltip:"Обновяване на скрипта", install_version:"Инсталиране на новата версия", visit_script_page:"Главна страница на скрипта", alliance_links:"Create links for members on alliance page to war-riders.de", fleet_times_local:"Show fleet arrival times in local time"}, 'FR' : { transport:"Transport", fleet_tool:"Fleet tool", fleet_tool_settings:"settings", homeworld:"Coordonnées de votre Planète Mère(ou destination désirée)" , homeworldhelp:"Cette option vous permet de régler les coordonnées de votre planète mère. Ensuite elles seront automatiquement inscrites dans le menu transport comme lieu d'arrivée. Cliquer sur le bouton ci dessus pour prendre votre première planète en tant que planète Cible.", homeworld_btn:"Régler Coordonnées", label_coords:"Coordonnées planète mère comme sous titre ", moon:"Choisir lune comme coordonnées de votre planète", wrong_coords_format:"Les coordonnées ne sont pas correctes. Elles doivent être dans un format tel que celui ci ---> 2:123:5. Réessayer SVP.", transportasmission:"Mission Transport", useallresources:"Utiliser toutes les ressources", metalleft:"Métal à laisser", crystalleft:"Cristal à laisser", deuteriumleft:"Deut à laisser", prefered_small_cargo:"Préférer les petits transporteurs", select_debris_on_recycler:"Sélectionner le CDR comme objectif de recycleur(s) si présents dans la flotte", table_source:"Source", table_target:"Cible", new_version_available:"Nouvelle version {0} disponible", install_tooltip:"Mise à Jour du script", install_version:"Installer la nouvelle version", visit_script_page:"Voir la page du script", alliance_links:"Create links for members on alliance page to war-riders.de", fleet_times_local:"Show fleet arrival times in local time"}, 'ES' : { transport:"Transportar", fleet_tool:"Herramienta de Flota", fleet_tool_settings:"settings", homeworld:"Planeta principal" , homeworldhelp:"Esta opcion te permite configurar las coordenadas de tu planeta principal. Si eliges esta opción, las coordenadas son insertadas automaticamente en el menú de transporte. Clickear en el botón de arriba para seleccionar el primer planeta de la lista a la derecha, como tu planeta principal.", homeworld_btn:"Obtener coordenadas", label_coords:"Coordenadas como una etiqueta de menú", moon:"Configurar la luna de tu planeta principal como objetivo", wrong_coords_format:"Las coordenadas no estan bien escritas. Deberia ser como 2:123:5. Por favor, intenta nuevamente.", transportasmission:"Mision de transporte", useallresources:"Usar todos los recursos", metalleft:"Dejar Metal", crystalleft:"Dejar Cristal", deuteriumleft:"Dejar Deuterio", prefered_small_cargo:"Usar naves pequeñas por defecto", select_debris_on_recycler:"Selecciona Reciclar campo de escombros, si hay recicladores en la flota", table_source:"Lugar de despegue", table_target:"Destino", new_version_available:"Nueva version {0} disponible", install_tooltip:"Actualizar script a la nueva version", install_version:"Instalar nueva version", visit_script_page:"Ver la pagina del script", alliance_links:"Create links for members on alliance page to war-riders.de", fleet_times_local:"Show fleet arrival times in local time"}, 'PT' : { transport:"Transportar", fleet_tool:"Ferramenta de Frota", fleet_tool_settings:"settings", homeworld:"Planeta de descarga" , homeworldhelp:"Esta opção permite configurar as coordenadas do planeta de descarga. Se definires esta opção, as coordenadas são inseridas automaticamente na página de frota. Clique no botão de cima para seleccionar o primeiro planeta da lista à direita, como teu planeta de descarga.", homeworld_btn:"Obter coordenadas", label_coords:"Homeworld coordinates are menu caption", moon:"Configurar a lua como destino", wrong_coords_format:"As coordenadas não estão bem escritas. Deveria ser tipo 1:234:5. Por favor, tente novamente.", transportasmission:"Missão a Transportar", useallresources:"Usar todos os recursos", metalleft:"Deixar o Metal", crystalleft:"Deixar o Cristal", deuteriumleft:"Deixar o Deutério", prefered_small_cargo:"Usar cargueiros pequenos por defeito", select_debris_on_recycler:"Seleccionar campo de destroços como alvo se houver recicladores na frota", table_source:"Fonte", table_target:"Alvo", new_version_available:"Nova versão {0} disponível", install_tooltip:"Actualizar o script para a nova versão", install_version:"Instalar nova versão", visit_script_page:"Ver a página do script", alliance_links:"Crie links para membros na página da aliança para war-riders.de", fleet_times_local:"Mostrar horários de chegada da frota no horário local"}, 'HU' : { transport:"Szállítás", fleet_tool:"Flotta Kiegészítő", fleet_tool_settings:"settings", homeworld:"Az anyabolygójának a koordinátái" , homeworldhelp:"Ez az opció lehetővé teszi az anyabolygója koordinátáinak beállítását. Ha beállítja itt a koordinátákat, akkor azok automatikusan beíródnak a szállítás menűbe. Kattintson a fenti gombra hogy a jobb oldali bolygólistában levő első bolygót állítsa be anyabolygónak.", homeworld_btn:"Koordináták beolvasása", label_coords:"Homeworld coordinates are menu caption", moon:"Legyen a hold a célpont az anyabolygón", wrong_coords_format:"A koordináták formátuma hibás. Helyes formátum 2:123:5. Kérem próbálja újra.", transportasmission:"Szállítás küldetés", useallresources:"Az összes nyersanyagot", metalleft:"Fémből maradjon", crystalleft:"Kristályból maradjon", deuteriumleft:"Deutériumból maradjon", prefered_small_cargo:"Kis szállítók legyenek a preferált szállállítók: ", select_debris_on_recycler:"Törmelékmező legyen a célpont, ha a flottában vannak szemetesek", table_source:"Kiindulópont", table_target:"Célpont", new_version_available:"Elérhető új verzió: {0}", install_tooltip:"Frissítés az új verzióra", install_version:"Új verzió telepítése", visit_script_page:"A script honlapja", alliance_links:"Create links for members on alliance page to war-riders.de", fleet_times_local:"Show fleet arrival times in local time"}, 'RS' : { transport:"Transport", fleet_tool:"Kontrola flote", fleet_tool_settings:"settings", homeworld:"Koordinate matične planete" , homeworldhelp:"Ova opcija vam omogućava da postavite koordinate svoje matične planete. Ako odaberete ovu opciju, koordinate se automatski unose na meniju za transport. Kliknite gore da biste prvu planetu na listi zdesna postavili za svoju matičnu planetu.", homeworld_btn:"Učitaj koordinate", label_coords:"Homeworld coordinates are menu caption", moon:"Postavi mesec kao cilj na matičnoj planeti", wrong_coords_format:"Koordinate nisu ispravno formirane. Treba da izgledaju ovako - 2:123:5. Molimo, pokušajte ponovo.", transportasmission:"Transportna misija", useallresources:"Upotrebi sve resurse", metalleft:"Ostaje od metala", crystalleft:"Ostaje od kristala", deuteriumleft:"Ostaje od deuterijuma", prefered_small_cargo:"Koristi male transportere kao osnovno transportno sredstvo", select_debris_on_recycler:"Odaberi otpadno polje kao metu ukoliko u floti postoji brod za reciklažu", table_source:"Polazište", table_target:"Cilj", new_version_available:"Nova verzija {0} na raspolaganju", install_tooltip:"Unapredi skript u novu verziju", install_version:"instaliraj novu verziju", visit_script_page:"pogledaj stranicu sa skriptom", alliance_links:"Create links for members on alliance page to war-riders.de", fleet_times_local:"Show fleet arrival times in local time"}, 'NL' : { transport:"Transport", fleet_tool:"Vloot Tool", fleet_tool_settings:"settings", homeworld:"Doelplaneet Coördinaten", homeworldhelp:"Met deze optie kan je een Doelplaneet instellen. Als je deze optie gebruikt zal bij het verzenden van een vloot automatisch de geselecteerde planeet als bestemming ingesteld worden. Klik op de knop om de eerste planeet in het menu in te stellen als Doelplaneet.", homeworld_btn:"Coördinaten Verkrijgen", label_coords:"Doelplaneet coördinaten zijn menu-item", moon:"Stel de maan van je Doelplaneet in als doel", wrong_coords_format:"De coördinaten van je Doelplaneet zijn niet correct, vul ze in als 2:123:5, zonder []. Probeer het opnieuw.", transportasmission:"Transport Missie", useallresources:"Alle grondstoffen inladen", metalleft:"Metaal dat achter moet blijven", crystalleft:"Kristal dat achter moet blijven", deuteriumleft:"Deuterium dat achter moet blijven", prefered_small_cargo:"Bij voorkeur Klein Vrachtschip gebruiken als transporter", select_debris_on_recycler:"Stel doel in op Puinveld als er een recycler meegaat", table_source:"Bron", table_target:"Doel", new_version_available:"Nieuwe versie beschikbaar {0}", install_tooltip:"Script updaten", install_version:"Nieuwe versie installeren", visit_script_page:"Scriptpagina bezoeken", alliance_links:"Create links for members on alliance page to war-riders.de", fleet_times_local:"Show fleet arrival times in local time"}, 'HR' : { transport:"Transport", fleet_tool:"Kontrola flote", fleet_tool_settings:"settings", homeworld:"Koordinate matiènog planeta" , homeworldhelp:"Ova opcija vam omoguæava da postavite koordinate svog matiènog planeta. Ako odaberete ovu opciju, koordinate se automatski unose na izborniku za transport. Kliknite gore da biste prvi planet na listi zdesna postavili za svoj matièni planet.", homeworld_btn:"Uèitaj koordinate", label_coords:"Homeworld coordinates are menu caption", moon:"Postavi mjesec kao cilj na matiènom planetu", wrong_coords_format:"Koordinate nisu ispravno formirane. Trebaju izgledati ovako - 2:123:5. Molimo, pokušajte ponovo.", transportasmission:"Transportna misija", useallresources:"Upotrijebi sve resurse", metalleft:"Ostaje od metala", crystalleft:"Ostaje od kristala", deuteriumleft:"Ostaje od deuterija", prefered_small_cargo:"Koristi male transportere kao osnovno transportno sredstvo", select_debris_on_recycler:"Odaberi otpadno polje kao metu ukoliko u floti postoji brod za reciklažu", table_source:"Polazište", table_target:"Cilj", new_version_available:"Nova verzija {0} na raspolaganju", install_tooltip:"Unaprijedi skript u novu verziju", install_version:"instaliraj novu verziju", visit_script_page:"pogledaj stranicu sa skriptom", alliance_links:"Create links for members on alliance page to war-riders.de", fleet_times_local:"Show fleet arrival times in local time"}, 'RU' : { transport:"Транспорт", fleet_tool:"Fleet tool", fleet_tool_settings:"settings", homeworld:"Координаты Главки" , homeworldhelp:"Эта опция позволяет установить координаты главной планеты. Если вы включите эту опцию координаты будут автоматически устанавливаться в меню транспорта. Кликните на кнопке выше, чтобы взять первую планету из списка справа, как главную.", homeworld_btn:"Взять координаты", label_coords:"Homeworld coordinates are menu caption", moon:"Установить луну, как цель ", wrong_coords_format:"Координаты в неправильном формате. Должно быть 2:123:5. Исправьте.", transportasmission:"Миссия Транспорт", useallresources:"Использовать все ресурсы", metalleft:"Металл оставить", crystalleft:"Кристалл оставить", deuteriumleft:"Дейт оставить", prefered_small_cargo:"Использовать малые транспорты как основные", select_debris_on_recycler:"Выбирать поле обломков, как цель если в флоте есть переработчик", table_source:"Источник", table_target:"Цель", new_version_available:"Доступна новая версия", install_tooltip:"Обновить скрипт на новую версию", install_version:"установить новую версию", visit_script_page:"открыть страницу скрипта", alliance_links:"Create links for members on alliance page to war-riders.de", fleet_times_local:"Show fleet arrival times in local time"} } // get Gameversion for several style and use switches var session_param=""; var newLinkClass=""; var ogame_version=data.version; var matchStr = ogame_version.match("^[0-9]"); // only major version is needed if(matchStr) { var iMatch = parseInt(matchStr); if(iMatch < 3){session_param = "&session=" + data.session;} if(iMatch >= 5){newLinkClass="true"} } var useWindow = window; // Greasemonkey and chrome uses different windows // look for external languages var external_lang; try { external_lang = unsafeWindow.fleet_tool_lang; useWindow = unsafeWindow; } catch(e) { external_lang = window.fleet_tool_lang; } if(external_lang) { for(var exLang in external_lang) { strings[exLang] = external_lang[exLang]; } } // fallback if language is not available if(strings[lang] == undefined) { lang = 'EN'; } //console.log('lang='+ lang + '; prefix=' + uni_server_prefix); var disable_update_box = function() { GM_setValue('show_update_box', false); } var show_update_box=function(version_text){var html='<div class="header"><h3>'+strings[lang]['fleet_tool']+'</h3></div><div class="content"><table class="construction" cellpadding="0" cellspacing="0"><tbody><tr><td colspan="2" class="idle">';html+=strings[lang]['new_version_available'].format(version_text)+'</td></tr><tr><td colspan="2" class="idle"><a id="update_script_link" class="tipsStandard" title="'+strings[lang]['install_tooltip']+' '+version_text+'" href="http://userscripts.org/scripts/source/78537.user.js">'+strings[lang]['install_version']+'</a><br>';html+='<a class="tipsStandard" title="'+strings[lang]['visit_script_page']+'" href="http://userscripts.org/scripts/show/78537" target="_blank">'+strings[lang]['visit_script_page']+'</a>';html+='</td></tr></tbody></table></div></div><div class="footer"></div>';var div_box=document.createElement('div');div_box.setAttribute('class','content-box-s');var found=false;var $content_boxes=$('div.content-box-s');if($content_boxes.length!=0){$content_boxes.each(function(){if($(this).next().length==0||!($(this).next().is('.content-box-s'))||$(this).next().is('.clearfloat')){$(this).after(div_box);found=true}})}if(found==true){$('div.content-box-s:last').html(html);document.getElementById('update_script_link').addEventListener("click",disable_update_box,false)}} // Update-check var show_box = GM_getValue('show_update_box', false); if(!chrome && document.location.href.indexOf('page=overview')!=-1&&(show_box||(parseInt(GM_getValue('last_update','0'))+86400000<=(new Date().getTime())))){GM_setValue('last_update',new Date().getTime()+'');var url='http://userscripts.org/scripts/source/78537.meta.js';try{GM_xmlhttpRequest({method:'GET',headers:{'Cache-Control':'no-cache'},url:url,onload:function(response){var meta,remote_version,local_version,version_text;meta=response.responseText;version_text=/@version\s*(.*?)\s*$/m.exec(meta)[1];remote_version=parseFloat(version_text);local_version=parseFloat(version);if(local_version!=-1){if(remote_version>local_version){GM_setValue('show_update_box',true);show_update_box(version_text)}}}})}catch(e){console.log(e)}} var on_get_coords=function(){var $_links = newLinkClass == "" ? $('.planetlink.tipsStandard') : $('.planetlink.tooltipRight.js_hideTipOnMobile');var planet=$_links.attr('title');var i=planet.indexOf('[');var j=planet.indexOf(']');$("input[name='"+uni_server_prefix+'homeworld'+"']").val(planet.substring(i+1,j));$("input[name='"+uni_server_prefix+'homeworld'+"']").focus()} var get=function(key,default_val){var unique_key=uni_server_prefix+key;var value=GM_getValue(unique_key);if(typeof(value) !== 'undefined'){return value}else{try{var host_suffix=host.toLowerCase()+'_';var s=unique_key.indexOf(host_suffix)+host_suffix.length;key=unique_key.substring(s,unique_key.length);value=GM_getValue(key);if(typeof(value) !== 'undefined'){return value}else{return default_val}}catch(e){return default_val}}} var store_option=function(){var value;if($(this).attr('type')=='checkbox'){value=$(this).is(':checked')}else{value=$(this).val()}if(value&&$(this).attr('name')==uni_server_prefix+'homeworld'){if(check_coords(value)){GM_setValue($(this).attr('name'),value)}else{alert(strings[lang]['wrong_coords_format'])}}else{GM_setValue($(this).attr('name'),value)}} var create_option=function(type,parent,id){var div_wrap=document.createElement('div');div_wrap.setAttribute('class','fieldwrapper');parent.appendChild(div_wrap);var label_wrap=document.createElement('label');label_wrap.setAttribute('class','styled textBeefy');label_wrap.appendChild(document.createTextNode(strings[lang][id]));div_wrap.appendChild(label_wrap);var div_field=document.createElement('div');div_field.setAttribute('class','thefield');var stored_info;var input=document.createElement('input');if(type=='text'){stored_info=get(id,'');input.setAttribute('value',stored_info?stored_info:'');if(id=='homeworld'){input.setAttribute('class','textInput');input.setAttribute('style','width: 80px;')}else{input.setAttribute('class','textInput w150')}input.setAttribute('size','20')}else{stored_info=(id=='moon'||id=='label_coords')?get(id,false):get(id,true);if(stored_info){input.setAttributeNode(document.createAttribute('checked'))}}input.setAttribute('name',uni_server_prefix+id);input.setAttribute('type',type);if(type=='text'){input.addEventListener("blur",store_option,false)}else{input.addEventListener("change",store_option,false)}div_field.appendChild(input);var btn;if(id=='homeworld'){btn=document.createElement('input');btn.setAttribute('type','button');btn.setAttribute('class','btn_blue');btn.setAttribute('name','homeworld_btn');btn.setAttribute('value',strings[lang]['homeworld_btn']);btn.addEventListener("click",on_get_coords,false)}div_wrap.appendChild(div_field);if(btn){var div_center=document.createElement('div');div_center.setAttribute('class','textCenter');div_center.appendChild(btn);parent.appendChild(div_center)}} var create_help_text=function(parent,text_key){var div_wrap=document.createElement('div');div_wrap.setAttribute('class','fieldwrapper');parent.appendChild(div_wrap);var p=document.createElement('p');div_wrap.appendChild(p);var text=strings[lang][text_key];if(!text){text="?"+text_key+"?"}p.appendChild(document.createTextNode(text))} var check_coords=function(value){return value.match(/^\d+:\d+:\d+$/)!=null} var showLangs=function(parent){var div_wrap=document.createElement('div');div_wrap.setAttribute('id','languagediv');div_wrap.setAttribute('class','fieldwrapper');parent.appendChild(div_wrap);var html='<p>All loaded languages:<ul>';for(var lang in strings){html+='<li><span style="color: #6F9FC8; width: 150px; font-weight: 700;">'+lang+'</span>';html+='<ul>';for(var text in strings[lang]){html+='<li style="margin-left: 25px;">'+text+': '+strings[lang][text]}html+='</ul>'}html+='</ul></p>';$('#languagediv').html(html)} var collectResourceAmounts=function(){var metaltext=$('#resources_metal').text().replace(/\D+/g,'');var crystaltext=$('#resources_crystal').text().replace(/\D+/g,'');var deuteriumtext=$('#resources_deuterium').text().replace(/\D+/g,'');var metal_amount=Math.max(parseInt(metaltext)-get('metalleft',0),0);var crystal_amount=Math.max(parseInt(crystaltext)-get('crystalleft',0),0);var deut_amount=Math.max(parseInt(deuteriumtext)-get('deuteriumleft',0),0);var sum=metal_amount+crystal_amount+deut_amount;var result={'metal':metal_amount,'crystal':crystal_amount,'deuterium':deut_amount,'sum':sum};console.log('resources: sum='+result.sum+'; metal='+result.metal+'; crystal='+result.crystal+'; deuterium='+result.deuterium);return result} /* BEGIN new feature, show player planets in alliance page */ var base_api_url= location.protocol + '//' +location.host + "/api/"; var user_list_url = base_api_url + 'players.xml'; var user_detail_url = base_api_url + 'playerData.xml?id='; var user_layer=$("<div></div>").attr('id','user_detail_layer').css({'display':'none','color':'white','z-index':'15','background-color':'#848484','border':'1px solid #6f9fc8','padding':'5px','position':'absolute','width':'300px','-webkit-border-radius':'5px','-moz-border-radius':'5px','border-radius':'5px'});$('body').append(user_layer); useWindow.showPlayerData=function(element,playerId){var $element=$(element);$.get(user_detail_url+playerId,function(xml){var $xml=$(xml);var html='<p style=\"margin-bottom: 3px;text-align:center;\">Players planets (from API)</p><ul>';$xml.find('planet').each(function(){html+='<li style=\"margin-bottom: 2px; border-bottom: 1px dashed #000000;\"><div style=\"float: left;\">'+$(this).attr('name')+'</div><div style=\"text-align: right;\">'+$(this).attr('coords')+'<div></li>'});html+='</ul>';$('#user_detail_layer').html(html).css({left:$element.offset().left,top:$element.offset().top+20,}).show()},"xml")} useWindow.hideUserLayer=function(){$('#user_detail_layer').html('').hide()} useWindow.showUserLayer=function(element,playername){$.get(user_list_url,function(xml){var $xml=$(xml);playername=playername.replace(' ','\\ ');$xml.find('player[name='+playername+']').each(function(){var id=$(this).attr('id');useWindow.showPlayerData(element,id)})},"xml")} /* END */ if(document.location.href.indexOf("page=ingame&component=research") !== -1) { // store current level let level = parseInt(document.querySelector('.hyperspaceTechnology .level').getAttribute('data-value')); console.log(`will store current level ${level}`); var unique_key=uni_server_prefix+"hyperspace_level"; GM_setValue(unique_key, level); } if(document.location.href.indexOf('page=alliance') != -1 && get('alliance_links', true)) { // On alliance page create link for each member to the war-riders.de page var timeoutFunction=function() {$("#form_assignRank > table > tbody > tr").each(function(i) {var text = $(this).find("td:first").text();var uname= text.replace(/\(.*\)/, '').trim();var language=$("meta[name='ogame-language']").attr('content');var universe=$("meta[name='ogame-universe']").attr('content');var link=encodeURI("http://www.war-riders.de/?lang="+language+"&uni="+universe+"&page=search&post=1&type=player&name="+uname);var aref='<a href="'+link+'" target="_blank" onmouseover="showUserLayer(this, \''+uname+'\')" onmouseout="hideUserLayer()">'+text+'</a>'; $(this).find("td:first").html(aref) })} useWindow.setTimeout(timeoutFunction, 1500); } // we only do something when mining-mode is activated, so someone clicked on the "transport" menu item var mining_mode = document.location.href.indexOf('&miningmode=on') != -1; if(-1!=document.location.href.indexOf("component=preferences")){ // add our options var $four=$("#four"),div_header=document.createElement("div");div_header.setAttribute("class","category fieldwrapper alt bar");$four.append(div_header);var label=document.createElement("label");label.setAttribute("class","styled textBeefy");label.setAttribute("data-element","fleettool");label.appendChild(document.createTextNode(" OGame "+strings[lang].fleet_tool+" v"+version));div_header.appendChild(label);var div_content=document.createElement("div");div_content.setAttribute("class","group bborder");div_content.setAttribute("style","display: none;");create_option("text",div_content,"homeworld");create_help_text(div_content,"homeworldhelp");create_option("checkbox",div_content,"label_coords");create_option("checkbox",div_content,"moon");create_option("checkbox",div_content,"transportasmission");create_option("checkbox",div_content,"useallresources");create_option("text",div_content,"metalleft");create_option("text",div_content,"crystalleft");create_option("text",div_content,"deuteriumleft");create_option("checkbox",div_content,"prefered_small_cargo");create_option("checkbox",div_content,"select_debris_on_recycler");create_option("checkbox",div_content,"alliance_links");create_option("checkbox",div_content,"fleet_times_local");var div_wrap2 = document.createElement("div");div_wrap2.setAttribute("class", "textCenter");var a = document.createElement("a");a.setAttribute("href", "https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=KWXJYVWUXGSUC&source=url");a.setAttribute("target", "_blank");var i = document.createElement("img");i.setAttribute("src", "https://www.paypal.com/en_US/i/btn/btn_donate_SM.gif");i.setAttribute("alt", "PayPal - The safer, easier way to pay online!");a.appendChild(i);div_wrap2.appendChild(a);div_content.appendChild(div_wrap2);$four.append(div_content);get("show_all_lang",!1)&&showLangs(div_content);mining_mode&&window.setTimeout("$('#tabExtended').click(); $('#four div.group:nth-child(2)').css('display', 'none'); $('#four div.group:nth-child(6)').css('display', 'block')",250) initPreferences(); // re-reads the sections and makes it collapsable }; var fleet_icon = 'https://gf1.geo.gfsrv.net/cdn32/17802a56c19935ccbc4ef329c0c867.gif' var fleet_icon_hover = 'https://gf1.geo.gfsrv.net/cdn70/fca390c937463b33442bcb7b255d1f.gif'; var fleet_icon_movement = 'https://gf1.geo.gfsrv.net/cdn41/3306093fa95dd704a1420b192110e5.gif'; var $fleetItem = $('#menuTable li:nth-child(8)'); var $fleetIconItem = $fleetItem.find('.menuImage'); var fleet_item = $fleetItem[0]; var fleet_icon_item = $fleetIconItem[0]; var movement = false; try { // stuff to create and set the "transport" menu item var menu_item = document.createElement('li'); menu_item.appendChild(document.createTextNode('')); var span_item = document.createElement('span'); span_item.setAttribute('class', 'menu_icon'); menu_item.appendChild(span_item); var a_item = document.createElement('a'); a_item.setAttribute('href', 'index.php?page=ingame&component=preferences&miningmode=on'+session_param); a_item.setAttribute('class', 'tooltipRight js_hideTipOnMobile'); a_item.setAttribute('title', strings[lang]['fleet_tool'] +' '+ strings[lang]['fleet_tool_settings']); a_item.setAttribute('target', '_self'); span_item.appendChild(a_item); var img_item = document.createElement('img'); img_item.setAttribute('class', 'mouseSwitch'); img_item.setAttribute('src', movement ? fleet_icon_movement : fleet_icon); img_item.setAttribute('rel', fleet_icon_hover); img_item.setAttribute('height', '29'); img_item.setAttribute('width', '38'); a_item.appendChild(img_item); var a_item2 = document.createElement('a'); var style; if(mining_mode) { style = 'menubutton selected'; // deselect the normal fleet button $('.menubutton.selected').removeClass('selected'); img_item.setAttribute('src', movement ? fleet_icon_movement : fleet_icon_hover); fleet_icon_item.setAttribute('src', movement ? fleet_icon_movement : fleet_icon); fleet_icon_item.setAttribute('rel', fleet_icon_hover); // set the mining attribute to all planetlinks on the rigth side // for changing planets and stay on transport page var $_links=newLinkClass==""?$('.planetlink.tipsStandard'):$('.planetlink.tooltipRight.js_hideTipOnMobile');$_links.each(function(i,e){var href=$(this).attr('href');href+='&miningmode=on';$(this).attr('href',href)});var $_moonLinks=newLinkClass==""?$('.moonlink.tipsStandard'):$('.moonlink');$_moonLinks.each(function(i,e){var href=$(this).attr('href');href+='&miningmode=on';$(this).attr('href',href)}); } else { style = 'menubutton'; } a_item2.setAttribute('class', style); a_item2.setAttribute('href', 'index.php?page=ingame&component=fleetdispatch&miningmode=on'+session_param); a_item2.setAttribute('accesskey', ''); a_item2.setAttribute('target', '_self'); menu_item.appendChild(a_item2); var span_item2 = document.createElement('span'); span_item2.setAttribute('class', 'textlabel'); var transport_text = strings[lang]['transport']; if(get('label_coords', false) == true && get('homeworld', '') != '') { transport_text = get('homeworld', transport_text); } if(get('moon', false)) { transport_text += ' M'; } span_item2.appendChild(document.createTextNode(transport_text)); a_item2.appendChild(span_item2); fleet_item.parentNode.insertBefore(menu_item, fleet_item.nextSibling); } catch(e) { console.log(e);} if (mining_mode && document.location.href.indexOf ('page=fleet1') != -1) { // change the action of the form so our miningmode is carried to page fleet 2 $("form[name='shipsChosen']").each(function(i, e){ var action = $(this).attr('action'); action += '&miningmode=on'; $(this).attr('action', action); }); } // only do something when no mission was selected; will now be handled from MutationObserver if (document.location.href.indexOf ('component=fleetdispatch') != -1 && $("input[name='mission']").val() == 0) { function fillFleet1Page() { if(!mining_mode) return; if(get('transportasmission', true) == true) { // set mission to transport $("input[name='mission']").val(3); } try { // check how many small and big transporters are there let ktElem = $('li[data-technology=202] span.amount'); let gtElem = $('li[data-technology=203] span.amount'); var ktCount = parseInt(ktElem.attr('data-value')); var gtCount = parseInt(gtElem.attr('data-value')); } catch(err) { // there is no fleet return; } var sc_pref = get('prefered_small_cargo', true); let shipData202 = fleetDispatcher.fleetHelper.shipsData["202"]; let shipData203 = fleetDispatcher.fleetHelper.shipsData["203"]; let smCapacity = shipData202.cargoCapacity; let gtCapacity = shipData203.cargoCapacity; console.log(`capacities: ${shipData202.name}: ${smCapacity}; ${shipData203.name}: ${gtCapacity}`); var amounts = collectResourceAmounts(); // calculate the sum and how much big transporters are needed var metal_amount = amounts.metal; var crystal_amount = amounts.crystal; var deut_amount = amounts.deuterium; var sum = amounts.sum; var diff = 0; var kt = sc_pref ? Math.round(sum / smCapacity) : 0; var gt = !(sc_pref) ? Math.round(sum / gtCapacity) : 0; if(sc_pref) { if((kt * smCapacity) < sum) { kt = kt +1; } // if we don't have so many small transporters ... if((kt - ktCount) > 0) { kt = ktCount; diff = sum - (ktCount * smCapacity); // .. try to use big transportes also if there are one if(gtCount && gtCount > 0) { gt = Math.round(diff / gtCapacity); if((gt * gtCapacity) < diff) { gt = gt + 1; } // check if so many cargos are available if(gt > gtCount) { gt = gtCount; } } } } else { if((gt * gtCapacity) < sum) { gt = gt +1; } // if we don't have so many big transporters ... if((gt - gtCount) > 0) { gt = gtCount; diff = sum - (gtCount * gtCapacity); // .. try to use small transportes also if there are one if(ktCount && ktCount > 0) { kt = Math.round(diff / smCapacity); if((kt * smCapacity) < diff) { kt = kt + 1; } // check if so many cargos are available if(kt > ktCount) { kt = ktCount; } } } } // when we have to use small transporters, fill the input field if( kt !== 0) { let ts = $('input[name="transporterSmall"]'); ts.val(kt); ts.change(); fleetDispatcher.selectShip(202, kt) console.log(`added ${kt} transporter small`); } // same for big transporters if( gt !== 0) { let tl = $('input[name="transporterLarge"]'); tl.val(gt); tl.change(); fleetDispatcher.selectShip(203, gt) console.log(`added ${gt} transporter large`); } if(kt !== 0 || gt !== 0) fleetDispatcher.refreshFleet1(); } function fillFleet2Page() { if(mining_mode) { $("form[name='details']").each(function(i, e){ var action = $(this).attr('action'); action += '&miningmode=on'; $(this).attr('action', action); }); try { if(unsafeWindow.returnLink) { unsafeWindow.returnLink += '&miningmode=on'; } } catch(e) { if(window.returnLink) { window.returnLink += '&miningmode=on'; } } // if homeworld is set in options, preselect galaxy, system and position var homeworld = get('homeworld', ''); var moon = get('moon', false); if(homeworld && homeworld != '') { var coords = homeworld.split(':'); var type = 1; // planet if(moon) { type = 3; } fleetDispatcher.setTargetPlanet({type: type, galaxy: coords[0], system: coords[1], position: coords[2]}) fleetDispatcher.refreshFleet2(); } } else { if(get('select_debris_on_recycler', true)) { // select debris field as target if minimum one recycler is in the fleet let count = 0; fleetDispatcher.shipsToSend.forEach(ts => {if(ts.id === 209)count = ts.number}) if((count > 0)) { fleetDispatcher.setTargetType(2); fleetDispatcher.updateTarget(); fleetDispatcher.refresh(); } } } } function fillFleet3Page() { if(mining_mode) { // if there was no mission selected or mission is transport, do it let selectedMission = $("input[name='mission']").val(); if(selectedMission === "0" || selectedMission === "3") { // stay in transport mode, even after sending fleet $("form[name='sendForm']").each(function(i, e){ var action = $(this).attr('action'); action += '&miningmode=on'; $(this).attr('action', action); }); try { if(unsafeWindow.returnLink) { unsafeWindow.returnLink += '&miningmode=on'; } } catch(e) { if(window.returnLink) { window.returnLink += '&miningmode=on'; } } // set mission to transport if(selectedMission === "0") document.querySelector('#missionButton3').click() if(get('useallresources', true) == true) { // collecting some resource values var amounts = collectResourceAmounts(); formatNumber($("#deuterium"), amounts.deuterium); formatNumber($("#crystal"), amounts.crystal); formatNumber($("#metal"), amounts.metal); fleetDispatcher.updateDeuterium(); fleetDispatcher.updateCrystal(); fleetDispatcher.updateMetal(); fleetDispatcher.refresh(); fleetDispatcher.refreshFleet3(); } } } else { // try to leave resources on planet if set in options } } var fleetObserver = new MutationObserver(function(mutations) { mutations.forEach(function(mutationRecord) { // check for fleet page elements let fleet1 = document.querySelector('#fleet1'); let fleet2 = document.querySelector('#fleet2'); let fleet3 = document.querySelector('#fleet3'); if(mutationRecord.target !== null && (mutationRecord.target === fleet1 || mutationRecord.target === fleet2 || mutationRecord.target === fleet3)) { let pages = [fleet1, fleet2, fleet3]; // active page has display = block or "" let active = pages.filter(p=>{ return p !== null && (p.style.display === 'block' || p.style.display === '')}); // should be only one or none if(active.length > 0 && mutationRecord.target.id === active[0].id) { console.log(`active fleet page is ${active[0].id}`) if(fleet1.id === active[0].id) fillFleet1Page(); else if(fleet2.id === active[0].id) fillFleet2Page(); else if(fleet3.id === active[0].id) fillFleet3Page(); } } }); }); let fleetdispatchcomponent = document.querySelector('#fleetdispatchcomponent'); fleetObserver.observe(fleetdispatchcomponent, { attributes: true, attributeFilter: ['style'], subtree: true }); // initially fill fleet page 1; then observer is active fillFleet1Page(); } if (document.referrer.indexOf('page=fleet3&miningmode=on') != -1) { /* * after sending fleet we are automatically on the movement page. * we want to send fleet fast from multiple planets, so change target to * transport in the small planet list on the right (fleet1 and miningmode). */ console.log('referrer is fleet3 and miningmode'); $_links=$('.smallplanet > a');$_links.each(function(i,e){var href=$(this).attr('href') + '&miningmode=on';$(this).attr('href',href)}); } /* * When the eventlist is opened, change all fleet arrival times to local time, if configured. */ if(get('fleet_times_local', false)) { console.log('show local times for fleet'); var t2=function() { $('.eventFleet').each( function(index){ var time = $(this).attr('data-arrival-time')*1000; var timeStr = new Date(time).toLocaleTimeString(); $($(this).find('.arrivalTime')[0]).text(timeStr); } );} var observer = new MutationObserver(function(mutations, observer) { t2() }); var eventListContent = document.getElementById('eventboxContent'); observer.observe(eventListContent, { childList: true }); } } })();