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