· 8 years ago · May 17, 2018, 04:10 PM
1// ==UserScript==
2// @name Ted's market UI FIXED
3// @namespace Ted's market UI FIXED
4// @version 1.473
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// @run-at document-idle
10// @grant none
11// ==/UserScript==
12var LOCALE = 'en-US';
13var updateNews = "Fixed trade history button that was not aligned properly. Removed the Price history graph button (the website is dead so the button serves no purpose). Use the price history from local data from dh2 fixed instead.<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: false
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: false,
179 alert: true,
180 },
181 useKeepAmount: {
182 text: "Remember amount not to sell when posting an item?",
183 value: false
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 brewingPlaceholder: {
217 text: "Show max potions brewable as placeholder text?",
218 value: true
219 },
220 craftingVialPlaceholder: {
221 text: "Show max vials craftable as placeholder text?",
222 value: true
223 },
224 displayNotificationTreasureMap: {
225 text: "Show notification when a treasure map is found?",
226 value: true
227 },
228 };
229
230 function itemNameFix(string) { // market style name to var style name; Bat Skin > batSkin
231 var a = string.replace(/\s/g, "");
232 return a.charAt(0).toLowerCase() + a.slice(1);
233 }
234 if (typeof(localStorage.tedSettings) == "undefined") {
235 localStorage.tedSettings = JSON.stringify(defaultSettings);
236 console.log("localstorage.tedSettings not found, creating based on defaultSettings");
237 console.log(localStorage.tedSettings);
238 }
239 var tedStoredSettings = JSON.parse(localStorage.getItem("tedSettings"));
240 for (var key in defaultSettings) {
241 if (!defaultSettings.hasOwnProperty(key)) continue;
242 if (tedStoredSettings[key] === undefined) {
243 //add from default
244 console.log("undefined " + key);
245 tedStoredSettings[key] = defaultSettings[key];
246 localStorage.tedSettings = JSON.stringify(tedStoredSettings);
247 console.log("Key not found, added from default: tedStoredSettings." + key);
248 if (key == "tedTradableItems") {
249 console.log("importing old data to tedTradableItems");
250 if (tedStoredSettings.tradableItemsKeepAmount) {
251 for (let i = 0; i < Object.keys(tedStoredSettings.tradableItemsKeepAmount.itemList).length; i++) {
252 tedStoredSettings.tedTradableItems.itemList[Object.keys(tedStoredSettings.tradableItemsKeepAmount.itemList)[i]].keepAmount = tedStoredSettings.tradableItemsKeepAmount.itemList[Object.keys(tedStoredSettings.tradableItemsKeepAmount.itemList)[i]];
253 }
254 delete tedStoredSettings.tradableItemsKeepAmount;
255 console.log("imported and deleted tedStoredSettings.tradableItemsKeepAmount");
256 }
257 if (tedStoredSettings.myItemList) {
258 for (let i = 0; i < tedStoredSettings.myItemList.length; i++) {
259 let itemName = itemNameFix(tedStoredSettings.myItemList[i][0]);
260 let myPrice = tedStoredSettings.myItemList[i][1];
261 tedStoredSettings.tedTradableItems.itemList[itemName].showAtPrice = myPrice;
262 }
263 delete tedStoredSettings.myItemList;
264 console.log("imported and deleted tedStoredSettings.myItemList");
265 }
266 if (tedStoredSettings.hideItemList) {
267 /*for (let i = 0; i < tedStoredSettings.hideItemList.length; i++) {
268 let itemName = itemNameFix(tedStoredSettings.hideItemList[i]);
269 tedStoredSettings.tedTradableItems.itemList[itemName].hideItem = true;
270 }*/
271 delete tedStoredSettings.hideItemList;
272 console.log("deleted tedStoredSettings.hideItemList");
273 }
274 }
275 } else if (debugToConsole) {
276 console.log("matched " + key);
277 }
278 for (var prop in defaultSettings[key]) {
279 if (tedStoredSettings[key].hasOwnProperty(prop)) continue;
280 console.log("tedStoredSettings." + key + "." + prop + " not found; adding from defaultSettings." + key + "." + prop);
281 tedStoredSettings[key][prop] = defaultSettings[key][prop];
282 }
283 if (tedStoredSettings[key].text && tedStoredSettings[key].text != defaultSettings[key].text) {
284 tedStoredSettings[key].text = defaultSettings[key].text;
285 localStorage.tedSettings = JSON.stringify(tedStoredSettings);
286 }
287 if (key == "tedTradableItems") { // check that tradableItems contains all tradable items
288 for (let i = 0; i < Object.keys(jsTradableItems).length; i++) {
289 if (typeof(tedStoredSettings.tedTradableItems.itemList[Object.keys(jsTradableItems)[i]]) === "undefined") {
290 tedStoredSettings.tedTradableItems.itemList[Object.keys(jsTradableItems)[i]] = {
291 keepAmount: 0,
292 showAtPrice: null,
293 alwaysShowLowest: true,
294 showAtMin: false
295 };
296 } else if (tedStoredSettings.tedTradableItems.itemList[Object.keys(jsTradableItems)[i]].tradeHistory) {
297 delete tedStoredSettings.tedTradableItems.itemList[Object.keys(jsTradableItems)[i]].tradeHistory;
298 }
299 }
300 }
301 if (key == "tradeHistory") {
302 // check that tradeHistory objects have "total" property
303 if (tedStoredSettings.tradeHistory && tedStoredSettings.tradeHistory[0]) {
304 if (!tedStoredSettings.tradeHistory[0].total) {
305 for (let i = 0; i < tedStoredSettings.tradeHistory.length; i++) {
306 if (typeof(tedStoredSettings.tradeHistory[i].total) == "undefined") {
307 tedStoredSettings.tradeHistory[i].total = (tedStoredSettings.tradeHistory[i].price * tedStoredSettings.tradeHistory[i].amount);
308 }
309 }
310 }
311 }
312 }
313 }
314 var notEnoughCoinsOpacity, showMaxCanBuy, showTotalPrice;
315 var smallMarketImages, marketImageSize = 30; //pixels, default:50, suggested: 30-40
316 var itemTooltips;
317 var autoUndercut, undercutBy = 2,
318 matchLowestPriceAt = 20;
319 var marketSlotsCustomUi;
320 var colorMinPrice, colorNextLowestToMinPrice, showSingleItems, colorSingleItems, colorMyListedLowest, colorMyListedLowestCanRaisePrice, colorMyListedNotLowest, colorLowestForMyListed, colorMyItemList, colorMyItemListNextLowest, colorAlwaysShowLowest;
321 var refreshMarketAfterBuyingItem_itemName;
322 var sendMarketData, sendMarketDataWaitTimeMins = 3 * 60 * 1000;
323 var useKeepAmount, useUndercutBox;
324 var showCheapestHeat, showCheapestEnergy, showCheapestBonemeal;
325 var stardustProfitGreenBox, superStardustProfitGreenBox, stargemProfitGreenBox;
326 var brewingPlaceholder, craftingVialPlaceholder;
327 var displayNotificationTreasureMap;
328
329
330 function updateVariables() {
331 localStorage.tedSettings = JSON.stringify(tedStoredSettings);
332 notEnoughCoinsOpacity = tedStoredSettings.notEnoughCoinsOpacity.value;
333 showMaxCanBuy = tedStoredSettings.showMaxCanBuy.value;
334 showTotalPrice = tedStoredSettings.showTotalPrice.value;
335 smallMarketImages = tedStoredSettings.smallMarketImages.value;
336 marketImageSize = 30; //pixels, default:50, suggested: 30-40
337 itemTooltips = tedStoredSettings.itemTooltips.value;
338 autoUndercut = tedStoredSettings.autoUndercut.value;
339 marketSlotsCustomUi = true; //tedStoredSettings.marketSlotsCustomUi.value;
340 undercutBy = 2;
341 matchLowestPriceAt = 20;
342 colorMinPrice = tedStoredSettings.colorMinPrice.bgcolor;
343 colorNextLowestToMinPrice = tedStoredSettings.colorNextLowestToMinPrice.bgcolor;
344 showSingleItems = tedStoredSettings.showSingleItems.value;
345 colorSingleItems = tedStoredSettings.colorSingleItems.bgcolor;
346 colorMyListedLowest = tedStoredSettings.colorMyListedLowest.bgcolor;
347 colorMyListedLowestCanRaisePrice = tedStoredSettings.colorMyListedLowestCanRaisePrice.bgcolor;
348 colorMyListedNotLowest = tedStoredSettings.colorMyListedNotLowest.bgcolor;
349 colorLowestForMyListed = tedStoredSettings.colorLowestForMyListed.bgcolor;
350 colorMyItemList = tedStoredSettings.colorMyItemList.bgcolor;
351 colorMyItemListNextLowest = tedStoredSettings.colorMyItemListNextLowest.bgcolor;
352 colorAlwaysShowLowest = tedStoredSettings.colorAlwaysShowLowest.bgcolor;
353 sendMarketData = tedStoredSettings.sendMarketData.value;
354 useKeepAmount = tedStoredSettings.useKeepAmount.value;
355 useUndercutBox = tedStoredSettings.useUndercutBox.value;
356 showCheapestHeat = tedStoredSettings.showCheapestHeat.value;
357 showCheapestEnergy = tedStoredSettings.showCheapestEnergy.value;
358 showCheapestBonemeal = tedStoredSettings.showCheapestBonemeal.value;
359 stardustProfitGreenBox = tedStoredSettings.stardustProfitGreenBox.value;
360 superStardustProfitGreenBox = tedStoredSettings.superStardustProfitGreenBox.value;
361 stargemProfitGreenBox = tedStoredSettings.stargemProfitGreenBox.value;
362 brewingPlaceholder = tedStoredSettings.brewingPlaceholder.value;
363 if (!brewingPlaceholder) document.getElementById("dialogue-brewing-input").removeAttribute("placeholder");
364 craftingVialPlaceholder = tedStoredSettings.craftingVialPlaceholder.value;
365 if (!craftingVialPlaceholder) document.getElementById("dialogue-multicraft-input").removeAttribute("placeholder");
366 displayNotificationTreasureMap = tedStoredSettings.displayNotificationTreasureMap.value;
367 }
368 updateVariables();
369 if (tedStoredSettings.sendMarketData.alert === true) {
370 //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");
371 tedStoredSettings.sendMarketData.alert = false;
372 updateVariables();
373 }
374 var arrMarketItems = {};
375
376 function marketTableLength() {
377 return document.getElementById("market-table").rows.length;
378 }
379 var arrMarketSlots = []; //updateMarketSlots
380 for (let msi = 1; 1 == 1; msi++) {
381 if (document.getElementById("market-slot-" + msi)) {
382 arrMarketSlots.push([0, 0]);
383 } else break;
384 }
385 var marketInterval;
386 var marketOn = true;
387 var cpi_itemName = "";
388 var tickStart = new Date().getTime();
389 var tickEnd = new Date().getTime();
390 var tickTime = tickEnd - tickStart;
391 var tickCheck = 0;
392 var sendToSpreadsheet_timeoutStart = new Date().getTime(),
393 sendToSpreadsheet_timeout = 0;
394 var myItemListAddName, myItemListAddPrice;
395 var undercutBoxText = document.createElement("span");
396 var keepAmountText = document.createElement("span");
397 var ms_collect_repeat = [true, true, true],
398 ph_brewing_repeat = true,
399 ph_brewing_cur_potion = "",
400 ph_vial_repeat = true,
401 ph_vial_cur_vial = "";
402 var quickCalcStargemBoxShadow, quickCalcSuperStardustBoxShadow, quickCalcStardustBoxShadow, quickCalcTooltip = document.createElement("div");
403 var quickCalcStargemString = "",
404 quickCalcSuperStardustString = "",
405 quickCalcStardustString = "";
406 var searchAllDelay = 2500;
407 var lastBrowsedItem = "Stardust";
408 var oreAverageOn = false,
409 gc_lastClicked,
410 lastHover,
411 browserMouseX = 0,
412 browserMouseY = 0,
413 pingTimeStart = 0,
414 pingTime = 0,
415 pingSent = false,
416 windLastCheck = -1,
417 notifyWindChange = true,
418 allowedBrowserNotifications = false,
419 oreAverageElement = document.createElement("div"),
420 currentOreReset = true;
421 var oreAverageStartTicks = playtime;
422 var oreAverageElapsedTicks;
423 var allOres = [
424 ["stone", 1],
425 ["copper", 2],
426 ["tin", 2],
427 ["iron", 5],
428 ["silver", 10],
429 ["gold", 20],
430 ["quartz", 30],
431 ["marble", 100],
432 ["promethium", 1000],
433 ["runite", 5000]
434 ];
435 var minedOres = {};
436 for (let i = 0; i < allOres.length; i++) {
437 minedOres[allOres[i][0]] = {
438 currentAmount: 0,
439 price: allOres[i][1],
440 startAmount: window[allOres[i][0]],
441 oreTick: 0,
442 coinTick: 0,
443 oreDay: 0,
444 coinDay: 0,
445 };
446 }
447 var marketSlotSpareElement = document.createElement("div");
448 marketSlotSpareElement.setAttribute("style","margin-left:3px;margin-right:3px");
449 var oldDialogueConfirmYesOnclick = document.getElementById('dialogue-confirm-yes').getAttribute("onclick");
450 var th_object, th_status = "free",
451 thString = "";
452 var keepAmountChosenItem = "";
453 var cheapestHeat, cheapestEnergy, cheapestBonemeal;
454 var totalFlipProfit = 0;
455 var cpi_totalPrice;
456 var exactMatch = true,
457 searchString, exactSearch, searchVal = "";
458 var sortedTradeHistory = tedStoredSettings.tradeHistory,
459 sortByTH = "date",
460 thSortToggle = true;
461 var arrSortItemsList = [
462 "Donor Coins",
463 "Stardust",
464 "Blood Diamond", "Diamond", "Ruby", "Emerald", "Sapphire",
465 "Empty Chisel",
466 "Red Axe Orb", "Red Fishing Bait Orb", "Red Magic Wand Orb", "Red Charcoal Factory Orb", "Red Mana Star Orb", "Red Combat Loot Orb", "Red Rocket Orb",
467 "Green Rocket Orb", "Green Oil Factory Orb", "Green Oil Storage Orb", "Green Empowered Rock Orb", "Green Combat Orb", "Green Bow Orb", "Green Bonemeal Bin Orb", "Green Brewing Kit Orb",
468 "Blue Axe Orb", "Blue Chisel Orb", "Blue Fishing Rod Orb", "Blue Hammer Orb", "Blue Meditation Orb", "Blue Oil Pipe Orb", "Blue Pickaxe Orb", "Blue Rake Orb", "Blue Shovel Orb", "Blue Trowel Orb",
469 "Essence",
470 "Cannon", "Cannon Barrel", "Cannon Stand", "Cannon Wheels",
471 "Scythe", "Ghost Amulet",
472 "Bow", "Ice Arrows", "Fire Arrows", "Arrows",
473 "Skeleton Sword", "Skeleton Shield", "Bone Amulet",
474 "Iron Dagger", "Stinger",
475 "Runite Helmet Mould", "Runite Body Mould", "Runite Legs Mould", "Runite Gloves Mould", "Runite Boots Mould",
476 "Promethium Helmet Mould", "Promethium Body Mould", "Promethium Legs Mould", "Promethium Gloves Mould", "Promethium Boots Mould",
477 "Ancient Logs", "Strange Logs", "Essence Logs","Stardust Logs", "Maple Logs", "Willow Logs", "Oak Logs", "Logs",
478 "Dark Bones", "Moon Bones", "Ice Bones", "Bones", "Ashes",
479 "Ancient Tree Seeds", "Strange Leaf Tree Seeds", "Essence Tree Seeds","Stardust Tree Seeds", "Maple Tree Seeds", "Willow Tree Seeds", "Oak Tree Seeds", "Tree Seeds",
480 "Striped Crystal Leaf Seeds", "Crystal Leaf Seeds", "Striped Gold Leaf Seeds", "Gold Leaf Seeds", "Lime Leaf Seeds", "Green Leaf Seeds", "Dotted Green Leaf Seeds", "Snapegrass Seeds", "Blewit Mushroom Seeds", "Red Mushroom Seeds",
481 "Striped Crystal Leaf", "Crystal Leaf", "Striped Gold Leaf", "Gold Leaf", "Lime Leaf", "Green Leaf", "Dotted Green Leaf", "Snapegrass", "Blewit Mushroom", "Red Mushroom",
482 "Stranger Leaf", "Strange Leaf", "Strange Purple Leaf", "Strange Pink Leaf", "Strange Blue Leaf", "Strange Yellow Leaf", "Strange Green Leaf",
483 "Enchant Stargem Potion Spell Scroll", "Very High Wind Spell Scroll", "Empty Orb Spell Scroll", "Ghost Scan Spell Scroll", "Change Promethium Mould Scroll", "Change Runite Mould Scroll",
484 "Rainbowfish", "Whale", "Shark", "Eel", "Swordfish", "Lobster", "Tuna", "Salmon", "Sardine", "Shrimp",
485 "Fishing Bait","Raw Rainbowfish", "Raw Whale", "Raw Shark", "Raw Eel", "Raw Swordfish", "Raw Lobster", "Raw Tuna", "Raw Salmon", "Raw Sardine", "Raw Shrimp", "Wheat",
486 "Runite Bar", "Promethium Bar", "Gold Bar", "Silver Bar", "Iron Bar", "Bronze Bar",
487 "Runite", "Promethium", "Marble", "Quartz", "Glass", "Sand", "Stone", "Moonstone", "Mars Rock",
488 "Bear Fur", "Bat Skin", "Snake Skin", "Thread"
489 ];
490
491
492 var coinImg = document.createElement("img");
493 coinImg.setAttribute("src", "images/coins.png");
494 coinImg.setAttribute("class", "image-icon-20");
495
496
497 String.prototype.replaceAll = function(search, replacement) {
498 var target = this;
499 return target.replace(new RegExp(search, 'g'), replacement);
500 };
501
502 function drawButtons() {
503 var zMarket = document.createElement("div");
504 var marketUiButton = document.createElement("button");
505 marketUiButton.setAttribute("id", "marketButton");
506 marketUiButton.setAttribute("type", "button");
507 var oreAverageButton = document.createElement("button");
508 oreAverageButton.setAttribute("id", "oreAverageButton");
509 oreAverageButton.setAttribute("type", "button");
510 var zMap = document.createElement("span");
511 zMap.setAttribute("id", "mapSpan");
512 zMap.setAttribute("style", "color:gold");
513 zMap.innerHTML = " You have an incomplete map!";
514 var zVer = document.createElement("span");
515 zVer.setAttribute("style", "color:silver");
516 zVer.innerHTML = " version: " + GM_info.script.version + " ";
517 zMarket.setAttribute("id", "zMarketId");
518 zMarket.append(marketUiButton);
519 zMarket.append(zVer);
520 zMarket.append(oreAverageButton);
521 //zMarket.append(zMap);
522 document.getElementById("game-div").appendChild(zMarket);
523 document.getElementById("marketButton").addEventListener("click", marketButtonClickAction, false);
524 document.getElementById("oreAverageButton").addEventListener("click", oreAverageButtonClickAction, false);
525 if (marketOn) {
526 document.getElementById("marketButton").innerHTML = "Ted's Market: ON";
527 } else document.getElementById("marketButton").innerHTML = "Ted's Market: OFF";
528 if (oreAverageOn) {
529 document.getElementById("oreAverageButton").innerHTML = "oreAverageText: ON";
530 } else document.getElementById("oreAverageButton").innerHTML = "oreAverageText: OFF";
531 }
532
533 function nextTick() {
534 if (playtime > tickCheck) {
535 tickCheck = playtime;
536 tickEnd = new Date().getTime();
537 tickTime = tickEnd - tickStart;
538 if (debugToConsole) {
539 console.log("Tick time: " + tickTime);
540 }
541 tickStart = new Date().getTime();
542 return true;
543 } else return false;
544 }
545
546 function isInArray(array, search) {
547 return array.indexOf(search) >= 0;
548 }
549
550 function getNumberValueImproved(number) {
551 let orig = number;
552 number = (number + "").toLowerCase().replace(/,/g, "");
553 if (number.includes("k")) {
554 number = number.substr(0, number.length - 1);
555 return parseInt(number * 1000);
556 } else if (number.includes("m")) {
557 number = number.substr(0, number.length - 1);
558 return parseInt(number * 1000000);
559 } else if (number.includes("b")) {
560 number = number.substr(0, number.length - 1);
561 return parseInt(number * 1000000000);
562 }
563 return orig;
564 }
565
566 window.numberWithCommas = function(x) { //string
567 if (x === null) return null;
568 if (typeof(x) == "undefined") return undefined;
569 x = getNumberValueImproved(x);
570 x = x.toString().replace(/,/g, "");
571 return x.replace(/\B(?=(\d{3})+(?!\d))/g, ",");
572 };
573
574 window.numberWithoutCommas = function(x) { //int
575 x = getNumberValueImproved(x);
576 return parseInt(x.toString().replace(/,/g, ""));
577 };
578
579 function abbreviate_number(num, fixed) {
580 if (num === null) {
581 return null;
582 } // terminate early
583 if (num === 0) {
584 return '0';
585 } // terminate early
586 fixed = (!fixed || fixed < 0) ? 0 : fixed; // number of decimal places to show
587 var b = (num).toPrecision(2).split("e"), // get power
588 k = b.length === 1 ? 0 : Math.floor(Math.min(b[1].slice(1), 14) / 3), // floor at decimals, ceiling at trillions
589 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
590 d = c < 0 ? c : Math.abs(c), // enforce -0 is 0
591 e = d + ['', 'k', 'M', 'B', 'T'][k]; // append power
592 return e;
593 }
594 window.openTradeHistory = function() {
595 if (tradeHistoryModalBody.style.display != "inline-block") {
596 sortTradeHistory("date");
597 }
598 tradeHistoryModalBody.style.display = "inline-block";
599 tradeHistoryModalBodyTable.innerHTML = thString;
600 document.getElementById("thSearch").focus();
601 if ($("#tradeHistoryModalBody").next().text() == " Browse"){
602 $("#tradeHistoryModalBody").after("<br/>");
603 }
604 };
605
606 function tedMarketUiSettings() {
607 var i, j;
608 var arrSettingsTH = ["tedMarket Configuration (may require refresh)", "Active"];
609 var zSettingsTable = document.createElement("table");
610 zSettingsTable.setAttribute("id", "marketSettingsTable");
611 zSettingsTable.setAttribute("style", "width:40%;margin-top:3%;margin-bottom:3%;");
612 zSettingsTable.setAttribute("class", "table-style1");
613 zSettingsTable.setAttribute("align", "center");
614 var zSettingsTBody = document.createElement("tbody");
615 zSettingsTBody.setAttribute("style", "border-color:black");
616 for (i = 0; i < 1; i++) {
617 var zSettingsTHRow = document.createElement("tr");
618 zSettingsTHRow.setAttribute("style", "background-color:grey;color:black;border-color:grey");
619 for (j = 0; j < 2; j++) {
620 var zSettingsTH = document.createElement("th");
621 var cellText = document.createTextNode(arrSettingsTH[j]);
622 zSettingsTH.appendChild(cellText);
623 zSettingsTHRow.appendChild(zSettingsTH);
624 }
625 zSettingsTBody.appendChild(zSettingsTHRow);
626 }
627 window.toggleAlwaysShowLowest = function() {
628 let isChecked = document.getElementsByClassName("ted-alwaysShowLowest-checkbox")[0].checked;
629 for (let i = 0; i < document.getElementsByClassName("ted-alwaysShowLowest-checkbox").length; i++) {
630 document.getElementsByClassName("ted-alwaysShowLowest-checkbox")[i].checked = !isChecked;
631 }
632 };
633 window.toggleShowAtMin = function() {
634 let isChecked = document.getElementsByClassName("ted-showAtMin-checkbox")[0].checked;
635 for (let i = 0; i < document.getElementsByClassName("ted-showAtMin-checkbox").length; i++) {
636 document.getElementsByClassName("ted-showAtMin-checkbox")[i].checked = !isChecked;
637 }
638 };
639 window.saveItemSettings = function() {
640 let showAtPrice = document.getElementsByClassName("ted-showAtPrice-input");
641 let alwaysShowLowest = document.getElementsByClassName("ted-alwaysShowLowest-checkbox");
642 let showAtMin = document.getElementsByClassName("ted-showAtMin-checkbox");
643 for (let i = 0; i < document.getElementsByClassName("ted-showAtPrice-input").length; i++) {
644 let itemName = showAtPrice[i].name;
645 let val = numberWithoutCommas(showAtPrice[i].value);
646 if (isNaN(val)) val = null;
647 if (tedStoredSettings.tedTradableItems.itemList[itemName]) {
648 tedStoredSettings.tedTradableItems.itemList[itemName].showAtPrice = val;
649 }
650 }
651 for (let i = 0; i < alwaysShowLowest.length; i++) {
652 let itemName = alwaysShowLowest[i].name;
653 let val = alwaysShowLowest[i].checked;
654 if (tedStoredSettings.tedTradableItems.itemList[itemName]) {
655 tedStoredSettings.tedTradableItems.itemList[itemName].alwaysShowLowest = val;
656 }
657 }
658 for (let i = 0; i < showAtMin.length; i++) {
659 let itemName = showAtMin[i].name;
660 let val = showAtMin[i].checked;
661 if (tedStoredSettings.tedTradableItems.itemList[itemName]) {
662 tedStoredSettings.tedTradableItems.itemList[itemName].showAtMin = val;
663 }
664 }
665 for (let i = 0; i < document.getElementsByClassName("ted-cheapest-stuff").length; i++) {
666 let val = numberWithoutCommas(document.getElementsByClassName("ted-cheapest-stuff")[i].value);
667 if (isNaN(val)) val = 999999;
668 //forgive me
669 if (document.getElementsByClassName("ted-cheapest-stuff")[i].id == "cheapest-Heat-showAtPrice") tedStoredSettings.showCheapestHeat.showAt = val;
670 if (document.getElementsByClassName("ted-cheapest-stuff")[i].id == "cheapest-Energy-showAtPrice") tedStoredSettings.showCheapestEnergy.showAt = val;
671 if (document.getElementsByClassName("ted-cheapest-stuff")[i].id == "cheapest-Bonemeal-showAtPrice") tedStoredSettings.showCheapestBonemeal.showAt = val;
672 }
673 updateVariables();
674 scrollText("none", "lime", "Saved");
675 };
676 window.changeSetting = function(prop) {
677 if (tedStoredSettings && tedStoredSettings[prop]) {
678 if (tedStoredSettings[prop].value === true) {
679 tedStoredSettings[prop].value = false;
680 document.getElementById("celltick-" + prop).setAttribute("src", "images/icons/x.png");
681 updateVariables();
682 } else if (tedStoredSettings[prop].value === false) {
683 tedStoredSettings[prop].value = true;
684 document.getElementById("celltick-" + prop).setAttribute("src", "images/icons/check.png");
685 updateVariables();
686 } else if (tedStoredSettings[prop].bgcolor) {
687 document.getElementById("celltick-" + prop).style.backgroundColor = tedStoredSettings[prop].bgcolor;
688 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);");
689 while (colorModalBody.firstChild) {
690 colorModalBody.removeChild(colorModalBody.firstChild);
691 }
692 var colorModalBodyContent = document.createElement("div");
693 colorModalBody.appendChild(colorModalBodyContent);
694 colorModalBodyContent.innerHTML = "";
695 KEYS.forEach((key) => {
696 if (tedStoredSettings[key].bgcolor) {
697 var colorModalInput = document.createElement("input");
698 colorModalInput.setAttribute("id", key);
699 colorModalInput.setAttribute("value", tedStoredSettings[key].bgcolor);
700 colorModalInput.setAttribute("style", "background-color:" + tedStoredSettings[key].bgcolor);
701 colorModalBodyContent.appendChild(colorModalInput);
702 var colorModalAddBtn = document.createElement("button");
703 colorModalAddBtn.setAttribute("onclick", "changeColor('" + key + "',document.getElementById('" + key + "').value);changeSetting('" + key + "')");
704 colorModalAddBtn.append("Change");
705 colorModalBodyContent.append(colorModalInput);
706 colorModalBodyContent.append(colorModalAddBtn);
707 colorModalBodyContent.append(tedStoredSettings[key].text);
708 // tedStoredSettings[key].text+" = "+colorModalInput+" = "+colorModalBtn
709 colorModalBodyContent.innerHTML += '<br><br>';
710 }
711 });
712 var colorResetBtn = document.createElement("button");
713 colorResetBtn.append("RESET COLORS");
714 colorResetBtn.setAttribute("onclick", "resetColors();changeSetting('colorMinPrice');");
715 colorModalBodyContent.append(colorResetBtn);
716 } else if (tedStoredSettings[prop].itemList) {
717 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;");
718 while (myItemListModalBody.firstChild) {
719 myItemListModalBody.removeChild(myItemListModalBody.firstChild);
720 }
721 var myItemListModalBodyNameInput = document.createElement("input");
722 myItemListModalBodyNameInput.setAttribute("id", "myItemListModalBodyNameInput");
723 if (typeof(myItemListAddName) == "undefined") myItemListAddName = "";
724 myItemListModalBodyNameInput.setAttribute("value", myItemListAddName);
725 myItemListModalBodyNameInput.setAttribute("placeholder", "Item Name");
726 myItemListModalBody.append(myItemListModalBodyNameInput);
727 var myItemListModalBodyPriceInput = document.createElement("input");
728 myItemListModalBodyPriceInput.setAttribute("id", "myItemListModalBodyPriceInput");
729 myItemListModalBodyPriceInput.setAttribute("onkeydown", "if (event.keyCode == 13) { document.getElementById('myItemListAddBtn').click(); }");
730 if (typeof(myItemListAddPrice) == "undefined") myItemListAddPrice = "";
731 myItemListModalBodyPriceInput.setAttribute("value", myItemListAddPrice);
732 myItemListModalBodyPriceInput.setAttribute("placeholder", "Show At Price");
733 myItemListModalBody.append(myItemListModalBodyPriceInput);
734 var myItemListAddBtn = document.createElement("button");
735 myItemListAddBtn.setAttribute("id", "myItemListAddBtn");
736 myItemListAddBtn.setAttribute("style", "cursor:pointer");
737 myItemListAddBtn.setAttribute("onclick", "myItemListAdd(myItemListModalBodyNameInput.value,myItemListModalBodyPriceInput.value);changeSetting('myItemList')");
738 myItemListAddBtn.append("Add");
739 myItemListModalBody.append(myItemListAddBtn);
740 myItemListModalBody.append(document.createElement("br"));
741 myItemListModalBody.append(document.createElement("br"));
742 var saveItemSettingsBtn = document.createElement("button");
743 saveItemSettingsBtn.setAttribute("id", "saveItemSettingsBtn");
744 saveItemSettingsBtn.setAttribute("style", "cursor:pointer;background-color:lightgreen");
745 saveItemSettingsBtn.setAttribute("onclick", "saveItemSettings();changeSetting('tedTradableItems')");
746 saveItemSettingsBtn.append("Save Item Settings (MUST PUSH AFTER CHANGING BELOW)");
747 myItemListModalBody.append(saveItemSettingsBtn);
748 myItemListModalBody.append(document.createElement("br"));
749 myItemListModalBody.append(document.createElement("br"));
750 var itemListModalBodyString = "";
751 var objCheapest = {
752 heat: {
753 name: "Heat",
754 showAt: tedStoredSettings.showCheapestHeat.showAt,
755 currentLow: cheapestHeat,
756 image: "images/icons/fire.png"
757 },
758 energy: {
759 name: "Energy",
760 showAt: tedStoredSettings.showCheapestEnergy.showAt,
761 currentLow: cheapestEnergy,
762 image: "images/steak.png"
763 },
764 bonemeal: {
765 name: "Bonemeal",
766 showAt: tedStoredSettings.showCheapestBonemeal.showAt,
767 currentLow: cheapestBonemeal,
768 image: "images/filledBonemealBin.png"
769 }
770 };
771 itemListModalBodyString += "<table style='border-spacing:20px 2px'><tbody><tr><th>Cheapest</th><th>Show At Price</th><th>Current Price</th></tr>";
772 Object.keys(objCheapest).forEach((key) => {
773 itemListModalBodyString += "<tr>";
774 itemListModalBodyString += "<td style='text-align:right'>" + objCheapest[key].name + "</td>";
775 var showAt = objCheapest[key].showAt;
776 if (showAt === null) showAt = "";
777 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>";
778 itemListModalBodyString += "<td style='text-align:right'>" + numberWithCommas(objCheapest[key].currentLow) + "</td>";
779 itemListModalBodyString += "</tr>";
780 });
781 itemListModalBodyString += "</tbody></table><br>";
782 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>";
783 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>";
784 var showAtPrice;
785 for (var itemName in tedStoredSettings.tedTradableItems.itemList) {
786 if (!isInArray(arrSortItemsList, getItemName(itemName))) {
787 showAtPrice = tedStoredSettings.tedTradableItems.itemList[itemName].showAtPrice;
788 if (showAtPrice === null) {
789 showAtPrice = "";
790 }
791 itemListModalBodyString += "<tr>";
792 itemListModalBodyString += "<td style='text-align:right'>" + getItemName(itemName) + "</td>";
793 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>";
794 itemListModalBodyString += "<td style='text-align:center'><input type='checkbox' name='" + itemName + "' class='ted-showAtMin-checkbox' style='width:16px;height:16px;cursor:pointer' /></td>";
795 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>";
796 itemListModalBodyString += "</tr>";
797 }
798 }
799 for (let i = 0; i < arrSortItemsList.length; i++) {
800 itemName = itemNameFix(arrSortItemsList[i]);
801 if (tedStoredSettings.tedTradableItems.itemList[itemName]) {
802 showAtPrice = tedStoredSettings.tedTradableItems.itemList[itemName].showAtPrice;
803 if (showAtPrice === null) {
804 showAtPrice = "";
805 }
806 itemListModalBodyString += "<tr>";
807 itemListModalBodyString += "<td style='text-align:right'>" + getItemName(itemName) + "</td><td>";
808 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>";
809 itemListModalBodyString += "<td style='text-align:center'><input type='checkbox' name='" + itemName + "' class='ted-showAtMin-checkbox' style='width:16px;height:16px;cursor:pointer' /></td>";
810 itemListModalBodyString += "<td style='text-align:center'><input type='checkbox' name='" + itemName + "' class='ted-alwaysShowLowest-checkbox' style='width:16px;height:16px;cursor:pointer' /></td>";
811 itemListModalBodyString += "</tr>";
812 }
813 }
814 itemListModalBodyString += "</tbody></table>";
815 myItemListModalBody.innerHTML += itemListModalBodyString;
816 for (let i = 0; i < document.getElementsByClassName("ted-alwaysShowLowest-checkbox").length; i++) {
817 let itemName = document.getElementsByClassName("ted-alwaysShowLowest-checkbox")[i].name;
818 document.getElementsByClassName("ted-alwaysShowLowest-checkbox")[i].checked = tedStoredSettings.tedTradableItems.itemList[itemName].alwaysShowLowest;
819 }
820 for (let i = 0; i < document.getElementsByClassName("ted-showAtMin-checkbox").length; i++) {
821 let itemName = document.getElementsByClassName("ted-showAtMin-checkbox")[i].name;
822 document.getElementsByClassName("ted-showAtMin-checkbox")[i].checked = tedStoredSettings.tedTradableItems.itemList[itemName].showAtMin;
823 }
824 for (let i = 0; i < document.getElementsByClassName("ted-showAtPrice-input").length; i++) {
825 let itemName = document.getElementsByClassName("ted-showAtPrice-input")[i].name;
826 if (document.getElementsByName(itemName)[0].value === "" && document.getElementsByName(itemName)[1].checked === false && document.getElementsByName(itemName)[2].checked === false) {
827 upToParentByTag(document.getElementById(itemName + "-showAtPrice"), "tr").style.backgroundColor = "#ff7878";
828 }
829 }
830 document.getElementById("myItemListModalBodyPriceInput").focus();
831 setTimeout(function() {
832 document.getElementById("myItemListModalBodyPriceInput").selectionStart = document.getElementById("myItemListModalBodyPriceInput").selectionEnd = 10000;
833 }, 0);
834 }
835 }
836 };
837 const KEYS = Object.keys(defaultSettings);
838 KEYS.forEach((key) => {
839 if (!tedStoredSettings[key].hideFromSettings && key !== "tradeHistory") {
840 var zSettingsRow = document.createElement("tr");
841 var zSettingsCell = document.createElement("td");
842 zSettingsCell.setAttribute("style", "text-align:left;padding:0px 5px;");
843 var cellText = document.createTextNode(tedStoredSettings[key].text);
844 if (key == "tedTradableItems") {
845 cellText = document.createTextNode("Click to open item settings menu");
846 }
847 var cellTick = document.createElement("div");
848 if (tedStoredSettings[key].value === true) {
849 cellTick = document.createElement("img");
850 cellTick.setAttribute("src", "images/icons/check.png");
851 cellTick.setAttribute("style", "width:20px;height:20px;vertical-align:bottom");
852 } else if (tedStoredSettings[key].value === false) {
853 cellTick = document.createElement("img");
854 cellTick.setAttribute("src", "images/icons/x.png");
855 cellTick.setAttribute("style", "width:20px;height:20px;vertical-align:bottom");
856 } else if (tedStoredSettings[key].bgcolor) {
857 cellTick.setAttribute("style", "display:block;background-color:" + tedStoredSettings[key].bgcolor);
858 cellTick.innerHTML = "+";
859 }
860 zSettingsRow.setAttribute("id", "checkbox-" + key);
861 zSettingsRow.setAttribute("onclick", "changeSetting('" + key + "')");
862 cellTick.setAttribute("id", "celltick-" + key);
863 zSettingsCell.appendChild(cellText);
864 zSettingsRow.appendChild(zSettingsCell);
865 zSettingsCell = document.createElement("td");
866 zSettingsCell.appendChild(cellTick);
867 zSettingsRow.appendChild(zSettingsCell);
868 zSettingsRow.setAttribute("align", "center");
869 zSettingsTBody.appendChild(zSettingsRow);
870 }
871 });
872 zSettingsTable.appendChild(zSettingsTBody);
873 document.getElementById("tab-container-profile").appendChild(zSettingsTable);
874 var hideItemListModal = document.createElement("div");
875 hideItemListModal.setAttribute("id", "hideItemListModal");
876 hideItemListModal.setAttribute("style", "display:none");
877 var hideItemListModalBody = document.createElement("div");
878 hideItemListModalBody.setAttribute("id", "hideItemListModalBody");
879 hideItemListModalBody.setAttribute("style", "background-color:#ffcc44;padding:1%;margin:2%;");
880 document.getElementById("game-div").append(hideItemListModal);
881 document.getElementById("hideItemListModal").append(hideItemListModalBody);
882 window.myItemListRemove = function(itemName) {
883 tedStoredSettings.tedTradableItems.itemList[itemName].showAtPrice = null;
884 updateVariables();
885 };
886 window.myItemListAdd = function(itemName, price) {
887 itemName = itemNameFix(itemName);
888 price = numberWithoutCommas(price);
889 if (!isNaN(price)) {
890 if (tedStoredSettings.tedTradableItems.itemList[itemName]) {
891 tedStoredSettings.tedTradableItems.itemList[itemName].showAtPrice = price;
892 document.getElementById(itemName + "-showAtPrice").value = numberWithCommas(price);
893 document.getElementById("myItemListModalBodyNameInput").value = "";
894 document.getElementById("myItemListModalBodyPriceInput").value = "";
895 updateVariables();
896 scrollText("none", "lime", "Added " + getItemName(itemName) + " @ " + price);
897 return;
898 }
899 }
900 scrollText("none", "red", "Failed to add " + getItemName(itemName) + " @ " + price);
901 };
902 var myItemListModal = document.createElement("div");
903 myItemListModal.setAttribute("id", "myItemListModal");
904 myItemListModal.setAttribute("style", "display:none");
905 var myItemListModalBody = document.createElement("div");
906 myItemListModalBody.setAttribute("id", "myItemListModalBody");
907 myItemListModalBody.setAttribute("style", "background-color:#ffcc44;padding:1%;margin:10%;overflow-y:scroll;min-height:200px;");
908 document.getElementById("game-div").append(myItemListModal);
909 document.getElementById("myItemListModal").append(myItemListModalBody);
910 window.changeColor = function(key, color) {
911 tedStoredSettings[key].bgcolor = color;
912 updateVariables();
913 };
914 window.resetColors = function() {
915 KEYS.forEach((key) => {
916 if (tedStoredSettings[key].bgcolor) {
917 tedStoredSettings[key].bgcolor = defaultSettings[key].bgcolor;
918 document.getElementById("celltick-" + key).style.backgroundColor = tedStoredSettings[key].bgcolor;
919 }
920 });
921 updateVariables();
922 };
923 var colorModal = document.createElement("div");
924 colorModal.setAttribute("id", "colorModal");
925 colorModal.setAttribute("style", "display:none");
926 var colorModalBody = document.createElement("div");
927 colorModalBody.setAttribute("id", "colorModalBody");
928 colorModalBody.setAttribute("style", "position:fixed;bottom:0;background-color:#fefefe;width:100%;padding:5%");
929 document.getElementById("game-div").append(colorModal);
930 document.getElementById("colorModal").append(colorModalBody);
931 window.onclick = function(event) {
932 if (event.target == hideItemListModal) {
933 hideItemListModal.style.display = "none";
934 }
935 if (event.target == myItemListModal) {
936 myItemListModal.style.display = "none";
937 }
938 if (event.target == colorModal) {
939 colorModal.style.display = "none";
940 }
941 };
942 }
943
944 function quickCalcMain() {
945 var i, a, b;
946 var arrQuickCalcHeat = ["Error, search for all (infinity symbol)", 999999, 0, 999999, 0, 0]; // name, heatprice, amount, logprice, heat, row
947 var arrLogs = [
948 ["Logs", 1],
949 ["Oak Logs", 2],
950 ["Willow Logs", 5],
951 ["Maple Logs", 10],
952 ["Stardust Logs", 20],
953 ["Strange Logs", 30]
954 ];
955 var arrQuickCalcEnergy = ["Error, search for all (infinity symbol)", 999999, 0, 999999, 0, 0]; // name, energyprice, amount, fishprice, energy, row
956 var arrEnergy = [
957 ["Shrimp", 50],
958 ["Sardine", 400],
959 ["Tuna", 1000],
960 ["Swordfish", 7500],
961 ["Shark", 20000]
962 ];
963 var arrQuickCalcBonemeal = ["Error, search for all (infinity symbol)", 999999, 0, 999999, 0, 0]; // name, bonemealprice, amount, boneprice, bonemeal, row
964 var arrBonemeal = [
965 ["Bones", 1],
966 ["Ashes", 2],
967 ["Ice Bones", 3]
968 ];
969 var hasBrewingKit;
970 var arrStargemInput = [
971 ["Blewit Mushroom", 100, 0, 0],
972 ["Gold Leaf", 1, 0, 0],
973 ["Sapphire", 1, 0, 0],
974 ["Emerald", 1, 0, 0],
975 ["Ruby", 1, 0, 0],
976 ["Diamond", 1, 0, 0],
977 ["Sand", 25, 0, 0],
978 ["Glass", 25, 0, 0]
979 ]; //name,amt need, amt have, ttl price
980 var arrStargemOutput = [
981 ["Stardust", 0]
982 ]; // name, price
983 var arrSmallVialInput = [
984 ["Glass", 5, 0, 0],
985 ["Sand", 5, 0, 0]
986 ]; //or
987 var arrSuperStardustInput = [
988 ["Lime Leaf", 5, 0, 0],
989 ["Snapegrass", 50, 0, 0]
990 ];
991 var arrSuperStardustOutput = [
992 ["Stardust", 0]
993 ];
994 var potionDurationModifier = 1 + (achBrewingEasyCompleted * 0.05);
995
996 var avgSdGainStardustPotion = Math.floor( ((0 + 40) * (1 + (achBrewingEasyCompleted * 0.05))) / 2);//per tick
997 var avgSdGainSuperStardustPotion = Math.floor( ((0 + 220) * (1 + (achBrewingEasyCompleted * 0.05))) / 2);// per tick
998
999 var stardustPotionDuration = Math.floor(300 * (1 + ((getLevel(brewingXp) / 100 * 0.2) * potionDurationModifier) ));
1000 var superStardustPotionDuration = Math.floor(300 * (1 + ((getLevel(brewingXp) / 100 * 0.2) * potionDurationModifier) ));
1001
1002 avgSdGainStardustPotion = avgSdGainStardustPotion * stardustPotionDuration;
1003 avgSdGainSuperStardustPotion = avgSdGainSuperStardustPotion * superStardustPotionDuration;
1004
1005
1006 var arrStardustInput = [
1007 ["Dotted Green Leaf", 1, 0, 0],
1008 ["Red Mushroom", 25, 0, 0]
1009 ];
1010 var arrStardustOutput = [
1011 ["Stardust", 0]
1012 ];
1013 var lowestVial, lowestVialSource, lowestSmallVial, lowestSmallVialSource;
1014 var stargemNetMinusOne, stargemNet, stargemNetPlusOne, totalPrice;
1015
1016 function calculateAndModifyHeatEnergy(array, array2) {
1017 var pricePerHeat;
1018 for (a = 0; a < array.length; a++) {
1019 let itemName = itemNameFix(array[a][0]);
1020 if (arrMarketItems[itemName]) {
1021 let itemPrice = arrMarketItems[itemName][0].price;
1022 let itemAmount = arrMarketItems[itemName][0].amount;
1023 let itemRow = arrMarketItems[itemName][0].row;
1024 if (typeof(pricePerHeat) == "undefined" || itemPrice / array[a][1] < pricePerHeat) {
1025 pricePerHeat = itemPrice / array[a][1];
1026 //if (pricePerHeat < array2[1]) {
1027 array2[0] = array[a][0];
1028 array2[1] = Math.ceil(itemPrice / array[a][1]);
1029 array2[2] = itemAmount;
1030 array2[3] = itemPrice;
1031 array2[4] = array[a][1];
1032 array2[5] = itemRow;
1033 }
1034 if (itemName == "stardustLogs") {
1035 if (arrMarketItems.stardust[0]) {
1036 let avgSdValue = ((2500 + 10000) / 2) * (arrMarketItems.stardust[0].price - 1);
1037 let sdLogHeatCost = Math.ceil((itemPrice - avgSdValue) / array[a][1]);
1038 if (sdLogHeatCost < array2[1]) {
1039 array2[0] = array[a][0];
1040 array2[1] = sdLogHeatCost;
1041 array2[2] = itemAmount;
1042 array2[3] = itemPrice;
1043 array2[4] = array[a][1];
1044 array2[5] = itemRow;
1045 }
1046 }
1047 }
1048 if (debugToConsole) {
1049 console.item(itemName, itemPrice / array[a][1], itemAmount);
1050 }
1051 if (debugToConsole) {
1052 console.item(array2[0], array2[1], array2[2]);
1053 }
1054 }
1055 }
1056 }
1057
1058 function calculateAndModifyInput(array) {
1059 for (a = 0; a < array.length; a++) {
1060 let itemName = itemNameFix(array[a][0]);
1061 if (arrMarketItems[itemName]) {
1062 for (b = 0; b < arrMarketItems[itemName].length; b++) {
1063 if (array[a][2] < array[a][1]) {
1064 if (arrMarketItems[itemName][b].amount < array[a][1] - array[a][2]) {
1065 array[a][2] += arrMarketItems[itemName][b].amount;
1066 array[a][3] += arrMarketItems[itemName][b].price * arrMarketItems[itemName][b].amount;
1067 } else if (arrMarketItems[itemName][b].amount >= array[a][1] - array[a][2]) {
1068 array[a][3] += (array[a][1] - array[a][2]) * arrMarketItems[itemName][b].price;
1069 array[a][2] = array[a][1];
1070 }
1071 if (debugToConsole) {
1072 console.log(array[a][0], array[a][1], array[a][2], array[a][3]);
1073 }
1074 }
1075 }
1076 }
1077 }
1078 }
1079
1080 function calculateAndModifyOutput(array) {
1081 for (a = 0; a < array.length; a++) {
1082 let output = itemNameFix(array[a][0]);
1083 if (arrMarketItems[output]) {
1084 array[a][1] = arrMarketItems[output][0].price;
1085 break;
1086 }
1087 }
1088 }
1089 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) {
1090 //heat
1091 calculateAndModifyHeatEnergy(arrLogs, arrQuickCalcHeat);
1092 //energy
1093 calculateAndModifyHeatEnergy(arrEnergy, arrQuickCalcEnergy);
1094 //bonemeal
1095 calculateAndModifyHeatEnergy(arrBonemeal, arrQuickCalcBonemeal);
1096 //small vial
1097 calculateAndModifyInput(arrSmallVialInput);
1098 //stardust
1099 calculateAndModifyInput(arrStardustInput);
1100 calculateAndModifyOutput(arrStardustOutput);
1101 //super stardust
1102 calculateAndModifyInput(arrSuperStardustInput);
1103 calculateAndModifyOutput(arrSuperStardustOutput);
1104 //stargem
1105 calculateAndModifyInput(arrStargemInput);
1106 calculateAndModifyOutput(arrStargemOutput);
1107 //stargem
1108
1109 //stargem
1110
1111 //small vial stuff
1112 if (arrSmallVialInput[0][2] == arrSmallVialInput[0][1] && arrSmallVialInput[1][2] == arrSmallVialInput[1][1]) { // enough both
1113 if (arrSmallVialInput[1][3] <= arrSmallVialInput[0][3]) {
1114 lowestSmallVial = arrSmallVialInput[1][3];
1115 lowestSmallVialSource = arrSmallVialInput[1][0];
1116 } else if (arrSmallVialInput[0][3] < arrSmallVialInput[1][3]) {
1117 lowestSmallVial = arrSmallVialInput[0][3];
1118 lowestSmallVialSource = arrSmallVialInput[0][0];
1119 }
1120 } else if (arrSmallVialInput[0][2] == arrSmallVialInput[0][1] && arrSmallVialInput[1][2] != arrSmallVialInput[1][1]) { // glass only
1121 lowestSmallVial = arrSmallVialInput[0][3];
1122 lowestSmallVialSource = arrSmallVialInput[0][0];
1123 } else if (arrSmallVialInput[0][2] != arrSmallVialInput[0][1] && arrSmallVialInput[1][2] == arrSmallVialInput[1][1]) { // sand only
1124 lowestSmallVial = arrSmallVialInput[1][3];
1125 lowestSmallVialSource = arrSmallVialInput[1][0];
1126 } else if (arrSmallVialInput[0][2] != arrSmallVialInput[0][1] && arrSmallVialInput[1][2] != arrSmallVialInput[1][1]) { // not enough both
1127 lowestSmallVial = 0;
1128 lowestSmallVialSource = "<span style='color:red;background-color:black;'>ERR: Sand & Glass < 5</span>";
1129 }
1130
1131 //stardust tooltip hover
1132 var dottedGreenLeafPrice = arrStardustInput[0][3];
1133 var redMushroomPrice = arrStardustInput[1][3];
1134 var lowestSmallVialPrice = lowestSmallVial;
1135 if (boundBrewingKit == 1) {
1136 hasBrewingKit = true;
1137 for (i = 0; i < 2; i++) {
1138 arrStardustInput[i][3] = Math.ceil(arrStardustInput[i][3] / 1.1); // brewing kit 10% free ingredients
1139 }
1140 lowestSmallVialPrice = Math.ceil(lowestSmallVialPrice / 1.1); // brewing kit 10% free vial
1141 } else hasBrewingKit = false;
1142 quickCalcStardustString = "";
1143 quickCalcStardustBoxShadow = false;
1144 if (arrStardustInput[0][1] == arrStardustInput[0][2] && arrStardustInput[1][1] == arrStardustInput[1][2]) {
1145 quickCalcStardustString += "<span style='float:left;padding:5px;'>Stardust Profit</span>";
1146 if (hasBrewingKit) {
1147 quickCalcStardustString += "<span style='float:right;padding:5px;color:green;'>+Brewing Kit</span>";
1148 } else quickCalcStardustString += "<span style='float:right;padding:5px;color:black;'><s style='color:red'>Brewing Kit</s></span>";
1149 quickCalcStardustString += "<br>";
1150 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>";
1151 stargemNetMinusOne = abbreviate_number(((arrStargemOutput[0][1] - 1) * avgSdGainStardustPotion) - (arrStardustInput[0][3] + arrStardustInput[1][3] + lowestSmallVialPrice), 1);
1152 stargemNet = abbreviate_number(((arrStargemOutput[0][1]) * avgSdGainStardustPotion) - (arrStardustInput[0][3] + arrStardustInput[1][3] + lowestSmallVialPrice), 1);
1153 stargemNetPlusOne = abbreviate_number(((arrStargemOutput[0][1] + 1) * avgSdGainStardustPotion) - (arrStardustInput[0][3] + arrStardustInput[1][3] + lowestSmallVialPrice), 1);
1154 quickCalcStardustString += "<tr>";
1155 quickCalcStardustString += "<td style='text-align:center'><img class='image-icon-20' src='images/stardustPotion.png'></td>";
1156 totalPrice = (arrStardustInput[0][3] + arrStardustInput[1][3] + lowestSmallVialPrice);
1157 quickCalcStardustString += "<td>" + abbreviate_number(totalPrice, 2) + "</td>";
1158 if (abbreviate_number(totalPrice, 1) === 0) {
1159 quickCalcStardustString += "<td></td>";
1160 } else if (stargemNetMinusOne.indexOf("-") >= 0) {
1161 quickCalcStardustString += "<td style='color:red'>" + stargemNetMinusOne + "</td>";
1162 } else {
1163 quickCalcStardustString += "<td style='color:lightgreen'>" + stargemNetMinusOne + "</td>";
1164 quickCalcStardustBoxShadow = true;
1165 }
1166 if (abbreviate_number(totalPrice, 1) === 0) {
1167 quickCalcStardustString += "<td></td>";
1168 } else if (stargemNet.indexOf("-") >= 0) {
1169 quickCalcStardustString += "<td style='color:red'>" + stargemNet + "</td>";
1170 } else {
1171 quickCalcStardustString += "<td style='color:lightgreen'>" + stargemNet + "</td>";
1172 quickCalcStardustBoxShadow = true;
1173 }
1174 if (abbreviate_number(totalPrice, 1) === 0) {
1175 quickCalcStardustString += "<td></td>";
1176 } else if (stargemNetPlusOne.indexOf("-") >= 0) {
1177 quickCalcStardustString += "<td style='color:red'>" + stargemNetPlusOne + "</td>";
1178 } else {
1179 quickCalcStardustString += "<td style='color:lightgreen'>" + stargemNetPlusOne + "</td>";
1180 }
1181 quickCalcStardustString += "</tr>";
1182 stargemNetMinusOne = abbreviate_number(24 * 12 * (((arrStargemOutput[0][1] - 1) * avgSdGainStardustPotion) - (arrStardustInput[0][3] + arrStardustInput[1][3] + lowestSmallVialPrice)), 1);
1183 stargemNet = abbreviate_number(24 * 12 * (((arrStargemOutput[0][1]) * avgSdGainStardustPotion) - (arrStardustInput[0][3] + arrStardustInput[1][3] + lowestSmallVialPrice)), 1);
1184 stargemNetPlusOne = abbreviate_number(24 * 12 * (((arrStargemOutput[0][1] + 1) * avgSdGainStardustPotion) - (arrStardustInput[0][3] + arrStardustInput[1][3] + lowestSmallVialPrice)), 1);
1185 quickCalcStardustString += "<tr>";
1186 quickCalcStardustString += "<td style='text-align:center;color:gold;'>24h</td>";
1187 totalPrice = 24 * 12 * (arrStardustInput[0][3] + arrStardustInput[1][3] + lowestSmallVialPrice);
1188 quickCalcStardustString += "<td>" + abbreviate_number(totalPrice, 1) + "</td>";
1189 if (abbreviate_number(totalPrice, 1) === 0) {
1190 quickCalcStardustString += "<td></td>";
1191 } else if (stargemNetMinusOne.indexOf("-") >= 0) {
1192 quickCalcStardustString += "<td style='color:red'>" + stargemNetMinusOne + "</td>";
1193 } else {
1194 quickCalcStardustString += "<td style='color:lightgreen'>" + stargemNetMinusOne + "</td>";
1195 quickCalcStardustBoxShadow = true;
1196 }
1197 if (abbreviate_number(totalPrice, 1) === 0) {
1198 quickCalcStardustString += "<td></td>";
1199 } else if (stargemNet.indexOf("-") >= 0) {
1200 quickCalcStardustString += "<td style='color:red'>" + stargemNet + "</td>";
1201 } else {
1202 quickCalcStardustString += "<td style='color:lightgreen'>" + stargemNet + "</td>";
1203 quickCalcStardustBoxShadow = true;
1204 }
1205 if (abbreviate_number(totalPrice, 1) === 0) {
1206 quickCalcStardustString += "<td></td>";
1207 } else if (stargemNetPlusOne.indexOf("-") >= 0) {
1208 quickCalcStardustString += "<td style='color:red'>" + stargemNetPlusOne + "</td>";
1209 } else {
1210 quickCalcStardustString += "<td style='color:lightgreen'>" + stargemNetPlusOne + "</td>";
1211 }
1212 quickCalcStardustString += "</tr>";
1213 quickCalcStardustString += "</tbody></table>";
1214 quickCalcStardustString += arrStardustInput[0][0] + ": " + abbreviate_number(dottedGreenLeafPrice, 0) + "<br>";
1215 quickCalcStardustString += arrStardustInput[1][0] + ": " + abbreviate_number(redMushroomPrice, 0) + "<br>";
1216 quickCalcStardustString += lowestSmallVialSource + ": " + abbreviate_number(lowestSmallVial, 0) + "<br><br>";
1217 quickCalcStardustString += "Avg SD: " + numberWithCommas(avgSdGainStardustPotion) + "<br>";
1218 var stardustPotionDurationDate = new Date(null);
1219 stardustPotionDurationDate.setSeconds(stardustPotionDuration);
1220 var stardustPotionDurationDateFormatted = stardustPotionDurationDate.toISOString().substr(14, 5);
1221 quickCalcStardustString += "Potion Duration: " + stardustPotionDurationDateFormatted;
1222 }
1223 if (arrStardustInput[0][1] != arrStardustInput[0][2]) quickCalcStardustString += "Not enough " + arrStardustInput[0][0] + " " + arrStardustInput[0][2] + "/" + arrStardustInput[0][1] + "<br>";
1224 if (arrStardustInput[1][1] != arrStardustInput[1][2]) quickCalcStardustString += "Not enough " + arrStardustInput[1][0] + " " + arrStardustInput[1][2] + "/" + arrStardustInput[1][1] + "<br>";
1225 //super stardust tooltip hover
1226 var limeLeafPrice = arrSuperStardustInput[0][3];
1227 var snapegrassPrice = arrSuperStardustInput[1][3];
1228 lowestSmallVialPrice = lowestSmallVial;
1229 if (boundBrewingKit == 1) {
1230 hasBrewingKit = true;
1231 for (i = 0; i < 2; i++) {
1232 arrSuperStardustInput[i][3] = Math.ceil(arrSuperStardustInput[i][3] / 1.1); // brewing kit 10% free ingredients
1233 }
1234 lowestSmallVialPrice = Math.ceil(lowestSmallVialPrice / 1.1); // brewing kit 10% free vial
1235 } else hasBrewingKit = false;
1236 quickCalcSuperStardustString = "";
1237 quickCalcSuperStardustBoxShadow = false;
1238 if (arrSuperStardustInput[0][1] == arrSuperStardustInput[0][2] && arrSuperStardustInput[1][1] == arrSuperStardustInput[1][2]) {
1239 quickCalcSuperStardustString += "<span style='float:left;padding:5px;'>S Stardust Profit</span>";
1240 if (hasBrewingKit) {
1241 quickCalcSuperStardustString += "<span style='float:right;padding:5px;color:green;'>+Brewing Kit</span>";
1242 } else quickCalcSuperStardustString += "<span style='float:right;padding:5px;color:black;'><s style='color:red'>Brewing Kit</s></span>";
1243 quickCalcSuperStardustString += "<br>";
1244 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>";
1245 stargemNetMinusOne = abbreviate_number(((arrStargemOutput[0][1] - 1) * avgSdGainSuperStardustPotion) - (arrSuperStardustInput[0][3] + arrSuperStardustInput[1][3] + lowestSmallVialPrice), 1);
1246 stargemNet = abbreviate_number(((arrStargemOutput[0][1]) * avgSdGainSuperStardustPotion) - (arrSuperStardustInput[0][3] + arrSuperStardustInput[1][3] + lowestSmallVialPrice), 1);
1247 stargemNetPlusOne = abbreviate_number(((arrStargemOutput[0][1] + 1) * avgSdGainSuperStardustPotion) - (arrSuperStardustInput[0][3] + arrSuperStardustInput[1][3] + lowestSmallVialPrice), 1);
1248 quickCalcSuperStardustString += "<tr>";
1249 quickCalcSuperStardustString += "<td style='text-align:center'><img class='image-icon-20' src='images/superStardustPotion.png'></td>";
1250 totalPrice = (arrSuperStardustInput[0][3] + arrSuperStardustInput[1][3] + lowestSmallVialPrice);
1251 quickCalcSuperStardustString += "<td>" + abbreviate_number(totalPrice, 2) + "</td>";
1252 if (abbreviate_number(totalPrice, 1) === 0) {
1253 quickCalcSuperStardustString += "<td></td>";
1254 } else if (stargemNetMinusOne.indexOf("-") >= 0) {
1255 quickCalcSuperStardustString += "<td style='color:red'>" + stargemNetMinusOne + "</td>";
1256 } else {
1257 quickCalcSuperStardustString += "<td style='color:lightgreen'>" + stargemNetMinusOne + "</td>";
1258 quickCalcSuperStardustBoxShadow = true;
1259 }
1260 if (abbreviate_number(totalPrice, 1) === 0) {
1261 quickCalcSuperStardustString += "<td></td>";
1262 } else if (stargemNet.indexOf("-") >= 0) {
1263 quickCalcSuperStardustString += "<td style='color:red'>" + stargemNet + "</td>";
1264 } else {
1265 quickCalcSuperStardustString += "<td style='color:lightgreen'>" + stargemNet + "</td>";
1266 quickCalcSuperStardustBoxShadow = true;
1267 }
1268 if (abbreviate_number(totalPrice, 1) === 0) {
1269 quickCalcSuperStardustString += "<td></td>";
1270 } else if (stargemNetPlusOne.indexOf("-") >= 0) {
1271 quickCalcSuperStardustString += "<td style='color:red'>" + stargemNetPlusOne + "</td>";
1272 } else {
1273 quickCalcSuperStardustString += "<td style='color:lightgreen'>" + stargemNetPlusOne + "</td>";
1274 }
1275 quickCalcSuperStardustString += "</tr>";
1276 stargemNetMinusOne = abbreviate_number(24 * 12 * (((arrStargemOutput[0][1] - 1) * avgSdGainSuperStardustPotion) - (arrSuperStardustInput[0][3] + arrSuperStardustInput[1][3] + lowestSmallVialPrice)), 0);
1277 stargemNet = abbreviate_number(24 * 12 * (((arrStargemOutput[0][1]) * avgSdGainSuperStardustPotion) - (arrSuperStardustInput[0][3] + arrSuperStardustInput[1][3] + lowestSmallVialPrice)), 0);
1278 stargemNetPlusOne = abbreviate_number(24 * 12 * (((arrStargemOutput[0][1] + 1) * avgSdGainSuperStardustPotion) - (arrSuperStardustInput[0][3] + arrSuperStardustInput[1][3] + lowestSmallVialPrice)), 0);
1279 quickCalcSuperStardustString += "<tr>";
1280 quickCalcSuperStardustString += "<td style='text-align:center;color:gold;'>24h</td>";
1281 totalPrice = 24 * 12 * (arrSuperStardustInput[0][3] + arrSuperStardustInput[1][3] + lowestSmallVialPrice);
1282 quickCalcSuperStardustString += "<td>" + abbreviate_number(totalPrice, 0) + "</td>";
1283 if (abbreviate_number(totalPrice, 1) === 0) {
1284 quickCalcSuperStardustString += "<td></td>";
1285 } else if (stargemNetMinusOne.indexOf("-") >= 0) {
1286 quickCalcSuperStardustString += "<td style='color:red'>" + stargemNetMinusOne + "</td>";
1287 } else {
1288 quickCalcSuperStardustString += "<td style='color:lightgreen'>" + stargemNetMinusOne + "</td>";
1289 quickCalcSuperStardustBoxShadow = true;
1290 }
1291 if (abbreviate_number(totalPrice, 1) === 0) {
1292 quickCalcSuperStardustString += "<td></td>";
1293 } else if (stargemNet.indexOf("-") >= 0) {
1294 quickCalcSuperStardustString += "<td style='color:red'>" + stargemNet + "</td>";
1295 } else {
1296 quickCalcSuperStardustString += "<td style='color:lightgreen'>" + stargemNet + "</td>";
1297 quickCalcSuperStardustBoxShadow = true;
1298 }
1299 if (abbreviate_number(totalPrice, 1) === 0) {
1300 quickCalcSuperStardustString += "<td></td>";
1301 } else if (stargemNetPlusOne.indexOf("-") >= 0) {
1302 quickCalcSuperStardustString += "<td style='color:red'>" + stargemNetPlusOne + "</td>";
1303 } else {
1304 quickCalcSuperStardustString += "<td style='color:lightgreen'>" + stargemNetPlusOne + "</td>";
1305 }
1306 quickCalcSuperStardustString += "</tr>";
1307 quickCalcSuperStardustString += "</tbody></table>";
1308 quickCalcSuperStardustString += arrSuperStardustInput[0][0] + ": " + abbreviate_number(limeLeafPrice, 0) + "<br>";
1309 quickCalcSuperStardustString += arrSuperStardustInput[1][0] + ": " + abbreviate_number(snapegrassPrice, 0) + "<br>";
1310 quickCalcSuperStardustString += lowestSmallVialSource + ": " + abbreviate_number(lowestSmallVial, 0) + "<br><br>";
1311 quickCalcSuperStardustString += "Avg SD: " + numberWithCommas(avgSdGainSuperStardustPotion) + "<br>";
1312 var superStardustPotionDurationDate = new Date(null);
1313 superStardustPotionDurationDate.setSeconds(superStardustPotionDuration);
1314 var superStardustPotionDurationDateFormatted = superStardustPotionDurationDate.toISOString().substr(14, 5);
1315 quickCalcSuperStardustString += "Potion Duration: " + superStardustPotionDurationDateFormatted;
1316 }
1317 if (arrSuperStardustInput[0][1] != arrSuperStardustInput[0][2]) quickCalcSuperStardustString += "Not enough " + arrSuperStardustInput[0][0] + " " + arrSuperStardustInput[0][2] + "/" + arrSuperStardustInput[0][1] + "<br>";
1318 if (arrSuperStardustInput[1][1] != arrSuperStardustInput[1][2]) quickCalcSuperStardustString += "Not enough " + arrSuperStardustInput[1][0] + " " + arrSuperStardustInput[1][2] + "/" + arrSuperStardustInput[1][1] + "<br>";
1319 //stargem tooltip hover
1320 if (arrStargemInput[6][2] == arrStargemInput[6][1] && arrStargemInput[7][2] == arrStargemInput[7][1]) { // enough both
1321 if (arrStargemInput[7][3] <= arrStargemInput[6][3]) {
1322 lowestVial = arrStargemInput[7][3];
1323 lowestVialSource = arrStargemInput[7][0];
1324 } else if (arrStargemInput[6][3] < arrStargemInput[7][3]) {
1325 lowestVial = arrStargemInput[6][3];
1326 lowestVialSource = arrStargemInput[6][0];
1327 }
1328 } else if (arrStargemInput[6][2] == arrStargemInput[6][1] && arrStargemInput[7][2] != arrStargemInput[7][1]) { // sand only
1329 lowestVial = arrStargemInput[6][3];
1330 lowestVialSource = arrStargemInput[6][0];
1331 } else if (arrStargemInput[6][2] != arrStargemInput[6][1] && arrStargemInput[7][2] == arrStargemInput[7][1]) { // glass only
1332 lowestVial = arrStargemInput[7][3];
1333 lowestVialSource = arrStargemInput[7][0];
1334 } else if (arrStargemInput[6][2] != arrStargemInput[6][1] && arrStargemInput[7][2] != arrStargemInput[7][1]) { // not enough both
1335 lowestVial = 0;
1336 lowestVialSource = "<span style='color:red;background-color:black;'>ERR: Sand & Glass < 25</span>";
1337 }
1338 var blewitMushroomPrice = arrStargemInput[0][3];
1339 var goldLeafPrice = arrStargemInput[1][3];
1340 var lowestVialPrice = lowestVial;
1341 if (boundBrewingKit == 1) {
1342 hasBrewingKit = true;
1343 for (i = 0; i < 2; i++) {
1344 arrStargemInput[i][3] = Math.ceil(arrStargemInput[i][3] / 1.1); // brewing kit 10% free ingredients
1345 }
1346 lowestVialPrice = Math.ceil(lowestVialPrice / 1.1); // brewing kit 10% free vial
1347 } else hasBrewingKit = false;
1348 quickCalcStargemString = "";
1349 quickCalcStargemBoxShadow = false;
1350 if (arrStargemInput[0][1] == arrStargemInput[0][2] && arrStargemInput[1][1] == arrStargemInput[1][2]) {
1351 quickCalcStargemString += "<span style='float:left;padding:5px;'>Stargem Profit</span>";
1352 if (hasBrewingKit) {
1353 quickCalcStargemString += "<span style='float:right;padding:5px;color:green;'>+Brewing Kit</span>";
1354 } else quickCalcStargemString += "<span style='float:right;padding:5px;color:black;'><s style='color:red'>Brewing Kit</s></span>";
1355 quickCalcStargemString += "<br>";
1356 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>";
1357 for (a = 2; a < arrStargemInput.length - 2; a++) {
1358 if (a == 5) {
1359 stargemNetMinusOne = abbreviate_number(((arrStargemOutput[0][1] - 1) * (a * 120000)) - (arrStargemInput[a][3] + arrStargemInput[0][3] + arrStargemInput[1][3] + lowestVialPrice), 1);
1360 stargemNet = abbreviate_number(((arrStargemOutput[0][1]) * (a * 120000)) - (arrStargemInput[a][3] + arrStargemInput[0][3] + arrStargemInput[1][3] + lowestVialPrice), 1);
1361 stargemNetPlusOne = abbreviate_number(((arrStargemOutput[0][1] + 1) * (a * 120000)) - (arrStargemInput[a][3] + arrStargemInput[0][3] + arrStargemInput[1][3] + lowestVialPrice), 1);
1362 } else {
1363 stargemNetMinusOne = abbreviate_number(((arrStargemOutput[0][1] - 1) * ((a - 1) * 100000)) - (arrStargemInput[a][3] + arrStargemInput[0][3] + arrStargemInput[1][3] + lowestVialPrice), 1);
1364 stargemNet = abbreviate_number((arrStargemOutput[0][1] * ((a - 1) * 100000)) - (arrStargemInput[a][3] + arrStargemInput[0][3] + arrStargemInput[1][3] + lowestVialPrice), 1);
1365 stargemNetPlusOne = abbreviate_number(((arrStargemOutput[0][1] + 1) * ((a - 1) * 100000)) - (arrStargemInput[a][3] + arrStargemInput[0][3] + arrStargemInput[1][3] + lowestVialPrice), 1);
1366 }
1367 quickCalcStargemString += "<tr>";
1368 quickCalcStargemString += "<td style='text-align:center'><img class='image-icon-20' src='images/" + itemNameFix(arrStargemInput[a][0]) + ".png'></td>";
1369 if (arrStargemInput[a][2] === 0) {
1370 quickCalcStargemString += "<td></td><td></td><td></td><td></td>";
1371 } else {
1372 quickCalcStargemString += "<td>" + abbreviate_number(arrStargemInput[a][3], 2) + "</td>";
1373 if (abbreviate_number(arrStargemInput[a][3], 1) === 0) {
1374 quickCalcStargemString += "<td></td>";
1375 } else if (stargemNetMinusOne.indexOf("-") >= 0) {
1376 quickCalcStargemString += "<td style='color:red'>" + stargemNetMinusOne + "</td>";
1377 } else {
1378 quickCalcStargemString += "<td style='color:lightgreen'>" + stargemNetMinusOne + "</td>";
1379 quickCalcStargemBoxShadow = true;
1380 }
1381 if (abbreviate_number(arrStargemInput[a][3], 1) === 0) {
1382 quickCalcStargemString += "<td></td>";
1383 } else if (stargemNet.indexOf("-") >= 0) {
1384 quickCalcStargemString += "<td style='color:red'>" + stargemNet + "</td>";
1385 } else {
1386 quickCalcStargemString += "<td style='color:lightgreen'>" + stargemNet + "</td>";
1387 quickCalcStargemBoxShadow = true;
1388 }
1389 if (abbreviate_number(arrStargemInput[a][3], 1) === 0) {
1390 quickCalcStargemString += "<td></td>";
1391 } else if (stargemNetPlusOne.indexOf("-") >= 0) {
1392 quickCalcStargemString += "<td style='color:red'>" + stargemNetPlusOne + "</td>";
1393 } else {
1394 quickCalcStargemString += "<td style='color:lightgreen'>" + stargemNetPlusOne + "</td>";
1395 }
1396 }
1397 quickCalcStargemString += "</tr>";
1398 }
1399 quickCalcStargemString += "</tbody></table>";
1400 quickCalcStargemString += arrStargemInput[0][0] + ": " + abbreviate_number(blewitMushroomPrice, 0) + "<br>";
1401 quickCalcStargemString += arrStargemInput[1][0] + ": " + abbreviate_number(goldLeafPrice, 0) + "<br>";
1402 quickCalcStargemString += lowestVialSource + ": " + abbreviate_number(lowestVial, 0) + "<br>";
1403 }
1404 if (arrStargemInput[0][1] != arrStargemInput[0][2]) quickCalcStargemString += "Not enough " + arrStargemInput[0][0] + " " + arrStargemInput[0][2] + "/" + arrStargemInput[0][1] + "<br>";
1405 if (arrStargemInput[1][1] != arrStargemInput[1][2]) quickCalcStargemString += "Not enough " + arrStargemInput[1][0] + " " + arrStargemInput[1][2] + "/" + arrStargemInput[1][1] + "<br>";
1406 //essence tooltip hover
1407
1408 /*
1409 if (arrEssenceInput[0][1] == arrEssenceInput[0][2] && arrEssenceInput[1][1] == arrEssenceInput[1][2]) {
1410 quickCalcEssenceString += "<span style='float:left;padding:5px;'>Essence Profit</span>";
1411 if (hasBrewingKit) {
1412 quickCalcEssenceString += "<span style='float:right;padding:5px;color:green;'>+Brewing Kit</span>";
1413 } else quickCalcEssenceString += "<span style='float:right;padding:5px;color:black;'><s style='color:red'>Brewing Kit</s></span>";
1414 quickCalcEssenceString += "<br>";
1415 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>";
1416 quickCalcEssenceString += "<tr>";
1417 quickCalcEssenceString += "<td style='text-align:center'><img class='image-icon-20' src='images/essencePotion.png'></td>";
1418 totalPrice = (arrEssenceInput[0][3] + arrEssenceInput[1][3] + lowestSmallVialPrice);
1419 var essenceProfit = essencePotionAvgEssence * 1;
1420 quickCalcEssenceString += "<td>" + abbreviate_number(totalPrice, 2) + "</td>";
1421 if (abbreviate_number(totalPrice, 1) === 0) {
1422 quickCalcEssenceString += "<td></td>";
1423 } else if (abbreviate_number(essenceProfit).indexOf("-") >= 0) {
1424 quickCalcEssenceString += "<td style='color:red'>" + Number(essencePotionAvgEssence.toFixed(2)) + "</td>";
1425 } else {
1426 quickCalcEssenceString += "<td style='color:lightgreen'>" + Number(essencePotionAvgEssence.toFixed(2)) + "</td>";
1427 quickCalcEssenceBoxShadow = true;
1428 }
1429 if (abbreviate_number(totalPrice, 1) === 0) {
1430 quickCalcEssenceString += "<td></td>";
1431 } else if (abbreviate_number(essenceProfit).indexOf("-") >= 0) {
1432 quickCalcEssenceString += "<td style='color:red'>" + abbreviate_number(Number(essenceProfit.toFixed(2)), 2) + "</td>";
1433 } else {
1434 quickCalcEssenceString += "<td style='color:lightgreen'>" + abbreviate_number(Number(essenceProfit.toFixed(2)), 2) + "</td>";
1435 quickCalcEssenceBoxShadow = true;
1436 }
1437 quickCalcEssenceString += "<tr>";
1438 quickCalcEssenceString += "<td style='text-align:center;color:gold;'>24h</td>";
1439 totalPrice = (24 * 60 * 60 / essencePotionDuration) * (arrEssenceInput[0][3] + arrEssenceInput[1][3] + lowestSmallVialPrice);
1440 var essenceProfit24 = (24 * 60 * 60 / essencePotionDuration) * essencePotionAvgEssence * 1;
1441 quickCalcEssenceString += "<td>" + abbreviate_number(totalPrice, 2) + "</td>";
1442 if (abbreviate_number(totalPrice, 1) === 0) {
1443 quickCalcEssenceString += "<td></td>";
1444 } else if (abbreviate_number(essenceProfit).indexOf("-") >= 0) {
1445 quickCalcEssenceString += "<td style='color:red'>" + Number(((24 * 60 * 60 / essencePotionDuration) * essencePotionAvgEssence).toFixed(2)) + "</td>";
1446 } else {
1447 quickCalcEssenceString += "<td style='color:lightgreen'>" + Number(((24 * 60 * 60 / essencePotionDuration) * essencePotionAvgEssence).toFixed(2)) + "</td>";
1448 quickCalcEssenceBoxShadow = true;
1449 }
1450 if (abbreviate_number(totalPrice, 1) === 0) {
1451 quickCalcEssenceString += "<td></td>";
1452 } else if (abbreviate_number(essenceProfit).indexOf("-") >= 0) {
1453 quickCalcEssenceString += "<td style='color:red'>" + abbreviate_number(Number(essenceProfit24.toFixed(0)), 1) + "</td>"; //avg proft
1454 } else {
1455 quickCalcEssenceString += "<td style='color:lightgreen'>" + abbreviate_number(Number(essenceProfit24.toFixed(0)), 1) + "</td>";
1456 quickCalcEssenceBoxShadow = true;
1457 }
1458 quickCalcEssenceString += "</tr>";
1459 quickCalcEssenceString += "</tbody></table>";
1460 dottedGreenLeafPrice = arrEssenceInput[0][3];
1461 blewitMushroomPrice = arrEssenceInput[1][3];
1462 quickCalcEssenceString += arrEssenceInput[0][0] + ": " + abbreviate_number(dottedGreenLeafPrice, 0) + "<br>";
1463 quickCalcEssenceString += arrEssenceInput[1][0] + ": " + abbreviate_number(blewitMushroomPrice, 0) + "<br>";
1464 quickCalcEssenceString += lowestSmallVialSource + ": " + abbreviate_number(lowestSmallVial, 0) + "<br>";
1465 quickCalcEssenceString += "<br>";
1466 quickCalcEssenceString += "Ess Chance: 1/" + numberWithCommas(essencePotionEssenceChance) + "/tick<br>";
1467 var essencePotionDurationDate = new Date(null);
1468 essencePotionDurationDate.setSeconds(essencePotionDuration);
1469 var essencePotionDurationFormatted = essencePotionDurationDate.toISOString().substr(11, 8);
1470 quickCalcEssenceString += "Potion Duration: " + essencePotionDurationFormatted;
1471 }
1472 if (arrEssenceInput[0][1] != arrEssenceInput[0][2]) quickCalcEssenceString += "Not enough " + arrEssenceInput[0][0] + " " + arrEssenceInput[0][2] + "/" + arrEssenceInput[0][1] + "<br>";
1473 if (arrEssenceInput[1][1] != arrEssenceInput[1][2]) quickCalcEssenceString += "Not enough " + arrEssenceInput[1][0] + " " + arrEssenceInput[1][2] + "/" + arrEssenceInput[1][1] + "<br>";
1474 */
1475 //Super Essence tooltip hover
1476
1477 /*
1478 if (arrSuperEssenceInput[0][1] == arrSuperEssenceInput[0][2] && arrSuperEssenceInput[1][1] == arrSuperEssenceInput[1][2]) {
1479 quickCalcSuperEssenceString += "<span style='float:left;padding:5px;'>S Ess Profit</span>";
1480 if (hasBrewingKit) {
1481 quickCalcSuperEssenceString += "<span style='float:right;padding:5px;color:green;'>+Brewing Kit</span>";
1482 } else quickCalcSuperEssenceString += "<span style='float:right;padding:5px;color:black;'><s style='color:red'>Brewing Kit</s></span>";
1483 quickCalcSuperEssenceString += "<br>";
1484 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>";
1485 quickCalcSuperEssenceString += "<tr>";
1486 quickCalcSuperEssenceString += "<td style='text-align:center'><img class='image-icon-20' src='images/superEssencePotion.png'></td>";
1487 totalPrice = (arrSuperEssenceInput[0][3] + arrSuperEssenceInput[1][3] + lowestVialPrice);
1488 var superEssenceProfit = superEssencePotionAvgEssence * 1;
1489 quickCalcSuperEssenceString += "<td>" + abbreviate_number(totalPrice, 2) + "</td>";
1490 if (abbreviate_number(totalPrice, 1) === 0) {
1491 quickCalcSuperEssenceString += "<td></td>";
1492 } else if (abbreviate_number(superEssenceProfit).indexOf("-") >= 0) {
1493 quickCalcSuperEssenceString += "<td style='color:red'>" + Number(superEssencePotionAvgEssence.toFixed(2)) + "</td>";
1494 } else {
1495 quickCalcSuperEssenceString += "<td style='color:lightgreen'>" + Number(superEssencePotionAvgEssence.toFixed(2)) + "</td>";
1496 quickCalcSuperEssenceBoxShadow = true;
1497 }
1498 if (abbreviate_number(totalPrice, 1) === 0) {
1499 quickCalcSuperEssenceString += "<td></td>";
1500 } else if (abbreviate_number(superEssenceProfit).indexOf("-") >= 0) {
1501 quickCalcSuperEssenceString += "<td style='color:red'>" + abbreviate_number(Number(superEssenceProfit.toFixed(2)), 2) + "</td>";
1502 } else {
1503 quickCalcSuperEssenceString += "<td style='color:lightgreen'>" + abbreviate_number(Number(superEssenceProfit.toFixed(2)), 2) + "</td>";
1504 quickCalcSuperEssenceBoxShadow = true;
1505 }
1506 quickCalcSuperEssenceString += "<tr>";
1507 quickCalcSuperEssenceString += "<td style='text-align:center;color:gold;'>24h</td>";
1508 totalPrice = (24 * 60 * 60 / superEssencePotionDuration) * (arrSuperEssenceInput[0][3] + arrSuperEssenceInput[1][3] + lowestSmallVialPrice);
1509 var superEssenceProfit24 = (24 * 60 * 60 / superEssencePotionDuration) * superEssencePotionAvgEssence * 1;
1510 quickCalcSuperEssenceString += "<td>" + abbreviate_number(totalPrice, 2) + "</td>";
1511 if (abbreviate_number(totalPrice, 1) === 0) {
1512 quickCalcSuperEssenceString += "<td></td>";
1513 } else if (abbreviate_number(superEssenceProfit).indexOf("-") >= 0) {
1514 quickCalcSuperEssenceString += "<td style='color:red'>" + Number(((24 * 60 * 60 / superEssencePotionDuration) * superEssencePotionAvgEssence).toFixed(2)) + "</td>";
1515 } else {
1516 quickCalcSuperEssenceString += "<td style='color:lightgreen'>" + Number(((24 * 60 * 60 / superEssencePotionDuration) * superEssencePotionAvgEssence).toFixed(2)) + "</td>";
1517 quickCalcSuperEssenceBoxShadow = true;
1518 }
1519 if (abbreviate_number(totalPrice, 1) === 0) {
1520 quickCalcSuperEssenceString += "<td></td>";
1521 } else if (abbreviate_number(superEssenceProfit).indexOf("-") >= 0) {
1522 quickCalcSuperEssenceString += "<td style='color:red'>" + abbreviate_number(Number(superEssenceProfit24.toFixed(0)), 1) + "</td>"; //avg proft
1523 } else {
1524 quickCalcSuperEssenceString += "<td style='color:lightgreen'>" + abbreviate_number(Number(superEssenceProfit24.toFixed(0)), 1) + "</td>";
1525 quickCalcSuperEssenceBoxShadow = true;
1526 }
1527 quickCalcSuperEssenceString += "</tr>";
1528 quickCalcSuperEssenceString += "</tbody></table>";
1529 dottedGreenLeafPrice = arrSuperEssenceInput[0][3];
1530 blewitMushroomPrice = arrSuperEssenceInput[1][3];
1531 quickCalcSuperEssenceString += arrSuperEssenceInput[0][0] + ": " + abbreviate_number(dottedGreenLeafPrice, 0) + "<br>";
1532 quickCalcSuperEssenceString += arrSuperEssenceInput[1][0] + ": " + abbreviate_number(blewitMushroomPrice, 0) + "<br>";
1533 quickCalcSuperEssenceString += lowestVialSource + ": " + abbreviate_number(lowestVial, 0) + "<br>";
1534 quickCalcSuperEssenceString += "<br>";
1535 quickCalcSuperEssenceString += "Ess Chance: 1/" + numberWithCommas(superEssencePotionEssenceChance) + "/tick<br>";
1536 var superEssencePotionDurationDate = new Date(null);
1537 superEssencePotionDurationDate.setSeconds(superEssencePotionDuration); // specify value for SECONDS here
1538 var superEssencePotionDurationFormatted = superEssencePotionDurationDate.toISOString().substr(11, 8);
1539 quickCalcSuperEssenceString += "Potion Duration: " + superEssencePotionDurationFormatted;
1540 }
1541 if (arrSuperEssenceInput[0][1] != arrSuperEssenceInput[0][2]) quickCalcSuperEssenceString += "Not enough " + arrSuperEssenceInput[0][0] + " " + arrSuperEssenceInput[0][2] + "/" + arrSuperEssenceInput[0][1] + "<br>";
1542 if (arrSuperEssenceInput[1][1] != arrSuperEssenceInput[1][2]) quickCalcSuperEssenceString += "Not enough " + arrSuperEssenceInput[1][0] + " " + arrSuperEssenceInput[1][2] + "/" + arrSuperEssenceInput[1][1] + "<br>";
1543 */
1544 if (quickCalcStardustBoxShadow && stardustProfitGreenBox) {
1545 document.getElementById("quickCalcStardust").style.boxShadow = "0 0 40px -10px rgba(0,255,0,1) inset,0 0 5px 0px rgba(0,255,0,1)";
1546 } else document.getElementById("quickCalcStardust").style.boxShadow = "";
1547 if (quickCalcSuperStardustBoxShadow && superStardustProfitGreenBox) {
1548 document.getElementById("quickCalcSuperStardust").style.boxShadow = "0 0 40px -10px rgba(0,255,0,1) inset,0 0 5px 0px rgba(0,255,0,1)";
1549 } else document.getElementById("quickCalcSuperStardust").style.boxShadow = "";
1550 if (quickCalcStargemBoxShadow && stargemProfitGreenBox) {
1551 document.getElementById("quickCalcStargem").style.boxShadow = "0 0 40px -10px rgba(0,255,0,1) inset,0 0 5px 0px rgba(0,255,0,1)";
1552 } else document.getElementById("quickCalcStargem").style.boxShadow = "";
1553 /*
1554 if (quickCalcEssenceBoxShadow && essenceProfitGreenBox) {
1555 document.getElementById("quickCalcEssence").style.boxShadow = "0 0 40px -10px rgba(0,255,0,1) inset,0 0 5px 0px rgba(0,255,0,1)";
1556 } else document.getElementById("quickCalcEssence").style.boxShadow = "";
1557 if (quickCalcSuperEssenceBoxShadow && superEssenceProfitGreenBox) {
1558 document.getElementById("quickCalcSuperEssence").style.boxShadow = "0 0 40px -10px rgba(0,255,0,1) inset,0 0 5px 0px rgba(0,255,0,1)";
1559 } else document.getElementById("quickCalcSuperEssence").style.boxShadow = "";
1560 */
1561 //heat on market table
1562 cheapestHeat = arrQuickCalcHeat[1];
1563 if (showCheapestHeat && arrQuickCalcHeat[1] <= tedStoredSettings.showCheapestHeat.showAt) {
1564 var quickCalcBestHeat = document.createElement("img");
1565 quickCalcBestHeat.setAttribute("style", "float:left;padding-left:15px;");
1566 quickCalcBestHeat.setAttribute("src", "images/icons/fire.png");
1567 quickCalcBestHeat.setAttribute("class", "image-icon-20");
1568 quickCalcBestHeat.setAttribute("title", "Cheapest heat @ " + numberWithCommas(arrQuickCalcHeat[1]));
1569 document.getElementById("market-table").rows[arrQuickCalcHeat[5]].style.display = "table-row";
1570 if (document.getElementById("market-table").rows[arrQuickCalcHeat[5]].style.background === "") {
1571 document.getElementById("market-table").rows[arrQuickCalcHeat[5]].style.background = "linear-gradient(#f2f2f2," + colorLuminance("#f2f2f2", -0.1) + ")";
1572 }
1573 document.getElementById("market-table").rows[arrQuickCalcHeat[5]].cells[0].insertBefore(quickCalcBestHeat, document.getElementById("market-table").rows[arrQuickCalcHeat[5]].cells[0].childNodes[1]);
1574 }
1575 //energy on market table
1576 cheapestEnergy = arrQuickCalcEnergy[1];
1577 if (showCheapestEnergy && arrQuickCalcEnergy[1] <= tedStoredSettings.showCheapestEnergy.showAt) {
1578 var quickCalcBestEnergy = document.createElement("img");
1579 quickCalcBestEnergy.setAttribute("style", "float:left;padding-left:15px;");
1580 quickCalcBestEnergy.setAttribute("src", "images/steak.png");
1581 quickCalcBestEnergy.setAttribute("class", "image-icon-20");
1582 quickCalcBestEnergy.setAttribute("title", "Cheapest energy @ " + numberWithCommas(arrQuickCalcEnergy[1]));
1583 document.getElementById("market-table").rows[arrQuickCalcEnergy[5]].style.display = "table-row";
1584 if (document.getElementById("market-table").rows[arrQuickCalcEnergy[5]].style.background === "") {
1585 document.getElementById("market-table").rows[arrQuickCalcEnergy[5]].style.background = "linear-gradient(#f2f2f2," + colorLuminance("#f2f2f2", -0.1) + ")";
1586 }
1587 document.getElementById("market-table").rows[arrQuickCalcEnergy[5]].cells[0].insertBefore(quickCalcBestEnergy, document.getElementById("market-table").rows[arrQuickCalcEnergy[5]].cells[0].childNodes[1]);
1588 }
1589 //bonemeal on market table
1590 cheapestBonemeal = arrQuickCalcBonemeal[1];
1591 if (showCheapestBonemeal && arrQuickCalcBonemeal[1] <= tedStoredSettings.showCheapestBonemeal.showAt) {
1592 var quickCalcBestBonemeal = document.createElement("img");
1593 quickCalcBestBonemeal.setAttribute("style", "float:left;padding-left:15px;");
1594 quickCalcBestBonemeal.setAttribute("src", "images/filledBonemealBin.png");
1595 quickCalcBestBonemeal.setAttribute("class", "image-icon-20");
1596 quickCalcBestBonemeal.setAttribute("title", "Cheapest bonemeal @ " + numberWithCommas(arrQuickCalcBonemeal[1]));
1597 document.getElementById("market-table").rows[arrQuickCalcBonemeal[5]].style.display = "table-row";
1598 if (document.getElementById("market-table").rows[arrQuickCalcBonemeal[5]].style.background === "") {
1599 document.getElementById("market-table").rows[arrQuickCalcBonemeal[5]].style.background = "linear-gradient(#f2f2f2," + colorLuminance("#f2f2f2", -0.1) + ")";
1600 }
1601 document.getElementById("market-table").rows[arrQuickCalcBonemeal[5]].cells[0].insertBefore(quickCalcBestBonemeal, document.getElementById("market-table").rows[arrQuickCalcBonemeal[5]].cells[0].childNodes[1]);
1602 }
1603 }
1604 }
1605
1606 function oreAverageButtonClickAction() {
1607 if (oreAverageOn === true) {
1608 oreAverageOn = false;
1609 oreAverageElement.style.display = "none";
1610 document.getElementById("oreAverageButton").innerHTML = "oreAverageText: OFF";
1611 } else if (oreAverageOn === false) {
1612 oreAverageOn = true;
1613 oreAverageMain();
1614 document.getElementById("oreAverageButton").innerHTML = "oreAverageText: ON";
1615 }
1616 }
1617
1618 window.timeSince = function(date) {
1619 if (typeof date !== 'object') {
1620 date = new Date(date);
1621 }
1622 var seconds = Math.floor((new Date() - date) / 1000);
1623 var intervalType;
1624
1625 var interval = Math.floor(seconds / 31536000);
1626 if (interval >= 1) {
1627 intervalType = 'year';
1628 } else {
1629 interval = Math.floor(seconds / 2592000);
1630 if (interval >= 1) {
1631 intervalType = 'month';
1632 } else {
1633 interval = Math.floor(seconds / 86400);
1634 if (interval >= 1) {
1635 intervalType = 'day';
1636 } else {
1637 interval = Math.floor(seconds / 3600);
1638 if (interval >= 1) {
1639 intervalType = "hour";
1640 } else {
1641 interval = Math.floor(seconds / 60);
1642 if (interval >= 1) {
1643 intervalType = "minute";
1644 } else {
1645 interval = seconds;
1646 intervalType = "second";
1647 }
1648 }
1649 }
1650 }
1651 }
1652 if (interval > 1 || interval === 0) {
1653 intervalType += 's';
1654 }
1655 return interval + ' ' + intervalType;
1656 };
1657
1658 // START OF MINIGAMES
1659
1660 // END OF MINIGAMES
1661 function getMarketItems() {
1662 var currentItemId;
1663 arrMarketItems = {};
1664 for (var i = 1; i < document.getElementById("market-table").rows.length; i++) {
1665 if (typeof(document.getElementById("market-table").rows[i].childNodes[0]) != "undefined" && document.getElementById("market-table").rows[i].childNodes[0] !== null) {
1666 let itemName = itemNameFix(document.getElementById("market-table").rows[i].childNodes[0].innerHTML);
1667 let itemId = parseInt(document.getElementById("market-table").rows[i].getAttribute("data-market-itemid"));
1668 let itemPrice = parseInt(document.getElementById("market-table").rows[i].getAttribute("data-market-price"));
1669 let itemAmount = parseInt(document.getElementById("market-table").rows[i].getAttribute("data-market-amount"));
1670 let itemMarketId = parseInt(document.getElementById("market-table").rows[i].getAttribute("data-market-marketid"));
1671 let row = parseInt(i);
1672 if (itemId != currentItemId) {
1673 currentItemId = itemId;
1674 if (!arrMarketItems[itemName]) {
1675 arrMarketItems[itemName] = [];
1676 }
1677 }
1678 arrMarketItems[itemName].push({
1679 id: itemId,
1680 price: itemPrice,
1681 amount: itemAmount,
1682 marketid: itemMarketId,
1683 row: row
1684 });
1685 }
1686 }
1687 }
1688
1689 function addItemTooltips() {
1690 if (itemTooltips) {
1691 for (var i = 0; i < Object.keys(arrMarketItems).length; i++) {
1692 if (document.getElementById("tooltip-" + Object.keys(arrMarketItems)[i]) !== null) {
1693 let itemName = Object.keys(arrMarketItems)[i];
1694 let minPrice = arrMarketItems[Object.keys(arrMarketItems)[i]][0].price;
1695 let marketTotal = window[itemName] * minPrice;
1696 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);
1697 if (document.getElementById("tooltip-" + itemName).lastElementChild.tagName == "DIV") {
1698 document.getElementById("tooltip-" + itemName).removeChild(document.getElementById("tooltip-" + itemName).lastChild);
1699 }
1700 var tooltipElement = document.createElement("div");
1701 tooltipElement.innerHTML = newTooltip;
1702 document.getElementById("tooltip-" + itemName).appendChild(tooltipElement);
1703 }
1704 }
1705 }
1706 }
1707 window.disableBtn = function(btn, time) {
1708 if (!btn.disabled) {
1709 var oldStyle;
1710 if (btn.parentNode && btn.parentNode.id == "browseAllElementWrapper") {
1711 oldStyle = "margin:5px;padding:0px;";
1712 } else oldStyle = "";
1713 btn.disabled = true;
1714 sendToSpreadsheet_timeoutStart = new Date().getTime();
1715 if (btn.id == "ted-browse-all" && sendMarketData === true && sendToSpreadsheet_timeoutStart - sendToSpreadsheet_timeout > sendMarketDataWaitTimeMins) {
1716 btn.setAttribute("style", oldStyle + "box-shadow: 0 0 30px 6px rgba(0, 255, 0, 1) inset;transition: box-shadow 0.3s ease-out;");
1717 setTimeout(function() {
1718 btn.setAttribute("style", oldStyle + "box-shadow: 0 0 30px 6px rgba(0, 255, 0, 0) inset;transition: box-shadow 0.3s ease-out;");
1719 btn.disabled = false;
1720 }, time);
1721 } else {
1722 btn.setAttribute("style", oldStyle + "box-shadow: 0 0 30px 6px rgba(255, 0, 0, 1) inset;transition: box-shadow 0.3s ease-out;");
1723 setTimeout(function() {
1724 btn.setAttribute("style", oldStyle + "box-shadow: 0 0 30px 6px rgba(255, 0, 0, 0) inset;transition: box-shadow 0.3s ease-out;");
1725 btn.disabled = false;
1726 }, time);
1727 }
1728 }
1729 };
1730
1731 function sendToSpreadsheet(msg) {
1732 if (sendMarketData === true) {
1733 sendToSpreadsheet_timeoutStart = new Date().getTime();
1734 if (sendToSpreadsheet_timeoutStart - sendToSpreadsheet_timeout > sendMarketDataWaitTimeMins) {
1735 sendToSpreadsheet_timeout = sendToSpreadsheet_timeoutStart;
1736 //$.post("https://script.google.com/macros/s/AKfycbx_izl1yk0PLUNp4te3swi3uSxrEu4L7E0JueJ72cS0r899Wj7z/exec", {
1737 //marketData: msg,
1738 //user: username
1739 // });
1740 //$.post("https://dhmarket.000webhostapp.com/data_post.php", {
1741 // marketData: msg,
1742 //user: username
1743 // });
1744 console.log("Ted's Market: Don't worry about 'XMLHttpRequest cannot load...' error, data was sent successfully.");
1745 }
1746 }
1747 }
1748
1749 function calculateFlips() {
1750 totalFlipProfit = 0;
1751 var arrProfitDone = [];
1752 for (let i = 0; i < tedStoredSettings.tradeHistory.length; i++) {
1753 var objArr = [];
1754 let th = tedStoredSettings.tradeHistory[i];
1755 if (!isInArray(arrProfitDone, th.name)) {
1756 if ((exactMatch && th.name.toLowerCase().match(exactSearch)) || !exactMatch && (searchString === "" || th.name.toLowerCase().includes(searchString) || getItemName(th.name).toLowerCase().includes(searchString))) {
1757 for (let a = i; a < tedStoredSettings.tradeHistory.length; a++) {
1758 let tha = tedStoredSettings.tradeHistory[a];
1759 if (tha.name == th.name) {
1760 let tradeType = tha.tradetype;
1761 if (tradeType == "buy") {
1762 if (typeof(tha.flipaccountedfor == "undefined")) {
1763 tha.flipaccountedfor = 0;
1764 }
1765 if (tha.flipaccountedfor == tha.amount) {
1766 continue;
1767 } else {
1768 objArr.push(tha);
1769 }
1770 } else if (tradeType == "sell") {
1771 if (typeof(tha.flipamount == "undefined")) {
1772 tha.flipamount = 0;
1773 }
1774 if (typeof(tha.flipprofit == "undefined")) {
1775 tha.flipprofit = 0;
1776 }
1777 if (tha.flipamount == tha.amount) {
1778 totalFlipProfit += tha.flipprofit;
1779 continue;
1780 } else if (objArr.length > 0) {
1781 objArr.sort(function(a, b) {
1782 return a.price == b.price ? 0 : +(a.price > b.price) || -1;
1783 });
1784 for (let b = 0; b < objArr.length; b++) {
1785 if (objArr[b].flipaccountedfor == objArr[b].amount) {
1786 continue;
1787 } else {
1788 let price = objArr[b].price;
1789 if (price !== tha.price) {
1790 let amountUnaccounted = objArr[b].amount - objArr[b].flipaccountedfor;
1791 let diff = tha.amount - tha.flipamount;
1792 if (amountUnaccounted < diff) {
1793 tha.flipamount += amountUnaccounted;
1794 tha.flipprofit += ((tha.price - price) * amountUnaccounted);
1795 objArr[b].flipaccountedfor = objArr[b].amount;
1796 } else if (amountUnaccounted >= diff) {
1797 tha.flipamount += diff;
1798 tha.flipprofit += ((tha.price - price) * diff);
1799 objArr[b].flipaccountedfor += diff;
1800 }
1801 }
1802 }
1803 }
1804 totalFlipProfit += tha.flipprofit;
1805 }
1806 }
1807 }
1808 }
1809 }
1810 }
1811 arrProfitDone.push(th.name);
1812 }
1813 if (searchVal === "") {
1814 document.getElementById("thTotalFlipProfit").innerHTML = "Total Flip Profit: " + numberWithCommas(totalFlipProfit);
1815 } else {
1816 document.getElementById("thTotalFlipProfit").innerHTML = "\"" + searchVal + "\" Flip Profit: " + numberWithCommas(totalFlipProfit);
1817 }
1818 updateVariables();
1819 }
1820 window.thSearchLogic = function() {
1821 searchVal = document.getElementById("thSearch").value;
1822 let tempSearchVal = document.getElementById("thSearch").value;
1823 setTimeout(function() {
1824 if (tempSearchVal == document.getElementById("thSearch").value) {
1825 if (document.getElementById("thSearch").value[0] === "=") {
1826 exactMatch = true;
1827 searchString = document.getElementById("thSearch").value.substring(1, document.getElementById("thSearch").value.length).toLowerCase().replace(/\s/g, "");
1828 exactSearch = new RegExp("^" + searchString + "$");
1829 } else {
1830 exactMatch = false;
1831 searchString = document.getElementById("thSearch").value.toLowerCase();
1832 }
1833 generateTradeHistoryTable();
1834 calculateFlips();
1835 }
1836 }, 250);
1837 };
1838 window.thDelete = function(arrnum, source) {
1839 if (source.getAttribute("thdeletewarned") == "false") {
1840 setTimeout(function() {
1841 source.setAttribute("thdeletewarned", "true");
1842 }, 300);
1843 source.style.boxShadow = "0 0 30px 3px rgba(255, 0, 0, 1) inset";
1844 source.style.transition = "box-shadow 0.5s ease-in-out";
1845 setTimeout(function() {
1846 if (source) {
1847 source.setAttribute("thdeletewarned", "false");
1848 source.style.boxShadow = "0 0 30px 3px rgba(255, 0, 0, 0) inset";
1849 source.style.transition = "box-shadow 0.5s ease-in-out";
1850 }
1851 }, 1500);
1852 } else if (source.getAttribute("thdeletewarned") == "true") {
1853 for (let i = 0; i < tedStoredSettings.tradeHistory.length; i++) {
1854 if (JSON.stringify(sortedTradeHistory[arrnum]) == JSON.stringify(tedStoredSettings.tradeHistory[i])) {
1855 tedStoredSettings.tradeHistory.splice(i, 1);
1856 calculateFlips();
1857 sortTradeHistory(sortByTH);
1858 updateVariables();
1859 break;
1860 }
1861 }
1862 }
1863 };
1864 window.highlightSorted = function() {
1865 for (let i = 0; i < document.getElementsByClassName("thTH").length; i++) {
1866 if (document.getElementsByClassName("thTH")[i].getAttribute("prop") == sortByTH) {
1867 if ((thSortToggle && sortByTH !== "name") || (!thSortToggle && sortByTH == "name")) {
1868 document.getElementsByClassName("thTH")[i].style.boxShadow = "0px -2px 10px -2px, 0px 2px 3px 1px inset";
1869 document.getElementsByClassName("thTH")[i].style.borderTopStyle = "hidden";
1870 } else {
1871 document.getElementsByClassName("thTH")[i].style.boxShadow = "0px 5px 10px -2px, 0px -2px 3px 1px inset";
1872 document.getElementsByClassName("thTH")[i].style.borderBottomStyle = "hidden";
1873 }
1874 document.getElementsByClassName("thTH")[i].style.transition = "box-shadow 0.25s ease";
1875 break;
1876 }
1877 }
1878 };
1879 window.sortTradeHistory = function(sortBy, invertible) {
1880 if (typeof(invertible) !== "boolean") {
1881 invertible = false;
1882 }
1883 sortedTradeHistory = JSON.parse(JSON.stringify(tedStoredSettings.tradeHistory));
1884 if (invertible && sortBy == sortByTH) {
1885 thSortToggle = !thSortToggle;
1886 } else if (invertible && sortBy == "name") {
1887 thSortToggle = false;
1888 } else if (invertible) {
1889 thSortToggle = true;
1890 }
1891 sortedTradeHistory.sort(function(a, b) {
1892 if (thSortToggle) {
1893 if (a[sortBy] > b[sortBy]) return -1;
1894 }
1895 if (!thSortToggle) {
1896 if (a[sortBy] < b[sortBy]) return -1;
1897 }
1898 if (a[sortBy] == b[sortBy]) {
1899 if (a.date > b.date) return -1;
1900 if (a.date < b.date) return 1;
1901 return 0;
1902 }
1903 if (typeof(a[sortBy]) == "undefined" || a[sortBy] === null || a[sortBy] === 0) return 1;
1904 if (typeof(b[sortBy]) == "undefined" || b[sortBy] === null || b[sortBy] === 0) return -1;
1905 return 1;
1906 });
1907 generateTradeHistoryTable();
1908 sortByTH = sortBy;
1909 };
1910 window.generateTradeHistoryTable = function() {
1911 thString = "";
1912 thString += "<table class='market-table' cellpadding='5px' style='width:100%;cursor:default'>";
1913 thString += "<tr style='background-color:lightgrey'>";
1914 thString += "<th style='width:30px'></th>";
1915 thString += "<th style='cursor:pointer' class='thTH' prop='name' onclick='sortTradeHistory("name", true);sortByTH="name"'>Name</th>";
1916 thString += "<th style='width:30px'>Type</th>";
1917 thString += "<th style='cursor:pointer;width:105px' class='thTH' prop='price' onclick='sortTradeHistory("price", true);sortByTH="price"'>Price</th>";
1918 thString += "<th style='cursor:pointer;width:105px' class='thTH' prop='amount' onclick='sortTradeHistory("amount", true);sortByTH="amount"'>Amount</th>";
1919 thString += "<th style='cursor:pointer;width:105px' class='thTH' prop='total' onclick='sortTradeHistory("total", true);sortByTH="total"'>Total</th>";
1920 thString += "<th style='cursor:pointer;width:105px' class='thTH' prop='flipamount' onclick='sortTradeHistory("flipamount", true);sortByTH="flipamount"'>Flip Amount</th>";
1921 thString += "<th style='cursor:pointer;width:105px' class='thTH' prop='flipprofit' onclick='sortTradeHistory("flipprofit", true);sortByTH="flipprofit"'>Flip Profit</th>";
1922 thString += "<th style='cursor:pointer;width:175px' class='thTH' prop='date' onclick='sortTradeHistory("date", true);sortByTH="date"'>Timestamp</th>";
1923 thString += "<th style='width:60px'>Delete</th>";
1924 thString += "</tr>";
1925 var max3 = 0;
1926 let sellColFade = colorLuminance("#96c896", -0.2);
1927 let buyColFade = colorLuminance("#c89696", -0.2);
1928 for (let i = 0; i < sortedTradeHistory.length; i++) {
1929 if (!sortedTradeHistory[i]) break;
1930 let tradeType = sortedTradeHistory[i].tradetype;
1931 if ((tradeType == "buy" && document.getElementById("thBuyCheckbox").checked) || (tradeType == "sell" && document.getElementById("thSellCheckbox").checked)) {
1932 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 == " ")) {
1933 if (document.getElementById("thMax3Checkbox").checked) {
1934 if (max3 >= 3) {
1935 break;
1936 }
1937 max3++;
1938 }
1939 let rowColor = "#96c896"; // sell
1940 let rowColor2 = sellColFade; // sell
1941 if (sortedTradeHistory[i].tradetype == "buy") {
1942 rowColor = "#c89696"; // buy
1943 rowColor2 = buyColFade; // buy
1944 }
1945 thString += "<tr onmouseover='highlightRow(this, true);' onmouseout='highlightRow(this, false);' style='background:linear-gradient(" + rowColor + "," + rowColor2 + ")'>";
1946 thString += "<td style='text-align:center'><img class='image-icon-30' src='images/" + sortedTradeHistory[i].name + ".png'></td>";
1947 thString += "<td style='text-align:center'>" + getItemName(sortedTradeHistory[i].name) + "</td>";
1948 thString += "<td style='text-align:center'>" + sortedTradeHistory[i].tradetype + "</td>";
1949 thString += "<td style='text-align:right'>" + numberWithCommas(sortedTradeHistory[i].price) + "</td>";
1950 thString += "<td style='text-align:right'>" + numberWithCommas(sortedTradeHistory[i].amount) + "</td>";
1951 thString += "<td style='text-align:right'>" + numberWithCommas(sortedTradeHistory[i].price * sortedTradeHistory[i].amount) + "</td>";
1952 if (sortedTradeHistory[i].flipamount) {
1953 thString += "<td style='text-align:right'>" + numberWithCommas(sortedTradeHistory[i].flipamount) + "</td>";
1954 } else thString += "<td></td>";
1955 if (sortedTradeHistory[i].flipprofit) {
1956 thString += "<td style='text-align:right'>" + numberWithCommas(sortedTradeHistory[i].flipprofit) + "</td>";
1957 } else thString += "<td></td>";
1958 let d = new Date(sortedTradeHistory[i].date);
1959 let date = new Date(d.getTime() - (d.getTimezoneOffset() * 60000));
1960 thString += "<td style='text-align:center'>" + date.toISOString().substring(11, 19) + " | " + date.toISOString().substring(0, 10) + "</td>";
1961 thString += "<td title='First click: enable delete\nSecond click: permanently delete' arrnum='" + i + "' thdeletewarned='false' style='text-align:center' onclick='thDelete(this.getAttribute("arrnum"),this)'><img class='image-icon-30' src='https://i.imgur.com/S4WuNVn.png'></td>";
1962 thString += "</tr>";
1963 }
1964 }
1965 }
1966 thString += "</table>";
1967 if (document.getElementById("tradeHistoryModalBody").style.display != "none") {
1968 tradeHistoryModalBodyTable.innerHTML = thString;
1969 }
1970 setTimeout(function() {
1971 highlightSorted();
1972 }, 0);
1973 };
1974
1975 function getArrMarketItemObjectFromMarketId(marketId) {
1976 marketId = parseInt(marketId);
1977 for (var i = 0; i < Object.keys(arrMarketItems).length; i++) {
1978 let itemName = Object.keys(arrMarketItems)[i];
1979 for (var a = 0; a < arrMarketItems[itemName].length; a++) {
1980 if (arrMarketItems[itemName][a].marketid == marketId) {
1981 return arrMarketItems[itemName][a];
1982 }
1983 }
1984 }
1985 return undefined;
1986 }
1987 function addWebsocketHook() { // thanks florb
1988 const msgGameArr = ["Poker"],
1989 msgMainArr = ["SEND_LOBBY"];
1990 var origOnMessage = window.webSocket.onmessage;
1991 window.webSocket.onmessage = function(e) {
1992 origOnMessage.apply(this, arguments);
1993 let msg = e.data;
1994 /*
1995 if (msg.includes("TMG#")) {
1996 let msgFrom = msg.substring(0, msg.indexOf("="));
1997 msg = msg.replace(msgFrom, "").replace("=", "");
1998 // p2p("ted120",msg) = "ted120=TMG#Game Name#msgMain#msgSub1#msgSub2#msgSub3"
1999 console.log(msgFrom + "=" + msg);
2000 try {
2001 let arrMsg = msg.replace("TMG#", "").split("#");
2002 let msgGame = arrMsg[0];
2003 let msgMain = arrMsg[1];
2004 let msgSub1 = arrMsg[2];
2005 let msgSub2 = arrMsg[3];
2006 let msgSub3 = arrMsg[4];
2007 let msgSub4 = arrMsg[5];
2008 if (msgMain == "PING") {
2009 sendp2p(msgFrom, "PINGRETURN");
2010 return;
2011 } else if (msgMain == "PINGRETURN") {
2012 pingTime = new Date().getTime() - pingTimeStart;
2013 pingSent = false;
2014 return;
2015 }
2016 if (msgGame == "Poker") {
2017 if (window.username == pokerServerUsername) {
2018 // if we are poker server
2019 window.tmg_pokerSendLobby = function() {
2020 var sendDataArray = [], lobbyDataArray = [], thisTableString = "";
2021 for (let table in minigamesObject[msgGame].tables) {
2022 let sb = minigamesObject[msgGame].tables[table].gameInfo.sb;
2023 let bb = minigamesObject[msgGame].tables[table].gameInfo.bb;
2024 let gameType = minigamesObject[msgGame].tables[table].gameInfo.gameType;
2025 let minBuyin = minigamesObject[msgGame].tables[table].gameInfo.minBuyin;
2026 let maxBuyin = minigamesObject[msgGame].tables[table].gameInfo.maxBuyin;
2027 let minPlayers = minigamesObject[msgGame].tables[table].gameInfo.minPlayers;
2028 let maxPlayers = minigamesObject[msgGame].tables[table].gameInfo.maxPlayers;
2029 thisTableString = [table, sb, bb, gameType, minBuyin, maxBuyin, minPlayers, maxPlayers].join() + ",";
2030 let arrPlayers = [];
2031 for (let player in minigamesObject[msgGame].tables[table].seats) {
2032 let seatNumber = minigamesObject[msgGame].tables[table].seats[player].seat;
2033 let chips = minigamesObject[msgGame].tables[table].seats[player].chips;
2034 let chipsInPotThisStreet = minigamesObject[msgGame].tables[table].seats[player].chipsInPotThisStreet;
2035 let status = minigamesObject[msgGame].tables[table].seats[player].status;
2036 arrPlayers.push([player, seatNumber, chips, chipsInPotThisStreet, status].join("."));
2037 }
2038 thisTableString += arrPlayers.join(",");
2039 lobbyDataArray.push(thisTableString);
2040 }
2041 let headerString = [window.username + "=TMG", "Poker", "SEND_LOBBY#"].join("#");
2042 while (lobbyDataArray.length > 0) {
2043 let count = 0;
2044 let thisString = headerString + lobbyDataArray[count++];
2045 let nextString = thisString + "@" + lobbyDataArray[count];
2046 while (nextString) {
2047 if (!lobbyDataArray[count] || nextString.length > 255) {
2048 nextString = false;
2049 } else if (nextString.length <= 255) {
2050 thisString = nextString;
2051 nextString += lobbyDataArray[++count];
2052 }
2053 }
2054 if (thisString.length > 255) {
2055 lobbyDataArray.splice(0, 1);
2056 console.log("too long: " + thisString);
2057 } else {
2058 thisString = thisString.replace([window.username + "=TMG", "Poker"].join("#")+"#","");
2059 sendDataArray.push(thisString);
2060 lobbyDataArray.splice(0, count);
2061 }
2062 }
2063 sendDataArray.forEach(data => {
2064 sendp2p(msgFrom, data);
2065 });
2066 };
2067 if (msgMain == "CONNECT") {
2068 pokerServerPlayersConnected[msgFrom] = {
2069 status: "connected",
2070 lastActivity: new Date().getTime(),
2071 };
2072 sendp2p(msgFrom, "CONNECTED");
2073 tmg_pokerSendLobby();
2074 } else if (msgMain == "DISCONNECT") {
2075 if (pokerServerPlayersConnected[msgFrom]) {
2076 delete pokerServerPlayersConnected[msgFrom];
2077 }
2078 sendp2p(msgFrom, "DISCONNECTED");
2079 } else if (msgMain == "SEATED") {
2080 let gameId = msgSub1;
2081 let action = msgSub2;
2082 let amount = msgSub3;
2083 if (minigamesObject[msgGame].tables[gameId] && minigamesObject[msgGame].tables[gameId].players.indexOf(msgFrom) >= 0) {
2084 if (minigamesObject[msgGame].tables[gameId].currentTurn == msgFrom) {
2085 if (action == "BET" || action == "RAISE" || action == "FOLD") {
2086 tmg_pokerCalculateMove(msgGame, gameId, msgFrom, action, amount);
2087 } else if (action == "LEAVE_TABLE") {
2088 tmg_pokerLeaveTable(msgGame, msgFrom, gameId);
2089 } else sendp2p(msgFrom, "ERROR", "ACTION_UNKNOWN");
2090 } else sendp2p(msgFrom, "ERROR", "NOT_YOUR_TURN");
2091 } else sendp2p(msgFrom, "ERROR", "NOT_SEATED");
2092 } else if (msgMain == "LOBBY") {
2093 if (msgSub1 == "LOAD_LOBBY") {
2094 tmg_pokerSendLobby();
2095 } else if (msgSub1 == "CREATEROOM") {
2096 let nextId = parseInt(Object.keys(minigamesObject[msgGame].tables)[Object.keys(minigamesObject[msgGame].tables).length-1]) + 1; // last id in array +1
2097 minigamesObject[msgGame].tables[nextId] = {
2098 players: [],
2099 seats: {},
2100 currentTurn: null,
2101 maxPlayers: 7,
2102 };
2103 } else if (msgSub1 == "JOINTABLE") {
2104 let desiredTable = msgSub2;
2105 let desiredSeat = msgSub3;
2106 let buyinAmount = msgSub4;
2107 if (!tmg_pokerAlreadySeated(msgGame, msgFrom)) {
2108 if (minigamesObject[msgGame].tables[desiredTable]) {
2109 for (let player in minigamesObject[msgGame].tables[desiredTable].seats) {
2110 if (minigamesObject[msgGame].tables[desiredTable].seats[player].seat == desiredSeat) {
2111 sendp2p(msgFrom, "ERROR", "SEAT_TAKEN");
2112 tmg_pokerSendLobby();
2113 return;
2114 }
2115 }
2116 if (!minigamesObject[msgGame].tables[desiredTable].seats[desiredSeat]) {
2117 minigamesObject[msgGame].tables[desiredTable].seats[msgFrom] = {
2118 name: msgFrom,
2119 seat: desiredSeat,
2120 chips: buyinAmount,
2121 chipsInPotThisStreet: 0,
2122 status: "folded",
2123 };
2124 tmg_pokerSendLobby();
2125 sendp2p(msgFrom, "JOIN_GAME", desiredTable, desiredSeat, buyinAmount);
2126 let currentHandJSON = JSON.stringify(minigamesObject[msgGame].tables[desiredTable].currentHand);
2127 let handNumber = minigamesObject.Poker.tables[desiredTable].handNumber;
2128 sendp2p(msgFrom, "CURRENT_HAND", desiredTable, handNumber, currentHandJSON);
2129 // check if sat at another table, if so prompt remove
2130 // check if seat available
2131 // add player to seat
2132 } else sendp2p(msgFrom, "ERROR", "SEAT_TAKEN");
2133 } else sendp2p(msgFrom, "ERROR", "TABLE_NOT_EXIST");
2134 }
2135 } else if (msgSub1 == "LEAVE_TABLE") {
2136 tmg_pokerLeaveTable(msgGame, msgFrom, msgSub1, msgSub2);
2137 }
2138 }
2139 } else if (msgFrom == pokerServerUsername && window.username !== pokerServerUsername) {
2140 minigameLastMessageFromPokerServer = new Date().getTime();
2141 minigamePokerServerStatus = "online";
2142 // if we receive a message from poker server
2143 if (msgMain == "CONNECTED") {
2144 document.getElementById("tmg_pokerServerConnect").value = "Connected";
2145 document.getElementById("tmg_pokerServerConnect").style.border = "#38761d ridge";
2146 document.getElementById("tmg_pokerServerConnect").style.background = "radial-gradient(white, #d9ead3, #b6d7a8)";
2147 tmg_pokerServerPingSent = false;
2148 minigameConnectedToPokerServer = true;
2149 } else if (msgMain == "DISCONNECTED") {
2150 document.getElementById("tmg_pokerServerConnect").value = "Disconnected";
2151 document.getElementById("tmg_pokerServerConnect").style.border = "#990000 ridge";
2152 document.getElementById("tmg_pokerServerConnect").style.background = "radial-gradient(white, #f4cccc, #ea9999)";
2153 minigameConnectedToPokerServer = false;
2154 } else if (msgMain == "SEND_LOBBY") {
2155 let tableInfo = msgSub1.split("@");
2156 for (let table in tableInfo) {
2157 let arrTable = tableInfo[table].split(",");
2158 let tableNumber = arrTable[0];
2159 let sb = arrTable[1];
2160 let bb = arrTable[2];
2161 let gameType = arrTable[3];
2162 let minBuyin = arrTable[4];
2163 let maxBuyin = arrTable[5];
2164 let minPlayers = arrTable[6];
2165 let maxPlayers = arrTable[7];
2166 minigamesObject[minigameCurrentSelectedGame].tables[tableNumber] = {
2167 gameInfo: {
2168 sb: sb,
2169 bb: bb,
2170 gameType: gameType,
2171 minBuyin: minBuyin,
2172 maxBuyin: maxBuyin,
2173 minPlayers: minPlayers,
2174 maxPlayers: maxPlayers,
2175 },
2176 seats: {
2177 },
2178 };
2179 for (let i = 8; i < arrTable.length; i++) {
2180 let playerInfo = arrTable[i].split(".");
2181 let playerName = playerInfo[0];
2182 let playerSeat = playerInfo[1];
2183 let playerChips = playerInfo[2];
2184 let chipsInPotThisStreet = playerInfo[3];
2185 let status = playerInfo[4];
2186 minigamesObject[minigameCurrentSelectedGame].tables[tableNumber].seats[playerName] = {
2187 name: playerName,
2188 seat: playerSeat,
2189 chips: playerChips,
2190 chipsInPotThisStreet: chipsInPotThisStreet,
2191 status: status,
2192 };
2193 }
2194 }
2195 loadPokerLobby();
2196 } else if (msgMain == "SEATS") {
2197 let tableNumber = msgSub1;
2198 let curArray = msgSub2.split("@@");
2199 for (let seatNumber in curArray) {
2200 curArray[seatNumber] = curArray[seatNumber].replaceAll("@","");
2201 let arrSeat = curArray[seatNumber].split(",");
2202 minigamesObject[minigameGame].tables[tableNumber].seats.name = arrSeat[0];
2203 minigamesObject[minigameGame].tables[tableNumber].seats.seat = arrSeat[1];
2204 minigamesObject[minigameGame].tables[tableNumber].seats.chips = arrSeat[2];
2205 minigamesObject[minigameGame].tables[tableNumber].seats.chipsInPotThisStreet = arrSeat[3];
2206 minigamesObject[minigameGame].tables[tableNumber].seats.status = arrSeat[4];
2207 }
2208 } else if (msgMain == "CURRENT_HAND") {
2209 //"TMG#ted120#Ten Plus Poker#CURRENT_HAND#table#hand#currentTurn,dealer,sb,bb,flop,turn,river,potpreviousstreets,totalpot"
2210 let tableNumber = msgSub1;
2211 let handNumber = msgSub2;
2212 let currentHandJSON = msgSub3;
2213 minigamesObject[minigameGame].tables[tableNumber].currentHand = JSON.parse(currentHandJSON);
2214 } else if (msgMain == "JOIN_GAME") {
2215 //p2p(msgFrom, "TMG#"+window.username+"#Ten Plus Poker#JOIN_GAME#"+desiredTable+"#"+desiredSeat+"#"+buyinAmount);
2216 minigamePokerMyTable = msgSub1;
2217 minigamePokerMySeat = msgSub2;
2218 minigamePokerMyBuyin = msgSub3;
2219 loadMinigame(msgGame);
2220 } else if (msgMain == "LEAVE_TABLE") {
2221 //p2p(msgFrom, "TMG#"+window.username+"#"+game+"#LEAVE_TABLE#"+msgFrom+"#"+table);
2222 tmg_pokerLeaveTable(msgGame, msgSub2, msgSub3);
2223 } else if (msgMain == "LOG") {
2224 let tableNumber = msgSub1;
2225 let handNumber = msgSub2;
2226 //let curArray = msgSub3.split(",");
2227 minigamesObject[minigameGame].tables[tableNumber].log = [msgSub3];
2228 }
2229 }
2230 } else if (minigameMyStatus == "ingame" && msgFrom == minigameOpp) {
2231 if (msgGame == "Grid Control") {
2232 if (msgMain == "MOVE") {
2233 gc_interpretMove(msgSub1, msgSub2, msgSub3, true);
2234 minigameMyTurn = true;
2235 } else if (msgMain == "SURRENDER") {
2236 gc_checkVictory(msgSub1);
2237 }
2238 } //end Grid Control
2239 if (msgMain == "QUIT") {
2240 minigameMyStatus = "free";
2241 minigameOpp = "";
2242 document.getElementById("versusContainer").style.display = "none";
2243 document.getElementById("challengeContainer").style.display = "flex";
2244 loadMinigame("Minigames");
2245 minigameQuitReason = msgSub1;
2246 }
2247 } else if (minigameMyStatus == "starting") {
2248 if (msgMain == "LOADED") {
2249 //we challenged, they accepted, we said ready, they said ready
2250 minigameMyStatus = "ingame";
2251 minigameManager.challenges[msgFrom].status = "ingame";
2252 minigameOpp = msgFrom;
2253 minigameOppPlayer = "player2";
2254 minigameMyPlayer = "player1";
2255 minigameGame = msgGame;
2256 minigameVersion = msgSub2;
2257 minigameSeed = msgSub3;
2258 loadChallenges();
2259 loadMinigame(msgGame);
2260 minigameMyTurn = true;
2261 loadVersus();
2262 sendp2p(msgFrom, "LOADED", "MYMOVE", msgSub2, msgSub3);
2263 }
2264 } else if (minigameMyStatus == "confirming start") {
2265 if (msgMain == "LOADGAME" && msgGame == minigameManager.challenges[msgFrom].game && minigameManager.challenges[msgFrom].status == "Accepted") {
2266 //they challenged, we accepted, they said ready
2267 minigameMyStatus = "ingame";
2268 minigameManager.challenges[msgFrom].status = "ingame";
2269 minigameOpp = msgFrom;
2270 minigameOppPlayer = "player1";
2271 minigameMyPlayer = msgSub1;
2272 minigameGame = msgGame;
2273 minigameVersion = msgSub2;
2274 minigameSeed = msgSub3;
2275 loadChallenges();
2276 loadMinigame(msgGame);
2277 minigameMyTurn = false;
2278 loadVersus();
2279 sendp2p(msgFrom, "LOADED", "NOTMYMOVE", msgSub2, msgSub3);
2280 }
2281 } else if (minigameMyStatus == "free") {
2282 if (msgSub1 == "ACCSTART" && minigameManager.challenges[msgFrom] && minigameManager.challenges[msgFrom].status == "Challenge received" && msgGame == minigameManager.challenges[msgFrom].game) {
2283 //we challenged, they accepted
2284 minigameMyStatus = "starting";
2285 minigameOpp = msgFrom;
2286 minigameManager.challenges[msgFrom].status = "Starting";
2287 setTimeout(function() {
2288 if (minigameMyStatus == "starting") {
2289 minigameMyStatus = "free";
2290 minigameOpp = "";
2291 minigameManager.challenges[msgFrom].status = "Timed out";
2292 }
2293 }, 3000);
2294 sendp2p(msgFrom,"LOADGAME", "player2", msgSub2, msgSub3); //from, loadgame, player, version, seed
2295 }
2296 }
2297 if (msgMain == "CHALLENGE") {
2298 if (msgSub1 == "REQSTART") {
2299 //they challenged
2300 sendp2p(msgFrom, "CHALLENGE", "RECEIVED", msgSub2, msgSub3);
2301 minigameManager.challenges[msgFrom] = {
2302 from: msgFrom,
2303 game: msgGame,
2304 version: msgSub2,
2305 seed: msgSub3,
2306 status: "Accept",
2307 };
2308 if (minigameMyStatus == "free" && allowedBrowserNotifications) {
2309 var minigameChallengeNotification = new Notification("Minigame Challenge", {
2310 body: msgGame + " challenge from " + msgFrom
2311 });
2312 setTimeout(function() {
2313 minigameChallengeNotification.close();
2314 }, 5000);
2315 }
2316 } else if (msgSub1 == "DECSTART" && minigameManager.challenges[msgFrom] && minigameManager.challenges[msgFrom].status != "We declined") {
2317 //they declined our challenge
2318 if (minigameManager.challenges[msgFrom].status == "Accept") {
2319 minigameManager.challenges[msgFrom].status = "Challenge cancelled";
2320 } else {
2321 minigameManager.challenges[msgFrom].status = "Challenge declined";
2322 }
2323 } else if (msgSub1 == "RECEIVED" && minigameManager.challenges[msgFrom]) {
2324 //they received our challenge
2325 minigameManager.challenges[msgFrom].status = "Challenge received";
2326 }
2327 loadChallenges();
2328 }
2329 if (minigameMyStatus != "free" && msgFrom != minigameOpp && msgMain != "AUTOREPLY") {
2330 sendp2p(msgFrom, "AUTOREPLY", minigameMyStatus);
2331 } else if (msgMain == "AUTOREPLY") {
2332 minigameManager.challenges[msgFrom].status = "Already ingame";
2333 }
2334 }
2335 catch(err) {
2336 console.log(err);
2337 }
2338 }
2339 */
2340 if (msg.startsWith("MARKET_BROWSE=") && msg.length > 1000) {
2341 sendToSpreadsheet(msg);
2342 }
2343 if (msg.includes("Item Purchased")) {
2344 if (th_status == "sent") {
2345 th_status = "purchased";
2346 let itemName = itemNameFix(getMarketItemNameFromMarketId(th_object.marketid));
2347 let total = th_object.price * th_object.thAmount;
2348 tedStoredSettings.tradeHistory.push({
2349 marketid: th_object.marketid,
2350 tradetype: "buy",
2351 date: new Date(),
2352 name: itemName,
2353 amount: th_object.thAmount,
2354 price: th_object.price,
2355 total: total
2356 });
2357 updateVariables();
2358 calculateFlips();
2359 sortTradeHistory(sortByTH);
2360 }
2361 }
2362 if (msg.startsWith("MARKET_SLOT=")) { //marketid, name, amountleft, price, coinstocollect, slot, expiresin
2363 let arr = msg.substring(msg.lastIndexOf("=") + 1).split("~");
2364 let marketid = parseInt(arr[0]);
2365 let itemName = arr[1];
2366 let price = parseInt(arr[3]);
2367 let coinstocollect = parseInt(arr[4]);
2368 let amountleft = parseInt(arr[2]);
2369 let amountsold = coinstocollect / price;
2370 let startamount = amountleft + amountsold;
2371 var thUpdated = false;
2372 var totalSold = 0,
2373 earliestStartAmount = 0;
2374 if (coinstocollect > 0) {
2375 for (let i = 0; i < tedStoredSettings.tradeHistory.length; i++) {
2376 if (tedStoredSettings.tradeHistory[i].hasOwnProperty("marketid") && tedStoredSettings.tradeHistory[i].marketid == marketid) {
2377 totalSold += tedStoredSettings.tradeHistory[i].amount;
2378 if (earliestStartAmount === 0) {
2379 earliestStartAmount = tedStoredSettings.tradeHistory[i].startamount;
2380 thUpdated = true;
2381 }
2382 }
2383 }
2384 if (thUpdated) {
2385 amountsold = (earliestStartAmount - totalSold) - amountleft;
2386 }
2387 if (amountsold > 0) {
2388 tedStoredSettings.tradeHistory.push({
2389 startamount: startamount,
2390 marketid: marketid,
2391 tradetype: "sell",
2392 date: new Date(),
2393 name: itemName,
2394 amount: amountsold,
2395 price: price,
2396 total: coinstocollect
2397 });
2398 updateVariables();
2399 calculateFlips();
2400 sortTradeHistory(sortByTH);
2401 }
2402 }
2403 }
2404 };
2405 var origOnSend = window.webSocket.send;
2406 window.webSocket.send = function(e) {
2407 origOnSend.apply(this, arguments);
2408 let msg = e;
2409 if (msg.startsWith("MARKET_BUY=")) {
2410 let marketId = msg.substring(msg.lastIndexOf("=") + 1, msg.lastIndexOf("~"));
2411 th_object = getArrMarketItemObjectFromMarketId(marketId);
2412 th_object.thAmount = parseInt(msg.substring(msg.lastIndexOf("~") + 1));
2413 if (typeof(th_object) == "undefined") return;
2414 th_status = "sent";
2415 }
2416 };
2417 }
2418
2419
2420 function openInNewTab(url) {
2421 var win = window.open(url, '_blank');
2422 win.focus();
2423 }
2424 window.openPriceGraph = function() {
2425 if (!jsTradableItems[itemNameFix(lastBrowsedItem)]) { // if item is not on tradable list
2426 lastBrowsedItem = "stardust";
2427 }
2428 openInNewTab("http://dhmarket.tk/?formItem=" + itemNameFix(lastBrowsedItem));
2429 };
2430 window.displayQuickCalcTooltip = function(id, on) {
2431 if (on) {
2432 quickCalcTooltip.setAttribute("style", "display:block;position:absolute;top:0;background-color:#f2f2f2;text-align:center;width:100%;");
2433 if (id == "quickCalcStargem") {
2434 quickCalcTooltip.innerHTML = quickCalcStargemString;
2435 } else if (id == "quickCalcStardust") {
2436 quickCalcTooltip.innerHTML = quickCalcStardustString;
2437 } else if (id == "quickCalcSuperStardust") {
2438 quickCalcTooltip.innerHTML = quickCalcSuperStardustString;
2439 }
2440 } else if (!on) {
2441 quickCalcTooltip.setAttribute("style", "display:none;");
2442 }
2443 };
2444 window.totalNetWorth = function() {
2445 var total = 0,
2446 marketSlots = 0;
2447 let tnwArr = [];
2448 if (Object.keys(arrMarketItems).length > 1) {
2449 for (let key in Object.keys(jsTradableItems)) {
2450 if (arrMarketItems[Object.keys(jsTradableItems)[key]]) {
2451 if (window[Object.keys(jsTradableItems)[key]] > 0) {
2452 total += arrMarketItems[Object.keys(jsTradableItems)[key]][0].price * window[Object.keys(jsTradableItems)[key]];
2453 tnwArr.push({
2454 name: Object.keys(jsTradableItems)[key],
2455 price: arrMarketItems[Object.keys(jsTradableItems)[key]][0].price * window[Object.keys(jsTradableItems)[key]],
2456 });
2457 }
2458 } else console.log("Not on market: " + Object.keys(jsTradableItems)[key]);
2459 }
2460 for (let i = 0; i < arrMarketSlots.length; i++) {
2461 if (arrMarketItems[arrMarketSlots[i][2]]) {
2462 let amount = numberWithoutCommas(document.getElementById("market-slot-" + (i + 1) + "-amount").innerHTML);
2463 marketSlots += arrMarketItems[arrMarketSlots[i][2]][0].price * amount;
2464 tnwArr.push({
2465 name: Object.keys(jsTradableItems)[key]+" (market slot)",
2466 price: arrMarketItems[arrMarketSlots[i][2]][0].price * amount,
2467 });
2468 }
2469 }
2470 tnwArr.sort(function(a, b) {
2471 return a.price == b.price ? 0 : +(a.price > b.price) || -1;
2472 });
2473 tnwArr.forEach(obj => {
2474 console.log(obj.name + ": "+ numberWithCommas(obj.price));
2475 });
2476 console.log("Total net worth: " + numberWithCommas(coins + total + marketSlots) + "\n\nCoins: " + numberWithCommas(coins) + "\nItems: " + numberWithCommas(total) + "\nSlots: " + numberWithCommas(marketSlots));
2477 } else console.log("Search all first");
2478 };
2479
2480 function alterMarketSlots() {
2481 if (marketSlotsCustomUi) {
2482 if (typeof(document.getElementById("market-slot-1").parentNode) != "undefined" && document.getElementById("market-slot-1").parentNode.id != "tedMarketSlotContainer") {
2483 var tedMarketUiElement = document.createElement("div");
2484 tedMarketUiElement.setAttribute("style", "position:relative;height:325px;width:230px;background:linear-gradient(gold,silver);display:flex;flex-direction:column;justify-content:flex-end");
2485 tedMarketUiElement.setAttribute("id", "ted-market-ui");
2486 marketSlotSpareElement.innerHTML = updateNews;
2487 if (document.getElementById("ted-market-ui") === null) {
2488 quickCalcTooltip.setAttribute("style", "display:none");
2489 var quickCalcDiv = document.createElement("div");
2490 quickCalcDiv.setAttribute("style", "text-align:center;height:52px;line-height:52px;");
2491 var quickCalcStargem = document.createElement("img");
2492 quickCalcStargem.setAttribute("id", "quickCalcStargem");
2493 quickCalcStargem.setAttribute("onmouseover", "displayQuickCalcTooltip(this.id, true);");
2494 quickCalcStargem.setAttribute("onmouseout", "displayQuickCalcTooltip(this.id, false);");
2495 quickCalcStargem.setAttribute("src", "images/stargemPotion.png");
2496 quickCalcStargem.setAttribute("class", "image-icon-30");
2497 var quickCalcSuperStardust = document.createElement("img");
2498 quickCalcSuperStardust.setAttribute("id", "quickCalcSuperStardust");
2499 quickCalcSuperStardust.setAttribute("onmouseover", "displayQuickCalcTooltip(this.id, true);");
2500 quickCalcSuperStardust.setAttribute("onmouseout", "displayQuickCalcTooltip(this.id, false);");
2501 quickCalcSuperStardust.setAttribute("src", "images/superStardustPotion.png");
2502 quickCalcSuperStardust.setAttribute("class", "image-icon-30");
2503 var quickCalcStardust = document.createElement("img");
2504 quickCalcStardust.setAttribute("id", "quickCalcStardust");
2505 quickCalcStardust.setAttribute("onmouseover", "displayQuickCalcTooltip(this.id, true);");
2506 quickCalcStardust.setAttribute("onmouseout", "displayQuickCalcTooltip(this.id, false);");
2507 quickCalcStardust.setAttribute("src", "images/stardustPotion.png");
2508 quickCalcStardust.setAttribute("class", "image-icon-30");
2509 var browseAllElementWrapper = document.createElement("div");
2510 browseAllElementWrapper.setAttribute("id", "browseAllElementWrapper");
2511 browseAllElementWrapper.setAttribute("style", "border-top:1px solid black;");
2512 var browseAllElement = document.createElement("div");
2513 browseAllElement.setAttribute("style", "margin:5px;padding:0px");
2514 browseAllElement.setAttribute("class", "basic-smallbox-grey");
2515 browseAllElement.setAttribute("id", "ted-browse-all");
2516 browseAllElement.setAttribute("title", "Browse All");
2517 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'>";
2518 var priceGraphElement = document.createElement("div");
2519 priceGraphElement.setAttribute("style", "margin:5px;padding:0px");
2520 priceGraphElement.setAttribute("class", "basic-smallbox-grey");
2521 priceGraphElement.setAttribute("id", "ted-price-graph");
2522 priceGraphElement.setAttribute("title", "Price History Graph");
2523 priceGraphElement.innerHTML = "<input type='image' style='padding:10px' onclick='disableBtn(this.parentNode,500);openPriceGraph();' src='https://i.imgur.com/XhYzZRt.png' class='image-icon-30'>";
2524 var tradeHistoryElement = document.createElement("div");
2525 tradeHistoryElement.setAttribute("style", "margin:5px;padding:0px");
2526 tradeHistoryElement.setAttribute("class", "basic-smallbox-grey");
2527 tradeHistoryElement.setAttribute("id", "ted-trade-history");
2528 tradeHistoryElement.setAttribute("title", "Trade History");
2529 tradeHistoryElement.innerHTML = "<input type='image' style='padding:10px' onclick='disableBtn(this.parentNode,500);openTradeHistory();' src='https://i.imgur.com/ch5nOjq.png' class='image-icon-30'>";
2530 var tedMarketSlotContainer = document.createElement("div");
2531 tedMarketSlotContainer.setAttribute("style", "display:flex;justify-content:space-between;width:80%;max-width:1200px;min-width:800px;");
2532 document.getElementById("market-slot-1").parentNode.appendChild(tedMarketSlotContainer);
2533 for (var i = 0; i < arrMarketSlots.length; i++) {
2534 document.getElementById("market-slot-" + (i + 1)).style.margin = "0px 2px";
2535 tedMarketSlotContainer.appendChild(document.getElementById("market-slot-" + (i + 1)));
2536 }
2537 tedMarketSlotContainer.appendChild(tedMarketUiElement);
2538 document.getElementById("ted-market-ui").append(quickCalcTooltip);
2539 document.getElementById("ted-market-ui").appendChild(marketSlotSpareElement);
2540 document.getElementById("ted-market-ui").appendChild(browseAllElementWrapper);
2541 document.getElementById("browseAllElementWrapper").appendChild(browseAllElement);
2542 //document.getElementById("browseAllElementWrapper").appendChild(priceGraphElement);
2543 document.getElementById("browseAllElementWrapper").appendChild(tradeHistoryElement);
2544 let browseAndHistory = document.getElementById("ted-market-ui").appendChild(document.createElement("div"));
2545 //browseAndHistory.appendChild(document.getElementsByClassName("market-browse-button")[0]);
2546 //browseAndHistory.appendChild(document.getElementsByClassName("market-browse-button")[1]);
2547 //document.getElementsByClassName("market-browse-button")[0].setAttribute("style","width:50%;padding:10px 0");
2548 //document.getElementsByClassName("market-browse-button")[1].setAttribute("style","width:50%;padding:10px 0");
2549 browseAndHistory.setAttribute("style", "display:flex");
2550
2551 document.getElementById("ted-market-ui").appendChild(quickCalcDiv);
2552
2553 quickCalcDiv.appendChild(quickCalcStardust);
2554 quickCalcDiv.appendChild(quickCalcSuperStardust);
2555 quickCalcDiv.appendChild(quickCalcStargem);
2556 //quickCalcDiv.appendChild(quickCalcEssence);
2557 //quickCalcDiv.appendChild(quickCalcSuperEssence);
2558
2559 }
2560 // various player market formatting improvements, dear lord forgive me
2561 if (document.getElementById("tab-container-playermarket").children[0].innerHTML == "Player Market") {
2562 document.getElementById("tab-container-playermarket").children[0].remove();
2563 document.getElementById("tab-container-playermarket").prepend(document.createElement("br"));
2564 }
2565 if (document.getElementsByClassName("error-msg")[0].parentNode.parentNode.id == "market-listings") {
2566 document.getElementsByClassName("error-msg")[0].parentNode.remove();
2567 }
2568 if (document.getElementById("market-listings").children[1].getAttribute("style") == "clear:both") {
2569 document.getElementById("market-listings").children[1].remove();
2570 }
2571 setTimeout(function() {
2572 if (document.getElementById("market-listings").children[1].children[6].tagName == "BR") {
2573 document.getElementById("market-listings").children[1].children[6].remove();
2574 }
2575 if (document.getElementById("market-listings").children[1].children[5].tagName == "BR") {
2576 document.getElementById("market-listings").children[1].children[5].remove();
2577 }
2578 if (document.getElementById("market-listings").children[1].children[3].tagName == "BR") {
2579 document.getElementById("market-listings").children[1].children[3].remove();
2580 }
2581 if (document.getElementById("market-listings").children[1].children[2].tagName == "BR") {
2582 document.getElementById("market-listings").children[1].children[2].remove();
2583 }
2584 }, 1);
2585 for (let i = 0; i < arrMarketSlots.length; i++) {
2586 document.getElementsByClassName("market-slot-collect")[i].previousElementSibling.style.borderLeft = "0px";
2587 document.getElementsByClassName("market-slot-collect")[i].previousElementSibling.style.borderRight = "0px";
2588 }
2589 }
2590 }
2591 }
2592 window.myItemListBtnAction = function(itemName, itemPrice) {
2593 myItemListAddName = itemName;
2594 myItemListAddPrice = numberWithCommas(itemPrice);
2595 changeSetting("tedTradableItems");
2596 };
2597 window.upToParentByTag = function(el, tag) {
2598 // Climbs the DOM until it gets to the given tag.
2599 tag = tag.toUpperCase();
2600 el = el.parentNode;
2601 while (el.nodeName !== tag && el.nodeName !== 'HTML') {
2602 el = el.parentNode;
2603 }
2604 if (el.modeName === 'HTML') {
2605 el = null;
2606 }
2607 return el;
2608 };
2609
2610 function colorToRGBA(color) {
2611 // Returns the color as an array of [r, g, b, a] -- all range from 0 - 255
2612 // color must be a valid canvas fillStyle. This will cover most anything
2613 // you'd want to use.
2614 // Examples:
2615 // colorToRGBA('red') # [255, 0, 0, 255]
2616 // colorToRGBA('#f00') # [255, 0, 0, 255]
2617 var cvs, ctx;
2618 cvs = document.createElement('canvas');
2619 cvs.height = 1;
2620 cvs.width = 1;
2621 ctx = cvs.getContext('2d');
2622 ctx.fillStyle = color;
2623 ctx.fillRect(0, 0, 1, 1);
2624 return ctx.getImageData(0, 0, 1, 1).data;
2625 }
2626
2627 function byteToHex(num) {
2628 // Turns a number (0-255) into a 2-character hex number (00-ff)
2629 return ('0' + num.toString(16)).slice(-2);
2630 }
2631
2632 function colorToHex(color) {
2633 // Convert any CSS color to a hex representation
2634 // Examples:
2635 // colorToHex('red') # '#ff0000'
2636 // colorToHex('rgb(255, 0, 0)') # '#ff0000'
2637 var rgba, hex;
2638 rgba = colorToRGBA(color);
2639 hex = [0, 1, 2].map(function(idx) {
2640 return byteToHex(rgba[idx]);
2641 }).join('');
2642 return "#" + hex;
2643 }
2644
2645 function colorLuminance(hex, lum) {
2646 hex = colorToHex(hex);
2647 // validate hex string
2648 hex = String(hex).replace(/[^0-9a-f]/gi, '');
2649 if (hex.length < 6) {
2650 hex = hex[0] + hex[0] + hex[1] + hex[1] + hex[2] + hex[2];
2651 }
2652 lum = lum || 0;
2653 // convert to decimal and change luminosity
2654 var rgb = "#",
2655 c, i;
2656 for (i = 0; i < 3; i++) {
2657 c = parseInt(hex.substr(i * 2, 2), 16);
2658 c = Math.round(Math.min(Math.max(0, c + (c * lum)), 255)).toString(16);
2659 rgb += ("00" + c).substr(c.length);
2660 }
2661 return rgb;
2662 }
2663
2664 function colorMarketTable() {
2665 var minPrice, secondPrice, firstRow, secondRow, table, itemName, length;
2666 for (let i = 0; i < Object.keys(arrMarketItems).length; i++) {
2667 table = document.getElementById("market-table");
2668 itemName = Object.keys(arrMarketItems)[i];
2669 minPrice = arrMarketItems[itemName][0].price;
2670 length = arrMarketItems[itemName].length;
2671 if (length >= 2) {
2672 secondPrice = arrMarketItems[itemName][1].price;
2673 } else secondPrice = null;
2674 firstRow = arrMarketItems[itemName][0].row;
2675 if (length >= 2) {
2676 secondRow = arrMarketItems[itemName][1].row;
2677 } else secondRow = null;
2678 if (minPrice <= tedStoredSettings.tedTradableItems.itemList[itemName].showAtPrice) {
2679 table.rows[firstRow].style.background = "linear-gradient(" + colorMyItemList + "," + colorLuminance(colorMyItemList, -0.1) + ")";
2680 table.rows[firstRow].style.display = "table-row";
2681 if (length >= 2) {
2682 table.rows[firstRow].setAttribute("tedcolored", "true");
2683 table.rows[secondRow].style.background = "linear-gradient(" + colorMyItemListNextLowest + "," + colorLuminance(colorMyItemListNextLowest, -0.1) + ")";
2684 table.rows[secondRow].style.display = "table-row";
2685 }
2686 } else if (tedStoredSettings.tedTradableItems.itemList[itemName].showAtMin && secondPrice && (Math.ceil(secondPrice * 0.86) > minPrice)) {
2687 table.rows[firstRow].setAttribute("tedcolored", "true");
2688 document.getElementById("market-table").rows[firstRow].style.background = "linear-gradient(" + colorMinPrice + "," + colorLuminance(colorMinPrice, -0.1) + ")";
2689 document.getElementById("market-table").rows[firstRow].style.display = "table-row";
2690 document.getElementById("market-table").rows[secondRow].style.background = "linear-gradient(" + colorNextLowestToMinPrice + "," + colorLuminance(colorNextLowestToMinPrice, -0.1) + ")";
2691 document.getElementById("market-table").rows[secondRow].style.display = "table-row";
2692 } else if (tedStoredSettings.tedTradableItems.itemList[itemName].alwaysShowLowest) {
2693 table.rows[firstRow].style.background = "linear-gradient(" + colorAlwaysShowLowest + "," + colorLuminance(colorAlwaysShowLowest, -0.1) + ")";
2694 table.rows[firstRow].style.display = "table-row";
2695 } else if (showSingleItems && length == 1) {
2696 document.getElementById("market-table").rows[firstRow].style.background = "linear-gradient(" + colorSingleItems + "," + colorLuminance(colorSingleItems, -0.1) + ")";
2697 document.getElementById("market-table").rows[firstRow].style.display = "table-row";
2698 }
2699 }
2700 for (s = 0; s < arrMarketSlots.length; s++) {
2701 if (arrMarketSlots[s][1] === true) {
2702 var myItemName, myMarketId, myRow, myListPosition, foundItem = false;
2703 for (var i = 0; i < Object.keys(arrMarketItems).length; i++) {
2704 myItemName = Object.keys(arrMarketItems)[i];
2705 firstRow = arrMarketItems[myItemName][0].row;
2706 length = arrMarketItems[myItemName].length;
2707 for (var a = 0; a < arrMarketItems[myItemName].length; a++) {
2708 let itemString = document.getElementById("market-slot-" + (s + 1) + "-taken").children[0].src;
2709 arrMarketSlots[s].push(itemString.substring(itemString.indexOf("/images/") + 8, itemString.indexOf(".png")));
2710 if (arrMarketItems[myItemName][a].marketid == arrMarketSlots[s][0]) {
2711 myMarketId = arrMarketItems[myItemName][a].marketid;
2712 myRow = arrMarketItems[myItemName][a].row;
2713 myListPosition = a;
2714 foundItem = true;
2715 break;
2716 }
2717 }
2718 if (foundItem) break;
2719 }
2720 if (!foundItem) continue;
2721 if (myListPosition === 0) {
2722 document.getElementById("market-table").rows[myRow].style.display = "table-row";
2723 document.getElementById("market-table").rows[myRow].style.background = "linear-gradient(" + colorMyListedLowest + "," + colorLuminance(colorMyListedLowest, -0.1) + ")";
2724 if (length >= 2) {
2725 document.getElementById("market-table").rows[(myRow + 1)].style.display = "table-row";
2726 document.getElementById("market-table").rows[(myRow + 1)].style.background = "linear-gradient(" + colorMyListedLowestCanRaisePrice + "," + colorLuminance(colorMyListedLowestCanRaisePrice, -0.1) + ")";
2727 }
2728 } else if (myListPosition > 0) {
2729 document.getElementById("market-table").rows[myRow].style.background = "linear-gradient(" + colorMyListedNotLowest + "," + colorLuminance(colorMyListedNotLowest, -0.1) + ")";
2730 document.getElementById("market-table").rows[myRow].style.display = "table-row";
2731 if (table.rows[firstRow].getAttribute("tedcolored") === null) {
2732 document.getElementById("market-table").rows[firstRow].style.background = "linear-gradient(" + colorLowestForMyListed + "," + colorLuminance(colorLowestForMyListed, -0.1) + ")";
2733 document.getElementById("market-table").rows[firstRow].style.display = "table-row";
2734 }
2735 } else console.log("error 12751");
2736 }
2737 }
2738 }
2739 window.highlightRow = function(row, display) {
2740 if (display) {
2741 row.style.boxShadow = "0 3px 5px -2px inset, 0 -3px 5px -3px inset";
2742 } else if (!display) {
2743 row.style.boxShadow = "";
2744 }
2745 };
2746
2747 function tradeHistory() {
2748 var tradeHistoryModal = document.createElement("div");
2749 tradeHistoryModal.setAttribute("id", "tradeHistoryModal");
2750 tradeHistoryModal.setAttribute("style", "display:none");
2751 var tradeHistoryModalBody = document.createElement("div");
2752 tradeHistoryModalBody.setAttribute("id", "tradeHistoryModalBody");
2753 tradeHistoryModalBody.setAttribute("style", "display:none;background-color:silver;width:80%;min-width:800px;max-width:1200px;margin-bottom:5px;");
2754 var thBuyCheckbox = document.createElement("input");
2755 thBuyCheckbox.setAttribute("type", "checkbox");
2756 thBuyCheckbox.setAttribute("id", "thBuyCheckbox");
2757 thBuyCheckbox.setAttribute("onclick", "generateTradeHistoryTable();document.getElementById('thSearch').focus();");
2758 thBuyCheckbox.setAttribute("checked", "true");
2759 var thBuyCheckboxLabel = document.createElement("label");
2760 thBuyCheckboxLabel.htmlFor = "thBuyCheckbox";
2761 thBuyCheckboxLabel.appendChild(document.createTextNode('Buy'));
2762 var thSellCheckbox = document.createElement("input");
2763 thSellCheckbox.setAttribute("type", "checkbox");
2764 thSellCheckbox.setAttribute("id", "thSellCheckbox");
2765 thSellCheckbox.setAttribute("onclick", "generateTradeHistoryTable();document.getElementById('thSearch').focus();");
2766 thSellCheckbox.setAttribute("checked", "true");
2767 var thSellCheckboxLabel = document.createElement("label");
2768 thSellCheckboxLabel.htmlFor = "thSellCheckbox";
2769 thSellCheckboxLabel.appendChild(document.createTextNode('Sell'));
2770 var thMax3Checkbox = document.createElement("input");
2771 thMax3Checkbox.setAttribute("type", "checkbox");
2772 thMax3Checkbox.setAttribute("id", "thMax3Checkbox");
2773 thMax3Checkbox.setAttribute("onclick", "generateTradeHistoryTable();document.getElementById('thSearch').focus();");
2774 thMax3Checkbox.setAttribute("checked", "true");
2775 var thMax3CheckboxLabel = document.createElement("label");
2776 thMax3CheckboxLabel.htmlFor = "thMax3Checkbox";
2777 thMax3CheckboxLabel.appendChild(document.createTextNode('Last 3'));
2778 var thSearch = document.createElement("input");
2779 thSearch.setAttribute("type", "text");
2780 thSearch.setAttribute("id", "thSearch");
2781 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");
2782 thSearch.setAttribute("onchange", "thSearchLogic();");
2783 thSearch.setAttribute("onkeypress", "this.onchange();");
2784 thSearch.setAttribute("onpaste", "this.onchange();");
2785 thSearch.setAttribute("oninput", "this.onchange();");
2786 thSearch.setAttribute("placeholder", "search by name...");
2787 var thClose = document.createElement("button");
2788 thClose.setAttribute("style", "float:right;height:18px;width:18px;border-radius:18px;cursor:pointer;background-color:#ff7878;margin:2px");
2789 thClose.setAttribute("onclick", "this.parentNode.style.display='none'");
2790 thClose.setAttribute("id", "thClose");
2791 var thTotalFlipProfit = document.createElement("span");
2792 thTotalFlipProfit.setAttribute("style", "float:left;margin:2px");
2793 thTotalFlipProfit.setAttribute("id", "thTotalFlipProfit");
2794 var tradeHistoryModalBodyTable = document.createElement("div");
2795 tradeHistoryModalBodyTable.setAttribute("id", "tradeHistoryModalBodyTable");
2796 tradeHistoryModalBodyTable.setAttribute("style", "background-color:silver;margin:auto;");
2797 document.getElementById("market-table").parentNode.prepend(tradeHistoryModalBody);
2798 document.getElementById("market-table").parentNode.prepend(document.createElement("br"));
2799 document.getElementById("tradeHistoryModalBody").append(thTotalFlipProfit);
2800 document.getElementById("tradeHistoryModalBody").append(thSearch);
2801 document.getElementById("tradeHistoryModalBody").append(thBuyCheckbox);
2802 document.getElementById("tradeHistoryModalBody").append(thBuyCheckboxLabel);
2803 document.getElementById("tradeHistoryModalBody").append(thSellCheckbox);
2804 document.getElementById("tradeHistoryModalBody").append(thSellCheckboxLabel);
2805 document.getElementById("tradeHistoryModalBody").append(thMax3Checkbox);
2806 document.getElementById("tradeHistoryModalBody").append(thMax3CheckboxLabel);
2807 document.getElementById("tradeHistoryModalBody").append(thClose);
2808 document.getElementById("tradeHistoryModalBody").append(tradeHistoryModalBodyTable);
2809 }
2810
2811 function alterMarketTable() {
2812 var i, a, b, s, maxCanBuy, totalPrice, arrToAppend;
2813 document.getElementById("market-table").rows[0].style.backgroundColor = "gold";
2814 if (document.getElementById("market-table").rows[1]) {
2815 for (i = 2; i < 4; i++) {
2816 while (document.getElementById("market-table").rows[0].childNodes[i].firstChild) {
2817 document.getElementById("market-table").rows[0].childNodes[i].removeChild(document.getElementById("market-table").rows[0].childNodes[i].firstChild);
2818 }
2819 }
2820 if (showMaxCanBuy) {
2821 var headerMaxCanBuy = document.createElement("div");
2822 headerMaxCanBuy.setAttribute("style", "float:left;padding-left:10px;");
2823 headerMaxCanBuy.append("maxCanBuy");
2824 document.getElementById("market-table").rows[0].childNodes[2].append(headerMaxCanBuy);
2825 }
2826 var headerAmount = document.createElement("div");
2827 headerAmount.setAttribute("style", "text-align:right;padding-right:10px;");
2828 headerAmount.append("Amount");
2829 document.getElementById("market-table").rows[0].childNodes[2].append(headerAmount);
2830 if (showTotalPrice) {
2831 var headerTotalPrice = document.createElement("div");
2832 headerTotalPrice.setAttribute("style", "float:right;padding-right:10px;");
2833 headerTotalPrice.append("Total maxCanBuy Price");
2834 document.getElementById("market-table").rows[0].childNodes[3].append(headerTotalPrice);
2835 }
2836 var headerPrice = document.createElement("div");
2837 headerPrice.setAttribute("style", "text-align:left;padding-left:10px;");
2838 headerPrice.append("Price each");
2839 document.getElementById("market-table").rows[0].childNodes[3].append(headerPrice);
2840 }
2841 if (document.getElementById("market-table").nextSibling.id != "tedMarketTable") {
2842 var tedMarketTable = document.createElement("table");
2843 tedMarketTable.setAttribute("id", "tedMarketTable");
2844 tedMarketTable.setAttribute("class", "market-table");
2845 tedMarketTable.setAttribute("style", "max-width:1200px;min-width:800px;");
2846 document.getElementById("market-table").style.display = "none";
2847 if (document.getElementById("market-table").nextSibling) {
2848 document.getElementById("market-table").parentNode.insertBefore(tedMarketTable, document.getElementById("market-table").nextSibling);
2849 } else {
2850 document.getElementById("market-table").parentNode.appendChild(document.getElementById("tedmarketTable"));
2851 }
2852 }
2853 if (document.getElementById("market-table").rows[0].childNodes[0]) document.getElementById("market-table").rows[0].childNodes[0].style.width = "25%";
2854 if (document.getElementById("market-table").rows[0].childNodes[1]) document.getElementById("market-table").rows[0].childNodes[1].style.width = "50px";
2855 //document.getElementById("tedMarketTable").rows[0].childNodes[2].style.width = "25%";
2856 //document.getElementById("tedMarketTable").rows[0].childNodes[3].style.width = "25%";
2857 if (document.getElementById("market-table").rows[0].childNodes[4]) document.getElementById("market-table").rows[0].childNodes[4].style.width = "10%";
2858 if (debugToConsole) {
2859 console.log(arrMarketItems);
2860 }
2861 for (i = 0; i < Object.keys(arrMarketItems).length; i++) {
2862 var itemName = Object.keys(arrMarketItems)[i];
2863 var marketItemName = getItemName(itemName);
2864 var length = arrMarketItems[itemName].length;
2865 var firstRow = arrMarketItems[itemName][0].row;
2866 var minPrice = arrMarketItems[itemName][0].price;
2867 if (length >= 2) {
2868 var secondRow = arrMarketItems[itemName][1].row;
2869 var secondPrice = arrMarketItems[itemName][1].price;
2870 }
2871 //fixes Name column for first market entry to add buttons without onclick to buy item
2872 document.getElementById("market-table").rows[firstRow].removeAttribute("onclick");
2873 for (b = 1; b < document.getElementById("market-table").rows[firstRow].childNodes.length; b++) {
2874 document.getElementById("market-table").rows[firstRow].childNodes[b].setAttribute("onclick", "openBuyFromPlayerMarketDialogue(this.parentNode);");
2875 }
2876 var btnMyItemListDiv = document.createElement("div");
2877 btnMyItemListDiv.setAttribute("style", "float:left;padding-left:15px");
2878 var btnMyItemList = document.createElement("BUTTON");
2879 btnMyItemList.setAttribute("onclick", "myItemListBtnAction(upToParentByTag(this,'tr').getAttribute('teditemname'),upToParentByTag(this,'tr').getAttribute('data-market-price'));");
2880 btnMyItemList.setAttribute("style", "background-color:#ffccff");
2881 btnMyItemList.setAttribute("title", "Add to Item List");
2882 var btnMyItemListText = document.createTextNode("+");
2883 btnMyItemList.appendChild(btnMyItemListText);
2884 btnMyItemListDiv.appendChild(btnMyItemList);
2885 var itemNameTextDiv = document.createElement("div");
2886 itemNameTextDiv.setAttribute("onclick", "openBuyFromPlayerMarketDialogue(upToParentByTag(this,'tr'));");
2887 var itemNameText = document.createElement("span");
2888 itemNameText.setAttribute("style", "vertical-align:middle;padding: 0 10px");
2889 itemNameText.append(marketItemName);
2890 itemNameTextDiv.append(itemNameText);
2891 while (document.getElementById("market-table").rows[firstRow].childNodes[0].firstChild) {
2892 document.getElementById("market-table").rows[firstRow].childNodes[0].removeChild(document.getElementById("market-table").rows[firstRow].childNodes[0].firstChild);
2893 }
2894 document.getElementById("market-table").rows[firstRow].childNodes[0].append(btnMyItemListDiv);
2895 document.getElementById("market-table").rows[firstRow].childNodes[0].append(itemNameTextDiv);
2896 for (a = 0; a < arrMarketItems[itemName].length; a++) {
2897 var row = arrMarketItems[itemName][a].row;
2898 var price = arrMarketItems[itemName][a].price;
2899 var amount = arrMarketItems[itemName][a].amount;
2900 var marketid = arrMarketItems[itemName][a].marketid;
2901 document.getElementById("market-table").rows[row].setAttribute("teditemname", itemName);
2902 document.getElementById("market-table").rows[row].setAttribute("teditemprice", price);
2903 document.getElementById("market-table").rows[row].setAttribute("teditemamount", amount);
2904 document.getElementById("market-table").rows[row].setAttribute("class", "tedMarketRow");
2905 document.getElementById("market-table").rows[row].setAttribute("onmouseover", "highlightRow(this, true);");
2906 document.getElementById("market-table").rows[row].setAttribute("onmouseout", "highlightRow(this, false);");
2907 for (b = 0; b < 4; b++) {
2908 if (b == 1) continue;
2909 if (a === 0 && b === 0) {
2910 document.getElementById("market-table").rows[row].childNodes[b].setAttribute("style", "text-align:right;");
2911 } else document.getElementById("market-table").rows[row].childNodes[b].setAttribute("style", "text-align:right;padding: 0 10px;");
2912 }
2913 if (smallMarketImages) {
2914 document.getElementById("market-table").childNodes[0].childNodes[row].childNodes[1].childNodes[0].style = "height: " + marketImageSize + "px;width: " + marketImageSize + "px;";
2915 }
2916 //Amount column
2917 maxCanBuy = Math.floor(coins / price);
2918 if (maxCanBuy >= amount) {
2919 maxCanBuy = amount;
2920 }
2921 if (showMaxCanBuy) {
2922 if (maxCanBuy < amount) {
2923 var maxCanBuyDiv = document.createElement("div");
2924 maxCanBuyDiv.setAttribute("style", "float:left;");
2925 maxCanBuyDiv.setAttribute("class", "maxCanBuyClass");
2926 maxCanBuyDiv.append(" (x" + numberWithCommas(maxCanBuy) + ") ");
2927 document.getElementById("market-table").rows[row].cells[2].prepend(maxCanBuyDiv);
2928 }
2929 }
2930 //price
2931 while (document.getElementById("market-table").rows[row].childNodes[3].firstChild) {
2932 document.getElementById("market-table").rows[row].childNodes[3].removeChild(document.getElementById("market-table").rows[row].childNodes[3].firstChild);
2933 }
2934 var itemPriceDiv = document.createElement("div");
2935 itemPriceDiv.setAttribute("style", "white-space:nowrap;float:left;");
2936 itemPriceDiv.setAttribute("class", "itemPriceClass");
2937 document.getElementById("market-table").rows[row].childNodes[3].append(itemPriceDiv);
2938 itemPriceDiv.append(numberWithCommas(upToParentByTag(itemPriceDiv, 'tr').getAttribute('teditemprice')));
2939 itemPriceDiv.append(coinImg.cloneNode());
2940 if (showTotalPrice) {
2941 if (amount > 1) {
2942 totalPrice = maxCanBuy * price;
2943 var totalPriceDiv = document.createElement("div");
2944 totalPriceDiv.setAttribute("style", "white-space:nowrap;float:right");
2945 totalPriceDiv.append(numberWithCommas(totalPrice));
2946 totalPriceDiv.append(coinImg.cloneNode());
2947 document.getElementById("market-table").rows[row].childNodes[3].append(totalPriceDiv);
2948 }
2949 }
2950 var oldOnclick = document.getElementById('market-table').rows[row].getAttribute('onclick');
2951 if (oldOnclick !== null) {
2952 document.getElementById("market-table").rows[row].setAttribute("onclick", oldOnclick + ";document.getElementById('buyFromMarket-input').value = " + maxCanBuy + ";");
2953 } else document.getElementById("market-table").rows[row].setAttribute("onclick", "document.getElementById('buyFromMarket-input').value = " + maxCanBuy + ";");
2954 if (notEnoughCoinsOpacity && maxCanBuy === 0) {
2955 document.getElementById("market-table").rows[row].style.opacity = "0.3";
2956 }
2957 if (document.getElementById("market-table").rows.length > 16) { // if we are searching all
2958 if (document.getElementById("market-table").rows[row].style.display === "") {
2959 document.getElementById("market-table").rows[row].style.display = "none";
2960 }
2961 if (i == Object.keys(arrMarketItems).length - 1 && a == length - 1) { //after last item in arrMarketItems
2962 quickCalcMain();
2963 }
2964 }
2965 } // end of for (a..
2966 } // end of for i
2967 colorMarketTable();
2968 // sort market table
2969 arrToAppend = [];
2970 for (s = 0; s < arrSortItemsList.length; s++) {
2971 if (arrMarketItems[itemNameFix(arrSortItemsList[s])]) {
2972 for (i = 0; i < arrMarketItems[itemNameFix(arrSortItemsList[s])].length; i++) {
2973 arrToAppend.push(document.getElementById("market-table").rows[arrMarketItems[itemNameFix(arrSortItemsList[s])][i].row]);
2974 }
2975 }
2976 }
2977 for (i = 0; i < arrToAppend.length; i++) {
2978 document.getElementById("market-table").append(arrToAppend[i]);
2979 }
2980 // append to tedMarketTable
2981 arrToAppend = [];
2982 for (i = 0; i < document.getElementById("market-table").childNodes.length; i++) {
2983 arrToAppend.push(document.getElementById("market-table").childNodes[i]);
2984 }
2985 while (document.getElementById("tedMarketTable").firstChild) {
2986 document.getElementById("tedMarketTable").removeChild(document.getElementById("tedMarketTable").firstChild);
2987 }
2988 for (i = 0; i < arrToAppend.length; i++) {
2989 document.getElementById("tedMarketTable").append(arrToAppend[i]);
2990 }
2991 // modify text widths perfectly, thanks florb you fucking god
2992 let widestMaxCanBuy = Array.prototype.slice.call(document.querySelectorAll(".maxCanBuyClass")).reduce((acc, val) => {
2993 return (acc > val.offsetWidth ? acc : val.offsetWidth);
2994 }, 0);
2995 Array.prototype.slice.call(document.querySelectorAll(".maxCanBuyClass")).forEach(e => {
2996 e.style.width = (widestMaxCanBuy) + "px";
2997 });
2998 let widestItemPrice = Array.prototype.slice.call(document.querySelectorAll(".itemPriceClass")).reduce((acc, val) => {
2999 return (acc > val.offsetWidth ? acc : val.offsetWidth);
3000 }, 0);
3001 Array.prototype.slice.call(document.querySelectorAll(".itemPriceClass")).forEach(e => {
3002 e.style.width = (widestItemPrice) + "px";
3003 });
3004 }
3005
3006 function updateMarketSlots() {
3007 for (let i = 0; i < arrMarketSlots.length; i++) { //arrMarketSlots format: [marketid, in use?]
3008 arrMarketSlots[i][0] = window["marketSlot" + (i + 1)];
3009 if (document.getElementById("market-slot-" + (i + 1) + "-free").style.display === "") {
3010 arrMarketSlots[i][1] = false;
3011 } else arrMarketSlots[i][1] = true;
3012 if (debugToConsole) {
3013 console.log("Market slot: " + (i + 1), arrMarketSlots[i][0], arrMarketSlots[i][1]);
3014 }
3015 }
3016 }
3017
3018 function marketReloaded() {
3019 if (typeof(document.getElementById("market-table").rows[0]) != "undefined" && document.getElementById("market-table").rows[0] !== null) {
3020 // exists
3021 if (document.getElementById("market-table").rows[0].style.backgroundColor != "gold") {
3022 updateMarketSlots();
3023 getMarketItems();
3024 addItemTooltips();
3025 alterMarketTable();
3026 }
3027 }
3028 }
3029
3030 function marketMain() {
3031 if (marketOn === true) {
3032 marketInterval = setInterval(marketReloaded, 0);
3033 }
3034 }
3035
3036 function marketButtonClickAction() {
3037 if (marketOn === true) {
3038 marketOn = false;
3039 clearInterval(marketInterval);
3040 document.getElementById("market-table").style.display = "";
3041 if (document.getElementById("tedMarketTable")) {
3042 document.getElementById("tedMarketTable").style.display = "none";
3043 }
3044 document.getElementById("marketButton").innerHTML = "Ted's Market: OFF";
3045 } else if (marketOn === false) {
3046 marketOn = true;
3047 document.getElementById("market-table").style.display = "none";
3048 if (document.getElementById("tedMarketTable")) {
3049 document.getElementById("tedMarketTable").style.display = "";
3050 }
3051 marketMain();
3052 document.getElementById("marketButton").innerHTML = "Ted's Market: ON";
3053 }
3054 }
3055
3056 function getRowFromMarketId(marketId) {
3057 for (var i = 0; i < Object.keys(arrMarketItems).length; i++) {
3058 let itemName = Object.keys(arrMarketItems)[i];
3059 for (var a = 0; a < arrMarketItems[itemName].length; a++) {
3060 if (arrMarketItems[itemName][a].marketid == marketId) {
3061 return arrMarketItems[itemName][a].marketid;
3062 }
3063 }
3064 }
3065 return undefined;
3066 }
3067
3068 function getMarketItemNameFromMarketId(marketId) {
3069 for (var i = 0; i < Object.keys(arrMarketItems).length; i++) {
3070 let itemName = Object.keys(arrMarketItems)[i];
3071 for (var a = 0; a < arrMarketItems[itemName].length; a++) {
3072 if (arrMarketItems[itemName][a].marketid == marketId) {
3073 return getItemName(itemName);
3074 }
3075 }
3076 }
3077 return undefined;
3078 }
3079
3080 function refreshMarketAfterBuyingItem() {
3081 //refresh market after final confirmation when buying item
3082 if (document.getElementById("dialogue-confirm-cmd").value.substring(0, 10) != "MARKET_BUY" && document.getElementById("dialogue-confirm-yes").getAttribute("onclick") != oldDialogueConfirmYesOnclick) {
3083 document.getElementById("dialogue-confirm-yes").setAttribute("onclick", oldDialogueConfirmYesOnclick);
3084 }
3085 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") {
3086 document.getElementById("dialogue-confirm-yes").value = "Confirm Purchase "; //break infinite loop
3087 if (document.getElementById("tedMarketTable").rows.length > 16) { // if we searched all
3088 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);") {
3089 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);");
3090 }
3091 } else if (document.getElementById("tedMarketTable").rows.length <= 16) { // if we searched for a single item
3092 var marketBuyString = document.getElementById('dialogue-confirm-cmd').value;
3093 var marketId = marketBuyString.substring(marketBuyString.lastIndexOf("=") + 1, marketBuyString.lastIndexOf("~"));
3094 var itemName = getMarketItemNameFromMarketId(marketId);
3095 if (typeof(itemName) != "undefined") {
3096 refreshMarketAfterBuyingItem_itemName = itemNameFix(itemName);
3097 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);") {
3098 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);");
3099 }
3100 }
3101 }
3102 }
3103 }
3104 window.modifyKeepList = function(chosenItem) {
3105 var keepAmount = window[chosenItem] - numberWithoutCommas(document.getElementById("chosenpostitem-amount").value);
3106 if (keepAmount < 0) keepAmount = 0;
3107 if (tedStoredSettings.tedTradableItems.itemList[chosenItem].keepAmount != keepAmount) {
3108 tedStoredSettings.tedTradableItems.itemList[chosenItem].keepAmount = keepAmount;
3109 updateVariables();
3110 }
3111 };
3112 window.fixCpiNumbers = function() {
3113 document.getElementById("chosenpostitem-amount").value = numberWithoutCommas(document.getElementById("chosenpostitem-amount").value);
3114 document.getElementById("chosenpostitem-price").value = numberWithoutCommas(document.getElementById("chosenpostitem-price").value);
3115 };
3116 window.keepAmountSetMax = function() {
3117 document.getElementById("chosenpostitem-amount").value = numberWithCommas(window[document.getElementById("chosenpostitem-itemName").value]);
3118 };
3119
3120 function dialogue_market_chosenpostitem() {
3121 if (document.getElementById("dialogue-market-chosenpostitem").parentNode.style.display == "none") {
3122 cpi_itemName = "";
3123 }
3124 if (document.getElementById("dialogue-market-chosenpostitem").parentNode.style.display != "none") {
3125 if (document.getElementById("chosenpostitem-price").value === "" && document.getElementById("chosenpostitem-itemName").value != cpi_itemName) {
3126 cpi_itemName = document.getElementById("chosenpostitem-itemName").value;
3127 var currentPrice = Math.ceil((numberWithoutCommas(document.getElementById("chosenpostitem-upper").innerHTML) + numberWithoutCommas(document.getElementById("chosenpostitem-lower").innerHTML)) / 1.9);
3128 if (autoUndercut) {
3129 if (currentPrice > matchLowestPriceAt) {
3130 document.getElementById("chosenpostitem-price").value = (currentPrice - undercutBy);
3131 } else {
3132 let item = itemNameFix(lastBrowsedItem).toLowerCase();
3133 if (arrMarketItems[item] && arrMarketItems[item][0]) {
3134 let count = 0,
3135 itemPrice = 0;
3136 for (let i = 0; i < arrMarketItems[item].length; i++) {
3137 count++;
3138 itemPrice += arrMarketItems[item][i].price;
3139 }
3140 document.getElementById("chosenpostitem-price").value = Math.ceil(itemPrice / count);
3141 } else document.getElementById("chosenpostitem-price").value = currentPrice;
3142 }
3143 }
3144 if (useUndercutBox) {
3145 var undercutBoxTextInner = "Undercut " + numberWithCommas(currentPrice) + " by<br><br>";
3146 if (undercutBoxText.innerHTML != undercutBoxTextInner) {
3147 undercutBoxText.innerHTML = undercutBoxTextInner;
3148 }
3149 }
3150 if (useKeepAmount) {
3151 var cpiPostString = document.getElementById("cpi-post").getAttribute("onclick");
3152 if (document.getElementById("chosenpostitem-itemName").value !== "") {
3153 keepAmountChosenItem = document.getElementById("chosenpostitem-itemName").value;
3154 var keepAmount = tedStoredSettings.tedTradableItems.itemList[keepAmountChosenItem].keepAmount;
3155 var amountToChangeTo = window[keepAmountChosenItem] - keepAmount;
3156 if (amountToChangeTo < 0) amountToChangeTo = 0;
3157 document.getElementById("chosenpostitem-amount").value = amountToChangeTo;
3158 if (keepAmount !== undefined) {
3159 var keepAmountTextInner = "<br>Keep: " + numberWithCommas(keepAmount) + " | Total: " + numberWithCommas(window[keepAmountChosenItem]) + " | <input type='button' value='All' onclick='keepAmountSetMax();'/>";
3160 if (keepAmountText.innerHTML != keepAmountTextInner) {
3161 keepAmountText.innerHTML = keepAmountTextInner;
3162 }
3163 }
3164 if (!cpiPostString.includes("modifyKeepList")) {
3165 cpiPostString = "modifyKeepList('" + keepAmountChosenItem + "');" + cpiPostString;
3166 document.getElementById("cpi-post").setAttribute("onclick", cpiPostString);
3167 }
3168 let cpiCurrentModify = cpiPostString.substring(cpiPostString.indexOf("modifyKeepList"), cpiPostString.indexOf(";") + 1);
3169 let cpiExpectedModify = "modifyKeepList('" + keepAmountChosenItem + "');";
3170 if (cpiCurrentModify != cpiExpectedModify) {
3171 cpiPostString = cpiPostString.replace(cpiCurrentModify, cpiExpectedModify);
3172 document.getElementById("cpi-post").setAttribute("onclick", cpiPostString);
3173 }
3174 }
3175 }
3176 cpi_itemName = document.getElementById("chosenpostitem-itemName").value;
3177 let itemPrice = numberWithCommas(document.getElementById("chosenpostitem-price").value);
3178 if (document.getElementById("chosenpostitem-price").value != itemPrice) {
3179 document.getElementById("chosenpostitem-price").value = itemPrice;
3180 }
3181 let itemAmount = numberWithCommas(document.getElementById("chosenpostitem-amount").value);
3182 if (document.getElementById("chosenpostitem-amount").value != itemAmount) {
3183 document.getElementById("chosenpostitem-amount").value = itemAmount;
3184 }
3185 }
3186 let totalPrice = parseInt(numberWithoutCommas(document.getElementById("chosenpostitem-amount").value)) * parseInt(numberWithoutCommas(document.getElementById("chosenpostitem-price").value));
3187 if (isNaN(totalPrice)) totalPrice = "";
3188 if (cpi_totalPrice != totalPrice) {
3189 chosenpostitem_total();
3190 }
3191 } else if (document.getElementById("dialogue-market-chosenpostitem").parentNode.style.display == "none") {
3192 if (cpi_itemName !== "") {
3193 cpi_itemName = "";
3194 }
3195 if (document.getElementById("chosenpostitem-price").value !== "") {
3196 document.getElementById("chosenpostitem-price").value = "";
3197 }
3198 if (document.getElementById("chosenpostitem-itemName").value !== "") {
3199 document.getElementById("chosenpostitem-itemName").value = "";
3200 }
3201 }
3202 }
3203
3204 function market_slots() {
3205 for (let i = 1; i <= arrMarketSlots.length; i++) {
3206 if (parseInt(document.getElementById("market-slot-" + i + "-collect").innerHTML) > 0 && ms_collect_repeat[i]) {
3207 ms_collect_repeat[i] = false;
3208 document.getElementById("market-slot-" + i + "-collect").parentNode.style.boxShadow = "0 0 30px 3px rgba(255, 0, 0, 1) inset";
3209 document.getElementById("market-slot-" + i + "-collect").parentNode.style.transition = "box-shadow 0.5s ease-in-out";
3210 setTimeout(function() {
3211 document.getElementById("market-slot-" + i + "-collect").parentNode.style.boxShadow = "0 0 30px 3px rgba(255, 0, 0, 0) inset";
3212 document.getElementById("market-slot-" + i + "-collect").parentNode.style.transition = "box-shadow 0.5s ease-in-out";
3213 setTimeout(function() {
3214 ms_collect_repeat[i] = true;
3215 }, 500);
3216 }, 500);
3217 }
3218 let marketSlotPrice = document.getElementById("market-slot-" + i + "-price").innerHTML;
3219 if (marketSlotPrice.includes(" ")) {
3220 marketSlotPrice = document.getElementById("market-slot-" + i + "-price").innerHTML.substr(0, document.getElementById("market-slot-" + i + "-price").innerHTML.indexOf(" "));
3221 }
3222 if (document.getElementById("market-slot-" + i + "-price").innerHTML != numberWithCommas(marketSlotPrice)) {
3223 document.getElementById("market-slot-" + i + "-price").innerHTML = numberWithCommas(marketSlotPrice);
3224 }
3225 if (document.getElementById("market-slot-" + i + "-amount").innerHTML != numberWithCommas(document.getElementById("market-slot-" + i + "-amount").innerHTML)) {
3226 document.getElementById("market-slot-" + i + "-amount").innerHTML = numberWithCommas(document.getElementById("market-slot-" + i + "-amount").innerHTML);
3227 }
3228 if (document.getElementById("market-slot-" + i + "-collect").innerHTML != numberWithCommas(document.getElementById("market-slot-" + i + "-collect").innerHTML)) {
3229 document.getElementById("market-slot-" + i + "-collect").innerHTML = numberWithCommas(document.getElementById("market-slot-" + i + "-collect").innerHTML);
3230 }
3231 }
3232 }
3233
3234 function brewingMaxPlaceholder() {
3235 if (brewingPlaceholder) {
3236 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 !== "") {
3237 ph_brewing_repeat = false;
3238 ph_brewing_cur_potion = document.getElementById('dialogue-potion-chosen').value;
3239 document.getElementById('dialogue-brewing-input').value = "";
3240 var placeholderBrewing, vialRequired, placeholderBrewingText;
3241 for (var i = 0; i < brewingRecipes[ph_brewing_cur_potion].recipe.length; i++) {
3242 var maxAmount = Math.floor(window[brewingRecipes[ph_brewing_cur_potion].recipe[i]] / brewingRecipes[ph_brewing_cur_potion].recipeCost[i]);
3243 if (i === 0 || maxAmount < placeholderBrewing) {
3244 placeholderBrewing = maxAmount;
3245 }
3246 }
3247 let arrVials = ["stardustPotion", "treePotion", "seedPotion", "smeltingPotion", "oilPotion", "barPotion", "superStardustPotion", "combatCooldownPotion", "farmingSpeedPotion"];
3248 let arrLargeVials = ["stargemPotion", "superOilPotion", "stardustCrystalPotion", "superTreePotion", "superCombatCooldownPotion"];
3249 let arrHugeVials = ["superCompostPotion"];
3250 if (arrVials.indexOf(ph_brewing_cur_potion) >= 0) {
3251 vialRequired = "vialOfWater";
3252 } else if (arrLargeVials.indexOf(ph_brewing_cur_potion) >= 0) {
3253 vialRequired = "largeVialOfWater";
3254 } else if (arrHugeVials.indexOf(ph_brewing_cur_potion) >= 0) {
3255 vialRequired = "hugeVialOfWater";
3256 } else vialRequired = "error";
3257 if (vialRequired != "error" && Math.floor(window[vialRequired] / placeholderBrewing) < 1) {
3258 let placeholderBrewing2 = window[vialRequired];
3259 placeholderBrewingText = "max: " + placeholderBrewing2 + ", need: +" + (placeholderBrewing - placeholderBrewing2) + " vials";
3260 } else placeholderBrewingText = "max: " + placeholderBrewing;
3261 if (placeholderBrewingText != document.getElementById("dialogue-brewing-input").getAttribute("placeholder")) {
3262 document.getElementById("dialogue-brewing-input").setAttribute("placeholder", placeholderBrewingText);
3263 }
3264 } else if (document.getElementById("dialogue-brewing").parentNode.style.display == "none") {
3265 ph_brewing_repeat = true;
3266 }
3267 }
3268 }
3269
3270 function craftingVialMaxPlaceholder() {
3271 if (craftingVialPlaceholder) {
3272 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 !== "") {
3273 ph_vial_repeat = false;
3274 ph_vial_cur_vial = document.getElementById("dialogue-multicraft-chosen").value;
3275 document.getElementById('dialogue-multicraft-input').value = "";
3276 var glassRequired;
3277 if (ph_vial_cur_vial == "vialOfWater") {
3278 glassRequired = document.getElementById("recipe-cost-vialOfWater-0").innerHTML;
3279 } else if (ph_vial_cur_vial == "largeVialOfWater") {
3280 glassRequired = document.getElementById("recipe-cost-largeVialOfWater-0").innerHTML;
3281 } else if (ph_vial_cur_vial == "hugeVialOfWater") {
3282 glassRequired = document.getElementById("recipe-cost-hugeVialOfWater-0").innerHTML;
3283 }
3284 var maxAmount = Math.floor(glass / glassRequired);
3285 var placeholderVialText = "max: " + maxAmount;
3286 if (placeholderVialText != document.getElementById("dialogue-multicraft-input").getAttribute("placeholder")) {
3287 document.getElementById("dialogue-multicraft-input").setAttribute("placeholder", placeholderVialText);
3288 }
3289 } else if (document.getElementById("dialogue-multicraft").parentNode.style.display == "none") {
3290 ph_vial_repeat = true;
3291 }
3292 }
3293 }
3294
3295 function getLowestMarketPrice(item) {
3296 item = itemNameFix(item);
3297 if (arrMarketItems[item]) { // if we have seen item
3298 return arrMarketItems[item][0].price;
3299 }
3300 return 0;
3301 }
3302 window.resetOreAverage = function() {
3303 currentOreReset = true;
3304 };
3305
3306 function oreAverageMain() {
3307 if (oreAverageOn && oreAverageElement.style.display !== "") {
3308 oreAverageElement.style.display = "";
3309 } else if (!oreAverageOn && oreAverageElement.style.display != "none") {
3310 oreAverageElement.style.display = "none";
3311 }
3312 var i, keys = Object.keys(minedOres);
3313 if (currentOreReset) {
3314 keys.forEach((key) => {
3315 minedOres[key].startAmount = window[key];
3316 });
3317 oreAverageStartTicks = playtime;
3318 currentOreReset = false;
3319 }
3320 oreAverageElapsedTicks = playtime - oreAverageStartTicks;
3321 var oreAverageInnerText = "";
3322 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>";
3323 oreAverageInnerText += "<button onclick='resetOreAverage();'>Reset</button><br><br>";
3324 oreAverageInnerText += "<span style='color:white'>Elapsed ticks: " + oreAverageElapsedTicks + "<br><br>";
3325 oreAverageInnerText += "Current config:</span><br><br>";
3326 oreAverageInnerText += "<table style='text-align:right;color:white;width:16.66%;border-style:solid;border-color:white;border-width:1px;'>";
3327 oreAverageInnerText += "<tr><td>miners:</td><td>" + miner + "</td></tr>";
3328 oreAverageInnerText += "<tr><td>drills:</td><td>" + drillsOn + "</td></tr>";
3329 oreAverageInnerText += "<tr><td>crushers:</td><td>" + crushersOn + "</td></tr>";
3330 oreAverageInnerText += "<tr><td>giant drills:</td><td>" + giantDrillsOn + "</td></tr>";
3331 oreAverageInnerText += "<tr><td>excavators:</td><td>" + excavatorsOn + "</td></tr>";
3332 oreAverageInnerText += "<tr><td>giant excavators:</td><td>" + giantExcavatorsOn + "</td></tr>";
3333 oreAverageInnerText += "</table><br>";
3334 oreAverageInnerText += "<table class='top-bar' style='text-align:right'>";
3335 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>";
3336 for (i = 6; i < Object.keys(minedOres).length; i++) {
3337 if (Object.keys(arrMarketItems).length > 1) {
3338 minedOres[Object.keys(minedOres)[i]].price = getLowestMarketPrice(Object.keys(minedOres)[i]); // set high tier ore price
3339 }
3340 }
3341 var oreTickTotal = 0,
3342 coinTickTotal = 0,
3343 oreDayTotal = 0,
3344 coinDayTotal = 0,
3345 oresMinedTotal = 0;
3346 keys.forEach((key) => {
3347 minedOres[key].currentAmount = window[key];
3348 var oreName = key;
3349 var orePrice = minedOres[key].price;
3350 var oresMined = minedOres[key].currentAmount - minedOres[key].startAmount;
3351 minedOres[key].oreTick = ((minedOres[key].currentAmount - minedOres[key].startAmount) / oreAverageElapsedTicks);
3352 minedOres[key].coinTick = (minedOres[key].oreTick * minedOres[key].price);
3353 minedOres[key].oreDay = (((minedOres[key].currentAmount - minedOres[key].startAmount) / oreAverageElapsedTicks) * 86400);
3354 minedOres[key].coinDay = (minedOres[key].coinTick * 86400);
3355 oreAverageInnerText += "<tr><td>" + oreName + "</td>";
3356 oreAverageInnerText += "<td>" + numberWithCommas(orePrice) + "</td>";
3357 oreAverageInnerText += "<td>" + numberWithCommas(oresMined) + "</td>";
3358 if (Object.keys(minedOres).indexOf(key) <= 7) { // if ore is marble or lower
3359 oreAverageInnerText += "<td>" + minedOres[key].oreTick.toFixed(3) + "</td>";
3360 } else oreAverageInnerText += "<td>" + Number(minedOres[key].oreTick).toFixed(6) + "</td>";
3361 oreAverageInnerText += "<td>" + minedOres[key].coinTick.toFixed(2) + "</td>";
3362 if (Object.keys(minedOres).indexOf(key) <= 7) { // if ore is marble or lower
3363 oreAverageInnerText += "<td>" + numberWithCommas(parseInt(minedOres[key].oreDay)) + "</td>";
3364 } else oreAverageInnerText += "<td>" + numberWithCommas(Number(minedOres[key].oreDay).toFixed(2)) + "</td>";
3365 oreAverageInnerText += "<td>" + numberWithCommas(parseInt(minedOres[key].coinDay)) + "</td></tr>";
3366 oresMinedTotal += parseInt(oresMined);
3367 oreTickTotal += parseFloat(minedOres[key].oreTick.toFixed(2));
3368 coinTickTotal += parseFloat(minedOres[key].coinTick.toFixed(2));
3369 oreDayTotal += parseInt(minedOres[key].oreDay);
3370 coinDayTotal += parseInt(minedOres[key].coinDay);
3371 });
3372 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>";
3373 oreAverageInnerText += "</table>";
3374 oreAverageElement.innerHTML = oreAverageInnerText;
3375 }
3376 window.bfmCommaFix = function() {
3377 document.getElementById('buyFromMarket-input').value = numberWithoutCommas(document.getElementById('buyFromMarket-input').value);
3378 document.getElementById('buyFromMarket-price').innerHTML = numberWithoutCommas(document.getElementById('buyFromMarket-price').innerHTML);
3379 };
3380
3381 function dialogue_buyFromMarket() {
3382 //comma fix for price each
3383 if (document.getElementById("dialogue-buyFromMarket").parentNode.style.display === "" && document.getElementById("buyFromMarket-price").innerHTML != numberWithCommas(document.getElementById("buyFromMarket-price").innerHTML)) {
3384 document.getElementById("buyFromMarket-price").innerHTML = numberWithCommas(document.getElementById("buyFromMarket-price").innerHTML);
3385 }
3386 //comma fix for enter amount
3387 if (document.getElementById('buyFromMarket-input').value != numberWithCommas(document.getElementById('buyFromMarket-input').value)) {
3388 document.getElementById('buyFromMarket-input').value = numberWithCommas(document.getElementById('buyFromMarket-input').value);
3389 }
3390 //set price to no commas onclick Buy
3391 var bfmBuyString = document.getElementById('buyFromMarket-buy').getAttribute("onclick");
3392 if (!bfmBuyString.includes("bfmCommaFix();")) {
3393 bfmBuyString = "bfmCommaFix();" + bfmBuyString;
3394 document.getElementById("buyFromMarket-buy").setAttribute("onclick", bfmBuyString);
3395 }
3396 //change Are you sure you want to spend... price to comma format
3397 if (document.getElementById("dialogue-confirm-cmd").parentNode.parentNode.style.display === "" && document.getElementById("dialogue-confirm-cmd").value.includes("MARKET_BUY=")) {
3398 let priceString = document.getElementById("dialogue-confirm-text").innerHTML;
3399 let price = priceString.substring(priceString.indexOf("<img src=\"images/coins.png\" class=\"image-icon-20\">") + 51, priceString.indexOf(" on this purchase"));
3400 if (document.getElementById("dialogue-confirm-text").innerHTML != priceString.replace(price, numberWithCommas(price))) {
3401 document.getElementById("dialogue-confirm-text").innerHTML = priceString.replace(price, numberWithCommas(price));
3402 }
3403 }
3404 }
3405
3406 function persistentInterval() {
3407
3408 if (marketOn) {
3409 //dh2fixed input box type=number fix
3410 if (document.getElementById("chosenpostitem-amount").getAttribute("type") != "text") {
3411 document.getElementById("chosenpostitem-amount").setAttribute("type","text");
3412 }
3413 if (document.getElementById("chosenpostitem-price").getAttribute("type") != "text") {
3414 document.getElementById("chosenpostitem-price").setAttribute("type","text");
3415 }
3416 if (nextTick()) {
3417 oreAverageMain();
3418 /*
3419 if (treasureMap > 0 && document.getElementById("mapSpan").style.display !== "") {
3420 document.getElementById("mapSpan").style.display = "";
3421 } else if (treasureMap === 0 && document.getElementById("mapSpan").style.display != "none") {
3422 document.getElementById("mapSpan").style.display = "none";
3423 }
3424*/
3425 //marketCancelCooldownSlots overwrite Cancel with countdown
3426 let arrMarketCancelCooldownSlots = [marketCancelCooldownSlot1, marketCancelCooldownSlot2, marketCancelCooldownSlot3];
3427 for (let i = 0; i < arrMarketCancelCooldownSlots.length; i++) {
3428 if (arrMarketCancelCooldownSlots[i] === 0) {
3429 if (document.getElementById("market-slot-" + (i + 1) + "-cancel-btn").innerHTML != "Cancel") {
3430 document.getElementById("market-slot-" + (i + 1) + "-cancel-btn").innerHTML = "Cancel";
3431 }
3432 } else if (document.getElementById("market-slot-" + (i + 1) + "-cancel-btn").innerHTML != arrMarketCancelCooldownSlots[i]) {
3433 document.getElementById("market-slot-" + (i + 1) + "-cancel-btn").innerHTML = arrMarketCancelCooldownSlots[i];
3434 }
3435 }
3436 }
3437 dialogue_market_chosenpostitem();
3438 dialogue_buyFromMarket();
3439 refreshMarketAfterBuyingItem();
3440 market_slots();
3441 brewingMaxPlaceholder();
3442 craftingVialMaxPlaceholder();
3443 }
3444 if (displayNotificationTreasureMap && treasureMap > 0 && document.getElementById("tedmarket-notif-map").style.display != "inline-block") {
3445 document.getElementById("tedmarket-notif-map").style.display = "inline-block";
3446 } else if (treasureMap === 0 && document.getElementById("tedmarket-notif-map").style.display != "none") {
3447 document.getElementById("tedmarket-notif-map").style.display = "none";
3448 }
3449 if (allowedBrowserNotifications && notifyWindChange) {
3450 if (windLastCheck == -1) {
3451 windLastCheck = sailBoatWindGlobal;
3452 } else if (windLastCheck != sailBoatWindGlobal) {
3453 windLastCheck = sailBoatWindGlobal;
3454 let windLevel = "";
3455 switch (windLastCheck) {
3456 case 0:
3457 windLevel = "no wind";
3458 break;
3459 case 1:
3460 windLevel = "low wind";
3461 break;
3462 case 2:
3463 windLevel = "medium wind";
3464 break;
3465 case 3:
3466 windLevel = "high wind";
3467 break;
3468 case 4:
3469 windLevel = "very high wind";
3470 break;
3471 }
3472 new Notification("The wind level has changed!", {
3473 body: "The wind level is now: " + windLevel,
3474 icon: "images/sailBoat.png"
3475 });
3476 }
3477 }
3478
3479 }
3480 window.setLastBrowsedItem = function(item) {
3481 lastBrowsedItem = item;
3482 };
3483
3484 function addLastBrowsedItemOnclick() {
3485 for (var i = 0; i < document.getElementById("dialogue-market-items-area").childNodes.length; i++) {
3486 for (var j = 0; j < document.getElementById("dialogue-market-items-area").childNodes[i].children.length; j++) {
3487 var oldOnclick = document.getElementById("dialogue-market-items-area").childNodes[i].children[j].getAttribute("onclick");
3488 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);
3489 }
3490 }
3491 }
3492 var objEnergy = {
3493 shrimp: 50,
3494 sardine: 400,
3495 tuna: 1000,
3496 swordfish: 7500,
3497 shark: 20000,
3498 };
3499 var objHeat = {
3500 logs: 1,
3501 oakLogs: 2,
3502 willowLogs: 5,
3503 mapleLogs: 10,
3504 stardustLogs: 20,
3505 strangeLogs: 30,
3506 };
3507 var objBonemeal = {
3508 bones: 1,
3509 ashes: 2,
3510 iceBones: 3,
3511 };
3512
3513 function otherSettingsRunOnce() {
3514 //send market data to developer
3515 addWebsocketHook();
3516 //press enter in input box when buying item to progress dialogue and go to confirm
3517 document.getElementById("buyFromMarket-input").setAttribute("onkeydown", "if (event.keyCode == 13) { document.getElementById('buyFromMarket-buy').click(); }");
3518 //add undercut buttons to dialogue-market-chosenpostitem
3519 if (useUndercutBox) {
3520 var arrUndercut = ["2", "0.25%", "0.5%", "1%", "2%", "5%", "10%", "cheapest", "min", "match", "max"];
3521 var undercutBox = document.createElement("div");
3522 undercutBox.setAttribute("class", "basic-smallbox");
3523 undercutBox.setAttribute("id", "undercutBox");
3524 undercutBox.setAttribute("style", "text-align:center");
3525 document.getElementById("dialogue-market-chosenpostitem").insertBefore(undercutBox, document.getElementById("dialogue-market-chosenpostitem").getElementsByTagName("span")[0].nextSibling);
3526 document.getElementById("dialogue-market-chosenpostitem").insertBefore(document.createElement("br"), document.getElementById("dialogue-market-chosenpostitem").getElementsByTagName("span")[0].nextSibling);
3527 document.getElementById("dialogue-market-chosenpostitem").insertBefore(document.createElement("br"), document.getElementById("dialogue-market-chosenpostitem").getElementsByTagName("span")[0].nextSibling);
3528 window.setUndercut = function(undercutAmount, btn) {
3529 var undercutValue;
3530 var currentPrice = Math.ceil((numberWithoutCommas(document.getElementById("chosenpostitem-upper").innerHTML) + numberWithoutCommas(document.getElementById("chosenpostitem-lower").innerHTML)) / 1.9);
3531 if (undercutAmount == "cheapest") {
3532 let itemName = itemNameFix(lastBrowsedItem);
3533 var cheapest, price = null;
3534 if (objEnergy[itemName]) {
3535 for (let key in objEnergy) {
3536 if (Object.keys(arrMarketItems).length <= 1) {
3537 document.getElementById("chosenpostitem-price").value = "Search all first";
3538 break;
3539 }
3540 if (arrMarketItems[key] && arrMarketItems[key][0].price) {
3541 if (arrMarketItems[key][0].price / objEnergy[key] < cheapest || typeof(cheapest) == "undefined") {
3542 cheapest = arrMarketItems[key][0].price / objEnergy[key];
3543 price = Math.ceil(cheapest * objEnergy[itemName]) - 2;
3544 }
3545 }
3546 }
3547 } else if (objHeat[itemName]) {
3548 var avgSdValue, avgFragValue;
3549 for (let key in objHeat) {
3550 if (Object.keys(arrMarketItems).length <= 1) {
3551 document.getElementById("chosenpostitem-price").value = "Search all first";
3552 break;
3553 }
3554 if (arrMarketItems[key] && arrMarketItems[key][0].price && key == "stardustLogs") {
3555 if (arrMarketItems.stardust[0] && arrMarketItems.stardustLogs[0]) {
3556 var stardustPrice;
3557 if (arrMarketItems.stardust && arrMarketItems.stardust[0]) {
3558 let count = 0,
3559 itemPrice = 0;
3560 for (let i = 0; i < arrMarketItems.stardust.length; i++) {
3561 count++;
3562 itemPrice += arrMarketItems.stardust[i].price;
3563 }
3564 stardustPrice = Math.ceil(itemPrice / count);
3565 } else continue;
3566 avgSdValue = ((2500 + 10000) / 2) * (stardustPrice - 1); //sd value per log at average-1 when selling
3567 let sdLogHeatCost = Math.ceil(((arrMarketItems.stardustLogs[0].price - avgSdValue) / objHeat.stardustLogs));
3568 if (sdLogHeatCost < cheapest) {
3569 cheapest = sdLogHeatCost;
3570 }
3571 }
3572 }else if (arrMarketItems[key] && arrMarketItems[key][0].price) {
3573 if (arrMarketItems[key][0].price / objHeat[key] < cheapest || typeof(cheapest) == "undefined") {
3574 cheapest = arrMarketItems[key][0].price / objHeat[key];
3575 }
3576 }
3577 }
3578 if (typeof(cheapest) !== "undefined") {
3579 if (itemName == "stardustLogs") {
3580 if (arrMarketItems.stardustLogs && arrMarketItems.stardustLogs[0].price) {
3581 price = (cheapest - 1) * objHeat[itemName] + avgSdValue;
3582 }
3583 } else {
3584 price = Math.ceil(cheapest * objHeat[itemName]) - 2;
3585 }
3586 }
3587 } else if (objBonemeal[itemName]) {
3588 for (let key in objBonemeal) {
3589 if (Object.keys(arrMarketItems).length <= 1) {
3590 document.getElementById("chosenpostitem-price").value = "Search all first";
3591 break;
3592 }
3593 if (arrMarketItems[key] && arrMarketItems[key][0].price) {
3594 if (arrMarketItems[key][0].price / objBonemeal[key] < cheapest || typeof(cheapest) == "undefined") {
3595 cheapest = arrMarketItems[key][0].price / objBonemeal[key];
3596 price = Math.ceil(cheapest * objBonemeal[itemName]) - 2;
3597 }
3598 }
3599 }
3600 }
3601 if (typeof(cheapest) !== "undefined") {
3602 undercutValue = price;
3603 } else undercutValue = null;
3604 } else if (undercutAmount == "min") {
3605 undercutValue = numberWithoutCommas(document.getElementById("chosenpostitem-lower").innerHTML);
3606 } else if (undercutAmount == "match") {
3607 undercutValue = currentPrice;
3608 } else if (undercutAmount == "max") {
3609 undercutValue = numberWithoutCommas(document.getElementById("chosenpostitem-upper").innerHTML);
3610 } else if (undercutAmount.indexOf("%") > -1) {
3611 undercutValue = currentPrice * ((100 - undercutAmount.replace(/%/g, "")) / 100);
3612 } else {
3613 undercutValue = currentPrice - undercutAmount;
3614 }
3615 if (undercutValue !== null && typeof(undercutValue) !== "undefined") {
3616 if (undercutValue < numberWithoutCommas(document.getElementById("chosenpostitem-lower").innerHTML)) {
3617 document.getElementById("chosenpostitem-price").value = numberWithCommas(document.getElementById("chosenpostitem-lower").innerHTML);
3618 } else if (undercutValue > numberWithoutCommas(document.getElementById("chosenpostitem-upper").innerHTML)) {
3619 document.getElementById("chosenpostitem-price").value = numberWithCommas(document.getElementById("chosenpostitem-upper").innerHTML);
3620 } else {
3621 document.getElementById("chosenpostitem-price").value = numberWithCommas(Math.ceil(undercutValue));
3622 }
3623 } else if (undercutValue === null || typeof(undercutValue) == "undefined") {
3624 disableBtn(btn, 1000);
3625 }
3626 };
3627 undercutBoxText.setAttribute("style", "text-align:center");
3628 undercutBox.append(undercutBoxText);
3629 for (var i = 0; i < arrUndercut.length; i++) {
3630 var undercutBtn = document.createElement("button");
3631 undercutBtn.setAttribute("onclick", "setUndercut('" + arrUndercut[i] + "',this);");
3632 if (arrUndercut[i] == "cheapest") {
3633 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'>";
3634 undercutBtn.title = "Undercut cheapest heat/energy/bonemeal";
3635 } else undercutBtn.append(arrUndercut[i]);
3636 undercutBox.append(undercutBtn);
3637 if (arrUndercut[i] == "cheapest") {
3638 document.getElementById("undercutBox").insertBefore(document.createElement("br"), document.getElementById("undercutBox").lastChild);
3639 document.getElementById("undercutBox").insertBefore(document.createElement("br"), document.getElementById("undercutBox").lastChild);
3640 }
3641 document.getElementById("undercutBox").append(document.createTextNode("\u00a0")); //nbsp
3642 }
3643 // remove unnecessary multiple BR's that smitty left behind in dialogue-market-chosenpostitem
3644 var el = document.getElementById("undercutBox").nextElementSibling;
3645 while (el.nextElementSibling && el.tagName !== undefined && el.tagName != "BR") {
3646 el = el.nextElementSibling;
3647 }
3648 if (el.tagName == "BR" && el.nextElementSibling && el.nextElementSibling.tagName == "BR") {
3649 while (el.nextElementSibling.tagName == "BR") {
3650 el.nextElementSibling.parentNode.removeChild(el.nextElementSibling);
3651 }
3652 }
3653 }
3654 // set global variable lastBrowsedItem to last browsed item via onclick
3655 addLastBrowsedItemOnclick();
3656 //add maps to noficiation area
3657 var mapNotifWrapper = document.createElement("span");
3658 mapNotifWrapper.setAttribute("class", "notif-box");
3659 mapNotifWrapper.setAttribute("style", "display:none;background: linear-gradient(black, gold);");
3660 mapNotifWrapper.setAttribute("id", "tedmarket-notif-map");
3661 mapNotifWrapper.setAttribute("onclick", "clicksTreasureMap();");
3662 var mapNotif = document.createElement("img");
3663 mapNotif.setAttribute("src", "images/treasureMap.png");
3664 mapNotif.setAttribute("class", "image-icon-50");
3665 mapNotifWrapper.append(mapNotif);
3666 document.getElementById("notifaction-area").prepend(mapNotifWrapper);
3667 //add keepAmount to dialogue-market-chosenpostitem
3668 if (useKeepAmount) {
3669 keepAmountText.innerHTML = "Keep: error";
3670 document.getElementById("chosenpostitem-amount").parentNode.insertBefore(keepAmountText, document.getElementById("chosenpostitem-amount").nextSibling);
3671 document.getElementById("chosenpostitem-amount").parentNode.insertBefore(document.createElement("br"), document.getElementById("chosenpostitem-amount").nextSibling);
3672 //document.getElementById("chosenpostitem-amount").parentNode.insertBefore(document.createTextNode('\u00a0'),document.getElementById("chosenpostitem-amount").nextSibling);
3673 }
3674 //fix collect button padding to allow 123,456,789 format
3675 for (let i = 1; i <= arrMarketSlots.length; i++) {
3676 document.getElementById("market-slot-" + i + "-collect-btn").style.padding = "10px 5px";
3677 }
3678 //add tooltips to items that do not have a tooltip
3679 function tedTooltips() {
3680 if (!document.getElementById("tooltip-stone")) { // don't add tooltips until default tooltips are loaded
3681 setTimeout(function() {
3682 tedTooltips();
3683 }, 100);
3684 } else {
3685 var tKeys = Object.keys(jsTradableItems);
3686 tKeys.forEach((key) => {
3687 if (key == "emptyChisel") return;
3688 if (!document.getElementById("tooltip-" + key)) {
3689 if (document.getElementById("item-box-" + key)) {
3690 let newTooltip = document.createElement("div");
3691 document.getElementById("tooltip-list").append(newTooltip);
3692 newTooltip.outerHTML = "<div id='tooltip-" + key + "' style='display:none;'> <span style='font-size:20pt'>" + getItemName(key) + "</span><br><br></div>";
3693 document.getElementById("item-box-" + key).removeAttribute("title");
3694 document.getElementById("item-box-" + key).setAttribute("data-tooltip-id", "tooltip-" + key);
3695 }
3696 }
3697 });
3698 loadTooltips();
3699 }
3700 }
3701 tedTooltips();
3702 tradeHistory();
3703 document.body.append(oreAverageElement);
3704 calculateFlips();
3705 sortTradeHistory(sortByTH);
3706 //add an id to Post button in dialogue-market-chosenpostitem
3707 for (let i = 0; i < document.getElementById("dialogue-market-chosenpostitem").children.length; i++) {
3708 if (document.getElementById("dialogue-market-chosenpostitem").children[i].defaultValue == "Post") {
3709 document.getElementById("dialogue-market-chosenpostitem").children[i].setAttribute("id", "cpi-post");
3710 break;
3711 }
3712 }
3713 //add an id to Buy button in buyFromMarket-dialogue
3714 for (let i = 0; i < document.getElementById("dialogue-buyFromMarket").children.length; i++) {
3715 if (document.getElementById("dialogue-buyFromMarket").children[i].defaultValue == "Buy") {
3716 document.getElementById("dialogue-buyFromMarket").children[i].setAttribute("id", "buyFromMarket-buy");
3717 }
3718 }
3719 //add fixCpiNumbers to convert commas to without commas on post
3720 var cpiPostString = document.getElementById("cpi-post").getAttribute("onclick");
3721 if (!cpiPostString.includes("fixCpiNumbers();")) {
3722 cpiPostString = "fixCpiNumbers();" + cpiPostString;
3723 document.getElementById("cpi-post").setAttribute("onclick", cpiPostString);
3724 }
3725 // show total price when posting an item
3726 if (document.getElementById("chosenpostitem-itemName").nextElementSibling && document.getElementById("chosenpostitem-itemName").nextElementSibling.className == "basic-smallbox") {
3727 let chosenpostitem_totalprice = document.createElement("span");
3728 chosenpostitem_totalprice.setAttribute("id", "chosenpostitem-totalprice");
3729 document.getElementById("chosenpostitem-itemName").nextElementSibling.append(chosenpostitem_totalprice);
3730 }
3731 window.chosenpostitem_total = function() {
3732 let totalPrice = parseInt(numberWithoutCommas(document.getElementById("chosenpostitem-amount").value)) * parseInt(numberWithoutCommas(document.getElementById("chosenpostitem-price").value));
3733 if (isNaN(totalPrice)) totalPrice = "";
3734 cpi_totalPrice = totalPrice;
3735 document.getElementById("chosenpostitem-totalprice").innerHTML = "<br><br>Total Price: " + numberWithCommas(totalPrice);
3736 };
3737 document.getElementById("chosenpostitem-amount").setAttribute("onchange", "chosenpostitem_total();");
3738 document.getElementById("chosenpostitem-amount").setAttribute("onkeypress", "this.onchange();");
3739 document.getElementById("chosenpostitem-amount").setAttribute("onpaste", "this.onchange();");
3740 document.getElementById("chosenpostitem-amount").setAttribute("oninput", "this.onchange();");
3741 document.getElementById("chosenpostitem-price").setAttribute("onchange", "chosenpostitem_total();");
3742 document.getElementById("chosenpostitem-price").setAttribute("onkeypress", "this.onchange();");
3743 document.getElementById("chosenpostitem-price").setAttribute("onpaste", "this.onchange();");
3744 document.getElementById("chosenpostitem-price").setAttribute("oninput", "this.onchange();");
3745 //browser notification permission check
3746 if (!("Notification" in window)) {
3747 console.log("This browser does not support system notifications");
3748 } else if (Notification.permission == "granted") { // Let's check whether notification permissions have already been granted
3749 allowedBrowserNotifications = true;
3750 } else if (Notification.permission != 'denied') { // Otherwise, we need to ask the user for permission
3751 Notification.requestPermission(function(permission) {
3752 if (permission == "granted") {
3753 allowedBrowserNotifications = true;
3754 } else {
3755 allowedBrowserNotifications = false;
3756 }
3757 });
3758 } else {
3759 allowedBrowserNotifications = false;
3760 }
3761 }
3762
3763 tedMarketUiSettings();
3764 drawButtons();
3765 marketMain();
3766 alterMarketSlots();
3767 otherSettingsRunOnce();
3768 //minigamesInit();
3769 //setInterval(persistentInterval, 1500);
3770 //setInterval(tmg_pokerConnectionHandler, 1000);
3771 }
3772});