Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // ==UserScript==
- // @name richard.kolisek
- // @version 1.8
- // @description utility
- // @grant none
- // @require http://code.jquery.com/jquery-1.10.2.min.js
- // @require https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.4.0/Chart.bundle.min.js
- // @include http://www.meliorannis.com/*
- // ==/UserScript==
- var searchHoursInPast;
- var percentColors = [
- { pct: 0.0, color: { r: 0xff, g: 0x00, b: 0 } },
- { pct: 0.5, color: { r: 168, g: 168, b: 168 } },
- { pct: 1.0, color: { r: 0x00, g: 0xff, b: 0 } } ];
- var percentToColor = function(pct)
- {
- for (var i = 0; i < percentColors.length; i++)
- {
- if (pct <= percentColors[i].pct)
- {
- var lower = (i === 0) ? percentColors[i] : percentColors[i - 1];
- var upper = (i === 0) ? percentColors[i + 1] : percentColors[i];
- var range = upper.pct - lower.pct;
- var rangePct = (pct - lower.pct) / range;
- var pctLower = 1 - rangePct;
- var pctUpper = rangePct;
- var color =
- {
- r: Math.floor(lower.color.r * pctLower + upper.color.r * pctUpper),
- g: Math.floor(lower.color.g * pctLower + upper.color.g * pctUpper),
- b: Math.floor(lower.color.b * pctLower + upper.color.b * pctUpper)
- };
- return 'rgb(' + [color.r, color.g, color.b].join(',') + ')';
- }
- }
- };
- function getLastDbValue(id, property)
- {
- var dbValues = localStorage[id];
- if (dbValues)
- {
- dbValues = JSON.parse(dbValues);
- dbValues.reverse();
- for (var i in dbValues) {
- var hourDifference = Math.abs(new Date() - new Date(dbValues[i].date)) / 36e5;
- if (searchHoursInPast && hourDifference > searchHoursInPast)
- {
- if (dbValues[i][property])
- return dbValues[i][property];
- }
- else if (!searchHoursInPast)
- {
- if (dbValues[i][property])
- return dbValues[i][property];
- }
- }
- }
- return -1;
- }
- function renderChangesValue(id, power, area, powerPos, areaPos, row, ot, otPos)
- {
- var powerDb = getLastDbValue(id, 'power');
- var areaDb = getLastDbValue(id, 'area');
- var otDb = getLastDbValue(id, 'ot');
- var columns = $(row).children();
- var powerColumn = $(columns[powerPos]);
- renrerValue(id, 'power', power, powerDb==-1 ? power : powerDb, true, powerColumn);
- $('#' + id + '-dialog').click(function() {
- $('#' + id + '-dialog').css("display", "none");
- });
- if(areaPos)
- {
- var areaColumn = $(columns[areaPos]);
- renrerValue(id, 'area', area, areaDb==-1 ? area : areaDb, false, areaColumn);
- }
- if (otPos)
- {
- var otPlus = Number(ot) - Number(otDb);
- if (otPlus || otPlus > -1)
- {
- var otColumn = $(columns[otPos]);
- renrerValue(id, 'ot', otPlus, otPlus, false, otColumn);
- }
- }
- }
- function renrerValue(id, type, value, valueDb, isPercent, whereToRender)
- {
- var percent = Math.round(percent * 10) / 10;
- percent = (value / (valueDb / 100) - 100).toFixed(1) + '%';
- var val = (Math.round((value - valueDb) / 100) / 10) + 'k';
- if (type === 'ot')
- {
- val = value;
- }
- var element = '<font size="2" class="to-remove">(<span id="' + id + '-' + type + '" class="' + type +'">' + (isPercent ? percent : val) + '</span>)';
- whereToRender.append(element);
- whereToRender.click(function()
- {
- var storage = localStorage[id];
- var fakeRowId = 'fakeRow' + id;
- if (storage && $('#' + fakeRowId).length === 0)
- {
- var data = JSON.parse(storage);
- data.reverse();
- $('<tr class="fakeRow"><td colspan="20" >' +
- '<div id="' + fakeRowId + '"style="background-color: white; width: 800px;"></div>' +
- '</td></tr>').insertAfter($(whereToRender.parent()));
- renderChart(data, 'power', id, $('#' + fakeRowId));
- renderChart(data, 'area', id, $('#' + fakeRowId));
- renderChart(data, 'ot', id, $('#' + fakeRowId));
- $('#' + fakeRowId).click(function() {$('.fakeRow').remove();});
- }
- else
- {
- $('.fakeRow').remove();
- }
- });
- }
- function renderChart(data, type, id, elemtToAppend)
- {
- var chartId = type + 'Chart' + id;
- $(elemtToAppend).append('<canvas id="' + chartId + '" width="1000" height="200"/>');
- var datasets = createDataSet(data, type);
- var tempData = {
- type: "line",
- data: {
- datasets : [ {label : datasets.label, data : datasets.data}]
- },
- options: {
- responsive : true,
- scales: {
- yAxes: [
- { position : 'right'}
- ],
- xAxes: [{
- type: 'time',
- unit: 'hour',
- unitStepSize: 1,
- time: {
- displayFormats: {
- 'millisecond': 'HH:mm',
- 'second': 'HH:mm',
- 'minute': 'HH:mm',
- 'hour': 'HH:mm',
- 'day': 'HH:mm',
- 'week': 'HH:mm',
- 'month': 'HH:mm',
- 'quarter': 'HH:mm',
- 'year': 'HH:mm',
- },
- round : 'hour'
- }
- }]
- },
- title: {
- display: false
- }
- },
- };
- var ctx = document.getElementById(chartId).getContext("2d");
- new Chart(ctx, tempData);
- }
- function createDataSet(data, type)
- {
- var includedHours = [];
- var hoursBack = 48;
- var clearData = $(data).filter(
- function(index, row)
- {
- var hourDiff = Math.round(((new Date() - new Date(row.date)) / 36e5) * 10) / 10;
- // every 1/10h should have one value, 24h back
- var result = row[type] && hourDiff < hoursBack;// && !includedHours.includes(hourDiff);
- includedHours.push(hourDiff);
- return result;
- });
- var labels = [], chartData=[];
- var yesterday = new Date(new Date().getTime() - (hoursBack * 60 * 60 * 1000));
- chartData.push({x : yesterday, y : null});
- $.each(clearData, function(index, packet) {
- chartData.push({x : new Date(packet.date), y : parseFloat(packet[type])});
- });
- var now = new Date();
- chartData.push({x : now, y : null});
- return { label : type, labels : labels, data: chartData };
- }
- function formatDate(date)
- {
- var d = new Date(date);
- return [d.getDate(), (d.getMonth()+1)].join('.') + ' ' +
- [ d.getHours(), d.getMinutes()].join(':');
- }
- function spies()
- {
- var table = $('#spies_report');
- if (table)
- {
- var id = table.find('sup').text().replace('(', '').replace(')', '');
- var powerColumn = table.find('td:contains("Síla provincie")').next();
- var power = Number(powerColumn.text().split('(')[0]);
- var powerMine = Number($('.value_power').text());
- var powerDb = getLastDbValue(id, 'power');
- if (powerColumn.length !== 0)
- {
- powerColumn.append('<br/><a id="adjustArmy">Pripravit armadu na utok</a>');
- renrerValue(id, 'power', power, powerDb==-1 ? power : powerDb, true, powerColumn);
- }
- $('#adjustArmy').click(
- function() {
- localStorage.powerDiff = (power * 1.245) - powerMine;
- window.location.href = $( "a:contains('Armáda')" ).attr('href');
- });
- }
- $('#left_column_wrapper').append('<label>Nazev jednotky stitu</label><br/>');
- $('#left_column_wrapper').append('<input type="text" id="shieldUnit" style="width: 120px;" />');
- $('#shieldUnit').css('background', 'url("/html/img/inputs_sprite.png") 0 0 no-repeat transparent');
- $('#shieldUnit').val(localStorage.shieldUnit ? localStorage.shieldUnit : '');
- $('#shieldUnit').on("change keyup paste", function() { localStorage.shieldUnit = $('#shieldUnit').val();});
- if (localStorage.powerDiff && localStorage.powerDiff !== '' && localStorage.shieldUnit)
- {
- var selectUnit = $($('select')[1]).find('option:contains(' + localStorage.shieldUnit + ')').val();
- var unitPower = Number($('#army_table_army tr:contains(' + localStorage.shieldUnit + ') .army_unit_power').text());
- var unitExp = Number($('#army_table_army tr:contains(' + localStorage.shieldUnit + ') .army_unit_exp').text().replace('%', '').trim());
- var oneUnitPower;
- if (localStorage.powerDiff < 0)
- {
- oneUnitPower = (unitPower / 100) * unitExp;
- $($('select')[0]).val(selectUnit);
- $($('input[name="kolik"]')[0]).val(Math.abs(Math.round(localStorage.powerDiff / oneUnitPower)));
- $($('input[name="kolik"]')[0]).change();
- }
- else
- {
- oneUnitPower = unitPower * 0.4;
- $($('select')[1]).val(selectUnit);
- $($('input[name="kolik"]')[1]).val(Math.abs(Math.round(localStorage.powerDiff / oneUnitPower)));
- $($('input[name="kolik"]')[1]).change();
- }
- localStorage.powerDiff = '';
- }
- }
- function makeTableOrderable()
- {
- var tables = $('table:contains("Síla"):contains("ID")');
- $.each(
- tables,
- function (i, table)
- {
- var headRow = $(table).find('.heading');
- var headColumns = $(headRow).find('td');
- $.each(headColumns,
- function (index, value)
- {
- $(value).click(function(){
- var table = $(this).parents('table').eq(0)
- var rows = table.find('tr:gt(0)').toArray().sort(comparer($(this).index()))
- this.asc = !this.asc
- if (!this.asc){rows = rows.reverse()}
- for (var i = 0; i < rows.length; i++){table.append(rows[i])}
- })
- });
- });
- function comparer(index) {
- return function(a, b) {
- var valA = getCellValue(a, index);
- var valB = getCellValue(b, index);
- if ($.isNumeric(valA.replace(" ", "").replace(/ *\([^)]*\) */g, "")))
- {
- valA = valA.replace(" ", "").replace(/ *\([^)]*\) */g, "");
- valB = valB.replace(" ", "").replace(/ *\([^)]*\) */g, "");
- }
- return $.isNumeric(valA) && $.isNumeric(valB) ? valA - valB : valA.toString().localeCompare(valB);
- }
- }
- function getCellValue(row, index){ return $(row).children('td').eq(index).text() }
- }
- function main()
- {
- var tables = $('table:contains("Síla"):contains("ID")');
- $.each(
- tables,
- function (i, table)
- {
- var rows = $(table).find('tr');
- var headRow = rows.filter(
- function(index, row)
- {
- return $(row).find('td:contains("ID")').length==1;
- }
- );
- var idPos;
- var namePos;
- var powerPos;
- var areaPos;
- var otPos;
- var headColumns = $(headRow).find('td');
- $.each(headColumns,
- function (index, value)
- {
- var text = $(value).text().trim();
- console.log('head text: -' + text + '-');
- if(text==='ID')
- idPos = index;
- if(text==='Regent')
- namePos = index;
- if(text.indexOf("Síla")===0)
- powerPos = index;
- if(text==='Rozloha' || text === 'hAR')
- areaPos = index;
- if(text==='O.T.')
- otPos = index;
- if (text === 'Titul')
- $('td:nth-child(' + (index + 1) + ')').hide();
- }
- );
- console.log('powerPos: ' + powerPos);
- console.log('areaPos: ' + areaPos);
- console.log('otPos: ' + otPos);
- $.each(rows,
- function (index, value)
- {
- if (index > 0) // skip header row
- {
- var columns = $(value).children();
- var id = $(columns[idPos]).children("span").clone().children().remove().end().text().trim();
- var name = $(columns[namePos]).text().trim();
- var power = $(columns[powerPos]).text().split('*').join('').trim();
- var prot = $(value).text().indexOf('*') != -1 || $(value).find('.listings_prot_mil').length;
- var area;
- var ot;
- if(areaPos)
- area = $(columns[areaPos]).text().trim();
- if(otPos)
- ot = $(columns[otPos]).text().trim();
- renderChangesValue(id, power, area, powerPos, areaPos, value, ot, otPos);
- if(!isNaN(parseFloat(id)))
- {
- var data = localStorage[id];
- var array = [];
- var lastDbValPower = getLastDbValue(id, 'power');
- var lastDbValOt = getLastDbValue(id, 'ot');
- var lastDbValArea = getLastDbValue(id, 'area');
- var dataChanged = true;
- if (lastDbValPower || lastDbValOt)
- dataChanged = (power && power !== lastDbValPower) || (ot && ot !== lastDbValOt) || (area && area !== lastDbValArea);
- if(data)
- array= JSON.parse(data);
- if (dataChanged && power)
- {
- array.push({"power" : power, "area" : area, "date" : Date(), "ot": ot});
- localStorage[id] = JSON.stringify(array);
- }
- updatePlayer(id, name, Number(power), prot);
- }
- }
- }
- );
- }
- );
- colorPercentages('.power');
- colorPercentages('.area');
- colorPercentages('.ot');
- }
- function colorPercentages(selector)
- {
- var percentElements = $(selector);
- var percentValues = $.map(
- percentElements,
- function(value)
- {
- return $(value).text().replace('k','').replace('%', '').replace('(', '').replace(')', '');
- }
- );
- var percentMax = Math.max.apply(Math, percentValues);
- var percentMin = Math.min.apply(Math, percentValues);
- percentMax = percentMax === 0 ? 1 : percentMax;
- percentMin = percentMin === 0 ? 1 : percentMin;
- $.each(
- percentElements,
- function(index, value)
- {
- var currentValue = $(value).text().replace('k','').replace('%', '').replace('(', '').replace(')', '');
- var relativePercent = 0;
- if(currentValue >= 0)
- {
- relativePercent = 50 + (Math.abs(currentValue) / (Math.abs(percentMax) / 50));
- }
- else
- {
- relativePercent = 50 - (Math.abs(currentValue) / (Math.abs(percentMin) / 50));
- }
- $(value).css('color', percentToColor(relativePercent / 100));
- }
- );
- }
- function renderHistoryTextField()
- {
- var tables = $('table:contains("Síla"):contains("ID")');
- $.each(
- tables,
- function (i, table)
- {
- $(table).after("<label>Pocet hodin do zadu</label><input id='hour-field' type='text'/>");
- });
- $('#hour-field').change(function() {
- searchHoursInPast = Number($( this ).val().trim());
- $( ".to-remove" ).remove();
- main();
- });
- }
- function kokotMeasure()
- {
- if (!localStorage.kokotMeasure)
- localStorage.kokotMeasure = 0;
- localStorage.kokotMeasure = Number(localStorage.kokotMeasure) + 1;
- $('body').append('<label style="position: absolute; left: 0; top: 0;">Jak velky jsi kokot: ' + localStorage.kokotMeasure + '</div>');
- }
- function myPower()
- {
- var power = $('.value_power').text();
- var powerDb = Number(localStorage.me);
- var powerDifference = (power - powerDb);
- if (powerDifference)
- {
- $('#LS_power_value').append('<span id="powerId" style="padding-left: 5px;">' + powerDifference + '</span>');
- if (powerDifference < 0)
- {
- $('#powerId').css('color', 'RGB(255, 0, 0)');
- document.title = 'Pokles o ' + powerDifference;
- beep(powerDifference);
- }
- else
- {
- $('#powerId').css('color', 'RGB(0, 255, 0)');
- }
- }
- localStorage.me = power;
- }
- function beep(difference)
- {
- if (localStorage.powerDiffEnabled === "true" && Math.abs(difference) > Number(localStorage.powerDiffTreshold))
- {
- (new Audio('http://www.freespecialeffects.co.uk/soundfx/music/trumpets.wav')).play();
- }
- }
- function checkNewMessage()
- {
- if (!localStorage.powerDiffTreshold)
- {
- localStorage.powerDiffTreshold = 0;
- }
- $('#left_column_wrapper').append('<br/><label style="padding-right: 25px;">New message notifier</label>');
- $('#left_column_wrapper').append('<input id="messageNotifier" type="checkbox"/><br/>');
- $('#messageNotifier').prop('checked', localStorage.messageNotifier === "true");
- $('#messageNotifier').on("change keyup paste", function() {localStorage.messageNotifier = $("#messageNotifier").is(':checked');});
- if ($('.new_post').length > 0 && localStorage.messageNotifier === "true")
- {
- (new Audio('https://www.mediacollege.com/downloads/sound-effects/star-trek/tng/tng-worf-incomingmessage.wav')).play();
- }
- }
- function renderShieldStackPerc()
- {
- var shieldPwrElem = $('#econ_units_list').find('tr.tr_even:first > td:nth-child(6)');
- var shieldPwr = Number(shieldPwrElem.text());
- var totalPwr = Number($('#econ_units_list').find('.tr_econ_summary > td:nth-child(3)').text());
- if (shieldPwr && totalPwr)
- {
- var shieldPerc = (100 * shieldPwr) / totalPwr;
- shieldPwrElem.append(' (<span style="color: RGB(0, 255, 0);">' + shieldPerc.toFixed(1) + '%</span>)');
- }
- }
- function renderNotes()
- {
- $('#left_column_wrapper').append('<br/><label>Notes</label><br/>');
- $('#left_column_wrapper').append('<textarea rows="4" cols="50" id="notes"></textarea>');
- $('#notes').val(localStorage.notes ? localStorage.notes : '');
- $('#notes').on("change keyup paste", function() {
- localStorage.notes = $('#notes').val();
- });
- }
- function getPlayer() {
- return $('#player_detail').find('.governor').text().trim();
- }
- var apiKey = 'axde8wuFzZUNAeK1UMqaovDhD49TCa5X';
- var database = 'https://api.mlab.com/api/1/databases/ma/';
- var csColl = database + "collections/cs?apiKey=" + apiKey;
- var playerColl = database + "collections/players?apiKey=" + apiKey;
- // make ajax get to load all cs from DB and pass it to callback
- // usage: getAllCs(function(data) {...})
- function getAllCs(callback) {
- $.get(csColl, callback);
- }
- // remove all player cs
- function removePlayerCs(player, successCallback) {
- $.ajax({url: csColl + '&q={"player":"' + player + '"}',
- data: JSON.stringify([]),
- type: "PUT",
- contentType: "application/json",
- success: successCallback});
- }
- // insert given cs to database
- function insertPlayerCs(player, id, regent, aliance, time, power, pass, protection, result) {
- var cs = {
- "id": id,
- "regent": regent,
- "aliance": aliance,
- "time": time,
- "power": power,
- "pass": pass,
- "protection": protection,
- "result": result,
- "player": player,
- "lastUpdate": new Date()
- };
- $.ajax({url: csColl,
- data: JSON.stringify(cs),
- type: "POST",
- contentType: "application/json" });
- }
- function getAllPlayers(callback) {
- $.get(playerColl + '&s={"power": -1}', callback);
- }
- function updatePlayer(id, name, power, protection) {
- if (id && name && power) {
- var player = {
- "id": id,
- "name": name,
- "power": power,
- "protection": protection,
- "lastUpdate": new Date()
- };
- $.ajax({url: playerColl + '&q={"id":"' + id + '"}&u=true',
- data: JSON.stringify(player),
- type: "PUT",
- contentType: "application/json" });
- }
- }
- function updateAllCs() {
- var player = getPlayer();
- var csRows = $('div.attacks_list_wrapper:contains(Bráněné útoky)').find('.attacks_table > tbody > tr[class!="heading"]:contains(nevráceno)');
- if (csRows.length) {
- removePlayerCs(player, function() {
- $.each(csRows, function (i, csRow) {
- var id = $(csRow).find('td.attacks_id').text().split(" ")[0].trim();
- var regent = $(csRow).find('td.attacks_regent').text().trim();
- var aliance = $(csRow).find('td.attacks_aliance').text().trim();
- var time = $(csRow).find('td.attacks_time').text().split(" ")[0].trim().replace('(', '').replace(')', '');
- var power = $(csRow).find('td.attacks_pwr').text().split("(")[0].trim();
- var pass = $(csRow).find('td.attacks_pass').text().trim();
- var protection = $(csRow).find('td.attacks_attack').text().indexOf("*") != -1;
- var attacker = $(csRow).find('td.attacks_attacker').text().trim();
- var defender = $(csRow).find('td.attacks_defender').text().trim();
- var result = attacker + " : " + defender;
- insertPlayerCs(player, id, regent, aliance, time, power, pass, protection, result);
- });
- });
- }
- }
- function renderCs() {
- function groupCsByPlayer(csArray) {
- var csByPlayer = {};
- for (var i = 0; i < csArray.length; i++) {
- if (!csByPlayer[csArray[i].player])
- csByPlayer[csArray[i].player] = [];
- csByPlayer[csArray[i].player].push(csArray[i]);
- }
- return csByPlayer;
- }
- function getPlayerCsTable(player, cs) {
- var tableStart =
- '<div class="attacks_list_wrapper">' +
- '<div class="attacks_wrapper">' +
- '<div class="attacks_type_wrapper">' + player + '</div>' +
- '<table class="attacks_table"><tbody>' +
- '<tr class="heading">' +
- '<td class="attacks_id">ID</td>' +
- '<td class="attacks_regent">Regent</td>' +
- '<td class="attacks_aliance">Aliance</td>' +
- '<td class="attacks_time">Doba od útoku</td>' +
- '<td class="attacks_pwr">Síla</td>' +
- '<td class="attacks_pass">Status útoku</td>' +
- '<td class="attacks_protection"></td>' +
- '<td class="attacks_result">Ztráty útočník : obránce</td>' +
- '</tr>';
- for (var i = 0; i < cs.length; i++) {
- tableStart = tableStart +
- '<tr>' +
- '<td class="attacks_id">' + cs[i].id + '</td>' +
- '<td class="attacks_regent">' + cs[i].regent + '</td>' +
- '<td class="attacks_aliance">' + cs[i].aliance + '</td>' +
- '<td class="attacks_time">' + cs[i].time + '</td>' +
- '<td class="attacks_pwr">' + cs[i].power + '</td>' +
- '<td class="attacks_pass">' + cs[i].pass + '</td>' +
- '<td class="attacks_protection">' + (cs[i].protection ? '*' : '') + '</td>' +
- '<td class="attacks_result">' + cs[i].result + '</td>' +
- '</tr>';
- }
- var tableEnd = '</tbody></table></div></div>';
- return tableStart + tableEnd;
- }
- var csLink = $('#Attacks_list_detail a').attr("href").replace("vypis=utoky_detailne", "cs");
- $('#Attacks_list_detail').after('<li id="csLink"><a href="' + csLink + '">Cska</a></li>');
- if (window.location.href.indexOf("cs") != -1) {
- $('#central_column_bottom').empty();
- getAllCs(function(data) {
- var csByPlayer = groupCsByPlayer(data);
- for (var player in csByPlayer) {
- if (csByPlayer.hasOwnProperty(player)) {
- $('#central_column_bottom').append(getPlayerCsTable(player, csByPlayer[player]));
- }
- }
- });
- }
- }
- function formatDuration(duration) {
- var seconds = (duration / 1000).toFixed(0);
- if (seconds > 60) {
- var minutes = (seconds / 60).toFixed(0);
- if (minutes > 60) {
- var hours = (minutes / 60).toFixed(0);
- if (hours > 24) {
- var days = (hours / 24).toFixed(0);
- return "před " + days + "d";
- } else {
- return "před " + hours + "h";
- }
- } else {
- return "před " + minutes + "m";
- }
- } else {
- return "před " + seconds + "s";
- }
- }
- function renderPlayers() {
- function getPlayerTable(players) {
- var currentTime = new Date();
- var tableStart =
- '<table id="listings_table_top20"><tbody>' +
- '<tr class="heading">' +
- '<td class="attacks_id">ID</td>' +
- '<td class="attacks_regent">Regent</td>' +
- '<td class="attacks_pwr">Síla</td>' +
- '<td class="attacks_protection"></td>' +
- '<td class="attacks_time">Čas vložení</td>' +
- '</tr>';
- for (var i = 0; i < players.length; i++) {
- tableStart = tableStart +
- '<tr>' +
- '<td class="attacks_id">' + players[i].id + '</td>' +
- '<td class="attacks_regent">' + players[i].name + '</td>' +
- '<td class="attacks_pwr">' + players[i].power + '</td>' +
- '<td class="attacks_protection">' + (players[i].protection ? '*' : '') + '</td>' +
- '<td class="attacks_time">' + (formatDuration(Math.abs(currentTime - new Date(players[i].lastUpdate)))) + '</td></tr>';
- }
- var tableEnd = '</tbody></table></div></div>';
- return tableStart + tableEnd;
- }
- var playersLink = $('#Attacks_list_detail a').attr("href").replace("vypis=utoky_detailne", "players");
- $('#Attacks_list_detail').after('<li id="playersLink"><a href="' + playersLink + '">Hráči</a></li>');
- if (window.location.href.indexOf("players") != -1) {
- $('#central_column_bottom').empty();
- getAllPlayers(function(data) {
- $('#central_column_bottom').append(getPlayerTable(data));
- });
- }
- }
- function autorefresh()
- {
- $('#left_column_wrapper').append('<br/><label>Auto hlidka (sec)</label><br/>');
- $('#left_column_wrapper').append('<input id="watchInterval" type="text" style="width: 120px;">');
- $('#left_column_wrapper').append('<input id="autoWatch" type="checkbox"/><br/>');
- $('#autoWatch').css('position', 'absolute');
- $('#autoWatch').css('top', '20px');
- $('#autoWatch').css('left', '5px');
- $('#watchInterval').css('background', 'url("/html/img/inputs_sprite.png") 0 0 no-repeat transparent');
- $('#watchInterval').val(localStorage.watchInterval ? localStorage.watchInterval : '');
- $('#watchInterval').on("change keyup paste", function() { localStorage.watchInterval = $('#watchInterval').val();});
- $('#autoWatch').prop('checked', localStorage.autoWatch === "true");
- var timer;
- if (localStorage.autoWatch === "true")
- {
- timer = startTimer();
- }
- $('#autoWatch').on("change keyup paste",
- function()
- {
- localStorage.autoWatch = $("#autoWatch").is(':checked');
- if ($("#autoWatch").is(':checked'))
- {
- timer = startTimer();
- }
- else if(timer)
- {
- clearInterval(timer);
- }
- });
- }
- function startTimer()
- {
- var counter = Number(localStorage.watchInterval) * 1000;
- var timer = setTimeout(
- function()
- {
- var type = Math.floor(Math.random() * 13);
- console.log(type);
- if (type < 4)
- {
- window.location.href = $( "a:contains('Bestiář')" ).attr('href');
- }
- else if (type < 8 && type >= 4)
- {
- window.location.href = $( "a:contains('Výpis útoků')" ).attr('href');
- }
- else if (type === 8)
- {
- window.location.href = $( "a:contains('Armáda')" ).attr('href');
- }
- else if (type === 9)
- {
- window.location.href = $( "a:contains('Hospodaření')" ).attr('href');
- }
- else if (type === 10)
- {
- window.location.href = $( "a:contains('Magie a kouzla')" ).attr('href');
- }
- else if (type === 11)
- {
- window.location.href = $( "a:contains('Moje aliance')" ).attr('href');
- }
- else if (type === 12)
- {
- window.location.href = $( "a:contains('Obrana')" ).attr('href');
- }
- timer = setTimeout(this, 1000 + counter * Math.random());
- }, (2500 + counter * Math.random()));
- return timer;
- }
- function powerDiffAlarm()
- {
- if (!localStorage.powerDiffTreshold)
- {
- localStorage.powerDiffTreshold = 0;
- }
- $('#left_column_wrapper').append('<br/><label style="padding-right: 25px;">Power alarm (power)</label>');
- $('#left_column_wrapper').append('<input id="powerDiffEnabled" type="checkbox"/><br/>');
- $('#powerDiffEnabled').prop('checked', localStorage.powerDiffEnabled === "true");
- $('#powerDiffEnabled').on("change keyup paste", function() {localStorage.powerDiffEnabled = $("#powerDiffEnabled").is(':checked');});
- $('#left_column_wrapper').append('<input id="powerDiffTreshold" type="text" style="width: 120px;"><br/>');
- $('#powerDiffTreshold').css('background', 'url("/html/img/inputs_sprite.png") 0 0 no-repeat transparent');
- $('#powerDiffTreshold').val(localStorage.powerDiffTreshold);
- $('#powerDiffTreshold').on("change keyup paste", function() { localStorage.powerDiffTreshold = $('#powerDiffTreshold').val();});
- }
- function checkBestiar()
- {
- $('#left_column_wrapper').append('<br/><label style="padding-right: 25px;">Bestiar check (unit.exp,unit2.exp)</label>');
- $('#left_column_wrapper').append('<input id="bestiarEnabled" type="checkbox"/><br/>');
- $('#bestiarEnabled').prop('checked', localStorage.bestiarEnabled === "true");
- $('#bestiarEnabled').on("change keyup paste", function() { localStorage.bestiarEnabled = $("#bestiarEnabled").is(':checked'); });
- $('#left_column_wrapper').append('<textarea id="bestiarText" rows="2" cols="50"><br/>');
- $('#bestiarText').val(localStorage.bestiarText ? localStorage.bestiarText : '');
- $('#bestiarText').on("change keyup paste", function() { localStorage.bestiarText = $('#bestiarText').val();});
- if (window.location.pathname.includes("obchod") && localStorage.bestiarText && localStorage.bestiarEnabled === "true")
- {
- var unitExpPairs = localStorage.bestiarText.split(",");
- var count = 0;
- $.each(unitExpPairs,
- function(index, unitExpPair)
- {
- var unit = unitExpPair.split(".")[0].trim();
- var exp = Number(unitExpPair.split(".")[1].trim());
- var stack;
- if (unit.includes("#"))
- {
- stack = unit.split('#')[1].trim();
- unit = unit.split('#')[0].trim();
- }
- // unit elements
- var elements = $("#beast_shop tr:not(.best_me_buyer):contains('" + unit + "')");
- elements = elements.filter(
- function(i, el)
- {
- var expEl = $(el).find(".beast_shop_unit_exp");
- var stackV = $(el).find(".beast_shop_unit_stack");
- return exp <= Number($(expEl).text().replace('%', '')) || stack <= Number($(stackV).text());
- }
- );
- $.each(elements,
- function(index, el)
- {
- $(el).css('background-color', 'darkred');
- });
- // contains unit
- if (elements.length !== 0)
- {
- if (unit === 'Str')
- {
- unit = "Shooter stack bigger " + stack;
- }
- var url = 'http://api.voicerss.org/?key=9ed0aef9a2c64bc5abd65ca333588164&c=wav&hl=ru-ru&src=' + unit;
- setTimeout(function(){
- (new Audio(url)).play();}, 1000 * count);
- count++;
- }
- }
- );
- }
- }
- function checkCs() {
- var csList = $(".attacks_list_wrapper:contains('Bráněné útoky') > .attacks_wrapper > .attacks_table > tbody > tr:not('.heading'):contains('nevráceno')");
- var count = 0;
- $.each(csList, function (i, cs) {
- var name = $(cs).find('.attacks_regent').text();
- var powerDiff = Number($(cs).find('.attacks_pwr').text().split('%')[0].split('(')[1]);
- console.log(cs);
- if (powerDiff < 0) {
- var url = 'http://api.voicerss.org/?key=9ed0aef9a2c64bc5abd65ca333588164&c=wav&hl=ru-ru&src=' + name + '%20down';
- setTimeout(function() {
- (new Audio(url)).play();}, 1000 * count);
- count++;
- }
- });
- }
- function renderPlayersOnline()
- {
- $('#left_column_wrapper').append('<br/><label style="padding-right: 25px;">Online player treshold (h)</label>');
- $('#left_column_wrapper').append('<input id="onlinePlayerEnabled" type="checkbox"/><br/>');
- $('#onlinePlayerEnabled').prop('checked', localStorage.onlinePlayerEnabled === "true");
- $('#onlinePlayerEnabled').on("change keyup paste", function(){localStorage.onlinePlayerEnabled = $("#onlinePlayerEnabled").is(':checked');});
- $('#left_column_wrapper').append('<input type="text" id="onlinePlayerTreshold" style="width: 120px;" /><br/>');
- $('#onlinePlayerTreshold').val(localStorage.onlinePlayerTreshold ? localStorage.onlinePlayerTreshold : '');
- $('#onlinePlayerTreshold').on("change keyup paste", function() { localStorage.onlinePlayerTreshold = $('#onlinePlayerTreshold').val();});
- if (!localStorage.onlinePlayerTreshold)
- {
- localStorage.onlinePlayerTreshold = 0.5;
- }
- if (localStorage.onlinePlayerEnabled !== "true")
- {
- return;
- }
- var tableContent = Array.apply(0, new Array(localStorage.length))
- .map(function (o, i) {return localStorage.key(i);})
- .filter(function(i){return /^\d+$/.test(i)})
- .filter(function(id)
- {
- var treshold = Number(localStorage.onlinePlayerTreshold);
- var dbValues = filterDbValuesByTimeTreashold(id, treshold);
- if (dbValues.length > 1)
- {
- var hourDifference = Math.abs(new Date(dbValues[0].date) - new Date(dbValues[dbValues.length-1].date)) / 36e5;
- var currectHourDifference = Math.abs(new Date() - new Date(dbValues[0].date)) / 36e5;
- var otsDiff = getLastOtsDiff(id, treshold);
- return hourDifference < treshold && currectHourDifference < treshold && otsDiff !== 0;
- }
- return false;
- })
- .map(function(id)
- {
- var treshold = Number(localStorage.onlinePlayerTreshold);
- var powerDb = getLastDbValue(id, 'power');
- var areaDb = getLastDbValue(id, 'area');
- var timeDiff = Math.abs(new Date() - new Date(getLastDbValue(id, 'date')));
- var otsDiff = getLastOtsDiff(id, treshold);
- return '<tr><td>' + id + '</td><td>' + powerDb + '</td><td>' + areaDb + '</td><td>+' + otsDiff + '</td><td>' + formatDuration(timeDiff) + '</td></tr>';
- })
- .join('');
- $('#right_column_wrapper').append('<table id="onlinePlayers">' +
- '<tr><td colspan="5">Last online players</td></tr>' +
- '<tr><td>ID</td><td>Síla</td><td>hAR</td><td>O.T.+</td><td><td></tr>' +
- tableContent +
- '</table>');
- }
- function getLastOtsDiff(id, treshold)
- {
- var ots = filterDbValuesByTimeTreashold(id, treshold)
- .map(function(val) {return val.ot})
- .filter(function(val) {return val});
- var otDiff = 0;
- if (ots.length > 1)
- {
- otDiff = ots[0] - ots[1];
- }
- return otDiff;
- }
- function filterDbValuesByTimeTreashold(id, treshold)
- {
- var dbValues = JSON.parse(localStorage[id]);
- dbValues.reverse();
- return dbValues.filter(function(i) {return (Math.abs(new Date() - new Date(i.date)) / 36e5) < treshold;});
- }
- makeTableOrderable();
- renderNotes();
- checkBestiar();
- powerDiffAlarm();
- renderCs();
- renderPlayers();
- renderShieldStackPerc();
- myPower();
- kokotMeasure();
- renderHistoryTextField();
- main();
- spies();
- autorefresh();
- updateAllCs();
- checkCs();
- renderPlayersOnline();
- checkNewMessage();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement