· 8 years ago · Nov 28, 2017, 08:12 PM
1// ==UserScript==
2// @name Dead Fish
3// @namespace koc.dead.fish
4// @include http://www.kingsofchaos.com/*
5// @exclude http://*.kingsofchaos.com/confirm.login.php*
6// @exclude http://*.kingsofchaos.com/security.php*
7// @exclude http://www.kingsofchaos.com/error.php
8// @exclude http://www.kingsofchaos.com/inbox.php
9// @exclude http://www.kingsofchaos.com/attacklog.php
10// @exclude http://www.kingsofchaos.com/detail.php
11// @grant unsafeWindow
12// @grant GM_xmlhttpRequest
13// @grant GM_setValue
14// @grant GM_getValue
15// @grant GM_deleteValue
16// @grant GM_openInTab
17// @grant GM_addStyle
18
19// ==/UserScript==
20// Google Chrome Support
21var isChrome = /Chrome/.test(navigator.userAgent) && /Google Inc/.test(navigator.vendor);
22if (isChrome) {
23 this.GM_getValue=function (key,def) {
24 return localStorage[key] || def;
25 };
26 this.GM_setValue=function (key,value) {
27 return localStorage[key]=value;
28 };
29 this.GM_deleteValue=function (key) {
30 return delete localStorage[key];
31 };
32}
33
34if(DetectRunningInstance() == true)
35{
36 alert("You are running multiple instances of the DF script!\nManually remove the duplicates from Greasemonkey menu.");
37}
38
39var DF_version = 42;
40var DF_server = "http://againstallauthority.nl/script/";
41
42var DF_username = GM_getValue("DF_username", "");
43var DF_password = GM_getValue("DF_password", "");
44var DF_statid = GM_getValue("DF_statid", "");
45
46var soldiers; // used on some pages like train.php, mercs.php
47var mercs; // available mercs
48var bfPlayers = []; // list of stats for players on the current bf
49
50var gold = GetGold();
51var url = document.location.toString();
52
53
54var weaponList = ["Blackpowder Missile", "Invisibility Shield", "Chariot", "Dragonskin", "Nunchaku", "Lookout Tower", "Skeleton Key", "Guard Dog", "Grappling Hook"];
55var _weapons = [
56 {afk:'BPM', name:'Blackpowder Missile'},
57 {afk:'CH', name:'Chariot'},
58 {afk:'IS', name:'Invisibility Shield'},
59 {afk:'DS', name:'Dragonskin'},
60 {afk:'NUN', name:'Nunchaku'},
61 {afk:'SK', name:'Skeleton Key'},
62 {afk:'GH', name:'Grappling Hook'},
63 {afk:'CK', name:'Cloak'},
64 {afk:'LT', name:'Lookout Tower'},
65 {afk:'GD', name:'Guard Dog'},
66 {afk:'TW', name:'Tripwire'},
67];
68
69if(document.body.innerHTML.indexOf("logout.php") < 0
70 || document.body.innerHTML.indexOf("is a registered trademark of Kings of Chaos") < 0)
71{
72 //logged out or incomplete page
73}
74
75checkVersion();
76
77AddMenuItems();
78
79CheckExpForNextTech();
80
81if(url.indexOf("/base.php") > 0)
82{
83 BasePHP();
84}
85else if(url.indexOf("/armory.php") > 0)
86{
87 ArmoryPHP();
88}
89else if(url.indexOf("/train.php") > 0)
90{
91 TrainPHP();
92}
93else if(url.indexOf("/mercs.php") > 0)
94{
95 MercsPHP();
96}
97else if(url.indexOf("/stats.php") > 0)
98{
99 StatsPHP();
100}
101else if(url.indexOf("/attack.php") > 0)
102{
103 AttackPHP();
104}
105else if(url.indexOf("/inteldetail.php") > 0)
106{
107 InteldetailPHP();
108}
109else if(url.indexOf("/detail.php") > 0)
110{
111 DetailPHP();
112}
113else if(url.indexOf("/battlefield.php") > 0)
114{
115 BattlefieldPHP();
116}
117else if(url.indexOf("/conquest.php") > 0)
118{
119 ConquestPHP();
120}
121else if(url.indexOf("/writemail.php") > 0)
122{
123 WritemailPHP();
124}
125else if(url.indexOf("/attacklog.php") > 0)
126{
127 AttackLogPHP();
128}
129else if(url.indexOf("/inbox.php") > 0)
130{
131 InboxPHP();
132}
133else if(url.indexOf("/recruit.php") > 0)
134{
135 RecruitPHP();
136}
137
138//scroll into the content (on detail php, it scrolls itself)
139if(GM_getValue("DF_OptionScrollIntoContent", 1) != 0 && url.indexOf("/detail.php") < 0)
140{
141 document.getElementsByTagName('table')[2].scrollIntoView();
142}
143
144if(GM_getValue("DF_OptionStickyMenu", 0) != 0)
145{
146 var cell_menu = document.getElementsByClassName('menu_cell')[0];
147 cell_menu.setAttribute('style', 'width:;');
148 var html = cell_menu.innerHTML;
149 cell_menu.innerHTML= "";
150
151 var outer = document.createElement('div');
152 outer.setAttribute('style', 'width:137px;');
153
154 var inner = document.createElement('div');
155 inner.id = "sticky_menu";
156 inner.innerHTML = html;
157
158 outer.appendChild(inner);
159 cell_menu.appendChild(outer);
160
161 window.onscroll = function(){
162 if(document.body.scrollTop > 160){
163 document.getElementById('sticky_menu').setAttribute('style', 'position:fixed;left:5px;top:5px;');
164 }
165 else {
166 document.getElementById('sticky_menu').setAttribute('style', '');
167 }
168 }
169}
170
171AddBfSearch();
172
173// If any traces left, disable.
174// Disable hotkeys as per mods request
175GM_setValue("DF_OptionKS", 0);
176
177// Disable armory/train/mercs buy helper
178GM_setValue("DF_OptionBH", 1);
179
180// Disable autoredirect
181GM_setValue("DF_OptionARD", 0);
182
183/*****************************************************************************/
184/********************************* PAGES *************************************/
185/*****************************************************************************/
186function BasePHP()
187{
188 var statid = GetText("b>Name</b", "id=", "\"");
189 var username = GetText("b>Name</b", "\">", "<");
190 var uniqid = GetText("uniqid=", "\"");
191
192 GM_setValue("DF_username", username);
193 GM_setValue("DF_statid", statid);
194 GM_setValue("DF_uniqid", uniqid);
195
196 // Display the custom div on top
197 GM_xmlhttpRequest(
198 {
199 method: "GET",
200 url: DF_server + "checkstatus.php?whoami=" + username + "&password=" + DF_password + "&userid=" + statid + "&recruitid=" + uniqid,
201 onload: function(r)
202 {
203 if(r.status == 200)
204 {
205 //alert(r.responseText); // For Debugging
206 if(r.responseText == "Unregistered")
207 {
208 var customDiv = document.createElement("div");
209 customDiv.innerHTML = "<br><center><table class=table_lines width=100%><tr><th style=\"border-color: darkred; background-color:red; height: 4ex;\">You haven't registered a Dead Fish account!</th></tr>"
210 + "<tr><td><a href=# id=registerDF onClick=\"return false;\">Click here</a> to register your DF account. Please choose an unique password"
211 + "<br><br>If this is not working, contact <a href=http://www.kingsofchaos.com/stats.php?id=4506801>BlAaAstoise</a> via KoC pm.</td></tr>"
212 + "</table></center><br><br>";
213 document.getElementsByClassName("content")[0].insertBefore(customDiv, document.getElementsByClassName('table_lines')[0]);
214
215 document.getElementById('registerDF').addEventListener('click', function(){ BasePHP_OnRegisterDF(username, statid, uniqid, DF_password); }, false);
216 GM_setValue("DF_eligable", 0);
217 }
218 else if(r.responseText == "Invalid Password")
219 {
220 var customDiv = document.createElement("div");
221 customDiv.innerHTML = "<br><center><table class=table_lines width=100%><tr><th style=\"border-color: darkred; background-color:red; height: 4ex;\">Your Dead Fish password is invalid!</th></tr>"
222 + "<tr><td>Click <a href=# id=putDFPassword onClick=\"return false;\">here</a> to re-enter your DF password."
223 + "<br><br>If you do not remember your DF password, contact <a href=http://www.kingsofchaos.com/stats.php?id=4506801>BlAaAstoise</a> via KoC pm.</td></tr>"
224 + "</table></center><br><br>";
225 document.getElementsByClassName("content")[0].insertBefore(customDiv, document.getElementsByClassName('table_lines')[0]);
226
227 document.getElementById('putDFPassword').addEventListener('click', function(){ BasePHP_OnputDFPassword(username, DF_password); }, false);
228 GM_setValue("DF_eligable", 0);
229 }
230 else if(r.responseText == "Not Activated")
231 {
232 var customDiv = document.createElement("div");
233 customDiv.innerHTML = "<br><center><table class=table_lines width=100%><tr><th style=\"border-color: darkorange; background-color:orange; height: 4ex;\">Your Dead Fish account is not activated!</th></tr>"
234 + "<tr><td>If this is taking too long, contact <a href=http://www.kingsofchaos.com/stats.php?id=4506801>BlAaAstoise</a> via KoC pm.</td></tr>"
235 + "</table></center><br><br>";
236 document.getElementsByClassName("content")[0].insertBefore(customDiv, document.getElementsByClassName('table_lines')[0]);
237 GM_setValue("DF_eligable", 0);
238 }
239 else
240 {
241 var customDiv = document.createElement("div");
242 customDiv.innerHTML = r.responseText.indexOf("<div id=\"x\">") >= 0 ? r.responseText : "<center><b>Server is currently down. Please wait a few minutes.</b></center><br>";
243
244 document.getElementsByClassName("content")[0].insertBefore(customDiv, document.getElementsByClassName('table_lines')[0]);
245 GM_setValue("DF_eligable", 1);
246 }
247 }
248 }
249 });
250
251
252 var MilOverviewTable = GetTable("Military Overview");
253 if (MilOverviewTable) {
254 var projIncomeRow = GetTableRow(MilOverviewTable, 0, "<b>Projected Income");
255 if (projIncomeRow >= 0) {
256 var projIncome = GetTextIn(MilOverviewTable.rows[projIncomeRow].cells[1].innerHTML, "", " ").replace(/,/g, "");
257 MilOverviewTable.insertRow(projIncomeRow + 1).innerHTML = "<td><b>Hourly Income</b></td><td>" + AddCommas(Math.floor((projIncome * 60)).toString()) + " Gold (in 60 mins)</td>"
258 }
259 if (projIncomeRow >= 0) {
260 var projIncome = GetTextIn(MilOverviewTable.rows[projIncomeRow].cells[1].innerHTML, "", " ").replace(/,/g, "");
261 MilOverviewTable.insertRow(projIncomeRow + 2).innerHTML = "<td><b>Daily Income</b></td><td>" + AddCommas(Math.floor((projIncome * 60*24)).toString()) + " Gold (per day)</td>"
262 }
263 }
264
265 // Update own stats
266 var sa = GetText(">Strike Action<", "\">", "<").replace(/,/g, "");
267 var da = GetText(">Defensive Action<", "\">", "<").replace(/,/g, "");
268 var spy = GetText(">Spy Rating<", "\">", "<").replace(/,/g, "");
269 var sentry = GetText(">Sentry Rating<", "\">", "<").replace(/,/g, "");
270 var officerBonus = GetText("in today (x ",")");
271
272 var fort = GetText(">Fortification<", "<td>", "</td>");
273 var siege = GetText(">Siege Technology<", "<td>", "</td>");
274 var up = GetText(">Conscription<", "<td>", "</td>").replace(/ soldiers per 24 hours/g, "");
275 var lvl = GetText(">Covert Level<", "<td>", "</td>").replace(/,/g, "");
276 var turns = GetText(">Game Turns<", "<td>", "</td>").replace(/\/ 50000/g, "").replace(/ /g, "").replace(/,/g, "");
277 var soldiers = GetSoldiers();
278
279
280 GM_setValue("DF_Fort", fort);
281 GM_setValue("DF_Siege", siege);
282 GM_setValue("DF_Conscription", up);
283 GM_setValue("DF_CovertSkill", lvl);
284 GM_setValue("DF_Turns", turns);
285 GM_setValue("DF_currentOfficerBonus", officerBonus);
286
287
288 // Add the DF options button
289 var table = GetTag('th', "Preferences").parentNode.parentNode;
290 table.insertRow(2).innerHTML = "<td align=center><a style=\"cursor:pointer\" id=bOpenDFOptions>DF Options</a>";
291 document.getElementById('bOpenDFOptions').addEventListener('click', BasePHP_OnToggleDFOptions, false);
292
293 // Add the DF options
294 var dfOptions = "<table width=100% class=table_lines cellspacing=0 cellpadding=8><tr><th colspan=2>DF Options</th></tr>"
295 + "<tr><td align=right><label for=dfOptionArmoryDetail>Add Armory Detail Stats</label></td><td><input type=checkbox id=dfOptionArmoryDetail " + (GM_getValue("DF_OptionArmoryDetail", 1) == 0 ? "" : "checked") + "></input></td></tr>"
296 + "<tr><td align=right><label for=dfOptionScrollIntoContent>Scroll into the content</label></td><td><input type=checkbox id=dfOptionScrollIntoContent " + (GM_getValue("DF_OptionScrollIntoContent", 1) == 0 ? "" : "checked") + "></input></td></tr>"
297 + "<tr><td align=right><label for=dfOptionEconomicDevelopment>Remove Economic Development</label></td><td><input type=checkbox id=dfOptionEconomicDevelopment " + (GM_getValue("DF_OptionEconomicDevelopment", 1) == 0 ? "" : "checked") + "></input></td></tr>"
298 + "<tr><td align=right><label for=dfOptionSpecialEffects>Special effects</label></td><td><input type=checkbox id=dfOptionSpecialEffects " + (GM_getValue("DF_OptionSpecialEffects", 1) == 0 ? "" : "checked") + "></input></td></tr>"
299 + "<tr><td align=right><label for=dfOptionShowLastMsgSent>Show last msg sent</label></td><td><input type=checkbox id=dfOptionShowLastMsgSent " + (GM_getValue("DF_OptionShowLastMsgSent", 1) == 0 ? "" : "checked") + "></input></td></tr>"
300 + "<tr><td align=right><label for=dfOptionStickyMenu>Sticky menu</label></td><td><input type=checkbox id=dfOptionStickyMenu " + (GM_getValue("DF_OptionStickyMenu", 0) == 0 ? "" : "checked") + "></input></td></tr>"
301 + "<tr><td align=right>Password</td><td><input id=dfOptionPassword value=\"" + GM_getValue("DF_password", "") + "\"></input></td></tr>"
302 + "<tr><td colspan=2 align=right style=\"border-bottom:0; padding:2em;\"><button id=bSaveDFOptions>Save</button> <button id=bCancelDFOptions>Cancel</button></td></tr>"
303 + "</table>";
304
305 var dfOptionsContainerDiv = document.createElement('div');
306 dfOptionsContainerDiv.innerHTML = "<div id=ddfOptionsContainer style=\"display:none; position:fixed; width:100%; height:100%; left:0; top:0; background-color:gray; opacity:0.50; z-index:10;\"></div>";
307
308 var dfOptionsDiv = document.createElement('div');
309 dfOptionsDiv.innerHTML = "<div id=ddfOptions style=\"display:none; position:fixed; width:60ex; height:25em; left:50%; margin-left:-30ex; top:50%; margin-top:-10em; background-color:black; z-index:15; padding:10px;\">" + dfOptions + "</div>";
310
311 document.body.appendChild(dfOptionsContainerDiv);
312 document.body.appendChild(dfOptionsDiv);
313
314 document.getElementById('bSaveDFOptions').addEventListener('click', BasePHP_OnSaveDFOptions, false);
315 document.getElementById('bCancelDFOptions').addEventListener('click', BasePHP_OnToggleDFOptions, false);
316
317 // Expand/collapse tables
318 ExpandCollapseTable("Grow Your Army");
319 ExpandCollapseTable("Notice from Commander");
320 ExpandCollapseTable("Recent Attacks on You");
321 ExpandCollapseTable("Military Overview");
322 ExpandCollapseTable("Military Effectiveness");
323 ExpandCollapseTable("Previous Logins");
324 ExpandCollapseTable("Preferences");
325 ExpandCollapseTable("Officers");
326}
327
328function ArmoryPHP()
329{
330 if(GM_getValue("DF_eligable", 0) == 0)
331 {
332 return;
333 }
334
335 // Update own stats
336 var sa = GetText(">Strike Action<", "\">", "<").replace(/,/g, "");
337 var da = GetText(">Defensive Action<", "\">", "<").replace(/,/g, "");
338 var spy = GetText(">Spy Rating<", "\">", "<").replace(/,/g, "");
339 var sentry = GetText(">Sentry Rating<", "\">", "<").replace(/,/g, "");
340
341 var fort = GM_getValue("DF_Fort", "");
342 var siege = GM_getValue("DF_Siege", "");
343 var up = GM_getValue("DF_Conscription", 0);
344 var lvl = GM_getValue("DF_CovertSkill",0);
345 var turns = GM_getValue("DF_Turns",0);
346
347 // Read current weapons and tools
348 var statsTable = GetTable("Military Effectiveness");
349 var weaponsTable = GetTable("Current Weapon Inventory");
350 var toolsTable = GetTable("Current Tool Inventory");
351 var buyWeaponsTable = GetTable("Buy Weapons");
352
353 // Show how much weapon is held
354 soldiers = GetSoldiers();
355
356 var weapons = []; // holds the number of current weapons+tools (length is same as the global weaponList)
357 var totalSellValue = 0;
358 var totalInvestedValue = 0;
359
360 var totalAttackWeapons = 0;
361 var totalDefenseWeapons = 0;
362 var totalSpyTools = 0;
363 var totalSentryTools = 0;
364
365 for(var i = 0; i < weaponList.length; i++)
366 {
367 weapons.push(0);
368 }
369
370 var passedDefenseWeapons = 0;
371 var idxDefenseWeaponsTh = -1;
372
373 for(var i = 0; i < weaponsTable.rows.length; i++)
374 {
375 if(weaponsTable.rows[i].cells.length < 4) continue;
376
377 var wepName = weaponsTable.rows[i].cells[0].innerHTML;
378
379 if(wepName == "Defense Weapons")
380 {
381 passedDefenseWeapons = 1;
382 idxDefenseWeaponsTh = i;
383 continue;
384 }
385
386 var wepCount = parseInt( weaponsTable.rows[i].cells[1].innerHTML.replace(/,/g, "") );
387 var wepSell = parseInt( GetTextIn(weaponsTable.rows[i].cells[3].innerHTML, "Sell for ", " Gold").replace(/,/g, "") );
388
389 if(isNaN(wepCount) == false && isNaN(wepSell) == false)
390 {
391 totalSellValue += (wepCount * wepSell);
392 }
393
394 var j = GetTableRow(buyWeaponsTable, 0, wepName);
395 if(j >= 0)
396 {
397 var wepCost = parseInt( buyWeaponsTable.rows[j].cells[2].innerHTML.replace(/,/g, "") );
398 if(isNaN(wepCount) == false && isNaN(wepCost) == false)
399 {
400 totalInvestedValue += (wepCount * wepCost);
401 }
402 }
403
404 var idx = weaponList.indexOf(wepName);
405 if(idx >= 0)
406 {
407 weapons[idx] = wepCount;
408 }
409
410 if(passedDefenseWeapons == 0)
411 {
412 totalAttackWeapons += wepCount;
413 }
414 else
415 {
416 totalDefenseWeapons += wepCount;
417 }
418 }
419
420 // same for the tools
421 var passedSentryTools = 0;
422 var idxSentryToolsTh = -1;
423
424 for(var i = 0; i < toolsTable.rows.length; i++)
425 {
426 if(toolsTable.rows[i].cells.length < 4) continue;
427
428 var wepName = toolsTable.rows[i].cells[0].innerHTML;
429
430 if(wepName == "Sentry Tools")
431 {
432 passedSentryTools = 1;
433 idxSentryToolsTh = i;
434 continue;
435 }
436
437
438
439 var wepCount = parseInt( toolsTable.rows[i].cells[1].innerHTML.replace(/,/g, "") );
440 var wepSell = parseInt( GetTextIn(toolsTable.rows[i].cells[3].innerHTML, "Sell for ", " Gold").replace(/,/g, "") );
441
442 if(isNaN(wepCount) == false && isNaN(wepSell) == false)
443 {
444 totalSellValue += (wepCount * wepSell);
445 }
446
447
448 var j = GetTableRow(buyWeaponsTable, 0, wepName);
449 if(j >= 0)
450 {
451 var wepCost = parseInt( buyWeaponsTable.rows[j].cells[2].innerHTML.replace(/,/g, "") );
452 if(isNaN(wepCount) == false && isNaN(wepCost) == false)
453 {
454 totalInvestedValue += (wepCount * wepCost);
455 }
456 }
457
458 var idx = weaponList.indexOf(wepName);
459 if(idx >= 0)
460 {
461 weapons[idx] = wepCount;
462 }
463
464 if(passedSentryTools == 0)
465 {
466 if(isNaN(wepCount) == false && isNaN(wepSell) == false)
467 {
468 totalSpyTools += wepCount;
469 }
470 }
471 else
472 {
473 if(isNaN(wepCount) == false && isNaN(wepSell) == false)
474 {
475 totalSentryTools += wepCount;
476 }
477 }
478
479 }
480
481 var strWeapons = "[bpm]" + weapons[0] + "[/bpm][is]" + weapons[1] + "[/is][nun]" + weapons[4] + "[/nun][lt]" + weapons[5] + "[/lt][ch]" + weapons[2] + "[/ch][ds]" + weapons[3] + "[/ds][sk]" + weapons[6] + "[/sk][gd]" + weapons[7] + "[/gd][gh]" + weapons[8] + "[/gh]";
482
483
484
485 // show the aat and sell value (weapons)
486 if(weaponsTable.rows.length > 2)
487 {
488 weaponsTable.rows[1].innerHTML = weaponsTable.rows[1].innerHTML.replace("Weapons</th>", "Weapons</th><th class=subh align=right>AAT</th>");
489 }
490
491 for(var i = 2; i < weaponsTable.rows.length; i++)
492 {
493 if(weaponsTable.rows[i].cells.length < 4) continue;
494
495 var wepName = weaponsTable.rows[i].cells[0].innerHTML;
496 if(wepName == "Defense Weapons")
497 {
498 weaponsTable.rows[i].innerHTML = weaponsTable.rows[i].innerHTML.replace("Weapons</th>", "Weapons</th><th class=subh align=right>AAT</th>");
499 continue;
500 }
501
502 var wepCount = parseInt( weaponsTable.rows[i].cells[1].innerHTML.replace(/,/g, "") );
503 var wepSell = parseInt( GetTextIn(weaponsTable.rows[i].cells[3].innerHTML, "Sell for ", " Gold").replace(/,/g, "") );
504 var sellValue = wepCount * wepSell;
505
506 var j = GetTableRow(buyWeaponsTable, 0, wepName);
507 var wepCost = parseInt( buyWeaponsTable.rows[j].cells[2].innerHTML.replace(/,/g, "") );
508
509 var aat = parseInt( Math.floor(totalInvestedValue / (wepCost * 400)) );
510
511 weaponsTable.rows[i].insertCell(1).innerHTML = AddCommas(Math.min(aat, wepCount).toString());
512 weaponsTable.rows[i].cells[1].setAttribute('align', "right");
513 if(GM_getValue("DF_OptionArmoryDetail", 1) != 0)
514 {
515 weaponsTable.rows[i].cells[0].innerHTML = weaponsTable.rows[i].cells[0].innerHTML + "<br><span style='padding-left: 5px; color: #FFCC00; font-size: 80%;'>Sell value: " + addCommas(sellValue) + "</span>";
516 }
517 }
518
519 // show the aat and sell value (tools)
520 if(toolsTable.rows.length > 2)
521 {
522 toolsTable.rows[1].innerHTML = toolsTable.rows[1].innerHTML.replace("Tools</th>", "Tools</th><th class=subh align=right>AAT</th>");
523 }
524
525 for(var i = 2; i < toolsTable.rows.length; i++)
526 {
527 if(toolsTable.rows[i].cells.length < 4) continue;
528
529 var wepName = toolsTable.rows[i].cells[0].innerHTML;
530 if(wepName == "Sentry Tools")
531 {
532 toolsTable.rows[i].innerHTML = toolsTable.rows[i].innerHTML.replace("Tools</th>", "Tools</th><th class=subh align=right>AAT</th>");
533 continue;
534 }
535
536 var wepCount = parseInt( toolsTable.rows[i].cells[1].innerHTML.replace(/,/g, "") );
537 var wepSell = parseInt( GetTextIn(toolsTable.rows[i].cells[3].innerHTML, "Sell for ", " Gold").replace(/,/g, "") );
538 var sellValue = wepCount * wepSell;
539
540 var j = GetTableRow(buyWeaponsTable, 0, wepName);
541 var wepCost = parseInt( buyWeaponsTable.rows[j].cells[2].innerHTML.replace(/,/g, "") );
542
543 var aat = parseInt( Math.floor(totalInvestedValue / (wepCost * 400)) );
544
545 toolsTable.rows[i].insertCell(1).innerHTML = AddCommas(Math.min(aat, wepCount).toString());
546 toolsTable.rows[i].cells[1].setAttribute('align', "right");
547 if(GM_getValue("DF_OptionArmoryDetail", 1) != 0)
548 {
549 toolsTable.rows[i].cells[0].innerHTML = toolsTable.rows[i].cells[0].innerHTML + "<br><span style='padding-left: 5px; color: #FFCC00; font-size: 80%;'>Sell value: " + addCommas(sellValue) + "</span>";
550 }
551 }
552
553 if(GM_getValue("DF_OptionArmoryDetail", 1) != 0)
554 {
555 // TO-DO: Merge this with above. So we don't have to do another loop
556 // Add strength for each weapon
557 var htmlHead = document.getElementsByTagName("head")[0].innerHTML;
558 var myRace = FindText(FindText(htmlHead,'<link href="/images/css/common.css" rel="','css" r'),'/css/','.');
559 var saBonus = 1;
560 var daBonus = 1;
561 var spyBonus = 1;
562 var sentryBonus = 1;
563
564 switch(myRace)
565 {
566 case 'Humans': { spyBonus = 1.35; break;}
567 case 'Dwarves': { daBonus = 1.4; break; }
568 case 'Elves': { spyBonus = 1.45; break;}
569 case 'Orcs': { daBonus = 1.2; saBonus = 1.35; break; }
570 case 'Undead': { sentryBonus = 1.35; break;}
571 }
572
573 var techMulti = GM_getValue("DF_currentTech", 1);
574 var officerBonus = GM_getValue("DF_currentOfficerBonus", 1);
575
576 var myFortText = FindText(FindText(document.body.innerHTML,'Current Fortification','<td align="center">'),'<td>','</td>').split(" (")[0];
577 var mySiegeText = FindText(FindText(document.body.innerHTML,'Current Siege Technolog','<td align="center">'),'<td>','</td>').split(" (")[0];
578
579 SiegeArray = SiegeList(mySiegeText).split('|');
580 FortArray = FortList(myFortText).split('|');
581 // Returns: Multiply | Next Upgrade | Next Price | Next Multiply
582
583 var siegeBonus = 0;
584 var fortBonus = 0;
585
586 if(SiegeArray[0] != "Max")
587 siegeBonus = SiegeArray[0];
588 else {
589 siegeBonus = 39.37;
590 }
591
592 if(FortArray[0] != "Max")
593 fortBonus = FortArray[0];
594 else
595 fortBonus = 35.53;
596
597 var strength = 0;
598 var atDefenseWeapons = 0;
599 var atSentryTools = 0;
600
601 for(var i = 2; i < weaponsTable.rows.length; i++)
602 {
603 var wepName = weaponsTable.rows[i].cells[0].innerHTML;
604 //alert(wepName);
605 if(wepName == "Defense Weapons")
606 {
607 atDefenseWeapons = 1;
608 continue;
609 }
610 if(wepName.indexOf("repair") > 0)
611 {
612 continue;
613 }
614
615 strength = weaponsTable.rows[i].cells[3].innerHTML.split("/")[1].replace(/,/g, "");
616
617 if(atDefenseWeapons == 0)
618 weaponsTable.rows[i].cells[3].innerHTML = weaponsTable.rows[i].cells[3].innerHTML + "<div style=\"display: inline; color: #905000; font-size: 80%; cursor: help;\" title=\"The strength of 1 weapon\"><br>[" + addCommas(Math.round(strength * techMulti * officerBonus * saBonus * siegeBonus * 5)) + "]</div>";
619 else
620 weaponsTable.rows[i].cells[3].innerHTML = weaponsTable.rows[i].cells[3].innerHTML + "<div style=\"display: inline; color: #905000; font-size: 80%; cursor: help;\" title=\"The strength of 1 weapon\"><br>[" + addCommas(Math.round(strength * techMulti * officerBonus * daBonus * fortBonus * 5)) + "]</div>";
621
622 }
623
624 for(var i = 2; i < toolsTable.rows.length; i++)
625 {
626 if(toolsTable.rows[i].cells.length < 4) continue;
627
628 strength = toolsTable.rows[i].cells[3].innerHTML.replace(/,/g, "");
629
630 var wepName = toolsTable.rows[i].cells[0].innerHTML;
631 if(wepName == "Sentry Tools")
632 {
633 atSentryTools = 1;
634 continue;
635 }
636
637 if(atSentryTools == 0)
638 toolsTable.rows[i].cells[3].innerHTML = toolsTable.rows[i].cells[3].innerHTML + "<div style=\"display: inline; color: #905000; font-size: 80%; cursor: help;\" title=\"The strength of 1 weapon\"><br>[" + addCommas(Math.round(strength * officerBonus * techMulti * spyBonus * Math.pow(1.60,GM_getValue("DF_CovertSkill",15)))) + "]</div>";
639 else
640 toolsTable.rows[i].cells[3].innerHTML = toolsTable.rows[i].cells[3].innerHTML + "<div style=\"display: inline; color: #905000; font-size: 80%; cursor: help;\" title=\"The strength of 1 weapon\"><br>[" + addCommas(Math.round(strength * officerBonus * techMulti * sentryBonus * Math.pow(1.60,GM_getValue("DF_CovertSkill",15)))) + "]</div>";
641 }
642 }
643
644 if(totalAttackWeapons > 0)
645 {
646 var attackSoldiers = soldiers.tas + soldiers.tam + soldiers.us + soldiers.um;
647 var unheld = totalAttackWeapons - attackSoldiers;
648 if(unheld > 0)
649 {
650 weaponsTable.rows[1].cells[0].innerHTML += " <span style='color:red; border-left: 1px solid white'> Unheld: " + unheld + "</span>";
651 }
652 }
653
654 if(totalDefenseWeapons > 0)
655 {
656 var defenseSoldiers = soldiers.tds + soldiers.tdm + soldiers.us + soldiers.um;
657 var unheld = totalDefenseWeapons - defenseSoldiers;
658 if(unheld > 0)
659 {
660 weaponsTable.rows[idxDefenseWeaponsTh].cells[0].innerHTML += " <span style='color:red; border-left: 1px solid white'> Unheld: " + unheld + "</span>";
661 }
662 }
663
664 if(totalSpyTools > 0)
665 {
666 var unheld = totalSpyTools - soldiers.spy;
667 if(unheld > 0)
668 {
669 toolsTable.rows[1].cells[0].innerHTML += " <span style='color:red; border-left: 1px solid white'> Unheld: " + unheld + "</span>";
670
671 var calculatedSpy = 0;
672 //spy tools
673 var spyTools = ["Nunchaku", "Skeleton Key", "Grappling Hook"];
674 for( var i =0; i < spyTools.length; i++){
675 var index = weaponList.indexOf(spyTools[i]);
676 if(index >= 0)
677 {
678 var number = weapons[index];
679 var strength = GetStrength(spyTools[i]);
680 calculatedSpy += Math.round(number * strength * officerBonus * techMulti * spyBonus * Math.pow(1.60,GM_getValue("DF_CovertSkill",15)))
681 }
682 }
683 //spies
684 calculatedSpy += Math.round(soldiers.spy * 1 * officerBonus * techMulti * spyBonus * Math.pow(1.60,GM_getValue("DF_CovertSkill",15)))
685
686 if(calculatedSpy > spy){
687 statsTable.rows[3].cells[0].innerHTML += "<br/> <span style='padding-left: 5px; color: #FFCC00; font-size: 80%;'>If all held: " + addCommas(calculatedSpy) + "</span>";
688 }
689 }
690 }
691
692 if(totalSentryTools > 0)
693 {
694 var unheld = totalSentryTools - soldiers.sentry;
695 if(unheld > 0)
696 {
697 toolsTable.rows[idxSentryToolsTh].cells[0].innerHTML += " <span style='color:red; border-left: 1px solid white'> Unheld: " + unheld + "</span>";
698
699 var calculatedSentry = 0;
700 //sentry tools
701 var sentryTools = ["Lookout Tower", "Guard Dog"];
702 for( var i =0; i < sentryTools.length; i++){
703 var index = weaponList.indexOf(sentryTools[i]);
704 if(index >= 0)
705 {
706 var number = weapons[index];
707 var strength = GetStrength(sentryTools[i]);
708 calculatedSentry += Math.round(number * strength * officerBonus * techMulti * sentryBonus * Math.pow(1.60,GM_getValue("DF_CovertSkill",15)))
709 }
710 }
711 //sentries
712 calculatedSentry += Math.round(soldiers.sentry * 1 * officerBonus * techMulti * sentryBonus * Math.pow(1.60,GM_getValue("DF_CovertSkill",15)))
713
714 if(calculatedSentry > sentry){
715 statsTable.rows[4].cells[0].innerHTML += "<br/> <span style='padding-left: 5px; color: #FFCC00; font-size: 80%;'> If all held: " + addCommas(calculatedSentry) + "</span>";
716 }
717 }
718 }
719
720
721 // Fix the width of the weapons and tools table together
722 if(!weaponsTable.rows[1].cells[0].value == 'There are no weapons in your inventory.')
723 {
724 weaponsTable.rows[1].cells[0].width = '20%';
725 weaponsTable.rows[1].cells[1].width = '15%';
726 weaponsTable.rows[1].cells[2].width = '15%';
727 weaponsTable.rows[1].cells[3].width = '15%';
728 weaponsTable.rows[1].cells[4].width = '35%';
729 }
730
731 //alert(toolsTable.rows[1].cells[0].innerHTML);
732 if(!toolsTable.rows[1].cells[0] == 'undefined') { toolsTable.rows[1].cells[0].width = '20%'; }
733 if(!toolsTable.rows[1].cells[1] == 'undefined') { toolsTable.rows[1].cells[1].width = '15%'; }
734 if(!toolsTable.rows[1].cells[2] == 'undefined') { toolsTable.rows[1].cells[2].width = '15%'; }
735 if(!toolsTable.rows[1].cells[3] == 'undefined') { toolsTable.rows[1].cells[3].width = '15%'; }
736 if(!toolsTable.rows[1].cells[4] == 'undefined') { toolsTable.rows[1].cells[4].width = '35%'; }
737
738 // Fix the centerization of strength in tools table
739 for(var i = 0; i < toolsTable.rows.length; i++)
740 {
741 if(toolsTable.rows[i].cells.length >= 5)
742 {
743 toolsTable.rows[i].cells[3].align = "right";
744
745 // make the tools sell form 90% to align with the weapons
746 var toolId = GetTextIn(toolsTable.rows[i].cells[4].innerHTML, "scrapsell[", "]");
747 if(toolId == "")
748 {
749 continue;
750 }
751
752 var e = document.getElementsByName("scrapsell[" + toolId + "]");
753 if(e.length != 1)
754 {
755 continue;
756 }
757
758 e[0].parentNode.parentNode.parentNode.parentNode.width = "90%";
759 e[0].parentNode.parentNode.parentNode.parentNode.align = "center";
760 }
761 }
762
763 // Show the armory value
764 toolsTable.insertRow(-1).innerHTML = "<td colspan=5></td>";
765 toolsTable.insertRow(-1).innerHTML = "<td colspan=5 align=center style='background-color:#003333; border-bottom:0'><strong>Sell value: " + AddCommas(totalSellValue.toString()) + " Gold</strong><strong> - Buy value: " + AddCommas(totalInvestedValue.toString()) + " Gold</strong></td>";
766
767 // Check for loss
768 var lostLog = [];
769
770 var nowDate = new Date();
771 var now = nowDate.getTime();
772
773 var BPM = 0;
774 var CH = 0;
775 var DS = 0;
776 var IS = 0;
777
778 for(var i = 0; i < weaponList.length; i++)
779 {
780 if(weaponList[i] == 'Invisibility Shield') { IS = weapons[i]; }
781 if(weaponList[i] == 'Dragonskin') { DS = weapons[i]; }
782 if(weaponList[i] == 'Blackpowder Missile') { BPM = weapons[i]; }
783 if(weaponList[i] == 'Chariot') { CH = weapons[i]; }
784
785 var oldCount = GM_getValue("DF_armory_" + weaponList[i].replace(/ /g, "_"), -1);
786 var soldCount = GM_getValue("DF_armory_" + weaponList[i].replace(/ /g, "_") + "_sold", 0);
787
788 oldCount -= soldCount;
789
790 if(weapons[i] < oldCount)
791 {
792 lostLog.push((oldCount - weapons[i]) + ":" + weaponList[i] + ":" + now);
793 }
794
795 GM_setValue("DF_armory_" + weaponList[i].replace(/ /g, "_"), weapons[i]);
796 GM_setValue("DF_armory_" + weaponList[i].replace(/ /g, "_") + "_sold", 0);
797 }
798
799 // Keep the last 10 logs of lost weapons
800 var lostLogGlobal = [];
801
802 for(var i = 0; i < 10; i++)
803 {
804 lostLogGlobal.push(GM_getValue("DF_lost_wep_log_" + i, "::"));
805 }
806
807 // Add to the lost weapon log
808 var lostLogTop = []; // to show at the top of the page
809
810 for(var i = 0; i < lostLog.length; i++)
811 {
812 lostLogGlobal.unshift(lostLog[i]);
813
814 var lostWepDetails = lostLog[i].split(":");
815 lostLogTop.push("You are missing " + lostWepDetails[0] + " " + lostWepDetails[1] + (lostWepDetails[0] > 1 ? "s" : ""));
816 }
817
818 if(lostLogTop.length > 0)
819 {
820 weaponsTable.insertRow(0).innerHTML = "<td colspan=5 style='background-color:red'><strong>" + lostLogTop.join("<br>") + "</strong></td>";
821
822 // Special effect, I made this, dont steal!
823 if(GM_getValue("DF_OptionSpecialEffects", 1) != 0)
824 {
825 var bloodDiv = document.createElement('div');
826 bloodDiv.setAttribute('style', "position:fixed; left:0; top:0; width:100%; height:100%; background-color:red; opacity:1.0; z-index:1000;");
827 bloodDiv.setAttribute('id', "bloodDiv");
828 document.body.appendChild(bloodDiv);
829
830 setTimeout(ArmoryPHP_ReduceBloodEffect, 100);
831 }
832 }
833
834
835 if(GM_getValue("DF_OptionArmoryDetail", 1) != 0)
836 {
837 // When to upgrade (Added By Shane)
838 var htmlHead = document.getElementsByTagName("head")[0].innerHTML;
839 var myRace = FindText(FindText(htmlHead,'<link href="/images/css/common.css" rel="','css" r'),'/css/','.');
840 var saBonus=1;
841 var daBonus=1;
842
843 var techMulti = GM_getValue("DF_currentTech", 1);
844 var officerBonus = GM_getValue("DF_currentOfficerBonus", 1);
845
846 switch(myRace)
847 {
848 case 'Dwarves': { daBonus = 1.4; break }
849 case 'Orcs': { daBonus = 1.2;saBonus = 1.35; break }
850 }
851
852 var upgradeTable = GetTable("Armory Autofill Preferences");
853 upgradeTable.insertRow(-1).innerHTML = "<td colspan=3></td>";
854 upgradeTable.insertRow(-1).innerHTML = "<th colspan=3>Upgrade Table</th>";
855
856 var myFort = FindText(FindText(document.body.innerHTML,'Current Fortification','<td align="center">'),'<td>','</td>').split(" (")[0]
857 var mySiege = FindText(FindText(document.body.innerHTML,'Current Siege Technolog','<td align="center">'),'<td>','</td>').split(" (")[0]
858
859 GM_setValue("DF_Fort", myFort);
860 GM_setValue("DF_Siege", mySiege);
861
862 FortArray = FortList(myFort).split('|');
863 SiegeArray = SiegeList(mySiege).split('|');
864 // Returns: Multiply | Next Upgrade | Next Price | Next Multiply
865
866 var BPMMsg = '';
867 var CHMsg = '';
868 var ISMsg = '';
869 var DSMsg = '';
870
871 var attackSol = ((((soldiers.tas + soldiers.tam) * 5) * techMulti) * officerBonus);
872 var defenceSol = ((((soldiers.tds + soldiers.tdm) * 5) * techMulti) * officerBonus);
873 var untrainedSol = ((((soldiers.us + soldiers.um) * 4) * techMulti) * officerBonus);
874
875 if((!isNaN(BPM)) && (!isNaN(CH))) {
876
877 if(SiegeArray[1] != 'Max') // We have some upgrades left.
878 {
879 var currentSA = ((((BPM*SiegeArray[0])*1000)*6)*saBonus + ((((CH*SiegeArray[0])*600)*6)*saBonus)); // Forumla is correct.
880
881 var tmpcurrentSA = addCommas(Math.round((((currentSA * techMulti) * officerBonus) + attackSol) + untrainedSol));
882
883
884 var sellBPM = Math.round(removeComma(SiegeArray[2]) / 700000);
885 var sellCH = Math.round(removeComma(SiegeArray[2]) / 315000);
886
887 var newBPM = BPM-sellBPM; //New amount of BPM after selling for upgrade.
888 var newCH = CH-sellCH;
889
890
891 var newSA = (((newBPM*SiegeArray[3])*1000)*6)*saBonus + (((CH*SiegeArray[3])*600)*6)*saBonus;
892 var newSACH = (((newCH*SiegeArray[3])*600)*6)*saBonus + (((BPM*SiegeArray[3])*1000)*6)*saBonus
893
894 if(currentSA < newSA)
895 {
896 if(sellBPM < BPM)
897 {
898 BPMMsg += "Sell " + sellBPM + " BPMs and buy " + SiegeArray[1];
899 BPMMsg += "<br>You'll gain " + addCommas(Math.round(((newSA-currentSA) * techMulti)*officerBonus)) + " SA...";
900 }else{
901 BPMMsg += 'Its not profitable to buy ' + SiegeArray[1] + ' yet with BPMs';
902 }
903
904 if(currentSA < newSACH)
905 {
906 if(sellCH < CH){
907 CHMsg += "Sell " + sellCH + " Chariots and buy " + SiegeArray[1];
908 CHMsg += "<br>You'll gain " + addCommas(Math.round(((newSACH-currentSA) * techMulti)*officerBonus)) + " SA...";
909 }else{
910 CHMsg += 'Its not profitable to buy ' + SiegeArray[1] + ' yet with CHs';
911 }
912 }else{
913 CHMsg += 'Its not profitable to buy ' + SiegeArray[1] + ' yet with CHs';
914 }
915 }else{
916 BPMMsg += 'Its not profitable to buy ' + SiegeArray[1] + ' yet with BPMs';
917 if(currentSA < newSACH)
918 {
919 if(sellCH < CH)
920 {
921 CHMsg += "Sell " + sellCH + " Chariots and buy " + SiegeArray[1];
922 CHMsg += "<br>You'll gain " + addCommas(Math.round(((newSACH-currentSA) * techMulti)*officerBonus)) + " SA...";
923 }
924 }else{
925 CHMsg += 'Its not profitable to buy ' + SiegeArray[1] + ' yet with CHs';
926 }
927
928 }
929 }else{
930 CHMsg = 'Already got all sa upgrades.';
931 BPMMsg = 'Already got all sa upgrades.';
932 }
933 }else{
934 CHMsg = "Couldn't detect your Chariots.";
935 BPMMsg = "Couldn't detect your BPMs.";
936 }
937
938
939
940
941 if((!isNaN(IS)) && (!isNaN(DS))) {
942 if(FortArray[1] != 'Max') // We have some upgrades left.
943 {
944 //alert((((1*FortArray[0])*256)*5)*daBonus); // 41,813,923
945 var currentDA = ((((IS*FortArray[0])*1000)*6)*daBonus + (((DS*FortArray[0])*256)*6)*daBonus); // Forumla is correct.
946 var tmpcurrentDA = addCommas(Math.round((((currentDA * techMulti) * officerBonus) + defenceSol) + untrainedSol));
947
948 var sellIS = Math.round(removeComma(FortArray[2]) / 700000);
949 var sellDS = Math.round(removeComma(FortArray[2]) / 140000);
950
951 var newIS = IS-sellIS; //New amount ofIS after selling for upgrade.
952 var newDS = DS-sellDS; //New amount of DS after selling for upgrade.
953
954 var newDA = ((((newIS*FortArray[3])*1000)*6)*daBonus + (((DS*FortArray[3])*256)*6)*daBonus); // Forumla is correct.
955
956 var newDADS = ((((newDS*FortArray[3])*256)*6)*daBonus + (((IS*FortArray[3])*1000)*6)*daBonus); // Forumla is correct.
957
958 if(currentDA < newDA)
959 {
960 if(newIS < IS){
961 ISMsg += "Sell " + sellIS + " ISs and buy " + FortArray[1];
962 ISMsg += "<br>You'll gain " + addCommas(Math.round(((newDA-currentDA) * techMulti)*officerBonus))+ " DA...";
963 }else{
964 ISMsg += 'Its not profitable to buy ' + FortArray[1] + ' yet with ISs';
965 }
966
967 if(currentDA < newDADS)
968 {
969 if(sellDS < DS){
970 DSMsg += "Sell " + sellDS + " Dragon Skins and buy " + FortArray[1];
971 DSMsg += "<br>You'll gain " + addCommas(Math.round(((newDADS-currentDA) * techMulti)*officerBonus))+ " DA...";
972 }else{
973 DSMsg += 'Its not profitable to buy ' + FortArray[1] + ' yet with Dragon Skins';
974 }
975 }else{
976 DSMsg += 'Its not profitable to buy ' + FortArray[1] + ' yet with Dragon Skins';
977 }
978 }else{
979 ISMsg += 'Its not profitable to buy ' + FortArray[1] + ' yet with ISs';
980 if(currentDA < newDADS)
981 {
982 if(sellDS < DS){
983 DSMsg += "Sell " + sellDS + " DSs and buy " + FortArray[1];
984 DSMsg += "<br>You'll gain " + addCommas(Math.round(((newDADS-currentDA) * techMulti)*officerBonus))+ " DA...";
985 }else{
986 DSMsg = 'Its not profitable to buy ' + FortArray[1] + ' with dragon skins';
987 }
988 }else{
989 DSMsg = 'Its not profitable to buy ' + FortArray[1] + ' with dragon skins';
990 }
991 }
992 }else{
993 ISMsg = 'Already got all da upgrades.';
994 DSMsg = 'Already got all da upgrades.';
995 }
996 }else{
997 upgradeMsgDA = "Couldn't detect your IS [or] DS count";
998 }
999
1000 upgradeTable.insertRow(-1).innerHTML = "<td align=right>SA Upgrade</td>"
1001 + "<td align=left>BPM</td>"
1002 + "<td align=left>" + BPMMsg + "</td>";
1003
1004 upgradeTable.insertRow(-1).innerHTML = "<td align=right>SA Upgrade</td>"
1005 + "<td align=left>Chariots</td>"
1006 + "<td align=left>" + CHMsg + "</td>";
1007
1008 upgradeTable.insertRow(-1).innerHTML = "<td align=right>DA Upgrade</td>"
1009 + "<td align=left>IS</td>"
1010 + "<td align=left>" + ISMsg + "</td>";
1011
1012 upgradeTable.insertRow(-1).innerHTML = "<td align=right>DA Upgrade</td>"
1013 + "<td align=left>Dragon Skins</td>"
1014 + "<td align=left>" + DSMsg + "</td>";
1015
1016 upgradeTable.insertRow(-1).innerHTML = "<td colspan=3 align=center><button id=upgradeTest onClick=\"return false;\" style='width:9ex'>Read me</button></td>";
1017
1018 document.getElementById('upgradeTest').addEventListener('click', function(event) {
1019 var testUpgrade = "Upgrade Table is in its beta stage, to ensure people don't make mistakes; use this as a guildline\n\n";
1020 testUpgrade += "Your SA is: " + addCommas(sa) + "\n";
1021 testUpgrade += "Our formula calculated your SA to be: " + tmpcurrentSA + "\n";
1022 testUpgrade += "If these two values are similar; its safe to trust our upgrade suggestions.\n\n";
1023
1024 testUpgrade += "Your DA is: " + addCommas(da) + "\n";
1025 testUpgrade += "Our formula calculated your DA to be: " + tmpcurrentDA + "\n";
1026 testUpgrade += "If these two values are similar; its safe to trust our upgrade suggestions.\n\n";
1027
1028 testUpgrade += "\n\n\n If the numbers are highly wrong, please visit training page, and command centre so DF can store your officer bonus; and tech bonus.";
1029 testUpgrade += "\n\n Please note: Our formula only calculates big weapons, it doesn't include soldiers and small weapons.";
1030 (testUpgrade);
1031
1032 }, false);
1033 // End of when to upgrade.
1034 }
1035 // Lost weapons log
1036 var lostTable = GetTable("Armory Autofill Preferences");
1037 lostTable.insertRow(-1).innerHTML = "<td colspan=3></td>";
1038 lostTable.insertRow(-1).innerHTML = "<th colspan=3>Lost Weapons Log</th>";
1039
1040 var anyLossLogged = false;
1041
1042 for(var i = 0; i < 10; i++)
1043 {
1044 GM_setValue("DF_lost_wep_log_" + i, lostLogGlobal[i]);
1045
1046 if(lostLogGlobal[i].length > 2) // at least "::"
1047 {
1048 var lostWepDetails = lostLogGlobal[i].split(":");
1049
1050 // fix plural
1051 lostWepDetails[1] += (lostWepDetails[0] > 1 ? "s" : "");
1052
1053 // compute elapsed time
1054 var elapsed = now - parseInt(lostWepDetails[2]);
1055 lostWepDetails[2] = elapsed > 0 ? PrintableTime(elapsed) + " ago" : "NOW!";
1056
1057 if(elapsed == 0)
1058 {
1059 lostWepDetails[0] = "<strong style='color:red'>" + lostWepDetails[0] + "</strong>";
1060 lostWepDetails[1] = "<strong style='color:red'>" + lostWepDetails[1] + "</strong>";
1061 lostWepDetails[2] = "<strong style='color:red'>" + lostWepDetails[2] + "</strong>";
1062 }
1063
1064 lostTable.insertRow(-1).innerHTML = "<td align=right>" + lostWepDetails[0] + "</td>"
1065 + "<td align=left>" + lostWepDetails[1] + "</td>"
1066 + "<td align=left>" + lostWepDetails[2] + "</td>";
1067
1068 anyLossLogged = true;
1069 }
1070 }
1071
1072 if(!anyLossLogged)
1073 {
1074 lostTable.insertRow(-1).innerHTML = "<td colspan=3 align=center>Nothing has been logged yet.</td>";
1075 }
1076
1077 // Listen to sell buttons so that sells wont be logged as missing
1078 var sellButtons = document.getElementsByName('doscrapsell');
1079 for(var i = 0; i < sellButtons.length; i++)
1080 {
1081 sellButtons[i].addEventListener('click', ArmoryPHP_OnSellButton, false);
1082 }
1083
1084 // Add a clear button for the lost weapons log
1085 lostTable.insertRow(-1).innerHTML = "<td colspan=3 align=center><button id=clearLostLog onClick=\"return false;\" style='width:9ex'>Clear</button></td>";
1086 document.getElementById('clearLostLog').addEventListener('click', ArmoryPHP_OnClearLostLog, false);
1087
1088 // Add keyboard shortcut to repair all button
1089 var repairBut = GetElement('input', "Repair all");
1090 if(repairBut && GM_getValue("DF_OptionKS", 1) != 0 )
1091 {
1092 repairBut.value = repairBut.value.replace("Repair", "Repair (r)");
1093
1094 document.addEventListener('keyup',
1095 function(e)
1096 {
1097 if(e.target.type == "text") return;
1098 if(e.target.type == "textarea") return;
1099 if(e.target.type == "select-one") return;
1100
1101 switch(e.keyCode)
1102 {
1103 case 82: // R
1104 GetElement('input', "Repair (r)").click();
1105 break;
1106 }
1107
1108 }, false);
1109 }
1110
1111 // Add helper buttons for buying, if enabled
1112 if(GM_getValue("DF_OptionBH", 0) == 1)
1113 {
1114 buyWeaponsTable.rows[1].cells[3].setAttribute('colspan', 2);
1115
1116 for(var i = 2; i < buyWeaponsTable.rows.length; i++)
1117 {
1118 if(buyWeaponsTable.rows[i].cells[0].innerHTML.indexOf("Defense Weapons") >= 0)
1119 {
1120 buyWeaponsTable.rows[i].cells[3].setAttribute('colspan', 2);
1121 continue;
1122 }
1123
1124 if(buyWeaponsTable.rows[i].cells[0].innerHTML.indexOf("Spy Tools") >= 0)
1125 {
1126 buyWeaponsTable.rows[i].cells[3].setAttribute('colspan', 2);
1127 continue;
1128 }
1129 if(buyWeaponsTable.rows[i].cells[0].innerHTML.indexOf("Sentry Tools") >= 0)
1130 {
1131 buyWeaponsTable.rows[i].cells[3].setAttribute('colspan', 2);
1132 continue;
1133 }
1134
1135 if(buyWeaponsTable.rows[i].cells[0].innerHTML.indexOf("Buy Tools") >= 0) continue;
1136 if(buyWeaponsTable.rows[i].cells.length < 4) continue;
1137
1138 buybutId = GetTextIn(buyWeaponsTable.rows[i].cells[3].innerHTML, "name=\"", "\"");
1139 buyWeaponsTable.rows[i].insertCell(4).innerHTML = "<button id=" + buybutId + " onClick='return false'>0</button>";
1140 buyWeaponsTable.rows[i].cells[4].align = "center";
1141 document.getElementById(buybutId).addEventListener('click', function(){ document.getElementsByName(this.id)[0].value = this.innerHTML; ArmoryPHP_UpdateWeaponButtons(); }, false);
1142 document.getElementsByName(buybutId)[0].addEventListener('blur', ArmoryPHP_UpdateWeaponButtons, false);
1143 }
1144 }
1145
1146 if(GM_getValue("DF_OptionKS", 0) == 1)
1147 {
1148 // Add another buy button and a clear button at top of the weapons
1149 buyWeaponsTable.insertRow(0).innerHTML = "<td colspan=5></td>";
1150 buyWeaponsTable.insertRow(0).innerHTML = "<td colspan=5 align=center style='background-color:#222222; border-bottom:1px solid #555555'>"
1151 + "<button id=buybut2 onClick='this.disabled=true; this.innerHTML=\"Buying...\"; document.buyform.buybut.click(); return false;' style='margin-right:-9ex'>Buy Weapons</button>"
1152 + "<button id=clearButtonTop style='float:right; width:9ex; margin-right:6px;' onClick='return false;'>Clear</button></td>";
1153 document.getElementById('clearButtonTop').addEventListener('click', ArmoryPHP_OnClearBuyButtons, false);
1154 }
1155
1156 // Add a clean button to the bottom
1157 buyWeaponsTable.rows[buyWeaponsTable.rows.length-1].cells[0].innerHTML += "<button id=clearButtonBottom style='float:right; width:9ex; margin-right:6px;' onClick='return false;'>Clear</button>";
1158 document.getElementsByName('buybut')[0].style.marginRight = "-9ex";
1159 document.getElementById('clearButtonBottom').addEventListener('click', ArmoryPHP_OnClearBuyButtons, false);
1160 buyWeaponsTable.rows[buyWeaponsTable.rows.length-1].cells[0].style.backgroundColor = "#222222";
1161
1162 // Add a buying note on top of the buy table
1163 buyWeaponsTable.insertRow(1).innerHTML = "<td style='background-color:#222222; border-bottom:0'>Buying:</td>"
1164 + "<td id=BuyingNote colspan=4 style='background-color:#222222; border-bottom:0'>Nothing</td>";
1165
1166 ArmoryPHP_UpdateWeaponButtons();
1167}
1168
1169function TrainPHP()
1170{
1171 if(GM_getValue("DF_eligable", 0) == 0)
1172 {
1173 return;
1174 }
1175
1176 soldiers = GetSoldiers();
1177
1178 // Put helper buttons for training, if enabled
1179 if(GM_getValue("DF_OptionBH", 0) == 1)
1180 {
1181 AddSoldierButton("Attack Specialist", "assign_attack", TrainPHP_OnAssignSoldier);
1182 AddSoldierButton("Defense Specialist", "assign_defense", TrainPHP_OnAssignSoldier);
1183 AddSoldierButton("Spy", "assign_spy", TrainPHP_OnAssignSoldier);
1184 AddSoldierButton("Sentry", "assign_sentry", TrainPHP_OnAssignSoldier);
1185
1186 document.getElementsByName('train[attacker]')[0].addEventListener('blur', TrainPHP_UpdateTrainingButtons, false);
1187 document.getElementsByName('train[defender]')[0].addEventListener('blur', TrainPHP_UpdateTrainingButtons, false);
1188 document.getElementsByName('train[spy]')[0].addEventListener('blur', TrainPHP_UpdateTrainingButtons, false);
1189 document.getElementsByName('train[sentry]')[0].addEventListener('blur', TrainPHP_UpdateTrainingButtons, false);
1190
1191 TrainPHP_UpdateTrainingButtons();
1192
1193 }
1194 // Fix the training table spannings
1195
1196 var t = GetTag('th', "Train Your Troops");
1197 if(t) t.attributes.getNamedItem('colspan').value++;
1198
1199 t = GetTag('th', "Quantity");
1200 if(t) t.setAttribute('colspan', 2);
1201
1202 t = GetElement('input', "Train!");
1203 if(t) t.parentNode.attributes.getNamedItem('colspan').value++;
1204
1205 if(GM_getValue("DF_OptionBH", 0) != 1)
1206 {
1207 t = GetTag('td', "Attack Specialist");
1208 if(t) t.parentNode.innerHTML += "<td> </td>";
1209
1210 t = GetTag('td', "Defense Specialist");
1211 if(t) t.parentNode.innerHTML += "<td> </td>";
1212
1213 t = GetTag('td', "Spy");
1214 if(t) t.parentNode.innerHTML += "<td> </td>";
1215
1216 t = GetTag('td', "Sentry");
1217 if(t) t.parentNode.innerHTML += "<td> </td>";
1218 }
1219
1220 t = GetTag('td', "Reassign Attack Specialist");
1221 if(t) t.parentNode.innerHTML += "<td> </td>";
1222
1223 t = GetTag('td', "Reassign Defense Specialist");
1224 if(t) t.parentNode.innerHTML += "<td> </td>";
1225
1226 // Add a clean button next to the train button
1227 var input = GetElement('input', "Train!");
1228
1229 if(input)
1230 {
1231 input.parentNode.innerHTML += "<button style=\"margin-left: 6px\" id=clear_training onClick=\"return false;\">Clear</button>";
1232 document.getElementById('clear_training').addEventListener('click', TrainPHP_ClearTraining, false);
1233
1234 // Colorize the buttons' row
1235 input = GetElement('input', "Train!");
1236 input.parentNode.style.backgroundColor = "#222222";
1237 }
1238
1239 // Remove the ! from the Train button (no other spend button has it)
1240 t = GetElement('input', "Train!");
1241 if(t) t.value = "Train";
1242
1243 // Hide the list of techs
1244 var th = GetTag('th', "Technological Development");
1245
1246 if(th)
1247 {
1248 var table = th.parentNode.parentNode;
1249
1250 if(table.rows.length > 3)
1251
1252 {
1253 table.rows[2].cells[0].innerHTML += "<span id=toggle_techs style=\"float:right;\"><tt>-</tt></span>";
1254 table.rows[2].addEventListener('click', TrainPHP_OnToggleTechs, false);
1255 table.rows[2].style.cursor = 'pointer';
1256
1257 // By default, hide techs
1258 TrainPHP_OnToggleTechs();
1259 }
1260 }
1261
1262 var x;
1263 x = FindText(document.body.innerHTML,'upgrade_tech','strength');
1264 if(x)
1265 {
1266 x = FindText(x, "(x "," ");
1267 }
1268 else
1269 {
1270 // Reseach button is gone, because of highest tech reached
1271 x = 7.39;
1272
1273 }
1274
1275 GM_setValue("DF_currentTech", x);
1276
1277 var c = FindText(document.body.innerHTML,'Level ','upgrade_spy')
1278 if(c){
1279 c = parseInt(c.substring(0,2).replace('<',''));
1280 }
1281 else {
1282 c = 15;
1283 }
1284
1285 GM_setValue("DF_CovertSkill", c);
1286
1287 var u = FindText(FindText(document.body.innerHTML,'Current Conscription Rate','</td>'),'<td>', ' soldiers per day');
1288 if(u) {
1289 u = parseInt(u);
1290 }
1291 else {
1292 u = 40960;
1293 }
1294
1295 GM_setValue("DF_Conscription", u);
1296
1297 // Get the required exp for the next tech
1298 var t = GetElement('input', "Research!");
1299 if(t)
1300 {
1301 var str = t.value.toString();
1302 var pos = str.indexOf(" ", 11);
1303 var exp = parseInt( str.substring(11, pos).replace(/,/g, ""), 10 );
1304
1305 GM_setValue("DF_nextTechExp", exp);
1306 }
1307 else
1308 {
1309 // highest tech reached?
1310 GM_setValue("DF_nextTechExp", -1);
1311 }
1312
1313 // Remove economic development
1314 if(GM_getValue("DF_OptionEconomicDevelopment", 1) != 0)
1315 {
1316 GetTag('th', "Economic Development").parentNode.parentNode.style.display = "none";
1317 }
1318
1319}
1320
1321function MercsPHP()
1322{
1323 if(GM_getValue("DF_eligable", 0) == 0)
1324 {
1325 return;
1326 }
1327
1328 soldiers = GetSoldiers();
1329 mercs = GetAvailableMercs();
1330
1331 // Put helper buttons for training, if enabled
1332 if(GM_getValue("DF_OptionBH", 0) == 1)
1333 {
1334 AddSoldierButton("Attack Specialist", "assign_attack", MercsPHP_OnAssignMerc);
1335 AddSoldierButton("Defense Specialist", "assign_defense", MercsPHP_OnAssignMerc);
1336 AddSoldierButton("Untrained", "assign_untrained", MercsPHP_OnAssignMerc);
1337
1338 document.getElementsByName('mercs[attack]')[0].addEventListener('blur', MercsPHP_UpdateMercButtons, false);
1339 document.getElementsByName('mercs[defend]')[0].addEventListener('blur', MercsPHP_UpdateMercButtons, false);
1340 document.getElementsByName('mercs[general]')[0].addEventListener('blur', MercsPHP_UpdateMercButtons, false);
1341
1342 MercsPHP_UpdateMercButtons();
1343 }
1344
1345 // Fix the mercs table spannings and shorten some headers
1346 var t = GetTag('th', "Buy Mercenaries");
1347 if(t) t.attributes.getNamedItem('colspan').value++;
1348
1349 t = GetTag('th', "Quantity to Buy");
1350 if(t) t.setAttribute('colspan', 2);
1351
1352 t = GetElement('input', "Buy");
1353 if(t) t.parentNode.attributes.getNamedItem('colspan').value++;
1354
1355 t = GetTag('th', "Quantity Available");
1356 if(t) t.innerHTML = "Available";
1357
1358 t = GetTag('th', "Quantity to Buy");
1359 if(t) t.innerHTML = "Quantity";
1360
1361
1362 // Fix a design bug (main contaioner table is not 100% width in mercs.php)
1363 document.getElementsByTagName("table")[6].setAttribute('width', '100%');
1364
1365 // Add a clean button next to the buy button
1366 var input = GetElement('input', "Buy");
1367
1368 if(input)
1369 {
1370 input.parentNode.innerHTML += "<button style=\"margin-left: 6px\" id=clear_mercs onClick=\"return false;\">Clear</button>";
1371 document.getElementById('clear_mercs').addEventListener('click', MercsPHP_ClearMercs, false);
1372
1373 input = GetElement('input', "Buy");
1374 input.parentNode.style.backgroundColor = "#222222";
1375
1376 if(document.body.innerHTML.indexOf("There are not enough mercenaries available") > 0)
1377 {
1378 MercsPHP_ClearMercs();
1379 }
1380 }
1381
1382}
1383
1384function StatsPHP()
1385{
1386 if(GM_getValue("DF_eligable", 0) == 0)
1387 {
1388 return;
1389 }
1390
1391 // Get the statid
1392 var endPos = url.indexOf("&");
1393 var statid = url.substring(41, endPos > 0 ? endPos : url.length);
1394
1395 if(!IsNumeric(statid))
1396 {
1397 CustomPage(statid);
1398 return;
1399 }
1400
1401 if(document.body.innerHTML.indexOf("Invalid User ID") > 0)
1402 {
1403 GM_xmlhttpRequest(
1404 {
1405 method: "GET",
1406 url: DF_server + "backbone.php?code=inactive&whoami=" + DF_username + "&password=" + DF_password + "&whoamid=" + DF_statid + "&userid=" + statid,
1407 onload: function(r)
1408 {
1409 if(r.status == 200)
1410 {
1411 if(r.responseText.indexOf("Access Denied") >= 0)
1412 {
1413 return;
1414 }
1415
1416 if(r.responseText.length > 0)
1417 {
1418 var td = GetContentTD();
1419
1420 td.innerHTML = td.innerHTML.replace("<h3>Error</h3>\nInvalid User ID", r.responseText);
1421 }
1422 }
1423 }
1424 });
1425
1426 return;
1427 }
1428
1429 var username = GetText(">Name:<", "<td>", "<").trim();
1430 InteldetailPHP_CalcReconsLeft(username);
1431 document.getElementsByName('spyrbut')[0].value = "Recon (" + GM_getValue("DF_recon_cnt_" + username, 15) + ")";
1432
1433 document.addEventListener('click', function(event) {
1434
1435 if(event.target.value)
1436 {
1437
1438 if( event.target.value.length > 5)
1439 {
1440 var value = String(event.target.value);
1441
1442 var p = value.indexOf("Raid");
1443 if(p)
1444 {
1445 document.cookie = "attackType=notRaid;";
1446 }else{
1447 document.cookie = "attackType=raid;";
1448 }
1449 }
1450 }
1451
1452 }, true);
1453
1454 // Gather user specific information
1455 var commander = GetText(">Commander:<", "<td>", "</td>");
1456 if(commander != "None") commander = GetText(">Commander:<", "\">", "<");
1457
1458 var supreme = GetText(">Supreme Commander", "\">", "<");
1459 if(supreme == "") supreme = "None";
1460
1461 var chain = GetText(">Chain Name:", "<td>", "</td>");
1462 if(chain == "") chain = "None";
1463
1464 var alliance = GetText(">Alliances:", "<b>", "alliances.php?id=", ">", "<");
1465 if(alliance == "") alliance = "None";
1466
1467 var treasury = GetText(">Treasury:", "<td>", "</td>").replace(/,/g, "");
1468 if(treasury == "") treasury = "???";
1469
1470 var morale = GetText(">Army Morale:", "<td>", "</td>").replace(/,/g, "");
1471
1472 var race = GetText(">Race:", "<td>", "</td>");
1473
1474 var rank = GetText("b>Rank:", "<td>", "</td>").replace(/,/g, "");
1475
1476 var tff = GetText(">Army Size:", "<td>", "</td>").replace(/,/g, "");
1477
1478 var fort = GetText(">Fortifications:", "<td>", "</td>").replace(/,/g, "");
1479
1480 // Add place holders for additional data, such as treasury, tbg, ...
1481 var userTable = GetTag('th', "User Stats").parentNode.parentNode;
1482 var treasuryRow = 0;
1483 var allianceRow = 0;
1484
1485 for(i = 0; i < userTable.rows.length; i++)
1486 {
1487
1488 if(userTable.rows[i].innerHTML.indexOf("Alliances") >= 0)
1489 {
1490 allianceRow = i;
1491 }
1492
1493 if(userTable.rows[i].innerHTML.indexOf("Army Morale") >= 0)
1494 {
1495 if(treasury == "???")
1496 {
1497 treasuryRow = userTable.insertRow(i+1);
1498
1499 treasuryRow.insertCell(0).innerHTML = "<b>Treasury:</b>";
1500 treasuryRow.insertCell(1).innerHTML = "Loading...";
1501 }
1502
1503 var style="padding-left:30px;font-size:70%;font-style:italic;";
1504
1505 var tbg60Row = userTable.insertRow(i+2);
1506 var tbg60Row_1 = tbg60Row.insertCell(0);
1507 tbg60Row_1.innerHTML = "<b>TBG (60T):</b>";
1508 tbg60Row_1.setAttribute('style', style);
1509 var tbg60Row_2 = tbg60Row.insertCell(1);
1510 tbg60Row_2.innerHTML = AddCommas( Math.floor(tff * 60 * (race == "Dwarves" ? 1.15 : (race == "Humans" ? 1.3 : 1))).toString() );
1511 tbg60Row_2.setAttribute('style', style);
1512
1513 var tbg100Row = userTable.insertRow(i+3);
1514 var tbg100Row_1 = tbg100Row.insertCell(0);
1515 tbg100Row_1.innerHTML = "<b>TBG (100T):</b>";
1516 tbg100Row_1.setAttribute('style', style);
1517 var tbg100Row_2 = tbg100Row.insertCell(1);
1518 tbg100Row_2.innerHTML = AddCommas( Math.floor(tff * 100 * (race == "Dwarves" ? 1.15 : (race == "Humans" ? 1.3 : 1))).toString() );
1519 tbg100Row_2.setAttribute('style', style);
1520
1521 var tbgdayRow = userTable.insertRow(i+4);
1522 var tbgdayRow_1 = tbgdayRow.insertCell(0);
1523 tbgdayRow_1.innerHTML = "<b>TBG (day):</b>";
1524 tbgdayRow_1.setAttribute('style', style);
1525 var tbgdayRow_2 = tbgdayRow.insertCell(1);
1526 tbgdayRow_2.innerHTML = AddCommas( Math.floor(tff * 60 * 24 * (race == "Dwarves" ? 1.15 : (race == "Humans" ? 1.3 : 1))).toString() );
1527 tbgdayRow_2.setAttribute('style', style);
1528
1529 break;
1530 }
1531 }
1532
1533 // Add place holders for user's stats
1534 var th = GetTag('th', "Recent Battles");
1535 if(!th) th = GetTag('th', "Recent Intelligence");
1536 if(!th) th = GetTag('th', "Officers");
1537 if(!th) return;
1538
1539 var statsTableHtml = "<table width=100% class=table_lines cellspacing=0 cellpadding=6>"
1540 + "<tr><th colspan=3>" + username + "'s Stats</th></tr>"
1541 + "<tr><td width=30%><b>Strike Action</b></td><td align=right id=DB_sa width=40%>Loading...</td><td align=right id=DB_saTime> </td></tr>"
1542 + "<tr><td><b>Defensive Action</b></td><td align=right id=DB_da>Loading...</td><td align=right id=DB_daTime> </td></tr>"
1543 + "<tr><td><b>Spy Rating</b></td><td align=right id=DB_spy>Loading...</td><td align=right id=DB_spyTime> </td></tr>"
1544 + "<tr><td><b>Sentry Rating</b></td><td align=right id=DB_sentry>Loading...</td><td align=right id=DB_sentryTime> </td></tr>"
1545 + "</table><br /><br />";
1546
1547 var userlinks = "<div id='userlinks'></div>";
1548
1549 var statsPlace = th.parentNode.parentNode.parentNode.parentNode;
1550 statsPlace.innerHTML = statsTableHtml + userlinks + statsPlace.innerHTML;
1551
1552 // Update the database and get details about this target (fill placeholders)
1553 GM_xmlhttpRequest(
1554 {
1555 method: "GET",
1556 url: DF_server + "backbone.php?code=statspage&whoami=" + DF_username + "&password=" + DF_password + "&whoamid=" + DF_statid + "&username=" + username + "&userid=" + statid + "&commander=" + commander + "&supremecommander=" + supreme + "&chain=" + encodeURIComponent(chain) + "&alliance=" + encodeURIComponent(alliance) + "&race=" + race + "&gold=" + treasury + "&morale=" + morale + "&rank=" + rank + "&tff=" + tff + "&fort=" + encodeURIComponent(fort),
1557 onload: function(r)
1558 {
1559 if(r.status == 200)
1560 {
1561
1562 if(r.responseText.indexOf("Access Denied") >= 0)
1563 {
1564 return;
1565 }
1566
1567 document.getElementById('DB_sa').innerHTML = GetTextIn(r.responseText, "[SA]", "[/SA]");
1568 document.getElementById('DB_da').innerHTML = GetTextIn(r.responseText, "[DA]", "[/DA]");
1569 document.getElementById('DB_spy').innerHTML = GetTextIn(r.responseText, "[SPY]", "[/SPY]");
1570 document.getElementById('DB_sentry').innerHTML = GetTextIn(r.responseText, "[SENTRY]", "[/SENTRY]");
1571
1572 document.getElementById('DB_saTime').innerHTML = GetTextIn(r.responseText, "[aSA]", "[/aSA]");
1573 document.getElementById('DB_daTime').innerHTML = GetTextIn(r.responseText, "[aDA]", "[/aDA]");
1574 document.getElementById('DB_spyTime').innerHTML = GetTextIn(r.responseText, "[aSPY]", "[/aSPY]");
1575 document.getElementById('DB_sentryTime').innerHTML = GetTextIn(r.responseText, "[aSENTRY]", "[/aSENTRY]");
1576
1577 var DB_gold = GetTextIn(r.responseText, "[GOLD]", "[/GOLD]");
1578 var DB_goldTime = GetTextIn(r.responseText, "[aGOLD]", "[/aGOLD]");
1579
1580 // Update treasury
1581 if(treasuryRow)
1582 {
1583 treasuryRow.cells[1].innerHTML = DB_gold + "<span style=\"margin-left: 20px;\">( " + DB_goldTime + " )</span>";
1584 }
1585
1586
1587 // Has alliance title or ap? Then display
1588 var allianceTitle = GetTextIn(r.responseText, "[TITLE]", "[/TITLE]");
1589 var alliancePoints = GetTextIn(r.responseText, "[AP]", "[/AP]");
1590 if(allianceTitle)
1591 {
1592 allianceTitleRow = userTable.insertRow(allianceRow+2);
1593
1594 allianceTitleRow.insertCell(0).innerHTML = "<b>Alliance Title:</b>";
1595 allianceTitleRow.insertCell(1).innerHTML = allianceTitle + " (" + alliancePoints + ")";
1596
1597 }
1598
1599
1600
1601 }
1602 }
1603 });
1604
1605
1606 GM_xmlhttpRequest(
1607 {
1608 method: "GET",
1609 url: DF_server + "backbone.php?code=userlinks&whoami=" + DF_username + "&password=" + DF_password + "&whoamid=" + DF_statid + "&username=" + username + "&userid=" + statid,
1610 onload: function(r)
1611 {
1612 if(r.status != 200) return;
1613
1614 var container = document.getElementById("userlinks");
1615
1616 if(r.responseText.indexOf("[START]") >= 0)
1617 {
1618 container.innerHTML = GetTextIn(r.responseText, "[START]", "[END]");
1619 }
1620 }
1621 });
1622
1623 // Collapse the recent battles and intelligence
1624 ExpandCollapseTable("Recent Battles");
1625 ExpandCollapseTable("Recent Intelligence");
1626
1627 // Remove the ! from make commander button
1628 var t = GetElement('input', "Make " + username + " my commander!");
1629 if(t) t.value = "Make " + username + " my commander";
1630
1631 // Give Send Message button also 2px padding like the Make Commander button has
1632 var sendMsgButton = GetElement('input', "Send Message");
1633 if(sendMsgButton) sendMsgButton.style.padding = "2px";
1634
1635 // Add last message sent
1636 if(GM_getValue("DF_OptionShowLastMsgSent", 1) == 1)
1637 {
1638 var lastMsgRow = GetElement('input', "Send Message").parentNode.parentNode.parentNode.parentNode;
1639 if(GM_getValue("DF_msg_sent_content_" + username, "") != "") // if has msg sent
1640 {
1641 lastMsgRow.innerHTML += "<p style=\"font-size: small; margin-top: -15px\"><a href=\"#\" onClick=\"document.getElementById('PMBox').style.visibility = 'visible'; return false;\">Last Msg: " + AttackPHP_GetLastMsgSent(username) + "</a></p>";
1642
1643 // Box for showing PM
1644 var PMBox = document.createElement('div');
1645 PMBox.setAttribute('id', 'PMBox');
1646 PMBox.style.visibility = 'hidden';
1647 PMBox.style.position = 'absolute';
1648 PMBox.style.left = '0';
1649 PMBox.style.top = '0';
1650 PMBox.style.width = '100%';
1651 PMBox.style.height = window.outerHeight;
1652 PMBox.style.textAlign = 'center';
1653 PMBox.style.zIndex = '1000';
1654 PMBox.style.backgroundColor = ' rgba(0,0,0,.75)';
1655 PMBox.innerHTML = '<div style="width: 600px; margin: 300px auto; padding: 10px; text-align: center;"> \
1656<textarea cols="80" rows="12" style="padding: 10px;">' + GM_getValue("DF_msg_sent_content_" + username, "") + '</textarea><br> \
1657<input type="button" onclick="var PMBox = document.getElementById(\'PMBox\'); PMBox.style.visibility = \'hidden\';" value="Close" style="margin-top: 5px; width: 150px; height: 35px; cursor: pointer;"> \
1658</div>';
1659 document.body.appendChild(PMBox);
1660 }
1661 else
1662 {
1663 lastMsgRow.innerHTML += "<p style=\"font-size: small; margin-top: -15px\">Last Msg: " + AttackPHP_GetLastMsgSent(username) + "</p>";
1664 }
1665 }
1666
1667 // Redesign the user table
1668 var userTable = GetTag('th', "User Stats").parentNode.parentNode;
1669
1670 // Shorten supreme commander
1671 if(userTable.rows[3].cells[0].innerHTML.indexOf("Supreme") >= 0)
1672 {
1673 userTable.rows[3].cells[0].innerHTML = "<b>Supreme:</b>";
1674 }
1675
1676 // Merge rank and highest rank rows
1677 var rowId = GetTableRow(userTable, 0, "Rank:");
1678 if(rowId >= 0)
1679 {
1680 userTable.rows[rowId].cells[1].innerHTML += " ( " + userTable.rows[rowId + 1].cells[1].innerHTML + " )";
1681 userTable.deleteRow(rowId + 1);
1682 }
1683
1684 // Merge buddy status and buddy button rows
1685 var rowId = GetTableRow(userTable, 0, "Buddy");
1686 if(rowId >= 0)
1687 {
1688 var buddyStatus = userTable.rows[rowId].cells[1].innerHTML;
1689 buddyStatus = buddyStatus.substring(0, buddyStatus.indexOf(">") + 1);
1690 buddyStatus = buddyStatus.replace(">", "> ");
1691
1692 var buddyForm = userTable.rows[rowId + 1].cells[0].innerHTML.replace("Recognize player as", "");
1693 userTable.rows[rowId].innerHTML = "<td><b>Buddy Status:</b></td><td style='padding-top:20px;'>" + buddyForm.replace("post\">", "post\">" + buddyStatus) + "</td>";
1694
1695 userTable.deleteRow(rowId + 1);
1696 userTable.deleteRow(rowId - 1); // remove the empty row
1697 }
1698
1699 // Collapse the alliances except the primary
1700 var rowId = GetTableRow(userTable, 0, "Alliances");
1701 if(rowId >= 0)
1702 {
1703 var expandedAlliances = userTable.rows[rowId].cells[1].innerHTML;
1704
1705 var alliances = expandedAlliances.split(",");
1706 var primaryAlliance = 0;
1707
1708 for(i = 0; i < alliances.length; i++)
1709 {
1710 if(alliances[i].indexOf("(Primary)") >= 0)
1711 {
1712 primaryAlliance = alliances[i];
1713 break;
1714 }
1715 }
1716
1717 if(primaryAlliance)
1718 {
1719 userTable.rows[rowId].cells[1].innerHTML = primaryAlliance;
1720
1721 if(alliances.length > 1)
1722 {
1723 userTable.rows[rowId].cells[1].innerHTML += ", <a style=\"cursor:pointer;\" id=showAlliances>(+)</a>";
1724
1725 document.getElementById('showAlliances').addEventListener('click',
1726 function()
1727 {
1728 this.parentNode.innerHTML = expandedAlliances;
1729 }, false);
1730 }
1731 }
1732 }
1733
1734 // Add shortcut to attack, raid, recon and sab
1735 var listenKeyboard = GM_getValue("DF_OptionKS", 1);
1736
1737 var shortcuts = userTable.insertRow(1).insertCell(0);
1738 shortcuts.innerHTML = "<table border=0 cellspacing=0 cellpadding=4 width=100%><tr><td width=25% style=\"border:0\"><button id=sAttack style=\"width:100%\" onClick=\"this.innerHTML = 'Attacking...'; this.disabled = true; document.getElementsByName('attackbut')[0].click();\">Attack" + (listenKeyboard == 0 ? "" : " (k)") + "</button></td>"
1739 + "<td width=25% style=\"border:0\"><button id=sRaid style=\"width:100%\" onClick=\"this.innerHTML = 'Raiding...'; this.disabled = true; document.getElementsByName('attackbut')[1].click();\">Raid" + (listenKeyboard == 0 ? "" : " (p)") + "</button></td>"
1740 + "<td width=25% style=\"border:0\"><button id=sRecon value=\"Recon\" style=\"width:100%\" onClick=\"this.innerHTML = 'Reconning...'; this.disabled = true; document.getElementsByName('spyrbut')[0].click();\">Recon" + (listenKeyboard == 0 ? "" : " (r)") + "</button></td>"
1741 + "<td width=25% style=\"border:0\"><button id=sSab style=\"width:100%\" onClick=\"window.location = 'attack.php?id=" + statid + "#sab' \">Sabotage" + (listenKeyboard == 0 ? "" : " (s)") + "</button></td></tr></table>";
1742
1743 shortcuts.setAttribute('colspan', 2);
1744}
1745
1746function InteldetailPHP()
1747{
1748 if(GM_getValue("DF_eligable", 0) == 0)
1749 {
1750 return;
1751 }
1752
1753 var doc = document.body.innerHTML;
1754
1755 var listenKeyboard = GM_getValue("DF_OptionKS", 1);
1756
1757 if(doc.indexOf("Your Chief of Intelligence dispatches") >= 0) // Sab
1758 {
1759 if(doc.indexOf("armory undetected,") >= 0) // Sab got through
1760 {
1761 var reportId = url.substring(54, url.length);
1762 var sabbee = GetText("Your spies successfully enter ", "'s");
1763 var weapon = GetText("attempt to sabotage", "weapons of type ", ".");
1764 var amount = GetText("and destroy ", " of the ").replace(/,/g, "");
1765 if(amount == "") amount = 0;
1766
1767 // Place holder for the logging
1768 var but = GetElement('input', "Attack / Spy Again");
1769 but.parentNode.innerHTML = but.parentNode.innerHTML + "<span id=logSab style=\"margin-left: 20px;\">Logging your sab...</span>";
1770
1771 GM_xmlhttpRequest(
1772 {
1773 method: "GET",
1774 url: DF_server + "backbone.php?code=logsabs&whoami=" + DF_username + "&whoamid=" + DF_statid + "&password=" + DF_password + "&target=" + sabbee + "&weapon=" + weapon + "&amount=" + amount + "&rid=" + reportId,
1775 onload: function(r)
1776 {
1777 if(r.status == 200)
1778 {
1779 document.getElementById('logSab').innerHTML = r.responseText;
1780 }
1781 }
1782 });
1783 }
1784 else // Sab failed
1785 {
1786
1787 }
1788
1789 }
1790 else // Recon
1791 {
1792 if(doc.indexOf("with the information gathered") >= 0)
1793 {
1794 // Record recon
1795 var reportId = url.substring(54, url.length);
1796 var username = GetText("your spy sneaks into ", "'s camp");
1797 var sa = GetText(">Strike Action:<", "\">", "<").replace(/,/g, "");
1798 var da = GetText(">Defensive Action<", "\">", "<").replace(/,/g, "");
1799 var spy = GetText(">Spy Rating<", "\">", "<").replace(/,/g, "");
1800 var sentry = GetText(">Sentry Rating<", "\">", "<").replace(/,/g, "");
1801 var coverts = GetText(">Covert Operatives:<", "\">", "<").replace(/,/g, "");
1802 var turns = GetText(">Attack Turns:<", "\">", "<").replace(/,/g, "");
1803 var treasury = GetText(">Treasury<", "\">", "<").replace(/,/g, "").replace(" Gold", "");
1804 var lvl = GetText(">Covert Skill:<", "\">", "<").replace(/,/g, "");
1805 var siege = GetText(">Siege Technology:<", "\">", "<");
1806 var up = GetText(">Unit Production:<", "\">", "<").replace(/,/g, "");
1807 var statid = GetText("name=\"id\" value=\"", "\"");
1808
1809 // Reduce one recon count
1810 AttackPHP_SetReconCnt(username);
1811
1812 var soldiers = GetText("<td>Soldiers</td>","</tr>").match(/[^><]+?(?=<|$)/g,"");
1813 var sa_sol = soldiers[1].replace(/,/g, "");
1814 var da_sol = soldiers[3].replace(/,/g, "");
1815 var untrained = soldiers[5].replace(/,/g, "");
1816
1817 var table = GetTag('th', "Weapons").parentNode.parentNode;
1818
1819 var BPM = "???";
1820 var IS = "???";
1821 var DS = "???";
1822 var CHR = "???";
1823 var NUN = "???";
1824 var LT = "???";
1825 var SK = "???";
1826 var GD = "???";
1827 var GH = "???";
1828 var TW = "???";
1829 var CK = "???";
1830
1831 for(i = 2; i < table.rows.length; i++)
1832 {
1833 if(table.rows[i].cells.length < 4) continue;
1834
1835 var wepName = table.rows[i].cells[0].innerHTML;
1836 var wepType = table.rows[i].cells[1].innerHTML;
1837 var wepCount = table.rows[i].cells[2].innerHTML.replace(/,/g, "");
1838 var wepStrength = table.rows[i].cells[3].innerHTML.replace(/,/g, "");
1839 wepStrength = wepStrength.substring(wepStrength.indexOf("/") + 1, wepStrength.length);
1840 if(wepStrength == "???") wepStrength = table.rows[i].cells[3].innerHTML.replace(/,/g, "").split("/")[0];
1841
1842 if(wepCount == "???") continue;
1843
1844 // Find the weapon directly from its name
1845 if(wepName == "Blackpowder Missile")
1846 {
1847 BPM = wepCount;
1848 }
1849 else if(wepName == "Invisibility Shield")
1850 {
1851 IS = wepCount;
1852 }
1853 else if(wepName == "Dragonskin")
1854 {
1855 DS = wepCount;
1856 }
1857 else if(wepName == "Chariot")
1858 {
1859 CHR = wepCount;
1860 }
1861 else if(wepName == "Nunchaku")
1862 {
1863 NUN = wepCount;
1864 }
1865 else if(wepName == "Lookout Tower")
1866 {
1867 LT = wepCount;
1868 }
1869 else if(wepName == "Skeleton Key")
1870 {
1871 SK = wepCount;
1872 }
1873 else if(wepName == "Guard Dog")
1874 {
1875 GD = wepCount;
1876 }
1877 else if(wepName == "Grappling Hook")
1878 {
1879 GH = wepCount;
1880 }
1881 else if(wepName == "Tripwire")
1882 {
1883 TW = wepCount;
1884 }
1885 else if(wepName == "Cloak")
1886 {
1887 CK = wepCount;
1888 }
1889
1890 // Find the weapon using type + strength
1891 if(wepType == "Attack" && wepStrength == "1000")
1892 {
1893 BPM = wepCount;
1894 }
1895 else if(wepType == "Attack" && wepStrength == "600")
1896 {
1897 CHR = wepCount;
1898 }
1899 if(wepType == "Defend" && wepStrength == "1000")
1900 {
1901 IS = wepCount;
1902 }
1903 if(wepType == "Defend" && wepStrength == "256")
1904 {
1905 DS = wepCount;
1906 }
1907 if(wepType == "Spy" && wepStrength == "1000")
1908 {
1909 NUN = wepCount;
1910 }
1911 if(wepType == "Sentry" && wepStrength == "1000")
1912 {
1913 LT = wepCount;
1914 }
1915 if(wepType == "Spy" && wepStrength == "600")
1916 {
1917 SK = wepCount;
1918 }
1919 if(wepType == "Sentry" && wepStrength == "250")
1920 {
1921 GD = wepCount;
1922 }
1923 if(wepType == "Spy" && wepStrength == "250")
1924 {
1925 GH = wepCount;
1926 }
1927 if(wepType == "Sentry" && wepStrength == "140")
1928 {
1929 TW = wepCount;
1930 }
1931 if(wepType == "Spy" && wepStrength == "140")
1932 {
1933 CK = wepCount;
1934 }
1935 }
1936
1937 var weapons = "[bpm]" + BPM + "[/bpm][is]" + IS + "[/is][nun]" + NUN + "[/nun][lt]" + LT + "[/lt][ch]" + CHR + "[/ch][ds]" + DS + "[/ds][sk]" + SK + "[/sk][gd]" + GD + "[/gd][gh]" + GH + "[/gh][tw]" + TW + "[/tw][ck]" + CK + "[/ck]";
1938
1939 // Place holder for the logging
1940 var th = GetTag('th', "Treasury");
1941 th.parentNode.parentNode.innerHTML += "<tr><td></td></tr><tr><td style='padding-left: 4ex; border-bottom:0'><a href=attack.php?id=" + statid + "><button>Attack / Spy Again" + (listenKeyboard == 0 ? "" : " (rs)") + "</button></a><span id=logRecon style=\"margin-left: 20px;\">Logging your recon...</span></td></tr>";
1942
1943 GM_xmlhttpRequest(
1944 {
1945 method: "GET",
1946 url: DF_server + "backbone.php?code=reconpage&whoami=" + DF_username + "&password=" + DF_password + "&whoamid=" + DF_statid + "&username=" + username + "&sa=" + sa + "&da=" + da + "&spy=" + spy + "&sentry=" + sentry + "&userid=" + statid + "&gold=" + treasury + "&coverts=" + coverts + "&turns=" + turns + "&weapons=" + weapons + "&untrained=" + untrained + "&rid=" + reportId + "&lvl=" + lvl + "&siege=" + encodeURIComponent(siege) + "&up=" + up,
1947 onload: function(r)
1948 {
1949 if(r.status == 200)
1950 {
1951 document.getElementById('logRecon').innerHTML = r.responseText;
1952 }
1953 }
1954 });
1955 }
1956 else // Recon Failed
1957 {
1958 var username = GetText("your spy sneaks into ", "'s camp");
1959 AttackPHP_SetReconCnt(username);
1960
1961 }
1962 }
1963}
1964
1965function ConquestPHP()
1966{
1967 if(GM_getValue("DF_eligable", 0) == 0)
1968 {
1969 return;
1970 }
1971}
1972
1973function AttackPHP()
1974{
1975 if(GM_getValue("DF_eligable", 0) == 0)
1976 {
1977 return;
1978 }
1979
1980 var doc = document.body.innerHTML;
1981
1982 // Get the statid
1983 var endPos = url.indexOf("&");
1984 var statid = url.substring(42, endPos > 0 ? endPos : url.length);
1985
1986 if(document.body.innerHTML.indexOf("Invalid User ID") > 0)
1987 {
1988 GM_xmlhttpRequest(
1989 {
1990 method: "GET",
1991 url: DF_server + "backbone.php?code=inactive&whoami=" + DF_username + "&password=" + DF_password + "&whoamid=" + DF_statid + "&userid=" + statid,
1992 onload: function(r)
1993 {
1994 if(r.status == 200)
1995 {
1996 if(r.responseText.indexOf("Access Denied") >= 0)
1997 {
1998 return;
1999 }
2000
2001 if(r.responseText.length > 0)
2002 {
2003 var td = GetContentTD();
2004
2005 td.innerHTML = td.innerHTML.replace("<h3>Error</h3>\nInvalid User ID", r.responseText);
2006 }
2007 }
2008 }
2009 });
2010
2011 return;
2012 }
2013
2014 var username = GetText("Target:", "\">", "<");
2015 if(username == "") return;
2016
2017 var statid = GetText("Target:", "id=", "\">");
2018 if(statid == "") return;
2019
2020 if(doc.indexOf("You can recon a player only 15 times") > 0)
2021 {
2022 GM_setValue("DF_recon_cnt_" + username, 0);
2023 }
2024
2025 document.addEventListener('click', function(event) {
2026 if(event.target.value)
2027 {
2028 var value = String(event.target.value);
2029
2030 var p = value.indexOf("Raid");
2031
2032 if(p)
2033 {
2034 document.cookie = "attackType=notRaid;";
2035 }else{
2036 document.cookie = "attackType=raid;";
2037 }
2038 }
2039
2040 }, true);
2041
2042 // Add how many recons left on target
2043 InteldetailPHP_CalcReconsLeft(username);
2044 document.getElementsByName('spyrbut')[0].value = "Recon (" + GM_getValue("DF_recon_cnt_" + username, 15) + ")";
2045
2046 // Fix the width of Target: to display the target's name properly
2047 var t = GetTag('th', "Attack Mission");
2048 if(t)
2049 {
2050 var table = t.parentNode.parentNode;
2051 table.rows[1].cells[0].width = '50%';
2052 }
2053
2054 // Add another sab button and change the original sab button to 'sab' instead of 'send spies'
2055 var th = GetTag('th', "Sabotage Mission");
2056 if(th) th.parentNode.parentNode.insertRow(1).innerHTML = "<td colspan=2 align=center><input name=spybut0 onclick=\"document.spy.spybut0.value='Sabotaging..'; document.spy.spybut0.disabled=true; document.spy.submit();\" type=submit value=\"Sab!\"></td>";
2057 document.getElementsByName('spybut')[0].value = "Sab!";
2058
2059 if(doc.indexOf("has already suffered heavy losses") >= 0)
2060 {
2061 GM_xmlhttpRequest(
2062 {
2063 method: "GET",
2064 url: DF_server + "backbone.php?code=maxed&whoami=" + DF_username + "&whoamid=" + DF_statid + "&password=" + DF_password + "&target=" + username
2065 });
2066 }
2067
2068 // Put an additional +1 / +5 button next to the weapon amount in sab form
2069 document.getElementsByName('numsab')[0].parentNode.innerHTML += "<button style=\"margin-left: 20px;\" onClick=\"document.spy.numsab.value = parseInt(document.spy.numsab.value, 10) + 1; return false;\">+1</button>"
2070 + "<button style=\"margin-left: 20px;\" onClick=\"document.spy.numsab.value = parseInt(document.spy.numsab.value, 10) + 5; return false;\">+5</button>";
2071
2072 // Put an additional +1 button next to the number of spies
2073 document.getElementsByName('numspies')[0].parentNode.innerHTML += "<button style=\"margin-left: 20px;\" onClick=\"document.spy.numspies.value = parseInt(document.spy.numspies.value, 10) + 1; return false;\">+1</button>";
2074
2075 // Add place holders for user's stats and move your stats above the personnel table
2076 var th = GetTag('th', "<span ");
2077 var statsPlace = th.parentNode.parentNode.parentNode.parentNode;
2078
2079 var statsTableHtml = "<table width=100% class=table_lines cellspacing=0 cellpadding=6>"
2080 + "<tr><th colspan=3>" + username + "'s Stats</th></tr>"
2081 + "<tr><td width=30%><b>Strike Action</b></td><td align=right id=DB_sa width=40%>Loading...</td><td align=right id=DB_saTime> </td></tr>"
2082 + "<tr><td><b>Defensive Action</b></td><td align=right id=DB_da>Loading...</td><td align=right id=DB_daTime> </td></tr>"
2083 + "<tr><td><b>Spy Rating</b></td><td align=right id=DB_spy>Loading...</td><td align=right id=DB_spyTime> </td></tr>"
2084 + "<tr><td><b>Sentry Rating</b></td><td align=right id=DB_sentry>Loading...</td><td align=right id=DB_sentryTime> </td></tr>"
2085 + "<tr style='background-color:#111100;'><td><b>Recent Gold</b></td><td align=right id=DB_gold>Loading...</td><td align=right id=DB_goldTime> </td></tr>"
2086 + "</table><br /><br />";
2087
2088 var inventoryTableHtml = "<table id=tblInventory width=100% class=table_lines border=0 cellspacing=0 cellpadding=6>"
2089 + "<thead>"
2090 + "<tr><th colspan=5>" + username + "'s Inventory</th></tr>"
2091 + "<tr><th class=subh width=30%>Weapon</th><th class=subh colspan=2>Quantity</th><th class=subh width=20%>AAT</th><th class=subh width=1%> </th></tr>"
2092 + "</thead>"
2093 + "<tbody>"
2094 + "</tbody>"
2095 + "</table>";
2096
2097
2098 // Remove the Personnel table, which is useless
2099 var personnelTableHtml = GetTag('th', "<span").parentNode.parentNode.innerHTML;
2100 statsPlace.innerHTML = statsPlace.innerHTML.replace(personnelTableHtml, "<br>");
2101
2102 statsPlace.innerHTML = statsTableHtml + inventoryTableHtml + statsPlace.innerHTML;
2103
2104
2105 // Add place holders for the target's inventory and the last sab
2106 var sabotageTable = GetTag('th', "Sabotage Mission").parentNode.parentNode;
2107
2108 var lastSabRow = sabotageTable.insertRow(sabotageTable.rows.length - 1);
2109 lastSabRow.insertCell(0).innerHTML = "Last Sab";
2110 lastSabRow.insertCell(1).innerHTML = "Loading...";
2111 lastSabRow.cells[0].width = "50%";
2112
2113 // Add Message Button
2114 if(GM_getValue("DF_OptionShowLastMsgSent", 1) == 1)
2115 {
2116 var lastMsgRow = sabotageTable.insertRow(sabotageTable.rows.length);
2117 lastMsgRow.insertCell(0).innerHTML = '<button onclick=\"window.location = \'http://www.kingsofchaos.com/writemail.php?to=' + statid + '\'; return false;\">Send Message</button>';
2118 if(GM_getValue("DF_msg_sent_content_" + username, "") != "") // if has msg sent
2119 {
2120 lastMsgRow.insertCell(1).innerHTML = "<a href=\"#\" onClick=\"document.getElementById('PMBox').style.visibility = 'visible'; return false;\">Last Msg: " + AttackPHP_GetLastMsgSent(username) + "</a>";
2121
2122 // Box for showing PM
2123 var PMBox = document.createElement('div');
2124 PMBox.setAttribute('id', 'PMBox');
2125 PMBox.style.visibility = 'hidden';
2126 PMBox.style.position = 'absolute';
2127 PMBox.style.left = '0';
2128 PMBox.style.top = '0';
2129 PMBox.style.width = '100%';
2130 PMBox.style.height = window.outerHeight;
2131 PMBox.style.textAlign = 'center';
2132 PMBox.style.zIndex = '1000';
2133 PMBox.style.backgroundColor = ' rgba(0,0,0,.75)';
2134 PMBox.innerHTML = '<div style="width: 600px; margin: 300px auto; padding: 10px; text-align: center;"> \
2135<textarea cols="80" rows="12" disabled="disabled" style="padding: 10px;">' + GM_getValue("DF_msg_sent_content_" + username, "") + '</textarea><br> \
2136<input type="button" onclick="var PMBox = document.getElementById(\'PMBox\'); PMBox.style.visibility = \'hidden\';" value="Close" style="margin-top: 5px; width: 150px; height: 35px; cursor: pointer;"> \
2137</div>';
2138 document.body.appendChild(PMBox);
2139 }
2140 else
2141 {
2142 lastMsgRow.insertCell(1).innerHTML = 'Last Msg: ' + AttackPHP_GetLastMsgSent(username);
2143 }
2144
2145 lastMsgRow.cells[0].width = "50%";
2146 }
2147
2148 // Does the script remembers your sab options? If not, last sab will be taken as the option
2149 var sabRemember = false;
2150
2151 // Show additional information about the target
2152 GM_xmlhttpRequest(
2153 {
2154 method: "GET",
2155 url: DF_server + "backbone.php?code=aat2&whoami=" + DF_username + "&password=" + DF_password + "&whoamid=" + DF_statid + "&username=" + username,
2156 onload: function(r)
2157 {
2158 if(r.status == 200)
2159 {
2160
2161 document.getElementById('DB_sa').innerHTML = GetTextIn(r.responseText, "[SA]", "[/SA]");
2162 document.getElementById('DB_da').innerHTML = GetTextIn(r.responseText, "[DA]", "[/DA]");
2163 document.getElementById('DB_spy').innerHTML = GetTextIn(r.responseText, "[SPY]", "[/SPY]");
2164 document.getElementById('DB_sentry').innerHTML = GetTextIn(r.responseText, "[SENTRY]", "[/SENTRY]");
2165
2166 document.getElementById('DB_saTime').innerHTML = GetTextIn(r.responseText, "[tSA]", "[/tSA]");
2167 document.getElementById('DB_daTime').innerHTML = GetTextIn(r.responseText, "[tDA]", "[/tDA]");
2168 document.getElementById('DB_spyTime').innerHTML = GetTextIn(r.responseText, "[tSPY]", "[/tSPY]");
2169 document.getElementById('DB_sentryTime').innerHTML = GetTextIn(r.responseText, "[tSENTRY]", "[/tSENTRY]");
2170
2171 document.getElementById('DB_gold').innerHTML = GetTextIn(r.responseText, "[GOLD]", "[/GOLD]");
2172 document.getElementById('DB_goldTime').innerHTML = GetTextIn(r.responseText, "[tGOLD]", "[/tGOLD]");
2173
2174 var lastSabber = GetTextIn(r.responseText, "[uSAB]", "[/uSAB]");
2175 var lastWep = GetTextIn(r.responseText, "[bSAB]", "[/bSAB]");
2176
2177 lastSabRow.cells[0].innerHTML += " " + GetTextIn(r.responseText, "[tSAB]", "[/tSAB]");
2178 lastSabRow.cells[1].innerHTML = (lastWep == "" ? "Never" : lastWep + " by " + lastSabber);
2179
2180 var html = "";
2181 for(var i = 0; i < _weapons.length; i++) {
2182 var weapon = _weapons[i];
2183 var amount = parseInt(GetTextIn(r.responseText, "[" + weapon.afk + "]", "[/" + weapon.afk + "]").replace(/,/g, ""));
2184 if(isNaN(amount) || amount == 0){
2185 continue;
2186 }
2187 else{
2188 var time = GetTextIn(r.responseText, "[t" + weapon.afk + "]", "[/t" + weapon.afk + "]");
2189 var aat = GetTextIn(r.responseText, "[b" + weapon.afk + "]", "[/b" + weapon.afk + "]");
2190
2191 html += "<tr><td>" + weapon.name+ "</td><td align=right id=>" + addCommas(amount) + "</td><td align=left>" + time + "</td><td align=center>" + aat + "</td><td><button weapon=" + weapon.afk + " name=removeWeapon>X</button></td></tr>"
2192 }
2193 }
2194 document.getElementById('tblInventory').getElementsByTagName('tbody')[0].innerHTML = html;
2195
2196 // Update button meanings in the inventory table
2197 var aatButtons = document.getElementsByName("aatButton");
2198
2199 for(var i = 0; i < aatButtons.length; i++)
2200 {
2201 aatButtons[i].addEventListener('click', function()
2202 {
2203 document.getElementsByTagName('select')[0].value = GetText("label=\"" + this.getAttribute("weapon").trim() + "\"", "value=\"", "\"");
2204 document.getElementsByName('numsab')[0].value = parseInt(this.innerHTML.replace(/,/g, ""));
2205
2206 }, false);
2207
2208 if(i == 0) // skip the last sabber button
2209 continue;
2210
2211 aatButtons[i].style.width = "80%";
2212 }
2213
2214
2215 // If the script cannot remember the sab options agains this opponent, take the last sab
2216 if(!sabRemember)
2217 {
2218 if(aatButtons.length == 7) // if there is a last sab
2219 {
2220 aatButtons[0].click();
2221 }
2222 else // if there is no last sab, take LT/BROKENSTICK aat
2223 {
2224 //document.getElementsByTagName('select')[0].value = 69;
2225 //document.getElementsByName('numsab')[0].value = 1;
2226 aatButtons[5].click();
2227 }
2228 }
2229
2230
2231 // Remove Weapons buttons
2232 var removeButtons = document.getElementsByName("removeWeapon");
2233
2234 for(var i = 0; i < removeButtons.length; i++)
2235 {
2236 removeButtons[i].addEventListener('click', function()
2237 {
2238 GM_xmlhttpRequest(
2239 {
2240 method: "POST",
2241 url: DF_server + "backbone.php",
2242 headers: { 'Content-type' : 'application/x-www-form-urlencoded' },
2243 data: encodeURI("code=removeWeapon&whoami=" + DF_username + "&password=" + DF_password + "&whoamid=" + DF_statid + "&target=" + username + "&weapon=" + this.getAttribute("weapon")),
2244 onload: function(r)
2245 {
2246
2247 if(r.status != 200) return;
2248 location.reload(true);
2249 }
2250 });
2251 }, false);
2252 }
2253 }
2254 }
2255 });
2256
2257
2258 // Remember sabotage settings for this target
2259 document.getElementsByTagName('select')[0].value = GM_getValue("DF_sab_wep_" + username, 69);
2260 document.getElementsByName('numsab')[0].value = GM_getValue("DF_sab_cnt_" + username, 1);
2261 document.getElementsByName('numspies')[0].value = GM_getValue("DF_sab_spies_" + username, 1);
2262 document.getElementsByTagName('select')[1].value = GM_getValue("DF_sab_turns_" + username, 5);
2263
2264 sabRemember = (GM_getValue("DF_sab_wep_" + username, -1) != -1);
2265
2266 // Lower aat if cannot get through
2267 if(document.body.innerHTML.indexOf("you will never be able to get away") > 0)
2268 {
2269 if(document.getElementsByName('numsab')[0].value > 0)
2270 {
2271 document.getElementsByName('numsab')[0].value -= 1;
2272 }
2273 }
2274
2275 document.getElementsByTagName('form')[2].addEventListener('submit', function() { AttackPHP_OnSubmitSab(username); }, false);
2276 document.getElementsByName('spybut')[0].addEventListener('click', function() { AttackPHP_OnSubmitSab(username); }, false);
2277 document.getElementsByName('spybut0')[0].addEventListener('click', function() { AttackPHP_OnSubmitSab(username); }, false);
2278}
2279
2280function BattlefieldPHP()
2281{
2282 if(GM_getValue("DF_eligable", 0) == 0)
2283 {
2284 return;
2285 }
2286
2287 // Disable ajax navigation on koc
2288 GetContentTD().innerHTML = GetContentTD().innerHTML;
2289
2290 // Find the bf table
2291 var tables = document.getElementsByClassName("table_lines battlefield");
2292 if(tables.length == 0) return;
2293
2294 bfTable = tables[0];
2295
2296 // Add next and back buttons at top
2297 if(bfTable.rows.length > 11)
2298 {
2299 bfTable.insertRow(1).innerHTML = bfTable.rows[bfTable.rows.length - 1].innerHTML;
2300 bfTable.rows[1].style.backgroundColor = "#222222";
2301 }
2302 bfTable.rows[bfTable.rows.length - 1].style.backgroundColor = "#222222";
2303
2304 // Dont let the alliance column dominate
2305 bfTable.rows[0].cells[1].width = "15%";
2306
2307 // Log bf gold
2308 var logList = "";
2309
2310 for(var i = 0; i < bfTable.rows.length; i++)
2311 {
2312 if(bfTable.rows[i].cells.length != 7) continue;
2313
2314 var usernameInner = bfTable.rows[i].cells[2].innerHTML;
2315 var username = GetTextIn(usernameInner, ">", "<");
2316 var statid = GetTextIn(usernameInner, "id=", "\"");
2317
2318 var tff = bfTable.rows[i].cells[3].innerHTML.replace(/,/g, "");
2319 var race = bfTable.rows[i].cells[4].innerHTML.trim();
2320 var treasury = bfTable.rows[i].cells[5].innerHTML.replace(/,/g, "").replace(" Gold", "");
2321 var rank = bfTable.rows[i].cells[6].innerHTML.replace(/,/g, "");
2322
2323 logList += "#username=" + username + "*gold=" + treasury + "*tff=" + tff + "*userid=" + statid + "*rank=" + rank + "*race=" + race;
2324 if(treasury > 200000000){ bfTable.rows[i].style.backgroundColor = "#2F4F4F";}
2325 if(treasury > 1000000000){ bfTable.rows[i].style.backgroundColor = "#8B0000"; }
2326 // Also make username links open in new tab
2327 bfTable.rows[i].cells[2].innerHTML = bfTable.rows[i].cells[2].innerHTML.replace("href=", "target=_blank href=");
2328 }
2329
2330 var statDiv = document.createElement('div');
2331 statDiv.setAttribute('id', "statDiv");
2332 statDiv.setAttribute('style', "text-align:center; position:fixed; right:10px; bottom:10px; width:15ex; border:1px solid gray; background-color:black; color:white; font-size:10pt;");
2333 statDiv.innerHTML = "Loading...";
2334 document.body.appendChild(statDiv);
2335
2336 GM_xmlhttpRequest(
2337 {
2338 method: "POST",
2339 url: DF_server + "backbone.php",
2340 headers: { 'Content-type' : 'application/x-www-form-urlencoded' },
2341 data: encodeURI("code=logbattlefield&whoami=" + DF_username + "&password=" + DF_password + "&whoamid=" + DF_statid + "&fill=" + GM_getValue("DF_fillBattlefield", 1) + "&list=" + logList),
2342 onload: function(r)
2343 {
2344
2345 if(r.status != 200) return;
2346
2347 if(GM_getValue("DF_fillBattlefield", 1) != 1) return;
2348
2349 document.getElementById('statDiv').innerHTML = "Loaded!";
2350
2351 for(var i = 0; i < bfTable.rows.length; i++)
2352 {
2353 if(bfTable.rows[i].cells.length != 7) continue;
2354
2355 var username = GetTextIn(bfTable.rows[i].cells[2].innerHTML, ">", "<");
2356 var data = GetTextIn(r.responseText, "[" + username + "]", "[/" + username + "]");
2357
2358 if(data == "") continue;
2359
2360 if(bfTable.rows[i].cells[5].innerHTML == "??? Gold")
2361 {
2362 bfTable.rows[i].cells[5].innerHTML = GetTextIn(data, "[aGOLD]", "[/aGOLD]") + "   <span style='color:yellow'>" + GetTextIn(data, "[GOLD]", "[/GOLD]") + "</span> Gold";
2363 }
2364
2365 var sa = GetTextIn(data, "[SA]", "[/SA]");
2366 var da = GetTextIn(data, "[DA]", "[/DA]");
2367 var spy = GetTextIn(data, "[SPY]", "[/SPY]");
2368 var sentry = GetTextIn(data, "[SENTRY]", "[/SENTRY]");
2369
2370 var saTime = GetTextIn(data, "[aSA]", "[/aSA]");
2371 var daTime = GetTextIn(data, "[aDA]", "[/aDA]");
2372 var spyTime = GetTextIn(data, "[aSPY]", "[/aSPY]");
2373 var sentryTime = GetTextIn(data, "[aSENTRY]", "[/aSENTRY]");
2374
2375 var player = [username, sa, saTime, da, daTime, spy, spyTime, sentry, sentryTime];
2376 bfPlayers[i] = player;
2377
2378 bfTable.rows[i].addEventListener('mouseover', BattlefieldPHP_OnShowStat, true);
2379 bfTable.rows[i].addEventListener('mouseout', function(){ document.getElementById('statDiv').style.display = 'none'; }, true);
2380 }
2381 }
2382 });
2383
2384 // Add an option to fill the battlefield
2385 bfTable.rows[0].cells[0].innerHTML = "<input type=checkbox id=FillBattlefield " + (GM_getValue("DF_fillBattlefield", 1) == 1 ? "checked" : "") + "><label for=FillBattlefield>Fill BF</label>";
2386 document.getElementById('FillBattlefield').addEventListener('click', function(){ GM_setValue("DF_fillBattlefield", this.checked ? 1 : 0); window.location = window.location; }, false);
2387
2388 if(GM_getValue("DF_fillBattlefield", 1) != 1)
2389 {
2390 statDiv.innerHTML = "Logged!";
2391 }
2392}
2393
2394function BattlefieldPHP_OnShowStat()
2395{
2396 var username = GetTextIn(this.cells[2].innerHTML, ">", "<");
2397
2398 var idx = -1;
2399
2400 for(var i = 0; i < bfPlayers.length; i++)
2401 {
2402 if(bfPlayers[i] && bfPlayers[i][0] == username)
2403 {
2404 idx = i;
2405 break;
2406 }
2407 }
2408
2409 if(idx < 0) return;
2410
2411 var sa = bfPlayers[idx][1];
2412 var da = bfPlayers[idx][3];
2413 var spy = bfPlayers[idx][5];
2414 var sentry = bfPlayers[idx][7];
2415
2416 var saTime = bfPlayers[idx][2];
2417 var daTime = bfPlayers[idx][4];
2418 var spyTime = bfPlayers[idx][6];
2419 var sentryTime = bfPlayers[idx][8];
2420
2421 var statDiv = document.getElementById('statDiv');
2422
2423 statDiv.innerHTML = "<table width=100% class=table_lines cellspacing=0 cellpadding=6>"
2424 + "<tr><th colspan=3>" + username + "'s Stats</th></tr>"
2425 + "<tr><td><b>Attack</b></td><td align=right id=DB_sa>" + sa + "</td><td align=right id=DB_saTime>" + saTime + "</td></tr>"
2426 + "<tr><td><b>Defense</b></td><td align=right id=DB_da>" + da + "</td><td align=right id=DB_daTime>" + daTime + "</td></tr>"
2427 + "<tr><td><b>Spy</b></td><td align=right id=DB_spy>" + spy + "</td><td align=right id=DB_spyTime>" + spyTime + "</td></tr>"
2428 + "<tr><td><b>Sentry</b></td><td align=right id=DB_sentry>" + sentry + "</td><td align=right id=DB_sentryTime>" + sentryTime + "</td></tr>"
2429 + "</table>";
2430
2431 statDiv.style.width = "60ex";
2432 statDiv.style.display = '';
2433}
2434
2435function DetailPHP()
2436{
2437 if(GM_getValue("DF_eligable", 0) == 0)
2438 {
2439 return;
2440 }
2441
2442 var listenKeyboard = GM_getValue("DF_OptionKS", 1);
2443
2444 if(url.indexOf("suspense=1") >= 0)
2445 {
2446 // Remove suspense
2447 var th = GetTag('th', "Battle Report");
2448 var content = th.parentNode.parentNode.parentNode.parentNode.parentNode;
2449 var scriptSource = GetTextIn(content.innerHTML, "<script", "</script>");
2450
2451
2452 if(scriptSource != "")
2453 {
2454 var content2 = content.innerHTML.replace(scriptSource, ">");
2455
2456 content2 = content2.replace("table_lines battle", "table_lines");
2457 content2 = content2.replace(/display: none/g, "");
2458
2459 content.innerHTML = content2;
2460 }
2461 }
2462
2463 // Scroll down to the useful part
2464 var but = GetElement('input', "Attack / Spy Again");
2465 but.scrollIntoView();
2466
2467 // Log the attack
2468 var attackType = GetText("your soldiers are trained ", " specialists");
2469 if(attackType != "attack")
2470 {
2471 // Log only attacks from our players ;)
2472 return;
2473 }
2474
2475 var reportId = url.indexOf("suspense") >= 0 ? GetTextIn(url, "_id=", "&suspense") : url.substring(49, url.length);
2476 var treasury = 0;
2477 var opponent = GetText("casualties!",">", "'s forces").trim();
2478 opponent = opponent.split("\n")[1];
2479
2480 var result = document.body.innerHTML.indexOf("You <font ") > 0 ? "Successful" : "Defended";
2481
2482 if(document.body.innerHTML.indexOf("You stole") >= 0)
2483 {
2484 treasury = parseInt( GetText("You stole", ">", "<").replace(/,/g, "") );
2485
2486 // Add a shortcut to armory
2487 but.parentNode.innerHTML += "<a href='http://www.kingsofchaos.com/armory.php' style='border: 1px solid #888888; background: black; font-size: 10pt; color: white; padding: 1px 10px;'> Armory" + (listenKeyboard == 0 ? "" : " (b)") + "</a>";
2488 but = GetElement('input', "Attack / Spy Again");
2489 }
2490
2491 var untrained = 0;
2492
2493 if(document.body.innerHTML.indexOf("untrained soldiers with weapons and ") >= 0)
2494 {
2495 untrained += parseInt(GetText("The enemy has <b>","</b> untrained soldiers").replace(/,/g,""));
2496 untrained += parseInt(GetText("untrained soldiers with weapons and <b>","</b> with no weapons").replace(/,/g,""));
2497 }
2498
2499
2500 if(document.body.innerHTML.indexOf(">None</font> of the enemy's ") >= 0)
2501 {
2502 if(GetText("None</font> of the enemy's "," untrained soldiers have weapons"))
2503 {
2504 untrained += parseInt(GetText("None</font> of the enemy's "," untrained soldiers have weapons").replace(/,/,""));
2505 }
2506 }
2507
2508 var elost = 0;
2509 if(document.body.innerHTML.indexOf("The enemy sustains ") >= 0)
2510 {
2511 elost = parseInt(String(FindText(GetText('The enemy sustains','/fon'),">","<")).replace(/,/g, ''));
2512 }
2513
2514 // Add a place golder for the result of the logging
2515 but.parentNode.innerHTML = but.parentNode.innerHTML.replace("Attack / Spy Again", "Attack / Spy Again" + (listenKeyboard == 0 ? "" : " (kp)")) + "<span id=logAttack style=\"margin-left: 20px;\">Logging your attack...</span>";
2516
2517
2518 if ( Get_Cookie("attackType") == "raid" )
2519 {
2520 var aType = "raid";
2521 }else if(treasury > 1)
2522 {
2523 var aType = "succesful";
2524 }else{
2525 var aType = "defended";
2526 }
2527
2528
2529 document.cookie = "attackType=notRaid;";
2530
2531
2532}
2533
2534function WritemailPHP()
2535{
2536 if(url.indexOf("recruit") != -1) {
2537 var username = GetTextIn(document.body.innerHTML, "</b>", "</th").trim();
2538
2539 var msg = GM_getValue("DF_msg_recruit", "").replace(/%name%/g, username);
2540
2541 if(msg.length == 0){
2542 alert("You can set you recruit msg in your inbox. In the top right click 'set recruit msg'");
2543 }
2544
2545 document.getElementsByTagName('textarea')[0].value = msg;
2546 }
2547 else {
2548 document.getElementsByTagName('textarea')[0].value = GM_getValue("DF_msg_sig", "");
2549 }
2550
2551 // If send button is clicked, save time
2552 document.addEventListener('click', function(event) {
2553 if(event.target.value)
2554 {
2555 var value = String(event.target.value);
2556 if(value.indexOf("Send") == 0)
2557 {
2558 GM_setValue("DF_msg_sent_time_" + username, getCurrentTime());
2559 GM_setValue("DF_msg_sent_content_" + username, document.getElementsByTagName('textarea')[0].value);
2560 }
2561 }
2562
2563 }, true);
2564}
2565
2566function AttackLogPHP()
2567{
2568 if(GM_getValue("DF_eligable", 0) == 0)
2569 {
2570 return;
2571 }
2572
2573 // Disable ajax navigation on koc
2574 GetContentTD().innerHTML = GetContentTD().innerHTML;
2575
2576 // Find the log tables
2577 var tables = document.getElementsByClassName("table_lines attacklog");
2578 if(tables.length == 0) return;
2579
2580
2581 for(var i = 0; i < tables.length; i++)
2582 {
2583 var table = tables[i];
2584 var log = "";
2585 var incoming = false;
2586
2587 if(table.rows[0].cells[0].innerHTML.indexOf("Attacks on You") != -1){
2588 incoming = true;
2589 }
2590
2591 for(var j = 2; j < table.rows.length; j++)
2592 {
2593 var row = table.rows[j];
2594
2595 if(incoming){
2596 if(row.cells.length != 9) continue;
2597
2598 var attacker = GetTextIn(row.cells[2].innerHTML, ">", "<");
2599 var attacked = DF_username;
2600 var type = row.cells[3].innerHTML;
2601 var reportId = GetTextIn(row.cells[4].innerHTML, "attack_id=", "\"");
2602 var gold = "0";
2603 var result = "Defended";
2604 var goldStr = GetTextIn(row.cells[4].innerHTML, ">", "<");
2605 if(goldStr.indexOf(" Gold stolen") != -1){
2606 result = "Successful";
2607 gold = goldStr.replace(/,/g, "").replace(" Gold stolen", "");
2608 }
2609 var lost = row.cells[5].innerHTML.replace(/,/g, "");
2610 var extra = row.cells[0].innerHTML + " " + row.cells[1].innerHTML;
2611
2612 log += "#username=" + attacker + "*target=" + attacked + "*type=" + type + "*reportid=" + reportId + "*result=" + result + "*gold=" + gold + "*lost=" + lost + "*extra=" + extra;
2613 }
2614 else {
2615 if(row.cells.length != 8) continue;
2616
2617 var attacker = DF_username;;
2618 var attacked = GetTextIn(row.cells[2].innerHTML, ">", "<");
2619 var type = "";
2620 var reportId = GetTextIn(row.cells[3].innerHTML, "attack_id=", "\"");
2621 var gold = "0";
2622 var result = "Defended";
2623 var goldStr = GetTextIn(row.cells[3].innerHTML, ">", "<");
2624 if(goldStr.indexOf(" Gold stolen") != -1){
2625 result = "Successful";
2626 gold = goldStr.replace(/,/g, "").replace(" Gold stolen", "");
2627 }
2628 var lost = row.cells[4].innerHTML.replace(/,/g, "");
2629 var extra = row.cells[0].innerHTML + " " + row.cells[1].innerHTML;
2630
2631 log += "#username=" + attacker + "*target=" + attacked + "*type=" + type + "*reportid=" + reportId + "*result=" + result + "*gold=" + gold + "*lost=" + lost + "*extra=" + extra;
2632 }
2633 }
2634
2635 GM_xmlhttpRequest(
2636 {
2637 method: "POST",
2638 url: DF_server + "backbone.php",
2639 headers: { 'Content-type' : 'application/x-www-form-urlencoded' },
2640 data: encodeURI("code=logattacks&whoami=" + DF_username + "&password=" + DF_password + "&whoamid=" + DF_statid + "&list=" + log)
2641 });
2642 }
2643}
2644
2645
2646function InboxPHP()
2647{
2648 // Create Set Signature Button
2649 var setSignature = GetElement('input', "Delete Entire Inbox").parentNode.parentNode;
2650 setSignature.innerHTML = '<button onclick="document.getElementById(\'signatureBox\').style.visibility = \'visible\'; return false;" style="float: right; margin-left: 15px;">Set Signature</button>' + setSignature.innerHTML;
2651
2652 // Box for Signature Editing
2653 var signatureBox = document.createElement('div');
2654 signatureBox.setAttribute('id', 'signatureBox');
2655 signatureBox.style.visibility = 'hidden';
2656 signatureBox.style.position = 'absolute';
2657 signatureBox.style.left = '0';
2658 signatureBox.style.top = '0';
2659 signatureBox.style.width = '100%';
2660 signatureBox.style.height = window.outerHeight;
2661 signatureBox.style.textAlign = 'center';
2662 signatureBox.style.zIndex = '1000';
2663 signatureBox.style.backgroundColor = ' rgba(0,0,0,.75)';
2664 signatureBox.innerHTML = '<div style="width: 80%; margin: 50px auto; padding: 10px; text-align: center;"> \
2665 <h1>EDIT SIGNATURE</h1> \
2666 <textarea id="signature" style="width: 650px;height:350px;">' + GM_getValue("DF_msg_sig", "") + '</textarea><br> \
2667 <input type="button" onclick="var signatureBox = document.getElementById(\'signatureBox\'); signatureBox.style.visibility = \'hidden\';" value="Save Signature" style="margin-top: 5px; width: 150px; height: 35px;"> \
2668 </div>';
2669 document.body.appendChild(signatureBox);
2670
2671 // Create Set recruit msg Button
2672 setSignature.innerHTML = '<button onclick="document.getElementById(\'recruitBox\').style.visibility = \'visible\'; return false;" style="float: right; margin-left: 15px;">Set recruit msg</button>' + setSignature.innerHTML;
2673
2674 // Box for recruit msg Editing
2675 var recruitBox = document.createElement('div');
2676 recruitBox.setAttribute('id', 'recruitBox');
2677 recruitBox.style.visibility = 'hidden';
2678 recruitBox.style.position = 'absolute';
2679 recruitBox.style.left = '0';
2680 recruitBox.style.top = '0';
2681 recruitBox.style.width = '100%';
2682 recruitBox.style.height = window.outerHeight;
2683 recruitBox.style.textAlign = 'center';
2684 recruitBox.style.zIndex = '1000';
2685 recruitBox.style.backgroundColor = ' rgba(0,0,0,.75)';
2686 recruitBox.innerHTML = '<div style="width: 80%; margin: 50px auto; padding: 10px; text-align: center;"> \
2687 <h1>EDIT RECRUIT MESSAGE</h1> \
2688 <p>%name% will be replace by username<p> \
2689 <textarea id="recruit" style="width: 850px;height:350px;">' + GM_getValue("DF_msg_recruit", "") + '</textarea><br> \
2690 <input type="button" onclick="var recruitBox = document.getElementById(\'recruitBox\'); recruitBox.style.visibility = \'hidden\';" value="Save recruit msg" style="margin-top: 5px; width: 150px; height: 35px;"> \
2691 </div>';
2692 document.body.appendChild(recruitBox);
2693
2694 // Save signature when clicked on Save button
2695 document.addEventListener('click', function(event) {
2696 if(event.target.value)
2697 {
2698 var value = String(event.target.value);
2699 if(value.indexOf("Save Signature") == 0)
2700 {
2701 GM_setValue("DF_msg_sig", document.getElementById('signature').value);
2702 }
2703 else if(value.indexOf("Save recruit msg") == 0)
2704 {
2705 GM_setValue("DF_msg_recruit", document.getElementById('recruit').value);
2706 }
2707 }
2708
2709 }, true);
2710}
2711
2712function RecruitPHP()
2713{
2714 var kocid = GetText("<a href=\"stats.php?id=", '"');
2715 var recruitid= document.URL.substring( document.URL.indexOf("=") +1 );
2716 //alert(kocid + " " + recruitid);
2717
2718 GM_xmlhttpRequest(
2719 {
2720 method: "POST",
2721 url: DF_server + "backbone.php",
2722 headers: { 'Content-type' : 'application/x-www-form-urlencoded' },
2723 data: encodeURI("code=addrecruitid&whoami=" + DF_username + "&password=" + DF_password + "&whoamid=" + DF_statid + "&kocid=" + kocid + "&recruitid=" + recruitid),
2724 onload: function(r)
2725 {
2726 if(r.status != 200) return;
2727 }
2728 });
2729}
2730
2731/*****************************************************************************/
2732/********************************* FUNCTIONS *********************************/
2733/*****************************************************************************/
2734
2735function AddCommas(val)
2736{
2737 var val2 = "";
2738
2739 for(var i = val.length - 1, j = 1; i >= 0; i--, j++)
2740 {
2741 val2 += val[i];
2742
2743 if(j % 3 == 0 && i)
2744 {
2745 val2 += ",";
2746 }
2747 }
2748
2749 var val3 = "";
2750
2751 for(var i = val2.length - 1; i >= 0; i--)
2752 {
2753 val3 += val2[i];
2754 }
2755
2756 return val3;
2757}
2758
2759//first n-1 args are 'begin', last one is end, should send at least 2 args
2760function GetText()
2761{
2762 var doc = document.body.innerHTML;
2763
2764 var pos = 0;
2765
2766 for(z = 0; z < (arguments.length - 1); z++)
2767 {
2768 pos = doc.indexOf(arguments[z], pos);
2769 if(pos < 0) return "";
2770
2771 pos += arguments[z].length;
2772 }
2773
2774 var pos2 = doc.indexOf(arguments[arguments.length - 1], pos);
2775 if(pos2 < 0) return "";
2776
2777 return doc.substring(pos, pos2);
2778}
2779
2780//the very first argumant is the text to search in, the rest is the same as GeText
2781function GetTextIn()
2782{
2783 var pos = 0;
2784
2785 for(var i = 1; i < (arguments.length - 1); i++)
2786 {
2787 pos = arguments[0].indexOf(arguments[i], pos);
2788 if(pos < 0) return "";
2789
2790 pos += arguments[i].length;
2791 }
2792
2793 var pos2 = arguments[0].indexOf(arguments[arguments.length - 1], pos);
2794 if(pos2 < 0) return "";
2795
2796 return arguments[0].substring(pos, pos2);
2797}
2798
2799function GetTag(tag, inner)
2800{
2801 var tagList = document.getElementsByTagName(tag);
2802
2803 for(z = 0; z < tagList.length; z++)
2804 {
2805 if(tagList[z].innerHTML.indexOf(inner) == 0)
2806 {
2807 return tagList[z];
2808 }
2809 }
2810
2811 return 0;
2812}
2813
2814function GetElement(elem, val)
2815{
2816 var elemList = document.getElementsByTagName(elem);
2817
2818 for(var i = 0; i < elemList.length; i++)
2819 {
2820 if(elemList[i].value.toString().indexOf(val) == 0)
2821 {
2822 return elemList[i];
2823 }
2824 }
2825
2826 return 0;
2827}
2828
2829function GetTable(thInner)
2830{
2831 var th = GetTag('th', thInner);
2832 if(!th) return 0;
2833
2834 return th.parentNode.parentNode;
2835}
2836
2837// returns 0-based index
2838function GetTableRow(table, cellId, inner)
2839{
2840 for(var i = 0; i < table.rows.length; i++)
2841 {
2842 if(table.rows[i].cells[cellId].innerHTML.indexOf(inner) >= 0)
2843 {
2844 return i;
2845 }
2846 }
2847
2848 return -1;
2849}
2850
2851function GetContentTD()
2852{
2853 var tables = document.getElementsByClassName("content");
2854 if(tables.length == 0) return 0;
2855
2856 return tables[0];
2857}
2858
2859// Convert ms to ... ago
2860function PrintableTime(elapsedMs)
2861{
2862 var secs = elapsedMs / 1000;
2863
2864 var months = parseInt( Math.floor(secs / 2592000) );
2865 secs -= months * 2592000;
2866
2867 var days = parseInt( Math.floor(secs / 86400) );
2868 secs -= days * 86400;
2869
2870 var s = parseInt( Math.floor(secs / 3600) );
2871 secs -= hours * 3600;
2872
2873 var minutes = parseInt( Math.floor(secs / 60) );
2874 secs -= minutes * 3600;
2875
2876 secs = parseInt( Math.floor(secs) );
2877
2878 var str = "";
2879
2880 if(months > 0) str += (months + " month" + (months > 1 ? "s " : " "));
2881 if(days > 0) str += (days + " day" + (days > 1 ? "s " : " "));
2882 if(hours > 0) str += (hours + " hour" + (hours > 1 ? "s " : " "));
2883 if(minutes > 0) str += (minutes + " minute" + (minutes > 1 ? "s " : " "));
2884 if(secs > 0) str += (secs + " second" + (secs > 1 ? "s " : " "));
2885
2886 return str.trim();
2887}
2888
2889function GetGold()
2890{
2891 var goldText = GetText("Gold:", ">", "<");
2892 if(goldText == "") return 0;
2893
2894 return parseInt( goldText.trim().replace(/,/g, "").replace('M', '000000') );
2895}
2896
2897function GetSoldier(type)
2898{
2899 var soldierText = GetText(type, "right\">", "<");
2900 if(soldierText == "") return 0;
2901
2902 return parseInt( soldierText.replace(/,/g, "") );
2903}
2904
2905function GetSoldiers()
2906{
2907 var tas = GetSoldier("Trained Attack Soldiers");
2908 var tam = GetSoldier("Trained Attack Mercenaries");
2909 var tds = GetSoldier("Trained Defense Soldiers");
2910 var tdm = GetSoldier("Trained Defense Mercenaries");
2911 var us = GetSoldier("Untrained Soldiers");
2912 var um = GetSoldier("Untrained Mercenaries");
2913 var spy = GetSoldier("Spies");
2914 var sentry = GetSoldier("Sentries");
2915 var tff = GetSoldier("Total Fighting Force");
2916
2917 return {'tas' : tas, 'tam' : tam, 'tds' : tds, 'tdm' : tdm, 'us' : us, 'um' : um, 'spy' : spy, 'sentry' : sentry, 'tff' : tff};
2918}
2919
2920function GetAvailableMerc(type)
2921{
2922 var mercText = GetText('>' + type + '<', "right\">", "right\">", "<");
2923 if(mercText == "None" || mercText == "") return 0;
2924
2925 return parseInt( mercText.replace(/,/g, "") );
2926}
2927
2928function GetAvailableMercs()
2929{
2930 var am = GetAvailableMerc("Attack Specialist");
2931 var dm = GetAvailableMerc("Defense Specialist");
2932 var um = GetAvailableMerc("Untrained");
2933
2934 return {'am' : am, 'dm' : dm, 'um' : um};
2935}
2936
2937function AddSoldierButton(soldierName, buttonId, callback)
2938{
2939 var td = GetTag('td', soldierName);
2940
2941 if(td)
2942 {
2943 td.parentNode.innerHTML += "<td><button id=" + buttonId + " onClick=\"return false;\">0</button></td>";
2944
2945 document.getElementById(buttonId).addEventListener('click', callback, false);
2946 }
2947}
2948
2949function ExpandCollapseTable(header, collapse)
2950{
2951 var th = GetTag('th', header);
2952 if(!th) return;
2953
2954 th.innerHTML += "<span id=toggle_" + header.replace(/ /g, "_") + " style=\"float:right\"><tt>-</tt></span>";
2955
2956 var table = th.parentNode.parentNode;
2957
2958 table.rows[0].addEventListener('click', function(){ OnExpColTable(header); }, false);
2959 table.rows[0].style.cursor = "pointer";
2960
2961 // Set the initial state
2962 if(collapse == undefined)
2963 {
2964 collapse = GM_getValue("DF_expcol_" + header.replace(/ /g, "_"), 1) == 0; // 1: expanded, 0: collapsed
2965 }
2966
2967 if(collapse)
2968 {
2969 OnExpColTable(header);
2970 }
2971}
2972
2973function OnExpColTable(header)
2974{
2975 var th = GetTag('th', header);
2976 if(!th) return;
2977
2978 var table = th.parentNode.parentNode;
2979
2980 if(table.rows.length < 2) return;
2981
2982 var disp = (table.rows[1].style.display == "none" ? "" : "none");
2983
2984 for(i = 1; i < table.rows.length; i++)
2985 {
2986 table.rows[i].style.display = disp;
2987 }
2988
2989 document.getElementById('toggle_' + header.replace(/ /g, "_")).innerHTML = "<tt>" + (disp == "none" ? "+" : "-") + "</tt>";
2990
2991 GM_setValue("DF_expcol_" + header.replace(/ /g, "_"), disp == "none" ? 0 : 1);
2992}
2993
2994function checkVersion()
2995{
2996 lastCheck = GM_getValue("DF_LastUpdateCheck_time", "");
2997 if(lastCheck == "")
2998 {
2999 GM_xmlhttpRequest(
3000 {
3001 method: "GET",
3002 url: DF_server + "version.php?ver=" + DF_version,
3003 onload: function(r)
3004 {
3005 if(r.status != 200) return;
3006 GM_setValue("DF_LastUpdateCheck_time", getCurrentTime());
3007 }
3008 });
3009 GM_setValue("DF_LastUpdateCheck_time", getCurrentTime());
3010 }
3011 else
3012 {
3013 if(getCurrentTime() - lastCheck > 600)
3014 {
3015 GM_xmlhttpRequest(
3016 {
3017 method: "GET",
3018 url: DF_server + "version.php?ver=" + DF_version,
3019 onload: function(r)
3020 {
3021 if(r.status != 200) return;
3022 var ver = parseInt(GetTextIn(r.responseText, "[VER]", "[/VER]"));
3023 var dlink = GetTextIn(r.responseText, "[LINK]", "[/LINK]");
3024 var changelog = GetTextIn(r.responseText, "[CHANGELOG]", "[/CHANGELOG]");
3025 if(DF_version < ver) {
3026 alert("You're using an old version of AaA's DF!\n----Changelog----\n " + changelog), GM_openInTab(dlink);
3027 GM_setValue("DF_LastUpdateCheck_time", getCurrentTime());
3028 }
3029 }
3030 });
3031 GM_setValue("DF_LastUpdateCheck_time", getCurrentTime());
3032 }
3033 }
3034}
3035
3036function getCurrentTime()
3037{
3038 return Math.round(new Date / 1E3);
3039}
3040
3041function AddMenuItems()
3042{
3043 var table = GetTag('td', "<img src=\"/images/menubar/age").parentNode.parentNode;
3044
3045 table.insertRow(3).insertCell(0).innerHTML = "<a href=\"http://www.kingsofchaos.com/stats.php?id=targetlist\"><img alt=\"Target List\" src=\"" + DF_server + "images/menubar_targets.gif\"></a>";
3046 table.insertRow(4).insertCell(0).innerHTML = "<a href=\"http://www.kingsofchaos.com/stats.php?id=farmlist\"><img alt=\"Farm List\" src=\"" + DF_server + "images/menubar_farmlist.gif\"></a>";
3047 table.insertRow(13).insertCell(0).innerHTML = "<a href=\"http://www.kingsofchaos.com/stats.php?id=links\"><img alt=\"Third Party Links\" src=\"" + DF_server + "images/links.gif\"></a>";
3048
3049 // check if there was a war last time
3050 var warStatus = GM_getValue("GO_war_status", 0);
3051 var warLink = GM_getValue("GO_war_link", "");
3052
3053 if(warStatus > 0)
3054 {
3055 // Add new menu item for the war
3056 table.insertRow(3).insertCell(0).innerHTML = "<a target=_blank href=\"" + warLink + "\"><img alt=\"War missions!\" src=\"" + DF_server + "images/missions.gif\"></a>";
3057 }
3058
3059 GM_xmlhttpRequest(
3060 {
3061 method: "GET",
3062 url: DF_server + "backbone.php?code=war&whoami=" + DF_username + "&password=" + DF_password,
3063 onload: function(r)
3064 {
3065 if(r.status != 200) return;
3066
3067
3068 if(r.responseText.indexOf("hide") < 0)
3069 {
3070 warLink = r.responseText.replace("[NAME]", DF_username);
3071
3072 if(warStatus > 0) // if there was war, just update
3073 {
3074 table.rows[3].cells[0].innerHTML = "<a target=_blank href=\"" + warLink + "\"><img alt=\"War missions!\" src=\"http://www.againstallauthority.nl/script/images/missions.gif\"></a>";
3075 }
3076 else
3077 {
3078 // Add new menu item for the war
3079 table.insertRow(3).insertCell(0).innerHTML = "<a target=_blank href=\"" + warLink + "\"><img alt=\"War missions!\" src=\"http://www.againstallauthority.nlscript/images/missions.gif\"></a>";
3080
3081 // Switch on war status
3082 GM_setValue("GO_war_status", 1);
3083 }
3084
3085 GM_setValue("GO_war_link", warLink);
3086 }
3087 else
3088 {
3089 // Switch off war status
3090 GM_setValue("GO_war_status", 0);
3091 GM_setValue("GO_war_link", "");
3092 }
3093
3094 }
3095 });
3096
3097}
3098
3099function AddBfSearch()
3100{
3101 var links = document.getElementsByTagName('a');
3102
3103 var firefoxLink = 0;
3104
3105 for(var i = 0; i < links.length; i++)
3106 {
3107 if(links[i].href.indexOf("spreadfirefox") >= 0)
3108 {
3109 firefoxLink = links[i];
3110 break;
3111 }
3112 }
3113
3114 if(firefoxLink)
3115 {
3116
3117 firefoxLink.parentNode.innerHTML = "<table border=\"0\" cellpadding=\"6\" cellspacing=\"0\" width=\"100%\"><tr><th>Battlefield</th></tr><tr><td align=\"center\"><input type=text id=bfSearchName style='width:120px;' /></td></tr><tr><td align=\"center\"><button id=bfSearchButton onClick=\"window.location='http://www.kingsofchaos.com/battlefield.php?search=' + document.getElementById('bfSearchName').value.trim();\">Search</button></td></tr><tr><td><div style='position:relative'><div id=resultsDiv style='position:absolute; margin-top: -80px; margin-left: 90px;z-index: 99;'><ul id=results style='list-style-type:none;'></ul></div></div></td></tr>";
3118
3119 var inputElem = document.getElementById("bfSearchName");
3120 inputElem.addEventListener('keyup', findUsername, true);
3121 }
3122
3123}
3124
3125function findUsername(e)
3126{
3127 if(e.keyCode == 27 || document.getElementById("bfSearchName").value == "")
3128 {
3129 document.getElementById("results").innerHTML = "";
3130 }
3131 else
3132 {
3133 GM_xmlhttpRequest(
3134 {
3135 method: "GET",
3136 url: DF_server + "backbone.php?code=findUsername&username=" + document.getElementById("bfSearchName").value,
3137 onload: function(r)
3138 {
3139 if(r.status == 200)
3140 {
3141 document.getElementById('results').innerHTML = r.responseText;
3142
3143 }
3144 }
3145 });
3146 }
3147}
3148
3149function CheckExpForNextTech()
3150{
3151 var targetExp = GM_getValue("DF_nextTechExp", -1);
3152 if(targetExp < 0)
3153 {
3154 return;
3155 }
3156
3157 var curExp = parseInt( GetText("Experience:", "color", ">", "<").trim().replace(/,/g, ""), 10 );
3158 if(isNaN(curExp))
3159 {
3160 return;
3161 }
3162
3163 if(curExp >= targetExp)
3164 {
3165 var t = GetTag('td', "Experience:");
3166 if(t)
3167 {
3168 t.style.color = "#CC0000";
3169 }
3170 }
3171}
3172
3173function DetectRunningInstance()
3174{
3175 if(document.getElementById('InstanceDF'))
3176 {
3177 return true;
3178 }
3179
3180 var instanceDiv = document.createElement('div');
3181 instanceDiv.style.display = 'none';
3182 instanceDiv.setAttribute('id', "InstanceDF");
3183 document.body.appendChild(instanceDiv);
3184
3185 return false;
3186}
3187
3188/*************************** base.php Functions ******************************/
3189
3190function BasePHP_OnRegisterDF(username, statid, uniqid, password, email)
3191{
3192 // ask for password
3193 var ret = password;
3194 while(true)
3195 {
3196 ret = prompt("Hello " + username + "!\nEnter your DF password:", password);
3197 if(ret == null)
3198 {
3199 return;
3200 }
3201
3202 if(ret.length > 0)
3203 {
3204 break;
3205 }
3206 };
3207
3208 password = ret;
3209 GM_setValue("DF_password", password);
3210 GM_setValue("password", password);
3211
3212 GM_xmlhttpRequest(
3213 {
3214 method: "GET",
3215 url: DF_server + "register.php?username=" + username + "&password=" + password + "&userid=" + statid + "&recruitid=" + uniqid
3216 });
3217
3218 alert("Your registration details have been sent to the AaA server.\n"
3219 + "Please wait until an AaA administrator activates your DF account.\n");
3220
3221 window.location = "http://www.kingsofchaos.com/base.php";
3222}
3223
3224function BasePHP_OnputDFPassword(username, password)
3225{
3226 // ask for password
3227 var ret = password;
3228 while(true)
3229 {
3230 ret = prompt("Hello " + username + "!\nEnter your DF password:", password);
3231 if(ret == null)
3232 {
3233 return;
3234 }
3235
3236 if(ret.length > 0)
3237 {
3238 break;
3239 }
3240 };
3241
3242 password = ret;
3243 GM_setValue("DF_password", password);
3244 GM_setValue("password", password);
3245
3246 window.location = "http://www.kingsofchaos.com/base.php";
3247}
3248
3249function BasePHP_OnToggleDFOptions()
3250{
3251 if(document.getElementById('ddfOptionsContainer').style.display == '')
3252 {
3253 document.getElementById('ddfOptionsContainer').style.display = 'none';
3254 document.getElementById('ddfOptions').style.display = 'none';
3255 }
3256 else
3257 {
3258 document.getElementById('ddfOptionsContainer').style.display = '';
3259 document.getElementById('ddfOptions').style.display = '';
3260 }
3261}
3262
3263function BasePHP_OnSaveDFOptions()
3264{
3265 GM_setValue("DF_OptionArmoryDetail", document.getElementById('dfOptionArmoryDetail').checked == true ? 1 : 0);
3266 GM_setValue("DF_OptionScrollIntoContent", document.getElementById('dfOptionScrollIntoContent').checked == true ? 1 : 0);
3267 GM_setValue("DF_OptionEconomicDevelopment", document.getElementById('dfOptionEconomicDevelopment').checked == true ? 1 : 0);
3268 GM_setValue("DF_OptionSpecialEffects", document.getElementById('dfOptionSpecialEffects').checked == true ? 1 : 0);
3269 GM_setValue("DF_OptionShowLastMsgSent", document.getElementById('dfOptionShowLastMsgSent').checked == true ? 1 : 0);
3270 GM_setValue("DF_OptionStickyMenu", document.getElementById('dfOptionStickyMenu').checked == true ? 1 : 0);
3271
3272 GM_setValue("DF_password", document.getElementById("dfOptionPassword").value);
3273
3274 // hide the options
3275 BasePHP_OnToggleDFOptions();
3276
3277 window.location = "base.php";
3278}
3279
3280
3281/*************************** armory.php Functions *****************************/
3282function ArmoryPHP_OnClearLostLog()
3283{
3284 var cf = confirm("Are you sure you want to clear the log?");
3285 if(!cf) return;
3286
3287 for(var i = 0; i < 10; i++)
3288 {
3289 GM_setValue("DF_lost_wep_log_" + i, "::");
3290 }
3291
3292 window.location = "armory.php";
3293}
3294
3295function ArmoryPHP_ReduceBloodEffect()
3296{
3297 var bloodDiv = document.getElementById('bloodDiv');
3298
3299 bloodDiv.style.opacity -= 0.1;
3300
3301 if(bloodDiv.style.opacity > 0)
3302 {
3303 setTimeout(ArmoryPHP_ReduceBloodEffect, 100);
3304 }
3305 else
3306 {
3307 bloodDiv.style.display = 'none';
3308 }
3309}
3310
3311function ArmoryPHP_UpdateWeaponButtons()
3312{
3313 var totalGoldNeed = 0;
3314
3315 var buyTable = GetTable("Buy Weapons");
3316
3317 for(var i = 2; i < buyTable.rows.length; i++)
3318 {
3319 if(buyTable.rows[i].cells.length < 5) continue;
3320
3321 var buybutId = GetTextIn(buyTable.rows[i].cells[3].innerHTML, "name=\"", "\"");
3322
3323 var wepCost = parseInt( buyTable.rows[i].cells[2].innerHTML.replace(/,/g, "") );
3324
3325 var wepCount = parseInt( document.getElementsByName(buybutId)[0].value, 10 );
3326
3327 if(isNaN(wepCount) || wepCount < 0)
3328 {
3329 wepCount = 0;
3330 document.getElementsByName(buybutId)[0].value = 0;
3331 }
3332
3333 totalGoldNeed += (wepCost * wepCount);
3334 }
3335
3336 if(totalGoldNeed > gold)
3337 {
3338 if(this.name.length > 0)
3339 {
3340 this.value = 0;
3341
3342 ArmoryPHP_UpdateWeaponButtons();
3343
3344 return;
3345 }
3346 }
3347
3348 // Update the buttons with the left amount and compose the buying note
3349 var leftGold = gold - totalGoldNeed;
3350 var buyingNote = [];
3351
3352 for(var i = 2; i < buyTable.rows.length; i++)
3353 {
3354 if(buyTable.rows[i].cells.length < 5) continue;
3355
3356 var buybutId = GetTextIn(buyTable.rows[i].cells[3].innerHTML, "name=\"", "\"");
3357
3358 var wepCost = parseInt( buyTable.rows[i].cells[2].innerHTML.replace(/,/g, "") );
3359
3360 var wepCount = parseInt( document.getElementsByName(buybutId)[0].value, 10 );
3361
3362 document.getElementById(buybutId).innerHTML = wepCount + Math.floor( leftGold / wepCost );
3363
3364 // buying note
3365 var wepName = buyTable.rows[i].cells[0].innerHTML;
3366
3367 if(weaponList.indexOf(wepName) >= 0 && wepCount > 0)
3368 {
3369 buyingNote.push(wepCount + " " + wepName + (wepCount > 1 ? "s" : ""));
3370 }
3371 }
3372
3373 // Update the buying note
3374 document.getElementById('BuyingNote').innerHTML = (buyingNote.length == 0 ? "Nothing" : buyingNote.join("<br />"));
3375}
3376
3377function ArmoryPHP_OnClearBuyButtons()
3378{
3379 var buyTable = GetTable("Buy Weapons");
3380
3381 for(var i = 2; i < buyTable.rows.length; i++)
3382 {
3383 if(buyTable.rows[i].cells.length < 5) continue;
3384
3385 var buybutId = GetTextIn(buyTable.rows[i].cells[3].innerHTML, "name=\"", "\"");
3386
3387 document.getElementsByName(buybutId)[0].value = 0;
3388 }
3389
3390 ArmoryPHP_UpdateWeaponButtons();
3391}
3392
3393function ArmoryPHP_OnSellButton()
3394{
3395 var wepId = GetTextIn(this.parentNode.parentNode.innerHTML, "scrapsell[", "]");
3396
3397 var wepBuyBut = document.getElementById("buy_weapon[" + wepId + "]");
3398 if(!wepBuyBut) return;
3399
3400 var wepName = wepBuyBut.parentNode.parentNode.cells[0].innerHTML;
3401 if(weaponList.indexOf(wepName) < 0) return;
3402
3403 var wepSellCount = parseInt( document.getElementsByName('scrapsell[' + wepId + ']')[0].value, 10 );
3404 if(wepSellCount < 0) return;
3405
3406 GM_setValue("DF_armory_" + wepName.replace(/ /g, "_") + "_sold", wepSellCount);
3407}
3408
3409
3410/*************************** attack.php Functions *****************************/
3411
3412function AttackPHP_OnSubmitSab(targetname)
3413{
3414 // Remember sabotage settings for this target
3415 GM_setValue("DF_sab_wep_" + targetname, document.getElementsByTagName('select')[0].value);
3416 GM_setValue("DF_sab_cnt_" + targetname, document.getElementsByName('numsab')[0].value);
3417 GM_setValue("DF_sab_spies_" + targetname, document.getElementsByName('numspies')[0].value);
3418 GM_setValue("DF_sab_turns_" + targetname, document.getElementsByTagName('select')[1].value);
3419}
3420
3421function SaveLastSab(targetname, weapon, amount, spies, turns)
3422{
3423 // Remember sabotage settings for this target
3424 GM_setValue("DF_sab_wep_" + targetname, weapon);
3425 GM_setValue("DF_sab_cnt_" + targetname, amount);
3426 GM_setValue("DF_sab_spies_" + targetname, spies);
3427 GM_setValue("DF_sab_turns_" + targetname, turns);
3428}
3429
3430function AttackPHP_SetReconCnt(username)
3431{
3432 if(GM_getValue("DF_recon_cnt_" + username, 15) > 0)
3433 {
3434 GM_setValue("DF_recon_cnt_" + username, GM_getValue("DF_recon_cnt_" + username, 15) - 1);
3435 GM_setValue("DF_recon_dates_" + username, GM_getValue("DF_recon_dates_"+ username, "") + getCurrentTime() + ",");
3436 }
3437}
3438
3439function AttackPHP_GetLastMsgSent(username)
3440{
3441 if(GM_getValue("DF_msg_sent_time_" + username, "Never") == "Never")
3442 {
3443 return "<span style=color:gray>" + "Never" + "</span>";
3444 }
3445 else
3446 {
3447 var timeAgo = ConvertTimeSimple(GM_getValue("DF_msg_sent_time_" + username)) + " ago";
3448 if(timeAgo.indexOf("second") >= 0) return "<span style=color:red>" + timeAgo + "</span>";
3449 else if(timeAgo.indexOf("minute") >= 0)
3450 {
3451 var timeAgoSplit = timeAgo.split(" ");
3452 if(timeAgoSplit[0] <= 15) return "<span style=color:yellow>" + timeAgo + "</span>";
3453 else return "<span style=color:green>" + timeAgo + "</span>";
3454 }
3455 else if(timeAgo.indexOf("hour") >= 0) return "<span style=color:green>" + timeAgo + "</span>";
3456 else return "<span style=color:gray>" + timeAgo + "</span>";
3457 }
3458}
3459
3460function InteldetailPHP_CalcReconsLeft(username)
3461{
3462 var reconDatesStr = GM_getValue("DF_recon_dates_"+ username, "");
3463 var reconDates = reconDatesStr.split(",");
3464 var newReconDatesStr = "";
3465
3466 if(reconDates.length >= 1 && reconDates[0] != "")
3467 {
3468 if(getCurrentTime() - reconDates[0] > 86400) // 24 hours = 60 * 60 * 24 = 86400
3469 {
3470 GM_setValue("DF_recon_cnt_" + username, GM_getValue("DF_recon_cnt_" + username, 15) + 1);
3471 reconDates.splice(0, 1);
3472
3473 for(var i = 0; i < reconDates.length; i++)
3474 {
3475 if(reconDates[i] != "")
3476 {
3477 newReconDatesStr += reconDates[i] + ",";
3478 }
3479 }
3480
3481 if(newReconDatesStr == "")
3482 {
3483 GM_deleteValue("DF_recon_dates_" + username);
3484 GM_deleteValue("DF_recon_cnt_" + username);
3485 }
3486 else
3487 {
3488 GM_setValue("DF_recon_dates_" + username, newReconDatesStr);
3489 InteldetailPHP_CalcReconsLeft(username);
3490 }
3491 }
3492 }
3493}
3494
3495/*************************** train.php Functions *****************************/
3496
3497function TrainPHP_OnAssignSoldier()
3498{
3499 switch(this.id)
3500 {
3501 case 'assign_attack':
3502 document.getElementsByName('train[attacker]')[0].value = document.getElementById(this.id).innerHTML;
3503 break;
3504
3505 case 'assign_defense':
3506 document.getElementsByName('train[defender]')[0].value = document.getElementById(this.id).innerHTML;
3507 break;
3508
3509 case 'assign_spy':
3510 document.getElementsByName('train[spy]')[0].value = document.getElementById(this.id).innerHTML;
3511 break;
3512
3513 case 'assign_sentry':
3514 document.getElementsByName('train[sentry]')[0].value = document.getElementById(this.id).innerHTML;
3515 break;
3516 }
3517
3518 TrainPHP_UpdateTrainingButtons();
3519}
3520
3521function TrainPHP_UpdateTrainingButtons()
3522{
3523 var tattack = 1 * document.getElementsByName('train[attacker]')[0].value;
3524 var tdefense = 1 * document.getElementsByName('train[defender]')[0].value;
3525 var tspy = 1 * document.getElementsByName('train[spy]')[0].value;
3526 var tsentry = 1 * document.getElementsByName('train[sentry]')[0].value;
3527
3528 if(tattack < 0 || isNaN(tattack)) tattack = 0;
3529 if(tdefense < 0 || isNaN(tdefense)) tdefense = 0;
3530 if(tspy < 0 || isNaN(tspy)) tspy = 0;
3531 if(tsentry < 0 || isNaN(tsentry)) tsentry = 0;
3532
3533 var remainingSoldiers = soldiers.us - (tattack + tdefense + tspy + tsentry);
3534
3535 if(remainingSoldiers < 0)
3536 {
3537 tattack = tdefense = tspy = tsentry = 0;
3538 remainingSoldiers = soldiers.us;
3539 }
3540
3541 var remainingGold = gold - (tattack + tdefense) * 2000 - (tspy + tsentry) * 3500;
3542 if(remainingGold <= 0) remainingGold = 0;
3543
3544 var remain2 = Math.min( Math.floor(remainingGold / 2000), remainingSoldiers );
3545 var remain3 = Math.min( Math.floor(remainingGold / 3500), remainingSoldiers );
3546
3547 document.getElementById('assign_attack').innerHTML = remain2 ? tattack + remain2 : 0;
3548 document.getElementById('assign_defense').innerHTML = remain2 ? tdefense + remain2 : 0;
3549 document.getElementById('assign_spy').innerHTML = remain3 ? tspy + remain3 : 0;
3550 document.getElementById('assign_sentry').innerHTML = remain3 ? tsentry + remain3 : 0;
3551
3552 document.getElementsByName('train[attacker]')[0].value = tattack;
3553 document.getElementsByName('train[defender]')[0].value = tdefense;
3554 document.getElementsByName('train[spy]')[0].value = tspy;
3555
3556 document.getElementsByName('train[sentry]')[0].value = tsentry;
3557}
3558
3559function TrainPHP_ClearTraining()
3560{
3561 document.getElementsByName('train[attacker]')[0].value = 0;
3562 document.getElementsByName('train[defender]')[0].value = 0;
3563 document.getElementsByName('train[spy]')[0].value = 0;
3564 document.getElementsByName('train[sentry]')[0].value = 0;
3565 document.getElementsByName('train[unattacker]')[0].value = 0;
3566 document.getElementsByName('train[undefender]')[0].value = 0;
3567
3568 TrainPHP_UpdateTrainingButtons();
3569}
3570
3571function TrainPHP_OnToggleTechs()
3572{
3573 var stateSpan = document.getElementById('toggle_techs');
3574 var state = stateSpan.innerHTML.indexOf("+") >= 0;
3575 var table = GetTag('th', "Technological Development").parentNode.parentNode;
3576
3577 for(i = 3; i < table.rows.length; i++)
3578 {
3579 table.rows[i].style.display = state ? '' : 'none';
3580 }
3581
3582 stateSpan.innerHTML = stateSpan.innerHTML.replace(state ? '+' : '-', state ? '-' : '+');
3583}
3584
3585
3586/*************************** mercs.php Functions *****************************/
3587
3588function MercsPHP_OnAssignMerc()
3589{
3590 switch(this.id)
3591 {
3592 case 'assign_attack':
3593 document.getElementsByName('mercs[attack]')[0].value = document.getElementById(this.id).innerHTML;
3594 break;
3595
3596 case 'assign_defense':
3597 document.getElementsByName('mercs[defend]')[0].value = document.getElementById(this.id).innerHTML;
3598 break;
3599
3600 case 'assign_untrained':
3601 document.getElementsByName('mercs[general]')[0].value = document.getElementById(this.id).innerHTML;
3602 break;
3603 }
3604
3605 MercsPHP_UpdateMercButtons();
3606}
3607
3608function MercsPHP_UpdateMercButtons()
3609{
3610 var mattack = 1 * document.getElementsByName('mercs[attack]')[0].value;
3611 var mdefense = 1 * document.getElementsByName('mercs[defend]')[0].value;
3612 var muntrained = 1 * document.getElementsByName('mercs[general]')[0].value;
3613
3614 if(mattack < 0 || isNaN(mattack)) mattack = 0;
3615 if(mdefense < 0 || isNaN(mdefense)) mdefense = 0;
3616 if(muntrained < 0 || isNaN(muntrained)) muntrained = 0;
3617
3618 var mercLimit = Math.floor((soldiers.tas + soldiers.tds + soldiers.us) / 3) - (soldiers.tam + soldiers.tdm + soldiers.um);
3619
3620 // display how much merc is at hand
3621 var t = GetTag('h3', "Mercenaries");
3622 if(t)
3623 {
3624 if(mercLimit <= 0)
3625 {
3626 //you cannot but any more mercs
3627 if(t.innerHTML.indexOf("You have ") < 0)
3628 {
3629 t.innerHTML += "<font color=red style=\"float: right; margin-right: 4ex;\">Warning: You have at least 25% mercs!</font>";
3630 }
3631 }
3632 else
3633 {
3634 if(t.innerHTML.indexOf("You have ") < 0)
3635 {
3636 var perc = 100 * (soldiers.tam + soldiers.tdm + soldiers.um) / soldiers.tff;
3637 t.innerHTML += "<font color=white style=\"float: right; margin-right: 4ex;\">You have " + perc.toFixed(2) + "% mercs</font>";
3638 }
3639 }
3640 }
3641
3642 mercLimit -= (mattack + mdefense + muntrained);
3643
3644 if(mercLimit < 0)
3645 {
3646 mattack = mdefense = muntrained = 0;
3647 mercLimit = Math.floor((soldiers.tas + soldiers.tds + soldiers.us) / 3) - (soldiers.tam + soldiers.tdm + soldiers.um);
3648
3649 if(mercLimit <= 0)
3650 {
3651 mercLimit = 0;
3652 }
3653 }
3654
3655 var remainingGold = gold - (mattack + mdefense) * 4500 - muntrained * 3500;
3656 if(remainingGold <= 0) remainingGold = 0;
3657
3658 var maxAttack = Math.min( Math.min( Math.floor(remainingGold / 4500), mercLimit ), mercs.am);
3659 var maxDefense = Math.min( Math.min( Math.floor(remainingGold / 4500), mercLimit ), mercs.dm);
3660 var maxUntrained = Math.min( Math.min( Math.floor(remainingGold / 3500), mercLimit ), mercs.um);
3661
3662 document.getElementById('assign_attack').innerHTML = maxAttack ? mattack + maxAttack : 0;
3663 document.getElementById('assign_defense').innerHTML = maxDefense ? mdefense + maxDefense : 0;
3664 document.getElementById('assign_untrained').innerHTML = maxUntrained ? muntrained + maxUntrained : 0;
3665
3666 document.getElementsByName('mercs[attack]')[0].value = mattack;
3667 document.getElementsByName('mercs[defend]')[0].value = mdefense;
3668 document.getElementsByName('mercs[general]')[0].value = muntrained;
3669}
3670
3671function MercsPHP_ClearMercs()
3672{
3673 document.getElementsByName('mercs[attack]')[0].value = 0;
3674 document.getElementsByName('mercs[defend]')[0].value = 0;
3675 document.getElementsByName('mercs[general]')[0].value = 0;
3676
3677 MercsPHP_UpdateMercButtons();
3678}
3679
3680
3681/*************************** Custom page *****************************/
3682function CustomPage(page)
3683{
3684 // Find the content holder
3685 var td = GetContentTD();
3686
3687 if(td)
3688 {
3689 td.innerHTML = "<h3>Loading...</h3>Please wait...";
3690
3691 qry = "";
3692
3693 // Parse other inputs
3694 if(url.indexOf("&") > 0)
3695 {
3696 qry = url.substring(url.indexOf("&"), url.length);
3697 }
3698
3699 GM_xmlhttpRequest(
3700 {
3701 method: "GET",
3702 url: DF_server + "pages/" + page + ".php?whoami=" + DF_username + "&password=" + DF_password + qry,
3703 onload: function(r)
3704 {
3705 if(r.status != 200) return;
3706
3707 if(r.responseText.indexOf("[START]") >= 0)
3708 {
3709 td.innerHTML = GetTextIn(r.responseText, "[START]", "[END]");
3710
3711 if(td.innerHTML == "")
3712 {
3713 td.innerHTML = "<h3>Not available</h3>";
3714 }
3715 }
3716 else
3717 {
3718 if(r.finalUrl.indexOf("kingsofchaos.com") >= 0) {
3719 document.location = r.finalUrl;
3720 }
3721 else {
3722 td.innerHTML = "<h3>Not available</h3>";
3723 }
3724 }
3725 }
3726 });
3727 }
3728}
3729
3730function InputMessage(event) {
3731 var stuff = document.body.innerHTML;
3732
3733 user = stuff.split("<b>To:</b> ");
3734 user = user[1].split("</th>");
3735 Username = user[0]
3736
3737 var pm = GM_getValue("MessageAutoFill").replace("%name%",Username);
3738
3739 document.getElementsByTagName('textarea')[0].value=pm;
3740
3741}
3742
3743function SetMessage(event)
3744{
3745 addCSS("#_xxmd_prefs {position:fixed; left:20%; right:20; bottom:100; top:auto; width:70%; color:#ffffff; font: 11px Verdana; border-top:1px #888888 solid; background:#000000;}",
3746 "#_xxmd_prefs .main { text-align: left;padding:5px 0 0.4em 0; width:800px; margin: auto;}",
3747 "#_xxmd_prefs input[type=submit] {font: normal 11px sans-serif; border: 1px solid #0080cc; color: #333; cursor: pointer; background: #FFF;}",
3748 "#_md_prefs input[x ]{background: #CCC;}",
3749 "#_xxmd_prefs input[type=text] { width: 50px; }",
3750 ".label { widtH: 125px; float: left; }",
3751 ".input { width: 51px; float:right; }");
3752
3753 var prefs = document.createElement("div");
3754 prefs.id = "_xxmd_prefs";
3755 prefs.innerHTML = '<center>%name% to replace username.<textarea name="message" rows="10" cols="130">' + GM_getValue("MessageAutoFill") + '</textarea><div align="center" id="SaveMessage">Save Message</div></centre>';
3756 document.body.appendChild(prefs);
3757
3758 document.addEventListener('click', function(event) {
3759
3760 if(event.target.id == "SaveMessage"){
3761 var messagex = document.getElementsByTagName('textarea')[1].value;
3762 GM_setValue('MessageAutoFill', messagex);
3763
3764 var prefs = document.getElementById("_xxmd_prefs");
3765 if(prefs) prefs.style.display="none";
3766 }
3767
3768 }, true);
3769
3770}
3771
3772function ConvertTime(oldtime)
3773{
3774 var dt = new Date();
3775 var unixtime = Math.max((Date.parse(dt))/1000);
3776 var diff = Math.max(unixtime - oldtime);
3777 var strTime = "";
3778
3779 if (diff > 86400) {
3780 var d = Math.max(Math.floor(diff / 86400));
3781 diff = Math.max(diff - Math.max(d * 86400));
3782 strTime = strTime + d + " days, ";
3783 }
3784
3785 if (diff > 3600) {
3786 var h = Math.max(Math.floor(diff / 3600));
3787 diff = Math.max(diff - Math.max(h * 3600));
3788 strTime = strTime + h + " hours, ";
3789
3790 }
3791
3792 if (diff > 60) {
3793 var m = Math.max(Math.floor(diff / 60));
3794 diff = Math.max(diff - Math.max(m * 60));
3795 strTime = strTime + m + " minutes, ";
3796 }
3797
3798 strTime = strTime + diff + " seconds ago";
3799
3800 return strTime;
3801}
3802
3803function ConvertTimeSimple(date)
3804{
3805 var seconds = Math.floor(((new Date().getTime()/1000) - date)),
3806 interval = Math.floor(seconds / 31536000);
3807
3808 if (interval >= 1) return interval + " years";
3809
3810 interval = Math.floor(seconds / 2592000);
3811 if (interval >= 1) return interval + " months";
3812
3813 interval = Math.floor(seconds / 86400);
3814 if (interval >= 1) if(interval == 1) {return interval + " day"}else{ return interval + " days"};
3815
3816 interval = Math.floor(seconds / 3600);
3817 if (interval >= 1) return interval + " hours";
3818
3819 interval = Math.floor(seconds / 60);
3820 if (interval >= 1) return interval + " minutes";
3821
3822 return Math.floor(seconds) + " seconds";
3823
3824}
3825
3826function DisplayMessage(message)
3827{
3828 var gm_button=document.createElement('div');
3829 gm_button.setAttribute('name','gm-button');
3830 gm_button.setAttribute('id','gm-button');
3831 gm_button.setAttribute('style','position:fixed;bottom:10px;right:10px;background-color:#000000;border: 1px solid rgb(102, 102, 102);padding:5px;text-align:center;');
3832 var gm_paragraph=document.createElement('p');
3833 gm_paragraph.setAttribute('id','GM_Message');
3834 gm_paragraph.setAttribute('style','font:normal normal normal 12px Arial,Helvetica,sans-serif;color:#ffffff;text-decoration:none;margin:0;padding:0;');
3835 gm_paragraph.innerHTML = message;
3836
3837 var gm_span_1=document.createElement('span');
3838 gm_span_1.setAttribute('id','gm-span-1');
3839 gm_span_1.setAttribute('style','cursor:pointer;');
3840
3841 document.getElementsByTagName('body')[0].appendChild(gm_button);
3842 gm_button.appendChild(gm_paragraph);
3843 gm_paragraph.appendChild(gm_span_1);
3844}
3845
3846
3847function DisplayMessage2(message)
3848{
3849 var gm_button = document.getElementById("GM_Message2");
3850 if(gm_button){
3851 gm_button.innerHTML = message;
3852 }else{
3853 var gm_button=document.createElement('div');
3854 gm_button.setAttribute('name','gm-button');
3855 gm_button.setAttribute('id','gm-button');
3856 gm_button.setAttribute('style','position:fixed;top:10px;right:10px;background-color:#000000;border: 1px solid rgb(102, 102, 102);padding:5px;text-align:center;');
3857 var gm_paragraph=document.createElement('p');
3858 gm_paragraph.setAttribute('id','GM_Message');
3859 gm_paragraph.setAttribute('style','font:normal normal normal 12px Arial,Helvetica,sans-serif;color:#ffffff;text-decoration:none;margin:0;padding:0;');
3860 gm_paragraph.innerHTML = message;
3861
3862 var gm_span_1=document.createElement('span');
3863 gm_span_1.setAttribute('id','gm-span-1');
3864 gm_span_1.setAttribute('style','cursor:pointer;');
3865
3866 document.getElementsByTagName('body')[0].appendChild(gm_button);
3867 gm_button.appendChild(gm_paragraph);
3868 gm_paragraph.appendChild(gm_span_1);
3869 }
3870}
3871
3872
3873function MakeRequest(url)
3874{
3875 GM_xmlhttpRequest({
3876 method: 'GET',
3877 url: GM_getValue("serverURL") + '\n' + url,
3878 onload: function(responseDetails) {
3879 DisplayMessage("Data Collected");
3880 },
3881 onerror: function(responseDetails) {
3882 // alert("Request for contact resulted in error code: " + responseDetails.status);
3883 }
3884 });
3885}
3886
3887
3888function FindText(str, str1, str2)
3889{
3890 var pos1 = str.indexOf(str1);
3891 if (pos1 == -1) return '';
3892
3893 pos1 += str1.length;
3894
3895 var pos2 = str.indexOf(str2, pos1);
3896 if (pos2 == -1) return '';
3897
3898 return str.substring(pos1, pos2);
3899}
3900
3901
3902function ReturnRequest(url,msg,cb)
3903{
3904 GM_xmlhttpRequest({
3905 method: 'GET',
3906 url: DF_server + url,
3907 onload: function(responseDetails) {
3908 cb(responseDetails.responseText);
3909 },
3910 });
3911}
3912
3913function SortIt(TheArr,u,v,w,x,y,z){
3914
3915 TheArr.sort(Sorter);
3916
3917 function Sorter(a,b){
3918 var swap=0;
3919 if (isNaN(a[u]-b[u])){
3920 if((isNaN(a[u]))&&(isNaN(b[u]))){swap=(b[u]<a[u])-(a[u]<b[u]);}
3921 else {swap=(isNaN(a[u])?1:-1);}
3922 }
3923 else {swap=(a[u]-b[u]);}
3924 if((v==undefined)||(swap!=0)){return swap;}
3925 else{
3926 if (isNaN(a[v]-b[v])){
3927 if((isNaN(a[v]))&&(isNaN(b[v]))){swap=(b[v]<a[v])-(a[v]<b[v]);}
3928 else {swap=(isNaN(a[v])?1:-1);}
3929 }
3930 else {swap=(a[v]-b[v]);}
3931 }
3932 if((w==undefined)||(swap!=0)){return swap;}
3933 else{
3934 if (isNaN(a[w]-b[w])){
3935 if((isNaN(a[w]))&&(isNaN(b[w]))){swap=(b[w]<a[w])-(a[w]<b[w]);}
3936 else {swap=(isNaN(a[w])?1:-1);}
3937 }
3938 else {swap=(a[w]-b[w]);}
3939 }
3940 if((x==undefined)||(swap!=0)){return swap;}
3941 else{
3942 if (isNaN(a[x]-b[x])){
3943 if((isNaN(a[x]))&&(isNaN(b[x]))){swap=(b[x]<a[x])-(a[x]<b[x]);}
3944 else {swap=(isNaN(a[x])?1:-1);}
3945 }
3946 else {swap=(a[x]-b[x]);}
3947 }
3948 if((y==undefined)||(swap!=0)){return swap;}
3949 else{
3950 if (isNaN(a[y]-b[y])){
3951 if((isNaN(a[y]))&&(isNaN(b[y]))){swap=(b[y]<a[y])-(a[y]<b[y]);}
3952 else {swap=(isNaN(a[y])?1:-1);}
3953 }
3954 else {swap=(a[y]-b[y]);}
3955 }
3956 if((z==undefined)||(swap!=0)){return swap;}
3957 else{
3958 if (isNaN(a[z]-b[z])){
3959 if((isNaN(a[z]))&&(isNaN(b[z]))){swap=(b[z]<a[z])-(a[z]<b[z]);}
3960 else {swap=(isNaN(a[z])?1:-1);}
3961 }
3962 else {swap=(a[z]-b[z]);}
3963 }
3964 return swap;
3965 }
3966}
3967
3968function addCommas( sValue ) //addCommas function wrote by Lukas Brueckner
3969{
3970 sValue = String(sValue);
3971 var sRegExp = new RegExp('(-?[0-9]+)([0-9]{3})');
3972
3973 while(sRegExp.test(sValue)) {
3974 sValue = sValue.replace(sRegExp, '$1,$2');
3975 }
3976 return sValue;
3977}
3978
3979function ReturnRequest1(url,msg,cb)
3980{
3981 GM_xmlhttpRequest({
3982 method: 'GET',
3983 url: GM_getValue("serverURL") + '\n' + url,
3984 headers: {'User-agent': 'Mozilla/1.0 (compatible)', },
3985 onload: function(responseDetails) {
3986 cb(responseDetails.responseText);
3987 if(msg == 1) { DisplayMessage("Data Collected"); }
3988 },
3989 onerror: function(responseDetails) {
3990 // alert("Request for contact resulted in error code: " + responseDetails.status);
3991 }
3992 });
3993}
3994
3995function addCSS(css){
3996 GM_addStyle(css);
3997}
3998
3999function IsNumeric(sText)
4000{
4001 var ValidChars = "0123456789.";
4002 var IsNumber=true;
4003 var Char;
4004
4005 for (i = 0; i < sText.length && IsNumber == true; i++)
4006 {
4007 Char = sText.charAt(i);
4008 if (ValidChars.indexOf(Char) == -1)
4009 {
4010 IsNumber = false;
4011 }
4012 }
4013 return IsNumber;
4014}
4015
4016function InStr(strSearch, strFind)
4017{
4018 strSearch = String(strSearch);
4019 strFind = String(strFind);
4020 return (strSearch.indexOf(strFind) >= 0);
4021}
4022
4023function Get_Cookie( check_name ) {
4024 // first we'll split this cookie up into name/value pairs
4025 // note: document.cookie only returns name=value, not the other components
4026 var a_all_cookies = document.cookie.split( ';' );
4027 var a_temp_cookie = '';
4028 var cookie_name = '';
4029 var cookie_value = '';
4030 var b_cookie_found = false; // set boolean t/f default f
4031
4032 for ( i = 0; i < a_all_cookies.length; i++ )
4033 {
4034 // now we'll split apart each name=value pair
4035 a_temp_cookie = a_all_cookies[i].split( '=' );
4036 // and trim left/right whitespace while we're at it
4037 cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');
4038 // if the extracted name matches passed check_name
4039 if ( cookie_name == check_name )
4040 {
4041 b_cookie_found = true;
4042 // we need to handle case where cookie has no value but exists (no = sign, that is):
4043 if ( a_temp_cookie.length > 1 )
4044 {
4045 cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
4046 }
4047 // note that in cases where cookie is initialized but no value, null is returned
4048 return cookie_value;
4049 break;
4050 }
4051 a_temp_cookie = null;
4052 cookie_name = '';
4053 }
4054 if ( !b_cookie_found )
4055 {
4056 return null;
4057 }
4058}
4059
4060function SiegeList(m) // Returns: Multiply | Next Upgrade | Next Price | Next Multiply
4061{
4062 switch(m)
4063 {
4064 case 'None': { return '1|Flaming Arrows|40,000|1.3'; break }
4065 case 'Flaming Arrows': { return '1.3|Ballistas|80,000|1.69'; break }
4066 case 'Ballistas': { return '1.69|Battering Ram|160,000|2.197'; break }
4067 case 'Battering Ram': { return '2.197|Ladders|320,000|2.85'; break }
4068 case 'Ladders': { return '2.85|Trojan Horse|640,000|3.71'; break }
4069 case 'Trojan Horse': { return '3.71|Catapults|1,280,000|4.82'; break }
4070 case 'Catapults': { return '4.82|War Elephants|2,560,000|6.27'; break }
4071 case 'War Elephants': { return '6.27|Siege Towers|5,120,000|8.15'; break }
4072 case 'Siege Towers': { return '8.15|Trebuchets|10,240,000|10.60'; break }
4073 case 'Trebuchets': { return '10.60|Black Powder|20,480,000|13.78'; break }
4074 case 'Black Powder': { return '13.78|Sappers|40,960,000|17.92'; break }
4075 case 'Sappers': { return '17.92|Dynamite|81,920,000|23.29'; break }
4076 case 'Dynamite': { return '23.29|Greek Fire|163,840,000|30.28'; break }
4077 case 'Greek Fire': { return '30.28|Cannons|327,680,000|39.37'; break }
4078 case 'Cannons': { return '39.37|Max|Max|Max'; break }
4079 default: { return 'Max|Max|Max|Max'; break }
4080 }
4081}
4082
4083function FortList(m) // Returns: Multiply | Next Upgrade | Next Price | Next Multiply
4084{
4085 switch(m)
4086 {
4087 case 'Camp': { return '1|Stockade|40,000|1.25'; break }
4088 case 'Stockade': { return '1.25|Rabid Pitbulls|80,000|1.563'; break }
4089 case 'Rabid Pitbulls': { return '1.563|Walled Town|160,000|1.953'; break }
4090 case 'Walled Town': { return '1.953|Towers|320,000|2.441'; break }
4091 case 'Towers': { return '2.441|Battlements|640,000|3.052'; break }
4092 case 'Battlements': { return '3.052|Portcullis|1,280,000|3.815'; break }
4093 case 'Portcullis': { return '3.815|Boiling Oil|2,560,000|4.768'; break }
4094 case 'Boiling Oil': { return '4.768|Trenches|5,120,000|5.960'; break }
4095 case 'Trenches': { return '5.960|Moat|10,240,000|7.451'; break }
4096 case 'Moat': { return '7.451|Drawbridge|20,480,000|9.313'; break }
4097 case 'Drawbridge': { return '9.313|Fortress|40,960,000|11.642'; break }
4098 case 'Fortress': { return '11.642|Stronghold|81,920,000|14.552'; break }
4099 case 'Stronghold': { return '14.552|Palace|163,840,000|18.190'; break }
4100 case 'Palace': { return '18.190|Keep|327,680,000|22.737'; break }
4101 case 'Keep': { return '22.737|Citadel|655,360,000|28.422'; break }
4102 case 'Citadel': { return '28.422|Hand of God|1,310,720,000|35.527'; break }
4103 case 'Hand of God': { return '35.527|Max|Max|Max'; break }
4104 default: { return 'Max|Max|Max|Max'; break }
4105 }
4106}
4107
4108function GetStrength(weapon)
4109{
4110 switch(weapon)
4111 {
4112 case 'Nunchaku':
4113 case 'Lookout Tower':
4114 return 1000;
4115 break;
4116 case 'Skeleton Key':
4117 return 600;
4118 break;
4119 case 'Grappling Hook':
4120 case 'Guard Dog':
4121 return 250;
4122 break;
4123 default:
4124 return 0;
4125 break;
4126 }
4127}
4128
4129
4130function removeComma(num) {
4131 return num.replace(/,/g, "");
4132}