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