Advertisement
Guest User

Untitled

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