]> git.sesse.net Git - pkanalytics/blob - ultimate.js
Move MainWindow into its own class.
[pkanalytics] / ultimate.js
1 'use strict';
2
3 // No frameworks, no compilers, no npm, just JavaScript. :-)
4
5 let global_json;
6 let global_filters = [];
7
8 addEventListener('hashchange', () => { process_matches(global_json, global_filters); });
9 addEventListener('click', possibly_close_menu);
10 fetch('ultimate.json')
11    .then(response => response.json())
12    .then(response => { global_json = response; process_matches(global_json, global_filters); });
13
14 function attribute_player_time(player, to, from, offense) {
15         let delta_time;
16         if (player.on_field_since > from) {
17                 // Player came in while play happened (without a stoppage!?).
18                 delta_time = to - player.on_field_since;
19         } else {
20                 delta_time = to - from;
21         }
22         player.playing_time_ms += delta_time;
23         if (offense === true) {
24                 player.offensive_playing_time_ms += delta_time;
25         } else if (offense === false) {
26                 player.defensive_playing_time_ms += delta_time;
27         }
28 }
29
30 function take_off_field(player, t, live_since, offense, keep) {
31         if (keep) {
32                 if (live_since === null) {
33                         // Play isn't live, so nothing to do.
34                 } else {
35                         attribute_player_time(player, t, live_since, offense);
36                 }
37                 if (player.on_field_since !== null) {  // Just a safeguard; out without in should never happen.
38                         player.field_time_ms += t - player.on_field_since;
39                 }
40         }
41         player.on_field_since = null;
42 }
43
44 function add_cell(tr, element_type, text) {
45         let element = document.createElement(element_type);
46         element.textContent = text;
47         tr.appendChild(element);
48         return element;
49 }
50
51 function add_th(tr, text, colspan) {
52         let element = document.createElement('th');
53         let link = document.createElement('a');
54         link.style.cursor = 'pointer';
55         link.addEventListener('click', (e) => {
56                 sort_by(element);
57                 process_matches(global_json, global_filters);
58         });
59         link.textContent = text;
60         element.appendChild(link);
61         tr.appendChild(element);
62
63         if (colspan > 0) {
64                 element.setAttribute('colspan', colspan);
65         } else {
66                 element.setAttribute('colspan', '3');
67         }
68         return element;
69 }
70
71 function add_3cell(tr, text, cls) {
72         let p1 = add_cell(tr, 'td', '');
73         let element = add_cell(tr, 'td', text);
74         let p2 = add_cell(tr, 'td', '');
75
76         p1.classList.add('pad');
77         p2.classList.add('pad');
78         if (cls === undefined) {
79                 element.classList.add('num');
80         } else {
81                 element.classList.add(cls);
82         }
83         return element;
84 }
85
86 function add_3cell_with_filler_ci(tr, text, cls) {
87         let element = add_3cell(tr, text, cls);
88
89         let svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
90         svg.classList.add('fillerci');
91         svg.setAttribute('width', ci_width);
92         svg.setAttribute('height', ci_height);
93         element.appendChild(svg);
94
95         return element;
96 }
97
98 function add_3cell_ci(tr, ci) {
99         if (isNaN(ci.val)) {
100                 add_3cell_with_filler_ci(tr, 'N/A');
101                 return;
102         }
103
104         let text;
105         if (ci.format === 'percentage') {
106                 text = (100 * ci.val).toFixed(0) + '%';
107         } else {
108                 text = ci.val.toFixed(2);
109         }
110         let element = add_3cell(tr, text);
111         let to_x = (val) => { return ci_width * (val - ci.min) / (ci.max - ci.min); };
112
113         // Container.
114         let svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
115         if (ci.inverted === true) {
116                 svg.classList.add('invertedci');
117         } else {
118                 svg.classList.add('ci');
119         }
120         svg.setAttribute('width', ci_width);
121         svg.setAttribute('height', ci_height);
122
123         // The good (green) and red (bad) ranges.
124         let s0 = document.createElementNS('http://www.w3.org/2000/svg', 'rect');
125         s0.classList.add('range');
126         s0.classList.add('s0');
127         s0.setAttribute('width', to_x(ci.desired));
128         s0.setAttribute('height', ci_height);
129         s0.setAttribute('x', '0');
130
131         let s1 = document.createElementNS('http://www.w3.org/2000/svg', 'rect');
132         s1.classList.add('range');
133         s1.classList.add('s1');
134         s1.setAttribute('width', ci_width - to_x(ci.desired));
135         s1.setAttribute('height', ci_height);
136         s1.setAttribute('x', to_x(ci.desired));
137
138         // Confidence bar.
139         let bar = document.createElementNS('http://www.w3.org/2000/svg', 'rect');
140         bar.classList.add('bar');
141         bar.setAttribute('width', to_x(ci.upper_ci) - to_x(ci.lower_ci));
142         bar.setAttribute('height', ci_height / 3);
143         bar.setAttribute('x', to_x(ci.lower_ci));
144         bar.setAttribute('y', ci_height / 3);
145
146         // Marker line for average.
147         let marker = document.createElementNS('http://www.w3.org/2000/svg', 'line');
148         marker.classList.add('marker');
149         marker.setAttribute('x1', to_x(ci.val));
150         marker.setAttribute('x2', to_x(ci.val));
151         marker.setAttribute('y1', ci_height / 6);
152         marker.setAttribute('y2', ci_height * 5 / 6);
153
154         svg.appendChild(s0);
155         svg.appendChild(s1);
156         svg.appendChild(bar);
157         svg.appendChild(marker);
158
159         element.appendChild(svg);
160 }
161
162 function process_matches(json, filters) {
163         let players = {};
164         for (const player of json['players']) {
165                 players[player['player_id']] = {
166                         'name': player['name'],
167                         'number': player['number'],
168
169                         'goals': 0,
170                         'assists': 0,
171                         'hockey_assists': 0,
172                         'catches': 0,
173                         'touches': 0,
174                         'num_throws': 0,
175                         'throwaways': 0,
176                         'drops': 0,
177                         'was_ds': 0,
178
179                         'defenses': 0,
180                         'interceptions': 0,
181                         'points_played': 0,
182                         'playing_time_ms': 0,
183                         'offensive_playing_time_ms': 0,
184                         'defensive_playing_time_ms': 0,
185                         'field_time_ms': 0,
186
187                         // For efficiency.
188                         'offensive_points_completed': 0,
189                         'offensive_points_won': 0,
190                         'defensive_points_completed': 0,
191                         'defensive_points_won': 0,
192
193                         'offensive_soft_plus': 0,
194                         'offensive_soft_minus': 0,
195                         'defensive_soft_plus': 0,
196                         'defensive_soft_minus': 0,
197
198                         'pulls': 0,
199                         'pull_times': [],
200                         'oob_pulls': 0,
201
202                         // Internal.
203                         'last_point_seen': null,
204                         'on_field_since': null,
205                 };
206         }
207
208         // Globals.
209         players['globals'] = {
210                 'points_played': 0,
211                 'playing_time_ms': 0,
212                 'offensive_playing_time_ms': 0,
213                 'defensive_playing_time_ms': 0,
214                 'field_time_ms': 0,
215
216                 'offensive_points_completed': 0,
217                 'offensive_points_won': 0,
218                 'defensive_points_completed': 0,
219                 'defensive_points_won': 0,
220         };
221         let globals = players['globals'];
222
223         for (const match of json['matches']) {
224                 if (!keep_match(match['match_id'], filters)) {
225                         continue;
226                 }
227
228                 let our_score = 0;
229                 let their_score = 0;
230                 let handler = null;
231                 let prev_handler = null;
232                 let live_since = null;
233                 let offense = null;  // True/false/null (unknown).
234                 let puller = null;
235                 let pull_started = null;
236                 let last_pull_was_ours = null;  // Effectively whether we're playing an O or D point (not affected by turnovers).
237                 let point_num = 0;
238                 let game_started = null;
239                 let last_goal = null;
240
241                 // The last used formations of the given kind, if any; they may be reused
242                 // when the point starts, if nothing else is set.
243                 let last_offensive_formation = null;
244                 let last_defensive_formation = null;
245
246                 // Formations we've set, but haven't really had the chance to use yet
247                 // (e.g., we get a “use zone defense” event while we're still on offense).
248                 let pending_offensive_formation = null;
249                 let pending_defensive_formation = null;
250
251                 // Formations that we have played at least once this point, after all
252                 // heuristics and similar.
253                 let formations_used_this_point = new Set();
254
255                 for (const [q,p] of Object.entries(players)) {
256                         p.on_field_since = null;
257                         p.last_point_seen = null;
258                 }
259                 for (const e of match['events']) {
260                         let t = e['t'];
261                         let type = e['type'];
262                         let p = players[e['player']];
263
264                         // Sub management
265                         let keep = keep_event(players, formations_used_this_point, filters);
266                         if (type === 'in' && p.on_field_since === null) {
267                                 p.on_field_since = t;
268                                 if (!keep && keep_event(players, formations_used_this_point, filters)) {
269                                         // A player needed for the filters went onto the field,
270                                         // so pretend people walked on right now (to start their
271                                         // counting time).
272                                         for (const [q,p2] of Object.entries(players)) {
273                                                 if (p2.on_field_since !== null) {
274                                                         p2.on_field_since = t;
275                                                 }
276                                         }
277                                 }
278                         } else if (type === 'out') {
279                                 take_off_field(p, t, live_since, offense, keep);
280                                 if (keep && !keep_event(players, formations_used_this_point, filters)) {
281                                         // A player needed for the filters went off the field,
282                                         // so we need to attribute time for all the others.
283                                         // Pretend they walked off and then immediately on again.
284                                         //
285                                         // TODO: We also need to take care of this to get the globals right.
286                                         for (const [q,p2] of Object.entries(players)) {
287                                                 if (p2.on_field_since !== null) {
288                                                         take_off_field(p2, t, live_since, offense, keep);
289                                                         p2.on_field_since = t;
290                                                 }
291                                         }
292                                 }
293                         }
294
295                         keep = keep_event(players, formations_used_this_point, filters);  // Recompute after in/out.
296
297                         // Liveness management
298                         if (type === 'pull' || type === 'their_pull' || type === 'restart') {
299                                 live_since = t;
300                         } else if (type === 'catch' && last_pull_was_ours === null) {
301                                 // Someone forgot to add the pull, so we'll need to wing it.
302                                 console.log('Missing pull on ' + our_score + '\u2013' + their_score + ' in ' + match['description'] + '; pretending to have one.');
303                                 live_since = t;
304                                 last_pull_was_ours = !offense;
305                         } else if (type === 'goal' || type === 'their_goal' || type === 'stoppage') {
306                                 for (const [q,p] of Object.entries(players)) {
307                                         if (p.on_field_since === null) {
308                                                 continue;
309                                         }
310                                         if (type !== 'stoppage' && p.last_point_seen !== point_num) {
311                                                 if (keep) {
312                                                         // In case the player did nothing this point,
313                                                         // not even subbing in.
314                                                         p.last_point_seen = point_num;
315                                                         ++p.points_played;
316                                                 }
317                                         }
318                                         if (keep) attribute_player_time(p, t, live_since, offense);
319
320                                         if (type !== 'stoppage') {
321                                                 if (keep) {
322                                                         if (last_pull_was_ours === true) {  // D point.
323                                                                 ++p.defensive_points_completed;
324                                                                 if (type === 'goal') {
325                                                                         ++p.defensive_points_won;
326                                                                 }
327                                                         } else if (last_pull_was_ours === false) {  // O point.
328                                                                 ++p.offensive_points_completed;
329                                                                 if (type === 'goal') {
330                                                                         ++p.offensive_points_won;
331                                                                 }
332                                                         }
333                                                 }
334                                         }
335                                 }
336
337                                 if (keep) {
338                                         if (type !== 'stoppage') {
339                                                 // Update globals.
340                                                 ++globals.points_played;
341                                                 if (last_pull_was_ours === true) {  // D point.
342                                                         ++globals.defensive_points_completed;
343                                                         if (type === 'goal') {
344                                                                 ++globals.defensive_points_won;
345                                                         }
346                                                 } else if (last_pull_was_ours === false) {  // O point.
347                                                         ++globals.offensive_points_completed;
348                                                         if (type === 'goal') {
349                                                                 ++globals.offensive_points_won;
350                                                         }
351                                                 }
352                                         }
353                                         if (live_since !== null) {
354                                                 globals.playing_time_ms += t - live_since;
355                                                 if (offense === true) {
356                                                         globals.offensive_playing_time_ms += t - live_since;
357                                                 } else if (offense === false) {
358                                                         globals.defensive_playing_time_ms += t - live_since;
359                                                 }
360                                         }
361                                 }
362
363                                 live_since = null;
364                         }
365
366                         // Score management
367                         if (type === 'goal') {
368                                 ++our_score;
369                         } else if (type === 'their_goal') {
370                                 ++their_score;
371                         }
372
373                         // Point count management
374                         if (p !== undefined && type !== 'out' && p.last_point_seen !== point_num) {
375                                 if (keep) {
376                                         p.last_point_seen = point_num;
377                                         ++p.points_played;
378                                 }
379                         }
380                         if (type === 'goal' || type === 'their_goal') {
381                                 ++point_num;
382                                 last_goal = t;
383                         }
384                         if (type !== 'out' && game_started === null) {
385                                 game_started = t;
386                         }
387
388                         // Pull management
389                         if (type === 'pull') {
390                                 puller = e['player'];
391                                 pull_started = t;
392                                 if (keep) ++p.pulls;
393                         } else if (type === 'in' || type === 'out' || type === 'stoppage' || type === 'restart' || type === 'unknown' || type === 'set_defense' || type === 'set_offense') {
394                                 // No effect on pull.
395                         } else if (type === 'pull_landed' && puller !== null) {
396                                 if (keep) players[puller].pull_times.push(t - pull_started);
397                         } else if (type === 'pull_oob' && puller !== null) {
398                                 if (keep) ++players[puller].oob_pulls;
399                         } else {
400                                 // Not pulling (if there was one, we never recorded its outcome, but still count it).
401                                 puller = pull_started = null;
402                         }
403
404                         // Offense/defense management
405                         let last_offense = offense;
406                         if (type === 'set_defense' || type === 'goal' || type === 'throwaway' || type === 'drop' || type === 'was_d') {
407                                 offense = false;
408                         } else if (type === 'set_offense' || type === 'their_goal' || type === 'their_throwaway' || type === 'defense' || type === 'interception') {
409                                 offense = true;
410                         }
411                         if (last_offense !== offense && live_since !== null) {
412                                 // Switched offense/defense status, so attribute this drive as needed,
413                                 // and update live_since to take that into account.
414                                 if (keep) {
415                                         for (const [q,p] of Object.entries(players)) {
416                                                 if (p.on_field_since === null) {
417                                                         continue;
418                                                 }
419                                                 attribute_player_time(p, t, live_since, last_offense);
420                                         }
421                                         globals.playing_time_ms += t - live_since;
422                                         if (offense === true) {
423                                                 globals.offensive_playing_time_ms += t - live_since;
424                                         } else if (offense === false) {
425                                                 globals.defensive_playing_time_ms += t - live_since;
426                                         }
427                                 }
428                                 live_since = t;
429                         }
430
431                         if (type === 'pull') {
432                                 last_pull_was_ours = true;
433                         } else if (type === 'their_pull') {
434                                 last_pull_was_ours = false;
435                         } else if (type === 'set_offense' && last_pull_was_ours === null) {
436                                 // set_offense could either be “changed to offense for some reason
437                                 // we could not express”, or “we started in the middle of a point,
438                                 // and we are offense”. We assume that if we already saw the pull,
439                                 // it's the former, and if not, it's the latter; thus, the === null
440                                 // test above. (It could also be “we set offense before the pull,
441                                 // so that we get the right button enabled”, in which case it will
442                                 // be overwritten by the next pull/their_pull event anyway.)
443                                 last_pull_was_ours = false;
444                         } else if (type === 'set_defense' && last_pull_was_ours === null) {
445                                 // Similar.
446                                 last_pull_was_ours = true;
447                         } else if (type === 'goal' || type === 'their_goal') {
448                                 last_pull_was_ours = null;
449                         }
450
451                         // Formation management
452                         if (type === 'formation_offense' || type === 'formation_defense') {
453                                 let id = e.formation === null ? 0 : e.formation;
454                                 let for_offense = (type === 'formation_offense');
455                                 if (offense === for_offense) {
456                                         formations_used_this_point.add(id);
457                                 } else if (for_offense) {
458                                         pending_offensive_formation = id;
459                                 } else {
460                                         pending_defensive_formation = id;
461                                 }
462                                 if (for_offense) {
463                                         last_offensive_formation = id;
464                                 } else {
465                                         last_defensive_formation = id;
466                                 }
467                         } else if (last_offense !== offense) {
468                                 if (offense === true && pending_offensive_formation !== null) {
469                                         formations_used_this_point.add(pending_offensive_formation);
470                                         pending_offensive_formation = null;
471                                 } else if (offense === false && pending_defensive_formation !== null) {
472                                         formations_used_this_point.add(pending_defensive_formation);
473                                         pending_defensive_formation = null;
474                                 } else if (offense === true && last_defensive_formation !== null) {
475                                         if (should_reuse_last_formation(match['events'], t)) {
476                                                 formations_used_this_point.add(last_defensive_formation);
477                                         }
478                                 } else if (offense === false && last_offensive_formation !== null) {
479                                         if (should_reuse_last_formation(match['events'], t)) {
480                                                 formations_used_this_point.add(last_offensive_formation);
481                                         }
482                                 }
483                         }
484
485                         // Event management
486                         if (type === 'catch' || type === 'goal') {
487                                 if (handler !== null) {
488                                         if (keep) {
489                                                 ++players[handler].num_throws;
490                                                 ++p.catches;
491                                         }
492                                 }
493
494                                 if (keep) ++p.touches;
495                                 if (type === 'goal') {
496                                         if (keep) {
497                                                 if (prev_handler !== null) {
498                                                         ++players[prev_handler].hockey_assists;
499                                                 }
500                                                 if (handler !== null) {
501                                                         ++players[handler].assists;
502                                                 }
503                                                 ++p.goals;
504                                         }
505                                         handler = prev_handler = null;
506                                 } else {
507                                         // Update hold history.
508                                         prev_handler = handler;
509                                         handler = e['player'];
510                                 }
511                         } else if (type === 'throwaway') {
512                                 if (keep) {
513                                         ++p.num_throws;
514                                         ++p.throwaways;
515                                 }
516                                 handler = prev_handler = null;
517                         } else if (type === 'drop') {
518                                 if (keep) ++p.drops;
519                                 handler = prev_handler = null;
520                         } else if (type === 'was_d') {
521                                 if (keep) ++p.was_ds;
522                                 handler = prev_handler = null;
523                         } else if (type === 'defense') {
524                                 if (keep) ++p.defenses;
525                         } else if (type === 'interception') {
526                                 if (keep) {
527                                         ++p.interceptions;
528                                         ++p.defenses;
529                                         ++p.touches;
530                                 }
531                                 prev_handler = null;
532                                 handler = e['player'];
533                         } else if (type === 'offensive_soft_plus' || type === 'offensive_soft_minus' || type === 'defensive_soft_plus' || type === 'defensive_soft_minus') {
534                                 if (keep) ++p[type];
535                         } else if (type !== 'in' && type !== 'out' && type !== 'pull' &&
536                                    type !== 'their_goal' && type !== 'stoppage' && type !== 'restart' && type !== 'unknown' &&
537                                    type !== 'set_defense' && type !== 'goal' && type !== 'throwaway' &&
538                                    type !== 'drop' && type !== 'was_d' && type !== 'set_offense' && type !== 'their_goal' &&
539                                    type !== 'pull' && type !== 'pull_landed' && type !== 'pull_oob' && type !== 'their_pull' &&
540                                    type !== 'their_throwaway' && type !== 'defense' && type !== 'interception' &&
541                                    type !== 'formation_offense' && type !== 'formation_defense') {
542                                 console.log("Unknown event:", e);
543                         }
544
545                         if (type === 'goal' || type === 'their_goal') {
546                                 formations_used_this_point.clear();
547                         }
548                 }
549
550                 // Add field time for all players still left at match end.
551                 const keep = keep_event(players, formations_used_this_point, filters);
552                 if (keep) {
553                         for (const [q,p] of Object.entries(players)) {
554                                 if (p.on_field_since !== null && last_goal !== null) {
555                                         p.field_time_ms += last_goal - p.on_field_since;
556                                 }
557                         }
558                         if (game_started !== null && last_goal !== null) {
559                                 globals.field_time_ms += last_goal - game_started;
560                         }
561                         if (live_since !== null && last_goal !== null) {
562                                 globals.playing_time_ms += last_goal - live_since;
563                                 if (offense === true) {
564                                         globals.offensive_playing_time_ms += last_goal - live_since;
565                                 } else if (offense === false) {
566                                         globals.defensive_playing_time_ms += last_goal - live_since;
567                                 }
568                         }
569                 }
570         }
571
572         let chosen_category = get_chosen_category();
573         write_main_menu(chosen_category);
574
575         let rows = [];
576         if (chosen_category === 'general') {
577                 rows = make_table_general(players);
578         } else if (chosen_category === 'offense') {
579                 rows = make_table_offense(players);
580         } else if (chosen_category === 'defense') {
581                 rows = make_table_defense(players);
582         } else if (chosen_category === 'playing_time') {
583                 rows = make_table_playing_time(players);
584         } else if (chosen_category === 'per_point') {
585                 rows = make_table_per_point(players);
586         }
587         document.getElementById('stats').replaceChildren(...rows);
588 }
589
590 function get_chosen_category() {
591         if (window.location.hash === '#offense') {
592                 return 'offense';
593         } else if (window.location.hash === '#defense') {
594                 return 'defense';
595         } else if (window.location.hash === '#playing_time') {
596                 return 'playing_time';
597         } else if (window.location.hash === '#per_point') {
598                 return 'per_point';
599         } else {
600                 return 'general';
601         }
602 }
603
604 function write_main_menu(chosen_category) {
605         let elems = [];
606         if (chosen_category === 'general') {
607                 let span = document.createElement('span');
608                 span.innerText = 'General';
609                 elems.push(span);
610         } else {
611                 let a = document.createElement('a');
612                 a.appendChild(document.createTextNode('General'));
613                 a.setAttribute('href', '#general');
614                 elems.push(a);
615         }
616
617         if (chosen_category === 'offense') {
618                 let span = document.createElement('span');
619                 span.innerText = 'Offense';
620                 elems.push(span);
621         } else {
622                 let a = document.createElement('a');
623                 a.appendChild(document.createTextNode('Offense'));
624                 a.setAttribute('href', '#offense');
625                 elems.push(a);
626         }
627
628         if (chosen_category === 'defense') {
629                 let span = document.createElement('span');
630                 span.innerText = 'Defense';
631                 elems.push(span);
632         } else {
633                 let a = document.createElement('a');
634                 a.appendChild(document.createTextNode('Defense'));
635                 a.setAttribute('href', '#defense');
636                 elems.push(a);
637         }
638
639         if (chosen_category === 'playing_time') {
640                 let span = document.createElement('span');
641                 span.innerText = 'Playing time';
642                 elems.push(span);
643         } else {
644                 let a = document.createElement('a');
645                 a.appendChild(document.createTextNode('Playing time'));
646                 a.setAttribute('href', '#playing_time');
647                 elems.push(a);
648         }
649
650         if (chosen_category === 'per_point') {
651                 let span = document.createElement('span');
652                 span.innerText = 'Per point';
653                 elems.push(span);
654         } else {
655                 let a = document.createElement('a');
656                 a.appendChild(document.createTextNode('Per point'));
657                 a.setAttribute('href', '#per_point');
658                 elems.push(a);
659         }
660
661         document.getElementById('mainmenu').replaceChildren(...elems);
662 }
663
664 // https://en.wikipedia.org/wiki/1.96#History
665 const z = 1.959964;
666
667 const ci_width = 100;
668 const ci_height = 20;
669
670 function make_binomial_ci(val, num, z) {
671         let avg = val / num;
672
673         // https://en.wikipedia.org/wiki/Binomial_proportion_confidence_interval#Wilson_score_interval
674         let low  = (avg + z*z/(2*num) - z * Math.sqrt(avg * (1.0 - avg) / num + z*z/(4*num*num))) / (1 + z*z/num);   
675         let high = (avg + z*z/(2*num) + z * Math.sqrt(avg * (1.0 - avg) / num + z*z/(4*num*num))) / (1 + z*z/num); 
676
677         // Fix the signs so that we don't get -0.00.
678         low = Math.max(low, 0.0);
679         return {
680                 'val': avg,
681                 'lower_ci': low,
682                 'upper_ci': high,
683                 'min': 0.0,
684                 'max': 1.0,
685         };
686 }
687
688 // These can only happen once per point, but you get -1 and +1
689 // instead of 0 and +1. After we rewrite to 0 and 1, it's a binomial,
690 // and then we can rewrite back.
691 function make_efficiency_ci(points_won, points_completed, z)
692 {
693         let ci = make_binomial_ci(points_won, points_completed, z);
694         ci.val = 2.0 * ci.val - 1.0;
695         ci.lower_ci = 2.0 * ci.lower_ci - 1.0;
696         ci.upper_ci = 2.0 * ci.upper_ci - 1.0;
697         ci.min = -1.0;
698         ci.max = 1.0;
699         ci.desired = 0.0;  // Desired = positive efficiency.
700         return ci;
701 }
702
703 // Ds, throwaways and drops can happen multiple times per point,
704 // so they are Poisson distributed.
705 //
706 // Modified Wald (recommended by http://www.ine.pt/revstat/pdf/rs120203.pdf
707 // since our rates are definitely below 2 per point).
708 function make_poisson_ci(val, num, z, inverted)
709 {
710         let low  = (val == 0) ? 0.0 : ((val - 0.5) - Math.sqrt(val - 0.5)) / num;
711         let high = (val == 0) ? -Math.log(0.025) / num : ((val + 0.5) + Math.sqrt(val + 0.5)) / num;
712
713         // Fix the signs so that we don't get -0.00.
714         low = Math.max(low, 0.0);
715
716         // The display range of 0 to 0.25 is fairly arbitrary. So is the desired 0.05 per point.
717         let avg = val / num;
718         return {
719                 'val': avg,
720                 'lower_ci': low,
721                 'upper_ci': high,
722                 'min': 0.0,
723                 'max': 0.25,
724                 'desired': 0.05,
725                 'inverted': inverted,
726         };
727 }
728
729 function make_table_general(players) {
730         let rows = [];
731         {
732                 let header = document.createElement('tr');
733                 add_th(header, 'Player');
734                 add_th(header, '+/-');
735                 add_th(header, 'Soft +/-');
736                 add_th(header, 'O efficiency');
737                 add_th(header, 'D efficiency');
738                 add_th(header, 'Points played');
739                 rows.push(header);
740         }
741
742         for (const [q,p] of get_sorted_players(players)) {
743                 if (q === 'globals') continue;
744                 let row = document.createElement('tr');
745                 let pm = p.goals + p.assists + p.hockey_assists + p.defenses - p.throwaways - p.drops - p.was_ds;
746                 let soft_pm = p.offensive_soft_plus + p.defensive_soft_plus - p.offensive_soft_minus - p.defensive_soft_minus;
747                 let o_efficiency = make_efficiency_ci(p.offensive_points_won, p.offensive_points_completed, z);
748                 let d_efficiency = make_efficiency_ci(p.defensive_points_won, p.defensive_points_completed, z);
749                 let name = add_3cell(row, p.name, 'name');  // TODO: number?
750                 add_3cell(row, pm > 0 ? ('+' + pm) : pm);
751                 add_3cell(row, soft_pm > 0 ? ('+' + soft_pm) : soft_pm);
752                 add_3cell_ci(row, o_efficiency);
753                 add_3cell_ci(row, d_efficiency);
754                 add_3cell(row, p.points_played);
755                 row.dataset.player = q;
756                 rows.push(row);
757         }
758
759         // Globals.
760         let globals = players['globals'];
761         let o_efficiency = make_efficiency_ci(globals.offensive_points_won, globals.offensive_points_completed, z);
762         let d_efficiency = make_efficiency_ci(globals.defensive_points_won, globals.defensive_points_completed, z);
763         let row = document.createElement('tr');
764         add_3cell(row, '');
765         add_3cell(row, '');
766         add_3cell(row, '');
767         add_3cell_ci(row, o_efficiency);
768         add_3cell_ci(row, d_efficiency);
769         add_3cell(row, globals.points_played);
770         rows.push(row);
771
772         return rows;
773 }
774
775 function make_table_offense(players) {
776         let rows = [];
777         {
778                 let header = document.createElement('tr');
779                 add_th(header, 'Player');
780                 add_th(header, 'Goals');
781                 add_th(header, 'Assists');
782                 add_th(header, 'Hockey assists');
783                 add_th(header, 'Throws');
784                 add_th(header, 'Throwaways');
785                 add_th(header, '%OK');
786                 add_th(header, 'Catches');
787                 add_th(header, 'Drops');
788                 add_th(header, 'D-ed');
789                 add_th(header, '%OK');
790                 add_th(header, 'Soft +/-', 6);
791                 rows.push(header);
792         }
793
794         let num_throws = 0;
795         let throwaways = 0;
796         let catches = 0;
797         let drops = 0;
798         let was_ds = 0;
799         for (const [q,p] of get_sorted_players(players)) {
800                 if (q === 'globals') continue;
801                 let throw_ok = make_binomial_ci(p.num_throws - p.throwaways, p.num_throws, z);
802                 let catch_ok = make_binomial_ci(p.catches, p.catches + p.drops + p.was_ds, z);
803
804                 throw_ok.format = 'percentage';
805                 catch_ok.format = 'percentage';
806
807                 // Desire at least 90% percentage. Fairly arbitrary.
808                 throw_ok.desired = 0.9;
809                 catch_ok.desired = 0.9;
810
811                 let row = document.createElement('tr');
812                 add_3cell(row, p.name, 'name');  // TODO: number?
813                 add_3cell(row, p.goals);
814                 add_3cell(row, p.assists);
815                 add_3cell(row, p.hockey_assists);
816                 add_3cell(row, p.num_throws);
817                 add_3cell(row, p.throwaways);
818                 add_3cell_ci(row, throw_ok);
819                 add_3cell(row, p.catches);
820                 add_3cell(row, p.drops);
821                 add_3cell(row, p.was_ds);
822                 add_3cell_ci(row, catch_ok);
823                 add_3cell(row, '+' + p.offensive_soft_plus);
824                 add_3cell(row, '-' + p.offensive_soft_minus);
825                 row.dataset.player = q;
826                 rows.push(row);
827
828                 num_throws += p.num_throws;
829                 throwaways += p.throwaways;
830                 catches += p.catches;
831                 drops += p.drops;
832                 was_ds += p.was_ds;
833         }
834
835         // Globals.
836         let throw_ok = make_binomial_ci(num_throws - throwaways, num_throws, z);
837         let catch_ok = make_binomial_ci(catches, catches + drops + was_ds, z);
838         throw_ok.format = 'percentage';
839         catch_ok.format = 'percentage';
840         throw_ok.desired = 0.9;
841         catch_ok.desired = 0.9;
842
843         let row = document.createElement('tr');
844         add_3cell(row, '');
845         add_3cell(row, '');
846         add_3cell(row, '');
847         add_3cell(row, '');
848         add_3cell(row, num_throws);
849         add_3cell(row, throwaways);
850         add_3cell_ci(row, throw_ok);
851         add_3cell(row, catches);
852         add_3cell(row, drops);
853         add_3cell(row, was_ds);
854         add_3cell_ci(row, catch_ok);
855         add_3cell(row, '');
856         add_3cell(row, '');
857         rows.push(row);
858
859         return rows;
860 }
861
862 function make_table_defense(players) {
863         let rows = [];
864         {
865                 let header = document.createElement('tr');
866                 add_th(header, 'Player');
867                 add_th(header, 'Ds');
868                 add_th(header, 'Pulls');
869                 add_th(header, 'OOB pulls');
870                 add_th(header, 'OOB%');
871                 add_th(header, 'Avg. hang time (IB)');
872                 add_th(header, 'Soft +/-', 6);
873                 rows.push(header);
874         }
875         for (const [q,p] of get_sorted_players(players)) {
876                 if (q === 'globals') continue;
877                 let sum_time = 0;
878                 for (const t of p.pull_times) {
879                         sum_time += t;
880                 }
881                 let avg_time = 1e-3 * sum_time / (p.pulls - p.oob_pulls);
882                 let oob_pct = 100 * p.oob_pulls / p.pulls;
883
884                 let ci_oob = make_binomial_ci(p.oob_pulls, p.pulls, z);
885                 ci_oob.format = 'percentage';
886                 ci_oob.desired = 0.2;  // Arbitrary.
887                 ci_oob.inverted = true;
888
889                 let row = document.createElement('tr');
890                 add_3cell(row, p.name, 'name');  // TODO: number?
891                 add_3cell(row, p.defenses);
892                 add_3cell(row, p.pulls);
893                 add_3cell(row, p.oob_pulls);
894                 add_3cell_ci(row, ci_oob);
895                 if (p.pulls > p.oob_pulls) {
896                         add_3cell(row, avg_time.toFixed(1) + ' sec');
897                 } else {
898                         add_3cell(row, 'N/A');
899                 }
900                 add_3cell(row, '+' + p.defensive_soft_plus);
901                 add_3cell(row, '-' + p.defensive_soft_minus);
902                 row.dataset.player = q;
903                 rows.push(row);
904         }
905         return rows;
906 }
907
908 function make_table_playing_time(players) {
909         let rows = [];
910         {
911                 let header = document.createElement('tr');
912                 add_th(header, 'Player');
913                 add_th(header, 'Points played');
914                 add_th(header, 'Time played');
915                 add_th(header, 'O time');
916                 add_th(header, 'D time');
917                 add_th(header, 'Time on field');
918                 add_th(header, 'O points');
919                 add_th(header, 'D points');
920                 rows.push(header);
921         }
922
923         for (const [q,p] of get_sorted_players(players)) {
924                 if (q === 'globals') continue;
925                 let row = document.createElement('tr');
926                 add_3cell(row, p.name, 'name');  // TODO: number?
927                 add_3cell(row, p.points_played);
928                 add_3cell(row, Math.floor(p.playing_time_ms / 60000) + ' min');
929                 add_3cell(row, Math.floor(p.offensive_playing_time_ms / 60000) + ' min');
930                 add_3cell(row, Math.floor(p.defensive_playing_time_ms / 60000) + ' min');
931                 add_3cell(row, Math.floor(p.field_time_ms / 60000) + ' min');
932                 add_3cell(row, p.offensive_points_completed);
933                 add_3cell(row, p.defensive_points_completed);
934                 row.dataset.player = q;
935                 rows.push(row);
936         }
937
938         // Globals.
939         let globals = players['globals'];
940         let row = document.createElement('tr');
941         add_3cell(row, '');
942         add_3cell(row, globals.points_played);
943         add_3cell(row, Math.floor(globals.playing_time_ms / 60000) + ' min');
944         add_3cell(row, Math.floor(globals.offensive_playing_time_ms / 60000) + ' min');
945         add_3cell(row, Math.floor(globals.defensive_playing_time_ms / 60000) + ' min');
946         add_3cell(row, Math.floor(globals.field_time_ms / 60000) + ' min');
947         add_3cell(row, globals.offensive_points_completed);
948         add_3cell(row, globals.defensive_points_completed);
949         rows.push(row);
950
951         return rows;
952 }
953
954 function make_table_per_point(players) {
955         let rows = [];
956         {
957                 let header = document.createElement('tr');
958                 add_th(header, 'Player');
959                 add_th(header, 'Goals');
960                 add_th(header, 'Assists');
961                 add_th(header, 'Hockey assists');
962                 add_th(header, 'Ds');
963                 add_th(header, 'Throwaways');
964                 add_th(header, 'Recv. errors');
965                 add_th(header, 'Touches');
966                 rows.push(header);
967         }
968
969         let goals = 0;
970         let assists = 0;
971         let hockey_assists = 0;
972         let defenses = 0;
973         let throwaways = 0;
974         let receiver_errors = 0;
975         let touches = 0;
976         for (const [q,p] of get_sorted_players(players)) {
977                 if (q === 'globals') continue;
978
979                 // Can only happen once per point, so these are binomials.
980                 let ci_goals = make_binomial_ci(p.goals, p.points_played, z);
981                 let ci_assists = make_binomial_ci(p.assists, p.points_played, z);
982                 let ci_hockey_assists = make_binomial_ci(p.hockey_assists, p.points_played, z);
983                 // Arbitrarily desire at least 10% (not everybody can score or assist).
984                 ci_goals.desired = 0.1;
985                 ci_assists.desired = 0.1;
986                 ci_hockey_assists.desired = 0.1;
987
988                 let row = document.createElement('tr');
989                 add_3cell(row, p.name, 'name');  // TODO: number?
990                 add_3cell_ci(row, ci_goals);
991                 add_3cell_ci(row, ci_assists);
992                 add_3cell_ci(row, ci_hockey_assists);
993                 add_3cell_ci(row, make_poisson_ci(p.defenses, p.points_played, z));
994                 add_3cell_ci(row, make_poisson_ci(p.throwaways, p.points_played, z, true));
995                 add_3cell_ci(row, make_poisson_ci(p.drops + p.was_ds, p.points_played, z, true));
996                 if (p.points_played > 0) {
997                         add_3cell(row, p.touches == 0 ? 0 : (p.touches / p.points_played).toFixed(2));
998                 } else {
999                         add_3cell(row, 'N/A');
1000                 }
1001                 row.dataset.player = q;
1002                 rows.push(row);
1003
1004                 goals += p.goals;
1005                 assists += p.assists;
1006                 hockey_assists += p.hockey_assists;
1007                 defenses += p.defenses;
1008                 throwaways += p.throwaways;
1009                 receiver_errors += p.drops + p.was_ds;
1010                 touches += p.touches;
1011         }
1012
1013         // Globals.
1014         let globals = players['globals'];
1015         let row = document.createElement('tr');
1016         add_3cell(row, '');
1017         if (globals.points_played > 0) {
1018                 add_3cell_with_filler_ci(row, goals == 0 ? 0 : (goals / globals.points_played).toFixed(2));
1019                 add_3cell_with_filler_ci(row, assists == 0 ? 0 : (assists / globals.points_played).toFixed(2));
1020                 add_3cell_with_filler_ci(row, hockey_assists == 0 ? 0 : (hockey_assists / globals.points_played).toFixed(2));
1021                 add_3cell_with_filler_ci(row, defenses == 0 ? 0 : (defenses / globals.points_played).toFixed(2));
1022                 add_3cell_with_filler_ci(row, throwaways == 0 ? 0 : (throwaways / globals.points_played).toFixed(2));
1023                 add_3cell_with_filler_ci(row, receiver_errors == 0 ? 0 : (receiver_errors / globals.points_played).toFixed(2));
1024                 add_3cell(row, touches == 0 ? 0 : (touches / globals.points_played).toFixed(2));
1025         } else {
1026                 add_3cell_with_filler_ci(row, 'N/A');
1027                 add_3cell_with_filler_ci(row, 'N/A');
1028                 add_3cell_with_filler_ci(row, 'N/A');
1029                 add_3cell_with_filler_ci(row, 'N/A');
1030                 add_3cell_with_filler_ci(row, 'N/A');
1031                 add_3cell_with_filler_ci(row, 'N/A');
1032                 add_3cell(row, 'N/A');
1033         }
1034         rows.push(row);
1035
1036         return rows;
1037 }
1038
1039 function open_filter_menu() {
1040         document.getElementById('filter-submenu').style.display = 'none';
1041
1042         let menu = document.getElementById('filter-add-menu');
1043         menu.style.display = 'block';
1044         menu.replaceChildren();
1045
1046         // Place the menu directly under the “click to add” label;
1047         // we don't anchor it since that label will move around
1048         // and the menu shouldn't.
1049         let rect = document.getElementById('filter-click-to-add').getBoundingClientRect();
1050         menu.style.left = rect.left + 'px';
1051         menu.style.top = (rect.bottom + 10) + 'px';
1052
1053         add_menu_item(menu, 0, 'match', 'Match (any)');
1054         add_menu_item(menu, 1, 'player_any', 'Player on field (any)');
1055         add_menu_item(menu, 2, 'player_all', 'Player on field (all)');
1056         add_menu_item(menu, 3, 'formation_offense', 'Offense played (any)');
1057         add_menu_item(menu, 4, 'formation_defense', 'Defense played (any)');
1058 }
1059
1060 function add_menu_item(menu, menu_idx, filter_type, title) {
1061         let item = document.createElement('div');
1062         item.classList.add('option');
1063         item.appendChild(document.createTextNode(title));
1064
1065         let arrow = document.createElement('div');
1066         arrow.classList.add('arrow');
1067         arrow.textContent = '▸';
1068         item.appendChild(arrow);
1069
1070         menu.appendChild(item);
1071
1072         item.addEventListener('click', (e) => { show_submenu(menu_idx, null, filter_type); });
1073 }
1074
1075 function show_submenu(menu_idx, pill, filter_type) {
1076         let submenu = document.getElementById('filter-submenu');
1077         let subitems = [];
1078         const filter = find_filter(filter_type);
1079
1080         let choices = [];
1081         if (filter_type === 'match') {
1082                 for (const match of global_json['matches']) {
1083                         choices.push({
1084                                 'title': match['description'],
1085                                 'id': match['match_id']
1086                         });
1087                 }
1088         } else if (filter_type === 'player_any' || filter_type === 'player_all') {
1089                 for (const player of global_json['players']) {
1090                         choices.push({
1091                                 'title': player['name'],
1092                                 'id': player['player_id']
1093                         });
1094                 }
1095         } else if (filter_type === 'formation_offense') {
1096                 choices.push({
1097                         'title': '(None/unknown)',
1098                         'id': 0,
1099                 });
1100                 for (const formation of global_json['formations']) {
1101                         if (formation['offense']) {
1102                                 choices.push({
1103                                         'title': formation['name'],
1104                                         'id': formation['formation_id']
1105                                 });
1106                         }
1107                 }
1108         } else if (filter_type === 'formation_defense') {
1109                 choices.push({
1110                         'title': '(None/unknown)',
1111                         'id': 0,
1112                 });
1113                 for (const formation of global_json['formations']) {
1114                         if (!formation['offense']) {
1115                                 choices.push({
1116                                         'title': formation['name'],
1117                                         'id': formation['formation_id']
1118                                 });
1119                         }
1120                 }
1121         }
1122
1123         for (const choice of choices) {
1124                 let label = document.createElement('label');
1125
1126                 let subitem = document.createElement('div');
1127                 subitem.classList.add('option');
1128
1129                 let check = document.createElement('input');
1130                 check.setAttribute('type', 'checkbox');
1131                 check.setAttribute('id', 'choice' + choice.id);
1132                 if (filter !== null && filter.elements.has(choice.id)) {
1133                         check.setAttribute('checked', 'checked');
1134                 }
1135                 check.addEventListener('change', (e) => { checkbox_changed(e, filter_type, choice.id); });
1136
1137                 subitem.appendChild(check);
1138                 subitem.appendChild(document.createTextNode(choice.title));
1139
1140                 label.appendChild(subitem);
1141                 subitems.push(label);
1142         }
1143         submenu.replaceChildren(...subitems);
1144         submenu.style.display = 'block';
1145
1146         if (pill !== null) {
1147                 let rect = pill.getBoundingClientRect();
1148                 submenu.style.top = (rect.bottom + 10) + 'px';
1149                 submenu.style.left = rect.left + 'px';
1150         } else {
1151                 // Position just outside the selected menu.
1152                 let rect = document.getElementById('filter-add-menu').getBoundingClientRect();
1153                 submenu.style.top = (rect.top + menu_idx * 35) + 'px';
1154                 submenu.style.left = (rect.right - 1) + 'px';
1155         }
1156 }
1157
1158 // Find the right filter, if it exists.
1159 function find_filter(filter_type) {
1160         for (let f of global_filters) {
1161                 if (f.type === filter_type) {
1162                         return f;
1163                 }
1164         }
1165         return null;
1166 }
1167
1168 function checkbox_changed(e, filter_type, id) {
1169         let filter = find_filter(filter_type);
1170         if (e.target.checked) {
1171                 // See if we must add a new filter to the list.
1172                 if (filter === null) {
1173                         filter = {
1174                                 'type': filter_type,
1175                                 'elements': new Set([ id ]),
1176                         };
1177                         filter.pill = make_filter_pill(filter);
1178                         global_filters.push(filter);
1179                         document.getElementById('filters').appendChild(filter.pill);
1180                 } else {
1181                         filter.elements.add(id);
1182                         let new_pill = make_filter_pill(filter);
1183                         document.getElementById('filters').replaceChild(new_pill, filter.pill);
1184                         filter.pill = new_pill;
1185                 }
1186         } else {
1187                 filter.elements.delete(id);
1188                 if (filter.elements.size === 0) {
1189                         document.getElementById('filters').removeChild(filter.pill);
1190                         global_filters = global_filters.filter(f => f !== filter);
1191                 } else {
1192                         let new_pill = make_filter_pill(filter);
1193                         document.getElementById('filters').replaceChild(new_pill, filter.pill);
1194                         filter.pill = new_pill;
1195                 }
1196         }
1197
1198         process_matches(global_json, global_filters);
1199 }
1200
1201 function make_filter_pill(filter) {
1202         let pill = document.createElement('div');
1203         pill.classList.add('filter-pill');
1204         let text;
1205         if (filter.type === 'match') {
1206                 text = 'Match: ';
1207
1208                 let all_names = [];
1209                 for (const match_id of filter.elements) {
1210                         all_names.push(find_match(match_id)['description']);
1211                 }
1212                 let common_prefix = find_common_prefix_of_all(all_names);
1213                 if (common_prefix !== null) {
1214                         text += common_prefix + '(';
1215                 }
1216
1217                 let first = true;
1218                 let sorted_match_id = Array.from(filter.elements).sort((a, b) => a - b);
1219                 for (const match_id of sorted_match_id) {
1220                         if (!first) {
1221                                 text += ', ';
1222                         }
1223                         let desc = find_match(match_id)['description'];
1224                         if (common_prefix === null) {
1225                                 text += desc;
1226                         } else {
1227                                 text += desc.substr(common_prefix.length);
1228                         }
1229                         first = false;
1230                 }
1231
1232                 if (common_prefix !== null) {
1233                         text += ')';
1234                 }
1235         } else if (filter.type === 'player_any') {
1236                 text = 'Player (any): ';
1237                 let sorted_players = Array.from(filter.elements).sort((a, b) => player_pos(a) - player_pos(b));
1238                 let first = true;
1239                 for (const player_id of sorted_players) {
1240                         if (!first) {
1241                                 text += ', ';
1242                         }
1243                         text += find_player(player_id)['name'];
1244                         first = false;
1245                 }
1246         } else if (filter.type === 'player_all') {
1247                 text = 'Players: ';
1248                 let sorted_players = Array.from(filter.elements).sort((a, b) => player_pos(a) - player_pos(b));
1249                 let first = true;
1250                 for (const player_id of sorted_players) {
1251                         if (!first) {
1252                                 text += ' AND ';
1253                         }
1254                         text += find_player(player_id)['name'];
1255                         first = false;
1256                 }
1257         } else if (filter.type === 'formation_offense' || filter.type === 'formation_defense') {
1258                 const offense = (filter.type === 'formation_offense');
1259                 if (offense) {
1260                         text = 'Offense: ';
1261                 } else {
1262                         text = 'Defense: ';
1263                 }
1264
1265                 let all_names = [];
1266                 for (const formation_id of filter.elements) {
1267                         all_names.push(find_formation(formation_id)['name']);
1268                 }
1269                 let common_prefix = find_common_prefix_of_all(all_names);
1270                 if (common_prefix !== null) {
1271                         text += common_prefix + '(';
1272                 }
1273
1274                 let first = true;
1275                 let sorted_formation_id = Array.from(filter.elements).sort((a, b) => a - b);
1276                 for (const formation_id of sorted_formation_id) {
1277                         if (!first) {
1278                                 text += ', ';
1279                         }
1280                         let desc = find_formation(formation_id)['name'];
1281                         if (common_prefix === null) {
1282                                 text += desc;
1283                         } else {
1284                                 text += desc.substr(common_prefix.length);
1285                         }
1286                         first = false;
1287                 }
1288
1289                 if (common_prefix !== null) {
1290                         text += ')';
1291                 }
1292         }
1293
1294         let text_node = document.createElement('span');
1295         text_node.innerText = text;
1296         text_node.addEventListener('click', (e) => show_submenu(null, pill, filter.type));
1297         pill.appendChild(text_node);
1298
1299         pill.appendChild(document.createTextNode(' '));
1300
1301         let delete_node = document.createElement('span');
1302         delete_node.innerText = '✖';
1303         delete_node.addEventListener('click', (e) => {
1304                 // Delete this filter entirely.
1305                 document.getElementById('filters').removeChild(pill);
1306                 global_filters = global_filters.filter(f => f !== filter);
1307                 process_matches(global_json, global_filters);
1308
1309                 let add_menu = document.getElementById('filter-add-menu');
1310                 let add_submenu = document.getElementById('filter-submenu');
1311                 add_menu.style.display = 'none';
1312                 add_submenu.style.display = 'none';
1313         });
1314         pill.appendChild(delete_node);
1315         pill.style.cursor = 'pointer';
1316
1317         return pill;
1318 }
1319
1320 function find_common_prefix(a, b) {
1321         let ret = '';
1322         for (let i = 0; i < Math.min(a.length, b.length); ++i) {
1323                 if (a[i] === b[i]) {
1324                         ret += a[i];
1325                 } else {
1326                         break;
1327                 }
1328         }
1329         return ret;
1330 }
1331
1332 function find_common_prefix_of_all(values) {
1333         if (values.length < 2) {
1334                 return null;
1335         }
1336         let common_prefix = null;
1337         for (const desc of values) {
1338                 if (common_prefix === null) {
1339                         common_prefix = desc;
1340                 } else {
1341                         common_prefix = find_common_prefix(common_prefix, desc);
1342                 }
1343         }
1344         if (common_prefix.length >= 3) {
1345                 return common_prefix;
1346         } else {
1347                 return null;
1348         }
1349 }
1350
1351 function find_match(match_id) {
1352         for (const match of global_json['matches']) {
1353                 if (match['match_id'] === match_id) {
1354                         return match;
1355                 }
1356         }
1357         return null;
1358 }
1359
1360 function find_formation(formation_id) {
1361         for (const formation of global_json['formations']) {
1362                 if (formation['formation_id'] === formation_id) {
1363                         return formation;
1364                 }
1365         }
1366         return null;
1367 }
1368
1369 function find_player(player_id) {
1370         for (const player of global_json['players']) {
1371                 if (player['player_id'] === player_id) {
1372                         return player;
1373                 }
1374         }
1375         return null;
1376 }
1377
1378 function player_pos(player_id) {
1379         let i = 0;
1380         for (const player of global_json['players']) {
1381                 if (player['player_id'] === player_id) {
1382                         return i;
1383                 }
1384                 ++i;
1385         }
1386         return null;
1387 }
1388
1389 function keep_match(match_id, filters) {
1390         for (const filter of filters) {
1391                 if (filter.type === 'match') {
1392                         return filter.elements.has(match_id);
1393                 }
1394         }
1395         return true;
1396 }
1397
1398 function filter_passes(players, formations_used_this_point, filter) {
1399         if (filter.type === 'player_any') {
1400                 for (const p of Array.from(filter.elements)) {
1401                         if (players[p].on_field_since !== null) {
1402                                 return true;
1403                         }
1404                 }
1405                 return false;
1406         } else if (filter.type === 'player_all') {
1407                 for (const p of Array.from(filter.elements)) {
1408                         if (players[p].on_field_since === null) {
1409                                 return false;
1410                         }
1411                 }
1412                 return true;
1413         } else if (filter.type === 'formation_offense' || filter.type === 'formation_defense') {
1414                 for (const f of Array.from(filter.elements)) {
1415                         if (formations_used_this_point.has(f)) {
1416                                 return true;
1417                         }
1418                 }
1419                 return false;
1420         }
1421         return true;
1422 }
1423
1424 function keep_event(players, formations_used_this_point, filters) {
1425         for (const filter of filters) {
1426                 if (!filter_passes(players, formations_used_this_point, filter)) {
1427                         return false;
1428                 }
1429         }
1430         return true;
1431 }
1432
1433 // Heuristic: If we go at least ten seconds without the possession changing
1434 // or the operator specifying some other formation, we probably play the
1435 // same formation as the last point.
1436 function should_reuse_last_formation(events, t) {
1437         for (const e of events) {
1438                 if (e.t <= t) {
1439                         continue;
1440                 }
1441                 if (e.t > t + 10000) {
1442                         break;
1443                 }
1444                 const type = e.type;
1445                 if (type === 'their_goal' || type === 'goal' ||
1446                     type === 'set_defense' || type === 'set_offense' ||
1447                     type === 'throwaway' || type === 'their_throwaway' ||
1448                     type === 'drop' || type === 'defense' || type === 'interception' ||
1449                     type === 'pull' || type === 'pull_landed' || type === 'pull_oob' || type === 'their_pull' ||
1450                     type === 'formation_offense' || type === 'formation_defense') {
1451                         return false;
1452                 }
1453         }
1454         return true;
1455 }
1456
1457 function possibly_close_menu(e) {
1458         if (e.target.closest('#filter-click-to-add') === null &&
1459             e.target.closest('#filter-add-menu') === null &&
1460             e.target.closest('#filter-submenu') === null &&
1461             e.target.closest('.filter-pill') === null) {
1462                 let add_menu = document.getElementById('filter-add-menu');
1463                 let add_submenu = document.getElementById('filter-submenu');
1464                 add_menu.style.display = 'none';
1465                 add_submenu.style.display = 'none';
1466         }
1467 }
1468
1469 let global_sort = {};
1470
1471 function sort_by(th) {
1472         let tr = th.parentElement;
1473         let child_idx = 0;
1474         for (let column_idx = 0; column_idx < tr.children.length; ++column_idx) {
1475                 let element = tr.children[column_idx];
1476                 if (element === th) {
1477                         ++child_idx;  // Pad.
1478                         break;
1479                 }
1480                 if (element.hasAttribute('colspan')) {
1481                         child_idx += parseInt(element.getAttribute('colspan'));
1482                 } else {
1483                         ++child_idx;
1484                 }
1485         }
1486
1487         global_sort = {};
1488         let table = tr.parentElement;
1489         for (let row_idx = 1; row_idx < table.children.length - 1; ++row_idx) {  // Skip header and globals.
1490                 let row = table.children[row_idx];
1491                 let player = parseInt(row.dataset.player);
1492                 let value = row.children[child_idx].textContent;
1493                 global_sort[player] = value;
1494         }
1495 }
1496
1497 function get_sorted_players(players)
1498 {
1499         let p = Object.entries(players);
1500         if (global_sort.length !== 0) {
1501                 p.sort((a,b) => {
1502                         let ai = parseFloat(global_sort[a[0]]);
1503                         let bi = parseFloat(global_sort[b[0]]);
1504                         if (ai == ai && bi == bi) {
1505                                 return bi - ai;  // Reverse numeric.
1506                         } else if (global_sort[a[0]] < global_sort[b[0]]) {
1507                                 return -1;
1508                         } else if (global_sort[a[0]] > global_sort[b[0]]) {
1509                                 return 1;
1510                         } else {
1511                                 return 0;
1512                         }
1513                 });
1514         }
1515         return p;
1516 }