C&C "NOVAGAMA" Ultimate Pack Continued

Ultimate Packing script for C&C Tiberium Alliance Web Game.

当前为 2014-06-05 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name C&C "NOVAGAMA" Ultimate Pack Continued
  3. // @namespace https://prodgame*.alliances.commandandconquer.com/*/index.aspx*
  4. // @include https://prodgame*.alliances.commandandconquer.com/*/index.aspx*
  5. // @grant GM_log
  6. // @grant GM_setValue
  7. // @grant GM_getValue
  8. // @grant GM_registerMenuCommand
  9. // @grant GM_xmlhttpRequest
  10. // @grant GM_updatingEnabled
  11. // @grant unsafeWindow
  12. // @description Ultimate Packing script for C&C Tiberium Alliance Web Game.
  13. */
  14. // @version 4.0
  15. // @icon http://s3.amazonaws.com/uso_ss/icon/165888/large.png
  16. // @author dark_atticus, continued by TFlipp
  17. // ==/UserScript==
  18.  
  19. // type: /chelp in any text box and hit <enter> for a list of commands
  20.  
  21. /***********************************************************************************
  22. Infernal Wrapper
  23. ***********************************************************************************/
  24.  
  25. (function () {
  26. var CCTAWrapper_main = function () {
  27. try {
  28. _log = function () {
  29. if (typeof console != 'undefined') console.log(arguments);
  30. else if (window.opera) opera.postError(arguments);
  31. else GM_log(arguments);
  32. }
  33.  
  34. function createCCTAWrapper() {
  35. console.log('CCTAWrapper loaded');
  36. _log('wrapper loading' + PerforceChangelist);
  37. System = $I;
  38. SharedLib = $I;
  39. var strFunction;
  40. // SharedLib.Combat.CbtSimulation.prototype.DoStep
  41. for (var x in $I) {
  42. for (var key in $I[x].prototype) {
  43. if ($I[x].prototype.hasOwnProperty(key) && typeof($I[x].prototype[key]) === 'function') { // reduced iterations from 20K to 12K
  44. strFunction = $I[x].prototype[key].toString();
  45. if (strFunction.indexOf("().l;var b;for (var d = 0 ; d < c.length ; d++){b = c[d];if((b.") > -1) {
  46. $I[x].prototype.DoStep = $I[x].prototype[key];
  47. console.log("SharedLib.Combat.CbtSimulation.prototype.DoStep = $I." + x + ".prototype." + key);
  48. break;
  49. }
  50. }
  51. }
  52. }
  53.  
  54. // ClientLib.Data.CityRepair.prototype.CanRepair
  55. for (var key in ClientLib.Data.CityRepair.prototype) {
  56. if (typeof ClientLib.Data.CityRepair.prototype[key] === 'function') {
  57. strFunction = ClientLib.Data.CityRepair.prototype[key].toString();
  58. if (strFunction.indexOf("DefenseSetup") > -1 && strFunction.indexOf("DamagedEntity") > -1) { // order important to reduce iterations
  59. ClientLib.Data.CityRepair.prototype.CanRepair = ClientLib.Data.CityRepair.prototype[key];
  60. console.log("ClientLib.Data.CityRepair.prototype.CanRepair = ClientLib.Data.CityRepair.prototype." + key);
  61. break;
  62. }
  63. }
  64. }
  65.  
  66. // ClientLib.Data.CityRepair.prototype.UpdateCachedFullRepairAllCost
  67. for (var key in ClientLib.Data.CityRepair.prototype) {
  68. if (typeof ClientLib.Data.CityRepair.prototype[key] === 'function') {
  69. strFunction = ClientLib.Data.CityRepair.prototype[key].toString();
  70. if (strFunction.indexOf("Type==7") > -1 && strFunction.indexOf("var a=0;if") > -1) { // order important to reduce iterations
  71. ClientLib.Data.CityRepair.prototype.UpdateCachedFullRepairAllCost = ClientLib.Data.CityRepair.prototype[key];
  72. console.log("ClientLib.Data.CityRepair.prototype.UpdateCachedFullRepairAllCost = ClientLib.Data.CityRepair.prototype." + key);
  73. break;
  74. }
  75. }
  76. }
  77.  
  78. // ClientLib.Data.CityUnits.prototype.get_OffenseUnits
  79. strFunction = ClientLib.Data.CityUnits.prototype.HasUnitMdbId.toString();
  80. var searchString = "for (var b in {d:this.";
  81. var startPos = strFunction.indexOf(searchString) + searchString.length;
  82. var fn_name = strFunction.slice(startPos, startPos + 6);
  83. strFunction = "var $createHelper;return this." + fn_name + ";";
  84. var fn = Function('', strFunction);
  85. ClientLib.Data.CityUnits.prototype.get_OffenseUnits = fn;
  86. console.log("ClientLib.Data.CityUnits.prototype.get_OffenseUnits = function(){var $createHelper;return this." + fn_name + ";}");
  87.  
  88. // ClientLib.Data.CityUnits.prototype.get_DefenseUnits
  89. strFunction = ClientLib.Data.CityUnits.prototype.HasUnitMdbId.toString();
  90. searchString = "for (var c in {d:this.";
  91. startPos = strFunction.indexOf(searchString) + searchString.length;
  92. fn_name = strFunction.slice(startPos, startPos + 6);
  93. strFunction = "var $createHelper;return this." + fn_name + ";";
  94. fn = Function('', strFunction);
  95. ClientLib.Data.CityUnits.prototype.get_DefenseUnits = fn;
  96. console.log("ClientLib.Data.CityUnits.prototype.get_DefenseUnits = function(){var $createHelper;return this." + fn_name + ";}");
  97.  
  98. // ClientLib.Vis.Battleground.Battleground.prototype.get_Simulation
  99. strFunction = ClientLib.Vis.Battleground.Battleground.prototype.StartBattle.toString();
  100. searchString = "=0;for(var a=0; (a<9); a++){this.";
  101. startPos = strFunction.indexOf(searchString) + searchString.length;
  102. fn_name = strFunction.slice(startPos, startPos + 6);
  103. strFunction = "return this." + fn_name + ";";
  104. fn = Function('', strFunction);
  105. ClientLib.Vis.Battleground.Battleground.prototype.get_Simulation = fn;
  106. console.log("ClientLib.Vis.Battleground.Battleground.prototype.get_Simulation = function(){return this." + fn_name + ";}");
  107.  
  108. // GetNerfBoostModifier
  109. if (typeof ClientLib.Vis.Battleground.Battleground.prototype.GetNerfAndBoostModifier == 'undefined') ClientLib.Vis.Battleground.Battleground.prototype.GetNerfAndBoostModifier = ClientLib.Base.Util.GetNerfAndBoostModifier;
  110.  
  111. _log('wrapper loaded');
  112. }
  113. } catch (e) {
  114. console.log("createCCTAWrapper: ", e);
  115. }
  116.  
  117. function CCTAWrapper_checkIfLoaded() {
  118. try {
  119. if (typeof qx !== 'undefined') {
  120. createCCTAWrapper();
  121. } else {
  122. window.setTimeout(CCTAWrapper_checkIfLoaded, 1000);
  123. }
  124. } catch (e) {
  125. CCTAWrapper_IsInstalled = false;
  126. console.log("CCTAWrapper_checkIfLoaded: ", e);
  127. }
  128. }
  129.  
  130. if (/commandandconquer\.com/i.test(document.domain)) {
  131. window.setTimeout(CCTAWrapper_checkIfLoaded, 1000);
  132. }
  133. }
  134.  
  135. try {
  136. var CCTAWrapper = document.createElement("script");
  137. CCTAWrapper.innerHTML = "var CCTAWrapper_IsInstalled = true; (" + CCTAWrapper_main.toString() + ")();";
  138. CCTAWrapper.type = "text/javascript";
  139. if (/commandandconquer\.com/i.test(document.domain)) {
  140. document.getElementsByTagName("head")[0].appendChild(CCTAWrapper);
  141. }
  142. } catch (e) {
  143. console.log("CCTAWrapper: init error: ", e);
  144. }
  145. })();
  146.  
  147. /***********************************************************************************
  148. Tiberium Alliances Zoom
  149. ***********************************************************************************/
  150.  
  151. (function (){
  152. var tazoom_main = function() {
  153. function initialize() {
  154. console.log("Zoom Loaded");
  155. var zoomMin = 1.0; // Larger number means able to zoom in closer.
  156. var zoomMax = 0.2; // Smaller number means able to zoom out further.
  157. var zoomInc = 0.05; // Larger number for faster zooming, Smaller number for slower zooming.
  158. webfrontend.gui.BackgroundArea.prototype.onHotKeyPress = function(be) {
  159. if(!this.active || be.getTarget() != this.mapContainer)
  160. return;
  161. var bh = be.getKeyIdentifier();
  162. var bf = ClientLib.Vis.VisMain.GetInstance();
  163. switch(bh) {
  164. case "+":
  165. var bg = bf.get_Region().get_ZoomFactor() + zoomInc;
  166. bf.get_Region().set_ZoomFactor(Math.min(zoomMin, Math.max(zoomMax, bg)));
  167. break;
  168. case "-":
  169. var bg = bf.get_Region().get_ZoomFactor() - zoomInc;
  170. bf.get_Region().set_ZoomFactor(Math.min(zoomMin, Math.max(zoomMax, bg)));
  171. break;
  172. }
  173. this.closeCityInfo();
  174. this.closeCityList();
  175. }
  176.  
  177. var backgroundArea = qx.core.Init.getApplication().getBackgroundArea();
  178. qx.bom.Element.removeListener(backgroundArea.mapContainer, "mousewheel", backgroundArea._onMouseWheel, backgroundArea);
  179. qx.bom.Element.removeListener(backgroundArea.mapBlocker, "mousewheel", backgroundArea._onMouseWheel, backgroundArea);
  180. webfrontend.gui.BackgroundArea.prototype._onMouseWheel = function(e) {
  181. if(this.activeSceneView == null)
  182. return;
  183. var bz = e.getWheelDelta();
  184. var by = this.activeSceneView.get_ZoomFactor();
  185. by += bz > 0 ? -zoomInc : zoomInc;
  186. by = Math.min(zoomMin, Math.max(zoomMax, by));
  187. this.activeSceneView.set_ZoomFactor(by);
  188. e.stop();
  189. }
  190. qx.bom.Element.addListener(backgroundArea.mapContainer, "mousewheel", backgroundArea._onMouseWheel, backgroundArea);
  191. qx.bom.Element.addListener(backgroundArea.mapBlocker, "mousewheel", backgroundArea._onMouseWheel, backgroundArea);
  192. }
  193. function tazoom_checkIfLoaded() {
  194. try {
  195. if (typeof qx != 'undefined') {
  196. a = qx.core.Init.getApplication(); // application
  197. mb = qx.core.Init.getApplication().getMenuBar();
  198. if (a && mb) {
  199. initialize();
  200. } else
  201. window.setTimeout(tazoom_checkIfLoaded, 1000);
  202. } else {
  203. window.setTimeout(tazoom_checkIfLoaded, 1000);
  204. }
  205. } catch (e) {
  206. if (typeof console != 'undefined') console.log(e);
  207. else if (window.opera) opera.postError(e);
  208. else GM_log(e);
  209. }
  210. }
  211. if (/commandandconquer\.com/i.test(document.domain)) {
  212. window.setTimeout(tazoom_checkIfLoaded, 1000);
  213. }
  214. }
  215.  
  216. // injecting, because there seem to be problems when creating game interface with unsafeWindow
  217. var tazoomScript = document.createElement("script");
  218. tazoomScript.innerHTML = "(" + tazoom_main.toString() + ")();";
  219. tazoomScript.type = "text/javascript";
  220. if (/commandandconquer\.com/i.test(document.domain)) {
  221. document.getElementsByTagName("head")[0].appendChild(tazoomScript);
  222. }
  223. })();
  224.  
  225. /***********************************************************************************
  226. ADDON Basescanner
  227. ***********************************************************************************/
  228. // ==UserScript==
  229. // @name Maelstrom ADDON Basescanner
  230. // @namespace http*://prodgame*.alliances.commandandconquer.com/*/index.aspx*
  231. // @description Maelstrom ADDON Basescanner
  232. // @include http*://prodgame*.alliances.commandandconquer.com/*/index.aspx*
  233. // @version 1.8.4
  234. // @author BlinDManX
  235. // @grant none
  236. // @copyright 2012+, Claus Neumann
  237. // @license CC BY-NC-ND 3.0 - http://creativecommons.org/licenses/by-nc-nd/3.0/
  238. // @updateURL https://userscripts.org/scripts/source/145168.meta.js
  239. // @downloadURL https://userscripts.org/scripts/source/145168.user.js
  240. // ==/UserScript==
  241. (function(){var b=function(){var e=["__msbs_version","1.8.4","Addons.BaseScannerGUI","singleton","Window","window","ui","base","Addons.BaseScannerGUI ","info","T","getInstance","Language","setWidth","setHeight","setContentPadding","setShowMinimize","setShowMaximize","setShowClose","setResizable","setAllowMaximize","setAllowMinimize","setAllowClose","setShowStatusbar","setDecorator","setPadding","layout","setLayout","src","stats","http://goo.gl/DrJ2x","ZE","removeAll","add","setData","ZL","Addons.BaseScannerGUI.construct: ","debug","img","createElement","setCaption","isVisible","close","updateCityCache","Cache","MaelstromTools","ZC","Cities","form","Basescanner_LastCityID","getserver","LocalStorage","get_Id","Object","setSelection","open","moveTo","MaelstromTools.DefaultObject.openWindow: ","log","model","table","ID","LoadState","City","get","Location","Level","Tiberium","Crystal","Dollar","Research","Crystalfields","Tiberiumfields","Building state","Defense state","CP","Def.HP/Off.HP","Sum Tib+Cry+Cre","(Tib+Cry+Cre)/CP","CY","DF","base set up at","setColumns","YY","get_Player","MainData","Data","ZN","setColumnVisibilityButtonVisible","setColumnWidth","Basescanner_ColWidth_2","Basescanner_ColWidth_3","Basescanner_ColWidth_4","Basescanner_ColWidth_5","Basescanner_ColWidth_6","Basescanner_ColWidth_7","Basescanner_ColWidth_8","Basescanner_ColWidth_9","Basescanner_ColWidth_10","Basescanner_ColWidth_11","Basescanner_ColWidth_12","Basescanner_ColWidth_13","Basescanner_ColWidth_14","Basescanner_ColWidth_15","Basescanner_ColWidth_16","Basescanner_ColWidth_17","Basescanner_ColWidth_18","Basescanner_ColWidth_19","getTableColumnModel","getColumnCount","Basescanner_Column_","setColumnVisible","Statics","images","headerrenderer","setHeaderCellRenderer","FA","set","cellrenderer","setDataCellRenderer","cellDblclick","BaseScannerGUI","addListener","widthChanged","col","getData","newWidth","Basescanner_ColWidth_","setserver","Addons.BaseScannerGUI.FI: ","getRow","length",":","split","VisMain","Vis","getValue","ZK","getApplication","Init","core","closeCityInfo","getBackgroundArea","pavmCombatSetupDefense","PlayerAreaViewMode","setView","getPlayArea","get_CurrentOwnCity","get_Cities","set_CurrentTargetBaseId","get_CityArmyFormationsManager","Addons.BaseScannerGUI FB error: ","Scan","setLabel","ZG","ZH","format","util","setGroupingUsed","setMaximumFractionDigits","abs","floor","k","M","G","container","setMargin","changeSelection","CP Limit","white","basic","ZQ","Basescanner_Cplimiter","","min Level","Basescanner_minLevel","1","ZY","Player","setTextColor","Basescanner_Show0","setValue","changeValue","Bases","Basescanner_Show1","Outpost","Basescanner_Show2","Camp","Basescanner_Show3","execute","solid","blue","decoration","ZV","red","ZU","green","ZX","center","YZ","clear Cache","ZZ","Only center on World","ZJ","7 "," 5 ","6 "," 6 ","5 "," 7 ","ZD","Get Layouts","BaseScannerLayout","Addons","BaseScanner Layout","openWindow","setEnabled","ZB","Loader","gui","ZR","getColumnName","isColumnVisible","index","ZO","+","ZI","addAfter","-","remove","right","setAlignX","ZF","Addons.BaseScannerGUI.createOptions: ","\x3Ca href=\x22https://sites.google.com/site/blindmanxdonate\x22 target=\x22_blank\x22\x3ESupport Development of BlinDManX Addons\x3C/a\x3E","ZP","getModel","getSelection","get_PosX","get_PosY","set_CurrentCityId","ZT","prototype","WorldObjectCity","WorldSector","$ctor","ClientLib.Data.WorldSector.WorldObjectCity","getLevel","Error - ClientLib.Data.WorldSector.WorldObjectCity.Level undefined","error","getID","Error - ClientLib.Data.WorldSector.WorldObjectCity.ID undefined","WorldObjectNPCBase","ClientLib.Data.WorldSector.WorldObjectNPCBase","Error - ClientLib.Data.WorldSector.WorldObjectNPCBase.Level undefined","Error - ClientLib.Data.WorldSector.WorldObjectNPCBase.ID undefined","WorldObjectNPCCamp","ClientLib.Data.WorldSector.WorldObjectNPCCamp","Error - ClientLib.Data.WorldSector.WorldObjectNPCCamp.Level undefined","getCampType","Error - ClientLib.Data.WorldSector.WorldObjectNPCCamp.CampType undefined","Error - ClientLib.Data.WorldSector.WorldObjectNPCCamp.ID undefined","Pause","window.Addons.BaseScannerGUI.getInstance().FJ()","setTimeout","window.Addons.BaseScannerGUI.getInstance().FG()","/","ZM","get_World","Scanning from: ","get_Name","get_MaxAttackDistance","get_Server","sqrt","Type","function","push","sortByColumn","name","DR01D","Maelstrom_Basescanner FJ error: ","data null: ","warn","data[i] null: ","get_PlayerId","get_AllianceId","get_IsGhostMode","get_CityUnitsData","d","get_Buildings","get_DefenseUnits","get_OffenseUnits","EResourceType","Base","Gold","ResearchPoints","ZA","get_Health","get_MdbUnitId","get_CoordY","HPRecord"," finish","countlastidchecked"," on "," removed (GetBuildingsConditionInPercent == 0)","splice"," removed (IsGhostMode)","lastid"," removed (found no data)","MaelstromTools_Basescanner getResources","ZS","define","Class","Addons.BaseScannerLayout","Addons.BaseScannerLayout ","ZW","Addons.BaseScannerLayout.construct: ","Addons.BaseScannerLayout.openWindow: ","ZE null: ","\x3Ctable border=\x222\x22 cellspacing=\x220\x22 cellpadding=\x220\x22\x3E"," - ","\x3Ctr\x3E\x3Ctd colspan=\x229\x22\x3E\x3Cfont color=\x22#FFF\x22\x3E","\x3C/font\x3E\x3C/td\x3E\x3C/tr\x3E","\x3Ctr\x3E","\x3Cimg width=\x2214\x22 height=\x2214\x22 src=\x22","\x22\x3E","Emptypixels","\x3Ctd\x3E","\x3C/td\x3E","\x3C/tr\x3E","\x3C/table\x3E","#303030","cid","click","setReturnValue","Addons.LocalStorage","static","undefined","isSupported","stringify","Addons.LocalStorage.setglobal: ","isdefined","parse","Addons.LocalStorage.getglobal: ","object","LocalStorage data from server not null, but not object","LocalStorage data from server not null, but parsererror","Addons.LocalStorage.setserver: ","isdefineddata","Addons.LocalStorage.getserver: ","Addons.Language","main","hasOwnProperty","Translate Added ","Addons.Language.addtranslateobj main not define","getLocale","Manager","locale","_","Addons.Language.get "," not translate for locale ","qx.ui.table.cellrenderer.Replace","Default","Function","value","getReplaceMap","getReplaceFunction","escape","String","bom","Maelstrom_Basescanner initalisiert","Point","Position","addtranslateobj","BaseScanner Overview","Basescanner Übersicht","Visão geral do scanner de base","Aperçu du scanner de base","Scannen","Esquadrinhar","Balayer","Lage","localização","Emplacement","Spieler","Jogador","Joueur","Camp,Outpost","Lager,Vorposten","Camp,posto avançado","Camp,avant-poste","Lager","Vorposten","posto avançado","avant-poste","Layout da Base de Dados de Scanner","Mise scanner de base","Show Layouts","Layouts anzeigen","Mostrar Layouts","Voir Layouts","Gebäudezustand","construção do Estado","construction de l\x27État","Verteidigungszustand","de Defesa do Estado","défense de l\x27Etat","KP","KP begrenzen","CP limitar","CP limiter","min. Level","nível mínimo","niveau minimum","Cache leeren","limpar cache","vider le cache","Nur auf Welt zentrieren","Único centro no Mundial","Seul centre sur World","Basis errichtbar","base de configurar a","mis en place à la base","Infantry","Infanterie","Infantaria","Vehicle","Fahrzeuge","Veículos","Vehicule","Aircraft","Flugzeuge","Aeronaves","Aviation","Tibério","Kristalle","Cristal","Power","Strom","Potência","Energie","Credits","Créditos","Crédit","Forschung","Investigação","Recherche","-----","--","FileManager","File","BaseScanner","ui/icons/icon_item.png","createNewImage","ui/menues/main_menu/misc_empty_pixel.png","version ","desktopPosition","createDesktopButton"," version ","addToMainMenu","AddonMainMenu","Basescanner","ALT+B","Wrapper","Count","get_HitpointsPercent","MaelstromTools_Basescanner getResourcesPart","replace","match","Error - ","not found","MaelstromTools_Basescanner_checkIfLoaded: ","domain","test"];window[e[0]]=e[1];function j(){qx[e[312]][e[311]](e[2],{type:e[3],extend:qx[e[6]][e[5]][e[4]],construct:function(){try{this[e[7]](arguments);console[e[9]](e[8]+window[e[0]]);this[e[10]]=Addons[e[12]][e[11]]();this[e[13]](820);this[e[14]](400);this[e[15]](10);this[e[16]](true);this[e[17]](true);this[e[18]](true);this[e[19]](true);this[e[20]](true);this[e[21]](true);this[e[22]](true);this[e[23]](false);this[e[24]](null);this[e[25]](5);this[e[27]](new qx[e[6]][e[26]].VBox(3));this[e[29]][e[28]]=e[30];this.FI();this.FH();this.FD();if(this[e[31]]==null){this[e[31]]=[];}this[e[25]](0);this[e[32]]();this[e[33]](this.ZF);this[e[33]](this.ZN);this[e[33]](this.ZP);this[e[35]][e[34]](this.ZE);}catch(t){console[e[37]](e[36],t);}},members:{stats:document[e[39]](e[38]),T:null,ZA:0,ZB:null,ZC:null,ZD:null,ZE:null,ZF:null,ZG:null,ZH:false,ZI:true,ZJ:null,ZK:null,ZL:null,ZM:null,ZN:null,ZO:null,ZP:null,ZQ:null,ZR:[],ZT:true,ZU:null,ZV:null,ZX:null,ZY:null,ZZ:[],ZS:{},YZ:null,YY:null,openWindow:function(w){try{this[e[40]](w);if(this[e[41]]()){this[e[42]]();}else{q[e[43]]();q=window[e[45]][e[44]][e[11]]();var v;this[e[46]][e[32]]();for(v in q[e[47]]){var u=new qx[e[6]][e[48]].ListItem(v,null,q[e[47]][v].Object);this[e[46]][e[33]](u);if(Addons[e[51]][e[50]](e[49])==q[e[47]][v][e[53]][e[52]]()){this[e[46]][e[54]]([u]);}}this[e[55]]();this[e[56]](100,100);}}catch(t){console[e[58]](e[57],t);}},FI:function(){try{this[e[35]]=new qx[e[6]][e[60]][e[59]].Simple();this[e[35]][e[82]]([e[61],e[62],this[e[10]][e[64]](e[63]),this[e[10]][e[64]](e[65]),this[e[10]][e[64]](e[66]),this[e[10]][e[64]](e[67]),this[e[10]][e[64]](e[68]),this[e[10]][e[64]](e[69]),this[e[10]][e[64]](e[70]),e[71],e[72],this[e[10]][e[64]](e[73]),this[e[10]][e[64]](e[74]),this[e[10]][e[64]](e[75]),e[76],e[77],e[78],e[79],e[80],this[e[10]][e[64]](e[81])]);this[e[83]]=ClientLib[e[86]][e[85]].GetInstance()[e[84]]();this[e[87]]=new qx[e[6]][e[60]].Table(this.ZL);this[e[87]][e[88]](false);this[e[87]][e[89]](0,0);this[e[87]][e[89]](1,0);this[e[87]][e[89]](2,Addons[e[51]][e[50]](e[90],120));this[e[87]][e[89]](3,Addons[e[51]][e[50]](e[91],60));this[e[87]][e[89]](4,Addons[e[51]][e[50]](e[92],50));this[e[87]][e[89]](5,Addons[e[51]][e[50]](e[93],60));this[e[87]][e[89]](6,Addons[e[51]][e[50]](e[94],60));this[e[87]][e[89]](7,Addons[e[51]][e[50]](e[95],60));this[e[87]][e[89]](8,Addons[e[51]][e[50]](e[96],60));this[e[87]][e[89]](9,Addons[e[51]][e[50]](e[97],30));this[e[87]][e[89]](10,Addons[e[51]][e[50]](e[98],30));this[e[87]][e[89]](11,Addons[e[51]][e[50]](e[99],50));this[e[87]][e[89]](12,Addons[e[51]][e[50]](e[100],50));this[e[87]][e[89]](13,Addons[e[51]][e[50]](e[101],30));this[e[87]][e[89]](14,Addons[e[51]][e[50]](e[102],60));this[e[87]][e[89]](15,Addons[e[51]][e[50]](e[103],60));this[e[87]][e[89]](16,Addons[e[51]][e[50]](e[104],60));this[e[87]][e[89]](17,Addons[e[51]][e[50]](e[105],50));this[e[87]][e[89]](18,Addons[e[51]][e[50]](e[106],50));this[e[87]][e[89]](19,Addons[e[51]][e[50]](e[107],40));var u=0;var t=this[e[87]][e[108]]();for(u=0;u<this[e[35]][e[109]]();u++){if(u==0||u==1||u==11||u==12){t[e[111]](u,Addons[e[51]][e[50]](e[110]+u,false));}else{t[e[111]](u,Addons[e[51]][e[50]](e[110]+u,true));}}t[e[111]](1,false);t[e[115]](9,new qx[e[6]][e[60]][e[114]].Icon(p[e[113]][MaelstromTools[e[112]][e[68]]]),e[71]);t[e[115]](10,new qx[e[6]][e[60]][e[114]].Icon(p[e[113]][MaelstromTools[e[112]][e[67]]],e[72]));t[e[119]](5,new qx[e[6]][e[60]][e[118]].Replace()[e[117]]({ReplaceFunction:this[e[116]]}));t[e[119]](6,new qx[e[6]][e[60]][e[118]].Replace()[e[117]]({ReplaceFunction:this[e[116]]}));t[e[119]](7,new qx[e[6]][e[60]][e[118]].Replace()[e[117]]({ReplaceFunction:this[e[116]]}));t[e[119]](8,new qx[e[6]][e[60]][e[118]].Replace()[e[117]]({ReplaceFunction:this[e[116]]}));t[e[119]](15,new qx[e[6]][e[60]][e[118]].Replace()[e[117]]({ReplaceFunction:this[e[116]]}));t[e[119]](16,new qx[e[6]][e[60]][e[118]].Replace()[e[117]]({ReplaceFunction:this[e[116]]}));t[e[119]](19,new qx[e[6]][e[60]][e[118]].Boolean());this[e[87]][e[122]](e[120],function(w){Addons[e[121]][e[11]]().FB(w);},this);t[e[122]](e[123],function(y){var x=y[e[125]]()[e[124]];var w=y[e[125]]()[e[126]];Addons[e[51]][e[128]](e[127]+x,w);},t);}catch(v){console[e[37]](e[129],v);}},FB:function(y){try{var A=this[e[31]][y[e[130]]()][0];var z=this[e[31]][y[e[130]]()][3];if(z!=null&&z[e[133]](e[132])[e[131]]==2){var x=parseInt(z[e[133]](e[132])[0]);var w=parseInt(z[e[133]](e[132])[1]);ClientLib[e[135]][e[134]].GetInstance().CenterGridPosition(x,w);}if(A&&!(this[e[137]][4][e[136]]())){var u=qx[e[140]][e[139]][e[138]]();u[e[142]]()[e[141]]();u[e[146]]()[e[145]](ClientLib[e[86]][e[144]][e[143]],A,0,0);}var t=ClientLib[e[86]][e[85]].GetInstance()[e[148]]()[e[147]]();if(t!=null){t[e[150]]()[e[149]](A);}}catch(v){console[e[37]](e[151],v);}},FN:function(t){this[e[154]][e[153]](this[e[10]][e[64]](e[152]));this[e[155]]=false;},CBChanged:function(t){this[e[155]]=false;},FA:function(t){var u=new qx[e[157]][e[156]].NumberFormat();u[e[158]](true);u[e[159]](3);if(!isNaN(t)){if(Math[e[160]](t)<100000){t=u[e[156]](Math[e[161]](t));}else{if(Math[e[160]](t)>=100000&&Math[e[160]](t)<1000000){t=u[e[156]](Math[e[161]](t/100)/10)+e[162];}else{if(Math[e[160]](t)>=1000000&&Math[e[160]](t)<10000000){t=u[e[156]](Math[e[161]](t/1000)/1000)+e[163];}else{if(Math[e[160]](t)>=10000000&&Math[e[160]](t)<100000000){t=u[e[156]](Math[e[161]](t/10000)/100)+e[163];}else{if(Math[e[160]](t)>=100000000&&Math[e[160]](t)<1000000000){t=u[e[156]](Math[e[161]](t/100000)/10)+e[163];}else{if(Math[e[160]](t)>=1000000000&&Math[e[160]](t)<10000000000){t=u[e[156]](Math[e[161]](t/1000000)/1000)+e[164];}else{if(Math[e[160]](t)>=10000000000&&Math[e[160]](t)<100000000000){t=u[e[156]](Math[e[161]](t/10000000)/100)+e[164];}else{if(Math[e[160]](t)>=100000000000&&Math[e[160]](t)<1000000000000){t=u[e[156]](Math[e[161]](t/100000000)/10)+e[164];}else{if(Math[e[160]](t)>=1000000000000&&Math[e[160]](t)<10000000000000){t=u[e[156]](Math[e[161]](t/1000000000)/1000)+e[10];}else{if(Math[e[160]](t)>=10000000000000&&Math[e[160]](t)<100000000000000){t=u[e[156]](Math[e[161]](t/10000000000)/100)+e[10];}else{if(Math[e[160]](t)>=100000000000000&&Math[e[160]](t)<1000000000000000){t=u[e[156]](Math[e[161]](t/100000000000)/10)+e[10];}else{if(Math[e[160]](t)>=1000000000000000){t=u[e[156]](Math[e[161]](t/1000000000000))+e[10];}}}}}}}}}}}}}return t.toString();},FH:function(){try{var D=new qx[e[6]][e[26]].Flow();var C=new qx[e[6]][e[165]].Composite(D);this[e[46]]=new qx[e[6]][e[48]].SelectBox();this[e[46]][e[14]](25);this[e[46]][e[166]](5);q[e[43]]();q=window[e[45]][e[44]][e[11]]();var G;for(G in q[e[47]]){var F=new qx[e[6]][e[48]].ListItem(G,null,q[e[47]][G].Object);this[e[46]][e[33]](F);if(Addons[e[51]][e[50]](e[49])==q[e[47]][G][e[53]][e[52]]()){this[e[46]][e[54]]([F]);}}this[e[46]][e[122]](e[167],function(H){this.FP(0,1,200);this[e[155]]=false;this[e[154]][e[153]](this[e[10]][e[64]](e[152]));},this);C[e[33]](this.ZC);var B=new qx[e[6]][e[170]].Label()[e[117]]({value:this[e[10]][e[64]](e[168]),textColor:e[169],margin:5});C[e[33]](B);this[e[171]]=new qx[e[6]][e[48]].SelectBox();this[e[171]][e[13]](50);this[e[171]][e[14]](25);this[e[171]][e[166]](5);var z=Addons[e[51]][e[50]](e[172],25);for(var x=11;x<41;x+=1){F=new qx[e[6]][e[48]].ListItem(e[173]+x,null,x);this[e[171]][e[33]](F);if(z==x){this[e[171]][e[54]]([F]);}}this[e[171]][e[122]](e[167],function(H){this[e[31]]=[];this.FP(0,1,200);this[e[155]]=false;this[e[154]][e[153]](this[e[10]][e[64]](e[152]));},this);C[e[33]](this.ZQ);var v=new qx[e[6]][e[170]].Label()[e[117]]({value:this[e[10]][e[64]](e[174]),textColor:e[169],margin:5});C[e[33]](v);var u=Addons[e[51]][e[50]](e[175],e[176]);this[e[177]]=new qx[e[6]][e[48]].TextField(u)[e[117]]({width:50});C[e[33]](this.ZY);this[e[137]]=[];this[e[137]][0]=new qx[e[6]][e[48]].CheckBox(this[e[10]][e[64]](e[178]));this[e[137]][0][e[166]](5);this[e[137]][0][e[179]](e[169]);this[e[137]][0][e[181]](Addons[e[51]][e[50]](e[180],false));this[e[137]][0][e[122]](e[182],function(H){this[e[31]]=[];this.FP(0,1,200);this[e[155]]=false;this[e[154]][e[153]](this[e[10]][e[64]](e[152]));},this);C[e[33]](this[e[137]][0]);this[e[137]][1]=new qx[e[6]][e[48]].CheckBox(this[e[10]][e[64]](e[183]));this[e[137]][1][e[166]](5);this[e[137]][1][e[179]](e[169]);this[e[137]][1][e[181]](Addons[e[51]][e[50]](e[184],false));this[e[137]][1][e[122]](e[182],function(H){this[e[31]]=[];this.FP(0,1,200);this[e[155]]=false;this[e[154]][e[153]](this[e[10]][e[64]](e[152]));},this);C[e[33]](this[e[137]][1]);this[e[137]][2]=new qx[e[6]][e[48]].CheckBox(this[e[10]][e[64]](e[185]));this[e[137]][2][e[166]](5);this[e[137]][2][e[179]](e[169]);this[e[137]][2][e[181]](Addons[e[51]][e[50]](e[186],false));this[e[137]][2][e[122]](e[182],function(H){this[e[31]]=[];this.FP(0,1,200);this[e[155]]=false;this[e[154]][e[153]](this[e[10]][e[64]](e[152]));},this);C[e[33]](this[e[137]][2]);this[e[137]][3]=new qx[e[6]][e[48]].CheckBox(this[e[10]][e[64]](e[187]));this[e[137]][3][e[166]](5);this[e[137]][3][e[179]](e[169]);this[e[137]][3][e[181]](Addons[e[51]][e[50]](e[188],true));this[e[137]][3][e[122]](e[182],function(H){this[e[31]]=[];this.FP(0,1,200);this[e[155]]=false;this[e[154]][e[153]](this[e[10]][e[64]](e[152]));},this);C[e[33]](this[e[137]][3],{lineBreak:true});this[e[154]]=new qx[e[6]][e[48]].Button(this[e[10]][e[64]](e[152]))[e[117]]({width:100,minWidth:100,maxWidth:100,height:25,margin:5});this[e[154]][e[122]](e[189],function(){this.FE();},this);C[e[33]](this.ZG);var t=new qx[e[6]][e[192]].Single(2,e[190],e[191]);this[e[193]]=new qx[e[6]][e[165]].Composite(new qx[e[6]][e[26]].Basic())[e[117]]({decorator:t,backgroundColor:e[194],allowGrowX:false,height:20,width:200});this[e[195]]=new qx[e[6]][e[140]].Widget()[e[117]]({decorator:null,backgroundColor:e[196],width:0});this[e[193]][e[33]](this.ZU);this[e[197]]=new qx[e[6]][e[170]].Label(e[173])[e[117]]({decorator:null,textAlign:e[198],width:200});this[e[193]][e[33]](this.ZX,{left:0,top:-3});C[e[33]](this.ZV);this[e[199]]=new qx[e[6]][e[48]].Button(this[e[10]][e[64]](e[200]))[e[117]]({minWidth:100,height:25,margin:5});this[e[199]][e[122]](e[189],function(){this[e[201]]=[];},this);C[e[33]](this.YZ);this[e[137]][4]=new qx[e[6]][e[48]].CheckBox(this[e[10]][e[64]](e[202]));this[e[137]][4][e[166]](5);this[e[137]][4][e[179]](e[169]);C[e[33]](this[e[137]][4],{lineBreak:true});this[e[203]]=new qx[e[6]][e[48]].SelectBox();this[e[203]][e[13]](150);this[e[203]][e[14]](25);this[e[203]][e[166]](5);var F=new qx[e[6]][e[48]].ListItem(e[204]+this[e[10]][e[64]](MaelstromTools[e[112]].Tiberium)+e[205]+this[e[10]][e[64]](MaelstromTools[e[112]].Crystal),null,7);this[e[203]][e[33]](F);F=new qx[e[6]][e[48]].ListItem(e[206]+this[e[10]][e[64]](MaelstromTools[e[112]].Tiberium)+e[207]+this[e[10]][e[64]](MaelstromTools[e[112]].Crystal),null,6);this[e[203]][e[33]](F);F=new qx[e[6]][e[48]].ListItem(e[208]+this[e[10]][e[64]](MaelstromTools[e[112]].Tiberium)+e[209]+this[e[10]][e[64]](MaelstromTools[e[112]].Crystal),null,5);this[e[203]][e[33]](F);C[e[33]](this.ZJ);this[e[210]]=new qx[e[6]][e[48]].Button(this[e[10]][e[64]](e[211]))[e[117]]({width:120,minWidth:120,maxWidth:120,height:25,margin:5});this[e[210]][e[122]](e[189],function(){var H=window[e[213]][e[212]][e[11]]();H[e[215]](this[e[10]][e[64]](e[214]));},this);this[e[210]][e[216]](false);C[e[33]](this.ZD);this[e[217]]=new qx[e[6]][e[165]].Composite();this[e[217]][e[27]](new qx[e[6]][e[26]].Flow());this[e[217]][e[13]](750);var A=webfrontend[e[219]][e[26]][e[218]][e[11]]();var y=2;for(y=2;y<this[e[35]][e[109]]();y++){var w=y-2;this[e[220]][w]=new qx[e[6]][e[48]].CheckBox(this[e[35]][e[221]](y));this[e[220]][w][e[181]](this[e[87]][e[108]]()[e[222]](y));this[e[220]][w][e[179]](e[169]);this[e[220]][w][e[223]]=y;this[e[220]][w][e[60]]=this[e[87]];this[e[220]][w][e[122]](e[182],function(H){var I=this[e[60]][e[108]]();I[e[111]](this[e[223]],H[e[125]]());Addons[e[51]][e[128]](e[110]+this[e[223]],H[e[125]]());});this[e[217]][e[33]](this[e[220]][w]);}this[e[224]]=new qx[e[6]][e[48]].Button(e[225])[e[117]]({margin:5});this[e[224]][e[122]](e[189],function(){if(this[e[226]]){C[e[227]](this.ZB,this.ZO);this[e[224]][e[153]](e[228]);}else{C[e[229]](this.ZB);this[e[224]][e[153]](e[225]);}this[e[226]]=!this[e[226]];},this);this[e[224]][e[231]](e[230]);C[e[33]](this.ZO,{lineBreak:true});this[e[232]]=C;}catch(E){console[e[37]](e[233],E);}},FD:function(){var v=ClientLib[e[86]][e[85]].GetInstance()[e[148]]();var t=v[e[147]]();var u=e[234];var w=new qx[e[6]][e[170]].Label()[e[117]]({value:u,rich:true,width:800});this[e[235]]=w;},FE:function(){var u=this[e[46]][e[237]]()[0][e[236]]();ClientLib[e[135]][e[134]].GetInstance().CenterGridPosition(u[e[238]](),u[e[239]]());ClientLib[e[135]][e[134]].GetInstance().Update();ClientLib[e[135]][e[134]].GetInstance().ViewUpdate();ClientLib[e[86]][e[85]].GetInstance()[e[148]]()[e[240]](u[e[52]]());if(this[e[241]]){var t=ClientLib[e[86]][e[244]][e[243]][e[242]];var y=g(t[e[245]],/this\.(.{6})=\(?\(?g>>8\)?\&.*d\+=f;this\.(.{6})=\(/,e[246],2);if(y!=null&&y[1][e[131]]==6){t[e[247]]=function(){return this[y[1]];};}else{console[e[249]](e[248]);}if(y!=null&&y[2][e[131]]==6){t[e[250]]=function(){return this[y[2]];};}else{console[e[249]](e[251]);}t=ClientLib[e[86]][e[244]][e[252]][e[242]];var x=g(t[e[245]],/100\){0,1};this\.(.{6})=Math.floor.*d\+=f;this\.(.{6})=\(/,e[253],2);if(x!=null&&x[1][e[131]]==6){t[e[247]]=function(){return this[x[1]];};}else{console[e[249]](e[254]);}if(x!=null&&x[2][e[131]]==6){t[e[250]]=function(){return this[x[2]];};}else{console[e[249]](e[255]);}t=ClientLib[e[86]][e[244]][e[256]][e[242]];var w=g(t[e[245]],/100\){0,1};this\.(.{6})=Math.floor.*this\.(.{6})=\(*g\>\>(22|0x16)\)*\&.*=-1;\}this\.(.{6})=\(/,e[257],4);if(w!=null&&w[1][e[131]]==6){t[e[247]]=function(){return this[w[1]];};}else{console[e[249]](e[258]);}if(w!=null&&w[2][e[131]]==6){t[e[259]]=function(){return this[w[2]];};}else{console[e[249]](e[260]);}if(w!=null&&w[4][e[131]]==6){t[e[250]]=function(){return this[w[4]];};}else{console[e[249]](e[261]);}this[e[241]]=false;}if(this[e[31]]==null){this[e[155]]=false;this[e[154]][e[153]](e[262]);this[e[210]][e[216]](false);window[e[264]](e[263],1000);return;}var v=0;for(i=0;i<this[e[31]][e[131]];i++){if(this[e[31]][i][1]==-1){v++;}}if(!this[e[155]]){this[e[154]][e[153]](e[262]);this[e[210]][e[216]](false);if(v>0){this[e[155]]=true;window[e[264]](e[265],1000);return;}else{this[e[155]]=false;window[e[264]](e[263],1000);}}else{this[e[155]]=false;this[e[154]][e[153]](this[e[10]][e[64]](e[152]));}},FP:function(v,u,t){if(this[e[195]]!=null&&this[e[197]]!=null){this[e[195]][e[13]](parseInt(v/u*t,10));this[e[197]][e[181]](v+e[266]+u);}},FJ:function(){try{this[e[267]]={};this[e[31]]=[];var N=this[e[46]][e[237]]()[0][e[236]]();Addons[e[51]][e[128]](e[49],N[e[52]]());var G=this[e[171]][e[237]]()[0][e[236]]();Addons[e[51]][e[128]](e[172],G);Addons[e[51]][e[128]](e[175],this[e[177]][e[136]]());var M=this[e[137]][0][e[136]]();var L=this[e[137]][1][e[136]]();var K=this[e[137]][2][e[136]]();var J=this[e[137]][3][e[136]]();var I=parseInt(this[e[177]][e[136]](),10);Addons[e[51]][e[128]](e[180],M);Addons[e[51]][e[128]](e[184],L);Addons[e[51]][e[128]](e[186],K);Addons[e[51]][e[128]](e[188],J);var F=N[e[238]]();var E=N[e[239]]();var H=0;var C=0;var B=ClientLib[e[86]][e[85]].GetInstance()[e[268]]();console[e[9]](e[269]+N[e[270]]());var A=true;var y=true;var w=true;var u=ClientLib[e[86]][e[85]].GetInstance()[e[272]]()[e[271]]();for(C=E-Math[e[161]](u+1);C<=E+Math[e[161]](u+1);C++){for(H=F-Math[e[161]](u+1);H<=F+Math[e[161]](u+1);H++){var t=Math[e[160]](F-H);var R=Math[e[160]](E-C);var Q=Math[e[273]]((t*t)+(R*R));if(Q<=u){var P=B.GetObjectFromPosition(H,C);var z={};if(P){if(P[e[274]]==1&&A){}if(P[e[274]]==2&&y){}if(P[e[274]]==3&&w){}if(P[e[274]]==3){if(I<=parseInt(P[e[247]](),10)){}}var x=N.CalculateAttackCommandPointCostToCoord(H,C);if(x<=G&&typeof P[e[247]]==e[275]){if(I<=parseInt(P[e[247]](),10)){var v=this.FL(P[e[250]](),0);var D=this.FL(P[e[250]](),1);if(D!=null){this[e[267]][P[e[250]]()]=D;}if(P[e[274]]==1&&M){if(v!=null){this[e[31]][e[276]](v);}else{this[e[31]][e[276]]([P[e[250]](),-1,this[e[10]][e[64]](e[178]),H+e[132]+C,P[e[247]](),0,0,0,0,0,0,0,0,x,0,0,0,0]);}}if(P[e[274]]==2&&L){if(v!=null){this[e[31]][e[276]](v);}else{this[e[31]][e[276]]([P[e[250]](),-1,this[e[10]][e[64]](e[183]),H+e[132]+C,P[e[247]](),0,0,0,0,0,0,0,0,x,0,0,0,0]);}}if(P[e[274]]==3&&(K||J)){if(v!=null){if(P[e[259]]()==2&&J){this[e[31]][e[276]](v);}if(P[e[259]]()==3&&K){this[e[31]][e[276]](v);}}else{if(P[e[259]]()==2&&J){this[e[31]][e[276]]([P[e[250]](),-1,this[e[10]][e[64]](e[187]),H+e[132]+C,P[e[247]](),0,0,0,0,0,0,0,0,x,0,0,0,0]);}if(P[e[259]]()==3&&K){this[e[31]][e[276]]([P[e[250]](),-1,this[e[10]][e[64]](e[185]),H+e[132]+C,P[e[247]](),0,0,0,0,0,0,0,0,x,0,0,0,0]);}}}}}}}}}this[e[155]]=true;this[e[35]][e[34]](this.ZE);this.FP(0,this[e[31]][e[131]],200);this[e[35]][e[277]](4,false);if(this[e[83]][e[278]]!=e[279]){window[e[264]](e[265],50);}}catch(O){console[e[37]](e[280],O);}},FG:function(){try{var u=false;var t=0;var X=10;var y=0;var R=150;while(!u){var Q=null;var O=0;var M=0;if(this[e[31]]==null){console[e[282]](e[281]);this[e[155]]=false;break;}for(y=0;y<this[e[31]][e[131]];y++){if(this[e[31]][y][1]==-1){break;}}if(y==this[e[31]][e[131]]){this[e[155]]=false;}this.FP(y,this[e[31]][e[131]],200);if(this[e[31]][y]==null){console[e[282]](e[283]);this[e[155]]=false;this[e[154]][e[153]](this[e[10]][e[64]](e[152]));this[e[210]][e[216]](true);break;}posData=this[e[31]][y][3];if(posData!=null&&posData[e[133]](e[132])[e[131]]==2){posX=parseInt(posData[e[133]](e[132])[0]);posY=parseInt(posData[e[133]](e[132])[1]);var K=ClientLib[e[86]][e[85]].GetInstance()[e[148]]()[e[147]]();var v=ClientLib[e[86]][e[85]].GetInstance()[e[268]]();var I=v.CheckFoundBase(posX,posY,K[e[284]](),K[e[285]]());this[e[31]][y][19]=(I==0)?true:false;M=this[e[31]][y][0];ClientLib[e[86]][e[85]].GetInstance()[e[148]]()[e[240]](M);Q=ClientLib[e[86]][e[85]].GetInstance()[e[148]]().GetCity(M);if(Q!=null){if(!Q[e[286]]()){var E=Q[e[287]]();if(E!=null){var T=this[e[46]][e[237]]()[0][e[236]]();var C=Q[e[289]]()[e[288]];var z=E[e[290]]()[e[288]];var w=T[e[287]]()[e[291]]()[e[288]];if(C!=null){var P=d(C);var L=d(z);this[e[31]][y][2]=Q[e[270]]();this[e[31]][y][5]=P[ClientLib[e[293]][e[292]][e[67]]]+L[ClientLib[e[293]][e[292]][e[67]]];this[e[31]][y][6]=P[ClientLib[e[293]][e[292]][e[68]]]+L[ClientLib[e[293]][e[292]][e[68]]];this[e[31]][y][7]=P[ClientLib[e[293]][e[292]][e[294]]]+L[ClientLib[e[293]][e[292]][e[294]]];this[e[31]][y][8]=P[ClientLib[e[293]][e[292]][e[295]]]+L[ClientLib[e[293]][e[292]][e[295]]];if(Q.GetBuildingsConditionInPercent()!=0){this[e[296]]=0;if(this[e[31]][y][5]!=0){var S=0;var J=0;var B=0;var H=0;var G=0;this[e[267]][M]=new Array(9);for(B=0;B<9;B++){this[e[267]][M][B]=new Array(8);}for(H=0;H<9;H++){for(G=0;G<8;G++){switch(Q.GetResourceType(H,G)){case 1:this[e[267]][M][H][G]=1;S++;break;case 2:this[e[267]][M][H][G]=2;J++;break;default:break;}}}this[e[31]][y][9]=S;this[e[31]][y][10]=J;this[e[31]][y][11]=Q.GetBuildingsConditionInPercent();this[e[31]][y][12]=Q.GetDefenseConditionInPercent();try{var F=w;var D=0;var A=0;for(var V in F){D+=F[V][e[297]]();}F=z;for(var V in F){A+=F[V][e[297]]();}F=C;for(var V in F){var U=F[V][e[298]]();if(U==158||U==131||U==195){this[e[31]][y][18]=8-F[V][e[299]]();}if(U==112||U==151||U==177){this[e[31]][y][17]=8-F[V][e[299]]();}}}catch(N){console[e[37]](e[300],N);}this[e[31]][y][14]=(A/D);this[e[31]][y][15]=this[e[31]][y][5]+this[e[31]][y][6]+this[e[31]][y][7];this[e[31]][y][16]=this[e[31]][y][15]/this[e[31]][y][13];this[e[31]][y][1]=0;u=true;console[e[9]](Q[e[270]](),e[301]);this[e[296]]=0;this[e[302]]=0;this.FK(this[e[31]][y],this[e[267]][M],M);this[e[35]][e[34]](this.ZE);}}else{if(this[e[296]]>250){console[e[9]](this[e[31]][y][2],e[303],posX,posY,e[304]);this[e[31]][e[305]](y,1);this[e[296]]=0;this[e[302]]=0;break;}this[e[296]]++;}}}}else{console[e[9]](this[e[31]][y][2],e[303],posX,posY,e[306]);this[e[31]][e[305]](y,1);break;}}}t++;if(t>=X){u=true;break;}}if(this[e[307]]!=y){this[e[307]]=y;this[e[302]]=0;this[e[296]]=0;}else{if(this[e[302]]>16){console[e[9]](this[e[31]][y][2],e[303],posX,posY,e[308]);this[e[31]][e[305]](y,1);this[e[302]]=0;}else{if(this[e[302]]>10){R=500;}else{if(this[e[302]]>4){R=250;}}}this[e[302]]++;}if(this[e[155]]&&Addons[e[121]][e[11]]()[e[41]]()){window[e[264]](e[265],R);}else{this[e[154]][e[153]](this[e[10]][e[64]](e[152]));this[e[155]]=false;}}catch(W){console[e[37]](e[309],W);}},FK:function(v,u,t){this[e[201]][e[276]](v);this[e[310]][t]=u;},FL:function(u,v){if(v==0){for(var t=0;t<this[e[201]][e[131]];t++){if(this[e[201]][t][0]==u){return this[e[201]][t];}}}else{if(this[e[310]][u]){return this[e[310]][u];}}return null;}}});qx[e[312]][e[311]](e[313],{type:e[3],extend:qx[e[6]][e[5]][e[4]],construct:function(){try{this[e[7]](arguments);console[e[9]](e[314]+window[e[0]]);this[e[13]](820);this[e[14]](400);this[e[15]](10);this[e[16]](false);this[e[17]](true);this[e[18]](true);this[e[19]](true);this[e[20]](true);this[e[21]](false);this[e[22]](true);this[e[23]](false);this[e[24]](null);this[e[25]](10);this[e[27]](new qx[e[6]][e[26]].Grow());this[e[315]]=[];this[e[32]]();this[e[201]]=new qx[e[6]][e[165]].Scroll();this[e[177]]=new qx[e[6]][e[165]].Composite(new qx[e[6]][e[26]].Flow());this[e[33]](this.ZZ,{flex:3});this[e[201]][e[33]](this.ZY);}catch(t){console[e[37]](e[316],t);}},members:{ZW:null,ZZ:null,ZY:null,ZX:null,openWindow:function(u){try{this[e[40]](u);if(this[e[41]]()){this[e[42]]();}else{this[e[55]]();this[e[56]](100,100);this.FO();}}catch(t){console[e[58]](e[317],t);}},FO:function(){var H=window[e[213]][e[121]][e[11]]()[e[267]];var F=window[e[213]][e[121]][e[11]]()[e[31]];this[e[197]]=[];var D=window[e[213]][e[121]][e[11]]()[e[203]][e[237]]()[0][e[236]]();var B=null;if(F==null){console[e[9]](e[318]);return;}this[e[315]]=[];var w;var u;var z;var y;var I;for(w in H){for(u=0;u<F[e[131]];u++){if(F[u][0]==w){B=F[u];}}if(B==null){continue;}if(D>4&&D<8){if(D!=B[10]){continue;}}else{continue;}posData=B[3];if(posData!=null&&posData[e[133]](e[132])[e[131]]==2){posX=parseInt(posData[e[133]](e[132])[0]);posY=parseInt(posData[e[133]](e[132])[1]);}var t=e[319];var G=B[2]+e[320]+B[3];t=t+e[321]+G+e[322];for(y=0;y<8;y++){t=t+e[323];for(z=0;z<9;z++){var E=e[173];var C=H[w][z][y];switch(C==undefined?0:C){case 2:E=e[324]+p[e[113]][MaelstromTools[e[112]][e[67]]]+e[325];break;case 1:E=e[324]+p[e[113]][MaelstromTools[e[112]][e[68]]]+e[325];break;default:E=e[324]+p[e[113]][e[326]]+e[325];break;}t=t+e[327]+E+e[328];}t=t+e[329];}t=t+e[330];var v=new qx[e[6]][e[170]].Label()[e[117]]({backgroundColor:e[331],value:t,rich:true});v[e[332]]=w;this[e[197]][e[276]](w);v[e[122]](e[333],function(L){var K=qx[e[140]][e[139]][e[138]]();K[e[142]]()[e[141]]();K[e[146]]()[e[145]](ClientLib[e[86]][e[144]][e[143]],this[e[332]],0,0);var J=ClientLib[e[86]][e[85]].GetInstance()[e[148]]()[e[147]]();if(J!=null){J[e[150]]()[e[149]](this[e[332]]);}});v[e[334]]=w;this[e[315]][e[276]](v);}this[e[177]][e[32]]();var A=0;var x=0;for(I=0;I<this[e[315]][e[131]];I++){this[e[177]][e[33]](this[e[315]][I],{row:A,column:x});x++;if(x>4){x=0;A++;}}}}});qx[e[312]][e[311]](e[335],{type:e[336],extend:qx[e[140]][e[53]],statics:{isSupported:function(){return typeof(localStorage)!==e[337];},isdefined:function(t){return(localStorage[t]!==e[337]&&localStorage[t]!=null);},isdefineddata:function(u,t){return(u[t]!==e[337]&&u[t]!=null);},setglobal:function(v,t){try{if(Addons[e[51]][e[338]]()){localStorage[v]=JSON[e[339]](t);}}catch(u){console[e[37]](e[340],u);}},getglobal:function(v,u){try{if(Addons[e[51]][e[338]]()){if(Addons[e[51]][e[341]](v)){return JSON[e[342]](localStorage[v]);}}}catch(t){console[e[58]](e[343],t);}return u;},setserver:function(w,t){try{if(Addons[e[51]][e[338]]()){var v=ClientLib[e[86]][e[85]].GetInstance()[e[272]]()[e[270]]();var x;if(Addons[e[51]][e[341]](v)){try{x=JSON[e[342]](localStorage[v]);if(!(typeof x===e[344])){x={};console[e[37]](e[345]);}}catch(u){console[e[37]](e[346],u);x={};}}else{x={};}x[w]=t;localStorage[v]=JSON[e[339]](x);}}catch(u){console[e[37]](e[347],u);}},getserver:function(w,v){try{if(Addons[e[51]][e[338]]()){var u=ClientLib[e[86]][e[85]].GetInstance()[e[272]]()[e[270]]();if(Addons[e[51]][e[341]](u)){var x=JSON[e[342]](localStorage[u]);if(Addons[e[51]][e[348]](x,w)){return x[w];}}}}catch(t){console[e[58]](e[349],t);}return v;}}});if(typeof Addons[e[12]]===e[337]){qx[e[312]][e[311]](e[350],{type:e[3],extend:qx[e[140]][e[53]],members:{d:{},debug:false,addtranslateobj:function(t){if(t[e[352]](e[351])){this[e[288]][t[e[351]].toString()]=t;if(this[e[37]]){console[e[58]](e[353],t[e[351]].toString());}delete t[e[351]];}else{console[e[37]](e[354]);}},get:function(v){var u=qx[e[357]][e[356]][e[11]]()[e[355]]();var t=u[e[133]](e[358])[0];if(this[e[288]][e[352]](v)){if(this[e[288]][v][e[352]](t)){return this[e[288]][v][t];}}if(this[e[37]]){console[e[37]](e[359],v,e[360],t);}return v;}}});}qx[e[312]][e[311]](e[361],{extend:qx[e[6]][e[60]][e[118]][e[362]],properties:{replaceMap:{check:e[53],nullable:true,init:null},replaceFunction:{check:e[363],nullable:true,init:null}},members:{_getContentHtml:function(w){var x=w[e[364]];var v=this[e[365]]();var u=this[e[366]]();var t;if(v){t=v[x];if(typeof t!=e[337]){w[e[364]]=t;return qx[e[369]][e[368]][e[367]](this._formatValue(w));}}if(u){w[e[364]]=u(x);}return qx[e[369]][e[368]][e[367]](this._formatValue(w));},addReversedReplaceMap:function(){var t=this[e[365]]();for(var v in t){var u=t[v];t[u]=v;}return true;}}});console[e[9]](e[370]);var s=Addons[e[12]][e[11]]();s[e[37]]=false;s[e[373]]({main:e[371],de:e[372],pt:e[372],fr:e[372]});s[e[373]]({main:e[374],de:e[375],pt:e[376],fr:e[377]});s[e[373]]({main:e[152],de:e[378],pt:e[379],fr:e[380]});s[e[373]]({main:e[65],de:e[381],pt:e[382],fr:e[383]});s[e[373]]({main:e[178],de:e[384],pt:e[385],fr:e[386]});s[e[373]]({main:e[183],de:e[183],pt:e[183],fr:e[183]});s[e[373]]({main:e[387],de:e[388],pt:e[389],fr:e[390]});s[e[373]]({main:e[187],de:e[391],pt:e[187],fr:e[187]});s[e[373]]({main:e[185],de:e[392],pt:e[393],fr:e[394]});s[e[373]]({main:e[214],de:e[214],pt:e[395],fr:e[396]});s[e[373]]({main:e[397],de:e[398],pt:e[399],fr:e[400]});s[e[373]]({main:e[73],de:e[401],pt:e[402],fr:e[403]});s[e[373]]({main:e[74],de:e[404],pt:e[405],fr:e[406]});s[e[373]]({main:e[75],de:e[407],pt:e[75],fr:e[75]});s[e[373]]({main:e[168],de:e[408],pt:e[409],fr:e[410]});s[e[373]]({main:e[174],de:e[411],pt:e[412],fr:e[413]});s[e[373]]({main:e[200],de:e[414],pt:e[415],fr:e[416]});s[e[373]]({main:e[202],de:e[417],pt:e[418],fr:e[419]});s[e[373]]({main:e[81],de:e[420],pt:e[421],fr:e[422]});s[e[373]]({main:e[423],de:e[424],pt:e[425],fr:e[424]});s[e[373]]({main:e[426],de:e[427],pt:e[428],fr:e[429]});s[e[373]]({main:e[430],de:e[431],pt:e[432],fr:e[433]});s[e[373]]({main:e[67],de:e[67],pt:e[434],fr:e[67]});s[e[373]]({main:e[68],de:e[435],pt:e[436],fr:e[436]});s[e[373]]({main:e[437],de:e[438],pt:e[439],fr:e[440]});s[e[373]]({main:e[69],de:e[441],pt:e[442],fr:e[443]});s[e[373]]({main:e[70],de:e[444],pt:e[445],fr:e[446]});s[e[373]]({main:e[447],de:e[448],pt:e[448],fr:e[448]});var r=null;var q=null;var p=null;var o=null;var n=0;var m=0;o=ClientLib[e[450]][e[449]].GetInstance();r=window[e[45]][e[12]][e[11]]();q=window[e[45]][e[44]][e[11]]();p=window[e[45]][e[293]][e[11]]();p[e[453]](e[451],e[452],o);p[e[453]](e[326],e[454],o);var l=p[e[457]](s[e[64]](e[374])+e[455]+window[e[0]],e[451],false,p[e[456]](2));l[e[122]](e[189],function(){Addons[e[121]][e[11]]()[e[215]](s[e[64]](e[374])+e[458]+window[e[0]]);},this);Addons[e[121]][e[11]]()[e[122]](e[42],Addons[e[121]][e[11]]().FN,Addons[e[121]][e[11]]());p[e[459]](e[451],l);if(typeof Addons[e[460]]!==e[337]){var k=Addons[e[460]][e[11]]();k.AddMainMenu(e[461],function(){Addons[e[121]][e[11]]()[e[215]](s[e[64]](e[374])+e[458]+window[e[0]]);},e[462]);}}function d(o){try{var q=[0,0,0,0,0,0,0,0];if(o==null){return q;}for(var l in o){var n=o[l];var m=MaelstromTools[e[463]].GetUnitLevelRequirements(n);for(var k=0;k<m[e[131]];k++){q[m[k][e[274]]]+=m[k][e[464]]*n[e[465]]();if(n[e[465]]()<1){}}}return q;}catch(p){console[e[37]](e[466],p);}}function f(k){var m;for(m in k){if(typeof(k[m])==e[275]){var l=k[m].toString();console[e[37]](m,l);}}}function g(k,r,q,m){var p=[];var o=k.toString();var n=o[e[467]](/\s/gim,e[173]);p=n[e[468]](r);var l;for(l=1;l<(m+1);l++){if(p!=null&&p[l][e[131]]==6){console[e[37]](q,l,p[l]);}else{if(p!=null&&p[l][e[131]]>0){console[e[282]](q,l,p[l]);}else{console[e[249]](e[469],q,l,e[470]);console[e[282]](q,n);}}}return p;}function h(){try{if(typeof qx!=e[337]&&typeof MaelstromTools!=e[337]){j();}else{window[e[264]](h,1000);}}catch(k){console[e[37]](e[471],k);}}if(/commandandconquer\.com/i[e[473]](document[e[472]])){window[e[264]](h,10000);}};try{var a=document.createElement("script");a.innerHTML="("+b.toString()+")();";a.type="text/javascript";if(/commandandconquer\.com/i.test(document.domain)){document.getElementsByTagName("head")[0].appendChild(a);}}catch(c){console.debug("MaelstromTools_Basescanner: init error: ",c);}})();
  242.  
  243.  
  244. /***********************************************************************************
  245. Tiberium Alliances Info Sticker
  246. ***********************************************************************************/
  247.  
  248. (function () {
  249. var InfoSticker_main = function () {
  250. try {
  251. function createInfoSticker() {
  252. console.log('InfoSticker loaded');
  253. // define Base
  254. qx.Class.define("InfoSticker.Base", {
  255. type: "singleton",
  256. extend: qx.core.Object,
  257. members: {
  258. /* Desktop */
  259. dataTimerInterval: 1000,
  260. positionInterval: 500,
  261. tibIcon: null,
  262. cryIcon: null,
  263. powIcon: null,
  264. creditIcon: null,
  265. repairIcon: null,
  266. hasStorage: false,
  267.  
  268. initialize: function () {
  269. try {
  270. this.hasStorage = 'localStorage' in window && window['localStorage'] !== null;
  271. } catch (se) {}
  272. try {
  273. var fileManager = ClientLib.File.FileManager.GetInstance();
  274. this.tibIcon = fileManager.GetPhysicalPath("ui/common/icn_res_tiberium.png");
  275. this.cryIcon = fileManager.GetPhysicalPath("ui/common/icn_res_chrystal.png");
  276. this.powIcon = fileManager.GetPhysicalPath("ui/common/icn_res_power.png");
  277. this.creditIcon = fileManager.GetPhysicalPath("ui/common/icn_res_dollar.png");
  278. this.repairIcon = fileManager.GetPhysicalPath("ui/icons/icn_repair_off_points.png");
  279. if (typeof phe.cnc.Util.attachNetEvent == 'undefined')
  280. this.attachEvent = webfrontend.gui.Util.attachNetEvent;
  281. else
  282. this.attachEvent = phe.cnc.Util.attachNetEvent;
  283. this.runMainTimer();
  284. } catch (e) {
  285. console.log("InfoSticker.initialize: ", e.toString());
  286. }
  287. },
  288. runMainTimer: function () {
  289. try {
  290. var self = this;
  291. this.calculateInfoData();
  292. window.setTimeout(function () {
  293. self.runMainTimer();
  294. }, this.dataTimerInterval);
  295. } catch (e) {
  296. console.log("InfoSticker.runMainTimer: ", e.toString());
  297. }
  298. },
  299. runPositionTimer: function () {
  300. try {
  301. var self = this;
  302. this.repositionSticker();
  303. window.setTimeout(function () {
  304. self.runPositionTimer();
  305. }, this.positionInterval);
  306. } catch (e) {
  307. console.log("InfoSticker.runPositionTimer: ", e.toString());
  308. }
  309. },
  310. infoSticker: null,
  311. mcvPopup: null,
  312. mcvTimerLabel: null,
  313. mcvInfoLabel: null,
  314. mcvPane: null,
  315. repairPopup: null,
  316. repairTimerLabel: null,
  317.  
  318. resourcePane: null,
  319. resourceHidden: false,
  320. resourceTitleLabel: null,
  321. resourceHideButton: null,
  322. resourceLabel1: null,
  323. resourceLabel2: null,
  324. resourceLabel3: null,
  325.  
  326. resourceLabel1per: null,
  327. resourceLabel2per: null,
  328. resourceLabel3per: null,
  329.  
  330. productionTitleLabel: null,
  331. productionLabelPower: null,
  332. productionLabelCredit: null,
  333.  
  334. repairInfoLabel: null,
  335.  
  336. lastButton: null,
  337.  
  338. top_image: null,
  339. bot_image: null,
  340.  
  341. toFlipH: [],
  342.  
  343. pinButton: null,
  344. pinned: false,
  345.  
  346. pinTop: 130,
  347. pinButtonDecoration: null,
  348. pinPane: null,
  349.  
  350. pinIconFix: false,
  351. lockButton: null,
  352. locked: false,
  353.  
  354. lockButtonDecoration: null,
  355. lockPane: null,
  356.  
  357. lockIconFix: false,
  358. mcvHide: false,
  359. repairHide: false,
  360. resourceHide: false,
  361. productionHide: false,
  362. stickerBackground: null,
  363. mcvPane: null,
  364. pinLockPos: 0,
  365. attachEvent: function() {},
  366. isNull: function(e) {
  367. return typeof e == "undefined" || e == null;
  368. },
  369. getApp: function() {
  370. return qx.core.Init.getApplication();
  371. },
  372. getBaseListBar: function() {
  373. var app = this.getApp();
  374. var b;
  375. if(!this.isNull(app)) {
  376. b = app.getBaseNavigationBar();
  377. if(!this.isNull(b)) {
  378. if(b.getChildren().length > 0) {
  379. b = b.getChildren()[0];
  380. if(b.getChildren().length > 0) {
  381. b = b.getChildren()[0];
  382. return b;
  383. }
  384. }
  385. }
  386. }
  387. return null;
  388. },
  389. repositionSticker: function () {
  390. try {
  391. var i;
  392. if (this.infoSticker && !this.mcvInfoLabel.isDisposed() && !this.mcvPopup.isDisposed()) {
  393. var dele;
  394.  
  395. try {
  396. if (this.top_image != null) {
  397. dele = this.top_image.getContentElement().getDomElement();
  398. if (dele != null) {
  399. dele.style["-moz-transform"] = "scaleY(-1)";
  400. dele.style["-o-transform"] = "scaleY(-1)";
  401. dele.style["-webkit-transform"] = "scaleY(-1)";
  402. dele.style.transform = "scaleY(-1)";
  403. dele.style.filter = "FlipV";
  404. dele.style["-ms-filter"] = "FlipV";
  405. this.top_image = null;
  406. }
  407. }
  408. for (i = this.toFlipH.length - 1; i >= 0; i--) {
  409. var e = this.toFlipH[i];
  410. if(e.isDisposed()) this.toFlipH.splice(i, 1);
  411. else {
  412. dele = e.getDecoratorElement().getDomElement();
  413. if (dele != null) {
  414. dele.style["-moz-transform"] = "scaleX(-1)";
  415. dele.style["-o-transform"] = "scaleX(-1)";
  416. dele.style["-webkit-transform"] = "scaleX(-1)";
  417. dele.style.transform = "scaleX(-1)";
  418. dele.style.filter = "FlipH";
  419. dele.style["-ms-filter"] = "FlipH";
  420. this.toFlipH.splice(i, 1);
  421. }
  422. }
  423. }
  424. } catch (e2) {
  425. console.log("Error flipping images.", e2.toString());
  426. }
  427. var baseListBar = this.getBaseListBar();
  428. if(baseListBar!=null) {
  429. var baseCont = baseListBar.getChildren();
  430. for (i = 0; i < baseCont.length; i++) {
  431. var baseButton = baseCont[i];
  432. if(typeof baseButton.getBaseId === 'function') {
  433. if(baseButton.getBaseId() == ClientLib.Data.MainData.GetInstance().get_Cities().get_CurrentOwnCity().get_Id()
  434. && baseButton.getBounds() != null && baseButton.getBounds().top!=null) {
  435. //var baseButtonDecorator = baseButton.getDecorator();
  436. //if (baseButton!=this.mcvPopup && baseButtonDecorator != null && typeof baseButtonDecorator === "string" && baseButton.getBounds() != null && baseButton.getBounds().top!=null) {
  437. //if (baseButtonDecorator.indexOf("focused") >= 0 || baseButtonDecorator.indexOf("pressed") >= 0) {
  438. if(this.locked) {
  439. if(!this.pinned) {
  440. if(baseListBar.indexOf(this.mcvPopup)>=0) {
  441. baseListBar.remove(this.mcvPopup);
  442. }
  443. this.pinLockPos = baseListBar.indexOf(baseButton)+1;
  444. baseListBar.addAt(this.mcvPopup, this.pinLockPos);
  445. } else if(baseListBar.indexOf(this.mcvPopup)<0) {
  446. baseListBar.addAt(this.mcvPopup, Math.max(0, Math.min(this.pinLockPos, baseCont.length)));
  447. }
  448. } else {
  449. if(baseListBar.indexOf(this.mcvPopup)>=0) {
  450. baseListBar.remove(this.mcvPopup);
  451. }
  452. if (!this.pinned) {
  453. var top = baseButton.getBounds().top;
  454. var infoTop;
  455. try {
  456. var stickerHeight = this.infoSticker.getContentElement().getDomElement().style.height;
  457. stickerHeight = stickerHeight.substring(0, stickerHeight.indexOf("px"));
  458. infoTop = Math.min(130 + top, Math.max(660, window.innerHeight) - parseInt(stickerHeight, 10) - 130);
  459. } catch (heighterror) {
  460. infoTop = 130 + top;
  461. }
  462. if(this.infoSticker.getContentElement().getDomElement()!=null)
  463. this.infoSticker.setDomTop(infoTop);
  464. this.pinTop = infoTop;
  465. }
  466. }
  467. break;
  468. }
  469. }
  470. }
  471. }
  472. }
  473. } catch (ex) {
  474. console.log("InfoSticker.repositionSticker: ", ex.toString());
  475. }
  476. },
  477. toLock: function (e) {
  478. try {
  479. this.locked = !this.locked;
  480. if(!this.locked) {
  481. this.infoSticker.show();
  482. this.stickerBackground.add(this.mcvPopup);
  483. }
  484. else this.infoSticker.hide();
  485. this.lockButton.setIcon(this.locked ? "FactionUI/icons/icn_thread_locked_active.png" : "FactionUI/icons/icn_thread_locked_inactive.png");
  486. this.updateLockButtonDecoration();
  487. if (this.hasStorage) {
  488. if (this.locked) {
  489. localStorage["infoSticker-locked"] = "true";
  490. if(this.pinned) localStorage["infoSticker-pinLock"] = this.pinLockPos.toString();
  491. } else {
  492. localStorage["infoSticker-locked"] = "false";
  493. }
  494. }
  495. if(this.locked && this.pinned) {
  496. this.menuUpButton.setEnabled(true);
  497. this.menuDownButton.setEnabled(true);
  498. } else {
  499. this.menuUpButton.setEnabled(false);
  500. this.menuDownButton.setEnabled(false);
  501. }
  502. this.repositionSticker();
  503. } catch(e) {
  504. console.log("InfoSticker.toLock: ", e.toString());
  505. }
  506. },
  507. updateLockButtonDecoration: function () {
  508. var light = "#CDD9DF";
  509. var mid = "#9CA4A8";
  510. var dark = "#8C9499";
  511. this.lockPane.setDecorator(null);
  512. this.lockButtonDecoration = new qx.ui.decoration.Background();
  513. this.lockButtonDecoration.setBackgroundColor(this.locked ? dark : light);
  514. this.lockPane.setDecorator(this.lockButtonDecoration);
  515. },
  516. toPin: function (e) {
  517. try {
  518. this.pinned = !this.pinned;
  519. this.pinButton.setIcon(this.pinned ? "FactionUI/icons/icn_thread_pin_active.png" : "FactionUI/icons/icn_thread_pin_inactive.png");
  520. this.updatePinButtonDecoration();
  521. if (this.hasStorage) {
  522. if (this.pinned) {
  523. localStorage["infoSticker-pinned"] = "true";
  524. localStorage["infoSticker-top"] = this.pinTop.toString();
  525. if(this.locked) {
  526. localStorage["infoSticker-pinLock"] = this.pinLockPos.toString();
  527. }
  528. } else {
  529. localStorage["infoSticker-pinned"] = "false";
  530. }
  531. }
  532. if(this.locked && this.pinned) {
  533. this.menuUpButton.setEnabled(true);
  534. this.menuDownButton.setEnabled(true);
  535. } else {
  536. this.menuUpButton.setEnabled(false);
  537. this.menuDownButton.setEnabled(false);
  538. }
  539. } catch(e) {
  540. console.log("InfoSticker.toPin: ", e.toString());
  541. }
  542. },
  543. updatePinButtonDecoration: function () {
  544. var light = "#CDD9DF";
  545. var mid = "#9CA4A8";
  546. var dark = "#8C9499";
  547. this.pinPane.setDecorator(null);
  548. this.pinButtonDecoration = new qx.ui.decoration.Background().set({
  549. //innerOpacity: 0.5
  550. });
  551. //this.pinButtonDecoration.setInnerColor(this.pinned ? mid : light);
  552. //this.pinButtonDecoration.setOuterColor(this.pinned ? light : mid);
  553. this.pinButtonDecoration.setBackgroundColor(this.pinned ? dark : light);
  554. this.pinPane.setDecorator(this.pinButtonDecoration);
  555. },
  556. hideResource: function () {
  557. try {
  558. //if(this.resourceHidden)
  559. if (this.resourcePane.isVisible()) {
  560. //this.resourcePane.hide();
  561. this.resourcePane.exclude();
  562. this.resourceHideButton.setLabel("+");
  563. } else {
  564. this.resourcePane.show();
  565. this.resourceHideButton.setLabel("-");
  566. }
  567. } catch(e) {
  568. console.log("InfoSticker.hideResource: ", e.toString());
  569. }
  570. },
  571. lastPane: null,
  572. createSection: function (parent, titleLabel, visible, visibilityStorageName) {
  573. try {
  574. var pane = new qx.ui.container.Composite(new qx.ui.layout.VBox()).set({
  575. padding: [5, 0, 5, 5],
  576. width: 124,
  577. decorator: new qx.ui.decoration.Background().set({
  578. backgroundImage: "decoration/pane_messaging_item/messaging_items_pane.png",
  579. backgroundRepeat: "scale",
  580. }),
  581. alignX: "right"
  582. });
  583. var labelStyle = {
  584. font: qx.bom.Font.fromString('bold').set({
  585. size: 12
  586. }),
  587. textColor: '#595969'
  588. };
  589. titleLabel.set(labelStyle);
  590. var hidePane = new qx.ui.container.Composite(new qx.ui.layout.VBox()).set({
  591. width: 124,
  592. alignX: "right"
  593. });
  594. var hideButton = new qx.ui.form.Button("-").set({
  595. //decorator: new qx.ui.decoration.Single(1, "solid", "black"),
  596. maxWidth: 15,
  597. maxHeight: 10,
  598. //textColor: "black"
  599. });
  600. var self = this;
  601. //resourceHideButton.addListener("execute", this.hideResource, this);
  602. hideButton.addListener("execute", function () {
  603. if (hidePane.isVisible()) {
  604. hidePane.exclude();
  605. hideButton.setLabel("+");
  606. } else {
  607. hidePane.show();
  608. hideButton.setLabel("-");
  609. }
  610. if(self.hasStorage)
  611. localStorage["infoSticker-"+visibilityStorageName] = !hidePane.isVisible();
  612. });
  613.  
  614. var titleBar = new qx.ui.container.Composite(new qx.ui.layout.HBox(0));
  615. titleBar.add(hideButton);
  616. titleBar.add(titleLabel);
  617. pane.add(titleBar);
  618. pane.add(hidePane);
  619. if(!visible) hidePane.exclude();
  620. this.toFlipH.push(pane);
  621.  
  622. this.lastPane = pane;
  623. parent.add(pane);
  624. return hidePane;
  625. } catch(e) {
  626. console.log("InfoSticker.createSection: ", e.toString());
  627. throw e;
  628. }
  629. },
  630. createHBox: function (ele1, ele2, ele3) {
  631. var cnt;
  632. cnt = new qx.ui.container.Composite();
  633. cnt.setLayout(new qx.ui.layout.HBox(0));
  634. if (ele1 != null) {
  635. cnt.add(ele1);
  636. ele1.setAlignY("middle");
  637. }
  638. if (ele2 != null) {
  639. cnt.add(ele2);
  640. ele2.setAlignY("bottom");
  641. }
  642. if (ele3 != null) {
  643. cnt.add(ele3);
  644. ele3.setAlignY("bottom");
  645. }
  646.  
  647. return cnt;
  648. },
  649. formatCompactTime: function (time) {
  650. var comps = time.split(":");
  651. var i = 0;
  652. var value = Math.round(parseInt(comps[i], 10)).toString();
  653. var len = comps.length;
  654. while(value==0) {
  655. value = Math.round(parseInt(comps[++i], 10)).toString();
  656. len--;
  657. }
  658. var unit;
  659. switch(len) {
  660. case 1: unit = "s"; break;
  661. case 2: unit = "m"; break;
  662. case 3: unit = "h"; break;
  663. case 4: unit = "d"; break;
  664. }
  665. return value+unit;
  666. },
  667. createImage: function(icon) {
  668. var image = new qx.ui.basic.Image(icon);
  669. image.setScale(true);
  670. image.setWidth(20);
  671. image.setHeight(20);
  672. return image;
  673. },
  674.  
  675. createMCVPane: function() {
  676. try {
  677. this.mcvInfoLabel = new qx.ui.basic.Label();
  678. this.mcvTimerLabel = new qx.ui.basic.Label().set({
  679. font: qx.bom.Font.fromString('bold').set({
  680. size: 18
  681. }),
  682. textColor: '#282828',
  683. height: 20,
  684. width: 114,
  685. textAlign: 'center'
  686. });
  687. this.mcvTimerCreditProdLabel = new qx.ui.basic.Label().set({
  688. font: qx.bom.Font.fromString('normal').set({
  689. size: 12
  690. }),
  691. textColor: '#282828',
  692. height: 20,
  693. width: 114,
  694. textAlign: 'center',
  695. marginTop: 4,
  696. marginBottom: -4
  697. });
  698. var app = qx.core.Init.getApplication();
  699. var b3 = app.getBaseNavigationBar().getChildren()[0].getChildren()[0];
  700. var pane = this.createSection(b3, this.mcvInfoLabel, !this.mcvHide, "mcvHide");
  701. pane.add(this.mcvTimerLabel);
  702. pane.add(this.mcvTimerCreditProdLabel);
  703. this.mcvPane = this.lastPane;
  704. this.lastPane.setMarginLeft(7);
  705. } catch(e) {
  706. console.log("InfoSticker.createMCVPopup", e.toString());
  707. }
  708. },
  709. moveStickerUp: function() {
  710. try {
  711. var baseListBar = this.getBaseListBar();
  712. this.pinLockPos=Math.max(0, this.pinLockPos-1);
  713. if(baseListBar.indexOf(this.mcvPopup)>=0) {
  714. baseListBar.remove(this.mcvPopup);
  715. }
  716. if (this.hasStorage) {
  717. localStorage["infoSticker-pinLock"] = this.pinLockPos.toString();
  718. }
  719. } catch(e) {
  720. console.log("InfoSticker.moveStickerUp", e.toString());
  721. }
  722. },
  723. moveStickerDown: function() {
  724. try {
  725. var baseListBar = this.getBaseListBar();
  726. this.pinLockPos=Math.min(baseListBar.getChildren().length, this.pinLockPos+1);
  727. if(baseListBar.indexOf(this.mcvPopup)>=0) {
  728. baseListBar.remove(this.mcvPopup);
  729. }
  730. if (this.hasStorage) {
  731. localStorage["infoSticker-pinLock"] = this.pinLockPos.toString();
  732. }
  733. } catch(e) {
  734. console.log("InfoSticker.moveStickerDown", e.toString());
  735. }
  736. },
  737. menuUpButton: null,
  738. menuDownButton: null,
  739. createMCVPopup: function() {
  740. try {
  741. var self = this;
  742. this.mcvPopup = new qx.ui.container.Composite(new qx.ui.layout.VBox().set({
  743. spacing: 3})).set({
  744. paddingLeft: 5,
  745. width: 105,
  746. decorator: new qx.ui.decoration.Background()
  747. });
  748. var menu = new qx.ui.menu.Menu();
  749. var menuPinButton = new qx.ui.menu.Button("Pin", "FactionUI/icons/icn_thread_pin_inactive.png");
  750. menuPinButton.addListener("execute", this.toPin, this);
  751. menu.add(menuPinButton);
  752. var menuLockButton = new qx.ui.menu.Button("Lock", "FactionUI/icons/icn_thread_locked_inactive.png");
  753. menuLockButton.addListener("execute", this.toLock, this);
  754. menu.add(menuLockButton);
  755. var fileManager = ClientLib.File.FileManager.GetInstance();
  756. this.menuUpButton = new qx.ui.menu.Button("Move up", fileManager.GetPhysicalPath("ui/icons/icon_tracker_arrow_up.png"));
  757. //ui/icons/icon_tracker_arrow_up.png ui/gdi/icons/cht_opt_arrow_down.png
  758. this.menuUpButton.addListener("execute", this.moveStickerUp, this);
  759. menu.add(this.menuUpButton);
  760. this.menuDownButton = new qx.ui.menu.Button("Move down", fileManager.GetPhysicalPath("ui/icons/icon_tracker_arrow_down.png"));
  761. this.menuDownButton.addListener("execute", this.moveStickerDown, this);
  762. menu.add(this.menuDownButton);
  763. this.mcvPopup.setContextMenu(menu);
  764. if(!this.locked) {
  765. this.stickerBackground.add(this.mcvPopup);
  766. }
  767. ////////////////////////////----------------------------------------------------------
  768. this.pinButton = new webfrontend.ui.SoundButton().set({
  769. decorator: "button-forum-light",
  770. icon: this.pinned ? "FactionUI/icons/icn_thread_pin_active.png" : "FactionUI/icons/icn_thread_pin_inactive.png",
  771. iconPosition: "top",
  772. show: "icon",
  773. cursor: "pointer",
  774. height: 23,
  775. width: 50,
  776. //maxHeight: 25,
  777. maxWidth: 33,
  778. maxHeight: 19,
  779. alignX: "center"
  780. });
  781. this.pinButton.addListener("execute", this.toPin, this);
  782. this.pinPane = new qx.ui.container.Composite(new qx.ui.layout.VBox()).set({
  783. //width: 50,
  784. maxWidth: 37,
  785. });
  786. this.updatePinButtonDecoration();
  787. this.pinPane.setDecorator(this.pinButtonDecoration);
  788. this.pinPane.add(this.pinButton);
  789. //this.mcvPopup.add(this.pinPane);
  790. //this.toFlipH.push(this.pinPane);
  791. var icon = this.pinButton.getChildControl("icon");
  792. icon.setWidth(15);
  793. icon.setHeight(15);
  794. icon.setScale(true);
  795. ////////////////////////////----------------------------------------------------------
  796. this.lockButton = new webfrontend.ui.SoundButton().set({
  797. decorator: "button-forum-light",
  798. icon: this.pinned ? "FactionUI/icons/icn_thread_locked_active.png" : "FactionUI/icons/icn_thread_locked_inactive.png",
  799. iconPosition: "top",
  800. show: "icon",
  801. cursor: "pointer",
  802. height: 23,
  803. width: 50,
  804. //maxHeight: 25,
  805. maxWidth: 33,
  806. maxHeight: 19,
  807. alignX: "center"
  808. });
  809. this.lockButton.addListener("execute", this.toLock, this);
  810. this.lockPane = new qx.ui.container.Composite(new qx.ui.layout.VBox()).set({
  811. //width: 50,
  812. maxWidth: 37,
  813. });
  814. this.updateLockButtonDecoration();
  815. this.lockPane.setDecorator(this.lockButtonDecoration);
  816. this.lockPane.add(this.lockButton);
  817. //this.mcvPopup.add(this.pinPane);
  818. //this.toFlipH.push(this.pinPane);
  819. icon = this.lockButton.getChildControl("icon");
  820. icon.setWidth(15);
  821. icon.setHeight(15);
  822. icon.setScale(true);
  823. ////////////////////////////----------------------------------------------------------
  824. this.resourceTitleLabel = new qx.ui.basic.Label();
  825. this.resourceTitleLabel.setValue("Base");
  826. var resStyle = {
  827. font: qx.bom.Font.fromString('bold').set({
  828. size: 14
  829. }),
  830. textColor: '#282828',
  831. height: 20,
  832. width: 65,
  833. marginLeft: -10,
  834. textAlign: 'right'
  835. };
  836. this.resourceLabel1 = new qx.ui.basic.Label().set(resStyle);
  837. this.resourceLabel2 = new qx.ui.basic.Label().set(resStyle);
  838. this.resourceLabel3 = new qx.ui.basic.Label().set(resStyle);
  839. var perStyle = {
  840. font: qx.bom.Font.fromString('bold').set({
  841. size: 9
  842. }),
  843. textColor: '#282828',
  844. height: 18,
  845. width: 33,
  846. textAlign: 'right'
  847. };
  848. this.resourceLabel1per = new qx.ui.basic.Label().set(perStyle);
  849. this.resourceLabel2per = new qx.ui.basic.Label().set(perStyle);
  850. this.resourceLabel3per = new qx.ui.basic.Label().set(perStyle);
  851. var pane3 = this.createSection(this.mcvPopup, this.resourceTitleLabel, !this.resourceHide, "resourceHide");
  852. this.repairTimerLabel = new qx.ui.basic.Label().set({
  853. font: qx.bom.Font.fromString('bold').set({
  854. size: 16
  855. }),
  856. textColor: '#282828',
  857. height: 20,
  858. width: 85,
  859. marginLeft: 0,
  860. textAlign: 'center'
  861. });
  862. pane3.add(this.createHBox(this.createImage(this.repairIcon), this.repairTimerLabel));
  863. pane3.add(this.createHBox(this.createImage(this.tibIcon), this.resourceLabel1, this.resourceLabel1per));
  864. pane3.add(this.createHBox(this.createImage(this.cryIcon), this.resourceLabel2, this.resourceLabel2per));
  865. pane3.add(this.createHBox(this.createImage(this.powIcon), this.resourceLabel3, this.resourceLabel3per));
  866. var mcvC = this.mcvPopup.getChildren();
  867. mcvC[mcvC.length-1].getChildren()[0].add(this.pinPane);
  868. mcvC[mcvC.length-1].getChildren()[0].add(this.lockPane);
  869. ////////////////////////////----------------------------------------------------------
  870. this.productionTitleLabel = new qx.ui.basic.Label();
  871. this.productionTitleLabel.setValue("Productions");
  872. var productionStyle = {
  873. font: qx.bom.Font.fromString('bold').set({
  874. size: 13
  875. }),
  876. textColor: '#282828',
  877. height: 20,
  878. width: 60,
  879. textAlign: 'right',
  880. marginTop: 2,
  881. marginBottom: -2
  882. };
  883. this.productionLabelPower = new qx.ui.basic.Label().set(productionStyle);
  884. this.productionLabelCredit = new qx.ui.basic.Label().set(productionStyle);
  885. var pane4 = this.createSection(this.mcvPopup, this.productionTitleLabel, !this.productionHide, "productionHide");
  886. pane4.add(this.createHBox(this.createImage(this.powIcon), this.productionLabelPower));
  887. pane4.add(this.createHBox(this.createImage(this.creditIcon), this.productionLabelCredit));
  888. ////////////////////////////----------------------------------------------------------
  889. } catch(e) {
  890. console.log("InfoSticker: createMCVPopup", e.toString());
  891. }
  892. },
  893. currentCityChange: function() {
  894. this.calculateInfoData();
  895. this.repositionSticker();
  896. },
  897. disposeRecover: function() {
  898. try {
  899. if(this.mcvPane.isDisposed()) {
  900. this.createMCVPane();
  901. }
  902. if(this.mcvPopup.isDisposed()) {
  903. this.createMCVPopup();
  904. this.repositionSticker();
  905. }
  906. this.waitingRecovery = false;
  907. } catch(e) {
  908. console.log("InfoSticker: disposeRecover", e.toString());
  909. }
  910. },
  911. waitingRecovery: false,
  912. citiesChange: function() {
  913. try {
  914. var self = this;
  915. var baseListBar = this.getBaseListBar();
  916. this.disposeRecover();
  917. if(baseListBar.indexOf(this.mcvPopup)>=0) {
  918. baseListBar.remove(this.mcvPopup);
  919. this.mcvPopup.dispose();
  920. }
  921. if(baseListBar.indexOf(this.mcvPane)>=0) {
  922. baseListBar.remove(this.mcvPane);
  923. this.mcvPane.dispose();
  924. }
  925. if(!this.waitingRecovery) {
  926. this.waitingRecovery = true;
  927. window.setTimeout(function () {
  928. self.disposeRecover();
  929. }, 10);
  930. }
  931. } catch(e) {
  932. console.log("InfoSticker: citiesChange", e.toString());
  933. }
  934. },
  935. calculateInfoData: function () {
  936. try {
  937. var self = this;
  938. var player = ClientLib.Data.MainData.GetInstance().get_Player();
  939. var cw = player.get_Faction();
  940. var cj = ClientLib.Base.Tech.GetTechIdFromTechNameAndFaction(ClientLib.Base.ETechName.Research_BaseFound, cw);
  941. var cr = player.get_PlayerResearch();
  942. var cd = cr.GetResearchItemFomMdbId(cj);
  943. var app = qx.core.Init.getApplication();
  944. var b3 = app.getBaseNavigationBar().getChildren()[0].getChildren()[0];
  945. if(b3.getChildren().length==0) return;
  946. if (!this.infoSticker) {
  947. this.infoSticker = new qx.ui.container.Composite(new qx.ui.layout.VBox().set({
  948. alignX: "right"
  949. })).set({
  950. width: 105,
  951. });
  952.  
  953. var top = 130;
  954. if (this.hasStorage) {
  955. var l = localStorage["infoSticker-locked"] == "true";
  956. if (l != null) {
  957. this.locked = l;
  958. var pl = localStorage["infoSticker-pinLock"];
  959. if(pl!=null) {
  960. try {
  961. this.pinLockPos = parseInt(pl, 10);
  962. } catch(etm) {}
  963. }
  964. }
  965. var p = localStorage["infoSticker-pinned"];
  966. var t = localStorage["infoSticker-top"];
  967. if (p != null && t != null) {
  968. var tn;
  969. try {
  970. this.pinned = p == "true";
  971. if (this.pinned) {
  972. tn = parseInt(t, 10);
  973. top = tn;
  974. }
  975. } catch (etn) {}
  976. }
  977. this.mcvHide = localStorage["infoSticker-mcvHide"] == "true";
  978. this.repairHide = localStorage["infoSticker-repairHide"] == "true";
  979. this.resourceHide = localStorage["infoSticker-resourceHide"] == "true";
  980. this.productionHide = localStorage["infoSticker-productionHide"] == "true";
  981. }
  982. app.getDesktop().add(this.infoSticker, {
  983. right: 124,
  984. top: top
  985. });
  986. if(this.locked) {
  987. this.infoSticker.hide();
  988. }
  989.  
  990. this.stickerBackground = new qx.ui.container.Composite(new qx.ui.layout.VBox()).set({
  991. //paddingLeft: 5,
  992. width: 105,
  993. decorator: new qx.ui.decoration.Background().set({
  994. backgroundImage: "webfrontend/ui/common/bgr_region_world_select_scaler.png",
  995. backgroundRepeat: "scale",
  996. })
  997. });
  998. this.createMCVPane();
  999. this.createMCVPopup();
  1000. if(this.locked && this.pinned) {
  1001. this.menuUpButton.setEnabled(true);
  1002. this.menuDownButton.setEnabled(true);
  1003. } else {
  1004. this.menuUpButton.setEnabled(false);
  1005. this.menuDownButton.setEnabled(false);
  1006. }
  1007. this.top_image = new qx.ui.basic.Image("webfrontend/ui/common/bgr_region_world_select_end.png");
  1008. this.infoSticker.add(this.top_image);
  1009.  
  1010. this.infoSticker.add(this.stickerBackground);
  1011. //this.infoSticker.add(this.mcvPopup);
  1012.  
  1013. this.bot_image = new qx.ui.basic.Image("webfrontend/ui/common/bgr_region_world_select_end.png");
  1014. this.infoSticker.add(this.bot_image);
  1015.  
  1016. this.runPositionTimer();
  1017.  
  1018. try {
  1019. this.attachEvent(ClientLib.Data.MainData.GetInstance().get_Cities(), "CurrentOwnChange", ClientLib.Data.CurrentOwnCityChange, this, this.currentCityChange);
  1020. this.attachEvent(ClientLib.Data.MainData.GetInstance().get_Cities(), "Change", ClientLib.Data.CitiesChange, this, this.citiesChange);
  1021. } catch(eventError) {
  1022. console.log("InfoSticker.EventAttach:", eventError);
  1023. console.log("The script will continue to run, but with slower response speed.");
  1024. }
  1025. }
  1026. this.disposeRecover();
  1027. if (cd == null) {
  1028. if (this.mcvPopup) {
  1029. //this.mcvInfoLabel.setValue("MCV ($???)");
  1030. this.mcvInfoLabel.setValue("MCV<br>$???");
  1031. this.mcvTimerLabel.setValue("Loading");
  1032. }
  1033. } else {
  1034. var nextLevelInfo = cd.get_NextLevelInfo_Obj();
  1035. var resourcesNeeded = [];
  1036. for (var i in nextLevelInfo.rr) {
  1037. if (nextLevelInfo.rr[i].t > 0) {
  1038. resourcesNeeded[nextLevelInfo.rr[i].t] = nextLevelInfo.rr[i].c;
  1039. }
  1040. }
  1041. //var researchNeeded = resourcesNeeded[ClientLib.Base.EResourceType.ResearchPoints];
  1042. //var currentResearchPoints = player.get_ResearchPoints();
  1043. var creditsNeeded = resourcesNeeded[ClientLib.Base.EResourceType.Gold];
  1044. var creditsResourceData = player.get_Credits();
  1045. var creditGrowthPerHour = (creditsResourceData.Delta + creditsResourceData.ExtraBonusDelta) * ClientLib.Data.MainData.GetInstance().get_Time().get_StepsPerHour();
  1046. var creditTimeLeftInHours = (creditsNeeded - player.GetCreditsCount()) / creditGrowthPerHour;
  1047. this.mcvInfoLabel.setValue("MCV ($ " + this.formatNumbersCompact(creditsNeeded) + ")");
  1048. //this.mcvInfoLabel.setValue("MCV<br>$" + this.formatNumbersCompact(creditsNeeded));
  1049. this.mcvTimerCreditProdLabel.setValue("at " + this.formatNumbersCompact(creditGrowthPerHour) + "/h");
  1050. if (creditTimeLeftInHours <= 0) {
  1051. this.mcvTimerLabel.setValue("Ready");
  1052. } else if (creditGrowthPerHour == 0) {
  1053. this.mcvTimerLabel.setValue("Never");
  1054. } else {
  1055. if(creditTimeLeftInHours >= 24 * 100) {
  1056. this.mcvTimerLabel.setValue("> 99 days");
  1057. } else {
  1058. this.mcvTimerLabel.setValue(this.FormatTimespan(creditTimeLeftInHours * 60 * 60));
  1059. }
  1060. }
  1061. }
  1062.  
  1063. var ncity = ClientLib.Data.MainData.GetInstance().get_Cities().get_CurrentOwnCity();
  1064. if (ncity == null) {
  1065. if (this.mcvPopup) {
  1066. this.repairTimerLabel.setValue("Select a base");
  1067.  
  1068. this.resourceLabel1.setValue("N/A");
  1069. this.resourceLabel2.setValue("N/A");
  1070. this.resourceLabel3.setValue("N/A");
  1071. }
  1072. } else {
  1073.  
  1074. var rt = Math.min(ncity.GetResourceCount(ClientLib.Base.EResourceType.RepairChargeInf),
  1075. ncity.GetResourceCount(ClientLib.Base.EResourceType.RepairChargeVeh),
  1076. ncity.GetResourceCount(ClientLib.Base.EResourceType.RepairChargeAir));
  1077. if (ncity.get_CityUnitsData().get_UnitLimitOffense() == 0) {
  1078. this.repairTimerLabel.setValue("No army");
  1079. } else {
  1080. this.repairTimerLabel.setValue(this.FormatTimespan(rt));
  1081. }
  1082.  
  1083. var tib = ncity.GetResourceCount(ClientLib.Base.EResourceType.Tiberium);
  1084. var tibMax = ncity.GetResourceMaxStorage(ClientLib.Base.EResourceType.Tiberium);
  1085. var tibRatio = tib / tibMax;
  1086. this.resourceLabel1.setTextColor(this.formatNumberColor(tib, tibMax));
  1087. this.resourceLabel1.setValue(this.formatNumbersCompact(tib));
  1088. this.resourceLabel1per.setValue(this.formatPercent(tibRatio));
  1089.  
  1090. var cry = ncity.GetResourceCount(ClientLib.Base.EResourceType.Crystal);
  1091. var cryMax = ncity.GetResourceMaxStorage(ClientLib.Base.EResourceType.Crystal);
  1092. var cryRatio = cry / cryMax;
  1093. this.resourceLabel2.setTextColor(this.formatNumberColor(cry, cryMax));
  1094. this.resourceLabel2.setValue(this.formatNumbersCompact(cry));
  1095. this.resourceLabel2per.setValue(this.formatPercent(cryRatio));
  1096.  
  1097. var power = ncity.GetResourceCount(ClientLib.Base.EResourceType.Power);
  1098. var powerMax = ncity.GetResourceMaxStorage(ClientLib.Base.EResourceType.Power);
  1099. var powerRatio = power / powerMax;
  1100. this.resourceLabel3.setTextColor(this.formatNumberColor(power, powerMax));
  1101. this.resourceLabel3.setValue(this.formatNumbersCompact(power));
  1102. this.resourceLabel3per.setValue(this.formatPercent(powerRatio));
  1103.  
  1104. var powerCont = ncity.GetResourceGrowPerHour(ClientLib.Base.EResourceType.Power, false, false);
  1105. var powerBonus = ncity.GetResourceBonusGrowPerHour(ClientLib.Base.EResourceType.Power);
  1106. var alliance = ClientLib.Data.MainData.GetInstance().get_Alliance();
  1107. var powerAlly = alliance.GetPOIBonusFromResourceType(ClientLib.Base.EResourceType.Power);
  1108. var powerProd = powerCont + powerBonus + powerAlly;
  1109.  
  1110. var creditCont = ClientLib.Base.Resource.GetResourceGrowPerHour(ncity.get_CityCreditsProduction(), false);
  1111. var creditBonus = ClientLib.Base.Resource.GetResourceBonusGrowPerHour(ncity.get_CityCreditsProduction(), false);
  1112. var creditProd = creditCont + creditBonus;
  1113.  
  1114. this.productionLabelPower.setValue(this.formatNumbersCompact(powerProd) + "/h");
  1115. this.productionLabelCredit.setValue(this.formatNumbersCompact(creditProd) + "/h");
  1116. }
  1117. } catch (e) {
  1118. console.log("InfoSticker.calculateInfoData", e.toString());
  1119. }
  1120. },
  1121. formatPercent: function (value) {
  1122. return value > 999 / 100 ? ">999%" : this.formatNumbersCompact(value * 100, 0) + "%";
  1123. //return this.formatNumbersCompact(value*100, 0) + "%";
  1124. },
  1125. formatNumberColor: function (value, max) {
  1126. var ratio = value / max;
  1127.  
  1128. var color;
  1129. var black = [40, 180, 40];
  1130. var yellow = [181, 181, 0];
  1131. var red = [187, 43, 43];
  1132.  
  1133. if (ratio < 0.5) color = black;
  1134. else if (ratio < 0.75) color = this.interpolateColor(black, yellow, (ratio - 0.5) / 0.25);
  1135. else if (ratio < 1) color = this.interpolateColor(yellow, red, (ratio - 0.75) / 0.25);
  1136. else color = red;
  1137.  
  1138. //console.log(qx.util.ColorUtil.rgbToHexString(color));
  1139. return qx.util.ColorUtil.rgbToHexString(color);
  1140. },
  1141. interpolateColor: function (color1, color2, s) {
  1142. //console.log("interp "+s+ " " + color1[1]+" " +color2[1]+" " +(color1[1]+s*(color2[1]-color1[1])));
  1143. return [Math.floor(color1[0] + s * (color2[0] - color1[0])),
  1144. Math.floor(color1[1] + s * (color2[1] - color1[1])),
  1145. Math.floor(color1[2] + s * (color2[2] - color1[2]))];
  1146. },
  1147. formatNumbersCompact: function (value, decimals) {
  1148. if (decimals == undefined) decimals = 2;
  1149. var valueStr;
  1150. var unit = "";
  1151. if (value < 1000) valueStr = value.toString();
  1152. else if (value < 1000 * 1000) {
  1153. valueStr = (value / 1000).toString();
  1154. unit = "k";
  1155. } else if (value < 1000 * 1000 * 1000) {
  1156. valueStr = (value / 1000000).toString();
  1157. unit = "M";
  1158. } else {
  1159. valueStr = (value / 1000000000).toString();
  1160. unit = "G";
  1161. }
  1162. if (valueStr.indexOf(".") >= 0) {
  1163. var whole = valueStr.substring(0, valueStr.indexOf("."));
  1164. if (decimals === 0) {
  1165. valueStr = whole;
  1166. } else {
  1167. var fraction = valueStr.substring(valueStr.indexOf(".") + 1);
  1168. if (fraction.length > decimals) fraction = fraction.substring(0, decimals);
  1169. valueStr = whole + "." + fraction;
  1170. }
  1171. }
  1172.  
  1173. valueStr = valueStr + unit;
  1174. return valueStr;
  1175. },
  1176. FormatTimespan: function (value) {
  1177. var i;
  1178. var t = ClientLib.Vis.VisMain.FormatTimespan(value);
  1179. var colonCount = 0;
  1180. for (i = 0; i < t.length; i++) {
  1181. if (t.charAt(i) == ':') colonCount++;
  1182. }
  1183. var r = "";
  1184. for (i = 0; i < t.length; i++) {
  1185. if (t.charAt(i) == ':') {
  1186. if (colonCount > 2) {
  1187. r += "d ";
  1188. } else {
  1189. r += t.charAt(i);
  1190. }
  1191. colonCount--;
  1192. } else {
  1193. r += t.charAt(i);
  1194. }
  1195. }
  1196. return r;
  1197. }
  1198. }
  1199. });
  1200. }
  1201. } catch (e) {
  1202. console.log("InfoSticker: createInfoSticker: ", e.toString());
  1203. }
  1204.  
  1205. function InfoSticker_checkIfLoaded() {
  1206. try {
  1207. if (typeof qx != 'undefined' && qx.core.Init.getApplication() && qx.core.Init.getApplication().getUIItem(ClientLib.Data.Missions.PATH.BAR_NAVIGATION) && qx.core.Init.getApplication().getUIItem(ClientLib.Data.Missions.PATH.BAR_NAVIGATION).isVisible()) {
  1208. createInfoSticker();
  1209. window.InfoSticker.Base.getInstance().initialize();
  1210. } else {
  1211. window.setTimeout(InfoSticker_checkIfLoaded, 1000);
  1212. }
  1213. } catch (e) {
  1214. console.log("InfoSticker_checkIfLoaded: ", e.toString());
  1215. }
  1216. }
  1217. if (/commandandconquer\.com/i.test(document.domain)) {
  1218. window.setTimeout(InfoSticker_checkIfLoaded, 1000);
  1219. }
  1220. }
  1221. try {
  1222. var InfoStickerScript = document.createElement("script");
  1223. InfoStickerScript.innerHTML = "(" + InfoSticker_main.toString() + ")();";
  1224. InfoStickerScript.type = "text/javascript";
  1225. if (/commandandconquer\.com/i.test(document.domain)) {
  1226. document.getElementsByTagName("head")[0].appendChild(InfoStickerScript);
  1227. }
  1228. } catch (e) {
  1229. console.log("InfoSticker: init error: ", e.toString());
  1230. }
  1231. })();
  1232.  
  1233. /***********************************************************************************
  1234. WarChiefs - Tiberium Alliances Sector HUD
  1235. ***********************************************************************************/
  1236. // ==UserScript==
  1237. // @name WarChiefs - Tiberium Alliances Sector HUD
  1238. // @description Displays a tiny HUD with the Sector you are viewing.
  1239. // @author Eistee
  1240. // @version 13.12.18
  1241. // @namespace http*://*.alliances.commandandconquer.com/*
  1242. // @include http*://*.alliances.commandandconquer.com/*
  1243. // @require http://usocheckup.redirectme.net/172683.js
  1244. // @icon http://s3.amazonaws.com/uso_ss/icon/172683/large.png
  1245. // @updateURL https://userscripts.org/scripts/source/172683.meta.js
  1246. // @downloadURL https://userscripts.org/scripts/source/172683.user.js
  1247. // @grant GM_getValue
  1248. // @grant GM_log
  1249. // @grant GM_openInTab
  1250. // @grant GM_registerMenuCommand
  1251. // @grant GM_setValue
  1252. // @grant GM_xmlhttpRequest
  1253. // ==/UserScript==
  1254. /**
  1255. * License: CC-BY-NC-SA 3.0
  1256. */
  1257. (function () {
  1258. var injectFunction = function () {
  1259. function createClasses() {
  1260. qx.Class.define("SectorHUD", {
  1261. type: "singleton",
  1262. extend: qx.core.Object,
  1263. construct: function () {
  1264. this.SectorText = new qx.ui.basic.Label("").set({
  1265. textColor : "#FFFFFF",
  1266. font : "font_size_11"
  1267. });
  1268. var HUD = new qx.ui.container.Composite(new qx.ui.layout.HBox()).set({
  1269. decorator : new qx.ui.decoration.Background().set({
  1270. backgroundRepeat : "no-repeat",
  1271. backgroundImage : "webfrontend/ui/menues/notifications/bgr_ticker_container.png",
  1272. backgroundPositionX : "center"
  1273. }),
  1274. padding : 2,
  1275. opacity: 0.8
  1276. });
  1277. HUD.add(this.SectorText);
  1278. HUD.addListener("click", function (e) {
  1279. if (e.getButton() == "left") this.paste_Coords();
  1280. if (e.getButton() == "right") this.jump_Coords();
  1281. }, this);
  1282. this.__refresh = false;
  1283. qx.core.Init.getApplication().getDesktop().add(HUD, {left: 128, top: 0});
  1284. phe.cnc.Util.attachNetEvent(ClientLib.Vis.VisMain.GetInstance().get_Region(), "PositionChange", ClientLib.Vis.PositionChange, this, this._update);
  1285. },
  1286. destruct: function () {},
  1287. members: {
  1288. __refresh: null,
  1289. SectorText: null,
  1290. get_SectorText: function (i) {
  1291. var qxApp = qx.core.Init.getApplication();
  1292. switch (i) {
  1293. case 0:
  1294. return qxApp.tr("tnf:south abbr");
  1295. case 1:
  1296. return qxApp.tr("tnf:southwest abbr");
  1297. case 2:
  1298. return qxApp.tr("tnf:west abbr");
  1299. case 3:
  1300. return qxApp.tr("tnf:northwest abbr");
  1301. case 4:
  1302. return qxApp.tr("tnf:north abbr");
  1303. case 5:
  1304. return qxApp.tr("tnf:northeast abbr");
  1305. case 6:
  1306. return qxApp.tr("tnf:east abbr");
  1307. case 7:
  1308. return qxApp.tr("tnf:southeast abbr");
  1309. }
  1310. },
  1311. get_SectorNo: function (x, y) {
  1312. var WorldX2 = Math.floor(ClientLib.Data.MainData.GetInstance().get_Server().get_WorldWidth() / 2),
  1313. WorldY2 = Math.floor(ClientLib.Data.MainData.GetInstance().get_Server().get_WorldHeight() / 2),
  1314. SectorCount = ClientLib.Data.MainData.GetInstance().get_Server().get_SectorCount(),
  1315. WorldCX = (WorldX2 - x),
  1316. WorldCY = (y - WorldY2),
  1317. WorldCa = ((Math.atan2(WorldCX, WorldCY) * SectorCount) / 6.2831853071795862) + (SectorCount + 0.5);
  1318. return (Math.floor(WorldCa) % SectorCount);
  1319. },
  1320. get_Coords: function () {
  1321. var Region = ClientLib.Vis.VisMain.GetInstance().get_Region();
  1322. GridWidth = Region.get_GridWidth(),
  1323. GridHeight = Region.get_GridHeight(),
  1324. RegionPosX = Region.get_PosX(),
  1325. RegionPosY = Region.get_PosY(),
  1326. ViewWidth = Region.get_ViewWidth(),
  1327. ViewHeight = Region.get_ViewHeight(),
  1328. ZoomFactor = Region.get_ZoomFactor(),
  1329. ViewCoordX = Math.floor((RegionPosX + ViewWidth / 2 / ZoomFactor) / GridWidth - 0.5),
  1330. ViewCoordY = Math.floor((RegionPosY + ViewHeight / 2 / ZoomFactor) / GridHeight - 0.5);
  1331. return {X: ViewCoordX, Y: ViewCoordY};
  1332. },
  1333. paste_Coords: function(){
  1334. var Coords = this.get_Coords(),
  1335. input = qx.core.Init.getApplication().getChat().getChatWidget().getEditable(),
  1336. inputDOM = input.getContentElement().getDomElement(),
  1337. text = [];
  1338. text.push(inputDOM.value.substring(0, inputDOM.selectionStart));
  1339. text.push("[coords]" + Coords.X + ':' + Coords.Y + "[/coords]");
  1340. text.push(inputDOM.value.substring(inputDOM.selectionEnd, inputDOM.value.length));
  1341. input.setValue(text.join(' '));
  1342. },
  1343. jump_Coords: function(){
  1344. var coords = prompt("Jump to Coords:");
  1345. if (coords) {
  1346. coords.replace(/(\[coords\])?([#])?(\d{1,4})\D(\d{1,4})(\D\w+)?(\[\/coords\])?/gi, function () {
  1347. if (arguments.length >= 5) {
  1348. ClientLib.Vis.VisMain.GetInstance().get_Region().CenterGridPosition(parseInt(arguments[3], 10), parseInt(arguments[4], 10));
  1349. }
  1350. });
  1351. }
  1352. },
  1353. _update: function () {
  1354. if (this.__refresh === false) {
  1355. this.__refresh = true;
  1356. setTimeout(this.__update.bind(this), 500);
  1357. }
  1358. },
  1359. __update: function () {
  1360. var Coords = this.get_Coords();
  1361. this.SectorText.setValue(Coords.X + ":" + Coords.Y + " [" + this.get_SectorText(this.get_SectorNo(Coords.X, Coords.Y)) + "]");
  1362. this.__refresh = false;
  1363. }
  1364. }
  1365. });
  1366. }
  1367. function waitForGame() {
  1368. try {
  1369. if (typeof qx !== "undefined" && typeof qx.core !== "undefined" && typeof qx.core.Init !== "undefined" && typeof ClientLib !== "undefined" && typeof phe !== "undefined") {
  1370. var app = qx.core.Init.getApplication();
  1371. if (app.initDone === true) {
  1372. try {
  1373. console.time("loaded in");
  1374. createClasses();
  1375. SectorHUD.getInstance();
  1376. console.group("WarChiefs - Sector HUD");
  1377. console.timeEnd("loaded in");
  1378. console.groupEnd();
  1379. } catch (e) {
  1380. console.group("WarChiefs - Sector HUD");
  1381. console.error("Error in waitForGame", e);
  1382. console.groupEnd();
  1383. }
  1384. } else
  1385. window.setTimeout(waitForGame, 1000);
  1386. } else {
  1387. window.setTimeout(waitForGame, 1000);
  1388. }
  1389. } catch (e) {
  1390. console.group("WarChiefs - Sector HUD");
  1391. console.error("Error in waitForGame", e);
  1392. console.groupEnd();
  1393. }
  1394. }
  1395. window.setTimeout(waitForGame, 1000);
  1396. };
  1397. var script = document.createElement("script");
  1398. var txt = injectFunction.toString();
  1399. script.innerHTML = "(" + txt + ")();";
  1400. script.type = "text/javascript";
  1401. document.getElementsByTagName("head")[0].appendChild(script);
  1402. })();
  1403.  
  1404.  
  1405. /***********************************************************************************
  1406. MaelstromTools Dev
  1407. ***********************************************************************************/
  1408. // ==UserScript==
  1409. // @name MaelstromTools Dev
  1410. // @namespace MaelstromTools
  1411. // @description Just a set of statistics & summaries about repair time and base resources. Mainly for internal use, but you are free to test and comment it.
  1412. // @version 0.1.3.2
  1413. // @author Maelstrom, HuffyLuf, KRS_L and Krisan
  1414. // @include http*://prodgame*.alliances.commandandconquer.com/*/index.aspx*
  1415. // ==/UserScript==
  1416. //var offense_units = own_city.get_CityArmyFormationsManager().GetFormationByTargetBaseId(current_city.get_Id()).get_ArmyUnits().l;
  1417. //System.Int64 GetForumIdByType (ClientLib.Data.Forum.EForumType eForumType)
  1418. //static ClientLib.Data.Forum.EForumType NormalForum
  1419. //System.Collections.Generic.List$1 get_ForumsAlliance ()
  1420. //System.Void CreateThread (System.Int64 forumId ,System.String threadTitle ,System.String threadPost ,System.Boolean autoSubscribe)
  1421. //System.Void CreatePost (System.Int64 forumId ,System.Int64 threadId ,System.String postMessage)
  1422. //System.Void StartGetForumThreadData (System.Int64 forumId ,System.Int32 skip ,System.Int32 take)
  1423. //System.Void OnForumThreadDataReceived (System.Object context ,System.Object result)
  1424. //System.Void add_ThreadsFetched (ClientLib.Data.ForumThreadsFetched value)
  1425. //System.Void MarkThreadsAsRead (System.Int64 forumId ,System.Int64[] threadIds)
  1426. //
  1427. //var score = ClientLib.Base.PointOfInterestTypes.GetScoreByLevel(lvl);
  1428. //var scoreNext = ClientLib.Base.PointOfInterestTypes.GetNextScore(score);
  1429. //var resBonus = ClientLib.Base.PointOfInterestTypes.GetBonusByType(ClientLib.Base.EPOIType.TiberiumBonus, score);
  1430. //var unitBonus = ClientLib.Base.PointOfInterestTypes.GetBonusByType(ClientLib.Base.EPOIType.InfanteryBonus, score);
  1431. //console.log("POI lvl" + lvl + "gives " + score + "points, next lvl at " + scoreNext + " points. Resource bonus: " + resBonus + " Unit bonus: " + unitBonus + "%");
  1432. /*
  1433. ClientLib.Data.Player
  1434. get_ResearchPoints
  1435. GetCreditsCount
  1436. GetCreditsGrowth
  1437. ClientLib.Data.PlayerResearch get_PlayerResearch ()
  1438. ClientLib.Data.PlayerResearchItem GetResearchItemFomMdbId (System.Int32 _mdbId)
  1439. ClientLib.Data.PlayerResearchItem.System.Object get_NextLevelInfo_Obj ()
  1440.  
  1441. var cw=ClientLib.Data.MainData.GetInstance().get_Player().get_Faction();
  1442. var cj=ClientLib.Base.Tech.GetTechIdFromTechNameAndFaction(ClientLib.Base.ETechName.Research_BaseFound,cw);
  1443. var cd=cr.GetResearchItemFomMdbId(cj);
  1444. */
  1445. (function () {
  1446. var MaelstromTools_main = function () {
  1447. try {
  1448. function CCTAWrapperIsInstalled() {
  1449. return (typeof (CCTAWrapper_IsInstalled) != 'undefined' && CCTAWrapper_IsInstalled);
  1450. }
  1451.  
  1452. function createMaelstromTools() {
  1453. console.log('MaelstromTools loaded');
  1454.  
  1455. qx.Class.define("MaelstromTools.Language", {
  1456. type: "singleton",
  1457. extend: qx.core.Object,
  1458. construct: function (language) {
  1459. this.Languages = ['de', 'pt', 'fr', 'tr']; // en is default, not needed in here!
  1460. if (language != null) {
  1461. this.MyLanguage = language;
  1462. }
  1463. },
  1464. members: {
  1465. MyLanguage: "en",
  1466. Languages: null,
  1467. Data: null,
  1468.  
  1469. loadData: function (language) {
  1470. var l = this.Languages.indexOf(language);
  1471.  
  1472. if (l < 0) {
  1473. this.Data = null;
  1474. return;
  1475. }
  1476.  
  1477. this.Data = new Object();
  1478. this.Data["Collect all packages"] = ["Alle Pakete einsammeln", "Recolher todos os pacotes", "Récupérez tous les paquets", "Tüm paketleri topla"][l];
  1479. this.Data["Overall production"] = ["Produktionsübersicht", "Produção global", "La production globale", "Genel üretim"][l];
  1480. this.Data["Army overview"] = ["Truppenübersicht", "Vista Geral de Exército", "Armée aperçu", "Ordu önizlemesi"][l];
  1481. this.Data["Base resources"] = ["Basis Ressourcen", "Recursos base", "ressources de base", "Üs önizlemesi"][l];
  1482. this.Data["Main menu"] = ["Hauptmenü", "Menu Principal", "menu principal", "Ana menü"][l];
  1483. this.Data["Repair all units"] = ["Alle Einheiten reparieren", "Reparar todas as unidades", "Réparer toutes les unités", "Tüm üniteleri onar"][l];
  1484. this.Data["Repair all defense buildings"] = ["Alle Verteidigungsgebäude reparieren", "Reparar todos os edifícios de defesa", "Réparer tous les bâtiments de défense", "Tüm savunma binalarını onar"][l];
  1485. this.Data["Repair all buildings"] = ["Alle Gebäurde reparieren", "Reparar todos os edifícios", "Réparer tous les bâtiments", "Tüm binaları onar"][l];
  1486. this.Data["Base status overview"] = ["Basisübersicht", "Estado geral da base", "aperçu de l'état de base", "Üs durumu önizlemesi"][l];
  1487. this.Data["Upgrade priority overview"] = ["Upgrade Übersicht", "Prioridade de upgrades", "aperçu des priorités de mise à niveau", "Yükseltme önceliği önizlemesi"][l];
  1488. this.Data["MaelstromTools Preferences"] = ["MaelstromTools Einstellungen", "Preferências de MaelstromTools", "Préférences MaelstromTools", "MaelstromTools Ayarları"][l];
  1489. this.Data["Options"] = ["Einstellungen", "Opções", "Options", "Seçenekler"][l];
  1490. this.Data["Target out of range, no resource calculation possible"] = ["Ziel nicht in Reichweite, kann die plünderbaren Ressourcen nicht berechnen", "Alvo fora do alcance, não é possivel calcular os recursos", "Cible hors de portée, pas de calcul de ressources possible",
  1491. "Hedef menzil dışında, kaynak hesaplaması olanaksız"][l];
  1492. this.Data["Lootable resources"] = ["Plünderbare Ressourcen", "Recursos roubáveis", "Ressources à piller", "Yağmalanabilir kaynaklar"][l];
  1493. this.Data["per CP"] = ["pro KP", "por PC", "par PC", "KP başına"][l];
  1494. this.Data["2nd run"] = ["2. Angriff", "2º ataque", "2° attaque", "2. saldırı"][l];
  1495. this.Data["3rd run"] = ["3. Angriff", "3º ataque", "3° attaque", "3. saldırı"][l];
  1496. this.Data["Calculating resources..."] = ["Berechne plünderbare Ressourcen...", "A calcular recursos...", "calcul de ressources ...", "Kaynaklar hesaplanıyor..."][l];
  1497. this.Data["Next MCV"] = ["MBF", "MCV", "VCM"][l];
  1498. this.Data["Show time to next MCV"] = ["Zeige Zeit bis zum nächsten MBF", "Mostrar tempo restante até ao próximo MCV", "Afficher l'heure pour le prochain VCM ", "Sırdaki MCV için gereken süreyi göster"][l];
  1499. this.Data["Show lootable resources (restart required)"] = ["Zeige plünderbare Ressourcen (Neustart nötig)", "Mostrar recursos roubáveis (é necessário reiniciar)", "Afficher les ressources fouiller (redémarrage nécessaire)", "Yağmalanabilir kaynakları göster (yeniden başlatma gerekli)"][l];
  1500. this.Data["Use dedicated Main Menu (restart required)"] = ["Verwende extra Hauptmenü (Neustart nötig)", "Usar botão para o Menu Principal (é necessário reiniciar)", "Utiliser dédiée du menu principal (redémarrage nécessaire)", "Ana menü tuşunu kullan (yeniden başlatma gerekli)"][l];
  1501. this.Data["Autocollect packages"] = ["Sammle Pakete automatisch", "Auto recolher pacotes", "paquets autocollecté", "Paketleri otomatik topla"][l];
  1502. this.Data["Autorepair units"] = ["Repariere Einheiten automatisch", "Auto reparar o exército", "unités autoréparé", "Üniteleri otomatik onar"][l];
  1503. this.Data["Autorepair defense (higher prio than buildings)"] = ["Repariere Verteidigung automatisch (höhere Prio als Gebäude)", "Auto reparar defesa (maior prioridade do que os edifícios)", "réparation automatique la défense (priorité plus élevé que les bâtiments) ", "Savunmayı otomatik onar (binalardan daha yüksek öncelikli olarak)"][l];
  1504. this.Data["Autorepair buildings"] = ["Repariere Gebäude automatisch", "Auto reparar edifícios", "bâtiments autoréparé", "Binaları otomatik onar"][l];
  1505. this.Data["Automatic interval in minutes"] = ["Auto-Intervall in Minuten", "Intervalo de tempo automático (em minutos)", "intervalle automatique en quelques minutes", "Otomatik toplama aralığı (dk)"][l];
  1506. this.Data["Apply changes"] = ["Speichern", "Confirmar", "Appliquer changements", "Uygula"][l];
  1507. this.Data["Discard changes"] = ["Abbrechen", "Cancelar", "Annuler changements", "İptal"][l];
  1508. this.Data["Reset to default"] = ["Auf Standard zurücksetzen", "Definições padrão", "Réinitialiser", "Sıfırla"][l];
  1509. this.Data["Continuous"] = ["Kontinuierlich", "Contínua", "continue", "Sürekli"][l];
  1510. this.Data["Bonus"] = ["Pakete", "Bónus", "Bonus", "Bonus"][l];
  1511. this.Data["POI"] = ["POI", "POI", "POI", "POI"][l];
  1512. this.Data["Total / h"] = ["Gesamt / h", "Total / h", "Total / h", "Toplam / sa."][l];
  1513. this.Data["Repaircharges"] = ["Reparaturzeiten", "Custo de reparação", "frais de réparation", "Onarım maliyeti"][l];
  1514. this.Data["Repairtime"] = ["Max. verfügbar", "Tempo de reparação", "Temps de réparation", "Onarım süresi"][l];
  1515. this.Data["Attacks"] = ["Angriffe", "Ataques", "Attaques", "Saldırılar"][l];
  1516. this.Data[MaelstromTools.Statics.Infantry] = ["Infanterie", "Infantaria", "Infanterie", "Piyade"][l];
  1517. this.Data[MaelstromTools.Statics.Vehicle] = ["Fahrzeuge", "Veículos", "Vehicule", "Motorlu B."][l];
  1518. this.Data[MaelstromTools.Statics.Aircraft] = ["Flugzeuge", "Aeronaves", "Aviation", "Hava A."][l];
  1519. this.Data[MaelstromTools.Statics.Tiberium] = ["Tiberium", "Tibério", "Tiberium", "Tiberium"][l];
  1520. this.Data[MaelstromTools.Statics.Crystal] = ["Kristalle", "Cristal", "Cristal", "Kristal"][l];
  1521. this.Data[MaelstromTools.Statics.Power] = ["Strom", "Potência", "Energie", "Güç"][l];
  1522. this.Data[MaelstromTools.Statics.Dollar] = ["Credits", "Créditos", "Crédit", "Kredi"][l];
  1523. this.Data[MaelstromTools.Statics.Research] = ["Forschung", "Investigação", "Recherche", "Araştırma"][l];
  1524. this.Data["Base"] = ["Basis", "Base", "Base", "Üs"][l];
  1525. this.Data["Defense"] = ["Verteidigung", "Defesa", "Défense", "Savunma"][l];
  1526. this.Data["Army"] = ["Armee", "Exército", "Armée", "Ordu"][l];
  1527. this.Data["Level"] = ["Stufe", "Nível", "Niveau", "Seviye"][l];
  1528. this.Data["Buildings"] = ["Gebäude", "Edifícios", "Bâtiments", "Binalar"][l];
  1529. this.Data["Health"] = ["Leben", "Vida", "Santé", "Sağlık"][l];
  1530. this.Data["Units"] = ["Einheiten", "Unidades", "Unités", "Üniteler"][l];
  1531. this.Data["Hide Mission Tracker"] = ["Missionsfenster ausblenden", "Esconder janela das Missões", "Cacher la fenêtre de mission", "Görev İzleyicisini Gizle"][l];
  1532. this.Data["none"] = ["keine", "nenhum", "aucun", "hiçbiri"][l];
  1533. this.Data["Cooldown"] = ["Cooldown", "Relocalização", "Recharge", "Cooldown"][l];
  1534. this.Data["Protection"] = ["Geschützt bis", "Protecção", "Protection", "Koruma"][l];
  1535. this.Data["Available weapon"] = ["Verfügbare Artillerie", "Apoio disponível", "arme disponible", "Mevcut silah"][l];
  1536. this.Data["Calibrated on"] = ["Kalibriert auf", "Calibrado em", "Calibré sur ", "Kalibreli"][l];
  1537. this.Data["Total resources"] = ["Gesamt", "Total de recursos", "Ressources totales", "Toplam kaynaklar"][l];
  1538. this.Data["Max. storage"] = ["Max. Kapazität", "Armazenamento Máx.", "Max. de stockage", "Maks. Depo"][l];
  1539. this.Data["Storage full!"] = ["Lager voll!", "Armazenamento cheio!", "Stockage plein", "Depo dolu!"][l];
  1540. this.Data["Storage"] = ["Lagerstand", "Armazenamento", "Stockage", "Depo"][l];
  1541. this.Data["display only top buildings"] = ["Nur Top-Gebäude anzeigen", "Mostrar apenas melhores edifícios", "afficher uniquement les bâtiments principaux", "yalnızca en iyi binaları göster"][l];
  1542. this.Data["display only affordable buildings"] = ["Nur einsetzbare Gebäude anzeigen", "Mostrar apenas edíficios acessíveis", "afficher uniquement les bâtiments abordables", "yalnızca satın alınabilir binaları göster"][l];
  1543. this.Data["City"] = ["Stadt", "Base", "Base", "Şehir"][l];
  1544. this.Data["Type (coord)"] = ["Typ (Koord.)", "Escrever (coord)", "Type (coord)", "Tip (koord.)"][l];
  1545. this.Data["to Level"] = ["Auf Stufe", "para nível", "à Niveau ", "Seviye için"][l];
  1546. this.Data["Gain/h"] = ["Zuwachs/h", "Melhoria/h", "Gain / h", "Kazanç / sa."][l];
  1547. this.Data["Factor"] = ["Faktor", "Factor", "Facteur", "Faktör"][l];
  1548. this.Data["Tib/gain"] = ["Tib./Zuwachs", "Tib/melhoria", "Tib / gain", "Tib/Kazanç"][l];
  1549. this.Data["Pow/gain"] = ["Strom/Zuwachs", "Potencia/melhoria", "Puissance / Gain", "Güç/Kazanç"][l];
  1550. this.Data["ETA"] = ["Verfügbar in", "Tempo restante", "Temps restant", "Kalan Zaman"][l];
  1551. this.Data["Upgrade"] = ["Aufrüsten", "Upgrade", "Upgrade", "Yükselt"][l];
  1552. this.Data["Powerplant"] = ["Kratfwerk", "Central de Energia", "Centrale", "Güç Santrali"][l];
  1553. this.Data["Refinery"] = ["Raffinerie", "Refinaria", "Raffinerie", "Rafineri"][l];
  1554. this.Data["Harvester"] = ["Sammler", "Harvester", "Collecteur", "Biçerdöver"][l];
  1555. this.Data["Silo"] = ["Silo", "Silo", "Silo", "Silo"][l];
  1556. this.Data["Accumulator"] = ["Akkumulator", "Acumulador", "Accumulateur", "Akümülatör"][l];
  1557. this.Data["Calibrate support"] = ["Artillerie kalibrieren", "Calibrar apoio", "Calibrer soutien", "Takviyeyi kalibre et"][l];
  1558. this.Data["Access"] = ["Öffne", "Aceder", "Accès ", "Aç"][l];
  1559. this.Data["Focus on"] = ["Zentriere auf", "Concentrar em", "Centré sur", "Odaklan"][l];
  1560. this.Data["Possible attacks from this base (available CP)"] = ["Mögliche Angriffe (verfügbare KP)", "Possible attacks from this base (available CP)","Possible attacks from this base (available CP)", "Bu üsten yapılması mümkün olan saldırılar (mevcut KP)"][l];
  1561. //this.Data[""] = [""][l];
  1562. },
  1563. get: function (ident) {
  1564. return this.gt(ident);
  1565. },
  1566. gt: function (ident) {
  1567. if (!this.Data || !this.Data[ident]) {
  1568. /*if(!parseInt(ident.substr(0, 1), 10) && ident != "0") {
  1569. console.log("missing language data: " + ident);
  1570. }*/
  1571. return ident;
  1572. }
  1573. return this.Data[ident];
  1574. }
  1575. }
  1576. }),
  1577.  
  1578. // define Base
  1579. qx.Class.define("MaelstromTools.Base", {
  1580. type: "singleton",
  1581. extend: qx.core.Object,
  1582. members: {
  1583. /* Desktop */
  1584. timerInterval: 1500,
  1585. mainTimerInterval: 5000,
  1586. lootStatusInfoInterval: null,
  1587. images: null,
  1588. mWindows: null,
  1589. mainMenuWindow: null,
  1590.  
  1591. itemsOnDesktop: null,
  1592. itemsOnDesktopCount: null,
  1593. itemsInMainMenu: null,
  1594. itemsInMainMenuCount: null,
  1595. buttonCollectAllResources: null,
  1596. buttonRepairAllUnits: null,
  1597. buttonRepairAllBuildings: null,
  1598.  
  1599. lootWidget: null,
  1600.  
  1601. initialize: function () {
  1602. try {
  1603. //console.log(qx.locale.Manager.getInstance().getLocale());
  1604. Lang.loadData(qx.locale.Manager.getInstance().getLocale());
  1605. //console.log("Client version: " + MaelstromTools.Wrapper.GetClientVersion());
  1606. this.itemsOnDesktopCount = new Array();
  1607. this.itemsOnDesktop = new Object();
  1608. this.itemsInMainMenuCount = new Array();
  1609. this.itemsInMainMenu = new Object();
  1610.  
  1611. var fileManager = ClientLib.File.FileManager.GetInstance();
  1612. //ui/icons/icon_mainui_defense_button
  1613. //ui/icons/icon_mainui_base_button
  1614. //ui/icons/icon_army_points
  1615. //icon_def_army_points
  1616. var factionText = ClientLib.Base.Util.GetFactionGuiPatchText();
  1617. this.createNewImage(MaelstromTools.Statics.Tiberium, "ui/common/icn_res_tiberium.png", fileManager);
  1618. this.createNewImage(MaelstromTools.Statics.Crystal, "ui/common/icn_res_chrystal.png", fileManager);
  1619. this.createNewImage(MaelstromTools.Statics.Power, "ui/common/icn_res_power.png", fileManager);
  1620. this.createNewImage(MaelstromTools.Statics.Dollar, "ui/common/icn_res_dollar.png", fileManager);
  1621. this.createNewImage(MaelstromTools.Statics.Research, "ui/common/icn_res_research.png", fileManager);
  1622. this.createNewImage("Sum", "ui/common/icn_build_slots.png", fileManager);
  1623. this.createNewImage("AccessBase", "ui/" + factionText + "/icons/icon_mainui_enterbase.png", fileManager);
  1624. this.createNewImage("FocusBase", "ui/" + factionText + "/icons/icon_mainui_focusbase.png", fileManager);
  1625. this.createNewImage("Packages", "ui/" + factionText + "/icons/icon_collect_packages.png", fileManager);
  1626. this.createNewImage("RepairAllUnits", "ui/" + factionText + "/icons/icon_army_points.png", fileManager);
  1627. this.createNewImage("RepairAllBuildings", "ui/" + factionText + "/icons/icn_build_slots.png", fileManager);
  1628. this.createNewImage("ResourceOverviewMenu", "ui/common/icn_res_chrystal.png", fileManager);
  1629. this.createNewImage("ProductionMenu", "ui/" + factionText + "/icons/icn_build_slots.png", fileManager);
  1630. this.createNewImage("RepairTimeMenu", "ui/" + factionText + "/icons/icon_repair_all_button.png", fileManager);
  1631. this.createNewImage("Crosshair", "ui/icons/icon_support_tnk_white.png", fileManager);
  1632. this.createNewImage("UpgradeBuilding", "ui/" + factionText + "/icons/icon_building_detail_upgrade.png", fileManager);
  1633.  
  1634. this.createNewWindow("MainMenu", "R", 125, 140, 120, 100, "B");
  1635. this.createNewWindow("Production", "L", 120, 60, 340, 140);
  1636. this.createNewWindow("RepairTime", "L", 120, 60, 340, 140);
  1637. this.createNewWindow("ResourceOverview", "L", 120, 60, 340, 140);
  1638. this.createNewWindow("BaseStatusOverview", "L", 120, 60, 340, 140);
  1639. this.createNewWindow("Preferences", "L", 120, 60, 440, 140);
  1640. this.createNewWindow("UpgradePriority", "L", 120, 60, 870, 400);
  1641.  
  1642. if (!this.mainMenuWindow) {
  1643. this.mainMenuWindow = new qx.ui.popup.Popup(new qx.ui.layout.Canvas()).set({
  1644. //backgroundColor: "#303030",
  1645. padding: 5,
  1646. paddingRight: 0
  1647. });
  1648. if (MT_Preferences.Settings.useDedicatedMainMenu) {
  1649. this.mainMenuWindow.setPlaceMethod("mouse");
  1650. this.mainMenuWindow.setPosition("top-left");
  1651. } else {
  1652. this.mainMenuWindow.setPlaceMethod("widget");
  1653. this.mainMenuWindow.setPosition("bottom-right");
  1654. this.mainMenuWindow.setAutoHide(false);
  1655. this.mainMenuWindow.setBackgroundColor("transparent");
  1656. this.mainMenuWindow.setShadow(null);
  1657. this.mainMenuWindow.setDecorator(new qx.ui.decoration.Background());
  1658. }
  1659. }
  1660.  
  1661. var desktopPositionModifier = 0;
  1662.  
  1663. this.buttonCollectAllResources = this.createDesktopButton(Lang.gt("Collect all packages"), "Packages", true, this.desktopPosition(desktopPositionModifier));
  1664. this.buttonCollectAllResources.addListener("execute", this.collectAllPackages, this);
  1665.  
  1666. var openProductionWindowButton = this.createDesktopButton(Lang.gt("Overall production"), "ProductionMenu", false, this.desktopPosition(desktopPositionModifier));
  1667. openProductionWindowButton.addListener("execute", function () {
  1668. window.MaelstromTools.Production.getInstance().openWindow("Production", Lang.gt("Overall production"));
  1669. }, this);
  1670.  
  1671. var openResourceOverviewWindowButton = this.createDesktopButton(Lang.gt("Base resources"), "ResourceOverviewMenu", false, this.desktopPosition(desktopPositionModifier));
  1672. openResourceOverviewWindowButton.addListener("execute", function () {
  1673. window.MaelstromTools.ResourceOverview.getInstance().openWindow("ResourceOverview", Lang.gt("Base resources"));
  1674. }, this);
  1675.  
  1676. desktopPositionModifier++;
  1677. var openMainMenuButton = this.createDesktopButton(Lang.gt("Main menu"), "ProductionMenu", false, this.desktopPosition(desktopPositionModifier));
  1678. openMainMenuButton.addListener("click", function (e) {
  1679. this.mainMenuWindow.placeToMouse(e);
  1680. this.mainMenuWindow.show();
  1681. }, this);
  1682.  
  1683. this.buttonRepairAllUnits = this.createDesktopButton(Lang.gt("Repair all units"), "RepairAllUnits", true, this.desktopPosition(desktopPositionModifier));
  1684. this.buttonRepairAllUnits.addListener("execute", this.repairAllUnits, this);
  1685.  
  1686. this.buttonRepairAllBuildings = this.createDesktopButton(Lang.gt("Repair all buildings"), "RepairAllBuildings", true, this.desktopPosition(desktopPositionModifier));
  1687. this.buttonRepairAllBuildings.addListener("execute", this.repairAllBuildings, this);
  1688.  
  1689. var openRepairTimeWindowButton = this.createDesktopButton(Lang.gt("Army overview"), "RepairTimeMenu", false, this.desktopPosition(desktopPositionModifier));
  1690. openRepairTimeWindowButton.addListener("execute", function () {
  1691. window.MaelstromTools.RepairTime.getInstance().openWindow("RepairTime", Lang.gt("Army overview"));
  1692. }, this);
  1693.  
  1694. var openBaseStatusOverview = this.createDesktopButton(Lang.gt("Base status overview"), "Crosshair", false, this.desktopPosition(desktopPositionModifier));
  1695. openBaseStatusOverview.addListener("execute", function () {
  1696. window.MaelstromTools.BaseStatus.getInstance().openWindow("BaseStatusOverview", Lang.gt("Base status overview"));
  1697. }, this);
  1698.  
  1699. desktopPositionModifier++;
  1700. var openHuffyUpgradeOverview = this.createDesktopButton(Lang.gt("Upgrade priority overview"), "UpgradeBuilding", false, this.desktopPosition(desktopPositionModifier));
  1701. openHuffyUpgradeOverview.addListener("execute", function () {
  1702. window.HuffyTools.UpgradePriorityGUI.getInstance().openWindow("UpgradePriority", Lang.gt("Upgrade priority overview"));
  1703. }, this);
  1704.  
  1705. desktopPositionModifier++;
  1706. var preferencesButton = new qx.ui.form.Button(Lang.gt("Options")).set({
  1707. appearance: "button-text-small",
  1708. width: 100,
  1709. minWidth: 100,
  1710. maxWidth: 100
  1711. });
  1712. preferencesButton.setUserData("desktopPosition", this.desktopPosition(desktopPositionModifier));
  1713. preferencesButton.addListener("execute", function () {
  1714. window.MaelstromTools.Preferences.getInstance().openWindow("Preferences", Lang.gt("MaelstromTools Preferences"), true);
  1715. }, this);
  1716.  
  1717. if (MT_Preferences.Settings.useDedicatedMainMenu) {
  1718. this.addToDesktop("MainMenu", openMainMenuButton);
  1719. }
  1720. this.addToMainMenu("ResourceOverviewMenu", openResourceOverviewWindowButton);
  1721. this.addToMainMenu("ProductionMenu", openProductionWindowButton);
  1722. this.addToMainMenu("BaseStatusMenu", openBaseStatusOverview);
  1723. this.addToMainMenu("RepairTimeMenu", openRepairTimeWindowButton);
  1724. this.addToMainMenu("UpgradeBuilding", openHuffyUpgradeOverview);
  1725.  
  1726. this.addToMainMenu("PreferencesMenu", preferencesButton);
  1727.  
  1728. if (!MT_Preferences.Settings.useDedicatedMainMenu) {
  1729. this.mainMenuWindow.show();
  1730. var target = qx.core.Init.getApplication().getOptionsBar(); //getServerBar(); //qx.core.Init.getApplication().getUIItem(ClientLib.Data.Missions.PATH.BAR_APPOINTMENTS);
  1731. this.mainMenuWindow.placeToWidget(target, true);
  1732. }
  1733.  
  1734. webfrontend.gui.chat.ChatWidget.recvbufsize = MaelstromTools.LocalStorage.get(MaelstromTools.Preferences.CHATHISTORYLENGTH, 64);
  1735. this.runSecondlyTimer();
  1736. this.runMainTimer();
  1737. this.runAutoCollectTimer();
  1738. } catch (e) {
  1739. console.log("MaelstromTools.initialize: ", e);
  1740. }
  1741. },
  1742.  
  1743. desktopPosition: function (modifier) {
  1744. if (!modifier) modifier = 0;
  1745. return modifier;
  1746. },
  1747.  
  1748. createDesktopButton: function (title, imageName, isNotification, desktopPosition) {
  1749. try {
  1750. if (!isNotification) {
  1751. isNotification = false;
  1752. }
  1753. if (!desktopPosition) {
  1754. desktopPosition = this.desktopPosition();
  1755. }
  1756. var desktopButton = new qx.ui.form.Button(null, this.images[imageName]).set({
  1757. toolTipText: title,
  1758. width: 50,
  1759. height: 40,
  1760. maxWidth: 50,
  1761. maxHeight: 40,
  1762. appearance: (isNotification ? "button-standard-nod" : "button-playarea-mode-frame"), //"button-standard-"+factionText), button-playarea-mode-red-frame
  1763. center: true
  1764. });
  1765.  
  1766. desktopButton.setUserData("isNotification", isNotification);
  1767. desktopButton.setUserData("desktopPosition", desktopPosition);
  1768. return desktopButton;
  1769. } catch (e) {
  1770. console.log("MaelstromTools.createDesktopButton: ", e);
  1771. }
  1772. },
  1773.  
  1774. createNewImage: function (name, path, fileManager) {
  1775. try {
  1776. if (!this.images) {
  1777. this.images = new Object();
  1778. }
  1779. if (!fileManager) {
  1780. return;
  1781. }
  1782.  
  1783. this.images[name] = fileManager.GetPhysicalPath(path);
  1784. } catch (e) {
  1785. console.log("MaelstromTools.createNewImage: ", e);
  1786. }
  1787. },
  1788.  
  1789. createNewWindow: function (name, align, x, y, w, h, alignV) {
  1790. try {
  1791. if (!this.mWindows) {
  1792. this.mWindows = new Object();
  1793. }
  1794. this.mWindows[name] = new Object();
  1795. this.mWindows[name]["Align"] = align;
  1796. this.mWindows[name]["AlignV"] = alignV;
  1797. this.mWindows[name]["x"] = x;
  1798. this.mWindows[name]["y"] = y;
  1799. this.mWindows[name]["w"] = w;
  1800. this.mWindows[name]["h"] = h;
  1801. } catch (e) {
  1802. console.log("MaelstromTools.createNewWindow: ", e);
  1803. }
  1804. },
  1805.  
  1806. addToMainMenu: function (name, button) {
  1807. try {
  1808. /*if(!this.useDedicatedMainMenu) {
  1809. return;
  1810. }*/
  1811. if (this.itemsInMainMenu[name] != null) {
  1812. return;
  1813. }
  1814. var desktopPosition = button.getUserData("desktopPosition");
  1815. var isNotification = button.getUserData("isNotification");
  1816. if (!desktopPosition) {
  1817. desktopPosition = this.desktopPosition();
  1818. }
  1819. if (!isNotification) {
  1820. isNotification = false;
  1821. }
  1822.  
  1823. if (isNotification && MT_Preferences.Settings.useDedicatedMainMenu) {
  1824. this.addToDesktop(name, button);
  1825. } else {
  1826. if (!this.itemsInMainMenuCount[desktopPosition]) {
  1827. this.itemsInMainMenuCount[desktopPosition] = 0;
  1828. }
  1829. this.mainMenuWindow.add(button, {
  1830. right: 5 + (52 * this.itemsInMainMenuCount[desktopPosition]),
  1831. top: 0 + (42 * (desktopPosition)) //bottom: 0 - (42 * (desktopPosition - 1))
  1832. });
  1833.  
  1834. this.itemsInMainMenu[name] = button;
  1835. this.itemsInMainMenuCount[desktopPosition]++;
  1836. }
  1837. } catch (e) {
  1838. console.log("MaelstromTools.addToMainMenu: ", e);
  1839. }
  1840. },
  1841.  
  1842. removeFromMainMenu: function (name, rearrange) {
  1843. try {
  1844. if (rearrange == null) {
  1845. rearrange = true;
  1846. }
  1847. if (this.itemsOnDesktop[name] != null) {
  1848. var isNotification = this.itemsOnDesktop[name].getUserData("isNotification");
  1849. if (!isNotification) {
  1850. isNotification = false;
  1851. }
  1852. if (isNotification && MT_Preferences.Settings.useDedicatedMainMenu) {
  1853. this.removeFromDesktop(name, rearrange);
  1854. }
  1855. } else if (this.itemsInMainMenu[name] != null) {
  1856. var desktopPosition = this.itemsInMainMenu[name].getUserData("desktopPosition");
  1857. var isNotification = this.itemsInMainMenu[name].getUserData("isNotification");
  1858. if (!desktopPosition) {
  1859. desktopPosition = this.desktopPosition();
  1860. }
  1861. if (!isNotification) {
  1862. isNotification = false;
  1863. }
  1864.  
  1865. this.mainMenuWindow.remove(this.itemsInMainMenu[name]);
  1866. this.itemsInMainMenu[name] = null;
  1867. this.itemsInMainMenuCount[desktopPosition]--;
  1868.  
  1869. if (rearrange && this.itemsInMainMenu[desktopPosition] > 1) {
  1870. var tmpItems = new Object();
  1871. // remove notifications
  1872. for (var itemName in this.itemsOnDesktop) {
  1873. if (this.itemsInMainMenu[itemName] == null) {
  1874. continue;
  1875. }
  1876. if (!isNotification) {
  1877. continue;
  1878. }
  1879. tmpItems[itemName] = this.itemsInMainMenu[itemName];
  1880. this.removeFromMainMenu(itemName, false);
  1881. }
  1882. // rearrange notifications
  1883. for (var itemName2 in tmpItems) {
  1884. var tmp = tmpItems[itemName2];
  1885. if (tmp == null) {
  1886. continue;
  1887. }
  1888. this.addToMainMenu(itemName2, tmp);
  1889. }
  1890. }
  1891. }
  1892. } catch (e) {
  1893. console.log("MaelstromTools.removeFromDesktop: ", e);
  1894. }
  1895. },
  1896.  
  1897. addToDesktop: function (name, button) {
  1898. try {
  1899. if (this.itemsOnDesktop[name] != null) {
  1900. return;
  1901. }
  1902. var desktopPosition = button.getUserData("desktopPosition");
  1903. if (!desktopPosition) {
  1904. desktopPosition = this.desktopPosition();
  1905. }
  1906.  
  1907. if (!this.itemsOnDesktopCount[desktopPosition]) {
  1908. this.itemsOnDesktopCount[desktopPosition] = 0;
  1909. }
  1910.  
  1911. var app = qx.core.Init.getApplication();
  1912. //var navBar = app.getNavigationBar();
  1913.  
  1914. // console.log("add to Desktop at pos: " + this.itemsOnDesktopCount);
  1915. app.getDesktop().add(button, {
  1916. //right: navBar.getBounds().width + (52 * this.itemsOnDesktopCount[desktopPosition]),
  1917. //top: 42 * (desktopPosition - 1)
  1918. right: 5 + (52 * this.itemsOnDesktopCount[desktopPosition]),
  1919. //top: this.initialAppointmentBarHeight + 125 + (42 * (desktopPosition - 1))
  1920. bottom: 140 - (42 * (desktopPosition - 1))
  1921. });
  1922.  
  1923. this.itemsOnDesktop[name] = button;
  1924. this.itemsOnDesktopCount[desktopPosition]++;
  1925. } catch (e) {
  1926. console.log("MaelstromTools.addToDesktop: ", e);
  1927. }
  1928. },
  1929.  
  1930. removeFromDesktop: function (name, rearrange) {
  1931. try {
  1932. if (rearrange == null) {
  1933. rearrange = true;
  1934. }
  1935. var app = qx.core.Init.getApplication();
  1936.  
  1937. if (this.itemsOnDesktop[name] != null) {
  1938. var desktopPosition = this.itemsOnDesktop[name].getUserData("desktopPosition");
  1939. var isNotification = this.itemsOnDesktop[name].getUserData("isNotification");
  1940. if (!desktopPosition) {
  1941. desktopPosition = this.desktopPosition();
  1942. }
  1943. if (!isNotification) {
  1944. isNotification = false;
  1945. }
  1946.  
  1947. app.getDesktop().remove(this.itemsOnDesktop[name]);
  1948. this.itemsOnDesktop[name] = null;
  1949. this.itemsOnDesktopCount[desktopPosition]--;
  1950.  
  1951. if (rearrange && this.itemsOnDesktopCount[desktopPosition] > 1) {
  1952. var tmpItems = new Object();
  1953. // remove notifications
  1954. for (var itemName in this.itemsOnDesktop) {
  1955. if (this.itemsOnDesktop[itemName] == null) {
  1956. continue;
  1957. }
  1958. if (!this.itemsOnDesktop[itemName].getUserData("isNotification")) {
  1959. continue;
  1960. }
  1961. tmpItems[itemName] = this.itemsOnDesktop[itemName];
  1962. this.removeFromDesktop(itemName, false);
  1963. }
  1964. // rearrange notifications
  1965. for (var itemName2 in tmpItems) {
  1966. var tmp = tmpItems[itemName2];
  1967. if (tmp == null) {
  1968. continue;
  1969. }
  1970. this.addToMainMenu(itemName2, tmp);
  1971. }
  1972. }
  1973. }
  1974. } catch (e) {
  1975. console.log("MaelstromTools.removeFromDesktop: ", e);
  1976. }
  1977. },
  1978.  
  1979. runSecondlyTimer: function () {
  1980. try {
  1981. this.calculateCostsForNextMCV();
  1982.  
  1983. var self = this;
  1984. window.setTimeout(function () {
  1985. self.runSecondlyTimer();
  1986. }, 1000);
  1987. } catch (e) {
  1988. console.log("MaelstromTools.runSecondlyTimer: ", e);
  1989. }
  1990. },
  1991.  
  1992. runMainTimer: function () {
  1993. try {
  1994. this.checkForPackages();
  1995. if (CCTAWrapperIsInstalled()) {
  1996. this.checkRepairAllUnits();
  1997. this.checkRepairAllBuildings();
  1998. }
  1999.  
  2000. var missionTracker = typeof (qx.core.Init.getApplication().getMissionsBar) === 'function' ? qx.core.Init.getApplication().getMissionsBar() : qx.core.Init.getApplication().getMissionTracker(); //fix for PerforceChangelist>=376877
  2001. if (MT_Preferences.Settings.autoHideMissionTracker) {
  2002. if (missionTracker.isVisible()) {
  2003. missionTracker.hide();
  2004. }
  2005. if (typeof (qx.core.Init.getApplication().getMissionsBar) === 'function') {
  2006. if (qx.core.Init.getApplication().getMissionsBar().getSizeHint().height != 0) {
  2007. qx.core.Init.getApplication().getMissionsBar().getSizeHint().height = 0;
  2008. qx.core.Init.getApplication().triggerDesktopResize();
  2009. }
  2010. }
  2011. } else {
  2012. if (!missionTracker.isVisible()) {
  2013. missionTracker.show();
  2014. if (typeof (qx.core.Init.getApplication().getMissionsBar) === 'function') {
  2015. qx.core.Init.getApplication().getMissionsBar().initHeight();
  2016. qx.core.Init.getApplication().triggerDesktopResize();
  2017. }
  2018. }
  2019. }
  2020. var self = this;
  2021. window.setTimeout(function () {
  2022. self.runMainTimer();
  2023. }, this.mainTimerInterval);
  2024. } catch (e) {
  2025. console.log("MaelstromTools.runMainTimer: ", e);
  2026. }
  2027. },
  2028.  
  2029. runAutoCollectTimer: function () {
  2030. try {
  2031. //console.log("runAutoCollectTimer ", MT_Preferences.Settings.AutoCollectTimer);
  2032. if (!CCTAWrapperIsInstalled()) return; // run timer only then wrapper is running
  2033. if (this.checkForPackages() && MT_Preferences.Settings.autoCollectPackages) {
  2034. this.collectAllPackages();
  2035. }
  2036. if (this.checkRepairAllUnits() && MT_Preferences.Settings.autoRepairUnits) {
  2037. this.repairAllUnits();
  2038. }
  2039. if (this.checkRepairAllBuildings() && MT_Preferences.Settings.autoRepairBuildings) {
  2040. this.repairAllBuildings();
  2041. }
  2042.  
  2043. var self = this;
  2044. window.setTimeout(function () {
  2045. self.runAutoCollectTimer();
  2046. }, MT_Preferences.Settings.AutoCollectTimer * 60000);
  2047. } catch (e) {
  2048. console.log("MaelstromTools.runMainTimer: ", e);
  2049. }
  2050. },
  2051.  
  2052. openWindow: function (windowObj, windowName, skipMoveWindow) {
  2053. try {
  2054. if (!windowObj.isVisible()) {
  2055. if (windowName == "MainMenu") {
  2056. windowObj.show();
  2057. } else {
  2058. if (!skipMoveWindow) {
  2059. this.moveWindow(windowObj, windowName);
  2060. }
  2061. windowObj.open();
  2062. }
  2063. }
  2064. } catch (e) {
  2065. console.log("MaelstromTools.openWindow: ", e);
  2066. }
  2067. },
  2068.  
  2069. moveWindow: function (windowObj, windowName) {
  2070. try {
  2071. var x = this.mWindows[windowName]["x"];
  2072. var y = this.mWindows[windowName]["y"];
  2073. if (this.mWindows[windowName]["Align"] == "R") {
  2074. x = qx.bom.Viewport.getWidth(window) - this.mWindows[windowName]["x"];
  2075. }
  2076. if (this.mWindows[windowName]["AlignV"] == "B") {
  2077. y = qx.bom.Viewport.getHeight(window) - this.mWindows[windowName]["y"] - windowObj.height;
  2078. }
  2079. windowObj.moveTo(x, y);
  2080. if (windowName != "MainMenu") {
  2081. windowObj.setHeight(this.mWindows[windowName]["h"]);
  2082. windowObj.setWidth(this.mWindows[windowName]["w"]);
  2083. }
  2084. } catch (e) {
  2085. console.log("MaelstromTools.moveWindow: ", e);
  2086. }
  2087. },
  2088.  
  2089. checkForPackages: function () {
  2090. try {
  2091. MT_Cache.updateCityCache();
  2092.  
  2093. for (var cname in MT_Cache.Cities) {
  2094. var ncity = MT_Cache.Cities[cname].Object;
  2095. if (ncity.get_CityBuildingsData().get_HasCollectableBuildings()) {
  2096. this.addToMainMenu("CollectAllResources", this.buttonCollectAllResources);
  2097. return true;
  2098. }
  2099. }
  2100. this.removeFromMainMenu("CollectAllResources");
  2101. return false;
  2102. } catch (e) {
  2103. console.log("MaelstromTools.checkForPackages: ", e);
  2104. return false;
  2105. }
  2106. },
  2107.  
  2108. collectAllPackages: function () {
  2109. try {
  2110. MT_Cache.updateCityCache();
  2111. for (var cname in MT_Cache.Cities) {
  2112. var ncity = MT_Cache.Cities[cname].Object;
  2113. if (ncity.get_CityBuildingsData().get_HasCollectableBuildings()) {
  2114. if (MT_Cache.CityCount <= 1) {
  2115. var buildings = ncity.get_Buildings().d;
  2116. for (var x in buildings) {
  2117. var building = buildings[x];
  2118. if (building.get_ProducesPackages() && building.get_ReadyToCollect()) {
  2119. ClientLib.Net.CommunicationManager.GetInstance().SendCommand("CollectResource",{cityid:ncity.get_Id(), posX:building.get_CoordX(),posY:building.get_CoordY()}, null, null, true);
  2120. }
  2121. }
  2122. } else {
  2123. ncity.CollectAllResources();
  2124. }
  2125. }
  2126. }
  2127. this.removeFromMainMenu("CollectAllResources");
  2128. } catch (e) {
  2129. console.log("MaelstromTools.collectAllPackages: ", e);
  2130. }
  2131. },
  2132.  
  2133. checkRepairAll: function (visMode, buttonName, button) {
  2134. try {
  2135. MT_Cache.updateCityCache();
  2136.  
  2137. for (var cname in MT_Cache.Cities) {
  2138. var ncity = MT_Cache.Cities[cname].Object;
  2139. if (MaelstromTools.Wrapper.CanRepairAll(ncity, visMode)) {
  2140. this.addToMainMenu(buttonName, button);
  2141. return true;
  2142. }
  2143. }
  2144.  
  2145. this.removeFromMainMenu(buttonName);
  2146. return false;
  2147. } catch (e) {
  2148. console.log("MaelstromTools.checkRepairAll: ", e);
  2149. return false;
  2150. }
  2151. },
  2152.  
  2153. checkRepairAllUnits: function () {
  2154. return this.checkRepairAll(ClientLib.Vis.Mode.ArmySetup, "RepairAllUnits", this.buttonRepairAllUnits);
  2155. },
  2156.  
  2157. checkRepairAllBuildings: function () {
  2158. return this.checkRepairAll(ClientLib.Vis.Mode.City, "RepairAllBuildings", this.buttonRepairAllBuildings);
  2159. },
  2160.  
  2161. repairAll: function (visMode, buttonName) {
  2162. try {
  2163. MT_Cache.updateCityCache();
  2164.  
  2165. for (var cname in MT_Cache.Cities) {
  2166. var ncity = MT_Cache.Cities[cname].Object;
  2167. if (MaelstromTools.Wrapper.CanRepairAll(ncity, visMode)) {
  2168. MaelstromTools.Wrapper.RepairAll(ncity, visMode);
  2169. }
  2170.  
  2171. }
  2172. this.removeFromMainMenu(buttonName);
  2173. } catch (e) {
  2174. console.log("MaelstromTools.repairAll: ", e);
  2175. }
  2176. },
  2177.  
  2178. //ClientLib.Data.City.prototype.get_CityRepairData
  2179. //ClientLib.Data.CityRepair.prototype.CanRepairAll
  2180. //ClientLib.Data.CityRepair.prototype.RepairAll
  2181. repairAllUnits: function () {
  2182. try {
  2183. this.repairAll(ClientLib.Vis.Mode.ArmySetup, "RepairAllUnits");
  2184. } catch (e) {
  2185. console.log("MaelstromTools.repairAllUnits: ", e);
  2186. }
  2187. },
  2188.  
  2189. repairAllBuildings: function () {
  2190. try {
  2191. this.repairAll(ClientLib.Vis.Mode.City, "RepairAllBuildings");
  2192. } catch (e) {
  2193. console.log("MaelstromTools.repairAllBuildings: ", e);
  2194. }
  2195. },
  2196.  
  2197. updateLoot: function (ident, visCity, widget) {
  2198. try {
  2199. clearInterval(this.lootStatusInfoInterval);
  2200. if (!MT_Preferences.Settings.showLoot) {
  2201. if (this.lootWidget[ident]) {
  2202. this.lootWidget[ident].removeAll();
  2203. }
  2204. return;
  2205. }
  2206.  
  2207. var baseLoadState = MT_Cache.updateLoot(visCity);
  2208. if (baseLoadState == -2) { // base already cached and base not changed
  2209. return;
  2210. }
  2211.  
  2212. if (!this.lootWidget) {
  2213. this.lootWidget = new Object();
  2214. }
  2215. if (!this.lootWidget[ident]) {
  2216. this.lootWidget[ident] = new qx.ui.container.Composite(new qx.ui.layout.Grid(5, 5));
  2217. this.lootWidget[ident].setTextColor("white");
  2218. widget.add(this.lootWidget[ident]);
  2219. }
  2220. var lootWidget = this.lootWidget[ident];
  2221.  
  2222. var rowIdx = 1;
  2223. var colIdx = 1;
  2224. lootWidget.removeAll();
  2225. switch (baseLoadState) {
  2226. case -1:
  2227. {
  2228. MaelstromTools.Util.addLabel(lootWidget, rowIdx, colIdx++, "Target out of range, no resource calculation possible", null, null, 'bold', null);
  2229. break;
  2230. }
  2231. case 1:
  2232. {
  2233. var Resources = MT_Cache.SelectedBaseResources;
  2234. this.createResourceLabels(lootWidget, ++rowIdx, "Possible attacks from this base (available CP)", Resources, - 1);
  2235. this.createResourceLabels(lootWidget, ++rowIdx, "Lootable resources", Resources, 1);
  2236. this.createResourceLabels(lootWidget, ++rowIdx, "per CP", Resources, 1 * Resources.CPNeeded);
  2237. this.createResourceLabels(lootWidget, ++rowIdx, "2nd run", Resources, 2 * Resources.CPNeeded);
  2238. this.createResourceLabels(lootWidget, ++rowIdx, "3rd run", Resources, 3 * Resources.CPNeeded);
  2239. break;
  2240. }
  2241. default:
  2242. {
  2243. MaelstromTools.Util.addLabel(lootWidget, rowIdx, colIdx++, "Calculating resources...", null, null, 'bold', null);
  2244. this.lootStatusInfoInterval = setInterval(function () {
  2245. MaelstromTools.Base.getInstance().updateLoot(ident, visCity, widget);
  2246. }, 100);
  2247. break;
  2248. }
  2249. }
  2250. } catch (e) {
  2251. console.log("MaelstromTools.updateLoot: ", e);
  2252. }
  2253. },
  2254.  
  2255. createResourceLabels: function (lootWidget, rowIdx, Label, Resources, Modifier) {
  2256. var colIdx = 1;
  2257. var font = (Modifier > 1 ? null : 'bold');
  2258.  
  2259. if (Modifier == -1 && Resources.CPNeeded > 0) {
  2260. Label = Lang.gt(Label) + ": " + Math.floor(ClientLib.Data.MainData.GetInstance().get_Player().GetCommandPointCount() / Resources.CPNeeded);
  2261. MaelstromTools.Util.addLabel(lootWidget, rowIdx, colIdx++, Label, null, 'left', font, null, 9);
  2262. return;
  2263. }
  2264. colIdx = 1;
  2265. if (Modifier > 0) {
  2266. MaelstromTools.Util.addLabel(lootWidget, rowIdx, colIdx++, Lang.gt(Label) + ":", null, null, font);
  2267. MaelstromTools.Util.addImage(lootWidget, rowIdx, colIdx++, MaelstromTools.Util.getImage(MaelstromTools.Statics.Research));
  2268. MaelstromTools.Util.addLabel(lootWidget, rowIdx, colIdx++, MaelstromTools.Wrapper.FormatNumbersCompact(Resources[MaelstromTools.Statics.Research] / Modifier), 50, 'right', font);
  2269. MaelstromTools.Util.addImage(lootWidget, rowIdx, colIdx++, MaelstromTools.Util.getImage(MaelstromTools.Statics.Tiberium));
  2270. MaelstromTools.Util.addLabel(lootWidget, rowIdx, colIdx++, MaelstromTools.Wrapper.FormatNumbersCompact(Resources[MaelstromTools.Statics.Tiberium] / Modifier), 50, 'right', font);
  2271. MaelstromTools.Util.addImage(lootWidget, rowIdx, colIdx++, MaelstromTools.Util.getImage(MaelstromTools.Statics.Crystal));
  2272. MaelstromTools.Util.addLabel(lootWidget, rowIdx, colIdx++, MaelstromTools.Wrapper.FormatNumbersCompact(Resources[MaelstromTools.Statics.Crystal] / Modifier), 50, 'right', font);
  2273. MaelstromTools.Util.addImage(lootWidget, rowIdx, colIdx++, MaelstromTools.Util.getImage(MaelstromTools.Statics.Dollar));
  2274. MaelstromTools.Util.addLabel(lootWidget, rowIdx, colIdx++, MaelstromTools.Wrapper.FormatNumbersCompact(Resources[MaelstromTools.Statics.Dollar] / Modifier), 50, 'right', font);
  2275. MaelstromTools.Util.addImage(lootWidget, rowIdx, colIdx++, MaelstromTools.Util.getImage("Sum"));
  2276. MaelstromTools.Util.addLabel(lootWidget, rowIdx, colIdx++, MaelstromTools.Wrapper.FormatNumbersCompact(Resources["Total"] / Modifier), 50, 'right', font);
  2277. }
  2278. },
  2279.  
  2280. mcvPopup: null,
  2281. mcvPopupX : 0,
  2282. mcvPopupY : 0,
  2283. mcvTimerLabel: null,
  2284. calculateCostsForNextMCV: function () {
  2285. try {
  2286. if (!MT_Preferences.Settings.showCostsForNextMCV) {
  2287. if (this.mcvPopup) {
  2288. this.mcvPopup.close();
  2289. }
  2290. return;
  2291. }
  2292. var player = ClientLib.Data.MainData.GetInstance().get_Player();
  2293. var cw = player.get_Faction();
  2294. var cj = ClientLib.Base.Tech.GetTechIdFromTechNameAndFaction(ClientLib.Base.ETechName.Research_BaseFound, cw);
  2295. var cr = player.get_PlayerResearch();
  2296. var cd = cr.GetResearchItemFomMdbId(cj);
  2297. if (cd == null) {
  2298. if (this.mcvPopup) {
  2299. this.mcvPopup.close();
  2300. }
  2301. return;
  2302. }
  2303.  
  2304. if (!this.mcvPopup) {
  2305. this.mcvPopup = new qx.ui.window.Window("").set({
  2306. contentPadding : 0,
  2307. showMinimize : false,
  2308. showMaximize : false,
  2309. showClose : false,
  2310. resizable : false
  2311. });
  2312. this.mcvPopup.setLayout(new qx.ui.layout.VBox());
  2313. this.mcvPopup.addListener("move", function (e) {
  2314. var base = MaelstromTools.Base.getInstance();
  2315. var size = qx.core.Init.getApplication().getRoot().getBounds();
  2316. var value = size.width - e.getData().left;
  2317. base.mcvPopupX = value < 0 ? 150 : value;
  2318. value = size.height - e.getData().top;
  2319. base.mcvPopupY = value < 0 ? 70 : value;
  2320. MaelstromTools.LocalStorage.set("mcvPopup", {
  2321. x : base.mcvPopupX,
  2322. y : base.mcvPopupY
  2323. });
  2324. });
  2325. var font = qx.bom.Font.fromString('bold').set({
  2326. size: 20
  2327. });
  2328.  
  2329. this.mcvTimerLabel = new qx.ui.basic.Label().set({
  2330. font: font,
  2331. textColor: 'red',
  2332. width: 155,
  2333. textAlign: 'center',
  2334. marginBottom : 5
  2335. });
  2336. this.mcvPopup.add(this.mcvTimerLabel);
  2337. var serverBar = qx.core.Init.getApplication().getServerBar().getBounds();
  2338. var pos = MaelstromTools.LocalStorage.get("mcvPopup", {
  2339. x : serverBar.width + 150,
  2340. y : 70
  2341. });
  2342. this.mcvPopupX = pos.x;
  2343. this.mcvPopupY = pos.y;
  2344. this.mcvPopup.open();
  2345. }
  2346. var size = qx.core.Init.getApplication().getRoot().getBounds();
  2347. this.mcvPopup.moveTo(size.width - this.mcvPopupX, size.height - this.mcvPopupY);
  2348.  
  2349. var nextLevelInfo = cd.get_NextLevelInfo_Obj();
  2350. var resourcesNeeded = new Array();
  2351. for (var i in nextLevelInfo.rr) {
  2352. if (nextLevelInfo.rr[i].t > 0) {
  2353. resourcesNeeded[nextLevelInfo.rr[i].t] = nextLevelInfo.rr[i].c;
  2354. }
  2355. }
  2356. //var researchNeeded = resourcesNeeded[ClientLib.Base.EResourceType.ResearchPoints];
  2357. //var currentResearchPoints = player.get_ResearchPoints();
  2358.  
  2359. var creditsNeeded = resourcesNeeded[ClientLib.Base.EResourceType.Gold];
  2360. var creditsResourceData = player.get_Credits();
  2361. var creditGrowthPerHour = (creditsResourceData.Delta + creditsResourceData.ExtraBonusDelta) * ClientLib.Data.MainData.GetInstance().get_Time().get_StepsPerHour();
  2362. var creditTimeLeftInHours = (creditsNeeded - player.GetCreditsCount()) / creditGrowthPerHour;
  2363.  
  2364. if (creditGrowthPerHour == 0 || creditTimeLeftInHours <= 0) {
  2365. if (this.mcvPopup) {
  2366. this.mcvPopup.close();
  2367. }
  2368. return;
  2369. }
  2370.  
  2371. this.mcvPopup.setCaption(Lang.gt("Next MCV") + " ($ " + MaelstromTools.Wrapper.FormatNumbersCompact(creditsNeeded) + ")");
  2372. this.mcvTimerLabel.setValue(MaelstromTools.Wrapper.FormatTimespan(creditTimeLeftInHours * 60 * 60));
  2373.  
  2374. if (!this.mcvPopup.isVisible()) {
  2375. this.mcvPopup.open();
  2376. }
  2377. } catch (e) {
  2378. console.log("calculateCostsForNextMCV", e);
  2379. }
  2380. }
  2381. }
  2382. });
  2383.  
  2384. // define Preferences
  2385. qx.Class.define("MaelstromTools.Preferences", {
  2386. type: "singleton",
  2387. extend: qx.core.Object,
  2388.  
  2389. statics: {
  2390. USEDEDICATEDMAINMENU: "useDedicatedMainMenu",
  2391. AUTOCOLLECTPACKAGES: "autoCollectPackages",
  2392. AUTOREPAIRUNITS: "autoRepairUnits",
  2393. AUTOREPAIRBUILDINGS: "autoRepairBuildings",
  2394. AUTOHIDEMISSIONTRACKER: "autoHideMissionTracker",
  2395. AUTOCOLLECTTIMER: "AutoCollectTimer",
  2396. SHOWLOOT: "showLoot",
  2397. SHOWCOSTSFORNEXTMCV: "showCostsForNextMCV",
  2398. CHATHISTORYLENGTH: "ChatHistoryLength"
  2399. },
  2400.  
  2401. members: {
  2402. Window: null,
  2403. Widget: null,
  2404. Settings: null,
  2405. FormElements: null,
  2406.  
  2407. readOptions: function () {
  2408. try {
  2409. if (!this.Settings) {
  2410. this.Settings = new Object();
  2411. }
  2412.  
  2413. /*
  2414. if(MaelstromTools.LocalStorage.get("useDedicatedMainMenu") == null) {
  2415. if(qx.bom.Viewport.getWidth(window) > 1800) {
  2416. this.Settings["useDedicatedMainMenu"] = false;
  2417. }
  2418. } else {
  2419. this.Settings["useDedicatedMainMenu"] = (MaelstromTools.LocalStorage.get("useDedicatedMainMenu", 1) == 1);
  2420. }*/
  2421. this.Settings[MaelstromTools.Preferences.USEDEDICATEDMAINMENU] = (MaelstromTools.LocalStorage.get(MaelstromTools.Preferences.USEDEDICATEDMAINMENU, 1) == 1);
  2422. this.Settings[MaelstromTools.Preferences.AUTOCOLLECTPACKAGES] = (MaelstromTools.LocalStorage.get(MaelstromTools.Preferences.AUTOCOLLECTPACKAGES, 0) == 1);
  2423. this.Settings[MaelstromTools.Preferences.AUTOREPAIRUNITS] = (MaelstromTools.LocalStorage.get(MaelstromTools.Preferences.AUTOREPAIRUNITS, 0) == 1);
  2424. this.Settings[MaelstromTools.Preferences.AUTOREPAIRBUILDINGS] = (MaelstromTools.LocalStorage.get(MaelstromTools.Preferences.AUTOREPAIRBUILDINGS, 0) == 1);
  2425. this.Settings[MaelstromTools.Preferences.AUTOHIDEMISSIONTRACKER] = (MaelstromTools.LocalStorage.get(MaelstromTools.Preferences.AUTOHIDEMISSIONTRACKER, 0) == 1);
  2426. this.Settings[MaelstromTools.Preferences.AUTOCOLLECTTIMER] = MaelstromTools.LocalStorage.get(MaelstromTools.Preferences.AUTOCOLLECTTIMER, 60);
  2427. this.Settings[MaelstromTools.Preferences.SHOWLOOT] = (MaelstromTools.LocalStorage.get(MaelstromTools.Preferences.SHOWLOOT, 1) == 1);
  2428. this.Settings[MaelstromTools.Preferences.SHOWCOSTSFORNEXTMCV] = (MaelstromTools.LocalStorage.get(MaelstromTools.Preferences.SHOWCOSTSFORNEXTMCV, 1) == 1);
  2429. this.Settings[MaelstromTools.Preferences.CHATHISTORYLENGTH] = MaelstromTools.LocalStorage.get(MaelstromTools.Preferences.CHATHISTORYLENGTH, 64);
  2430.  
  2431. if (!CCTAWrapperIsInstalled()) {
  2432. this.Settings[MaelstromTools.Preferences.AUTOREPAIRUNITS] = false;
  2433. this.Settings[MaelstromTools.Preferences.AUTOREPAIRBUILDINGS] = false;
  2434. //this.Settings[MaelstromTools.Preferences.SHOWLOOT] = false;
  2435. }
  2436. //console.log(this.Settings);
  2437.  
  2438. } catch (e) {
  2439. console.log("MaelstromTools.Preferences.readOptions: ", e);
  2440. }
  2441. },
  2442.  
  2443. openWindow: function (WindowName, WindowTitle) {
  2444. try {
  2445. if (!this.Window) {
  2446. //this.Window = new qx.ui.window.Window(WindowTitle).set({
  2447. this.Window = new webfrontend.gui.OverlayWindow().set({
  2448. autoHide: false,
  2449. title: WindowTitle,
  2450. minHeight: 350
  2451.  
  2452. //resizable: false,
  2453. //showMaximize:false,
  2454. //showMinimize:false,
  2455. //allowMaximize:false,
  2456. //allowMinimize:false,
  2457. //showStatusbar: false
  2458. });
  2459. this.Window.clientArea.setPadding(10);
  2460. this.Window.clientArea.setLayout(new qx.ui.layout.VBox(3));
  2461.  
  2462. this.Widget = new qx.ui.container.Composite(new qx.ui.layout.Grid().set({
  2463. spacingX: 5,
  2464. spacingY: 5
  2465. }));
  2466.  
  2467. //this.Widget.setTextColor("white");
  2468.  
  2469. this.Window.clientArea.add(this.Widget);
  2470. }
  2471.  
  2472. if (this.Window.isVisible()) {
  2473. this.Window.close();
  2474. } else {
  2475. MT_Base.openWindow(this.Window, WindowName);
  2476. this.setWidgetLabels();
  2477. }
  2478. } catch (e) {
  2479. console.log("MaelstromTools.Preferences.openWindow: ", e);
  2480. }
  2481. },
  2482.  
  2483. addFormElement: function (name, element) {
  2484. this.FormElements[name] = element;
  2485. },
  2486.  
  2487. setWidgetLabels: function () {
  2488. try {
  2489. this.readOptions();
  2490.  
  2491. this.FormElements = new Object();
  2492. this.Widget.removeAll();
  2493. var rowIdx = 1;
  2494. var colIdx = 1;
  2495.  
  2496. var chkAutoHideMissionTracker = new qx.ui.form.CheckBox(Lang.gt("Hide Mission Tracker")).set({
  2497. value: this.Settings[MaelstromTools.Preferences.AUTOHIDEMISSIONTRACKER] == 1
  2498. });
  2499. var chkUseDedicatedMainMenu = new qx.ui.form.CheckBox(Lang.gt("Use dedicated Main Menu (restart required)")).set({
  2500. value: this.Settings[MaelstromTools.Preferences.USEDEDICATEDMAINMENU] == 1
  2501. });
  2502. var chkShowLoot = new qx.ui.form.CheckBox(Lang.gt("Show lootable resources (restart required)")).set({
  2503. value: this.Settings[MaelstromTools.Preferences.SHOWLOOT] == 1/*,
  2504. enabled: CCTAWrapperIsInstalled()*/
  2505. });
  2506. var chkCostsNextMCV = new qx.ui.form.CheckBox(Lang.gt("Show time to next MCV")).set({
  2507. value: this.Settings[MaelstromTools.Preferences.SHOWCOSTSFORNEXTMCV] == 1
  2508. });
  2509. MaelstromTools.Util.addElement(this.Widget, rowIdx++, colIdx, chkAutoHideMissionTracker, 2);
  2510. MaelstromTools.Util.addElement(this.Widget, rowIdx++, colIdx, chkUseDedicatedMainMenu, 2);
  2511. MaelstromTools.Util.addElement(this.Widget, rowIdx++, colIdx, chkShowLoot, 2);
  2512. MaelstromTools.Util.addElement(this.Widget, rowIdx++, colIdx, chkCostsNextMCV, 2);
  2513.  
  2514. var chkAutoCollectPackages = new qx.ui.form.CheckBox(Lang.gt("Autocollect packages")).set({
  2515. value: this.Settings[MaelstromTools.Preferences.AUTOCOLLECTPACKAGES] == 1
  2516. });
  2517. var chkAutoRepairUnits = new qx.ui.form.CheckBox(Lang.gt("Autorepair units")).set({
  2518. value: this.Settings[MaelstromTools.Preferences.AUTOREPAIRUNITS] == 1,
  2519. enabled: CCTAWrapperIsInstalled()
  2520. });
  2521. var chkAutoRepairBuildings = new qx.ui.form.CheckBox(Lang.gt("Autorepair buildings")).set({
  2522. value: this.Settings[MaelstromTools.Preferences.AUTOREPAIRBUILDINGS] == 1,
  2523. enabled: CCTAWrapperIsInstalled()
  2524. });
  2525.  
  2526. var spinnerChatHistoryLength = new qx.ui.form.Spinner().set({
  2527. minimum: 64,
  2528. maximum: 512,
  2529. value: this.Settings[MaelstromTools.Preferences.CHATHISTORYLENGTH]
  2530. });
  2531.  
  2532. MaelstromTools.Util.addLabel(this.Widget, rowIdx, colIdx, Lang.gt("Chat history length") + " (" + spinnerChatHistoryLength.getMinimum() + " - " + spinnerChatHistoryLength.getMaximum() + ")");
  2533. MaelstromTools.Util.addElement(this.Widget, rowIdx++, colIdx + 1, spinnerChatHistoryLength);
  2534.  
  2535. var spinnerAutoCollectTimer = new qx.ui.form.Spinner().set({
  2536. minimum: 5,
  2537. maximum: 60 * 6,
  2538. value: this.Settings[MaelstromTools.Preferences.AUTOCOLLECTTIMER]
  2539. });
  2540.  
  2541. MaelstromTools.Util.addLabel(this.Widget, rowIdx, colIdx, Lang.gt("Automatic interval in minutes") + " (" + spinnerAutoCollectTimer.getMinimum() + " - " + spinnerAutoCollectTimer.getMaximum() + ")");
  2542. MaelstromTools.Util.addElement(this.Widget, rowIdx++, colIdx + 1, spinnerAutoCollectTimer);
  2543. MaelstromTools.Util.addElement(this.Widget, rowIdx++, colIdx, chkAutoCollectPackages, 2);
  2544. MaelstromTools.Util.addElement(this.Widget, rowIdx++, colIdx, chkAutoRepairUnits, 2);
  2545. MaelstromTools.Util.addElement(this.Widget, rowIdx++, colIdx, chkAutoRepairBuildings, 2);
  2546.  
  2547. var applyButton = new qx.ui.form.Button(Lang.gt("Apply changes")).set({
  2548. appearance: "button-detailview-small",
  2549. width: 120,
  2550. minWidth: 120,
  2551. maxWidth: 120
  2552. });
  2553. applyButton.addListener("execute", this.applyChanges, this);
  2554.  
  2555. var cancelButton = new qx.ui.form.Button(Lang.gt("Discard changes")).set({
  2556. appearance: "button-detailview-small",
  2557. width: 120,
  2558. minWidth: 120,
  2559. maxWidth: 120
  2560. });
  2561. cancelButton.addListener("execute", function () {
  2562. this.Window.close();
  2563. }, this);
  2564.  
  2565. var resetButton = new qx.ui.form.Button(Lang.gt("Reset to default")).set({
  2566. appearance: "button-detailview-small",
  2567. width: 120,
  2568. minWidth: 120,
  2569. maxWidth: 120
  2570. });
  2571. resetButton.addListener("execute", this.resetToDefault, this);
  2572.  
  2573. MaelstromTools.Util.addElement(this.Widget, rowIdx++, colIdx, resetButton);
  2574. colIdx = 1;
  2575. MaelstromTools.Util.addElement(this.Widget, rowIdx, colIdx++, cancelButton);
  2576. MaelstromTools.Util.addElement(this.Widget, rowIdx++, colIdx, applyButton);
  2577.  
  2578. this.addFormElement(MaelstromTools.Preferences.AUTOHIDEMISSIONTRACKER, chkAutoHideMissionTracker);
  2579. this.addFormElement(MaelstromTools.Preferences.USEDEDICATEDMAINMENU, chkUseDedicatedMainMenu);
  2580. this.addFormElement(MaelstromTools.Preferences.SHOWLOOT, chkShowLoot);
  2581. this.addFormElement(MaelstromTools.Preferences.SHOWCOSTSFORNEXTMCV, chkCostsNextMCV);
  2582. this.addFormElement(MaelstromTools.Preferences.AUTOCOLLECTPACKAGES, chkAutoCollectPackages);
  2583. this.addFormElement(MaelstromTools.Preferences.AUTOREPAIRUNITS, chkAutoRepairUnits);
  2584. this.addFormElement(MaelstromTools.Preferences.AUTOREPAIRBUILDINGS, chkAutoRepairBuildings);
  2585. this.addFormElement(MaelstromTools.Preferences.AUTOCOLLECTTIMER, spinnerAutoCollectTimer);
  2586. this.addFormElement(MaelstromTools.Preferences.CHATHISTORYLENGTH, spinnerChatHistoryLength);
  2587. } catch (e) {
  2588. console.log("MaelstromTools.Preferences.setWidgetLabels: ", e);
  2589. }
  2590. },
  2591.  
  2592. applyChanges: function () {
  2593. try {
  2594. var autoRunNeeded = false;
  2595. for (var idx in this.FormElements) {
  2596. var element = this.FormElements[idx];
  2597. if (idx == MaelstromTools.Preferences.AUTOCOLLECTTIMER) {
  2598. autoRunNeeded = (MaelstromTools.LocalStorage.get(MaelstromTools.Preferences.AUTOCOLLECTTIMER, 0) != element.getValue());
  2599. }
  2600. if (idx == MaelstromTools.Preferences.CHATHISTORYLENGTH) {
  2601. webfrontend.gui.chat.ChatWidget.recvbufsize = element.getValue();
  2602. }
  2603. MaelstromTools.LocalStorage.set(idx, element.getValue());
  2604. }
  2605. this.readOptions();
  2606. if (autoRunNeeded) {
  2607. MT_Base.runAutoCollectTimer();
  2608. }
  2609. this.Window.close();
  2610. } catch (e) {
  2611. console.log("MaelstromTools.Preferences.applyChanges: ", e);
  2612. }
  2613. },
  2614.  
  2615. resetToDefault: function () {
  2616. try {
  2617. MaelstromTools.LocalStorage.clearAll();
  2618. this.setWidgetLabels();
  2619. } catch (e) {
  2620. console.log("MaelstromTools.Preferences.resetToDefault: ", e);
  2621. }
  2622. }
  2623. }
  2624. });
  2625.  
  2626. // define DefaultObject
  2627. qx.Class.define("MaelstromTools.DefaultObject", {
  2628. type: "abstract",
  2629. extend: qx.core.Object,
  2630. members: {
  2631. Window: null,
  2632. Widget: null,
  2633. Cache: {}, //k null
  2634. IsTimerEnabled: true,
  2635.  
  2636. calc: function () {
  2637. try {
  2638. if (this.Window.isVisible()) {
  2639. this.updateCache();
  2640. this.setWidgetLabels();
  2641. if (this.IsTimerEnabled) {
  2642. var self = this;
  2643. window.setTimeout(function () {
  2644. self.calc();
  2645. }, MT_Base.timerInterval);
  2646. }
  2647. }
  2648. } catch (e) {
  2649. console.log("MaelstromTools.DefaultObject.calc: ", e);
  2650. }
  2651. },
  2652.  
  2653. openWindow: function (WindowName, WindowTitle) {
  2654. try {
  2655. if (!this.Window) {
  2656. this.Window = new qx.ui.window.Window(WindowTitle).set({
  2657. resizable: false,
  2658. showMaximize: false,
  2659. showMinimize: false,
  2660. allowMaximize: false,
  2661. allowMinimize: false,
  2662. showStatusbar: false
  2663. });
  2664. this.Window.setPadding(10);
  2665. this.Window.setLayout(new qx.ui.layout.VBox(3));
  2666.  
  2667. this.Widget = new qx.ui.container.Composite(new qx.ui.layout.Grid());
  2668. this.Widget.setTextColor("white");
  2669.  
  2670. this.Window.add(this.Widget);
  2671. }
  2672.  
  2673. if (this.Window.isVisible()) {
  2674. this.Window.close();
  2675. } else {
  2676. MT_Base.openWindow(this.Window, WindowName);
  2677. this.calc();
  2678. }
  2679. } catch (e) {
  2680. console.log("MaelstromTools.DefaultObject.openWindow: ", e);
  2681. }
  2682. }
  2683. }
  2684. });
  2685.  
  2686. // define Production
  2687. qx.Class.define("MaelstromTools.Production", {
  2688. type: "singleton",
  2689. extend: MaelstromTools.DefaultObject,
  2690. members: {
  2691. updateCache: function (onlyForCity) {
  2692. try {
  2693. MT_Cache.updateCityCache();
  2694. var alliance = ClientLib.Data.MainData.GetInstance().get_Alliance();
  2695. //this.Cache = Object();
  2696.  
  2697. for (var cname in MT_Cache.Cities) {
  2698. if (onlyForCity != null && onlyForCity != cname) {
  2699. continue;
  2700. }
  2701. var ncity = MT_Cache.Cities[cname].Object;
  2702. if (typeof (this.Cache[cname]) !== 'object') this.Cache[cname] = {};
  2703. if (typeof (this.Cache[cname][MaelstromTools.Statics.Tiberium]) !== 'object') this.Cache[cname][MaelstromTools.Statics.Tiberium] = {}; // all have to be checked,
  2704. if (typeof (this.Cache[cname][MaelstromTools.Statics.Crystal]) !== 'object') this.Cache[cname][MaelstromTools.Statics.Crystal] = {}; // this.Cache[cname] can be created inside different namespaces
  2705. if (typeof (this.Cache[cname][MaelstromTools.Statics.Power]) !== 'object') this.Cache[cname][MaelstromTools.Statics.Power] = {}; // like the RepairTime etc... without those objs
  2706. if (typeof (this.Cache[cname][MaelstromTools.Statics.Dollar]) !== 'object') this.Cache[cname][MaelstromTools.Statics.Dollar] = {};
  2707.  
  2708. this.Cache[cname]["ProductionStopped"] = ncity.get_IsGhostMode();
  2709. this.Cache[cname]["PackagesStopped"] = (ncity.get_hasCooldown() || ncity.get_IsGhostMode());
  2710. this.Cache[cname][MaelstromTools.Statics.Tiberium]["Delta"] = ncity.GetResourceGrowPerHour(ClientLib.Base.EResourceType.Tiberium, false, false); // (production.d[ClientLib.Base.EResourceType.Tiberium]['Delta'] * serverTime.get_StepsPerHour());
  2711. this.Cache[cname][MaelstromTools.Statics.Tiberium]["ExtraBonusDelta"] = ncity.GetResourceBonusGrowPerHour(ClientLib.Base.EResourceType.Tiberium); //(production.d[ClientLib.Base.EResourceType.Tiberium]['ExtraBonusDelta'] * serverTime.get_StepsPerHour());
  2712. this.Cache[cname][MaelstromTools.Statics.Tiberium]["POI"] = alliance.GetPOIBonusFromResourceType(ClientLib.Base.EResourceType.Tiberium);
  2713. this.Cache[cname][MaelstromTools.Statics.Crystal]["Delta"] = ncity.GetResourceGrowPerHour(ClientLib.Base.EResourceType.Crystal, false, false); //(production.d[ClientLib.Base.EResourceType.Crystal]['Delta'] * serverTime.get_StepsPerHour());
  2714. this.Cache[cname][MaelstromTools.Statics.Crystal]["ExtraBonusDelta"] = ncity.GetResourceBonusGrowPerHour(ClientLib.Base.EResourceType.Crystal); //(production.d[ClientLib.Base.EResourceType.Crystal]['ExtraBonusDelta'] * serverTime.get_StepsPerHour());
  2715. this.Cache[cname][MaelstromTools.Statics.Crystal]["POI"] = alliance.GetPOIBonusFromResourceType(ClientLib.Base.EResourceType.Crystal);
  2716. this.Cache[cname][MaelstromTools.Statics.Power]["Delta"] = ncity.GetResourceGrowPerHour(ClientLib.Base.EResourceType.Power, false, false); //(production.d[ClientLib.Base.EResourceType.Power]['Delta'] * serverTime.get_StepsPerHour());
  2717. this.Cache[cname][MaelstromTools.Statics.Power]["ExtraBonusDelta"] = ncity.GetResourceBonusGrowPerHour(ClientLib.Base.EResourceType.Power); // (production.d[ClientLib.Base.EResourceType.Power]['ExtraBonusDelta'] * serverTime.get_StepsPerHour());
  2718. this.Cache[cname][MaelstromTools.Statics.Power]["POI"] = alliance.GetPOIBonusFromResourceType(ClientLib.Base.EResourceType.Power);
  2719. this.Cache[cname][MaelstromTools.Statics.Dollar]["Delta"] = ClientLib.Base.Resource.GetResourceGrowPerHour(ncity.get_CityCreditsProduction(), false); // (ncity.get_CityCreditsProduction()['Delta'] * serverTime.get_StepsPerHour());
  2720. this.Cache[cname][MaelstromTools.Statics.Dollar]["ExtraBonusDelta"] = ClientLib.Base.Resource.GetResourceBonusGrowPerHour(ncity.get_CityCreditsProduction(), false); // (ncity.get_CityCreditsProduction()['ExtraBonusDelta'] * serverTime.get_StepsPerHour());
  2721. this.Cache[cname][MaelstromTools.Statics.Dollar]["POI"] = 0;
  2722. this.Cache[cname]["BaseLevel"] = MaelstromTools.Wrapper.GetBaseLevel(ncity);
  2723. if (onlyForCity != null && onlyForCity == cname) return this.Cache[cname];
  2724. }
  2725. } catch (e) {
  2726. console.log("MaelstromTools.Production.updateCache: ", e);
  2727. }
  2728. },
  2729.  
  2730. createProductionLabels2: function (rowIdx, colIdx, cityName, resourceType) {
  2731. try {
  2732. if (cityName == "-Total-") {
  2733. var Totals = Object();
  2734. Totals["Delta"] = 0;
  2735. Totals["ExtraBonusDelta"] = 0;
  2736. Totals["POI"] = 0;
  2737. Totals["Total"] = 0;
  2738.  
  2739. for (var cname in this.Cache) {
  2740. Totals["Delta"] += this.Cache[cname][resourceType]['Delta'];
  2741. Totals["ExtraBonusDelta"] += this.Cache[cname][resourceType]['ExtraBonusDelta'];
  2742. Totals["POI"] += this.Cache[cname][resourceType]['POI'];
  2743. }
  2744. Totals["Total"] = Totals['Delta'] + Totals['ExtraBonusDelta'] + Totals['POI'];
  2745.  
  2746. rowIdx++;
  2747.  
  2748. MaelstromTools.Util.addLabel(this.Widget, rowIdx++, colIdx, MaelstromTools.Wrapper.FormatNumbersCompact(Totals['Delta']), 80, 'right', 'bold');
  2749. MaelstromTools.Util.addLabel(this.Widget, rowIdx++, colIdx, MaelstromTools.Wrapper.FormatNumbersCompact(Totals['ExtraBonusDelta']), 80, 'right', 'bold');
  2750. if (resourceType != MaelstromTools.Statics.Dollar) {
  2751. MaelstromTools.Util.addLabel(this.Widget, rowIdx++, colIdx, MaelstromTools.Wrapper.FormatNumbersCompact(Totals['POI']), 80, 'right', 'bold');
  2752. } else {
  2753. rowIdx++;
  2754. }
  2755. MaelstromTools.Util.addLabel(this.Widget, rowIdx++, colIdx, MaelstromTools.Wrapper.FormatNumbersCompact(Totals['Total']), 80, 'right', 'bold');
  2756. } else if (cityName == "-Labels-") {
  2757. MaelstromTools.Util.addImage(this.Widget, rowIdx++, colIdx, MaelstromTools.Util.getImage(resourceType));
  2758. MaelstromTools.Util.addLabel(this.Widget, rowIdx++, colIdx, "Continuous", 100, 'left');
  2759. MaelstromTools.Util.addLabel(this.Widget, rowIdx++, colIdx, "Bonus", 100, 'left');
  2760. if (resourceType != MaelstromTools.Statics.Dollar) {
  2761. MaelstromTools.Util.addLabel(this.Widget, rowIdx++, colIdx, "POI", 100, 'left');
  2762. } else {
  2763. MaelstromTools.Util.addLabel(this.Widget, rowIdx++, colIdx, "Total / BaseLevel", 100, 'left');
  2764. }
  2765. MaelstromTools.Util.addLabel(this.Widget, rowIdx++, colIdx, "Total / h", 100, 'left');
  2766. } else {
  2767. var cityCache = this.Cache[cityName];
  2768. if (rowIdx > 2) {
  2769. rowIdx++;
  2770. }
  2771. MaelstromTools.Util.addLabel(this.Widget, rowIdx++, colIdx, MaelstromTools.Wrapper.FormatNumbersCompact(cityCache[resourceType]['Delta']), 80, 'right', null, ((cityCache["ProductionStopped"] || cityCache[resourceType]['Delta'] == 0) ? "red" : "white"));
  2772. MaelstromTools.Util.addLabel(this.Widget, rowIdx++, colIdx, MaelstromTools.Wrapper.FormatNumbersCompact(cityCache[resourceType]['ExtraBonusDelta']), 80, 'right', null, ((cityCache["PackagesStopped"] || cityCache[resourceType]['ExtraBonusDelta'] == 0) ? "red" : "white"));
  2773. if (resourceType != MaelstromTools.Statics.Dollar) {
  2774. MaelstromTools.Util.addLabel(this.Widget, rowIdx++, colIdx, MaelstromTools.Wrapper.FormatNumbersCompact(cityCache[resourceType]['POI']), 80, 'right', null, (cityCache[resourceType]['POI'] == 0 ? "red" : "white"));
  2775. } else {
  2776. MaelstromTools.Util.addLabel(this.Widget, rowIdx++, colIdx, MaelstromTools.Wrapper.FormatNumbersCompact((cityCache[resourceType]['Delta'] + cityCache[resourceType]['ExtraBonusDelta'] + cityCache[resourceType]['POI']) / cityCache["BaseLevel"]), 80, 'right');
  2777. }
  2778. MaelstromTools.Util.addLabel(this.Widget, rowIdx++, colIdx, MaelstromTools.Wrapper.FormatNumbersCompact(cityCache[resourceType]['Delta'] + cityCache[resourceType]['ExtraBonusDelta'] + cityCache[resourceType]['POI']), 80, 'right', 'bold');
  2779. }
  2780. return rowIdx;
  2781. } catch (e) {
  2782. console.log("MaelstromTools.Production.createProductionLabels2: ", e);
  2783. }
  2784. },
  2785.  
  2786. setWidgetLabels: function () {
  2787. try {
  2788. this.Widget.removeAll();
  2789.  
  2790. var rowIdx = 1;
  2791. var colIdx = 1;
  2792.  
  2793. rowIdx = this.createProductionLabels2(rowIdx, colIdx, "-Labels-", MaelstromTools.Statics.Tiberium);
  2794. rowIdx = this.createProductionLabels2(rowIdx, colIdx, "-Labels-", MaelstromTools.Statics.Crystal);
  2795. rowIdx = this.createProductionLabels2(rowIdx, colIdx, "-Labels-", MaelstromTools.Statics.Power);
  2796. rowIdx = this.createProductionLabels2(rowIdx, colIdx, "-Labels-", MaelstromTools.Statics.Dollar);
  2797.  
  2798. colIdx++;
  2799. for (var cityName in this.Cache) {
  2800. rowIdx = 1;
  2801. MaelstromTools.Util.addLabel(this.Widget, rowIdx++, colIdx, cityName, 80, 'right');
  2802.  
  2803. rowIdx = this.createProductionLabels2(rowIdx, colIdx, cityName, MaelstromTools.Statics.Tiberium);
  2804. rowIdx = this.createProductionLabels2(rowIdx, colIdx, cityName, MaelstromTools.Statics.Crystal);
  2805. rowIdx = this.createProductionLabels2(rowIdx, colIdx, cityName, MaelstromTools.Statics.Power);
  2806. rowIdx = this.createProductionLabels2(rowIdx, colIdx, cityName, MaelstromTools.Statics.Dollar);
  2807.  
  2808. MaelstromTools.Util.addElement(this.Widget, rowIdx, colIdx++, MaelstromTools.Util.getAccessBaseButton(cityName));
  2809. }
  2810.  
  2811. rowIdx = 1;
  2812. MaelstromTools.Util.addLabel(this.Widget, rowIdx, colIdx, "Total / h", 80, 'right', 'bold');
  2813.  
  2814. rowIdx = this.createProductionLabels2(rowIdx, colIdx, "-Total-", MaelstromTools.Statics.Tiberium);
  2815. rowIdx = this.createProductionLabels2(rowIdx, colIdx, "-Total-", MaelstromTools.Statics.Crystal);
  2816. rowIdx = this.createProductionLabels2(rowIdx, colIdx, "-Total-", MaelstromTools.Statics.Power);
  2817. rowIdx = this.createProductionLabels2(rowIdx, colIdx, "-Total-", MaelstromTools.Statics.Dollar);
  2818. } catch (e) {
  2819. console.log("MaelstromTools.Production.setWidgetLabels: ", e);
  2820. }
  2821. }
  2822. }
  2823. });
  2824.  
  2825. // define RepairTime
  2826. qx.Class.define("MaelstromTools.RepairTime", {
  2827. type: "singleton",
  2828. extend: MaelstromTools.DefaultObject,
  2829. members: {
  2830.  
  2831. updateCache: function () {
  2832. try {
  2833. MT_Cache.updateCityCache();
  2834. this.Cache = Object();
  2835.  
  2836. for (var cname in MT_Cache.Cities) {
  2837. var ncity = MT_Cache.Cities[cname].Object;
  2838. var RepLargest = '';
  2839.  
  2840. this.Cache[cname] = Object();
  2841. this.Cache[cname]["RepairTime"] = Object();
  2842. this.Cache[cname]["Repaircharge"] = Object();
  2843. this.Cache[cname]["Repaircharge"]["Smallest"] = 999999999;
  2844. this.Cache[cname]["RepairTime"]["Largest"] = 0;
  2845.  
  2846. this.Cache[cname]["RepairTime"][MaelstromTools.Statics.Infantry] = ncity.get_CityUnitsData().GetRepairTimeFromEUnitGroup(ClientLib.Data.EUnitGroup.Infantry, false);
  2847. this.Cache[cname]["RepairTime"][MaelstromTools.Statics.Vehicle] = ncity.get_CityUnitsData().GetRepairTimeFromEUnitGroup(ClientLib.Data.EUnitGroup.Vehicle, false);
  2848. this.Cache[cname]["RepairTime"][MaelstromTools.Statics.Aircraft] = ncity.get_CityUnitsData().GetRepairTimeFromEUnitGroup(ClientLib.Data.EUnitGroup.Aircraft, false);
  2849. this.Cache[cname]["RepairTime"]["Maximum"] = ncity.GetResourceMaxStorage(ClientLib.Base.EResourceType.RepairChargeInf);
  2850. this.Cache[cname]["Repaircharge"][MaelstromTools.Statics.Infantry] = ncity.GetResourceCount(ClientLib.Base.EResourceType.RepairChargeInf);
  2851. this.Cache[cname]["Repaircharge"][MaelstromTools.Statics.Vehicle] = ncity.GetResourceCount(ClientLib.Base.EResourceType.RepairChargeVeh);
  2852. this.Cache[cname]["Repaircharge"][MaelstromTools.Statics.Aircraft] = ncity.GetResourceCount(ClientLib.Base.EResourceType.RepairChargeAir);
  2853.  
  2854. if (this.Cache[cname]["Repaircharge"][MaelstromTools.Statics.Infantry] < this.Cache[cname]["Repaircharge"]["Smallest"]) {
  2855. this.Cache[cname]["Repaircharge"]["Smallest"] = this.Cache[cname]["Repaircharge"][MaelstromTools.Statics.Infantry];
  2856. }
  2857. if (this.Cache[cname]["Repaircharge"][MaelstromTools.Statics.Vehicle] < this.Cache[cname]["Repaircharge"]["Smallest"]) {
  2858. this.Cache[cname]["Repaircharge"]["Smallest"] = this.Cache[cname]["Repaircharge"][MaelstromTools.Statics.Vehicle];
  2859. }
  2860. if (this.Cache[cname]["Repaircharge"][MaelstromTools.Statics.Aircraft] < this.Cache[cname]["Repaircharge"]["Smallest"]) {
  2861. this.Cache[cname]["Repaircharge"]["Smallest"] = this.Cache[cname]["Repaircharge"][MaelstromTools.Statics.Aircraft];
  2862. }
  2863.  
  2864. if (this.Cache[cname]["RepairTime"][MaelstromTools.Statics.Infantry] > this.Cache[cname]["RepairTime"]["Largest"]) {
  2865. this.Cache[cname]["RepairTime"]["Largest"] = this.Cache[cname]["RepairTime"][MaelstromTools.Statics.Infantry];
  2866. RepLargest = "Infantry";
  2867. }
  2868. if (this.Cache[cname]["RepairTime"][MaelstromTools.Statics.Vehicle] > this.Cache[cname]["RepairTime"]["Largest"]) {
  2869. this.Cache[cname]["RepairTime"]["Largest"] = this.Cache[cname]["RepairTime"][MaelstromTools.Statics.Vehicle];
  2870. RepLargest = "Vehicle";
  2871. }
  2872. if (this.Cache[cname]["RepairTime"][MaelstromTools.Statics.Aircraft] > this.Cache[cname]["RepairTime"]["Largest"]) {
  2873. this.Cache[cname]["RepairTime"]["Largest"] = this.Cache[cname]["RepairTime"][MaelstromTools.Statics.Aircraft];
  2874. RepLargest = "Aircraft";
  2875. }
  2876.  
  2877. //PossibleAttacks and MaxAttacks fixes
  2878. var offHealth = ncity.GetOffenseConditionInPercent();
  2879. if (RepLargest !== '') {
  2880. this.Cache[cname]["RepairTime"]["LargestDiv"] = this.Cache[cname]["RepairTime"][RepLargest];
  2881. var i = Math.ceil(this.Cache[cname]["Repaircharge"].Smallest / this.Cache[cname]["RepairTime"].LargestDiv); //fix
  2882. var j = this.Cache[cname]["Repaircharge"].Smallest / this.Cache[cname]["RepairTime"].LargestDiv;
  2883. if (offHealth !== 100) { i--; i += '*';} // Decrease number of attacks by 1 when unit unhealthy. Additional visual info: asterisk when units aren't healthy
  2884. this.Cache[cname]["RepairTime"]["PossibleAttacks"] = i;
  2885. var k = this.Cache[cname]["RepairTime"].Maximum / this.Cache[cname]["RepairTime"].LargestDiv;
  2886. this.Cache[cname]["RepairTime"]["MaxAttacks"] = Math.ceil(k); //fix
  2887. } else {
  2888. this.Cache[cname]["RepairTime"]["LargestDiv"] = 0;
  2889. this.Cache[cname]["RepairTime"]["PossibleAttacks"] = 0;
  2890. this.Cache[cname]["RepairTime"]["MaxAttacks"] = 0;
  2891. }
  2892.  
  2893. var unitsData = ncity.get_CityUnitsData();
  2894. this.Cache[cname]["Base"] = Object();
  2895. this.Cache[cname]["Base"]["Level"] = MaelstromTools.Wrapper.GetBaseLevel(ncity);
  2896. this.Cache[cname]["Base"]["UnitLimit"] = ncity.GetBuildingSlotLimit(); //ncity.GetNumBuildings();
  2897. this.Cache[cname]["Base"]["TotalHeadCount"] = ncity.GetBuildingSlotCount();
  2898. this.Cache[cname]["Base"]["FreeHeadCount"] = this.Cache[cname]["Base"]["UnitLimit"] - this.Cache[cname]["Base"]["TotalHeadCount"];
  2899. this.Cache[cname]["Base"]["HealthInPercent"] = ncity.GetBuildingsConditionInPercent();
  2900.  
  2901. this.Cache[cname]["Offense"] = Object();
  2902. this.Cache[cname]["Offense"]["Level"] = (Math.floor(ncity.get_LvlOffense() * 100) / 100).toFixed(2);
  2903. this.Cache[cname]["Offense"]["UnitLimit"] = unitsData.get_UnitLimitOffense();
  2904. this.Cache[cname]["Offense"]["TotalHeadCount"] = unitsData.get_TotalOffenseHeadCount();
  2905. this.Cache[cname]["Offense"]["FreeHeadCount"] = unitsData.get_FreeOffenseHeadCount();
  2906. this.Cache[cname]["Offense"]["HealthInPercent"] = offHealth > 0 ? offHealth : 0;
  2907.  
  2908. this.Cache[cname]["Defense"] = Object();
  2909. this.Cache[cname]["Defense"]["Level"] = (Math.floor(ncity.get_LvlDefense() * 100) / 100).toFixed(2);
  2910. this.Cache[cname]["Defense"]["UnitLimit"] = unitsData.get_UnitLimitDefense();
  2911. this.Cache[cname]["Defense"]["TotalHeadCount"] = unitsData.get_TotalDefenseHeadCount();
  2912. this.Cache[cname]["Defense"]["FreeHeadCount"] = unitsData.get_FreeDefenseHeadCount();
  2913. this.Cache[cname]["Defense"]["HealthInPercent"] = ncity.GetDefenseConditionInPercent() > 0 ? ncity.GetDefenseConditionInPercent() : 0;
  2914.  
  2915. //console.log(ncity.get_CityUnitsData().get_UnitLimitOffense() + " / " + ncity.get_CityUnitsData().get_TotalOffenseHeadCount() + " = " + ncity.get_CityUnitsData().get_FreeOffenseHeadCount());
  2916. //console.log(ncity.get_CityUnitsData().get_UnitLimitDefense() + " / " + ncity.get_CityUnitsData().get_TotalDefenseHeadCount() + " = " + ncity.get_CityUnitsData().get_FreeDefenseHeadCount());
  2917. }
  2918. } catch (e) {
  2919. console.log("MaelstromTools.RepairTime.updateCache: ", e);
  2920. }
  2921. },
  2922.  
  2923. setWidgetLabels: function () {
  2924. try {
  2925. this.Widget.removeAll();
  2926. var rowIdx = 1;
  2927.  
  2928. rowIdx = this.createOverviewLabels(rowIdx);
  2929. rowIdx = this.createRepairchargeLabels(rowIdx);
  2930. } catch (e) {
  2931. console.log("MaelstromTools.RepairTime.setWidgetLabels: ", e);
  2932. }
  2933. },
  2934.  
  2935. createRepairchargeLabels: function (rowIdx) {
  2936. try {
  2937. var colIdx = 2;
  2938. MaelstromTools.Util.addLabel(this.Widget, rowIdx++, colIdx++, "Repaircharges", null, 'left', null, null, 3);
  2939. colIdx = 2;
  2940.  
  2941. MaelstromTools.Util.addLabel(this.Widget, rowIdx, colIdx++, MaelstromTools.Statics.Infantry, 60, 'right');
  2942. MaelstromTools.Util.addLabel(this.Widget, rowIdx, colIdx++, MaelstromTools.Statics.Vehicle, 60, 'right');
  2943. MaelstromTools.Util.addLabel(this.Widget, rowIdx, colIdx++, MaelstromTools.Statics.Aircraft, 60, 'right');
  2944. MaelstromTools.Util.addLabel(this.Widget, rowIdx, colIdx++, "Repairtime", 80, 'right');
  2945. MaelstromTools.Util.addLabel(this.Widget, rowIdx, colIdx++, "Attacks", 60, 'right');
  2946. MaelstromTools.Util.addLabel(this.Widget, rowIdx, colIdx++, "Next at", 80, 'right');
  2947. MaelstromTools.Util.addLabel(this.Widget, rowIdx, colIdx++, "Max+1 at", 80, 'right');
  2948.  
  2949. rowIdx++;
  2950. for (var cityName in this.Cache) {
  2951. var cityCache = this.Cache[cityName];
  2952. if (cityCache.Offense.UnitLimit == 0) {
  2953. continue;
  2954. }
  2955. colIdx = 1;
  2956. MaelstromTools.Util.addLabel(this.Widget, rowIdx, colIdx++, cityName, 80, 'left');
  2957.  
  2958. // Skip bases with no armies
  2959. if (cityCache.Offense.UnitLimit > 0) {
  2960. MaelstromTools.Util.addLabel(this.Widget, rowIdx, colIdx++, MaelstromTools.Wrapper.FormatTimespan(cityCache.RepairTime.Infantry), 60, 'right', null, (cityCache.RepairTime.Infantry == cityCache.RepairTime.LargestDiv ? "yellow" : "white"));
  2961. MaelstromTools.Util.addLabel(this.Widget, rowIdx, colIdx++, MaelstromTools.Wrapper.FormatTimespan(cityCache.RepairTime.Vehicle), 60, 'right', null, (cityCache.RepairTime.Vehicle == cityCache.RepairTime.LargestDiv ? "yellow" : "white"));
  2962. MaelstromTools.Util.addLabel(this.Widget, rowIdx, colIdx++, MaelstromTools.Wrapper.FormatTimespan(cityCache.RepairTime.Aircraft), 60, 'right', null, (cityCache.RepairTime.Aircraft == cityCache.RepairTime.LargestDiv ? "yellow" : "white"));
  2963. MaelstromTools.Util.addLabel(this.Widget, rowIdx, colIdx++, MaelstromTools.Wrapper.FormatTimespan(cityCache.Repaircharge.Smallest), 80, 'right');
  2964. MaelstromTools.Util.addLabel(this.Widget, rowIdx, colIdx++, cityCache.RepairTime.PossibleAttacks + " / " + cityCache.RepairTime.MaxAttacks, 60, 'right', null, (cityCache.Offense.HealthInPercent !== 100 ? 'red' : null)); // mark red when unhealthy
  2965. var i = cityCache.RepairTime.LargestDiv * cityCache.RepairTime.PossibleAttacks;
  2966. var j = cityCache.RepairTime.LargestDiv * cityCache.RepairTime.MaxAttacks;
  2967. (i>0) ? MaelstromTools.Util.addLabel(this.Widget, rowIdx, colIdx++, MaelstromTools.Wrapper.FormatTimespan(i), 80, 'right', null, (i > cityCache.RepairTime.Maximum ? "yellow" : "white")) : colIdx++; /// yellow if more than Maximum RT
  2968. (j>0) ? MaelstromTools.Util.addLabel(this.Widget, rowIdx, colIdx++, MaelstromTools.Wrapper.FormatTimespan(j), 80, 'right') : colIdx++;
  2969. } else {
  2970. colIdx += 7;
  2971. }
  2972.  
  2973. colIdx += 4;
  2974. MaelstromTools.Util.addElement(this.Widget, rowIdx, colIdx++, MaelstromTools.Util.getAccessBaseButton(cityName, PerforceChangelist >= 376877 ? ClientLib.Data.PlayerAreaViewMode.pavmPlayerOffense : webfrontend.gui.PlayArea.PlayArea.modes.EMode_PlayerOffense));
  2975. rowIdx += 2;
  2976. }
  2977.  
  2978. return rowIdx;
  2979. } catch (e) {
  2980. console.log("MaelstromTools.RepairTime.createRepairchargeLabels: ", e);
  2981. }
  2982. },
  2983.  
  2984. createOverviewLabels: function (rowIdx) {
  2985. try {
  2986. var colIdx = 2;
  2987.  
  2988. MaelstromTools.Util.addLabel(this.Widget, rowIdx, colIdx, "Base", 60, 'right');
  2989. colIdx += 3;
  2990. MaelstromTools.Util.addLabel(this.Widget, rowIdx, colIdx, "Defense", 60, 'right');
  2991. colIdx += 3;
  2992. MaelstromTools.Util.addLabel(this.Widget, rowIdx, colIdx, "Army", 60, 'right');
  2993.  
  2994. rowIdx++;
  2995. colIdx = 2;
  2996.  
  2997. MaelstromTools.Util.addLabel(this.Widget, rowIdx, colIdx++, "Level", 60, 'right');
  2998. MaelstromTools.Util.addLabel(this.Widget, rowIdx, colIdx++, "Buildings", 60, 'right');
  2999. MaelstromTools.Util.addLabel(this.Widget, rowIdx, colIdx++, "Health", 60, 'right');
  3000.  
  3001. MaelstromTools.Util.addLabel(this.Widget, rowIdx, colIdx++, "Level", 60, 'right');
  3002. MaelstromTools.Util.addLabel(this.Widget, rowIdx, colIdx++, "Buildings", 60, 'right');
  3003. MaelstromTools.Util.addLabel(this.Widget, rowIdx, colIdx++, "Health", 60, 'right');
  3004.  
  3005. MaelstromTools.Util.addLabel(this.Widget, rowIdx, colIdx++, "Level", 60, 'right');
  3006. MaelstromTools.Util.addLabel(this.Widget, rowIdx, colIdx++, "Units", 60, 'right');
  3007. MaelstromTools.Util.addLabel(this.Widget, rowIdx, colIdx++, "Health", 60, 'right');
  3008.  
  3009. rowIdx++;
  3010. for (var cityName in this.Cache) {
  3011. var cityCache = this.Cache[cityName];
  3012. colIdx = 1;
  3013.  
  3014. MaelstromTools.Util.addLabel(this.Widget, rowIdx, colIdx++, cityName, 80, 'left');
  3015.  
  3016. MaelstromTools.Util.addLabel(this.Widget, rowIdx, colIdx++, cityCache.Base.Level, 60, 'right');
  3017. MaelstromTools.Util.addLabel(this.Widget, rowIdx, colIdx++, cityCache.Base.TotalHeadCount + " / " + cityCache.Base.UnitLimit, 60, 'right', null, (cityCache.Base.FreeHeadCount >= 1 ? "red" : "white"));
  3018. MaelstromTools.Util.addLabel(this.Widget, rowIdx, colIdx++, cityCache.Base.HealthInPercent + "%", 60, 'right', null, (cityCache.Base.HealthInPercent < 25 ? "red" : (cityCache.Base.HealthInPercent < 100 ? "yellow" : "white")));
  3019.  
  3020. if (cityCache.Defense.UnitLimit > 0) {
  3021. MaelstromTools.Util.addLabel(this.Widget, rowIdx, colIdx++, cityCache.Defense.Level, 60, 'right');
  3022. MaelstromTools.Util.addLabel(this.Widget, rowIdx, colIdx++, cityCache.Defense.TotalHeadCount + " / " + cityCache.Defense.UnitLimit, 60, 'right', null, (cityCache.Defense.FreeHeadCount >= 5 ? "red" : (cityCache.Defense.FreeHeadCount >= 3 ? "yellow" : "white")));
  3023. MaelstromTools.Util.addLabel(this.Widget, rowIdx, colIdx++, cityCache.Defense.HealthInPercent + "%", 60, 'right', null, (cityCache.Defense.HealthInPercent < 25 ? "red" : (cityCache.Defense.HealthInPercent < 100 ? "yellow" : "white")));
  3024. } else {
  3025. colIdx += 3;
  3026. }
  3027.  
  3028. // Skip bases with no armies
  3029. if (cityCache.Offense.UnitLimit > 0) {
  3030. MaelstromTools.Util.addLabel(this.Widget, rowIdx, colIdx++, cityCache.Offense.Level, 60, 'right');
  3031. MaelstromTools.Util.addLabel(this.Widget, rowIdx, colIdx++, cityCache.Offense.TotalHeadCount + " / " + cityCache.Offense.UnitLimit, 60, 'right', null, (cityCache.Offense.FreeHeadCount >= 10 ? "red" : (cityCache.Offense.FreeHeadCount >= 5 ? "yellow" : "white")));
  3032. MaelstromTools.Util.addLabel(this.Widget, rowIdx, colIdx++, cityCache.Offense.HealthInPercent + "%", 60, 'right', null, (cityCache.Offense.HealthInPercent < 25 ? "red" : (cityCache.Offense.HealthInPercent < 100 ? "yellow" : "white")));
  3033. } else {
  3034. colIdx += 3;
  3035. }
  3036.  
  3037. MaelstromTools.Util.addElement(this.Widget, rowIdx, colIdx++, MaelstromTools.Util.getAccessBaseButton(cityName));
  3038. rowIdx += 2;
  3039. }
  3040. return rowIdx;
  3041. } catch (e) {
  3042. console.log("MaelstromTools.RepairTime.createOverviewLabels: ", e);
  3043. }
  3044. }
  3045.  
  3046. }
  3047. });
  3048.  
  3049. // define ResourceOverview
  3050. qx.Class.define("MaelstromTools.ResourceOverview", {
  3051. type: "singleton",
  3052. extend: MaelstromTools.DefaultObject,
  3053. members: {
  3054. Table: null,
  3055. Model: null,
  3056.  
  3057. updateCache: function () {
  3058. try {
  3059. MT_Cache.updateCityCache();
  3060. this.Cache = Object();
  3061.  
  3062. for (var cname in MT_Cache.Cities) {
  3063. var ncity = MT_Cache.Cities[cname].Object;
  3064. var mtime = ClientLib.Data.MainData.GetInstance().get_Time();
  3065.  
  3066. this.Cache[cname] = Object();
  3067. this.Cache[cname][MaelstromTools.Statics.Tiberium] = ncity.GetResourceCount(ClientLib.Base.EResourceType.Tiberium);
  3068. this.Cache[cname][MaelstromTools.Statics.Tiberium + "Max"] = ncity.GetResourceMaxStorage(ClientLib.Base.EResourceType.Tiberium);
  3069. this.Cache[cname][MaelstromTools.Statics.Tiberium + "Full"] = mtime.GetJSStepTime(ncity.GetResourceStorageFullStep(ClientLib.Base.EResourceType.Tiberium));
  3070. this.Cache[cname][MaelstromTools.Statics.Crystal] = ncity.GetResourceCount(ClientLib.Base.EResourceType.Crystal);
  3071. this.Cache[cname][MaelstromTools.Statics.Crystal + "Max"] = ncity.GetResourceMaxStorage(ClientLib.Base.EResourceType.Crystal);
  3072. this.Cache[cname][MaelstromTools.Statics.Crystal + "Full"] = mtime.GetJSStepTime(ncity.GetResourceStorageFullStep(ClientLib.Base.EResourceType.Crystal));
  3073. this.Cache[cname][MaelstromTools.Statics.Power] = ncity.GetResourceCount(ClientLib.Base.EResourceType.Power);
  3074. this.Cache[cname][MaelstromTools.Statics.Power + "Max"] = ncity.GetResourceMaxStorage(ClientLib.Base.EResourceType.Power);
  3075. this.Cache[cname][MaelstromTools.Statics.Power + "Full"] = mtime.GetJSStepTime(ncity.GetResourceStorageFullStep(ClientLib.Base.EResourceType.Power));
  3076. }
  3077.  
  3078. } catch (e) {
  3079. console.log("MaelstromTools.ResourceOverview.updateCache: ", e);
  3080. }
  3081. },
  3082. /*
  3083. setWidgetLabelsTable: function () {
  3084. try {
  3085. if (!this.Table) {
  3086. this.Widget.setLayout(new qx.ui.layout.HBox());
  3087.  
  3088. this.Model = new qx.ui.table.model.Simple();
  3089. this.Model.setColumns(["City", "Tib. Storage", "Tiberium", "Full", "Crystal", "Full", "Power", "Storage", "Full"]);
  3090. this.Table = new qx.ui.table.Table(this.Model);
  3091. this.Widget.add(this.Table, {
  3092. flex: 1
  3093. });
  3094. }
  3095.  
  3096. var Totals = Object();
  3097. Totals[MaelstromTools.Statics.Tiberium] = 0;
  3098. Totals[MaelstromTools.Statics.Crystal] = 0;
  3099. Totals[MaelstromTools.Statics.Power] = 0;
  3100. Totals[MaelstromTools.Statics.Tiberium + "Max"] = 0;
  3101. Totals[MaelstromTools.Statics.Power + "Max"] = 0;
  3102.  
  3103. var rowData = [];
  3104.  
  3105. for (var cityName in this.Cache) {
  3106. var cityCache = this.Cache[cityName];
  3107.  
  3108. Totals[MaelstromTools.Statics.Tiberium] += cityCache[MaelstromTools.Statics.Tiberium];
  3109. Totals[MaelstromTools.Statics.Crystal] += cityCache[MaelstromTools.Statics.Crystal];
  3110. Totals[MaelstromTools.Statics.Power] += cityCache[MaelstromTools.Statics.Power];
  3111. Totals[MaelstromTools.Statics.Tiberium + "Max"] += cityCache[MaelstromTools.Statics.Tiberium + 'Max'];
  3112. Totals[MaelstromTools.Statics.Power + "Max"] += cityCache[MaelstromTools.Statics.Power + 'Max'];
  3113.  
  3114. rowData.push([
  3115. cityName,
  3116. MaelstromTools.Wrapper.FormatNumbersCompact(cityCache[MaelstromTools.Statics.Tiberium + 'Max']),
  3117. MaelstromTools.Wrapper.FormatNumbersCompact(cityCache[MaelstromTools.Statics.Tiberium]),
  3118. MaelstromTools.Wrapper.GetDateTimeString(cityCache[MaelstromTools.Statics.Tiberium + 'Full']),
  3119. MaelstromTools.Wrapper.FormatNumbersCompact(cityCache[MaelstromTools.Statics.Crystal]),
  3120. MaelstromTools.Wrapper.GetDateTimeString(cityCache[MaelstromTools.Statics.Crystal + 'Full']),
  3121. MaelstromTools.Wrapper.FormatNumbersCompact(cityCache[MaelstromTools.Statics.Power]),
  3122. MaelstromTools.Wrapper.FormatNumbersCompact(cityCache[MaelstromTools.Statics.Power + 'Max']),
  3123. MaelstromTools.Wrapper.GetDateTimeString(cityCache[MaelstromTools.Statics.Power + 'Full'])
  3124. ]);
  3125. }
  3126. rowData.push([
  3127. 'Total resources',
  3128. MaelstromTools.Wrapper.FormatNumbersCompact(Totals[MaelstromTools.Statics.Tiberium + 'Max']),
  3129. MaelstromTools.Wrapper.FormatNumbersCompact(Totals[MaelstromTools.Statics.Tiberium]),
  3130. '',
  3131. MaelstromTools.Wrapper.FormatNumbersCompact(Totals[MaelstromTools.Statics.Crystal]),
  3132. '',
  3133. MaelstromTools.Wrapper.FormatNumbersCompact(Totals[MaelstromTools.Statics.Power]),
  3134. MaelstromTools.Wrapper.FormatNumbersCompact(Totals[MaelstromTools.Statics.Power + 'Max']),
  3135. ''
  3136. ]);
  3137.  
  3138. this.Model.setData(rowData);
  3139. } catch (e) {
  3140. console.log("MaelstromTools.ResourceOverview.setWidgetLabels: ", e);
  3141. }
  3142. },
  3143.  
  3144. */
  3145. setWidgetLabels: function () {
  3146. try {
  3147. this.Widget.removeAll();
  3148.  
  3149. var first = true;
  3150. var rowIdx = 2;
  3151. var Totals = Object();
  3152. var colIdx = 1;
  3153. Totals[MaelstromTools.Statics.Tiberium] = 0;
  3154. Totals[MaelstromTools.Statics.Crystal] = 0;
  3155. Totals[MaelstromTools.Statics.Power] = 0;
  3156. Totals[MaelstromTools.Statics.Tiberium + "Max"] = 0;
  3157. Totals[MaelstromTools.Statics.Power + "Max"] = 0;
  3158.  
  3159. for (var cityName in this.Cache) {
  3160. var cityCache = this.Cache[cityName];
  3161. Totals[MaelstromTools.Statics.Tiberium] += cityCache[MaelstromTools.Statics.Tiberium];
  3162. Totals[MaelstromTools.Statics.Crystal] += cityCache[MaelstromTools.Statics.Crystal];
  3163. Totals[MaelstromTools.Statics.Power] += cityCache[MaelstromTools.Statics.Power];
  3164. Totals[MaelstromTools.Statics.Tiberium + "Max"] += cityCache[MaelstromTools.Statics.Tiberium + 'Max'];
  3165. Totals[MaelstromTools.Statics.Power + "Max"] += cityCache[MaelstromTools.Statics.Power + 'Max'];
  3166.  
  3167. colIdx = 1;
  3168.  
  3169. MaelstromTools.Util.addLabel(this.Widget, rowIdx, colIdx++, cityName, 100, 'left');
  3170. if (first) {
  3171. MaelstromTools.Util.addLabel(this.Widget, 1, colIdx, 'Max. storage', 80, 'left');
  3172. }
  3173. MaelstromTools.Util.addLabel(this.Widget, rowIdx, colIdx++, MaelstromTools.Wrapper.FormatNumbersCompact(cityCache[MaelstromTools.Statics.Tiberium + 'Max']), 80, 'right');
  3174.  
  3175. if (first) {
  3176. MaelstromTools.Util.addImage(this.Widget, 1, colIdx, MaelstromTools.Util.getImage(MaelstromTools.Statics.Tiberium));
  3177. }
  3178. MaelstromTools.Util.addLabel(this.Widget, rowIdx, colIdx++, MaelstromTools.Wrapper.FormatNumbersCompact(cityCache[MaelstromTools.Statics.Tiberium]), 60, 'right', null, (cityCache[MaelstromTools.Statics.Tiberium] >= cityCache[MaelstromTools.Statics.Tiberium + 'Max'] ? "red" : (cityCache[MaelstromTools.Statics.Tiberium] >= (0.75 * cityCache[MaelstromTools.Statics.Tiberium + 'Max']) ? "yellow" : "white")));
  3179.  
  3180. if (cityCache[MaelstromTools.Statics.Tiberium] < cityCache[MaelstromTools.Statics.Tiberium + 'Max']) {
  3181. MaelstromTools.Util.addLabel(this.Widget, rowIdx, colIdx++, MaelstromTools.Wrapper.GetDateTimeString(cityCache[MaelstromTools.Statics.Tiberium + 'Full']), 100, 'right', null, (cityCache[MaelstromTools.Statics.Tiberium] >= (0.75 * cityCache[MaelstromTools.Statics.Tiberium + 'Max']) ? "yellow" : "white"));
  3182. } else {
  3183. MaelstromTools.Util.addLabel(this.Widget, rowIdx, colIdx++, "Storage full!", 100, 'right', null, "red");
  3184. }
  3185. if (first) {
  3186. MaelstromTools.Util.addImage(this.Widget, 1, colIdx, MaelstromTools.Util.getImage(MaelstromTools.Statics.Crystal));
  3187. }
  3188. MaelstromTools.Util.addLabel(this.Widget, rowIdx, colIdx++, MaelstromTools.Wrapper.FormatNumbersCompact(cityCache[MaelstromTools.Statics.Crystal]), 60, 'right', null, (cityCache[MaelstromTools.Statics.Crystal] >= cityCache[MaelstromTools.Statics.Crystal + 'Max'] ? "red" : (cityCache[MaelstromTools.Statics.Crystal] >= (0.75 * cityCache[MaelstromTools.Statics.Crystal + 'Max']) ? "yellow" : "white")));
  3189.  
  3190. if (cityCache[MaelstromTools.Statics.Crystal] < cityCache[MaelstromTools.Statics.Crystal + 'Max']) {
  3191. MaelstromTools.Util.addLabel(this.Widget, rowIdx, colIdx++, MaelstromTools.Wrapper.GetDateTimeString(cityCache[MaelstromTools.Statics.Crystal + 'Full']), 100, 'right', null, (cityCache[MaelstromTools.Statics.Crystal] >= (0.75 * cityCache[MaelstromTools.Statics.Crystal + 'Max']) ? "yellow" : "white"));
  3192. } else {
  3193. MaelstromTools.Util.addLabel(this.Widget, rowIdx, colIdx++, "Storage full!", 100, 'right', null, "red");
  3194. }
  3195.  
  3196. if (first) {
  3197. MaelstromTools.Util.addImage(this.Widget, 1, colIdx, MaelstromTools.Util.getImage(MaelstromTools.Statics.Power));
  3198. }
  3199. MaelstromTools.Util.addLabel(this.Widget, rowIdx, colIdx++, MaelstromTools.Wrapper.FormatNumbersCompact(cityCache[MaelstromTools.Statics.Power]), 60, 'right', null, (cityCache[MaelstromTools.Statics.Power] >= cityCache[MaelstromTools.Statics.Power + 'Max'] ? "red" : (cityCache[MaelstromTools.Statics.Power] >= (0.75 * cityCache[MaelstromTools.Statics.Power + 'Max']) ? "yellow" : "white")));
  3200.  
  3201. if (first) {
  3202. MaelstromTools.Util.addLabel(this.Widget, 1, colIdx, 'Storage', 80, 'left');
  3203. }
  3204. MaelstromTools.Util.addLabel(this.Widget, rowIdx, colIdx++, MaelstromTools.Wrapper.FormatNumbersCompact(cityCache[MaelstromTools.Statics.Power + 'Max']), 80, 'right');
  3205.  
  3206. if (cityCache[MaelstromTools.Statics.Power] < cityCache[MaelstromTools.Statics.Power + 'Max']) {
  3207. MaelstromTools.Util.addLabel(this.Widget, rowIdx, colIdx++, MaelstromTools.Wrapper.GetDateTimeString(cityCache[MaelstromTools.Statics.Power + 'Full']), 100, 'right', null, (cityCache[MaelstromTools.Statics.Power] >= (0.75 * cityCache[MaelstromTools.Statics.Power + 'Max']) ? "yellow" : "white"));
  3208. } else {
  3209. MaelstromTools.Util.addLabel(this.Widget, rowIdx, colIdx++, "Storage full!", 100, 'right', null, "red");
  3210. }
  3211.  
  3212.  
  3213. MaelstromTools.Util.addElement(this.Widget, rowIdx, colIdx++, MaelstromTools.Util.getAccessBaseButton(cityName));
  3214. rowIdx++;
  3215. first = false;
  3216. }
  3217.  
  3218. colIdx = 1;
  3219. MaelstromTools.Util.addLabel(this.Widget, rowIdx, colIdx++, "Total resources", 100, 'left', 'bold');
  3220. MaelstromTools.Util.addLabel(this.Widget, rowIdx, colIdx++, MaelstromTools.Wrapper.FormatNumbersCompact(Totals[MaelstromTools.Statics.Tiberium + 'Max']), 80, 'right', 'bold');
  3221. MaelstromTools.Util.addLabel(this.Widget, rowIdx, colIdx++, MaelstromTools.Wrapper.FormatNumbersCompact(Totals[MaelstromTools.Statics.Tiberium]), 60, 'right', 'bold');
  3222. MaelstromTools.Util.addLabel(this.Widget, rowIdx, colIdx++, Math.round(Totals[MaelstromTools.Statics.Tiberium] / Totals[MaelstromTools.Statics.Tiberium + 'Max'] * 100) + '%', 100, 'center', 'bold');
  3223. MaelstromTools.Util.addLabel(this.Widget, rowIdx, colIdx++, MaelstromTools.Wrapper.FormatNumbersCompact(Totals[MaelstromTools.Statics.Crystal]), 60, 'right', 'bold');
  3224. MaelstromTools.Util.addLabel(this.Widget, rowIdx, colIdx++, Math.round(Totals[MaelstromTools.Statics.Crystal] / Totals[MaelstromTools.Statics.Tiberium + 'Max'] * 100) + '%', 100, 'center', 'bold');
  3225. MaelstromTools.Util.addLabel(this.Widget, rowIdx, colIdx++, MaelstromTools.Wrapper.FormatNumbersCompact(Totals[MaelstromTools.Statics.Power]), 60, 'right', 'bold');
  3226. MaelstromTools.Util.addLabel(this.Widget, rowIdx, colIdx++, MaelstromTools.Wrapper.FormatNumbersCompact(Totals[MaelstromTools.Statics.Power + 'Max']), 80, 'right', 'bold');
  3227. MaelstromTools.Util.addLabel(this.Widget, rowIdx, colIdx++, Math.round(Totals[MaelstromTools.Statics.Power] / Totals[MaelstromTools.Statics.Power + 'Max'] * 100) + '%', 100, 'center', 'bold');
  3228. } catch (e) {
  3229. console.log("MaelstromTools.ResourceOverview.setWidgetLabels: ", e);
  3230. }
  3231. }
  3232. }
  3233. });
  3234.  
  3235. // define BaseStatus
  3236. qx.Class.define("MaelstromTools.BaseStatus", {
  3237. type: "singleton",
  3238. extend: MaelstromTools.DefaultObject,
  3239. members: {
  3240. CityMenuButtons: null,
  3241.  
  3242. //City.SetDedicatedSupport
  3243. //City.RecallDedicatedSupport
  3244. //City.get_SupportDedicatedBaseId
  3245. //System.String get_SupportDedicatedBaseName ()
  3246. updateCache: function () {
  3247. try {
  3248. MT_Cache.updateCityCache();
  3249. this.Cache = Object();
  3250.  
  3251. for (var cname in MT_Cache.Cities) {
  3252. var ncity = MT_Cache.Cities[cname].Object;
  3253. var player = ClientLib.Data.MainData.GetInstance().get_Player();
  3254. var supportData = ncity.get_SupportData();
  3255. //System.String get_PlayerName ()
  3256. this.Cache[cname] = Object();
  3257. // Movement lock
  3258. this.Cache[cname]["HasCooldown"] = ncity.get_hasCooldown();
  3259. this.Cache[cname]["CooldownEnd"] = Math.max(ncity.get_MoveCooldownEndStep(), ncity.get_MoveRestictionEndStep());
  3260. this.Cache[cname]["MoveCooldownEnd"] = ncity.get_MoveCooldownEndStep();
  3261. this.Cache[cname]["MoveLockdownEnd"] = ncity.get_MoveRestictionEndStep();
  3262. this.Cache[cname]["IsProtected"] = ncity.get_isProtected();
  3263. this.Cache[cname]["ProtectionEnd"] = ncity.get_ProtectionEndStep();
  3264. this.Cache[cname]["IsProtected"] = ncity.get_ProtectionEndStep();
  3265. this.Cache[cname]["IsAlerted"] = ncity.get_isAlerted();
  3266.  
  3267. // Supportweapon
  3268. if (supportData == null) {
  3269. this.Cache[cname]["HasSupportWeapon"] = false;
  3270. } else {
  3271. this.Cache[cname]["HasSupportWeapon"] = true;
  3272. if (ncity.get_SupportDedicatedBaseId() > 0) {
  3273. this.Cache[cname]["SupportedCityId"] = ncity.get_SupportDedicatedBaseId();
  3274. this.Cache[cname]["SupportedCityName"] = ncity.get_SupportDedicatedBaseName();
  3275. var coordId = ncity.get_SupportDedicatedBaseCoordId();
  3276. this.Cache[cname]["SupportedCityX"] = (coordId & 0xffff);
  3277. this.Cache[cname]["SupportedCityY"] = ((coordId >> 0x10) & 0xffff);
  3278. /*
  3279. var cityX = ncity.get_PosX();
  3280. var cityY = ncity.get_PosY();
  3281. var mainData = ClientLib.Data.MainData.GetInstance();
  3282. var visRegion = ClientLib.Vis.VisMain.GetInstance().get_Region();
  3283.  
  3284. var gridW = visRegion.get_GridWidth();
  3285. var gridH = visRegion.get_GridHeight();
  3286. //console.log(cname);
  3287. //console.log("x: " + cityX + " y: " + cityY);
  3288.  
  3289. var worldObj = visRegion.GetObjectFromPosition((this.Cache[cname]["SupportedCityX"]*gridW), (this.Cache[cname]["SupportedCityY"]*gridH));
  3290. //ClientLib.Vis.Region.RegionCity
  3291. if (worldObj == null) {
  3292. this.Cache[cname]["SupportTime"] = "";
  3293. } else {
  3294. console.log(cname);
  3295. //console.log(worldObj.CalibrationSupportDuration());
  3296. var weaponState = worldObj.get_SupportWeaponStatus();
  3297. //console.log(this.calcDuration(ncity, worldObj));
  3298. var cities = ClientLib.Data.MainData.GetInstance().get_Cities();
  3299. cities.set_CurrentOwnCityId(ncity.get_Id());
  3300. var status = worldObj.get_SupportWeaponStatus();
  3301. var server = mainData.get_Server();
  3302. //console.log(worldObj.CalculateSupportCalibrationEndStep(worldObj.get_SupportData(), worldObj.get_SupportWeapon()));
  3303. console.log(status);
  3304. console.log(currStep);
  3305. this.Cache[cname]["SupportTime"] = mainData.get_Time().GetTimespanString(worldObj.CalculateSupportCalibrationEndStep(worldObj.get_SupportData(), worldObj.get_SupportWeapon()), currStep);
  3306. //status.Status&ClientLib.Vis.Region.ESupportWeaponStatus.Calibrating)==ClientLib.Vis.Region.ESupportWeaponStatus.Calibrating
  3307. var currStep = ClientLib.Data.MainData.GetInstance().get_Time().GetServerStep();
  3308. //this.Cache[cname]["SupportTime"] = webfrontend.Util.getTimespanString(ClientLib.Data.MainData.GetInstance().get_Time().GetTimeSpan(Math.max(0, status.CalibrationEndStep) - currStep), false);
  3309. //this.Cache[cname]["SupportTime"] = ClientLib.Data.MainData.GetInstance().get_Time().GetTimespanString(weaponState.CalibrationEndStep, currStep);
  3310. //this.Cache[cname]["SupportTime"] = webfrontend.Util.getTimespanString(ClientLib.Data.MainData.GetInstance().get_Time().GetTimeSpan(Math.max(0, worldObj.CalculateSupportCalibrationEndStep(worldObj.get_SupportData(), worldObj.get_SupportWeapon()) - currStep)), false);
  3311. //console.log(this.Cache[cname]["SupportTime"]);
  3312. }
  3313. */
  3314. } else { // prevent reference to undefined property ReferenceError
  3315. this.Cache[cname]["SupportedCityId"] = null;
  3316. this.Cache[cname]["SupportedCityName"] = null;
  3317. this.Cache[cname]["SupportedCityX"] = null;
  3318. this.Cache[cname]["SupportedCityY"] = null;
  3319. }
  3320. this.Cache[cname]["SupportRange"] = MaelstromTools.Wrapper.GetSupportWeaponRange(ncity.get_SupportWeapon());
  3321. var techName = ClientLib.Base.Tech.GetTechNameFromTechId(supportData.get_Type(), player.get_Faction());
  3322. this.Cache[cname]["SupportName"] = ClientLib.Base.Tech.GetProductionBuildingNameFromFaction(techName, player.get_Faction());
  3323. this.Cache[cname]["SupportLevel"] = supportData.get_Level();
  3324. //this.Cache[cname]["SupportBuilding"] = ncity.get_CityBuildingsData().GetUniqueBuildingByTechName(techName);
  3325. //console.log(this.Cache[cname]["SupportBuilding"]);
  3326. }
  3327. }
  3328. } catch (e) {
  3329. console.log("MaelstromTools.BaseStatus.updateCache: ", e);
  3330. }
  3331. },
  3332. /*
  3333. calcDuration: function(currOwnCity, regionCity) {
  3334. var targetCity = MaelstromTools.Wrapper.GetCity(regionCity.get_Id());
  3335. var supportBase=regionCity.get_SupportData();
  3336. if(supportBase == null)
  3337. {
  3338. return -1;
  3339. }
  3340. var weapon=regionCity.get_SupportWeapon();
  3341. if(weapon == null)
  3342. {
  3343. return -1;
  3344. }
  3345. if(currOwnCity.get_Id() == regionCity.get_Id())
  3346. {
  3347. if(supportBase.get_Magnitude() == 0) {
  3348. return -1;
  3349. }
  3350. return 0;
  3351. }
  3352. var dx=(currOwnCity.get_X() - targetCity.get_PosX());
  3353. var dy=(currOwnCity.get_Y() - targetCity.get_PosY());
  3354. var distance=((dx * dx) + (dy * dy));
  3355. return Math.floor((weapon.pt + (weapon.tpf * Math.floor((Math.sqrt(distance) + 0.5)))));
  3356. },*/
  3357.  
  3358. setWidgetLabels: function () {
  3359. try {
  3360. this.Widget.removeAll();
  3361. var rowIdx = 1;
  3362. var colIdx = 2;
  3363.  
  3364. MaelstromTools.Util.addLabel(this.Widget, rowIdx, colIdx++, "Cooldown", 85, 'left');
  3365. MaelstromTools.Util.addLabel(this.Widget, rowIdx, colIdx++, "Protection", 85, 'left');
  3366. MaelstromTools.Util.addLabel(this.Widget, rowIdx, colIdx++, "Available weapon", 140, 'left');
  3367. MaelstromTools.Util.addLabel(this.Widget, rowIdx, colIdx++, "Calibrated on", 140, 'left');
  3368.  
  3369. //colIdx++;
  3370. var rowIdxRecall = rowIdx;
  3371. var colIdxRecall = 0;
  3372. var supportWeaponCount = 0;
  3373.  
  3374. rowIdx++;
  3375. for (var cityName in this.Cache) {
  3376. var cityCache = this.Cache[cityName];
  3377. colIdx = 1;
  3378.  
  3379. MaelstromTools.Util.addLabel(this.Widget, rowIdx, colIdx++, cityName, 100, 'left', null, (cityCache.IsAlerted ? 'red' : null));
  3380.  
  3381. MaelstromTools.Util.addLabel(this.Widget, rowIdx, colIdx++, MaelstromTools.Wrapper.GetStepTime(cityCache.CooldownEnd), 70, 'right');
  3382. MaelstromTools.Util.addLabel(this.Widget, rowIdx, colIdx++, MaelstromTools.Wrapper.GetStepTime(cityCache.ProtectionEnd), 70, 'right');
  3383.  
  3384. if (!cityCache.HasSupportWeapon) {
  3385. MaelstromTools.Util.addLabel(this.Widget, rowIdx, colIdx++, "none", 140, 'left');
  3386. colIdx += 2;
  3387. } else {
  3388. supportWeaponCount++;
  3389. MaelstromTools.Util.addLabel(this.Widget, rowIdx, colIdx++, cityCache.SupportName + " (" + cityCache.SupportLevel + ")", 140, 'left');
  3390.  
  3391. if (cityCache.SupportedCityId > 0) {
  3392. MaelstromTools.Util.addLabel(this.Widget, rowIdx, colIdx++, cityCache.SupportedCityName, 140, 'left');
  3393. colIdxRecall = colIdx;
  3394. MaelstromTools.Util.addElement(this.Widget, rowIdx, colIdx++, this.getRecallButton(cityName));
  3395. } else {
  3396. colIdx += 2;
  3397. }
  3398. }
  3399.  
  3400. MaelstromTools.Util.addElement(this.Widget, rowIdx, colIdx++, MaelstromTools.Util.getAccessBaseButton(cityName));
  3401. MaelstromTools.Util.addElement(this.Widget, rowIdx, colIdx++, MaelstromTools.Util.getFocusBaseButton(cityName));
  3402.  
  3403. rowIdx++;
  3404. }
  3405.  
  3406. if (supportWeaponCount > 0 && colIdxRecall > 0) {
  3407. MaelstromTools.Util.addElement(this.Widget, rowIdxRecall, colIdxRecall, this.getRecallAllButton());
  3408. }
  3409. } catch (e) {
  3410. console.log("MaelstromTools.BaseStatus.setWidgetLabels: ", e);
  3411. }
  3412. },
  3413.  
  3414. getRecallAllButton: function () {
  3415. var button = new qx.ui.form.Button("Recall all").set({
  3416. appearance: "button-text-small",
  3417. toolTipText: "Recall all support weapons",
  3418. width: 100,
  3419. height: 20
  3420. });
  3421. button.addListener("execute", function (e) {
  3422. MaelstromTools.Util.recallAllSupport();
  3423. }, this);
  3424. return button;
  3425. },
  3426.  
  3427. getRecallButton: function (cityName) {
  3428. var button = new qx.ui.form.Button("Recall").set({
  3429. appearance: "button-text-small",
  3430. toolTipText: "Recall support to " + cityName,
  3431. width: 100,
  3432. height: 20
  3433. });
  3434. button.addListener("execute", function (e) {
  3435. MaelstromTools.Util.recallSupport(cityName);
  3436. }, this);
  3437. return button;
  3438. }
  3439. /*
  3440. getCalibrateAllOnSelectedBaseButton: function() {
  3441. var button = new qx.ui.form.Button("Calibrate all weapons on selected base").set({
  3442. appearance: "button-text-small",
  3443. toolTipText: "Calibrate all weapons",
  3444. width: 100,
  3445. height: 20
  3446. });
  3447. button.addListener("execute", function(e){
  3448. Util.calibrateWholeSupport(ClientLib.Data.MainData.GetInstance().get_Cities().get_CurrentCityId());
  3449. }, this);
  3450. return button;
  3451. }*/
  3452.  
  3453.  
  3454. }
  3455. });
  3456.  
  3457. // define Statics
  3458. qx.Class.define("MaelstromTools.Statics", {
  3459. type: "static",
  3460. statics: {
  3461. Tiberium: 'Tiberium',
  3462. Crystal: 'Crystal',
  3463. Power: 'Power',
  3464. Dollar: 'Dollar',
  3465. Research: 'Research',
  3466. Vehicle: "Vehicle",
  3467. Aircraft: "Aircraft",
  3468. Infantry: "Infantry",
  3469.  
  3470. LootTypeName: function (ltype) {
  3471. switch (ltype) {
  3472. case ClientLib.Base.EResourceType.Tiberium:
  3473. return MaelstromTools.Statics.Tiberium;
  3474. break;
  3475. case ClientLib.Base.EResourceType.Crystal:
  3476. return MaelstromTools.Statics.Crystal;
  3477. break;
  3478. case ClientLib.Base.EResourceType.Power:
  3479. return MaelstromTools.Statics.Power;
  3480. break;
  3481. case ClientLib.Base.EResourceType.Gold:
  3482. return MaelstromTools.Statics.Dollar;
  3483. break;
  3484. default:
  3485. return "";
  3486. break;
  3487. }
  3488. }
  3489. }
  3490. });
  3491.  
  3492. // define Util
  3493. //ClientLib.Data.Cities.prototype.GetCityByCoord
  3494. //ClientLib.Data.City.prototype.get_HasIncommingAttack
  3495. qx.Class.define("MaelstromTools.Util", {
  3496. type: "static",
  3497. statics: {
  3498. ArrayUnique: function (array) {
  3499. var o = {};
  3500. var l = array.length;
  3501. r = [];
  3502. for (var i = 0; i < l; i++) o[array[i]] = array[i];
  3503. for (var i in o) r.push(o[i]);
  3504. return r;
  3505. },
  3506.  
  3507. ArraySize: function (array) {
  3508. var size = 0;
  3509. for (var key in array)
  3510. if (array.hasOwnProperty(key)) size++;
  3511. return size;
  3512. },
  3513.  
  3514. addLabel: function (widget, rowIdx, colIdx, value, width, textAlign, font, color, colSpan) {
  3515. try {
  3516. var label = new qx.ui.basic.Label().set({
  3517. value: Lang.gt(value)
  3518. });
  3519. if (width) {
  3520. label.setWidth(width);
  3521. }
  3522. if (textAlign) {
  3523. label.setTextAlign(textAlign);
  3524. }
  3525. if (color) {
  3526. label.setTextColor(color);
  3527. }
  3528. if (font) {
  3529. label.setFont(font);
  3530. }
  3531. if (!colSpan || colSpan == 0) {
  3532. colSpan = 1;
  3533. }
  3534.  
  3535. widget.add(label, {
  3536. row: rowIdx,
  3537. column: colIdx,
  3538. colSpan: colSpan
  3539. });
  3540. } catch (e) {
  3541. console.log("MaelstromTools.Util.addLabel: ", e);
  3542. }
  3543. },
  3544.  
  3545. addElement: function (widget, rowIdx, colIdx, element, colSpan) {
  3546. try {
  3547. if (!colSpan || colSpan == 0) {
  3548. colSpan = 1;
  3549. }
  3550. widget.add(element, {
  3551. row: rowIdx,
  3552. column: colIdx,
  3553. colSpan: colSpan
  3554. });
  3555. } catch (e) {
  3556. console.log("MaelstromTools.Util.addElement: ", e);
  3557. }
  3558. },
  3559.  
  3560. addImage: function (widget, rowIdx, colIdx, image) {
  3561. try {
  3562. widget.add(image, {
  3563. row: rowIdx,
  3564. column: colIdx
  3565. });
  3566. } catch (e) {
  3567. console.log("MaelstromTools.Util.addImage: ", e);
  3568. }
  3569. },
  3570.  
  3571. getImage: function (name) {
  3572. var image = new qx.ui.basic.Image(MT_Base.images[name]);
  3573. image.setScale(true);
  3574. image.setWidth(20);
  3575. image.setHeight(20);
  3576. return image;
  3577. },
  3578.  
  3579. getAccessBaseButton: function (cityName, viewMode) {
  3580. try {
  3581. var cityButton = new qx.ui.form.Button(null, MT_Base.images["AccessBase"]).set({
  3582. appearance: "button-detailview-small",
  3583. toolTipText: Lang.gt("Access") + " " + cityName,
  3584. width: 20,
  3585. height: 20,
  3586. marginLeft: 5
  3587. });
  3588. cityButton.setUserData("cityId", MT_Cache.Cities[cityName].ID);
  3589. cityButton.setUserData("viewMode", viewMode);
  3590. cityButton.addListener("execute", function (e) {
  3591. MaelstromTools.Util.accessBase(e.getTarget().getUserData("cityId"), e.getTarget().getUserData("viewMode"));
  3592. }, this);
  3593. return cityButton;
  3594. } catch (e) {
  3595. console.log("MaelstromTools.Util.getAccessBaseButton: ", e);
  3596. }
  3597. },
  3598.  
  3599. getFocusBaseButton: function (cityName) {
  3600. try {
  3601. var cityButton = new qx.ui.form.Button(null, MT_Base.images["FocusBase"]).set({
  3602. appearance: "button-detailview-small",
  3603. toolTipText: Lang.gt("Focus on") + " " + cityName,
  3604. width: 20,
  3605. height: 20,
  3606. marginLeft: 5
  3607. });
  3608. cityButton.setUserData("cityId", MT_Cache.Cities[cityName].ID);
  3609. cityButton.addListener("execute", function (e) {
  3610. MaelstromTools.Util.focusBase(e.getTarget().getUserData("cityId"));
  3611. }, this);
  3612. return cityButton;
  3613. } catch (e) {
  3614. console.log("MaelstromTools.Util.getFocusBaseButton: ", e);
  3615. }
  3616. },
  3617.  
  3618. accessBase: function (cityId, viewMode) {
  3619. try {
  3620. if (cityId > 0) {
  3621. var ncity = MaelstromTools.Wrapper.GetCity(cityId);
  3622.  
  3623. if (ncity != null && !ncity.get_IsGhostMode()) {
  3624. if (viewMode) {
  3625. webfrontend.gui.UtilView.openVisModeInMainWindow(viewMode, cityId, false);
  3626. } else {
  3627. webfrontend.gui.UtilView.openCityInMainWindow(cityId);
  3628. }
  3629. }
  3630. }
  3631. } catch (e) {
  3632. console.log("MaelstromTools.Util.accessBase: ", e);
  3633. }
  3634. },
  3635. focusBase: function (cityId) {
  3636. try {
  3637. if (cityId > 0) {
  3638. var ncity = MaelstromTools.Wrapper.GetCity(cityId);
  3639.  
  3640. if (ncity != null && !ncity.get_IsGhostMode()) {
  3641. webfrontend.gui.UtilView.centerCityOnRegionViewWindow(cityId);
  3642. }
  3643. }
  3644. } catch (e) {
  3645. console.log("MaelstromTools.Util.focusBase: ", e);
  3646. }
  3647. },
  3648.  
  3649. recallSupport: function (cityName) {
  3650. try {
  3651. var ncity = MT_Cache.Cities[cityName]["Object"];
  3652. ncity.RecallDedicatedSupport();
  3653. } catch (e) {
  3654. console.log("MaelstromTools.Util.recallSupport: ", e);
  3655. }
  3656. },
  3657.  
  3658. recallAllSupport: function () {
  3659. try {
  3660. MT_Cache.updateCityCache();
  3661. for (var cityName in MT_Cache.Cities) {
  3662. var ncity = MT_Cache.Cities[cityName]["Object"];
  3663. ncity.RecallDedicatedSupport();
  3664. }
  3665. } catch (e) {
  3666. console.log("MaelstromTools.Util.recallAllSupport: ", e);
  3667. }
  3668. },
  3669.  
  3670. checkIfSupportIsAllowed: function (selectedBase) {
  3671. try {
  3672. if (selectedBase.get_VisObjectType() != ClientLib.Vis.VisObject.EObjectType.RegionCityType) {
  3673. return false;
  3674. }
  3675. if (selectedBase.get_Type() != ClientLib.Vis.Region.RegionCity.ERegionCityType.Own && selectedBase.get_Type() != ClientLib.Vis.Region.RegionCity.ERegionCityType.Alliance) {
  3676. return false;
  3677. }
  3678. return true;
  3679. } catch (e) {
  3680. console.log("MaelstromTools.Util.checkIfSupportIsAllowed: ", e);
  3681. return false;
  3682. }
  3683. },
  3684.  
  3685. calibrateWholeSupportOnSelectedBase: function () {
  3686. if (this.checkIfSupportIsAllowed(MT_Cache.SelectedBaseForMenu)) {
  3687. this.calibrateWholeSupport(MT_Cache.SelectedBaseForMenu);
  3688. }
  3689. },
  3690.  
  3691. calibrateWholeSupport: function (targetRegionCity) {
  3692. try {
  3693. MT_Cache.updateCityCache();
  3694. for (var cityName in MT_Cache.Cities) {
  3695. var ncity = MT_Cache.Cities[cityName]["Object"];
  3696. //var targetCity = MaelstromTools.Wrapper.GetCity(targetCityId);
  3697. var weapon = ncity.get_SupportWeapon();
  3698.  
  3699. //console.log("checking support weapon for " + ncity.get_Name() + " calibrating on " + targetRegionCity.get_Name());
  3700.  
  3701. if (targetRegionCity != null && weapon != null) {
  3702. //console.log("city at " + ncity.get_X() + " / " + ncity.get_Y());
  3703. //console.log("targetRegionCity at " + targetRegionCity.get_RawX() + " / " + targetRegionCity.get_RawY());
  3704. //var distance = ClientLib.Base.Util.CalculateDistance(ncity.get_X(), ncity.get_Y(), targetRegionCity.get_RawX(), targetRegionCity.get_RawY());
  3705. var dx = (ncity.get_X() - targetRegionCity.get_RawX());
  3706. var dy = (ncity.get_Y() - targetRegionCity.get_RawY());
  3707. var distance = ((dx * dx) + (dy * dy));
  3708. var range = MaelstromTools.Wrapper.GetSupportWeaponRange(weapon);
  3709. //console.log("distance is " + distance);
  3710. //console.log("range isy " + range*range);
  3711. if (distance <= (range * range)) {
  3712. ncity.SetDedicatedSupport(targetRegionCity.get_Id());
  3713. }
  3714. }
  3715. }
  3716. } catch (e) {
  3717. console.log("MaelstromTools.Util.calibrateWholeSupport: ", e);
  3718. }
  3719. },
  3720.  
  3721. // visCity : ClientLib.Vis.Region.RegionObject
  3722. getResources: function (visCity) { // to verifier against PerforceChangelist>=376877
  3723. try {
  3724. var loot = new Object();
  3725. if (visCity.get_X() < 0 || visCity.get_Y() < 0) {
  3726. loot["LoadState"] = 0;
  3727. return loot;
  3728. }
  3729. var currentOwnCity = ClientLib.Data.MainData.GetInstance().get_Cities().get_CurrentOwnCity();
  3730.  
  3731. var distance = ClientLib.Base.Util.CalculateDistance(currentOwnCity.get_X(), currentOwnCity.get_Y(), visCity.get_RawX(), visCity.get_RawY());
  3732. var maxAttackDistance = ClientLib.Data.MainData.GetInstance().get_Server().get_MaxAttackDistance();
  3733. if (distance > maxAttackDistance) {
  3734. loot["LoadState"] = -1;
  3735. return loot;
  3736. }
  3737.  
  3738. var ncity = MaelstromTools.Wrapper.GetCity(visCity.get_Id());
  3739. /* ClientLib.Data.CityBuildings */
  3740. //var cityBuildings = ncity.get_CityBuildingsData();
  3741. var cityUnits = ncity.get_CityUnitsData();
  3742.  
  3743. //var buildings = MaelstromTools.Wrapper.GetBuildings(cityBuildings);
  3744. var buildings = ncity.get_Buildings().d;
  3745. var defenseUnits = MaelstromTools.Wrapper.GetDefenseUnits(cityUnits);
  3746. //var defenseUnits = MaelstromTools.Wrapper.GetDefenseUnits();
  3747.  
  3748. /*for(var u in buildings) {
  3749. console.log(buildings[u].get_MdbBuildingId());
  3750. console.log("----------------");
  3751. }*/
  3752.  
  3753. var buildingLoot = MaelstromTools.Util.getResourcesPart(buildings);
  3754. //var buildingLoot2 = MaelstromTools.Util.getResourcesPart(this.collectBuildings(ncity));
  3755.  
  3756. var unitLoot = MaelstromTools.Util.getResourcesPart(defenseUnits);
  3757.  
  3758. loot[MaelstromTools.Statics.Tiberium] = buildingLoot[ClientLib.Base.EResourceType.Tiberium] + unitLoot[ClientLib.Base.EResourceType.Tiberium];
  3759. loot[MaelstromTools.Statics.Crystal] = buildingLoot[ClientLib.Base.EResourceType.Crystal] + unitLoot[ClientLib.Base.EResourceType.Crystal];
  3760. loot[MaelstromTools.Statics.Dollar] = buildingLoot[ClientLib.Base.EResourceType.Gold] + unitLoot[ClientLib.Base.EResourceType.Gold];
  3761. loot[MaelstromTools.Statics.Research] = buildingLoot[ClientLib.Base.EResourceType.ResearchPoints] + unitLoot[ClientLib.Base.EResourceType.ResearchPoints];
  3762. loot["Factor"] = loot[MaelstromTools.Statics.Tiberium] + loot[MaelstromTools.Statics.Crystal] + loot[MaelstromTools.Statics.Dollar] + loot[MaelstromTools.Statics.Research];
  3763. loot["CPNeeded"] = currentOwnCity.CalculateAttackCommandPointCostToCoord(ncity.get_X(), ncity.get_Y());
  3764. loot["LoadState"] = (loot["Factor"] > 0 ? 1 : 0);
  3765. loot["Total"] = loot[MaelstromTools.Statics.Research] + loot[MaelstromTools.Statics.Tiberium] + loot[MaelstromTools.Statics.Crystal] + loot[MaelstromTools.Statics.Dollar];
  3766.  
  3767. /*console.log("Building loot");
  3768. console.log( buildingLoot[ClientLib.Base.EResourceType.Tiberium] + " vs " + buildingLoot2[ClientLib.Base.EResourceType.Tiberium]);
  3769. console.log( buildingLoot[ClientLib.Base.EResourceType.Crystal] + " vs " + buildingLoot2[ClientLib.Base.EResourceType.Crystal]);
  3770. console.log( buildingLoot[ClientLib.Base.EResourceType.Gold] + " vs " + buildingLoot2[ClientLib.Base.EResourceType.Gold]);
  3771. console.log( buildingLoot[ClientLib.Base.EResourceType.ResearchPoints] + " vs " + buildingLoot2[ClientLib.Base.EResourceType.ResearchPoints]);
  3772. console.log("-------------");*/
  3773. return loot;
  3774. } catch (e) {
  3775. console.log("MaelstromTools.Util.getResources", e);
  3776. }
  3777. },
  3778. /*
  3779. collectBuildings: function(ncity) {
  3780. var cityBuildings = ncity.get_CityBuildingsData();
  3781. var buildings = new Array();
  3782. var count = 0;
  3783. // ncity.GetNumBuildings()
  3784. for(var i = 0; i < 100000; i++) {
  3785. var building = cityBuildings.GetBuildingByMDBId(i);
  3786. if(!building) {
  3787. continue;
  3788. }
  3789. //console.log(building.get_TechName() + " - " + ncity.get_CityFaction() + " - " + ClientLib.Base.Tech.GetTechIdFromTechNameAndFaction(building.get_TechName(), ncity.get_CityFaction()) + " at lvl " + building.get_CurrentLevel());
  3790. buildings.push(building);
  3791. //buildings[count++] = building;
  3792. }
  3793. return buildings; //MaelstromTools.Util.ArrayUnique(buildings);
  3794. },*/
  3795.  
  3796. getResourcesPart: function (cityEntities) {
  3797. try {
  3798. var loot = [0, 0, 0, 0, 0, 0, 0, 0];
  3799. if (cityEntities == null) {
  3800. return loot;
  3801. }
  3802.  
  3803. var objcityEntities = [];
  3804. if (PerforceChangelist >= 376877) { //new
  3805. for (var o in cityEntities) objcityEntities.push(cityEntities[o]);
  3806. } else { //old
  3807. for (var i = 0; i < cityEntities.length; i++) objcityEntities.push(cityEntities[i]);
  3808. }
  3809.  
  3810. for (var i = 0; i < objcityEntities.length; i++) {
  3811. var cityEntity = objcityEntities[i];
  3812. var unitLevelRequirements = MaelstromTools.Wrapper.GetUnitLevelRequirements(cityEntity);
  3813.  
  3814. for (var x = 0; x < unitLevelRequirements.length; x++) {
  3815. loot[unitLevelRequirements[x].Type] += unitLevelRequirements[x].Count * cityEntity.get_HitpointsPercent();
  3816. if (cityEntity.get_HitpointsPercent() < 1.0) {
  3817. // destroyed
  3818.  
  3819. }
  3820. }
  3821. }
  3822.  
  3823. return loot;
  3824. } catch (e) {
  3825. console.log("MaelstromTools.Util.getResourcesPart", e);
  3826. }
  3827. }
  3828.  
  3829. /*
  3830. findBuildings: function(city) {
  3831. for (var k in city) {
  3832. if ((typeof(city[k]) == "object") && city[k] && city[k] && 0 in city[k]) {
  3833. if ((typeof(city[k][0]) == "object") && city[k][0] && "BuildingDBId" in city[k][0]) {
  3834. return city[k];
  3835. }
  3836. }
  3837. }
  3838. return [];
  3839. }*/
  3840. }
  3841. });
  3842.  
  3843. // define Wrapper
  3844. qx.Class.define("MaelstromTools.Wrapper", {
  3845. type: "static",
  3846. statics: {
  3847. GetStepTime: function (step, defaultString) {
  3848. if (!defaultString) {
  3849. defaultString = "";
  3850. }
  3851. var endTime = ClientLib.Data.MainData.GetInstance().get_Time().GetTimespanString(step, ClientLib.Data.MainData.GetInstance().get_Time().GetServerStep());
  3852. if (endTime == "00:00") {
  3853. return defaultString;
  3854. }
  3855. return endTime;
  3856. },
  3857.  
  3858. FormatNumbersCompact: function (value) {
  3859. if (PerforceChangelist >= 387751) { //new
  3860. return phe.cnc.gui.util.Numbers.formatNumbersCompact(value);
  3861. } else { //old
  3862. return webfrontend.gui.Util.formatNumbersCompact(value);
  3863. }
  3864. },
  3865.  
  3866. GetDateTimeString: function (value) {
  3867. return phe.cnc.Util.getDateTimeString(value);
  3868. },
  3869.  
  3870. FormatTimespan: function (value) {
  3871. return ClientLib.Vis.VisMain.FormatTimespan(value);
  3872. },
  3873.  
  3874. GetSupportWeaponRange: function (weapon) {
  3875. return weapon.r;
  3876. },
  3877.  
  3878. GetCity: function (cityId) {
  3879. return ClientLib.Data.MainData.GetInstance().get_Cities().GetCity(cityId);
  3880. },
  3881.  
  3882. RepairAll: function (ncity, visMode) {
  3883. var oldMode = ClientLib.Vis.VisMain.GetInstance().get_Mode();
  3884. ClientLib.Vis.VisMain.GetInstance().set_Mode(visMode);
  3885. ncity.RepairAll();
  3886. ClientLib.Vis.VisMain.GetInstance().set_Mode(oldMode);
  3887. },
  3888.  
  3889. CanRepairAll: function (ncity, viewMode) {
  3890. try {
  3891. /*var oldMode = ClientLib.Vis.VisMain.GetInstance().get_Mode();
  3892. ClientLib.Vis.VisMain.GetInstance().set_Mode(visMode);
  3893. var retVal = ncity.CanRepairAll();
  3894. ClientLib.Vis.VisMain.GetInstance().set_Mode(oldMode);
  3895. return retVal;*/
  3896.  
  3897. var repairData = ncity.get_CityRepairData();
  3898. var myRepair = repairData.CanRepair(0, viewMode);
  3899. repairData.UpdateCachedFullRepairAllCost(viewMode);
  3900. return ((myRepair != null) && (!ncity.get_IsLocked() || (viewMode != ClientLib.Vis.Mode.ArmySetup)));
  3901.  
  3902. return false;
  3903. } catch (e) {
  3904. console.log("MaelstromTools.Wrapper.CanRepairAll: ", e);
  3905. return false;
  3906. }
  3907. },
  3908. /*GetBuildings: function (cityBuildings) {
  3909. if (PerforceChangelist >= 376877) { //new
  3910. return (cityBuildings.get_Buildings() != null ? cityBuildings.get_Buildings().d : null);
  3911. } else { //old
  3912. return (cityBuildings.get_Buildings() != null ? cityBuildings.get_Buildings().l : null);
  3913. }
  3914. },*/
  3915. GetDefenseUnits: function (cityUnits) {
  3916. //GetDefenseUnits: function () {
  3917. if (PerforceChangelist >= 392583) { //endgame patch
  3918. return (cityUnits.get_DefenseUnits() != null ? cityUnits.get_DefenseUnits().d : null);
  3919. } else { //old
  3920. var defenseObjects = [];
  3921. for (var x = 0; x < 9; x++) {
  3922. for (var y = 0; y < 8; y++) {
  3923. var defenseObject = ClientLib.Vis.VisMain.GetInstance().get_DefenseSetup().GetDefenseObjectFromPosition((x * ClientLib.Vis.VisMain.GetInstance().get_City().get_GridWidth()),(y * ClientLib.Vis.VisMain.GetInstance().get_City().get_GridHeight()));
  3924. if (defenseObject !== null && defenseObject.get_CityEntity() !== null) {
  3925. defenseObjects.push(defenseObject.get_UnitDetails());
  3926. }
  3927. }
  3928. }
  3929. return defenseObjects;
  3930. }
  3931. },
  3932. GetUnitLevelRequirements: function (cityEntity) {
  3933. if (PerforceChangelist >= 376877) { //new
  3934. return (cityEntity.get_UnitLevelRepairRequirements() != null ? cityEntity.get_UnitLevelRepairRequirements() : null);
  3935. } else { //old
  3936. return (cityEntity.get_UnitLevelRequirements() != null ? cityEntity.get_UnitLevelRequirements() : null);
  3937. }
  3938. },
  3939.  
  3940. GetBaseLevel: function (ncity) {
  3941. return (Math.floor(ncity.get_LvlBase() * 100) / 100).toFixed(2);
  3942. }
  3943. /*,
  3944. GetPointsByLevelWithThresholds: function (_levelThresholds,_levelFactors,_iLevel) {
  3945. var result=0;
  3946. var lastLevel=_iLevel;
  3947. if(_levelThresholds.length != _levelFactors.length) {
  3948. return 0;
  3949. }
  3950. for (var i=(_levelThresholds.length - 1); (i >= 0); i--) {
  3951. var threshold=(_levelThresholds[i] - 1);
  3952. if(lastLevel >= threshold) {
  3953. result += ((lastLevel - threshold) * _levelFactors[i]);
  3954. lastLevel=threshold;
  3955. }
  3956. }
  3957. return result;
  3958. },
  3959. GetArmyPoints: function(_iLevel) {
  3960. var server = ClientLib.Data.MainData.GetInstance().get_Server();
  3961. var m_iArmyPointsPerLevelThresholds = server.get_ArmyPointsPerLevelThresholds();
  3962. var m_fArmyPointsPerLevel = server.get_ArmyPointsPerLevel();
  3963. _iLevel += 4;
  3964. var armyPoints = MaelstromTools.Wrapper.GetPointsByLevelWithThresholds(m_iArmyPointsPerLevelThresholds, m_fArmyPointsPerLevel, _iLevel);
  3965. return Math.min(armyPoints, server.get_MaxArmyPoints());
  3966. },
  3967. GetBuilding: function(ncity, techName) {
  3968. return ncity.get_CityBuildingsData().GetUniqueBuildingByTechName(techName)
  3969. },
  3970. GetCommandCenter: function(ncity) {
  3971. //var techName = ClientLib.Base.Tech.GetTechIdFromTechNameAndFaction(ClientLib.Base.ETechName.Command_Center, ClientLib.Data.MainData.GetInstance().get_Player().get_Faction());
  3972.  
  3973. return MaelstromTools.Wrapper.GetBuilding(ncity, ClientLib.Base.ETechName.Command_Center);
  3974. // conyard return this.GetBuildingCondition$0(ClientLib.Base.Tech.GetTechIdFromTechNameAndFaction$0(0, ClientLib.Data.MainData.GetInstance$9().get_Player$2().get_Faction$2()));
  3975. // ClientLib.Data.City.prototype.GetOffenseConditionInPercent=ClientLib.Data.City.prototype.GetOffenseConditionInPercent$0;
  3976. }*/
  3977. }
  3978. });
  3979.  
  3980. // define LocalStorage
  3981. qx.Class.define("MaelstromTools.LocalStorage", {
  3982. type: "static",
  3983. statics: {
  3984. isSupported: function () {
  3985. return typeof (Storage) !== "undefined";
  3986. },
  3987. set: function (key, value) {
  3988. try {
  3989. if (MaelstromTools.LocalStorage.isSupported()) {
  3990. localStorage["CCTA_MaelstromTools_" + key] = JSON.stringify(value);
  3991. }
  3992. } catch (e) {
  3993. console.log("MaelstromTools.LocalStorage.set: ", e);
  3994. }
  3995. },
  3996. get: function (key, defaultValueIfNotSet) {
  3997. try {
  3998. if (MaelstromTools.LocalStorage.isSupported()) {
  3999. if (localStorage["CCTA_MaelstromTools_" + key] != null && localStorage["CCTA_MaelstromTools_" + key] != 'undefined') {
  4000. return JSON.parse(localStorage["CCTA_MaelstromTools_" + key]);
  4001. }
  4002. }
  4003. } catch (e) {
  4004. console.log("MaelstromTools.LocalStorage.get: ", e);
  4005. }
  4006. return defaultValueIfNotSet;
  4007. },
  4008. clearAll: function () {
  4009. try {
  4010. if (!MaelstromTools.LocalStorage.isSupported()) {
  4011. return;
  4012. }
  4013. for (var key in localStorage) {
  4014. if (key.indexOf("CCTA_MaelstromTools_") == 0) {
  4015. localStorage.removeItem(key);
  4016. }
  4017. }
  4018. } catch (e) {
  4019. console.log("MaelstromTools.LocalStorage.clearAll: ", e);
  4020. }
  4021. }
  4022. }
  4023. });
  4024.  
  4025. // define Cache
  4026. qx.Class.define("MaelstromTools.Cache", {
  4027. type: "singleton",
  4028. extend: qx.core.Object,
  4029. members: {
  4030. CityCount: 0,
  4031. Cities: null,
  4032. SelectedBaseForMenu: null,
  4033. SelectedBaseResources: null,
  4034. SelectedBaseForLoot: null,
  4035.  
  4036. updateCityCache: function () {
  4037. try {
  4038. this.CityCount = 0;
  4039. this.Cities = Object();
  4040.  
  4041. var cities = ClientLib.Data.MainData.GetInstance().get_Cities().get_AllCities();
  4042. for (var cindex in cities.d) {
  4043. this.CityCount++;
  4044. var ncity = MaelstromTools.Wrapper.GetCity(cindex);
  4045. var ncityName = ncity.get_Name();
  4046. this.Cities[ncityName] = Object();
  4047. this.Cities[ncityName]["ID"] = cindex;
  4048. this.Cities[ncityName]["Object"] = ncity;
  4049. }
  4050. } catch (e) {
  4051. console.log("MaelstromTools.Cache.updateCityCache: ", e);
  4052. }
  4053. },
  4054.  
  4055. updateLoot: function (visCity) {
  4056. var cityId = visCity.get_Id();
  4057.  
  4058. if (this.SelectedBaseForLoot != null && cityId == this.SelectedBaseForLoot.get_Id() && this.SelectedBaseResources != null && this.SelectedBaseResources["LoadState"] > 0) {
  4059. return -2;
  4060. }
  4061. this.SelectedBaseForLoot = visCity;
  4062. this.SelectedBaseResources = MaelstromTools.Util.getResources(visCity);
  4063. return this.SelectedBaseResources["LoadState"];
  4064. }
  4065. }
  4066. });
  4067.  
  4068. // define HuffyTools.ImageRender
  4069. qx.Class.define("HuffyTools.ImageRender", {
  4070. extend: qx.ui.table.cellrenderer.AbstractImage,
  4071. construct: function (width, height) {
  4072. this.base(arguments);
  4073. if (width) {
  4074. this.__imageWidth = width;
  4075. }
  4076. if (height) {
  4077. this.__imageHeight = height;
  4078. }
  4079. this.__am = qx.util.AliasManager.getInstance();
  4080. },
  4081. members: {
  4082. __am: null,
  4083. __imageHeight: 16,
  4084. __imageWidth: 16,
  4085. // overridden
  4086. _identifyImage: function (cellInfo) {
  4087. var imageHints = {
  4088. imageWidth: this.__imageWidth,
  4089. imageHeight: this.__imageHeight
  4090. };
  4091. if (cellInfo.value == "") {
  4092. imageHints.url = null;
  4093. } else {
  4094. imageHints.url = this.__am.resolve(cellInfo.value);
  4095. }
  4096. imageHints.tooltip = cellInfo.tooltip;
  4097. return imageHints;
  4098. }
  4099. },
  4100. destruct: function () {
  4101. this.__am = null;
  4102. }
  4103. });
  4104.  
  4105. // define HuffyTools.ReplaceRender
  4106. qx.Class.define("HuffyTools.ReplaceRender", {
  4107. extend: qx.ui.table.cellrenderer.Default,
  4108. properties: {
  4109. replaceFunction: {
  4110. check: "Function",
  4111. nullable: true,
  4112. init: null
  4113. }
  4114. },
  4115. members: {
  4116. // overridden
  4117. _getContentHtml: function (cellInfo) {
  4118. var value = cellInfo.value;
  4119. var replaceFunc = this.getReplaceFunction();
  4120. // use function
  4121. if (replaceFunc) {
  4122. cellInfo.value = replaceFunc(value);
  4123. }
  4124. return qx.bom.String.escape(this._formatValue(cellInfo));
  4125. }
  4126. }
  4127. });
  4128.  
  4129. qx.Class.define("HuffyTools.CityCheckBox", {
  4130. extend: qx.ui.form.CheckBox,
  4131. members: {
  4132. HT_CityID: null
  4133. }
  4134. });
  4135.  
  4136. // define HuffyTools.UpgradePriorityGUI
  4137. qx.Class.define("HuffyTools.UpgradePriorityGUI", {
  4138. type: "singleton",
  4139. extend: MaelstromTools.DefaultObject,
  4140. members: {
  4141. HT_TabView: null,
  4142. HT_Options: null,
  4143. HT_ShowOnlyTopBuildings: null,
  4144. HT_ShowOnlyAffordableBuildings: null,
  4145. HT_CityBuildings: null,
  4146. HT_Pages: null,
  4147. HT_Tables: null,
  4148. HT_Models: null,
  4149. HT_SelectedResourceType: null,
  4150. BuildingList: null,
  4151. upgradeInProgress: null,
  4152. init: function () {
  4153. /*
  4154. Done:
  4155. - Added cost per gain to the lists
  4156. - Added building coordinates to the lists
  4157. - Only display the top affordable and not affordable building
  4158. - Persistent filter by city, top and affordable per resource type
  4159. - Reload onTabChange for speed optimization
  4160. - Estimated time until upgrade is affordable
  4161. ToDo:
  4162. - let the user decide to sort by colums he like i.e. timefactor or cost/gain and save it in the configuration
  4163. - integrate buttons to transfer resources ?
  4164.  
  4165. */
  4166. try {
  4167. this.HT_SelectedResourceType = -1;
  4168. this.IsTimerEnabled = false;
  4169. this.upgradeInProgress = false;
  4170.  
  4171. this.HT_TabView = new qx.ui.tabview.TabView();
  4172. this.HT_TabView.set({
  4173. contentPadding: 0,
  4174. appearance: "tabview",
  4175. margin: 5,
  4176. barPosition: 'left'
  4177. });
  4178. this.Widget = new qx.ui.tabview.Page("UpgradePriority");
  4179. this.Widget.setPadding(0);
  4180. this.Widget.setMargin(0);
  4181. this.Widget.setBackgroundColor("#BEC8CF");
  4182. this.Widget.setLayout(new qx.ui.layout.VBox(2));
  4183. //this.Widget.add(this.HT_Options);
  4184. this.Widget.add(this.HT_TabView, {
  4185. flex: 1
  4186. });
  4187. this.Window.setPadding(0);
  4188. this.Window.set({
  4189. resizable: true
  4190. });
  4191.  
  4192. this.Window.removeAll();
  4193. this.Window.add(this.Widget);
  4194.  
  4195. this.BuildingList = new Array;
  4196. this.HT_Models = new Array;
  4197. this.HT_Tables = new Array;
  4198. this.HT_Pages = new Array;
  4199.  
  4200. this.createTabPage(ClientLib.Base.EResourceType.Tiberium);
  4201. this.createTable(ClientLib.Base.EResourceType.Tiberium);
  4202. this.HT_Tables[ClientLib.Base.EResourceType.Tiberium].addListener("cellClick", function (e) {
  4203. this.upgradeBuilding(e, ClientLib.Base.EResourceType.Tiberium);
  4204. }, this);
  4205.  
  4206.  
  4207. this.createTabPage(ClientLib.Base.EResourceType.Crystal);
  4208. this.createTable(ClientLib.Base.EResourceType.Crystal);
  4209. this.HT_Tables[ClientLib.Base.EResourceType.Crystal].addListener("cellClick", function (e) {
  4210. this.upgradeBuilding(e, ClientLib.Base.EResourceType.Crystal);
  4211. }, this);
  4212.  
  4213. this.createTabPage(ClientLib.Base.EResourceType.Power);
  4214. this.createTable(ClientLib.Base.EResourceType.Power);
  4215. this.HT_Tables[ClientLib.Base.EResourceType.Power].addListener("cellClick", function (e) {
  4216. this.upgradeBuilding(e, ClientLib.Base.EResourceType.Power);
  4217. }, this);
  4218.  
  4219. this.createTabPage(ClientLib.Base.EResourceType.Gold);
  4220. this.createTable(ClientLib.Base.EResourceType.Gold);
  4221. this.HT_Tables[ClientLib.Base.EResourceType.Gold].addListener("cellClick", function (e) {
  4222. this.upgradeBuilding(e, ClientLib.Base.EResourceType.Gold);
  4223. }, this);
  4224.  
  4225.  
  4226. MT_Cache.updateCityCache();
  4227. this.HT_Options = new Array();
  4228. this.HT_ShowOnlyTopBuildings = new Array();
  4229. this.HT_ShowOnlyAffordableBuildings = new Array();
  4230. this.HT_CityBuildings = new Array();
  4231. for (var mPage in this.HT_Pages) {
  4232. this.createOptions(mPage);
  4233. this.HT_Pages[mPage].add(this.HT_Options[mPage]);
  4234. this.HT_Pages[mPage].add(this.HT_Tables[mPage], {
  4235. flex: 1
  4236. });
  4237. this.HT_TabView.add(this.HT_Pages[mPage]);
  4238. }
  4239.  
  4240. // Zeigen wir Dollars an !
  4241. this.HT_TabView.setSelection([this.HT_TabView.getChildren()[2]]);
  4242. this.HT_SelectedResourceType = ClientLib.Base.EResourceType.Gold;
  4243. } catch (e) {
  4244. console.log("HuffyTools.UpgradePriority.init: ", e);
  4245. }
  4246. },
  4247. createOptions: function (eType) {
  4248. var oBox = new qx.ui.layout.Flow();
  4249. var oOptions = new qx.ui.container.Composite(oBox);
  4250. oOptions.setMargin(5);
  4251. this.HT_ShowOnlyTopBuildings[eType] = new qx.ui.form.CheckBox(Lang.gt("display only top buildings"));
  4252. this.HT_ShowOnlyTopBuildings[eType].setMargin(5);
  4253. this.HT_ShowOnlyTopBuildings[eType].setValue(MaelstromTools.LocalStorage.get("UGL_TOPBUILDINGS_" + eType, true));
  4254. this.HT_ShowOnlyTopBuildings[eType].addListener("execute", this.CBChanged, this);
  4255. oOptions.add(this.HT_ShowOnlyTopBuildings[eType], {
  4256. left: 10,
  4257. top: 10
  4258. });
  4259. this.HT_ShowOnlyAffordableBuildings[eType] = new qx.ui.form.CheckBox(Lang.gt("display only affordable buildings"));
  4260. this.HT_ShowOnlyAffordableBuildings[eType].setMargin(5);
  4261. this.HT_ShowOnlyAffordableBuildings[eType].setValue(MaelstromTools.LocalStorage.get("UGL_AFFORDABLE_" + eType, true));
  4262. this.HT_ShowOnlyAffordableBuildings[eType].addListener("execute", this.CBChanged, this);
  4263. oOptions.add(this.HT_ShowOnlyAffordableBuildings[eType], {
  4264. left: 10,
  4265. top: 10,
  4266. lineBreak: true
  4267. });
  4268. this.HT_CityBuildings[eType] = new Array();
  4269. for (var cname in MT_Cache.Cities) {
  4270. var oCity = MT_Cache.Cities[cname].Object;
  4271. var oCityBuildings = new HuffyTools.CityCheckBox(cname);
  4272. oCityBuildings.HT_CityID = oCity.get_Id();
  4273. oCityBuildings.setMargin(5);
  4274. oCityBuildings.setValue(MaelstromTools.LocalStorage.get("UGL_CITYFILTER_" + eType + "_" + oCity.get_Id(), true));
  4275. oCityBuildings.addListener("execute", this.CBChanged, this);
  4276. oOptions.add(oCityBuildings, {
  4277. left: 10,
  4278. top: 10
  4279. });
  4280. this.HT_CityBuildings[eType][cname] = oCityBuildings;
  4281. }
  4282. this.HT_Options[eType] = oOptions;
  4283. },
  4284. createTable: function (eType) {
  4285. try {
  4286. this.HT_Models[eType] = new qx.ui.table.model.Simple();
  4287. this.HT_Models[eType].setColumns(["ID", Lang.gt("City"), Lang.gt("Type (coord)"), Lang.gt("to Level"), Lang.gt("Gain/h"), Lang.gt("Factor"), Lang.gt("Tiberium"), Lang.gt("Power"), Lang.gt("Tib/gain"), Lang.gt("Pow/gain"), Lang.gt("ETA"), Lang.gt("Upgrade"), "State"]);
  4288. this.HT_Tables[eType] = new qx.ui.table.Table(this.HT_Models[eType]);
  4289. this.HT_Tables[eType].setColumnVisibilityButtonVisible(false);
  4290. this.HT_Tables[eType].setColumnWidth(0, 0);
  4291. this.HT_Tables[eType].setColumnWidth(1, 90);
  4292. this.HT_Tables[eType].setColumnWidth(2, 120);
  4293. this.HT_Tables[eType].setColumnWidth(3, 55);
  4294. this.HT_Tables[eType].setColumnWidth(4, 70);
  4295. this.HT_Tables[eType].setColumnWidth(5, 60);
  4296. this.HT_Tables[eType].setColumnWidth(6, 70);
  4297. this.HT_Tables[eType].setColumnWidth(7, 70);
  4298. this.HT_Tables[eType].setColumnWidth(8, 70);
  4299. this.HT_Tables[eType].setColumnWidth(9, 70);
  4300. this.HT_Tables[eType].setColumnWidth(10, 70);
  4301. this.HT_Tables[eType].setColumnWidth(11, 40);
  4302. this.HT_Tables[eType].setColumnWidth(12, 0);
  4303. var tcm = this.HT_Tables[eType].getTableColumnModel();
  4304. tcm.setColumnVisible(0, false);
  4305. tcm.setColumnVisible(12, false);
  4306. tcm.setDataCellRenderer(4, new qx.ui.table.cellrenderer.Number().set({
  4307. numberFormat: new qx.util.format.NumberFormat().set({
  4308. maximumFractionDigits: 2,
  4309. minimumFractionDigits: 2
  4310. })
  4311. }));
  4312. tcm.setDataCellRenderer(5, new qx.ui.table.cellrenderer.Number().set({
  4313. numberFormat: new qx.util.format.NumberFormat().set({
  4314. maximumFractionDigits: 5,
  4315. minimumFractionDigits: 5
  4316. })
  4317. }));
  4318. tcm.setDataCellRenderer(6, new HuffyTools.ReplaceRender().set({
  4319. ReplaceFunction: this.formatTiberiumAndPower
  4320. }));
  4321. tcm.setDataCellRenderer(7, new HuffyTools.ReplaceRender().set({
  4322. ReplaceFunction: this.formatTiberiumAndPower
  4323. }));
  4324. tcm.setDataCellRenderer(11, new HuffyTools.ImageRender(40, 20));
  4325. } catch (e) {
  4326. console.log("HuffyTools.UpgradePriority.createTable: ", e);
  4327. }
  4328. },
  4329. createTabPage: function (resource_type) {
  4330. try {
  4331. var sName = MaelstromTools.Statics.LootTypeName(resource_type);
  4332. var oRes = new qx.ui.tabview.Page(Lang.gt(sName), MT_Base.images[sName]);
  4333. oRes.setLayout(new qx.ui.layout.VBox(2));
  4334. oRes.setPadding(5);
  4335. var btnTab = oRes.getChildControl("button");
  4336. btnTab.resetWidth();
  4337. btnTab.resetHeight();
  4338. btnTab.set({
  4339. show: "icon",
  4340. margin: 0,
  4341. padding: 0,
  4342. toolTipText: sName
  4343. });
  4344. btnTab.addListener("execute", this.TabChanged, [this, resource_type]);
  4345. this.HT_Pages[resource_type] = oRes;
  4346. return oRes;
  4347. } catch (e) {
  4348. console.log("HuffyTools.UpgradePriority.createTabPage: ", e);
  4349. }
  4350. },
  4351.  
  4352. TabChanged: function (e) {
  4353. try {
  4354. this[0].HT_SelectedResourceType = this[1];
  4355. this[0].UpgradeCompleted(null, null);
  4356. } catch (e) {
  4357. console.log("HuffyTools.UpgradePriority.TabChanged: ", e);
  4358. }
  4359. },
  4360.  
  4361. upgradeBuilding: function (e, eResourceType) {
  4362. if (this.upgradeInProgress == true) {
  4363. console.log("upgradeBuilding:", "upgrade in progress !");
  4364. return;
  4365. }
  4366. try {
  4367. if (e.getColumn() == 11) {
  4368. var buildingID = this.HT_Models[eResourceType].getValue(0, e.getRow());
  4369. var iState = parseInt(this.HT_Models[eResourceType].getValue(12, e.getRow()));
  4370. if (iState != 1) {
  4371. return;
  4372. }
  4373. if (buildingID in this.BuildingList) {
  4374. this.upgradeInProgress = true;
  4375. if (PerforceChangelist >= 382917) { //new
  4376. ClientLib.Net.CommunicationManager.GetInstance().SendCommand("UpgradeBuilding", this.BuildingList[buildingID], phe.cnc.Util.createEventDelegate(ClientLib.Net.CommandResult, this, this.UpgradeCompleted), null, true);
  4377. } else { //old
  4378. ClientLib.Net.CommunicationManager.GetInstance().SendCommand("UpgradeBuilding", this.BuildingList[buildingID], webfrontend.Util.createEventDelegate(ClientLib.Net.CommandResult, this, this.UpgradeCompleted), null, true);
  4379. }
  4380. }
  4381. }
  4382. } catch (e) {
  4383. console.log("HuffyTools.UpgradePriority.upgradeBuilding: ", e);
  4384. }
  4385. },
  4386. UpgradeCompleted: function (context, result) {
  4387. var self = this;
  4388. window.setTimeout(function () {
  4389. self.calc();
  4390. }, 1000);
  4391. this.upgradeInProgress = false;
  4392. },
  4393. CBChanged: function (e) {
  4394. this.UpgradeCompleted(null, null);
  4395. },
  4396. formatTiberiumAndPower: function (oValue) {
  4397. if (PerforceChangelist >= 387751) { //new
  4398. return phe.cnc.gui.util.Numbers.formatNumbersCompact(oValue);
  4399. } else { //old
  4400. return webfrontend.gui.Util.formatNumbersCompact(oValue);
  4401. }
  4402. },
  4403. updateCache: function () {
  4404. try {
  4405. if (!this.HT_TabView) {
  4406. this.init();
  4407. }
  4408. var eType = this.HT_SelectedResourceType;
  4409. var bTop = this.HT_ShowOnlyTopBuildings[eType].getValue();
  4410. MaelstromTools.LocalStorage.set("UGL_TOPBUILDINGS_" + eType, bTop);
  4411. var bAffordable = this.HT_ShowOnlyAffordableBuildings[eType].getValue();
  4412. MaelstromTools.LocalStorage.set("UGL_AFFORDABLE_" + eType, bAffordable);
  4413. var oCityFilter = new Array();
  4414. for (var cname in this.HT_CityBuildings[eType]) {
  4415. var oCityBuildings = this.HT_CityBuildings[eType][cname];
  4416. var bFilterBuilding = oCityBuildings.getValue();
  4417. MaelstromTools.LocalStorage.set("UGL_CITYFILTER_" + eType + "_" + oCityBuildings.HT_CityID, bFilterBuilding);
  4418. oCityFilter[cname] = bFilterBuilding;
  4419. }
  4420. window.HuffyTools.UpgradePriority.getInstance().collectData(bTop, bAffordable, oCityFilter, eType);
  4421. } catch (e) {
  4422. console.log("HuffyTools.UpgradePriority.updateCache: ", e);
  4423. }
  4424. },
  4425. setWidgetLabels: function () {
  4426. try {
  4427. var HuffyCalc = window.HuffyTools.UpgradePriority.getInstance();
  4428. var UpgradeList = HuffyCalc.Cache;
  4429.  
  4430. for (var eResourceType in UpgradeList) {
  4431. //var eResourceType = MaelstromTools.Statics.LootTypeName(eResourceName);
  4432. var rowData = [];
  4433.  
  4434. this.HT_Models[eResourceType].setData([]);
  4435.  
  4436. for (var mCity in UpgradeList[eResourceType]) {
  4437. for (var mBuilding in UpgradeList[eResourceType][mCity]) {
  4438. var UpItem = UpgradeList[eResourceType][mCity][mBuilding];
  4439. if (typeof (UpItem.Type) == "undefined") {
  4440. continue;
  4441. }
  4442. if (!(mBuilding in this.BuildingList)) {
  4443. this.BuildingList[UpItem.ID] = UpItem.Building;
  4444. }
  4445. var iTiberiumCosts = 0;
  4446. if (ClientLib.Base.EResourceType.Tiberium in UpItem.Costs) {
  4447. iTiberiumCosts = UpItem.Costs[ClientLib.Base.EResourceType.Tiberium];
  4448. }
  4449. var iTiberiumPerGain = 0;
  4450. if (ClientLib.Base.EResourceType.Tiberium in UpItem.Costs) {
  4451. iTiberiumPerGain = UpItem.Costs[ClientLib.Base.EResourceType.Tiberium] / UpItem.GainPerHour;
  4452. }
  4453. var iPowerCosts = 0;
  4454. if (ClientLib.Base.EResourceType.Power in UpItem.Costs) {
  4455. iPowerCosts = UpItem.Costs[ClientLib.Base.EResourceType.Power];
  4456. }
  4457. var iPowerPerGain = 0;
  4458. if (ClientLib.Base.EResourceType.Power in UpItem.Costs) {
  4459. iPowerPerGain = UpItem.Costs[ClientLib.Base.EResourceType.Power] / UpItem.GainPerHour;
  4460. }
  4461. var img = MT_Base.images["UpgradeBuilding"];
  4462. if (UpItem.Affordable == false) {
  4463. img = "";
  4464. }
  4465. var sType = UpItem.Type;
  4466. sType = sType + "(" + UpItem.PosX + ":" + UpItem.PosY + ")";
  4467. var iETA = 0;
  4468. if (UpItem.TimeTillUpgradable[ClientLib.Base.EResourceType.Tiberium] > 0) {
  4469. iETA = UpItem.TimeTillUpgradable[ClientLib.Base.EResourceType.Tiberium];
  4470. }
  4471. if (UpItem.TimeTillUpgradable[ClientLib.Base.EResourceType.Power] > iETA) {
  4472. iETA = UpItem.TimeTillUpgradable[ClientLib.Base.EResourceType.Power];
  4473. }
  4474. var sETA = "";
  4475. if (iETA > 0) {
  4476. sETA = ClientLib.Vis.VisMain.FormatTimespan(iETA);
  4477. }
  4478. var iState = 0;
  4479. if (UpItem.Affordable == true) {
  4480. iState = 1;
  4481. } else if (UpItem.AffordableByTransfer == true) {
  4482. iState = 2;
  4483. } else {
  4484. iState = 3;
  4485. }
  4486. rowData.push([UpItem.ID, mCity, sType, UpItem.Level, UpItem.GainPerHour, UpItem.Ticks, iTiberiumCosts, iPowerCosts, iTiberiumPerGain, iPowerPerGain, sETA, img, iState]);
  4487. }
  4488. }
  4489. this.HT_Models[eResourceType].setData(rowData);
  4490. }
  4491. } catch (e) {
  4492. console.log("HuffyTools.UpgradePriority.setWidgetLabels: ", e);
  4493. }
  4494. }
  4495. }
  4496. });
  4497.  
  4498. // define HuffyTools.UpgradePriority
  4499. qx.Class.define("HuffyTools.UpgradePriority", {
  4500. type: "singleton",
  4501. extend: qx.core.Object,
  4502. members: {
  4503. list_units: null,
  4504. list_buildings: null,
  4505.  
  4506. comparePrio: function (elem1, elem2) {
  4507. if (elem1.Ticks < elem2.Ticks) return -1;
  4508. if (elem1.Ticks > elem2.Ticks) return 1;
  4509. return 0;
  4510. },
  4511. getPrioList: function (city, arTechtypes, eModPackageSize, eModProduction, bOnlyTopBuildings, bOnlyAffordableBuildings) {
  4512. try {
  4513. var RSI = window.MaelstromTools.ResourceOverview.getInstance();
  4514. RSI.updateCache();
  4515. var TotalTiberium = 0;
  4516.  
  4517. for (var cityName in this.Cache) {
  4518. var cityCache = this.Cache[cityName];
  4519. var i = cityCache[MaelstromTools.Statics.Tiberium];
  4520. if (typeof (i) !== 'undefined') {
  4521. TotalTiberium += i;
  4522. //but never goes here during test.... // to optimize - to do
  4523. }
  4524. }
  4525. var resAll = new Array();
  4526. var prod = MaelstromTools.Production.getInstance().updateCache(city.get_Name());
  4527. //var buildings = MaelstromTools.Wrapper.GetBuildings(city.get_CityBuildingsData());
  4528. var buildings = city.get_Buildings().d;
  4529.  
  4530. // 376877 & old fixes
  4531. var objbuildings = [];
  4532. if (PerforceChangelist >= 376877) { //new
  4533. for (var o in buildings) objbuildings.push(buildings[o]);
  4534. } else { //old
  4535. for (var i = 0; i < buildings.length; i++) objbuildings.push(buildings[i]);
  4536. }
  4537.  
  4538.  
  4539. for (var i = 0; i < objbuildings.length; i++) {
  4540. var city_building = objbuildings[i];
  4541.  
  4542. // TODO: check for destroyed building
  4543.  
  4544. var iTechType = city_building.get_TechName();
  4545. var bSkip = true;
  4546. for (var iTypeKey in arTechtypes) {
  4547. if (arTechtypes[iTypeKey] == iTechType) {
  4548. bSkip = false;
  4549. break;
  4550. }
  4551. }
  4552. if (bSkip == true) {
  4553. continue;
  4554. }
  4555. var city_buildingdetailview = city.GetBuildingDetailViewInfo(city_building);
  4556. if (city_buildingdetailview == null) {
  4557. continue;
  4558. }
  4559. var bindex = city_building.get_Id();
  4560. var resbuilding = new Array();
  4561. resbuilding["ID"] = bindex;
  4562. resbuilding["Type"] = this.TechTypeName(parseInt(iTechType, 10));
  4563. resbuilding["PosX"] = city_building.get_CoordX();
  4564. resbuilding["PosY"] = city_building.get_CoordY();
  4565.  
  4566. resbuilding["Building"] = {
  4567. cityid: city.get_Id(),
  4568. posX: resbuilding["PosX"],
  4569. posY: resbuilding["PosY"],
  4570. isPaid: true
  4571. };
  4572.  
  4573. resbuilding["GainPerHour"] = 0;
  4574. resbuilding["Level"] = city_building.get_CurrentLevel() + 1;
  4575. for (var ModifierType in city_buildingdetailview.OwnProdModifiers.d) {
  4576. switch (parseInt(ModifierType, 10)) {
  4577. case eModPackageSize:
  4578. {
  4579. var ModOj = city_buildingdetailview.OwnProdModifiers.d[city_building.get_MainModifierTypeId()];
  4580. var Mod = (ModOj.TotalValue + ModOj.NewLvlDelta) / ClientLib.Data.MainData.GetInstance().get_Time().get_StepsPerHour();
  4581. resbuilding["GainPerHour"] += (city_buildingdetailview.OwnProdModifiers.d[ModifierType].NewLvlDelta / Mod);
  4582. break;
  4583. }
  4584. case eModProduction:
  4585. {
  4586. resbuilding["GainPerHour"] += city_buildingdetailview.OwnProdModifiers.d[ModifierType].NewLvlDelta;
  4587. break;
  4588. }
  4589. }
  4590. }
  4591. // Nutzen ins Verhältnis zu den Kosten setzten
  4592. var TechLevelData = ClientLib.Base.Util.GetTechLevelResourceRequirements_Obj(city_building.get_CurrentLevel() + 1, city_building.get_TechGameData_Obj());
  4593. var RatioPerCostType = new Object();
  4594. var sRatio = "";
  4595. var sCosts = "";
  4596. var lTicks = 0;
  4597. var bHasPower = true;
  4598. var bHasTiberium = true;
  4599. var bAffordableByTransfer = true;
  4600. var oCosts = new Array();
  4601. var oTimes = new Array();
  4602. for (var costtype in TechLevelData) {
  4603. if (typeof (TechLevelData[costtype]) == "function") {
  4604. continue;
  4605. }
  4606. if (TechLevelData[costtype].Type == "0") {
  4607. continue;
  4608. }
  4609.  
  4610. oCosts[TechLevelData[costtype].Type] = TechLevelData[costtype].Count;
  4611. if (parseInt(TechLevelData[costtype].Count) <= 0) {
  4612. continue;
  4613. }
  4614. RatioPerCostType[costtype] = TechLevelData[costtype].Count / resbuilding["GainPerHour"];
  4615. if (sCosts.length > 0) {
  4616. sCosts = sCosts + ", ";
  4617. }
  4618. sCosts = sCosts + MaelstromTools.Wrapper.FormatNumbersCompact(TechLevelData[costtype].Count) + " " + MaelstromTools.Statics.LootTypeName(TechLevelData[costtype].Type);
  4619. if (sRatio.length > 0) {
  4620. sRatio = sRatio + ", ";
  4621. }
  4622. // Upgrade affordable ?
  4623. if (city.GetResourceCount(TechLevelData[costtype].Type) < TechLevelData[costtype].Count) {
  4624. switch (TechLevelData[costtype].Type) {
  4625. case ClientLib.Base.EResourceType.Tiberium:
  4626. {
  4627. bHasTiberium = false;
  4628. if (TotalTiberium < TechLevelData[costtype].Count) {
  4629. bAffordableByTransfer = false;
  4630. }
  4631. }
  4632. break;
  4633. case ClientLib.Base.EResourceType.Power:
  4634. {
  4635. bHasPower = false;
  4636. }
  4637. break;
  4638. }
  4639. }
  4640. sRatio = sRatio + MaelstromTools.Wrapper.FormatNumbersCompact(RatioPerCostType[costtype]);
  4641.  
  4642. var techlevelData = MaelstromTools.Statics.LootTypeName(TechLevelData[costtype].Type);
  4643.  
  4644. var dCityProduction = prod[techlevelData].Delta + prod[techlevelData].ExtraBonusDelta + prod[techlevelData].POI;
  4645. if (dCityProduction > 0) {
  4646. if (lTicks < (3600 * RatioPerCostType[costtype] / dCityProduction)) {
  4647. lTicks = (3600 * RatioPerCostType[costtype] / dCityProduction);
  4648. }
  4649. }
  4650. oTimes[TechLevelData[costtype].Type] = 0;
  4651. if (oCosts[TechLevelData[costtype].Type] > city.GetResourceCount(TechLevelData[costtype].Type)) {
  4652. oTimes[TechLevelData[costtype].Type] = (3600 * (oCosts[TechLevelData[costtype].Type] - city.GetResourceCount(TechLevelData[costtype].Type))) / dCityProduction;
  4653. }
  4654. }
  4655. resbuilding["Ticks"] = lTicks;
  4656. resbuilding["Time"] = ClientLib.Vis.VisMain.FormatTimespan(lTicks);
  4657. resbuilding["Costtext"] = sCosts;
  4658. resbuilding["Costs"] = oCosts;
  4659. resbuilding["TimeTillUpgradable"] = oTimes;
  4660. resbuilding["Ratio"] = sRatio;
  4661. resbuilding["Affordable"] = bHasTiberium && bHasPower;
  4662. resbuilding["AffordableByTransfer"] = bHasPower && bAffordableByTransfer;
  4663. if (resbuilding["GainPerHour"] > 0 && (bOnlyAffordableBuildings == false || resbuilding["Affordable"] == true)) {
  4664. resAll[bindex] = resbuilding;
  4665. }
  4666. }
  4667.  
  4668.  
  4669. resAll = resAll.sort(this.comparePrio);
  4670. if (!bOnlyTopBuildings) {
  4671. return resAll;
  4672. }
  4673. var res2 = new Array();
  4674. if (MaelstromTools.Util.ArraySize(resAll) > 0) {
  4675. var iTopNotAffordable = -1;
  4676. var iTopAffordable = -1;
  4677. var iNextNotAffordable = -1;
  4678. var iLastIndex = -1;
  4679. for (var iNewIndex in resAll) {
  4680. if (resAll[iNewIndex].Affordable == true) {
  4681. if (iTopAffordable == -1) {
  4682. iTopAffordable = iNewIndex;
  4683. iNextNotAffordable = iLastIndex;
  4684. }
  4685. } else {
  4686. if (iTopNotAffordable == -1) {
  4687. iTopNotAffordable = iNewIndex;
  4688. }
  4689. }
  4690. iLastIndex = iNewIndex;
  4691. }
  4692. if (iTopAffordable == -1) {
  4693. iNextNotAffordable = iLastIndex;
  4694. }
  4695. var iIndex = 0;
  4696. if (iTopNotAffordable != -1) {
  4697. res2[iIndex++] = resAll[iTopNotAffordable];
  4698. }
  4699. if (iNextNotAffordable != -1) {
  4700. res2[iIndex++] = resAll[iNextNotAffordable];
  4701. }
  4702. if (iTopAffordable != -1) {
  4703. res2[iIndex++] = resAll[iTopAffordable];
  4704. }
  4705. }
  4706. res2 = res2.sort(this.comparePrio);
  4707. return res2;
  4708. } catch (e) {
  4709. console.log("HuffyTools.getPrioList: ", e);
  4710. }
  4711. },
  4712. TechTypeName: function (iTechType) {
  4713. switch (iTechType) {
  4714. case ClientLib.Base.ETechName.PowerPlant:
  4715. {
  4716. return Lang.gt("Powerplant");
  4717. break;
  4718. }
  4719. case ClientLib.Base.ETechName.Refinery:
  4720. {
  4721. return Lang.gt("Refinery");
  4722. break;
  4723. }
  4724. case ClientLib.Base.ETechName.Harvester_Crystal:
  4725. {
  4726. return Lang.gt("Harvester");
  4727. break;
  4728. }
  4729. case ClientLib.Base.ETechName.Harvester:
  4730. {
  4731. return Lang.gt("Harvester");
  4732. break;
  4733. }
  4734. case ClientLib.Base.ETechName.Silo:
  4735. {
  4736. return Lang.gt("Silo");
  4737. break;
  4738. }
  4739. case ClientLib.Base.ETechName.Accumulator:
  4740. {
  4741. return Lang.gt("Accumulator");
  4742. break;
  4743. }
  4744. }
  4745. return "?";
  4746. },
  4747. collectData: function (bOnlyTopBuildings, bOnlyAffordableBuildings, oCityFilter, eSelectedResourceType) {
  4748. try {
  4749. MT_Cache.updateCityCache();
  4750. this.Cache = new Object();
  4751. if (eSelectedResourceType == ClientLib.Base.EResourceType.Tiberium) {
  4752. this.Cache[ClientLib.Base.EResourceType.Tiberium] = new Object();
  4753. }
  4754. if (eSelectedResourceType == ClientLib.Base.EResourceType.Crystal) {
  4755. this.Cache[ClientLib.Base.EResourceType.Crystal] = new Object();
  4756. }
  4757. if (eSelectedResourceType == ClientLib.Base.EResourceType.Power) {
  4758. this.Cache[ClientLib.Base.EResourceType.Power] = new Object();
  4759. }
  4760. if (eSelectedResourceType == ClientLib.Base.EResourceType.Gold) {
  4761. this.Cache[ClientLib.Base.EResourceType.Gold] = new Object();
  4762. }
  4763. for (var cname in MT_Cache.Cities) {
  4764. var city = MT_Cache.Cities[cname].Object;
  4765. if (oCityFilter[cname] == false) {
  4766. continue;
  4767. }
  4768. if (eSelectedResourceType == ClientLib.Base.EResourceType.Tiberium) {
  4769. this.Cache[ClientLib.Base.EResourceType.Tiberium][cname] = this.getPrioList(city, [ClientLib.Base.ETechName.Harvester, ClientLib.Base.ETechName.Silo], ClientLib.Base.EModifierType.TiberiumPackageSize, ClientLib.Base.EModifierType.TiberiumProduction, bOnlyTopBuildings, bOnlyAffordableBuildings);
  4770. }
  4771. if (eSelectedResourceType == ClientLib.Base.EResourceType.Crystal) {
  4772. this.Cache[ClientLib.Base.EResourceType.Crystal][cname] = this.getPrioList(city, [ClientLib.Base.ETechName.Harvester, ClientLib.Base.ETechName.Silo], ClientLib.Base.EModifierType.CrystalPackageSize, ClientLib.Base.EModifierType.CrystalProduction, bOnlyTopBuildings, bOnlyAffordableBuildings);
  4773. }
  4774. if (eSelectedResourceType == ClientLib.Base.EResourceType.Power) {
  4775. this.Cache[ClientLib.Base.EResourceType.Power][cname] = this.getPrioList(city, [ClientLib.Base.ETechName.PowerPlant, ClientLib.Base.ETechName.Accumulator], ClientLib.Base.EModifierType.PowerPackageSize, ClientLib.Base.EModifierType.PowerProduction, bOnlyTopBuildings, bOnlyAffordableBuildings);
  4776. }
  4777. if (eSelectedResourceType == ClientLib.Base.EResourceType.Gold) {
  4778. this.Cache[ClientLib.Base.EResourceType.Gold][cname] = this.getPrioList(city, [ClientLib.Base.ETechName.Refinery, ClientLib.Base.ETechName.PowerPlant], ClientLib.Base.EModifierType.CreditsPackageSize, ClientLib.Base.EModifierType.CreditsProduction, bOnlyTopBuildings, bOnlyAffordableBuildings);
  4779. }
  4780. }
  4781. } catch (e) {
  4782. console.log("HuffyTools.UpgradePriority.collectData: ", e);
  4783. }
  4784. }
  4785. }
  4786. });
  4787.  
  4788. var __MTCity_initialized = false; //k undeclared
  4789.  
  4790. var Lang = window.MaelstromTools.Language.getInstance();
  4791. var MT_Cache = window.MaelstromTools.Cache.getInstance();
  4792. var MT_Base = window.MaelstromTools.Base.getInstance();
  4793. var MT_Preferences = window.MaelstromTools.Preferences.getInstance();
  4794. MT_Preferences.readOptions();
  4795.  
  4796. if (!webfrontend.gui.region.RegionCityMenu.prototype.__MTCity_showMenu) {
  4797. webfrontend.gui.region.RegionCityMenu.prototype.__MTCity_showMenu = webfrontend.gui.region.RegionCityMenu.prototype.showMenu;
  4798. }
  4799. webfrontend.gui.region.RegionCityMenu.prototype.showMenu = function (selectedVisObject) {
  4800.  
  4801. MT_Cache.SelectedBaseForMenu = selectedVisObject;
  4802. var baseStatusOverview = window.MaelstromTools.BaseStatus.getInstance();
  4803.  
  4804. if (__MTCity_initialized == false) {
  4805. //console.log(selectedBase.get_Name());
  4806. __MTCity_initialized = true;
  4807. baseStatusOverview.CityMenuButtons = new Array();
  4808.  
  4809. for (var k in this) {
  4810. try {
  4811. if (this.hasOwnProperty(k)) {
  4812. if (this[k] && this[k].basename == "Composite") {
  4813. var button = new qx.ui.form.Button(Lang.gt("Calibrate support"));
  4814. button.addListener("execute", function (e) {
  4815. MaelstromTools.Util.calibrateWholeSupportOnSelectedBase();
  4816. }, this);
  4817.  
  4818. this[k].add(button);
  4819. baseStatusOverview.CityMenuButtons.push(button);
  4820. }
  4821. }
  4822. } catch (e) {
  4823. console.log("webfrontend.gui.region.RegionCityMenu.prototype.showMenu: ", e);
  4824. }
  4825. }
  4826. }
  4827.  
  4828. var isAllowed = MaelstromTools.Util.checkIfSupportIsAllowed(MT_Cache.SelectedBaseForMenu);
  4829.  
  4830. for (var x = 0; x < baseStatusOverview.CityMenuButtons.length; ++x) {
  4831. baseStatusOverview.CityMenuButtons[x].setVisibility(isAllowed ? 'visible' : 'excluded');
  4832. }
  4833. this.__MTCity_showMenu(selectedVisObject);
  4834. };
  4835.  
  4836. if (MT_Preferences.Settings.showLoot) {
  4837. // Wrap onCitiesChange method
  4838. if (!webfrontend.gui.region.RegionNPCCampStatusInfo.prototype.__MTCity_NPCCamp) {
  4839. webfrontend.gui.region.RegionNPCCampStatusInfo.prototype.__MTCity_NPCCamp = webfrontend.gui.region.RegionNPCCampStatusInfo.prototype.onCitiesChange;
  4840. }
  4841. webfrontend.gui.region.RegionNPCCampStatusInfo.prototype.onCitiesChange = function () {
  4842. MT_Base.updateLoot(1, ClientLib.Vis.VisMain.GetInstance().get_SelectedObject(), webfrontend.gui.region.RegionNPCCampStatusInfo.getInstance());
  4843. return this.__MTCity_NPCCamp();
  4844. };
  4845.  
  4846. if (!webfrontend.gui.region.RegionNPCBaseStatusInfo.prototype.__MTCity_NPCBase) {
  4847. webfrontend.gui.region.RegionNPCBaseStatusInfo.prototype.__MTCity_NPCBase = webfrontend.gui.region.RegionNPCBaseStatusInfo.prototype.onCitiesChange;
  4848. }
  4849. webfrontend.gui.region.RegionNPCBaseStatusInfo.prototype.onCitiesChange = function () {
  4850. MT_Base.updateLoot(2, ClientLib.Vis.VisMain.GetInstance().get_SelectedObject(), webfrontend.gui.region.RegionNPCBaseStatusInfo.getInstance());
  4851. //MT_Base.updateLoot(2, ClientLib.Data.MainData.GetInstance().get_Cities().get_CurrentCity(), webfrontend.gui.region.RegionNPCBaseStatusInfo.getInstance());
  4852. return this.__MTCity_NPCBase();
  4853. };
  4854.  
  4855. if (!webfrontend.gui.region.RegionCityStatusInfoEnemy.prototype.__MTCity_City) {
  4856. webfrontend.gui.region.RegionCityStatusInfoEnemy.prototype.__MTCity_City = webfrontend.gui.region.RegionCityStatusInfoEnemy.prototype.onCitiesChange;
  4857. }
  4858. webfrontend.gui.region.RegionCityStatusInfoEnemy.prototype.onCitiesChange = function () {
  4859. MT_Base.updateLoot(3, ClientLib.Vis.VisMain.GetInstance().get_SelectedObject(), webfrontend.gui.region.RegionCityStatusInfoEnemy.getInstance());
  4860. //MT_Base.updateLoot(3, ClientLib.Data.MainData.GetInstance().get_Cities().get_CurrentCity(), webfrontend.gui.region.RegionCityStatusInfoEnemy.getInstance());
  4861. return this.__MTCity_City();
  4862. };
  4863. }
  4864.  
  4865. }
  4866. } catch (e) {
  4867. console.log("createMaelstromTools: ", e);
  4868. }
  4869.  
  4870. function MaelstromTools_checkIfLoaded() {
  4871. try {
  4872. if (typeof qx != 'undefined' && qx.core.Init.getApplication() && qx.core.Init.getApplication().getUIItem(ClientLib.Data.Missions.PATH.BAR_NAVIGATION) && qx.core.Init.getApplication().getUIItem(ClientLib.Data.Missions.PATH.BAR_NAVIGATION).isVisible()) {
  4873. createMaelstromTools();
  4874. window.MaelstromTools.Base.getInstance().initialize();
  4875. } else {
  4876. window.setTimeout(MaelstromTools_checkIfLoaded, 1000);
  4877. }
  4878. } catch (e) {
  4879. console.log("MaelstromTools_checkIfLoaded: ", e);
  4880. }
  4881. }
  4882.  
  4883. if (/commandandconquer\.com/i.test(document.domain)) {
  4884. window.setTimeout(MaelstromTools_checkIfLoaded, 1000);
  4885. }
  4886. };
  4887.  
  4888. try {
  4889. var MaelstromScript = document.createElement("script");
  4890. MaelstromScript.innerHTML = "(" + MaelstromTools_main.toString() + ")();";
  4891. MaelstromScript.type = "text/javascript";
  4892. if (/commandandconquer\.com/i.test(document.domain)) {
  4893. document.getElementsByTagName("head")[0].appendChild(MaelstromScript);
  4894. }
  4895. } catch (e) {
  4896. console.log("MaelstromTools: init error: ", e);
  4897. }
  4898. })();
  4899.  
  4900.  
  4901. /***********************************************************************************
  4902. WarChiefs - Tiberium Alliances Upgrade Base/Defense/Army
  4903. ***********************************************************************************/
  4904. // ==UserScript==
  4905. // @name WarChiefs - Tiberium Alliances Upgrade Base/Defense/Army
  4906. // @description Upgrade your Base,Defense Army to a specific Level.
  4907. // @author Eistee
  4908. // @version 13.10.30
  4909. // @namespace http*://*.alliances.commandandconquer.com/*
  4910. // @include http*://*.alliances.commandandconquer.com/*
  4911. // @require http://usocheckup.redirectme.net/167564.js
  4912. // @icon http://s3.amazonaws.com/uso_ss/icon/167564/large.png
  4913. // @updateURL https://userscripts.org/scripts/source/167564.meta.js
  4914. // @downloadURL https://userscripts.org/scripts/source/167564.user.js
  4915. // @grant GM_getValue
  4916. // @grant GM_log
  4917. // @grant GM_openInTab
  4918. // @grant GM_registerMenuCommand
  4919. // @grant GM_setValue
  4920. // @grant GM_xmlhttpRequest
  4921. // ==/UserScript==
  4922. /**
  4923. * License: CC-BY-NC-SA 3.0
  4924. *
  4925. * thx to TheStriker for his API knowledge.
  4926. *
  4927. */
  4928. (function () {
  4929. var injectFunction = function () {
  4930. function createClasses() {
  4931. qx.Class.define("Upgrade", {
  4932. type: "singleton",
  4933. extend: qx.core.Object,
  4934. construct: function () {
  4935. try {
  4936. var qxApp = qx.core.Init.getApplication();
  4937.  
  4938. var stats = document.createElement('img')
  4939. stats.src = "http://goo.gl/BuvwKs"; // http://goo.gl/#analytics/goo.gl/BuvwKs/all_time
  4940.  
  4941. var btnUpgrade = new qx.ui.form.Button(qxApp.tr("tnf:toggle upgrade mode"), "FactionUI/icons/icon_building_detail_upgrade.png").set({
  4942. toolTipText: qxApp.tr("tnf:toggle upgrade mode"),
  4943. alignY: "middle",
  4944. show: "icon",
  4945. width : 60,
  4946. allowGrowX : false,
  4947. allowGrowY : false,
  4948. appearance : "button"
  4949. });
  4950. btnUpgrade.addListener("click", this.toggleWindow, this);
  4951.  
  4952. var btnTrade = qx.core.Init.getApplication().getPlayArea().getHUD().getUIItem(ClientLib.Data.Missions.PATH.WDG_TRADE);
  4953. btnTrade.getLayoutParent().addAfter(btnUpgrade, btnTrade);
  4954. } catch (e) {
  4955. console.log("Error setting up Upgrade Constructor: ");
  4956. console.log(e.toString());
  4957. }
  4958. },
  4959. destruct: function () {},
  4960. members: {
  4961. toggleWindow: function () {
  4962. if (Upgrade.Window.getInstance().isVisible()) Upgrade.Window.getInstance().close();
  4963. else Upgrade.Window.getInstance().open();
  4964. }
  4965. }
  4966. });
  4967. qx.Class.define("Upgrade.Window", {
  4968. type: "singleton",
  4969. extend: qx.ui.window.Window,
  4970. construct: function () {
  4971. try {
  4972. this.base(arguments);
  4973. this.set({
  4974. layout: new qx.ui.layout.VBox().set({ spacing: 0 }),
  4975. contentPadding: 5,
  4976. contentPaddingTop: 0,
  4977. allowMaximize: false,
  4978. showMaximize: false,
  4979. allowMinimize: false,
  4980. showMinimize: false,
  4981. resizable: false
  4982. });
  4983. this.moveTo(124, 31);
  4984. this.getChildControl("icon").set({ width : 18, height : 18, scale : true, alignY : "middle" });
  4985.  
  4986. this.add(new Upgrade.Current());
  4987. this.add(new Upgrade.All());
  4988. this.add(new Upgrade.Repairtime());
  4989.  
  4990. this.addListener("appear", this.onOpen, this);
  4991. this.addListener("close", this.onClose, this);
  4992. } catch (e) {
  4993. console.log("Error setting up Upgrade.Window Constructor: ");
  4994. console.log(e.toString());
  4995. }
  4996. },
  4997. destruct: function () {},
  4998. members: {
  4999. onOpen: function () {
  5000. phe.cnc.Util.attachNetEvent(ClientLib.Vis.VisMain.GetInstance(), "ViewModeChange", ClientLib.Vis.ViewModeChange, this, this.onViewModeChanged);
  5001. this.onViewModeChanged(null, ClientLib.Vis.VisMain.GetInstance().get_Mode());
  5002. },
  5003. onClose: function () {
  5004. phe.cnc.Util.detachNetEvent(ClientLib.Vis.VisMain.GetInstance(), "ViewModeChange", ClientLib.Vis.ViewModeChange, this, this.onViewModeChanged);
  5005. },
  5006. onViewModeChanged: function (oldMode, newMode) {
  5007. if (oldMode !== newMode) {
  5008. var qxApp = qx.core.Init.getApplication();
  5009. switch (newMode) {
  5010. case ClientLib.Vis.Mode.City:
  5011. this.setCaption(qxApp.tr("tnf:toggle upgrade mode") + ": " + qxApp.tr("tnf:base"));
  5012. this.setIcon("FactionUI/icons/icon_arsnl_base_buildings.png");
  5013. break;
  5014. case ClientLib.Vis.Mode.DefenseSetup:
  5015. this.setCaption(qxApp.tr("tnf:toggle upgrade mode") + ": " + qxApp.tr("tnf:defense"));
  5016. this.setIcon("FactionUI/icons/icon_def_army_points.png");
  5017. break;
  5018. case ClientLib.Vis.Mode.ArmySetup:
  5019. this.setCaption(qxApp.tr("tnf:toggle upgrade mode") + ": " + qxApp.tr("tnf:offense"));
  5020. this.setIcon("FactionUI/icons/icon_army_points.png");
  5021. break;
  5022. default:
  5023. this.close();
  5024. break;
  5025. }
  5026. }
  5027. },
  5028. }
  5029. });
  5030. qx.Class.define("Upgrade.All", {
  5031. extend: qx.ui.container.Composite,
  5032. construct: function () {
  5033. try {
  5034. qx.ui.container.Composite.call(this);
  5035. this.set({
  5036. layout : new qx.ui.layout.VBox(5),
  5037. padding: 5,
  5038. decorator: "pane-light-opaque"
  5039. });
  5040. this.add(this.title = new qx.ui.basic.Label("").set({ alignX: "center", font: "font_size_14_bold" }));
  5041.  
  5042. var level = new qx.ui.container.Composite(new qx.ui.layout.HBox(5))
  5043. level.add(new qx.ui.basic.Label(this.tr("tnf:level:")).set({ alignY: "middle" }));
  5044. level.add(this.txtLevel = new qx.ui.form.Spinner(1).set({ maximum: 150, minimum: 1 }));
  5045. this.txtLevel.addListener("changeValue", this.onInput, this);
  5046. level.add(this.btnLevel = new qx.ui.form.Button(this.tr("tnf:toggle upgrade mode"), "FactionUI/icons/icon_building_detail_upgrade.png"));
  5047. this.btnLevel.addListener("execute", this.onUpgrade, this);
  5048. this.add(level);
  5049.  
  5050. var requires = new qx.ui.container.Composite(new qx.ui.layout.HBox(5));
  5051. requires.add(new qx.ui.basic.Label(this.tr("tnf:requires:")));
  5052. var resource = new qx.ui.container.Composite(new qx.ui.layout.VBox(5));
  5053. resource.add(this.resTiberium = new qx.ui.basic.Atom("-", "webfrontend/ui/common/icn_res_tiberium.png"));
  5054. this.resTiberium.setToolTipIcon("webfrontend/ui/common/icn_res_tiberium.png");
  5055. this.resTiberium.getChildControl("icon").set({ width: 18, height: 18, scale: true, alignY: "middle" });
  5056. resource.add(this.resChrystal = new qx.ui.basic.Atom("-", "webfrontend/ui/common/icn_res_chrystal.png"));
  5057. this.resChrystal.setToolTipIcon("webfrontend/ui/common/icn_res_chrystal.png");
  5058. this.resChrystal.getChildControl("icon").set({ width: 18, height: 18, scale: true, alignY: "middle" });
  5059. resource.add(this.resPower = new qx.ui.basic.Atom("-", "webfrontend/ui/common/icn_res_power.png"));
  5060. this.resPower.setToolTipIcon("webfrontend/ui/common/icn_res_power.png");
  5061. this.resPower.getChildControl("icon").set({ width: 18, height: 18, scale: true, alignY: "middle" });
  5062. requires.add(resource);
  5063. this.add(requires);
  5064.  
  5065. this.addListener("appear", this.onAppear, this);
  5066. this.addListener("disappear", this.onDisappear, this);
  5067. } catch (e) {
  5068. console.log("Error setting up Upgrade.All Constructor: ");
  5069. console.log(e.toString());
  5070. }
  5071. },
  5072. destruct: function () {},
  5073. members: {
  5074. title: null,
  5075. txtLevel: null,
  5076. btnLevel: null,
  5077. resTiberium: null,
  5078. resChrystal: null,
  5079. resPower: null,
  5080. onAppear: function () {
  5081. phe.cnc.Util.attachNetEvent(ClientLib.Vis.VisMain.GetInstance(), "ViewModeChange", ClientLib.Vis.ViewModeChange, this, this.onViewModeChanged);
  5082. phe.cnc.Util.attachNetEvent(ClientLib.Data.MainData.GetInstance().get_Cities(), "CurrentOwnChange", ClientLib.Data.CurrentOwnCityChange, this, this.onCurrentCityChange);
  5083. phe.cnc.Util.attachNetEvent(ClientLib.Data.MainData.GetInstance().get_Cities(), "CurrentChange", ClientLib.Data.CurrentCityChange, this, this.onCurrentCityChange);
  5084. phe.cnc.base.Timer.getInstance().addListener("uiTick", this.onTick, this);
  5085. this.onViewModeChanged(null, ClientLib.Vis.VisMain.GetInstance().get_Mode());
  5086. },
  5087. onDisappear: function () {
  5088. phe.cnc.Util.detachNetEvent(ClientLib.Vis.VisMain.GetInstance(), "ViewModeChange", ClientLib.Vis.ViewModeChange, this, this.onViewModeChanged);
  5089. phe.cnc.Util.detachNetEvent(ClientLib.Data.MainData.GetInstance().get_Cities(), "CurrentOwnChange", ClientLib.Data.CurrentOwnCityChange, this, this.onCurrentCityChange);
  5090. phe.cnc.Util.detachNetEvent(ClientLib.Data.MainData.GetInstance().get_Cities(), "CurrentChange", ClientLib.Data.CurrentCityChange, this, this.onCurrentCityChange);
  5091. phe.cnc.base.Timer.getInstance().removeListener("uiTick", this.onTick, this);
  5092. },
  5093. onViewModeChanged: function (oldViewMode, newViewMode) {
  5094. if (oldViewMode !== newViewMode) {
  5095. switch (newViewMode) {
  5096. case ClientLib.Vis.Mode.City:
  5097. this.title.setValue(this.tr("All buildings"));
  5098. this.reset();
  5099. break;
  5100. case ClientLib.Vis.Mode.DefenseSetup:
  5101. this.title.setValue(this.tr("All defense units"));
  5102. this.reset();
  5103. break;
  5104. case ClientLib.Vis.Mode.ArmySetup:
  5105. this.title.setValue(this.tr("All army units"));
  5106. this.reset();
  5107. break;
  5108. }
  5109. }
  5110. },
  5111. onCurrentCityChange: function (oldCurrentCity, newCurrentCity) {
  5112. if (oldCurrentCity !== newCurrentCity) {
  5113. this.reset();
  5114. }
  5115. },
  5116. getResTime: function (need, type) {
  5117. var CurrentOwnCity = ClientLib.Data.MainData.GetInstance().get_Cities().get_CurrentOwnCity();
  5118. var Alliance = ClientLib.Data.MainData.GetInstance().get_Alliance();
  5119. need -= CurrentOwnCity.GetResourceCount(type);
  5120. need = Math.max(0, need);
  5121. var Con = CurrentOwnCity.GetResourceGrowPerHour(type);
  5122. var Bonus = CurrentOwnCity.get_hasCooldown() ? 0 : CurrentOwnCity.GetResourceBonusGrowPerHour(type);
  5123. var POI = CurrentOwnCity.get_IsGhostMode() ? 0 : Alliance.GetPOIBonusFromResourceType(type);
  5124. return (need <= 0 ? 0 : need / (Con + Bonus + POI) * 3600);
  5125. },
  5126. getUpgradeCostsToLevel: function (newLevel) {
  5127. if (newLevel > 0) {
  5128. switch (ClientLib.Vis.VisMain.GetInstance().get_Mode()) {
  5129. case ClientLib.Vis.Mode.City:
  5130. return ClientLib.API.City.GetInstance().GetUpgradeCostsForAllBuildingsToLevel(newLevel);
  5131. case ClientLib.Vis.Mode.DefenseSetup:
  5132. return ClientLib.API.Defense.GetInstance().GetUpgradeCostsForAllUnitsToLevel(newLevel);
  5133. case ClientLib.Vis.Mode.ArmySetup:
  5134. return ClientLib.API.Army.GetInstance().GetUpgradeCostsForAllUnitsToLevel(newLevel);
  5135. }
  5136. }
  5137. return null;
  5138. },
  5139. getLowLevel: function () {
  5140. for (var newLevel = 1, Tib = 0, Cry = 0, Pow = 0; Tib === 0 && Cry === 0 && Pow === 0 && newLevel < 1000; newLevel++) {
  5141. var costs = this.getUpgradeCostsToLevel(newLevel);
  5142. if (costs !== null) {
  5143. for (var i = 0; i < costs.length; i++) {
  5144. var uCosts = costs[i];
  5145. var cType = parseInt(uCosts.Type, 10);
  5146. switch (cType) {
  5147. case ClientLib.Base.EResourceType.Tiberium:
  5148. Tib += uCosts.Count;
  5149. break;
  5150. case ClientLib.Base.EResourceType.Crystal:
  5151. Cry += uCosts.Count;
  5152. break;
  5153. case ClientLib.Base.EResourceType.Power:
  5154. Pow += uCosts.Count;
  5155. break;
  5156. }
  5157. }
  5158. }
  5159. }
  5160. return (newLevel === 1000?0:(newLevel - 1));
  5161. },
  5162. reset: function () {
  5163. var LowLevel = this.getLowLevel();
  5164. if (LowLevel > 0) {
  5165. this.txtLevel.setMinimum(LowLevel);
  5166. this.txtLevel.setMaximum(LowLevel + 50);
  5167. this.txtLevel.setValue(LowLevel);
  5168. this.txtLevel.setEnabled(true);
  5169. this.btnLevel.setEnabled(true);
  5170. } else {
  5171. this.txtLevel.setMinimum(0);
  5172. this.txtLevel.setMaximum(0);
  5173. this.txtLevel.resetValue();
  5174. this.txtLevel.setEnabled(false);
  5175. this.btnLevel.setEnabled(false);
  5176. }
  5177. this.onInput();
  5178. },
  5179. onTick: function () {
  5180. this.onInput();
  5181. },
  5182. onInput: function () {
  5183. var newLevel = parseInt(this.txtLevel.getValue(), 10);
  5184. var costs = this.getUpgradeCostsToLevel(newLevel);
  5185. if (newLevel > 0 && costs !== null) {
  5186. for (var i = 0, Tib = 0, Cry = 0, Pow = 0, TibTime = 0, CryTime = 0, PowTime = 0; i < costs.length; i++) {
  5187. var uCosts = costs[i];
  5188. switch (parseInt(uCosts.Type, 10)) {
  5189. case ClientLib.Base.EResourceType.Tiberium:
  5190. Tib += uCosts.Count;
  5191. TibTime += this.getResTime(uCosts.Count, ClientLib.Base.EResourceType.Tiberium);
  5192. break;
  5193. case ClientLib.Base.EResourceType.Crystal:
  5194. Cry += uCosts.Count;
  5195. CryTime += this.getResTime(uCosts.Count, ClientLib.Base.EResourceType.Crystal);
  5196. break;
  5197. case ClientLib.Base.EResourceType.Power:
  5198. Pow += uCosts.Count;
  5199. PowTime += this.getResTime(uCosts.Count, ClientLib.Base.EResourceType.Power);
  5200. break;
  5201. }
  5202. }
  5203. this.resTiberium.setLabel(phe.cnc.gui.util.Numbers.formatNumbersCompact(Tib) + (TibTime > 0 ? " @ " + phe.cnc.Util.getTimespanString(TibTime) : ""));
  5204. this.resTiberium.setToolTipText(phe.cnc.gui.util.Numbers.formatNumbers(Tib));
  5205. if (Tib === 0) this.resTiberium.exclude();
  5206. else this.resTiberium.show();
  5207. this.resChrystal.setLabel(phe.cnc.gui.util.Numbers.formatNumbersCompact(Cry) + (CryTime > 0 ? " @ " + phe.cnc.Util.getTimespanString(CryTime) : ""));
  5208. this.resChrystal.setToolTipText(phe.cnc.gui.util.Numbers.formatNumbers(Cry));
  5209. if (Cry === 0) this.resChrystal.exclude();
  5210. else this.resChrystal.show();
  5211. this.resPower.setLabel(phe.cnc.gui.util.Numbers.formatNumbersCompact(Pow) + (PowTime > 0 ? " @ " + phe.cnc.Util.getTimespanString(PowTime) : ""));
  5212. this.resPower.setToolTipText(phe.cnc.gui.util.Numbers.formatNumbers(Pow));
  5213. if (Pow === 0) this.resPower.exclude();
  5214. else this.resPower.show();
  5215. } else {
  5216. this.resTiberium.setLabel("-");
  5217. this.resTiberium.resetToolTipText();
  5218. this.resTiberium.show();
  5219. this.resChrystal.setLabel("-");
  5220. this.resChrystal.resetToolTipText();
  5221. this.resChrystal.show();
  5222. this.resPower.setLabel("-");
  5223. this.resPower.resetToolTipText();
  5224. this.resPower.show();
  5225. }
  5226. },
  5227. onUpgrade: function () {
  5228. var newLevel = parseInt(this.txtLevel.getValue(), 10);
  5229. if (newLevel > 0) {
  5230. switch (ClientLib.Vis.VisMain.GetInstance().get_Mode()) {
  5231. case ClientLib.Vis.Mode.City:
  5232. ClientLib.API.City.GetInstance().UpgradeAllBuildingsToLevel(newLevel);
  5233. this.reset()
  5234. break;
  5235. case ClientLib.Vis.Mode.DefenseSetup:
  5236. ClientLib.API.Defense.GetInstance().UpgradeAllUnitsToLevel(newLevel);
  5237. this.reset()
  5238. break;
  5239. case ClientLib.Vis.Mode.ArmySetup:
  5240. ClientLib.API.Army.GetInstance().UpgradeAllUnitsToLevel(newLevel);
  5241. this.reset()
  5242. break;
  5243. }
  5244. }
  5245. }
  5246. }
  5247. });
  5248. qx.Class.define("Upgrade.Current", {
  5249. extend: qx.ui.container.Composite,
  5250. construct: function () {
  5251. try {
  5252. qx.ui.container.Composite.call(this);
  5253. this.set({
  5254. layout : new qx.ui.layout.VBox(5),
  5255. padding: 5,
  5256. decorator: "pane-light-opaque"
  5257. });
  5258. this.add(this.title = new qx.ui.basic.Label("").set({ alignX: "center", font: "font_size_14_bold" }));
  5259. this.add(this.txtSelected = new qx.ui.basic.Label("").set({ alignX: "center" }));
  5260.  
  5261. var level = new qx.ui.container.Composite(new qx.ui.layout.HBox(5))
  5262. level.add(new qx.ui.basic.Label(this.tr("tnf:level:")).set({ alignY: "middle" }));
  5263. level.add(this.txtLevel = new qx.ui.form.Spinner(1).set({ maximum: 150, minimum: 1 }));
  5264. this.txtLevel.addListener("changeValue", this.onInput, this);
  5265. level.add(this.btnLevel = new qx.ui.form.Button(this.tr("tnf:toggle upgrade mode"), "FactionUI/icons/icon_building_detail_upgrade.png"));
  5266. this.btnLevel.addListener("execute", this.onUpgrade, this);
  5267. this.add(level);
  5268.  
  5269. var requires = new qx.ui.container.Composite(new qx.ui.layout.HBox(5));
  5270. requires.add(new qx.ui.basic.Label(this.tr("tnf:requires:")));
  5271. var resource = new qx.ui.container.Composite(new qx.ui.layout.VBox(5));
  5272. resource.add(this.resTiberium = new qx.ui.basic.Atom("-", "webfrontend/ui/common/icn_res_tiberium.png"));
  5273. this.resTiberium.setToolTipIcon("webfrontend/ui/common/icn_res_tiberium.png");
  5274. this.resTiberium.getChildControl("icon").set({ width: 18, height: 18, scale: true, alignY: "middle" });
  5275. resource.add(this.resChrystal = new qx.ui.basic.Atom("-", "webfrontend/ui/common/icn_res_chrystal.png"));
  5276. this.resChrystal.setToolTipIcon("webfrontend/ui/common/icn_res_chrystal.png");
  5277. this.resChrystal.getChildControl("icon").set({ width: 18, height: 18, scale: true, alignY: "middle" });
  5278. resource.add(this.resPower = new qx.ui.basic.Atom("-", "webfrontend/ui/common/icn_res_power.png"));
  5279. this.resPower.setToolTipIcon("webfrontend/ui/common/icn_res_power.png");
  5280. this.resPower.getChildControl("icon").set({ width: 18, height: 18, scale: true, alignY: "middle" });
  5281. requires.add(resource);
  5282. this.add(requires);
  5283.  
  5284. this.addListener("appear", this.onAppear, this);
  5285. this.addListener("disappear", this.onDisappear, this);
  5286. } catch (e) {
  5287. console.log("Error setting up Upgrade.Current Constructor: ");
  5288. console.log(e.toString());
  5289. }
  5290. },
  5291. destruct: function () {},
  5292. members: {
  5293. title: null,
  5294. txtSelected: null,
  5295. txtLevel: null,
  5296. btnLevel: null,
  5297. resTiberium: null,
  5298. resChrystal: null,
  5299. resPower: null,
  5300. Selection: null,
  5301. onAppear: function () {
  5302. phe.cnc.Util.attachNetEvent(ClientLib.Vis.VisMain.GetInstance(), "ViewModeChange", ClientLib.Vis.ViewModeChange, this, this.onViewModeChanged);
  5303. phe.cnc.Util.attachNetEvent(ClientLib.Vis.VisMain.GetInstance(), "SelectionChange", ClientLib.Vis.SelectionChange, this, this.onSelectionChange);
  5304. phe.cnc.Util.attachNetEvent(ClientLib.Data.MainData.GetInstance().get_Cities(), "CurrentOwnChange", ClientLib.Data.CurrentOwnCityChange, this, this.onCurrentCityChange);
  5305. phe.cnc.Util.attachNetEvent(ClientLib.Data.MainData.GetInstance().get_Cities(), "CurrentChange", ClientLib.Data.CurrentCityChange, this, this.onCurrentCityChange);
  5306. phe.cnc.base.Timer.getInstance().addListener("uiTick", this.onTick, this);
  5307. this.onViewModeChanged(null, ClientLib.Vis.VisMain.GetInstance().get_Mode());
  5308. },
  5309. onDisappear: function () {
  5310. phe.cnc.Util.detachNetEvent(ClientLib.Vis.VisMain.GetInstance(), "ViewModeChange", ClientLib.Vis.ViewModeChange, this, this.onViewModeChanged);
  5311. phe.cnc.Util.detachNetEvent(ClientLib.Vis.VisMain.GetInstance(), "SelectionChange", ClientLib.Vis.SelectionChange, this, this.onSelectionChange);
  5312. phe.cnc.Util.detachNetEvent(ClientLib.Data.MainData.GetInstance().get_Cities(), "CurrentOwnChange", ClientLib.Data.CurrentOwnCityChange, this, this.onCurrentCityChange);
  5313. phe.cnc.Util.detachNetEvent(ClientLib.Data.MainData.GetInstance().get_Cities(), "CurrentChange", ClientLib.Data.CurrentCityChange, this, this.onCurrentCityChange);
  5314. phe.cnc.base.Timer.getInstance().removeListener("uiTick", this.onTick, this);
  5315. },
  5316. onViewModeChanged: function (oldViewMode, newViewMode) {
  5317. if (oldViewMode !== newViewMode) {
  5318. switch (newViewMode) {
  5319. case ClientLib.Vis.Mode.City:
  5320. this.title.setValue(this.tr("Selected building"));
  5321. this.reset();
  5322. break;
  5323. case ClientLib.Vis.Mode.DefenseSetup:
  5324. this.title.setValue(this.tr("Selected defense unit"));
  5325. this.reset();
  5326. break;
  5327. case ClientLib.Vis.Mode.ArmySetup:
  5328. this.title.setValue(this.tr("Selected army unit"));
  5329. this.reset();
  5330. break;
  5331. }
  5332. }
  5333. },
  5334. onSelectionChange: function (oldSelection, newSelection) {
  5335. if (newSelection != null) {
  5336. switch (newSelection.get_VisObjectType()) {
  5337. case ClientLib.Vis.VisObject.EObjectType.CityBuildingType:
  5338. this.Selection = newSelection;
  5339. var name = newSelection.get_BuildingName();
  5340. var level = newSelection.get_BuildingLevel();
  5341. this.txtSelected.setValue(name + " (" + level + ")");
  5342. this.txtLevel.setMinimum(level + 1);
  5343. this.txtLevel.setMaximum(level + 51);
  5344. this.txtLevel.setValue(level + 1);
  5345. this.txtLevel.setEnabled(true);
  5346. this.btnLevel.setEnabled(true);
  5347. this.onInput();
  5348. break;
  5349. case ClientLib.Vis.VisObject.EObjectType.DefenseUnitType:
  5350. case ClientLib.Vis.VisObject.EObjectType.ArmyUnitType:
  5351. this.Selection = newSelection;
  5352. var name = newSelection.get_UnitName();
  5353. var level = newSelection.get_UnitLevel();
  5354. this.txtSelected.setValue(name + " (" + level + ")");
  5355. this.txtLevel.setMinimum(level + 1);
  5356. this.txtLevel.setMaximum(level + 51);
  5357. this.txtLevel.setValue(level + 1);
  5358. this.txtLevel.setEnabled(true);
  5359. this.btnLevel.setEnabled(true);
  5360. this.onInput();
  5361. break;
  5362. }
  5363. }
  5364. },
  5365. onCurrentCityChange: function (oldCurrentCity, newCurrentCity) {
  5366. if (oldCurrentCity !== newCurrentCity) {
  5367. this.reset();
  5368. }
  5369. },
  5370. getResTime: function (need, type) {
  5371. var CurrentOwnCity = ClientLib.Data.MainData.GetInstance().get_Cities().get_CurrentOwnCity();
  5372. var Alliance = ClientLib.Data.MainData.GetInstance().get_Alliance();
  5373. need -= CurrentOwnCity.GetResourceCount(type);
  5374. need = Math.max(0, need);
  5375. var Con = CurrentOwnCity.GetResourceGrowPerHour(type);
  5376. var Bonus = CurrentOwnCity.get_hasCooldown() ? 0 : CurrentOwnCity.GetResourceBonusGrowPerHour(type);
  5377. var POI = CurrentOwnCity.get_IsGhostMode() ? 0 : Alliance.GetPOIBonusFromResourceType(type);
  5378. return (need <= 0 ? 0 : need / (Con + Bonus + POI) * 3600);
  5379. },
  5380. getUpgradeCostsToLevel: function (unit, newLevel) {
  5381. var costs = null;
  5382. if (unit !== null && newLevel > 0) {
  5383. switch (unit.get_VisObjectType()) {
  5384. case ClientLib.Vis.VisObject.EObjectType.CityBuildingType:
  5385. if (newLevel > unit.get_BuildingLevel())
  5386. costs = ClientLib.API.City.GetInstance().GetUpgradeCostsForBuildingToLevel(unit.get_BuildingDetails(), newLevel);
  5387. break;
  5388. case ClientLib.Vis.VisObject.EObjectType.DefenseUnitType:
  5389. if (newLevel > unit.get_UnitLevel())
  5390. costs = ClientLib.API.Defense.GetInstance().GetUpgradeCostsForUnitToLevel(unit.get_UnitDetails(), newLevel);
  5391. break;
  5392. case ClientLib.Vis.VisObject.EObjectType.ArmyUnitType:
  5393. if (newLevel > unit.get_UnitLevel())
  5394. costs = ClientLib.API.Army.GetInstance().GetUpgradeCostsForUnitToLevel(unit.get_UnitDetails(), newLevel);
  5395. break;
  5396. }
  5397. }
  5398. return costs;
  5399. },
  5400. reset: function () {
  5401. this.Selection = null;
  5402. this.txtSelected.setValue("-");
  5403. this.txtLevel.setMinimum(0);
  5404. this.txtLevel.setMaximum(0);
  5405. this.txtLevel.resetValue();
  5406. this.txtLevel.setEnabled(false);
  5407. this.btnLevel.setEnabled(false);
  5408. this.onInput();
  5409. },
  5410. onTick: function () {
  5411. this.onInput();
  5412. },
  5413. onInput: function () {
  5414. var costs = this.getUpgradeCostsToLevel(this.Selection, parseInt(this.txtLevel.getValue(), 10));
  5415. if (costs !== null) {
  5416. for (var i = 0, Tib = 0, Cry = 0, Pow = 0, TibTime = 0, CryTime = 0, PowTime = 0; i < costs.length; i++) {
  5417. var uCosts = costs[i];
  5418. switch (parseInt(uCosts.Type, 10)) {
  5419. case ClientLib.Base.EResourceType.Tiberium:
  5420. Tib += uCosts.Count;
  5421. TibTime += this.getResTime(uCosts.Count, ClientLib.Base.EResourceType.Tiberium);
  5422. break;
  5423. case ClientLib.Base.EResourceType.Crystal:
  5424. Cry += uCosts.Count;
  5425. CryTime += this.getResTime(uCosts.Count, ClientLib.Base.EResourceType.Crystal);
  5426. break;
  5427. case ClientLib.Base.EResourceType.Power:
  5428. Pow += uCosts.Count;
  5429. PowTime += this.getResTime(uCosts.Count, ClientLib.Base.EResourceType.Power);
  5430. break;
  5431. }
  5432. }
  5433. this.resTiberium.setLabel(phe.cnc.gui.util.Numbers.formatNumbersCompact(Tib) + (TibTime > 0 ? " @ " + phe.cnc.Util.getTimespanString(TibTime) : ""));
  5434. this.resTiberium.setToolTipText(phe.cnc.gui.util.Numbers.formatNumbers(Tib));
  5435. if (Tib === 0) this.resTiberium.exclude();
  5436. else this.resTiberium.show();
  5437. this.resChrystal.setLabel(phe.cnc.gui.util.Numbers.formatNumbersCompact(Cry) + (CryTime > 0 ? " @ " + phe.cnc.Util.getTimespanString(CryTime) : ""));
  5438. this.resChrystal.setToolTipText(phe.cnc.gui.util.Numbers.formatNumbers(Cry));
  5439. if (Cry === 0) this.resChrystal.exclude();
  5440. else this.resChrystal.show();
  5441. this.resPower.setLabel(phe.cnc.gui.util.Numbers.formatNumbersCompact(Pow) + (PowTime > 0 ? " @ " + phe.cnc.Util.getTimespanString(PowTime) : ""));
  5442. this.resPower.setToolTipText(phe.cnc.gui.util.Numbers.formatNumbers(Pow));
  5443. if (Pow === 0) this.resPower.exclude();
  5444. else this.resPower.show();
  5445. } else {
  5446. this.resTiberium.setLabel("-");
  5447. this.resTiberium.resetToolTipText();
  5448. this.resTiberium.show();
  5449. this.resChrystal.setLabel("-");
  5450. this.resChrystal.resetToolTipText();
  5451. this.resChrystal.show();
  5452. this.resPower.setLabel("-");
  5453. this.resPower.resetToolTipText();
  5454. this.resPower.show();
  5455. }
  5456. },
  5457. onUpgrade: function() {
  5458. var newLevel = parseInt(this.txtLevel.getValue(), 10);
  5459. if (newLevel > 0 && this.Selection !== null) {
  5460. switch (this.Selection.get_VisObjectType()) {
  5461. case ClientLib.Vis.VisObject.EObjectType.CityBuildingType:
  5462. if (newLevel > this.Selection.get_BuildingLevel()) {
  5463. ClientLib.API.City.GetInstance().UpgradeBuildingToLevel(this.Selection.get_BuildingDetails(), newLevel);
  5464. this.onSelectionChange(null, this.Selection);
  5465. }
  5466. break;
  5467. case ClientLib.Vis.VisObject.EObjectType.DefenseUnitType:
  5468. if (newLevel > this.Selection.get_UnitLevel()) {
  5469. ClientLib.API.Defense.GetInstance().UpgradeUnitToLevel(this.Selection.get_UnitDetails(), newLevel);
  5470. this.onSelectionChange(null, this.Selection);
  5471. }
  5472. break;
  5473. case ClientLib.Vis.VisObject.EObjectType.ArmyUnitType:
  5474. if (newLevel > this.Selection.get_UnitLevel()) {
  5475. ClientLib.API.Army.GetInstance().UpgradeUnitToLevel(this.Selection.get_UnitDetails(), newLevel);
  5476. this.onSelectionChange(null, this.Selection);
  5477. }
  5478. break;
  5479. }
  5480. }
  5481. }
  5482. }
  5483. });
  5484. qx.Class.define("Upgrade.Repairtime", {
  5485. extend: qx.ui.container.Composite,
  5486. construct: function () {
  5487. try {
  5488. qx.ui.container.Composite.call(this);
  5489. this.set({
  5490. layout : new qx.ui.layout.VBox(5),
  5491. padding: 5,
  5492. decorator: "pane-light-opaque"
  5493. });
  5494. this.add(this.title = new qx.ui.basic.Label(this.tr("tnf:repair points")).set({ alignX: "center", font: "font_size_14_bold" }));
  5495. this.add(this.grid = new qx.ui.container.Composite(new qx.ui.layout.Grid()));
  5496.  
  5497. this.grid.add(this.basRT = new qx.ui.basic.Atom("", "FactionUI/icons/icon_arsnl_base_buildings.png").set({toolTipText: this.tr("tnf:base")}), {row: 0, column: 0});
  5498. this.basRT.getChildControl("icon").set({ width: 18, height: 18, scale: true, alignY: "middle" });
  5499. this.grid.add(new qx.ui.basic.Label("").set({ alignX: "right", alignY: "middle" }), {row: 0, column: 2});
  5500. this.grid.add(new qx.ui.basic.Label("").set({ alignX: "right", alignY: "middle" }), {row: 0, column: 4});
  5501. this.grid.add(this.btnBuildings = new qx.ui.form.Button(null, "FactionUI/icons/icon_building_detail_upgrade.png").set({toolTipText: this.tr("tnf:toggle upgrade mode"), width: 25, maxHeight: 17, alignY: "middle", show: "icon", iconPosition: "top", appearance: "button-addpoints"}), {row: 0, column: 6});
  5502. this.btnBuildings.getChildControl("icon").set({width: 14, height: 14, scale: true});
  5503. this.btnBuildings.addListener("execute", function (e) { this.upgradeBuilding(ClientLib.Base.ETechName.Construction_Yard); }, this);
  5504.  
  5505. this.grid.add(this.infRT = new qx.ui.basic.Atom("", "FactionUI/icons/icon_arsnl_off_squad.png").set({toolTipText: this.tr("tnf:infantry repair title")}), {row: 1, column: 0});
  5506. this.infRT.getChildControl("icon").set({ width: 18, height: 18, scale: true, alignY: "middle" });
  5507. this.grid.add(new qx.ui.basic.Label("").set({ alignX: "right", alignY: "middle" }), {row: 1, column: 2});
  5508. this.grid.add(new qx.ui.basic.Label("").set({ alignX: "right", alignY: "middle" }), {row: 1, column: 4});
  5509. this.grid.add(this.btnInfantry = new qx.ui.form.Button(null, "FactionUI/icons/icon_building_detail_upgrade.png").set({toolTipText: this.tr("tnf:toggle upgrade mode"), width: 25, maxHeight: 17, alignY: "middle", show: "icon", iconPosition: "top", appearance: "button-addpoints"}), {row: 1, column: 6});
  5510. this.btnInfantry.getChildControl("icon").set({width: 14, height: 14, scale: true});
  5511. this.btnInfantry.addListener("execute", function (e) { this.upgradeBuilding(ClientLib.Base.ETechName.Barracks); }, this);
  5512.  
  5513. this.grid.add(this.vehRT = new qx.ui.basic.Atom("", "FactionUI/icons/icon_arsnl_off_vehicle.png").set({toolTipText: this.tr("tnf:vehicle repair title")}), {row: 2, column: 0});
  5514. this.vehRT.getChildControl("icon").set({ width: 18, height: 18, scale: true, alignY: "middle" });
  5515. this.grid.add(new qx.ui.basic.Label("").set({ alignX: "right", alignY: "middle" }), {row: 2, column: 2});
  5516. this.grid.add(new qx.ui.basic.Label("").set({ alignX: "right", alignY: "middle" }), {row: 2, column: 4});
  5517. this.grid.add(this.btnVehicle = new qx.ui.form.Button(null, "FactionUI/icons/icon_building_detail_upgrade.png").set({toolTipText: this.tr("tnf:toggle upgrade mode"), width: 25, maxHeight: 17, alignY: "middle", show: "icon", iconPosition: "top", appearance: "button-addpoints"}), {row: 2, column: 6});
  5518. this.btnVehicle.getChildControl("icon").set({width: 14, height: 14, scale: true});
  5519. this.btnVehicle.addListener("execute", function (e) { this.upgradeBuilding(ClientLib.Base.ETechName.Factory); }, this);
  5520.  
  5521. this.grid.add(this.airRT = new qx.ui.basic.Atom("", "FactionUI/icons/icon_arsnl_off_plane.png").set({toolTipText: this.tr("tnf:aircraft repair title")}), {row: 3, column: 0});
  5522. this.airRT.getChildControl("icon").set({ width: 18, height: 18, scale: true, alignY: "middle" });
  5523. this.grid.add(new qx.ui.basic.Label("").set({ alignX: "right", alignY: "middle" }), {row: 3, column: 2});
  5524. this.grid.add(new qx.ui.basic.Label("").set({ alignX: "right", alignY: "middle" }), {row: 3, column: 4});
  5525. this.grid.add(this.btnAircraft = new qx.ui.form.Button(null, "FactionUI/icons/icon_building_detail_upgrade.png").set({toolTipText: this.tr("tnf:toggle upgrade mode"), width: 25, maxHeight: 17, alignY: "middle", show: "icon", iconPosition: "top", appearance: "button-addpoints"}), {row: 3, column: 6});
  5526. this.btnAircraft.getChildControl("icon").set({width: 14, height: 14, scale: true});
  5527. this.btnAircraft.addListener("execute", function (e) { this.upgradeBuilding(ClientLib.Base.ETechName.Airport); }, this);
  5528.  
  5529. this.grid.getLayout().setRowFlex(0, 0);
  5530. this.grid.getLayout().setRowFlex(1, 0);
  5531. this.grid.getLayout().setRowFlex(2, 0);
  5532. this.grid.getLayout().setRowFlex(3, 0);
  5533. this.grid.getLayout().setColumnFlex(1, 200);
  5534. this.grid.getLayout().setColumnFlex(3, 200);
  5535. this.grid.getLayout().setColumnFlex(5, 200);
  5536.  
  5537. this.addListener("appear", this.onAppear, this);
  5538. this.addListener("disappear", this.onDisappear, this);
  5539. } catch (e) {
  5540. console.log("Error setting up Upgrade.Repairtime Constructor: ");
  5541. console.log(e.toString());
  5542. }
  5543. },
  5544. destruct: function () {},
  5545. members: {
  5546. title: null,
  5547. grid: null,
  5548. btnBuildings: null,
  5549. btnInfantry: null,
  5550. btnVehicle: null,
  5551. btnAircraft: null,
  5552. onAppear: function () {
  5553. phe.cnc.Util.attachNetEvent(ClientLib.Data.MainData.GetInstance().get_Cities(), "CurrentOwnChange", ClientLib.Data.CurrentOwnCityChange, this, this.onCurrentCityChange);
  5554. phe.cnc.Util.attachNetEvent(ClientLib.Data.MainData.GetInstance().get_Cities(), "CurrentChange", ClientLib.Data.CurrentCityChange, this, this.onCurrentCityChange);
  5555. phe.cnc.base.Timer.getInstance().addListener("uiTick", this.onTick, this);
  5556. this.getInfo();
  5557. },
  5558. onDisappear: function () {
  5559. phe.cnc.Util.detachNetEvent(ClientLib.Data.MainData.GetInstance().get_Cities(), "CurrentOwnChange", ClientLib.Data.CurrentOwnCityChange, this, this.onCurrentCityChange);
  5560. phe.cnc.Util.detachNetEvent(ClientLib.Data.MainData.GetInstance().get_Cities(), "CurrentChange", ClientLib.Data.CurrentCityChange, this, this.onCurrentCityChange);
  5561. phe.cnc.base.Timer.getInstance().removeListener("uiTick", this.onTick, this);
  5562. },
  5563. onTick: function () {
  5564. this.getInfo();
  5565. },
  5566. onCurrentCityChange: function (oldCurrentCity, newCurrentCity) {
  5567. if (oldCurrentCity !== newCurrentCity) {
  5568. this.getInfo();
  5569. }
  5570. },
  5571. canUpgradeBuilding: function (ETechName) {
  5572. var city = ClientLib.Data.MainData.GetInstance().get_Cities().get_CurrentOwnCity();
  5573. var building = city.get_CityBuildingsData().GetUniqueBuildingByTechName(ETechName);
  5574. if (building) {
  5575. var ResourceRequirements_Obj = ClientLib.Base.Util.GetUnitLevelResourceRequirements_Obj(building.get_CurrentLevel() + 1, building.get_UnitGameData_Obj())
  5576. return (building.get_CurrentDamage() == 0 && !city.get_IsLocked() && city.HasEnoughResources(ResourceRequirements_Obj));
  5577. } else return false;
  5578. },
  5579. upgradeBuilding: function (ETechName) {
  5580. var city = ClientLib.Data.MainData.GetInstance().get_Cities().get_CurrentOwnCity();
  5581. var building = city.get_CityBuildingsData().GetUniqueBuildingByTechName(ETechName);
  5582. if (building) {
  5583. ClientLib.Net.CommunicationManager.GetInstance().SendCommand("UpgradeBuilding", {
  5584. cityid : city.get_Id(),
  5585. posX : building.get_CoordX(),
  5586. posY : building.get_CoordY()
  5587. }, null, null, true);
  5588. }
  5589. },
  5590. getInfo: function () {
  5591. try {
  5592. var lvl, win, city = ClientLib.Data.MainData.GetInstance().get_Cities().get_CurrentOwnCity();
  5593.  
  5594. lvl = city.get_CityBuildingsData().GetUniqueBuildingByTechName(ClientLib.Base.ETechName.Construction_Yard).get_CurrentLevel();
  5595. win = (city.get_CityBuildingsData().GetFullRepairTime(true) - city.get_CityBuildingsData().GetFullRepairTime(false)) * -1;
  5596. this.grid.getLayout().getCellWidget(0, 0).setLabel("("+ lvl +")");
  5597. this.grid.getLayout().getCellWidget(0, 2).setValue(phe.cnc.Util.getTimespanString(city.get_CityBuildingsData().GetFullRepairTime()));
  5598. this.grid.getLayout().getCellWidget(0, 4).setValue("-"+ phe.cnc.Util.getTimespanString(win));
  5599.  
  5600. if (city.get_CityUnitsData().GetRepairTimeFromEUnitGroup(ClientLib.Data.EUnitGroup.Infantry, false) > 0) {
  5601. lvl = city.get_CityBuildingsData().GetUniqueBuildingByTechName(ClientLib.Base.ETechName.Barracks).get_CurrentLevel();
  5602. win = (city.get_CityUnitsData().GetRepairTimeFromEUnitGroup(ClientLib.Data.EUnitGroup.Infantry, true) - city.get_CityUnitsData().GetRepairTimeFromEUnitGroup(ClientLib.Data.EUnitGroup.Infantry, false)) * -1;
  5603. this.grid.getLayout().getCellWidget(1, 0).setLabel("("+ lvl +")");
  5604. this.grid.getLayout().getCellWidget(1, 2).setValue(phe.cnc.Util.getTimespanString(city.get_CityUnitsData().GetRepairTimeFromEUnitGroup(ClientLib.Data.EUnitGroup.Infantry, false)));
  5605. this.grid.getLayout().getCellWidget(1, 4).setValue("-"+ phe.cnc.Util.getTimespanString(win));
  5606. this.grid.getLayout().setRowHeight(1, 18);
  5607. } else {
  5608. this.grid.getLayout().setRowHeight(1, 0);
  5609. }
  5610.  
  5611. if (city.get_CityUnitsData().GetRepairTimeFromEUnitGroup(ClientLib.Data.EUnitGroup.Vehicle, false) > 0) {
  5612. lvl = city.get_CityBuildingsData().GetUniqueBuildingByTechName(ClientLib.Base.ETechName.Factory).get_CurrentLevel();
  5613. win = (city.get_CityUnitsData().GetRepairTimeFromEUnitGroup(ClientLib.Data.EUnitGroup.Vehicle, true) - city.get_CityUnitsData().GetRepairTimeFromEUnitGroup(ClientLib.Data.EUnitGroup.Vehicle, false)) * -1;
  5614. this.grid.getLayout().getCellWidget(2, 0).setLabel("("+ lvl +")");
  5615. this.grid.getLayout().getCellWidget(2, 2).setValue(phe.cnc.Util.getTimespanString(city.get_CityUnitsData().GetRepairTimeFromEUnitGroup(ClientLib.Data.EUnitGroup.Vehicle, false)));
  5616. this.grid.getLayout().getCellWidget(2, 4).setValue("-"+ phe.cnc.Util.getTimespanString(win));
  5617. this.grid.getLayout().setRowHeight(2, 18);
  5618. } else {
  5619. this.grid.getLayout().setRowHeight(2, 0);
  5620. }
  5621.  
  5622. if (city.get_CityUnitsData().GetRepairTimeFromEUnitGroup(ClientLib.Data.EUnitGroup.Aircraft, false) > 0) {
  5623. lvl = city.get_CityBuildingsData().GetUniqueBuildingByTechName(ClientLib.Base.ETechName.Airport).get_CurrentLevel();
  5624. win = (city.get_CityUnitsData().GetRepairTimeFromEUnitGroup(ClientLib.Data.EUnitGroup.Aircraft, true) - city.get_CityUnitsData().GetRepairTimeFromEUnitGroup(ClientLib.Data.EUnitGroup.Aircraft, false)) * -1;
  5625. this.grid.getLayout().getCellWidget(3, 0).setLabel("("+ lvl +")");
  5626. this.grid.getLayout().getCellWidget(3, 2).setValue(phe.cnc.Util.getTimespanString(city.get_CityUnitsData().GetRepairTimeFromEUnitGroup(ClientLib.Data.EUnitGroup.Aircraft, false)));
  5627. this.grid.getLayout().getCellWidget(3, 4).setValue("-"+ phe.cnc.Util.getTimespanString(win));
  5628. this.grid.getLayout().setRowHeight(3, 18);
  5629. } else {
  5630. this.grid.getLayout().setRowHeight(3, 0);
  5631. }
  5632.  
  5633. if (this.canUpgradeBuilding(ClientLib.Base.ETechName.Construction_Yard)) this.btnBuildings.setEnabled(true);
  5634. else this.btnBuildings.setEnabled(false);
  5635. if (this.canUpgradeBuilding(ClientLib.Base.ETechName.Barracks)) this.btnInfantry.setEnabled(true);
  5636. else this.btnInfantry.setEnabled(false);
  5637. if (this.canUpgradeBuilding(ClientLib.Base.ETechName.Factory)) this.btnVehicle.setEnabled(true);
  5638. else this.btnVehicle.setEnabled(false);
  5639. if (this.canUpgradeBuilding(ClientLib.Base.ETechName.Airport)) this.btnAircraft.setEnabled(true);
  5640. else this.btnAircraft.setEnabled(false);
  5641. } catch (e) {
  5642. console.log("Error in Upgrade.Repairtime.getInfo: ");
  5643. console.log(e.toString());
  5644. }
  5645. }
  5646. }
  5647. });
  5648.  
  5649. }
  5650. function translation() {
  5651. var localeManager = qx.locale.Manager.getInstance();
  5652.  
  5653. // Default language is english (en)
  5654. // Available Languages are: ar,ce,cs,da,de,en,es,fi,fr,hu,id,it,nb,nl,pl,pt,ro,ru,sk,sv,ta,tr,uk
  5655. // You can send me translations so i can include them in the Script.
  5656.  
  5657. // German
  5658. localeManager.addTranslation("de", {
  5659. "Selected building": "Markiertes Gebäude",
  5660. "All buildings": "Alle Gebäude",
  5661. "Selected defense unit": "Markierte Abwehrstellung",
  5662. "All defense units": "Alle Abwehrstellungen",
  5663. "Selected army unit": "Markierte Armee-Einheit",
  5664. "All army units": "Alle Armee-Einheiten"
  5665. });
  5666.  
  5667. // Hungarian
  5668. localeManager.addTranslation("hu", {
  5669. "Selected building": "Kiválasztott létesítmény",
  5670. "All buildings": "Összes létesítmény",
  5671. "Selected defense unit": "Kiválasztott védelmi egység",
  5672. "All defense units": "Minden védelmi egység",
  5673. "Selected army unit": "Kiválasztott katonai egység",
  5674. "All army units": "Minden katonai egység"
  5675. });
  5676. }
  5677. function waitForGame() {
  5678. try {
  5679. if (typeof qx != 'undefined' && typeof qx.core != 'undfined' && typeof qx.core.Init != 'undefined') {
  5680. var app = qx.core.Init.getApplication();
  5681. if (app.initDone == true) {
  5682. try {
  5683. console.log("WarChiefs - Tiberium Alliances Upgrade Base/Defense/Army: Loading");
  5684. translation();
  5685. createClasses();
  5686. Upgrade.getInstance();
  5687. console.log("WarChiefs - Tiberium Alliances Upgrade Base/Defense/Army: Loaded");
  5688. } catch (e) {
  5689. console.log(e);
  5690. }
  5691. } else {
  5692. window.setTimeout(waitForGame, 1000);
  5693. }
  5694. } else {
  5695. window.setTimeout(waitForGame, 1000);
  5696. }
  5697. } catch (e) {
  5698. console.log(e);
  5699. }
  5700. }
  5701. window.setTimeout(waitForGame, 1000);
  5702. };
  5703.  
  5704. var script = document.createElement("script");
  5705. var txt = injectFunction.toString();
  5706. script.innerHTML = "(" + txt + ")();";
  5707. script.type = "text/javascript";
  5708.  
  5709. document.getElementsByTagName("head")[0].appendChild(script);
  5710. })();
  5711.  
  5712. /***********************************************************************************
  5713. Tiberium Alliances PvP/PvE Player Info Mod
  5714. ***********************************************************************************/
  5715. // ==UserScript==
  5716. // @name Tiberium Alliances PvP/PvE Player Info Mod
  5717. // @description Separates the number of bases destroyed into PvP and PvE in the Player Info window. Now also includes a tab showing all the POI the player is holding.
  5718. // @namespace player_info_mod
  5719. // @include https://prodgame*.alliances.commandandconquer.com/*/index.aspx*
  5720. // @version 1.2
  5721. // @author KRS_L
  5722. // ==/UserScript==
  5723. (function () {
  5724. var PlayerInfoMod_main = function () {
  5725. var playerInfoWindow = null;
  5726. var general = null;
  5727. var pvpScoreLabel = null;
  5728. var pveScoreLabel = null;
  5729. var playerName = null;
  5730. var tabView = null;
  5731. var tableModel = null;
  5732. var baseCoords = null;
  5733. var rowData = null;
  5734.  
  5735. function createPlayerInfoMod() {
  5736. try {
  5737. console.log('Player Info Mod loaded');
  5738. var tr = qx.locale.Manager.tr;
  5739. playerInfoWindow = webfrontend.gui.info.PlayerInfoWindow.getInstance();
  5740. general = playerInfoWindow.getChildren()[0].getChildren()[0].getChildren()[0].getChildren()[0].getChildren()[0].getChildren()[1].getChildren()[0];
  5741. tabView = playerInfoWindow.getChildren()[0];
  5742. playerName = general.getChildren()[1];
  5743.  
  5744. var pvpLabel = new qx.ui.basic.Label("- PvP:");
  5745. pvpScoreLabel = new qx.ui.basic.Label("").set({
  5746. textColor: "text-value",
  5747. font: "font_size_13_bold"
  5748. });
  5749. general.add(pvpLabel, {
  5750. row: 3,
  5751. column: 3
  5752. });
  5753. general.add(pvpScoreLabel, {
  5754. row: 3,
  5755. column: 4
  5756. });
  5757.  
  5758. var pveLabel = new qx.ui.basic.Label("- PvE:");
  5759. pveScoreLabel = new qx.ui.basic.Label("").set({
  5760. textColor: "text-value",
  5761. font: "font_size_13_bold"
  5762. });
  5763. general.add(pveLabel, {
  5764. row: 4,
  5765. column: 3
  5766. });
  5767. general.add(pveScoreLabel, {
  5768. row: 4,
  5769. column: 4
  5770. });
  5771.  
  5772. var poiTab = new qx.ui.tabview.Page("POI");
  5773. poiTab.setLayout(new qx.ui.layout.Canvas());
  5774. poiTab.setPaddingTop(6);
  5775. poiTab.setPaddingLeft(8);
  5776. poiTab.setPaddingRight(10);
  5777. poiTab.setPaddingBottom(8);
  5778.  
  5779. tableModel = new webfrontend.data.SimpleColFormattingDataModel().set({
  5780. caseSensitiveSorting: false
  5781. });
  5782.  
  5783. tableModel.setColumns([tr("tnf:name"), tr("tnf:lvl"), tr("tnf:points"), tr("tnf:coordinates")], ["t", "l", "s", "c"]);
  5784. tableModel.setColFormat(3, "<div style=\"cursor:pointer;color:" + webfrontend.gui.util.BBCode.clrLink + "\">", "</div>");
  5785. var poiTable = new webfrontend.gui.widgets.CustomTable(tableModel);
  5786. poiTable.addListener("cellClick", centerCoords, this);
  5787.  
  5788. var columnModel = poiTable.getTableColumnModel();
  5789. columnModel.setColumnWidth(0, 250);
  5790. columnModel.setColumnWidth(1, 80);
  5791. columnModel.setColumnWidth(2, 120);
  5792. columnModel.setColumnWidth(3, 120);
  5793. columnModel.setDataCellRenderer(3, new qx.ui.table.cellrenderer.Html());
  5794. columnModel.getDataCellRenderer(2).setUseAutoAlign(false);
  5795. poiTable.setStatusBarVisible(false);
  5796. poiTable.setColumnVisibilityButtonVisible(false);
  5797. poiTab.add(poiTable, {
  5798. left: 0,
  5799. top: 0,
  5800. right: 0,
  5801. bottom: 0
  5802. });
  5803. tabView.add(poiTab);
  5804.  
  5805. playerInfoWindow.addListener("close", onPlayerInfoWindowClose, this);
  5806. playerName.addListener("changeValue", onPlayerChanged, this);
  5807.  
  5808. } catch (e) {
  5809. console.log("createPlayerInfoMod: ", e);
  5810. }
  5811. }
  5812.  
  5813. function centerCoords(e) {
  5814. try {
  5815. var poiCoord = tableModel.getRowData(e.getRow())[3].split(":");
  5816. if (e.getColumn() == 3) webfrontend.gui.UtilView.centerCoordinatesOnRegionViewWindow(Number(poiCoord[0]), Number(poiCoord[1]));
  5817. } catch (e) {
  5818. console.log("centerCoords: ", e);
  5819. }
  5820. }
  5821.  
  5822. function onPlayerInfo(context, data) {
  5823. try {
  5824. pvpScoreLabel.setValue((data.bd - data.bde).toString());
  5825. pveScoreLabel.setValue(data.bde.toString());
  5826. var bases = data.c;
  5827. baseCoords = new Object;
  5828. for (var i in bases) {
  5829. var base = bases[i];
  5830. baseCoords[i] = new Object();
  5831. baseCoords[i]["x"] = base.x;
  5832. baseCoords[i]["y"] = base.y;
  5833. }
  5834. ClientLib.Net.CommunicationManager.GetInstance().SendSimpleCommand("GetPublicAllianceInfo", {
  5835. id: data.a
  5836. }, phe.cnc.Util.createEventDelegate(ClientLib.Net.CommandResult, this, onAllianceInfo), null);
  5837. } catch (e) {
  5838. console.log("onPlayerInfo: ", e);
  5839. }
  5840. }
  5841.  
  5842. function onAllianceInfo(context, data) {
  5843. try {
  5844. rowData = [];
  5845. var pois = data.opois;
  5846. for (var i in pois) {
  5847. var poi = pois[i];
  5848. for (var j in baseCoords) {
  5849. var distanceX = Math.abs(baseCoords[j].x - poi.x);
  5850. var distanceY = Math.abs(baseCoords[j].y - poi.y);
  5851. if (distanceX > 2 || distanceY > 2) continue;
  5852. if (distanceX == 2 && distanceY == 2) continue;
  5853. var name = phe.cnc.gui.util.Text.getPoiInfosByType(poi.t).name;
  5854. var level = poi.l;
  5855. var score = ClientLib.Base.PointOfInterestTypes.GetScoreByLevel(poi.l);
  5856. var coords = phe.cnc.gui.util.Numbers.formatCoordinates(poi.x, poi.y);
  5857. rowData.push([name, level, score, coords]);
  5858. break;
  5859. }
  5860. }
  5861. tableModel.setData(rowData);
  5862. tableModel.sortByColumn(0, true);
  5863. } catch (e) {
  5864. console.log("onAllianceInfo: ", e);
  5865. }
  5866. }
  5867.  
  5868. function onPlayerChanged() {
  5869. try {
  5870. if (playerName.getValue().length > 0) {
  5871. ClientLib.Net.CommunicationManager.GetInstance().SendSimpleCommand("GetPublicPlayerInfoByName", {
  5872. name: playerName.getValue()
  5873. }, phe.cnc.Util.createEventDelegate(ClientLib.Net.CommandResult, this, onPlayerInfo), null);
  5874. }
  5875. } catch (e) {
  5876. console.log("onPlayerChanged: ", e);
  5877. }
  5878. }
  5879.  
  5880. function onPlayerInfoWindowClose() {
  5881. try {
  5882. pvpScoreLabel.setValue("");
  5883. pveScoreLabel.setValue("");
  5884. tableModel.setData([]);
  5885. } catch (e) {
  5886. console.log("onPlayerInfoWindowClose: ", e);
  5887. }
  5888. }
  5889.  
  5890. function PlayerInfoMod_checkIfLoaded() {
  5891. try {
  5892. if (typeof qx !== 'undefined' && typeof qx.locale !== 'undefined' && typeof qx.locale.Manager !== 'undefined') {
  5893. if (ClientLib.Data.MainData.GetInstance().get_Alliance().get_FirstLeaders() !== null && ClientLib.Data.MainData.GetInstance().get_Alliance().get_FirstLeaders().l.length != 0) {
  5894. createPlayerInfoMod();
  5895. } else {
  5896. window.setTimeout(PlayerInfoMod_checkIfLoaded, 1000);
  5897. }
  5898. } else {
  5899. window.setTimeout(PlayerInfoMod_checkIfLoaded, 1000);
  5900. }
  5901. } catch (e) {
  5902. console.log("PlayerInfoMod_checkIfLoaded: ", e);
  5903. }
  5904. }
  5905.  
  5906. if (/commandandconquer\.com/i.test(document.domain)) {
  5907. window.setTimeout(PlayerInfoMod_checkIfLoaded, 1000);
  5908. }
  5909. }
  5910.  
  5911. try {
  5912. var PlayerInfoMod = document.createElement("script");
  5913. PlayerInfoMod.innerHTML = "(" + PlayerInfoMod_main.toString() + ")();";
  5914. PlayerInfoMod.type = "text/javascript";
  5915. if (/commandandconquer\.com/i.test(document.domain)) {
  5916. document.getElementsByTagName("head")[0].appendChild(PlayerInfoMod);
  5917. }
  5918. } catch (e) {
  5919. console.log("PlayerInfoMod: init error: ", e);
  5920. }
  5921. })();
  5922.  
  5923. /***********************************************************************************
  5924. CNCOpt Link Button
  5925. ***********************************************************************************/
  5926.  
  5927. // ==UserScript==
  5928. // @version 1.7.6b
  5929. // @updateURL https://userscripts.org/scripts/source/131289.meta.js
  5930. // @downloadURL https://userscripts.org/scripts/source/131289.user.js
  5931. // @name C&C:TA CNCOpt Link Button for SC
  5932. // @namespace http://cncopt.com/
  5933. // @icon http://cncopt.com/favicon.ico
  5934. // @description Creates a "CNCOpt" button when selecting a base in Command & Conquer: Tiberium Alliances. The share button takes you to http://cncopt.com/ and fills in the selected base information so you can analyze or share the base.
  5935. // @include http*://prodgame*.alliances.commandandconquer.com/*/index.aspx*
  5936. // @include http*://*.cncopt.com/*
  5937. // @include http*://cncopt.com/*
  5938. // @grant GM_log
  5939. // @grant GM_setValue
  5940. // @grant GM_getValue
  5941. // @grant GM_registerMenuCommand
  5942. // @grant GM_xmlhttpRequest
  5943. // @grant GM_updatingEnabled
  5944. // @grant unsafeWindow
  5945. // @contributor PythEch (http://http://userscripts.org/users/220246)
  5946. // @contributor jerbri (http://userscripts.org/users/507954)
  5947. // @contributor Der_Flake
  5948. // ==/UserScript==
  5949. /*
  5950.  
  5951. 2013-03-03: Special thanks to jerbri for fixing this up so it worked again!
  5952. 2012-11-25: Special thanks to PythEch for fixing this up so it worked again!
  5953.  
  5954. */
  5955. var scity = null;
  5956. var tcity = null;
  5957. var tbase = null;
  5958. try {
  5959. unsafeWindow.__cncopt_version = "1.7.6";
  5960. (function () {
  5961. var cncopt_main = function () {
  5962.  
  5963. var defense_unit_map = {
  5964. /* GDI Defense Units */"GDI_Wall": "w",
  5965. "GDI_Cannon": "c",
  5966. "GDI_Antitank Barrier": "t",
  5967. "GDI_Barbwire": "b",
  5968. "GDI_Turret": "m",
  5969. "GDI_Flak": "f",
  5970. "GDI_Art Inf": "r",
  5971. "GDI_Art Air": "e",
  5972. "GDI_Art Tank": "a",
  5973. "GDI_Def_APC Guardian": "g",
  5974. "GDI_Def_Missile Squad": "q",
  5975. "GDI_Def_Pitbull": "p",
  5976. "GDI_Def_Predator": "d",
  5977. "GDI_Def_Sniper": "s",
  5978. "GDI_Def_Zone Trooper": "z",
  5979. /* Nod Defense Units */"NOD_Def_Antitank Barrier": "t",
  5980. "NOD_Def_Art Air": "e",
  5981. "NOD_Def_Art Inf": "r",
  5982. "NOD_Def_Art Tank": "a",
  5983. "NOD_Def_Attack Bike": "p",
  5984. "NOD_Def_Barbwire": "b",
  5985. "NOD_Def_Black Hand": "z",
  5986. "NOD_Def_Cannon": "c",
  5987. "NOD_Def_Confessor": "s",
  5988. "NOD_Def_Flak": "f",
  5989. "NOD_Def_MG Nest": "m",
  5990. "NOD_Def_Militant Rocket Soldiers": "q",
  5991. "NOD_Def_Reckoner": "g",
  5992. "NOD_Def_Scorpion Tank": "d",
  5993. "NOD_Def_Wall": "w",
  5994.  
  5995. /* Forgotten Defense Units */"FOR_Wall": "w",
  5996. "FOR_Barbwire_VS_Inf": "b",
  5997. "FOR_Barrier_VS_Veh": "t",
  5998. "FOR_Inf_VS_Inf": "g",
  5999. "FOR_Inf_VS_Veh": "r",
  6000. "FOR_Inf_VS_Air": "q",
  6001. "FOR_Sniper": "n",
  6002. "FOR_Mammoth": "y",
  6003. "FOR_Veh_VS_Inf": "o",
  6004. "FOR_Veh_VS_Veh": "s",
  6005. "FOR_Veh_VS_Air": "u",
  6006. "FOR_Turret_VS_Inf": "m",
  6007. "FOR_Turret_VS_Inf_ranged": "a",
  6008. "FOR_Turret_VS_Veh": "v",
  6009. "FOR_Turret_VS_Veh_ranged": "d",
  6010. "FOR_Turret_VS_Air": "f",
  6011. "FOR_Turret_VS_Air_ranged": "e",
  6012. "": ""
  6013. };
  6014.  
  6015. var offense_unit_map = {
  6016. /* GDI Offense Units */"GDI_APC Guardian": "g",
  6017. "GDI_Commando": "c",
  6018. "GDI_Firehawk": "f",
  6019. "GDI_Juggernaut": "j",
  6020. "GDI_Kodiak": "k",
  6021. "GDI_Mammoth": "m",
  6022. "GDI_Missile Squad": "q",
  6023. "GDI_Orca": "o",
  6024. "GDI_Paladin": "a",
  6025. "GDI_Pitbull": "p",
  6026. "GDI_Predator": "d",
  6027. "GDI_Riflemen": "r",
  6028. "GDI_Sniper Team": "s",
  6029. "GDI_Zone Trooper": "z",
  6030.  
  6031. /* Nod Offense Units */"NOD_Attack Bike": "b",
  6032. "NOD_Avatar": "a",
  6033. "NOD_Black Hand": "z",
  6034. "NOD_Cobra": "r",
  6035. "NOD_Commando": "c",
  6036. "NOD_Confessor": "s",
  6037. "NOD_Militant Rocket Soldiers": "q",
  6038. "NOD_Militants": "m",
  6039. "NOD_Reckoner": "k",
  6040. "NOD_Salamander": "l",
  6041. "NOD_Scorpion Tank": "o",
  6042. "NOD_Specter Artilery": "p",
  6043. "NOD_Venom": "v",
  6044. "NOD_Vertigo": "t",
  6045. "": ""
  6046. };
  6047.  
  6048.  
  6049. function findTechLayout(city) {
  6050. for (var k in city) {
  6051. //console.log(typeof(city[k]), "1.city[", k, "]", city[k])
  6052. if ((typeof (city[k]) == "object") && city[k] && 0 in city[k] && 8 in city[k]) {
  6053. if ((typeof (city[k][0]) == "object") && city[k][0] && city[k][0] && 0 in city[k][0] && 15 in city[k][0]) {
  6054. if ((typeof (city[k][0][0]) == "object") && city[k][0][0] && "BuildingIndex" in city[k][0][0]) {
  6055. return city[k];
  6056. }
  6057. }
  6058. }
  6059. }
  6060. return null;
  6061. }
  6062.  
  6063. function findBuildings(city) {
  6064. var cityBuildings = city.get_CityBuildingsData();
  6065. for (var k in cityBuildings) {
  6066. if (PerforceChangelist >= 376877) {
  6067. if ((typeof (cityBuildings[k]) === "object") && cityBuildings[k] && "d" in cityBuildings[k] && "c" in cityBuildings[k] && cityBuildings[k].c > 0) {
  6068. return cityBuildings[k].d;
  6069. }
  6070. } else {
  6071. if ((typeof (cityBuildings[k]) === "object") && cityBuildings[k] && "l" in cityBuildings[k]) {
  6072. return cityBuildings[k].l;
  6073. }
  6074. }
  6075. }
  6076. }
  6077.  
  6078. function isOffenseUnit(unit) {
  6079. return (unit.get_UnitGameData_Obj().n in offense_unit_map);
  6080. }
  6081.  
  6082. function isDefenseUnit(unit) {
  6083. return (unit.get_UnitGameData_Obj().n in defense_unit_map);
  6084. }
  6085.  
  6086. function getUnitArrays(city) {
  6087. var ret = [];
  6088. for (var k in city) {
  6089. if ((typeof (city[k]) == "object") && city[k]) {
  6090. for (var k2 in city[k]) {
  6091. if (PerforceChangelist >= 376877) {
  6092. if ((typeof (city[k][k2]) == "object") && city[k][k2] && "d" in city[k][k2]) {
  6093. var lst = city[k][k2].d;
  6094. if ((typeof (lst) == "object") && lst) {
  6095. for (var i in lst) {
  6096. if (typeof (lst[i]) == "object" && lst[i] && "get_CurrentLevel" in lst[i]) {
  6097. ret.push(lst);
  6098. }
  6099. }
  6100. }
  6101. }
  6102. } else {
  6103. if ((typeof (city[k][k2]) == "object") && city[k][k2] && "l" in city[k][k2]) {
  6104. var lst = city[k][k2].l;
  6105. if ((typeof (lst) == "object") && lst) {
  6106. for (var i in lst) {
  6107. if (typeof (lst[i]) == "object" && lst[i] && "get_CurrentLevel" in lst[i]) {
  6108. ret.push(lst);
  6109. }
  6110. }
  6111. }
  6112. }
  6113. }
  6114. }
  6115. }
  6116. }
  6117. return ret;
  6118. }
  6119.  
  6120. function getDefenseUnits(city) {
  6121. var arr = getUnitArrays(city);
  6122. for (var i = 0; i < arr.length; ++i) {
  6123. for (var j in arr[i]) {
  6124. if (isDefenseUnit(arr[i][j])) {
  6125. return arr[i];
  6126. }
  6127. }
  6128. }
  6129. return [];
  6130. }
  6131.  
  6132. function getOffenseUnits(city) {
  6133. var arr = getUnitArrays(city);
  6134. for (var i = 0; i < arr.length; ++i) {
  6135. for (var j in arr[i]) {
  6136. if (isOffenseUnit(arr[i][j])) {
  6137. return arr[i];
  6138. }
  6139. }
  6140. }
  6141. return [];
  6142. }
  6143.  
  6144.  
  6145. function cncopt_create() {
  6146. console.log("CNCOpt Link Button v" + window.__cncopt_version + " loaded");
  6147. var cncopt = {
  6148. selected_base: null,
  6149. keymap: {
  6150. /* GDI Buildings */"GDI_Accumulator": "a",
  6151. "GDI_Refinery": "r",
  6152. "GDI_Trade Center": "u",
  6153. "GDI_Silo": "s",
  6154. "GDI_Power Plant": "p",
  6155. "GDI_Construction Yard": "y",
  6156. "GDI_Airport": "d",
  6157. "GDI_Barracks": "b",
  6158. "GDI_Factory": "f",
  6159. "GDI_Defense HQ": "q",
  6160. "GDI_Defense Facility": "w",
  6161. "GDI_Command Center": "e",
  6162. "GDI_Support_Art": "z",
  6163. "GDI_Support_Air": "x",
  6164. "GDI_Support_Ion": "i",
  6165. /* Forgotten Buildings */"FOR_Silo": "s",
  6166. "FOR_Refinery": "r",
  6167. "FOR_Tiberium Booster": "b",
  6168. "FOR_Crystal Booster": "v",
  6169. "FOR_Trade Center": "u",
  6170. "FOR_Defense Facility": "w",
  6171. "FOR_Construction Yard": "y",
  6172. "FOR_Harvester_Tiberium": "h",
  6173. "FOR_Defense HQ": "q",
  6174. "FOR_Harvester_Crystal": "n",
  6175. /* Nod Buildings */"NOD_Refinery": "r",
  6176. "NOD_Power Plant": "p",
  6177. "NOD_Harvester": "h",
  6178. "NOD_Construction Yard": "y",
  6179. "NOD_Airport": "d",
  6180. "NOD_Trade Center": "u",
  6181. "NOD_Defense HQ": "q",
  6182. "NOD_Barracks": "b",
  6183. "NOD_Silo": "s",
  6184. "NOD_Factory": "f",
  6185. "NOD_Harvester_Crystal": "n",
  6186. "NOD_Command Post": "e",
  6187. "NOD_Support_Art": "z",
  6188. "NOD_Support_Ion": "i",
  6189. "NOD_Accumulator": "a",
  6190. "NOD_Support_Air": "x",
  6191. "NOD_Defense Facility": "w",
  6192. //"NOD_Tech Lab": "",
  6193. //"NOD_Recruitment Hub": "X",
  6194. //"NOD_Temple of Nod": "X",
  6195.  
  6196. /* GDI Defense Units */"GDI_Wall": "w",
  6197. "GDI_Cannon": "c",
  6198. "GDI_Antitank Barrier": "t",
  6199. "GDI_Barbwire": "b",
  6200. "GDI_Turret": "m",
  6201. "GDI_Flak": "f",
  6202. "GDI_Art Inf": "r",
  6203. "GDI_Art Air": "e",
  6204. "GDI_Art Tank": "a",
  6205. "GDI_Def_APC Guardian": "g",
  6206. "GDI_Def_Missile Squad": "q",
  6207. "GDI_Def_Pitbull": "p",
  6208. "GDI_Def_Predator": "d",
  6209. "GDI_Def_Sniper": "s",
  6210. "GDI_Def_Zone Trooper": "z",
  6211. /* Nod Defense Units */"NOD_Def_Antitank Barrier": "t",
  6212. "NOD_Def_Art Air": "e",
  6213. "NOD_Def_Art Inf": "r",
  6214. "NOD_Def_Art Tank": "a",
  6215. "NOD_Def_Attack Bike": "p",
  6216. "NOD_Def_Barbwire": "b",
  6217. "NOD_Def_Black Hand": "z",
  6218. "NOD_Def_Cannon": "c",
  6219. "NOD_Def_Confessor": "s",
  6220. "NOD_Def_Flak": "f",
  6221. "NOD_Def_MG Nest": "m",
  6222. "NOD_Def_Militant Rocket Soldiers": "q",
  6223. "NOD_Def_Reckoner": "g",
  6224. "NOD_Def_Scorpion Tank": "d",
  6225. "NOD_Def_Wall": "w",
  6226.  
  6227. /* Forgotten Defense Units */"FOR_Wall": "w",
  6228. "FOR_Barbwire_VS_Inf": "b",
  6229. "FOR_Barrier_VS_Veh": "t",
  6230. "FOR_Inf_VS_Inf": "g",
  6231. "FOR_Inf_VS_Veh": "r",
  6232. "FOR_Inf_VS_Air": "q",
  6233. "FOR_Sniper": "n",
  6234. "FOR_Mammoth": "y",
  6235. "FOR_Veh_VS_Inf": "o",
  6236. "FOR_Veh_VS_Veh": "s",
  6237. "FOR_Veh_VS_Air": "u",
  6238. "FOR_Turret_VS_Inf": "m",
  6239. "FOR_Turret_VS_Inf_ranged": "a",
  6240. "FOR_Turret_VS_Veh": "v",
  6241. "FOR_Turret_VS_Veh_ranged": "d",
  6242. "FOR_Turret_VS_Air": "f",
  6243. "FOR_Turret_VS_Air_ranged": "e",
  6244.  
  6245. /* GDI Offense Units */"GDI_APC Guardian": "g",
  6246. "GDI_Commando": "c",
  6247. "GDI_Firehawk": "f",
  6248. "GDI_Juggernaut": "j",
  6249. "GDI_Kodiak": "k",
  6250. "GDI_Mammoth": "m",
  6251. "GDI_Missile Squad": "q",
  6252. "GDI_Orca": "o",
  6253. "GDI_Paladin": "a",
  6254. "GDI_Pitbull": "p",
  6255. "GDI_Predator": "d",
  6256. "GDI_Riflemen": "r",
  6257. "GDI_Sniper Team": "s",
  6258. "GDI_Zone Trooper": "z",
  6259.  
  6260. /* Nod Offense Units */"NOD_Attack Bike": "b",
  6261. "NOD_Avatar": "a",
  6262. "NOD_Black Hand": "z",
  6263. "NOD_Cobra": "r",
  6264. "NOD_Commando": "c",
  6265. "NOD_Confessor": "s",
  6266. "NOD_Militant Rocket Soldiers": "q",
  6267. "NOD_Militants": "m",
  6268. "NOD_Reckoner": "k",
  6269. "NOD_Salamander": "l",
  6270. "NOD_Scorpion Tank": "o",
  6271. "NOD_Specter Artilery": "p",
  6272. "NOD_Venom": "v",
  6273. "NOD_Vertigo": "t",
  6274.  
  6275. "<last>": "."
  6276. },
  6277. make_sharelink: function () {
  6278. try {
  6279. var selected_base = cncopt.selected_base;
  6280. var city_id = selected_base.get_Id();
  6281. var city = ClientLib.Data.MainData.GetInstance().get_Cities().GetCity(city_id);
  6282. var own_city = ClientLib.Data.MainData.GetInstance().get_Cities().get_CurrentOwnCity();
  6283. var alliance = ClientLib.Data.MainData.GetInstance().get_Alliance();
  6284. var server = ClientLib.Data.MainData.GetInstance().get_Server();
  6285. var doLinkCity = (city.get_CityFaction() > 2 ? own_city.get_CityFaction() : city.get_CityFaction());
  6286. var doCity = (city.get_CityFaction() > 2 ? own_city : city);
  6287. tbase = selected_base;
  6288. tcity = city;
  6289. scity = own_city;
  6290. //console.log("Target City: ", city);
  6291. //console.log("Own City: ", own_city);
  6292. var link = "http://cncopt.com/?map=";
  6293. link += "3|"; /* link version */
  6294. switch (city.get_CityFaction()) {
  6295. case 1:
  6296. /* GDI */
  6297. link += "G|";
  6298. break;
  6299. case 2:
  6300. /* NOD */
  6301. link += "N|";
  6302. break;
  6303. case 3:
  6304. /* FOR faction - unseen, but in GAMEDATA */
  6305. case 4:
  6306. /* Forgotten Bases */
  6307. case 5:
  6308. /* Forgotten Camps */
  6309. case 6:
  6310. /* Forgotten Outposts */
  6311. link += "F|";
  6312. break;
  6313. default:
  6314. console.log("cncopt: Unknown faction: " + city.get_CityFaction());
  6315. link += "E|";
  6316. break;
  6317. }
  6318. //switch (own_city.get_CityFaction()) {
  6319. switch (doLinkCity) {
  6320. case 1:
  6321. /* GDI */
  6322. link += "G|";
  6323. break;
  6324. case 2:
  6325. /* NOD */
  6326. link += "N|";
  6327. break;
  6328. case 3:
  6329. /* FOR faction - unseen, but in GAMEDATA */
  6330. case 4:
  6331. /* Forgotten Bases */
  6332. case 5:
  6333. /* Forgotten Camps */
  6334. case 6:
  6335. /* Forgotten Outposts */
  6336. link += "F|";
  6337. break;
  6338. default:
  6339. console.log("cncopt: Unknown faction: " + own_city.get_CityFaction());
  6340. link += "E|";
  6341. break;
  6342. }
  6343. link += city.get_Name() + "|";
  6344. defense_units = []
  6345. for (var i = 0; i < 20; ++i) {
  6346. var col = [];
  6347. for (var j = 0; j < 9; ++j) {
  6348. col.push(null);
  6349. }
  6350. defense_units.push(col)
  6351. }
  6352. var defense_unit_list = getDefenseUnits(city);
  6353. if (PerforceChangelist >= 376877) {
  6354. for (var i in defense_unit_list) {
  6355. var unit = defense_unit_list[i];
  6356. defense_units[unit.get_CoordX()][unit.get_CoordY() + 8] = unit;
  6357. }
  6358. } else {
  6359. for (var i = 0; i < defense_unit_list.length; ++i) {
  6360. var unit = defense_unit_list[i];
  6361. defense_units[unit.get_CoordX()][unit.get_CoordY() + 8] = unit;
  6362. }
  6363. }
  6364.  
  6365. offense_units = []
  6366. for (var i = 0; i < 20; ++i) {
  6367. var col = [];
  6368. for (var j = 0; j < 9; ++j) {
  6369. col.push(null);
  6370. }
  6371. offense_units.push(col)
  6372. }
  6373.  
  6374. //var offense_unit_list = getOffenseUnits(own_city);
  6375. var offense_unit_list = getOffenseUnits(doCity);
  6376. if (PerforceChangelist >= 376877) {
  6377. for (var i in offense_unit_list) {
  6378. var unit = offense_unit_list[i];
  6379. offense_units[unit.get_CoordX()][unit.get_CoordY() + 16] = unit;
  6380. }
  6381. } else {
  6382. for (var i = 0; i < offense_unit_list.length; ++i) {
  6383. var unit = offense_unit_list[i];
  6384. offense_units[unit.get_CoordX()][unit.get_CoordY() + 16] = unit;
  6385. }
  6386. }
  6387.  
  6388. var techLayout = findTechLayout(city);
  6389. var buildings = findBuildings(city);
  6390. for (var i = 0; i < 20; ++i) {
  6391. row = [];
  6392. for (var j = 0; j < 9; ++j) {
  6393. var spot = i > 16 ? null : techLayout[j][i];
  6394. var level = 0;
  6395. var building = null;
  6396. if (spot && spot.BuildingIndex >= 0) {
  6397. building = buildings[spot.BuildingIndex];
  6398. level = building.get_CurrentLevel();
  6399. }
  6400. var defense_unit = defense_units[j][i];
  6401. if (defense_unit) {
  6402. level = defense_unit.get_CurrentLevel();
  6403. }
  6404. var offense_unit = offense_units[j][i];
  6405. if (offense_unit) {
  6406. level = offense_unit.get_CurrentLevel();
  6407. }
  6408. if (level > 1) {
  6409. link += level;
  6410. }
  6411.  
  6412. switch (i > 16 ? 0 : city.GetResourceType(j, i)) {
  6413. case 0:
  6414. if (building) {
  6415. var techId = building.get_MdbBuildingId();
  6416. if (GAMEDATA.Tech[techId].n in cncopt.keymap) {
  6417. link += cncopt.keymap[GAMEDATA.Tech[techId].n];
  6418. } else {
  6419. console.log("cncopt [5]: Unhandled building: " + techId, building);
  6420. link += ".";
  6421. }
  6422. } else if (defense_unit) {
  6423. if (defense_unit.get_UnitGameData_Obj().n in cncopt.keymap) {
  6424. link += cncopt.keymap[defense_unit.get_UnitGameData_Obj().n];
  6425. } else {
  6426. console.log("cncopt [5]: Unhandled unit: " + defense_unit.get_UnitGameData_Obj().n);
  6427. link += ".";
  6428. }
  6429. } else if (offense_unit) {
  6430. if (offense_unit.get_UnitGameData_Obj().n in cncopt.keymap) {
  6431. link += cncopt.keymap[offense_unit.get_UnitGameData_Obj().n];
  6432. } else {
  6433. console.log("cncopt [5]: Unhandled unit: " + offense_unit.get_UnitGameData_Obj().n);
  6434. link += ".";
  6435. }
  6436. } else {
  6437. link += ".";
  6438. }
  6439. break;
  6440. case 1:
  6441. /* Crystal */
  6442. if (spot.BuildingIndex < 0) link += "c";
  6443. else link += "n";
  6444. break;
  6445. case 2:
  6446. /* Tiberium */
  6447. if (spot.BuildingIndex < 0) link += "t";
  6448. else link += "h";
  6449. break;
  6450. case 4:
  6451. /* Woods */
  6452. link += "j";
  6453. break;
  6454. case 5:
  6455. /* Scrub */
  6456. link += "h";
  6457. break;
  6458. case 6:
  6459. /* Oil */
  6460. link += "l";
  6461. break;
  6462. case 7:
  6463. /* Swamp */
  6464. link += "k";
  6465. break;
  6466. default:
  6467. console.log("cncopt [4]: Unhandled resource type: " + city.GetResourceType(j, i));
  6468. link += ".";
  6469. break;
  6470. }
  6471. }
  6472. }
  6473. /* Tack on our alliance bonuses */
  6474. if (alliance && scity.get_AllianceId() == tcity.get_AllianceId()) {
  6475. link += "|" + alliance.get_POITiberiumBonus();
  6476. link += "|" + alliance.get_POICrystalBonus();
  6477. link += "|" + alliance.get_POIPowerBonus();
  6478. link += "|" + alliance.get_POIInfantryBonus();
  6479. link += "|" + alliance.get_POIVehicleBonus();
  6480. link += "|" + alliance.get_POIAirBonus();
  6481. link += "|" + alliance.get_POIDefenseBonus();
  6482. }
  6483. if (server.get_TechLevelUpgradeFactorBonusAmount() != 1.20) {
  6484. link += "|newEconomy";
  6485. }
  6486.  
  6487. //console.log(link);
  6488. window.open(link, "_blank");
  6489. } catch (e) {
  6490. console.log("cncopt [1]: ", e);
  6491. }
  6492. }
  6493. };
  6494. if (!webfrontend.gui.region.RegionCityMenu.prototype.__cncopt_real_showMenu) {
  6495. webfrontend.gui.region.RegionCityMenu.prototype.__cncopt_real_showMenu = webfrontend.gui.region.RegionCityMenu.prototype.showMenu;
  6496. }
  6497.  
  6498. var check_ct = 0;
  6499. var check_timer = null;
  6500. var button_enabled = 123456;
  6501. /* Wrap showMenu so we can inject our Sharelink at the end of menus and
  6502. * sync Base object to our cncopt.selected_base variable */
  6503. webfrontend.gui.region.RegionCityMenu.prototype.showMenu = function (selected_base) {
  6504. try {
  6505. var self = this;
  6506. //console.log(selected_base);
  6507. cncopt.selected_base = selected_base;
  6508. if (this.__cncopt_initialized != 1) {
  6509. this.__cncopt_initialized = 1;
  6510. this.__cncopt_links = [];
  6511. for (var i in this) {
  6512. try {
  6513. if (this[i] && this[i].basename == "Composite") {
  6514. var link = new qx.ui.form.Button("CNCOpt", "http://cncopt.com/favicon.ico");
  6515. link.addListener("execute", function () {
  6516. var bt = qx.core.Init.getApplication();
  6517. bt.getBackgroundArea().closeCityInfo();
  6518. cncopt.make_sharelink();
  6519. });
  6520. this[i].add(link);
  6521. this.__cncopt_links.push(link)
  6522. }
  6523. } catch (e) {
  6524. console.log("cncopt [2]: ", e);
  6525. }
  6526. }
  6527. }
  6528. var tf = false;
  6529. switch (selected_base.get_VisObjectType()) {
  6530. case ClientLib.Vis.VisObject.EObjectType.RegionCityType:
  6531. switch (selected_base.get_Type()) {
  6532. case ClientLib.Vis.Region.RegionCity.ERegionCityType.Own:
  6533. tf = true;
  6534. break;
  6535. case ClientLib.Vis.Region.RegionCity.ERegionCityType.Alliance:
  6536. case ClientLib.Vis.Region.RegionCity.ERegionCityType.Enemy:
  6537. tf = true;
  6538. break;
  6539. }
  6540. break;
  6541. case ClientLib.Vis.VisObject.EObjectType.RegionGhostCity:
  6542. tf = false;
  6543. console.log("cncopt: Ghost City selected.. ignoring because we don't know what to do here");
  6544. break;
  6545. case ClientLib.Vis.VisObject.EObjectType.RegionNPCBase:
  6546. tf = true;
  6547. break;
  6548. case ClientLib.Vis.VisObject.EObjectType.RegionNPCCamp:
  6549. tf = true;
  6550. break;
  6551. }
  6552.  
  6553. var orig_tf = tf;
  6554.  
  6555. function check_if_button_should_be_enabled() {
  6556. try {
  6557. tf = orig_tf;
  6558. var selected_base = cncopt.selected_base;
  6559. var still_loading = false;
  6560. if (check_timer != null) {
  6561. clearTimeout(check_timer);
  6562. }
  6563.  
  6564. /* When a city is selected, the data for the city is loaded in the background.. once the
  6565. * data arrives, this method is called again with these fields set, but until it does
  6566. * we can't actually generate the link.. so this section of the code grays out the button
  6567. * until the data is ready, then it'll light up. */
  6568. if (selected_base && selected_base.get_Id) {
  6569. var city_id = selected_base.get_Id();
  6570. var city = ClientLib.Data.MainData.GetInstance().get_Cities().GetCity(city_id);
  6571. //if (!city || !city.m_CityUnits || !city.m_CityUnits.m_DefenseUnits) {
  6572. //console.log("City", city);
  6573. //console.log("get_OwnerId", city.get_OwnerId());
  6574. if (!city || city.get_OwnerId() == 0) {
  6575. still_loading = true;
  6576. tf = false;
  6577. }
  6578. } else {
  6579. tf = false;
  6580. }
  6581. if (tf != button_enabled) {
  6582. button_enabled = tf;
  6583. for (var i = 0; i < self.__cncopt_links.length; ++i) {
  6584. self.__cncopt_links[i].setEnabled(tf);
  6585. }
  6586. }
  6587. if (!still_loading) {
  6588. check_ct = 0;
  6589. } else {
  6590. if (check_ct > 0) {
  6591. check_ct--;
  6592. check_timer = setTimeout(check_if_button_should_be_enabled, 100);
  6593. } else {
  6594. check_timer = null;
  6595. }
  6596. }
  6597. } catch (e) {
  6598. console.log("cncopt [3]: ", e);
  6599. tf = false;
  6600. }
  6601. }
  6602.  
  6603. check_ct = 50;
  6604. check_if_button_should_be_enabled();
  6605. } catch (e) {
  6606. console.log("cncopt [3]: ", e);
  6607. }
  6608. this.__cncopt_real_showMenu(selected_base);
  6609. }
  6610. }
  6611.  
  6612.  
  6613. /* Nice load check (ripped from AmpliDude's LoU Tweak script) */
  6614. function cnc_check_if_loaded() {
  6615. try {
  6616. if (typeof qx != 'undefined') {
  6617. a = qx.core.Init.getApplication(); // application
  6618. if (a) {
  6619. cncopt_create();
  6620. } else {
  6621. window.setTimeout(cnc_check_if_loaded, 1000);
  6622. }
  6623. } else {
  6624. window.setTimeout(cnc_check_if_loaded, 1000);
  6625. }
  6626. } catch (e) {
  6627. if (typeof console != 'undefined') console.log(e);
  6628. else if (window.opera) opera.postError(e);
  6629. else GM_log(e);
  6630. }
  6631. }
  6632. if (/commandandconquer\.com/i.test(document.domain)) window.setTimeout(cnc_check_if_loaded, 1000);
  6633. }
  6634.  
  6635. // injecting because we can't seem to hook into the game interface via unsafeWindow
  6636. // (Ripped from AmpliDude's LoU Tweak script)
  6637. var script_block = document.createElement("script");
  6638. txt = cncopt_main.toString();
  6639. script_block.innerHTML = "(" + txt + ")();";
  6640. script_block.type = "text/javascript";
  6641. if (/commandandconquer\.com/i.test(document.domain)) document.getElementsByTagName("head")[0].appendChild(script_block);
  6642. })();
  6643. } catch (e) {
  6644. GM_log(e);
  6645. }
  6646.  
  6647.  
  6648. /***********************************************************************************
  6649. Tiberium Alliances Transfer All Resources
  6650. ***********************************************************************************/
  6651. // ==UserScript==
  6652. // @name Tiberium Alliances Transfer All Resources
  6653. // @description Integrates a transfer all feature into the transfer window.
  6654. // @namespace transfer_all
  6655. // @include https://prodgame*.alliances.commandandconquer.com/*/index.aspx*
  6656. // @version 1.6.1
  6657. // @author KRS_L
  6658. // @updateURL https://userscripts.org/scripts/source/158164.meta.js
  6659. // @downloadURL https://userscripts.org/scripts/source/158164.user.js
  6660. // ==/UserScript==
  6661. (function () {
  6662. var TransferAll_main = function () {
  6663. var chkbxConfirm = null;
  6664. var resTypeToggle = null;
  6665. var transferQueue = null;
  6666. var transferWindow = null;
  6667. var retry = null;
  6668. var resType = null;
  6669. var resAmount = null;
  6670.  
  6671. function createTransferAll() {
  6672. try {
  6673. console.log('TransferAll loaded');
  6674. chkbxConfirm = new qx.ui.form.CheckBox("");
  6675. transferWindow = webfrontend.gui.trade.TradeOverlay.getInstance().getLayoutChildren()[13].getLayoutChildren()[1].getLayout()._getLayoutChildren();
  6676. resTypeToggle = transferWindow[1].getLayoutChildren()[2];
  6677. var btnTransferAll=new webfrontend.ui.SoundButton("Transfer All").set({width:80,enabled:false});
  6678.  
  6679. chkbxConfirm.addListener("changeValue", function () {
  6680. btnTransferAll.setEnabled(chkbxConfirm.getValue());
  6681. if (chkbxConfirm.getValue()) performAction('costCalculation');
  6682. }, this);
  6683.  
  6684. resTypeToggle.addListener("changeValue", function () {
  6685. chkbxConfirm.setValue(false);
  6686. }, this);
  6687.  
  6688. btnTransferAll.addListener("click", function () {
  6689. performAction('transfer');
  6690. }, this);
  6691.  
  6692. transferWindow[3].add(btnTransferAll,{right:2,top:100});
  6693. transferWindow[3].add(chkbxConfirm,{right:68,top:104});
  6694. } catch (e) {
  6695. console.log("createTransferAll: ", e);
  6696. }
  6697. }
  6698.  
  6699. function performAction(action) {
  6700. try {
  6701. var cities = ClientLib.Data.MainData.GetInstance().get_Cities();
  6702. var ownCity = cities.get_CurrentOwnCity();
  6703. var allCities = cities.get_AllCities().d;
  6704. var isTiberium = resTypeToggle.getValue();
  6705. var costLabel = transferWindow[3].getLayoutChildren()[1].getLayoutChildren()[1].getLayoutChildren()[2];
  6706. resType = ClientLib.Base.EResourceType.Crystal;
  6707. var transferCost = 0;
  6708. resAmount;
  6709. if (isTiberium) resType = ClientLib.Base.EResourceType.Tiberium;
  6710. var item = [];
  6711. transferQueue = [];
  6712.  
  6713. for (var sourceCity in allCities) {
  6714. if (sourceCity == ownCity.get_Id()) continue;
  6715. resAmount = Math.floor(allCities[sourceCity].GetResourceCount(resType));
  6716. if (allCities[sourceCity].CanTrade() == ClientLib.Data.ETradeError.None && ownCity.CanTrade() == ClientLib.Data.ETradeError.None) {
  6717. if (action == 'transfer') {
  6718. item = [ownCity,allCities[sourceCity],resType,resAmount];
  6719. transferQueue.push(item);
  6720. }
  6721. if (action == 'costCalculation') transferCost += allCities[sourceCity].CalculateTradeCostToCoord(ownCity.get_PosX(), ownCity.get_PosY(), resAmount);
  6722. }
  6723. }
  6724. if (action == 'transfer') {
  6725. chkbxConfirm.setValue(false);
  6726. retry = false;
  6727. transfer();
  6728. }
  6729. if (action == 'costCalculation') {
  6730. costLabel.setValue(phe.cnc.gui.util.Numbers.formatNumbersCompactAfterMillion(transferCost));
  6731. if (transferCost > ClientLib.Data.MainData.GetInstance().get_Player().GetCreditsCount()) costLabel.setTextColor("red");
  6732. }
  6733. } catch (e) {
  6734. console.log("performAction: ", e);
  6735. }
  6736. }
  6737.  
  6738. function transfer() {
  6739. try {
  6740. if (transferQueue.length > 0) {
  6741. var targetCity = transferQueue[0][0];
  6742. var sourceCity = transferQueue[0][1];
  6743. resType = transferQueue[0][2];
  6744. resAmount = transferQueue[0][3];
  6745. ClientLib.Net.CommunicationManager.GetInstance().SendCommand ("SelfTrade",{targetCityId:targetCity.get_Id(),sourceCityId:sourceCity.get_Id(),resourceType:resType,amount:resAmount}, phe.cnc.Util.createEventDelegate(ClientLib.Net.CommandResult, this, transferResult), null, true);
  6746. }
  6747. } catch (e) {
  6748. console.log("transfer: ", e);
  6749. }
  6750. }
  6751.  
  6752. function transferResult(context, result) {
  6753. try {
  6754. if (result != 0 && retry == false) {
  6755. retry = true;
  6756. transfer();
  6757. } else {
  6758. transferQueue.splice(0,1);
  6759. retry = false;
  6760. transfer();
  6761. }
  6762. } catch (e) {
  6763. console.log("transferResult: ", e);
  6764. }
  6765. }
  6766.  
  6767. function TransferAll_checkIfLoaded() {
  6768. try {
  6769. if (typeof qx !== 'undefined') {
  6770. if (ClientLib.Data.MainData.GetInstance().get_Player().get_Faction() !== null) {
  6771. createTransferAll();
  6772. } else {
  6773. window.setTimeout(TransferAll_checkIfLoaded, 1000);
  6774. }
  6775. } else {
  6776. window.setTimeout(TransferAll_checkIfLoaded, 1000);
  6777. }
  6778. } catch (e) {
  6779. console.log("TransferAll_checkIfLoaded: ", e);
  6780. }
  6781. }
  6782.  
  6783. if (/commandandconquer\.com/i.test(document.domain)) {
  6784. window.setTimeout(TransferAll_checkIfLoaded, 1000);
  6785. }
  6786. };
  6787.  
  6788. try {
  6789. var TransferAll = document.createElement("script");
  6790. TransferAll.innerHTML = "(" + TransferAll_main.toString() + ")();";
  6791. TransferAll.type = "text/javascript";
  6792. if (/commandandconquer\.com/i.test(document.domain)) {
  6793. document.getElementsByTagName("head")[0].appendChild(TransferAll);
  6794. }
  6795. } catch (e) {
  6796. console.log("TransferAll: init error: ", e);
  6797. }
  6798. })();
  6799.  
  6800.  
  6801. /***********************************************************************************
  6802. C&C: Tiberium Alliances Map
  6803. ***********************************************************************************/
  6804. // ==UserScript==
  6805. // @name Command & Conquer TA World Map
  6806. // @description Creates a detailed map of bases and pois of the alliance and enemies.
  6807. // @namespace https://prodgame*.alliances.commandandconquer.com/*/index.aspx*
  6808. // @include https://prodgame*.alliances.commandandconquer.com/*/index.aspx*
  6809. // @version 1.0.0
  6810. // @grant none
  6811. // @author zdoom
  6812. // @updateURL https://userscripts.org/scripts/source/173330.meta.js
  6813. // @downloadURL https://userscripts.org/scripts/source/173330.user.js
  6814. // ==/UserScript==
  6815.  
  6816. (function(){
  6817.  
  6818. var injectScript = function()
  6819. {
  6820. function create_ccta_map_class()
  6821. {
  6822. qx.Class.define("ccta_map",
  6823. {
  6824. type: "singleton",
  6825. extend: qx.core.Object,
  6826. construct: function()
  6827. {
  6828. try
  6829. {
  6830. var root = this;
  6831. var mapButton = new qx.ui.form.Button('Map').set({ enabled: false });
  6832. var app = qx.core.Init.getApplication();
  6833. var optionsBar = app.getOptionsBar().getLayoutParent();
  6834. this.__mapButton = mapButton;
  6835. optionsBar.getChildren()[0].getChildren()[2].addAt(mapButton,1);
  6836. var onReady = function()
  6837. {
  6838. console.log('checking if data is ready');
  6839. var alliance = ClientLib.Data.MainData.GetInstance().get_Alliance().get_Relationships;
  6840. var world = ClientLib.Data.MainData.GetInstance().get_World();
  6841. var endGame = ClientLib.Data.MainData.GetInstance().get_EndGame().get_Hubs().d;
  6842. var command = ClientLib.Net.CommunicationManager.GetInstance().SendSimpleCommand;
  6843. var delegate = phe.cnc.Util.createEventDelegate;
  6844. if(!!alliance && !!world && !!command && !!delegate && !!endGame)
  6845. {
  6846. var worldWidth = world.get_WorldWidth();
  6847. if(!worldWidth) return;
  6848. var factor = 500 / worldWidth;
  6849. var hubs = [], fortress = [];
  6850. for (var index in endGame)
  6851. {
  6852. var currentHub = endGame[index];
  6853. if (currentHub.get_Type() == 1) hubs.push([(currentHub.get_X() + 2) * factor, (currentHub.get_Y() + 2) * factor]);
  6854. if (currentHub.get_Type() == 3) fortress = [(currentHub.get_X() + 2) * factor, (currentHub.get_Y() + 2) * factor];
  6855. }
  6856. if (hubs.length > 0)
  6857. {
  6858. timer.stop();
  6859. root.__factor = factor;
  6860. root.__endGame['hubs'] = hubs;
  6861. root.__endGame['fortress'] = fortress;
  6862. root.__init();
  6863. }
  6864. console.log(hubs);
  6865. }
  6866. console.log(!!alliance, !!world, !!command, !!delegate, !!endGame);
  6867. };
  6868. var timer = new qx.event.Timer(1000);
  6869. timer.addListener('interval', onReady, this);
  6870. timer.start();
  6871. }
  6872. catch(e)
  6873. {
  6874. console.log(e.toString());
  6875. }
  6876. console.log('ccta_map initialization completed');
  6877. },
  6878. destruct: function(){},
  6879. members:
  6880. {
  6881. __mapButton: null,
  6882. __allianceExist: null,
  6883. __allianceName: null,
  6884. __allianceId: null,
  6885. __allianceHasRelations: false,
  6886. __defaultAlliances: null,
  6887. __selectedAlliances: null,
  6888. __data: null,
  6889. __totalProcesses: null,
  6890. __completedProcesses: 0,
  6891. __endGame: {},
  6892. __isLoading: false,
  6893. __factor: null,
  6894. __init: function()
  6895. {
  6896. try
  6897. {
  6898. var root = this;
  6899. var data = ClientLib.Data.MainData.GetInstance();
  6900. var alliance_data = data.get_Alliance();
  6901. var alliance_exists = alliance_data.get_Exists();
  6902. if(alliance_exists)
  6903. {
  6904. var alliance_name = alliance_data.get_Name();
  6905. var alliance_id = alliance_data.get_Id();
  6906. var alliance_relations = alliance_data.get_Relationships();
  6907. this.__allianceExist = true;
  6908. this.__allianceId = alliance_id;
  6909. this.__allianceName = alliance_name;
  6910. var selectedAlliancesList = [];
  6911. selectedAlliancesList[0] = [alliance_id, 'alliance', alliance_name, 0];
  6912. if (alliance_relations != null)
  6913. {
  6914. this.__allianceHasRelations = true;
  6915. alliance_relations.map(function(x)
  6916. {
  6917. var type = x.Relationship, id = x.OtherAllianceId, name = x.OtherAllianceName;
  6918. if ((type == 3) && (selectedAlliancesList.length < 9)) selectedAlliancesList.push([id, 'enemy', name, 0]);
  6919. });
  6920. }
  6921. this.__defaultAlliances = selectedAlliancesList;
  6922. }
  6923. else
  6924. {
  6925. this.__allianceExist = false;
  6926. }
  6927. if (typeof(Storage) !== 'undefined' && typeof(localStorage.ccta_map_settings) !== 'undefined')
  6928. {
  6929. this.__selectedAlliances = JSON.parse(localStorage.ccta_map_settings);
  6930. }
  6931. this.__mapButton.setEnabled(true);
  6932. this.__mapButton.addListener('execute', function()
  6933. {
  6934. root.getData();
  6935. ccta_map.container.getInstance().open(1);
  6936. }, this);
  6937. }
  6938. catch(e)
  6939. {
  6940. console.log(e.toString());
  6941. }
  6942. },
  6943. getData: function()
  6944. {
  6945. if (this.__isLoading === true) return;
  6946. this.__isLoading = true;
  6947. var arr = (this.__selectedAlliances == null) ? this.__defaultAlliances : this.__selectedAlliances;
  6948. if(arr != null)
  6949. {
  6950. this.__data = [];
  6951. this.__totalProcesses = arr.length;
  6952. for(var i = 0; i < arr.length; i++)
  6953. {
  6954. this.__getAlliance(arr[i][0], arr[i][1], arr[i][3]);
  6955. }
  6956. }
  6957. },
  6958. __getAlliance: function(aid, type, color)
  6959. {
  6960. try
  6961. {
  6962. var alliance = {}, root = this, factor = this.__factor;
  6963. alliance.id = aid;
  6964. alliance.players = {};
  6965. var totalProcesses = this.__totalProcesses;
  6966. var getBases = function(pid, pn, p, tp)
  6967. {
  6968. ClientLib.Net.CommunicationManager.GetInstance().SendSimpleCommand("GetPublicPlayerInfo", { id: pid },
  6969. phe.cnc.Util.createEventDelegate(ClientLib.Net.CommandResult, this, function(context, data)
  6970. {
  6971. if (data.c != null)
  6972. {
  6973. var totalBases = data.c.length;
  6974. var player = {};
  6975. var bases = [];
  6976. for (var b = 0; b < data.c.length; b++)
  6977. {
  6978. var id = data.c[b].i;
  6979. var name = data.c[b].n;
  6980. var x = data.c[b].x * factor;
  6981. var y = data.c[b].y * factor;
  6982. bases.push([x, y, name, id]);
  6983. if((p == tp - 1) && (b == totalBases - 1))
  6984. {
  6985. root.__completedProcesses++;
  6986. var loader = ccta_map.container.getInstance().loader;
  6987. loader.setValue('Loading: ' + root.__completedProcesses + "/" + totalProcesses);
  6988. }
  6989. if(root.__completedProcesses == totalProcesses) root.__onProcessComplete();
  6990. }
  6991. player.id = pid;
  6992. player.name = pn;
  6993. player.bases = bases;
  6994. alliance.players[pn] = player;
  6995. }
  6996. }), null);
  6997. };
  6998. ClientLib.Net.CommunicationManager.GetInstance().SendSimpleCommand("GetPublicAllianceInfo", { id: aid },
  6999. phe.cnc.Util.createEventDelegate(ClientLib.Net.CommandResult, this, function(context, data)
  7000. {
  7001. if (data == null) return;
  7002. if (data.opois != null)
  7003. {
  7004. var pois = [];
  7005. data.opois.map(function(poi)
  7006. {
  7007. pois.push({'i': poi.i, 'l': poi.l, 't': poi.t, 'x': poi.x * factor, 'y': poi.y * factor});
  7008. });
  7009. alliance.pois = pois;
  7010. }
  7011. if (data.n != null) alliance.name = data.n;
  7012. if (data.m != null)
  7013. {
  7014. for (var p = 0; p < data.m.length; p++)
  7015. {
  7016. var playerName = data.m[p].n;
  7017. var playerId = data.m[p].i;
  7018. getBases(playerId, playerName, p, data.m.length);
  7019. }
  7020. root.__data.push([alliance, type, color]);
  7021. }
  7022. }), null);
  7023. }
  7024. catch(e)
  7025. {
  7026. console.log(e.toString());
  7027. }
  7028. },
  7029. __onProcessComplete: function()
  7030. {
  7031. console.log('process completed - alliances data has been generated', this.__data);
  7032. this.__isLoading = false;
  7033. var win = ccta_map.container.getInstance();
  7034. win.receivedData = this.__data;
  7035. win.__updateList();
  7036. win.drawCanvas();
  7037. win.loader.setValue('Completed');
  7038. this.__totalProcess = null;
  7039. this.__completedProcesses = 0;
  7040. setTimeout(function(){
  7041. win.loader.setValue('');
  7042. }, 3000);
  7043. }
  7044. }
  7045. });
  7046. qx.Class.define("ccta_map.container",
  7047. {
  7048. type: "singleton",
  7049. extend: qx.ui.container.Composite,
  7050. construct: function()
  7051. {
  7052. try
  7053. {
  7054. this.base(arguments);
  7055. var layout = new qx.ui.layout.Canvas();
  7056. this._setLayout(layout);
  7057. var worldWidth = ClientLib.Data.MainData.GetInstance().get_World().get_WorldWidth();
  7058. var factor = 500 / worldWidth;
  7059. this.__factor = factor;
  7060. var zoomIn = new qx.ui.form.Button('+').set({ width: 30 });
  7061. var zoomOut = new qx.ui.form.Button('-').set({ width: 30, enabled: false });
  7062. var zoomReset = new qx.ui.form.Button('R').set({ width: 30, enabled: false });
  7063. var grid = new qx.ui.container.Composite(new qx.ui.layout.Grid(3,1));
  7064. var info = new qx.ui.container.Composite(new qx.ui.layout.VBox()).set({ minHeight: 300, padding: 10 });
  7065. var canvasContainer = new qx.ui.container.Composite(new qx.ui.layout.VBox());
  7066. var rightBar = new qx.ui.container.Composite(new qx.ui.layout.VBox(10));
  7067. var leftBar = new qx.ui.container.Composite(new qx.ui.layout.VBox(10));
  7068. var widget = new qx.ui.core.Widget().set({ width: 500, height: 500 });
  7069. var div = new qx.html.Element('div', null, {id: 'canvasContainer'});
  7070. var li1 = new qx.ui.form.ListItem('All', null, "all");
  7071. var li2 = new qx.ui.form.ListItem('My Bases', null, "bases");
  7072. var li3 = new qx.ui.form.ListItem('My Alliance', null, "alliance");
  7073. var li4 = new qx.ui.form.ListItem('Selected', null, "selected");
  7074. var displayMode = new qx.ui.form.SelectBox().set({ height: 28 });
  7075. displayMode.add(li1);
  7076. displayMode.add(li2);
  7077. displayMode.add(li3);
  7078. displayMode.add(li4);
  7079. var zoomBar = new qx.ui.container.Composite(new qx.ui.layout.HBox(15));
  7080. var bothOpt = new qx.ui.form.RadioButton('Both').set({ model: "both" });
  7081. var basesOpt = new qx.ui.form.RadioButton('Base').set({ model: "bases" });;
  7082. var poisOpt = new qx.ui.form.RadioButton('Poi').set({ model: "pois" });
  7083. var displayOptions = new qx.ui.form.RadioButtonGroup().set({ layout: new qx.ui.layout.HBox(), font :'font_size_11' });
  7084. displayOptions.add(bothOpt);
  7085. displayOptions.add(basesOpt);
  7086. displayOptions.add(poisOpt);
  7087. var allianceList = new qx.ui.form.List().set({ font :'font_size_11', height: 215 });
  7088. var editAlliance = new qx.ui.form.Button('Edit Alliances');
  7089. var label = new qx.ui.basic.Label('Transparency');
  7090. var slider = new qx.ui.form.Slider().set({ minimum: 30, maximum: 100, value: 100 });
  7091. var coordsField = new qx.ui.form.TextField().set({maxWidth: 100, textAlign: 'center', readOnly: 'true', alignX: 'center'});
  7092. var loader = new qx.ui.basic.Label().set({ marginTop: 100 });
  7093. grid.set({ minWidth: 780, backgroundColor: '#8e979b', minHeight: 524, margin: 3, paddingTop: 10 });
  7094. rightBar.set({ maxWidth: 130, minWidth: 130, paddingTop: 30, paddingRight: 10 });
  7095. leftBar.set({ maxWidth: 130, minWidth: 130, paddingTop: 30, paddingLeft: 10 });
  7096. var hints = [[zoomIn,'Zoom in'], [zoomOut,'Zoom out'], [zoomReset,'Restet zoom'], [basesOpt,'Show bases only'] , [poisOpt,'Show POIs only'], [bothOpt,'Show bases and POIs']]
  7097. for(var i = 0; i < hints.length; i++)
  7098. {
  7099. var tooltip = new qx.ui.tooltip.ToolTip(hints[i][1]);
  7100. hints[i][0].setToolTip(tooltip);
  7101. }
  7102. zoomBar.add(zoomIn);
  7103. zoomBar.add(zoomOut);
  7104. zoomBar.add(zoomReset);
  7105. rightBar.add(zoomBar);
  7106. rightBar.add(displayMode);
  7107. rightBar.add(displayOptions);
  7108. rightBar.add(allianceList);
  7109. rightBar.add(editAlliance);
  7110. rightBar.add(label);
  7111. rightBar.add(slider);
  7112. leftBar.add(coordsField);
  7113. leftBar.add(info);
  7114. leftBar.add(loader);
  7115. canvasContainer.add(widget);
  7116. widget.getContentElement().add(div);
  7117. grid.add(leftBar, {row: 1, column: 1});
  7118. grid.add(rightBar, {row: 1, column: 3});
  7119. grid.add(canvasContainer, {row: 1, column: 2});
  7120. this.info = info;
  7121. this.coordsField = coordsField;
  7122. this.allianceList = allianceList;
  7123. this.panel = [zoomOut, zoomReset, zoomIn, displayOptions, displayMode, allianceList, editAlliance];
  7124. this.loader = loader;
  7125. this.zoomIn = zoomIn;
  7126. this.zoomOut = zoomOut;
  7127. this.zoomReset = zoomReset;
  7128. //canvas
  7129. var cont = document.createElement('div'),
  7130. mask = document.createElement('div'),
  7131. canvas = document.createElement('canvas'),
  7132. ctx = canvas.getContext("2d"),
  7133. root = this;
  7134. cont.style.width = '500px';
  7135. cont.style.height = '500px';
  7136. cont.style.position = 'absolute';
  7137. cont.style.overflow = 'hidden';
  7138. cont.style.backgroundColor = '#0b2833';
  7139. canvas.style.position = 'absolute';
  7140. canvas.style.backgroundColor = '#0b2833';
  7141. mask.style.position = 'absolute';
  7142. mask.style.width = '500px';
  7143. mask.style.height = '500px';
  7144. mask.style.background = 'url("http://archeikhmeri.co.uk/images/map_mask.png") center center no-repeat';
  7145. this.canvas = canvas;
  7146. this.mask = mask;
  7147. this.ctx = ctx;
  7148. var __zoomIn = function(){ if (root.scale < 12) root.__scaleMap('up') };
  7149. var __zoomOut = function(){if (root.scale > 1) root.__scaleMap('down') };
  7150. var __zoomReset = function()
  7151. {
  7152. canvas.width = 500;
  7153. canvas.height = 500;
  7154. canvas.style.left = 0;
  7155. canvas.style.top = 0;
  7156. root.scale = 1;
  7157. root.drawCanvas();
  7158. zoomIn.setEnabled(true);
  7159. zoomOut.setEnabled(false);
  7160. zoomReset.setEnabled(false);
  7161. };
  7162. cont.appendChild(canvas);
  7163. cont.appendChild(mask);
  7164. root.__draggable(mask);
  7165. root.resetMap();
  7166. slider.addListener('changeValue', function(e)
  7167. {
  7168. if (e.getData())
  7169. {
  7170. var val = e.getData() / 100;
  7171. this.setOpacity(val);
  7172. slider.setToolTipText(" " + val * 100 + "% ");
  7173. }
  7174. }, this);
  7175. allianceList.addListener('changeSelection', function(e)
  7176. {
  7177. if ((root.__displayM == "bases") || (root.__displayM == "alliance") || !e.getData()[0]) return;
  7178. var aid = e.getData()[0].getModel();
  7179. root.__selectedA = aid;
  7180. root.drawCanvas();
  7181. }, this);
  7182. displayMode.addListener('changeSelection', function(e)
  7183. {
  7184. var dm = e.getData()[0].getModel();
  7185. root.__displayM = dm;
  7186. root.__updateList();
  7187. if(dm == "bases")
  7188. {
  7189. displayOptions.setSelection([basesOpt]);
  7190. poisOpt.setEnabled(false);
  7191. bothOpt.setEnabled(false);
  7192. root.__displayO = "bases";
  7193. }
  7194. else
  7195. {
  7196. if(!poisOpt.isEnabled()) poisOpt.setEnabled(true);
  7197. if(!bothOpt.isEnabled()) bothOpt.setEnabled(true);
  7198. displayOptions.setSelection([bothOpt]);
  7199. root.__displayO = "both";
  7200. }
  7201. root.drawCanvas();
  7202. }, this);
  7203. displayOptions.addListener('changeSelection', function(e)
  7204. {
  7205. if (!e.getData()[0]) return;
  7206. var dop = e.getData()[0].getModel();
  7207. root.__displayO = dop;
  7208. root.drawCanvas();
  7209. }, this);
  7210. editAlliance.addListener('execute', function()
  7211. {
  7212. ccta_map.options.getInstance().open();
  7213. }, this);
  7214. var desktop = qx.core.Init.getApplication().getDesktop();
  7215. desktop.addListener('resize', this._onResize, this);
  7216. zoomIn.addListener('execute', __zoomIn, this);
  7217. zoomOut.addListener('execute', __zoomOut, this);
  7218. zoomReset.addListener('execute', __zoomReset, this);
  7219. this.add(grid);
  7220. this.wdgAnchor = new qx.ui.basic.Image("webfrontend/ui/common/frame_basewin/frame_basewindow_tl1.png").set({ width: 3, height: 32 });
  7221. this.__imgTopRightCorner = new qx.ui.basic.Image("webfrontend/ui/common/frame_basewin/frame_basewindow_tr.png").set({ width: 34, height: 35 });
  7222. this._add(this.__imgTopRightCorner, { right: 0, top: 0, bottom: 28 });
  7223. this._add(new qx.ui.basic.Image("webfrontend/ui/common/frame_basewin/frame_basewindow_r.png").set({ width: 3, height: 1, allowGrowY: true, scale: true }), { right: 0, top: 35, bottom: 29 });
  7224. this._add(new qx.ui.basic.Image("webfrontend/ui/common/frame_basewin/frame_basewindow_br.png").set({ width: 5, height: 28, allowGrowY: true, scale: true }), { right: 0, bottom: 0 });
  7225. this._add(new qx.ui.basic.Image("webfrontend/ui/common/frame_basewin/frame_basewindow_b.png").set({ width: 1, height: 3, allowGrowX: true, scale: true }), { right: 5, bottom: 0, left: 5 });
  7226. this._add(new qx.ui.basic.Image("webfrontend/ui/common/frame_basewin/frame_basewindow_bl.png").set({ width: 5, height: 29 }), { left: 0, bottom: 0 });
  7227. this._add(new qx.ui.basic.Image("webfrontend/ui/common/frame_basewin/frame_basewindow_l.png").set({ width: 3, height: 1, allowGrowY: true, scale: true }), { left: 0, bottom: 29, top: 32 });
  7228. this._add(this.wdgAnchor, { left: 0, top: 0 });
  7229. this._add(new qx.ui.basic.Image("webfrontend/ui/common/frame_basewin/frame_basewindow_tl2.png").set({ width: 25, height: 5 }), { left: 3, top: 0 });
  7230. this._add(new qx.ui.basic.Image("webfrontend/ui/common/frame_basewin/frame_basewindow_t.png").set({ width: 1, height: 3, allowGrowX: true, scale: true }), { left: 28, right: 34, top: 0 });
  7231. this.__btnClose = new webfrontend.ui.SoundButton(null, "FactionUI/icons/icon_close_button.png").set({ appearance: "button-close", width: 23, height: 23, toolTipText: this.tr("tnf:close base view") });
  7232. this.__btnClose.addListener("execute", this._onClose, this);
  7233. this._add(this.__btnClose, { top: 6, right: 5 });
  7234. var onLoaded = function()
  7235. {
  7236. var counter = 0;
  7237. var check = function()
  7238. {
  7239. if(counter > 60) return;
  7240. var htmlDiv = document.getElementById('canvasContainer');
  7241. (htmlDiv) ? htmlDiv.appendChild(cont) : setTimeout(check, 1000);
  7242. console.log('retrying check for canvasContainer is loaded');
  7243. counter++;
  7244. };
  7245. check();
  7246. };
  7247. onLoaded();
  7248. }
  7249. catch(e)
  7250. {
  7251. console.log(e.toString());
  7252. }
  7253. console.log('container creation completed');
  7254. },
  7255. destruct: function(){},
  7256. members:
  7257. {
  7258. info: null,
  7259. coordsField: null,
  7260. panel: null,
  7261. loader: null,
  7262. canvas: null,
  7263. mask: null,
  7264. ctx: null,
  7265. receivedData: null,
  7266. allianceList: null,
  7267. circles: [53, 85, 113, 145, 242],
  7268. scale: 1,
  7269. selectedBase: false,
  7270. elements: [],
  7271. locations: [],
  7272. inProgress: false,
  7273. isRadarVisible: false,
  7274. __interval: null,
  7275. __pointerX: null,
  7276. __pointerY: null,
  7277. __selectedA: null,
  7278. __selectedB: null,
  7279. __displayM: "all",
  7280. __displayO: "both",
  7281. __factor: null,
  7282. __setInfo: function(base)
  7283. {
  7284. try
  7285. {
  7286. // console.log(base);
  7287. var info = this.info;
  7288. info.removeAll();
  7289. if(!base) return;
  7290. for ( var i = 0; i < base.length; i++)
  7291. {
  7292. var title = new qx.ui.basic.Label(base[i][0]).set({font: 'font_size_13_bold', textColor: '#375773'});
  7293. var value = new qx.ui.basic.Label(base[i][1]).set({font: 'font_size_11', textColor: '#333333', marginBottom: 5});
  7294. info.add(title);
  7295. info.add(value);
  7296. }
  7297. }
  7298. catch(e)
  7299. {
  7300. console.log(e.toString());
  7301. }
  7302. },
  7303. __createLayout: function()
  7304. {
  7305. var s = this.scale, circles = this.circles, ctx = this.ctx;
  7306. for (var i = 0; i < circles.length; i++) {
  7307. var r = circles[i];
  7308. ctx.beginPath();
  7309. ctx.arc(250, 250, r, 0, Math.PI * 2, true);
  7310. ctx.lineWidth = (i == 4) ? 1/s : 0.3/s;
  7311. ctx.strokeStyle = '#8ce9ef';
  7312. ctx.stroke();
  7313. ctx.closePath();
  7314. }
  7315. for(var i = 0; i < 8; i++){
  7316. var r = circles[4], a = (Math.PI * i / 4) - Math.PI / 8;
  7317. ctx.beginPath();
  7318. ctx.moveTo(250,250);
  7319. ctx.lineTo((r * Math.cos(a)) + 250, (r * Math.sin(a)) + 250);
  7320. ctx.lineWidth = 0.3/s;
  7321. ctx.strokeStyle = '#8ce9ef';
  7322. ctx.stroke();
  7323. ctx.closePath();
  7324. }
  7325. var endGame = ccta_map.getInstance().__endGame, hubs = endGame.hubs, fortress = endGame.fortress;
  7326. var fortressX = fortress[0];
  7327. var fortressY = fortress[1];
  7328. var grd = ctx.createLinearGradient(fortressX, fortressY - 0.5, fortressX, fortressY + 0.5);
  7329. grd.addColorStop(0, 'rgba(200, 228, 228, 0.5)');
  7330. grd.addColorStop(1, 'rgba(170, 214, 118, 0.5)');
  7331. ctx.beginPath();
  7332. ctx.arc(fortressX - 0.2, fortressY - 0.2, 1, 0, Math.PI * 2, true);
  7333. ctx.fillStyle = grd;
  7334. ctx.lineWidth = 0.1;
  7335. ctx.strokeStyle = '#a5fe6a';
  7336. ctx.fill();
  7337. ctx.stroke();
  7338. ctx.closePath();
  7339. for(var i = 0; i < hubs.length; i++)
  7340. {
  7341. var c = 'rgba(200, 228, 228, 0.5)', d = 'rgba(170, 214, 118, 0.5)', l = 1.3, b = 0.1;
  7342. var x = hubs[i][0];
  7343. var y = hubs[i][1];
  7344. var grd = ctx.createLinearGradient(x, y, x, y+l);
  7345. grd.addColorStop(0, c);
  7346. grd.addColorStop(1, d);
  7347. ctx.beginPath();
  7348. ctx.rect(x-b, y-b, l, l);
  7349. ctx.fillStyle = grd;
  7350. ctx.fill();
  7351. ctx.strokeStyle = '#a5fe6a';
  7352. ctx.lineWidth = b;
  7353. ctx.stroke();
  7354. ctx.closePath();
  7355. }
  7356. },
  7357. __createAlliance: function(name, data, type, color)
  7358. {
  7359. try
  7360. {
  7361. this.inProgress = true;
  7362. var colors = {
  7363. "bases": {"alliance":[["#86d3fb","#75b7d9"]], "owner":[["#ffc48b","#d5a677"]], "enemy":[["#ff8e8b","#dc7a78"],['#e25050','#cc2d2d'],['#93b7f8','#527ef2'],['#d389aa','#b14e69']], "nap":[["#ffffff","#cccccc"]], "selected":[["#ffe50e", "#d7c109"]], "ally":[["#6ce272", "#5fc664"],['#d4e17e','#b3ca47'],['#92f8f2','#52f2e8'],['#1cba1c','#108510']]},
  7364. "pois": [["#add2a8","#6db064"], ["#75b9da","#4282bd"], ["#abd2d6","#6bafb7"], ["#e2e0b7","#ccc880"], ["#e5c998","#d09e53"], ["#d4a297","#b35a54"], ["#afa3b1","#755f79"]]
  7365. };
  7366. var owner = ClientLib.Data.MainData.GetInstance().get_Player().name, ctx = this.ctx, factor = this.__factor;
  7367. var dop = this.__displayO, dmd = this.__displayM, root = this, s = this.scale;
  7368. var r = (s < 3) ? 0.65 : (s > 3) ? 0.35 : 0.5;
  7369. var createBase = function (x, y, bt, clr)
  7370. {
  7371. var c = colors.bases[bt][clr][0], d = colors.bases[bt][clr][1];
  7372. var grd=ctx.createLinearGradient(x, y-r, x, y+r);
  7373. grd.addColorStop(0, c);
  7374. grd.addColorStop(1, d);
  7375. ctx.beginPath();
  7376. ctx.arc(x, y, r, 0, Math.PI * 2, true);
  7377. ctx.closePath();
  7378. ctx.fillStyle = grd;
  7379. ctx.fill();
  7380. ctx.lineWidth = 0.1;
  7381. ctx.strokeStyle = '#000000';
  7382. ctx.stroke();
  7383. ctx.closePath();
  7384. };
  7385. var createPoi = function(x, y, t)
  7386. {
  7387. var c = colors.pois[t][0], d = colors.pois[t][1];
  7388. var grd = ctx.createLinearGradient(x, y-r, x, y+r);
  7389. grd.addColorStop(0, c);
  7390. grd.addColorStop(1, d);
  7391. ctx.beginPath();
  7392. ctx.rect(x-r, y-r, r*2, r*2);
  7393. ctx.fillStyle = grd;
  7394. ctx.fill();
  7395. ctx.strokeStyle = "#000000";
  7396. ctx.lineWidth = 0.1;
  7397. ctx.stroke();
  7398. ctx.closePath();
  7399. };
  7400. if (dop != "pois")
  7401. {
  7402. for (var player in data.players) {
  7403. for (var i = 0; i < data.players[player].bases.length; i++){
  7404. var b = data.players[player].bases[i], pid = data.players[player].id;
  7405. if(dmd == "bases")
  7406. {
  7407. if (player == owner)
  7408. {
  7409. this.elements.push({"x":b[0],"y":b[1],"an":name,"pn":player,"bn":b[2],"bi":b[3],"ai":data.id,"pi":pid,"type":"base"});
  7410. this.locations.push([b[0]/factor, b[1]/factor]);
  7411. createBase(b[0], b[1], 'owner', 0);
  7412. }
  7413. }
  7414. else
  7415. {
  7416. this.elements.push({"x":b[0],"y":b[1],"an":name,"pn":player,"bn":b[2],"bi":b[3],"ai":data.id,"pi":pid,"type":"base"});
  7417. this.locations.push([b[0]/factor, b[1]/factor]);
  7418. (player == owner) ? createBase(b[0], b[1], 'owner', 0) : createBase(b[0], b[1], type, color);
  7419. }
  7420. }
  7421. }
  7422. }
  7423. if (dop != "bases")
  7424. {
  7425. for (var i = 0; i < data.pois.length; i++){
  7426. var x = data.pois[i].x, y = data.pois[i].y, t = data.pois[i].t, l = data.pois[i].l;
  7427. createPoi(x, y, t - 2);
  7428. this.elements.push({"x": x, "y": y, "an": name, "ai": data.id, "t": t, "l": l});
  7429. this.locations.push([x/factor, y/factor]);
  7430. }
  7431. }
  7432. this.inProgress = false;
  7433. }
  7434. catch(e)
  7435. {
  7436. console.log(e.toString());
  7437. }
  7438. },
  7439. __draggable: function(mask)
  7440. {
  7441. try
  7442. {
  7443. var start, end, initCoords = [], selectedBase = false, root = this, canvas = this.canvas, c = 0;
  7444. var factor = root.__factor;
  7445. var displayBaseInfo = function()
  7446. {
  7447. try
  7448. {
  7449. if (!selectedBase || root.inProgress) return;
  7450. var base = [];
  7451. var pois = ['Tiberium', 'Crystal', 'Reactor', 'Tungesten', 'Uranium', 'Aircraft Guidance', 'Resonater'];
  7452. for ( var i in selectedBase)
  7453. {
  7454. var txt = "", val = "";
  7455. switch(i)
  7456. {
  7457. case "an": txt = "Alliance: "; val = selectedBase[i]; break;
  7458. case "bn": txt = "Base : "; val = selectedBase[i]; break;
  7459. case "pn": txt = "Player : "; val = selectedBase[i]; break;
  7460. case "l" : txt = "Level : "; val = selectedBase[i]; break;
  7461. case "t" : txt = "Type : "; val = pois[selectedBase[i] - 2]; break;
  7462. default : txt = false;
  7463. }
  7464. if(txt)
  7465. {
  7466. base.push([txt, val]);
  7467. }
  7468. root.__setInfo(base);
  7469. }
  7470. }
  7471. catch(e)
  7472. {
  7473. console.log(e.toString());
  7474. }
  7475. };
  7476. var onMapHover = function(event)
  7477. {
  7478. var loc = root.locations, elements = root.elements, coordsField = root.coordsField;
  7479. var getCoords = function()
  7480. {
  7481. var canvasRect = canvas.getBoundingClientRect();
  7482. var x = (event.pageX - canvasRect.left), y = (event.pageY - canvasRect.top);
  7483. return [x, y];
  7484. };
  7485. var coords = getCoords();
  7486. var x = coords[0] + canvas.offsetLeft, y = coords[1] + canvas.offsetTop;
  7487. if(Math.sqrt(Math.pow(x - 250, 2) + Math.pow(y - 250, 2)) > 242)
  7488. {
  7489. coordsField.setValue("");
  7490. return;
  7491. }
  7492. x = Math.round(coords[0] / (root.scale * factor)); root.__pointerX = x;
  7493. y = Math.round(coords[1] / (root.scale * factor)); root.__pointerY = y;
  7494. coordsField.setValue(x + ":" + y);
  7495. if (root.scale < 2 || root.inProgress) return;
  7496. for(var i = 0; i < loc.length; i++)
  7497. {
  7498. var elmX = loc[i][0], elmY = loc[i][1];
  7499. if ((x == elmX) && (y == elmY))
  7500. {
  7501. selectedBase = elements[i];
  7502. displayBaseInfo();
  7503. break;
  7504. }
  7505. else
  7506. {
  7507. selectedBase = false;
  7508. root.__setInfo(false);
  7509. }
  7510. }
  7511. };
  7512. var onMapDrag = function(event)
  7513. {
  7514. if (root.scale == 1 || root.inProgress) return;
  7515. var cx = canvas.offsetLeft, cy = canvas.offsetTop, mx = event.pageX, my = event.pageY;
  7516. var newX = cx + mx - initCoords[0], newY = cy + my - initCoords[1];
  7517. initCoords[0] = mx;
  7518. initCoords[1] = my;
  7519. canvas.style.top = newY + 'px';
  7520. canvas.style.left = newX + 'px';
  7521. };
  7522. var onMapWheel = function(event)
  7523. {
  7524. if (root.inProgress) return;
  7525. var delta = Math.max(-1, Math.min(1, (event.wheelDelta || -event.detail)));
  7526. if((delta < 0 && root.scale <= 1) || (delta > 0 && root.scale >= 12)) return;
  7527. c += delta;
  7528. var str = ( Math.abs(c) % 3 == 0 ) ? ((delta < 0) ? 'down' : 'up') : false;
  7529. if(str) root.__scaleMap(str);
  7530. };
  7531. var onMapDown = function(event){
  7532. var x = event.pageX, y = event.pageY, t = new Date();
  7533. initCoords = [x,y];
  7534. start = t.getTime();
  7535. mask.removeEventListener('mousemove', onMapHover, false);
  7536. mask.addEventListener('mousemove', onMapDrag, false);
  7537. };
  7538. var onMapUp = function(event){
  7539. var x = event.pageX, y = event.pageY, t = new Date();
  7540. end = t.getTime();
  7541. initCoords = [x,y];
  7542. mask.removeEventListener('mousemove', onMapDrag, false);
  7543. mask.addEventListener('mousemove', onMapHover, false);
  7544. if (end - start < 150) webfrontend.gui.UtilView.centerCoordinatesOnRegionViewWindow(root.__pointerX, root.__pointerY);
  7545. };
  7546. var onMapOut = function(event){
  7547. mask.removeEventListener('mousemove', onMapDrag, false);
  7548. mask.addEventListener('mousemove', onMapHover, false);
  7549. };
  7550. mask.addEventListener('mouseup', onMapUp, false);
  7551. mask.addEventListener('mousedown', onMapDown, false);
  7552. mask.addEventListener('mousemove', onMapHover, false);
  7553. mask.addEventListener('mouseout', onMapOut, false);
  7554. mask.addEventListener('mousewheel', onMapWheel, false);
  7555. mask.addEventListener('DOMMouseScroll', onMapWheel, false);
  7556. }
  7557. catch(e)
  7558. {
  7559. console.log(e.toString());
  7560. }
  7561. },
  7562. __startRadarScan: function()
  7563. {
  7564. this.isRadarVisible = true;
  7565. var FRAMES_PER_CYCLE = 20, FRAMERATE = 20, RINGS = 6;
  7566. var canvas = this.canvas, ctx = this.ctx, canvassize = 400, animationframe = 0, root = this;
  7567. var ringsize = canvassize / (2 * RINGS + 1);
  7568. var radiusmax = ringsize / 2 + ringsize + (RINGS - 1) * ringsize;
  7569. function animateRadarFrame() {
  7570. ctx.clearRect(0, 0, canvas.width, canvas.height);
  7571. root.__createLayout();
  7572. var radius, alpha;
  7573. for (var ringno = 0; ringno < RINGS; ringno++)
  7574. {
  7575. radius = ringsize / 2 + (animationframe / FRAMES_PER_CYCLE) * ringsize + ringno * ringsize;
  7576. alpha = (radiusmax - radius) / radiusmax;
  7577. ctx.beginPath();
  7578. ctx.fillStyle = "rgba(92,178,112," + alpha + ")";
  7579. ctx.arc(250, 250, radius, 0, 2 * Math.PI, false);
  7580. ctx.fill();
  7581. ctx.closePath();
  7582. }
  7583. ctx.beginPath();
  7584. ctx.fillStyle = "rgb(100,194,122)";
  7585. ctx.arc(250, 250, ringsize / 2, 0, 2 * Math.PI, false);
  7586. ctx.fill();
  7587. ctx.closePath();
  7588. animationframe = (animationframe >= (FRAMES_PER_CYCLE - 1)) ? 0 : animationframe + 1;
  7589. }
  7590. this.__interval = setInterval(animateRadarFrame, 1000 / FRAMERATE);
  7591. },
  7592. __stopRadarScan: function()
  7593. {
  7594. if(!this.isRadarVisible) return;
  7595. clearInterval(this.__interval);
  7596. this.isRadarVisible = false;
  7597. this.__enablePanel();
  7598. },
  7599. __disablePanel: function()
  7600. {
  7601. this.inProgress = true;
  7602. for (var i = 0; i < this.panel.length; i++) this.panel[i].setEnabled(false);
  7603. },
  7604. __enablePanel: function()
  7605. {
  7606. for (var i = 0; i < this.panel.length; i++) if(i>1) this.panel[i].setEnabled(true);
  7607. },
  7608. __createIcon: function(color, width, height)
  7609. {
  7610. var canvas = document.createElement("canvas");
  7611. canvas.width = width;
  7612. canvas.height = height;
  7613. var ctx = canvas.getContext("2d");
  7614. ctx.beginPath();
  7615. ctx.rect(0, 0, width, height);
  7616. ctx.fillStyle = color;
  7617. ctx.fill();
  7618. ctx.closePath();
  7619. var data = canvas.toDataURL("image/png");
  7620. return data;
  7621. },
  7622. __updateList: function()
  7623. {
  7624. var dm = this.__displayM;
  7625. this.__selectedA = null;
  7626. this.allianceList.removeAll();
  7627. var d = this.receivedData, root = this;
  7628. var colors = {"enemy":["#ff807d", "#a93939", "#739bf5", "#c26b89"], "ally": ["#3bbe5d", "#c4d663", "#73f5ed", "#169f16"], "nap": ["#ffffff"], "selected": ["#ffe50e"], "alliance": ["#75b7d9"], "owner": ["#ffc48b"]};
  7629. for (var i = 0; i < d.length; i++)
  7630. {
  7631. var name = d[i][0].name, type = d[i][1], aid = d[i][0].id, clr = d[i][2];
  7632. if((dm == "all") || (dm == "selected"))
  7633. {
  7634. var color = colors[type][clr];
  7635. var li = new qx.ui.form.ListItem(name, root.__createIcon(color, 10, 10), aid);
  7636. var tooltip = new qx.ui.tooltip.ToolTip(name + " - " + type, root.__createIcon(color, 15, 15));
  7637. li.setToolTip(tooltip);
  7638. this.allianceList.add(li);
  7639. }
  7640. else
  7641. {
  7642. if(type == "alliance")
  7643. {
  7644. var li = new qx.ui.form.ListItem(name, null, aid);
  7645. var tooltip = new qx.ui.tooltip.ToolTip(name + " - " + type, root.__createIcon(color, 15, 15));
  7646. li.setToolTip(tooltip);
  7647. this.allianceList.add(li);
  7648. break;
  7649. }
  7650. }
  7651. }
  7652. },
  7653. drawCanvas: function()
  7654. {
  7655. var dmd = this.__displayM, b = this.receivedData, list = this.allianceList;
  7656. var selected = (this.__selectedA != null && typeof this.__selectedA == 'number') ? this.__selectedA : false;
  7657. var mask = this.mask, n = this.scale, canvas = this.canvas, ctx = this.ctx;
  7658. this.elements = [];
  7659. this.locations = [];
  7660. this.__stopRadarScan();
  7661. canvas.width = n * 500;
  7662. canvas.height = n * 500;
  7663. ctx = canvas.getContext("2d");
  7664. ctx.scale(n, n);
  7665. this.__createLayout();
  7666. for (var i = 0; i < b.length; i++)
  7667. {
  7668. var name = b[i][0].name, data = b[i][0], type = b[i][1], aid = b[i][0].id, color = b[i][2];
  7669. if(((dmd == "alliance") || (dmd == "bases")) && (type == "alliance"))
  7670. {
  7671. this.__createAlliance(name, data, type, 0);
  7672. break;
  7673. }
  7674. if(dmd == "all")
  7675. {
  7676. if(selected && (aid == selected))
  7677. {
  7678. type = 'selected';
  7679. color = 0;
  7680. }
  7681. this.__createAlliance(name, data, type, color);
  7682. }
  7683. if((dmd == "selected") && selected && (aid == selected))
  7684. {
  7685. this.__createAlliance(name, data, type, color);
  7686. break;
  7687. }
  7688. }
  7689. },
  7690. __scaleMap: function(str)
  7691. {
  7692. try
  7693. {
  7694. var newScale = (str == 'up') ? this.scale + 2 : this.scale - 2;
  7695. if (newScale > 12 || newScale < 1 || this.inProgress) return;
  7696. var canvas = this.canvas, ctx = this.ctx;
  7697. var x = ((canvas.offsetLeft - 250) * newScale/this.scale) + 250,
  7698. y = ((canvas.offsetTop - 250) * newScale/this.scale) + 250;
  7699. this.scale = newScale;
  7700. switch (this.scale)
  7701. {
  7702. case 1: this.zoomOut.setEnabled(false); this.zoomReset.setEnabled(false); this.zoomIn.setEnabled(true); break
  7703. case 11: this.zoomOut.setEnabled(true); this.zoomReset.setEnabled(true); this.zoomIn.setEnabled(false); break
  7704. default: this.zoomOut.setEnabled(true); this.zoomReset.setEnabled(true); this.zoomIn.setEnabled(true); break
  7705. }
  7706. ctx.clearRect(0, 0, canvas.width, canvas.height);
  7707. this.drawCanvas();
  7708. canvas.style.left = newScale == 1 ? 0 : x + 'px';
  7709. canvas.style.top = newScale == 1 ? 0 : y + 'px';
  7710. }
  7711. catch(e)
  7712. {
  7713. console.log(e.toString());
  7714. }
  7715. },
  7716. resetMap: function()
  7717. {
  7718. var canvas = this.canvas, ctx = this.ctx;
  7719. this.scale = 1;
  7720. canvas.width = 500; canvas.height = 500; canvas.style.left = 0; canvas.style.top = 0;
  7721. ctx.clearRect(0, 0, canvas.width, canvas.height);
  7722. this.__disablePanel();
  7723. this.__startRadarScan();
  7724. },
  7725. open: function(faction)
  7726. {
  7727. var app = qx.core.Init.getApplication();
  7728. var mainOverlay = app.getMainOverlay();
  7729. this.setWidth(mainOverlay.getWidth());
  7730. this.setMaxWidth(mainOverlay.getMaxWidth());
  7731. this.setHeight(mainOverlay.getHeight());
  7732. this.setMaxHeight(mainOverlay.getMaxHeight());
  7733. app.getDesktop().add(this, { left: mainOverlay.getBounds().left, top: mainOverlay.getBounds().top });
  7734. },
  7735. _onClose: function()
  7736. {
  7737. var opt = ccta_map.options.getInstance();
  7738. var app = qx.core.Init.getApplication();
  7739. app.getDesktop().remove(this);
  7740. if(opt.isSeeable()) opt.close();
  7741. },
  7742. _onResize: function()
  7743. {
  7744. var windowWidth = window.innerWidth - 10;
  7745. var width = this.getWidth();
  7746. var offsetLeft = (windowWidth - width) / 2;
  7747. this.setDomLeft(offsetLeft);
  7748. var opt = ccta_map.options.getInstance();
  7749. if (opt.isSeeable()) opt.setDomLeft(offsetLeft + width + 5);
  7750. }
  7751. }
  7752. });
  7753. qx.Class.define('ccta_map.options',
  7754. {
  7755. type: 'singleton',
  7756. extend: webfrontend.gui.CustomWindow,
  7757. construct: function()
  7758. {
  7759. try
  7760. {
  7761. this.base(arguments);
  7762. this.setLayout(new qx.ui.layout.VBox(10));
  7763. this.set({
  7764. width: 200,
  7765. height: 500,
  7766. showMinimize: false,
  7767. showMaximize: false,
  7768. alwaysOnTop: true,
  7769. caption: 'Edit Alliances'
  7770. });
  7771. this.__getAlliances();
  7772. var root = this;
  7773. var searchBox = new qx.ui.form.TextField().set({ placeholder: 'Search...'});
  7774. var list = new qx.ui.form.List().set({ height: 80 });
  7775. var editList = new qx.ui.form.List().set({ height: 160, selectionMode: 'additive' });
  7776. var radioButtons = [['Enemy', 'enemy'],['Ally', 'ally'],['NAP', 'nap']];
  7777. var radioGroup = new qx.ui.form.RadioButtonGroup().set({ layout: new qx.ui.layout.HBox(10), textColor: '#aaaaaa' });
  7778. for (var i = 0; i < radioButtons.length; i++)
  7779. {
  7780. var radioButton = new qx.ui.form.RadioButton(radioButtons[i][0]);
  7781. radioButton.setModel(radioButtons[i][1]);
  7782. radioGroup.add(radioButton);
  7783. }
  7784. var colors = root.__colors;
  7785. var colorSelectBox = new qx.ui.form.SelectBox().set({ height: 28 });
  7786. var addColors = function(type)
  7787. {
  7788. colorSelectBox.removeAll();
  7789. for (var i = 0; i < colors[type].length; i++)
  7790. {
  7791. var src = root.__createIcon(colors[type][i], 60, 15);
  7792. var listItem = new qx.ui.form.ListItem(null, src, i);
  7793. colorSelectBox.add(listItem);
  7794. }
  7795. };
  7796. addColors('enemy');
  7797. var addButton = new qx.ui.form.Button('Add').set({ enabled: false, width: 85, toolTipText: 'Maximum allowed number of alliances is 8.' });;
  7798. var removeButton = new qx.ui.form.Button('Remove').set({ enabled: false, width: 85 });;
  7799. var applyButton = new qx.ui.form.Button('Apply').set({ enabled: false });;
  7800. var defaultsButton = new qx.ui.form.Button('Defaults').set({ enabled: false, width: 85 });;
  7801. var saveButton = new qx.ui.form.Button('Save').set({ enabled: false, width: 85 });;
  7802. var hbox1 = new qx.ui.container.Composite(new qx.ui.layout.HBox(10))
  7803. var hbox2 = new qx.ui.container.Composite(new qx.ui.layout.HBox(10))
  7804. hbox1.add(addButton);
  7805. hbox1.add(removeButton);
  7806. hbox2.add(saveButton);
  7807. hbox2.add(defaultsButton);
  7808. this.searchBox = searchBox;
  7809. this.list = list;
  7810. this.editList = editList;
  7811. this.radioGroup = radioGroup;
  7812. this.colorSelectBox = colorSelectBox;
  7813. this.addButton = addButton;
  7814. this.removeButton = removeButton;
  7815. this.saveButton = saveButton;
  7816. this.defaultsButton = defaultsButton;
  7817. this.applyButton = applyButton;
  7818. this.add(searchBox);
  7819. this.add(list);
  7820. this.add(editList);
  7821. this.add(radioGroup);
  7822. this.add(colorSelectBox);
  7823. this.add(hbox1);
  7824. this.add(hbox2);
  7825. this.add(applyButton);
  7826. this.addListener('appear', function()
  7827. {
  7828. var cont = ccta_map.container.getInstance()
  7829. var bounds = cont.getBounds(), left = bounds.left, top = bounds.top, width = bounds.width, height = bounds.height;
  7830. searchBox.setValue('');
  7831. list.removeAll();
  7832. addButton.setEnabled(false);
  7833. removeButton.setEnabled(false);
  7834. applyButton.setEnabled(false);
  7835. radioGroup.setSelection([ radioGroup.getSelectables()[0] ]);
  7836. colorSelectBox.setSelection([ colorSelectBox.getSelectables()[0] ]);
  7837. this.__updateList();
  7838. this.__checkDefaults();
  7839. this.__checkSavedSettings();
  7840. this.setUserBounds(left + width + 5, top, 200, height);
  7841. }, this);
  7842. searchBox.addListener('keyup', this.__searchAlliances, this);
  7843. radioGroup.addListener('changeSelection', function(e)
  7844. {
  7845. if(e.getData()[0]) addColors(e.getData()[0].getModel());
  7846. }, this);
  7847. list.addListener('changeSelection', function(e)
  7848. {
  7849. if (!e.getData()[0]) return;
  7850. var items = this.__items, aid = e.getData()[0].getModel();
  7851. (((items != null) && (items.indexOf(aid) > -1)) || (items.length > 8)) ? addButton.setEnabled(false) : addButton.setEnabled(true);
  7852. }, this);
  7853. editList.addListener('changeSelection', function(e)
  7854. {
  7855. (e.getData()[0]) ? removeButton.setEnabled(true) : removeButton.setEnabled(false);
  7856. }, this);
  7857. addButton.addListener('execute', function()
  7858. {
  7859. var aid = list.getSelection()[0].getModel(),
  7860. name = list.getSelection()[0].getLabel(),
  7861. type = radioGroup.getSelection()[0].getModel(),
  7862. color = colorSelectBox.getSelection()[0].getModel();
  7863. var li = new qx.ui.form.ListItem(name + " - " + type, root.__createIcon(colors[type][color], 15, 15), {'aid': aid, 'type': type, 'name': name, 'color': color});
  7864. editList.add(li);
  7865. list.resetSelection();
  7866. addButton.setEnabled(false);
  7867. root.__updateItems();
  7868. }, this);
  7869. removeButton.addListener('execute', function()
  7870. {
  7871. var selection = (editList.isSelectionEmpty()) ? null : editList.getSelection();
  7872. var ownAlliance = ccta_map.getInstance().__allianceName;
  7873. if(selection != null)
  7874. {
  7875. for(var i = selection.length - 1; i > -1; i--) if(selection[i].getModel().name != ownAlliance) editList.remove(selection[i]);
  7876. root.__updateItems();
  7877. editList.resetSelection();
  7878. }
  7879. }, this);
  7880. applyButton.addListener('execute', this.__applyChanges, this);
  7881. defaultsButton.addListener('execute', this.__setDefaults, this);
  7882. saveButton.addListener('execute', this.__saveSettings, this);
  7883. }
  7884. catch(e)
  7885. {
  7886. console.log(e.toString());
  7887. }
  7888. console.log('Options Panel creation completed');
  7889. },
  7890. destruct: function()
  7891. {
  7892. },
  7893. members:
  7894. {
  7895. __data: null,
  7896. searchBox: null,
  7897. list: null,
  7898. editList: null,
  7899. radioGroup: null,
  7900. colorSelectBox: null,
  7901. addButton: null,
  7902. removeButton: null,
  7903. saveButton: null,
  7904. applyButton: null,
  7905. defaultsButton: null,
  7906. __items: null,
  7907. __colors: {"enemy":["#ff807d", "#a93939", "#739bf5", "#c26b89"], "ally": ["#3bbe5d", "#c4d663", "#73f5ed", "#169f16"], "nap": ["#ffffff"], "selected": ["#ffe50e"], "alliance": ["#75b7d9"], "owner": ["#ffc48b"]},
  7908. __getAlliances: function()
  7909. {
  7910. var root = this;
  7911. ClientLib.Net.CommunicationManager.GetInstance().SendSimpleCommand("RankingGetData",
  7912. {firstIndex: 0, lastIndex: 3000, ascending: true, view: 1, rankingType: 0, sortColumn: 2},
  7913. phe.cnc.Util.createEventDelegate(ClientLib.Net.CommandResult, this, function(context, data)
  7914. {
  7915. if(data.a != null)
  7916. {
  7917. var arr = [];
  7918. for( var i = 0; i < data.a.length; i++) arr[i] = [data.a[i].an, data.a[i].a];
  7919. root.__data = arr;
  7920. }
  7921. }), null);
  7922. },
  7923. __createIcon: function(color, width, height)
  7924. {
  7925. var canvas = document.createElement("canvas");
  7926. canvas.width = width;
  7927. canvas.height = height;
  7928. var ctx = canvas.getContext("2d");
  7929. ctx.beginPath();
  7930. ctx.rect(0,0,width,height);
  7931. ctx.fillStyle = color;
  7932. ctx.fill();
  7933. ctx.closePath();
  7934. var data = canvas.toDataURL("image/png");
  7935. return data;
  7936. },
  7937. __updateList: function()
  7938. {
  7939. var map = ccta_map.getInstance();
  7940. var selectedItems = [], list = this.editList, root = this;
  7941. var alliancesList = (map.__selectedAlliances == null) ? map.__defaultAlliances : map.__selectedAlliances;
  7942. var colors = this.__colors;
  7943. list.removeAll();
  7944. alliancesList.map(function(a)
  7945. {
  7946. var aid = a[0], at = a[1], an = a[2], c = a[3];
  7947. var li = new qx.ui.form.ListItem(an + " - " + at, root.__createIcon(colors[at][c], 15, 15), {'aid': aid, 'type': at, 'name': an, 'color': c});
  7948. list.add(li);
  7949. selectedItems.push(aid);
  7950. });
  7951. this.__items = selectedItems;
  7952. },
  7953. __setDefaults: function()
  7954. {
  7955. var map = ccta_map.getInstance();
  7956. var selectedItems = [], list = this.editList, root = this, colors = this.__colors;
  7957. var alliancesList = map.__defaultAlliances;
  7958. list.removeAll();
  7959. alliancesList.map(function(a)
  7960. {
  7961. var aid = a[0], at = a[1], an = a[2], c = a[3];
  7962. var li = new qx.ui.form.ListItem(an + " - " + at, root.__createIcon(colors[at][c], 15, 15), {'aid': aid, 'type': at, 'name': an, 'color': c});
  7963. list.add(li);
  7964. selectedItems.push(aid);
  7965. });
  7966. this.__items = selectedItems;
  7967. this.__currentListModified();
  7968. this.defaultsButton.setEnabled(false);
  7969. },
  7970. __searchAlliances: function()
  7971. {
  7972. var str = this.searchBox.getValue(), data = this.__data, list = this.list;
  7973. list.removeAll();
  7974. if (!data || (str == '')) return;
  7975. data.map(function(x)
  7976. {
  7977. var patt = new RegExp("^" + str + ".+$", "i");
  7978. var test = patt.test(x[0]);
  7979. if(test)
  7980. {
  7981. var listItem = new qx.ui.form.ListItem(x[0], null, x[1]);
  7982. list.add(listItem);
  7983. }
  7984. });
  7985. },
  7986. __updateItems: function()
  7987. {
  7988. var items = [], listItems = this.editList.getSelectables();
  7989. for (var i = 0; i < listItems.length; i++) items.push(listItems[i].getModel().aid);
  7990. this.__items = items;
  7991. this.__checkSavedSettings();
  7992. this.__currentListModified();
  7993. },
  7994. __applyChanges: function()
  7995. {
  7996. var selectedAlliances = [], listItems = this.editList.getSelectables();
  7997. for(var i = 0; i < listItems.length; i++)
  7998. {
  7999. var model = listItems[i].getModel(), aid = model.aid, type = model.type, name = model.name, color = model.color;
  8000. selectedAlliances.push([aid, type, name, color]);
  8001. }
  8002. ccta_map.getInstance().__selectedAlliances = selectedAlliances;
  8003. ccta_map.container.getInstance().resetMap();
  8004. ccta_map.getInstance().getData();
  8005. this.close();
  8006. },
  8007. __saveSettings: function()
  8008. {
  8009. if(typeof(Storage) === 'undefined') return;
  8010. var selectedAlliances = [], listItems = this.editList.getSelectables();
  8011. for(var i = 0; i < listItems.length; i++)
  8012. {
  8013. var model = listItems[i].getModel(), aid = model.aid, type = model.type, name = model.name, color = model.color;
  8014. selectedAlliances.push([aid, type, name, color]);
  8015. }
  8016. (!localStorage.ccta_map_settings) ? localStorage['ccta_map_settings'] = JSON.stringify(selectedAlliances) : localStorage.ccta_map_settings = JSON.stringify(selectedAlliances);
  8017. this.saveButton.setEnabled(false);
  8018. // console.log(localStorage.ccta_map_settings);
  8019. },
  8020. __checkSavedSettings: function()
  8021. {
  8022. if(typeof(Storage) === 'undefined') return;
  8023. var original = (localStorage.ccta_map_settings) ? JSON.parse(localStorage.ccta_map_settings) : null;
  8024. var items = this.__items;
  8025. var changed = false;
  8026. if ((items != null) && (original != null) && (items.length != original.length)) changed = true;
  8027. if ((items != null) && (original != null) && (items.length == original.length))
  8028. {
  8029. original.map(function(x)
  8030. {
  8031. if (items.indexOf(x[0]) < 0) changed = true;
  8032. });
  8033. }
  8034. ((items.length > 0) && ((original === null) || changed)) ? this.saveButton.setEnabled(true) : this.saveButton.setEnabled(false);
  8035. },
  8036. __checkDefaults: function()
  8037. {
  8038. var defaults = ccta_map.getInstance().__defaultAlliances, items = this.__items, changed = false;
  8039. if(!defaults) return;
  8040. if ((items != null) && (defaults != null) && (items.length != defaults.length)) changed = true;
  8041. if ((items != null) && (defaults != null) && (items.length == defaults.length))
  8042. {
  8043. defaults.map(function(x)
  8044. {
  8045. if (items.indexOf(x[0]) < 0) changed = true;
  8046. });
  8047. }
  8048. (changed) ? this.defaultsButton.setEnabled(true) : this.defaultsButton.setEnabled(false);
  8049. },
  8050. __currentListModified: function()
  8051. {
  8052. var map = ccta_map.getInstance(), current = (map.__selectedAlliances == null) ? map.__defaultAlliances : map.__selectedAlliances;
  8053. var items = this.__items, changed = false;
  8054. current.map(function(x)
  8055. {
  8056. if(items.indexOf(x[0]) < 0) changed = true;
  8057. });
  8058. ((items.length > 0) && ((items.length != current.length) || (changed == true))) ? this.applyButton.setEnabled(true) : this.applyButton.setEnabled(false);
  8059. }
  8060. }
  8061. });
  8062. }
  8063. var cctaMapLoader = function()
  8064. {
  8065. var qx = window["qx"];
  8066. var ClientLib = window["ClientLib"];
  8067. var webfrontend = window["webfrontend"];
  8068. if ((typeof ClientLib == 'undefined') || (typeof qx == 'undefined') || (qx.core.Init.getApplication().initDone == false))
  8069. {
  8070. setTimeout(cctaMapLoader, 1000);
  8071. console.log('retrying....');
  8072. }
  8073. else
  8074. {
  8075. create_ccta_map_class();
  8076. ccta_map.getInstance();
  8077. }
  8078. };
  8079. window.setTimeout(cctaMapLoader, 10000);
  8080.  
  8081. };
  8082. function inject()
  8083. {
  8084. var script = document.createElement("script");
  8085. script.innerHTML = "(" + injectScript.toString() + ")();";
  8086. script.type = "text/javascript";
  8087. if (/commandandconquer\.com/i.test(document.domain)) {
  8088. document.getElementsByTagName("head")[0].appendChild(script);
  8089. console.log('injected');
  8090. }
  8091. }
  8092. inject();
  8093. })();
  8094.  
  8095. /***********************************************************************************
  8096. Chat Helper Enhanced
  8097. ***********************************************************************************/
  8098.  
  8099. // ==UserScript==
  8100. // @name C&C: Tiberium Alliances Chat Helper Enhanced
  8101. // @namespace https://prodgame*.alliances.commandandconquer.com/*/index.aspx*
  8102. // @description Automates the use of chat and message BB-Codes: [coords][url][player][alliance][b][i][s][u] - Contact list for whispering - Type /chelp <enter> in chat for help.
  8103. // @include https://prodgame*.alliances.commandandconquer.com/*/index.aspx*
  8104. // @version 3.1.6
  8105. // @updateURL https://userscripts.org/scripts/source/152177.meta.js
  8106. // @downloadURL https://userscripts.org/scripts/source/152177.user.js
  8107. // @icon https://sites.google.com/site/titlemod/home/favicon.png
  8108. // @grant none
  8109. // ==/UserScript==
  8110.  
  8111. // type: /chelp in any text box and hit <enter> for a list of commands
  8112.  
  8113. // Please report urls that are not tagged properly
  8114.  
  8115. // window.chatHelper_suppressBrowserAltKeys suppresses normal browser menu keys [Alt+(a,p,b,i,u,s)] when you are in a textarea so that the menus don't open.
  8116.  
  8117. (function () {
  8118. var chatHelper_main = function () {
  8119. window.chatHelper_debug = 0; //initial debug level, top level for easy console access
  8120. var chlog = function chlog(str,lvl){
  8121. if (lvl > 0) { //lvl 1+
  8122. if (window.chatHelper_debug == 1) { // lvl 1
  8123. console.log("ChatHelper_debug: "+str+"\n");
  8124. }
  8125. if (window.chatHelper_debug == 2) { // lvl 2
  8126. console.log("ChatHelper_debug: "+str+"\n");
  8127. }
  8128. } else { //lvl 0 or no arg passed to lvl
  8129. console.log("ChatHelper_log: "+str+"\n");
  8130. }
  8131. };
  8132. try {
  8133. function createchatHelper() {
  8134. var onkeyupDelay = 50; //ms to wait after a keyupevent before searching contacts list. Lower for faster searching. Higher for better performance.
  8135. window.chatHelper_suppressBrowserAltKeys = true;
  8136. window.chatHelper_version = "3.1.6";
  8137. window.chatHelper_name = "C&C: Tiberium Alliances Chat Helper Enhanced";
  8138. chlog(window.chatHelper_name + ' v' + window.chatHelper_version + ': loading.',0);
  8139. var saveObj = {
  8140. saveObjVer : "3.1.6",
  8141. contacts : []
  8142. }
  8143. var validCharPatt = /[-\w\.]/;
  8144. var isWhisp = false;
  8145. var contacts = [];
  8146. var timer;
  8147. var _sub;
  8148.  
  8149. function getCaretPos(obj) {
  8150. // getCaretPos from: http://userscripts.org/scripts/show/151099
  8151. obj.focus();
  8152. if (obj.selectionStart) {
  8153. return obj.selectionStart; //Gecko
  8154. } else if (document.selection) //IE
  8155. {
  8156. var sel = document.selection.createRange();
  8157. var clone = sel.duplicate();
  8158. sel.collapse(true);
  8159. clone.moveToElementText(obj);
  8160. clone.setEndPoint('EndToEnd', sel);
  8161. return clone.text.length;
  8162. }
  8163. return 0;
  8164. }
  8165. function moveCaret(inputObject, pos) {
  8166. // moveCaretPos from: http://userscripts.org/scripts/show/151099
  8167. if (inputObject.selectionStart) {
  8168. inputObject.setSelectionRange(pos, pos);
  8169. inputObject.focus();
  8170. }
  8171. }
  8172. function getCursorWordPos(inputField) {
  8173. var pos = getCaretPos(inputField);
  8174. var inText = inputField.value;
  8175. var lc = inText.charAt(pos - 1);
  8176. if (lc.match(validCharPatt) != null) {
  8177. var sPos = pos;
  8178. var ePos = pos;
  8179. var t = inputField.value;
  8180. while (sPos >= 0 && t.charAt(sPos - 1).match(validCharPatt) != null) {
  8181. sPos--;
  8182. }
  8183. while (ePos <= t.length && t.charAt(ePos).match(validCharPatt) != null) {
  8184. ePos++;
  8185. }
  8186. //inputField.setSelectionRange(sPos,ePos);
  8187. return [sPos, ePos];
  8188. }
  8189. }
  8190. function tagWith(tag, inputField) {
  8191. var eTag = tag.replace('[', '[/'); //closing tag
  8192. var tagLen = tag.length;
  8193. var eTagLen = eTag.length;
  8194. if (inputField != null) {
  8195. var pos = getCaretPos(inputField);
  8196. var inText = inputField.value;
  8197. //save scroll position
  8198. if (inputField.type === 'textarea')
  8199. var st = inputField.scrollTop;
  8200. //if there is selected text
  8201. if (inputField.selectionStart !== inputField.selectionEnd) {
  8202. var a = inText.slice(0, inputField.selectionStart);
  8203. var b = inText.slice(inputField.selectionStart, inputField.selectionEnd);
  8204. var c = inText.slice(inputField.selectionEnd, inText.length);
  8205. inputField.value = a + tag + b + eTag + c;
  8206. moveCaret(inputField, pos + tagLen + eTagLen + b.length);
  8207. //if ((input IS empty) OR (the last char was a space)) AND next char ISNOT a left sqbracket
  8208. } else if ((inText === "" || inText.charAt(pos - 1) === " ") && (inText.charAt(pos) !== '[')) {
  8209. inputField.value = inText.substr(0, pos) + tag + eTag + inText.substr(pos, inText.length);
  8210. moveCaret(inputField, pos + tagLen);
  8211. //if last character is a valid playername character
  8212. } else if (inText.charAt(pos - 1).match(validCharPatt) != null) {
  8213. var arr = getCursorWordPos(inputField); //
  8214. var s = arr[0];
  8215. var e = arr[1];
  8216. inputField.value = inText.slice(0, s) + tag + inText.slice(s, e) + eTag + inText.slice(e, inText.length);
  8217. moveCaret(inputField, e + tagLen + eTagLen);
  8218. }
  8219. //restore scroll position
  8220. if (inputField.type === 'textarea')
  8221. inputField.scrollTop = st;
  8222. }
  8223. }
  8224. function showHelp() {
  8225. alert("Type /chelp in any text box to show this message.\n\nEnter key in chat:\tsearches your chat string for Urls and Coords and wraps them before submission.\n\nAlt + 1\t:\tsearches for Urls and Coords in a message or forum post and tags accordingly. Cursor is moved to the beginning.\nAlt + 2\t:\tManual URL insertion popup window\nAlt + 0\t:\tclears all tags\n\nWord wraps: tags a selected word -or- tags the word where the cursor is (if chat is empty or you hit <space> empty tags are inserted).\nAttempts to preserve cursor and scroll position.\n|\tAlt + p or Alt + 3\t:\tplayer tags\n|\tAlt + a or Alt + 4\t:\talliance tags\n|\tAlt + b\t\t\t:\tbold tags\n|\tAlt + i\t\t\t:\titalic tags\n|\tAlt + u\t\t\t:\tunderline tags\n|__\tAlt + s\t\t\t:\tstrikethrough tags\n\nContact list commands:\n/list -or- /contacts\n/add\n/del\n/del all - wipes your whole contact list");
  8226. }
  8227. function saveData() {
  8228. saveObj.contacts = contacts;
  8229. var jString = JSON.stringify(saveObj);
  8230. chlog("saveJSON: "+jString, 1);
  8231. localStorage.setItem('chatHelper', jString);
  8232. }
  8233.  
  8234. function loadData() {
  8235. try{
  8236. if (localStorage.getItem('myContacts')) { //should be removed eventually
  8237. var dat = localStorage.getItem('myContacts');
  8238. dat = dat.split(',');
  8239. saveObj.contacts = dat;
  8240. //unset old storage
  8241. localStorage.removeItem('myContacts');
  8242. } else if (localStorage.getItem('chatHelper')) {
  8243. var saveObjTmp = JSON.parse(localStorage.getItem('chatHelper'));
  8244. if (saveObjTmp.saveObjVer != window.chatHelper_version){
  8245. //version changed
  8246. var va = saveObjTmp.saveObjVer.split('.');
  8247. var vb = window.chatHelper_version.split('.');
  8248. if (va[0] != vb[0]){ //major version change
  8249. chlog("ChatHelper: Major version change from v"+va[0]+"."+va[1]+"."+va[2]+" to v"+vb[0]+"."+vb[1]+"."+vb[2]);
  8250. } else {
  8251. if (va[1] != vb[1]){ //minor version change
  8252. chlog("ChatHelper: Minor version change from v"+va[0]+"."+va[1]+"."+va[2]+" to v"+vb[0]+"."+vb[1]+"."+vb[2]);
  8253. } else {
  8254. if (va[2] != vb[2]){ //patch release
  8255. chlog("ChatHelper: Version Patched from v"+va[0]+"."+va[1]+"."+va[2]+" to v"+vb[0]+"."+vb[1]+"."+vb[2]);
  8256. }
  8257. }
  8258. }
  8259. } else {
  8260. //no version change
  8261. localStorage.getItem('chatHelper');
  8262. }
  8263. saveObj = saveObjTmp;
  8264. }
  8265. contacts = saveObj.contacts;
  8266. saveData();
  8267. }catch(err){
  8268. chlog(err);
  8269. }
  8270. }
  8271. if (!localStorage.myContacts) {
  8272. chlog("Deprecated contacts variable does not exist.",1);
  8273. loadData();
  8274. } else {
  8275. //contacts = loadData();
  8276. loadData();
  8277. chlog("Contacts: " + contacts, 1);
  8278. }
  8279. function saveContact(fr) {
  8280. chlog("Number of contacts == "+contacts.length,1);
  8281. contacts.push(fr);
  8282. chlog(fr + " added to contacts list.",1);
  8283. saveData();
  8284. }
  8285. function caseInsensitiveSort(a, b) {
  8286. a = a.toLowerCase();
  8287. b = b.toLowerCase();
  8288. if (a > b)
  8289. return 1;
  8290. if (a < b)
  8291. return -1;
  8292. return 0;
  8293. }
  8294. function listContacts() {
  8295. var len = contacts.length;
  8296. var a = contacts.sort(caseInsensitiveSort);
  8297. if (len == 1) {
  8298. alert(len + " Contact:\n\n" + a.join("\n") + "\n");
  8299. } else if (len > 1) {
  8300. alert(len + " Contacts:\n\n" + a.join("\n") + "\n");
  8301. } else {
  8302. var p = prompt("Your contacts list is empty.\n\nType a name here to add a contact:\n", "");
  8303. if (p) {
  8304. saveContact(p);
  8305. }
  8306. }
  8307. }
  8308. function deleteContact(fr) {
  8309. if (fr === "all") {
  8310. contacts = [];
  8311. chlog("All contacts deleted",1);
  8312. saveData();
  8313. } else {
  8314. var ind = contacts.indexOf(fr);
  8315. if (ind > -1) {
  8316. saveObj.contacts = contacts.splice(ind, 1);
  8317. saveData();
  8318. chlog(contacts,1);
  8319. chlog(fr + " deleted from contacts list.");
  8320. }
  8321. }
  8322. }
  8323. function keyUpTimer(kEv) {
  8324. kEv = kEv || window.event;
  8325. if (kEv.target.type === "text" && kEv.target.value != '') {
  8326. var inputField = kEv.target;
  8327. var inText = inputField.value;
  8328. var len = inText.length;
  8329. var sub;
  8330. var kc = kEv.keyCode;
  8331. if (len >= 10 && inText.match(/^(\/whisper)/) != null) {
  8332. isWhisp = true;
  8333. }
  8334. if (isWhisp && len >= 10 && !kEv.altGraphKey && !kEv.ctrlKey && !kEv.altKey && kc > 47 && kc < 91) {
  8335. chlog("keyUpTimer keyCode =="+kEv.keyCode,1);
  8336. sub = inText.substr(9);
  8337. if (!sub.match(/\s/)) {
  8338. for (var i = 0; i < contacts.length; i++) {
  8339. var slen = sub.length;
  8340. if (contacts[i][slen - 1] === sub[slen - 1] && contacts[i].substr(0, slen) == sub) {
  8341. inputField.value = "/whisper " + contacts[i] + " ";
  8342. inputField.setSelectionRange(10 + slen - 1, 10 + contacts[i].length, "forward");
  8343. }
  8344. }
  8345. } else {
  8346. isWhisp = false;
  8347. }
  8348. } else {
  8349. isWhisp = false;
  8350. }
  8351. }
  8352. }
  8353. document.onkeyup = function (kEv) {
  8354. clearTimeout(timer);
  8355. timer = setTimeout(function () {
  8356. keyUpTimer(kEv);
  8357. }, onkeyupDelay);
  8358. }
  8359. function delayedConfirm() {
  8360. if (confirm("Add " + _sub + " to your contacts list?\n\nYou can see a list of your contacts by typing /list")) {
  8361. saveContact(_sub);
  8362. }
  8363. }
  8364. function autoTag(inputField, inText) {
  8365. var isUrl = false;
  8366. var lookBack;
  8367. //the code here is mostly from Bruce Doan: http://userscripts.org/scripts/show/151965
  8368. ////auto url
  8369. inText = inText.replace(/(\[url\])*(https?:\/\/)([\da-z\.-]+)(\.[a-z]{2,6})([\/\w\.\-\=\?\&\%\+\|#:;,~\*\(\)\$]*)*\/?(\[\/url\])*/gi, function () {
  8370. var result = new Array();
  8371. var protocol = arguments[2].match(/https?:\/\//);
  8372. for (var i in arguments){
  8373. chlog("autoTag url reg arg "+i + "= " + arguments[i],1);
  8374. }
  8375. result.push('[url]');
  8376. result.push(arguments[2]); // http[s]://
  8377. result.push(arguments[3]); // domain
  8378. result.push(arguments[4]); // ext
  8379. result.push(arguments[5]); // query string
  8380. result.push('[/url]');
  8381. if (protocol === null){
  8382. chlog("autotag url - no protocol",2);
  8383. } else {
  8384. isUrl = true;
  8385. chlog("bypassing coords tagging\n detected protocol = " + protocol,2);
  8386. }
  8387. return result.join('');
  8388. });
  8389. ////auto coords
  8390. if (!isUrl) {
  8391. chlog("checking for coords",1);
  8392. lookBack = inText.replace(/(\[coords\])?([#])?([0-9]{3,4})[:.]([0-9]{3,4})([:.]\w+)?(\[\/coords\])?/gi, function () {
  8393. for (var i in arguments){
  8394. chlog("autoTag coords reg arg " + i + " = " + arguments[i],1);
  8395. }
  8396. var hashBefore = arguments[2];
  8397. chlog("hashBefore "+hashBefore,1);
  8398. if (!hashBefore) {
  8399. chlog("no hash returning");
  8400. var result = new Array();
  8401. result.push('[coords]');
  8402. result.push(arguments[3]);
  8403. result.push(':');
  8404. result.push(arguments[4]);
  8405. if (arguments[5] != undefined) {
  8406. result.push(arguments[5].replace('.', ':'));
  8407. }
  8408. result.push('[/coords]');
  8409. return result.join('');
  8410. } else {
  8411. return arguments[0];
  8412. }
  8413. });
  8414. inText = lookBack;
  8415. chlog("lookedback",1);
  8416. chlog("LB string: "+lookBack,1);
  8417. }
  8418. // shorthand for player
  8419. inText = inText.replace(/\[p\]([a-z0-9_\-\s]+)\[\/p\]/gi, '[player]$1[/player]');
  8420. // shorthand for alliance
  8421. inText = inText.replace(/\[a\]([a-z0-9_\-\s]+)\[\/a\]/gi, '[alliance]$1[/alliance]');
  8422. return inText;
  8423. }
  8424. document.onkeydown = function (kEv) {
  8425. kEv = kEv || window.event;
  8426. /* Tab key
  8427. if (kEv.keyCode == 9){
  8428. chlog("Tab key pressed",1)
  8429. var input = qx.core.Init.getApplication().getChat().getChatWidget().getEditable(); // Input
  8430. kEv.preventDefault();
  8431. kEv.stopPropagation();
  8432. }
  8433. */
  8434. if (!kEv.shiftKey && kEv.keyCode === 13 && (kEv.target.type === "text" || kEv.target.type === "textarea")) {
  8435. var inputField = kEv.target;
  8436. var inText = inputField.value;
  8437. var add = inText.match(/^(\/add)/);
  8438. var del = inText.match(/^(\/del)/);
  8439. var showContacts = inText.match(/^((\/contacts)|(\/list))/);
  8440. var sub;
  8441. var cf;
  8442. if (inText.match(/^(\/whisper)/) != null || add != null) {
  8443. if (add != null) {
  8444. sub = inText.substr(5);
  8445. } else {
  8446. sub = inText.substr(9);
  8447. }
  8448. if (sub.match(/^(\w*)\s/)) {
  8449. //if space after player name (is a whisper or a typo)
  8450. var arr = sub.match(/^(\w*)/);
  8451. sub = arr[0].replace(/\s$/, "");
  8452. if (contacts.indexOf(sub) == -1) {
  8453. //not in contacts list
  8454. _sub = sub;
  8455. setTimeout(delayedConfirm, 500);
  8456. }
  8457. } else if (contacts.indexOf(sub) == -1) {
  8458. //no message to send, not in contacts, promt to add, clear input
  8459. chlog("clearing input field",1);
  8460. inputField.focus(); //?necessary?
  8461. inputField.value = "";
  8462. var cf = confirm("Add " + sub + " to your contacts list?\n\nYou can see a list of your contacts by typing /list");
  8463. if (cf) {
  8464. saveContact(sub);
  8465. return false;
  8466. } else {
  8467. return false;
  8468. }
  8469. } else if (sub && contacts.indexOf(sub) > -1) {
  8470. //not a whisper, reject duplicate contact
  8471. alert(sub + " is already in your contacts list.");
  8472. }
  8473. }
  8474. //remove contact(s)
  8475. if (del) {
  8476. sub = inText.substr(5);
  8477. chlog("clearing input field",1);
  8478. inputField.value = "";
  8479. if ((contacts.indexOf(sub) > -1 || sub == "all") && confirm("Really delete " + sub + " from your contacts?")) {
  8480. deleteContact(sub);
  8481. } else {
  8482. alert(sub + " is not in your contacts list.");
  8483. }
  8484. return false;
  8485. }
  8486. // show contacts list
  8487. if (showContacts) {
  8488. chlog("clearing input field",1);
  8489. inputField.value = "";
  8490. listContacts();
  8491. return false;
  8492. }
  8493. // /chelp dialog
  8494. if (inText.length === 6 && inText.match(/^(\/chelp)/) != null) {
  8495. chlog("clearing input field",1);
  8496. inputField.value = "";
  8497. showHelp();
  8498. return false;
  8499. }
  8500. if (inputField != null && inputField.type === "text" && inText !== "") {
  8501. chlog("onEnter auto-tagging",1);
  8502. inText = autoTag(inputField, inText); //auto-tag
  8503. if (inText !== inputField.value) {
  8504. inputField.value = inText;
  8505. }
  8506. }
  8507. }
  8508. if (kEv.altKey && !kEv.shiftKey && !kEv.altGraphKey && !kEv.ctrlKey && kEv.target != null && (kEv.target.type === "textarea" || kEv.target.type === "text")) {
  8509. var inputField = kEv.target;
  8510. var inText = inputField.value;
  8511. // Alt key, not Ctrl or AltGr
  8512. if (kEv.altKey && !kEv.altGraphKey && !kEv.ctrlKey) {
  8513. var cc = kEv.charCode;
  8514. var kc = kEv.keyCode;
  8515. chlog("charCode == "+cc,1);
  8516. chlog("keyCode == "+kc,1);
  8517.  
  8518. /* Alt+1 for auto Coordinates/Urls in message body */
  8519. if (inputField.type === "textarea" && (cc === 49 || kc === 49)) {
  8520. var pos = getCaretPos(inputField);
  8521. chlog("attempting Alt+1 message auto-tag",1);
  8522. if (inputField != null) {
  8523. var st = inputField.scrollTop;
  8524. inText = autoTag(inputField, inText); //auto-tag
  8525. if (inText !== "" || inText !== inputField.value) {
  8526. inputField.value = inText;
  8527. inputField.scrollTop = st;
  8528. moveCaret(inputField, 0);
  8529. }
  8530. }
  8531. }
  8532. /* Alt+2 for URLs fallback */
  8533. if (cc === 50 || kc === 50) {
  8534. if (inputField != null) {
  8535. var url = prompt("Website (Syntax: google.com or www.google.com)", "");
  8536. if (url != null) {
  8537. inputField.value += '[url]' + url + '[/url]';
  8538. }
  8539. }
  8540. }
  8541. /* Alt+3 or Alt+p for players */
  8542. if ((cc === 112 || kc === 80) || (cc === 51 || kc === 51)) {
  8543. tagWith('[player]', inputField);
  8544. if (window.chatHelper_suppressBrowserAltKeys)
  8545. return false;
  8546. }
  8547. /* Alt+4 or Alt+a for alliances */
  8548. if ((cc === 97 || kc === 65) || (cc === 52 || kc === 52)) {
  8549. tagWith('[alliance]', inputField);
  8550. if (window.chatHelper_suppressBrowserAltKeys)
  8551. return false;
  8552. }
  8553. /* Alt+0 to clear tags */
  8554. if (cc === 48 || kc === 48) {
  8555. if (inputField.type === 'textarea')
  8556. var st = inputField.scrollTop;
  8557. if (inputField != null) {
  8558. inText = inText.replace(/\[\/?coords\]/gi, '');
  8559. inText = inText.replace(/\[\/?url\]/gi, '');
  8560. inText = inText.replace(/\[\/?player\]/gi, '');
  8561. inText = inText.replace(/\[\/?alliance\]/gi, '');
  8562. inText = inText.replace(/\[\/?b\]/gi, '');
  8563. inText = inText.replace(/\[\/?i\]/gi, '');
  8564. inText = inText.replace(/\[\/?u\]/gi, '');
  8565. inText = inText.replace(/\[\/?s\]/gi, '');
  8566. inputField.value = inText;
  8567. }
  8568. if (inputField.type === 'textarea')
  8569. inputField.scrollTop = st;
  8570. }
  8571. /* Alt+b for bold */
  8572. if (cc === 98 || kc === 66) {
  8573. tagWith('[b]', inputField);
  8574. if (window.chatHelper_suppressBrowserAltKeys)
  8575. return false;
  8576. }
  8577. /* Alt+i for italics */
  8578. if (cc === 105 || kc === 73) {
  8579. tagWith('[i]', inputField);
  8580. if (window.chatHelper_suppressBrowserAltKeys)
  8581. return false;
  8582. }
  8583. /* Alt+u for underline */
  8584. if (cc === 117 || kc === 85) {
  8585. tagWith('[u]', inputField);
  8586. if (window.chatHelper_suppressBrowserAltKeys)
  8587. return false;
  8588. }
  8589. /* Alt+s for strikethrough */
  8590. if (cc === 115 || kc === 83) {
  8591. tagWith('[s]', inputField);
  8592. if (window.chatHelper_suppressBrowserAltKeys)
  8593. return false;
  8594. }
  8595. }
  8596. }
  8597. }
  8598. }
  8599. } catch (err) {
  8600. chlog("createchatHelper: "+ err,1);
  8601. console.error(err);
  8602. }
  8603. function chatHelper_checkIfLoaded() {
  8604. try {
  8605. if (typeof qx !== 'undefined') {
  8606. createchatHelper();
  8607. } else {
  8608. window.setTimeout(chatHelper_checkIfLoaded, 1333);
  8609. }
  8610. } catch (err) {
  8611. console.log("chatHelper_checkIfLoaded: ", err);
  8612. }
  8613. }
  8614. window.setTimeout(chatHelper_checkIfLoaded, 1333);
  8615. };
  8616. try {
  8617. var chatHelper = document.createElement("script");
  8618. chatHelper.innerHTML = "(" + chatHelper_main.toString() + ")();";
  8619. chatHelper.type = "text/javascript";
  8620. document.getElementsByTagName("head")[0].appendChild(chatHelper);
  8621. } catch (err) {
  8622. console.log("chatHelper: init error: ", err);
  8623. }
  8624. })();
  8625.  
  8626.  
  8627. /***********************************************************************************
  8628. C&C:Tiberium Alliances Coords Button
  8629. ***********************************************************************************/
  8630. // ==UserScript==
  8631. // @name C&C:Tiberium Alliances Coords Button - All
  8632. // @namespace CNCTACoordsButtonAll
  8633. // @description Copy & Paste selected world object coords to chat message
  8634. // @include https://prodgame*.alliances.commandandconquer.com/*/index.aspx*
  8635. // @version 2.0.1
  8636. // @author Bruce Doan, Chiantii
  8637. // @updateURL https://userscripts.org/scripts/source/167957.meta.js
  8638. // @downloadURL https://userscripts.org/scripts/source/167957.user.js
  8639. // ==/UserScript==
  8640. (function () {
  8641. var CNCTACoordsButtonAll_main = function () {
  8642. try {
  8643. function createCoordsButton() {
  8644. console.log('C&C:Tiberium Alliances Coords Button All loaded.');
  8645.  
  8646. /*
  8647. $a = qx.core.Init.getApplication(); // Application
  8648. $c = $a.getChat(); // ChatWindow
  8649. $w = $c.getChatWidget(); // ChatWidget
  8650. $i = $cw.getEditable(); // Input
  8651. $d = $i.getContentElement().getDomElement(); // Input DOM Element
  8652. */
  8653.  
  8654. var coordsButton = {
  8655. selectedBase: null,
  8656. pasteCoords: function(){
  8657. var $i = qx.core.Init.getApplication().getChat().getChatWidget().getEditable(); // Input
  8658. var $d = $i.getContentElement().getDomElement(); // Input DOM Element
  8659.  
  8660. var result = new Array();
  8661. result.push($d.value.substring(0,$d.selectionStart)); // start
  8662.  
  8663. result.push('[coords]' + coordsButton.selectedBase.get_RawX() + ':' + coordsButton.selectedBase.get_RawY() + '[/coords]');
  8664.  
  8665. result.push($d.value.substring($d.selectionEnd, $d.value.length)); // end
  8666.  
  8667. $i.setValue(result.join(' '));
  8668. }
  8669. };
  8670.  
  8671. if (!webfrontend.gui.region.RegionCityMenu.prototype.__coordsButton_showMenu) {
  8672. webfrontend.gui.region.RegionCityMenu.prototype.__coordsButton_showMenu = webfrontend.gui.region.RegionCityMenu.prototype.showMenu;
  8673.  
  8674. webfrontend.gui.region.RegionCityMenu.prototype.showMenu = function (selectedVisObject) {
  8675. coordsButton.selectedBase = selectedVisObject;
  8676. if (this.__coordsButton_initialized != 1) {
  8677. this.__coordsButton_initialized = 1;
  8678. this.__newComposite = new qx.ui.container.Composite(new qx.ui.layout.VBox(0)).set({
  8679. padding: 2
  8680. });
  8681. for(i in this) {
  8682. if(this[i] && this[i].basename == "Composite") {
  8683. var button = new qx.ui.form.Button("Paste Coords");
  8684. button.addListener("execute", function () {
  8685. coordsButton.pasteCoords();
  8686. });
  8687. this[i].add(button);
  8688. }
  8689. }
  8690. }
  8691. this.__coordsButton_showMenu(selectedVisObject);
  8692. switch (selectedVisObject.get_VisObjectType()) {
  8693. case ClientLib.Vis.VisObject.EObjectType.RegionPointOfInterest:
  8694. case ClientLib.Vis.VisObject.EObjectType.RegionRuin:
  8695. case ClientLib.Vis.VisObject.EObjectType.RegionHubControl:
  8696. case ClientLib.Vis.VisObject.EObjectType.RegionHubServer:
  8697. this.add(this.__newComposite);
  8698. break;
  8699. }
  8700. }
  8701. }
  8702. }
  8703. } catch (e) {
  8704. console.log("createCoordsButton: ", e);
  8705. }
  8706.  
  8707. function CNCTACoordsButtonAll_checkIfLoaded() {
  8708. try {
  8709. if (typeof qx !== 'undefined') {
  8710. createCoordsButton();
  8711. } else {
  8712. window.setTimeout(CNCTACoordsButtonAll_checkIfLoaded, 1000);
  8713. }
  8714. } catch (e) {
  8715. console.log("CNCTACoordsButtonAll_checkIfLoaded: ", e);
  8716. }
  8717. }
  8718. window.setTimeout(CNCTACoordsButtonAll_checkIfLoaded, 1000);
  8719. };
  8720. try {
  8721. var CNCTACoordsButtonAll = document.createElement("script");
  8722. CNCTACoordsButtonAll.innerHTML = "(" + CNCTACoordsButtonAll_main.toString() + ")();";
  8723. CNCTACoordsButtonAll.type = "text/javascript";
  8724. document.getElementsByTagName("head")[0].appendChild(CNCTACoordsButtonAll);
  8725. } catch (e) {
  8726. console.log("CNCTACoordsButtonAll: init error: ", e);
  8727. }
  8728. })();
  8729.  
  8730. /***********************************************************************************
  8731. Command & Conquer TA POIs Analyser
  8732. ***********************************************************************************/
  8733. // ==UserScript==
  8734. // @name Command & Conquer TA POIs Analyser
  8735. // @description Display alliance's POIs scores and next tier requirements.
  8736. // @namespace https://prodgame*.alliances.commandandconquer.com/*/index.aspx*
  8737. // @include https://prodgame*.alliances.commandandconquer.com/*/index.aspx*
  8738. // @version 2.0.1
  8739. // @grant none
  8740. // @author zdoom
  8741. // @updateURL https://userscripts.org/scripts/source/171353.meta.js
  8742. // @downloadURL https://userscripts.org/scripts/source/171353.user.js
  8743. // ==/UserScript==
  8744.  
  8745. (function()
  8746. {
  8747. var injectScript = function()
  8748. {
  8749. function create_ccta_pa_class()
  8750. {
  8751. qx.Class.define('ccta_pa',
  8752. {
  8753. type: 'singleton',
  8754. extend: qx.ui.tabview.Page,
  8755. construct: function()
  8756. {
  8757. try
  8758. {
  8759. this.base(arguments);
  8760. this.set({layout: new qx.ui.layout.Grow(), label: "Alliance POIs", padding: 10});
  8761. var root = this;
  8762. var footerLayout = new qx.ui.layout.Grid();
  8763. footerLayout.setColumnFlex(1,1);
  8764. var footer = new qx.ui.container.Composite(footerLayout).set({font: "font_size_13", padding: [5, 10], marginTop: 5, decorator: "pane-light-opaque"});
  8765. var label = new qx.ui.basic.Label().set({textColor: "text-value", font: "font_size_13", padding: 10, alignX: 'right'});
  8766. var checkBox = new qx.ui.form.CheckBox('Show/Hide image and alliance appreviation.')
  8767. checkBox.set({textColor: webfrontend.gui.util.BBCode.clrLink, font: "font_size_13"});
  8768. var abr = new qx.ui.basic.Label().set({alignX: 'center', marginTop: 30, font: 'font_size_14', textColor: 'black'});
  8769. var manager = qx.theme.manager.Font.getInstance();
  8770. var defaultFont = manager.resolve(abr.getFont());
  8771. var newFont = defaultFont.clone();
  8772. newFont.setSize(32);
  8773. abr.setFont(newFont);
  8774. var deco = new qx.ui.decoration.Background().set({backgroundImage: "http://archeikhmeri.co.uk/images/fop2.png"});
  8775. var imgCont = new qx.ui.container.Composite(new qx.ui.layout.VBox());
  8776. imgCont.set({minWidth: 363, minHeight: 356, maxWidth: 363, maxHeight: 356, decorator: deco, alignX: 'center'});
  8777. var scrl = new qx.ui.container.Scroll();
  8778. var cont = new qx.ui.container.Composite(new qx.ui.layout.VBox()).set({allowGrowY: true, padding: 10});
  8779. var gb = new qx.ui.groupbox.GroupBox("Statistics").set({layout: new qx.ui.layout.VBox(), marginLeft: 2});
  8780. var lgb = new webfrontend.gui.GroupBoxLarge().set({layout: new qx.ui.layout.Canvas()});
  8781. var lgbc = new qx.ui.container.Composite(new qx.ui.layout.VBox()).set({padding: [50,10,20,10]});
  8782. var widget = new qx.ui.core.Widget().set({minWidth: 628, minHeight: 335});
  8783. var html = new qx.html.Element('div', null, {id: "graph"});
  8784. var info = new qx.ui.groupbox.GroupBox("Additional Information").set({layout: new qx.ui.layout.VBox(), marginTop: 10});
  8785. var buttonCont = new qx.ui.container.Composite(new qx.ui.layout.VBox()).set({marginTop: 10});
  8786. var tableCont = new qx.ui.container.Composite(new qx.ui.layout.VBox()).set({minWidth: 500});
  8787. var grid = new qx.ui.container.Composite(new qx.ui.layout.Grid(2,1));
  8788. grid.add(buttonCont, {row: 1, column: 1});
  8789. grid.add(tableCont, {row: 1, column: 2});
  8790. var noAllianceLabel = new qx.ui.basic.Label('No Alliance found, please create or join an alliance.').set({maxHeight: 30});
  8791. var data = ClientLib.Data.MainData.GetInstance();
  8792. var alliance = data.get_Alliance();
  8793. var exists = alliance.get_Exists();
  8794. var allianceName = alliance.get_Name();
  8795. var allianceAbbr = alliance.get_Abbreviation();
  8796. var faction = ClientLib.Base.Util.GetFactionGuiPatchText();
  8797. var fileManager = ClientLib.File.FileManager.GetInstance();
  8798. var opois = alliance.get_OwnedPOIs();
  8799. var poiUtil = ClientLib.Base.PointOfInterestTypes;
  8800. var getScore = poiUtil.GetScoreByLevel;
  8801. var getMultiplier = poiUtil.GetBoostModifierByRank;
  8802. var getBonus = poiUtil.GetBonusByType;
  8803. var getNextScore = poiUtil.GetNextScore;
  8804. var startRank = ClientLib.Base.EPOIType.RankedTypeBegin;
  8805. var endRank = ClientLib.Base.EPOIType.RankedTypeEnd;
  8806. var maxPoiLevel = ClientLib.Data.MainData.GetInstance().get_Server().get_MaxCenterLevel();
  8807. var poiInfo = phe.cnc.gui.util.Text.getPoiInfosByType;
  8808. var startRank = ClientLib.Base.EPOIType.RankedTypeBegin;
  8809. var tiersData = [], scoreData = [], bonusData = [], tiers = [];
  8810. for (var i = 0; i < 50; i++)
  8811. {
  8812. var previousScore = (i == 0) ? 0 : bonusData[i - 1][1];
  8813. var score = getNextScore(previousScore);
  8814. var bonus = getBonus(startRank, score);
  8815. var percent = getBonus(endRank - 1, score);
  8816. if (score != previousScore)
  8817. {
  8818. bonusData[i] = [i + 1, score, bonus, percent + '%'];
  8819. tiers[i] = [i, previousScore, score];
  8820. }
  8821. else break;
  8822. }
  8823. for (var i = 1; i <= maxPoiLevel; i++)
  8824. {
  8825. if (getScore(i + 1) == 1) continue;
  8826. scoreData.push([i, getScore(i)]);
  8827. }
  8828. for (var i = 1; i < 41; i++) tiersData.push([i, '+' + getMultiplier(i) + '%']);
  8829. var createTable = function()
  8830. {
  8831. var columns = [["POI Level", "Score"], ["Tier", "Score Required", "Bonus", "Percentage"], ["Rank", "Multiplier"]];
  8832. var rows = [scoreData, bonusData, tiersData];
  8833. var make = function(n)
  8834. {
  8835. var model = new qx.ui.table.model.Simple().set({columns: columns[n], data: rows[n]});
  8836. var table = new qx.ui.table.Table(model).set({
  8837. columnVisibilityButtonVisible: false,
  8838. headerCellHeight: 25,
  8839. marginTop: 20,
  8840. minWidth: 500,
  8841. height: 400});
  8842. var renderer = new qx.ui.table.cellrenderer.Default().set({useAutoAlign: false});
  8843. for (i = 0; i < columns[n].length; i++) table.getTableColumnModel().setDataCellRenderer(i, renderer);
  8844. return table;
  8845. };
  8846. this.Scores = make(0);
  8847. this.Tiers = make(1);
  8848. this.Multiplier = make(2);
  8849. };
  8850. var tables = new createTable();
  8851. ['Scores', 'Multiplier', 'Tiers'].map(function(key)
  8852. {
  8853. var table = tables[key];
  8854. var button = new qx.ui.form.Button(key).set({width: 100, margin: [10, 10, 0, 10]}) ;
  8855. button.addListener('execute', function()
  8856. {
  8857. tableCont.removeAll();
  8858. tableCont.add(table)
  8859. scrl.scrollChildIntoViewY(tableCont, 'top');
  8860. }, this);
  8861. buttonCont.add(button);
  8862. });
  8863.  
  8864. info.add(grid);
  8865. var tabview = new qx.ui.tabview.TabView().set({marginTop: 20, maxWidth: 500, maxHeight: 500});
  8866. var coordsButton = new qx.ui.form.Button('Coords').set({width: 100, margin: [10, 10, 0, 10]});
  8867. coordsButton.addListener('execute', function()
  8868. {
  8869. tableCont.removeAll();
  8870. tableCont.add(tabview);
  8871. scrl.scrollChildIntoViewY(tableCont, 'top');
  8872. }, this);
  8873. var res =
  8874. [
  8875. "ui/common/icn_res_tiberium.png",
  8876. "ui/common/icn_res_chrystal.png",
  8877. "ui/common/icn_res_power.png",
  8878. "ui/" + faction + "/icons/icon_arsnl_off_squad.png",
  8879. "ui/" + faction + "/icons/icon_arsnl_off_vehicle.png",
  8880. "ui/" + faction + "/icons/icon_arsnl_off_plane.png",
  8881. "ui/" + faction + "/icons/icon_def_army_points.png"
  8882. ];
  8883. var columns = ['Coords', 'Level', 'Score'], models = [], pages = [];
  8884. for (var i = 0; i < 7; i++)
  8885. {
  8886. var page = new qx.ui.tabview.Page().set({layout: new qx.ui.layout.VBox()});
  8887. page.setIcon(fileManager.GetPhysicalPath(res[i]));
  8888. var model = new qx.ui.table.model.Simple().set({columns: columns});
  8889. model.sortByColumn(1, false);
  8890. var table = new qx.ui.table.Table(model)
  8891. table.set({columnVisibilityButtonVisible: false, headerCellHeight: 25, marginTop: 10, minWidth: 470, showCellFocusIndicator: false, height: 320});
  8892. var renderer = new qx.ui.table.cellrenderer.Default().set({useAutoAlign: false});
  8893. for (var n = 0; n < columns.length; n++)
  8894. {
  8895. if (n == 0) renderer = new qx.ui.table.cellrenderer.Html();
  8896. table.getTableColumnModel().setDataCellRenderer(n, renderer);
  8897. }
  8898. page.add(table);
  8899. tabview.add(page);
  8900. models.push(model);
  8901. pages.push(page);
  8902. }
  8903. this.__poisCoordsPages = pages;
  8904. //Simulator
  8905. var wrapper = new qx.ui.container.Composite(new qx.ui.layout.VBox()).set({decorator: 'tabview-pane-clear', padding: [10, 14, 13, 10], marginTop: 20});
  8906. var header = new qx.ui.container.Composite(new qx.ui.layout.HBox()).set({decorator: 'pane-light-opaque', padding: [8, 12]});
  8907. var initValCont = new qx.ui.container.Composite(new qx.ui.layout.HBox()).set({padding: [5,0], marginLeft: 20});
  8908. var initVals = ['Score:', 'Tier: ', 'Rank:', 'Bonus:'], valueLabels = [];
  8909. for (var i = 0; i < 4; i++)
  8910. {
  8911. var initCont = new qx.ui.container.Composite(new qx.ui.layout.HBox());
  8912. var ln = new qx.ui.basic.Label(initVals[i]).set({textColor: webfrontend.gui.util.BBCode.clrLink, font: 'font_size_11'});
  8913. var lv = new qx.ui.basic.Label().set({font: 'font_size_11', paddingLeft: 5, paddingRight: 10});
  8914. initCont.add(ln);
  8915. initCont.add(lv);
  8916. initValCont.add(initCont, {flex: 1});
  8917. valueLabels.push(lv);
  8918. }
  8919. var mainCont = new qx.ui.container.Composite(new qx.ui.layout.VBox()).set({maxWidth: 480});
  8920. var modifierCont = new qx.ui.container.Composite(new qx.ui.layout.HBox());
  8921. var rankingModel = new qx.ui.table.model.Simple().set({columns: ['Rank', 'Name', 'Score', 'Multiplier', 'Total Bonus']});
  8922. var custom =
  8923. {
  8924. tableColumnModel : function(obj)
  8925. {
  8926. return new qx.ui.table.columnmodel.Resize(obj);
  8927. }
  8928. };
  8929. var rankingTable = new qx.ui.table.Table(rankingModel, custom);
  8930. rankingTable.set({
  8931. columnVisibilityButtonVisible: false,
  8932. headerCellHeight: 25,
  8933. marginTop: 3,
  8934. showCellFocusIndicator: false,
  8935. statusBarVisible: false,
  8936. keepFirstVisibleRowComplete: false,
  8937. height: 105});
  8938. for (var n = 0; n < 5; n++)
  8939. {
  8940. if (n == 1) rankingTable.getTableColumnModel().setDataCellRenderer(n, new qx.ui.table.cellrenderer.Html());
  8941. else rankingTable.getTableColumnModel().setDataCellRenderer(n, new qx.ui.table.cellrenderer.Default().set({useAutoAlign: false}));
  8942. }
  8943. var rankingTableColumnModel = rankingTable.getTableColumnModel();
  8944. var rankingTableResizeBehavior = rankingTableColumnModel.getBehavior();
  8945. rankingTableResizeBehavior.setWidth(0, 50);
  8946. rankingTableResizeBehavior.setWidth(1, "2*");
  8947. rankingTableResizeBehavior.setWidth(2, 100);
  8948. rankingTableResizeBehavior.setWidth(3, 70);
  8949. rankingTableResizeBehavior.setWidth(4, 100);
  8950. var resultsModel = new qx.ui.table.model.Simple().set({columns: ['Property', 'Value']});
  8951. var resultsTable = new qx.ui.table.Table(resultsModel, custom);
  8952. var resultsTableColumnModel = resultsTable.getTableColumnModel();
  8953. var resultsTableResizeBehavior = resultsTableColumnModel.getBehavior();
  8954. resultsTableResizeBehavior.setWidth(0, 100);
  8955. resultsTableResizeBehavior.setWidth(1, "2*");
  8956. resultsTable.set({
  8957. columnVisibilityButtonVisible: false,
  8958. headerCellHeight: 25,
  8959. marginTop: 5,
  8960. width: 210,
  8961. maxWidth: 210,
  8962. showCellFocusIndicator: false,
  8963. height: 300});
  8964. resultsTable.getTableColumnModel().setDataCellRenderer(0, new qx.ui.table.cellrenderer.Html());
  8965. resultsTable.getTableColumnModel().setDataCellRenderer(1, new qx.ui.table.cellrenderer.Html());
  8966. var codeToString = function(s){ return String.fromCharCode(s).toLowerCase() };
  8967. label.setValue(String.fromCharCode(77) + [65,68,69,32,66,89,32,90,68,79,79,77].map(codeToString).join().replace(/,/g, ''));
  8968. var poisColumns = ['Coords', 'Level', 'Score', 'Enabled'];
  8969. var poisModel = new qx.ui.table.model.Simple().set({columns: poisColumns });
  8970. var poisTable = new qx.ui.table.Table(poisModel, custom);
  8971. poisTable.set({
  8972. columnVisibilityButtonVisible: false,
  8973. headerCellHeight: 25,
  8974. marginTop: 5,
  8975. marginLeft: 5,
  8976. showCellFocusIndicator: false,
  8977. height: 300});
  8978. for (var n = 0; n < 4; n++)
  8979. {
  8980. if (n == 0) poisTable.getTableColumnModel().setDataCellRenderer(n, new qx.ui.table.cellrenderer.Html());
  8981. else if (n == 3) poisTable.getTableColumnModel().setDataCellRenderer(n, new qx.ui.table.cellrenderer.Boolean())
  8982. else poisTable.getTableColumnModel().setDataCellRenderer(n, new qx.ui.table.cellrenderer.Default().set({useAutoAlign: false}));
  8983. }
  8984. var poisTableColumnModel = poisTable.getTableColumnModel();
  8985. var poisTableResizeBehavior = poisTableColumnModel.getBehavior();
  8986. poisTableResizeBehavior.setWidth(0, 70);
  8987. poisTableResizeBehavior.setWidth(1, 50);
  8988. poisTableResizeBehavior.setWidth(2, "2*");
  8989. poisTableResizeBehavior.setWidth(3, 60);
  8990. var selectionModel = poisTable.getSelectionManager().getSelectionModel();
  8991. selectionModel.setSelectionMode(qx.ui.table.selection.Model.MULTIPLE_INTERVAL_SELECTION_TOGGLE);
  8992. poisTable.getSelectionModel().addListener('changeSelection', function(e)
  8993. {
  8994. var table = this.__poisTable;
  8995. var tableModel = table.getTableModel();
  8996. var data = tableModel.getDataAsMapArray();
  8997. var score = 0;
  8998. for (var i = 0; i < data.length; i++)
  8999. {
  9000. var isSelected = selectionModel.isSelectedIndex(i);
  9001. var level = tableModel.getValue(1, i);
  9002. tableModel.setValue(3, i, !isSelected);
  9003. if (!isSelected) score += getScore(parseInt(level, 10));
  9004. }
  9005. this.__setResultsRows(score);
  9006. this.__setRankingRows(score);
  9007. table.setUserData('score', score);
  9008. }, this);
  9009. var addRowCont = new qx.ui.container.Composite(new qx.ui.layout.HBox()).set({decorator: 'pane-light-opaque', padding: [8, 12], marginTop: 5});
  9010. var selectPoiLabelCont = new qx.ui.container.Composite(new qx.ui.layout.HBox());
  9011. var selectPoiLabel = new qx.ui.basic.Label('Select POI\'s Level').set({margin: [5, 10], font: 'font_size_11'});
  9012. var selectLevel = new qx.ui.form.SelectBox().set({padding: [5, 15]});
  9013. for (var i = 12; i <= maxPoiLevel; i++) selectLevel.add(new qx.ui.form.ListItem('Level ' + i, null, i));
  9014. var addButton = new qx.ui.form.Button('Add POI').set({padding: [5, 20]});
  9015. var resetButton = new qx.ui.form.Button('Reset').set({padding: [5, 20], marginLeft: 5});
  9016. addButton.addListener('execute', function()
  9017. {
  9018. var level = selectLevel.getSelection()[0].getModel();
  9019. var score = getScore(parseInt(level, 10));
  9020. var originalScore = poisTable.getUserData('score');
  9021. poisModel.addRows([['<p style="padding:0; margin:0; color:' + webfrontend.gui.util.BBCode.clrLink + '">New</p>', level, this.__format(score), true]]);
  9022. var newScore = originalScore + score;
  9023. this.__setResultsRows(newScore);
  9024. this.__setRankingRows(newScore);
  9025. poisTable.setUserData('score', newScore);
  9026. }, this);
  9027. resetButton.addListener('execute', this.__initSim, this);
  9028. mainCont.add(rankingTable, {flex: 1});
  9029. modifierCont.add(resultsTable);
  9030. modifierCont.add(poisTable, {flex: 1});
  9031. mainCont.add(modifierCont);
  9032. selectPoiLabelCont.add(selectPoiLabel);
  9033. addRowCont.add(selectLevel);
  9034. addRowCont.add(selectPoiLabelCont, {flex: 1});
  9035. addRowCont.add(addButton);
  9036. addRowCont.add(resetButton);
  9037. mainCont.add(addRowCont);
  9038. var selectBox = new qx.ui.form.SelectBox().set({padding: [5,20]});
  9039. for (var i = 0; i < 7; i++)
  9040. {
  9041. var type = poiInfo(i + startRank).type;
  9042. var listItem = new qx.ui.form.ListItem(type, null, type);
  9043. selectBox.add(listItem);
  9044. }
  9045. selectBox.addListener('changeSelection', function(e)
  9046. {
  9047. if (!e.getData()[0]) return;
  9048. var type = e.getData()[0].getModel();
  9049. this.__selectedSimPoi = type;
  9050. this.__initSim();
  9051. }, this);
  9052. header.add(selectBox);
  9053. header.add(initValCont, {flex: 1});
  9054. wrapper.add(header);
  9055. wrapper.add(mainCont);
  9056. this.__simLabels = valueLabels;
  9057. this.__rankingModel = rankingModel;
  9058. this.__resultsModel = resultsModel;
  9059. this.__poisModel = poisModel;
  9060. this.__poisTable = poisTable;
  9061. this.__selectPoiLevel = selectLevel;
  9062. this.__simCont = wrapper;
  9063. this.__selectedSimPoi = poiInfo(startRank).type;
  9064. var simulatorButton = new qx.ui.form.Button('Simulator').set({width: 100, margin: [10, 10, 0, 10]});
  9065. simulatorButton.addListener('execute', function()
  9066. {
  9067. scrl.scrollChildIntoViewY(tableCont, 'top');
  9068. tableCont.removeAll();
  9069. tableCont.add(wrapper);
  9070. }, this);
  9071. ////////////////////////////////////////////////////////////////////////////////////////////////////////
  9072. var showImage = true;
  9073. if (typeof localStorage.ccta_pa == 'undefined')
  9074. {
  9075. localStorage.ccta_pa = JSON.stringify({'showImage': true});
  9076. }
  9077. else showImage = JSON.parse(localStorage.ccta_pa).showImage;
  9078. checkBox.setValue(showImage);
  9079. var toggleImage = function()
  9080. {
  9081. var isChecked = checkBox.getValue();
  9082. localStorage.ccta_pa = JSON.stringify({'showImage': isChecked});
  9083. if (!isChecked) cont.remove(imgCont);
  9084. else cont.addAt(imgCont, 0);
  9085. };
  9086. checkBox.addListener('changeValue', toggleImage, this);
  9087. footer.add(checkBox, {row: 0, column: 0});
  9088. footer.add(label, {row: 0, column: 1});
  9089. scrl.add(cont);
  9090. imgCont.add(abr);
  9091. if (showImage) cont.add(imgCont);
  9092. cont.add(lgb);
  9093. lgb.add(lgbc);
  9094. lgbc.add(gb);
  9095. lgbc.add(info);
  9096. lgbc.add(footer);
  9097. widget.getContentElement().add(html);
  9098. this.add(scrl);
  9099.  
  9100. if (exists)
  9101. {
  9102. gb.add(widget);
  9103. buttonCont.addAt(coordsButton, 0);
  9104. buttonCont.addAt(simulatorButton, 1);
  9105. tableCont.add(tabview);
  9106. abr.setValue(allianceAbbr);
  9107. this.__allianceName = allianceName;
  9108. this.__allianceAbbr = allianceAbbr;
  9109. }
  9110. else
  9111. {
  9112. gb.add(noAllianceLabel);
  9113. tableCont.add(tables.Scores);
  9114. noAllianceLabel.setValue('No Alliance found, please create or join an alliance.');
  9115. this.__isReset = true;
  9116. }
  9117. this.__models = models;
  9118. this.__tableCont = tableCont;
  9119. this.__timer = new qx.event.Timer(1000);
  9120. this.__tiers = tiers;
  9121. this.__timer.addListener('interval', this.__update, this);
  9122. this.addListener('appear', function()
  9123. {
  9124. try
  9125. {
  9126. var alliance = ClientLib.Data.MainData.GetInstance().get_Alliance();
  9127. var allianceName = alliance.get_Name();
  9128. var allianceAbbr = alliance.get_Abbreviation();
  9129. var exists = alliance.get_Exists();
  9130. if (!exists && !this.__isReset)
  9131. {
  9132. console.log('No alliance found');
  9133. gb.removeAll();
  9134. gb.add(noAllianceLabel);
  9135. buttonCont.remove(coordsButton);
  9136. buttonCont.remove(simulatorButton);
  9137. tableCont.removeAll();
  9138. tableCont.add(tables.Scores);
  9139. abr.setValue('');
  9140. this.__allianceName = '';
  9141. this.__allianceAbbr = '';
  9142. this.__pois = {};
  9143. this.__isReset = true;
  9144. }
  9145. else if (exists)
  9146. {
  9147. if (this.__isReset)
  9148. {
  9149. gb.removeAll();
  9150. gb.add(widget);
  9151. buttonCont.addAt(coordsButton, 0);
  9152. buttonCont.addAt(simulatorButton, 1);
  9153. abr.setValue(allianceAbbr);
  9154. this.__isReset = false;
  9155. this.__allianceName = allianceName;
  9156. this.__allianceAbbr = allianceAbbr;
  9157. }
  9158. tableCont.removeAll();
  9159. tableCont.add(tabview);
  9160. this.__update();
  9161. }
  9162. }
  9163. catch(e)
  9164. {
  9165. console.log(e.toString())
  9166. }
  9167. }, this);
  9168. var overlay = webfrontend.gui.alliance.AllianceOverlay.getInstance();
  9169. var mainTabview = overlay.getChildren()[12].getChildren()[0];
  9170. mainTabview.addAt(this, 0);
  9171. mainTabview.setSelection([this]);
  9172. }
  9173. catch(e)
  9174. {
  9175. console.log(e.toString());
  9176. }
  9177. },
  9178. destruct: function(){},
  9179. members:
  9180. {
  9181. __isReset: false,
  9182. __timer: null,
  9183. __allianceName: null,
  9184. __allianceAbbr: null,
  9185. __pois: null,
  9186. __tiers: null,
  9187. __ranks: {},
  9188. __models: null,
  9189. __poisCoordsPages: null,
  9190. __tableCont: null,
  9191. __simCont: null,
  9192. __selectedSimPoi: null,
  9193. __isolatedRanks: null,
  9194. __simLabels: [],
  9195. __rankingModel: null,
  9196. __resultsModel: null,
  9197. __poisModel: null,
  9198. __poisTable: null,
  9199. __selectPoi: null,
  9200. __style:
  9201. {
  9202. "table": {"margin": "5px", "borderTop": "1px solid #333", "borderBottom": "1px solid #333", "fontFamily": "Verdana, Geneva, sans-serif"},
  9203. "graph":
  9204. {
  9205. "td": {"width": "68px", "verticalAlign": "bottom", "textAlign": "center"},
  9206. "div": {"width": "24px", "margin": "0 auto -1px auto", "border": "3px solid #333", "borderBottom": "none"}
  9207. },
  9208. "icon":
  9209. {
  9210. "ul": {"listStyleType": "none", "margin": 0, "padding": 0},
  9211. "div": {"padding": "6px", "marginRight": "6px", "display": "inline-block", "border": "1px solid #000"},
  9212. "p": {"display": "inline", "fontSize": "10px", "color": "#555"},
  9213. "li": {"height": "15px", "padding": "2px", "marginLeft": "10px"}
  9214. },
  9215. "cell":
  9216. {
  9217. "data": {"width": "68px", "textAlign": "center", "color": "#555", "padding": "3px 2px"},
  9218. "header": {"color": "#416d96", "padding": "3px 2px"}
  9219. },
  9220. "rows":
  9221. {
  9222. "graph": {"borderBottom": "3px solid #333", "height": "200px"},
  9223. "tr": {"fontSize": "11px", "borderBottom": "1px solid #333", "backgroundColor": "#d6dde1"}
  9224. }
  9225. },
  9226. __element: function(tag)
  9227. {
  9228. var elm = document.createElement(tag), root = this;
  9229. this.css = function(a)
  9230. {
  9231. for (var b in a)
  9232. {
  9233. root.elm.style[b] = a[b];
  9234. root.__style[b] = a[b];
  9235. }
  9236. }
  9237. this.set = function(a)
  9238. {
  9239. for (var b in a) root.elm[b] = a[b];
  9240. }
  9241. this.append = function()
  9242. {
  9243. for (var i in arguments)
  9244. {
  9245. if (arguments[i].__instanceof == 'element') root.elm.appendChild(arguments[i].elm);
  9246. else if (arguments[i] instanceof Element) root.elm.appendChild(arguments[i]);
  9247. else console.log(arguments[i] + ' is not an element');
  9248. }
  9249. }
  9250. this.text = function(str)
  9251. {
  9252. var node = document.createTextNode(str);
  9253. root.elm.appendChild(node);
  9254. }
  9255. this.elm = elm;
  9256. this.__style = {};
  9257. this.__instanceof = 'element';
  9258. },
  9259. __format: function(n)
  9260. {
  9261. var f = "", n = n.toString();
  9262. if (n.length < 3) return n;
  9263. for (var i = 0; i < n.length; i++)
  9264. {
  9265. (((n.length - i) % 3 === 0) && (i !== 0)) ? f += "," + n[i] : f += n[i];
  9266. }
  9267. return f;
  9268. },
  9269. __update: function()
  9270. {
  9271. this.__timer.stop();
  9272. var div = document.getElementById('graph');
  9273. if (!div)
  9274. {
  9275. this.__timer.start();
  9276. console.log('Waiting for div dom element to be loaded');
  9277. }
  9278. if (div)
  9279. {
  9280. console.log('Reloading graph');
  9281. div.innerHTML = "";
  9282. this.__updatePOIList();
  9283. this.__updateGraph();
  9284. this.__updateRanks();
  9285. }
  9286. },
  9287. __updatePOIList: function()
  9288. {
  9289. var alliance = ClientLib.Data.MainData.GetInstance().get_Alliance();
  9290. var opois = alliance.get_OwnedPOIs();
  9291. var startRank = ClientLib.Base.EPOIType.RankedTypeBegin;
  9292. var getScore = ClientLib.Base.PointOfInterestTypes.GetScoreByLevel;
  9293. var models = this.__models, format = this.__format, pages = this.__poisCoordsPages;
  9294. for (var i = 0; i < 7; i++)
  9295. {
  9296. var rows = [];
  9297. opois.map(function(poi)
  9298. {
  9299. if (poi.t - startRank === i)
  9300. {
  9301. var a = webfrontend.gui.util.BBCode.createCoordsLinkText((poi.x + ':' + poi.y), poi.x, poi.y);
  9302. rows.push([a, poi.l, format(getScore(poi.l))]);
  9303. }
  9304. });
  9305. models[i].setData(rows);
  9306. models[i].sortByColumn(1, false);
  9307. pages[i].setLabel(rows.length);
  9308. }
  9309. },
  9310. __updateRanks: function()
  9311. {
  9312. this.__ranks = {}, this.__isolatedRanks = {}, root = this, allianceName = this.__allianceName;
  9313. var getPoiRankType = ClientLib.Base.PointOfInterestTypes.GetPOITypeFromPOIRanking;
  9314. var poiInfo = phe.cnc.gui.util.Text.getPoiInfosByType, startRank;
  9315. for (var i = 0; i < 20; i++) if (getPoiRankType(i) > 0) { startRank = i; break; };
  9316. var getPoiRanks = function(type, poiType, increment)
  9317. {
  9318. ClientLib.Net.CommunicationManager.GetInstance().SendSimpleCommand("RankingGetData",
  9319. {'ascending': true, 'firstIndex': 0, 'lastIndex': 100, 'rankingType': poiType, 'sortColumn': 200 + increment, 'view': 1},
  9320. phe.cnc.Util.createEventDelegate(ClientLib.Net.CommandResult, root, function(context, data)
  9321. {
  9322. if (data !== null)
  9323. {
  9324. var skip = 1, arr = [];
  9325. for (var i = 0; i < data.a.length; i++)
  9326. {
  9327. var alliance = data.a[i], name = alliance.an, score = (alliance.pois || 0);
  9328. if (name == allianceName)
  9329. {
  9330. skip = 0;
  9331. continue;
  9332. }
  9333. alliance.r = i + skip;
  9334. arr.push(alliance);
  9335. }
  9336. this.__isolatedRanks[type] = arr;
  9337. this.__ranks[type] = data.a;
  9338. if (this.__selectedSimPoi == type) this.__initSim();
  9339. }
  9340. }), null);
  9341. };
  9342. if (startRank) for (var n = 0; n < 7; n++) getPoiRanks(poiInfo(getPoiRankType(n + startRank)).type, n + startRank, n);
  9343. },
  9344. __setSimLabels: function()
  9345. {
  9346. var labels = this.__simLabels, pois = this.__pois, type = this.__selectedSimPoi, format = this.__format;
  9347. if (pois[type])
  9348. {
  9349. labels[0].setValue(pois[type].s);
  9350. labels[1].setValue((pois[type].tier == 0) ? "0" : pois[type].tier);
  9351. labels[2].setValue((pois[type].rank == 0) ? "0" : pois[type].rank);
  9352. labels[3].setValue(pois[type].tb);
  9353. }
  9354. },
  9355. __setRankingRows: function(score)
  9356. {
  9357. var isolatedRanks = this.__isolatedRanks, format = this.__format, allianceName = this.__allianceName, type = this.__selectedSimPoi, pois = this.__pois;
  9358. var poiUtil = ClientLib.Base.PointOfInterestTypes;
  9359. var getMultiplier = poiUtil.GetBoostModifierByRank;
  9360. var getBonus = poiUtil.GetBonusByType;
  9361. var getRankingData = function(i, type, nr)
  9362. {
  9363. var x = isolatedRanks[type][i], score = (x.pois || 0), name = webfrontend.gui.util.BBCode.createAllianceLinkText(x.an);
  9364. var bonus = getBonus(pois[type].index, score), multiplier = getMultiplier(nr), totalBonus = bonus + (bonus * multiplier / 100);
  9365. totalBonus = (pois[type].bonusType == 1) ? format(Math.round(totalBonus)) : Math.round(totalBonus * 100) / 100 + '%';
  9366. return [nr, name, format(score), '+' + multiplier + '%', totalBonus]
  9367. };
  9368. getMyRanking = function(s, i, p)
  9369. {
  9370. var b = getBonus(pois[p].index, s);
  9371. var m = getMultiplier(i);
  9372. var tb = b + (b * m / 100);
  9373. tb = (pois[p].bonusType == 1) ? format(Math.round(tb)) : Math.round(tb * 100) / 100 + '%';
  9374. var n = webfrontend.gui.util.BBCode.createAllianceLinkText(allianceName);
  9375. return [i, n, format(s), '+' + m + '%', tb];
  9376. };
  9377. var getRankingRows = function(s, type)
  9378. {
  9379. var rows;
  9380. for (var i = 0; i < isolatedRanks[type].length; i++)
  9381. {
  9382. if (s >= (isolatedRanks[type][i].pois || 0))
  9383. {
  9384. var matched = getRankingData(i, type, i + 2);
  9385. var nextMatched = getRankingData(i + 1, type, i + 3);
  9386. var preMatched = (i > 0) ? getRankingData(i - 1, type, i) : null;
  9387. if (i == 0) rows = [getMyRanking(s, i + 1, type), matched, nextMatched];
  9388. else rows = [preMatched, getMyRanking(s, i + 1, type), matched];
  9389. break;
  9390. }
  9391. }
  9392. return rows;
  9393. }
  9394. var rankingRows = getRankingRows(score, type);
  9395. if (rankingRows) this.__rankingModel.setData(rankingRows);
  9396. },
  9397. __setResultsRows: function(score)
  9398. {
  9399. var pois = this.__pois, tiers = this.__tiers, format = this.__format, type = this.__selectedSimPoi, ranks = this.__isolatedRanks;
  9400. var poiUtil = ClientLib.Base.PointOfInterestTypes;
  9401. var getScore = poiUtil.GetScoreByLevel;
  9402. var getMultiplier = poiUtil.GetBoostModifierByRank;
  9403. var getBonus = poiUtil.GetBonusByType;
  9404. var getTier = function(s)
  9405. {
  9406. if (s == 0) return "0";
  9407. else for (var i = 0; i < tiers.length; i++) if (s >= tiers[i][1] && s < tiers[i][2]) return tiers[i][0];
  9408. };
  9409. var getNextTier = function(s)
  9410. {
  9411. for (var i = 0; i < tiers.length; i++) if (s >= tiers[i][1] && s < tiers[i][2]) return (tiers[i][2] - s);
  9412. };
  9413. var getPreviousTier = function(s)
  9414. {
  9415. for (var i = 0; i < tiers.length; i++) if (s >= tiers[i][1] && s < tiers[i][2]) return (s - tiers[i][1]);
  9416. };
  9417. var getRank = function(s, t)
  9418. {
  9419. for (var i = 0; i < ranks[t].length; i++) if (s >= (ranks[t][i].pois || 0)) return i + 1;
  9420. };
  9421. var getNextRank = function(s, t)
  9422. {
  9423. for (var i = 0; i < ranks[t].length; i++) if (s >= (ranks[t][i].pois || 0)) return (ranks[t][i-1]) ? ranks[t][i-1].pois : s;
  9424. };
  9425. var getPreviousRank = function(s, t)
  9426. {
  9427. for (var i = 0; i < ranks[t].length; i++) if (s >= (ranks[t][i].pois || 0)) return (ranks[t][i].pois || 0);
  9428. };
  9429. var getSimulatedData = function(s, p)
  9430. {
  9431. var ot = pois[p].tier;
  9432. var or = pois[p].rank;
  9433. var ob = pois[p].bonus;
  9434. var otb = pois[p].totalBonus;
  9435. var pp = pois[p].bonusType;
  9436. var t = getTier(s);
  9437. var r = getRank(s, p);
  9438. var ps = getPreviousRank(s, p);
  9439. var ns = getNextRank(s, p);
  9440. var pr = s - ps;
  9441. var nr = ns - s;
  9442. var nt = getNextTier(s);
  9443. var pt = getPreviousTier(s);
  9444. var b = getBonus(pois[p].index, s);
  9445. var m = getMultiplier(r);
  9446. var f = format;
  9447. var tb = b + (b * m / 100);
  9448. var sc = function(val, org, poiType, fac)
  9449. {
  9450. var cs = [webfrontend.gui.util.BBCode.clrLink, '#41a921', '#e23636'];
  9451. var st = function(c){return '<p style="padding: 0; margin: 0; color: ' + c + '">'}, et = '</p>';
  9452. if (val == undefined) return null;
  9453. if (org == undefined) return st(cs[0]) + val + et;
  9454. else if (org != undefined && poiType == null) return ((val-org)*fac > 0) ? st(cs[1])+val+et : ((val-org)* fac < 0) ? st(cs[2])+val+et : val;
  9455. else
  9456. {
  9457. var fv = (poiType == 1) ? format(Math.round(val)) : Math.round(val * 100) / 100 + '%';
  9458. return ((val - org) * fac > 0) ? st(cs[1]) + fv + et : ((val - org) * fac < 0) ? st(cs[2]) + fv + et : fv;
  9459. }
  9460. };
  9461. var rows = ['Score', 'Tier', 'Rank', 'Multiplier', 'Previous Rank', 'Next Rank', 'Previous Tier', 'Next Tier', 'Bonus', 'Total Bonus'];
  9462. var data = [f(s), sc(t,ot,null,1), sc(r,or,null,-1), '+'+m+'%', '+'+f(pr), '-'+f(nr), '+'+f(pt), '-'+f(nt), sc(b,ob,pp,1), sc(tb,otb,pp,1)];
  9463. var results = [];
  9464. for (var i = 0; i < rows.length; i++) results.push([sc(rows[i]), data[i]]);
  9465. return results;
  9466. };
  9467. var resultsRows = getSimulatedData(score, type);
  9468. if (resultsRows) this.__resultsModel.setData(resultsRows);
  9469. },
  9470. __setPoisRows: function()
  9471. {
  9472. var poiUtil = ClientLib.Base.PointOfInterestTypes;
  9473. var getScore = poiUtil.GetScoreByLevel; //poi level
  9474. var alliance = ClientLib.Data.MainData.GetInstance().get_Alliance();
  9475. var opois = alliance.get_OwnedPOIs();
  9476. var poiInfo = phe.cnc.gui.util.Text.getPoiInfosByType;
  9477. var poisRows = [], type = this.__selectedSimPoi;
  9478. opois.map(function(poi)
  9479. {
  9480. if (poiInfo(poi.t).type == type)
  9481. {
  9482. var a = webfrontend.gui.util.BBCode.createCoordsLinkText((poi.x + ':' + poi.y), poi.x, poi.y);
  9483. poisRows.push([a, poi.l, getScore(poi.l), true]);
  9484. }
  9485. });
  9486. if (poisRows) this.__poisModel.setData(poisRows);
  9487. },
  9488. __initSim: function()
  9489. {
  9490. var score = this.__pois[this.__selectedSimPoi].score;
  9491. this.__setSimLabels();
  9492. this.__setRankingRows(score);
  9493. this.__setResultsRows(score);
  9494. this.__setPoisRows();
  9495. this.__poisTable.setUserData('score', score);
  9496. this.__poisTable.resetSelection();
  9497. this.__selectPoiLevel.setSelection([this.__selectPoiLevel.getSelectables()[0]]);
  9498. },
  9499. __updateGraph: function()
  9500. {
  9501. try
  9502. {
  9503. var data = ClientLib.Data.MainData.GetInstance();
  9504. var alliance = data.get_Alliance();
  9505. var ranks = alliance.get_POIRankScore();
  9506. var poiUtil = ClientLib.Base.PointOfInterestTypes;
  9507. var getScore = poiUtil.GetScoreByLevel;
  9508. var getMultiplier = poiUtil.GetBoostModifierByRank;
  9509. var getBonus = poiUtil.GetBonusByType;
  9510. var getNextScore = poiUtil.GetNextScore;
  9511. var startRank = ClientLib.Base.EPOIType.RankedTypeBegin;
  9512. var endRank = ClientLib.Base.EPOIType.RankedTypeEnd;
  9513. var poiInfo = phe.cnc.gui.util.Text.getPoiInfosByType;
  9514.  
  9515. var pois = {}, format = this.__format, tiers = this.__tiers;
  9516. var colors = ["#8dc186", "#5b9dcb", "#8cc1c7", "#d7d49c", "#dbb476", "#c47f76", "#928195"];
  9517. var getTier = function(s)
  9518. {
  9519. for (var i = 0; i < tiers.length; i++) if (s >= tiers[i][1] && s < tiers[i][2]) return tiers[i][0];
  9520. };
  9521. var getHeight = function(s)
  9522. {
  9523. if (s == 0) return 0;
  9524. for (var i = 0; i < tiers.length; i++)
  9525. if (s >= tiers[i][1] && s < tiers[i][2]) return Math.round((s - tiers[i][1]) / (tiers[i][2] - tiers[i][1]) * 100);
  9526. };
  9527.  
  9528. var colors = ["#8dc186", "#5b9dcb", "#8cc1c7", "#d7d49c", "#dbb476", "#c47f76", "#928195"];
  9529. for (var i = 0; i < ranks.length; i++)
  9530. {
  9531. var type = i + startRank;
  9532. var name = poiInfo(type).type;
  9533. var rank = ranks[i].r;
  9534. var multiplier = getMultiplier(rank);
  9535. var score = ranks[i].s;
  9536. var bonus = getBonus(type, score);
  9537. var nextScore = getNextScore(score);
  9538. var nextBonus = getBonus(type, nextScore);
  9539. var totalBonus = bonus + (bonus * multiplier / 100);
  9540. var nextTotalBonus = nextBonus + (nextBonus * multiplier / 100);
  9541. var nextTier = format(nextScore - score);
  9542. var poiType = (i > 2) ? 2 : 1;
  9543. var color = colors[i];
  9544. var tier = getTier(ranks[i].s);
  9545. var height = getHeight(ranks[i].s);
  9546. var f_score = format(score);
  9547. var f_rank = rank + ' (' + multiplier + '%)';
  9548. var f_totalBonus = (poiType == 1) ? format(totalBonus) : Math.round(totalBonus * 100) / 100 + ' %';
  9549. nextTotalBonus = (poiType == 1) ? format(nextTotalBonus) : Math.round(nextTotalBonus * 100) / 100 + ' %';
  9550. pois[name] =
  9551. {
  9552. 'score': score,
  9553. 'tier': tier,
  9554. 'bonus': bonus,
  9555. 'totalBonus': totalBonus,
  9556. 'index': type,
  9557. 'bonusType': poiType,
  9558. 'rank': rank,
  9559. 'multiplier': multiplier,
  9560. 't': tier,
  9561. 's': f_score,
  9562. 'r': f_rank,
  9563. 'nt': nextTier,
  9564. 'tb': f_totalBonus,
  9565. 'ntb': nextTotalBonus,
  9566. 'c': color,
  9567. 'h': height
  9568. };
  9569. }
  9570. console.log('data ready')
  9571. this.__pois = pois;
  9572. this.__graph.call(this);
  9573. }
  9574. catch(e)
  9575. {
  9576. console.log(e.toString());
  9577. }
  9578. },
  9579. __graph: function()
  9580. {
  9581. console.log('creating graph');
  9582. var root = this, pois = this.__pois, style = this.__style;
  9583. var create = function(a, b)
  9584. {
  9585. var elm = new root.__element(a);
  9586. if (b instanceof Object) elm.css(b);
  9587. return elm;
  9588. };
  9589. var addRow = function(title, arr, table, selected)
  9590. {
  9591. var row = create('tr', style.rows.tr), header = create('td', style.cell.header);
  9592. row.elm.onclick = function()
  9593. {
  9594. var tr = table.elm.getElementsByTagName('tr');
  9595. for (var i = 1; i < tr.length; i++)
  9596. {
  9597. tr[i].style.backgroundColor = '#d6dde1';
  9598. }
  9599. this.style.backgroundColor ='#ecf6fc';
  9600. };
  9601. if (selected == 1) row.css({'backgroundColor': '#ecf6fc'});
  9602. header.text(title);
  9603. row.append(header);
  9604. for (var key in arr)
  9605. {
  9606. var td = create('td', style.cell.data);
  9607. td.text(arr[key]);
  9608. row.append(td);
  9609. }
  9610. table.append(row);
  9611. };
  9612. var table = create('table', style.table);
  9613. var gc = create('tr', style.rows.graph);
  9614. var gh = create('td');
  9615. var ul = create('ul', style.icon.ul);
  9616. table.set({"id": "data", "cell-spacing": 0, "cell-padding": 0, "rules": "groups", "width": "100%"});
  9617. gh.append(ul);
  9618. gc.append(gh);
  9619. table.append(gc);
  9620. var score = [], tier = [], nextTier = [], bns = [], nextBns = [], poiRank = [], m = 0;
  9621. for (var key in pois)
  9622. {
  9623. var color = pois[key].c,
  9624. name = key,
  9625. h = pois[key].h,
  9626. td = create('td', style.graph.td),
  9627. div = create('div', style.graph.div),
  9628. li = create('li', style.icon.li),
  9629. icon = create('div', style.icon.div),
  9630. p = create('p', style.icon.p);
  9631. bns[m] = pois[key].tb;
  9632. poiRank[m] = pois[key].r;
  9633. score[m] = pois[key].s;
  9634. tier[m] = pois[key].t;
  9635. nextTier[m] = pois[key].nt;
  9636. nextBns[m] = pois[key].ntb;
  9637. div.css({'backgroundColor': color, 'height': h * 2 - 3 + 'px'});
  9638. td.append(div);
  9639. gc.append(td);
  9640. icon.css({'backgroundColor': color});
  9641. p.text(name);
  9642. li.append(icon);
  9643. li.append(p);
  9644. ul.append(li);
  9645. m++;
  9646. }
  9647. addRow('Tier', tier, table, 0);
  9648. addRow('Alliance Rank', poiRank, table, 0);
  9649. addRow('Score', score, table);
  9650. addRow('Next Tier Requires', nextTier, table, 0);
  9651. addRow('Bonus', bns, table, 1);
  9652. addRow('Next Tier Bonus', nextBns, table, 0);
  9653. document.getElementById('graph').appendChild(table.elm);
  9654. }
  9655. }
  9656. });
  9657. }
  9658. function initialize_ccta_pa()
  9659. {
  9660. console.log('poiAnalyser: ' + 'POIs Analyser retrying...');
  9661. if (typeof qx != 'undefined' && typeof qx.core != 'undefined' && typeof qx.core.Init != 'undefined' && typeof ClientLib != 'undefined' && typeof webfrontend != 'undefined' && typeof phe != 'undefined')
  9662. {
  9663. var app = qx.core.Init.getApplication();
  9664. if (app.initDone == true)
  9665. {
  9666. try
  9667. {
  9668. var isDefined = function(a){return (typeof a == 'undefined') ? false : true};
  9669. var data = ClientLib.Data.MainData.GetInstance();
  9670. var net = ClientLib.Net.CommunicationManager.GetInstance();
  9671. if (isDefined(data) && isDefined(net))
  9672. {
  9673. var alliance = data.get_Alliance();
  9674. var player = data.get_Player();
  9675. var poiUtil = ClientLib.Base.PointOfInterestTypes;
  9676. var poiInfo = phe.cnc.gui.util.Text.getPoiInfosByType;
  9677. if (isDefined(alliance) && isDefined(player) && isDefined(alliance.get_Exists()) && isDefined(player.get_Name()) && player.get_Name() != '' && isDefined(poiUtil) && isDefined(poiInfo))
  9678. {
  9679. try
  9680. {
  9681. console.log('poiAnalyser: ' + 'initializing POIs Analyser');
  9682. create_ccta_pa_class();
  9683. ccta_pa.getInstance();
  9684. }
  9685. catch(e)
  9686. {
  9687. console.log('poiAnalyser: ' + "POIs Analyser script init error:");
  9688. console.log('poiAnalyser: ' + e.toString());
  9689. }
  9690. }
  9691. else window.setTimeout(initialize_ccta_pa, 10000);
  9692. }
  9693. else window.setTimeout(initialize_ccta_pa, 10000);
  9694. }
  9695. catch(e)
  9696. {
  9697. console.log('poiAnalyser: ' + e.toString());
  9698. }
  9699. }
  9700. else window.setTimeout(initialize_ccta_pa, 10000);
  9701. }
  9702. else window.setTimeout(initialize_ccta_pa, 10000);
  9703. };
  9704. window.setTimeout(initialize_ccta_pa, 10000);
  9705. };
  9706. function inject()
  9707. {
  9708. var script = document.createElement("script");
  9709. script.innerHTML = "(" + injectScript.toString() + ")();";
  9710. script.type = "text/javascript";
  9711. if (/commandandconquer\.com/i.test(document.domain)) {
  9712. document.getElementsByTagName("head")[0].appendChild(script);
  9713. console.log('injected');
  9714. }
  9715. };
  9716. inject();
  9717. })();