· 8 years ago · Jan 24, 2018, 12:34 AM
1Ted's Market UI
2(script starts after this line)
3
4// ==UserScript==
5// @name Ted's market UI
6// @namespace Ted's market UI
7// @version 1.360
8// @description Ted's Diamond Hunt 2 custom market user interface
9// @author ted120
10// @match http://*.diamondhunt.co/
11// @match https://*.diamondhunt.co/
12// @match https://*.diamondhunt.co/index.php
13// @match https://*.diamondhunt.co/index.php
14// @require https://cdn.rawgit.com/goldfire/pokersolver/7611b7b89b0ee7f4fb7b07e64b65f727f428de37/pokersolver.js
15// @run-at document-idle
16// @grant none
17// ==/UserScript==
18var updateNews = "Fixed market table. Sorry for delayed update, was away for 3 days.<br><br>";
19$(document).ready(function() {
20 // nothing needs to be changed in code
21 /* TODO
22
23 improve minigames
24
25 MANY THANKS:
26
27 dersat
28
29 florb
30
31 John
32
33 flipskiz
34
35 */
36 //thanks florb
37 var currentVersion = String(GM_info.script.version),
38 versionHistoryString = "";
39 $.get("https://greasyfork.org/en/scripts/28422-ted-s-market-ui/versions", function(data) {
40 try {
41 const FIRST_SEARCH_STRING = 'input type="submit" value="Diff selected versions" data-disable-with="Diff selected versions';
42 const UL_START_STRING = '<ul>';
43 const UL_END_STRING = '</ul>';
44 let html = data;
45 // cut away up to first search string
46 html = html.substring(html.indexOf(FIRST_SEARCH_STRING) + FIRST_SEARCH_STRING.length);
47 // find UL start and end
48 html = html.substring(html.indexOf(UL_START_STRING), html.indexOf(UL_END_STRING) + UL_END_STRING.length);
49 let parser = new DOMParser();
50 let doc = parser.parseFromString(html, "text/html");
51 let lis = doc.getElementsByTagName("li");
52 if (lis.length === 0) return;
53 var expectedVersion = null;
54 for (let i = 0; i < lis.length; i++) {
55 let li = lis[i];
56 let version = li.getElementsByTagName("a")[0].innerHTML.replace(/v/g, "");
57 let versionText = li.lastChild.textContent.trim();
58 if (i === 0) {
59 expectedVersion = version;
60 }
61 if (version == currentVersion) {
62 break;
63 }
64 versionHistoryString += version + " " + versionText + "\n";
65 }
66 if (expectedVersion === null) {
67 console.log("Could not read expected version, skipping update check");
68 } else if (parseInt(currentVersion.replace(/\./g, '')) < parseInt(expectedVersion.replace(/\./g, ''))) {
69 if (window.confirm("Ted's Market Script\n\nOutdated Version:\n" + currentVersion + " current\n" + expectedVersion + " expected\n\nOK: Open the script page to manually update\nCancel: Proceed with outdated version\n\nWhat's new?\n\n" + versionHistoryString)) {
70 window.location.href = "https://greasyfork.org/en/scripts/28422-ted-s-market-ui";
71 }
72 }
73 } catch (err) {
74 console.log("Error checking for new updates:\n\n" + err);
75 }
76 });
77 let thisTick = playtime;
78
79 function waitForFirstTick() {
80 if (thisTick == playtime) {
81 setTimeout(function() {
82 waitForFirstTick();
83 }, 100);
84 } else {
85 tedsMarketScript();
86 }
87 }
88 waitForFirstTick();
89
90 function tedsMarketScript() {
91 var debugToConsole = false;
92 if (typeof(jsTradableItems) == "undefined") {
93 jsTradableItems = jsTradalbeItems;
94 }
95 let itemList = {};
96 for (let key in (jsTradableItems)) {
97 itemList[key] = {
98 keepAmount: 0,
99 showAtPrice: null,
100 alwaysShowLowest: true,
101 showAtMin: false
102 };
103 }
104 const defaultSettings = { // thanks WhoIsYou
105 notEnoughCoinsOpacity: {
106 text: "Display unaffordable market items as transparent?",
107 value: true
108 },
109 showMaxCanBuy: {
110 text: "Display maximum quantity purchasable when cannot afford to buy all?",
111 value: true
112 },
113 showTotalPrice: {
114 text: "Display total price if buying maximum?",
115 value: true
116 },
117 smallMarketImages: {
118 text: "Resize market images smaller?",
119 value: true
120 },
121 itemTooltips: {
122 text: "Display item tooltips? (shows after searching market for all items)",
123 value: true
124 },
125 autoUndercut: {
126 text: "Smart autofill price to undercut when posting an item?",
127 value: true
128 },
129 marketSlotsCustomUi: {
130 text: "[FORCED ON] Display custom market box? (refresh all, price history graph, stargem calc, etc)",
131 value: true
132 },
133 colorMinPrice: {
134 text: "Background color of min priced items",
135 bgcolor: "#90ee90", //lightgreen
136 },
137 colorNextLowestToMinPrice: {
138 text: "Background color of next lowest offer to min priced items",
139 bgcolor: "#ffcc66", //lightorange
140 },
141 showSingleItems: {
142 text: "Show single items on the market?",
143 value: false,
144 },
145 colorSingleItems: {
146 text: "Background color of single items",
147 bgcolor: "#ffff66", //lightyellow
148 },
149 colorMyListedLowest: {
150 text: "Background color of your listed item at lowest price",
151 bgcolor: "#bffffd", //lightblue
152 },
153 colorMyListedLowestCanRaisePrice: {
154 text: "Background color of next lowest offer to your lowest listed item",
155 bgcolor: "#6ffffd", //blue
156 },
157 colorMyListedNotLowest: {
158 text: "Background color of your listed item not at lowest price",
159 bgcolor: "#ffcccc", //lighterred
160 },
161 colorLowestForMyListed: {
162 text: "Background color of lowest offer for an item you have listed",
163 bgcolor: "#ff7878", //lightred
164 },
165 colorMyItemList: {
166 text: "Background color of items that match myItemList",
167 bgcolor: "#ff99ff", //lightpink
168 },
169 colorMyItemListNextLowest: {
170 text: "Background color of next lowest offer when an item matches myItemList",
171 bgcolor: "#f2f2f2", //lightgrey
172 },
173 colorAlwaysShowLowest: {
174 text: "Background color of alwaysShowLowest items",
175 bgcolor: "#d2d2d2", //grey
176 },
177 tedTradableItems: {
178 itemList,
179 },
180 tradeHistory: [],
181 sendMarketData: {
182 text: "Allow market data to be sent to the script developer? (When you click infinity symbol the following data is sent at a max of once every 3 mins: All items listed on market when you searched ALL, your username)",
183 value: true,
184 alert: true,
185 },
186 useKeepAmount: {
187 text: "Remember amount not to sell when posting an item?",
188 value: true
189 },
190 useUndercutBox: {
191 text: "Display undercut box when posting an item?",
192 value: true
193 },
194 showCheapestHeat: {
195 text: "Display cheapest heat item on market table?",
196 value: true,
197 showAt: 999999
198 },
199 showCheapestEnergy: {
200 text: "Display cheapest energy item on market table?",
201 value: true,
202 showAt: 999999
203 },
204 showCheapestBonemeal: {
205 text: "Display cheapest bonemeal item on market table?",
206 value: true,
207 showAt: 999999
208 },
209 stardustProfitGreenBox: {
210 text: "Show green box when Stardust Potion is profitable?",
211 value: false
212 },
213 superStardustProfitGreenBox: {
214 text: "Show green box when Super Stardust Potion is profitable?",
215 value: true
216 },
217 stargemProfitGreenBox: {
218 text: "Show green box when Stargem Potion is profitable?",
219 value: true
220 },
221 essenceProfitGreenBox: {
222 text: "Show green box when Essence Potion is profitable?",
223 value: true
224 },
225 superEssenceProfitGreenBox: {
226 text: "Show green box when Super Essence Potion is profitable?",
227 value: true
228 },
229 brewingPlaceholder: {
230 text: "Show max potions brewable as placeholder text?",
231 value: true
232 },
233 craftingVialPlaceholder: {
234 text: "Show max vials craftable as placeholder text?",
235 value: true
236 },
237 displayNotificationTreasureMap: {
238 text: "Show notification when a treasure map is found?",
239 value: true
240 },
241 poker: {
242 availableBalance: 0,
243 promotions: {
244 jackpotPool: 0,
245 bbj: {
246 previousWinner: null,
247 previousAmount: 123456789,
248 previousTime: 0,
249 },
250 hhj: {
251 highHand: [],
252 },
253 },
254 },
255 };
256
257 function itemNameFix(string) { // market style name to var style name; Bat Skin > batSkin
258 var a = string.replace(/\s/g, "");
259 return a.charAt(0).toLowerCase() + a.slice(1);
260 }
261 if (typeof(localStorage.tedSettings) == "undefined") {
262 localStorage.tedSettings = JSON.stringify(defaultSettings);
263 console.log("localstorage.tedSettings not found, creating based on defaultSettings");
264 console.log(localStorage.tedSettings);
265 }
266 var tedStoredSettings = JSON.parse(localStorage.getItem("tedSettings"));
267 for (var key in defaultSettings) {
268 if (!defaultSettings.hasOwnProperty(key)) continue;
269 if (tedStoredSettings[key] === undefined) {
270 //add from default
271 console.log("undefined " + key);
272 tedStoredSettings[key] = defaultSettings[key];
273 localStorage.tedSettings = JSON.stringify(tedStoredSettings);
274 console.log("Key not found, added from default: tedStoredSettings." + key);
275 if (key == "tedTradableItems") {
276 console.log("importing old data to tedTradableItems");
277 if (tedStoredSettings.tradableItemsKeepAmount) {
278 for (let i = 0; i < Object.keys(tedStoredSettings.tradableItemsKeepAmount.itemList).length; i++) {
279 tedStoredSettings.tedTradableItems.itemList[Object.keys(tedStoredSettings.tradableItemsKeepAmount.itemList)[i]].keepAmount = tedStoredSettings.tradableItemsKeepAmount.itemList[Object.keys(tedStoredSettings.tradableItemsKeepAmount.itemList)[i]];
280 }
281 delete tedStoredSettings.tradableItemsKeepAmount;
282 console.log("imported and deleted tedStoredSettings.tradableItemsKeepAmount");
283 }
284 if (tedStoredSettings.myItemList) {
285 for (let i = 0; i < tedStoredSettings.myItemList.length; i++) {
286 let itemName = itemNameFix(tedStoredSettings.myItemList[i][0]);
287 let myPrice = tedStoredSettings.myItemList[i][1];
288 tedStoredSettings.tedTradableItems.itemList[itemName].showAtPrice = myPrice;
289 }
290 delete tedStoredSettings.myItemList;
291 console.log("imported and deleted tedStoredSettings.myItemList");
292 }
293 if (tedStoredSettings.hideItemList) {
294 /*for (let i = 0; i < tedStoredSettings.hideItemList.length; i++) {
295 let itemName = itemNameFix(tedStoredSettings.hideItemList[i]);
296 tedStoredSettings.tedTradableItems.itemList[itemName].hideItem = true;
297 }*/
298 delete tedStoredSettings.hideItemList;
299 console.log("deleted tedStoredSettings.hideItemList");
300 }
301 }
302 } else if (debugToConsole) {
303 console.log("matched " + key);
304 }
305 for (var prop in defaultSettings[key]) {
306 if (tedStoredSettings[key].hasOwnProperty(prop)) continue;
307 console.log("tedStoredSettings." + key + "." + prop + " not found; adding from defaultSettings." + key + "." + prop);
308 tedStoredSettings[key][prop] = defaultSettings[key][prop];
309 }
310 if (tedStoredSettings[key].text && tedStoredSettings[key].text != defaultSettings[key].text) {
311 tedStoredSettings[key].text = defaultSettings[key].text;
312 localStorage.tedSettings = JSON.stringify(tedStoredSettings);
313 }
314 if (key == "tedTradableItems") { // check that tradableItems contains all tradable items
315 for (let i = 0; i < Object.keys(jsTradableItems).length; i++) {
316 if (typeof(tedStoredSettings.tedTradableItems.itemList[Object.keys(jsTradableItems)[i]]) === "undefined") {
317 tedStoredSettings.tedTradableItems.itemList[Object.keys(jsTradableItems)[i]] = {
318 keepAmount: 0,
319 showAtPrice: null,
320 alwaysShowLowest: true,
321 showAtMin: false
322 };
323 } else if (tedStoredSettings.tedTradableItems.itemList[Object.keys(jsTradableItems)[i]].tradeHistory) {
324 delete tedStoredSettings.tedTradableItems.itemList[Object.keys(jsTradableItems)[i]].tradeHistory;
325 }
326 }
327 }
328 if (key == "tradeHistory") {
329 // check that tradeHistory objects have "total" property
330 if (tedStoredSettings.tradeHistory && tedStoredSettings.tradeHistory[0]) {
331 if (!tedStoredSettings.tradeHistory[0].total) {
332 for (let i = 0; i < tedStoredSettings.tradeHistory.length; i++) {
333 if (typeof(tedStoredSettings.tradeHistory[i].total) == "undefined") {
334 tedStoredSettings.tradeHistory[i].total = (tedStoredSettings.tradeHistory[i].price * tedStoredSettings.tradeHistory[i].amount);
335 }
336 }
337 }
338 }
339 }
340 }
341 var notEnoughCoinsOpacity, showMaxCanBuy, showTotalPrice;
342 var smallMarketImages, marketImageSize = 30; //pixels, default:50, suggested: 30-40
343 var itemTooltips;
344 var autoUndercut, undercutBy = 2,
345 matchLowestPriceAt = 20;
346 var marketSlotsCustomUi;
347 var colorMinPrice, colorNextLowestToMinPrice, showSingleItems, colorSingleItems, colorMyListedLowest, colorMyListedLowestCanRaisePrice, colorMyListedNotLowest, colorLowestForMyListed, colorMyItemList, colorMyItemListNextLowest, colorAlwaysShowLowest;
348 var refreshMarketAfterBuyingItem_itemName;
349 var sendMarketData, sendMarketDataWaitTimeMins = 3 * 60 * 1000;
350 var useKeepAmount, useUndercutBox;
351 var showCheapestHeat, showCheapestEnergy, showCheapestBonemeal;
352 var stardustProfitGreenBox, superStardustProfitGreenBox, stargemProfitGreenBox, essenceProfitGreenBox, superEssenceProfitGreenBox;
353 var brewingPlaceholder, craftingVialPlaceholder;
354 var displayNotificationTreasureMap;
355 var minigamesPokerAvailableBalance;
356
357 function updateVariables() {
358 localStorage.tedSettings = JSON.stringify(tedStoredSettings);
359 notEnoughCoinsOpacity = tedStoredSettings.notEnoughCoinsOpacity.value;
360 showMaxCanBuy = tedStoredSettings.showMaxCanBuy.value;
361 showTotalPrice = tedStoredSettings.showTotalPrice.value;
362 smallMarketImages = tedStoredSettings.smallMarketImages.value;
363 marketImageSize = 30; //pixels, default:50, suggested: 30-40
364 itemTooltips = tedStoredSettings.itemTooltips.value;
365 autoUndercut = tedStoredSettings.autoUndercut.value;
366 marketSlotsCustomUi = true; //tedStoredSettings.marketSlotsCustomUi.value;
367 undercutBy = 2;
368 matchLowestPriceAt = 20;
369 colorMinPrice = tedStoredSettings.colorMinPrice.bgcolor;
370 colorNextLowestToMinPrice = tedStoredSettings.colorNextLowestToMinPrice.bgcolor;
371 showSingleItems = tedStoredSettings.showSingleItems.value;
372 colorSingleItems = tedStoredSettings.colorSingleItems.bgcolor;
373 colorMyListedLowest = tedStoredSettings.colorMyListedLowest.bgcolor;
374 colorMyListedLowestCanRaisePrice = tedStoredSettings.colorMyListedLowestCanRaisePrice.bgcolor;
375 colorMyListedNotLowest = tedStoredSettings.colorMyListedNotLowest.bgcolor;
376 colorLowestForMyListed = tedStoredSettings.colorLowestForMyListed.bgcolor;
377 colorMyItemList = tedStoredSettings.colorMyItemList.bgcolor;
378 colorMyItemListNextLowest = tedStoredSettings.colorMyItemListNextLowest.bgcolor;
379 colorAlwaysShowLowest = tedStoredSettings.colorAlwaysShowLowest.bgcolor;
380 sendMarketData = tedStoredSettings.sendMarketData.value;
381 useKeepAmount = tedStoredSettings.useKeepAmount.value;
382 useUndercutBox = tedStoredSettings.useUndercutBox.value;
383 showCheapestHeat = tedStoredSettings.showCheapestHeat.value;
384 showCheapestEnergy = tedStoredSettings.showCheapestEnergy.value;
385 showCheapestBonemeal = tedStoredSettings.showCheapestBonemeal.value;
386 stardustProfitGreenBox = tedStoredSettings.stardustProfitGreenBox.value;
387 superStardustProfitGreenBox = tedStoredSettings.superStardustProfitGreenBox.value;
388 stargemProfitGreenBox = tedStoredSettings.stargemProfitGreenBox.value;
389 essenceProfitGreenBox = tedStoredSettings.essenceProfitGreenBox.value;
390 superEssenceProfitGreenBox = tedStoredSettings.superEssenceProfitGreenBox.value;
391 brewingPlaceholder = tedStoredSettings.brewingPlaceholder.value;
392 if (!brewingPlaceholder) document.getElementById("dialogue-brewing-input").removeAttribute("placeholder");
393 craftingVialPlaceholder = tedStoredSettings.craftingVialPlaceholder.value;
394 if (!craftingVialPlaceholder) document.getElementById("dialogue-multicraft-input").removeAttribute("placeholder");
395 displayNotificationTreasureMap = tedStoredSettings.displayNotificationTreasureMap.value;
396 minigamesPokerAvailableBalance = tedStoredSettings.poker.availableBalance;
397 }
398 updateVariables();
399 if (tedStoredSettings.sendMarketData.alert === true) {
400 //alert("Ted's Market Script: One time alert: " + tedStoredSettings.sendMarketData.text + " currently set to: " + tedStoredSettings.sendMarketData.value + ". This data will be used to create price history graphs and other cool things. If you don't want to be involved you can disable this in Profile & Settings. If you have any questions /pm ted120");
401 tedStoredSettings.sendMarketData.alert = false;
402 updateVariables();
403 }
404 var arrMarketItems = {};
405
406 function marketTableLength() {
407 return document.getElementById("market-table").rows.length;
408 }
409 var arrMarketSlots = []; //updateMarketSlots
410 for (let msi = 1; 1 == 1; msi++) {
411 if (document.getElementById("market-slot-" + msi)) {
412 arrMarketSlots.push([0, 0]);
413 } else break;
414 }
415 var marketInterval;
416 var marketOn = true;
417 var cpi_itemName = "";
418 var tickStart = new Date().getTime();
419 var tickEnd = new Date().getTime();
420 var tickTime = tickEnd - tickStart;
421 var tickCheck = 0;
422 var sendToSpreadsheet_timeoutStart = new Date().getTime(),
423 sendToSpreadsheet_timeout = 0;
424 var myItemListAddName, myItemListAddPrice;
425 var undercutBoxText = document.createElement("span");
426 var keepAmountText = document.createElement("span");
427 var ms_collect_repeat = [true, true, true],
428 ph_brewing_repeat = true,
429 ph_brewing_cur_potion = "",
430 ph_vial_repeat = true,
431 ph_vial_cur_vial = "";
432 var quickCalcStargemBoxShadow, quickCalcSuperStardustBoxShadow, quickCalcStardustBoxShadow, quickCalcEssenceBoxShadow, quickCalcSuperEssenceBoxShadow, quickCalcTooltip = document.createElement("div");
433 var quickCalcStargemString = "",
434 quickCalcSuperStardustString = "",
435 quickCalcStardustString = "",
436 quickCalcEssenceString = "",
437 quickCalcSuperEssenceString = "";
438 var searchAllDelay = 2500;
439 var lastBrowsedItem = "Stardust";
440 var oreAverageOn = false,
441 minigamesOn = false,
442 minigameMyTurn = false,
443 minigameMyStatus = "free",
444 minigameMyPlayer,
445 minigameOppPlayer,
446 minigameOpp,
447 minigameGame,
448 minigameVersion,
449 minigameSeed,
450 minigameQuitReason,
451 pokerServerUsername = "tmg",
452 minigameCurrentSelectedGame = "Grid Control",
453 minigameConnectedToPokerServer = false,
454 minigameTryingToConnectToPokerServer = false,
455 minigameLastMessageFromPokerServer = -1,
456 minigamePokerServerStatus = "unknown",
457 minigamePokerMyTable,
458 minigamePokerMySeat,
459 minigamePokerMyBuyin,
460 gc_lastClicked,
461 lastHover,
462 browserMouseX = 0,
463 browserMouseY = 0,
464 pingTimeStart = 0,
465 pingTime = 0,
466 pingSent = false,
467 tmg_pokerServerPingSent = false,
468 tmg_pokerServerTimeoutVar,
469 windLastCheck = -1,
470 notifyWindChange = true,
471 allowedBrowserNotifications = false,
472 minigameManager = {
473 challenges: [],
474 },
475 oreAverageElement = document.createElement("div"),
476 minigamesElement = document.createElement("div"),
477 currentOreReset = true;
478 var oreAverageStartTicks = playtime;
479 var oreAverageElapsedTicks;
480 var allOres = [
481 ["stone", 1],
482 ["copper", 2],
483 ["tin", 2],
484 ["iron", 5],
485 ["silver", 10],
486 ["gold", 20],
487 ["quartz", 30],
488 ["marble", 100],
489 ["promethium", 1000],
490 ["runite", 5000]
491 ];
492 var minedOres = {};
493 for (let i = 0; i < allOres.length; i++) {
494 minedOres[allOres[i][0]] = {
495 currentAmount: 0,
496 price: allOres[i][1],
497 startAmount: window[allOres[i][0]],
498 oreTick: 0,
499 coinTick: 0,
500 oreDay: 0,
501 coinDay: 0,
502 };
503 }
504 var marketSlotSpareElement = document.createElement("div");
505 marketSlotSpareElement.setAttribute("style","margin-left:3px;margin-right:3px");
506 var oldDialogueConfirmYesOnclick = document.getElementById('dialogue-confirm-yes').getAttribute("onclick");
507 var th_object, th_status = "free",
508 thString = "";
509 var keepAmountChosenItem = "";
510 var cheapestHeat, cheapestEnergy, cheapestBonemeal;
511 var totalFlipProfit = 0;
512 var cpi_totalPrice;
513 var exactMatch = true,
514 searchString, exactSearch, searchVal = "";
515 var sortedTradeHistory = tedStoredSettings.tradeHistory,
516 sortByTH = "date",
517 thSortToggle = true;
518 var arrSortItemsList = [
519 "Stardust",
520 "Blood Diamond", "Diamond", "Ruby", "Emerald", "Sapphire",
521 "Empty Chisel",
522 "Green Rocket Orb", "Green Oil Factory Orb", "Green Oil Storage Orb", "Green Combat Orb", "Green Bow Orb", "Green Bonemeal Bin Orb", "Green Brewing Kit Orb",
523 "Blue Axe Orb", "Blue Chisel Orb", "Blue Fishing Rod Orb", "Blue Hammer Orb", "Blue Oil Pipe Orb", "Blue Pickaxe Orb", "Blue Rake Orb", "Blue Shovel Orb", "Blue Trowel Orb",
524 "Essence",
525 "Scythe", "Ghost Amulet",
526 "Bow", "Ice Arrows", "Fire Arrows", "Arrows",
527 "Skeleton Sword", "Skeleton Shield", "Bone Amulet",
528 "Iron Dagger", "Stinger",
529 "Promethium Helmet Mould", "Promethium Body Mould", "Promethium Legs Mould", "Promethium Gloves Mould", "Promethium Boots Mould",
530 "Essence Logs","Stardust Logs", "Maple Logs", "Willow Logs", "Oak Logs", "Logs",
531 "Moon Bones", "Ice Bones", "Bones", "Ashes",
532 "Essence Tree Seeds","Stardust Tree Seeds", "Maple Tree Seeds", "Willow Tree Seeds", "Oak Tree Seeds", "Tree Seeds",
533 "Striped Crystal Leaf Seeds", "Crystal Leaf Seeds", "Striped Gold Leaf Seeds", "Gold Leaf Seeds", "Blewit Mushroom Seeds", "Red Mushroom Seeds", "Lime Leaf Seeds", "Green Leaf Seeds", "Dotted Green Leaf Seeds", "Snapegrass Seeds",
534 "Striped Crystal Leaf", "Crystal Leaf", "Striped Gold Leaf", "Gold Leaf", "Blewit Mushroom", "Red Mushroom", "Stranger Leaf", "Strange Leaf", "Lime Leaf", "Green Leaf", "Dotted Green Leaf", "Snapegrass",
535 "Rainbowfish", "Whale", "Shark", "Eel", "Swordfish", "Lobster", "Tuna", "Salmon", "Sardine", "Shrimp",
536 "Fishing Bait","Raw Rainbowfish", "Raw Whale", "Raw Shark", "Raw Eel", "Raw Swordfish", "Raw Lobster", "Raw Tuna", "Raw Salmon", "Raw Sardine", "Raw Shrimp", "Wheat",
537 "Runite Bar", "Promethium Bar", "Gold Bar", "Silver Bar", "Iron Bar", "Bronze Bar",
538 "Runite", "Promethium", "Marble", "Quartz", "Glass", "Sand", "Stone",
539 "Bear Fur", "Bat Skin", "Snake Skin"
540 ];
541 window.pokerServerPlayersConnected = {};
542 window.minigamesObject = {
543 /*"Poker": {
544 tables: {
545 1: {
546 gameInfo: {
547 sb: 1,
548 bb: 2,
549 minBuyin: 100,
550 maxBuyin: 200,
551 minPlayers: 2,
552 maxPlayers: 6,
553 gameType: "Ten Plus",
554 },
555 seats: {
556 "testplayer1": {
557 name: "testplayer1",
558 seat: 3,
559 chips: 206,
560 chipsInPotThisStreet: 0,
561 status: "live",
562 },
563 "testaccount1": {
564 name: "testaccount1",
565 seat: 6,
566 chips: 194,
567 chipsInPotThisStreet: 3,
568 status: "folded",
569 },
570 },
571 currentHand: {
572 currentTurn: "ted120",
573 dealerButton: "ted120",
574 smallBlind: "testaccount1",
575 bigBlind: "test123",
576 flop: ["Ac","9d","7h"],
577 turn: ["8s"],
578 river: ["Ts"],
579 potPreviousStreets: 24,
580 totalPot: 36,
581 lastBetOrRaise: 2,
582 },
583 log: [], // hand history
584 handNumber: 1,
585 globalHandNumber: 1505,
586 },
587 2: {
588 gameInfo: {
589 sb: 2,
590 bb: 4,
591 minBuyin: 200,
592 maxBuyin: 400,
593 minPlayers: 2,
594 maxPlayers: 2,
595 gameType: "Holdem",
596 },
597 seats: {
598 "testplayer2": {
599 name: "testplayer2",
600 seat: 1,
601 chips: 432,
602 chipsInPotThisStreet: 0,
603 status: "live",
604 },
605 "testaccount2": {
606 name: "testaccount2",
607 seat: 2,
608 chips: 345,
609 chipsInPotThisStreet: 3,
610 status: "folded",
611 },
612 },
613 currentHand: {
614 currentTurn: "ted120",
615 dealerButton: "ted120",
616 smallBlind: "testaccount1",
617 bigBlind: "test123",
618 flop: ["Ac","9d","7h"],
619 turn: ["8s"],
620 river: ["Ts"],
621 potPreviousStreets: 24,
622 totalPot: 36,
623 lastBet: 2,
624 lastLastBet: 0,
625 },
626 log: [], // hand history
627 handNumber: 1,
628 globalHandNumber: 1505,
629 },
630 },
631 },
632 */"Grid Control": {
633 maps: {
634 "FlipskiZ map gen": {
635 mapGen: true,
636 mapData: [],
637 },
638 "Ted map gen": {
639 mapGen: true,
640 mapData: [],
641 },
642 "Standard map": {
643 mapGen: false,
644 mapData: [{
645 "gc_owner": "player1",
646 "id": 76,
647 "gc_str": 3,
648 }, {
649 "gc_owner": "player2",
650 "id": 4,
651 "gc_str": 3,
652 }, {
653 "gc_owner": "neutral",
654 "id": 60,
655 "gc_str": 2,
656 "gc_bonus": 2,
657 }, {
658 "gc_owner": "neutral",
659 "id": 24,
660 "gc_str": 2,
661 "gc_bonus": 2,
662 }, {
663 "gc_owner": "neutral",
664 "id": 48,
665 "gc_str": 1,
666 "gc_bonus": 1,
667 }, {
668 "gc_owner": "neutral",
669 "id": 30,
670 "gc_str": 1,
671 "gc_bonus": 1,
672 }, {
673 "gc_owner": "neutral",
674 "id": 72,
675 "gc_str": 6,
676 "gc_bonus": 5,
677 }, {
678 "gc_owner": "neutral",
679 "id": 0,
680 "gc_str": 6,
681 "gc_bonus": 5,
682 }, ],
683 },
684 },
685 players: {
686 "player1": {
687 color: "lightgreen",
688 wins: 0,
689 unitcount: 0,
690 },
691 "player2": {
692 color: "red",
693 wins: 0,
694 unitcount: 0,
695 },
696 },
697 },
698 };
699 var coinImg = document.createElement("img");
700 coinImg.setAttribute("src", "images/coins.png");
701 coinImg.setAttribute("class", "image-icon-20");
702
703 window.sendp2p = function(usernameTo) { //args order; name, main, subs
704 if (arguments.length <= 1) return false;
705 var sendArray = ["TMG", minigameCurrentSelectedGame];
706 if (window.username == pokerServerUsername) {
707 sendArray = ["TMG", "Poker"];
708 }
709 for (let i = 1; i < arguments.length; i++) {
710 sendArray.push(arguments[i]);
711 }
712 p2p(usernameTo, sendArray.join("#"));
713 console.log("sent: p2p(\"" + usernameTo + "\",\"" + sendArray.join("#")+"\")");
714 };
715
716 String.prototype.replaceAll = function(search, replacement) {
717 var target = this;
718 return target.replace(new RegExp(search, 'g'), replacement);
719 };
720
721 function drawButtons() {
722 var zMarket = document.createElement("div");
723 var marketUiButton = document.createElement("button");
724 marketUiButton.setAttribute("id", "marketButton");
725 marketUiButton.setAttribute("type", "button");
726 var oreAverageButton = document.createElement("button");
727 oreAverageButton.setAttribute("id", "oreAverageButton");
728 oreAverageButton.setAttribute("type", "button");
729 var minigamesButton = document.createElement("button");
730 minigamesButton.setAttribute("id", "minigamesButton");
731 minigamesButton.setAttribute("type", "button");
732 var zMap = document.createElement("span");
733 zMap.setAttribute("id", "mapSpan");
734 zMap.setAttribute("style", "color:gold");
735 zMap.innerHTML = " You have an incomplete map!";
736 var zVer = document.createElement("span");
737 zVer.setAttribute("style", "color:silver");
738 zVer.innerHTML = " version: " + GM_info.script.version + " ";
739 zMarket.setAttribute("id", "zMarketId");
740 zMarket.append(marketUiButton);
741 zMarket.append(zVer);
742 zMarket.append(oreAverageButton);
743 zMarket.append(minigamesButton);
744 zMarket.append(zMap);
745 document.getElementById("game-div").appendChild(zMarket);
746 document.getElementById("marketButton").addEventListener("click", marketButtonClickAction, false);
747 document.getElementById("oreAverageButton").addEventListener("click", oreAverageButtonClickAction, false);
748 document.getElementById("minigamesButton").addEventListener("click", minigamesButtonClickAction, false);
749 if (marketOn) {
750 document.getElementById("marketButton").innerHTML = "Ted's Market: ON";
751 } else document.getElementById("marketButton").innerHTML = "Ted's Market: OFF";
752 if (oreAverageOn) {
753 document.getElementById("oreAverageButton").innerHTML = "oreAverageText: ON";
754 } else document.getElementById("oreAverageButton").innerHTML = "oreAverageText: OFF";
755 if (minigamesOn) {
756 document.getElementById("minigamesButton").innerHTML = "Minigames: Open";
757 } else document.getElementById("minigamesButton").innerHTML = "Minigames: Minimised";
758 }
759
760 function nextTick() {
761 if (playtime > tickCheck) {
762 tickCheck = playtime;
763 tickEnd = new Date().getTime();
764 tickTime = tickEnd - tickStart;
765 if (debugToConsole) {
766 console.log("Tick time: " + tickTime);
767 }
768 tickStart = new Date().getTime();
769 return true;
770 } else return false;
771 }
772
773 function isInArray(array, search) {
774 return array.indexOf(search) >= 0;
775 }
776
777 function getNumberValueImproved(number) {
778 let orig = number;
779 number = (number + "").toLowerCase().replace(/,/g, "");
780 if (number.includes("k")) {
781 number = number.substr(0, number.length - 1);
782 return parseInt(number * 1000);
783 } else if (number.includes("m")) {
784 number = number.substr(0, number.length - 1);
785 return parseInt(number * 1000000);
786 } else if (number.includes("b")) {
787 number = number.substr(0, number.length - 1);
788 return parseInt(number * 1000000000);
789 }
790 return orig;
791 }
792
793 window.numberWithCommas = function(x) { //string
794 if (x === null) return null;
795 if (typeof(x) == "undefined") return undefined;
796 x = getNumberValueImproved(x);
797 x = x.toString().replace(/,/g, "");
798 return x.replace(/\B(?=(\d{3})+(?!\d))/g, ",");
799 };
800
801 window.numberWithoutCommas = function(x) { //int
802 x = getNumberValueImproved(x);
803 return parseInt(x.toString().replace(/,/g, ""));
804 };
805
806 function abbreviate_number(num, fixed) {
807 if (num === null) {
808 return null;
809 } // terminate early
810 if (num === 0) {
811 return '0';
812 } // terminate early
813 fixed = (!fixed || fixed < 0) ? 0 : fixed; // number of decimal places to show
814 var b = (num).toPrecision(2).split("e"), // get power
815 k = b.length === 1 ? 0 : Math.floor(Math.min(b[1].slice(1), 14) / 3), // floor at decimals, ceiling at trillions
816 c = k < 1 ? num.toFixed(0 + fixed) : k === 1 ? (num / Math.pow(10, k * 3)).toFixed(0) : (num / Math.pow(10, k * 3)).toFixed(0 + fixed), // divide by power
817 d = c < 0 ? c : Math.abs©, // enforce -0 is 0
818 e = d + ['', 'k', 'M', 'B', 'T'][k]; // append power
819 return e;
820 }
821 window.openTradeHistory = function() {
822 if (tradeHistoryModalBody.style.display != "inline-block") {
823 sortTradeHistory("date");
824 }
825 tradeHistoryModalBody.style.display = "inline-block";
826 tradeHistoryModalBodyTable.innerHTML = thString;
827 document.getElementById("thSearch").focus();
828 };
829
830 function tedMarketUiSettings() {
831 var i, j;
832 var arrSettingsTH = ["tedMarket Configuration (may require refresh)", "Active"];
833 var zSettingsTable = document.createElement("table");
834 zSettingsTable.setAttribute("id", "marketSettingsTable");
835 zSettingsTable.setAttribute("style", "width:40%;margin-top:3%;margin-bottom:3%;");
836 zSettingsTable.setAttribute("class", "table-style1");
837 zSettingsTable.setAttribute("align", "center");
838 var zSettingsTBody = document.createElement("tbody");
839 zSettingsTBody.setAttribute("style", "border-color:black");
840 for (i = 0; i < 1; i++) {
841 var zSettingsTHRow = document.createElement("tr");
842 zSettingsTHRow.setAttribute("style", "background-color:grey;color:black;border-color:grey");
843 for (j = 0; j < 2; j++) {
844 var zSettingsTH = document.createElement("th");
845 var cellText = document.createTextNode(arrSettingsTH[j]);
846 zSettingsTH.appendChild(cellText);
847 zSettingsTHRow.appendChild(zSettingsTH);
848 }
849 zSettingsTBody.appendChild(zSettingsTHRow);
850 }
851 window.toggleAlwaysShowLowest = function() {
852 let isChecked = document.getElementsByClassName("ted-alwaysShowLowest-checkbox")[0].checked;
853 for (let i = 0; i < document.getElementsByClassName("ted-alwaysShowLowest-checkbox").length; i++) {
854 document.getElementsByClassName("ted-alwaysShowLowest-checkbox")[i].checked = !isChecked;
855 }
856 };
857 window.toggleShowAtMin = function() {
858 let isChecked = document.getElementsByClassName("ted-showAtMin-checkbox")[0].checked;
859 for (let i = 0; i < document.getElementsByClassName("ted-showAtMin-checkbox").length; i++) {
860 document.getElementsByClassName("ted-showAtMin-checkbox")[i].checked = !isChecked;
861 }
862 };
863 window.saveItemSettings = function() {
864 let showAtPrice = document.getElementsByClassName("ted-showAtPrice-input");
865 let alwaysShowLowest = document.getElementsByClassName("ted-alwaysShowLowest-checkbox");
866 let showAtMin = document.getElementsByClassName("ted-showAtMin-checkbox");
867 for (let i = 0; i < document.getElementsByClassName("ted-showAtPrice-input").length; i++) {
868 let itemName = showAtPrice[i].name;
869 let val = numberWithoutCommas(showAtPrice[i].value);
870 if (isNaN(val)) val = null;
871 if (tedStoredSettings.tedTradableItems.itemList[itemName]) {
872 tedStoredSettings.tedTradableItems.itemList[itemName].showAtPrice = val;
873 }
874 }
875 for (let i = 0; i < alwaysShowLowest.length; i++) {
876 let itemName = alwaysShowLowest[i].name;
877 let val = alwaysShowLowest[i].checked;
878 if (tedStoredSettings.tedTradableItems.itemList[itemName]) {
879 tedStoredSettings.tedTradableItems.itemList[itemName].alwaysShowLowest = val;
880 }
881 }
882 for (let i = 0; i < showAtMin.length; i++) {
883 let itemName = showAtMin[i].name;
884 let val = showAtMin[i].checked;
885 if (tedStoredSettings.tedTradableItems.itemList[itemName]) {
886 tedStoredSettings.tedTradableItems.itemList[itemName].showAtMin = val;
887 }
888 }
889 for (let i = 0; i < document.getElementsByClassName("ted-cheapest-stuff").length; i++) {
890 let val = numberWithoutCommas(document.getElementsByClassName("ted-cheapest-stuff")[i].value);
891 if (isNaN(val)) val = 999999;
892 //forgive me
893 if (document.getElementsByClassName("ted-cheapest-stuff")[i].id == "cheapest-Heat-showAtPrice") tedStoredSettings.showCheapestHeat.showAt = val;
894 if (document.getElementsByClassName("ted-cheapest-stuff")[i].id == "cheapest-Energy-showAtPrice") tedStoredSettings.showCheapestEnergy.showAt = val;
895 if (document.getElementsByClassName("ted-cheapest-stuff")[i].id == "cheapest-Bonemeal-showAtPrice") tedStoredSettings.showCheapestBonemeal.showAt = val;
896 }
897 updateVariables();
898 scrollText("none", "lime", "Saved");
899 };
900 window.changeSetting = function(prop) {
901 if (tedStoredSettings && tedStoredSettings[prop]) {
902 if (tedStoredSettings[prop].value === true) {
903 tedStoredSettings[prop].value = false;
904 document.getElementById("celltick-" + prop).setAttribute("src", "images/icons/x.png");
905 updateVariables();
906 } else if (tedStoredSettings[prop].value === false) {
907 tedStoredSettings[prop].value = true;
908 document.getElementById("celltick-" + prop).setAttribute("src", "images/icons/check.png");
909 updateVariables();
910 } else if (tedStoredSettings[prop].bgcolor) {
911 document.getElementById("celltick-" + prop).style.backgroundColor = tedStoredSettings[prop].bgcolor;
912 colorModal.setAttribute("style", "display:block;position:fixed;z-index:1;left:0;top:0;width:100%;height:100%;overflow:auto;background-color:rgba(0,0,0,0.4);");
913 while (colorModalBody.firstChild) {
914 colorModalBody.removeChild(colorModalBody.firstChild);
915 }
916 var colorModalBodyContent = document.createElement("div");
917 colorModalBody.appendChild(colorModalBodyContent);
918 colorModalBodyContent.innerHTML = "";
919 KEYS.forEach((key) => {
920 if (tedStoredSettings[key].bgcolor) {
921 var colorModalInput = document.createElement("input");
922 colorModalInput.setAttribute("id", key);
923 colorModalInput.setAttribute("value", tedStoredSettings[key].bgcolor);
924 colorModalInput.setAttribute("style", "background-color:" + tedStoredSettings[key].bgcolor);
925 colorModalBodyContent.appendChild(colorModalInput);
926 var colorModalAddBtn = document.createElement("button");
927 colorModalAddBtn.setAttribute("onclick", "changeColor('" + key + "',document.getElementById('" + key + "').value);changeSetting('" + key + "')");
928 colorModalAddBtn.append("Change");
929 colorModalBodyContent.append(colorModalInput);
930 colorModalBodyContent.append(colorModalAddBtn);
931 colorModalBodyContent.append(tedStoredSettings[key].text);
932 // tedStoredSettings[key].text+" = "+colorModalInput+" = "+colorModalBtn
933 colorModalBodyContent.innerHTML += '<br><br>';
934 }
935 });
936 var colorResetBtn = document.createElement("button");
937 colorResetBtn.append("RESET COLORS");
938 colorResetBtn.setAttribute("onclick", "resetColors();changeSetting('colorMinPrice');");
939 colorModalBodyContent.append(colorResetBtn);
940 } else if (tedStoredSettings[prop].itemList) {
941 myItemListModal.setAttribute("style", "position:fixed;z-index:1;left:0;top:0;width:100%;height:100%;overflow:auto;background-color:rgba(0,0,0,0.4);display:flex;flex-direction:row;justify-content:center;");
942 while (myItemListModalBody.firstChild) {
943 myItemListModalBody.removeChild(myItemListModalBody.firstChild);
944 }
945 var myItemListModalBodyNameInput = document.createElement("input");
946 myItemListModalBodyNameInput.setAttribute("id", "myItemListModalBodyNameInput");
947 if (typeof(myItemListAddName) == "undefined") myItemListAddName = "";
948 myItemListModalBodyNameInput.setAttribute("value", myItemListAddName);
949 myItemListModalBodyNameInput.setAttribute("placeholder", "Item Name");
950 myItemListModalBody.append(myItemListModalBodyNameInput);
951 var myItemListModalBodyPriceInput = document.createElement("input");
952 myItemListModalBodyPriceInput.setAttribute("id", "myItemListModalBodyPriceInput");
953 myItemListModalBodyPriceInput.setAttribute("onkeydown", "if (event.keyCode == 13) { document.getElementById('myItemListAddBtn').click(); }");
954 if (typeof(myItemListAddPrice) == "undefined") myItemListAddPrice = "";
955 myItemListModalBodyPriceInput.setAttribute("value", myItemListAddPrice);
956 myItemListModalBodyPriceInput.setAttribute("placeholder", "Show At Price");
957 myItemListModalBody.append(myItemListModalBodyPriceInput);
958 var myItemListAddBtn = document.createElement("button");
959 myItemListAddBtn.setAttribute("id", "myItemListAddBtn");
960 myItemListAddBtn.setAttribute("style", "cursor:pointer");
961 myItemListAddBtn.setAttribute("onclick", "myItemListAdd(myItemListModalBodyNameInput.value,myItemListModalBodyPriceInput.value);changeSetting('myItemList')");
962 myItemListAddBtn.append("Add");
963 myItemListModalBody.append(myItemListAddBtn);
964 myItemListModalBody.append(document.createElement("br"));
965 myItemListModalBody.append(document.createElement("br"));
966 var saveItemSettingsBtn = document.createElement("button");
967 saveItemSettingsBtn.setAttribute("id", "saveItemSettingsBtn");
968 saveItemSettingsBtn.setAttribute("style", "cursor:pointer;background-color:lightgreen");
969 saveItemSettingsBtn.setAttribute("onclick", "saveItemSettings();changeSetting('tedTradableItems')");
970 saveItemSettingsBtn.append("Save Item Settings (MUST PUSH AFTER CHANGING BELOW)");
971 myItemListModalBody.append(saveItemSettingsBtn);
972 myItemListModalBody.append(document.createElement("br"));
973 myItemListModalBody.append(document.createElement("br"));
974 var itemListModalBodyString = "";
975 var objCheapest = {
976 heat: {
977 name: "Heat",
978 showAt: tedStoredSettings.showCheapestHeat.showAt,
979 currentLow: cheapestHeat,
980 image: "images/icons/fire.png"
981 },
982 energy: {
983 name: "Energy",
984 showAt: tedStoredSettings.showCheapestEnergy.showAt,
985 currentLow: cheapestEnergy,
986 image: "images/steak.png"
987 },
988 bonemeal: {
989 name: "Bonemeal",
990 showAt: tedStoredSettings.showCheapestBonemeal.showAt,
991 currentLow: cheapestBonemeal,
992 image: "images/filledBonemealBin.png"
993 }
994 };
995 itemListModalBodyString += "<table style='border-spacing:20px 2px'><tbody><tr><th>Cheapest</th><th>Show At Price</th><th>Current Price</th></tr>";
996 Object.keys(objCheapest).forEach((key) => {
997 itemListModalBodyString += "<tr>";
998 itemListModalBodyString += "<td style='text-align:right'>" + objCheapest[key].name + "</td>";
999 var showAt = objCheapest[key].showAt;
1000 if (showAt === null) showAt = "";
1001 itemListModalBodyString += "<td><input type='text' class='ted-cheapest-stuff' id='cheapest-" + objCheapest[key].name + "-showAtPrice' style='text-align:right;width:90px;padding:2px 5px;' value='" + numberWithCommas(showAt) + "'/></td>";
1002 itemListModalBodyString += "<td style='text-align:right'>" + numberWithCommas(objCheapest[key].currentLow) + "</td>";
1003 itemListModalBodyString += "</tr>";
1004 });
1005 itemListModalBodyString += "</tbody></table><br>";
1006 itemListModalBodyString += "Left to right priority. Show At Price > Show At Min > Always Show One. To never show an item (red background in table below): Show At Price = empty, Show At Min = unticked, Always Show One = unticked.<br><br>";
1007 itemListModalBodyString += "<table style='border-spacing:20px 2px'><tbody><tr><th>Item</th><th>Show At Price</th><th><input type='button' value='Show At Min' onclick='toggleShowAtMin();'></th><th><input type='button' value='Always Show One' onclick='toggleAlwaysShowLowest();'></th></tr>";
1008 var showAtPrice;
1009 for (var itemName in tedStoredSettings.tedTradableItems.itemList) {
1010 if (!isInArray(arrSortItemsList, getItemName(itemName))) {
1011 showAtPrice = tedStoredSettings.tedTradableItems.itemList[itemName].showAtPrice;
1012 if (showAtPrice === null) {
1013 showAtPrice = "";
1014 }
1015 itemListModalBodyString += "<tr>";
1016 itemListModalBodyString += "<td style='text-align:right'>" + getItemName(itemName) + "</td>";
1017 itemListModalBodyString += "<td><input type='text' name='" + itemName + "' class='ted-showAtPrice-input' id='" + itemName + "-showAtPrice' style='text-align:right;width:90px;padding:2px 5px;' value='" + numberWithCommas(showAtPrice) + "'/></td>";
1018 itemListModalBodyString += "<td style='text-align:center'><input type='checkbox' name='" + itemName + "' class='ted-showAtMin-checkbox' style='width:16px;height:16px;cursor:pointer' /></td>";
1019 itemListModalBodyString += "<td style='text-align:center'><input type='checkbox' name='" + itemName + "' class='ted-alwaysShowLowest-checkbox' style='width:16px;height:16px;cursor:pointer' checked='true' /></td>";
1020 itemListModalBodyString += "</tr>";
1021 }
1022 }
1023 for (let i = 0; i < arrSortItemsList.length; i++) {
1024 itemName = itemNameFix(arrSortItemsList[i]);
1025 if (tedStoredSettings.tedTradableItems.itemList[itemName]) {
1026 showAtPrice = tedStoredSettings.tedTradableItems.itemList[itemName].showAtPrice;
1027 if (showAtPrice === null) {
1028 showAtPrice = "";
1029 }
1030 itemListModalBodyString += "<tr>";
1031 itemListModalBodyString += "<td style='text-align:right'>" + getItemName(itemName) + "</td><td>";
1032 itemListModalBodyString += "<input type='text' name='" + itemName + "' class='ted-showAtPrice-input' id='" + itemName + "-showAtPrice' style='text-align:right;width:90px;padding:2px 5px;' value='" + numberWithCommas(showAtPrice) + "'/></td>";
1033 itemListModalBodyString += "<td style='text-align:center'><input type='checkbox' name='" + itemName + "' class='ted-showAtMin-checkbox' style='width:16px;height:16px;cursor:pointer' /></td>";
1034 itemListModalBodyString += "<td style='text-align:center'><input type='checkbox' name='" + itemName + "' class='ted-alwaysShowLowest-checkbox' style='width:16px;height:16px;cursor:pointer' /></td>";
1035 itemListModalBodyString += "</tr>";
1036 }
1037 }
1038 itemListModalBodyString += "</tbody></table>";
1039 myItemListModalBody.innerHTML += itemListModalBodyString;
1040 for (let i = 0; i < document.getElementsByClassName("ted-alwaysShowLowest-checkbox").length; i++) {
1041 let itemName = document.getElementsByClassName("ted-alwaysShowLowest-checkbox")[i].name;
1042 document.getElementsByClassName("ted-alwaysShowLowest-checkbox")[i].checked = tedStoredSettings.tedTradableItems.itemList[itemName].alwaysShowLowest;
1043 }
1044 for (let i = 0; i < document.getElementsByClassName("ted-showAtMin-checkbox").length; i++) {
1045 let itemName = document.getElementsByClassName("ted-showAtMin-checkbox")[i].name;
1046 document.getElementsByClassName("ted-showAtMin-checkbox")[i].checked = tedStoredSettings.tedTradableItems.itemList[itemName].showAtMin;
1047 }
1048 for (let i = 0; i < document.getElementsByClassName("ted-showAtPrice-input").length; i++) {
1049 let itemName = document.getElementsByClassName("ted-showAtPrice-input")[i].name;
1050 if (document.getElementsByName(itemName)[0].value === "" && document.getElementsByName(itemName)[1].checked === false && document.getElementsByName(itemName)[2].checked === false) {
1051 upToParentByTag(document.getElementById(itemName + "-showAtPrice"), "tr").style.backgroundColor = "#ff7878";
1052 }
1053 }
1054 document.getElementById("myItemListModalBodyPriceInput").focus();
1055 setTimeout(function() {
1056 document.getElementById("myItemListModalBodyPriceInput").selectionStart = document.getElementById("myItemListModalBodyPriceInput").selectionEnd = 10000;
1057 }, 0);
1058 }
1059 }
1060 };
1061 const KEYS = Object.keys(defaultSettings);
1062 KEYS.forEach((key) => {
1063 if (!tedStoredSettings[key].hideFromSettings && key !== "tradeHistory") {
1064 var zSettingsRow = document.createElement("tr");
1065 var zSettingsCell = document.createElement("td");
1066 zSettingsCell.setAttribute("style", "text-align:left;padding:0px 5px;");
1067 var cellText = document.createTextNode(tedStoredSettings[key].text);
1068 if (key == "tedTradableItems") {
1069 cellText = document.createTextNode("Click to open item settings menu");
1070 }
1071 var cellTick = document.createElement("div");
1072 if (tedStoredSettings[key].value === true) {
1073 cellTick = document.createElement("img");
1074 cellTick.setAttribute("src", "images/icons/check.png");
1075 cellTick.setAttribute("style", "width:20px;height:20px;vertical-align:bottom");
1076 } else if (tedStoredSettings[key].value === false) {
1077 cellTick = document.createElement("img");
1078 cellTick.setAttribute("src", "images/icons/x.png");
1079 cellTick.setAttribute("style", "width:20px;height:20px;vertical-align:bottom");
1080 } else if (tedStoredSettings[key].bgcolor) {
1081 cellTick.setAttribute("style", "display:block;background-color:" + tedStoredSettings[key].bgcolor);
1082 cellTick.innerHTML = "+";
1083 }
1084 zSettingsRow.setAttribute("id", "checkbox-" + key);
1085 zSettingsRow.setAttribute("onclick", "changeSetting('" + key + "')");
1086 cellTick.setAttribute("id", "celltick-" + key);
1087 zSettingsCell.appendChild(cellText);
1088 zSettingsRow.appendChild(zSettingsCell);
1089 zSettingsCell = document.createElement("td");
1090 zSettingsCell.appendChild(cellTick);
1091 zSettingsRow.appendChild(zSettingsCell);
1092 zSettingsRow.setAttribute("align", "center");
1093 zSettingsTBody.appendChild(zSettingsRow);
1094 }
1095 });
1096 zSettingsTable.appendChild(zSettingsTBody);
1097 document.getElementById("tab-container-profile").appendChild(zSettingsTable);
1098 var hideItemListModal = document.createElement("div");
1099 hideItemListModal.setAttribute("id", "hideItemListModal");
1100 hideItemListModal.setAttribute("style", "display:none");
1101 var hideItemListModalBody = document.createElement("div");
1102 hideItemListModalBody.setAttribute("id", "hideItemListModalBody");
1103 hideItemListModalBody.setAttribute("style", "background-color:#ffcc44;padding:1%;margin:2%;");
1104 document.getElementById("game-div").append(hideItemListModal);
1105 document.getElementById("hideItemListModal").append(hideItemListModalBody);
1106 window.myItemListRemove = function(itemName) {
1107 tedStoredSettings.tedTradableItems.itemList[itemName].showAtPrice = null;
1108 updateVariables();
1109 };
1110 window.myItemListAdd = function(itemName, price) {
1111 itemName = itemNameFix(itemName);
1112 price = numberWithoutCommas(price);
1113 if (!isNaN(price)) {
1114 if (tedStoredSettings.tedTradableItems.itemList[itemName]) {
1115 tedStoredSettings.tedTradableItems.itemList[itemName].showAtPrice = price;
1116 document.getElementById(itemName + "-showAtPrice").value = numberWithCommas(price);
1117 document.getElementById("myItemListModalBodyNameInput").value = "";
1118 document.getElementById("myItemListModalBodyPriceInput").value = "";
1119 updateVariables();
1120 scrollText("none", "lime", "Added " + getItemName(itemName) + " @ " + price);
1121 return;
1122 }
1123 }
1124 scrollText("none", "red", "Failed to add " + getItemName(itemName) + " @ " + price);
1125 };
1126 var myItemListModal = document.createElement("div");
1127 myItemListModal.setAttribute("id", "myItemListModal");
1128 myItemListModal.setAttribute("style", "display:none");
1129 var myItemListModalBody = document.createElement("div");
1130 myItemListModalBody.setAttribute("id", "myItemListModalBody");
1131 myItemListModalBody.setAttribute("style", "background-color:#ffcc44;padding:1%;margin:10%;overflow-y:scroll;min-height:200px;");
1132 document.getElementById("game-div").append(myItemListModal);
1133 document.getElementById("myItemListModal").append(myItemListModalBody);
1134 window.changeColor = function(key, color) {
1135 tedStoredSettings[key].bgcolor = color;
1136 updateVariables();
1137 };
1138 window.resetColors = function() {
1139 KEYS.forEach((key) => {
1140 if (tedStoredSettings[key].bgcolor) {
1141 tedStoredSettings[key].bgcolor = defaultSettings[key].bgcolor;
1142 document.getElementById("celltick-" + key).style.backgroundColor = tedStoredSettings[key].bgcolor;
1143 }
1144 });
1145 updateVariables();
1146 };
1147 var colorModal = document.createElement("div");
1148 colorModal.setAttribute("id", "colorModal");
1149 colorModal.setAttribute("style", "display:none");
1150 var colorModalBody = document.createElement("div");
1151 colorModalBody.setAttribute("id", "colorModalBody");
1152 colorModalBody.setAttribute("style", "position:fixed;bottom:0;background-color:#fefefe;width:100%;padding:5%");
1153 document.getElementById("game-div").append(colorModal);
1154 document.getElementById("colorModal").append(colorModalBody);
1155 window.onclick = function(event) {
1156 if (event.target == hideItemListModal) {
1157 hideItemListModal.style.display = "none";
1158 }
1159 if (event.target == myItemListModal) {
1160 myItemListModal.style.display = "none";
1161 }
1162 if (event.target == colorModal) {
1163 colorModal.style.display = "none";
1164 }
1165 };
1166 }
1167
1168 function quickCalcMain() {
1169 var i, a, b;
1170 var arrQuickCalcHeat = ["Error, search for all (infinity symbol)", 999999, 0, 999999, 0, 0]; // name, heatprice, amount, logprice, heat, row
1171 var arrLogs = [
1172 ["Logs", 1],
1173 ["Oak Logs", 2],
1174 ["Willow Logs", 5],
1175 ["Maple Logs", 10],
1176 ["Stardust Logs", 20],
1177 ["Essence Logs", 30]
1178 ];
1179 var arrQuickCalcEnergy = ["Error, search for all (infinity symbol)", 999999, 0, 999999, 0, 0]; // name, energyprice, amount, fishprice, energy, row
1180 var arrEnergy = [
1181 ["Shrimp", 50],
1182 ["Sardine", 400],
1183 ["Tuna", 1000],
1184 ["Swordfish", 7500],
1185 ["Shark", 20000]
1186 ];
1187 var arrQuickCalcBonemeal = ["Error, search for all (infinity symbol)", 999999, 0, 999999, 0, 0]; // name, bonemealprice, amount, boneprice, bonemeal, row
1188 var arrBonemeal = [
1189 ["Bones", 1],
1190 ["Ashes", 2],
1191 ["Ice Bones", 3]
1192 ];
1193 var hasBrewingKit;
1194 var arrStargemInput = [
1195 ["Blewit Mushroom", 100, 0, 0],
1196 ["Gold Leaf", 1, 0, 0],
1197 ["Sapphire", 1, 0, 0],
1198 ["Emerald", 1, 0, 0],
1199 ["Ruby", 1, 0, 0],
1200 ["Diamond", 1, 0, 0],
1201 ["Sand", 25, 0, 0],
1202 ["Glass", 25, 0, 0]
1203 ]; //name,amt need, amt have, ttl price
1204 var arrStargemOutput = [
1205 ["Stardust", 0]
1206 ]; // name, price
1207 var arrEssenceInput = [
1208 ["Dotted Green Leaf", 5, 0, 0],
1209 ["Blewit Mushroom", 30, 0, 0]
1210 ]; //name,amt need, amt have, ttl price
1211 var arrEssenceOutput = [
1212 ["Essence", 0]
1213 ];
1214 var arrSuperEssenceInput = [
1215 ["Dotted Green Leaf", 25, 0, 0],
1216 ["Blewit Mushroom", 100, 0, 0]
1217 ];
1218 var arrSuperEssenceOutput = [
1219 ["Essence", 0]
1220 ];
1221 var arrSmallVialInput = [
1222 ["Glass", 5, 0, 0],
1223 ["Sand", 5, 0, 0]
1224 ]; //or
1225 var arrSuperStardustInput = [
1226 ["Lime Leaf", 5, 0, 0],
1227 ["Snapegrass", 50, 0, 0]
1228 ];
1229 var arrSuperStardustOutput = [
1230 ["Stardust", 0]
1231 ];
1232 var potionDurationModifier = 1 + (achBrewingEasyCompleted * 0.05);
1233 var perkEssenceChanceModifier = (achBrewingHardCompleted * 0.75 || achBrewingMediumCompleted * 0.9 || 1),
1234 essencePotionEssenceChance = (16000 - (getLevel(miningXp) * 150)) * perkEssenceChanceModifier,
1235 superEssencePotionEssenceChance = (8000 - (getLevel(miningXp) * 75)) * perkEssenceChanceModifier;
1236 var avgSdGainStardustPotion = Math.floor( ((0 + 40) * (1 + (achBrewingEasyCompleted * 0.05))) / 2),//per tick
1237 avgSdGainSuperStardustPotion = Math.floor( ((0 + 220) * (1 + (achBrewingEasyCompleted * 0.05))) / 2),// per tick
1238 essencePotionAvgEssence = (1 / essencePotionEssenceChance),
1239 superEssencePotionAvgEssence = (1 / superEssencePotionEssenceChance);
1240 var stardustPotionDuration = Math.floor(300 * (1 + ((getLevel(brewingXp) / 100 * 0.2) * potionDurationModifier) )),
1241 superStardustPotionDuration = Math.floor(300 * (1 + ((getLevel(brewingXp) / 100 * 0.2) * potionDurationModifier) )),
1242 essencePotionDuration = Math.floor(3600 * (1 + ((getLevel(brewingXp) / 100 * 0.2) * potionDurationModifier) )),
1243 superEssencePotionDuration = Math.floor(3600 * (1 + ((getLevel(brewingXp) / 100 * 0.2) * potionDurationModifier) ));
1244 avgSdGainStardustPotion = avgSdGainStardustPotion * stardustPotionDuration;
1245 avgSdGainSuperStardustPotion = avgSdGainSuperStardustPotion * superStardustPotionDuration;
1246 essencePotionAvgEssence = essencePotionAvgEssence * essencePotionDuration;
1247 superEssencePotionAvgEssence = superEssencePotionAvgEssence * superEssencePotionDuration;
1248
1249 var arrStardustInput = [
1250 ["Dotted Green Leaf", 1, 0, 0],
1251 ["Red Mushroom", 25, 0, 0]
1252 ];
1253 var arrStardustOutput = [
1254 ["Stardust", 0]
1255 ];
1256 var lowestVial, lowestVialSource, lowestSmallVial, lowestSmallVialSource;
1257 var stargemNetMinusOne, stargemNet, stargemNetPlusOne, totalPrice;
1258
1259 function calculateAndModifyHeatEnergy(array, array2) {
1260 var pricePerHeat;
1261 for (a = 0; a < array.length; a++) {
1262 let itemName = itemNameFix(array[a][0]);
1263 if (arrMarketItems[itemName]) {
1264 let itemPrice = arrMarketItems[itemName][0].price;
1265 let itemAmount = arrMarketItems[itemName][0].amount;
1266 let itemRow = arrMarketItems[itemName][0].row;
1267 if (typeof(pricePerHeat) == "undefined" || itemPrice / array[a][1] < pricePerHeat) {
1268 pricePerHeat = itemPrice / array[a][1];
1269 //if (pricePerHeat < array2[1]) {
1270 array2[0] = array[a][0];
1271 array2[1] = Math.ceil(itemPrice / array[a][1]);
1272 array2[2] = itemAmount;
1273 array2[3] = itemPrice;
1274 array2[4] = array[a][1];
1275 array2[5] = itemRow;
1276 }
1277 if (itemName == "stardustLogs") {
1278 if (arrMarketItems.stardust[0]) {
1279 let avgSdValue = ((2500 + 10000) / 2) * (arrMarketItems.stardust[0].price - 1);
1280 let sdLogHeatCost = Math.ceil((itemPrice - avgSdValue) / array[a][1]);
1281 if (sdLogHeatCost < array2[1]) {
1282 array2[0] = array[a][0];
1283 array2[1] = sdLogHeatCost;
1284 array2[2] = itemAmount;
1285 array2[3] = itemPrice;
1286 array2[4] = array[a][1];
1287 array2[5] = itemRow;
1288 }
1289 }
1290 } else if (itemName == "essenceLogs") {
1291 if (arrMarketItems.essence) {
1292 let avgFragValue = ((1 + 14) / 200) * (arrMarketItems.essence[0].price * 0.95);
1293 let essLogHeatCost = Math.ceil((itemPrice - avgFragValue) / array[a][1]);
1294 if (essLogHeatCost < array2[1]) {
1295 array2[0] = array[a][0];
1296 array2[1] = essLogHeatCost;
1297 array2[2] = itemAmount;
1298 array2[3] = itemPrice;
1299 array2[4] = array[a][1];
1300 array2[5] = itemRow;
1301 }
1302 }
1303 }
1304 if (debugToConsole) {
1305 console.item(itemName, itemPrice / array[a][1], itemAmount);
1306 }
1307 if (debugToConsole) {
1308 console.item(array2[0], array2[1], array2[2]);
1309 }
1310 }
1311 }
1312 }
1313
1314 function calculateAndModifyInput(array) {
1315 for (a = 0; a < array.length; a++) {
1316 let itemName = itemNameFix(array[a][0]);
1317 if (arrMarketItems[itemName]) {
1318 for (b = 0; b < arrMarketItems[itemName].length; b++) {
1319 if (array[a][2] < array[a][1]) {
1320 if (arrMarketItems[itemName][b].amount < array[a][1] - array[a][2]) {
1321 array[a][2] += arrMarketItems[itemName][b].amount;
1322 array[a][3] += arrMarketItems[itemName][b].price * arrMarketItems[itemName][b].amount;
1323 } else if (arrMarketItems[itemName][b].amount >= array[a][1] - array[a][2]) {
1324 array[a][3] += (array[a][1] - array[a][2]) * arrMarketItems[itemName][b].price;
1325 array[a][2] = array[a][1];
1326 }
1327 if (debugToConsole) {
1328 console.log(array[a][0], array[a][1], array[a][2], array[a][3]);
1329 }
1330 }
1331 }
1332 }
1333 }
1334 }
1335
1336 function calculateAndModifyOutput(array) {
1337 for (a = 0; a < array.length; a++) {
1338 let output = itemNameFix(array[a][0]);
1339 if (arrMarketItems[output]) {
1340 array[a][1] = arrMarketItems[output][0].price;
1341 break;
1342 }
1343 }
1344 }
1345 if (typeof(document.getElementById("market-table").rows[1]) == "undefined" || document.getElementById("market-table").rows[1] === null) {} else if (typeof(document.getElementById("market-table").rows[1]) != "undefined" && document.getElementById("market-table").rows[1] !== null) {
1346 //heat
1347 calculateAndModifyHeatEnergy(arrLogs, arrQuickCalcHeat);
1348 //energy
1349 calculateAndModifyHeatEnergy(arrEnergy, arrQuickCalcEnergy);
1350 //bonemeal
1351 calculateAndModifyHeatEnergy(arrBonemeal, arrQuickCalcBonemeal);
1352 //small vial
1353 calculateAndModifyInput(arrSmallVialInput);
1354 //stardust
1355 calculateAndModifyInput(arrStardustInput);
1356 calculateAndModifyOutput(arrStardustOutput);
1357 //super stardust
1358 calculateAndModifyInput(arrSuperStardustInput);
1359 calculateAndModifyOutput(arrSuperStardustOutput);
1360 //stargem
1361 calculateAndModifyInput(arrStargemInput);
1362 calculateAndModifyOutput(arrStargemOutput);
1363 //stargem
1364 calculateAndModifyInput(arrEssenceInput);
1365 calculateAndModifyOutput(arrEssenceOutput);
1366 //stargem
1367 calculateAndModifyInput(arrSuperEssenceInput);
1368 calculateAndModifyOutput(arrSuperEssenceOutput);
1369 //small vial stuff
1370 if (arrSmallVialInput[0][2] == arrSmallVialInput[0][1] && arrSmallVialInput[1][2] == arrSmallVialInput[1][1]) { // enough both
1371 if (arrSmallVialInput[1][3] <= arrSmallVialInput[0][3]) {
1372 lowestSmallVial = arrSmallVialInput[1][3];
1373 lowestSmallVialSource = arrSmallVialInput[1][0];
1374 } else if (arrSmallVialInput[0][3] < arrSmallVialInput[1][3]) {
1375 lowestSmallVial = arrSmallVialInput[0][3];
1376 lowestSmallVialSource = arrSmallVialInput[0][0];
1377 }
1378 } else if (arrSmallVialInput[0][2] == arrSmallVialInput[0][1] && arrSmallVialInput[1][2] != arrSmallVialInput[1][1]) { // glass only
1379 lowestSmallVial = arrSmallVialInput[0][3];
1380 lowestSmallVialSource = arrSmallVialInput[0][0];
1381 } else if (arrSmallVialInput[0][2] != arrSmallVialInput[0][1] && arrSmallVialInput[1][2] == arrSmallVialInput[1][1]) { // sand only
1382 lowestSmallVial = arrSmallVialInput[1][3];
1383 lowestSmallVialSource = arrSmallVialInput[1][0];
1384 } else if (arrSmallVialInput[0][2] != arrSmallVialInput[0][1] && arrSmallVialInput[1][2] != arrSmallVialInput[1][1]) { // not enough both
1385 lowestSmallVial = 0;
1386 lowestSmallVialSource = "<span style='color:red;background-color:black;'>ERR: Sand & Glass < 5</span>";
1387 }
1388
1389 //stardust tooltip hover
1390 var dottedGreenLeafPrice = arrStardustInput[0][3];
1391 var redMushroomPrice = arrStardustInput[1][3];
1392 var lowestSmallVialPrice = lowestSmallVial;
1393 if (boundBrewingKit == 1) {
1394 hasBrewingKit = true;
1395 for (i = 0; i < 2; i++) {
1396 arrStardustInput[i][3] = Math.ceil(arrStardustInput[i][3] / 1.1); // brewing kit 10% free ingredients
1397 }
1398 lowestSmallVialPrice = Math.ceil(lowestSmallVialPrice / 1.1); // brewing kit 10% free vial
1399 } else hasBrewingKit = false;
1400 quickCalcStardustString = "";
1401 quickCalcStardustBoxShadow = false;
1402 if (arrStardustInput[0][1] == arrStardustInput[0][2] && arrStardustInput[1][1] == arrStardustInput[1][2]) {
1403 quickCalcStardustString += "<span style='float:left;padding:5px;'>Stardust Profit</span>";
1404 if (hasBrewingKit) {
1405 quickCalcStardustString += "<span style='float:right;padding:5px;color:green;'>+Brewing Kit</span>";
1406 } else quickCalcStardustString += "<span style='float:right;padding:5px;color:black;'><s style='color:red'>Brewing Kit</s></span>";
1407 quickCalcStardustString += "<br>";
1408 quickCalcStardustString += "<table style='text-align:center;padding:0 2px;' class='top-bar'><tbody><tr style='text-align:center'><th></th><th>Cost</th><th style='color:silver'>" + (arrStargemOutput[0][1] - 1) + "</th><th>" + (arrStargemOutput[0][1]) + "</th><th style='color:silver'>" + (arrStargemOutput[0][1] + 1) + "</th></tr>";
1409 stargemNetMinusOne = abbreviate_number(((arrStargemOutput[0][1] - 1) * avgSdGainStardustPotion) - (arrStardustInput[0][3] + arrStardustInput[1][3] + lowestSmallVialPrice), 1);
1410 stargemNet = abbreviate_number(((arrStargemOutput[0][1]) * avgSdGainStardustPotion) - (arrStardustInput[0][3] + arrStardustInput[1][3] + lowestSmallVialPrice), 1);
1411 stargemNetPlusOne = abbreviate_number(((arrStargemOutput[0][1] + 1) * avgSdGainStardustPotion) - (arrStardustInput[0][3] + arrStardustInput[1][3] + lowestSmallVialPrice), 1);
1412 quickCalcStardustString += "<tr>";
1413 quickCalcStardustString += "<td style='text-align:center'><img class='image-icon-20' src='images/stardustPotion.png'></td>";
1414 totalPrice = (arrStardustInput[0][3] + arrStardustInput[1][3] + lowestSmallVialPrice);
1415 quickCalcStardustString += "<td>" + abbreviate_number(totalPrice, 2) + "</td>";
1416 if (abbreviate_number(totalPrice, 1) === 0) {
1417 quickCalcStardustString += "<td></td>";
1418 } else if (stargemNetMinusOne.indexOf("-") >= 0) {
1419 quickCalcStardustString += "<td style='color:red'>" + stargemNetMinusOne + "</td>";
1420 } else {
1421 quickCalcStardustString += "<td style='color:lightgreen'>" + stargemNetMinusOne + "</td>";
1422 quickCalcStardustBoxShadow = true;
1423 }
1424 if (abbreviate_number(totalPrice, 1) === 0) {
1425 quickCalcStardustString += "<td></td>";
1426 } else if (stargemNet.indexOf("-") >= 0) {
1427 quickCalcStardustString += "<td style='color:red'>" + stargemNet + "</td>";
1428 } else {
1429 quickCalcStardustString += "<td style='color:lightgreen'>" + stargemNet + "</td>";
1430 quickCalcStardustBoxShadow = true;
1431 }
1432 if (abbreviate_number(totalPrice, 1) === 0) {
1433 quickCalcStardustString += "<td></td>";
1434 } else if (stargemNetPlusOne.indexOf("-") >= 0) {
1435 quickCalcStardustString += "<td style='color:red'>" + stargemNetPlusOne + "</td>";
1436 } else {
1437 quickCalcStardustString += "<td style='color:lightgreen'>" + stargemNetPlusOne + "</td>";
1438 }
1439 quickCalcStardustString += "</tr>";
1440 stargemNetMinusOne = abbreviate_number(24 * 12 * (((arrStargemOutput[0][1] - 1) * avgSdGainStardustPotion) - (arrStardustInput[0][3] + arrStardustInput[1][3] + lowestSmallVialPrice)), 1);
1441 stargemNet = abbreviate_number(24 * 12 * (((arrStargemOutput[0][1]) * avgSdGainStardustPotion) - (arrStardustInput[0][3] + arrStardustInput[1][3] + lowestSmallVialPrice)), 1);
1442 stargemNetPlusOne = abbreviate_number(24 * 12 * (((arrStargemOutput[0][1] + 1) * avgSdGainStardustPotion) - (arrStardustInput[0][3] + arrStardustInput[1][3] + lowestSmallVialPrice)), 1);
1443 quickCalcStardustString += "<tr>";
1444 quickCalcStardustString += "<td style='text-align:center;color:gold;'>24h</td>";
1445 totalPrice = 24 * 12 * (arrStardustInput[0][3] + arrStardustInput[1][3] + lowestSmallVialPrice);
1446 quickCalcStardustString += "<td>" + abbreviate_number(totalPrice, 1) + "</td>";
1447 if (abbreviate_number(totalPrice, 1) === 0) {
1448 quickCalcStardustString += "<td></td>";
1449 } else if (stargemNetMinusOne.indexOf("-") >= 0) {
1450 quickCalcStardustString += "<td style='color:red'>" + stargemNetMinusOne + "</td>";
1451 } else {
1452 quickCalcStardustString += "<td style='color:lightgreen'>" + stargemNetMinusOne + "</td>";
1453 quickCalcStardustBoxShadow = true;
1454 }
1455 if (abbreviate_number(totalPrice, 1) === 0) {
1456 quickCalcStardustString += "<td></td>";
1457 } else if (stargemNet.indexOf("-") >= 0) {
1458 quickCalcStardustString += "<td style='color:red'>" + stargemNet + "</td>";
1459 } else {
1460 quickCalcStardustString += "<td style='color:lightgreen'>" + stargemNet + "</td>";
1461 quickCalcStardustBoxShadow = true;
1462 }
1463 if (abbreviate_number(totalPrice, 1) === 0) {
1464 quickCalcStardustString += "<td></td>";
1465 } else if (stargemNetPlusOne.indexOf("-") >= 0) {
1466 quickCalcStardustString += "<td style='color:red'>" + stargemNetPlusOne + "</td>";
1467 } else {
1468 quickCalcStardustString += "<td style='color:lightgreen'>" + stargemNetPlusOne + "</td>";
1469 }
1470 quickCalcStardustString += "</tr>";
1471 quickCalcStardustString += "</tbody></table>";
1472 quickCalcStardustString += arrStardustInput[0][0] + ": " + abbreviate_number(dottedGreenLeafPrice, 0) + "<br>";
1473 quickCalcStardustString += arrStardustInput[1][0] + ": " + abbreviate_number(redMushroomPrice, 0) + "<br>";
1474 quickCalcStardustString += lowestSmallVialSource + ": " + abbreviate_number(lowestSmallVial, 0) + "<br><br>";
1475 quickCalcStardustString += "Avg SD: " + numberWithCommas(avgSdGainStardustPotion) + "<br>";
1476 var stardustPotionDurationDate = new Date(null);
1477 stardustPotionDurationDate.setSeconds(stardustPotionDuration);
1478 var stardustPotionDurationDateFormatted = stardustPotionDurationDate.toISOString().substr(14, 5);
1479 quickCalcStardustString += "Potion Duration: " + stardustPotionDurationDateFormatted;
1480 }
1481 if (arrStardustInput[0][1] != arrStardustInput[0][2]) quickCalcStardustString += "Not enough " + arrStardustInput[0][0] + " " + arrStardustInput[0][2] + "/" + arrStardustInput[0][1] + "<br>";
1482 if (arrStardustInput[1][1] != arrStardustInput[1][2]) quickCalcStardustString += "Not enough " + arrStardustInput[1][0] + " " + arrStardustInput[1][2] + "/" + arrStardustInput[1][1] + "<br>";
1483 //super stardust tooltip hover
1484 var limeLeafPrice = arrSuperStardustInput[0][3];
1485 var snapegrassPrice = arrSuperStardustInput[1][3];
1486 lowestSmallVialPrice = lowestSmallVial;
1487 if (boundBrewingKit == 1) {
1488 hasBrewingKit = true;
1489 for (i = 0; i < 2; i++) {
1490 arrSuperStardustInput[i][3] = Math.ceil(arrSuperStardustInput[i][3] / 1.1); // brewing kit 10% free ingredients
1491 }
1492 lowestSmallVialPrice = Math.ceil(lowestSmallVialPrice / 1.1); // brewing kit 10% free vial
1493 } else hasBrewingKit = false;
1494 quickCalcSuperStardustString = "";
1495 quickCalcSuperStardustBoxShadow = false;
1496 if (arrSuperStardustInput[0][1] == arrSuperStardustInput[0][2] && arrSuperStardustInput[1][1] == arrSuperStardustInput[1][2]) {
1497 quickCalcSuperStardustString += "<span style='float:left;padding:5px;'>S Stardust Profit</span>";
1498 if (hasBrewingKit) {
1499 quickCalcSuperStardustString += "<span style='float:right;padding:5px;color:green;'>+Brewing Kit</span>";
1500 } else quickCalcSuperStardustString += "<span style='float:right;padding:5px;color:black;'><s style='color:red'>Brewing Kit</s></span>";
1501 quickCalcSuperStardustString += "<br>";
1502 quickCalcSuperStardustString += "<table style='text-align:center;padding:0 2px;' class='top-bar'><tbody><tr style='text-align:center'><th></th><th>Cost</th><th style='color:silver'>" + (arrStargemOutput[0][1] - 1) + "</th><th>" + (arrStargemOutput[0][1]) + "</th><th style='color:silver'>" + (arrStargemOutput[0][1] + 1) + "</th></tr>";
1503 stargemNetMinusOne = abbreviate_number(((arrStargemOutput[0][1] - 1) * avgSdGainSuperStardustPotion) - (arrSuperStardustInput[0][3] + arrSuperStardustInput[1][3] + lowestSmallVialPrice), 1);
1504 stargemNet = abbreviate_number(((arrStargemOutput[0][1]) * avgSdGainSuperStardustPotion) - (arrSuperStardustInput[0][3] + arrSuperStardustInput[1][3] + lowestSmallVialPrice), 1);
1505 stargemNetPlusOne = abbreviate_number(((arrStargemOutput[0][1] + 1) * avgSdGainSuperStardustPotion) - (arrSuperStardustInput[0][3] + arrSuperStardustInput[1][3] + lowestSmallVialPrice), 1);
1506 quickCalcSuperStardustString += "<tr>";
1507 quickCalcSuperStardustString += "<td style='text-align:center'><img class='image-icon-20' src='images/superStardustPotion.png'></td>";
1508 totalPrice = (arrSuperStardustInput[0][3] + arrSuperStardustInput[1][3] + lowestSmallVialPrice);
1509 quickCalcSuperStardustString += "<td>" + abbreviate_number(totalPrice, 2) + "</td>";
1510 if (abbreviate_number(totalPrice, 1) === 0) {
1511 quickCalcSuperStardustString += "<td></td>";
1512 } else if (stargemNetMinusOne.indexOf("-") >= 0) {
1513 quickCalcSuperStardustString += "<td style='color:red'>" + stargemNetMinusOne + "</td>";
1514 } else {
1515 quickCalcSuperStardustString += "<td style='color:lightgreen'>" + stargemNetMinusOne + "</td>";
1516 quickCalcSuperStardustBoxShadow = true;
1517 }
1518 if (abbreviate_number(totalPrice, 1) === 0) {
1519 quickCalcSuperStardustString += "<td></td>";
1520 } else if (stargemNet.indexOf("-") >= 0) {
1521 quickCalcSuperStardustString += "<td style='color:red'>" + stargemNet + "</td>";
1522 } else {
1523 quickCalcSuperStardustString += "<td style='color:lightgreen'>" + stargemNet + "</td>";
1524 quickCalcSuperStardustBoxShadow = true;
1525 }
1526 if (abbreviate_number(totalPrice, 1) === 0) {
1527 quickCalcSuperStardustString += "<td></td>";
1528 } else if (stargemNetPlusOne.indexOf("-") >= 0) {
1529 quickCalcSuperStardustString += "<td style='color:red'>" + stargemNetPlusOne + "</td>";
1530 } else {
1531 quickCalcSuperStardustString += "<td style='color:lightgreen'>" + stargemNetPlusOne + "</td>";
1532 }
1533 quickCalcSuperStardustString += "</tr>";
1534 stargemNetMinusOne = abbreviate_number(24 * 12 * (((arrStargemOutput[0][1] - 1) * avgSdGainSuperStardustPotion) - (arrSuperStardustInput[0][3] + arrSuperStardustInput[1][3] + lowestSmallVialPrice)), 0);
1535 stargemNet = abbreviate_number(24 * 12 * (((arrStargemOutput[0][1]) * avgSdGainSuperStardustPotion) - (arrSuperStardustInput[0][3] + arrSuperStardustInput[1][3] + lowestSmallVialPrice)), 0);
1536 stargemNetPlusOne = abbreviate_number(24 * 12 * (((arrStargemOutput[0][1] + 1) * avgSdGainSuperStardustPotion) - (arrSuperStardustInput[0][3] + arrSuperStardustInput[1][3] + lowestSmallVialPrice)), 0);
1537 quickCalcSuperStardustString += "<tr>";
1538 quickCalcSuperStardustString += "<td style='text-align:center;color:gold;'>24h</td>";
1539 totalPrice = 24 * 12 * (arrSuperStardustInput[0][3] + arrSuperStardustInput[1][3] + lowestSmallVialPrice);
1540 quickCalcSuperStardustString += "<td>" + abbreviate_number(totalPrice, 0) + "</td>";
1541 if (abbreviate_number(totalPrice, 1) === 0) {
1542 quickCalcSuperStardustString += "<td></td>";
1543 } else if (stargemNetMinusOne.indexOf("-") >= 0) {
1544 quickCalcSuperStardustString += "<td style='color:red'>" + stargemNetMinusOne + "</td>";
1545 } else {
1546 quickCalcSuperStardustString += "<td style='color:lightgreen'>" + stargemNetMinusOne + "</td>";
1547 quickCalcSuperStardustBoxShadow = true;
1548 }
1549 if (abbreviate_number(totalPrice, 1) === 0) {
1550 quickCalcSuperStardustString += "<td></td>";
1551 } else if (stargemNet.indexOf("-") >= 0) {
1552 quickCalcSuperStardustString += "<td style='color:red'>" + stargemNet + "</td>";
1553 } else {
1554 quickCalcSuperStardustString += "<td style='color:lightgreen'>" + stargemNet + "</td>";
1555 quickCalcSuperStardustBoxShadow = true;
1556 }
1557 if (abbreviate_number(totalPrice, 1) === 0) {
1558 quickCalcSuperStardustString += "<td></td>";
1559 } else if (stargemNetPlusOne.indexOf("-") >= 0) {
1560 quickCalcSuperStardustString += "<td style='color:red'>" + stargemNetPlusOne + "</td>";
1561 } else {
1562 quickCalcSuperStardustString += "<td style='color:lightgreen'>" + stargemNetPlusOne + "</td>";
1563 }
1564 quickCalcSuperStardustString += "</tr>";
1565 quickCalcSuperStardustString += "</tbody></table>";
1566 quickCalcSuperStardustString += arrSuperStardustInput[0][0] + ": " + abbreviate_number(limeLeafPrice, 0) + "<br>";
1567 quickCalcSuperStardustString += arrSuperStardustInput[1][0] + ": " + abbreviate_number(snapegrassPrice, 0) + "<br>";
1568 quickCalcSuperStardustString += lowestSmallVialSource + ": " + abbreviate_number(lowestSmallVial, 0) + "<br><br>";
1569 quickCalcSuperStardustString += "Avg SD: " + numberWithCommas(avgSdGainSuperStardustPotion) + "<br>";
1570 var superStardustPotionDurationDate = new Date(null);
1571 superStardustPotionDurationDate.setSeconds(superStardustPotionDuration);
1572 var superStardustPotionDurationDateFormatted = superStardustPotionDurationDate.toISOString().substr(14, 5);
1573 quickCalcSuperStardustString += "Potion Duration: " + superStardustPotionDurationDateFormatted;
1574 }
1575 if (arrSuperStardustInput[0][1] != arrSuperStardustInput[0][2]) quickCalcSuperStardustString += "Not enough " + arrSuperStardustInput[0][0] + " " + arrSuperStardustInput[0][2] + "/" + arrSuperStardustInput[0][1] + "<br>";
1576 if (arrSuperStardustInput[1][1] != arrSuperStardustInput[1][2]) quickCalcSuperStardustString += "Not enough " + arrSuperStardustInput[1][0] + " " + arrSuperStardustInput[1][2] + "/" + arrSuperStardustInput[1][1] + "<br>";
1577 //stargem tooltip hover
1578 if (arrStargemInput[6][2] == arrStargemInput[6][1] && arrStargemInput[7][2] == arrStargemInput[7][1]) { // enough both
1579 if (arrStargemInput[7][3] <= arrStargemInput[6][3]) {
1580 lowestVial = arrStargemInput[7][3];
1581 lowestVialSource = arrStargemInput[7][0];
1582 } else if (arrStargemInput[6][3] < arrStargemInput[7][3]) {
1583 lowestVial = arrStargemInput[6][3];
1584 lowestVialSource = arrStargemInput[6][0];
1585 }
1586 } else if (arrStargemInput[6][2] == arrStargemInput[6][1] && arrStargemInput[7][2] != arrStargemInput[7][1]) { // sand only
1587 lowestVial = arrStargemInput[6][3];
1588 lowestVialSource = arrStargemInput[6][0];
1589 } else if (arrStargemInput[6][2] != arrStargemInput[6][1] && arrStargemInput[7][2] == arrStargemInput[7][1]) { // glass only
1590 lowestVial = arrStargemInput[7][3];
1591 lowestVialSource = arrStargemInput[7][0];
1592 } else if (arrStargemInput[6][2] != arrStargemInput[6][1] && arrStargemInput[7][2] != arrStargemInput[7][1]) { // not enough both
1593 lowestVial = 0;
1594 lowestVialSource = "<span style='color:red;background-color:black;'>ERR: Sand & Glass < 25</span>";
1595 }
1596 var blewitMushroomPrice = arrStargemInput[0][3];
1597 var goldLeafPrice = arrStargemInput[1][3];
1598 var lowestVialPrice = lowestVial;
1599 if (boundBrewingKit == 1) {
1600 hasBrewingKit = true;
1601 for (i = 0; i < 2; i++) {
1602 arrStargemInput[i][3] = Math.ceil(arrStargemInput[i][3] / 1.1); // brewing kit 10% free ingredients
1603 }
1604 lowestVialPrice = Math.ceil(lowestVialPrice / 1.1); // brewing kit 10% free vial
1605 } else hasBrewingKit = false;
1606 quickCalcStargemString = "";
1607 quickCalcStargemBoxShadow = false;
1608 if (arrStargemInput[0][1] == arrStargemInput[0][2] && arrStargemInput[1][1] == arrStargemInput[1][2]) {
1609 quickCalcStargemString += "<span style='float:left;padding:5px;'>Stargem Profit</span>";
1610 if (hasBrewingKit) {
1611 quickCalcStargemString += "<span style='float:right;padding:5px;color:green;'>+Brewing Kit</span>";
1612 } else quickCalcStargemString += "<span style='float:right;padding:5px;color:black;'><s style='color:red'>Brewing Kit</s></span>";
1613 quickCalcStargemString += "<br>";
1614 quickCalcStargemString += "<table style='text-align:center;padding:0 2px;' class='top-bar'><tbody><tr style='text-align:center'><th>Gem</th><th>Cost</th><th style='color:silver'>" + (arrStargemOutput[0][1] - 1) + "</th><th>" + (arrStargemOutput[0][1]) + "</th><th style='color:silver'>" + (arrStargemOutput[0][1] + 1) + "</th></tr>";
1615 for (a = 2; a < arrStargemInput.length - 2; a++) {
1616 if (a == 5) {
1617 stargemNetMinusOne = abbreviate_number(((arrStargemOutput[0][1] - 1) * (a * 120000)) - (arrStargemInput[a][3] + arrStargemInput[0][3] + arrStargemInput[1][3] + lowestVialPrice), 1);
1618 stargemNet = abbreviate_number(((arrStargemOutput[0][1]) * (a * 120000)) - (arrStargemInput[a][3] + arrStargemInput[0][3] + arrStargemInput[1][3] + lowestVialPrice), 1);
1619 stargemNetPlusOne = abbreviate_number(((arrStargemOutput[0][1] + 1) * (a * 120000)) - (arrStargemInput[a][3] + arrStargemInput[0][3] + arrStargemInput[1][3] + lowestVialPrice), 1);
1620 } else {
1621 stargemNetMinusOne = abbreviate_number(((arrStargemOutput[0][1] - 1) * ((a - 1) * 100000)) - (arrStargemInput[a][3] + arrStargemInput[0][3] + arrStargemInput[1][3] + lowestVialPrice), 1);
1622 stargemNet = abbreviate_number((arrStargemOutput[0][1] * ((a - 1) * 100000)) - (arrStargemInput[a][3] + arrStargemInput[0][3] + arrStargemInput[1][3] + lowestVialPrice), 1);
1623 stargemNetPlusOne = abbreviate_number(((arrStargemOutput[0][1] + 1) * ((a - 1) * 100000)) - (arrStargemInput[a][3] + arrStargemInput[0][3] + arrStargemInput[1][3] + lowestVialPrice), 1);
1624 }
1625 quickCalcStargemString += "<tr>";
1626 quickCalcStargemString += "<td style='text-align:center'><img class='image-icon-20' src='images/" + itemNameFix(arrStargemInput[a][0]) + ".png'></td>";
1627 if (arrStargemInput[a][2] === 0) {
1628 quickCalcStargemString += "<td></td><td></td><td></td><td></td>";
1629 } else {
1630 quickCalcStargemString += "<td>" + abbreviate_number(arrStargemInput[a][3], 2) + "</td>";
1631 if (abbreviate_number(arrStargemInput[a][3], 1) === 0) {
1632 quickCalcStargemString += "<td></td>";
1633 } else if (stargemNetMinusOne.indexOf("-") >= 0) {
1634 quickCalcStargemString += "<td style='color:red'>" + stargemNetMinusOne + "</td>";
1635 } else {
1636 quickCalcStargemString += "<td style='color:lightgreen'>" + stargemNetMinusOne + "</td>";
1637 quickCalcStargemBoxShadow = true;
1638 }
1639 if (abbreviate_number(arrStargemInput[a][3], 1) === 0) {
1640 quickCalcStargemString += "<td></td>";
1641 } else if (stargemNet.indexOf("-") >= 0) {
1642 quickCalcStargemString += "<td style='color:red'>" + stargemNet + "</td>";
1643 } else {
1644 quickCalcStargemString += "<td style='color:lightgreen'>" + stargemNet + "</td>";
1645 quickCalcStargemBoxShadow = true;
1646 }
1647 if (abbreviate_number(arrStargemInput[a][3], 1) === 0) {
1648 quickCalcStargemString += "<td></td>";
1649 } else if (stargemNetPlusOne.indexOf("-") >= 0) {
1650 quickCalcStargemString += "<td style='color:red'>" + stargemNetPlusOne + "</td>";
1651 } else {
1652 quickCalcStargemString += "<td style='color:lightgreen'>" + stargemNetPlusOne + "</td>";
1653 }
1654 }
1655 quickCalcStargemString += "</tr>";
1656 }
1657 quickCalcStargemString += "</tbody></table>";
1658 quickCalcStargemString += arrStargemInput[0][0] + ": " + abbreviate_number(blewitMushroomPrice, 0) + "<br>";
1659 quickCalcStargemString += arrStargemInput[1][0] + ": " + abbreviate_number(goldLeafPrice, 0) + "<br>";
1660 quickCalcStargemString += lowestVialSource + ": " + abbreviate_number(lowestVial, 0) + "<br>";
1661 }
1662 if (arrStargemInput[0][1] != arrStargemInput[0][2]) quickCalcStargemString += "Not enough " + arrStargemInput[0][0] + " " + arrStargemInput[0][2] + "/" + arrStargemInput[0][1] + "<br>";
1663 if (arrStargemInput[1][1] != arrStargemInput[1][2]) quickCalcStargemString += "Not enough " + arrStargemInput[1][0] + " " + arrStargemInput[1][2] + "/" + arrStargemInput[1][1] + "<br>";
1664 //essence tooltip hover
1665 if (boundBrewingKit == 1) {
1666 hasBrewingKit = true;
1667 for (i = 0; i < 2; i++) {
1668 arrEssenceInput[i][3] = Math.ceil(arrEssenceInput[i][3] / 1.1); // brewing kit 10% free ingredients
1669 }
1670 lowestSmallVialPrice = Math.ceil(lowestSmallVialPrice / 1.1); // brewing kit 10% free vial
1671 } else hasBrewingKit = false;
1672 quickCalcEssenceString = "";
1673 quickCalcEssenceBoxShadow = false;
1674 if (arrEssenceInput[0][1] == arrEssenceInput[0][2] && arrEssenceInput[1][1] == arrEssenceInput[1][2]) {
1675 quickCalcEssenceString += "<span style='float:left;padding:5px;'>Essence Profit</span>";
1676 if (hasBrewingKit) {
1677 quickCalcEssenceString += "<span style='float:right;padding:5px;color:green;'>+Brewing Kit</span>";
1678 } else quickCalcEssenceString += "<span style='float:right;padding:5px;color:black;'><s style='color:red'>Brewing Kit</s></span>";
1679 quickCalcEssenceString += "<br>";
1680 quickCalcEssenceString += "<table style='text-align:center;padding:0 2px;' class='top-bar'><tbody><tr style='text-align:center'><th></th><th>Cost</th><th>Avg Ess</th><th>Avg Profit</th></tr>";
1681 quickCalcEssenceString += "<tr>";
1682 quickCalcEssenceString += "<td style='text-align:center'><img class='image-icon-20' src='images/essencePotion.png'></td>";
1683 totalPrice = (arrEssenceInput[0][3] + arrEssenceInput[1][3] + lowestSmallVialPrice);
1684 var essenceProfit = essencePotionAvgEssence * arrMarketItems.essence[0].price - totalPrice;
1685 quickCalcEssenceString += "<td>" + abbreviate_number(totalPrice, 2) + "</td>";
1686 if (abbreviate_number(totalPrice, 1) === 0) {
1687 quickCalcEssenceString += "<td></td>";
1688 } else if (abbreviate_number(essenceProfit).indexOf("-") >= 0) {
1689 quickCalcEssenceString += "<td style='color:red'>" + Number(essencePotionAvgEssence.toFixed(2)) + "</td>";
1690 } else {
1691 quickCalcEssenceString += "<td style='color:lightgreen'>" + Number(essencePotionAvgEssence.toFixed(2)) + "</td>";
1692 quickCalcEssenceBoxShadow = true;
1693 }
1694 if (abbreviate_number(totalPrice, 1) === 0) {
1695 quickCalcEssenceString += "<td></td>";
1696 } else if (abbreviate_number(essenceProfit).indexOf("-") >= 0) {
1697 quickCalcEssenceString += "<td style='color:red'>" + abbreviate_number(Number(essenceProfit.toFixed(2)), 2) + "</td>";
1698 } else {
1699 quickCalcEssenceString += "<td style='color:lightgreen'>" + abbreviate_number(Number(essenceProfit.toFixed(2)), 2) + "</td>";
1700 quickCalcEssenceBoxShadow = true;
1701 }
1702 quickCalcEssenceString += "<tr>";
1703 quickCalcEssenceString += "<td style='text-align:center;color:gold;'>24h</td>";
1704 totalPrice = (24 * 60 * 60 / essencePotionDuration) * (arrEssenceInput[0][3] + arrEssenceInput[1][3] + lowestSmallVialPrice);
1705 var essenceProfit24 = (24 * 60 * 60 / essencePotionDuration) * essencePotionAvgEssence * arrMarketItems.essence[0].price - totalPrice;
1706 quickCalcEssenceString += "<td>" + abbreviate_number(totalPrice, 2) + "</td>";
1707 if (abbreviate_number(totalPrice, 1) === 0) {
1708 quickCalcEssenceString += "<td></td>";
1709 } else if (abbreviate_number(essenceProfit).indexOf("-") >= 0) {
1710 quickCalcEssenceString += "<td style='color:red'>" + Number(((24 * 60 * 60 / essencePotionDuration) * essencePotionAvgEssence).toFixed(2)) + "</td>";
1711 } else {
1712 quickCalcEssenceString += "<td style='color:lightgreen'>" + Number(((24 * 60 * 60 / essencePotionDuration) * essencePotionAvgEssence).toFixed(2)) + "</td>";
1713 quickCalcEssenceBoxShadow = true;
1714 }
1715 if (abbreviate_number(totalPrice, 1) === 0) {
1716 quickCalcEssenceString += "<td></td>";
1717 } else if (abbreviate_number(essenceProfit).indexOf("-") >= 0) {
1718 quickCalcEssenceString += "<td style='color:red'>" + abbreviate_number(Number(essenceProfit24.toFixed(0)), 1) + "</td>"; //avg proft
1719 } else {
1720 quickCalcEssenceString += "<td style='color:lightgreen'>" + abbreviate_number(Number(essenceProfit24.toFixed(0)), 1) + "</td>";
1721 quickCalcEssenceBoxShadow = true;
1722 }
1723 quickCalcEssenceString += "</tr>";
1724 quickCalcEssenceString += "</tbody></table>";
1725 dottedGreenLeafPrice = arrEssenceInput[0][3];
1726 blewitMushroomPrice = arrEssenceInput[1][3];
1727 quickCalcEssenceString += arrEssenceInput[0][0] + ": " + abbreviate_number(dottedGreenLeafPrice, 0) + "<br>";
1728 quickCalcEssenceString += arrEssenceInput[1][0] + ": " + abbreviate_number(blewitMushroomPrice, 0) + "<br>";
1729 quickCalcEssenceString += lowestSmallVialSource + ": " + abbreviate_number(lowestSmallVial, 0) + "<br>";
1730 quickCalcEssenceString += "<br>";
1731 quickCalcEssenceString += "Ess Chance: 1/" + numberWithCommas(essencePotionEssenceChance) + "/tick<br>";
1732 var essencePotionDurationDate = new Date(null);
1733 essencePotionDurationDate.setSeconds(essencePotionDuration);
1734 var essencePotionDurationFormatted = essencePotionDurationDate.toISOString().substr(11, 8);
1735 quickCalcEssenceString += "Potion Duration: " + essencePotionDurationFormatted;
1736 }
1737 if (arrEssenceInput[0][1] != arrEssenceInput[0][2]) quickCalcEssenceString += "Not enough " + arrEssenceInput[0][0] + " " + arrEssenceInput[0][2] + "/" + arrEssenceInput[0][1] + "<br>";
1738 if (arrEssenceInput[1][1] != arrEssenceInput[1][2]) quickCalcEssenceString += "Not enough " + arrEssenceInput[1][0] + " " + arrEssenceInput[1][2] + "/" + arrEssenceInput[1][1] + "<br>";
1739 //Super Essence tooltip hover
1740 if (boundBrewingKit == 1) {
1741 hasBrewingKit = true;
1742 for (i = 0; i < 2; i++) {
1743 arrSuperEssenceInput[i][3] = Math.ceil(arrSuperEssenceInput[i][3] / 1.1); // brewing kit 10% free ingredients
1744 }
1745 lowestVialPrice = Math.ceil(lowestVialPrice / 1.1); // brewing kit 10% free vial
1746 } else hasBrewingKit = false;
1747 quickCalcSuperEssenceString = "";
1748 quickCalcSuperEssenceBoxShadow = false;
1749 if (arrSuperEssenceInput[0][1] == arrSuperEssenceInput[0][2] && arrSuperEssenceInput[1][1] == arrSuperEssenceInput[1][2]) {
1750 quickCalcSuperEssenceString += "<span style='float:left;padding:5px;'>S Ess Profit</span>";
1751 if (hasBrewingKit) {
1752 quickCalcSuperEssenceString += "<span style='float:right;padding:5px;color:green;'>+Brewing Kit</span>";
1753 } else quickCalcSuperEssenceString += "<span style='float:right;padding:5px;color:black;'><s style='color:red'>Brewing Kit</s></span>";
1754 quickCalcSuperEssenceString += "<br>";
1755 quickCalcSuperEssenceString += "<table style='text-align:center;padding:0 2px;' class='top-bar'><tbody><tr style='text-align:center'><th></th><th>Cost</th><th>Avg Ess</th><th>Avg Profit</th></tr>";
1756 quickCalcSuperEssenceString += "<tr>";
1757 quickCalcSuperEssenceString += "<td style='text-align:center'><img class='image-icon-20' src='images/superEssencePotion.png'></td>";
1758 totalPrice = (arrSuperEssenceInput[0][3] + arrSuperEssenceInput[1][3] + lowestVialPrice);
1759 var superEssenceProfit = superEssencePotionAvgEssence * arrMarketItems.essence[0].price - totalPrice;
1760 quickCalcSuperEssenceString += "<td>" + abbreviate_number(totalPrice, 2) + "</td>";
1761 if (abbreviate_number(totalPrice, 1) === 0) {
1762 quickCalcSuperEssenceString += "<td></td>";
1763 } else if (abbreviate_number(superEssenceProfit).indexOf("-") >= 0) {
1764 quickCalcSuperEssenceString += "<td style='color:red'>" + Number(superEssencePotionAvgEssence.toFixed(2)) + "</td>";
1765 } else {
1766 quickCalcSuperEssenceString += "<td style='color:lightgreen'>" + Number(superEssencePotionAvgEssence.toFixed(2)) + "</td>";
1767 quickCalcSuperEssenceBoxShadow = true;
1768 }
1769 if (abbreviate_number(totalPrice, 1) === 0) {
1770 quickCalcSuperEssenceString += "<td></td>";
1771 } else if (abbreviate_number(superEssenceProfit).indexOf("-") >= 0) {
1772 quickCalcSuperEssenceString += "<td style='color:red'>" + abbreviate_number(Number(superEssenceProfit.toFixed(2)), 2) + "</td>";
1773 } else {
1774 quickCalcSuperEssenceString += "<td style='color:lightgreen'>" + abbreviate_number(Number(superEssenceProfit.toFixed(2)), 2) + "</td>";
1775 quickCalcSuperEssenceBoxShadow = true;
1776 }
1777 quickCalcSuperEssenceString += "<tr>";
1778 quickCalcSuperEssenceString += "<td style='text-align:center;color:gold;'>24h</td>";
1779 totalPrice = (24 * 60 * 60 / superEssencePotionDuration) * (arrSuperEssenceInput[0][3] + arrSuperEssenceInput[1][3] + lowestSmallVialPrice);
1780 var superEssenceProfit24 = (24 * 60 * 60 / superEssencePotionDuration) * superEssencePotionAvgEssence * arrMarketItems.essence[0].price - totalPrice;
1781 quickCalcSuperEssenceString += "<td>" + abbreviate_number(totalPrice, 2) + "</td>";
1782 if (abbreviate_number(totalPrice, 1) === 0) {
1783 quickCalcSuperEssenceString += "<td></td>";
1784 } else if (abbreviate_number(superEssenceProfit).indexOf("-") >= 0) {
1785 quickCalcSuperEssenceString += "<td style='color:red'>" + Number(((24 * 60 * 60 / superEssencePotionDuration) * superEssencePotionAvgEssence).toFixed(2)) + "</td>";
1786 } else {
1787 quickCalcSuperEssenceString += "<td style='color:lightgreen'>" + Number(((24 * 60 * 60 / superEssencePotionDuration) * superEssencePotionAvgEssence).toFixed(2)) + "</td>";
1788 quickCalcSuperEssenceBoxShadow = true;
1789 }
1790 if (abbreviate_number(totalPrice, 1) === 0) {
1791 quickCalcSuperEssenceString += "<td></td>";
1792 } else if (abbreviate_number(superEssenceProfit).indexOf("-") >= 0) {
1793 quickCalcSuperEssenceString += "<td style='color:red'>" + abbreviate_number(Number(superEssenceProfit24.toFixed(0)), 1) + "</td>"; //avg proft
1794 } else {
1795 quickCalcSuperEssenceString += "<td style='color:lightgreen'>" + abbreviate_number(Number(superEssenceProfit24.toFixed(0)), 1) + "</td>";
1796 quickCalcSuperEssenceBoxShadow = true;
1797 }
1798 quickCalcSuperEssenceString += "</tr>";
1799 quickCalcSuperEssenceString += "</tbody></table>";
1800 dottedGreenLeafPrice = arrSuperEssenceInput[0][3];
1801 blewitMushroomPrice = arrSuperEssenceInput[1][3];
1802 quickCalcSuperEssenceString += arrSuperEssenceInput[0][0] + ": " + abbreviate_number(dottedGreenLeafPrice, 0) + "<br>";
1803 quickCalcSuperEssenceString += arrSuperEssenceInput[1][0] + ": " + abbreviate_number(blewitMushroomPrice, 0) + "<br>";
1804 quickCalcSuperEssenceString += lowestVialSource + ": " + abbreviate_number(lowestVial, 0) + "<br>";
1805 quickCalcSuperEssenceString += "<br>";
1806 quickCalcSuperEssenceString += "Ess Chance: 1/" + numberWithCommas(superEssencePotionEssenceChance) + "/tick<br>";
1807 var superEssencePotionDurationDate = new Date(null);
1808 superEssencePotionDurationDate.setSeconds(superEssencePotionDuration); // specify value for SECONDS here
1809 var superEssencePotionDurationFormatted = superEssencePotionDurationDate.toISOString().substr(11, 8);
1810 quickCalcSuperEssenceString += "Potion Duration: " + superEssencePotionDurationFormatted;
1811 }
1812 if (arrSuperEssenceInput[0][1] != arrSuperEssenceInput[0][2]) quickCalcSuperEssenceString += "Not enough " + arrSuperEssenceInput[0][0] + " " + arrSuperEssenceInput[0][2] + "/" + arrSuperEssenceInput[0][1] + "<br>";
1813 if (arrSuperEssenceInput[1][1] != arrSuperEssenceInput[1][2]) quickCalcSuperEssenceString += "Not enough " + arrSuperEssenceInput[1][0] + " " + arrSuperEssenceInput[1][2] + "/" + arrSuperEssenceInput[1][1] + "<br>";
1814 if (quickCalcStardustBoxShadow && stardustProfitGreenBox) {
1815 document.getElementById("quickCalcStardust").style.boxShadow = "0 0 40px -10px rgba(0,255,0,1) inset,0 0 5px 0px rgba(0,255,0,1)";
1816 } else document.getElementById("quickCalcStardust").style.boxShadow = "";
1817 if (quickCalcSuperStardustBoxShadow && superStardustProfitGreenBox) {
1818 document.getElementById("quickCalcSuperStardust").style.boxShadow = "0 0 40px -10px rgba(0,255,0,1) inset,0 0 5px 0px rgba(0,255,0,1)";
1819 } else document.getElementById("quickCalcSuperStardust").style.boxShadow = "";
1820 if (quickCalcStargemBoxShadow && stargemProfitGreenBox) {
1821 document.getElementById("quickCalcStargem").style.boxShadow = "0 0 40px -10px rgba(0,255,0,1) inset,0 0 5px 0px rgba(0,255,0,1)";
1822 } else document.getElementById("quickCalcStargem").style.boxShadow = "";
1823 if (quickCalcEssenceBoxShadow && essenceProfitGreenBox) {
1824 document.getElementById("quickCalcEssence").style.boxShadow = "0 0 40px -10px rgba(0,255,0,1) inset,0 0 5px 0px rgba(0,255,0,1)";
1825 } else document.getElementById("quickCalcEssence").style.boxShadow = "";
1826 if (quickCalcSuperEssenceBoxShadow && superEssenceProfitGreenBox) {
1827 document.getElementById("quickCalcSuperEssence").style.boxShadow = "0 0 40px -10px rgba(0,255,0,1) inset,0 0 5px 0px rgba(0,255,0,1)";
1828 } else document.getElementById("quickCalcSuperEssence").style.boxShadow = "";
1829 //heat on market table
1830 cheapestHeat = arrQuickCalcHeat[1];
1831 if (showCheapestHeat && arrQuickCalcHeat[1] <= tedStoredSettings.showCheapestHeat.showAt) {
1832 var quickCalcBestHeat = document.createElement("img");
1833 quickCalcBestHeat.setAttribute("style", "float:left;padding-left:15px;");
1834 quickCalcBestHeat.setAttribute("src", "images/icons/fire.png");
1835 quickCalcBestHeat.setAttribute("class", "image-icon-20");
1836 quickCalcBestHeat.setAttribute("title", "Cheapest heat @ " + numberWithCommas(arrQuickCalcHeat[1]));
1837 document.getElementById("market-table").rows[arrQuickCalcHeat[5]].style.display = "table-row";
1838 if (document.getElementById("market-table").rows[arrQuickCalcHeat[5]].style.background === "") {
1839 document.getElementById("market-table").rows[arrQuickCalcHeat[5]].style.background = "linear-gradient(#f2f2f2," + colorLuminance("#f2f2f2", -0.1) + ")";
1840 }
1841 document.getElementById("market-table").rows[arrQuickCalcHeat[5]].cells[0].insertBefore(quickCalcBestHeat, document.getElementById("market-table").rows[arrQuickCalcHeat[5]].cells[0].childNodes[1]);
1842 }
1843 //energy on market table
1844 cheapestEnergy = arrQuickCalcEnergy[1];
1845 if (showCheapestEnergy && arrQuickCalcEnergy[1] <= tedStoredSettings.showCheapestEnergy.showAt) {
1846 var quickCalcBestEnergy = document.createElement("img");
1847 quickCalcBestEnergy.setAttribute("style", "float:left;padding-left:15px;");
1848 quickCalcBestEnergy.setAttribute("src", "images/steak.png");
1849 quickCalcBestEnergy.setAttribute("class", "image-icon-20");
1850 quickCalcBestEnergy.setAttribute("title", "Cheapest energy @ " + numberWithCommas(arrQuickCalcEnergy[1]));
1851 document.getElementById("market-table").rows[arrQuickCalcEnergy[5]].style.display = "table-row";
1852 if (document.getElementById("market-table").rows[arrQuickCalcEnergy[5]].style.background === "") {
1853 document.getElementById("market-table").rows[arrQuickCalcEnergy[5]].style.background = "linear-gradient(#f2f2f2," + colorLuminance("#f2f2f2", -0.1) + ")";
1854 }
1855 document.getElementById("market-table").rows[arrQuickCalcEnergy[5]].cells[0].insertBefore(quickCalcBestEnergy, document.getElementById("market-table").rows[arrQuickCalcEnergy[5]].cells[0].childNodes[1]);
1856 }
1857 //bonemeal on market table
1858 cheapestBonemeal = arrQuickCalcBonemeal[1];
1859 if (showCheapestBonemeal && arrQuickCalcBonemeal[1] <= tedStoredSettings.showCheapestBonemeal.showAt) {
1860 var quickCalcBestBonemeal = document.createElement("img");
1861 quickCalcBestBonemeal.setAttribute("style", "float:left;padding-left:15px;");
1862 quickCalcBestBonemeal.setAttribute("src", "images/filledBonemealBin.png");
1863 quickCalcBestBonemeal.setAttribute("class", "image-icon-20");
1864 quickCalcBestBonemeal.setAttribute("title", "Cheapest bonemeal @ " + numberWithCommas(arrQuickCalcBonemeal[1]));
1865 document.getElementById("market-table").rows[arrQuickCalcBonemeal[5]].style.display = "table-row";
1866 if (document.getElementById("market-table").rows[arrQuickCalcBonemeal[5]].style.background === "") {
1867 document.getElementById("market-table").rows[arrQuickCalcBonemeal[5]].style.background = "linear-gradient(#f2f2f2," + colorLuminance("#f2f2f2", -0.1) + ")";
1868 }
1869 document.getElementById("market-table").rows[arrQuickCalcBonemeal[5]].cells[0].insertBefore(quickCalcBestBonemeal, document.getElementById("market-table").rows[arrQuickCalcBonemeal[5]].cells[0].childNodes[1]);
1870 }
1871 }
1872 }
1873
1874 function oreAverageButtonClickAction() {
1875 if (oreAverageOn === true) {
1876 oreAverageOn = false;
1877 oreAverageElement.style.display = "none";
1878 document.getElementById("oreAverageButton").innerHTML = "oreAverageText: OFF";
1879 } else if (oreAverageOn === false) {
1880 oreAverageOn = true;
1881 oreAverageMain();
1882 document.getElementById("oreAverageButton").innerHTML = "oreAverageText: ON";
1883 }
1884 }
1885
1886 window.timeSince = function(date) {
1887 if (typeof date !== 'object') {
1888 date = new Date(date);
1889 }
1890 var seconds = Math.floor((new Date() - date) / 1000);
1891 var intervalType;
1892
1893 var interval = Math.floor(seconds / 31536000);
1894 if (interval >= 1) {
1895 intervalType = 'year';
1896 } else {
1897 interval = Math.floor(seconds / 2592000);
1898 if (interval >= 1) {
1899 intervalType = 'month';
1900 } else {
1901 interval = Math.floor(seconds / 86400);
1902 if (interval >= 1) {
1903 intervalType = 'day';
1904 } else {
1905 interval = Math.floor(seconds / 3600);
1906 if (interval >= 1) {
1907 intervalType = "hour";
1908 } else {
1909 interval = Math.floor(seconds / 60);
1910 if (interval >= 1) {
1911 intervalType = "minute";
1912 } else {
1913 interval = seconds;
1914 intervalType = "second";
1915 }
1916 }
1917 }
1918 }
1919 }
1920 if (interval > 1 || interval === 0) {
1921 intervalType += 's';
1922 }
1923 return interval + ' ' + intervalType;
1924 };
1925
1926 // START OF MINIGAMES
1927
1928 window.poker_shuffle = function(array) {
1929 //Fisher-Yates shuffle
1930 var m = array.length, t, i;
1931 while (m) {
1932 // pick a remaining element…
1933 i = Math.floor(Math.random() * m--); // then decrease m
1934 // and swap it with the current element
1935 t = array[m];
1936 array[m] = array[i];
1937 array[i] = t;
1938 }
1939 return array;
1940 };
1941
1942 window.poker_newDeck = function(gameType) {
1943 var ranks = ["A","K","Q","J","T",
1944 "9","8","7","6","5","4","3","2"];
1945 var suits = ["s", "h", "c", "d"];
1946 if (gameType == "tenplus") {
1947 ranks = ["A","K","Q","J","T"];
1948 }
1949 var deckArray = [];
1950 for (let s = 0; s < suits.length; s++) {
1951 for (let r = 0; r < ranks.length; r++) {
1952 let card = String(ranks[r]) + String(suits[s]);
1953 deckArray.push(card);
1954 }
1955 }
1956 return deckArray;
1957 };
1958
1959 window.countMatches = function(str, search) {
1960 str = String(str);
1961 var regExp = new RegExp(search, "gi");
1962 return (str.match(regExp) || []).length;
1963 };
1964
1965 window.loadCard = function(card, idToAppend) {
1966 let rank = card[0];
1967 let suit = card[1];
1968 let suits = {
1969 "s": {
1970 icon: "â™ ",
1971 solidColor: "black",
1972 weakColor: "rgb(230, 230, 230)",
1973 },
1974 "h": {
1975 icon: "♥",
1976 solidColor: "red",
1977 weakColor: "rgb(255, 230, 230)",
1978 },
1979 "c": {
1980 icon: "♣",
1981 solidColor: "green",
1982 weakColor: "rgb(230, 255, 230)",
1983 },
1984 "d": {
1985 icon: "♦",
1986 solidColor: "blue",
1987 weakColor: "rgb(230, 230, 255)",
1988 },
1989 "?": {
1990 icon: "",
1991 solidColor: "gold",
1992 weakColor: "black",
1993 },
1994 "*": {
1995 icon: "*",
1996 solidColor: "gold",
1997 weakColor: "black",
1998 },
1999 };
2000 let icon = suits[suit].icon;
2001 let solidColor = suits[suit].solidColor;
2002 let weakColor = suits[suit].weakColor;
2003 var svg_container = document.createElementNS("http://www.w3.org/2000/svg", "svg");
2004 svg_container.setAttribute("width", "80");
2005 svg_container.setAttribute("height", "112");
2006 svg_container.setAttribute("id", "tmg_pokerCard_"+card);
2007 let cardBackground = '<rect x="0" y="0" rx="8" ry="8"style="width:80;height:112;stroke:black;stroke-width:1px;fill:'+weakColor+'"></rect>';
2008 if (suit == "?") {
2009 /*cardBackground = '<rect x="0" y="0" rx="8" ry="8"style="width:80;height:112;stroke:black;stroke-width:1px;fill:'+weakColor+'"></rect>' +
2010 '<pattern id="diagonalHatch" patternUnits="userSpaceOnUse" width="8" height="8"><path d="M-1 1l2-2M0 4l4-4M3 5l2-2" style="stroke:yellow; stroke-width:1"></path></pattern>' +
2011 '<rect x="10" y="10" fill="url(#diagonalHatch)" style="width:60;height:92"></rect>'; */
2012 }
2013 let outerLine = '<polyline points="10,20 10,102 70,102 70,10 32,10" style="fill:none;stroke-width:1;stroke:#d2d2d2"></polyline>';
2014 let upperLeftText = '<text x="5" y="15" font-family="Monaco" font-size="15" text-anchor="left" style="fill:'+solidColor+';stroke-width:1;cursor:default;user-select:none">'+rank+' '+icon+'</text>';
2015 let middleText = '<text x="40" y="76" font-family="Monaco" font-size="60" text-anchor="middle" style="fill:'+solidColor+';stroke-width:1;cursor:default;user-select:none">'+rank+'</text>';
2016 svg_container.innerHTML = "" + cardBackground + outerLine + upperLeftText + middleText;
2017 document.getElementById(idToAppend).appendChild(svg_container);
2018 };
2019
2020 function minigamesButtonClickAction() {
2021 if (minigamesOn === true) {
2022 minigamesOn = false;
2023 document.getElementById("gameWrapper").style.display = "none";
2024 document.getElementById("minigamesButton").innerHTML = "Minigames: Minimised";
2025 } else if (minigamesOn === false) {
2026 minigamesOn = true;
2027 document.getElementById("gameWrapper").style.display = "flex";
2028 document.getElementById("minigamesButton").innerHTML = "Minigames: Open";
2029 if (minigameMyStatus != "ingame") {
2030 if (document.getElementById("inputOpp")) {
2031 document.getElementById("inputOpp").focus();
2032 }
2033 }
2034 }
2035 }
2036 window.minigameClose = function() {
2037 minigamesButtonClickAction();
2038 };
2039 window.declineChallenge = function(opponent, game) {
2040 if (opponent != window.username) {
2041 sendp2p(opponent, "CHALLENGE", "DECSTART");
2042 minigameManager.challenges[opponent].status = "We declined";
2043 loadChallenges();
2044 }
2045 };
2046 window.acceptChallenge = function(opponent, game, version, seed = "!NOSEED!") {
2047 if (opponent != window.username) {
2048 minigameManager.challenges[opponent].status = "Accepted";
2049 minigameMyStatus = "confirming start";
2050 setTimeout(function() {
2051 if (minigameMyStatus == "confirming start") {
2052 minigameMyStatus = "free";
2053 }
2054 }, 3000);
2055 sendp2p(opponent, "CHALLENGE", "ACCSTART", version, seed);
2056 }
2057 };
2058 window.sendChallenge = function() {
2059 let opponent = document.getElementById("inputOpp").value;
2060 if (opponent != window.username && opponent !== "") {
2061 let game = document.getElementById("inputGame").value;
2062 let version = document.getElementById("inputVersion").value;
2063 if (document.getElementById("inputSeed").value.replace(/[^a-z0-9]/gi, "") !== "") {
2064 minigameSeed = document.getElementById("inputSeed").value;
2065 } else minigameSeed = Math.floor(Math.random() * 1000000 + 1);
2066 if (minigameSeed.length > 12) {
2067 minigameSeed = minigameSeed.substring(0, 12);
2068 }
2069 minigameManager.challenges[opponent] = {
2070 from: opponent,
2071 game: game,
2072 version: version,
2073 seed: minigameSeed,
2074 status: "No response",
2075 };
2076 sendp2p(opponent, "CHALLENGE#REQSTART", version, minigameSeed);
2077 loadChallenges();
2078 }
2079 };
2080 window.tmgReset = function() {
2081 minigameMyStatus = "free";
2082 loadMinigame("Minigames");
2083 document.getElementById("challengeContainer").style.display = "flex";
2084 document.getElementById("versusContainer").style.display = "none";
2085 sendp2p(minigameOpp, "QUIT", "OPPONENT_RESET");
2086 minigameOpp = "";
2087 pingSent = false;
2088 document.getElementById("inputOpp").focus();
2089 };
2090 var challengeContainer = document.createElement("div");
2091 challengeContainer.setAttribute("style", "display:flex;flex-direction:column;align-items:center;justify-content:center");
2092 challengeContainer.setAttribute("id", "challengeContainer");
2093 function loadChallenges() {
2094 while (challengeContainer.firstChild) {
2095 challengeContainer.removeChild(challengeContainer.firstChild);
2096 }
2097 if (minigameMyStatus != "free") return;
2098 challengeContainer.style.display = "flex";
2099 let challengesText = document.createElement("span");
2100 challengesText.style.fontSize = "30px";
2101 challengesText.append("Challenges");
2102 challengeContainer.append(challengesText);
2103 challengeContainer.append(document.createElement("br"));
2104
2105 var challengeTable = document.createElement("table");
2106 challengeTable.setAttribute("style", "border-spacing:1px;");
2107 var objTableDetails = {
2108 headers: ["Opponent","Game","Version","Seed"],
2109 };
2110 var tr = challengeTable.appendChild(document.createElement("tr"));
2111 for (let c = 0; c < objTableDetails.headers.length; ++c) {
2112 let cell = tr.appendChild(document.createElement("td"));
2113 cell.setAttribute("style", "padding:15px;border:6px solid #ccc;text-align:center");
2114 cell.append(objTableDetails.headers[c]);
2115 }
2116 for (let r = 0; r < Object.keys(minigameManager.challenges).length; ++r) {
2117 let from = Object.keys(minigameManager.challenges)[r];
2118 let status = minigameManager.challenges[from].status;
2119 if (status == "We declined") continue;
2120 let game = minigameManager.challenges[from].game;
2121 let version = minigameManager.challenges[from].version;
2122 let seed = minigameManager.challenges[from].seed;
2123 let tr = challengeTable.appendChild(document.createElement("tr"));
2124 let cell = tr.appendChild(document.createElement("td"));
2125 cell.setAttribute("style","border-left:3px solid #ccc;border-bottom:1px solid #ccc;text-align:center;padding:10px");
2126 cell.append(from);
2127 cell = tr.appendChild(document.createElement("td"));
2128 cell.setAttribute("style","border-bottom:1px solid #ccc;text-align:center;padding:10px");
2129 cell.append(game);
2130 cell = tr.appendChild(document.createElement("td"));
2131 cell.setAttribute("style","border-bottom:1px solid #ccc;text-align:center;padding:10px");
2132 cell.append(version);
2133 cell = tr.appendChild(document.createElement("td"));
2134 cell.setAttribute("style","border-right:3px solid #ccc;border-bottom:1px solid #ccc;text-align:center;padding:10px");
2135 cell.append(seed);
2136 cell = tr.appendChild(document.createElement("td"));
2137 cell.setAttribute("style","text-align:center;padding:10px");
2138 let button1 = document.createElement("input");
2139 button1.setAttribute("type", "button");
2140 button1.setAttribute("value", status);
2141 if (status == "Accept") {
2142 button1.setAttribute("onclick", "acceptChallenge('" + from + "','" + game + "','" + version + "','" + seed + "')");
2143 } else { //if (status == "No response" || status == "Challenge received" || status == "Challenge declined" || status == "Challenge cancelled") {
2144 button1.setAttribute("disabled", "disabled");
2145 }
2146 cell.append(button1);
2147 cell = tr.appendChild(document.createElement("td"));
2148 cell.setAttribute("style","text-align:center;padding:10px");
2149 let button2 = document.createElement("input");
2150 button2.setAttribute("type", "button");
2151 button2.setAttribute("onclick", "declineChallenge('" + from + "','" + game + "','" + version + "','" + seed + "')");
2152 if (status == "Accept") {
2153 button2.setAttribute("value", "Decline");
2154 } else if (status == "Challenge cancelled") {
2155 button2.setAttribute("value", "Ok");
2156 } else { //if (status == "No Response" || status == "Challenge received" || status == "Challenge declined") {
2157 button2.setAttribute("value", "Cancel");
2158 }
2159 cell.append(button2);
2160 }
2161 challengeContainer.append(challengeTable);
2162 }
2163
2164 window.tmg_pokerSitAtTable = function(table, seat, buyin) {
2165 //minigameMyStatus = "ingame";
2166 buyin = 200;
2167 if (table && seat) {
2168 sendp2p(pokerServerUsername, "LOBBY", "JOINTABLE", table, seat, buyin);
2169 }
2170 };
2171 window.tmg_pokerRequestObserveTable = function(table) {
2172 sendp2p(pokerServerUsername, "LOBBY", "OBSERVE", table);
2173 };
2174 window.tmg_pokerObserveTable = function(table) {
2175 loadMinigame(minigameCurrentSelectedGame);
2176 };
2177 var pokerLobbyContainer = document.createElement("div");
2178 pokerLobbyContainer.setAttribute("style", "display:none;flex-direction:column;align-items:center;justify-content:center");
2179 pokerLobbyContainer.setAttribute("id", "pokerLobbyContainer");
2180 window.loadPokerLobby = function() {
2181 while (pokerLobbyContainer.firstChild) {
2182 pokerLobbyContainer.removeChild(pokerLobbyContainer.firstChild);
2183 }
2184 if (minigameMyStatus != "free") return;
2185 pokerLobbyContainer.style.display = "flex";
2186
2187 let pokerLobbyInfo = pokerLobbyContainer.appendChild(document.createElement("div"));
2188 pokerLobbyInfo.setAttribute("style","color:#f0f0f0;border:grey ridge;padding:1em;margin:0 1em;display:flex;flex-direction:row;align-items:flex-start;justify-content:space-around;min-width:500px;border-radius:10px;background:linear-gradient(#202020,#606060)");
2189
2190 let promotionInfo = pokerLobbyInfo.appendChild(document.createElement("div"));
2191 promotionInfo.setAttribute("style","width:50%;display:flex;flex-direction:column;align-items:center;justify-content:space-around");
2192 let jackpotText = promotionInfo.appendChild(document.createElement("div"));
2193 jackpotText.append("Jackpot Pool");
2194 let jackpotPool = promotionInfo.appendChild(document.createElement("div"));
2195 jackpotPool.setAttribute("style","color:gold");
2196 jackpotPool.append(coinImg.cloneNode());
2197 jackpotPool.append(" " + tedStoredSettings.poker.promotions.jackpotPool);
2198 promotionInfo.appendChild(document.createElement("br"));
2199 let badBeatText = promotionInfo.appendChild(document.createElement("div"));
2200 badBeatText.append("Bad Beat");
2201 badBeatText.setAttribute("style","border-bottom:1px dotted #f0f0f0");
2202 badBeatText.setAttribute("title","Lose with quads or better using both hole cards\n75% of jackpot goes to loser\n20% of jackpot is split to other players dealt into the hand\n 5% rolls over to next jackpot");
2203
2204 if (tedStoredSettings.poker.promotions.bbj.previousWinner !== null) {
2205 let badBeatPreviousWinnerText = promotionInfo.appendChild(document.createElement("div"));
2206 badBeatPreviousWinnerText.append("BBJ Previous Winner");
2207 let badBeatPreviousWinner = promotionInfo.appendChild(document.createElement("div"));
2208 badBeatPreviousWinner.append(tedStoredSettings.poker.promotions.bbj.previousWinner + " " + timeSince(tedStoredSettings.poker.promotions.bbj.previousTime) + " ago");
2209 let badBeatPreviousAmount = promotionInfo.appendChild(document.createElement("div"));
2210 badBeatPreviousAmount.setAttribute("style","color:gold");
2211 badBeatPreviousAmount.append(coinImg.cloneNode());
2212 badBeatPreviousAmount.append(numberWithCommas(tedStoredSettings.poker.promotions.bbj.previousAmount));
2213 }
2214
2215 promotionInfo.appendChild(document.createElement("br"));
2216 let highHandText = promotionInfo.appendChild(document.createElement("div"));
2217 highHandText.append("High Hand");
2218 highHandText.setAttribute("style","border-bottom:1px dotted #f0f0f0");
2219 highHandText.setAttribute("title","The highest hand when the timer runs out");
2220
2221
2222 // if previous winner, show info
2223
2224 let myInfo = pokerLobbyInfo.appendChild(document.createElement("div"));
2225 myInfo.setAttribute("style","width:50%;display:flex;flex-direction:column;align-items:center;justify-content:space-around");
2226 let availableBalance = myInfo.appendChild(document.createElement("div"));
2227 availableBalance.append("Available balance");
2228 let myPokerBalance = myInfo.appendChild(document.createElement("div"));
2229 myPokerBalance.setAttribute("style","border:grey ridge;border-radius:5px;margin:0.25em 0;text-align:center;width:160px;background:linear-gradient(#202020,#606060);color:#dfd4a1;white-space:nowrap");
2230 myPokerBalance.append(coinImg.cloneNode());
2231 myPokerBalance.append(" " + tedStoredSettings.poker.availableBalance);
2232 let depositWithdrawFlex = myInfo.appendChild(document.createElement("div"));
2233 depositWithdrawFlex.setAttribute("style","margin-bottom:0.25em;text-align:center;width:160px;white-space:nowrap");
2234 let depositButton = depositWithdrawFlex.appendChild(document.createElement("input"));
2235 depositButton.setAttribute("type", "button");
2236 depositButton.setAttribute("value", "Deposit");
2237 depositButton.setAttribute("style","font-weight:bold;border-radius:10px;user-select:none;cursor:pointer;background:linear-gradient(white,gold);border:1px solid gold");
2238 //depositButton.setAttribute("disabled","true");
2239 //depositButton.style.opacity = "0.8";
2240 depositWithdrawFlex.append(document.createTextNode("\u00a0")); //nbsp
2241 let withdrawButton = depositWithdrawFlex.appendChild(document.createElement("input"));
2242 withdrawButton.setAttribute("type", "button");
2243 withdrawButton.setAttribute("value", "Withdraw");
2244 withdrawButton.setAttribute("style","font-weight:bold;border-radius:10px;user-select:none;cursor:pointer;background:linear-gradient(white,gold);border:1px solid gold");
2245 //withdrawButton.setAttribute("disabled","true");
2246 //withdrawButton.style.opacity = "0.8";
2247
2248 let pokerTablesContainer = pokerLobbyContainer.appendChild(document.createElement("div"));
2249 pokerTablesContainer.setAttribute("style","border:grey ridge;margin:1em;min-width:500px;border-radius:10px;background:linear-gradient(#202020,#606060);cursor:default;user-select:none;color:#F0F0F0");
2250 pokerTablesContainer.setAttribute("id","pokerTablesContainer");
2251 let tablesHeader = document.createElement("div");
2252 tablesHeader.setAttribute("style","min-width:600px;margin:0.5em 0;display:flex;flex-direction:row;align-items:center;justify-content:space-around;text-align:center");
2253 let tablesHeaders = ["Table","Stakes","Game","Players", ""];
2254 tablesHeaders.forEach(header => {
2255 let headerDiv = document.createElement("div");
2256 headerDiv.setAttribute("style","width:" + 100 / tablesHeaders.length + "%");
2257 headerDiv.append(header);
2258 tablesHeader.append(headerDiv);
2259 });
2260 pokerTablesContainer.append(tablesHeader);
2261
2262 for (let table in minigamesObject[minigameCurrentSelectedGame].tables) {
2263 let tableBlock = pokerTablesContainer.appendChild(document.createElement("div"));
2264 tableBlock.setAttribute("style","padding:0.25em;border-top:grey ridge;display:flex;flex-direction:column;align-items:center;justify-content:space-around;text-align:center");
2265
2266 let tableGameInfo = tableBlock.appendChild(document.createElement("div"));
2267 tableGameInfo.setAttribute("style","width:100%;display:flex;flex-direction:row;align-items:center;justify-content:space-around;text-align:center");
2268
2269 let stakes = "" + minigamesObject[minigameCurrentSelectedGame].tables[table].gameInfo.sb + "/" + minigamesObject[minigameCurrentSelectedGame].tables[table].gameInfo.bb;
2270 let playerCount = Object.keys(minigamesObject[minigameCurrentSelectedGame].tables[table].seats).length;
2271 let players = "" + playerCount + "/" + minigamesObject[minigameCurrentSelectedGame].tables[table].gameInfo.maxPlayers;
2272 let gameType = minigamesObject[minigameCurrentSelectedGame].tables[table].gameInfo.gameType;
2273 let arrTableGameInfo = [table, stakes, gameType, players, "observeButton"];
2274
2275 arrTableGameInfo.forEach(thing => {
2276 if (thing == "observeButton") {
2277 let div = tableGameInfo.appendChild(document.createElement("div"));
2278 div.style.width = "" + 100 / arrTableGameInfo.length + "%";
2279 let btn = div.appendChild(document.createElement("input"));
2280 btn.setAttribute("type","button");
2281 btn.setAttribute("value","Observe");
2282 btn.setAttribute("style","cursor:pointer;color:#f0f0f0;background:linear-gradient(#3d85c6,#073763);font-weight:bold;border:silver ridge;padding:0.25em;border-radius:5px");
2283 btn.setAttribute("onclick","tmg_pokerRequestObserveTable('"+table+"')");
2284 } else {
2285 let div = tableGameInfo.appendChild(document.createElement("div"));
2286 div.style.width = "" + 100 / arrTableGameInfo.length + "%";
2287 div.append(thing);
2288 }
2289 });
2290
2291 tableGameInfo = tableBlock.appendChild(document.createElement("div"));
2292 tableGameInfo.setAttribute("style","width:100%;display:flex;flex-direction:row;align-items:center;justify-content:space-around;text-align:center");
2293
2294 for (let i = 1; i <= minigamesObject[minigameCurrentSelectedGame].tables[table].gameInfo.maxPlayers; i++) {
2295 let div = tableGameInfo.appendChild(document.createElement("div"));
2296 div.setAttribute("style","margin:0.25em");
2297 let player = "";
2298 for (let p in minigamesObject[minigameCurrentSelectedGame].tables[table].seats) {
2299 if (minigamesObject[minigameCurrentSelectedGame].tables[table].seats[p].seat == i) {
2300 player = p;
2301 }
2302 }
2303 if (player) {
2304 //if someone in this seat
2305 div.append(minigamesObject[minigameCurrentSelectedGame].tables[table].seats[player].name);
2306 div.append(document.createElement("br"));
2307 div.append(coinImg.cloneNode());
2308 div.append(minigamesObject[minigameCurrentSelectedGame].tables[table].seats[player].chips);
2309 } else {
2310 let seatMeBtn = document.createElement("input");
2311 seatMeBtn.setAttribute("type","button");
2312 seatMeBtn.setAttribute("value","Sit here");
2313 seatMeBtn.setAttribute("style","cursor:pointer;color:#f0f0f0;background:linear-gradient(#6aa84f,#274e13);font-weight:bold;border:silver ridge;padding:0.5em;border-radius:5px");
2314 seatMeBtn.setAttribute("onclick","tmg_pokerSitAtTable('"+table+"','"+i+"')");
2315 div.append(seatMeBtn);
2316 }
2317 }
2318 }
2319
2320 };
2321
2322 var versusContainer = document.createElement("div");
2323 //versusContainer.setAttribute("style", "display:flex;flex-direction:row;align-items:center;justify-content:center");
2324 versusContainer.setAttribute("id", "versusContainer");
2325 function loadVersus() {
2326 while (versusContainer.firstChild) {
2327 versusContainer.removeChild(versusContainer.firstChild);
2328 }
2329 if (minigameMyStatus != "ingame") return;
2330 versusContainer.style.display = "flex";
2331 let newFlex = document.createElement("div");
2332 newFlex.setAttribute("style", "display:flex;flex-direction:row;align-items:center;justify-content:space-around");
2333 let myColor = minigamesObject[minigameGame].players[minigameMyPlayer].color;
2334 if (myColor == "lightgreen") myColor = "green";
2335 let oppColor = minigamesObject[minigameGame].players[minigameOppPlayer].color;
2336 if (oppColor == "lightgreen") oppColor = "green";
2337
2338 let myVersusInfo = document.createElement("div");
2339 myVersusInfo.setAttribute("style", "width:45%;display:flex;flex-direction:row;align-items:center;justify-content:flex-end;font-size:20px;color:" + myColor); //text-align:right;font-size:30px;color:" + myColor
2340 let myUnits = document.createElement("div");
2341 myUnits.setAttribute("style", "display:flex;flex-direction:column;text-align:center");
2342 myUnits.setAttribute("id","gc_" + minigameMyPlayer + "_unitsdiv");
2343 myUnits.append("Units");
2344 let myUnitsNumber = document.createElement("div");
2345 myUnitsNumber.setAttribute("id","gc_" + minigameMyPlayer + "_unitcount");
2346 myUnitsNumber.append("0");
2347 myUnits.append(myUnitsNumber);
2348 myVersusInfo.append(myUnits);
2349 myVersusInfo.append(document.createTextNode("\u00a0")); //nbsp
2350 let myName = document.createElement("div");
2351 myName.setAttribute("style","font-size:40px;border-radius:200px");
2352 myName.setAttribute("id","gc_versus_"+minigameMyPlayer);
2353 myName.append(window.username);
2354 myVersusInfo.append(myName);
2355 myVersusInfo.append(document.createTextNode("\u00a0")); //nbsp
2356 let myWins = document.createElement("div");
2357 myWins.setAttribute("style", "display:flex;flex-direction:column");
2358 myWins.append("Wins");
2359 let myWinsNumber = document.createElement("div");
2360 myWinsNumber.setAttribute("id","gc_" + minigameMyPlayer + "_wins");
2361 myWinsNumber.setAttribute("style","text-align:center");
2362 myWinsNumber.append(minigamesObject[minigameGame].players[minigameMyPlayer].wins);
2363 myWins.append(myWinsNumber);
2364 myVersusInfo.append(myWins);
2365 newFlex.append(myVersusInfo);
2366 newFlex.append(document.createTextNode("\u00a0")); //nbsp
2367 newFlex.append(document.createTextNode('vs'));
2368 newFlex.append(document.createTextNode("\u00a0")); //nbsp
2369
2370 let oppVersusInfo = document.createElement("div");
2371 oppVersusInfo.setAttribute("style", "width:45%;display:flex;flex-direction:row;align-items:center;justify-content:flex-start;font-size:20px;color:" + oppColor); //text-align:right;font-size:30px;color:" + oppColor
2372 let oppWins = document.createElement("div");
2373 oppWins.setAttribute("style", "display:flex;flex-direction:column");
2374 oppWins.append("Wins");
2375 let oppWinsNumber = document.createElement("div");
2376 oppWinsNumber.setAttribute("id","gc_" + minigameOppPlayer + "_wins");
2377 oppWinsNumber.setAttribute("style","text-align:center");
2378 oppWinsNumber.append(minigamesObject[minigameGame].players[minigameOppPlayer].wins);
2379 oppWins.append(oppWinsNumber);
2380 oppVersusInfo.append(oppWins);
2381 oppVersusInfo.append(document.createTextNode("\u00a0")); //nbsp
2382 let oppName = document.createElement("div");
2383 oppName.setAttribute("style","font-size:40px;border-radius:200px");
2384 oppName.setAttribute("id","gc_versus_"+minigameOppPlayer);
2385 oppName.append(minigameOpp);
2386 oppVersusInfo.append(oppName);
2387 oppVersusInfo.append(document.createTextNode("\u00a0")); //nbsp
2388 let oppUnits = document.createElement("div");
2389 oppUnits.setAttribute("style", "display:flex;flex-direction:column;text-align:center");
2390 oppUnits.append("Units");
2391 let oppUnitsNumber = document.createElement("div");
2392 oppUnitsNumber.setAttribute("id","gc_" + minigameOppPlayer + "_unitcount");
2393 oppUnitsNumber.append("0");
2394 oppUnits.append(oppUnitsNumber);
2395 oppVersusInfo.append(oppUnits);
2396 newFlex.append(oppVersusInfo);
2397 versusContainer.append(newFlex);
2398 }
2399 function clickableGrid(rows, cols, map, callback) {
2400 var i = 0;
2401 var grid = document.createElement('table');
2402 grid.className = "grid";
2403 grid.setAttribute("style", "border-spacing:1px;border-style:ridge");
2404 for (var r = 0; r < rows; ++r) {
2405 var tr = grid.appendChild(document.createElement('tr'));
2406 for (var c = 0; c < cols; ++c) {
2407 var cell = tr.appendChild(document.createElement('td'));
2408 cell.setAttribute("style", "cursor:default;width:70px;height:70px;border:1px solid #ccc;text-align:center");
2409 cell.setAttribute("gc_row", r);
2410 cell.setAttribute("gc_col", c);
2411 cell.setAttribute("id", "gc_" + i);
2412 cell.setAttribute("gc_owner", "none");
2413 cell.setAttribute("gc_str", 0);
2414 cell.setAttribute("gc_bonus", "");
2415 cell.addEventListener('click', (function(el) {
2416 return function() {
2417 callback(el);
2418 };
2419 })(cell), false);
2420 i++;
2421 }
2422 }
2423 return grid;
2424 }
2425 window.endGameRematch = function(winner) {
2426 var color;
2427 if (minigamesObject[minigameGame].players[winner]) {
2428 color = minigamesObject[minigameGame].players[winner].color;
2429 } else color = "gold";
2430 if (minigamesObject[minigameGame].players[winner]) {
2431 document.getElementById("gc_" + winner + "_wins").innerHTML = parseInt(document.getElementById("gc_" + winner + "_wins").innerHTML) + 1;
2432 }
2433 document.getElementById("gc_container").style.boxShadow = "0 0 300px 400px " + color + " inset";
2434 document.getElementById("gc_container").style.transition = "box-shadow 2.5s";
2435 setTimeout(function() {
2436 if (minigameOpp !== "") {
2437 loadMinigame("Grid Control");
2438 }
2439 }, 2500);
2440 };
2441 window.gc_checkVictory = function(surrenderingPlayer) {
2442 if (minigameMyStatus != "ingame") {
2443 return;
2444 }
2445 if (surrenderingPlayer && minigamesObject[minigameGame].players[surrenderingPlayer]) {
2446 if (minigameMyPlayer == surrenderingPlayer) {
2447 sendp2p(minigameOpp, "SURRENDER", minigameMyPlayer);
2448 }
2449 }
2450 var playersAlive = [];
2451 for (let player in minigamesObject[minigameGame].players) {
2452 let playerTerritoriesOwned = $("[gc_owner]").filter(function() {
2453 return $(this).attr("gc_owner") == player;
2454 });
2455 if (playerTerritoriesOwned.length > 0) {
2456 playersAlive.push(player);
2457 }
2458 }
2459 if (playersAlive.indexOf(surrenderingPlayer) >= 0) {
2460 playersAlive.splice(playersAlive.indexOf(surrenderingPlayer), 1);
2461 }
2462 if (playersAlive.length === 0) {
2463 //draw
2464 endGameRematch();
2465 } else if (playersAlive.length === 1) {
2466 //somebody won
2467 endGameRematch(playersAlive[0]);
2468 }
2469 };
2470 window.gc_calculateBonuses = function(player) {
2471 let x = $("[gc_bonus]").filter(function() {
2472 return (parseInt($(this).attr("gc_bonus")) > 0 || parseInt($(this).attr("gc_bonus")) < 0);
2473 });
2474 for (let i = 0; i < x.length; i++) {
2475 if (x[i].getAttribute("gc_owner") == player) {
2476 let bonus = parseInt(x[i].getAttribute("gc_bonus"));
2477 let total = parseInt(x[i].getAttribute("gc_str")) + bonus;
2478 if (total <= 0) {
2479 total = 0;
2480 x[i].setAttribute("gc_owner", "none");
2481 }
2482 x[i].setAttribute("gc_str", total);
2483 }
2484 }
2485 };
2486 window.gc_interpretMove = function(from, to, percent, opp) {
2487 from = document.getElementById("gc_" + from);
2488 to = document.getElementById("gc_" + to);
2489 window.gc_moveUnits(from, to, percent, opp);
2490 };
2491 window.gc_moveUnits = function(from, to, percent, opp) {
2492 if (minigameMyTurn || opp) {
2493 if (minigameMyPlayer == from.getAttribute("gc_owner") || opp) {
2494 let newpercent;
2495 if (percent == "33") {
2496 newpercent = 1/3;
2497 } else newpercent = parseInt(percent) / 100;
2498 let fromStr = parseInt(from.getAttribute("gc_str"));
2499 let toStr = parseInt(to.getAttribute("gc_str"));
2500 let amtToMove = Math.floor(fromStr * newpercent);
2501 let fromOwned = from.getAttribute("gc_owner");
2502 let toOwned = to.getAttribute("gc_owner");
2503 if (amtToMove > 0) {
2504 if (fromOwned == toOwned || toOwned == "none") {
2505 fromStr = fromStr - amtToMove;
2506 toStr = toStr + amtToMove;
2507 from.setAttribute("gc_str", fromStr);
2508 to.setAttribute("gc_str", toStr);
2509 to.setAttribute("gc_owner", from.getAttribute("gc_owner"));
2510 } else if (fromOwned != toOwned) {
2511 fromStr = fromStr - amtToMove;
2512 from.setAttribute("gc_str", fromStr);
2513 if (amtToMove > toStr) {
2514 toStr = amtToMove - toStr;
2515 to.setAttribute("gc_owner", from.getAttribute("gc_owner"));
2516 to.setAttribute("gc_str", toStr);
2517 } else if (amtToMove < toStr) {
2518 toStr = toStr - amtToMove;
2519 to.setAttribute("gc_str", toStr);
2520 } else if (amtToMove == toStr) {
2521 to.setAttribute("gc_str", 0);
2522 toStr = 0;
2523 to.setAttribute("gc_owner", "none");
2524 }
2525 }
2526 if (from.getAttribute("gc_bonus")) {
2527 from.innerHTML = fromStr + " +" + from.getAttribute("gc_bonus");
2528 } else if (fromStr === 0) {
2529 from.innerHTML = "";
2530 from.setAttribute("gc_owner", "none");
2531 } else from.innerHTML = fromStr;
2532 if (to.getAttribute("gc_bonus")) {
2533 to.innerHTML = toStr + " +" + to.getAttribute("gc_bonus");
2534 if (to.getAttribute("gc_owner") == "none") {
2535 }
2536 } else if (toStr === 0) {
2537 to.innerHTML = "";
2538 to.setAttribute("gc_owner", "none");
2539 } else to.innerHTML = toStr;
2540 if (!opp) {
2541 gc_lastClicked.style.boxShadow = "";
2542 gc_lastClicked = to;
2543 to.style.boxShadow = "0px 0px 20px 5px gold inset";
2544 minigameMyTurn = false;
2545 sendp2p(minigameOpp, "MOVE", from.getAttribute("id").replace(/\D+/g, ""), to.getAttribute("id").replace(/\D+/g, ""), percent);
2546 gc_calculateBonuses(minigameOppPlayer);
2547 } else {
2548 minigameMyTurn = true;
2549 gc_calculateBonuses(minigameMyPlayer);
2550 if (allowedBrowserNotifications) {
2551 var minigameTurnNotification = new Notification("Your turn", {
2552 body: "It's your turn in Grid Control"
2553 });
2554 setTimeout(function() {
2555 minigameTurnNotification.close();
2556 }, 2000);
2557 }
2558 }
2559 gc_redrawGrid();
2560 window.gc_countUnits();
2561 gc_checkVictory();
2562 window.gc_highlightCurrentPlayer();
2563 }
2564 }
2565 }
2566 };
2567 window.gc_countUnits = function() {
2568 for (let player in minigamesObject[minigameGame].players) {
2569 let territoriesOwned = $("[gc_owner]").filter(function() {
2570 return $(this).attr("gc_owner") == player;
2571 });
2572 var unitCount = 0;
2573 Array.from(territoriesOwned).forEach(territory => {
2574 unitCount += parseInt(territory.getAttribute("gc_str"));
2575 });
2576 minigamesObject[minigameGame].players[player].unitcount = unitCount;
2577 document.getElementById("gc_" + player + "_unitcount").innerHTML = unitCount;
2578 }
2579 };
2580 window.gc_highlightCurrentPlayer = function() {
2581 var playerToHighlight;
2582 if (minigameMyTurn) {
2583 playerToHighlight = minigameMyPlayer;
2584 } else playerToHighlight = minigameOppPlayer;
2585 for (let player in minigamesObject[minigameGame].players) {
2586 if (player == playerToHighlight) {
2587 document.getElementById("gc_versus_" + player).style.boxShadow = "0px 5px 20px -5px black";
2588 } else document.getElementById("gc_versus_" + player).style.boxShadow = "";
2589 }
2590 };
2591 window.gc_redrawGrid = function() {
2592 for (let i = 0; i < 81; i++) {
2593 if (document.getElementById("gc_" + i)) {
2594 let td = document.getElementById("gc_" + i);
2595 if (td.getAttribute("gc_str") == "0") {
2596 if (td.getAttribute("gc_bonus") == "0") {
2597 td.setAttribute("gc_bonus","");
2598 td.innerHTML = "";
2599 } else if (td.getAttribute("gc_bonus")) {
2600 td.innerHTML = "0";
2601 } else td.innerHTML = "";
2602 } else td.innerHTML = td.getAttribute("gc_str");
2603 if (parseInt(td.getAttribute("gc_bonus")) > 0) {
2604 td.append(" +" + parseInt(td.getAttribute("gc_bonus")));
2605 td.style.color = "#d2d2d2";
2606 } else if (parseInt(td.getAttribute("gc_bonus")) < 0) {
2607 td.append(" " + parseInt(td.getAttribute("gc_bonus")));
2608 td.style.color = "grey";
2609 } else if (parseInt(td.getAttribute("gc_bonus")) === 0) {
2610 td.append(" -" + parseInt(td.getAttribute("gc_bonus")));
2611 td.style.color = "grey";
2612 }
2613 let owner = td.getAttribute("gc_owner");
2614 if (minigamesObject[minigameGame].players[owner] && minigamesObject[minigameGame].players[owner].color) {
2615 td.style.color = minigamesObject[minigameGame].players[owner].color;
2616 }
2617 }
2618 }
2619 };
2620 window.minigamePing = function(pingTo, game) {
2621 sendp2p(pingTo, "PING");
2622 pingTimeStart = new Date().getTime();
2623 };
2624 window.prngGen = function(seed) {
2625 //pseudo-random seeded number gen
2626 seed = String(seed).replace(/[^a-z0-9]/gi, "");
2627 if (seed.length > 10) {
2628 seed = seed.substring(0, 10);
2629 }
2630 seed = seed.split("");
2631 for (let i = 0; i < seed.length; i++) {
2632 if (isNaN(seed[i])) {
2633 seed[i] = String(seed[i].toLowerCase().charCodeAt(0) - 96);
2634 }
2635 }
2636 seed = parseInt(seed.join(""));
2637 this._seed = seed % 2147483647;
2638 if (this._seed <= 0) this._seed += 2147483646;
2639 };
2640 //Returns a pseudo-random value between 1 and 2^32 - 2.
2641 prngGen.prototype.next = function() {
2642 this._seed = this._seed * 16831 % 2147483647;
2643 return this._seed;
2644 };
2645 // Returns a pseudo-random floating point number from 0 to 1, non-inclusive.
2646 prngGen.prototype.nextFloat = function (min = 0, max = 1) {
2647 // We know that result of next() will be 1 to 2147483646 (inclusive).
2648 return ((this.next() - 1) / 2147483646)*(max-min)+min;
2649 };
2650 //Returns an integer in the range [min, max]
2651 prngGen.prototype.nextInt = function (min = 0, max = 1) {
2652 return this.next()%(max-min+1)+min;
2653 };
2654 window.initialHighlightLastClicked = function() {
2655 let myUnits = $("[gc_owner]").filter(function() {
2656 return $(this).attr("gc_owner") == minigameMyPlayer;
2657 });
2658 myUnits.sort(function(a, b) {
2659 return a.getAttribute("gc_str") == b.getAttribute("gc_str") ? 0 : +(a.getAttribute("gc_str") > b.getAttribute("gc_str")) || -1;
2660 });
2661 if (myUnits.length >= 1) {
2662 myUnits[0].style.boxShadow = "0px 0px 20px 5px gold inset";
2663 gc_lastClicked = myUnits[0];
2664 }
2665 };
2666 window.seedPRNG = function(seed) { // chosen by fair dice roll
2667 var arrGen = [],
2668 cnt = 0;
2669 for (let a = 0; a < 12; a++) {
2670 seed = String(seed).replace(/[^a-z0-9]/gi, "");
2671 if (seed.length > 12) {
2672 seed = seed.substring(0, 12);
2673 }
2674 if (seed == "0" || seed.length === 0) {
2675 seed = "1337";
2676 }
2677 seed = seed.split("");
2678 for (let i = 0; i < seed.length; i++) {
2679 if (isNaN(seed[i])) {
2680 cnt++;
2681 seed[i] = String(seed[i].toLowerCase().charCodeAt(0) - 96);
2682 }
2683 }
2684 while (seed.join("").length > 10) {
2685 cnt++;
2686 let x = parseInt(seed[0]) + parseInt(seed[seed.length - 1]);
2687 seed[seed.length - 1] = String(x);
2688 seed.splice(1, 1);
2689 }
2690 seed = parseInt(seed.join(""));
2691 while (String(seed).length < 10) {
2692 let x = String(seed).split("");
2693 for (let i = 0; i < x.length; i++) {
2694 cnt++;
2695 seed += parseInt(x[i] + i + a);
2696 }
2697 if (String(seed).length < 10) {
2698 x = String(seed).split("");
2699 for (let j = 0; j < 2; j++) {
2700 for (let i = 0; i < x.length; i++) {
2701 cnt++;
2702 if (parseInt(x[i] + 1) !== 0) {
2703 seed *= parseInt(x[i] + 1);
2704 seed += parseInt(x[i] + 1);
2705 }
2706 if (String(seed).length >= 10) break;
2707 }
2708 }
2709 }
2710 if (seed == "0") {
2711 break;
2712 }
2713 }
2714 let thisSeed = seed;
2715 seed = parseInt(String(thisSeed).substring(String(thisSeed).length - 9, String(thisSeed).length));
2716 if (String(seed).length != 9) {
2717 seed = parseInt(String(thisSeed).substring(String(thisSeed).length - 10, String(thisSeed).length - 1));
2718 if (String(seed).length != 9) {
2719 seed = parseInt(String(thisSeed).substring(0, 9));
2720 }
2721 }
2722 if (seed === 0) {
2723 seed = parseInt(thisSeed);
2724 }
2725 arrGen.push(seed);
2726 }
2727 if (debugToConsole) console.log(cnt);
2728 let randomString = String(arrGen).replace(/,/g, "");
2729 return randomString;
2730 };
2731 window.gc_mapFromSeed = function(seed) {
2732 if (seed.length < 108) return;
2733 let arrIds = [],
2734 seedCount = -1;
2735
2736 function nextRand() {
2737 seedCount++;
2738 if (!seed[seedCount]) return 0;
2739 return seed[seedCount];
2740 }
2741 for (let i = 0; i < 36; i++) { // for each grid on player2 side
2742 arrIds.push({
2743 location: document.getElementById("gc_" + i),
2744 seedValue: parseInt(nextRand()),
2745 });
2746 }
2747 arrIds.sort(function(a, b) {
2748 return a.seedValue == b.seedValue ? 0 : +(a.seedValue > b.seedValue) || -1;
2749 });
2750 for (let i = 0; i < 15; i++) {
2751 if (i === 0) { // player spawn
2752 arrIds[i].location.setAttribute("gc_owner", "player2");
2753 arrIds[i].location.setAttribute("gc_str", "3");
2754 } else if (i == 1) { // 1 + 1 bonus area
2755 arrIds[i].location.setAttribute("gc_str", "1");
2756 arrIds[i].location.setAttribute("gc_bonus", "1");
2757 arrIds[i].location.setAttribute("gc_owner", "neutral");
2758 } else if (i <= 5) { // 4 positive bonus
2759 arrIds[i].location.setAttribute("gc_str", nextRand());
2760 arrIds[i].location.setAttribute("gc_bonus", nextRand());
2761 arrIds[i].location.setAttribute("gc_owner", "neutral");
2762 } else { // negative bonus
2763 arrIds[i].location.setAttribute("gc_str", 0);
2764 arrIds[i].location.setAttribute("gc_bonus", parseInt(nextRand() * -1));
2765 arrIds[i].location.setAttribute("gc_owner", "neutral");
2766 }
2767 }
2768 for (let i = 0; i < 36; i++) {
2769 document.getElementById("gc_" + (80 - i)).setAttribute("gc_str", document.getElementById("gc_" + i).getAttribute("gc_str"));
2770 document.getElementById("gc_" + (80 - i)).setAttribute("gc_bonus", document.getElementById("gc_" + i).getAttribute("gc_bonus"));
2771 document.getElementById("gc_" + (80 - i)).setAttribute("gc_owner", document.getElementById("gc_" + i).getAttribute("gc_owner"));
2772 if (document.getElementById("gc_" + (80 - i)).getAttribute("gc_owner") == "player2") {
2773 document.getElementById("gc_" + (80 - i)).setAttribute("gc_owner", "player1");
2774 }
2775 }
2776 };
2777 window.gc_flipskiMapFromSeed = function(seed, mapDim = [9,9]) { //
2778 let seedRNG = new prngGen(seed); //turns the seed into a random number generator object
2779 mapArea = mapDim[0] * mapDim[1] - 1;
2780 let mapArr = [];
2781 let playerSpawnType = 0;
2782 let mapGenType = 0;
2783 let randomNumber = seedRNG.nextFloat();
2784 if (randomNumber < 0.8) { //80% chance for normal spawn
2785 playerSpawnType = 0;
2786 } else { //20% chance for multiple starting spawns
2787 playerSpawnType = 1;
2788 }
2789 randomNumber = seedRNG.nextFloat();
2790 if (randomNumber < 0.35) { //35% chance for a normal map
2791 mapGenType = 0;
2792 } else if (randomNumber < 0.50) { //15% chance for blob map
2793 mapGenType = 1;
2794 } else if (randomNumber < 0.60) { //10% chance for wall map
2795 mapGenType = 2;
2796 } else if (randomNumber < 0.70) { //10% chance for house map
2797 mapGenType = 3;
2798 } else if (randomNumber < 0.80) { //10% chance for rush map (lots of tiles with negative strength)
2799 mapGenType = 4;
2800 } else if (randomNumber < 0.90) { //10% chance for bigger bonus&strength the further away from spawn map
2801 mapGenType = 5;
2802 } else if (randomNumber < 0.99) { //9% chance for unbalanced map
2803 mapGenType = 6;
2804 } else { //1% chance for rare crazy map
2805 mapGenType = 7;
2806 }
2807 if (mapGenType === 0) { //Normal map
2808 for (let i = 0; i < mapDim[0] * Math.floor(mapDim[1] / 2); i++) { //loop through all the tiles on one map end.
2809 if (seedRNG.nextFloat() < 1 / 3) { //1/3 of the tiles will be generated
2810 let randomStrength = seedRNG.nextInt(0, 12); //0 to 12 inclusive.
2811 let randomBonus = seedRNG.nextInt(-3, 6);
2812 if (randomBonus === 0) {
2813 randomBonus = null;
2814 }
2815 let tile = {
2816 location: i,
2817 strength: randomStrength,
2818 bonus: randomBonus,
2819 owner: "neutral",
2820 };
2821 mapArr.push(tile);
2822 tile = {
2823 location: mapArea - i,
2824 strength: randomStrength,
2825 bonus: randomBonus,
2826 owner: "neutral",
2827 };
2828 mapArr.push(tile);
2829 }
2830 }
2831 } else if (mapGenType == 1) { //Blobs
2832 //We don't generate the blob core in the top or bottom row and in the side columns so that there is more space for the blob itself to generate.
2833 for (let x_t = 1; x_t < mapDim[0] - 1; x_t++) { //x-coordinate
2834 for (let y_t = 1; y_t < Math.floor(mapDim[1] / 2) - 1; y_t++) { //y-coordinate
2835 let tileLocation = x_t + (y_t * mapDim[0]);
2836 if (seedRNG.nextFloat() < 1 / 5) { //1 in 5 chance to generate a blob
2837 let randomStrength = seedRNG.nextInt(12, 36);
2838 let randomBonus = seedRNG.nextInt(4, 12);
2839 if (randomBonus === 0) {
2840 randomBonus = null;
2841 }
2842 let tile = {
2843 location: tileLocation,
2844 strength: randomStrength,
2845 bonus: randomBonus,
2846 owner: "neutral",
2847 };
2848 mapArr.push(tile);
2849 tile = {
2850 location: mapArea - tileLocation,
2851 strength: randomStrength,
2852 bonus: randomBonus,
2853 owner: "neutral",
2854 };
2855 mapArr.push(tile);
2856 for (let x_b = -1; x_b <= 1; x_b++) {
2857 for (let y_b = -1; y_b <= 1; y_b++) { //loop through the tiles surrounding the core
2858 if ((x_b !== 0 || y_b !== 0) && seedRNG.nextFloat() < 2 / 3) { //66.66..% chance to generate a tile if it's not on the core
2859 tileLocation = (x_t + x_b) + ((y_t + y_b) * mapDim[0]); //Update the location variable to account for the actual tile that surrounds the blob core.
2860 randomStrength = seedRNG.nextInt(3, 12);
2861 randomBonus = seedRNG.nextInt(0, 4);
2862 if (randomBonus === 0) {
2863 randomBonus = null;
2864 }
2865 let tile = {
2866 location: tileLocation,
2867 strength: randomStrength,
2868 bonus: randomBonus,
2869 owner: "neutral",
2870 };
2871 mapArr.push(tile);
2872 tile = {
2873 location: mapArea - tileLocation,
2874 strength: randomStrength,
2875 bonus: randomBonus,
2876 owner: "neutral",
2877 };
2878 mapArr.push(tile);
2879 }
2880 }
2881 }
2882 }
2883 }
2884 }
2885 } else if (mapGenType == 2) { //Wall
2886 let loops = mapDim[1];
2887 if (loops % 2 === 0) {
2888 loops--;
2889 }
2890 for (let i = 0; i < mapDim[0] * Math.floor(loops / 2); i++) { //loop through all the tiles on one map end. Except if it's an even number, then it leaves 2 rows for the wall.
2891 if (seedRNG.nextFloat() < 1 / 3) { //1/3 of the tiles will be generated
2892 let randomStrength = seedRNG.nextInt(0, 15); //0 to 12 inclusive.
2893 let randomBonus = seedRNG.nextInt(1, 6);
2894 if (randomBonus === 0) {
2895 randomBonus = null;
2896 }
2897 let tile = {
2898 location: i,
2899 strength: randomStrength,
2900 bonus: randomBonus,
2901 owner: "neutral",
2902 };
2903 mapArr.push(tile);
2904 tile = {
2905 location: mapArea - i,
2906 strength: randomStrength,
2907 bonus: randomBonus,
2908 owner: "neutral",
2909 };
2910 mapArr.push(tile);
2911 }
2912 }
2913 for (let i = mapDim[0] * Math.floor((mapDim[1]) / 2); i < mapDim[0] * (Math.floor(mapDim[1] / 2) + 1); i++) { //loop through the middle in order to generate the wall.
2914 let randomStrength = seedRNG.nextInt(0, 24);
2915 let randomBonus = seedRNG.nextInt(-8, 0);
2916 if (randomBonus === 0) {
2917 randomBonus = null;
2918 }
2919 let tile = {
2920 location: i,
2921 strength: randomStrength,
2922 bonus: randomBonus,
2923 owner: "neutral",
2924 };
2925 mapArr.push(tile);
2926 if (mapDim[1] % 2 === 0) { //If it's an even number
2927 tile = {
2928 location: mapArea - i,
2929 strength: randomStrength,
2930 bonus: randomBonus,
2931 owner: "neutral",
2932 };
2933 mapArr.push(tile);
2934 }
2935 }
2936 } else if (mapGenType == 3) { //House - Similar to blobs in generation
2937 for (let x_t = 1; x_t < mapDim[0] - 1; x_t++) { //x-coordinate
2938 for (let y_t = 1; y_t < Math.floor(mapDim[1] / 2) - 1; y_t++) { //y-coordinate
2939 let tileLocation = x_t + (y_t * mapDim[0]);
2940 if (seedRNG.nextFloat() < 1 / 5) { //1 in 5 chance to generate a house
2941 let randomStrength = seedRNG.nextInt(6, 12);
2942 let randomBonus = seedRNG.nextInt(4, 24);
2943 if (randomBonus === 0) {
2944 randomBonus = null;
2945 }
2946 let tile = {
2947 location: tileLocation,
2948 strength: randomStrength,
2949 bonus: randomBonus,
2950 owner: "neutral",
2951 };
2952 mapArr.push(tile);
2953 tile = {
2954 location: mapArea - tileLocation,
2955 strength: randomStrength,
2956 bonus: randomBonus,
2957 owner: "neutral",
2958 };
2959 mapArr.push(tile);
2960 let doorwayX = seedRNG.nextInt(-1, 1);
2961 let doorwayY = seedRNG.nextInt(-1, 1);
2962 while (Math.abs(doorwayX) == Math.abs(doorwayY)) { //Check if the doorway is on the core, or if it's in a diagonal space. Basically an XOR gate
2963 doorwayX = seedRNG.nextInt(-1, 1);
2964 doorwayY = seedRNG.nextInt(-1, 1);
2965 }
2966 for (let x_b = -1; x_b <= 1; x_b++) {
2967 for (let y_b = -1; y_b <= 1; y_b++) { //loop through the tiles surrounding the core
2968 if (!(x_b === 0 && y_b === 0) && !(x_b == doorwayX && y_b == doorwayY)) { //if it's not on the core and is not where the doorway is meant to be
2969 tileLocation = (x_t + x_b) + ((y_t + y_b) * mapDim[0]); //Update the location variable to account for the actual tile that surrounds the blob core.
2970 randomStrength = seedRNG.nextInt(6, 18);
2971 randomBonus = seedRNG.nextInt(-3, 0);
2972 if (randomBonus === 0) {
2973 randomBonus = null;
2974 }
2975 let tile = {
2976 location: tileLocation,
2977 strength: randomStrength,
2978 bonus: randomBonus,
2979 owner: "neutral",
2980 };
2981 mapArr.push(tile);
2982 tile = {
2983 location: mapArea - tileLocation,
2984 strength: randomStrength,
2985 bonus: randomBonus,
2986 owner: "neutral",
2987 };
2988 mapArr.push(tile);
2989 }
2990 }
2991 }
2992 }
2993 }
2994 }
2995 } else if (mapGenType == 4) { //Rush
2996 for (let i = 0; i < mapDim[0] * Math.floor(mapDim[1] / 2); i++) { //loop through all the tiles on one map end.
2997 if (seedRNG.nextFloat() < 1 / 2) {
2998 let randomStrength = seedRNG.nextInt(-16, -4); //0 to 12 inclusive.
2999 let randomBonus = seedRNG.nextInt(2, 6);
3000 if (randomBonus === 0) {
3001 randomBonus = null;
3002 }
3003 let tile = {
3004 location: i,
3005 strength: randomStrength,
3006 bonus: randomBonus,
3007 owner: "neutral",
3008 };
3009 mapArr.push(tile);
3010 tile = {
3011 location: mapArea - i,
3012 strength: randomStrength,
3013 bonus: randomBonus,
3014 owner: "neutral",
3015 };
3016 mapArr.push(tile);
3017 }
3018 }
3019 } else if (mapGenType == 5) { //Distance scaling bonus&strength from center
3020 let centerTileX = Math.floor(mapDim[0] / 2); //It won't be quite the center tile in an even dimensioned map, but it's close enough for my idea.
3021 let centerTileY = Math.floor(mapDim[1] / 2);
3022 for (let x_t = 0; x_t < mapDim[0]; x_t++) { //x-coordinate
3023 for (let y_t = 0; y_t < Math.floor(mapDim[1] / 2); y_t++) { //y-coordinate
3024 if (seedRNG.nextFloat() < 2 / 5) {
3025 let tileLocation = x_t + (y_t * mapDim[0]);
3026 let distanceFromCenter = Math.round(Math.sqrt(Math.pow(centerTileX - x_t, 2) + Math.pow(centerTileY - y_t, 2))); //distance from center rounded to nearest int. See: distance between two points.
3027 let distanceMulti = distanceFromCenter;
3028 let randomStrength = seedRNG.nextInt(3 * distanceMulti, 6 * distanceMulti); //0 to 12 inclusive.
3029 let randomBonus = seedRNG.nextInt(-2 * distanceMulti, 4 * distanceMulti);
3030 if (randomBonus === 0) {
3031 randomBonus = null;
3032 }
3033 let tile = {
3034 location: tileLocation,
3035 strength: randomStrength,
3036 bonus: randomBonus,
3037 owner: "neutral",
3038 };
3039 mapArr.push(tile);
3040 tile = {
3041 location: mapArea - tileLocation,
3042 strength: randomStrength,
3043 bonus: randomBonus,
3044 owner: "neutral",
3045 };
3046 mapArr.push(tile);
3047 }
3048 }
3049 }
3050 } else if (mapGenType == 6) { //Unbalanced
3051 for (let i = 0; i < mapDim[0] * mapDim[1]; i++) { //loop through all the tiles on one map end.
3052 if (seedRNG.nextFloat() < 2 / 5) {
3053 let randomStrength = seedRNG.nextInt(4, 12); //0 to 12 inclusive.
3054 let randomBonus = seedRNG.nextInt(1, 8);
3055 if (randomBonus === 0) {
3056 randomBonus = null;
3057 }
3058 let tile = {
3059 location: i,
3060 strength: randomStrength,
3061 bonus: randomBonus,
3062 owner: "neutral",
3063 };
3064 mapArr.push(tile);
3065 }
3066 }
3067 } else if (mapGenType == 7) { //Crazy
3068 for (let i = 0; i < mapDim[0] * Math.floor(mapDim[1] / 2); i++) { //loop through all the tiles on one map end.
3069 let randomStrength = seedRNG.nextInt(-20, 100); //0 to 12 inclusive.
3070 let randomBonus = seedRNG.nextInt(-40, 150);
3071 if (randomBonus === 0) {
3072 randomBonus = null;
3073 }
3074 let tile = {
3075 location: i,
3076 strength: randomStrength,
3077 bonus: randomBonus,
3078 owner: "neutral",
3079 };
3080 mapArr.push(tile);
3081 tile = {
3082 location: mapArea - i,
3083 strength: randomStrength,
3084 bonus: randomBonus,
3085 owner: "neutral",
3086 };
3087 mapArr.push(tile);
3088 }
3089 }
3090 if (playerSpawnType === 0) { //Player spawn gen is last so that it overwrites the map gen
3091 let playerLocation = seedRNG.nextInt(0, mapDim[0] * Math.floor(mapDim[1] / 2) - 1); //spawn in the upper half part of the map, excluding the middle row if there is any.
3092 let playerStrength = 1;
3093 let playerBonus = 1;
3094 let tile = { //player 2
3095 location: playerLocation,
3096 strength: playerStrength,
3097 bonus: playerBonus,
3098 owner: "player2",
3099 };
3100 mapArr.push(tile);
3101 tile = { //player 1
3102 location: mapArea - playerLocation,
3103 strength: playerStrength,
3104 bonus: playerBonus,
3105 owner: "player1",
3106 };
3107 mapArr.push(tile);
3108 } else if (playerSpawnType == 1) {
3109 let amountLoops = seedRNG.nextInt(2, 5); //2 to 5 player spawns
3110 for (let i = 0; i < amountLoops; i++) {
3111 let playerLocation = seedRNG.nextInt(0, mapDim[0] * Math.floor(mapDim[1] / 2) - 1); //spawn in the upper half part of the map, excluding the middle row if there is any.
3112 let playerStrength = seedRNG.nextInt(1, 5);
3113 let playerBonus = seedRNG.nextInt(0, 2);
3114 let tile = { //player 2
3115 location: playerLocation,
3116 strength: playerStrength,
3117 bonus: playerBonus,
3118 owner: "player2",
3119 };
3120 mapArr.push(tile);
3121 tile = { //player 1
3122 location: mapArea - playerLocation,
3123 strength: playerStrength,
3124 bonus: playerBonus,
3125 owner: "player1",
3126 };
3127 mapArr.push(tile);
3128 }
3129 }
3130 for (let i = 0; i < mapArr.length; i++) { //Generate the map
3131 let tile = document.getElementById("gc_" + mapArr[i].location);
3132 if (mapArr[i].owner != "neutral") {
3133 tile.setAttribute("gc_bonus", "");
3134 }
3135 //Tile can have strength, bonus, and owner.
3136 tile.setAttribute("gc_str", mapArr[i].strength);
3137 if (mapArr[i].bonus) {
3138 tile.setAttribute("gc_bonus", mapArr[i].bonus);
3139 }
3140 tile.setAttribute("gc_owner", mapArr[i].owner);
3141 }
3142 };
3143
3144 window.changeLobbyView = function() {
3145 minigameCurrentSelectedGame = document.getElementById("inputGame").value;
3146 loadMinigame(minigameGame);
3147 //document.getElementById("inputGame").value = minigameCurrentSelectedGame;
3148 };
3149 window.tmg_pokerServerConnectChangeButton = function() {
3150 if (document.getElementById("tmg_pokerServerConnect").getAttribute("value") == "Disconnected") {
3151 minigameTryingToConnectToPokerServer = true;
3152 tmg_pokerConnectionHandler();
3153 document.getElementById("tmg_pokerServerConnect").setAttribute("value","Connecting...");
3154 document.getElementById("tmg_pokerServerConnect").style.border = "#bf9000 ridge";
3155 document.getElementById("tmg_pokerServerConnect").style.background = "radial-gradient(white, #fff2cc, #ffe599)";
3156 } else if (document.getElementById("tmg_pokerServerConnect").getAttribute("value") == "Connected" || document.getElementById("tmg_pokerServerConnect").getAttribute("value") == "Retrying..." || document.getElementById("tmg_pokerServerConnect").getAttribute("value") == "Connecting...") {
3157 minigameTryingToConnectToPokerServer = false;
3158 tmg_pokerServerPingSent = false;
3159 clearTimeout(tmg_pokerServerTimeoutVar);
3160 tmg_pokerConnectionHandler();
3161 document.getElementById("tmg_pokerServerConnect").setAttribute("value","Disconnected");
3162 document.getElementById("tmg_pokerServerConnect").style.border = "#990000 ridge";
3163 document.getElementById("tmg_pokerServerConnect").style.background = "radial-gradient(white, #f4cccc, #ea9999)";
3164 }
3165 };
3166 window.tmg_pokerServerConnect = function() {
3167 if (minigameTryingToConnectToPokerServer) {
3168 sendp2p(pokerServerUsername,"CONNECT");
3169 if (minigameConnectedToPokerServer && minigameMyStatus != "ingame") {
3170 console.log(minigameConnectedToPokerServer + "yes");
3171 //tmg_pokerRequestGamesLobby();
3172 }
3173 }
3174 };
3175 window.tmg_pokerRequestGamesLobby = function() {
3176 sendp2p(pokerServerUsername,"LOBBY", "LOAD_LOBBY");
3177 };
3178 function tmg_pokerConnectionHandler() {
3179 let minigameTimeSinceLastContactFromPokerServer = new Date().getTime() - minigameLastMessageFromPokerServer;
3180 if (minigameConnectedToPokerServer && minigameTimeSinceLastContactFromPokerServer >= 15000) {
3181 minigameTryingToConnectToPokerServer = true;
3182 tmg_pokerServerPingSent = true;
3183 tmg_pokerServerConnect();
3184 tmg_pokerServerTimeoutVar = setTimeout(function() {
3185 if (tmg_pokerServerPingSent) {
3186 tmg_pokerConnectionLost();
3187 }
3188 }, 5000);
3189 }
3190 if (minigameTryingToConnectToPokerServer) {
3191 if ((minigameLastMessageFromPokerServer == -1 || minigameTimeSinceLastContactFromPokerServer >= 15000) && !tmg_pokerServerPingSent) {
3192 tmg_pokerServerPingSent = true;
3193 tmg_pokerServerConnect();
3194 tmg_pokerServerTimeoutVar = setTimeout(function() {
3195 if (tmg_pokerServerPingSent) {
3196 tmg_pokerConnectionLost();
3197 }
3198 }, 5000);
3199 }
3200 }
3201 }
3202 window.tmg_pokerInterpretMove = function(table, seat, action, amount) {
3203 if (table == minigamePokerMyTable) {
3204 if (minigamesObject[minigameCurrentSelectedGame].tables[table] && minigamesObject[minigameCurrentSelectedGame].tables[table].seats[seat]) {
3205 if (action == "BET" || action == "RAISE") {
3206 let coinString = '<img src="images/coins.png" class="image-icon-20">';
3207 document.getElementById("poker_betBox_"+seat).style.display = "";
3208 document.getElementById("poker_betBox_"+seat).innerHTML = coinString + numberWithCommas(amount);
3209 } else if (action == "FOLD") {
3210 if (minigamePokerMySeat && seat == minigamePokerMySeat) {
3211 document.getElementById("poker_"+seat+"_card1").style.opacity = "0.6";
3212 document.getElementById("poker_"+seat+"_card2").style.opacity = "0.6";
3213 } else {
3214 document.getElementById("poker_"+seat+"_card1").style.opacity = "0";
3215 document.getElementById("poker_"+seat+"_card2").style.opacity = "0";
3216 }
3217 }
3218 }
3219 }
3220 };
3221 window.loadMinigame = function(game) {
3222 while (minigamesElement.firstChild) {
3223 minigamesElement.removeChild(minigamesElement.firstChild);
3224 }
3225 minigameGame = game;
3226 console.log(minigameGame);
3227 let topDiv = document.createElement("div");
3228 topDiv.setAttribute("style","display:flex;align-items:center;width:100%;text-align:center;border-bottom: grey ridge;background: radial-gradient(gold, #f0f0f0)");
3229 let gameTitle = document.createElement("span");
3230 gameTitle.setAttribute("style","font-size:30px;user-select:none;cursor:default;flex-grow:1");
3231 gameTitle.setAttribute("id","tmg_gameTitle");
3232 gameTitle.append(game);
3233 topDiv.append(gameTitle);
3234
3235 var tmgClose = document.createElement("button");
3236 tmgClose.setAttribute("style", "cursor:pointer;float:right;height:18px;width:18px;border-radius:18px;cursor:pointer;background-color:#ff7878;margin:2px 9px 2px 2px");
3237 tmgClose.setAttribute("onclick", "minigamesButton.click()");
3238 tmgClose.setAttribute("id", "tmgClose");
3239 tmgClose.setAttribute("title", "Minimise");
3240 topDiv.append(tmgClose);
3241 minigamesElement.append(topDiv);
3242
3243 var offX, offY;
3244 function addListeners() {
3245 document.getElementById('tmg_gameTitle').addEventListener('mousedown', mouseDown, false);
3246 window.addEventListener('mouseup', mouseUp, false);
3247
3248 }
3249 function mouseUp() {
3250 window.removeEventListener('mousemove', divMove, true);
3251 }
3252 function mouseDown(e) {
3253 var div = document.getElementById('gameWrapper');
3254 offY= e.clientY-parseInt(div.offsetTop);
3255 offX= e.clientX-parseInt(div.offsetLeft);
3256 window.addEventListener('mousemove', divMove, true);
3257 }
3258 function divMove(e) {
3259 var div = document.getElementById("gameWrapper");
3260 div.style.position = "absolute";
3261 div.style.top = (e.clientY-offY) + 'px';
3262 div.style.left = (e.clientX-offX) + 'px';
3263 if (div.offsetLeft < 1) {
3264 div.style.left = "1px";
3265 }
3266 if (div.offsetTop < 50) {
3267 div.style.top = "50px";
3268 }
3269 /*if (div.offsetLeft > $(window).width() - 50 - div.offsetWidth) {
3270 div.style.left = $(window).width() - 50 - div.offsetWidth + "px";
3271 }
3272 if (div.offsetTop > $(window).height() - 50 - div.offsetHeight) {
3273 div.style.top = $(window).height() - 50 - div.offsetHeight + "px";
3274 }*/
3275 }
3276 addListeners();
3277
3278 minigamesElement.append(document.createElement("br"));
3279 let reset = document.createElement("input");
3280 reset.setAttribute("type", "button");
3281 reset.setAttribute("id", "tmg_reset");
3282 reset.setAttribute("value", "Temporary Reset Button");
3283 reset.setAttribute("onclick", "tmgReset()");
3284 reset.setAttribute("style", "float:right;padding-right:10px;");
3285 minigamesElement.append(reset);
3286 minigamesElement.append(document.createElement("br"));
3287
3288 let inputGame = document.createElement("select");
3289 inputGame.setAttribute("id", "inputGame");
3290 inputGame.setAttribute("style", "cursor:pointer;user-select:none;");
3291 inputGame.setAttribute("onchange", "changeLobbyView()");
3292 Object.keys(minigamesObject).forEach((game) => {
3293 let opt = document.createElement("option");
3294 opt.setAttribute("value", game);
3295 opt.append(game);
3296 inputGame.append⌥;
3297 });
3298 inputGame.setAttribute("value", minigameGame);
3299 minigamesElement.append(inputGame);
3300 minigamesElement.append(document.createElement("br"));
3301
3302 if (minigameCurrentSelectedGame.toLowerCase().includes("poker")) {
3303 let tmg_pokerServerConnect = document.createElement("input");
3304 tmg_pokerServerConnect.setAttribute("id","tmg_pokerServerConnect");
3305 tmg_pokerServerConnect.setAttribute("type","button");
3306 tmg_pokerServerConnect.setAttribute("value","Disconnected");
3307 tmg_pokerServerConnect.setAttribute("style","cursor:pointer;user-select:none;outline:0;font-weight:bold;border-radius:10px;border:#990000 ridge;background:radial-gradient(white, #f4cccc, #ea9999)");
3308 tmg_pokerServerConnect.setAttribute("onclick","tmg_pokerServerConnectChangeButton()");
3309 minigamesElement.append(tmg_pokerServerConnect);
3310 minigamesElement.append(document.createElement("br"));
3311 minigamesElement.append(pokerLobbyContainer);
3312 } else if (minigameCurrentSelectedGame == "Grid Control") {
3313 let tempHelp = document.createElement("span");
3314 tempHelp.style.fontSize = "20px";
3315 tempHelp.append("Super early version, click your coloured number, use the cursor to point at target square, use keys: 1/2/3/4 to move to adjacent square, capture territory bonuses to gain more units. 1= send 100%, 2=50%, 3=33%, 4=25%. If something bugs out use the Reset button to quit the current game. If the game unexpectedly closes, your opponent just hit Reset.");
3316 minigamesElement.append(tempHelp);
3317 minigamesElement.append(document.createElement("br"));
3318 let challengeFlex = document.createElement("div");
3319 challengeFlex.setAttribute("style", "display:flex;flex-direction:row;align-items:center;justify-content:center");
3320 minigamesElement.append(challengeFlex);
3321 minigamesElement.append(document.createElement("br"));
3322 let inputOpp = document.createElement("input");
3323 inputOpp.setAttribute("type", "text");
3324 inputOpp.setAttribute("id", "inputOpp");
3325 inputOpp.setAttribute("maxlength", "12");
3326 inputOpp.setAttribute("placeholder", "Opponent name...");
3327 inputOpp.setAttribute("style", "width:125px");
3328 window.enterSendChallenge = function() {
3329 if (typeof(inputOppChallengeSent) != "undefined" && event.keyCode == 13 && !inputOppChallengeSent) {
3330 document.getElementById('submitOpp').click();
3331 inputOppChallengeSent=true;
3332 }
3333 };
3334 inputOpp.setAttribute("onkeydown", "enterSendChallenge();");
3335 inputOpp.setAttribute("onkeyup", "inputOppChallengeSent=false");
3336 challengeFlex.append(inputOpp);
3337 challengeFlex.append(document.createTextNode("\u00a0")); //nbsp
3338 let inputVersion = document.createElement("select");
3339 inputVersion.setAttribute("id", "inputVersion");
3340 inputVersion.setAttribute("onchange", "showOrHideSeedInput()");
3341 Object.keys(minigamesObject[minigameCurrentSelectedGame].maps).forEach((map) => {
3342 let opt = document.createElement("option");
3343 opt.setAttribute("value", map);
3344 opt.append(map);
3345 inputVersion.append⌥;
3346 });
3347 challengeFlex.append(inputVersion);
3348 challengeFlex.append(document.createTextNode("\u00a0")); //nbsp
3349 let currentSelectedMap = document.getElementById("inputVersion").value;
3350 window.showOrHideSeedInput = function() {
3351 if (minigamesObject[document.getElementById("inputGame").value].maps[document.getElementById("inputVersion").value].mapGen) {
3352 document.getElementById("inputSeed").disabled = false;
3353 document.getElementById("inputSeed").focus();
3354 } else document.getElementById("inputSeed").disabled = true;
3355 };
3356 let inputSeed = document.createElement("input");
3357 inputSeed.setAttribute("type", "text");
3358 inputSeed.setAttribute("id", "inputSeed");
3359 inputSeed.setAttribute("placeholder", "Input seed...");
3360 inputSeed.setAttribute("style", "width: 125px");
3361 inputSeed.setAttribute("maxlength", "12");
3362 if (minigamesObject[minigameCurrentSelectedGame].maps[currentSelectedMap].mapGen) {
3363 inputSeed.disabled = false;
3364 } else inputSeed.disabled = true;
3365 if (minigameSeed && minigameSeed != "!NOSEED!") {
3366 inputSeed.setAttribute("value", minigameSeed);
3367 }
3368 challengeFlex.append(inputSeed);
3369 challengeFlex.append(document.createTextNode("\u00a0")); //nbsp
3370 let submitOpp = document.createElement("input");
3371 submitOpp.setAttribute("type", "button");
3372 submitOpp.setAttribute("id", "submitOpp");
3373 submitOpp.setAttribute("value", "Challenge");
3374 submitOpp.setAttribute("onclick", "sendChallenge()");
3375 challengeFlex.append(submitOpp);
3376 challengeFlex.append(document.createTextNode("\u00a0")); //nbsp
3377 if (minigameMyStatus == "ingame") {
3378 let surrender = document.createElement("input");
3379 surrender.setAttribute("type", "button");
3380 surrender.setAttribute("id", "tmg_surrender");
3381 surrender.setAttribute("value", "Surrender");
3382 surrender.setAttribute("onclick", "gc_checkVictory('"+minigameMyPlayer+"')");
3383 challengeFlex.append\_(-_-)_/;
3384 }
3385 minigamesElement.append(challengeContainer);
3386 minigamesElement.append(versusContainer);
3387 minigamesElement.append(document.createElement("br"));
3388 }
3389
3390 if (game == "Minigames") {
3391 } else if (game == "Poker") {
3392 //gamecode
3393 window.arrangeSeats = function() {
3394 let maxPlayers = minigamesObject.Poker.tables["1"].gameInfo.maxPlayers;
3395 var seatLocations = {
3396 1: {
3397 top: "10%",
3398 bottom: "",
3399 left: "12%",
3400 button: {
3401 top: "25%",
3402 bottom: "",
3403 left: "18%",
3404 },
3405 betBox: {
3406 top: "32%",
3407 bottom: "",
3408 left: "25%",
3409 },
3410 },
3411 2: {
3412 top: "0%",
3413 bottom: "",
3414 left: "50%",
3415 button: {
3416 top: "15%",
3417 bottom: "",
3418 left: "56%",
3419 },
3420 betBox: {
3421 top: "25%",
3422 bottom: "",
3423 left: "50%",
3424 },
3425 },
3426 3: {
3427 top: "10%",
3428 bottom: "",
3429 left: "88%",
3430 button: {
3431 top: "20%",
3432 bottom: "",
3433 left: "75%",
3434 },
3435 betBox: {
3436 top: "32%",
3437 bottom: "",
3438 left: "75%",
3439 },
3440 },
3441 4: {
3442 top: "",
3443 bottom: "10%",
3444 left: "88%",
3445 button: {
3446 top: "",
3447 bottom: "20%",
3448 left: "75%",
3449 },
3450 betBox: {
3451 top: "",
3452 bottom: "32%",
3453 left: "75%",
3454 },
3455 },
3456 5: {
3457 top: "",
3458 bottom: "0%",
3459 left: "50%",
3460 button: {
3461 top: "",
3462 bottom: "15%",
3463 left: "56%",
3464 },
3465 betBox: {
3466 top: "",
3467 bottom: "25%",
3468 left: "50%",
3469 },
3470 },
3471 6: {
3472 top: "",
3473 bottom: "10%",
3474 left: "12%",
3475 button: {
3476 top: "",
3477 bottom: "25%",
3478 left: "18%",
3479 },
3480 betBox: {
3481 top: "",
3482 bottom: "32%",
3483 left: "25%",
3484 },
3485 },
3486 }; // 6max
3487 var seatAdjust = 5 - minigamePokerMySeat; // rotate all seats so player is in seat 5 (bottom middle)
3488 for (let i = 1; i <= 6; i++) {
3489 let a = i + seatAdjust;
3490 if (a < 1) a = 6 - a;
3491 if (a > 6) a = a - 6;
3492 let pokerSeat = document.createElement("div");
3493 pokerSeat.setAttribute("style","display:none;position:absolute;top:"+seatLocations[a].top+";bottom:"+seatLocations[a].bottom+";left:"+seatLocations[a].left+";transform:translate(-50%, 0)");
3494 pokerSeat.setAttribute("id","poker_seat_"+i);
3495 let newFlex = document.createElement("div");
3496 newFlex.setAttribute("style","display:flex;flex-direction:row;align-items:center;justify-content:center");
3497 pokerSeat.append(newFlex);
3498 let cardSlot1 = document.createElement("div");
3499 cardSlot1.setAttribute("style","display:none;width:80px;height:112px");
3500 cardSlot1.setAttribute("id","poker_"+i+"_card1");
3501 newFlex.append(cardSlot1);
3502 let cardSlot2 = document.createElement("div");
3503 cardSlot2.setAttribute("style","display:none;width:80px;height:112px");
3504 cardSlot2.setAttribute("id","poker_"+i+"_card2");
3505 newFlex.append(cardSlot2);
3506 let playerInfo = document.createElement("div");
3507 playerInfo.setAttribute("style","display:none;flex-direction:column;align-items:center;justify-content:center;text-align:center;min-width:80px;border-style:ridge;border-color:grey;background:black;color:white");
3508 playerInfo.setAttribute("id","poker_"+i+"_playerinfo");
3509 playerInfo.append(document.createElement("br"));
3510 let chips = document.createElement("div");
3511 chips.append(coinImg.cloneNode());
3512 playerInfo.append(chips);
3513 newFlex.append(playerInfo);
3514 poker_table_container.append(pokerSeat);
3515
3516 let betBox = document.createElement("div");
3517 betBox.setAttribute("style","display:none;position:absolute;top:"+seatLocations[a].betBox.top+";bottom:"+seatLocations[a].betBox.bottom+";left:"+seatLocations[a].betBox.left+";transform:translate(-50%, 0);border-style:ridge;border-color:grey;background:black;color:white");
3518 betBox.setAttribute("id","poker_betBox_"+i);
3519 betBox.append(coinImg.cloneNode());
3520 poker_table_container.append(betBox);
3521
3522 let pokerButton = document.createElement("img");
3523 pokerButton.setAttribute("style","display:none;width:50px;height:50px;position:absolute;top:"+seatLocations[a].button.top+";bottom:"+seatLocations[a].button.bottom+";left:"+seatLocations[a].button.left+";transform:translate(-50%, 0)");
3524 pokerButton.setAttribute("id","poker_button_"+i);
3525 pokerButton.setAttribute("src","images/donorCoins.png");
3526 poker_table_container.append(pokerButton);
3527
3528 loadCard("??","poker_"+i+"_card1");
3529 loadCard("??","poker_"+i+"_card2");
3530 }
3531
3532 let communityCards = document.createElement("div");
3533 communityCards.setAttribute("style","display:flex;flex-direction:row;justify-content:flex-start;width:400px;height:112px;position:absolute;top:45%;left:50%;transform:translate(-50%, 0)");
3534 poker_table_container.append(communityCards);
3535 for (let i = 1; i <= 5; i++) {
3536 let community = document.createElement("div");
3537 community.setAttribute("style","display:none");
3538 community.setAttribute("id","poker_community_" + i);
3539 communityCards.append(community);
3540
3541 loadCard("3h","poker_community_"+i);
3542 }
3543 let potsContainer = poker_table_container.appendChild(document.createElement("div"));
3544 potsContainer.setAttribute("style","display:flex;justify-content:center;text-align:center;position:absolute;top:34%;left:50%;transform:translate(-50%, 0)");
3545 potsContainer.setAttribute("id","tmg_pokerPotsContainer");
3546 let mainPotContainer = potsContainer.appendChild(document.createElement("div"));
3547 mainPotContainer.setAttribute("style","text-align:center;background:black;color:white;border-style:ridge;border-color:grey;display:flex;flex-direction:column;justify-content:center;width:90px;height:35px");
3548 let mainPotText = mainPotContainer.appendChild(document.createTextNode("Main Pot"));
3549 mainPotContainer.append(document.createElement("br"));
3550 let mainPot = mainPotContainer.appendChild(document.createElement("div"));
3551 mainPot.setAttribute("id","tmg_pokerMainPot");
3552 mainPot.append("0");
3553 };
3554 var poker_table_container = document.createElement("div");
3555 poker_table_container.setAttribute("style", "position:relative");
3556 poker_table_container.setAttribute("id", "poker_table_container");
3557 minigamesElement.append(poker_table_container);
3558 let tableBackground = document.createElement("img");
3559 tableBackground.src = "http://i.imgur.com/CAVjRPT.png";
3560 tableBackground.setAttribute("style","width:1200px"); //width:90vw;max-width:1200px
3561 tableBackground.setAttribute("id","pokerTableBackground");
3562 poker_table_container.append(tableBackground);
3563 arrangeSeats();
3564 } else if (game == "Grid Control") {
3565 // Grid Control Game
3566 let gc_container = document.createElement("div");
3567 gc_container.setAttribute("style", "background:black;color:white");
3568 gc_container.setAttribute("id", "gc_container");
3569 minigamesElement.append(gc_container);
3570 gc_lastClicked = false;
3571 var grid = clickableGrid(9, 9, "Standard map", function(el) {
3572 if (minigameMyPlayer == el.getAttribute("gc_owner")) {
3573 el.style.boxShadow = "0px 0px 20px 5px gold inset";
3574 if (gc_lastClicked && el != gc_lastClicked) {
3575 gc_lastClicked.style.boxShadow = "";
3576 }
3577 gc_lastClicked = el;
3578 }
3579 });
3580 gc_container.appendChild(grid);
3581
3582 if (minigamesObject[game].maps[minigameVersion]) {
3583 if (!minigamesObject[game].maps[minigameVersion].mapGen && minigamesObject[game].maps[minigameVersion].mapData) {
3584 //not mapGen, but has mapData (default maps same every time)
3585 let mapData = minigamesObject[game].maps[minigameVersion].mapData;
3586 mapData.forEach(obj => {
3587 let gridObj = document.getElementById("gc_"+obj.id);
3588 for (let key in obj) {
3589 if (key == "id") continue;
3590 gridObj.setAttribute(key, obj[key]);
3591 }
3592 });
3593 } else if (minigamesObject[game].maps[minigameVersion].mapGen) {
3594 //mapGen using seed
3595 if (minigameVersion == "Ted map gen") {
3596 gc_mapFromSeed(seedPRNG(minigameSeed));
3597 } else if (minigameVersion == "FlipskiZ map gen"){
3598 gc_flipskiMapFromSeed(minigameSeed);
3599 }
3600 } else console.log("No map data or map gen for this version: "+minigameVersion);
3601 gc_redrawGrid();
3602 initialHighlightLastClicked();
3603 } else console.log(game+ " map not found: "+minigameVersion);
3604
3605 setTimeout(function() {
3606 window.gc_highlightCurrentPlayer();
3607 window.gc_countUnits();
3608 }, 1);
3609 window.onmousemove = function(mouseMove) {
3610 browserMouseX = mouseMove.clientX;
3611 browserMouseY = mouseMove.clientY;
3612 var overElements = document.elementsFromPoint(browserMouseX, browserMouseY);
3613 if (lastHover && lastHover != overElements[0] && (lastHover != gc_lastClicked || !gc_lastClicked)) {
3614 lastHover.style.boxShadow = "";
3615 }
3616 if (overElements.includes(gc_container) && overElements[0].getAttribute("gc_row")) {
3617 if (!gc_lastClicked || gc_lastClicked != overElements[0]) {
3618 overElements[0].style.boxShadow = "0px 0px 10px 5px green inset";
3619 }
3620 lastHover = overElements[0];
3621 }
3622 };
3623 window.onkeypress = function(event) {
3624 event = event || window.event;
3625 var charCode = event.keyCode || event.which;
3626 var overElements = document.elementsFromPoint(browserMouseX, browserMouseY);
3627 if (overElements.includes(gc_container) && gc_lastClicked && overElements[0].getAttribute("id").replace(/\D+/g, "")) {
3628 let endPoint = overElements[0];
3629 if (endPoint.getAttribute("id").replace(/\D+/g, "") !== gc_lastClicked.getAttribute("id").replace(/\D+/g, "") && endPoint.getAttribute("gc_row") - gc_lastClicked.getAttribute("gc_row") <= 1 && endPoint.getAttribute("gc_row") - gc_lastClicked.getAttribute("gc_row") >= -1 && endPoint.getAttribute("gc_col") - gc_lastClicked.getAttribute("gc_col") <= 1 && endPoint.getAttribute("gc_col") - gc_lastClicked.getAttribute("gc_col") >= -1) {
3630 if (charCode == 49) {
3631 gc_moveUnits(gc_lastClicked, endPoint, "100");
3632 } else if (charCode == 50) {
3633 gc_moveUnits(gc_lastClicked, endPoint, "50");
3634 } else if (charCode == 51) {
3635 gc_moveUnits(gc_lastClicked, endPoint, "33");
3636 } else if (charCode == 52) {
3637 gc_moveUnits(gc_lastClicked, endPoint, "25");
3638 }
3639 }
3640 }
3641 };
3642 }
3643 };
3644
3645 function minigamesInit() {
3646 let gameWrapper = document.createElement("div");
3647 gameWrapper.setAttribute("id", "gameWrapper");
3648 gameWrapper.setAttribute("style", "position:absolute;left:200px;top:200px;max-width:1200px;display:none;background-color:#dddddd;border-style:ridge;border-color:grey");
3649 document.body.append(gameWrapper);
3650 minigamesElement.setAttribute("style", "min-width:200px;background:linear-gradient(#eff1c5,#a2a77f);display:flex;flex-direction:column;align-items:center;justify-content:center");
3651 minigamesElement.setAttribute("id", "minigamesElement");
3652 gameWrapper.append(minigamesElement);
3653 loadMinigame("Minigames");
3654 }
3655 // END OF MINIGAMES
3656 function getMarketItems() {
3657 var currentItemId;
3658 arrMarketItems = {};
3659 for (var i = 1; i < document.getElementById("market-table").rows.length; i++) {
3660 if (typeof(document.getElementById("market-table").rows[i].childNodes[0]) != "undefined" && document.getElementById("market-table").rows[i].childNodes[0] !== null) {
3661 let itemName = itemNameFix(document.getElementById("market-table").rows[i].childNodes[0].innerHTML);
3662 let itemId = parseInt(document.getElementById("market-table").rows[i].getAttribute("data-market-itemid"));
3663 let itemPrice = parseInt(document.getElementById("market-table").rows[i].getAttribute("data-market-price"));
3664 let itemAmount = parseInt(document.getElementById("market-table").rows[i].getAttribute("data-market-amount"));
3665 let itemMarketId = parseInt(document.getElementById("market-table").rows[i].getAttribute("data-market-marketid"));
3666 let row = parseInt(i);
3667 if (itemId != currentItemId) {
3668 currentItemId = itemId;
3669 if (!arrMarketItems[itemName]) {
3670 arrMarketItems[itemName] = [];
3671 }
3672 }
3673 arrMarketItems[itemName].push({
3674 id: itemId,
3675 price: itemPrice,
3676 amount: itemAmount,
3677 marketid: itemMarketId,
3678 row: row
3679 });
3680 }
3681 }
3682 }
3683
3684 function addItemTooltips() {
3685 if (itemTooltips) {
3686 for (var i = 0; i < Object.keys(arrMarketItems).length; i++) {
3687 if (document.getElementById("tooltip-" + Object.keys(arrMarketItems)[i]) !== null) {
3688 let itemName = Object.keys(arrMarketItems)[i];
3689 let minPrice = arrMarketItems[Object.keys(arrMarketItems)[i]][0].price;
3690 let marketTotal = window[itemName] * minPrice;
3691 var newTooltip = "<b>Market price: </b><img class='image-icon-20' src='images/coins.png'> " + numberWithCommas(minPrice) + "<br><b>Market total: </b><img class='image-icon-20' src='images/coins.png'> " + numberWithCommas(marketTotal);
3692 if (document.getElementById("tooltip-" + itemName).lastElementChild.tagName == "DIV") {
3693 document.getElementById("tooltip-" + itemName).removeChild(document.getElementById("tooltip-" + itemName).lastChild);
3694 }
3695 var tooltipElement = document.createElement("div");
3696 tooltipElement.innerHTML = newTooltip;
3697 document.getElementById("tooltip-" + itemName).appendChild(tooltipElement);
3698 }
3699 }
3700 }
3701 }
3702 window.disableBtn = function(btn, time) {
3703 if (!btn.disabled) {
3704 var oldStyle;
3705 if (btn.parentNode && btn.parentNode.id == "browseAllElementWrapper") {
3706 oldStyle = "margin:5px;padding:0px;";
3707 } else oldStyle = "";
3708 btn.disabled = true;
3709 sendToSpreadsheet_timeoutStart = new Date().getTime();
3710 if (btn.id == "ted-browse-all" && sendMarketData === true && sendToSpreadsheet_timeoutStart - sendToSpreadsheet_timeout > sendMarketDataWaitTimeMins) {
3711 btn.setAttribute("style", oldStyle + "box-shadow: 0 0 30px 6px rgba(0, 255, 0, 1) inset;transition: box-shadow 0.3s ease-out;");
3712 setTimeout(function() {
3713 btn.setAttribute("style", oldStyle + "box-shadow: 0 0 30px 6px rgba(0, 255, 0, 0) inset;transition: box-shadow 0.3s ease-out;");
3714 btn.disabled = false;
3715 }, time);
3716 } else {
3717 btn.setAttribute("style", oldStyle + "box-shadow: 0 0 30px 6px rgba(255, 0, 0, 1) inset;transition: box-shadow 0.3s ease-out;");
3718 setTimeout(function() {
3719 btn.setAttribute("style", oldStyle + "box-shadow: 0 0 30px 6px rgba(255, 0, 0, 0) inset;transition: box-shadow 0.3s ease-out;");
3720 btn.disabled = false;
3721 }, time);
3722 }
3723 }
3724 };
3725
3726 function sendToSpreadsheet(msg) {
3727 if (sendMarketData === true) {
3728 sendToSpreadsheet_timeoutStart = new Date().getTime();
3729 if (sendToSpreadsheet_timeoutStart - sendToSpreadsheet_timeout > sendMarketDataWaitTimeMins) {
3730 sendToSpreadsheet_timeout = sendToSpreadsheet_timeoutStart;
3731 $.post("https://script.google.com/macros/s/AKfycbx_izl1yk0PLUNp4te3swi3uSxrEu4L7E0JueJ72cS0r899Wj7z/exec", {
3732 marketData: msg,
3733 user: username
3734 });
3735 $.post("https://dhmarket.000webhostapp.com/data_post.php", {
3736 marketData: msg,
3737 user: username
3738 });
3739 console.log("Ted's Market: Don't worry about 'XMLHttpRequest cannot load...' error, data was sent successfully.");
3740 }
3741 }
3742 }
3743
3744 function calculateFlips() {
3745 totalFlipProfit = 0;
3746 var arrProfitDone = [];
3747 for (let i = 0; i < tedStoredSettings.tradeHistory.length; i++) {
3748 var objArr = [];
3749 let th = tedStoredSettings.tradeHistory[i];
3750 if (!isInArray(arrProfitDone, th.name)) {
3751 if ((exactMatch && th.name.toLowerCase().match(exactSearch)) || !exactMatch && (searchString === "" || th.name.toLowerCase().includes(searchString) || getItemName(th.name).toLowerCase().includes(searchString))) {
3752 for (let a = i; a < tedStoredSettings.tradeHistory.length; a++) {
3753 let tha = tedStoredSettings.tradeHistory[a];
3754 if (tha.name == th.name) {
3755 let tradeType = tha.tradetype;
3756 if (tradeType == "buy") {
3757 if (typeof(tha.flipaccountedfor == "undefined")) {
3758 tha.flipaccountedfor = 0;
3759 }
3760 if (tha.flipaccountedfor == tha.amount) {
3761 continue;
3762 } else {
3763 objArr.push(tha);
3764 }
3765 } else if (tradeType == "sell") {
3766 if (typeof(tha.flipamount == "undefined")) {
3767 tha.flipamount = 0;
3768 }
3769 if (typeof(tha.flipprofit == "undefined")) {
3770 tha.flipprofit = 0;
3771 }
3772 if (tha.flipamount == tha.amount) {
3773 totalFlipProfit += tha.flipprofit;
3774 continue;
3775 } else if (objArr.length > 0) {
3776 objArr.sort(function(a, b) {
3777 return a.price == b.price ? 0 : +(a.price > b.price) || -1;
3778 });
3779 for (let b = 0; b < objArr.length; b++) {
3780 if (objArr[b].flipaccountedfor == objArr[b].amount) {
3781 continue;
3782 } else {
3783 let price = objArr[b].price;
3784 if (price !== tha.price) {
3785 let amountUnaccounted = objArr[b].amount - objArr[b].flipaccountedfor;
3786 let diff = tha.amount - tha.flipamount;
3787 if (amountUnaccounted < diff) {
3788 tha.flipamount += amountUnaccounted;
3789 tha.flipprofit += ((tha.price - price) * amountUnaccounted);
3790 objArr[b].flipaccountedfor = objArr[b].amount;
3791 } else if (amountUnaccounted >= diff) {
3792 tha.flipamount += diff;
3793 tha.flipprofit += ((tha.price - price) * diff);
3794 objArr[b].flipaccountedfor += diff;
3795 }
3796 }
3797 }
3798 }
3799 totalFlipProfit += tha.flipprofit;
3800 }
3801 }
3802 }
3803 }
3804 }
3805 }
3806 arrProfitDone.push(th.name);
3807 }
3808 if (searchVal === "") {
3809 document.getElementById("thTotalFlipProfit").innerHTML = "Total Flip Profit: " + numberWithCommas(totalFlipProfit);
3810 } else {
3811 document.getElementById("thTotalFlipProfit").innerHTML = "\"" + searchVal + "\" Flip Profit: " + numberWithCommas(totalFlipProfit);
3812 }
3813 updateVariables();
3814 }
3815 window.thSearchLogic = function() {
3816 searchVal = document.getElementById("thSearch").value;
3817 let tempSearchVal = document.getElementById("thSearch").value;
3818 setTimeout(function() {
3819 if (tempSearchVal == document.getElementById("thSearch").value) {
3820 if (document.getElementById("thSearch").value[0] === "=") {
3821 exactMatch = true;
3822 searchString = document.getElementById("thSearch").value.substring(1, document.getElementById("thSearch").value.length).toLowerCase().replace(/\s/g, "");
3823 exactSearch = new RegExp("^" + searchString + "$");
3824 } else {
3825 exactMatch = false;
3826 searchString = document.getElementById("thSearch").value.toLowerCase();
3827 }
3828 generateTradeHistoryTable();
3829 calculateFlips();
3830 }
3831 }, 250);
3832 };
3833 window.thDelete = function(arrnum, source) {
3834 if (source.getAttribute("thdeletewarned") == "false") {
3835 setTimeout(function() {
3836 source.setAttribute("thdeletewarned", "true");
3837 }, 300);
3838 source.style.boxShadow = "0 0 30px 3px rgba(255, 0, 0, 1) inset";
3839 source.style.transition = "box-shadow 0.5s ease-in-out";
3840 setTimeout(function() {
3841 if (source) {
3842 source.setAttribute("thdeletewarned", "false");
3843 source.style.boxShadow = "0 0 30px 3px rgba(255, 0, 0, 0) inset";
3844 source.style.transition = "box-shadow 0.5s ease-in-out";
3845 }
3846 }, 1500);
3847 } else if (source.getAttribute("thdeletewarned") == "true") {
3848 for (let i = 0; i < tedStoredSettings.tradeHistory.length; i++) {
3849 if (JSON.stringify(sortedTradeHistory[arrnum]) == JSON.stringify(tedStoredSettings.tradeHistory[i])) {
3850 tedStoredSettings.tradeHistory.splice(i, 1);
3851 calculateFlips();
3852 sortTradeHistory(sortByTH);
3853 updateVariables();
3854 break;
3855 }
3856 }
3857 }
3858 };
3859 window.highlightSorted = function() {
3860 for (let i = 0; i < document.getElementsByClassName("thTH").length; i++) {
3861 if (document.getElementsByClassName("thTH")[i].getAttribute("prop") == sortByTH) {
3862 if ((thSortToggle && sortByTH !== "name") || (!thSortToggle && sortByTH == "name")) {
3863 document.getElementsByClassName("thTH")[i].style.boxShadow = "0px -2px 10px -2px, 0px 2px 3px 1px inset";
3864 document.getElementsByClassName("thTH")[i].style.borderTopStyle = "hidden";
3865 } else {
3866 document.getElementsByClassName("thTH")[i].style.boxShadow = "0px 5px 10px -2px, 0px -2px 3px 1px inset";
3867 document.getElementsByClassName("thTH")[i].style.borderBottomStyle = "hidden";
3868 }
3869 document.getElementsByClassName("thTH")[i].style.transition = "box-shadow 0.25s ease";
3870 break;
3871 }
3872 }
3873 };
3874 window.sortTradeHistory = function(sortBy, invertible) {
3875 if (typeof(invertible) !== "boolean") {
3876 invertible = false;
3877 }
3878 sortedTradeHistory = JSON.parse(JSON.stringify(tedStoredSettings.tradeHistory));
3879 if (invertible && sortBy == sortByTH) {
3880 thSortToggle = !thSortToggle;
3881 } else if (invertible && sortBy == "name") {
3882 thSortToggle = false;
3883 } else if (invertible) {
3884 thSortToggle = true;
3885 }
3886 sortedTradeHistory.sort(function(a, b) {
3887 if (thSortToggle) {
3888 if (a[sortBy] > b[sortBy]) return -1;
3889 }
3890 if (!thSortToggle) {
3891 if (a[sortBy] < b[sortBy]) return -1;
3892 }
3893 if (a[sortBy] == b[sortBy]) {
3894 if (a.date > b.date) return -1;
3895 if (a.date < b.date) return 1;
3896 return 0;
3897 }
3898 if (typeof(a[sortBy]) == "undefined" || a[sortBy] === null || a[sortBy] === 0) return 1;
3899 if (typeof(b[sortBy]) == "undefined" || b[sortBy] === null || b[sortBy] === 0) return -1;
3900 return 1;
3901 });
3902 generateTradeHistoryTable();
3903 sortByTH = sortBy;
3904 };
3905 window.generateTradeHistoryTable = function() {
3906 thString = "";
3907 thString += "<table class='market-table' cellpadding='5px' style='width:100%;cursor:default'>";
3908 thString += "<tr style='background-color:lightgrey'>";
3909 thString += "<th style='width:30px'></th>";
3910 thString += "<th style='cursor:pointer' class='thTH' prop='name' onclick='sortTradeHistory("name", true);sortByTH="name"'>Name</th>";
3911 thString += "<th style='width:30px'>Type</th>";
3912 thString += "<th style='cursor:pointer;width:105px' class='thTH' prop='price' onclick='sortTradeHistory("price", true);sortByTH="price"'>Price</th>";
3913 thString += "<th style='cursor:pointer;width:105px' class='thTH' prop='amount' onclick='sortTradeHistory("amount", true);sortByTH="amount"'>Amount</th>";
3914 thString += "<th style='cursor:pointer;width:105px' class='thTH' prop='total' onclick='sortTradeHistory("total", true);sortByTH="total"'>Total</th>";
3915 thString += "<th style='cursor:pointer;width:105px' class='thTH' prop='flipamount' onclick='sortTradeHistory("flipamount", true);sortByTH="flipamount"'>Flip Amount</th>";
3916 thString += "<th style='cursor:pointer;width:105px' class='thTH' prop='flipprofit' onclick='sortTradeHistory("flipprofit", true);sortByTH="flipprofit"'>Flip Profit</th>";
3917 thString += "<th style='cursor:pointer;width:175px' class='thTH' prop='date' onclick='sortTradeHistory("date", true);sortByTH="date"'>Timestamp</th>";
3918 thString += "<th style='width:60px'>Delete</th>";
3919 thString += "</tr>";
3920 var max3 = 0;
3921 let sellColFade = colorLuminance("#96c896", -0.2);
3922 let buyColFade = colorLuminance("#c89696", -0.2);
3923 for (let i = 0; i < sortedTradeHistory.length; i++) {
3924 if (!sortedTradeHistory[i]) break;
3925 let tradeType = sortedTradeHistory[i].tradetype;
3926 if ((tradeType == "buy" && document.getElementById("thBuyCheckbox").checked) || (tradeType == "sell" && document.getElementById("thSellCheckbox").checked)) {
3927 if ((exactMatch && (sortedTradeHistory[i].name.toLowerCase().match(exactSearch) || getItemName(sortedTradeHistory[i].name).toLowerCase().match(exactSearch))) || !exactMatch && (getItemName(sortedTradeHistory[i].name).toLowerCase().includes(document.getElementById("thSearch").value.toLowerCase()) || sortedTradeHistory[i].name.toLowerCase().includes(document.getElementById("thSearch").value.toLowerCase()) || document.getElementById("thSearch").value === "" || document.getElementById("thSearch").value == " ")) {
3928 if (document.getElementById("thMax3Checkbox").checked) {
3929 if (max3 >= 3) {
3930 break;
3931 }
3932 max3++;
3933 }
3934 let rowColor = "#96c896"; // sell
3935 let rowColor2 = sellColFade; // sell
3936 if (sortedTradeHistory[i].tradetype == "buy") {
3937 rowColor = "#c89696"; // buy
3938 rowColor2 = buyColFade; // buy
3939 }
3940 thString += "<tr onmouseover='highlightRow(this, true);' onmouseout='highlightRow(this, false);' style='background:linear-gradient(" + rowColor + "," + rowColor2 + ")'>";
3941 thString += "<td style='text-align:center'><img class='image-icon-30' src='images/" + sortedTradeHistory[i].name + ".png'></td>";
3942 thString += "<td style='text-align:center'>" + getItemName(sortedTradeHistory[i].name) + "</td>";
3943 thString += "<td style='text-align:center'>" + sortedTradeHistory[i].tradetype + "</td>";
3944 thString += "<td style='text-align:right'>" + numberWithCommas(sortedTradeHistory[i].price) + "</td>";
3945 thString += "<td style='text-align:right'>" + numberWithCommas(sortedTradeHistory[i].amount) + "</td>";
3946 thString += "<td style='text-align:right'>" + numberWithCommas(sortedTradeHistory[i].price * sortedTradeHistory[i].amount) + "</td>";
3947 if (sortedTradeHistory[i].flipamount) {
3948 thString += "<td style='text-align:right'>" + numberWithCommas(sortedTradeHistory[i].flipamount) + "</td>";
3949 } else thString += "<td></td>";
3950 if (sortedTradeHistory[i].flipprofit) {
3951 thString += "<td style='text-align:right'>" + numberWithCommas(sortedTradeHistory[i].flipprofit) + "</td>";
3952 } else thString += "<td></td>";
3953 let d = new Date(sortedTradeHistory[i].date);
3954 let date = new Date(d.getTime() - (d.getTimezoneOffset() * 60000));
3955 thString += "<td style='text-align:center'>" + date.toISOString().substring(11, 19) + " | " + date.toISOString().substring(0, 10) + "</td>";
3956 thString += "<td title='First click: enable delete\nSecond click: permanently delete' arrnum='" + i + "' thdeletewarned='false' style='text-align:center' onclick='thDelete(this.getAttribute("arrnum"),this)'><img class='image-icon-30' src='http://i.imgur.com/S4WuNVn.png'></td>";
3957 thString += "</tr>";
3958 }
3959 }
3960 }
3961 thString += "</table>";
3962 if (document.getElementById("tradeHistoryModalBody").style.display != "none") {
3963 tradeHistoryModalBodyTable.innerHTML = thString;
3964 }
3965 setTimeout(function() {
3966 highlightSorted();
3967 }, 0);
3968 };
3969
3970 function getArrMarketItemObjectFromMarketId(marketId) {
3971 marketId = parseInt(marketId);
3972 for (var i = 0; i < Object.keys(arrMarketItems).length; i++) {
3973 let itemName = Object.keys(arrMarketItems)[i];
3974 for (var a = 0; a < arrMarketItems[itemName].length; a++) {
3975 if (arrMarketItems[itemName][a].marketid == marketId) {
3976 return arrMarketItems[itemName][a];
3977 }
3978 }
3979 }
3980 return undefined;
3981 }
3982
3983 function tmg_pokerCalculateMove(game, table, msgFrom, action, amount) {
3984 function nextPlayer(playersSeatArray, seatCurrentTurn) {
3985 let startSeatIndex = playersSeatArray.indexOf(seatCurrentTurn);
3986 if (startSeatIndex < 0) return -1;
3987 startSeatIndex++;
3988 for (let i = startSeatIndex; i < playersSeatArray.length; i++) {
3989 if (playersSeatArray[i] > startSeatIndex) {
3990 return playersSeatArray[i];
3991 }
3992 }
3993 for (let i = 0; i < playersSeatArray.length; i++) {
3994 if (playersSeatArray[i] > 0) {
3995 return playersSeatArray[i];
3996 }
3997 }
3998 }
3999 var livePlayers = [];
4000 let seat = minigamesObject[game].tables[table].seats[msgFrom].seat;
4001 for (let player in minigamesObject[game].tables[table].seats) {
4002 if (minigamesObject[game].tables[table].seats[player].status == "live") {
4003 livePlayers.push(seat);
4004 }
4005 }
4006 let nextTurn = nextPlayer(livePlayers, seat);
4007 if (nextTurn == seat) {
4008 // if only one person left in the hand
4009 }
4010 let bb = minigamesObject[game].tables[table].gameInfo.bb;
4011 let lastBet = minigamesObject[game].tables[table].currentHand.lastBet;
4012 let lastLastBet = minigamesObject[game].tables[table].currentHand.lastLastBet;
4013 let stack = minigamesObject[game].tables[table].seats[msgFrom].chips;
4014 let handNumber = minigamesObject[game].tables[table].handNumber;
4015 if (action == "FOLD") {
4016 minigamesObject[game].tables[table].seats[msgFrom].status = "folded";
4017 minigamesObject[game].tables[table].currentHand.currentTurn = nextTurn;
4018 let currentHandJSON = JSON.stringify(minigamesObject[game].tables[table].currentHand);
4019 for (let player in minigamesObject[game].tables[table].seats) {
4020 sendp2p(player, "CURRENT_HAND", table, handNumber, currentHandJSON);
4021 tmg_pokerInterpretMove(table, msgFrom, action, amount);
4022 }
4023 } else if (action == "BET" && lastBet == bb) {
4024 if (stack >= amount && (amount >= bb || (stack < bb && amount == stack))) {
4025 //valid bet
4026 minigamesObject[game].tables[table].currentHand.lastLastBet = minigamesObject[game].tables[table].currentHand.lastBet;
4027 minigamesObject[game].tables[table].currentHand.lastBet = amount;
4028 minigamesObject[game].tables[table].seats[msgFrom].chips -= amount;
4029 minigamesObject[game].tables[table].seats[msgFrom].chipsInPotThisStreet = amount;
4030 minigamesObject[game].tables[table].curentHand.totalPot += amount;
4031 sendp2p(msgFrom, "VALID_MOVE", action, amount);
4032 minigamesObject[game].tables[table].currentHand.currentTurn = nextTurn;
4033 let currentHandJSON = JSON.stringify(minigamesObject[game].tables[table].currentHand);
4034 for (let player in minigamesObject[game].tables[table].seats) {
4035 sendp2p(player, "CURRENT_HAND", table, handNumber, currentHandJSON);
4036 tmg_pokerInterpretMove(table, msgFrom, action, amount);
4037 }
4038 return true;
4039 } else {
4040 sendp2p(msgFrom, "INVALID_MOVE", action, amount);
4041 }
4042 } else if (action == "RAISE") {
4043 if (stack >= amount && ((amount >= ((lastBet * 2) - lastLastBet)) || amount == stack)) {
4044 //valid raise
4045 minigamesObject[game].tables[table].currentHand.lastLastBet = minigamesObject[game].tables[table].currentHand.lastBet;
4046 minigamesObject[game].tables[table].currentHand.lastBet = amount;
4047 minigamesObject[game].tables[table].seats[msgFrom].chips -= amount;
4048 minigamesObject[game].tables[table].seats[msgFrom].chipsInPotThisStreet += amount;
4049 let totalPot = minigamesObject[game].tables[table].currentHand.potPreviousStreets;
4050 for (let player in minigamesObject[game].tables[table].seats) {
4051 totalPot += minigamesObject[game].tables[table].seats[player].chipsInPotThisStreet;
4052 }
4053 minigamesObject[game].tables[table].curentHand.totalPot = totalPot;
4054 sendp2p(msgFrom, "VALID_MOVE", action, amount);
4055 minigamesObject[game].tables[table].currentHand.currentTurn = nextTurn;
4056 let currentHandJSON = JSON.stringify(minigamesObject[game].tables[table].currentHand);
4057 for (let player in minigamesObject[game].tables[table].seats) {
4058 sendp2p(player, "CURRENT_HAND", table, handNumber, currentHandJSON);
4059 tmg_pokerInterpretMove(table, msgFrom, action, amount);
4060 }
4061 return true;
4062 } else {
4063 sendp2p(msgFrom, "INVALID_MOVE", action, amount);
4064 }
4065 } else if (action == "CALL") {
4066 let chipsAlreadyIn = minigamesObject[game].tables[table].seats[msgFrom].chipsInPotThisStreet;
4067 var callAmount = amount;
4068 if (stack + chipsAlreadyIn <= amount) {
4069 minigamesObject[game].tables[table].seats[msgFrom].status = "all in";
4070 callAmount = stack + chipsAlreadyIn;
4071 }
4072 //below is unfinished copypaste from raise, need to figure out call amount and side pots :/
4073
4074 minigamesObject[game].tables[table].seats[msgFrom].chips -= amount;
4075 minigamesObject[game].tables[table].seats[msgFrom].chipsInPotThisStreet += amount;
4076 let totalPot = minigamesObject[game].tables[table].currentHand.potPreviousStreets;
4077 for (let player in minigamesObject[game].tables[table].seats) {
4078 totalPot += minigamesObject[game].tables[table].seats[player].chipsInPotThisStreet;
4079 }
4080 minigamesObject[game].tables[table].curentHand.totalPot = totalPot;
4081 sendp2p(msgFrom, "VALID_MOVE", action, amount);
4082 minigamesObject[game].tables[table].currentHand.currentTurn = nextTurn;
4083 let currentHandJSON = JSON.stringify(minigamesObject[game].tables[table].currentHand);
4084 for (let player in minigamesObject[game].tables[table].seats) {
4085 sendp2p(player, "CURRENT_HAND", table, handNumber, currentHandJSON);
4086 tmg_pokerInterpretMove(table, msgFrom, action, amount);
4087 }
4088 return true;
4089 }
4090 return false;
4091 }
4092
4093 function tmg_pokerAlreadySeated(game, msgFrom) {
4094 for (let table in minigamesObject[game].tables) {
4095 if (minigamesObject[game].tables[table].seats[msgFrom]) {
4096 return true;
4097 }
4098 }
4099 return false;
4100 }
4101 function tmg_pokerSendToAllAtTable(table, msg, excludeUser) {
4102 let arrSendList = [];
4103 for (let player in minigamesObject.Poker.tables[table].seats) {
4104 arrSendList.push(player);
4105 }
4106 for (let observer in minigamesObject.Poker.tables[table].observers) {
4107 arrSendList.push(observer);
4108 }
4109 if (excludeUser && arrSendList.indexOf(excludeUser) >= 0) {
4110 arrSendList.splice(indexOf(excludeUser), 1);
4111 }
4112 arrSendList.forEach(user => {
4113 sendp2p(user, msg);
4114 });
4115 }
4116 function tmg_pokerSitUp(game, msgFrom, table, seat) {
4117 if (minigamesObject[game].tables[table]) {
4118 if (minigamesObject[game].tables[table].seats[msgFrom]) {
4119 if (window.username == pokerServerUsername) {
4120 tmg_pokerSendToAllAtTable(table, ["LEAVE_TABLE", table, seat].join("#"), msgFrom);
4121 sendp2p(msgFrom, "SIT_UP", table, seat);
4122 } else if (minigamePokerMyTable == table) {
4123 //show sat up
4124 document.getElementById("poker_seat_" + seat).style.display = "none";
4125 document.getElementById("poker_betBox_" + seat).style.display = "none";
4126 }
4127 delete minigamesObject[game].tables[table].seats[msgFrom];
4128 if (msgFrom == window.username) {
4129 minigameMyStatus = "free";
4130 loadMinigame("Minigames");
4131 }
4132 return true;
4133 }
4134 }
4135 return false;
4136 }
4137 function tmg_pokerLeaveTable(game, msgFrom, table, seat) {
4138 if (minigamesObject[game].tables[table]) {
4139 if (minigamesObject[game].tables[table].seats[msgFrom]) {
4140 if (window.username == pokerServerUsername) {
4141 sendp2p(msgFrom, "LEAVE_TABLE", msgFrom, table);
4142 for (let player in minigamesObject[game].tables[table].seats) {
4143 sendp2p(player, "LEAVE_TABLE", table, seat);
4144 }
4145 }
4146 if (minigamePokerMyTable == table) {
4147 document.getElementById("poker_seat_"+seat).style.display = "none";
4148 document.getElementById("poker_betBox_"+seat).style.display = "none";
4149 }
4150 delete minigamesObject[game].tables[table].seats[msgFrom];
4151 if (msgFrom == window.username) {
4152 minigameMyStatus = "free";
4153 loadMinigame("Minigames");
4154 }
4155 return true;
4156 }
4157 }
4158 return false;
4159 }
4160
4161 window.tmg_pokerSetUpTable = function() {
4162 let table = minigamesObject.Poker.tables[minigamePokerMyTable];
4163 for (let player in table.seats) {
4164 let name = table.seats[player].name;
4165 let seat = table.seats[player].seat;
4166 let chips = table.seats[player].chips;
4167 let chipsInPotThisStreet = table.seats[player].chipsInPotThisStreet;
4168 let status = table.seats[player].status;
4169
4170 let pokerSeat = document.getElementById("poker_seat_"+seat);
4171 pokerSeat.style.display = "";
4172
4173 if (status.includes("live")) {
4174 document.getElementById("poker_"+seat+"_card1").style.display = "";
4175 document.getElementById("poker_"+seat+"_card2").style.display = "";
4176 }
4177
4178 let playerInfo = document.getElementById("poker_"+seat+"_playerinfo");
4179 playerInfo.style.display = "flex";
4180 while (playerInfo.firstChild) {
4181 playerInfo.removeChild(playerInfo.firstChild);
4182 }
4183 playerInfo.append(name);
4184 playerInfo.append(document.createElement("br"));
4185 let stackDiv = playerInfo.appendChild(document.createElement("div"));
4186 stackDiv.append(coinImg.cloneNode());
4187 stackDiv.append(chips);
4188
4189 if (minigamesObject.Poker.tables[minigamePokerMyTable].currentHand.dealerButton == name) {
4190 document.getElementById("poker_button_"+seat).style.display = "";
4191 }
4192 if (chipsInPotThisStreet >= 1) {
4193 let betBox = document.getElementById("poker_betBox_"+seat);
4194 betBox.style.display = "";
4195 betBox.append(coinImg.cloneNode());
4196 betBox.append(chipsInPotThisStreet);
4197 }
4198 }
4199 };
4200
4201 function tmg_pokerConnectionLost() {
4202 console.log("start of tmg_pokerConnectionLost");
4203 if (minigameTryingToConnectToPokerServer) {
4204 minigameConnectedToPokerServer = false;
4205 document.getElementById("tmg_pokerServerConnect").value = "Retrying...";
4206 document.getElementById("tmg_pokerServerConnect").style.border = "#bf9000 ridge";
4207 document.getElementById("tmg_pokerServerConnect").style.background = "radial-gradient(white, #fff2cc, #ffe599)";
4208 minigamePokerServerStatus = "offline";
4209 tmg_pokerServerTimeoutVar = setTimeout(function() {
4210 if (tmg_pokerServerPingSent) {
4211 tmg_pokerServerPingSent = false;
4212 console.log("tmg_pokerConnectionLost");
4213 }
4214 }, 5000);
4215 }
4216 }
4217
4218 function addWebsocketHook() { // thanks florb
4219 const msgGameArr = ["Poker"],
4220 msgMainArr = ["SEND_LOBBY"];
4221 var origOnMessage = window.webSocket.onmessage;
4222 window.webSocket.onmessage = function(e) {
4223 origOnMessage.apply(this, arguments);
4224 let msg = e.data;
4225 if (msg.includes("TMG#")) {
4226 let msgFrom = msg.substring(0, msg.indexOf("="));
4227 msg = msg.replace(msgFrom, "").replace("=", "");
4228 // p2p("ted120",msg) = "ted120=TMG#Game Name#msgMain#msgSub1#msgSub2#msgSub3"
4229 console.log(msgFrom + "=" + msg);
4230 try {
4231 let arrMsg = msg.replace("TMG#", "").split("#");
4232 let msgGame = arrMsg[0];
4233 let msgMain = arrMsg[1];
4234 let msgSub1 = arrMsg[2];
4235 let msgSub2 = arrMsg[3];
4236 let msgSub3 = arrMsg[4];
4237 let msgSub4 = arrMsg[5];
4238 if (msgMain == "PING") {
4239 sendp2p(msgFrom, "PINGRETURN");
4240 return;
4241 } else if (msgMain == "PINGRETURN") {
4242 pingTime = new Date().getTime() - pingTimeStart;
4243 pingSent = false;
4244 return;
4245 }
4246 if (msgGame == "Poker") {
4247 if (window.username == pokerServerUsername) {
4248 // if we are poker server
4249 window.tmg_pokerSendLobby = function() {
4250 var sendDataArray = [], lobbyDataArray = [], thisTableString = "";
4251 for (let table in minigamesObject[msgGame].tables) {
4252 let sb = minigamesObject[msgGame].tables[table].gameInfo.sb;
4253 let bb = minigamesObject[msgGame].tables[table].gameInfo.bb;
4254 let gameType = minigamesObject[msgGame].tables[table].gameInfo.gameType;
4255 let minBuyin = minigamesObject[msgGame].tables[table].gameInfo.minBuyin;
4256 let maxBuyin = minigamesObject[msgGame].tables[table].gameInfo.maxBuyin;
4257 let minPlayers = minigamesObject[msgGame].tables[table].gameInfo.minPlayers;
4258 let maxPlayers = minigamesObject[msgGame].tables[table].gameInfo.maxPlayers;
4259 thisTableString = [table, sb, bb, gameType, minBuyin, maxBuyin, minPlayers, maxPlayers].join() + ",";
4260 let arrPlayers = [];
4261 for (let player in minigamesObject[msgGame].tables[table].seats) {
4262 let seatNumber = minigamesObject[msgGame].tables[table].seats[player].seat;
4263 let chips = minigamesObject[msgGame].tables[table].seats[player].chips;
4264 let chipsInPotThisStreet = minigamesObject[msgGame].tables[table].seats[player].chipsInPotThisStreet;
4265 let status = minigamesObject[msgGame].tables[table].seats[player].status;
4266 arrPlayers.push([player, seatNumber, chips, chipsInPotThisStreet, status].join("."));
4267 }
4268 thisTableString += arrPlayers.join(",");
4269 lobbyDataArray.push(thisTableString);
4270 }
4271 let headerString = [window.username + "=TMG", "Poker", "SEND_LOBBY#"].join("#");
4272 while (lobbyDataArray.length > 0) {
4273 let count = 0;
4274 let thisString = headerString + lobbyDataArray[count++];
4275 let nextString = thisString + "@" + lobbyDataArray[count];
4276 while (nextString) {
4277 if (!lobbyDataArray[count] || nextString.length > 255) {
4278 nextString = false;
4279 } else if (nextString.length <= 255) {
4280 thisString = nextString;
4281 nextString += lobbyDataArray[++count];
4282 }
4283 }
4284 if (thisString.length > 255) {
4285 lobbyDataArray.splice(0, 1);
4286 console.log("too long: " + thisString);
4287 } else {
4288 thisString = thisString.replace([window.username + "=TMG", "Poker"].join("#")+"#","");
4289 sendDataArray.push(thisString);
4290 lobbyDataArray.splice(0, count);
4291 }
4292 }
4293 sendDataArray.forEach(data => {
4294 sendp2p(msgFrom, data);
4295 });
4296 };
4297 if (msgMain == "CONNECT") {
4298 pokerServerPlayersConnected[msgFrom] = {
4299 status: "connected",
4300 lastActivity: new Date().getTime(),
4301 };
4302 sendp2p(msgFrom, "CONNECTED");
4303 tmg_pokerSendLobby();
4304 } else if (msgMain == "DISCONNECT") {
4305 if (pokerServerPlayersConnected[msgFrom]) {
4306 delete pokerServerPlayersConnected[msgFrom];
4307 }
4308 sendp2p(msgFrom, "DISCONNECTED");
4309 } else if (msgMain == "SEATED") {
4310 let gameId = msgSub1;
4311 let action = msgSub2;
4312 let amount = msgSub3;
4313 if (minigamesObject[msgGame].tables[gameId] && minigamesObject[msgGame].tables[gameId].players.indexOf(msgFrom) >= 0) {
4314 if (minigamesObject[msgGame].tables[gameId].currentTurn == msgFrom) {
4315 if (action == "BET" || action == "RAISE" || action == "FOLD") {
4316 tmg_pokerCalculateMove(msgGame, gameId, msgFrom, action, amount);
4317 } else if (action == "LEAVE_TABLE") {
4318 tmg_pokerLeaveTable(msgGame, msgFrom, gameId);
4319 } else sendp2p(msgFrom, "ERROR", "ACTION_UNKNOWN");
4320 } else sendp2p(msgFrom, "ERROR", "NOT_YOUR_TURN");
4321 } else sendp2p(msgFrom, "ERROR", "NOT_SEATED");
4322 } else if (msgMain == "LOBBY") {
4323 if (msgSub1 == "LOAD_LOBBY") {
4324 tmg_pokerSendLobby();
4325 } else if (msgSub1 == "CREATEROOM") {
4326 let nextId = parseInt(Object.keys(minigamesObject[msgGame].tables)[Object.keys(minigamesObject[msgGame].tables).length-1]) + 1; // last id in array +1
4327 minigamesObject[msgGame].tables[nextId] = {
4328 players: [],
4329 seats: {},
4330 currentTurn: null,
4331 maxPlayers: 7,
4332 };
4333 } else if (msgSub1 == "JOINTABLE") {
4334 let desiredTable = msgSub2;
4335 let desiredSeat = msgSub3;
4336 let buyinAmount = msgSub4;
4337 if (!tmg_pokerAlreadySeated(msgGame, msgFrom)) {
4338 if (minigamesObject[msgGame].tables[desiredTable]) {
4339 for (let player in minigamesObject[msgGame].tables[desiredTable].seats) {
4340 if (minigamesObject[msgGame].tables[desiredTable].seats[player].seat == desiredSeat) {
4341 sendp2p(msgFrom, "ERROR", "SEAT_TAKEN");
4342 tmg_pokerSendLobby();
4343 return;
4344 }
4345 }
4346 if (!minigamesObject[msgGame].tables[desiredTable].seats[desiredSeat]) {
4347 minigamesObject[msgGame].tables[desiredTable].seats[msgFrom] = {
4348 name: msgFrom,
4349 seat: desiredSeat,
4350 chips: buyinAmount,
4351 chipsInPotThisStreet: 0,
4352 status: "folded",
4353 };
4354 tmg_pokerSendLobby();
4355 sendp2p(msgFrom, "JOIN_GAME", desiredTable, desiredSeat, buyinAmount);
4356 let currentHandJSON = JSON.stringify(minigamesObject[msgGame].tables[desiredTable].currentHand);
4357 let handNumber = minigamesObject.Poker.tables[desiredTable].handNumber;
4358 sendp2p(msgFrom, "CURRENT_HAND", desiredTable, handNumber, currentHandJSON);
4359 // check if sat at another table, if so prompt remove
4360 // check if seat available
4361 // add player to seat
4362 } else sendp2p(msgFrom, "ERROR", "SEAT_TAKEN");
4363 } else sendp2p(msgFrom, "ERROR", "TABLE_NOT_EXIST");
4364 }
4365 } else if (msgSub1 == "LEAVE_TABLE") {
4366 tmg_pokerLeaveTable(msgGame, msgFrom, msgSub1, msgSub2);
4367 }
4368 }
4369 } else if (msgFrom == pokerServerUsername && window.username !== pokerServerUsername) {
4370 minigameLastMessageFromPokerServer = new Date().getTime();
4371 minigamePokerServerStatus = "online";
4372 // if we receive a message from poker server
4373 if (msgMain == "CONNECTED") {
4374 document.getElementById("tmg_pokerServerConnect").value = "Connected";
4375 document.getElementById("tmg_pokerServerConnect").style.border = "#38761d ridge";
4376 document.getElementById("tmg_pokerServerConnect").style.background = "radial-gradient(white, #d9ead3, #b6d7a8)";
4377 tmg_pokerServerPingSent = false;
4378 minigameConnectedToPokerServer = true;
4379 } else if (msgMain == "DISCONNECTED") {
4380 document.getElementById("tmg_pokerServerConnect").value = "Disconnected";
4381 document.getElementById("tmg_pokerServerConnect").style.border = "#990000 ridge";
4382 document.getElementById("tmg_pokerServerConnect").style.background = "radial-gradient(white, #f4cccc, #ea9999)";
4383 minigameConnectedToPokerServer = false;
4384 } else if (msgMain == "SEND_LOBBY") {
4385 let tableInfo = msgSub1.split("@");
4386 for (let table in tableInfo) {
4387 let arrTable = tableInfo[table].split(",");
4388 let tableNumber = arrTable[0];
4389 let sb = arrTable[1];
4390 let bb = arrTable[2];
4391 let gameType = arrTable[3];
4392 let minBuyin = arrTable[4];
4393 let maxBuyin = arrTable[5];
4394 let minPlayers = arrTable[6];
4395 let maxPlayers = arrTable[7];
4396 minigamesObject[minigameCurrentSelectedGame].tables[tableNumber] = {
4397 gameInfo: {
4398 sb: sb,
4399 bb: bb,
4400 gameType: gameType,
4401 minBuyin: minBuyin,
4402 maxBuyin: maxBuyin,
4403 minPlayers: minPlayers,
4404 maxPlayers: maxPlayers,
4405 },
4406 seats: {
4407 },
4408 };
4409 for (let i = 8; i < arrTable.length; i++) {
4410 let playerInfo = arrTable[i].split(".");
4411 let playerName = playerInfo[0];
4412 let playerSeat = playerInfo[1];
4413 let playerChips = playerInfo[2];
4414 let chipsInPotThisStreet = playerInfo[3];
4415 let status = playerInfo[4];
4416 minigamesObject[minigameCurrentSelectedGame].tables[tableNumber].seats[playerName] = {
4417 name: playerName,
4418 seat: playerSeat,
4419 chips: playerChips,
4420 chipsInPotThisStreet: chipsInPotThisStreet,
4421 status: status,
4422 };
4423 }
4424 }
4425 loadPokerLobby();
4426 } else if (msgMain == "SEATS") {
4427 let tableNumber = msgSub1;
4428 let curArray = msgSub2.split("@@");
4429 for (let seatNumber in curArray) {
4430 curArray[seatNumber] = curArray[seatNumber].replaceAll("@","");
4431 let arrSeat = curArray[seatNumber].split(",");
4432 minigamesObject[minigameGame].tables[tableNumber].seats.name = arrSeat[0];
4433 minigamesObject[minigameGame].tables[tableNumber].seats.seat = arrSeat[1];
4434 minigamesObject[minigameGame].tables[tableNumber].seats.chips = arrSeat[2];
4435 minigamesObject[minigameGame].tables[tableNumber].seats.chipsInPotThisStreet = arrSeat[3];
4436 minigamesObject[minigameGame].tables[tableNumber].seats.status = arrSeat[4];
4437 }
4438 } else if (msgMain == "CURRENT_HAND") {
4439 //"TMG#ted120#Ten Plus Poker#CURRENT_HAND#table#hand#currentTurn,dealer,sb,bb,flop,turn,river,potpreviousstreets,totalpot"
4440 let tableNumber = msgSub1;
4441 let handNumber = msgSub2;
4442 let currentHandJSON = msgSub3;
4443 minigamesObject[minigameGame].tables[tableNumber].currentHand = JSON.parse(currentHandJSON);
4444 } else if (msgMain == "JOIN_GAME") {
4445 //p2p(msgFrom, "TMG#"+window.username+"#Ten Plus Poker#JOIN_GAME#"+desiredTable+"#"+desiredSeat+"#"+buyinAmount);
4446 minigamePokerMyTable = msgSub1;
4447 minigamePokerMySeat = msgSub2;
4448 minigamePokerMyBuyin = msgSub3;
4449 loadMinigame(msgGame);
4450 } else if (msgMain == "LEAVE_TABLE") {
4451 //p2p(msgFrom, "TMG#"+window.username+"#"+game+"#LEAVE_TABLE#"+msgFrom+"#"+table);
4452 tmg_pokerLeaveTable(msgGame, msgSub2, msgSub3);
4453 } else if (msgMain == "LOG") {
4454 let tableNumber = msgSub1;
4455 let handNumber = msgSub2;
4456 //let curArray = msgSub3.split(",");
4457 minigamesObject[minigameGame].tables[tableNumber].log = [msgSub3];
4458 }
4459 }
4460 } else if (minigameMyStatus == "ingame" && msgFrom == minigameOpp) {
4461 if (msgGame == "Grid Control") {
4462 if (msgMain == "MOVE") {
4463 gc_interpretMove(msgSub1, msgSub2, msgSub3, true);
4464 minigameMyTurn = true;
4465 } else if (msgMain == "SURRENDER") {
4466 gc_checkVictory(msgSub1);
4467 }
4468 } //end Grid Control
4469 if (msgMain == "QUIT") {
4470 minigameMyStatus = "free";
4471 minigameOpp = "";
4472 document.getElementById("versusContainer").style.display = "none";
4473 document.getElementById("challengeContainer").style.display = "flex";
4474 loadMinigame("Minigames");
4475 minigameQuitReason = msgSub1;
4476 }
4477 } else if (minigameMyStatus == "starting") {
4478 if (msgMain == "LOADED") {
4479 //we challenged, they accepted, we said ready, they said ready
4480 minigameMyStatus = "ingame";
4481 minigameManager.challenges[msgFrom].status = "ingame";
4482 minigameOpp = msgFrom;
4483 minigameOppPlayer = "player2";
4484 minigameMyPlayer = "player1";
4485 minigameGame = msgGame;
4486 minigameVersion = msgSub2;
4487 minigameSeed = msgSub3;
4488 loadChallenges();
4489 loadMinigame(msgGame);
4490 minigameMyTurn = true;
4491 loadVersus();
4492 sendp2p(msgFrom, "LOADED", "MYMOVE", msgSub2, msgSub3);
4493 }
4494 } else if (minigameMyStatus == "confirming start") {
4495 if (msgMain == "LOADGAME" && msgGame == minigameManager.challenges[msgFrom].game && minigameManager.challenges[msgFrom].status == "Accepted") {
4496 //they challenged, we accepted, they said ready
4497 minigameMyStatus = "ingame";
4498 minigameManager.challenges[msgFrom].status = "ingame";
4499 minigameOpp = msgFrom;
4500 minigameOppPlayer = "player1";
4501 minigameMyPlayer = msgSub1;
4502 minigameGame = msgGame;
4503 minigameVersion = msgSub2;
4504 minigameSeed = msgSub3;
4505 loadChallenges();
4506 loadMinigame(msgGame);
4507 minigameMyTurn = false;
4508 loadVersus();
4509 sendp2p(msgFrom, "LOADED", "NOTMYMOVE", msgSub2, msgSub3);
4510 }
4511 } else if (minigameMyStatus == "free") {
4512 if (msgSub1 == "ACCSTART" && minigameManager.challenges[msgFrom] && minigameManager.challenges[msgFrom].status == "Challenge received" && msgGame == minigameManager.challenges[msgFrom].game) {
4513 //we challenged, they accepted
4514 minigameMyStatus = "starting";
4515 minigameOpp = msgFrom;
4516 minigameManager.challenges[msgFrom].status = "Starting";
4517 setTimeout(function() {
4518 if (minigameMyStatus == "starting") {
4519 minigameMyStatus = "free";
4520 minigameOpp = "";
4521 minigameManager.challenges[msgFrom].status = "Timed out";
4522 }
4523 }, 3000);
4524 sendp2p(msgFrom,"LOADGAME", "player2", msgSub2, msgSub3); //from, loadgame, player, version, seed
4525 }
4526 }
4527 if (msgMain == "CHALLENGE") {
4528 if (msgSub1 == "REQSTART") {
4529 //they challenged
4530 sendp2p(msgFrom, "CHALLENGE", "RECEIVED", msgSub2, msgSub3);
4531 minigameManager.challenges[msgFrom] = {
4532 from: msgFrom,
4533 game: msgGame,
4534 version: msgSub2,
4535 seed: msgSub3,
4536 status: "Accept",
4537 };
4538 if (minigameMyStatus == "free" && allowedBrowserNotifications) {
4539 var minigameChallengeNotification = new Notification("Minigame Challenge", {
4540 body: msgGame + " challenge from " + msgFrom
4541 });
4542 setTimeout(function() {
4543 minigameChallengeNotification.close();
4544 }, 5000);
4545 }
4546 } else if (msgSub1 == "DECSTART" && minigameManager.challenges[msgFrom] && minigameManager.challenges[msgFrom].status != "We declined") {
4547 //they declined our challenge
4548 if (minigameManager.challenges[msgFrom].status == "Accept") {
4549 minigameManager.challenges[msgFrom].status = "Challenge cancelled";
4550 } else {
4551 minigameManager.challenges[msgFrom].status = "Challenge declined";
4552 }
4553 } else if (msgSub1 == "RECEIVED" && minigameManager.challenges[msgFrom]) {
4554 //they received our challenge
4555 minigameManager.challenges[msgFrom].status = "Challenge received";
4556 }
4557 loadChallenges();
4558 }
4559 if (minigameMyStatus != "free" && msgFrom != minigameOpp && msgMain != "AUTOREPLY") {
4560 sendp2p(msgFrom, "AUTOREPLY", minigameMyStatus);
4561 } else if (msgMain == "AUTOREPLY") {
4562 minigameManager.challenges[msgFrom].status = "Already ingame";
4563 }
4564 }
4565 catch(err) {
4566 console.log(err);
4567 }
4568 }
4569 if (msg.startsWith("MARKET_BROWSE=") && msg.length > 1000) {
4570 sendToSpreadsheet(msg);
4571 }
4572 if (msg.includes("Item Purchased")) {
4573 if (th_status == "sent") {
4574 th_status = "purchased";
4575 let itemName = itemNameFix(getMarketItemNameFromMarketId(th_object.marketid));
4576 let total = th_object.price * th_object.thAmount;
4577 tedStoredSettings.tradeHistory.push({
4578 marketid: th_object.marketid,
4579 tradetype: "buy",
4580 date: new Date(),
4581 name: itemName,
4582 amount: th_object.thAmount,
4583 price: th_object.price,
4584 total: total
4585 });
4586 updateVariables();
4587 calculateFlips();
4588 sortTradeHistory(sortByTH);
4589 }
4590 }
4591 if (msg.startsWith("MARKET_SLOT=")) { //marketid, name, amountleft, price, coinstocollect, slot, expiresin
4592 let arr = msg.substring(msg.lastIndexOf("=") + 1).split("~");
4593 let marketid = parseInt(arr[0]);
4594 let itemName = arr[1];
4595 let price = parseInt(arr[3]);
4596 let coinstocollect = parseInt(arr[4]);
4597 let amountleft = parseInt(arr[2]);
4598 let amountsold = coinstocollect / price;
4599 let startamount = amountleft + amountsold;
4600 var thUpdated = false;
4601 var totalSold = 0,
4602 earliestStartAmount = 0;
4603 if (coinstocollect > 0) {
4604 for (let i = 0; i < tedStoredSettings.tradeHistory.length; i++) {
4605 if (tedStoredSettings.tradeHistory[i].hasOwnProperty("marketid") && tedStoredSettings.tradeHistory[i].marketid == marketid) {
4606 totalSold += tedStoredSettings.tradeHistory[i].amount;
4607 if (earliestStartAmount === 0) {
4608 earliestStartAmount = tedStoredSettings.tradeHistory[i].startamount;
4609 thUpdated = true;
4610 }
4611 }
4612 }
4613 if (thUpdated) {
4614 amountsold = (earliestStartAmount - totalSold) - amountleft;
4615 }
4616 if (amountsold > 0) {
4617 tedStoredSettings.tradeHistory.push({
4618 startamount: startamount,
4619 marketid: marketid,
4620 tradetype: "sell",
4621 date: new Date(),
4622 name: itemName,
4623 amount: amountsold,
4624 price: price,
4625 total: coinstocollect
4626 });
4627 updateVariables();
4628 calculateFlips();
4629 sortTradeHistory(sortByTH);
4630 }
4631 }
4632 }
4633 };
4634 var origOnSend = window.webSocket.send;
4635 window.webSocket.send = function(e) {
4636 origOnSend.apply(this, arguments);
4637 let msg = e;
4638 if (msg.startsWith("MARKET_BUY=")) {
4639 let marketId = msg.substring(msg.lastIndexOf("=") + 1, msg.lastIndexOf("~"));
4640 th_object = getArrMarketItemObjectFromMarketId(marketId);
4641 th_object.thAmount = parseInt(msg.substring(msg.lastIndexOf("~") + 1));
4642 if (typeof(th_object) == "undefined") return;
4643 th_status = "sent";
4644 }
4645 };
4646 }
4647
4648 function openInNewTab(url) {
4649 var win = window.open(url, '_blank');
4650 win.focus();
4651 }
4652 window.openPriceGraph = function() {
4653 if (!jsTradableItems[itemNameFix(lastBrowsedItem)]) { // if item is not on tradable list
4654 lastBrowsedItem = "stardust";
4655 }
4656 openInNewTab("http://dhmarket.tk/?formItem=" + itemNameFix(lastBrowsedItem));
4657 };
4658 window.displayQuickCalcTooltip = function(id, on) {
4659 if (on) {
4660 quickCalcTooltip.setAttribute("style", "display:block;position:absolute;top:0;background-color:#f2f2f2;text-align:center;width:100%;");
4661 if (id == "quickCalcStargem") {
4662 quickCalcTooltip.innerHTML = quickCalcStargemString;
4663 } else if (id == "quickCalcStardust") {
4664 quickCalcTooltip.innerHTML = quickCalcStardustString;
4665 } else if (id == "quickCalcSuperStardust") {
4666 quickCalcTooltip.innerHTML = quickCalcSuperStardustString;
4667 } else if (id == "quickCalcEssence") {
4668 quickCalcTooltip.innerHTML = quickCalcEssenceString;
4669 } else if (id == "quickCalcSuperEssence") {
4670 quickCalcTooltip.innerHTML = quickCalcSuperEssenceString;
4671 }
4672 } else if (!on) {
4673 quickCalcTooltip.setAttribute("style", "display:none;");
4674 }
4675 };
4676 window.totalNetWorth = function() {
4677 var total = 0,
4678 marketSlots = 0;
4679 let tnwArr = [];
4680 if (Object.keys(arrMarketItems).length > 1) {
4681 for (let key in Object.keys(jsTradableItems)) {
4682 if (arrMarketItems[Object.keys(jsTradableItems)[key]]) {
4683 if (window[Object.keys(jsTradableItems)[key]] > 0) {
4684 total += arrMarketItems[Object.keys(jsTradableItems)[key]][0].price * window[Object.keys(jsTradableItems)[key]];
4685 tnwArr.push({
4686 name: Object.keys(jsTradableItems)[key],
4687 price: arrMarketItems[Object.keys(jsTradableItems)[key]][0].price * window[Object.keys(jsTradableItems)[key]],
4688 });
4689 }
4690 } else console.log("Not on market: " + Object.keys(jsTradableItems)[key]);
4691 }
4692 for (let i = 0; i < arrMarketSlots.length; i++) {
4693 if (arrMarketItems[arrMarketSlots[i][2]]) {
4694 let amount = numberWithoutCommas(document.getElementById("market-slot-" + (i + 1) + "-amount").innerHTML);
4695 marketSlots += arrMarketItems[arrMarketSlots[i][2]][0].price * amount;
4696 tnwArr.push({
4697 name: Object.keys(jsTradableItems)[key]+" (market slot)",
4698 price: arrMarketItems[arrMarketSlots[i][2]][0].price * amount,
4699 });
4700 }
4701 }
4702 tnwArr.sort(function(a, b) {
4703 return a.price == b.price ? 0 : +(a.price > b.price) || -1;
4704 });
4705 tnwArr.forEach(obj => {
4706 console.log(obj.name + ": "+ numberWithCommas(obj.price));
4707 });
4708 console.log("Total net worth: " + numberWithCommas(coins + total + marketSlots) + "\n\nCoins: " + numberWithCommas(coins) + "\nItems: " + numberWithCommas(total) + "\nSlots: " + numberWithCommas(marketSlots));
4709 } else console.log("Search all first");
4710 };
4711
4712 function alterMarketSlots() {
4713 if (marketSlotsCustomUi) {
4714 if (typeof(document.getElementById("market-slot-1").parentNode) != "undefined" && document.getElementById("market-slot-1").parentNode.id != "tedMarketSlotContainer") {
4715 var tedMarketUiElement = document.createElement("div");
4716 tedMarketUiElement.setAttribute("style", "position:relative;height:325px;width:230px;background:linear-gradient(gold,silver);display:flex;flex-direction:column;justify-content:flex-end");
4717 tedMarketUiElement.setAttribute("id", "ted-market-ui");
4718 marketSlotSpareElement.innerHTML = updateNews;
4719 if (document.getElementById("ted-market-ui") === null) {
4720 quickCalcTooltip.setAttribute("style", "display:none");
4721 var quickCalcDiv = document.createElement("div");
4722 quickCalcDiv.setAttribute("style", "text-align:center;height:52px;line-height:52px;");
4723 var quickCalcStargem = document.createElement("img");
4724 quickCalcStargem.setAttribute("id", "quickCalcStargem");
4725 quickCalcStargem.setAttribute("onmouseover", "displayQuickCalcTooltip(this.id, true);");
4726 quickCalcStargem.setAttribute("onmouseout", "displayQuickCalcTooltip(this.id, false);");
4727 quickCalcStargem.setAttribute("src", "images/stargemPotion.png");
4728 quickCalcStargem.setAttribute("class", "image-icon-30");
4729 var quickCalcSuperStardust = document.createElement("img");
4730 quickCalcSuperStardust.setAttribute("id", "quickCalcSuperStardust");
4731 quickCalcSuperStardust.setAttribute("onmouseover", "displayQuickCalcTooltip(this.id, true);");
4732 quickCalcSuperStardust.setAttribute("onmouseout", "displayQuickCalcTooltip(this.id, false);");
4733 quickCalcSuperStardust.setAttribute("src", "images/superStardustPotion.png");
4734 quickCalcSuperStardust.setAttribute("class", "image-icon-30");
4735 var quickCalcStardust = document.createElement("img");
4736 quickCalcStardust.setAttribute("id", "quickCalcStardust");
4737 quickCalcStardust.setAttribute("onmouseover", "displayQuickCalcTooltip(this.id, true);");
4738 quickCalcStardust.setAttribute("onmouseout", "displayQuickCalcTooltip(this.id, false);");
4739 quickCalcStardust.setAttribute("src", "images/stardustPotion.png");
4740 quickCalcStardust.setAttribute("class", "image-icon-30");
4741 var quickCalcEssence = document.createElement("img");
4742 quickCalcEssence.setAttribute("id", "quickCalcEssence");
4743 quickCalcEssence.setAttribute("onmouseover", "displayQuickCalcTooltip(this.id, true);");
4744 quickCalcEssence.setAttribute("onmouseout", "displayQuickCalcTooltip(this.id, false);");
4745 quickCalcEssence.setAttribute("src", "images/essencePotion.png");
4746 quickCalcEssence.setAttribute("class", "image-icon-30");
4747 var quickCalcSuperEssence = document.createElement("img");
4748 quickCalcSuperEssence.setAttribute("id", "quickCalcSuperEssence");
4749 quickCalcSuperEssence.setAttribute("onmouseover", "displayQuickCalcTooltip(this.id, true);");
4750 quickCalcSuperEssence.setAttribute("onmouseout", "displayQuickCalcTooltip(this.id, false);");
4751 quickCalcSuperEssence.setAttribute("src", "images/superEssencePotion.png");
4752 quickCalcSuperEssence.setAttribute("class", "image-icon-30");
4753 var browseAllElementWrapper = document.createElement("div");
4754 browseAllElementWrapper.setAttribute("id", "browseAllElementWrapper");
4755 browseAllElementWrapper.setAttribute("style", "border-top:1px solid black;");
4756 var browseAllElement = document.createElement("div");
4757 browseAllElement.setAttribute("style", "margin:5px;padding:0px");
4758 browseAllElement.setAttribute("class", "basic-smallbox-grey");
4759 browseAllElement.setAttribute("id", "ted-browse-all");
4760 browseAllElement.setAttribute("title", "Browse All");
4761 browseAllElement.innerHTML = "<input type='image' data-item-name='All Items' style='padding:10px' onclick='disableBtn(this.parentNode," + searchAllDelay + ");document.getElementById("dialogue-market-postitem-buyorsell").value = "buy";postItemDialogue(document.getElementById("dialogue-market-postitem-buyorsell"), "ALL", this);' src='images/icons/infinity.png' class='image-icon-30'>";
4762 var priceGraphElement = document.createElement("div");
4763 priceGraphElement.setAttribute("style", "margin:5px;padding:0px");
4764 priceGraphElement.setAttribute("class", "basic-smallbox-grey");
4765 priceGraphElement.setAttribute("id", "ted-price-graph");
4766 priceGraphElement.setAttribute("title", "Price History Graph");
4767 priceGraphElement.innerHTML = "<input type='image' style='padding:10px' onclick='disableBtn(this.parentNode,500);openPriceGraph();' src='http://i.imgur.com/XhYzZRt.png' class='image-icon-30'>";
4768 var tradeHistoryElement = document.createElement("div");
4769 tradeHistoryElement.setAttribute("style", "margin:5px;padding:0px");
4770 tradeHistoryElement.setAttribute("class", "basic-smallbox-grey");
4771 tradeHistoryElement.setAttribute("id", "ted-trade-history");
4772 tradeHistoryElement.setAttribute("title", "Trade History");
4773 tradeHistoryElement.innerHTML = "<input type='image' style='padding:10px' onclick='disableBtn(this.parentNode,500);openTradeHistory();' src='http://i.imgur.com/ch5nOjq.png' class='image-icon-30'>";
4774 var tedMarketSlotContainer = document.createElement("div");
4775 tedMarketSlotContainer.setAttribute("style", "display:flex;justify-content:space-between;width:80%;max-width:1200px;min-width:800px;");
4776 document.getElementById("market-slot-1").parentNode.appendChild(tedMarketSlotContainer);
4777 for (var i = 0; i < arrMarketSlots.length; i++) {
4778 document.getElementById("market-slot-" + (i + 1)).style.margin = "0px 2px";
4779 tedMarketSlotContainer.appendChild(document.getElementById("market-slot-" + (i + 1)));
4780 }
4781 tedMarketSlotContainer.appendChild(tedMarketUiElement);
4782 document.getElementById("ted-market-ui").append(quickCalcTooltip);
4783 document.getElementById("ted-market-ui").appendChild(marketSlotSpareElement);
4784 document.getElementById("ted-market-ui").appendChild(browseAllElementWrapper);
4785 document.getElementById("browseAllElementWrapper").appendChild(browseAllElement);
4786 document.getElementById("browseAllElementWrapper").appendChild(priceGraphElement);
4787 document.getElementById("browseAllElementWrapper").appendChild(tradeHistoryElement);
4788 let browseAndHistory = document.getElementById("ted-market-ui").appendChild(document.createElement("div"));
4789 browseAndHistory.appendChild(document.getElementsByClassName("market-browse-button")[0]);
4790 browseAndHistory.appendChild(document.getElementsByClassName("market-browse-button")[1]);
4791 document.getElementsByClassName("market-browse-button")[0].setAttribute("style","width:50%;padding:10px 0");
4792 document.getElementsByClassName("market-browse-button")[1].setAttribute("style","width:50%;padding:10px 0");
4793 browseAndHistory.setAttribute("style", "display:flex");
4794 document.getElementById("ted-market-ui").appendChild(quickCalcDiv);
4795 quickCalcDiv.appendChild(quickCalcStardust);
4796 quickCalcDiv.appendChild(quickCalcSuperStardust);
4797 quickCalcDiv.appendChild(quickCalcStargem);
4798 quickCalcDiv.appendChild(quickCalcEssence);
4799 quickCalcDiv.appendChild(quickCalcSuperEssence);
4800 }
4801 // various player market formatting improvements, dear lord forgive me
4802 if (document.getElementById("tab-container-playermarket").children[0].innerHTML == "Player Market") {
4803 document.getElementById("tab-container-playermarket").children[0].remove();
4804 document.getElementById("tab-container-playermarket").prepend(document.createElement("br"));
4805 }
4806 if (document.getElementsByClassName("error-msg")[0].parentNode.parentNode.id == "market-listings") {
4807 document.getElementsByClassName("error-msg")[0].parentNode.remove();
4808 }
4809 if (document.getElementById("market-listings").children[1].getAttribute("style") == "clear:both") {
4810 document.getElementById("market-listings").children[1].remove();
4811 }
4812 setTimeout(function() {
4813 if (document.getElementById("market-listings").children[1].children[6].tagName == "BR") {
4814 document.getElementById("market-listings").children[1].children[6].remove();
4815 }
4816 if (document.getElementById("market-listings").children[1].children[5].tagName == "BR") {
4817 document.getElementById("market-listings").children[1].children[5].remove();
4818 }
4819 if (document.getElementById("market-listings").children[1].children[3].tagName == "BR") {
4820 document.getElementById("market-listings").children[1].children[3].remove();
4821 }
4822 if (document.getElementById("market-listings").children[1].children[2].tagName == "BR") {
4823 document.getElementById("market-listings").children[1].children[2].remove();
4824 }
4825 }, 1);
4826 for (let i = 0; i < arrMarketSlots.length; i++) {
4827 document.getElementsByClassName("market-slot-collect")[i].previousElementSibling.style.borderLeft = "0px";
4828 document.getElementsByClassName("market-slot-collect")[i].previousElementSibling.style.borderRight = "0px";
4829 }
4830 }
4831 }
4832 }
4833 window.myItemListBtnAction = function(itemName, itemPrice) {
4834 myItemListAddName = itemName;
4835 myItemListAddPrice = numberWithCommas(itemPrice);
4836 changeSetting("tedTradableItems");
4837 };
4838 window.upToParentByTag = function(el, tag) {
4839 // Climbs the DOM until it gets to the given tag.
4840 tag = tag.toUpperCase();
4841 el = el.parentNode;
4842 while (el.nodeName !== tag && el.nodeName !== 'HTML') {
4843 el = el.parentNode;
4844 }
4845 if (el.modeName === 'HTML') {
4846 el = null;
4847 }
4848 return el;
4849 };
4850
4851 function colorToRGBA(color) {
4852 // Returns the color as an array of [r, g, b, a] -- all range from 0 - 255
4853 // color must be a valid canvas fillStyle. This will cover most anything
4854 // you'd want to use.
4855 // Examples:
4856 // colorToRGBA('red') # [255, 0, 0, 255]
4857 // colorToRGBA('#f00') # [255, 0, 0, 255]
4858 var cvs, ctx;
4859 cvs = document.createElement('canvas');
4860 cvs.height = 1;
4861 cvs.width = 1;
4862 ctx = cvs.getContext('2d');
4863 ctx.fillStyle = color;
4864 ctx.fillRect(0, 0, 1, 1);
4865 return ctx.getImageData(0, 0, 1, 1).data;
4866 }
4867
4868 function byteToHex(num) {
4869 // Turns a number (0-255) into a 2-character hex number (00-ff)
4870 return ('0' + num.toString(16)).slice(-2);
4871 }
4872
4873 function colorToHex(color) {
4874 // Convert any CSS color to a hex representation
4875 // Examples:
4876 // colorToHex('red') # '#ff0000'
4877 // colorToHex('rgb(255, 0, 0)') # '#ff0000'
4878 var rgba, hex;
4879 rgba = colorToRGBA(color);
4880 hex = [0, 1, 2].map(function(idx) {
4881 return byteToHex(rgba[idx]);
4882 }).join('');
4883 return "#" + hex;
4884 }
4885
4886 function colorLuminance(hex, lum) {
4887 hex = colorToHex(hex);
4888 // validate hex string
4889 hex = String(hex).replace(/[^0-9a-f]/gi, '');
4890 if (hex.length < 6) {
4891 hex = hex[0] + hex[0] + hex[1] + hex[1] + hex[2] + hex[2];
4892 }
4893 lum = lum || 0;
4894 // convert to decimal and change luminosity
4895 var rgb = "#",
4896 c, i;
4897 for (i = 0; i < 3; i++) {
4898 c = parseInt(hex.substr(i * 2, 2), 16);
4899 c = Math.round(Math.min(Math.max(0, c + (c * lum)), 255)).toString(16);
4900 rgb += ("00" + c).substr(c.length);
4901 }
4902 return rgb;
4903 }
4904
4905 function colorMarketTable() {
4906 var minPrice, secondPrice, firstRow, secondRow, table, itemName, length;
4907 for (let i = 0; i < Object.keys(arrMarketItems).length; i++) {
4908 table = document.getElementById("market-table");
4909 itemName = Object.keys(arrMarketItems)[i];
4910 minPrice = arrMarketItems[itemName][0].price;
4911 length = arrMarketItems[itemName].length;
4912 if (length >= 2) {
4913 secondPrice = arrMarketItems[itemName][1].price;
4914 } else secondPrice = null;
4915 firstRow = arrMarketItems[itemName][0].row;
4916 if (length >= 2) {
4917 secondRow = arrMarketItems[itemName][1].row;
4918 } else secondRow = null;
4919 if (minPrice <= tedStoredSettings.tedTradableItems.itemList[itemName].showAtPrice) {
4920 table.rows[firstRow].style.background = "linear-gradient(" + colorMyItemList + "," + colorLuminance(colorMyItemList, -0.1) + ")";
4921 table.rows[firstRow].style.display = "table-row";
4922 if (length >= 2) {
4923 table.rows[firstRow].setAttribute("tedcolored", "true");
4924 table.rows[secondRow].style.background = "linear-gradient(" + colorMyItemListNextLowest + "," + colorLuminance(colorMyItemListNextLowest, -0.1) + ")";
4925 table.rows[secondRow].style.display = "table-row";
4926 }
4927 } else if (tedStoredSettings.tedTradableItems.itemList[itemName].showAtMin && secondPrice && (Math.ceil(secondPrice * 0.86) > minPrice)) {
4928 table.rows[firstRow].setAttribute("tedcolored", "true");
4929 document.getElementById("market-table").rows[firstRow].style.background = "linear-gradient(" + colorMinPrice + "," + colorLuminance(colorMinPrice, -0.1) + ")";
4930 document.getElementById("market-table").rows[firstRow].style.display = "table-row";
4931 document.getElementById("market-table").rows[secondRow].style.background = "linear-gradient(" + colorNextLowestToMinPrice + "," + colorLuminance(colorNextLowestToMinPrice, -0.1) + ")";
4932 document.getElementById("market-table").rows[secondRow].style.display = "table-row";
4933 } else if (tedStoredSettings.tedTradableItems.itemList[itemName].alwaysShowLowest) {
4934 table.rows[firstRow].style.background = "linear-gradient(" + colorAlwaysShowLowest + "," + colorLuminance(colorAlwaysShowLowest, -0.1) + ")";
4935 table.rows[firstRow].style.display = "table-row";
4936 } else if (showSingleItems && length == 1) {
4937 document.getElementById("market-table").rows[firstRow].style.background = "linear-gradient(" + colorSingleItems + "," + colorLuminance(colorSingleItems, -0.1) + ")";
4938 document.getElementById("market-table").rows[firstRow].style.display = "table-row";
4939 }
4940 }
4941 for (s = 0; s < arrMarketSlots.length; s++) {
4942 if (arrMarketSlots[s][1] === true) {
4943 var myItemName, myMarketId, myRow, myListPosition, foundItem = false;
4944 for (var i = 0; i < Object.keys(arrMarketItems).length; i++) {
4945 myItemName = Object.keys(arrMarketItems)[i];
4946 firstRow = arrMarketItems[myItemName][0].row;
4947 length = arrMarketItems[myItemName].length;
4948 for (var a = 0; a < arrMarketItems[myItemName].length; a++) {
4949 let itemString = document.getElementById("market-slot-" + (s + 1) + "-taken").children[0].src;
4950 arrMarketSlots[s].push(itemString.substring(itemString.indexOf("/images/") + 8, itemString.indexOf(".png")));
4951 if (arrMarketItems[myItemName][a].marketid == arrMarketSlots[s][0]) {
4952 myMarketId = arrMarketItems[myItemName][a].marketid;
4953 myRow = arrMarketItems[myItemName][a].row;
4954 myListPosition = a;
4955 foundItem = true;
4956 break;
4957 }
4958 }
4959 if (foundItem) break;
4960 }
4961 if (!foundItem) continue;
4962 if (myListPosition === 0) {
4963 document.getElementById("market-table").rows[myRow].style.display = "table-row";
4964 document.getElementById("market-table").rows[myRow].style.background = "linear-gradient(" + colorMyListedLowest + "," + colorLuminance(colorMyListedLowest, -0.1) + ")";
4965 if (length >= 2) {
4966 document.getElementById("market-table").rows[(myRow + 1)].style.display = "table-row";
4967 document.getElementById("market-table").rows[(myRow + 1)].style.background = "linear-gradient(" + colorMyListedLowestCanRaisePrice + "," + colorLuminance(colorMyListedLowestCanRaisePrice, -0.1) + ")";
4968 }
4969 } else if (myListPosition > 0) {
4970 document.getElementById("market-table").rows[myRow].style.background = "linear-gradient(" + colorMyListedNotLowest + "," + colorLuminance(colorMyListedNotLowest, -0.1) + ")";
4971 document.getElementById("market-table").rows[myRow].style.display = "table-row";
4972 if (table.rows[firstRow].getAttribute("tedcolored") === null) {
4973 document.getElementById("market-table").rows[firstRow].style.background = "linear-gradient(" + colorLowestForMyListed + "," + colorLuminance(colorLowestForMyListed, -0.1) + ")";
4974 document.getElementById("market-table").rows[firstRow].style.display = "table-row";
4975 }
4976 } else console.log("error 12751");
4977 }
4978 }
4979 }
4980 window.highlightRow = function(row, display) {
4981 if (display) {
4982 row.style.boxShadow = "0 3px 5px -2px inset, 0 -3px 5px -3px inset";
4983 } else if (!display) {
4984 row.style.boxShadow = "";
4985 }
4986 };
4987
4988 function tradeHistory() {
4989 var tradeHistoryModal = document.createElement("div");
4990 tradeHistoryModal.setAttribute("id", "tradeHistoryModal");
4991 tradeHistoryModal.setAttribute("style", "display:none");
4992 var tradeHistoryModalBody = document.createElement("div");
4993 tradeHistoryModalBody.setAttribute("id", "tradeHistoryModalBody");
4994 tradeHistoryModalBody.setAttribute("style", "display:none;background-color:silver;width:80%;min-width:800px;max-width:1200px;margin-bottom:5px;");
4995 var thBuyCheckbox = document.createElement("input");
4996 thBuyCheckbox.setAttribute("type", "checkbox");
4997 thBuyCheckbox.setAttribute("id", "thBuyCheckbox");
4998 thBuyCheckbox.setAttribute("onclick", "generateTradeHistoryTable();document.getElementById('thSearch').focus();");
4999 thBuyCheckbox.setAttribute("checked", "true");
5000 var thBuyCheckboxLabel = document.createElement("label");
5001 thBuyCheckboxLabel.htmlFor = "thBuyCheckbox";
5002 thBuyCheckboxLabel.appendChild(document.createTextNode('Buy'));
5003 var thSellCheckbox = document.createElement("input");
5004 thSellCheckbox.setAttribute("type", "checkbox");
5005 thSellCheckbox.setAttribute("id", "thSellCheckbox");
5006 thSellCheckbox.setAttribute("onclick", "generateTradeHistoryTable();document.getElementById('thSearch').focus();");
5007 thSellCheckbox.setAttribute("checked", "true");
5008 var thSellCheckboxLabel = document.createElement("label");
5009 thSellCheckboxLabel.htmlFor = "thSellCheckbox";
5010 thSellCheckboxLabel.appendChild(document.createTextNode('Sell'));
5011 var thMax3Checkbox = document.createElement("input");
5012 thMax3Checkbox.setAttribute("type", "checkbox");
5013 thMax3Checkbox.setAttribute("id", "thMax3Checkbox");
5014 thMax3Checkbox.setAttribute("onclick", "generateTradeHistoryTable();document.getElementById('thSearch').focus();");
5015 thMax3Checkbox.setAttribute("checked", "true");
5016 var thMax3CheckboxLabel = document.createElement("label");
5017 thMax3CheckboxLabel.htmlFor = "thMax3Checkbox";
5018 thMax3CheckboxLabel.appendChild(document.createTextNode('Last 3'));
5019 var thSearch = document.createElement("input");
5020 thSearch.setAttribute("type", "text");
5021 thSearch.setAttribute("id", "thSearch");
5022 thSearch.setAttribute("title", "To match full search string use = before item name\n\n=gold leaf\nshows only Gold Leaf\n\ngold leaf\nshows Gold Leaf and Gold Leaf Seeds");
5023 thSearch.setAttribute("onchange", "thSearchLogic();");
5024 thSearch.setAttribute("onkeypress", "this.onchange();");
5025 thSearch.setAttribute("onpaste", "this.onchange();");
5026 thSearch.setAttribute("oninput", "this.onchange();");
5027 thSearch.setAttribute("placeholder", "search by name...");
5028 var thClose = document.createElement("button");
5029 thClose.setAttribute("style", "float:right;height:18px;width:18px;border-radius:18px;cursor:pointer;background-color:#ff7878;margin:2px");
5030 thClose.setAttribute("onclick", "this.parentNode.style.display='none'");
5031 thClose.setAttribute("id", "thClose");
5032 var thTotalFlipProfit = document.createElement("span");
5033 thTotalFlipProfit.setAttribute("style", "float:left;margin:2px");
5034 thTotalFlipProfit.setAttribute("id", "thTotalFlipProfit");
5035 var tradeHistoryModalBodyTable = document.createElement("div");
5036 tradeHistoryModalBodyTable.setAttribute("id", "tradeHistoryModalBodyTable");
5037 tradeHistoryModalBodyTable.setAttribute("style", "background-color:silver;margin:auto;");
5038 document.getElementById("market-table").parentNode.prepend(tradeHistoryModalBody);
5039 document.getElementById("market-table").parentNode.prepend(document.createElement("br"));
5040 document.getElementById("tradeHistoryModalBody").append(thTotalFlipProfit);
5041 document.getElementById("tradeHistoryModalBody").append(thSearch);
5042 document.getElementById("tradeHistoryModalBody").append(thBuyCheckbox);
5043 document.getElementById("tradeHistoryModalBody").append(thBuyCheckboxLabel);
5044 document.getElementById("tradeHistoryModalBody").append(thSellCheckbox);
5045 document.getElementById("tradeHistoryModalBody").append(thSellCheckboxLabel);
5046 document.getElementById("tradeHistoryModalBody").append(thMax3Checkbox);
5047 document.getElementById("tradeHistoryModalBody").append(thMax3CheckboxLabel);
5048 document.getElementById("tradeHistoryModalBody").append(thClose);
5049 document.getElementById("tradeHistoryModalBody").append(tradeHistoryModalBodyTable);
5050 }
5051
5052 function alterMarketTable() {
5053 var i, a, b, s, maxCanBuy, totalPrice, arrToAppend;
5054 document.getElementById("market-table").rows[0].style.backgroundColor = "gold";
5055 if (document.getElementById("market-table").rows[1]) {
5056 for (i = 2; i < 4; i++) {
5057 while (document.getElementById("market-table").rows[0].childNodes[i].firstChild) {
5058 document.getElementById("market-table").rows[0].childNodes[i].removeChild(document.getElementById("market-table").rows[0].childNodes[i].firstChild);
5059 }
5060 }
5061 if (showMaxCanBuy) {
5062 var headerMaxCanBuy = document.createElement("div");
5063 headerMaxCanBuy.setAttribute("style", "float:left;padding-left:10px;");
5064 headerMaxCanBuy.append("maxCanBuy");
5065 document.getElementById("market-table").rows[0].childNodes[2].append(headerMaxCanBuy);
5066 }
5067 var headerAmount = document.createElement("div");
5068 headerAmount.setAttribute("style", "text-align:right;padding-right:10px;");
5069 headerAmount.append("Amount");
5070 document.getElementById("market-table").rows[0].childNodes[2].append(headerAmount);
5071 if (showTotalPrice) {
5072 var headerTotalPrice = document.createElement("div");
5073 headerTotalPrice.setAttribute("style", "float:right;padding-right:10px;");
5074 headerTotalPrice.append("Total maxCanBuy Price");
5075 document.getElementById("market-table").rows[0].childNodes[3].append(headerTotalPrice);
5076 }
5077 var headerPrice = document.createElement("div");
5078 headerPrice.setAttribute("style", "text-align:left;padding-left:10px;");
5079 headerPrice.append("Price each");
5080 document.getElementById("market-table").rows[0].childNodes[3].append(headerPrice);
5081 }
5082 if (document.getElementById("market-table").nextSibling.id != "tedMarketTable") {
5083 var tedMarketTable = document.createElement("table");
5084 tedMarketTable.setAttribute("id", "tedMarketTable");
5085 tedMarketTable.setAttribute("class", "market-table");
5086 tedMarketTable.setAttribute("style", "max-width:1200px;min-width:800px;");
5087 document.getElementById("market-table").style.display = "none";
5088 if (document.getElementById("market-table").nextSibling) {
5089 document.getElementById("market-table").parentNode.insertBefore(tedMarketTable, document.getElementById("market-table").nextSibling);
5090 } else {
5091 document.getElementById("market-table").parentNode.appendChild(document.getElementById("tedmarketTable"));
5092 }
5093 }
5094 if (document.getElementById("market-table").rows[0].childNodes[0]) document.getElementById("market-table").rows[0].childNodes[0].style.width = "25%";
5095 if (document.getElementById("market-table").rows[0].childNodes[1]) document.getElementById("market-table").rows[0].childNodes[1].style.width = "50px";
5096 //document.getElementById("tedMarketTable").rows[0].childNodes[2].style.width = "25%";
5097 //document.getElementById("tedMarketTable").rows[0].childNodes[3].style.width = "25%";
5098 if (document.getElementById("market-table").rows[0].childNodes[4]) document.getElementById("market-table").rows[0].childNodes[4].style.width = "10%";
5099 if (debugToConsole) {
5100 console.log(arrMarketItems);
5101 }
5102 for (i = 0; i < Object.keys(arrMarketItems).length; i++) {
5103 var itemName = Object.keys(arrMarketItems)[i];
5104 var marketItemName = getItemName(itemName);
5105 var length = arrMarketItems[itemName].length;
5106 var firstRow = arrMarketItems[itemName][0].row;
5107 var minPrice = arrMarketItems[itemName][0].price;
5108 if (length >= 2) {
5109 var secondRow = arrMarketItems[itemName][1].row;
5110 var secondPrice = arrMarketItems[itemName][1].price;
5111 }
5112 //fixes Name column for first market entry to add buttons without onclick to buy item
5113 document.getElementById("market-table").rows[firstRow].removeAttribute("onclick");
5114 for (b = 1; b < document.getElementById("market-table").rows[firstRow].childNodes.length; b++) {
5115 document.getElementById("market-table").rows[firstRow].childNodes[b].setAttribute("onclick", "openBuyFromPlayerMarketDialogue(this.parentNode);");
5116 }
5117 var btnMyItemListDiv = document.createElement("div");
5118 btnMyItemListDiv.setAttribute("style", "float:left;padding-left:15px");
5119 var btnMyItemList = document.createElement("BUTTON");
5120 btnMyItemList.setAttribute("onclick", "myItemListBtnAction(upToParentByTag(this,'tr').getAttribute('teditemname'),upToParentByTag(this,'tr').getAttribute('data-market-price'));");
5121 btnMyItemList.setAttribute("style", "background-color:#ffccff");
5122 btnMyItemList.setAttribute("title", "Add to Item List");
5123 var btnMyItemListText = document.createTextNode("+");
5124 btnMyItemList.appendChild(btnMyItemListText);
5125 btnMyItemListDiv.appendChild(btnMyItemList);
5126 var itemNameTextDiv = document.createElement("div");
5127 itemNameTextDiv.setAttribute("onclick", "openBuyFromPlayerMarketDialogue(upToParentByTag(this,'tr'));");
5128 var itemNameText = document.createElement("span");
5129 itemNameText.setAttribute("style", "vertical-align:middle;padding: 0 10px");
5130 itemNameText.append(marketItemName);
5131 itemNameTextDiv.append(itemNameText);
5132 while (document.getElementById("market-table").rows[firstRow].childNodes[0].firstChild) {
5133 document.getElementById("market-table").rows[firstRow].childNodes[0].removeChild(document.getElementById("market-table").rows[firstRow].childNodes[0].firstChild);
5134 }
5135 document.getElementById("market-table").rows[firstRow].childNodes[0].append(btnMyItemListDiv);
5136 document.getElementById("market-table").rows[firstRow].childNodes[0].append(itemNameTextDiv);
5137 for (a = 0; a < arrMarketItems[itemName].length; a++) {
5138 var row = arrMarketItems[itemName][a].row;
5139 var price = arrMarketItems[itemName][a].price;
5140 var amount = arrMarketItems[itemName][a].amount;
5141 var marketid = arrMarketItems[itemName][a].marketid;
5142 document.getElementById("market-table").rows[row].setAttribute("teditemname", itemName);
5143 document.getElementById("market-table").rows[row].setAttribute("teditemprice", price);
5144 document.getElementById("market-table").rows[row].setAttribute("teditemamount", amount);
5145 document.getElementById("market-table").rows[row].setAttribute("class", "tedMarketRow");
5146 document.getElementById("market-table").rows[row].setAttribute("onmouseover", "highlightRow(this, true);");
5147 document.getElementById("market-table").rows[row].setAttribute("onmouseout", "highlightRow(this, false);");
5148 for (b = 0; b < 4; b++) {
5149 if (b == 1) continue;
5150 if (a === 0 && b === 0) {
5151 document.getElementById("market-table").rows[row].childNodes[b].setAttribute("style", "text-align:right;");
5152 } else document.getElementById("market-table").rows[row].childNodes[b].setAttribute("style", "text-align:right;padding: 0 10px;");
5153 }
5154 if (smallMarketImages) {
5155 document.getElementById("market-table").childNodes[0].childNodes[row].childNodes[1].childNodes[0].style = "height: " + marketImageSize + "px;width: " + marketImageSize + "px;";
5156 }
5157 //Amount column
5158 maxCanBuy = Math.floor(coins / price);
5159 if (maxCanBuy >= amount) {
5160 maxCanBuy = amount;
5161 }
5162 if (showMaxCanBuy) {
5163 if (maxCanBuy < amount) {
5164 var maxCanBuyDiv = document.createElement("div");
5165 maxCanBuyDiv.setAttribute("style", "float:left;");
5166 maxCanBuyDiv.setAttribute("class", "maxCanBuyClass");
5167 maxCanBuyDiv.append(" (x" + numberWithCommas(maxCanBuy) + ") ");
5168 document.getElementById("market-table").rows[row].cells[2].prepend(maxCanBuyDiv);
5169 }
5170 }
5171 //price
5172 while (document.getElementById("market-table").rows[row].childNodes[3].firstChild) {
5173 document.getElementById("market-table").rows[row].childNodes[3].removeChild(document.getElementById("market-table").rows[row].childNodes[3].firstChild);
5174 }
5175 var itemPriceDiv = document.createElement("div");
5176 itemPriceDiv.setAttribute("style", "white-space:nowrap;float:left;");
5177 itemPriceDiv.setAttribute("class", "itemPriceClass");
5178 document.getElementById("market-table").rows[row].childNodes[3].append(itemPriceDiv);
5179 itemPriceDiv.append(numberWithCommas(upToParentByTag(itemPriceDiv, 'tr').getAttribute('teditemprice')));
5180 itemPriceDiv.append(coinImg.cloneNode());
5181 if (showTotalPrice) {
5182 if (amount > 1) {
5183 totalPrice = maxCanBuy * price;
5184 var totalPriceDiv = document.createElement("div");
5185 totalPriceDiv.setAttribute("style", "white-space:nowrap;float:right");
5186 totalPriceDiv.append(numberWithCommas(totalPrice));
5187 totalPriceDiv.append(coinImg.cloneNode());
5188 document.getElementById("market-table").rows[row].childNodes[3].append(totalPriceDiv);
5189 }
5190 }
5191 var oldOnclick = document.getElementById('market-table').rows[row].getAttribute('onclick');
5192 if (oldOnclick !== null) {
5193 document.getElementById("market-table").rows[row].setAttribute("onclick", oldOnclick + ";document.getElementById('buyFromMarket-input').value = " + maxCanBuy + ";");
5194 } else document.getElementById("market-table").rows[row].setAttribute("onclick", "document.getElementById('buyFromMarket-input').value = " + maxCanBuy + ";");
5195 if (notEnoughCoinsOpacity && maxCanBuy === 0) {
5196 document.getElementById("market-table").rows[row].style.opacity = "0.3";
5197 }
5198 if (document.getElementById("market-table").rows.length > 16) { // if we are searching all
5199 if (document.getElementById("market-table").rows[row].style.display === "") {
5200 document.getElementById("market-table").rows[row].style.display = "none";
5201 }
5202 if (i == Object.keys(arrMarketItems).length - 1 && a == length - 1) { //after last item in arrMarketItems
5203 quickCalcMain();
5204 }
5205 }
5206 } // end of for (a..
5207 } // end of for i
5208 colorMarketTable();
5209 // sort market table
5210 arrToAppend = [];
5211 for (s = 0; s < arrSortItemsList.length; s++) {
5212 if (arrMarketItems[itemNameFix(arrSortItemsList[s])]) {
5213 for (i = 0; i < arrMarketItems[itemNameFix(arrSortItemsList[s])].length; i++) {
5214 arrToAppend.push(document.getElementById("market-table").rows[arrMarketItems[itemNameFix(arrSortItemsList[s])][i].row]);
5215 }
5216 }
5217 }
5218 for (i = 0; i < arrToAppend.length; i++) {
5219 document.getElementById("market-table").append(arrToAppend[i]);
5220 }
5221 // append to tedMarketTable
5222 arrToAppend = [];
5223 for (i = 0; i < document.getElementById("market-table").childNodes.length; i++) {
5224 arrToAppend.push(document.getElementById("market-table").childNodes[i]);
5225 }
5226 while (document.getElementById("tedMarketTable").firstChild) {
5227 document.getElementById("tedMarketTable").removeChild(document.getElementById("tedMarketTable").firstChild);
5228 }
5229 for (i = 0; i < arrToAppend.length; i++) {
5230 document.getElementById("tedMarketTable").append(arrToAppend[i]);
5231 }
5232 // modify text widths perfectly, thanks florb you fucking god
5233 let widestMaxCanBuy = Array.prototype.slice.call(document.querySelectorAll(".maxCanBuyClass")).reduce((acc, val) => {
5234 return (acc > val.offsetWidth ? acc : val.offsetWidth);
5235 }, 0);
5236 Array.prototype.slice.call(document.querySelectorAll(".maxCanBuyClass")).forEach(e => {
5237 e.style.width = (widestMaxCanBuy) + "px";
5238 });
5239 let widestItemPrice = Array.prototype.slice.call(document.querySelectorAll(".itemPriceClass")).reduce((acc, val) => {
5240 return (acc > val.offsetWidth ? acc : val.offsetWidth);
5241 }, 0);
5242 Array.prototype.slice.call(document.querySelectorAll(".itemPriceClass")).forEach(e => {
5243 e.style.width = (widestItemPrice) + "px";
5244 });
5245 }
5246
5247 function updateMarketSlots() {
5248 for (let i = 0; i < arrMarketSlots.length; i++) { //arrMarketSlots format: [marketid, in use?]
5249 arrMarketSlots[i][0] = window["marketSlot" + (i + 1)];
5250 if (document.getElementById("market-slot-" + (i + 1) + "-free").style.display === "") {
5251 arrMarketSlots[i][1] = false;
5252 } else arrMarketSlots[i][1] = true;
5253 if (debugToConsole) {
5254 console.log("Market slot: " + (i + 1), arrMarketSlots[i][0], arrMarketSlots[i][1]);
5255 }
5256 }
5257 }
5258
5259 function marketReloaded() {
5260 if (typeof(document.getElementById("market-table").rows[0]) != "undefined" && document.getElementById("market-table").rows[0] !== null) {
5261 // exists
5262 if (document.getElementById("market-table").rows[0].style.backgroundColor != "gold") {
5263 updateMarketSlots();
5264 getMarketItems();
5265 addItemTooltips();
5266 alterMarketTable();
5267 }
5268 }
5269 }
5270
5271 function marketMain() {
5272 if (marketOn === true) {
5273 marketInterval = setInterval(marketReloaded, 0);
5274 }
5275 }
5276
5277 function marketButtonClickAction() {
5278 if (marketOn === true) {
5279 marketOn = false;
5280 clearInterval(marketInterval);
5281 document.getElementById("market-table").style.display = "";
5282 if (document.getElementById("tedMarketTable")) {
5283 document.getElementById("tedMarketTable").style.display = "none";
5284 }
5285 document.getElementById("marketButton").innerHTML = "Ted's Market: OFF";
5286 } else if (marketOn === false) {
5287 marketOn = true;
5288 document.getElementById("market-table").style.display = "none";
5289 if (document.getElementById("tedMarketTable")) {
5290 document.getElementById("tedMarketTable").style.display = "";
5291 }
5292 marketMain();
5293 document.getElementById("marketButton").innerHTML = "Ted's Market: ON";
5294 }
5295 }
5296
5297 function getRowFromMarketId(marketId) {
5298 for (var i = 0; i < Object.keys(arrMarketItems).length; i++) {
5299 let itemName = Object.keys(arrMarketItems)[i];
5300 for (var a = 0; a < arrMarketItems[itemName].length; a++) {
5301 if (arrMarketItems[itemName][a].marketid == marketId) {
5302 return arrMarketItems[itemName][a].marketid;
5303 }
5304 }
5305 }
5306 return undefined;
5307 }
5308
5309 function getMarketItemNameFromMarketId(marketId) {
5310 for (var i = 0; i < Object.keys(arrMarketItems).length; i++) {
5311 let itemName = Object.keys(arrMarketItems)[i];
5312 for (var a = 0; a < arrMarketItems[itemName].length; a++) {
5313 if (arrMarketItems[itemName][a].marketid == marketId) {
5314 return getItemName(itemName);
5315 }
5316 }
5317 }
5318 return undefined;
5319 }
5320
5321 function refreshMarketAfterBuyingItem() {
5322 //refresh market after final confirmation when buying item
5323 if (document.getElementById("dialogue-confirm-cmd").value.substring(0, 10) != "MARKET_BUY" && document.getElementById("dialogue-confirm-yes").getAttribute("onclick") != oldDialogueConfirmYesOnclick) {
5324 document.getElementById("dialogue-confirm-yes").setAttribute("onclick", oldDialogueConfirmYesOnclick);
5325 }
5326 if (typeof(document.getElementById("tedMarketTable")) != "undefined" && document.getElementById("tedMarketTable") !== null && document.getElementById("dialogue-confirm-cmd").value.substring(0, 10) == "MARKET_BUY" && document.getElementById("dialogue-confirm-yes").value == "Confirm Purchase") {
5327 document.getElementById("dialogue-confirm-yes").value = "Confirm Purchase "; //break infinite loop
5328 if (document.getElementById("tedMarketTable").rows.length > 16) { // if we searched all
5329 if (document.getElementById('dialogue-confirm-yes').getAttribute("onclick") != "confirmedDialogue(this, document.getElementById('dialogue-confirm-cmd').value);document.getElementById('dialogue-market-postitem-buyorsell').value = 'buy';postItemDialogue(document.getElementById('dialogue-market-postitem-buyorsell'), 'ALL', this);") {
5330 document.getElementById("dialogue-confirm-yes").setAttribute("onclick", "confirmedDialogue(this, document.getElementById('dialogue-confirm-cmd').value);document.getElementById('dialogue-market-postitem-buyorsell').value = 'buy';postItemDialogue(document.getElementById('dialogue-market-postitem-buyorsell'), 'ALL', this);");
5331 }
5332 } else if (document.getElementById("tedMarketTable").rows.length <= 16) { // if we searched for a single item
5333 var marketBuyString = document.getElementById('dialogue-confirm-cmd').value;
5334 var marketId = marketBuyString.substring(marketBuyString.lastIndexOf("=") + 1, marketBuyString.lastIndexOf("~"));
5335 var itemName = getMarketItemNameFromMarketId(marketId);
5336 if (typeof(itemName) != "undefined") {
5337 refreshMarketAfterBuyingItem_itemName = itemNameFix(itemName);
5338 if (document.getElementById('dialogue-confirm-yes').getAttribute("onclick") != "confirmedDialogue(this, document.getElementById('dialogue-confirm-cmd').value);document.getElementById('dialogue-market-postitem-buyorsell').value = 'buy';postItemDialogue(document.getElementById('dialogue-market-postitem-buyorsell'), '" + refreshMarketAfterBuyingItem_itemName + "', this);") {
5339 document.getElementById("dialogue-confirm-yes").setAttribute("onclick", "confirmedDialogue(this, document.getElementById('dialogue-confirm-cmd').value);document.getElementById('dialogue-market-postitem-buyorsell').value = 'buy';postItemDialogue(document.getElementById('dialogue-market-postitem-buyorsell'), '" + refreshMarketAfterBuyingItem_itemName + "', this);");
5340 }
5341 }
5342 }
5343 }
5344 }
5345 window.modifyKeepList = function(chosenItem) {
5346 var keepAmount = window[chosenItem] - numberWithoutCommas(document.getElementById("chosenpostitem-amount").value);
5347 if (keepAmount < 0) keepAmount = 0;
5348 if (tedStoredSettings.tedTradableItems.itemList[chosenItem].keepAmount != keepAmount) {
5349 tedStoredSettings.tedTradableItems.itemList[chosenItem].keepAmount = keepAmount;
5350 updateVariables();
5351 }
5352 };
5353 window.fixCpiNumbers = function() {
5354 document.getElementById("chosenpostitem-amount").value = numberWithoutCommas(document.getElementById("chosenpostitem-amount").value);
5355 document.getElementById("chosenpostitem-price").value = numberWithoutCommas(document.getElementById("chosenpostitem-price").value);
5356 };
5357 window.keepAmountSetMax = function() {
5358 document.getElementById("chosenpostitem-amount").value = numberWithCommas(window[document.getElementById("chosenpostitem-itemName").value]);
5359 };
5360
5361 function dialogue_market_chosenpostitem() {
5362 if (document.getElementById("dialogue-market-chosenpostitem").parentNode.style.display == "none") {
5363 cpi_itemName = "";
5364 }
5365 if (document.getElementById("dialogue-market-chosenpostitem").parentNode.style.display != "none") {
5366 if (document.getElementById("chosenpostitem-price").value === "" && document.getElementById("chosenpostitem-itemName").value != cpi_itemName) {
5367 cpi_itemName = document.getElementById("chosenpostitem-itemName").value;
5368 var currentPrice = Math.ceil((numberWithoutCommas(document.getElementById("chosenpostitem-upper").innerHTML) + numberWithoutCommas(document.getElementById("chosenpostitem-lower").innerHTML)) / 2);
5369 if (autoUndercut) {
5370 if (currentPrice > matchLowestPriceAt) {
5371 document.getElementById("chosenpostitem-price").value = (currentPrice - undercutBy);
5372 } else {
5373 let item = itemNameFix(lastBrowsedItem).toLowerCase();
5374 if (arrMarketItems[item] && arrMarketItems[item][0]) {
5375 let count = 0,
5376 itemPrice = 0;
5377 for (let i = 0; i < arrMarketItems[item].length; i++) {
5378 count++;
5379 itemPrice += arrMarketItems[item][i].price;
5380 }
5381 document.getElementById("chosenpostitem-price").value = Math.ceil(itemPrice / count);
5382 } else document.getElementById("chosenpostitem-price").value = currentPrice;
5383 }
5384 }
5385 if (useUndercutBox) {
5386 var undercutBoxTextInner = "Undercut " + numberWithCommas(currentPrice) + " by<br><br>";
5387 if (undercutBoxText.innerHTML != undercutBoxTextInner) {
5388 undercutBoxText.innerHTML = undercutBoxTextInner;
5389 }
5390 }
5391 if (useKeepAmount) {
5392 var cpiPostString = document.getElementById("cpi-post").getAttribute("onclick");
5393 if (document.getElementById("chosenpostitem-itemName").value !== "") {
5394 keepAmountChosenItem = document.getElementById("chosenpostitem-itemName").value;
5395 var keepAmount = tedStoredSettings.tedTradableItems.itemList[keepAmountChosenItem].keepAmount;
5396 var amountToChangeTo = window[keepAmountChosenItem] - keepAmount;
5397 if (amountToChangeTo < 0) amountToChangeTo = 0;
5398 document.getElementById("chosenpostitem-amount").value = amountToChangeTo;
5399 if (keepAmount !== undefined) {
5400 var keepAmountTextInner = "<br>Keep: " + numberWithCommas(keepAmount) + " | Total: " + numberWithCommas(window[keepAmountChosenItem]) + " | <input type='button' value='All' onclick='keepAmountSetMax();'/>";
5401 if (keepAmountText.innerHTML != keepAmountTextInner) {
5402 keepAmountText.innerHTML = keepAmountTextInner;
5403 }
5404 }
5405 if (!cpiPostString.includes("modifyKeepList")) {
5406 cpiPostString = "modifyKeepList('" + keepAmountChosenItem + "');" + cpiPostString;
5407 document.getElementById("cpi-post").setAttribute("onclick", cpiPostString);
5408 }
5409 let cpiCurrentModify = cpiPostString.substring(cpiPostString.indexOf("modifyKeepList"), cpiPostString.indexOf(";") + 1);
5410 let cpiExpectedModify = "modifyKeepList('" + keepAmountChosenItem + "');";
5411 if (cpiCurrentModify != cpiExpectedModify) {
5412 cpiPostString = cpiPostString.replace(cpiCurrentModify, cpiExpectedModify);
5413 document.getElementById("cpi-post").setAttribute("onclick", cpiPostString);
5414 }
5415 }
5416 }
5417 cpi_itemName = document.getElementById("chosenpostitem-itemName").value;
5418 let itemPrice = numberWithCommas(document.getElementById("chosenpostitem-price").value);
5419 if (document.getElementById("chosenpostitem-price").value != itemPrice) {
5420 document.getElementById("chosenpostitem-price").value = itemPrice;
5421 }
5422 let itemAmount = numberWithCommas(document.getElementById("chosenpostitem-amount").value);
5423 if (document.getElementById("chosenpostitem-amount").value != itemAmount) {
5424 document.getElementById("chosenpostitem-amount").value = itemAmount;
5425 }
5426 }
5427 let totalPrice = parseInt(numberWithoutCommas(document.getElementById("chosenpostitem-amount").value)) * parseInt(numberWithoutCommas(document.getElementById("chosenpostitem-price").value));
5428 if (isNaN(totalPrice)) totalPrice = "";
5429 if (cpi_totalPrice != totalPrice) {
5430 chosenpostitem_total();
5431 }
5432 } else if (document.getElementById("dialogue-market-chosenpostitem").parentNode.style.display == "none") {
5433 if (cpi_itemName !== "") {
5434 cpi_itemName = "";
5435 }
5436 if (document.getElementById("chosenpostitem-price").value !== "") {
5437 document.getElementById("chosenpostitem-price").value = "";
5438 }
5439 if (document.getElementById("chosenpostitem-itemName").value !== "") {
5440 document.getElementById("chosenpostitem-itemName").value = "";
5441 }
5442 }
5443 }
5444
5445 function market_slots() {
5446 for (let i = 1; i <= arrMarketSlots.length; i++) {
5447 if (parseInt(document.getElementById("market-slot-" + i + "-collect").innerHTML) > 0 && ms_collect_repeat[i]) {
5448 ms_collect_repeat[i] = false;
5449 document.getElementById("market-slot-" + i + "-collect").parentNode.style.boxShadow = "0 0 30px 3px rgba(255, 0, 0, 1) inset";
5450 document.getElementById("market-slot-" + i + "-collect").parentNode.style.transition = "box-shadow 0.5s ease-in-out";
5451 setTimeout(function() {
5452 document.getElementById("market-slot-" + i + "-collect").parentNode.style.boxShadow = "0 0 30px 3px rgba(255, 0, 0, 0) inset";
5453 document.getElementById("market-slot-" + i + "-collect").parentNode.style.transition = "box-shadow 0.5s ease-in-out";
5454 setTimeout(function() {
5455 ms_collect_repeat[i] = true;
5456 }, 500);
5457 }, 500);
5458 }
5459 let marketSlotPrice = document.getElementById("market-slot-" + i + "-price").innerHTML;
5460 if (marketSlotPrice.includes(" ")) {
5461 marketSlotPrice = document.getElementById("market-slot-" + i + "-price").innerHTML.substr(0, document.getElementById("market-slot-" + i + "-price").innerHTML.indexOf(" "));
5462 }
5463 if (document.getElementById("market-slot-" + i + "-price").innerHTML != numberWithCommas(marketSlotPrice)) {
5464 document.getElementById("market-slot-" + i + "-price").innerHTML = numberWithCommas(marketSlotPrice);
5465 }
5466 if (document.getElementById("market-slot-" + i + "-amount").innerHTML != numberWithCommas(document.getElementById("market-slot-" + i + "-amount").innerHTML)) {
5467 document.getElementById("market-slot-" + i + "-amount").innerHTML = numberWithCommas(document.getElementById("market-slot-" + i + "-amount").innerHTML);
5468 }
5469 if (document.getElementById("market-slot-" + i + "-collect").innerHTML != numberWithCommas(document.getElementById("market-slot-" + i + "-collect").innerHTML)) {
5470 document.getElementById("market-slot-" + i + "-collect").innerHTML = numberWithCommas(document.getElementById("market-slot-" + i + "-collect").innerHTML);
5471 }
5472 }
5473 }
5474
5475 function brewingMaxPlaceholder() {
5476 if (brewingPlaceholder) {
5477 if ((ph_brewing_repeat || ph_brewing_cur_potion != document.getElementById('dialogue-potion-chosen').value) && document.getElementById("dialogue-brewing").parentNode.style.display != "none" && document.getElementById('dialogue-potion-chosen').value !== "") {
5478 ph_brewing_repeat = false;
5479 ph_brewing_cur_potion = document.getElementById('dialogue-potion-chosen').value;
5480 document.getElementById('dialogue-brewing-input').value = "";
5481 var placeholderBrewing, vialRequired, placeholderBrewingText;
5482 for (var i = 0; i < brewingRecipes[ph_brewing_cur_potion].recipe.length; i++) {
5483 var maxAmount = Math.floor(window[brewingRecipes[ph_brewing_cur_potion].recipe[i]] / brewingRecipes[ph_brewing_cur_potion].recipeCost[i]);
5484 if (i === 0 || maxAmount < placeholderBrewing) {
5485 placeholderBrewing = maxAmount;
5486 }
5487 }
5488 let arrVials = ["stardustPotion", "treePotion", "seedPotion", "smeltingPotion", "oilPotion", "barPotion", "superStardustPotion", "essencePotion", "combatCooldownPotion", "farmingSpeedPotion"];
5489 let arrLargeVials = ["stargemPotion", "superEssencePotion", "superOilPotion", "stardustCrystalPotion", "superTreePotion", "superCombatCooldownPotion"];
5490 let arrHugeVials = ["superCompostPotion"];
5491 if (arrVials.indexOf(ph_brewing_cur_potion) >= 0) {
5492 vialRequired = "vialOfWater";
5493 } else if (arrLargeVials.indexOf(ph_brewing_cur_potion) >= 0) {
5494 vialRequired = "largeVialOfWater";
5495 } else if (arrHugeVials.indexOf(ph_brewing_cur_potion) >= 0) {
5496 vialRequired = "hugeVialOfWater";
5497 } else vialRequired = "error";
5498 if (vialRequired != "error" && Math.floor(window[vialRequired] / placeholderBrewing) < 1) {
5499 let placeholderBrewing2 = window[vialRequired];
5500 placeholderBrewingText = "max: " + placeholderBrewing2 + ", need: +" + (placeholderBrewing - placeholderBrewing2) + " vials";
5501 } else placeholderBrewingText = "max: " + placeholderBrewing;
5502 if (placeholderBrewingText != document.getElementById("dialogue-brewing-input").getAttribute("placeholder")) {
5503 document.getElementById("dialogue-brewing-input").setAttribute("placeholder", placeholderBrewingText);
5504 }
5505 } else if (document.getElementById("dialogue-brewing").parentNode.style.display == "none") {
5506 ph_brewing_repeat = true;
5507 }
5508 }
5509 }
5510
5511 function craftingVialMaxPlaceholder() {
5512 if (craftingVialPlaceholder) {
5513 if ((ph_vial_repeat || ph_vial_cur_vial != document.getElementById("dialogue-multicraft-chosen").value) && document.getElementById("dialogue-multicraft").parentNode.style.display != "none" && document.getElementById("dialogue-multicraft-chosen").value !== "") {
5514 ph_vial_repeat = false;
5515 ph_vial_cur_vial = document.getElementById("dialogue-multicraft-chosen").value;
5516 document.getElementById('dialogue-multicraft-input').value = "";
5517 var glassRequired;
5518 if (ph_vial_cur_vial == "vialOfWater") {
5519 glassRequired = document.getElementById("recipe-cost-vialOfWater-0").innerHTML;
5520 } else if (ph_vial_cur_vial == "largeVialOfWater") {
5521 glassRequired = document.getElementById("recipe-cost-largeVialOfWater-0").innerHTML;
5522 } else if (ph_vial_cur_vial == "hugeVialOfWater") {
5523 glassRequired = document.getElementById("recipe-cost-hugeVialOfWater-0").innerHTML;
5524 }
5525 var maxAmount = Math.floor(glass / glassRequired);
5526 var placeholderVialText = "max: " + maxAmount;
5527 if (placeholderVialText != document.getElementById("dialogue-multicraft-input").getAttribute("placeholder")) {
5528 document.getElementById("dialogue-multicraft-input").setAttribute("placeholder", placeholderVialText);
5529 }
5530 } else if (document.getElementById("dialogue-multicraft").parentNode.style.display == "none") {
5531 ph_vial_repeat = true;
5532 }
5533 }
5534 }
5535
5536 function getLowestMarketPrice(item) {
5537 item = itemNameFix(item);
5538 if (arrMarketItems[item]) { // if we have seen item
5539 return arrMarketItems[item][0].price;
5540 }
5541 return 0;
5542 }
5543 window.resetOreAverage = function() {
5544 currentOreReset = true;
5545 };
5546
5547 function oreAverageMain() {
5548 if (oreAverageOn && oreAverageElement.style.display !== "") {
5549 oreAverageElement.style.display = "";
5550 } else if (!oreAverageOn && oreAverageElement.style.display != "none") {
5551 oreAverageElement.style.display = "none";
5552 }
5553 var i, keys = Object.keys(minedOres);
5554 if (currentOreReset) {
5555 keys.forEach((key) => {
5556 minedOres[key].startAmount = window[key];
5557 });
5558 oreAverageStartTicks = playtime;
5559 currentOreReset = false;
5560 }
5561 oreAverageElapsedTicks = playtime - oreAverageStartTicks;
5562 var oreAverageInnerText = "";
5563 oreAverageInnerText += "<br><span style='color:red'>Note: Table will be inaccurate if you change the number of ores you have. Avoid: trading ores, turning machinery on/off, opening lootbags, smelting bars. Use reset button after these changes for accurate results.</span><br><br>";
5564 oreAverageInnerText += "<button onclick='resetOreAverage();'>Reset</button><br><br>";
5565 oreAverageInnerText += "<span style='color:white'>Elapsed ticks: " + oreAverageElapsedTicks + "<br><br>";
5566 oreAverageInnerText += "Current config:</span><br><br>";
5567 oreAverageInnerText += "<table style='text-align:right;color:white;width:16.66%;border-style:solid;border-color:white;border-width:1px;'>";
5568 oreAverageInnerText += "<tr><td>miners:</td><td>" + miner + "</td></tr>";
5569 oreAverageInnerText += "<tr><td>drills:</td><td>" + drillsOn + "</td></tr>";
5570 oreAverageInnerText += "<tr><td>crushers:</td><td>" + crushersOn + "</td></tr>";
5571 oreAverageInnerText += "<tr><td>giant drills:</td><td>" + giantDrillsOn + "</td></tr>";
5572 oreAverageInnerText += "<tr><td>excavators:</td><td>" + excavatorsOn + "</td></tr>";
5573 oreAverageInnerText += "<tr><td>giant excavators:</td><td>" + giantExcavatorsOn + "</td></tr>";
5574 oreAverageInnerText += "</table><br>";
5575 oreAverageInnerText += "<table class='top-bar' style='text-align:right'>";
5576 oreAverageInnerText += "<th>Ore</th><th>Ore price</th><th>Ores mined</th><th>Ores/tick</th><th>Coins/tick</th><th>Ores/day</th><th>Coins/day</th>";
5577 for (i = 6; i < Object.keys(minedOres).length; i++) {
5578 if (Object.keys(arrMarketItems).length > 1) {
5579 minedOres[Object.keys(minedOres)[i]].price = getLowestMarketPrice(Object.keys(minedOres)[i]); // set high tier ore price
5580 }
5581 }
5582 var oreTickTotal = 0,
5583 coinTickTotal = 0,
5584 oreDayTotal = 0,
5585 coinDayTotal = 0,
5586 oresMinedTotal = 0;
5587 keys.forEach((key) => {
5588 minedOres[key].currentAmount = window[key];
5589 var oreName = key;
5590 var orePrice = minedOres[key].price;
5591 var oresMined = minedOres[key].currentAmount - minedOres[key].startAmount;
5592 minedOres[key].oreTick = ((minedOres[key].currentAmount - minedOres[key].startAmount) / oreAverageElapsedTicks);
5593 minedOres[key].coinTick = (minedOres[key].oreTick * minedOres[key].price);
5594 minedOres[key].oreDay = (((minedOres[key].currentAmount - minedOres[key].startAmount) / oreAverageElapsedTicks) * 86400);
5595 minedOres[key].coinDay = (minedOres[key].coinTick * 86400);
5596 oreAverageInnerText += "<tr><td>" + oreName + "</td>";
5597 oreAverageInnerText += "<td>" + numberWithCommas(orePrice) + "</td>";
5598 oreAverageInnerText += "<td>" + numberWithCommas(oresMined) + "</td>";
5599 if (Object.keys(minedOres).indexOf(key) <= 7) { // if ore is marble or lower
5600 oreAverageInnerText += "<td>" + minedOres[key].oreTick.toFixed(3) + "</td>";
5601 } else oreAverageInnerText += "<td>" + Number(minedOres[key].oreTick).toFixed(6) + "</td>";
5602 oreAverageInnerText += "<td>" + minedOres[key].coinTick.toFixed(2) + "</td>";
5603 if (Object.keys(minedOres).indexOf(key) <= 7) { // if ore is marble or lower
5604 oreAverageInnerText += "<td>" + numberWithCommas(parseInt(minedOres[key].oreDay)) + "</td>";
5605 } else oreAverageInnerText += "<td>" + numberWithCommas(Number(minedOres[key].oreDay).toFixed(2)) + "</td>";
5606 oreAverageInnerText += "<td>" + numberWithCommas(parseInt(minedOres[key].coinDay)) + "</td></tr>";
5607 oresMinedTotal += parseInt(oresMined);
5608 oreTickTotal += parseFloat(minedOres[key].oreTick.toFixed(2));
5609 coinTickTotal += parseFloat(minedOres[key].coinTick.toFixed(2));
5610 oreDayTotal += parseInt(minedOres[key].oreDay);
5611 coinDayTotal += parseInt(minedOres[key].coinDay);
5612 });
5613 oreAverageInnerText += "<tr><td> </td></tr><tr><td>Total:</td><td></td><td>" + numberWithCommas(oresMinedTotal) + "</td><td>" + numberWithCommas(oreTickTotal.toFixed(2)) + "</td><td>" + numberWithCommas(coinTickTotal.toFixed(2)) + "</td><td>" + numberWithCommas(oreDayTotal) + "</td><td>" + numberWithCommas(coinDayTotal) + "</td></tr>";
5614 oreAverageInnerText += "</table>";
5615 oreAverageElement.innerHTML = oreAverageInnerText;
5616 }
5617 window.bfmCommaFix = function() {
5618 document.getElementById('buyFromMarket-input').value = numberWithoutCommas(document.getElementById('buyFromMarket-input').value);
5619 document.getElementById('buyFromMarket-price').innerHTML = numberWithoutCommas(document.getElementById('buyFromMarket-price').innerHTML);
5620 };
5621
5622 function dialogue_buyFromMarket() {
5623 //comma fix for price each
5624 if (document.getElementById("dialogue-buyFromMarket").parentNode.style.display === "" && document.getElementById("buyFromMarket-price").innerHTML != numberWithCommas(document.getElementById("buyFromMarket-price").innerHTML)) {
5625 document.getElementById("buyFromMarket-price").innerHTML = numberWithCommas(document.getElementById("buyFromMarket-price").innerHTML);
5626 }
5627 //comma fix for enter amount
5628 if (document.getElementById('buyFromMarket-input').value != numberWithCommas(document.getElementById('buyFromMarket-input').value)) {
5629 document.getElementById('buyFromMarket-input').value = numberWithCommas(document.getElementById('buyFromMarket-input').value);
5630 }
5631 //set price to no commas onclick Buy
5632 var bfmBuyString = document.getElementById('buyFromMarket-buy').getAttribute("onclick");
5633 if (!bfmBuyString.includes("bfmCommaFix();")) {
5634 bfmBuyString = "bfmCommaFix();" + bfmBuyString;
5635 document.getElementById("buyFromMarket-buy").setAttribute("onclick", bfmBuyString);
5636 }
5637 //change Are you sure you want to spend... price to comma format
5638 if (document.getElementById("dialogue-confirm-cmd").parentNode.parentNode.style.display === "" && document.getElementById("dialogue-confirm-cmd").value.includes("MARKET_BUY=")) {
5639 let priceString = document.getElementById("dialogue-confirm-text").innerHTML;
5640 let price = priceString.substring(priceString.indexOf("<img src=\"images/coins.png\" class=\"image-icon-20\">") + 51, priceString.indexOf(" on this purchase"));
5641 if (document.getElementById("dialogue-confirm-text").innerHTML != priceString.replace(price, numberWithCommas(price))) {
5642 document.getElementById("dialogue-confirm-text").innerHTML = priceString.replace(price, numberWithCommas(price));
5643 }
5644 }
5645 }
5646
5647 function persistentInterval() {
5648 let minigameLastPingReceived = new Date().getTime() - pingTimeStart;
5649 if (minigameLastPingReceived >= 10000 && !pingSent && minigameMyStatus == "ingame" && minigameOpp) {
5650 pingSent = true;
5651 minigamePing(minigameOpp, minigameGame);
5652 setTimeout(function() {
5653 if (pingSent) {
5654 tmgReset();
5655 }
5656 }, 5000);
5657 }
5658 if (marketOn) {
5659 //dh2fixed input box type=number fix
5660 if (document.getElementById("chosenpostitem-amount").getAttribute("type") != "text") {
5661 document.getElementById("chosenpostitem-amount").setAttribute("type","text");
5662 }
5663 if (document.getElementById("chosenpostitem-price").getAttribute("type") != "text") {
5664 document.getElementById("chosenpostitem-price").setAttribute("type","text");
5665 }
5666 if (nextTick()) {
5667 oreAverageMain();
5668 if (treasureMap > 0 && document.getElementById("mapSpan").style.display !== "") {
5669 document.getElementById("mapSpan").style.display = "";
5670 } else if (treasureMap === 0 && document.getElementById("mapSpan").style.display != "none") {
5671 document.getElementById("mapSpan").style.display = "none";
5672 }
5673 //marketCancelCooldownSlots overwrite Cancel with countdown
5674 let arrMarketCancelCooldownSlots = [marketCancelCooldownSlot1, marketCancelCooldownSlot2, marketCancelCooldownSlot3];
5675 for (let i = 0; i < arrMarketCancelCooldownSlots.length; i++) {
5676 if (arrMarketCancelCooldownSlots[i] === 0) {
5677 if (document.getElementById("market-slot-" + (i + 1) + "-cancel-btn").innerHTML != "Cancel") {
5678 document.getElementById("market-slot-" + (i + 1) + "-cancel-btn").innerHTML = "Cancel";
5679 }
5680 } else if (document.getElementById("market-slot-" + (i + 1) + "-cancel-btn").innerHTML != arrMarketCancelCooldownSlots[i]) {
5681 document.getElementById("market-slot-" + (i + 1) + "-cancel-btn").innerHTML = arrMarketCancelCooldownSlots[i];
5682 }
5683 }
5684 }
5685 dialogue_market_chosenpostitem();
5686 dialogue_buyFromMarket();
5687 refreshMarketAfterBuyingItem();
5688 market_slots();
5689 brewingMaxPlaceholder();
5690 craftingVialMaxPlaceholder();
5691 }
5692 if (displayNotificationTreasureMap && treasureMap > 0 && document.getElementById("tedmarket-notif-map").style.display != "inline-block") {
5693 document.getElementById("tedmarket-notif-map").style.display = "inline-block";
5694 } else if (treasureMap === 0 && document.getElementById("tedmarket-notif-map").style.display != "none") {
5695 document.getElementById("tedmarket-notif-map").style.display = "none";
5696 }
5697 if (allowedBrowserNotifications && notifyWindChange) {
5698 if (windLastCheck == -1) {
5699 windLastCheck = sailBoatWindGlobal;
5700 } else if (windLastCheck != sailBoatWindGlobal) {
5701 windLastCheck = sailBoatWindGlobal;
5702 let windLevel = "";
5703 switch (windLastCheck) {
5704 case 0:
5705 windLevel = "no wind";
5706 break;
5707 case 1:
5708 windLevel = "low wind";
5709 break;
5710 case 2:
5711 windLevel = "medium wind";
5712 break;
5713 case 3:
5714 windLevel = "high wind";
5715 break;
5716 case 4:
5717 windLevel = "very high wind";
5718 break;
5719 }
5720 new Notification("The wind level has changed!", {
5721 body: "The wind level is now: " + windLevel,
5722 icon: "images/sailBoat.png"
5723 });
5724 }
5725 }
5726 }
5727 window.setLastBrowsedItem = function(item) {
5728 lastBrowsedItem = item;
5729 };
5730
5731 function addLastBrowsedItemOnclick() {
5732 for (var i = 0; i < document.getElementById("dialogue-market-items-area").childNodes.length; i++) {
5733 for (var j = 0; j < document.getElementById("dialogue-market-items-area").childNodes[i].children.length; j++) {
5734 var oldOnclick = document.getElementById("dialogue-market-items-area").childNodes[i].children[j].getAttribute("onclick");
5735 document.getElementById("dialogue-market-items-area").childNodes[i].children[j].setAttribute("onclick", "setLastBrowsedItem('" + document.getElementById('dialogue-market-items-area').childNodes[i].children[j].getAttribute('data-item-name') + "');" + oldOnclick);
5736 }
5737 }
5738 }
5739 var objEnergy = {
5740 shrimp: 50,
5741 sardine: 400,
5742 tuna: 1000,
5743 swordfish: 7500,
5744 shark: 20000,
5745 };
5746 var objHeat = {
5747 logs: 1,
5748 oakLogs: 2,
5749 willowLogs: 5,
5750 mapleLogs: 10,
5751 stardustLogs: 20,
5752 essenceLogs: 30,
5753 };
5754 var objBonemeal = {
5755 bones: 1,
5756 ashes: 2,
5757 iceBones: 3,
5758 };
5759
5760 function otherSettingsRunOnce() {
5761 //send market data to developer
5762 addWebsocketHook();
5763 //press enter in input box when buying item to progress dialogue and go to confirm
5764 document.getElementById("buyFromMarket-input").setAttribute("onkeydown", "if (event.keyCode == 13) { document.getElementById('buyFromMarket-buy').click(); }");
5765 //add undercut buttons to dialogue-market-chosenpostitem
5766 if (useUndercutBox) {
5767 var arrUndercut = ["2", "0.25%", "0.5%", "1%", "2%", "5%", "10%", "cheapest", "min", "match", "max"];
5768 var undercutBox = document.createElement("div");
5769 undercutBox.setAttribute("class", "basic-smallbox");
5770 undercutBox.setAttribute("id", "undercutBox");
5771 undercutBox.setAttribute("style", "text-align:center");
5772 document.getElementById("dialogue-market-chosenpostitem").insertBefore(undercutBox, document.getElementById("dialogue-market-chosenpostitem").getElementsByTagName("span")[0].nextSibling);
5773 document.getElementById("dialogue-market-chosenpostitem").insertBefore(document.createElement("br"), document.getElementById("dialogue-market-chosenpostitem").getElementsByTagName("span")[0].nextSibling);
5774 document.getElementById("dialogue-market-chosenpostitem").insertBefore(document.createElement("br"), document.getElementById("dialogue-market-chosenpostitem").getElementsByTagName("span")[0].nextSibling);
5775 window.setUndercut = function(undercutAmount, btn) {
5776 var undercutValue;
5777 var currentPrice = Math.ceil((numberWithoutCommas(document.getElementById("chosenpostitem-upper").innerHTML) + numberWithoutCommas(document.getElementById("chosenpostitem-lower").innerHTML)) / 2);
5778 if (undercutAmount == "cheapest") {
5779 let itemName = itemNameFix(lastBrowsedItem);
5780 var cheapest, price = null;
5781 if (objEnergy[itemName]) {
5782 for (let key in objEnergy) {
5783 if (Object.keys(arrMarketItems).length <= 1) {
5784 document.getElementById("chosenpostitem-price").value = "Search all first";
5785 break;
5786 }
5787 if (arrMarketItems[key] && arrMarketItems[key][0].price) {
5788 if (arrMarketItems[key][0].price / objEnergy[key] < cheapest || typeof(cheapest) == "undefined") {
5789 cheapest = arrMarketItems[key][0].price / objEnergy[key];
5790 price = Math.ceil(cheapest * objEnergy[itemName]) - 2;
5791 }
5792 }
5793 }
5794 } else if (objHeat[itemName]) {
5795 var avgSdValue, avgFragValue;
5796 for (let key in objHeat) {
5797 if (Object.keys(arrMarketItems).length <= 1) {
5798 document.getElementById("chosenpostitem-price").value = "Search all first";
5799 break;
5800 }
5801 if (arrMarketItems[key] && arrMarketItems[key][0].price && key == "stardustLogs") {
5802 if (arrMarketItems.stardust[0] && arrMarketItems.stardustLogs[0]) {
5803 var stardustPrice;
5804 if (arrMarketItems.stardust && arrMarketItems.stardust[0]) {
5805 let count = 0,
5806 itemPrice = 0;
5807 for (let i = 0; i < arrMarketItems.stardust.length; i++) {
5808 count++;
5809 itemPrice += arrMarketItems.stardust[i].price;
5810 }
5811 stardustPrice = Math.ceil(itemPrice / count);
5812 } else continue;
5813 avgSdValue = ((2500 + 10000) / 2) * (stardustPrice - 1); //sd value per log at average-1 when selling
5814 let sdLogHeatCost = Math.ceil(((arrMarketItems.stardustLogs[0].price - avgSdValue) / objHeat.stardustLogs));
5815 if (sdLogHeatCost < cheapest) {
5816 cheapest = sdLogHeatCost;
5817 }
5818 }
5819 } else if (arrMarketItems[key] && arrMarketItems[key][0].price && key == "essenceLogs") {
5820 if (arrMarketItems.essence[0]) {
5821 avgFragValue = ((1 + 14) / 200) * (arrMarketItems.essence[0].price); //ess at current low price when selling
5822 let essLogHeatCost = Math.ceil((arrMarketItems.essenceLogs[0].price - avgFragValue) / objHeat.essenceLogs);
5823 if (essLogHeatCost < cheapest) {
5824 cheapest = essLogHeatCost;
5825 }
5826 }
5827 } else if (arrMarketItems[key] && arrMarketItems[key][0].price) {
5828 if (arrMarketItems[key][0].price / objHeat[key] < cheapest || typeof(cheapest) == "undefined") {
5829 cheapest = arrMarketItems[key][0].price / objHeat[key];
5830 }
5831 }
5832 }
5833 if (typeof(cheapest) !== "undefined") {
5834 if (itemName == "stardustLogs") {
5835 if (arrMarketItems.stardustLogs && arrMarketItems.stardustLogs[0].price) {
5836 price = (cheapest - 1) * objHeat[itemName] + avgSdValue;
5837 }
5838 } else if (itemName == "essenceLogs") {
5839 if (arrMarketItems.essenceLogs && arrMarketItems.essenceLogs[0].price) {
5840 price = (cheapest - 1) * objHeat[itemName] + avgFragValue;
5841 }
5842 } else {
5843 price = Math.ceil(cheapest * objHeat[itemName]) - 2;
5844 }
5845 }
5846 } else if (objBonemeal[itemName]) {
5847 for (let key in objBonemeal) {
5848 if (Object.keys(arrMarketItems).length <= 1) {
5849 document.getElementById("chosenpostitem-price").value = "Search all first";
5850 break;
5851 }
5852 if (arrMarketItems[key] && arrMarketItems[key][0].price) {
5853 if (arrMarketItems[key][0].price / objBonemeal[key] < cheapest || typeof(cheapest) == "undefined") {
5854 cheapest = arrMarketItems[key][0].price / objBonemeal[key];
5855 price = Math.ceil(cheapest * objBonemeal[itemName]) - 2;
5856 }
5857 }
5858 }
5859 }
5860 if (typeof(cheapest) !== "undefined") {
5861 undercutValue = price;
5862 } else undercutValue = null;
5863 } else if (undercutAmount == "min") {
5864 undercutValue = numberWithoutCommas(document.getElementById("chosenpostitem-lower").innerHTML);
5865 } else if (undercutAmount == "match") {
5866 undercutValue = currentPrice;
5867 } else if (undercutAmount == "max") {
5868 undercutValue = numberWithoutCommas(document.getElementById("chosenpostitem-upper").innerHTML);
5869 } else if (undercutAmount.indexOf("%") > -1) {
5870 undercutValue = currentPrice * ((100 - undercutAmount.replace(/%/g, "")) / 100);
5871 } else {
5872 undercutValue = currentPrice - undercutAmount;
5873 }
5874 if (undercutValue !== null && typeof(undercutValue) !== "undefined") {
5875 if (undercutValue < numberWithoutCommas(document.getElementById("chosenpostitem-lower").innerHTML)) {
5876 document.getElementById("chosenpostitem-price").value = numberWithCommas(document.getElementById("chosenpostitem-lower").innerHTML);
5877 } else if (undercutValue > numberWithoutCommas(document.getElementById("chosenpostitem-upper").innerHTML)) {
5878 document.getElementById("chosenpostitem-price").value = numberWithCommas(document.getElementById("chosenpostitem-upper").innerHTML);
5879 } else {
5880 document.getElementById("chosenpostitem-price").value = numberWithCommas(Math.ceil(undercutValue));
5881 }
5882 } else if (undercutValue === null || typeof(undercutValue) == "undefined") {
5883 disableBtn(btn, 1000);
5884 }
5885 };
5886 undercutBoxText.setAttribute("style", "text-align:center");
5887 undercutBox.append(undercutBoxText);
5888 for (var i = 0; i < arrUndercut.length; i++) {
5889 var undercutBtn = document.createElement("button");
5890 undercutBtn.setAttribute("onclick", "setUndercut('" + arrUndercut[i] + "',this);");
5891 if (arrUndercut[i] == "cheapest") {
5892 undercutBtn.innerHTML = "<img class='image-icon-20' src='images/icons/fire.png'><img class='image-icon-20' src='images/steak.png'><img class='image-icon-20' src='images/filledBonemealBin.png'>";
5893 undercutBtn.title = "Undercut cheapest heat/energy/bonemeal";
5894 } else undercutBtn.append(arrUndercut[i]);
5895 undercutBox.append(undercutBtn);
5896 if (arrUndercut[i] == "cheapest") {
5897 document.getElementById("undercutBox").insertBefore(document.createElement("br"), document.getElementById("undercutBox").lastChild);
5898 document.getElementById("undercutBox").insertBefore(document.createElement("br"), document.getElementById("undercutBox").lastChild);
5899 }
5900 document.getElementById("undercutBox").append(document.createTextNode("\u00a0")); //nbsp
5901 }
5902 // remove unnecessary multiple BR's that smitty left behind in dialogue-market-chosenpostitem
5903 var el = document.getElementById("undercutBox").nextElementSibling;
5904 while (el.nextElementSibling && el.tagName !== undefined && el.tagName != "BR") {
5905 el = el.nextElementSibling;
5906 }
5907 if (el.tagName == "BR" && el.nextElementSibling && el.nextElementSibling.tagName == "BR") {
5908 while (el.nextElementSibling.tagName == "BR") {
5909 el.nextElementSibling.parentNode.removeChild(el.nextElementSibling);
5910 }
5911 }
5912 }
5913 // set global variable lastBrowsedItem to last browsed item via onclick
5914 addLastBrowsedItemOnclick();
5915 //add maps to noficiation area
5916 var mapNotifWrapper = document.createElement("span");
5917 mapNotifWrapper.setAttribute("class", "notif-box");
5918 mapNotifWrapper.setAttribute("style", "display:none;background: linear-gradient(black, gold);");
5919 mapNotifWrapper.setAttribute("id", "tedmarket-notif-map");
5920 mapNotifWrapper.setAttribute("onclick", "clicksTreasureMap();");
5921 var mapNotif = document.createElement("img");
5922 mapNotif.setAttribute("src", "images/treasureMap.png");
5923 mapNotif.setAttribute("class", "image-icon-50");
5924 mapNotifWrapper.append(mapNotif);
5925 document.getElementById("notifaction-area").prepend(mapNotifWrapper);
5926 //add keepAmount to dialogue-market-chosenpostitem
5927 if (useKeepAmount) {
5928 keepAmountText.innerHTML = "Keep: error";
5929 document.getElementById("chosenpostitem-amount").parentNode.insertBefore(keepAmountText, document.getElementById("chosenpostitem-amount").nextSibling);
5930 document.getElementById("chosenpostitem-amount").parentNode.insertBefore(document.createElement("br"), document.getElementById("chosenpostitem-amount").nextSibling);
5931 //document.getElementById("chosenpostitem-amount").parentNode.insertBefore(document.createTextNode('\u00a0'),document.getElementById("chosenpostitem-amount").nextSibling);
5932 }
5933 //fix collect button padding to allow 123,456,789 format
5934 for (let i = 1; i <= arrMarketSlots.length; i++) {
5935 document.getElementById("market-slot-" + i + "-collect-btn").style.padding = "10px 5px";
5936 }
5937 //add tooltips to items that do not have a tooltip
5938 function tedTooltips() {
5939 if (!document.getElementById("tooltip-stone")) { // don't add tooltips until default tooltips are loaded
5940 setTimeout(function() {
5941 tedTooltips();
5942 }, 100);
5943 } else {
5944 var tKeys = Object.keys(jsTradableItems);
5945 tKeys.forEach((key) => {
5946 if (key == "emptyChisel") return;
5947 if (!document.getElementById("tooltip-" + key)) {
5948 if (document.getElementById("item-box-" + key)) {
5949 let newTooltip = document.createElement("div");
5950 document.getElementById("tooltip-list").append(newTooltip);
5951 newTooltip.outerHTML = "<div id='tooltip-" + key + "' style='display:none;'> <span style='font-size:20pt'>" + getItemName(key) + "</span><br><br></div>";
5952 document.getElementById("item-box-" + key).removeAttribute("title");
5953 document.getElementById("item-box-" + key).setAttribute("data-tooltip-id", "tooltip-" + key);
5954 }
5955 }
5956 });
5957 loadTooltips();
5958 }
5959 }
5960 tedTooltips();
5961 tradeHistory();
5962 document.body.append(oreAverageElement);
5963 calculateFlips();
5964 sortTradeHistory(sortByTH);
5965 //add an id to Post button in dialogue-market-chosenpostitem
5966 for (let i = 0; i < document.getElementById("dialogue-market-chosenpostitem").children.length; i++) {
5967 if (document.getElementById("dialogue-market-chosenpostitem").children[i].defaultValue == "Post") {
5968 document.getElementById("dialogue-market-chosenpostitem").children[i].setAttribute("id", "cpi-post");
5969 break;
5970 }
5971 }
5972 //add an id to Buy button in buyFromMarket-dialogue
5973 for (let i = 0; i < document.getElementById("dialogue-buyFromMarket").children.length; i++) {
5974 if (document.getElementById("dialogue-buyFromMarket").children[i].defaultValue == "Buy") {
5975 document.getElementById("dialogue-buyFromMarket").children[i].setAttribute("id", "buyFromMarket-buy");
5976 }
5977 }
5978 //add fixCpiNumbers to convert commas to without commas on post
5979 var cpiPostString = document.getElementById("cpi-post").getAttribute("onclick");
5980 if (!cpiPostString.includes("fixCpiNumbers();")) {
5981 cpiPostString = "fixCpiNumbers();" + cpiPostString;
5982 document.getElementById("cpi-post").setAttribute("onclick", cpiPostString);
5983 }
5984 // show total price when posting an item
5985 if (document.getElementById("chosenpostitem-itemName").nextElementSibling && document.getElementById("chosenpostitem-itemName").nextElementSibling.className == "basic-smallbox") {
5986 let chosenpostitem_totalprice = document.createElement("span");
5987 chosenpostitem_totalprice.setAttribute("id", "chosenpostitem-totalprice");
5988 document.getElementById("chosenpostitem-itemName").nextElementSibling.append(chosenpostitem_totalprice);
5989 }
5990 window.chosenpostitem_total = function() {
5991 let totalPrice = parseInt(numberWithoutCommas(document.getElementById("chosenpostitem-amount").value)) * parseInt(numberWithoutCommas(document.getElementById("chosenpostitem-price").value));
5992 if (isNaN(totalPrice)) totalPrice = "";
5993 cpi_totalPrice = totalPrice;
5994 document.getElementById("chosenpostitem-totalprice").innerHTML = "<br><br>Total Price: " + numberWithCommas(totalPrice);
5995 };
5996 document.getElementById("chosenpostitem-amount").setAttribute("onchange", "chosenpostitem_total();");
5997 document.getElementById("chosenpostitem-amount").setAttribute("onkeypress", "this.onchange();");
5998 document.getElementById("chosenpostitem-amount").setAttribute("onpaste", "this.onchange();");
5999 document.getElementById("chosenpostitem-amount").setAttribute("oninput", "this.onchange();");
6000 document.getElementById("chosenpostitem-price").setAttribute("onchange", "chosenpostitem_total();");
6001 document.getElementById("chosenpostitem-price").setAttribute("onkeypress", "this.onchange();");
6002 document.getElementById("chosenpostitem-price").setAttribute("onpaste", "this.onchange();");
6003 document.getElementById("chosenpostitem-price").setAttribute("oninput", "this.onchange();");
6004 //browser notification permission check
6005 if (!("Notification" in window)) {
6006 console.log("This browser does not support system notifications");
6007 } else if (Notification.permission == "granted") { // Let's check whether notification permissions have already been granted
6008 allowedBrowserNotifications = true;
6009 } else if (Notification.permission != 'denied') { // Otherwise, we need to ask the user for permission
6010 Notification.requestPermission(function(permission) {
6011 if (permission == "granted") {
6012 allowedBrowserNotifications = true;
6013 } else {
6014 allowedBrowserNotifications = false;
6015 }
6016 });
6017 } else {
6018 allowedBrowserNotifications = false;
6019 }
6020 /*// add poker in skill tab
6021 let pokerTab = document.createElement("td");
6022 let marketTab = document.getElementById("tab-container-bar-shop");
6023 pokerTab.setAttribute("id","tab-container-bar-poker");
6024 pokerTab.setAttribute("onclick","openTab('poker')");
6025 pokerTab.setAttribute("style", "background: linear-gradient(black, grey);");
6026 let pokerImg = document.createElement("img");
6027 pokerImg.setAttribute("class", "image-icon-50");
6028 pokerImg.setAttribute("src", "http://i.imgur.com/Yyi11pG.gif");
6029 let pokerSpan = document.createElement("span");
6030 pokerSpan.setAttribute("id","tab-container-bar-poker-label");
6031 pokerSpan.append("Poker");
6032 document.getElementById("tab-container-bar-shop").parentNode.append(pokerTab);
6033 pokerTab.append(pokerImg);
6034 pokerTab.append(pokerSpan);
6035 let pokerTabContainer = document.createElement("div");
6036 pokerTabContainer.setAttribute("class","tab-container");
6037 pokerTabContainer.setAttribute("id","tab-container-poker");
6038 pokerTabContainer.setAttribute("style","display:none");
6039 $(pokerTabContainer).insertAfter(document.getElementById("tab-container-shop")); */
6040 }
6041 tedMarketUiSettings();
6042 drawButtons();
6043 marketMain();
6044 alterMarketSlots();
6045 otherSettingsRunOnce();
6046 minigamesInit();
6047 setInterval(persistentInterval, 10);
6048 setInterval(tmg_pokerConnectionHandler, 1000);
6049 }
6050});