· 7 years ago · Oct 26, 2018, 03:54 PM
1// ==UserScript==
2// @name Vitae Def Package [VDP]
3// @version 1.0
4// @author Unfriendly Sander & Warre
5// @grant none
6// @include https://nl*.tribalwars.nl*
7// ==/UserScript==
8
9$(document).ready(scriptPage);
10
11function scriptPage() {
12 var ownTribeName = 'Vitae',
13 ownTribeID = '4722',
14 h_mode = (game_data.player.sitter == '0') ? '' : '&t='+game_data.player.id,
15 world = game_data.world,
16 player = game_data.player.id,
17 mode = game_data.mode,
18 screen = game_data.screen,
19 data = getUserData(),
20 defUnitTDS = {'spear': 0, 'sword': 1, 'spy': 4, 'archer': 3, 'heavy': 7},
21 troop_names = ['Speervechters','Zwaardvechters','Bijlstrijders','Verkenners','Lichte cavalerie','Zware cavalerie', 'Rammen','Katapulten'],
22 shortNames = {'spear': 'Sp', 'sword': 'Zw', 'archer': 'Boog', 'axe': 'Bijl', 'spy': 'Ver', 'light': 'Lc', 'marcher': 'Bb', 'heavy': 'Zc', 'ram': 'Ram', 'catapult': 'Kata', 'knight': 'Ridder', 'snob': 'Edel'},
23 runtimes = {'Verk': 9, 'Scouts': 9, 'LCav': 10, 'Lc': 10, 'ZCav': 11, 'Zc': 11, 'Bijl': 18, 'Zwaard': 22, 'Ram': 30, 'Edel': 35, '**EDEL**': 35},
24 tagUnits = ['Verk', 'LCav', 'ZCav', 'Bijl', 'Zwaard', 'Ram', '**EDEL**'],
25 deffs_needed = (localStorage.getItem('PDP_Settings_'+game_data.world)) ? JSON.parse(localStorage.getItem('PDP_Settings_'+game_data.world)).deffs_needed : [0,2,3,4,5,6,7,7,8,8,8,8,9,9,9,9,10,10,10,10,10,11,11,11,11,11,12,12,12,12,12];
26
27 // TW ajax calls
28 if (typeof window.$.twAjax === 'undefined') {
29 window.$.twAjax = (function () {
30 var Ajax = function (options, promise) {
31 this.options = options;
32 this.promise = promise;
33 };
34
35 var queue = (function () {
36 var list = [];
37 var working = false;
38
39 var doNext = function () {
40 var item = list[0];
41
42 $.ajax(item.options).done(function() {
43 item.promise.resolve.apply(null, arguments);
44
45 list.splice(item, 1);
46 start();
47 }).fail(function() {
48 item.promise.reject.apply(null, arguments);
49 start();
50 });
51 };
52
53 var start = function () {
54 if (list.length) {
55 working = true;
56 doNext();
57 } else {
58 working = false;
59 }
60 };
61
62 var push = function (ajax) {
63 list.push(ajax);
64
65 if (!working) {
66 start();
67 }
68 };
69
70 return {
71 push: push
72 };
73 })();
74
75 return function(options) {
76 var promise = $.Deferred();
77 queue.push(new Ajax(options, promise));
78 return promise;
79 };
80 })();
81 }
82
83 function VDP_FadeOutMessage(message, length, clickclose, stayVisible, close, width) {
84 if (!clickclose) {$('.VDP_message').on('click', function(){$('.VDP_message').fadeOut(100, function(){$('.VDP_message').attr('style', 'display:none;')})});}
85 if (!stayVisible) {setInterval(function(){$('.VDP_message').fadeOut(1000, function(){$('.VDP_message').attr('style', 'display:none;')})}, length);}
86 if (close) {close = '<br><br><br><a href="javascript: $(\'.VDP_message\').remove();void(0);" style="float:right;">» Sluiten «</a>';} else {close = '';}
87 var style = 'position:fixed;overflow:auto;top:100px;max-height:'+(window.outerHeight-300)+'px;width:'+width+'px;left:'+(window.outerWidth/2-(width/2))+'px;background-color:#e8d4a9;border:2px solid #804000;padding:10px;text-align:center;font-size:12px;z-index:15000;box-shadow:0 0 50px 0px #000000;';
88 $('body').append('<div class="VDP_message" style="'+style+'">'+ message + close + '</div>');
89 }
90
91 function exeIncoming() {
92 var $incRows = $('#incomings_table').find('img[src*="attack.png"]').closest('tr');
93
94 insertButtonRows();
95 insertOpenVillagesButton();
96 commandsColoring($incRows);
97 massTaggerAdjust();
98 tableVisualizer($('#incomings_table tr'));
99 }
100
101 function exeOVUnits(tab) {
102 if (tab == 'In het dorp') {
103 insertDeffs();
104 insertFilterRow();
105 insertLinkOpener();
106 tableVisualizer($('.overview_table tr'));
107 } else {
108 insertOverviewTable(tab, getTableInfo(tab));
109 rowAB($('.VDP_table'));
110 tableVisualizer($('.VDP_table tr'));
111 checkForZero();
112 }
113 }
114
115 function exeOverview() {
116 var $incTable = $('#show_incoming_units'),
117 $outTable = $('#show_outgoing_units'),
118 $incRows = $incTable.find('img[src*="attack.png"]').closest('tr'),
119 $incTbl = $incTable.find('table').first();
120
121 if ($incTable.length > 0) {
122 var amountOfInc = incomingsCounter($incTable),
123 amountOfNobels = nobelCounter($incTable);
124 var $incMsg = $('<strong> - ' + amountOfInc + ((amountOfInc == 1)? ' aanval': ' aanvallen') + ' - ' + ((amountOfNobels > 0) ? amountOfNobels + ((amountOfNobels == 1)? ' edelaanval': ' edelaanvallen') : 'geen edelaanvallen') + '</strong>');
125 $incTable.find('th:contains("Aankomend")').append($incMsg);
126
127 $incTable.find('table').first().find('tr').last().find('td').first().append('<a href="#" class="openSettings" id="openSettings" title="Open instellingen menu"> - VDP Settings</a>');
128
129 commandsColoring($incRows);
130 hoverLabel($incRows);
131 renameHotkeys(data.labels, $incTbl);
132 insertRenameButtons(data.labels, $incTbl);
133 inserAutoSelect($incTbl);
134 splitArriavals($incTbl);
135 insertDaySelection();
136 doAutoSelect(data.autoSelect, $incTbl, false);
137 insertStackRating();
138 }
139
140 if ($outTable.length > 0) {
141 var timestamps = getTroopsBackTimestamps($outTable);
142 insertTroopsBack($incRows, timestamps);
143 }
144
145 restyleWidgets();
146
147 var amountOfDef = calculateDefTroops(screen, $('#show_units').find('div').first().find('table').find('tr')),
148 unitHeader = $('#show_units').find('h4').first();
149 insertCalculatedDef(screen, amountOfDef, unitHeader, false);
150 }
151 function exePlace() {
152 var $incTable = $('th:contains("Aankomend")').closest('table');
153 if ($incTable.length > 0) {
154 var amountOfInc = incomingsCounter($incTable),
155 amountOfNobels = nobelCounter($incTable);
156 var $incMsg = $('<strong> - ' + amountOfInc + ((amountOfInc == 1)? ' aanval': ' aanvallen') + ' - ' + ((amountOfNobels > 0) ? amountOfNobels + ((amountOfNobels == 1)? ' edelaanval': ' edelaanvallen') : 'geen edelaanvallen') + '</strong>');
157 $incTable.find('th:contains("Aankomend")').append($incMsg);
158
159 $incTable.find('tr').last().find('td').first().append('<a href="#" class="openSettings" id="openSettings" title="Open instellingen menu"> - VDP Settings</a>');
160 $('th:contains("Aankomend")').css('width', '70%');
161
162 var $incRows = $incTable.find('img[src*="attack.png"]').closest('tr');
163
164 commandsColoring($incRows);
165 hoverLabel($incRows);
166 renameHotkeys(data.labels, $incTable);
167 insertRenameButtons(data.labels, $incTable);
168 inserAutoSelect($incTable);
169 splitArriavals($incTable);
170 insertDaySelection();
171 doAutoSelect(data.autoSelect, $incTable, false);
172
173 switchToNextVillageUnderAttack();
174 } else {
175 $(document).off('keyup keydown keypress');
176 addHotkeyPlugin();
177 switchToNextVillageUnderAttack();
178 }
179 }
180
181 function exePlaceUnits() {
182 var $unitsHome = $('#units_home'),
183 $uddTD = $unitsHome.find('td:contains("Uit dit dorp")'),
184 $vbTD = $unitsHome.find('th:contains("Van buitenaf")'),
185 $lastTR = $unitsHome.find('tr').last(),
186 amountOfDef = calculateDefTroops(screen, [$uddTD.closest('tr'), $vbTD.closest('tr'), $lastTR]),
187 unitHeader = [$uddTD, $vbTD, $lastTR.find('th').first()];
188 insertCalculatedDef(screen, amountOfDef, unitHeader, false);
189
190 insertFields();
191 insertFromOutsideRest();
192 tableVisualizer($('#units_home tr'));
193
194 var btns = '<span style="float:right;">' +
195 '<input type="button" class="btn showVillageInfo" title="Toon de speler van het dorp, of het dorp incommings krijgt en hoe ze benoemd zijn." value="Toon dorpsinfo">' +
196 ' | <input type="text" class="fieldSelect_amount" size="4" placeholder="0"> <input type="button" class="btn fieldSelect" title="Vink dorpen aan die minder ver liggen dan opgegeven." value="Aanvinken">' +
197 ' | <input class="btn" type="submit" name="back" value="Terugsturen">' +
198 '</span>';
199 $unitsHome.find('th').first().append(btns);
200 $('.showVillageInfo').on('click', insertVillageInfo);
201 $('.fieldSelect').on('click', selectByFields);
202 }
203
204 function exeInfoVillage() {
205 var $incTable = $('th:contains("Aankomend")').closest('table');
206 if ($incTable.length > 0) {
207 var amountOfInc = incomingsCounter($incTable),
208 amountOfNobels = nobelCounter($incTable);
209 var $incMsg = $('<strong> - ' + amountOfInc + ((amountOfInc == 1)? ' aanval': ' aanvallen') + ' - ' + ((amountOfNobels > 0) ? amountOfNobels + ((amountOfNobels == 1)? ' edelaanval': ' edelaanvallen') : 'geen edelaanvallen') + '</strong>');
210 $incTable.find('th:contains("Aankomend")').append($incMsg);
211
212 var $incRows = $incTable.find('img[src*="attack.png"]').closest('tr');
213
214 commandsColoring($incRows);
215 hoverLabel($incRows);
216 renameHotkeys(data.labels, $incTable);
217 insertRenameButtons(data.labels, $incTable);
218 splitArriavals($incTable);
219 }
220 }
221
222 function exeCommandName(screen) {
223 if (screen == 'place') {
224 var $CDF = $('#command-data-form'),
225 tc = $CDF.find('td:contains("Doel:")').next('td').find('a').first().text().match(/\d{1,3}\|\d{1,3}/g).slice(-1)[0].toString(),
226 tp = $.trim($CDF.find('td:contains("Speler:")').next('td').find('a').first().text());
227
228 $('#attack_name').val(buildCommandString(tc, tp, $('#place_confirm_units .units-row')));
229 } else if (screen == 'info_command') {
230 if (!$('.quickedit-label').text().match(/(Sp|Zw|Boog|Bijl|Ver|Lc|Bb|Zc|Ram|Kata|Ridder|Edel)=\d+/)) {
231 var doel = $('#content_value table td:contains("Doel")'),
232 tc = doel.closest('tr').next('tr').find('td').last().find('a').first().text().match(/\d{1,3}\|\d{1,3}/g).slice(-1)[0].toString(),
233 tp = $.trim(doel.closest('tr').find('td').last().find('a').first().text());
234
235 $('.rename-icon').click();
236 $('.quickedit-edit').find('input[type="text"]').val(buildCommandString(tc, tp, $('#content_value table:last tr:last')));
237 $('.quickedit-edit').find('input[type="button"]').click();
238 }
239 }
240 }
241
242 function exeMap() {
243 $('#content_value h2').first().append('<span style="float:right;"><input type="button" class="btn showDeffsOnMap" value="Toon Stacks" title="laatst ingeladen: '+data.troopsOnMap.lastreadin+'"></span>');
244 $('.showDeffsOnMap').on('click', showStacksOnMap);
245 }
246
247 function exeOV() {
248 switch(mode) {
249 case 'incomings':
250 exeIncoming();
251 break;
252 case 'units':
253 var tab = $('.modemenu').not('#overview_menu').find('td.selected').find('a').first().text();
254 exeOVUnits(tab);
255 break;
256 }
257 }
258
259 switch(screen) {
260 case 'overview_villages':
261 exeOV();
262 break;
263 case 'overview':
264 exeOverview();
265 break;
266 case 'place':
267 if (mode == 'units' && ($('select[name="display"]').val() == 'units')) {
268 exePlaceUnits();
269 } else if (location.href.match(/try=confirm/)) {
270 exeCommandName(screen);
271 } else {
272 exePlace();
273 }
274 break;
275 case 'info_village':
276 exeInfoVillage();
277 break;
278 case 'map':
279 exeMap();
280 break;
281 case 'info_command':
282 if (location.href.match(/type=own/)) {
283 exeCommandName(screen);
284 }
285 break;
286 }
287
288 exeCommandNameImages($('a[href*="screen=info_command"] .quickedit-label:contains("=")'));
289
290 $('.openSettings').off().on('click', showSettings);
291 $('#units_home input[type="checkbox"]').off().on('change', updateTroops);
292
293 $('<style>' +
294 '.own_tooltip_style {' +
295 'position: absolute; z-index: 30000; border:1px solid #804000; padding: 5px; background: #f0e2be; background: -moz-linear-gradient(top, #e3c485 0%, #ecd09a 100%); background: -webkit-linear-gradient(top, #e3c485 0%,#ecd09a 100%); background: -o-linear-gradient(top, #e3c485 0%,#ecd09a 100%); background: -ms-linear-gradient(top, #e3c485 0%,#ecd09a 100%); background: linear-gradient(to bottom, #e3c485 0%,#ecd09a 100%); -webkit-box-shadow: 1px 1px 2px 0px rgba(60, 30, 0, 0.35); box-shadow: 1px 1px 2px 0px rgba(60, 30, 0, 0.35); -webkit-border-radius: 4px; border-radius: 4px;' +
296 '} ' +
297 '</style>').appendTo('head');
298
299 /************************
300 ****** Functions *******
301 ************************/
302
303 function getUserData() {
304 var data = localStorage.getItem('VitaePackage_'+world+'_'+player);
305 if (data) {
306 data = JSON.parse(data);
307 } else {
308 data = {
309 labels: {
310 'MARKEREN': {hotkey: 'm', color: '#FFFFFF'},
311 'OK': {hotkey: 'o', color: '#FFFF00'},
312 'DODGE': {hotkey: 'd', color: '#FF0000'},
313 'DODGED': {hotkey: 's', color: '#FF9900'},
314 'BIJSTACKEN': {hotkey: 'b', color: '#ADD8E6'},
315 'GEVRAAGD': {hotkey: 'g', color: '#0000FF'},
316 'LAATSTE': {hotkey: 'l', color: '#ADD402'}
317 },
318 hotkeyWhenNotHovered: false,
319 villageSwitch: {
320 deflinks: [],
321 currentLinkPlace: 0,
322 start: true
323 },
324 autoSelect: 'disabled',
325 troopsOnMap: {
326 lastreadin: 'nooit',
327 info: {}
328 },
329 autoRenamer: {
330 blockChecker: {
331 renameFor: 'always',
332 wallLower: true,
333 marge: '5'
334 },
335 dodgeChecker: {
336 renameFor: 'todayandtomorrow',
337 minTroops: '300',
338 maxTroops: '1300',
339 ignoreNobles: false
340 }
341 }
342 }
343 }
344
345 return data;
346 }
347
348 function saveSettings() {
349 var newLabels = {};
350 $('.VDP_message #labels .label_tr').each(function(){
351 var $this = $(this),
352 label = $this.find('.VDPlabel').text(),
353 hotkey = $this.find('.VDPhotkey').val(),
354 color = $this.find('.VDPcolor').val();
355
356 newLabels[label] = {'hotkey': hotkey, 'color': color};
357 });
358
359 data.labels = newLabels;
360 data.hotkeyWhenNotHovered = $('.hotkeyWhenNotHovered').prop('checked');
361 data.autoRenamer.blockChecker.renameFor = $('.blockChecker_select').val();
362 data.autoRenamer.blockChecker.wallLower = $('.wallLower_val').prop('checked');
363 data.autoRenamer.blockChecker.marge = $('.marge_val').val();
364 data.autoRenamer.dodgeChecker.renameFor = $('.dodgeChecker_select').val();
365 data.autoRenamer.dodgeChecker.minTroops = $('.minTroops_val').val();
366 data.autoRenamer.dodgeChecker.maxTroops = $('.maxTroops_val').val();
367 data.autoRenamer.dodgeChecker.ignoreNobles = $('.ignoreNobles_val').prop('checked');
368
369 localStorage.setItem('VitaePackage_'+world+'_'+player, JSON.stringify(data));$
370
371 location.reload();
372 }
373
374 function showSettings() {
375 if ($('.VDP_message').length == 0) {
376 var m = '<h2>VDP Settings</h2>'
377 + '<table id="labels" class="vis" style="width:100%;"><tr><th colspan="3">Tag instellingen</th></tr><th>Tag</th><th>Sneltoets</th><th>Kleur</th></tr>';
378 for (var prop in data.labels) {
379 m += '<tr class="label_tr"><td class="VDPlabel"><strong>'+prop+'</strong></td><td><input type="text" size="1" maxlength="1" class="VDPhotkey" value="'+data.labels[prop].hotkey+'"></td>'
380 + '<td><input type="color" class="VDPcolor" value="'+data.labels[prop].color+'"></td</tr>';
381 }
382 m += '<tr><td colspan="3" style="height: 18px;"></td</tr>' +
383 '<tr><td colspan="2">Sneltoets toepassen op alle incommings<br>indien er geen gehovered is:</td><td><input type="checkbox" class="hotkeyWhenNotHovered"></td></tr>' +
384 '</table><br>';
385
386 m += getAutoRenamerHTML(false);
387
388 m+= '<br><br><a href="#" class="btn saveSettings" id="saveSettings">Opslaan</a>';
389
390 VDP_FadeOutMessage(m, 0, false, true, true, 400);
391 $('.VDP_message').find('th').css('text-align', 'center');
392 $('#autoRenamer').find('td').css('padding-left', '5px');
393 if (data.hotkeyWhenNotHovered) {$('.hotkeyWhenNotHovered').prop('checked', true)}
394
395 $('.saveSettings').off().on('click', saveSettings)
396 }
397 }
398
399 function rowAB($table) {
400 var $trs = $table.find('td').closest('tr');
401 for (var i = 0, l = $trs.length; i < l; i++) {
402 var cl = (i % 2 == 0) ? 'row_a' : 'row_b',
403 curClass = $trs.eq(i).attr('class').replace(/row_a|row_b/, '');
404
405 $trs.eq(i).attr('class', curClass + ' ' + cl);
406 }
407 }
408
409 function checkForZero() {
410 $('.checkForZero:contains("0")').filter(function() {
411 return $(this).text() === '0';
412 }).attr('class', 'hidden');
413 }
414
415 function restyleWidgets(){
416 $('#overviewtable').append('<tbody><tr class="newLayoutTR"><td colspan="2"><div class="outerBorder newLayout"></div></td></tr></tbody>');
417 $('.newLayout').append($("#show_incoming_units")).append($("#show_outgoing_units"));
418 $('.newLayout').find('table').each(function(){$(this).find('tr').eq(0).find('th').eq(0).attr('width', '70%');})
419
420 var $ignoreTR = $('input[value="Negeren"]').closest('tr');
421 if ($ignoreTR.length > 0) {
422 $ignoreTR.prev('tr').find('th').first().append('<span style="float:right;">' + $ignoreTR.find('td').html() + '</span>');
423 $ignoreTR.remove();
424 }
425
426 $('.newLayoutTR').after('<tr><td valign="top" id="leftcolumn" class="newLeftColomn" width="612"></td> <td valign="top" id="rightcolumn" class="newRightColomn" width="612"></td></tr>');
427
428 var widgetsR = $('#rightcolumn').find('.widget'),
429 widgetsR_length = widgetsR.length,
430 overview_height = $('#show_summary').height()
431 height_count = 0,
432 x = 0;
433 for (var i = 0, l = widgetsR.length; i < l; i++) {
434 var $this = widgetsR.eq(i);
435 h = (parseInt($this.height()) + 15);
436
437 if (((height_count + h) > overview_height) && (!$this.find('.head:contains("Eenheden")').length)) {
438 var amount_left = Math.floor((widgetsR_length - (i + 1)) / 2);
439 if (amount_left < x) {
440 $('.newLeftColomn').append($this);
441 } else {
442 $('.newRightColomn').append($this);
443 }
444
445 x++;
446 }
447
448 height_count = height_count + h;
449 }
450 }
451
452 function exeCommandNameImages($items) {
453 for (var i = 0, l = $items.length; i < l; i++) {
454 var $this = $items.eq(i),
455 text = $.trim($this.text()),
456 unitString = text.match(/(Sp|Zw|Boog|Bijl|Ver|Lc|Bb|Zc|Ram|Kata|Ridder|Edel)=\d+/g),
457 restString = text.match(/(\d{1,3}\|\d{1,3} \(.*\) |\d{1,3}\|\d{1,3} )/)[0],
458 newString = restString;
459
460 for (var x = 0, z = unitString.length; x < z; x++) {
461 var split = unitString[x].toString().split('='),
462 unit = Object.keys(shortNames).filter(function(key) {return shortNames[key] === split[0]})[0],
463 end = (x == unitString.length - 1) ? '' : ' ';
464 newString += '<img src="/graphic/unit/unit_' + unit + '.png" style="width:13px;">' + split[1] + end;
465 }
466
467 $this.after(newString);
468 $this.css('display', 'none');
469 }
470 }
471
472 function getRenameForHTML(class_name) {
473 var options = {'Altijd': 'always', 'Vandaag': 'vandaag', 'Vandaag en Morgen': 'vandaagenmorgen', 'Morgen': 'morgen'},
474 select = '<select class="'+class_name+'_select">';
475 for (var prop in options) {
476 if (options[prop] == data.autoRenamer[class_name].renameFor) {
477 select += '<option value="'+options[prop]+'" selected>'+prop+'</option>';
478 } else {
479 select += '<option value="'+options[prop]+'">'+prop+'</option>';
480 }
481 }
482 select += '</select>';
483
484 return select;
485 }
486
487 function getAutoRenamerHTML(okButtons) {
488 var INchecked = (data.autoRenamer.dodgeChecker.ignoreNobles) ? 'checked' : '',
489 WLchecked = (data.autoRenamer.blockChecker.wallLower) ? 'checked' : '',
490 html = '<table id="autoRenamer" class="vis" style="width:100%;text-align:left;">' +
491 '<tr><th colspan="3" style="text-align: center;">Block Checker</th></tr>' +
492 '<tr><td>Bevelen herbenoemen voor:</td><td>' + getRenameForHTML('blockChecker') + '</td>';
493 if (okButtons) {
494 html += '<td rowspan="3"><input type="button" class="btn blockChecker_go" value="GO"></td>';
495 }
496 html += '</tr>' +
497 '<tr><td>Marge behouden van:</td><td><input type="number" size="4" class="marge_val" value="'+data.autoRenamer.blockChecker.marge+'"> clears</td></tr>' +
498 '<tr><td>Muur zakken toestaan:</td><td><input type="checkbox" class="wallLower_val" '+WLchecked+'></td></tr>';
499
500 html += '<tr><td colspan="3" style="height: 15px;background-color:#e8d4a9;"></td</tr>';
501
502 html += '<tr><th colspan="3" style="text-align: center;">Dodge Checker</th></tr>' +
503 '<tr><td>Bevelen herbenoemen voor:</td><td>' + getRenameForHTML('dodgeChecker') + '</td>';
504 if (okButtons) {
505 html += '<td rowspan="4"><input type="button" class="btn dodgeChecker_go" value="GO"></td>';
506 }
507 html += '</tr><tr><td>Minimaal aantal troepen:</td><td><input type="number" size="6" class="minTroops_val" value="'+data.autoRenamer.dodgeChecker.minTroops+'"></td></tr>' +
508 '<tr><td>Maximaal aantal troepen:</td><td><input type="number" size="6" class="maxTroops_val" value="'+data.autoRenamer.dodgeChecker.maxTroops+'"></td></tr>' +
509 '</tr><tr><td>Edels in thuisdorp negeren:</td><td><input type="checkbox" class="ignoreNobles_val" '+INchecked+'></td></tr>' +
510 '</table>';
511
512 return html;
513 }
514
515 function getButtonRowHTML(top, selectRow) {
516 var table_html = '<table id="VDP_table" class="vis VDP_table" style="width:100%;min-width: 1250px;">',
517 buttons = '<input class="btn VDP_label" type="submit" value="Label" name="label">'
518 + ' | <input type="button" class="btn autoRenamer" value="Auto Renamer" title="Start de auto renamer functie">'
519 + ' | <input type="button" class="btn filter" data-type="tag" value="Filter Tags" title="Filter de juist getagte aanvallen weg">'
520 + '<input type="button" class="btn filter" data-type="done" value="Filter Behandeld" title="Filter de al behandelde aanvallen weg">'
521 + ' | <input type="button" class="btn groupCom" value="Groeperen" title="Verschillende manieren van groeperen voor verschillande doeleinden">'
522 + ' | <input type="button" class="btn modus" data-mode="taggen" value="Taggen Modus" title="Ga naar de tag modus (filter op aanval, groep alle, pagina alle)">'
523 + '<input type="button" class="btn modus" data-mode="markeren" value="Markeren Modus" title="Ga naar de Markeren modus (filter op markeren, groep huidig, pagina 1)">'
524 + ' | <input type="button" class="btn stopTimer" value="Stop Timers" title="Stop de timers op de pagina">'
525 + ' | <input type="button" class="btn openSettings" value="Settings" title="Open instellingen menu">',
526 select = '<input name="all" type="checkbox" id="select_all" class="VDP_DayChecker" data-date="all"> <label for="select_all">alles selecteren</label>'
527 + ' | <input type="checkbox" id="select_today" class="VDP_DayChecker" data-date="vandaag"> <label for="select_today">vandaag selecteren</label>'
528 + ' | <input type="checkbox" id="select_todayandtomorrow" class="VDP_DayChecker" data-date="vandaagenmorgen"> <label for="select_todayandtomorrow">vandaag en morgen selecteren</label>'
529 + ' | <input type="checkbox" id="select_tomorrow" class="VDP_DayChecker" data-date="morgen"> <label for="select_tomorrow">morgen selecteren</label>',
530 toBottom = '<input type="button" class="btn toBottomTop" data-direction="bottom" value="▼" title="Scroll naar het einde van de pagina">',
531 toTop = '<input type="button" class="btn toBottomTop" data-direction="top" value="▲" title="Scroll naar het begin van de pagina">',
532 drop_down = '<span style="float:right;">Geselecteerde markeren als: <select class="renameSelectValue" style="width:100px;">';
533 for (var prop in data.labels) {
534 if (prop != 'LAATSTE') {
535 drop_down += '<option value="'+prop+'" style="background-color:'+data.labels[prop].color+';">'+prop+'</option>';
536 }
537 }
538 drop_down += '</select><input type="button" class="btn renameSelectGo" value="OK" title="Alle geselecteerde zullen hernoemt worden naar het gekozen label. In het geval van LAATSTE zal er per dorp worden nagegaan welke inc er laatst is en deze zal gelabeld wordnen."></span>';
539
540 var button_row = '<tr><th>' + buttons + '<span style="float:right;">' + ((top) ? toBottom : toTop) +'</span></th></tr>',
541 select_row = '<tr><th>' + select + drop_down + '</th></tr>';
542
543 if (top) {
544 if (selectRow) {
545 table_html += button_row + select_row;
546 } else {
547 table_html += button_row;
548 }
549 } else {
550 table_html += select_row + button_row;
551 }
552
553 table_html += '</table>';
554
555 return table_html;
556 }
557
558 function insertButtonRows() {
559 if ($('#incomings_table').length > 0) {
560 $('#incomings_table').before('<br>' + getButtonRowHTML(true, true)).after(getButtonRowHTML(false, true) + '<br>');
561 $('.VDP_DayChecker').off().on('click', handleDaySelection);
562 $('.renameSelectGo').off().on('click', renameBySelect);
563 } else {
564 $('.overview_filters_manage').after('<br>' + getButtonRowHTML(true, false) + '<br>');
565 }
566
567 $('.VDP_table').find('.btn').css('margin', '0px 5px 0px 5px');
568
569 $('.autoRenamer').on('click', doAutoRename);
570 $('.filter').on('click', filter);
571 $('.groupCom').on('click', groupIncomings);
572 $('.modus').on('click', toModus);
573 $('.stopTimer').on('click', stopTimers);
574 $('.toBottomTop').on('click', toBottomTop);
575 }
576
577 function renameBySelect() {
578 var $rows = $('.overview_table').find('input[type="checkbox"]:checked').closest('td').find('img[src*="attack.png"]').closest('tr'),
579 label = $('.renameSelectValue').val();
580 incomingsRenamer(false, label, $rows);
581 $( document ).ajaxComplete( function () {
582 var $row = $('.overview_table').find( 'img[src*="attack.png"]' ).closest( 'tr' );
583 giveColor( $row );
584 } );
585 }
586
587 function doAutoRename() {
588 VDP_FadeOutMessage('<h3>Auto Renamer</h3><br><span class="AR-content">' + getAutoRenamerHTML(true) + '</span>', 0, false, true, true, 400);
589 $('#autoRenamer').find('td').css('padding-left', '5px');
590
591 $('.blockChecker_go').off().on('click', exeBlockChecker);
592 // $('.dodgeChecker_go').off().on('click', exeDodgeChecker);
593 }
594
595 function exeBlockChecker() {
596 // get information
597 var date = $('.blockChecker_select').val(),
598 marge = $('.marge_val').val(),
599 wallLower = $('.wallLower_val').prop('checked');
600
601 // get data from table
602 var ARdata = getARdata();
603
604 // show process counter
605 var tbl = '<table class="vis AR_counter_tbl" style="width:100%;font-weight:bold;">' +
606 '<tr><th colspan="2" style="text-align:center;">Block Checker</th></tr>' +
607 '<tr><td style="height:30px;">Doeldorpen verwerkt:</td><td class="center" style="width:30%;"><span class="ARvillageDoneAmount">0</span> / ' + ARdata.coords.length + '</td></tr>' +
608 '<tr><td style="height:30px;" title="Incommings die in orde waren en hertagt zijn">Incomings verwerkt:</td><td class="center"><span class="ARincDoneAmount">0</span> / <span class="ARincAmount">0</span></td></tr>' +
609 '<tr><td colspan="2" style="height:15px;background-color:#e8d4a9;"></td></tr>' +
610 '<tr><th colspan="2" style="text-align:center;">STACK OK: bijstacken</th></tr>' +
611 '<tr><td class="center">' +
612 '<textarea class="blockChecker_SO" rows="10" style="width:80%;" onclick="this.select();"></textarea>' +
613 '</td><td class="center"><span class="ARblockChecker_SO_Amount">0</span> / <span class="ARblockChecker_SO_Tamount">0</span><br><br><input type="button" class="btn openVillageTabs" value="Open Tabs"></td></tr>' +
614 '<tr><td colspan="2" style="height:15px;background-color:#e8d4a9;"></td></tr>' +
615 '<tr><th colspan="2" style="text-align:center;">STACK NIET OK: bijstacken</th></tr>' +
616 '<tr><td class="center">' +
617 '<textarea class="blockChecker_SNO" rows="10" style="width:80%;" onclick="this.select();"></textarea>' +
618 '</td><td class="center"><span class="ARblockChecker_SNO_Amount">0</span> / <span class="ARblockChecker_SNO_Tamount">0</span><br><br><input type="button" class="btn openVillageTabs" value="Open Tabs"></td></tr>' +
619 '</table>';
620
621 $('.AR-content').html(tbl);
622 $('.AR-content').find('td').css('padding', '10px 0px 10px 0px');
623 $('.AR-content').find('td').not('.center').css('text-align', 'left').css('padding-left', '5px');
624
625 // loop trough villages
626 for (var i = 0, l = ARdata.coords.length; i < l; i++) {
627 getVillageInformation('blockChecker', date, ARdata.urls[i], function(stackInfo, $incRows, coord){
628 console.log($incRows);
629 Simulate(stackInfo.defence, stackInfo.wall, $incRows.length, function(result) {
630 var inc = $incRows.length,
631 inc_done = false,
632 firstAttackTime = $incRows.first().find('td').eq(1).text(),
633 currentDeffs = calculateDefTroops('byArray', stackInfo.defence).toFixed(0),
634 deffs_extra = (inc > deffs_needed.length) ? 'x' : (deffs_needed[inc] - currentDeffs);
635
636 if (inc < (parseInt(result.clears) - parseInt(data.autoRenamer.blockChecker.marge))) {
637 inc_done = true;
638 if (!result.wallLower) {
639 incomingsRenamer(false, 'OK', $incRows);
640 } else {
641 incomingsRenamer(false, 'OK [MUUR]', $incRows);
642 }
643 } else if (inc < (parseInt(result.clears))) {
644 inc_done = true;
645 if (!result.wallLower) {
646 incomingsRenamer(false, 'OK [CHECK]', $incRows);
647 } else {
648 incomingsRenamer(false, 'OK [CHECK + MUUR]', $incRows);
649 }
650
651 if (deffs_extra > 0) {
652 var onecPatern = $('.blockChecker_SO').text().trim() + '\n ' + coord + ' ' + deffs_extra + ' ' + makeTime(true, firstAttackTime);
653 $('.blockChecker_SO').text($.trim(onecPatern));
654 $('.ARblockChecker_SO_Tamount').text(parseInt($('.ARblockChecker_SO_Tamount').text()) + 1);
655 }
656 } else {
657 var onecPatern = $('.blockChecker_SNO').text().trim() + '\n ' + coord + ' ' + deffs_extra + ' ' + makeTime(true, firstAttackTime);
658 $('.blockChecker_SNO').text($.trim(onecPatern));
659 $('.ARblockChecker_SNO_Tamount').text(parseInt($('.ARblockChecker_SNO_Tamount').text()) + 1);
660 }
661
662 $('.ARvillageDoneAmount').text(parseInt($('.ARvillageDoneAmount').text()) + 1); // targets done counter
663 $('.ARincAmount').text(parseInt($('.ARincAmount').text()) + inc);
664 if (inc_done) $('.ARincDoneAmount').text(parseInt($('.ARincDoneAmount').text()) + inc);
665 })
666 })
667 }
668
669 // setting clicks
670 $( document ).ajaxComplete( function () {
671 var $row = $('.overview_table').find( 'img[src*="attack.png"]' ).closest( 'tr' );
672 giveColor( $row );
673 });
674
675 }
676
677 function getVillageInformation(type, date, url, callback) {
678 $.twAjax({
679 url: url,
680 datatype: 'html',
681 async: false,
682 success: function(html) {
683 var $html = $(html);
684
685 if (type == 'blockChecker') {
686 // get stack info
687 var coord = html.match(/"coord":"\d+\|\d+"/).toString().match(/\d+\|\d+/)[0],
688 stackInfo = {'defence': [], 'wall': 0},
689 wall = html.match(/"wall":"\d+"/).toString().match(/\d+/)[0],
690 def_troops = [];
691
692 for (var i in troop_names) {
693 var td = $html.find('#show_units td:contains("'+troop_names[i]+'")');
694 if (td.length !== 0) {
695 var aantal = parseInt(td.find('strong').eq(0).text());
696 def_troops.push(aantal);
697 } else {
698 def_troops.push(0);
699 }
700 }
701
702 stackInfo.defence = def_troops;
703 stackInfo.wall = wall;
704
705 //get inc rows
706 var $table = $('#show_incoming_units').find('table').first(), // VANUIT HTML VERTREKKEN
707 $attack_tr = $table.find('img[src*="attack.png"]').closest('tr'),
708 $incRows;
709
710 if (date == 'always') {
711 $incRows = $attack_tr;
712 } else if (date == 'vandaagenmorgen') {
713 $incRows = $attack_tr.find('td:contains("vandaag")').closest('tr');
714 $incRows = $attack_tr.find('td:contains("morgen")').closest('tr');
715 } else {
716 $incRows = $attack_tr.find('td:contains("' + date + '")').closest('tr');
717 }
718
719 callback(stackInfo, $incRows, coord);
720 }
721 },
722 error: function () {
723 var style = 'margin:auto;width:314px;font-size:9px;position:relative;line-height: 13px;padding:3px 18px 3px 28px;',
724 html = '<br><div class="info_box" style="'+style+'">' +
725 'Er is een fout opgetreden, contacteer de maker en vermeld volgende foutcode: Fout#1 getVillageInformation() failed.' +
726 '</div><br>';
727 if ($('.VDP_message').find('.info_box').length === 0)
728 $('.AR-content').append(html);
729 }
730 });
731 }
732
733 function getARdata() {
734 var $table = $('#incomings_table'),
735 $rows = $table.find('tbody').find('.row_a, .row_b'),
736 ARdata = {'coords': [], 'urls': []};
737
738 for (var i = 0, l = $rows.length; i < l; i++) {
739 var $this = $rows.eq(i),
740 coord = $this.find('td').first().next().find('a').first().text().match(/\d{1,3}\|\d{1,3}/g).slice(-1)[0].toString(),
741 url = $this.find('td').first().next().find('a').first().attr('href');
742
743 if (ARdata.coords.indexOf(coord) == -1) {
744 ARdata.coords.push(coord);
745 ARdata.urls.push(url);
746 }
747 }
748
749 return ARdata;
750 }
751
752 function makeTime(OneCommand, timestr) {
753 // vandaag om 16:49:08 uur
754 // op 21.08. om 05:04:11 uur
755 var T = timestr.match(/\d+\:\d+\:\d+/);
756 var ServerDate = $('#serverDate').text().split('/');
757 var daysInMonth = [31,28,31,30,31,30,31,31,30,31,30,31];
758
759 if (timestr.match('vandaag')) {
760 var D = ServerDate[0]+'.'+ServerDate[1]+'.';
761 } else if (timestr.match('morgen')) {
762 var tomorrow = parseInt(ServerDate[0], 10) + 1;
763 if (tomorrow > daysInMonth[ServerDate[1]]) {
764 tomorrow = 1;
765 var m = parseInt(ServerDate[1], 10) + 1;
766 } else {
767 var m = ServerDate[1];
768 }
769 var D = tomorrow+'.'+m+'.';
770 } else {
771 var D = timestr.match(/\d+\.\d+\./);
772 }
773
774 if (OneCommand) {
775 T = T.toString().split(':');
776 return D+ServerDate[2]+' '+T[0]+':'+T[1];
777 } else {
778 return 'VOOR '+D+' om '+T;
779 }
780 }
781
782 function filter(e) {
783 e.preventDefault();
784 var doneLabels = ($(this).attr('data-type') == 'done') ? ['OK', 'DODGED'] : ['MARKEREN', 'OK', 'DODGE', 'DODGED', 'BIJSTACKEN', 'GEVRAAGD'];
785
786 for (var i = 0; i < doneLabels.length; i++) {
787 $('#incomings_table').find('a:contains(' + doneLabels[i] + ')').closest('tr').remove();
788 }
789
790 overviewRecount();
791 }
792
793 function groupIncomings(e) {
794 e.stopPropagation();
795 e.preventDefault();
796 Timing.pause();
797
798 // saving data to switch between villages under attack
799 data.villageSwitch.deflinks = [];
800 data.villageSwitch.currentLinkPlace = 0;
801 data.villageSwitch.start = true;
802
803 var $table = $('#incomings_table'),
804 $rows = $table.find('tbody').find('.row_a, .row_b'),
805 coords = [];
806
807 for (var i = 0, l = $rows.length; i < l; i++) {
808 var $this = $rows.eq(i),
809 coord = $this.find('td').first().next().find('a').text().match(/\d{1,3}\|\d{1,3}/g).slice(-1)[0].toString();
810
811 if (coords.indexOf(coord) == -1) {
812 data.villageSwitch.deflinks.push($this.find('td').first().next().find('a').attr('href'));
813 coords.push(coord);
814 }
815 }
816
817 localStorage.setItem('VitaePackage_'+world+'_'+player, JSON.stringify(data));
818
819 var style = 'margin:auto;width:314px;font-size:9px;position:relative;line-height: 13px;padding:3px 18px 3px 28px;', html;
820 if ($('.VitaeSpace').length > 0) {
821 html = '<h3>Groeperen</h3><br>' +
822 '<div class="info_box" style="'+style+'">' +
823 'Er is al een groepeer functie uitgevoerd, herlaad de pagina om een nieuwe te kunnen uitvoeren !' +
824 '</div>';
825 } else {
826 html = '<h3>Groeperen</h3><br>' +
827 '<div class="info_box" style="'+style+'">' +
828 'Informatie voor het wisselen tussen dorpen onder aanval is ingeladen ! Als dit je doel was kan je deze kader sluiten.' +
829 '</div><br><br>' +
830 '<select class="grouping_select" style="width:360px;">' +
831 '<option value="byTarget">Groepeer op doeldorp (taggen)</option>' +
832 '<option value="bySendtime">Groepeer op verstuurtijd (clears zoeken)</option>' +
833 '<option value="byPlanning">Groepeer op planning (clears zoeken)</option>' +
834 '</select><br><br><table class="vis info_tbl" style="display:none;border: 1px solid #7D510F;width:360px;margin:auto;margin-bottom:15px;">' +
835 '<tr><th colspan="2" style="text-align: center;">Informatie groeperen op verstuurtijd</th></tr>' +
836 '<tr><td><b>Tijd tussen maken van planning:</b></td><td><input type="text" size="4" class="planningMinutes" value="5"> minuten</td></tr>' +
837 '<tr><td><b>Tijd tussen laden van tabs:</b></td><td><input type="text" size="4" class="tabsSeconds" value="10"> seconden</td></tr>' +
838 '</table>' +
839 '<div class="info_box infoB" data-type="byTarget" style="'+style+'">' +
840 'Groepeer de incommings in dit overzicht per doeldorp. Deze functie maakt het eenvoudig om te kijken hoe veel aanvallen er per dorp lopen,' +
841 ' geeft de mogelijkheid om een coordlijst te maken met bijhorend aantal incommings en geeft je een schatting van de eenheid en de mogelijkheid om deze eenvoudig te taggen wanneer ' +
842 'je niet online was toen er verstuurd werd. De schatting is op basis van het verschil tussen de eerste en de laatst verstuurde aanval, denk er aan dat dit geen 100% wetenschap is !</div>' +
843 '<div class="info_box infoB" data-type="bySendtime" style="'+style+'display:none;">' +
844 'Groepeer de incommings in dit overzicht op verzendtijd. Op basis van de tag zal de tool terugrekenen wanneer de aanval verzonden is (een juiste tag is daarbij noodzakelijk !).' +
845 'De incommings zullen worden gerangschikt per speler op verzendtijd en er zal een kolom worden toegevoegd met het verschil tussen elke aanval. Op basis van het verschil wordt er een optelling/schatting weergegeven' +
846 ' van waar er een nieuwe reeks tabs geladen wordt (aangegeven met een optel rij en een getal in de rechter kolom) en waar er een nieuwe planning is gemaakt (weergegeven in diezelfde rij helemaal rechts).' +
847 ' Om deze laatste goed weer te geven en omdat het schilt van persoon tot persoon die verstuurd kan je in de tabel hier boven extra info ingeven.' +
848 ' De mogelijkheid om een aanduiding van clear toe te voegen aan de tag is ook te vinden per planning. Net zoals alle anderen geen exacte wetenschap !</div>' +
849 '<div class="info_box infoB" data-type="byPlanning" style="'+style+'display:none;">' +
850 'Groepeer de incommings in dit overzicht op basis van planning. De tool zal aan de hand van het aantal aanvallen per dorp uitzoeken welke aanvallen tot dezelfde planning behoren. ' +
851 'De incommings worden getoont per speler, per planning en op volgorde van versturen. Houd er rekening mee dat je zelf aandachtig moet zijn en de verstuurtijden nakijken in de daarvoor voorziene kolom. ' +
852 'Een aanduiding van clear toevoegen in de tag is mogelijk per planning. Net zoals alle anderen geen exacte wetenschap !</div>' +
853 '<br><br><input type="button" class="btn grouping_go" value="Groepeer">';
854 }
855
856 VDP_FadeOutMessage(html, 0, false, true, true, 400);
857 $('.info_tbl').find('td').css('text-align', 'left');
858
859 $('.grouping_select').off().on('change', function(){
860 var val = $(this).val();
861 $('.infoB').hide();
862 $('.infoB[data-type="'+val+'"]').show();
863
864 $('.info_tbl').hide();
865 if (val == 'bySendtime') {
866 $('.info_tbl').show();
867 }
868 })
869
870 $('.grouping_go').off().on('click', function(){
871 switch($('.grouping_select').val()) {
872 case 'byTarget':
873 groupIncomingsbyTarget();
874 break;
875 case 'bySendtime':
876 groupIncomingsbySendtime($('.planningMinutes').val(), $('.tabsSeconds').val());
877 break;
878 case 'byPlanning':
879 groupIncomingsbyPlanning();
880 break;
881 }
882
883 $('.VDP_message').remove();
884 })
885 }
886
887 function toModus() {
888 var extra = '', filter = '';
889 if ($(this).attr('data-mode') == 'markeren') {
890 extra = '&subtype=attacks&mode=incomings&page=0&screen=overview_villages';
891 filter = 'MARKEREN';
892 } else {
893 extra = '&subtype=attacks&mode=incomings&group=0&page=-1&screen=overview_villages';
894 filter = 'Aanval';
895 }
896
897 $.twAjax({
898 url: game_data.link_base_pure + game_data.village.id + '&screen=overview_villages&mode=incomings&action=save_filters&h=' + game_data.csrf + h_mode,
899 type: 'POST',
900 async: false,
901 data: {
902 'return': '/game.php?village=' + game_data.village.id + '&screen=' + game_data.village.id + extra + h_mode,
903 'filters[target_comment]': filter,
904 'filters[target_name]': '',
905 'filters[origin_name]': '',
906 'filters[origin_player]': ''
907 }, success: function () {
908 window.location = '/game.php?village=' + game_data.village.id + '&screen=' + game_data.village.id + extra + h_mode;
909 }
910 });
911 }
912
913 function stopTimers(e) {
914 e.stopPropagation();
915 e.preventDefault();
916 if (Timing.paused) {
917 Timing.paused = false;
918 Timing.tickHandlers.timers.tick();
919 Timing.doGlobalTick();
920 $('.stopTimer').val('Stop Timers');
921 $('.stopTimer').attr('title', 'Stop de timers op de pagina');
922 } else {
923 Timing.pause();
924 $('.stopTimer').val('Start Timers');
925 $('.stopTimer').attr('title', 'Start de timers op de pagina');
926 }
927 }
928
929 function toBottomTop() {
930 if ($(this).attr('data-direction') == 'bottom') {
931 $('html,body').scrollTop($( document ).height());
932 } else {
933 $('html,body').scrollTop(0);
934 }
935 }
936
937 function insertOpenVillagesButton(){
938 var $table = $('#incomings_table');
939 $table.find('th:contains("Doel")').first().append('<input type="button" class="btn openVillageTabs" value="Open Tabs ▼" style="float:right;">');
940 $('.openVillageTabs').off().on('click', function(){
941 var $rows = $table.find('tbody').find('.row_a, .row_b'),
942 urls = [];
943
944 for (var i = 0, l = $rows.length; i < l; i++) {
945 var $this = $rows.eq(i),
946 url = $this.find('td').first().next().find('a').attr('href');
947
948 if (urls.indexOf(url) == -1) {
949 urls.push(url);
950 }
951 }
952
953 if (urls.length > 50) {
954 var c = confirm('U staat op het punt ' + urls.length + ' tabs te openen.\nWeet u zeker dat u wilt doorgaan ?');
955 if (c) {
956 openUrls(urls);
957 }
958 } else {
959 openUrls(urls);
960 }
961 })
962 }
963
964 function openUrls(urls) {
965 for (var i = 0, l = urls.length; i < l; i++) {
966 window.open(urls[i], '_blank');
967 }
968 }
969
970 function ArrayAllValuesSame(array) {
971 for(var i = 1; i < array.length; i++) {
972 if(array[i] !== array[0])
973 return false;
974 }
975
976 return true;
977 }
978
979 function overviewRecount() {
980 var $inc_tbl = $('#incomings_table'),
981 $th = $inc_tbl.find('th:contains("Bevel")'),
982 amount = $inc_tbl.find('.quickedit').length;
983
984 $th.text($th.text().replace(/\(\d+\)/, '('+amount+')'));
985 }
986
987 function massTaggerAdjust() {
988 var format = "MARKEREN %unit% (%coords%) %player%";
989 $("input[name=label_format]").val(format).parents("form").find("input[name=label]");
990 }
991
992 function tableVisualizer($rows) {
993 $rows.hover(function () {
994 $(this).find("td").css("background", "#FFF68F");
995 }, function () {
996 $(this).find("td").css("background", "");
997 });
998 }
999
1000 function giveColor($rows) {
1001 $('.marked').addClass('defaultColor');
1002 for (var prop in data.labels) {
1003 if (prop !== 'LAATSTE') {
1004 $rows.find('span.quickedit-label:contains("' + prop + '")').closest('td').find('.defaultColor, .marked').removeClass('defaultColor').addClass('marked').css('background-color', data.labels[prop].color);
1005 }
1006 }
1007 $('.defaultColor').css('background-color', 'red');
1008 }
1009
1010 function commandsColoring($rows) {
1011 var styleSpan = {
1012 'display': 'inline-block',
1013 'border': 'solid black 1px',
1014 'width': '10px',
1015 'height': '10px'
1016 };
1017
1018 for (var i = 0, amountOfRows = $rows.length; i < amountOfRows; i++) {
1019 $('<span class="defaultColor"></span>').css(styleSpan).insertBefore($rows.eq(i).find('td').first().find('span').first());
1020 }
1021
1022 giveColor($rows);
1023 }
1024
1025 function groupIncomingsbyTarget() {
1026 var $table = $('#incomings_table'),
1027 $rows = $table.find('tbody').find('.row_a, .row_b'),
1028 rGroup = {};
1029
1030 for (var i = 0, l = $rows.length; i < l; i++) {
1031 var $this = $rows.eq(i),
1032 targetCoord = $this.find('td').first().next().find('a').text().match(/\d{1,3}\|\d{1,3}/g).slice(-1)[0].toString(),
1033 homeCoord = $this.find('td').first().next().next().find('a').text().match(/\d{1,3}\|\d{1,3}/g).slice(-1)[0].toString(),
1034 player = $this.find('td').eq(3).find('a').first().text().trim(),
1035 id = $this.find('.quickedit').first().attr('data-id'),
1036 distance = getDistance(homeCoord, targetCoord),
1037 arrival = parseInt(convertToTimestamp($this.find('td').eq(5).text())),
1038 SendTimeArr = [];
1039
1040 for (var prop in runtimes) {
1041 if (!prop.match(/Scouts|Lc|Zc|Edel/)) {
1042 var time = arrival - (((distance * runtimes[prop]) * 60) * 1000);
1043 SendTimeArr.push(parseInt(time));
1044 }
1045 }
1046
1047 if (rGroup.hasOwnProperty(targetCoord)) {
1048 rGroup[targetCoord].rows.push($this);
1049 rGroup[targetCoord].attackers.push(player);
1050 rGroup[targetCoord].unitSendTimes.push(SendTimeArr);
1051 rGroup[targetCoord].ids.push(id);
1052 } else {
1053 rGroup[targetCoord] = {'rows': [$this], 'attackers': [player],'unitSendTimes': [SendTimeArr], 'ids': [id]};
1054 }
1055
1056 $this.remove();
1057 }
1058
1059 var bothBorders = 'border-bottom:1px solid rgb(128, 64, 0);border-top:1px solid rgb(128, 64, 0);background-color:transparent',
1060 $totalRows = [];
1061
1062 for (var prop in rGroup) {
1063 // check players
1064 if (!ArrayAllValuesSame(rGroup[prop].attackers)) {
1065 var VitaeInf = '<tr class="VitaeInf"><th title="Meerdere spelers, geen schatting mogelijk !">X</th><th>' + prop + '</th><th colspan="5">#' + rGroup[prop].rows.length +'</th></tr>',
1066 VitaeSpace = '<tr class="VitaeSpace"><td colspan="7" style="' + bothBorders + '"></td></tr>';
1067
1068 rGroup[prop].rows.push($(VitaeInf));
1069 rGroup[prop].rows.push($(VitaeSpace));
1070 $totalRows = $.merge($totalRows, rGroup[prop].rows);
1071 } else if (rGroup[prop].rows.length == 1) {
1072 var VitaeInf = '<tr class="VitaeInf"><th title="Maar 1 incomming, geen schatting mogelijk !">X</th><th>' + prop + '</th><th colspan="5">#' + rGroup[prop].rows.length +'</th></tr>',
1073 VitaeSpace = '<tr class="VitaeSpace"><td colspan="7" style="' + bothBorders + '"></td></tr>';
1074
1075 rGroup[prop].rows.push($(VitaeInf));
1076 rGroup[prop].rows.push($(VitaeSpace));
1077 $totalRows = $.merge($totalRows, rGroup[prop].rows);
1078 } else {
1079 // return tag option
1080 var sendTimes = {'low': [], 'high': []};
1081 for (var i = 0, l = rGroup[prop].unitSendTimes.length; i < l; i++) {
1082 for (var x = 0, z = rGroup[prop].unitSendTimes[i].length; x < z; x++) {
1083 if (i == 0) { // first round -> push first runtimes
1084 sendTimes.low.push(rGroup[prop].unitSendTimes[i][x]);
1085 sendTimes.high.push(rGroup[prop].unitSendTimes[i][x]);
1086 } else {
1087 if (sendTimes.low[x] > rGroup[prop].unitSendTimes[i][x]) sendTimes.low[x] = rGroup[prop].unitSendTimes[i][x];
1088 if (sendTimes.high[x] < rGroup[prop].unitSendTimes[i][x]) sendTimes.high[x] = rGroup[prop].unitSendTimes[i][x];
1089 }
1090 }
1091 }
1092
1093 var dif = [];
1094 for (var i = 0, l = sendTimes.low.length; i < l; i++) {
1095 dif.push(sendTimes.high[i] - sendTimes.low[i]);
1096 }
1097
1098 var diff = dif.slice(0).sort(function(a, b){return a-b}),
1099 lowest_dif = diff[0],
1100 index = dif.indexOf(lowest_dif),
1101 unit = tagUnits[index],
1102 VitaeInf = '<tr class="VitaeInf"><th>Geschatte eenheid: ' + unit + ' <span title="Laagste gevonden verschil in seconden tussen de eerste en de laatst verstuurde aanval op dit dorp.">' +
1103 '(' + convertMStoTime(lowest_dif, true, 'small') + ' sec)</span>' +
1104 '<input type="button" class="btn ownStyleButton doTag" data-tag="'+unit+'" data-player="'+rGroup[prop].attackers[0]+'" data-ids="'+rGroup[prop].ids.join('-')+'" value="TAG">' +
1105 '</th><th>' + prop + '</th><th colspan="5">#' + rGroup[prop].rows.length +'</th></tr>',
1106 VitaeSpace = '<tr class="VitaeSpace"><td colspan="7" style="' + bothBorders + '"></td></tr>';
1107
1108 rGroup[prop].rows.push($(VitaeInf));
1109 rGroup[prop].rows.push($(VitaeSpace));
1110 $totalRows = $.merge($totalRows, rGroup[prop].rows);
1111 }
1112 }
1113
1114 var firstRows = $table.find('tr').first().clone();
1115 $table.find('tr').first().remove();
1116 $table.prepend($totalRows).prepend(firstRows);
1117
1118 $('.VitaeInf').find('th').css('text-align', 'right');
1119 $('.VitaeSpace').css('height', '15px');
1120 $('th:contains("Bevel")').removeAttr('width').css('min-width',' 200px');
1121 $('.ownStyleButton').attr('style', 'padding:1px 3px;font-size:11px !important;');
1122 rowAB($table);
1123
1124 $('.doTag').off().on('click', function() {
1125 var $this = $(this),
1126 tag = $this.attr('data-tag'),
1127 player = $this.attr('data-player'),
1128 ids = $this.attr('data-ids').split('-');
1129
1130 for (var i = 0, l = ids.length; i < l; i++) {
1131 var coord = $('.quickedit[data-id="'+ids[i]+'"]').closest('td').next().next().find('a').text().match(/\d{1,3}\|\d{1,3}/g).slice(-1)[0].toString(),
1132 value = 'MARKEREN ' + tag + ' (' + coord + ') ' + player;
1133
1134 renameCommand(value, ids[i]);
1135 }
1136 })
1137
1138 $('#incomings_table').find('tr').first().find('th:contains("Doel")').append(' <input type="button" class="btn groupComOutput" style="float:right;" value="Coordlijst" title="Verkrijg een export met de coords en het aantal aanvallen per coord">');
1139 $('.groupComOutput').on('click', function(){
1140 var html = '<h3>Groepeer Doelen Coordlijst</h3><textarea cols="20" rows="20" onclick="this.select();">';
1141 for (var prop in rGroup) {
1142 html += prop + ' #' + rGroup[prop].rows.length + '\n';
1143 }
1144 html += '</textarea>';
1145
1146 VDP_FadeOutMessage(html, 0, false, true, true, 300);
1147 })
1148 }
1149
1150 function groupIncomingsbySendtime(planningMinutes, tabsSeconds) {
1151 var $table = $('#incomings_table'),
1152 $rows = $table.find('tbody').find('.row_a, .row_b'),
1153 rGroup = {};
1154
1155 for (var i = 0, l = $rows.length; i < l; i++) {
1156 var $this = $rows.eq(i),
1157 tag = $this.find('td').first().find('.quickedit-label').text(),
1158 targetCoord = $this.find('td').first().next().find('a').text().match(/\d{1,3}\|\d{1,3}/g).slice(-1)[0].toString(),
1159 homeCoord = $this.find('td').first().next().next().find('a').text().match(/\d{1,3}\|\d{1,3}/g).slice(-1)[0].toString(),
1160 player = $this.find('td').eq(3).find('a').first().text().trim(),
1161 distance = getDistance(homeCoord, targetCoord),
1162 arrival = parseInt(convertToTimestamp($this.find('td').eq(5).text())),
1163 matchCount = 0,
1164 runtimeMS = 0;
1165
1166 for (var prop in runtimes) {
1167 if (tag.indexOf(prop) > 0) {
1168 matchCount++;
1169 runtimeMS = ((distance * runtimes[prop]) * 60) * 1000;
1170 }
1171 }
1172
1173 if (matchCount === 1) {
1174 var sendTime = arrival - runtimeMS;
1175
1176 $this.find('td:eq(1), td:eq(2), td:eq(3)').remove();
1177 $this.find('td').last().html(convertFromTimestamp(sendTime));
1178
1179 if (rGroup.hasOwnProperty(player)) {
1180 rGroup[player][sendTime] = $this[0].outerHTML;
1181 } else {
1182 rGroup[player] = {};
1183 rGroup[player][sendTime] = $this[0].outerHTML;
1184 }
1185 } else if (matchCount === 0) {
1186 UI.ErrorMessage('Geen of foutieve tag ! Rij wordt verwijderd.');
1187 } else {
1188 UI.ErrorMessage('Meerdere tags ! Rij wordt verwijderd.');
1189 }
1190
1191 $this.remove();
1192 }
1193
1194 var tableContent = '',
1195 bothBorders = 'border-bottom:1px solid rgb(128, 64, 0);border-top:1px solid rgb(128, 64, 0);background-color:transparent';
1196
1197 for (var prop in rGroup) {
1198 tableContent += '<tr><th colspan="5">'+ prop +' (' + Object.keys(rGroup[prop]).length + ')</th></tr>';
1199
1200 var rGrouped = {};
1201 Object.keys(rGroup[prop]).sort().forEach(function(key) {
1202 rGrouped[key] = rGroup[prop][key];
1203 });
1204
1205 var prev = 0, count = 1, groupCount = 1, countRow, between;
1206 for (var elem in rGrouped) {
1207 if (prev == 0) {
1208 tableContent += rGrouped[elem].replace('</tr>', '<td>' + convertMStoTime('0', false, 'grey small') + ' <span class="small" style="float:right;">#'+count+'</span></td></tr>');
1209 prev = parseInt(elem);
1210 count++;
1211 groupCount++;
1212 } else if (elem == Object.keys(rGrouped)[Object.keys(rGrouped).length-1]) {
1213 between = parseInt(elem) - prev;
1214 countRow = '<tr class="VitaeSpace clearTagRow"><td style="text-align:right;"><b>__CLEAR</b> <input type="button" class="btn ownStyleButton doTag" value="TAG"></td>' +
1215 '<td colspan="3"></td><td style="font-weight:bold;"> #'+ (count) +' <span style="float:right;">#'+groupCount+'</span></td></tr>';
1216 tableContent += rGrouped[elem].replace('</tr>', '<td>' + convertMStoTime(between, false, 'grey small') +' <span class="small" style="float:right;">#'+count+'</span></td></tr>' + countRow);
1217 } else {
1218 between = parseInt(elem) - prev;
1219
1220 if (between > (parseInt(planningMinutes) * 60 * 1000)) { // laadtijd meer dan 5 minuten -> nieuwe planning ?
1221 countRow = '<tr class="VitaeSpace clearTagRow"><td style="border-bottom:1px solid rgb(128, 64, 0);text-align:right;"><b>__CLEAR</b> <input type="button" class="btn ownStyleButton doTag" value="TAG"></td>' +
1222 '<td colspan="3" style="border-bottom:1px solid rgb(128, 64, 0);"></td><td style="border-bottom:1px solid rgb(128, 64, 0);font-weight:bold;"> #'+ (count - 1) +' <span style="float:right;">#'+groupCount+'</span></td></tr>';
1223 count = 1;
1224 groupCount = 1;
1225 tableContent += rGrouped[elem].replace('</tr>', '<td>' + convertMStoTime(between, false, 'grey small') +' <span class="small" style="float:right;">#'+count+'</span></td></tr>').replace('<tr', countRow + '<tr');
1226 prev = parseInt(elem);
1227 count++;
1228 groupCount++;
1229 } else if (between > (parseInt(tabsSeconds) * 1000)) { // laadtijd meer dan 10 seconden -> nieuwe tabs ?
1230 countRow = '<tr class="VitaeSpace"><td colspan="4" style="border-bottom:1px solid rgb(128, 64, 0);"></td><td style="border-bottom:1px solid rgb(128, 64, 0);font-weight:bold;"> #'+ (count - 1) +'</td></tr>';
1231 count = 1;
1232 tableContent += rGrouped[elem].replace('</tr>', '<td>' + convertMStoTime(between, false, 'grey small') +' <span class="small" style="float:right;">#'+count+'</span></td></tr>').replace('<tr', countRow + '<tr');
1233 prev = parseInt(elem);
1234 count++;
1235 groupCount++;
1236 } else {
1237 tableContent += rGrouped[elem].replace('</tr>', '<td>' + convertMStoTime(between, false, 'grey small') + ' <span class="small" style="float:right;">#'+count+'</span></td></tr>');
1238 prev = parseInt(elem);
1239 count++;
1240 groupCount++;
1241 }
1242 }
1243 }
1244
1245 tableContent += '<tr class="VitaeSpace"><td colspan="5" style="' + bothBorders + '"></td></tr>';
1246 }
1247
1248 var $firstTR = $table.find('tr').first();
1249 $firstTR.find('th').not(':eq(0)').remove()
1250 $firstTR.append('<th>Afstand</th><th>Aankomst</th><th>Verstuurd</th><th>Verschil</th>');
1251 $firstTR.after(tableContent);
1252 $('.VitaeSpace').css('height', '25px');
1253 $('.ownStyleButton').attr('style', 'padding:1px 3px;font-size:11px !important;');
1254 rowAB($table);
1255
1256 $('.doTag').off().on('click', function() {
1257 var $this = $(this),
1258 $thisTR = $this.closest('tr'),
1259 $rows = $thisTR.prevUntil("tr.clearTagRow");
1260
1261 for (var i = 0, l = $rows.length; i < l; i++) {
1262 var $thiss = $rows.eq(i);
1263 if ($thiss.attr('class').indexOf('VitaeSpace') == -1) {
1264 var id = $thiss.find('td').first().find('.quickedit').attr('data-id'),
1265 currentTag = $thiss.find('td').first().find('.quickedit-label').text().trim();
1266
1267 renameCommand(currentTag + ' __CLEAR', id);
1268 }
1269 }
1270 })
1271 }
1272
1273 function groupIncomingsbyPlanning() {
1274 var $table = $('#incomings_table'),
1275 $rows = $table.find('tbody').find('.row_a, .row_b'),
1276 attacksOnVillage = {},
1277 playerAttacks = {},
1278 rGroup = {};
1279
1280 // loop to make attacksOnVillage object
1281 for (var i = 0, l = $rows.length; i < l; i++) {
1282 var $this = $rows.eq(i),
1283 targetCoord = $this.find('td').first().next().find('a').text().match(/\d{1,3}\|\d{1,3}/g).slice(-1)[0].toString(),
1284 player = $this.find('td').eq(3).find('a').first().text().trim();
1285
1286 if (attacksOnVillage.hasOwnProperty(targetCoord)) {
1287 attacksOnVillage[targetCoord] = (parseInt(attacksOnVillage[targetCoord]) + 1);
1288 } else {
1289 attacksOnVillage[targetCoord] = 1;
1290 }
1291
1292 if (playerAttacks.hasOwnProperty(player)) {
1293 playerAttacks[player] = (parseInt(playerAttacks[player]) + 1);
1294 } else {
1295 playerAttacks[player] = 1;
1296 }
1297 }
1298
1299 // loop to make rGroup object
1300 for (var i = 0, l = $rows.length; i < l; i++) {
1301 var $this = $rows.eq(i),
1302 tag = $this.find('td').first().find('.quickedit-label').text(),
1303 targetCoord = $this.find('td').first().next().find('a').text().match(/\d{1,3}\|\d{1,3}/g).slice(-1)[0].toString(),
1304 homeCoord = $this.find('td').first().next().next().find('a').text().match(/\d{1,3}\|\d{1,3}/g).slice(-1)[0].toString(),
1305 player = $this.find('td').eq(3).find('a').first().text().trim(),
1306 distance = getDistance(homeCoord, targetCoord),
1307 arrival = parseInt(convertToTimestamp($this.find('td').eq(5).text())),
1308 matchCount = 0,
1309 runtimeMS = 0;
1310
1311 for (var prop in runtimes) {
1312 if (tag.indexOf(prop) > 0) {
1313 matchCount++;
1314 runtimeMS = ((distance * runtimes[prop]) * 60) * 1000;
1315 }
1316 }
1317
1318 $this.find('td:eq(2), td:eq(3)').remove();
1319 if (matchCount === 1) {
1320 var sendTime = arrival - runtimeMS,
1321 amountOfInc = attacksOnVillage[targetCoord];
1322
1323 $this.find('td').last().html(convertFromTimestamp(sendTime));
1324 } else if (matchCount === 0) {
1325 $this.find('td').last().html('Berekening niet mogelijk: Geen of foutieve tag !');
1326 } else {
1327 $this.find('td').last().html('Berekening niet mogelijk: Meerdere tags !');
1328 }
1329
1330 if (rGroup.hasOwnProperty(player)) {
1331 if (rGroup[player].hasOwnProperty(amountOfInc)) {
1332 rGroup[player][amountOfInc][sendTime] = $this[0].outerHTML;
1333 } else {
1334 rGroup[player][amountOfInc] = {};
1335 rGroup[player][amountOfInc][sendTime] = $this[0].outerHTML;
1336 }
1337 } else {
1338 rGroup[player] = {};
1339 rGroup[player][amountOfInc] = {};
1340 rGroup[player][amountOfInc][sendTime] = $this[0].outerHTML;
1341 }
1342
1343 $this.remove();
1344 }
1345
1346 var tableContent = '',
1347 bothBorders = 'border-bottom:1px solid rgb(128, 64, 0);border-top:1px solid rgb(128, 64, 0);background-color:transparent';
1348
1349 for (var prop in rGroup) {
1350 tableContent += '<tr><th colspan="5">'+ prop +' (' + playerAttacks[prop] + ' aanvallen - ' + Object.keys(rGroup[prop]).length + ' planningen)</th></tr>';
1351
1352 // sorting the anountOfInc
1353 var amountOfIncGrouped = {};
1354 Object.keys(rGroup[prop]).sort().forEach(function(key) {
1355 amountOfIncGrouped[key] = rGroup[prop][key];
1356 });
1357
1358 var plan_count = 1;
1359 for (var x in amountOfIncGrouped) {
1360 tableContent += '<tr class="planning_tr"><th colspan="5">Planning #' + plan_count + '</th></tr>';
1361
1362 // sorting runtimes
1363 var runtimesGrouped = {};
1364 Object.keys(amountOfIncGrouped[x]).sort().forEach(function(key) {
1365 runtimesGrouped[key] = amountOfIncGrouped[x][key];
1366 });
1367
1368 for (var elem in runtimesGrouped) {
1369 if (elem == Object.keys(runtimesGrouped)[Object.keys(runtimesGrouped).length-1]) {
1370 var countRow = '<tr class="VitaeSpace clearTagRow"><td style="text-align:right;font-weight:bold;">_CLEAR_ <input type="button" class="btn ownStyleButton doTag" value="TAG"></td>' +
1371 '<td style="text-align:right;font-weight:bold;">' + (Object.keys(runtimesGrouped).length / x) + ' dorpen aan #' + x +
1372 ' per dorp</td><td colspan="3" style="text-align:right;font-weight:bold;"> #' + Object.keys(runtimesGrouped).length + ' totaal</td></tr>';
1373 tableContent += runtimesGrouped[elem].replace('</tr>', '</tr>' + countRow);
1374 } else {
1375 tableContent += runtimesGrouped[elem];
1376 }
1377 }
1378
1379 plan_count++;
1380 }
1381
1382 tableContent += '<tr class="VitaeSpace"><td colspan="5" style="' + bothBorders + '"></td></tr>';
1383 }
1384
1385 var $firstTR = $table.find('tr').first();
1386 $firstTR.find('th').not(':eq(0)').remove()
1387 $firstTR.append('<th>Doel</th><th>Afstand</th><th>Aankomst</th><th>Verstuurd</th>');
1388 $firstTR.after(tableContent);
1389 $('.VitaeSpace').css('height', '22px');
1390 $('.ownStyleButton').attr('style', 'padding:1px 3px;font-size:11px !important;');
1391 rowAB($table);
1392
1393 $('.doTag').off().on('click', function() {
1394 var $this = $(this),
1395 $thisTR = $this.closest('tr'),
1396 $rows = $thisTR.prevUntil("tr.planning_tr");
1397
1398 for (var i = 0, l = $rows.length; i < l; i++) {
1399 var $thiss = $rows.eq(i),
1400 id = $thiss.find('td').first().find('.quickedit').attr('data-id'),
1401 currentTag = $thiss.find('td').first().find('.quickedit-label').text().trim();
1402
1403 renameCommand(currentTag + ' _CLEAR_', id);
1404 }
1405 })
1406 }
1407
1408 function calculateDefTroops(screen, $tableRows) {
1409 var am = (screen == 'overview' || screen == 'byArray') ? 0 : [0, 0, 0],
1410 calculatedDef = (screen == 'overview' || screen == 'byArray') ? 0 : [0, 0, 0];
1411
1412 var units = {
1413 'spear': {'nl': 'Speer', 'amount': am, 'people': 1},
1414 'sword': {'nl': 'Zwaard', 'amount': am, 'people': 1},
1415 'archer': {'nl': 'Boog', 'amount': am, 'people': 1},
1416 'spy': {'nl': 'Verk', 'amount': am, 'people': 2},
1417 'heavy': {'nl': 'Zware', 'amount': am, 'people': 6}
1418 };
1419
1420 if (screen == 'byArray') {
1421 for (var prop in units) {
1422 var selectedprop = prop;
1423 var selectedprop = $tableRows[defUnitTDS[prop]];
1424 var selectedpropunites = units[prop].people;
1425
1426 calculatedDef = calculatedDef + ($tableRows[defUnitTDS[prop]] * units[prop].people);
1427 }
1428
1429 calculatedDef = calculatedDef / 20000;
1430 calculatedDef = (calculatedDef > 0) ? calculatedDef.toFixed(1) : 0;
1431 } else {
1432 if (screen == 'overview') {
1433 var $unitsInTable = $tableRows.find('.unit_link').closest('tr');
1434 for (var prop in units) {
1435 var $unitContainer = $unitsInTable.find('td:contains("' + units[prop].nl + '")');
1436 if ($unitContainer.length > 0) {
1437 units[prop].amount = parseInt($unitContainer.find('strong').text());
1438 }
1439 }
1440 } else if (screen == 'place') {
1441 for (var prop in units) {
1442 var arr = [];
1443 for (var i = 0, l = $tableRows.length; i < l; i++) {
1444 arr.push(parseInt($($tableRows[i]).find('.unit-item-'+prop).text()));
1445 }
1446
1447 units[prop].amount = arr;
1448 }
1449 }
1450
1451 if (screen == 'overview') {
1452 for (var prop in units) {
1453 calculatedDef = calculatedDef + (units[prop].amount * units[prop].people);
1454 }
1455
1456 calculatedDef = calculatedDef / 20000;
1457 calculatedDef = (calculatedDef > 0) ? calculatedDef.toFixed(1) : 0;
1458 } else if (screen == 'place') {
1459 for (var prop in units) {
1460 for (var i = 0, l = calculatedDef.length; i < l; i++) {
1461 calculatedDef[i] = calculatedDef[i] + (units[prop].amount[i] * units[prop].people);
1462 }
1463 }
1464
1465 for (var i = 0, l = calculatedDef.length; i < l; i++) {
1466 calculatedDef[i] = (calculatedDef[i] / 20000);
1467 calculatedDef[i] = (calculatedDef[i] > 0) ? calculatedDef[i].toFixed(1) : 0;
1468 }
1469 }
1470 }
1471
1472 return calculatedDef;
1473 }
1474
1475 function insertCalculatedDef(screen, calculatedDef, elementToAppendTo, doReplace) {
1476 if (screen == 'overview') {
1477 $('<span class="VDP_deffs" data-deffs="'+calculatedDef+'"> (' + calculatedDef + ' deffs)</span>').appendTo(elementToAppendTo);
1478 } else if (screen == 'place') {
1479 for (var i = 0, l = elementToAppendTo.length; i < l; i++) {
1480 if (doReplace) {
1481 $(elementToAppendTo[i]).find('.deffs_span').text(' (' + calculatedDef[i] + ' deffs)');
1482 } else {
1483 $('<span class="deffs_span"> (' + calculatedDef[i] + ' deffs)</span>').appendTo($(elementToAppendTo[i]));
1484 }
1485 }
1486 }
1487 }
1488
1489 function getDistance(homeC, awayC) {
1490 homeC = homeC.split('|');
1491 awayC = awayC.split('|');
1492 return Math.sqrt(((homeC[0]-awayC[0])*(homeC[0]-awayC[0])+(homeC[1]-awayC[1])*(homeC[1]-awayC[1])));
1493 }
1494
1495 function sortFields(obj){
1496 var trHTML = '';
1497 for (var prop in obj) {
1498 for (var i = 0, l = obj[prop].length; i < l; i++) {
1499 trHTML += '<tr>'+obj[prop][i]+'</tr>';
1500 }
1501 }
1502
1503 $('#units_home tr').eq(1).after(trHTML);
1504 $('.sortOnFields').remove();
1505 }
1506
1507 function insertFields() {
1508 var $unitsHome = $('#units_home'),
1509 as = $unitsHome.find('a[href*="screen=info_village&id="]'),
1510 homeCoord = game_data.village.coord,
1511 object = {};
1512
1513 for (var i = 0, l = as.length; i < l; i++) {
1514 var $this = as.eq(i),
1515 $tr = $this.closest('tr'),
1516 awayCoord = $this.text().match(/\d{1,3}\|\d{1,3}/g).slice(-1)[0].toString(),
1517 dis = getDistance(homeCoord, awayCoord),
1518 dis = dis.toFixed(0);
1519
1520 $tr.attr('class', 'sortOnFields').attr('data-fields', dis);
1521 $this.closest('td').append('<span class="distance" data-fields="'+dis+'" style="float:right;font-weight:bold;">F'+dis+'</span>');
1522
1523 if (object.hasOwnProperty(dis)) {
1524 object[dis].push($tr.html());
1525 } else {
1526 object[dis] = [$tr.html()];
1527 }
1528 }
1529
1530 sortFields(object);
1531 }
1532
1533 function doRecountFromOutside(doReplace) {
1534 var $unitAmountTR = $('.unitAmountTR'),
1535 $unitHeader = $('.unitHeader'),
1536 amountOfDef = calculateDefTroops(screen, [$unitAmountTR]),
1537 unitHeader = [$unitHeader];
1538 insertCalculatedDef(screen, amountOfDef, unitHeader, doReplace);
1539 }
1540
1541 function insertFromOutsideRest(){
1542 var $trVB = $('#units_home tr:contains("Van buitenaf")'),
1543 clone = $trVB.clone();
1544 $trVB.after(clone);
1545
1546 var $last_tr = $('#units_home tr:contains("Van buitenaf")').last();
1547 $last_tr.attr('class', 'unitAmountTR');
1548 $last_tr.find('th').first().replaceWith('<th class="unitHeader" title="Berekening van de troepen die overblijven nadat de aangevinkte teruggestuurd zouden worden.">Van buitenaf overblijvend</th>');
1549
1550 doRecountFromOutside(false);
1551 }
1552
1553 function updateTroops() {
1554 var totalUnits = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
1555 $unitsHome = $('#units_home'),
1556 trs = $unitsHome.find('a[href*="screen=info_village&id="]').closest('tr');
1557
1558 for (var i = 0, l = trs.length; i < l; i++) {
1559 var $this = trs.eq(i);
1560 if ($this.find('input[type="checkbox"]').prop('checked') == false) {
1561 var UI = $this.find('.unit-item');
1562 for (var x = 0, z = UI.length; x < z; x++) {
1563 totalUnits[x] = (totalUnits[x] + parseInt($(UI[x]).text()));
1564 }
1565 }
1566 }
1567
1568 var thss = $('.unitAmountTR').find('th').not(':first');
1569 for (var i = 0, l = thss.length; i < l; i++) {
1570 thss.eq(i).text(totalUnits[i]);
1571 }
1572
1573 doRecountFromOutside(true);
1574 }
1575
1576 function insertVillageInfo() {
1577 var $unitsHome = $('#units_home'),
1578 as = $unitsHome.find('a[href*="screen=info_village&id="]'),
1579 doPlayerHTML = '<input type="text" class="autocomplete plName ui-autocomplete-input" placeholder="Spelersnaam..." autocomplete="off" size="15">' +
1580 '<input type="button" class="btn doPlayer" value="Aanvinken">';
1581
1582 for (var i = 0, l = as.length; i < l; i++) {
1583 var $this = as.eq(i),
1584 link = $this.attr('href');
1585
1586 $.twAjax({
1587 url: link,
1588 datatype: 'html',
1589 async: false,
1590 success: function(html) {
1591 var $html = $(html),
1592 $pl_td = $html.find('#embedmap_village').closest('table').find('td:contains("Speler:")').next(),
1593 pl_link = $pl_td.html(),
1594 pl = $.trim($pl_td.text());
1595
1596 $this.closest('tr').attr('data-player', pl);
1597 $this.after(' <b>[' + pl_link + ']</b>');
1598
1599 if ($.trim($pl_td.text()) == game_data.player.name) {
1600 var table = $html.find('th:contains("Aankomend")').closest('table'),
1601 inc = incomingsCounter(table);
1602
1603 if (inc > 0) {
1604 $this.before('<img src="https://dsnl.innogamescdn.com/8.41/28068/graphic/command/attack.png" class="VDP_tooltip_'+i+'" style="margin-right:5px;">');
1605 UI.ToolTip('.VDP_tooltip_'+i, {
1606 bodyHandler: function() {
1607 return '<table class="vis">'+table.html()+'</table>';
1608 },
1609 'extraClass' : 'own_tooltip_style'
1610 });
1611 }
1612 }
1613 }
1614 });
1615 }
1616
1617 $('.showVillageInfo').replaceWith(doPlayerHTML);
1618
1619 $('.autocomplete').autocomplete({
1620 minLength: 2,
1621 source: UI.AutoComplete.source,
1622 focus: UI.AutoComplete.handleFocus
1623 });
1624
1625 $('.doPlayer').off().on('click', function(){
1626 $('#units_home tr[data-player="' + $('.plName').val() + '"]').find('input[type="checkbox"]').prop('checked', true).trigger('change');
1627 })
1628 }
1629
1630 function selectByFields() {
1631 var amount = parseInt($('.fieldSelect_amount').val()),
1632 $rows = $('.distance');
1633
1634 for (var i = 0, l = $rows.length; i < l; i++) {
1635 var $this = $rows.eq(i),
1636 fields = parseInt($this.attr('data-fields'));
1637
1638 if (fields < amount) {
1639 $this.closest('td').find('input').first().prop('checked', true).trigger('change');
1640 }
1641 }
1642
1643 UI.SuccessMessage('Dorpen geselecteerd !');
1644 }
1645
1646 function insertDeffs() {
1647 var $table = $('#units_table'),
1648 $rows = $table.find('tr');
1649
1650 for (var i = 0, l = $rows.length; i < l; i++) {
1651 var $this = $rows.eq(i);
1652
1653 if (i == 0) {
1654 $this.find('th').eq(1).replaceWith('<th style="text-align:center;">Deffs</th>');
1655 } else {
1656 var units = $this.find('td.unit-item'),
1657 troop_arr = [];
1658
1659 for (var x = 0, z = units.length; x < z; x++) {
1660 troop_arr.push(parseInt(units.eq(x).text()));
1661 }
1662
1663 var defTroops = calculateDefTroops('byArray', troop_arr);
1664 $this.attr('data-deffs', (defTroops * 10));
1665 $this.find('td').eq(1).replaceWith('<td style="text-align:center;font-weight:bold;">' + defTroops + '</td>');
1666 }
1667 }
1668 }
1669
1670 function insertFilterRow() {
1671 var row_html = '<table class="vis VDP_FilterRow" style="width:100%;"><tr>' +
1672 '<th style="text-align: center;">Filter: <select class="filter_type"><option value="more">Meer</option><option value="less">Minder</option></select> dan <input type="text" size="4" class="filter_amount" placeholder="0"> <input type="button" class="btn doFilter" value="OK"></th>' +
1673 '<th style="text-align: center;">Preventieve os lijst: <input type="text" size="4" class="os_amount" placeholder="0" title="Hoe veel def is er nodig in elk dorp ?"> <input type="button" class="btn doOsList" value="Aanmaken"></th>' +
1674 '<th style="text-align: center;"><input type="button" class="btn doSaveInfo" value="Informatie inladen"> <span style="font-size:9px;">(laatst ingeladen: <span class="lastreadin_msg">'+data.troopsOnMap.lastreadin+'</span>)</span> <input type="button" class="btn doResetInfo" value="X" title="Eerder ingelezen data resetten."></th>' +
1675 '</tr></table>';
1676
1677 $('.overview_table').before(row_html);
1678
1679 $('.doFilter').off().on('click', function() {
1680 var $rows = $('#units_table').find('tr').not(':first'),
1681 ftype = $('.filter_type').val(),
1682 amount = (parseInt($('.filter_amount').val()) * 10);
1683
1684 for (var i = 0, l = $rows.length; i < l; i++) {
1685 var $this = $rows.eq(i),
1686 a = parseInt($this.attr('data-deffs'));
1687
1688 if ((ftype == 'more' && (a <= amount)) || (ftype == 'less' && (a > amount))) {
1689 $this.remove();
1690 }
1691 }
1692 })
1693
1694 $('.doOsList').off().on('click', function() {
1695 var $rows = $('#units_table').find('tr').not(':first'),
1696 amount_needed = (parseInt($('.os_amount').val()) * 10),
1697 cnt = 1,
1698 tarea = '<h3>Preventieve OS lijst</h3><textarea cols="60" rows="20" onclick="this.select();">';
1699
1700 // Voor op het forum
1701 tarea += '[code]\n'
1702
1703 for (var i = 0, l = $rows.length; i < l; i++) {
1704 var $this = $rows.eq(i),
1705 a = parseInt($this.attr('data-deffs')),
1706 coord = $this.find('.quickedit-label').text().match(/\d{1,3}\|\d{1,3}/g).slice(-1)[0].toString(),
1707 need = Math.round((amount_needed - a) / 10);
1708
1709
1710
1711 if (need > 0) {
1712 //tarea += '[b]#'+cnt+' [coord]'+coord+'[/coord] -> '+need+' def dorpen[/b]\n';
1713 tarea += coord+' '+need+' 01.01.2100 00:00\n';
1714
1715 cnt++;
1716 }
1717
1718 }
1719 tarea += '[/code]'
1720 tarea += '</textarea>';
1721
1722 VDP_FadeOutMessage(tarea, 0, false, true, true, 600);
1723 })
1724
1725 $('.doSaveInfo').off().on('click', function() {
1726 var $rows = $('#units_table').find('tr').not(':first'),
1727 timestamp = $('#serverDate').text() + ' ' + $('#serverTime').text();
1728
1729 for (var i = 0, l = $rows.length; i < l; i++) {
1730 var $this = $rows.eq(i),
1731 coord = $this.find('.quickedit-label').text().match(/\d{1,3}\|\d{1,3}/g).slice(-1)[0].toString(),
1732 deffs = $this.find('td').eq(1).text();
1733
1734 if (Math.round(deffs) != 0) {
1735 data.troopsOnMap.info[coord] = deffs;
1736 }
1737 }
1738
1739 data.troopsOnMap.lastreadin = timestamp;
1740 localStorage.setItem('VitaePackage_'+world+'_'+player, JSON.stringify(data));
1741 $('.lastreadin_msg').text(timestamp);
1742 UI.SuccessMessage('Informatie ingeladen !');
1743 })
1744
1745 $('.doResetInfo').off().on('click', function() {
1746 data.troopsOnMap = {
1747 lastreadin: 'nooit',
1748 info: {}
1749 }
1750
1751 localStorage.setItem('VitaePackage_'+world+'_'+player, JSON.stringify(data));
1752 $('.lastreadin_msg').text('nooit');
1753 UI.SuccessMessage('Informatie gereset !');
1754 })
1755 }
1756
1757 function insertLinkOpener() {
1758 $('#units_table th:contains("Opdracht")').append(' <img class="openLinks" src="/graphic/arrow_down_padd.png" style="cursor:pointer;" title="Open alle troepenlinks">');
1759
1760 $('.openLinks').off().on('click', function() {
1761 $('#units_table a[href*="screen=place&mode=units"]').each(function() {
1762 window.open($(this).attr('href'), '_blank');
1763 });
1764 })
1765 }
1766
1767 function buildCommandString(target_coord, target_player, $unitTableRow) {
1768 var firstName = true,
1769 seperator = ' ',
1770 renamed = '';
1771
1772 renamed += target_coord + seperator;
1773 if (target_player !== undefined) {
1774 renamed += '(' + target_player + ')' + seperator;
1775 }
1776
1777 for (var prop in shortNames) {
1778 var amount = $.trim($unitTableRow.find('.unit-item-'+prop).text());
1779 if (amount != 0) {
1780 if (firstName) {
1781 renamed += shortNames[prop] + '=' + amount;
1782 firstName = false;
1783 } else {
1784 renamed += ', ' + shortNames[prop] + '=' + amount;
1785 }
1786 }
1787 }
1788
1789 return renamed;
1790 }
1791
1792 function showStacksOnMap() {
1793 if ($('#VDP_img').length == 0) {
1794 var info = data.troopsOnMap.info;
1795 if (Object.keys(info).length > 0) {
1796 var VDP_Map = TWMap;
1797
1798 function spawnSectorReplacer(data, sector) {
1799 VDP_Map.mapHandler.VDPspawnSector(data, sector);
1800 var beginX = sector.x - data.x,
1801 endX = beginX + VDP_Map.mapSubSectorSize,
1802 beginY = sector.y - data.y,
1803 endY = beginY + VDP_Map.mapSubSectorSize;
1804
1805 for (var x in data.tiles) {
1806 var x = parseInt(x, 10);
1807 if (x < beginX || x >= endX) {
1808 continue;
1809 }
1810
1811 for (var y in data.tiles[x]) {
1812 var y = parseInt(y, 10);
1813 if (y < beginY || y >= endY) {
1814 continue;
1815 }
1816
1817 var xCoord = data.x + x,
1818 yCoord = data.y + y,
1819 v = VDP_Map.villages[(xCoord) * 1000 + yCoord];
1820
1821 if (v) {
1822 for (var prop in info) {
1823 if (prop == (xCoord + "|" + yCoord)) {
1824 var colorStack = [[0, '#9900FF'], [4, '#FFFFFF'], [7, 'steelblue'], [9, '#C6DC65'], [12, 'orange'], [14, '#FF0000']],
1825 color = '';
1826
1827 for (var i = 0; i < colorStack.length; i++) {
1828 if (parseFloat(info[prop]) > colorStack[i][0]) {
1829 color = colorStack[i][1];
1830 }
1831 }
1832
1833 var img = document.createElement('div');
1834 img.style.position = 'absolute';
1835 img.style.zIndex = '50';
1836 img.style.width = (VDP_Map.map.scale[0]-1).toString() + 'px';
1837 img.style.height = (VDP_Map.map.scale[1]-1).toString() + 'px';
1838 img.style.backgroundPosition = 'center';
1839 img.id = 'VDP_img';
1840 img.innerHTML = '<span style="color:black;background-color:'+color+';position:absolute;font-size:12px;padding:1px;">'+info[prop]+'</span>';
1841 sector.appendElement(img, x - beginX, y - beginY);
1842 }
1843 }
1844 }
1845 }
1846 }
1847 }
1848
1849 VDP_Map.mapHandler.VDPspawnSector = VDP_Map.mapHandler.spawnSector;
1850 VDP_Map.mapHandler.spawnSector = spawnSectorReplacer;
1851 VDP_Map.reload();
1852 }
1853 }
1854 }
1855
1856 function insertOverviewTable(tab, infoObj) {
1857 if (tab == 'Ondersteuning') {
1858 var thRow = getThRow(['Dorp ('+Object.keys(infoObj['content']).length+')', 'Uimgs', 'Deffs']),
1859 html = '<table class="vis VDP_away_detail VDP_table" style="width:100%;"><tr><th colspan="11">' +
1860 '<input type="text" class="autocomplete plName" placeholder="Spelersnaam..."><input type="button" class="btn doPlayer" value="Aanvinken" style="margin-right:10px;">' +
1861 ' | <input type="button" class="btn doEnemy" value="Vijanden Aanvinken" title="Selecteer alle ossings die terug mogen van andere stammen" style="margin-left: 10px;margin-right: 10px;">' +
1862 ' | <input name="submit_units_back" class="btn" type="submit" value="Terugtrekken" style="margin-left:10px;">' +
1863 '</th></tr>' + thRow;
1864
1865 if (Object.keys(infoObj['content']).length == 0) {
1866 html += '<tr><td colspan="14" style="text-align:center;">Geen data gevonden</td></tr>';
1867 } else {
1868 for (var prop in infoObj['content']) {
1869 html += '<tr class="VDP_tr" data-player="'+infoObj['content'][prop].player+'" data-tribe="'+infoObj['content'][prop].tribe+'">' +
1870 '<td><input type="checkbox" class="VDP_village_checkbox village_checkbox" value="'+prop+'"> '+infoObj['content'][prop].link+'</td>';
1871
1872 for (var i = 0, l = infoObj['content'][prop].troops.length; i < l; i++) {
1873 html += '<td style="text-align:center;" class="checkForZero">'+infoObj['content'][prop].troops[i]+'</td>';
1874 }
1875
1876 html += '<td style="text-align:center;"><b>'+calculateDefTroops('byArray', infoObj['content'][prop].troops)+'</b></td>' +
1877 '</tr>';
1878 }
1879 }
1880
1881 html += '<tr><th>Totaal:</th>';
1882 for (var i = 0, l = infoObj.totaltroops.length; i < l; i++) {
1883 html += '<th style="text-align:center;" class="checkForZero">'+infoObj.totaltroops[i]+'</th>';
1884 }
1885 html += '<th style="text-align:center;">'+calculateDefTroops('byArray', infoObj.totaltroops)+'</th></tr>' +
1886 '</table><input name="submit_units_back" class="btn" type="submit" value="Terugtrekken"><br><br><br>';
1887
1888 $('.overview_table').before(html);
1889 $('.VDP_away_detail').append($('.overview_table').find('tr').last().clone());
1890 $('.selectAll').removeAttr('onclick');
1891
1892 $('.selectAll').off().on('click', function(){
1893 var checked = $(this).prop('checked');
1894 $('.selectAll').prop('checked', checked);
1895 $('.village_checkbox').prop('checked', checked);
1896 })
1897
1898 $('.VDP_village_checkbox').off().on('change', function(){
1899 $('span.village_anchor[data-id="' + $(this).val() + '"]').prev('.village_checkbox').prop('checked', $(this).prop('checked'));
1900 })
1901
1902 $('.autocomplete').autocomplete({
1903 minLength: 2,
1904 source: UI.AutoComplete.source,
1905 focus: UI.AutoComplete.handleFocus
1906 });
1907
1908 $('.doPlayer').off().on('click', function(){
1909 $('.VDP_table tr[data-player="' + $('.plName').val() + '"]').find('.village_checkbox').prop('checked', true).trigger('change');
1910 })
1911
1912 $('.doEnemy').off().on('click', function(){
1913 $('.VDP_table tr').not('[data-tribe="'+ownTribeName+'"]').find('.village_checkbox').prop('checked', true).trigger('change');
1914 })
1915 } else if (tab == 'Verdediging') {
1916 var thRow = getThRow(['Speler ('+Object.keys(infoObj['content']).length+')', 'support_img', 'Deffs', 'Uimgs'])
1917 html = '<table class="vis VDP_support_detail VDP_table" style="width:100%;">' + thRow;
1918
1919 if (Object.keys(infoObj['content']).length == 0) {
1920 html += '<tr><td colspan="14" style="text-align:center;">Geen data gevonden</td></tr>';
1921 } else {
1922 for (var prop in infoObj['content']) {
1923 html += '<tr>' +
1924 '<td>'+ infoObj['content'][prop].pl_link+' ['+ infoObj['content'][prop].tribe_link+']</td>' +
1925 '<td style="text-align:center;">'+ infoObj['content'][prop].os+'</td>' +
1926 '<td style="text-align:center;">'+calculateDefTroops('byArray', infoObj['content'][prop].troops)+'</td>';
1927
1928 for (var i = 0, l = infoObj['content'][prop].troops.length; i < l; i++) {
1929 html += '<td style="text-align:center;" class="checkForZero">'+infoObj['content'][prop].troops[i]+'</td>';
1930 }
1931
1932 html += '</tr>';
1933 }
1934 }
1935
1936 html += '<tr><th>Totaal:</th>' +
1937 '<th style="text-align:center;">'+infoObj.totalossings+' in '+infoObj.totalvillages.length+' dorpen</th>' +
1938 '<th style="text-align:center;">'+calculateDefTroops('byArray', infoObj.totaltroops)+'</th>';
1939 for (var i = 0, l = infoObj.totaltroops.length; i < l; i++) {
1940 html += '<th style="text-align:center;" class="checkForZero">'+infoObj.totaltroops[i]+'</th>';
1941 }
1942 html += '</tr></table><br><br><br>';
1943
1944 $('.overview_table').before(html);
1945 }
1946 }
1947
1948 function getThRow(thArr) {
1949 var thR = '<tr>';
1950 for (var i = 0, l = thArr.length; i < l; i++) {
1951 if (thArr[i] == 'Uimgs') {
1952 var imgs = $('.overview_table th[style="text-align:center"]');
1953 for (var x = 0, z = imgs.length; x < z; x++) {
1954 thR += '<th style="text-align:center">' + imgs.eq(x).html() + '</th>';
1955 }
1956 } else if (thArr[i] == 'support_img') {
1957 thR += '<th style="text-align:center;"><img src="https://cdn.tribalwars.net/graphic/command/support.png" title="Aantal ondersteuningen van deze speler die bij jou staan"></th>';
1958 } else {
1959 var center = (thArr[i] == 'Deffs') ? 'text-align:center;': '';
1960 thR += '<th style="'+center+'">' + thArr[i] + '</th>';
1961 }
1962 }
1963
1964 thR += '</tr>';
1965
1966 return thR;
1967 }
1968
1969 function getTableInfo(type) {
1970 var $table = $('#units_table'),
1971 obj = {
1972 'content': {},
1973 'totaltroops': [],
1974 'totalossings': 0,
1975 'totalvillages': []
1976 };
1977
1978 for (var i = 0, l = $('.overview_table tr:eq(0) img[src*="graphic/unit/"]').length; i < l; i++) {
1979 obj['totaltroops'].push(0);
1980 }
1981
1982 if (type == 'Ondersteuning') {
1983 var $cbx = $table.find('.village_checkbox');
1984
1985 for (var i = 0, l = $cbx.length; i < l; i++) {
1986 var $this = $cbx.eq(i),
1987 vil_id = $this.closest('span').find('.village_anchor').first().attr('data-id'),
1988 link = $this.closest('span').html().replace(/<input.*>/, '').replace('<a class="ctx" href="#"/>', ''),
1989 player = ($this.closest('span').find('a[href*="screen=info_player"]').length > 0) ? $.trim($this.closest('span').find('a[href*="screen=info_player"]').text()) : ($this.closest('span').text().match('(---)')) ? '---' : game_data.player.name,
1990 tribe = ($this.closest('span').find('a[href*="screen=info_ally"]').length > 0) ? $.trim($this.closest('span').find('a[href*="screen=info_ally"]').text()) : ownTribeName,
1991 units = $this.closest('tr').find('td.unit-item'),
1992 t = [],
1993 total = obj['totaltroops'];
1994
1995 if (obj['content'].hasOwnProperty(vil_id)) {
1996 t = obj['content'][vil_id].troops;
1997 for (var x = 0, z = units.length; x < z; x++) {
1998 t[x] = (t[x] + parseInt(units.eq(x).text()));
1999 }
2000
2001 obj['content'][vil_id].troops = t;
2002 } else {
2003 for (var x = 0, z = units.length; x < z; x++) {
2004 t.push(parseInt(units.eq(x).text()));
2005 }
2006
2007 obj['content'][vil_id] = {'link': link, 'player': player, 'tribe': tribe, 'troops': t};
2008 }
2009
2010 for (var x = 0, z = units.length; x < z; x++) {
2011 total[x] = (total[x] + parseInt(units.eq(x).text()));
2012 }
2013
2014 obj['totaltroops'] = total;
2015 }
2016 } else if (type == 'Verdediging') {
2017 var $va = $table.find('span.village_anchor');
2018
2019 for (var i = 0, l = $va.length; i < l; i++) {
2020 var $this = $va.eq(i),
2021 pl_id = $this.attr('data-player'),
2022 pl_link = ($this.closest('td').find('a[href*="screen=info_player"]').length > 0) ? $this.closest('td').find('a[href*="screen=info_player"]')[0].outerHTML : '<a href="/game.php?screen=info_player&id='+game_data.player.id+'" title="Tortuga">'+game_data.player.name+'</a>',
2023 tribe_link = ($this.closest('td').find('a[href*="screen=info_ally"]').length > 0) ? $this.closest('td').find('a[href*="screen=info_ally"]')[0].outerHTML : '<a href="/game.php?screen=info_ally&id='+ownTribeID+'">'+ownTribeName+'</a>',
2024 ossed_vill_id = $this.prev('input').attr('name').match(/\d+/)[0],
2025 units = $this.closest('tr').find('td.unit-item'),
2026 t = [],
2027 total = obj['totaltroops'];
2028
2029 if (obj['content'].hasOwnProperty(pl_id)) {
2030 t = obj['content'][pl_id].troops;
2031 for (var x = 0, z = units.length; x < z; x++) {
2032 t[x] = (t[x] + parseInt(units.eq(x).text()));
2033 }
2034
2035 obj['content'][pl_id].troops = t;
2036 obj['content'][pl_id].os = (obj['content'][pl_id].os + 1);
2037 } else {
2038 for (var x = 0, z = units.length; x < z; x++) {
2039 t.push(parseInt(units.eq(x).text()));
2040 }
2041
2042 obj['content'][pl_id] = {'pl_link': pl_link, 'tribe_link': tribe_link, 'os': 1, 'troops': t};
2043 }
2044
2045 for (var x = 0, z = units.length; x < z; x++) {
2046 total[x] = (total[x] + parseInt(units.eq(x).text()));
2047 }
2048
2049 obj['totaltroops'] = total;
2050 obj['totalossings'] = (obj['totalossings'] + 1);
2051
2052 if (obj['totalvillages'].indexOf(ossed_vill_id) == -1) {
2053 obj['totalvillages'].push(ossed_vill_id);
2054 }
2055 }
2056 }
2057
2058 return obj;
2059 }
2060
2061 function splitArriavals($siu) {
2062 $siu.find('tr').find('td:eq(1):contains("vandaag")').closest('tr').last().find('td').css('border-bottom', '1px solid #7D510F');
2063 $siu.find('tr').find('td:eq(1):contains("morgen")').closest('tr').last().find('td').css('border-bottom', '1px solid #7D510F');
2064 for (var i = 1, l = 32; i < l; i++) {
2065 var x = (i < 10) ? '0' + i.toString() : i.toString();
2066 $siu.find('tr').find('td:eq(1):contains("' + x + '.")').closest('tr').last().find('td').css('border-bottom', '1px solid #7D510F');
2067 }
2068 }
2069
2070 function handleDaySelection() {
2071 var $siu = (screen == 'overview_villages') ? $('.overview_table') : $(this).closest('table'),
2072 date = $(this).attr('data-date').toString(),
2073 $attack_tr = $siu.find('img[src*="attack.png"]').closest('tr');
2074
2075 $attack_tr.find('input[type="checkbox"]').prop('checked', false);
2076 $('.VDP_DayChecker').not(this).prop('checked', false);
2077
2078 if (date == 'all') {
2079 $attack_tr.find('input[type="checkbox"]').prop('checked', $(this).prop('checked'));
2080 $('.VDP_DayChecker').not(this).prop('checked', $(this).prop('checked'));
2081 /*if (screen == 'overview_villages') {
2082 $('.selectAll').prop('checked', $(this).prop('checked'));
2083 } --> visueel mooi om te doen, werkt tegen bij de optie "gemarkeerde selecteren als" */
2084 } else if (date == 'vandaagenmorgen') {
2085 $attack_tr.find('td:contains("vandaag")').closest('tr').find('input[type="checkbox"]').prop('checked', $(this).prop('checked'));
2086 $attack_tr.find('td:contains("morgen")').closest('tr').find('input[type="checkbox"]').prop('checked', $(this).prop('checked'));
2087 } else {
2088 $attack_tr.find('td:contains("' + date + '")').closest('tr').find('input[type="checkbox"]').prop('checked', $(this).prop('checked'));
2089 }
2090 }
2091
2092 function insertDaySelection() {
2093 var html = '<input name="all" type="checkbox" id="select_all" class="VDP_DayChecker" data-date="all"> <label for="select_all">alles selecteren</label>'
2094 + ' | <input type="checkbox" id="select_today" class="VDP_DayChecker" data-date="vandaag"> <label for="select_today">vandaag selecteren</label>'
2095 + ' | <input type="checkbox" id="select_todayandtomorrow" class="VDP_DayChecker" data-date="vandaagenmorgen"> <label for="select_todayandtomorrow">vandaag en morgen selecteren</label>'
2096 + ' | <input type="checkbox" id="select_tomorrow" class="VDP_DayChecker" data-date="morgen"> <label for="select_tomorrow">morgen selecteren</label>';
2097
2098 $('.selectAll').parent('th').html(html);
2099
2100 $('.VDP_DayChecker').off().on('click', handleDaySelection);
2101 }
2102
2103 function renameCommand(val, id) {
2104 var post_url = game_data.link_base_pure + 'info_command&ajaxaction=edit_other_comment&id=' + id + '&h=' + game_data.csrf + h_mode;
2105 $.twAjax({
2106 url: post_url,
2107 type: 'POST',
2108 data: {text: val},
2109 success: function () {
2110 $('span[data-id="' + id + '"]').find('span.quickedit-label').text(val);
2111 }
2112 });
2113 }
2114
2115 function incomingsCounter($table) {
2116 return $table.find('img[src*="attack.png"]').closest('tr').length;
2117 }
2118
2119 function nobelCounter($table) {
2120 var x = 0,
2121 nobleChecker = /edel|noble|snob|Edel|EDEL|Snob|Noble/,
2122 $inc = $table.find('img[src*="attack.png"]'),
2123 $inc_label = $inc.closest('tr').find('.quickedit-label');
2124
2125 for (var i = 0, l = $inc_label.length; i < l; i++) {
2126 var text = $inc_label.eq(i).text();
2127
2128 if (text.match(/\(\d{1,3}\|\d{1,3}\)/)) { // (632|661) -> exclude player names
2129 var split = text.split(/\(\d{1,3}\|\d{1,3}\)/)[0];
2130 if (split.match(nobleChecker)) {
2131 x++;
2132 }
2133 } else {
2134 if (text.match(nobleChecker)) {
2135 x++;
2136 }
2137 }
2138 }
2139
2140 return x;
2141 }
2142
2143 function addHotkeyPlugin() {
2144 (function (jQuery) {
2145 /*
2146 * jQuery Hotkeys Plugin
2147 * Copyright 2010, John Resig
2148 * Dual licensed under the MIT or GPL Version 2 licenses.
2149 *
2150 * Based upon the plugin by Tzury Bar Yochay:
2151 * http://github.com/tzuryby/hotkeys
2152 *
2153 * Original idea by:
2154 * Binny V A, http://www.openjs.com/scripts/events/keyboard_shortcuts/
2155 */
2156
2157 jQuery.hotkeys = {
2158 version: "0.8",
2159
2160 specialKeys: {
2161 8: "backspace", 9: "tab", 13: "return", 16: "shift", 17: "ctrl", 18: "alt", 19: "pause",
2162 20: "capslock", 27: "esc", 32: "space", 33: "pageup", 34: "pagedown", 35: "end", 36: "home",
2163 37: "left", 38: "up", 39: "right", 40: "down", 45: "insert", 46: "del",
2164 96: "0", 97: "1", 98: "2", 99: "3", 100: "4", 101: "5", 102: "6", 103: "7",
2165 104: "8", 105: "9", 106: "*", 107: "+", 109: "-", 110: ".", 111: "/",
2166 112: "f1", 113: "f2", 114: "f3", 115: "f4", 116: "f5", 117: "f6", 118: "f7", 119: "f8",
2167 120: "f9", 121: "f10", 122: "f11", 123: "f12", 144: "numlock", 145: "scroll", 191: "/", 224: "meta"
2168 },
2169
2170 shiftNums: {
2171 "`": "~", "1": "!", "2": "@", "3": "#", "4": "$", "5": "%", "6": "^", "7": "&",
2172 "8": "*", "9": "(", "0": ")", "-": "_", "=": "+", ";": ": ", "'": "\"", ",": "<",
2173 ".": ">", "/": "?", "\\": "|"
2174 }
2175 };
2176
2177 function keyHandler(handleObj) {
2178 // Only care when a possible input has been specified
2179 if (typeof handleObj.data !== "string") {
2180 return;
2181 }
2182
2183 var origHandler = handleObj.handler,
2184 keys = handleObj.data.toLowerCase().split(" ");
2185
2186 handleObj.handler = function (event) {
2187 // Don't fire in text-accepting inputs that we didn't directly bind to
2188 if (this !== event.target && (/textarea|select/i.test(event.target.nodeName) ||
2189 event.target.type === "text")) {
2190 return;
2191 }
2192
2193 // Keypress represents characters, not special keys
2194 var special = event.type !== "keypress" && jQuery.hotkeys.specialKeys[event.which],
2195 character = String.fromCharCode(event.which).toLowerCase(),
2196 key, modif = "", possible = {};
2197
2198 // check combinations (alt|ctrl|shift+anything)
2199 if (event.altKey && special !== "alt") {
2200 modif += "alt+";
2201 }
2202
2203 if (event.ctrlKey && special !== "ctrl") {
2204 modif += "ctrl+";
2205 }
2206
2207 if (event.metaKey && !event.ctrlKey && special !== "meta") {
2208 modif += "meta+";
2209 }
2210
2211 if (event.shiftKey && special !== "shift") {
2212 modif += "shift+";
2213 }
2214
2215 if (special) {
2216 possible[modif + special] = true;
2217
2218 } else {
2219 possible[modif + character] = true;
2220 possible[modif + jQuery.hotkeys.shiftNums[character]] = true;
2221
2222 // "$" can be triggered as "Shift+4" or "Shift+$" or just "$"
2223 if (modif === "shift+") {
2224 possible[jQuery.hotkeys.shiftNums[character]] = true;
2225 }
2226 }
2227
2228 for (var i = 0, l = keys.length; i < l; i++) {
2229 if (possible[keys[i]]) {
2230 return origHandler.apply(this, arguments);
2231 }
2232 }
2233 };
2234 }
2235
2236 jQuery.each(["keydown", "keyup", "keypress"], function () {
2237 jQuery.event.special[this] = {add: keyHandler};
2238 });
2239 })(jQuery);
2240 }
2241
2242 function incomingsRenamer(byHotkey, incPrefix, $table, isCustomPostfix, onlyAddLastTag) {
2243 var commandsChecker = /OK|DODGED|DODGE|MARKEREN|GEVRAAGD|BIJSTACKEN/;
2244
2245 if (screen == 'overview_villages') {
2246 for ( var i = 0, amountOfRows = $table.length; i < amountOfRows; i++ ) {
2247 var $currentRow = $table.eq( i ).find( 'td' ).first(),
2248 currentRowID = $currentRow.find( 'span.quickedit' ).data( 'id' ),
2249 currentRowLabel = $currentRow.find( 'span.quickedit-label' ).text().trim(),
2250 newLabel;
2251
2252 if ( currentRowLabel.match( commandsChecker ) !== null && currentRowLabel.match( commandsChecker ).length > 0 ) {
2253 newLabel = currentRowLabel.replace(/\[.+] /, '').replace( commandsChecker, incPrefix );
2254 } else {
2255 newLabel = incPrefix + ' ' + currentRowLabel.replace(/\[.+] /, '');
2256 }
2257 renameCommand( newLabel, currentRowID );
2258 }
2259 } else {
2260 if (onlyAddLastTag) {
2261 var $row = $table.find( 'img[src*="attack.png"]' ).closest( 'tr' ).last().find( 'td' ).first();
2262 var id = $row.find( 'span.quickedit' ).data( 'id' );
2263 var newTag = $row.find( 'span.quickedit-label' ).text().trim().replace( /LAATSTE/, '' ) + ' LAATSTE';
2264 renameCommand( newTag, id );
2265 } else {
2266 var $incRows = $table.find( 'img[src*="attack.png"]' ).closest( 'tr' ),
2267 incData = {},
2268 i = 0;
2269 var $row = $incRows.parent().find( '[data-vitaelabel*="true"]' );
2270 if ( byHotkey && $row.length > 0 ) {
2271 var label = $row.find( 'td' ).first().find( 'span.quickedit-label' ).text().trim();
2272 if ( label.match( commandsChecker ) !== null && label.match( commandsChecker ).length > 0 ) {
2273 label = label.replace( commandsChecker, incPrefix );
2274 } else {
2275 label = incPrefix + " " + label;
2276 }
2277 var labelId = $row.find( 'span.quickedit' ).data( 'id' );
2278 renameCommand( label, labelId );
2279 } else if (byHotkey === false || (byHotkey && data.hotkeyWhenNotHovered)) {
2280 var checkBoxChecked = function () {
2281 if ( screen == 'info_village' || (getUserData().autoSelect === 'disabled' && $('#show_incoming_units').find('input[type="checkbox"]:checked').length == 0 )) {
2282 return function () {
2283 return true;
2284 };
2285 } else {
2286 return function ( $row ) {
2287 return $row.find( 'input[type="checkbox"]' ).prop( 'checked' );
2288 };
2289 }
2290 }();
2291 for ( var i = 0, amountOfRows = $incRows.length; i < amountOfRows; i++ ) {
2292 var $currentRow = $incRows.eq( i ).find( 'td' ).first();
2293 var currentRowLabel = $currentRow.find( 'span.quickedit-label' ).text().trim();
2294 if ( currentRowLabel.indexOf( 'LAATSTE' ) != -1 ) {
2295 currentRowLabel = currentRowLabel.replace( /LAATSTE/, '' );
2296 }
2297
2298 if ( i === amountOfRows - 1 ) {
2299 currentRowLabel += " LAATSTE";
2300 }
2301
2302 if ( checkBoxChecked( $incRows.eq( i ) ) ) {
2303 incData[ $currentRow.find( 'span.quickedit' ).data( 'id' ) ] = currentRowLabel;
2304 }
2305 }
2306
2307 if ( isCustomPostfix) {
2308 incPrefix = (incPrefix == '') ? ' ' : ' [' + incPrefix.toUpperCase() + '] ';
2309 for ( var prop in incData ) {
2310 var match = incData[ prop ].match( commandsChecker );
2311
2312 if ( match ) {
2313 incData[ prop ] = match[ 0 ] + incPrefix + incData[ prop ].replace( commandsChecker, '' ).replace( /\[.+]/, '' );
2314 } else {
2315 incData[ prop ] = incPrefix + incData[ prop ];
2316 }
2317 renameCommand( incData[ prop ], prop );
2318 }
2319 } else {
2320 for ( var prop in incData ) {
2321 if ( incData[ prop ].match( commandsChecker ) !== null && incData[ prop ].match( commandsChecker ).length > 0 ) {
2322 incData[ prop ] = incData[ prop ].replace( commandsChecker, incPrefix );
2323 } else {
2324 incData[ prop ] = incPrefix + ' ' + incData[ prop ];
2325 }
2326 renameCommand( incData[ prop ], prop );
2327 }
2328 }
2329 }
2330 }
2331 }
2332 }
2333
2334 function shortcutGenerator( byHotkey, label, incTable, isCustomPostfix, onlyAddLastTag ) {
2335 return function () {
2336 label = (label === false) ? $('.custom_text').val() : label;
2337 incomingsRenamer( byHotkey, label, incTable, isCustomPostfix, onlyAddLastTag );
2338 $( document ).ajaxComplete( function () {
2339 var $rows = incTable.find( 'img[src*="attack.png"]' ).closest( 'tr' );
2340 giveColor( $rows );
2341 $('#custom-tag').off().on( 'click', shortcutGenerator(false, false, incTable, true ) );
2342 } );
2343 return false;
2344 }
2345 }
2346
2347 function renameHotkeys(labels, incTable) {
2348 addHotkeyPlugin();
2349 $( document ).off( 'keydown keyup keypress' );
2350 for ( var prop in labels ) {
2351 if ( prop !== 'LAATSTE' ) {
2352 $( document ).bind( 'keydown', labels[ prop ].hotkey, shortcutGenerator( true, prop, incTable ) );
2353 } else {
2354 $( document ).bind( 'keydown', labels[ prop ].hotkey, shortcutGenerator( true, prop, incTable, false, true ) );
2355 }
2356 }
2357
2358 switchToNextVillageUnderAttack();
2359 }
2360
2361 function doAutoSelect(val, $siu, save) {
2362 var $attack_tr = $siu.find('img[src*="attack.png"]').closest('tr');
2363
2364 $siu.find('input[type="checkbox"]').prop('checked', false);
2365
2366 if (val == 'vandaagenmorgen') {
2367 $attack_tr.find('td:contains("vandaag")').closest('tr').find('input[type="checkbox"]').prop('checked', true);
2368 $attack_tr.find('td:contains("morgen")').closest('tr').find('input[type="checkbox"]').prop('checked', true);
2369 } else {
2370 $attack_tr.find('td:contains("' + val + '")').closest('tr').find('input[type="checkbox"]').prop('checked', true);
2371 }
2372
2373 if (save) {
2374 data.autoSelect = val;
2375 localStorage.setItem('VitaePackage_'+world+'_'+player, JSON.stringify(data));
2376 }
2377 }
2378
2379 function insertRenameButtons(labels, $table) {
2380 // creating row
2381 var td_style = {
2382 'padding': '0',
2383 'margin': '0',
2384 'list-style': 'none',
2385 'display': '-webkit-box',
2386 'display': '-moz-box',
2387 'display': '-ms-flexbox',
2388 'display': '-webkit-flex',
2389 'display': 'flex',
2390 '-webkit-flex-flow': 'row wrap',
2391 'justify-content': 'space-around',
2392 '-webkit-justify-content': 'space-around',
2393 'flex-wrap': 'nowrap',
2394 '-webkit-flex-wrap': 'nowrap'
2395 }
2396
2397 var tr_html = (screen == 'info_village') ? '<tr><td class="button_td" colspan="4"></td></tr>' : '<tr><td class="button_td add_td_style"></td><td class="autoSelect_td" colspan="3" style="text-align: center;"></td></tr>';
2398 $table.find('tr:first').after(tr_html);
2399 $('.add_td_style').css(td_style);
2400
2401 // adding buttons
2402 for (var prop in labels) {
2403 var style = {
2404 'background-color': labels[prop].color,
2405 'margin': '3px 5px',
2406 'font-weight': 'bold',
2407 'border': '1px solid black',
2408 'cursor': 'pointer'
2409 }
2410
2411 if (prop !== 'LAATSTE') {
2412 $( '<input type="button" class="VDP-RenameButtons" value="' + prop + '">' ).css( style ).on( 'click', shortcutGenerator( false, prop, $table ) ).appendTo( $( '.button_td' ) );
2413 } else {
2414 $( '<a href="#"> - '+ prop +'</a>' ).on( 'click', shortcutGenerator( false, prop, $table, false, true ) ).appendTo( $table.find( 'td:contains("Ondersteuning aanvragen")' ) );
2415 }
2416 }
2417
2418 $('<span style="margin:3px 5px;">|</span><span title="Deze tag wordt toegevoegd tussen [ ]"><input type="text" class="custom_text" size="14" style="text-transform:uppercase;border: 1px solid black;font-weight:bold;margin: 3px 5px;"><input type="button" class="VDP-RenameButtons" id="custom-tag" style="font-weight:bold;border:1px solid black;cursor:pointer;margin-left:2px;" value="OK"></span>').appendTo($('.button_td'));
2419 $('.custom_text').off().on('keydown', function(e) {
2420 if (e.keyCode == 13) {
2421 e.preventDefault();
2422 $('#custom-tag').click();
2423 $('.custom_text').trigger('blur');
2424 }
2425 });
2426 $('#custom-tag').off().on( 'click', shortcutGenerator( false, false, $table, true ) );
2427 }
2428
2429 function inserAutoSelect($table) {
2430 // adding autoSelect
2431 var options = {'Uitgeschakeld': 'disabled', 'Vandaag': 'vandaag', 'Vandaag en Morgen': 'vandaagenmorgen', 'Morgen': 'morgen'},
2432 select = '<b>Automatisch geselecteerd:</b> <select class="autoSelect_select">';
2433 for (var prop in options) {
2434 if (options[prop] == data.autoSelect) {
2435 select += '<option value="'+options[prop]+'" selected>'+prop+'</option>';
2436 } else {
2437 select += '<option value="'+options[prop]+'">'+prop+'</option>';
2438 }
2439 }
2440 select += '</select>';
2441
2442 $('.autoSelect_td').append(select);
2443 $('.autoSelect_select').off().on('change', function(){doAutoSelect($(this).val(), $table, true);});
2444 }
2445
2446 function Simulate(defence, wall, inc, callback) {
2447 var clear = [];
2448 if (localStorage.getItem('IMSv2.1_clears_'+game_data.world+'_'+game_data.player.id)) {
2449 var IMS_Clears = JSON.parse(localStorage.getItem('IMSv2.1_clears_'+game_data.world+'_'+game_data.player.id));
2450 if (IMS_Clears['Standaard'] === undefined) {
2451 clear = [0, 0, 5800, 0, 3000, 0, 300, 50];
2452 } else {
2453 clear = IMS_Clears['Standaard'].split('_');
2454 }
2455 } else {
2456 clear = [0, 0, 5800, 0, 3000, 0, 300, 50];
2457 }
2458
2459 console.log(clear);
2460 console.log(defence);
2461 console.log(wall);
2462 console.log(inc);
2463
2464 //$.ajax({
2465 // url: 'https://swtools.programmingtuts.nl/IMSprivate/massSimulator.php',
2466 // type: 'POST',
2467 // data: {
2468 // 'bow': 0,
2469 // 'offence': clear,
2470 // 'defence': defence,
2471 // 'wall': wall,
2472 // 'morale': 1,
2473 // 'religious': 1,
2474 // 'katawall': 1
2475 // },
2476 // success: function (response) {
2477 // response = JSON.parse(response);
2478 // var _wall = response['restwall'][inc],
2479 // _wallLower = (_wall < wall) ? true : false;
2480 //callback({'clears': response['c'], 'resttroops': response['resttroops'][inc], 'wall': _wall, 'wallLower': _wallLower});
2481 // },
2482 // error: function () {
2483 // UI.ErrorMessage('Er is een fout opgetreden bij de simulatie !');
2484 // }
2485 //});
2486 }
2487
2488 function insertStackRating() {
2489 var $incTable = $('#show_incoming_units'),
2490 stackBeoordeling = {'text': '', 'color': ''},
2491 inc = incomingsCounter($incTable),
2492 def_troops = [];
2493
2494 for (var i in troop_names) {
2495 var td = $('#show_units td:contains("'+troop_names[i]+'")');
2496 if (td.length != 0) {
2497 var aantal = parseInt(td.find('strong').eq(0).text());
2498 def_troops.push(aantal);
2499 } else {
2500 def_troops.push(0);
2501 }
2502 }
2503
2504 Simulate(def_troops, game_data.village.buildings.wall, inc, function(result) {
2505 if (inc < (parseInt(result.clears) - parseInt(data.autoRenamer.blockChecker.marge))) {
2506 stackBeoordeling.color = 'green';
2507 if (!result.wallLower) {
2508 stackBeoordeling.text = 'STACK OK | ' + calculateDefTroops('byArray', result.resttroops) + ' deffs over | muur zakt niet';
2509 } else {
2510 stackBeoordeling.text = 'STACK OK | ' + calculateDefTroops('byArray', result.resttroops) + ' deffs over | muur zakt tot lvl ' + result.wall;
2511 }
2512 } else if (inc < (parseInt(result.clears))) {
2513 stackBeoordeling.color = 'yellow';
2514 if (!result.wallLower) {
2515 stackBeoordeling.text = 'STACK NIPT | ' + calculateDefTroops('byArray', result.resttroops) + ' deffs over | muur zakt niet';
2516 } else {
2517 stackBeoordeling.text = 'STACK NIPT | ' + calculateDefTroops('byArray', result.resttroops) + ' deffs over | muur zakt tot lvl ' + result.wall;
2518 }
2519 } else {
2520 var currentDeffs = parseInt($('.VDP_deffs').attr('data-deffs')).toFixed(0),
2521 deffs_extra = (inc > deffs_needed.length) ? 'x' : (deffs_needed[inc] - currentDeffs);
2522
2523 stackBeoordeling.color = 'red';
2524 stackBeoordeling.text = 'STACK NIET OK | bijstacken met ' + deffs_extra + ' deffs';
2525 }
2526
2527 $incTable.find('h4.head').first().append('<span style="float:right;margin-right:15px;font-style: normal;color: '+stackBeoordeling.color+';">'+stackBeoordeling.text+'</span>');
2528 });
2529 }
2530
2531 function convertMStoTime(s, onlySeconds, classs) {
2532 function pad(number, length) {
2533 var str = '' + number;
2534 while (str.length < length) {
2535 str = '0' + str;
2536 }
2537 return str;
2538 }
2539
2540 var ms = s % 1000;
2541 s = (s - ms) / 1000;
2542 var secs = s % 60;
2543 s = (s - secs) / 60;
2544 var mins = s % 60;
2545 var hrs = (s - mins) / 60;
2546
2547 if (onlySeconds) {
2548 return pad(secs, 1) + '.<span class="' + classs + '">' + pad(ms, 3) + '</span>';
2549 } else {
2550 return pad(hrs, 2) + ':' + pad(mins, 2) + ':' + pad(secs, 2) + ':<span class="' + classs + '">' + pad(ms, 3) + '</span>';
2551 }
2552 }
2553
2554 function convertFromTimestamp(unixTimestamp) {
2555 function pad(number, length) {
2556 var str = '' + number;
2557 while (str.length < length) {
2558 str = '0' + str;
2559 }
2560 return str;
2561 }
2562
2563 var dt = new Date(unixTimestamp * 1),
2564 day = dt.getDate(),
2565 month = dt.getMonth() + 1,
2566 year = String(dt.getFullYear()).slice(2),
2567 hours = dt.getHours(),
2568 minutes = dt.getMinutes(),
2569 seconds = dt.getSeconds(),
2570 milliseconds = dt.getMilliseconds(),
2571 today = new Date().getDate(),
2572 tomorow = today + 1;
2573
2574 if (day == today) {
2575 return 'vandaag om ' + pad(hours, 2) + ":" + pad(minutes, 2) + ":" + pad(seconds, 2) + ':<span class="grey small">' + pad(milliseconds, 3) + '</span> uur';
2576 } else if (day == tomorow) {
2577 return 'morgen om ' + pad(hours, 2) + ":" + pad(minutes, 2) + ":" + pad(seconds, 2) + ':<span class="grey small">' + pad(milliseconds, 3) + '</span> uur';
2578 } else {
2579 return 'op ' + pad(day, 2) + '.' + pad(month, 2) + '.' + pad(year, 2) + ' om ' + pad(hours, 2) + ":" + pad(minutes, 2) + ":" + pad(seconds, 2) + ':<span class="grey small">' + pad(milliseconds, 3) + '</span> uur';
2580 }
2581 }
2582
2583 function convertToTimestamp(timestr) {
2584 // vandaag om 16:49:08:000 uur
2585 // op 21.08. om 05:04:11:000 uur
2586 var pos = timestr.indexOf(':'),
2587 MS = timestr.substr(pos + 7, 3),
2588 T = timestr.substr(pos - 2, 8),
2589 Serverdate = $('#serverDate').text().split('/'),
2590 D;
2591
2592 Serverdate = Serverdate[1] + ' ' + Serverdate[0] + ', ' + Serverdate[2];
2593 var Serverdate = new Date(Date.parse(Serverdate + ' ' + T));
2594 Serverdate.setMilliseconds(Serverdate.getMilliseconds() + MS);
2595
2596 if (timestr.match('vandaag')) {
2597 D = Serverdate;
2598 } else if (timestr.match('morgen')) {
2599 D = Serverdate;
2600 D.setDate(D.getDate() + 1);
2601 D.setMilliseconds(D.getMilliseconds());
2602 } else {
2603 var pos = timestr.indexOf('.'),
2604 d = timestr.substr(pos - 2, 5).split('.');
2605 d = d[1] + '/' + d[0] + '/' + Serverdate.getFullYear() + ' ' + T;
2606 D = new Date(Date.parse(d));
2607 D.setMilliseconds(D.getMilliseconds() + MS);
2608 }
2609
2610 return D.getTime();
2611 }
2612
2613 function getTroopsBackTimestamps($outTable){
2614 var timestamps = [];
2615
2616 var images = $outTable.find('img[src*="command/back.png"], img[src*="command/return_attack_medium.png"], img[src*="command/return_attack_large.png"]');
2617 for (var i = 0, l = images.length; i < l; i++) {
2618 timestamps.push(convertToTimestamp(images.eq(i).closest('tr').find('td').eq(1).text()));
2619 }
2620
2621 return timestamps;
2622 }
2623
2624 function insertTroopsBack($incRows, timestamps) {
2625 for (var i = 0, l = timestamps.length; i < l; i++) {
2626 for (var x = 0, z = $incRows.length; x < z; x++) {
2627 var $td = $incRows.eq(x).find('td').eq(1),
2628 timestamp = convertToTimestamp($td.text());
2629
2630 if (timestamps[i] < timestamp) {
2631 $td.css('border-top', '2px solid #7D510F');
2632 break;
2633 }
2634 }
2635 }
2636 }
2637
2638 function switchToNextVillageUnderAttack() {
2639 var i = data.villageSwitch.currentLinkPlace;
2640 if (data.villageSwitch.start && i === 0) {
2641 i--;
2642 data.villageSwitch.start = false;
2643 }
2644
2645 $(document)
2646 .bind('keydown', 'left', goToLink(i - 1))
2647 .bind('keydown', 'right', goToLink(i + 1));
2648 localStorage.setItem('VitaePackage_'+world+'_'+player, JSON.stringify(data));
2649 }
2650
2651 function goToLink(linknr) {
2652 return function () {
2653 var links = data.villageSwitch.deflinks;
2654 if (links.length > 0) {
2655 if (linknr < 0) {
2656 UI.ErrorMessage('Enkel rechter pijl zal werken !');
2657 } else if (links.length - 1 < linknr) {
2658 UI.ErrorMessage('Enkel linker pijl zal werken !');
2659 } else {
2660 data.villageSwitch.currentLinkPlace = linknr;
2661 localStorage.setItem('VitaePackage_'+world+'_'+player, JSON.stringify(data));
2662 window.location = links[linknr];
2663 }
2664 } else {
2665 UI.ErrorMessage('Er is nog geen informatie ingeladen !');
2666 }
2667 };
2668 }
2669
2670 function hoverLabel($rows) {
2671 $rows.hover(function() {
2672 $(this).attr('data-VitaeLabel', true).find('td').css('background-color', '#FFF68F');
2673 }, function() {
2674 $(this).removeAttr('data-VitaeLabel').find('td').css('background-color', '');
2675 });
2676 }
2677
2678}