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