Advertisement
Guest User

Untitled

a guest
Feb 22nd, 2019
103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 42.11 KB | None | 0 0
  1. // ==UserScript==
  2. // @name MA - hlidka
  3. // @version 1.8
  4. // @description utility
  5. // @grant none
  6. // @require http://code.jquery.com/jquery-1.10.2.min.js
  7. // @require https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.4.0/Chart.bundle.min.js
  8. // @include http://www.meliorannis.com/*
  9. // ==/UserScript==
  10.  
  11. Array.prototype.diff = function(a) {
  12. return this.filter(function(i) {return a.indexOf(i) < 0;});
  13. };
  14.  
  15. var percentColors = [
  16. { pct: 0.0, color: { r: 0xff, g: 0x00, b: 0 } },
  17. { pct: 0.5, color: { r: 168, g: 168, b: 168 } },
  18. { pct: 1.0, color: { r: 0x00, g: 0xff, b: 0 } } ];
  19.  
  20. var percentToColor = function(pct)
  21. {
  22. for (var i = 0; i < percentColors.length; i++)
  23. {
  24. if (pct <= percentColors[i].pct)
  25. {
  26. var lower = (i === 0) ? percentColors[i] : percentColors[i - 1];
  27. var upper = (i === 0) ? percentColors[i + 1] : percentColors[i];
  28. var range = upper.pct - lower.pct;
  29. var rangePct = (pct - lower.pct) / range;
  30. var pctLower = 1 - rangePct;
  31. var pctUpper = rangePct;
  32.  
  33. var color =
  34. {
  35. r: Math.floor(lower.color.r * pctLower + upper.color.r * pctUpper),
  36. g: Math.floor(lower.color.g * pctLower + upper.color.g * pctUpper),
  37. b: Math.floor(lower.color.b * pctLower + upper.color.b * pctUpper)
  38. };
  39.  
  40. return 'rgb(' + [color.r, color.g, color.b].join(',') + ')';
  41. }
  42. }
  43. };
  44.  
  45. function getLastDbValue(id, property, searchHoursInPast)
  46. {
  47. var dbValues = localStorage[id];
  48. if (dbValues)
  49. {
  50. dbValues = JSON.parse(dbValues);
  51. dbValues.reverse();
  52.  
  53. for (var i in dbValues) {
  54.  
  55. var hourDifference = Math.abs(new Date() - new Date(dbValues[i].date)) / 36e5;
  56. if (searchHoursInPast && hourDifference > searchHoursInPast)
  57. {
  58. if (dbValues[i][property])
  59. return dbValues[i][property];
  60. }
  61. else if (!searchHoursInPast)
  62. {
  63. if (dbValues[i][property])
  64. return dbValues[i][property];
  65. }
  66. }
  67. }
  68.  
  69. return -1;
  70. }
  71.  
  72. function renderChangesValue(id, power, area, powerPos, areaPos, row, ot, otPos, pastValueResolver)
  73. {
  74. var powerDb = pastValueResolver(id, 'power');
  75. var areaDb = pastValueResolver(id, 'area');
  76. var otDb = pastValueResolver(id, 'ot');
  77.  
  78. var columns = $(row).children();
  79.  
  80. var powerColumn = $(columns[powerPos]);
  81. renrerValue(id, 'power', power, powerDb==-1 ? power : powerDb, true, powerColumn);
  82.  
  83. $('#' + id + '-dialog').click(function() {
  84. $('#' + id + '-dialog').css("display", "none");
  85. });
  86.  
  87. if(areaPos)
  88. {
  89. var areaColumn = $(columns[areaPos]);
  90. renrerValue(id, 'area', area, areaDb==-1 ? area : areaDb, false, areaColumn);
  91. }
  92.  
  93. if (otPos)
  94. {
  95. var otPlus = Number(ot) - Number(otDb);
  96.  
  97. if (otPlus || otPlus > -1)
  98. {
  99. var otColumn = $(columns[otPos]);
  100. renrerValue(id, 'ot', otPlus, otPlus, false, otColumn);
  101. }
  102. }
  103. }
  104.  
  105. function renrerValue(id, type, value, valueDb, isPercent, whereToRender)
  106. {
  107.  
  108. var percent = Math.round(percent * 10) / 10;
  109. percent = (value / (valueDb / 100) - 100).toFixed(1) + '%';
  110.  
  111. var val = (Math.round((value - valueDb) / 100) / 10) + 'k';
  112.  
  113. if (type === 'ot')
  114. {
  115. val = value;
  116. }
  117.  
  118. var element = '<font size="2" class="to-remove">(<span id="' + id + '-' + type + '" class="' + type +'">' + (isPercent ? percent : val) + '</span>)';
  119. whereToRender.append(element);
  120. whereToRender.click(function()
  121. {
  122. var storage = localStorage[id];
  123. var fakeRowId = 'fakeRow' + id;
  124.  
  125. if (storage && $('#' + fakeRowId).length === 0)
  126. {
  127. var data = JSON.parse(storage);
  128. data.reverse();
  129.  
  130. $('<tr class="fakeRow"><td colspan="20" >' +
  131. '<div id="' + fakeRowId + '"style="background-color: white; width: 800px;"></div>' +
  132. '</td></tr>').insertAfter($(whereToRender.parent()));
  133.  
  134. renderChart(data, 'power', id, $('#' + fakeRowId));
  135. renderChart(data, 'area', id, $('#' + fakeRowId));
  136. renderChart(data, 'ot', id, $('#' + fakeRowId));
  137.  
  138. $('#' + fakeRowId).click(function() {$('.fakeRow').remove();});
  139. }
  140. else
  141. {
  142. $('.fakeRow').remove();
  143. }
  144.  
  145. });
  146. }
  147.  
  148. function renderChart(data, type, id, elemtToAppend)
  149. {
  150. var chartId = type + 'Chart' + id;
  151.  
  152. $(elemtToAppend).append('<canvas id="' + chartId + '" width="1000" height="200"/>');
  153.  
  154. var datasets = createDataSet(data, type);
  155.  
  156. var tempData = {
  157. type: "line",
  158. data: {
  159. datasets : [ {label : datasets.label, data : datasets.data}]
  160. },
  161. options: {
  162. responsive : true,
  163. scales: {
  164. yAxes: [
  165. { position : 'right'}
  166. ],
  167. xAxes: [{
  168. type: 'time',
  169. unit: 'hour',
  170. unitStepSize: 1,
  171. time: {
  172. displayFormats: {
  173. 'millisecond': 'HH:mm',
  174. 'second': 'HH:mm',
  175. 'minute': 'HH:mm',
  176. 'hour': 'HH:mm',
  177. 'day': 'HH:mm',
  178. 'week': 'HH:mm',
  179. 'month': 'HH:mm',
  180. 'quarter': 'HH:mm',
  181. 'year': 'HH:mm',
  182. },
  183. round : 'hour'
  184. }
  185. }]
  186. },
  187. title: {
  188. display: false
  189. }
  190. },
  191. };
  192.  
  193. var ctx = document.getElementById(chartId).getContext("2d");
  194. new Chart(ctx, tempData);
  195. }
  196.  
  197. function createDataSet(data, type)
  198. {
  199. var includedHours = [];
  200. var hoursBack = 24;
  201.  
  202. var clearData = $(data).filter(
  203. function(index, row)
  204. {
  205. var hourDiff = Math.round(((new Date() - new Date(row.date)) / 36e5) * 10) / 10;
  206. // every 1/10h should have one value, 24h back
  207. var result = row[type] && hourDiff < hoursBack;// && !includedHours.includes(hourDiff);
  208. includedHours.push(hourDiff);
  209. return result;
  210. });
  211.  
  212. var labels = [], chartData=[];
  213.  
  214. var yesterday = new Date(new Date().getTime() - (hoursBack * 60 * 60 * 1000));
  215. chartData.push({x : yesterday, y : null});
  216.  
  217. $.each(clearData, function(index, packet) {
  218. chartData.push({x : new Date(packet.date), y : parseFloat(packet[type])});
  219. });
  220.  
  221. var now = new Date();
  222. chartData.push({x : now, y : null});
  223.  
  224. return { label : type, labels : labels, data: chartData };
  225. }
  226.  
  227. function formatDate(date)
  228. {
  229. var d = new Date(date);
  230. return [d.getDate(), (d.getMonth()+1)].join('.') + ' ' +
  231. [ d.getHours(), d.getMinutes()].join(':');
  232. }
  233.  
  234. function spies()
  235. {
  236. var table = $('#spies_report');
  237.  
  238. if (table)
  239. {
  240. var id = table.find('sup').text().replace('(', '').replace(')', '');
  241. var powerColumn = table.find('td:contains("Síla provincie")').next();
  242. var power = Number(powerColumn.text().split('(')[0]);
  243. var powerMine = Number($('.value_power').text());
  244.  
  245. var powerDb = getLastDbValue(id, 'power');
  246.  
  247. if (powerColumn.length !== 0)
  248. {
  249. powerColumn.append('<br/><a id="adjustArmy" style="color: green;">Pripravit armadu</a>');
  250. renrerValue(id, 'power', power, powerDb==-1 ? power : powerDb, true, powerColumn);
  251. }
  252.  
  253. $('#adjustArmy').click(
  254. function() {
  255. localStorage.powerDiff = (power * 1.245) - powerMine;
  256. window.location.href = $( "a:contains('Armáda')" ).attr('href');
  257. });
  258. }
  259.  
  260. $('#left_column_wrapper').append('<label>Nazev jednotky stitu</label><br/>');
  261. $('#left_column_wrapper').append('<input type="text" id="shieldUnit" style="width: 120px;" />');
  262.  
  263. $('#shieldUnit').css('background', 'url("/html/img/inputs_sprite.png") 0 0 no-repeat transparent');
  264. $('#shieldUnit').val(localStorage.shieldUnit ? localStorage.shieldUnit : '');
  265. $('#shieldUnit').on("change keyup paste", function() { localStorage.shieldUnit = $('#shieldUnit').val();});
  266.  
  267. if (localStorage.powerDiff && localStorage.powerDiff !== '' && localStorage.shieldUnit)
  268. {
  269. var selectUnit = $($('select')[1]).find('option:contains(' + localStorage.shieldUnit + ')').val();
  270. var unitPower = Number($('#army_table_army tr:contains(' + localStorage.shieldUnit + ') .army_unit_power').text());
  271. var unitExp = Number($('#army_table_army tr:contains(' + localStorage.shieldUnit + ') .army_unit_exp').text().replace('%', '').trim());
  272.  
  273. var oneUnitPower;
  274.  
  275. if (localStorage.powerDiff < 0)
  276. {
  277. oneUnitPower = (unitPower / 100) * unitExp;
  278. $($('select')[0]).val(selectUnit);
  279. $($('input[name="kolik"]')[0]).val(Math.abs(Math.round(localStorage.powerDiff / oneUnitPower)));
  280. $($('input[name="kolik"]')[0]).change();
  281. }
  282. else
  283. {
  284. oneUnitPower = unitPower * 0.4;
  285. $($('select')[1]).val(selectUnit);
  286. $($('input[name="kolik"]')[1]).val(Math.abs(Math.round(localStorage.powerDiff / oneUnitPower)));
  287. $($('input[name="kolik"]')[1]).change();
  288. }
  289.  
  290. localStorage.powerDiff = '';
  291. }
  292. }
  293.  
  294. function makeTableOrderable()
  295. {
  296. var tables = $('table:contains("Síla"):contains("ID")');
  297.  
  298. $.each(
  299. tables,
  300. function (i, table)
  301. {
  302.  
  303. var headRow = $(table).find('.heading');
  304.  
  305. var headColumns = $(headRow).find('td');
  306. $.each(headColumns,
  307. function (index, value)
  308. {
  309. $(value).click(function(){
  310. var table = $(this).parents('table').eq(0)
  311. var rows = table.find('tr:gt(0)').toArray().sort(comparer($(this).index()))
  312. this.asc = !this.asc
  313. if (!this.asc){rows = rows.reverse()}
  314. for (var i = 0; i < rows.length; i++){table.append(rows[i])}
  315. })
  316. });
  317. });
  318.  
  319. function comparer(index) {
  320. return function(a, b) {
  321. var valA = getCellValue(a, index);
  322. var valB = getCellValue(b, index);
  323.  
  324. if ($.isNumeric(valA.replace(" ", "").replace(/ *\([^)]*\) */g, "")))
  325. {
  326. valA = valA.replace(" ", "").replace(/ *\([^)]*\) */g, "");
  327. valB = valB.replace(" ", "").replace(/ *\([^)]*\) */g, "");
  328. }
  329.  
  330. return $.isNumeric(valA) && $.isNumeric(valB) ? valA - valB : valA.toString().localeCompare(valB);
  331. }
  332. }
  333. function getCellValue(row, index){ return $(row).children('td').eq(index).text() }
  334. }
  335.  
  336. function renderTableInfo(table, pastValueResolver)
  337. {
  338. var rows = $(table).find('tr');
  339.  
  340. var headRow = $(table).find('.heading');
  341.  
  342. var idPos;
  343. var namePos;
  344. var powerPos;
  345. var areaPos;
  346. var otPos;
  347. var protPos;
  348.  
  349. var headColumns = $(headRow).find('td');
  350. if(headColumns.length === 0)
  351. headColumns = $(headRow).find('th');
  352. $.each(headColumns,
  353. function (index, value)
  354. {
  355. var text = $(value).text().trim();
  356. if(text==='ID')
  357. idPos = index;
  358. if(text==='Regent')
  359. namePos = index;
  360. if(text.indexOf("Síla")===0)
  361. powerPos = index;
  362. if(text==='Rozloha' || text === 'hAR')
  363. areaPos = index;
  364. if(text==='O.T.')
  365. otPos = index;
  366. if(text===' Protekce')
  367. protPos = index;
  368.  
  369. });
  370.  
  371. $.each(rows,
  372. function (index, value)
  373. {
  374. if (index > 0) // skip header row
  375. {
  376. var columns = $(value).children();
  377. var id = $(columns[idPos]).children("span").clone().children().remove().end().text().trim();
  378.  
  379. if (!id)
  380. {
  381. id = $(columns[idPos]).text().trim();
  382. }
  383.  
  384. var name = $(columns[namePos]).text().trim();
  385. var power = $(columns[powerPos]).text().split('*').join('').trim();
  386. var area;
  387. var ot;
  388. var prot;
  389.  
  390. if(areaPos)
  391. area = $(columns[areaPos]).text().trim();
  392. if(otPos)
  393. ot = $(columns[otPos]).text().trim();
  394. if (protPos)
  395. prot = $(value).find('.listings_prot_mil').length === 1 ? "true" : "false";
  396.  
  397. renderChangesValue(id, power, area, powerPos, areaPos, value, ot, otPos, pastValueResolver);
  398.  
  399. if(!isNaN(parseFloat(id)))
  400. {
  401. var data = localStorage[id];
  402. var array = [];
  403.  
  404. var lastDbValPower = getLastDbValue(id, 'power');
  405. var lastDbValOt = getLastDbValue(id, 'ot');
  406. var lastDbValArea = getLastDbValue(id, 'area');
  407. var lastDbValProt = getLastDbValue(id, 'prot');
  408. var dataChanged = true;
  409.  
  410. if (lastDbValPower || lastDbValOt)
  411. dataChanged = (power && power !== lastDbValPower) || (ot && ot !== lastDbValOt) || (area && area !== lastDbValArea) || (prot && prot !== lastDbValProt);
  412.  
  413. if(data)
  414. array= JSON.parse(data);
  415.  
  416. if (dataChanged)
  417. {
  418. array.push({"power" : power, "area" : area, "date" : Date(), "ot": ot, "name": name, "prot" : prot});
  419. localStorage[id] = JSON.stringify(array);
  420. }
  421. else
  422. {
  423. array[array.length-1].date = new Date();
  424. localStorage[id] = JSON.stringify(array);
  425. }
  426. }
  427. }
  428. });
  429.  
  430. colorPercentages(table, '.power');
  431. colorPercentages(table, '.area');
  432. colorPercentages(table, '.ot');
  433. }
  434.  
  435. function main()
  436. {
  437. var tables = $('table:contains("Síla"):contains("ID"):not(#onlinePlayers)');
  438.  
  439. var pastValueResolver = (id, prop) => getLastDbValue(id, prop);
  440. $.each(tables, function (i, table) { renderTableInfo(table, pastValueResolver); });
  441. }
  442.  
  443. function colorPercentages(table, selector)
  444. {
  445. var percentElements = $(table).find(selector);
  446. var percentValues = $.map(
  447. percentElements,
  448. function(value)
  449. {
  450. return $(value).text().replace('k','').replace('%', '').replace('(', '').replace(')', '');
  451. }
  452. );
  453. var percentMax = Math.max.apply(Math, percentValues);
  454. var percentMin = Math.min.apply(Math, percentValues);
  455.  
  456. percentMax = percentMax === 0 ? 1 : percentMax;
  457. percentMin = percentMin === 0 ? 1 : percentMin;
  458.  
  459. $.each(
  460. percentElements,
  461. function(index, value)
  462. {
  463.  
  464. var currentValue = $(value).text().replace('k','').replace('%', '').replace('(', '').replace(')', '');
  465. var relativePercent = 0;
  466.  
  467. if(currentValue >= 0)
  468. {
  469. relativePercent = 50 + (Math.abs(currentValue) / (Math.abs(percentMax) / 50));
  470. }
  471. else
  472. {
  473. relativePercent = 50 - (Math.abs(currentValue) / (Math.abs(percentMin) / 50));
  474. }
  475.  
  476. $(value).css('color', percentToColor(relativePercent / 100));
  477. }
  478. );
  479. }
  480.  
  481. function renderHistoryTextField()
  482. {
  483. var tables = $('table:contains("Síla"):contains("ID"):not(#onlinePlayers)');
  484.  
  485. $.each(
  486. tables,
  487. function (i, table)
  488. {
  489. $(table).after("<label>Pocet hodin do zadu</label><input id='hour-field" + i + "' type='text'/>");
  490. $('#hour-field' + i).change(function()
  491. {
  492. var searchHoursInPast = Number($( this ).val().trim());
  493. var pastValueResolver = (id, prop) => getLastDbValue(id, prop);
  494.  
  495. $(table).find(".to-remove").remove();
  496. renderTableInfo(table, pastValueResolver);
  497. });
  498. });
  499. }
  500.  
  501. function kokotMeasure()
  502. {
  503. if (!localStorage.kokotMeasure)
  504. localStorage.kokotMeasure = 0;
  505. localStorage.kokotMeasure = Number(localStorage.kokotMeasure) + 1;
  506. $('body').append('<label style="position: absolute; left: 0; top: 0;">Jak velky jsi kokot: ' + localStorage.kokotMeasure + '</div>');
  507. }
  508.  
  509. function myPower()
  510. {
  511. var power = $('.value_power').text();
  512. var powerDb = Number(localStorage.me);
  513. var powerDifference = (power - powerDb);
  514.  
  515. if (powerDifference)
  516. {
  517. $('#LS_power_value').append('<span id="powerId" style="padding-left: 5px;">' + powerDifference + '</span>');
  518.  
  519. if (powerDifference < 0)
  520. {
  521. $('#powerId').css('color', 'RGB(255, 0, 0)');
  522.  
  523. document.title = 'Pokles o ' + powerDifference;
  524. beep(powerDifference);
  525. }
  526. else
  527. {
  528. $('#powerId').css('color', 'RGB(0, 255, 0)');
  529. }
  530. }
  531.  
  532. localStorage.me = power;
  533. }
  534.  
  535. function beep(difference)
  536. {
  537. if (localStorage.powerDiffEnabled === "true" && Math.abs(difference) > Number(localStorage.powerDiffTreshold))
  538. {
  539. sendSlackNotification($('#governor').text() + ' difference ' + difference);
  540. (new Audio('http://www.freespecialeffects.co.uk/soundfx/music/trumpets.wav')).play();
  541. }
  542. }
  543.  
  544. function checkNewMessage()
  545. {
  546. if (!localStorage.powerDiffTreshold)
  547. {
  548. localStorage.powerDiffTreshold = 0;
  549. }
  550.  
  551. $('#left_column_wrapper').append('<br/><label style="padding-right: 25px;">New message notifier</label>');
  552.  
  553. $('#left_column_wrapper').append('<input id="messageNotifier" type="checkbox"/><br/>');
  554. $('#messageNotifier').prop('checked', localStorage.messageNotifier === "true");
  555. $('#messageNotifier').on("change keyup paste", function() {localStorage.messageNotifier = $("#messageNotifier").is(':checked');});
  556.  
  557. if ($('.new_post').length > 0 && localStorage.messageNotifier === "true")
  558. {
  559. sendSlackNotification($('#governor').text() + ' nova posta');
  560. (new Audio('https://www.mediacollege.com/downloads/sound-effects/star-trek/tng/tng-worf-incomingmessage.wav')).play();
  561. }
  562. }
  563.  
  564. function renderShieldStackPerc()
  565. {
  566. var shieldPwrElem = $('#econ_units_list').find('tr.tr_even:first > td:nth-child(6)');
  567. var shieldPwr = Number(shieldPwrElem.text());
  568. var totalPwr = Number($('#econ_units_list').find('.tr_econ_summary > td:nth-child(3)').text());
  569.  
  570. if (shieldPwr && totalPwr)
  571. {
  572. var shieldPerc = (100 * shieldPwr) / totalPwr;
  573.  
  574. shieldPwrElem.append(' (<span style="color: RGB(0, 255, 0);">' + shieldPerc.toFixed(1) + '%</span>)');
  575. }
  576. }
  577.  
  578. function renderNotes()
  579. {
  580. $('#left_column_wrapper').append('<br/><label>Notes</label><br/>');
  581. $('#left_column_wrapper').append('<textarea rows="4" cols="50" id="notes"></textarea>');
  582. $('#notes').val(localStorage.notes ? localStorage.notes : '');
  583. $('#notes').on("change keyup paste", function() {
  584. localStorage.notes = $('#notes').val();
  585. });
  586. }
  587.  
  588.  
  589. function formatDuration(duration) {
  590. var seconds = (duration / 1000).toFixed(0);
  591.  
  592. if (seconds > 60) {
  593. var minutes = (seconds / 60).toFixed(0);
  594.  
  595. if (minutes > 60) {
  596. var hours = (minutes / 60).toFixed(0);
  597.  
  598. if (hours > 24) {
  599. var days = (hours / 24).toFixed(0);
  600.  
  601. return "před " + days + "d";
  602. } else {
  603. return "před " + hours + "h";
  604. }
  605. } else {
  606. return "před " + minutes + "m";
  607. }
  608. } else {
  609. return "před " + seconds + "s";
  610. }
  611. }
  612.  
  613. function renderPlayers() {
  614.  
  615. function getPlayerTable(players) {
  616. var currentTime = new Date();
  617.  
  618. var tableStart =
  619. '<table id="listings_table_top20"><tbody>' +
  620. '<tr class="heading">' +
  621. '<td class="attacks_id">ID</td>' +
  622. '<td class="attacks_regent">Regent</td>' +
  623. '<td class="attacks_pwr">Síla</td>' +
  624. '<td class="attacks_protection"></td>' +
  625. '<td class="attacks_time">Čas vložení</td>' +
  626. '</tr>';
  627.  
  628. for (var i = 0; i < players.length; i++) {
  629. tableStart = tableStart +
  630. '<tr>' +
  631. '<td class="attacks_id">' + players[i].id + '</td>' +
  632. '<td class="attacks_regent">' + players[i].name + '</td>' +
  633. '<td class="attacks_pwr">' + players[i].power + '</td>' +
  634. '<td class="attacks_protection">' + (players[i].protection ? '*' : '') + '</td>' +
  635. '<td class="attacks_time">' + (formatDuration(Math.abs(currentTime - new Date(players[i].lastUpdate)))) + '</td></tr>';
  636. }
  637.  
  638. var tableEnd = '</tbody></table></div></div>';
  639.  
  640. return tableStart + tableEnd;
  641. }
  642.  
  643. var playersLink = $('#Attacks_list_detail a').attr("href").replace("vypis=utoky_detailne", "players");
  644. $('#Attacks_list_detail').after('<li id="playersLink"><a href="' + playersLink + '">Hráči</a></li>');
  645.  
  646. if (window.location.href.indexOf("players") != -1) {
  647. $('#central_column_bottom').empty();
  648.  
  649. getAllPlayers(function(data) {
  650. $('#central_column_bottom').append(getPlayerTable(data));
  651. });
  652. }
  653. }
  654.  
  655. function autorefresh()
  656. {
  657.  
  658. $('#left_column_wrapper').append('<br/><label>Auto hlidka (sec)</label><br/>');
  659. $('#left_column_wrapper').append('<input id="watchInterval" type="text" style="width: 120px;">');
  660. $('#left_column_wrapper').append('<input id="autoWatch" type="checkbox"/><br/>');
  661. $('#left_column_wrapper').append('<label>Bestiar</label><input id="autowatchBestiar" type="checkbox"/><br/>');
  662. $('#left_column_wrapper').append('<label>Cska</label><input id="autowatchCs" type="checkbox"/><br/>');
  663. $('#left_column_wrapper').append('<label>Armada</label><input id="autowatchArmy" type="checkbox"/><br/>');
  664. $('#left_column_wrapper').append('<label>Hospodareni</label><input id="autowatchHospodareni" type="checkbox"/><br/>');
  665. $('#left_column_wrapper').append('<label>Kouzla</label><input id="autowatchMagic" type="checkbox"/><br/>');
  666. $('#left_column_wrapper').append('<label>Vase umisteni</label><input id="autowatchYourPlacing" type="checkbox"/><br/>');
  667. $('#left_column_wrapper').append('<label>Mozne cile</label><input id="autowatchAllowedTargets" type="checkbox"/><br/>');
  668.  
  669. $('#autoWatch').css('position', 'absolute');
  670. $('#autoWatch').css('top', '20px');
  671. $('#autoWatch').css('left', '5px');
  672.  
  673. $('#watchInterval').css('background', 'url("/html/img/inputs_sprite.png") 0 0 no-repeat transparent');
  674. $('#watchInterval').val(localStorage.watchInterval ? localStorage.watchInterval : '');
  675. $('#watchInterval').on("change keyup paste", function() { localStorage.watchInterval = $('#watchInterval').val();});
  676.  
  677. addCheckboxDbListener('autoWatch');
  678. addCheckboxDbListener('autowatchBestiar');
  679. addCheckboxDbListener('autowatchCs');
  680. addCheckboxDbListener('autowatchArmy');
  681. addCheckboxDbListener('autowatchHospodareni');
  682. addCheckboxDbListener('autowatchMagic');
  683. addCheckboxDbListener('autowatchYourPlacing');
  684. addCheckboxDbListener('autowatchAllowedTargets');
  685.  
  686. var timer;
  687.  
  688. if (localStorage.autoWatch === "true")
  689. {
  690. timer = startTimer();
  691. }
  692.  
  693. $('#autoWatch').on("change keyup paste",
  694. function()
  695. {
  696. if ($("#autoWatch").is(':checked'))
  697. {
  698. timer = startTimer();
  699. }
  700. else if(timer)
  701. {
  702. clearInterval(timer);
  703. }
  704. });
  705. }
  706.  
  707. function addCheckboxDbListener(id)
  708. {
  709. $('#' + id).prop('checked', localStorage[id] === "true");
  710. $('#' + id).on("change keyup paste", function() { localStorage[id] = $("#" + id).is(':checked')});
  711. }
  712.  
  713. function startTimer()
  714. {
  715. var counter = Number(localStorage.watchInterval) * 1000;
  716. var timer = setTimeout(
  717. function()
  718. {
  719. var settingArray = ['autowatchBestiar', 'autowatchCs', 'autowatchArmy', 'autowatchHospodareni', 'autowatchMagic', 'autowatchYourPlacing', 'autowatchAllowedTargets'];
  720. settingArray = settingArray.filter(setting => localStorage[setting] === 'true')
  721.  
  722. var type = settingArray[Math.floor(Math.random() * settingArray.length)];;
  723.  
  724. console.log(type);
  725.  
  726. if (type === 'autowatchBestiar')
  727. {
  728. window.location.href = $( "a:contains('Bestiář')" ).attr('href');
  729. }
  730. else if (type === 'autowatchCs')
  731. {
  732. window.location.href = $( "a:contains('Výpis útoků')" ).attr('href');
  733. }
  734. else if (type === 'autowatchArmy')
  735. {
  736. window.location.href = $( "a:contains('Armáda')" ).attr('href');
  737. }
  738. else if (type === 'autowatchHospodareni')
  739. {
  740. window.location.href = $( "a:contains('Hospodaření')" ).attr('href');
  741. }
  742. else if (type === 'autowatchMagic')
  743. {
  744. window.location.href = $( "a:contains('Magie a kouzla')" ).attr('href');
  745. }
  746. else if (type === 'autowatchYourPlacing')
  747. {
  748. window.location.href = $( "a:contains('Možné cíle')" ).attr('href').replace('&prehled=mozne_cile', '&prehled=vase_umisteni');
  749. }
  750. else if (type === 'autowatchAllowedTargets')
  751. {
  752. window.location.href = $( "a:contains('Možné cíle')" ).attr('href');
  753. }
  754.  
  755. timer = setTimeout(this, 1000 + counter * Math.random());
  756. }, (2500 + counter * Math.random()));
  757.  
  758. return timer;
  759. }
  760.  
  761. function powerDiffAlarm()
  762. {
  763. if (!localStorage.powerDiffTreshold)
  764. {
  765. localStorage.powerDiffTreshold = 0;
  766. }
  767.  
  768. $('#left_column_wrapper').append('<br/><label style="padding-right: 25px;">Power alarm (power)</label>');
  769.  
  770. $('#left_column_wrapper').append('<input id="powerDiffEnabled" type="checkbox"/><br/>');
  771. $('#powerDiffEnabled').prop('checked', localStorage.powerDiffEnabled === "true");
  772. $('#powerDiffEnabled').on("change keyup paste", function() {localStorage.powerDiffEnabled = $("#powerDiffEnabled").is(':checked');});
  773.  
  774. $('#left_column_wrapper').append('<input id="powerDiffTreshold" type="text" style="width: 120px;"><br/>');
  775. $('#powerDiffTreshold').css('background', 'url("/html/img/inputs_sprite.png") 0 0 no-repeat transparent');
  776. $('#powerDiffTreshold').val(localStorage.powerDiffTreshold);
  777. $('#powerDiffTreshold').on("change keyup paste", function() { localStorage.powerDiffTreshold = $('#powerDiffTreshold').val();});
  778. }
  779.  
  780. function checkBestiar()
  781. {
  782. $('#left_column_wrapper').append('<br/><label style="padding-right: 25px;">Bestiar check (unit.exp,unit2.exp)</label>');
  783.  
  784. $('#left_column_wrapper').append('<input id="bestiarEnabled" type="checkbox"/><br/>');
  785. $('#bestiarEnabled').prop('checked', localStorage.bestiarEnabled === "true");
  786. $('#bestiarEnabled').on("change keyup paste", function() { localStorage.bestiarEnabled = $("#bestiarEnabled").is(':checked'); });
  787.  
  788. $('#left_column_wrapper').append('<textarea id="bestiarText" rows="2" cols="50"><br/>');
  789.  
  790. $('#bestiarText').val(localStorage.bestiarText ? localStorage.bestiarText : '');
  791. $('#bestiarText').on("change keyup paste", function() { localStorage.bestiarText = $('#bestiarText').val();});
  792.  
  793. if (window.location.pathname.includes("obchod") && localStorage.bestiarText && localStorage.bestiarEnabled === "true")
  794. {
  795. var unitExpPairs = localStorage.bestiarText.split(",");
  796. var count = 0;
  797.  
  798. $.each(unitExpPairs,
  799. function(index, unitExpPair)
  800. {
  801. var unit = unitExpPair.split(".")[0].trim();
  802. var exp = Number(unitExpPair.split(".")[1].trim());
  803. var stack;
  804.  
  805. if (unit.includes("#"))
  806. {
  807. stack = unit.split('#')[1].trim();
  808. unit = unit.split('#')[0].trim();
  809. }
  810.  
  811. // unit elements
  812. var elements = $("#beast_shop tr:not(.best_me_buyer):contains('" + unit + "')");
  813.  
  814. elements = elements.filter(
  815. function(i, el)
  816. {
  817. var expEl = $(el).find(".beast_shop_unit_exp");
  818. var stackV = $(el).find(".beast_shop_unit_stack");
  819.  
  820. return exp <= Number($(expEl).text().replace('%', '')) || stack <= Number($(stackV).text());
  821. }
  822. );
  823.  
  824. $.each(elements,
  825. function(index, el)
  826. {
  827. $(el).css('background-color', 'darkred');
  828. });
  829.  
  830. // contains unit
  831. if (elements.length !== 0)
  832. {
  833. if (unit === 'Str')
  834. {
  835. unit = "Shooter stack bigger " + stack;
  836. }
  837.  
  838. var url = 'http://api.voicerss.org/?key=9ed0aef9a2c64bc5abd65ca333588164&c=wav&hl=ru-ru&src=' + unit;
  839.  
  840. setTimeout(function(){
  841. (new Audio(url)).play();}, 1000 * count);
  842. count++;
  843. }
  844. }
  845. );
  846. }
  847. }
  848.  
  849. function checkCs() {
  850.  
  851. if (!localStorage.csEnabled)
  852. {
  853. localStorage.csEnabled = "true";
  854. }
  855.  
  856. if (!localStorage.csTreasholdPercentage)
  857. {
  858. localStorage.csTreasholdPercentage = 5;
  859. }
  860.  
  861. $('#left_column_wrapper').append('<br/><label style="padding-right: 25px;">Cs treashold diff %</label>');
  862. $('#left_column_wrapper').append('<input id="csEnabled" type="checkbox"/>');
  863. $('#left_column_wrapper').append('<input type="text" id="csTreasholdPercentage" style="width: 120px;"/><br/>');
  864.  
  865.  
  866. $('#csEnabled').prop('checked', localStorage.csEnabled === "true");
  867. $('#csEnabled').on("change keyup paste", function() {localStorage.csEnabled = $("#csEnabled").is(':checked');});
  868. $('#csTreasholdPercentage').val(localStorage.csTreasholdPercentage ? localStorage.csTreasholdPercentage : '');
  869. $('#csTreasholdPercentage').on("change keyup paste", function() { localStorage.csTreasholdPercentage = $('#csTreasholdPercentage').val();});
  870.  
  871. var csList = $(".attacks_list_wrapper:contains('Bráněné útoky') > .attacks_wrapper > .attacks_table > tbody > tr:not('.heading'):contains('nevráceno')");
  872. var count = 0;
  873.  
  874. $.each(csList, function (i, cs) {
  875. var name = $(cs).find('.attacks_regent').text().trim();
  876. var id = $(cs).find('.attacks_id .tt_player').clone().children().remove().end().text().trim();
  877. var powerDb = getLastDbValue(id, 'power');
  878. var power = $(cs).find('.attacks_pwr').text().trim();
  879. var powerDiff = Math.abs(power - powerDb);
  880. var powerDiffPerc = (powerDiff / power) * 100;
  881.  
  882. console.log('cs ' + cs + ' id ' + id + ' powerdiff: ' + powerDiff);
  883.  
  884. if (localStorage.csEnabled === "true" && powerDiffPerc > Number(localStorage.csTreasholdPercentage)) {
  885. var url = 'http://soundbible.com/grab.php?id=2103&type=wav';
  886.  
  887. sendSlackNotification(name + ' spadl o ' + powerDiff);
  888.  
  889. setTimeout(function() {
  890. (new Audio(url)).play();}, 1000 * count);
  891. count++;
  892. }
  893. });
  894. }
  895.  
  896. function renderPlayersOnline()
  897. {
  898.  
  899. $('#left_column_wrapper').append('<br/><label style="padding-right: 25px;">Online player treshold (h)</label>');
  900.  
  901. $('#left_column_wrapper').append('<input id="onlinePlayerEnabled" type="checkbox"/><br/>');
  902. $('#onlinePlayerEnabled').prop('checked', localStorage.onlinePlayerEnabled === "true");
  903. $('#onlinePlayerEnabled').on("change keyup paste", function(){localStorage.onlinePlayerEnabled = $("#onlinePlayerEnabled").is(':checked');});
  904.  
  905. $('#left_column_wrapper').append('<input type="text" id="onlinePlayerTreshold" style="width: 120px;" /><br/>');
  906.  
  907. $('#onlinePlayerTreshold').val(localStorage.onlinePlayerTreshold ? localStorage.onlinePlayerTreshold : '');
  908. $('#onlinePlayerTreshold').on("change keyup paste", function() { localStorage.onlinePlayerTreshold = $('#onlinePlayerTreshold').val();});
  909.  
  910. if (!localStorage.onlinePlayerTreshold)
  911. {
  912. localStorage.onlinePlayerTreshold = 0.5;
  913. }
  914.  
  915. if (localStorage.onlinePlayerEnabled !== "true")
  916. {
  917. return;
  918. }
  919.  
  920. var treshold = Number(localStorage.onlinePlayerTreshold);
  921. var changedValues = Array.apply(0, new Array(localStorage.length))
  922. .map(function (o, i) {return localStorage.key(i);})
  923. .filter(function(i){return /^\d+$/.test(i)})
  924. .map(function(id)
  925. {
  926. var otVal = getPreviousVal(id, treshold, "ot");
  927. var areaVal = getPreviousVal(id, treshold, "area");
  928. var powerVal = getPreviousVal(id, treshold, "power");
  929. var powerDb = getLastDbValue(id, 'power');
  930.  
  931. var dates = [otVal, areaVal, powerVal]
  932. .filter(val => val)
  933. .sort((a, b) => (a.date > b.date) ? 1 : -1);
  934.  
  935. if (dates && dates.length > 0)
  936. {
  937. var result = dates[0];
  938. result["id"] = id;
  939. result["timeDiff"] = Math.abs(new Date() - new Date(result.date));;
  940. if (powerVal)
  941. {
  942. result["power"] = powerVal.power;
  943. }
  944. if (areaVal)
  945. {
  946. result["area"] = areaVal.area;
  947. }
  948. if (otVal)
  949. {
  950. result["ot"] = otVal.ot;
  951. }
  952. return result;
  953. }
  954. })
  955. .filter(val => val)
  956. .sort((a, b) => (a.timeDiff > b.timeDiff) ? 1 : -1);;
  957.  
  958. var tableContent = changedValues.map(function(val)
  959. {
  960. var powerDb = getLastDbValue(val.id, 'power');
  961. var areaDb = getLastDbValue(val.id, 'area');
  962. var name = getLastDbValue(val.id, 'name');
  963. var timeDiff = val.timeDiff;
  964. var otsDiff = getLastDiff(val.id, treshold, "ot");
  965.  
  966. var protDb = getLastDbValue(val.id, 'prot') === 'true' ? '*' : '';
  967. return '<tr><td class="onlineIds">' + val.id + '</td><td style="word-break: break-all;">' + name + protDb + '</td><td>' +
  968. powerDb + '</td><td>' + areaDb + '</td><td>+' +
  969. otsDiff + '</td><td>' + formatDuration(timeDiff) + '</td></tr>';
  970. })
  971. .join('');
  972.  
  973. $(document.body).append('<table id="onlinePlayers" style="bottom: 0;width: 300px; position: fixed;right: 0px;background-color: black;overflow-y: scroll;max-height: 100%;">' +
  974. '<tr class="heading"><td>ID</td><td>Name</td><td>Síla</td><td>hAR</td><td>TU</td><td><td></tr>' +
  975. tableContent +
  976. '</table>');
  977.  
  978. var selectedIds = localStorage["selectedIds"] ? JSON.parse(localStorage["selectedIds"]) : [];
  979. var onlineIds = $('.onlineIds').map(function(){
  980. return $.trim($(this).text());
  981. }).get();
  982.  
  983. var selectedOnlineIds = selectedIds
  984. .filter(id => onlineIds.includes(id))
  985. .filter(function(item, pos, self) {return self.indexOf(item) == pos;}); // remove redundances;
  986.  
  987. // remove non online from map
  988. localStorage["selectedIds"] = JSON.stringify(selectedOnlineIds);
  989. selectedOnlineIds.forEach(id => markTableRowWithId(id, true));
  990.  
  991. $('.onlineIds').on('click', function(event)
  992. {
  993. var id = $(event.target).text().trim();
  994. var selectedIds = JSON.parse(localStorage["selectedIds"]);
  995. if (selectedIds.includes(id))
  996. {
  997. selectedIds.pop(id);
  998. markTableRowWithId(id, false);
  999. }
  1000. else
  1001. {
  1002. selectedIds.push(id);
  1003. markTableRowWithId(id, true);
  1004. }
  1005. localStorage["selectedIds"] = JSON.stringify(selectedIds);
  1006. });
  1007.  
  1008. var pastValueResolver = (id, prop) =>
  1009. {
  1010. var filtered = changedValues.filter(val => val.id === id);
  1011.  
  1012. if (filtered && filtered[0][prop])
  1013. {
  1014. return filtered[0][prop];
  1015. }
  1016. return getLastDbValue(id, prop);
  1017. }
  1018. renderTableInfo($('#onlinePlayers'), pastValueResolver);
  1019. }
  1020.  
  1021. function markTableRowWithId(id, mark)
  1022. {
  1023. var tr = $('table:contains("ID")').find('tr:contains("' + id +'")');
  1024. if (tr && mark)
  1025. {
  1026. $(tr).css("background-color", "#9400D3");
  1027. $('html, body').animate({
  1028. scrollTop: ($(tr).first().offset().top)
  1029. },10);
  1030. }
  1031. else if (tr)
  1032. {
  1033. $(tr).css("background-color", "");
  1034. }
  1035. }
  1036.  
  1037.  
  1038. function getPreviousVal(id, treshold, property)
  1039. {
  1040. var arr = filterDbValuesByTimeTreashold(id, treshold);
  1041. var values = arr
  1042. .filter(function(val) {return val[property]})
  1043. .map(e => e[property])
  1044. .map((e, i, final) => final.indexOf(e) === i && i)
  1045. .filter(e => arr[e])
  1046. .map(e => arr[e]);
  1047.  
  1048. if (values.length > 1)
  1049. {
  1050. return values[1];
  1051. }
  1052. }
  1053.  
  1054. function getLastDiff(id, treshold, property)
  1055. {
  1056. var values = filterDbValuesByTimeTreashold(id, treshold)
  1057. .map(function(val) {return val[property]})
  1058. .filter(function(val) {return val})
  1059. .filter(function(item, pos, self) {return self.indexOf(item) == pos;}); // remove redundances
  1060.  
  1061. var diff = 0;
  1062.  
  1063. if (values.length > 1)
  1064. {
  1065. diff = values[0] - values[1];
  1066. }
  1067.  
  1068. return diff;
  1069. }
  1070.  
  1071. function filterDbValuesByTimeTreashold(id, treshold)
  1072. {
  1073. var dbValues = JSON.parse(localStorage[id]);
  1074.  
  1075. dbValues.reverse();
  1076. return dbValues.filter(function(i) {return ((Math.abs(new Date() - new Date(i.date)) + 1000) / 36e5) < treshold;});
  1077. }
  1078.  
  1079. function renderNoteForPlayer()
  1080. {
  1081. $('.tt_player').on('click', function(event)
  1082. {
  1083. // how to get id?
  1084. var id = $(event.target).text().trim().substring(0,4);
  1085.  
  1086. var popup = $('.tooltip:contains("' + id + '")')[0];
  1087.  
  1088. $('.tooltip').css('background-color', 'black');
  1089. if ($(popup).find('textarea').length === 0)
  1090. {
  1091. $(popup).append('<br/><label>Notes for player</label><br/>');
  1092. $(popup).append('<textarea rows="4" cols="50" id="notes' + id + '"></textarea>');
  1093. $('#notes' + id).val(localStorage["notes" + id] ? localStorage["notes" + id] : '');
  1094. $('#notes' + id).on("change keyup paste click", function(event)
  1095. {
  1096. localStorage["notes" + id] = $('#notes' + id).val();
  1097. event.stopPropagation();
  1098. });
  1099. }
  1100. });
  1101. }
  1102.  
  1103. function sendSlackNotification(message)
  1104. {
  1105. // general channel
  1106. var channel = "https://hooks.slack.com/services/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";
  1107.  
  1108. var player = $('#governor').text();
  1109.  
  1110. if (player === 'princezna Xena')
  1111. {
  1112. channel = "https://hooks.slack.com/services/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";
  1113. }
  1114. else if (player === 'Jeina')
  1115. {
  1116. channel = "https://hooks.slack.com/services/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";
  1117. }
  1118.  
  1119. $.ajax({
  1120. data: 'payload=' + JSON.stringify({
  1121. "text": message
  1122. }),
  1123. dataType: 'json',
  1124. processData: false,
  1125. type: 'POST',
  1126. url: channel
  1127. });
  1128. }
  1129.  
  1130. function searchEnhance()
  1131. {
  1132. // only for search page
  1133. if (window.location.href.includes('multifunc'))
  1134. {
  1135. var rows = $('#search_results_table').find('tr:not(.heading):not(.tr_summary)')
  1136.  
  1137. $.each(rows,
  1138. function(index, el)
  1139. {
  1140. var id = $($(el).children()[0]).text().trim().substring(0,4);
  1141. var powerCol = $(el).children()[4];
  1142. var atackCol = $(el).children()[7];
  1143. var power = Number($(powerCol).text().trim());
  1144. var powerMine = Number($('.value_power').text());
  1145.  
  1146. $(atackCol).append('<br/><a id="adjustArmy' + id +'" style="color: green;">Pripravit armadu</a>');
  1147. $('#adjustArmy' + id).click(
  1148. function() {
  1149. localStorage.powerDiff = (power * 1.245) - powerMine;
  1150. var win = window.open($("a:contains('Armáda')" ).attr('href'));
  1151. win.focus();
  1152. });
  1153. });
  1154.  
  1155. }
  1156. }
  1157.  
  1158. function isLogged()
  1159. {
  1160. return $('#player_detail').length > 0
  1161. }
  1162.  
  1163. function autoLoginSettings()
  1164. {
  1165. $('#left_column_wrapper').append('<br/><label style="padding-right: 25px;">Auto login (s)</label>');
  1166. $('#left_column_wrapper').append('<input id="autoLogin" type="checkbox"/>');
  1167. $('#left_column_wrapper').append('<input type="text" id="autoLoginInterval" style="width: 120px;"/><br/>');
  1168.  
  1169. $('#autoLogin').prop('checked', localStorage.autoLogin === "true");
  1170. $('#autoLogin').on("change keyup paste", function() {localStorage.autoLogin = $("#autoLogin").is(':checked');});
  1171. $('#autoLoginInterval').val(localStorage.autoLoginInterval ? localStorage.autoLoginInterval : '');
  1172. $('#autoLoginInterval').on("change keyup paste", function() { localStorage.autoLoginInterval = $('#autoLoginInterval').val();});
  1173. }
  1174. if (isLogged())
  1175. {
  1176. autoLoginSettings();
  1177. searchEnhance();
  1178. checkCs();
  1179. renderNoteForPlayer();
  1180. renderPlayersOnline();
  1181. makeTableOrderable();
  1182. renderNotes();
  1183. checkBestiar();
  1184. powerDiffAlarm();
  1185. renderPlayers();
  1186. renderShieldStackPerc();
  1187. myPower();
  1188. kokotMeasure();
  1189. renderHistoryTextField();
  1190. main();
  1191. spies();
  1192. autorefresh();
  1193. checkNewMessage();
  1194. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement