]> git.sesse.net Git - pkanalytics/blob - ultimate.js
Store event types internally as an enum.
[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                                 console.log(match['description'] + ' ' + format_time(t) + ': Disc came from subbed-out player ' + players[handler].name + '; not counting a pass.');
503                                 handler = null;
504                         }
505
506                         // Event management
507                         if (type === 'catch' || type === 'goal') {
508                                 if (handler !== null) {
509                                         if (keep) {
510                                                 ++players[handler].num_throws;
511                                                 ++p.catches;
512                                         }
513                                 }
514
515                                 if (keep) ++p.touches;
516                                 if (type === 'goal') {
517                                         if (keep) {
518                                                 if (prev_handler !== null) {
519                                                         ++players[prev_handler].hockey_assists;
520                                                 }
521                                                 if (handler !== null) {
522                                                         ++players[handler].assists;
523                                                 }
524                                                 ++p.goals;
525                                         }
526                                         handler = prev_handler = null;
527                                 } else {
528                                         // Update hold history.
529                                         prev_handler = handler;
530                                         handler = e['player'];
531                                 }
532                         } else if (type === 'throwaway') {
533                                 if (keep) {
534                                         ++p.num_throws;
535                                         ++p.throwaways;
536                                 }
537                                 handler = prev_handler = null;
538                         } else if (type === 'drop') {
539                                 if (keep) ++p.drops;
540                                 handler = prev_handler = null;
541                         } else if (type === 'stallout') {
542                                 if (keep) ++p.stallouts;
543                                 handler = prev_handler = null;
544                         } else if (type === 'was_d') {
545                                 if (keep) ++p.was_ds;
546                                 handler = prev_handler = null;
547                         } else if (type === 'defense') {
548                                 if (keep) ++p.defenses;
549                         } else if (type === 'interception') {
550                                 if (keep) {
551                                         ++p.catches;
552                                         ++p.defenses;
553                                         ++p.touches;
554                                 }
555                                 prev_handler = null;
556                                 handler = e['player'];
557                         } else if (type === 'offensive_soft_plus' || type === 'offensive_soft_minus' || type === 'defensive_soft_plus' || type === 'defensive_soft_minus') {
558                                 if (keep) ++p[type];
559                         } else if (type !== 'in' && type !== 'out' && type !== 'pull' &&
560                                    type !== 'their_goal' && type !== 'stoppage' && type !== 'restart' && type !== 'unknown' &&
561                                    type !== 'set_defense' && type !== 'goal' && type !== 'throwaway' &&
562                                    type !== 'drop' && type !== 'was_d' && type !== 'stallout' && type !== 'set_offense' && type !== 'their_goal' &&
563                                    type !== 'pull' && type !== 'pull_landed' && type !== 'pull_oob' && type !== 'their_pull' &&
564                                    type !== 'their_throwaway' && type !== 'defense' && type !== 'interception' &&
565                                    type !== 'formation_offense' && type !== 'formation_defense') {
566                                 console.log(format_time(t) + ": Unknown event “" + e + "”");
567                         }
568
569                         if (type === 'goal' || type === 'their_goal') {
570                                 formations_used_this_point.clear();
571                         }
572                 }
573
574                 // Add field time for all players still left at match end.
575                 const keep = keep_event(players, formations_used_this_point, filters);
576                 if (keep) {
577                         for (const [q,p] of Object.entries(players)) {
578                                 if (p.on_field_since !== null && last_goal !== null) {
579                                         p.field_time_ms += last_goal - p.on_field_since;
580                                 }
581                         }
582                         if (game_started !== null && last_goal !== null) {
583                                 globals.field_time_ms += last_goal - game_started;
584                         }
585                         if (live_since !== null && last_goal !== null) {
586                                 globals.playing_time_ms += last_goal - live_since;
587                                 if (offense === true) {
588                                         globals.offensive_playing_time_ms += last_goal - live_since;
589                                 } else if (offense === false) {
590                                         globals.defensive_playing_time_ms += last_goal - live_since;
591                                 }
592                         }
593                 }
594         }
595
596         let chosen_category = get_chosen_category();
597         write_main_menu(chosen_category);
598
599         let rows = [];
600         if (chosen_category === 'general') {
601                 rows = make_table_general(players);
602         } else if (chosen_category === 'offense') {
603                 rows = make_table_offense(players);
604         } else if (chosen_category === 'defense') {
605                 rows = make_table_defense(players);
606         } else if (chosen_category === 'playing_time') {
607                 rows = make_table_playing_time(players);
608         } else if (chosen_category === 'per_point') {
609                 rows = make_table_per_point(players);
610         }
611         document.getElementById('stats').replaceChildren(...rows);
612 }
613
614 function get_chosen_category() {
615         if (window.location.hash === '#offense') {
616                 return 'offense';
617         } else if (window.location.hash === '#defense') {
618                 return 'defense';
619         } else if (window.location.hash === '#playing_time') {
620                 return 'playing_time';
621         } else if (window.location.hash === '#per_point') {
622                 return 'per_point';
623         } else {
624                 return 'general';
625         }
626 }
627
628 function write_main_menu(chosen_category) {
629         let elems = [];
630         if (chosen_category === 'general') {
631                 let span = document.createElement('span');
632                 span.innerText = 'General';
633                 elems.push(span);
634         } else {
635                 let a = document.createElement('a');
636                 a.appendChild(document.createTextNode('General'));
637                 a.setAttribute('href', '#general');
638                 elems.push(a);
639         }
640
641         if (chosen_category === 'offense') {
642                 let span = document.createElement('span');
643                 span.innerText = 'Offense';
644                 elems.push(span);
645         } else {
646                 let a = document.createElement('a');
647                 a.appendChild(document.createTextNode('Offense'));
648                 a.setAttribute('href', '#offense');
649                 elems.push(a);
650         }
651
652         if (chosen_category === 'defense') {
653                 let span = document.createElement('span');
654                 span.innerText = 'Defense';
655                 elems.push(span);
656         } else {
657                 let a = document.createElement('a');
658                 a.appendChild(document.createTextNode('Defense'));
659                 a.setAttribute('href', '#defense');
660                 elems.push(a);
661         }
662
663         if (chosen_category === 'playing_time') {
664                 let span = document.createElement('span');
665                 span.innerText = 'Playing time';
666                 elems.push(span);
667         } else {
668                 let a = document.createElement('a');
669                 a.appendChild(document.createTextNode('Playing time'));
670                 a.setAttribute('href', '#playing_time');
671                 elems.push(a);
672         }
673
674         if (chosen_category === 'per_point') {
675                 let span = document.createElement('span');
676                 span.innerText = 'Per point';
677                 elems.push(span);
678         } else {
679                 let a = document.createElement('a');
680                 a.appendChild(document.createTextNode('Per point'));
681                 a.setAttribute('href', '#per_point');
682                 elems.push(a);
683         }
684
685         document.getElementById('mainmenu').replaceChildren(...elems);
686 }
687
688 // https://en.wikipedia.org/wiki/1.96#History
689 const z = 1.959964;
690
691 const ci_width = 100;
692 const ci_height = 20;
693
694 function make_binomial_ci(val, num, z) {
695         let avg = val / num;
696
697         // https://en.wikipedia.org/wiki/Binomial_proportion_confidence_interval#Wilson_score_interval
698         let low  = (avg + z*z/(2*num) - z * Math.sqrt(avg * (1.0 - avg) / num + z*z/(4*num*num))) / (1 + z*z/num);   
699         let high = (avg + z*z/(2*num) + z * Math.sqrt(avg * (1.0 - avg) / num + z*z/(4*num*num))) / (1 + z*z/num); 
700
701         // Fix the signs so that we don't get -0.00.
702         low = Math.max(low, 0.0);
703         return {
704                 'val': avg,
705                 'lower_ci': low,
706                 'upper_ci': high,
707                 'min': 0.0,
708                 'max': 1.0,
709         };
710 }
711
712 // These can only happen once per point, but you get -1 and +1
713 // instead of 0 and +1. After we rewrite to 0 and 1, it's a binomial,
714 // and then we can rewrite back.
715 function make_efficiency_ci(points_won, points_completed, z)
716 {
717         let ci = make_binomial_ci(points_won, points_completed, z);
718         ci.val = 2.0 * ci.val - 1.0;
719         ci.lower_ci = 2.0 * ci.lower_ci - 1.0;
720         ci.upper_ci = 2.0 * ci.upper_ci - 1.0;
721         ci.min = -1.0;
722         ci.max = 1.0;
723         ci.desired = 0.0;  // Desired = positive efficiency.
724         return ci;
725 }
726
727 // Ds, throwaways and drops can happen multiple times per point,
728 // so they are Poisson distributed.
729 //
730 // Modified Wald (recommended by http://www.ine.pt/revstat/pdf/rs120203.pdf
731 // since our rates are definitely below 2 per point).
732 function make_poisson_ci(val, num, z, inverted)
733 {
734         let low  = (val == 0) ? 0.0 : ((val - 0.5) - Math.sqrt(val - 0.5)) / num;
735         let high = (val == 0) ? -Math.log(0.025) / num : ((val + 0.5) + Math.sqrt(val + 0.5)) / num;
736
737         // Fix the signs so that we don't get -0.00.
738         low = Math.max(low, 0.0);
739
740         // The display range of 0 to 0.25 is fairly arbitrary. So is the desired 0.05 per point.
741         let avg = val / num;
742         return {
743                 'val': avg,
744                 'lower_ci': low,
745                 'upper_ci': high,
746                 'min': 0.0,
747                 'max': 0.25,
748                 'desired': 0.05,
749                 'inverted': inverted,
750         };
751 }
752
753 function make_table_general(players) {
754         let rows = [];
755         {
756                 let header = document.createElement('tr');
757                 add_th(header, 'Player');
758                 add_th(header, '+/-');
759                 add_th(header, 'Soft +/-');
760                 add_th(header, 'O efficiency');
761                 add_th(header, 'D efficiency');
762                 add_th(header, 'Points played');
763                 rows.push(header);
764         }
765
766         for (const [q,p] of get_sorted_players(players)) {
767                 if (q === 'globals') continue;
768                 let row = document.createElement('tr');
769                 let pm = p.goals + p.assists + p.hockey_assists + p.defenses - p.throwaways - p.drops - p.was_ds - p.stallouts;
770                 let soft_pm = p.offensive_soft_plus + p.defensive_soft_plus - p.offensive_soft_minus - p.defensive_soft_minus;
771                 let o_efficiency = make_efficiency_ci(p.offensive_points_won, p.offensive_points_completed, z);
772                 let d_efficiency = make_efficiency_ci(p.defensive_points_won, p.defensive_points_completed, z);
773                 let name = add_3cell(row, p.name, 'name');  // TODO: number?
774                 add_3cell(row, pm > 0 ? ('+' + pm) : pm);
775                 add_3cell(row, soft_pm > 0 ? ('+' + soft_pm) : soft_pm);
776                 add_3cell_ci(row, o_efficiency);
777                 add_3cell_ci(row, d_efficiency);
778                 add_3cell(row, p.points_played);
779                 row.dataset.player = q;
780                 rows.push(row);
781         }
782
783         // Globals.
784         let globals = players['globals'];
785         let o_efficiency = make_efficiency_ci(globals.offensive_points_won, globals.offensive_points_completed, z);
786         let d_efficiency = make_efficiency_ci(globals.defensive_points_won, globals.defensive_points_completed, z);
787         let row = document.createElement('tr');
788         add_3cell(row, '');
789         add_3cell(row, '');
790         add_3cell(row, '');
791         add_3cell_ci(row, o_efficiency);
792         add_3cell_ci(row, d_efficiency);
793         add_3cell(row, globals.points_played);
794         rows.push(row);
795
796         return rows;
797 }
798
799 function make_table_offense(players) {
800         let rows = [];
801         {
802                 let header = document.createElement('tr');
803                 add_th(header, 'Player');
804                 add_th(header, 'Goals');
805                 add_th(header, 'Assists');
806                 add_th(header, 'Hockey assists');
807                 add_th(header, 'Throws');
808                 add_th(header, 'Throwaways');
809                 add_th(header, '%OK');
810                 add_th(header, 'Catches');
811                 add_th(header, 'Drops');
812                 add_th(header, 'D-ed');
813                 add_th(header, '%OK');
814                 add_th(header, 'Stalls');
815                 add_th(header, 'Soft +/-', 6);
816                 rows.push(header);
817         }
818
819         let num_throws = 0;
820         let throwaways = 0;
821         let catches = 0;
822         let drops = 0;
823         let was_ds = 0;
824         let stallouts = 0;
825         for (const [q,p] of get_sorted_players(players)) {
826                 if (q === 'globals') continue;
827                 let throw_ok = make_binomial_ci(p.num_throws - p.throwaways, p.num_throws, z);
828                 let catch_ok = make_binomial_ci(p.catches, p.catches + p.drops + p.was_ds, z);
829
830                 throw_ok.format = 'percentage';
831                 catch_ok.format = 'percentage';
832
833                 // Desire at least 90% percentage. Fairly arbitrary.
834                 throw_ok.desired = 0.9;
835                 catch_ok.desired = 0.9;
836
837                 let row = document.createElement('tr');
838                 add_3cell(row, p.name, 'name');  // TODO: number?
839                 add_3cell(row, p.goals);
840                 add_3cell(row, p.assists);
841                 add_3cell(row, p.hockey_assists);
842                 add_3cell(row, p.num_throws);
843                 add_3cell(row, p.throwaways);
844                 add_3cell_ci(row, throw_ok);
845                 add_3cell(row, p.catches);
846                 add_3cell(row, p.drops);
847                 add_3cell(row, p.was_ds);
848                 add_3cell_ci(row, catch_ok);
849                 add_3cell(row, p.stallouts);
850                 add_3cell(row, '+' + p.offensive_soft_plus);
851                 add_3cell(row, '-' + p.offensive_soft_minus);
852                 row.dataset.player = q;
853                 rows.push(row);
854
855                 num_throws += p.num_throws;
856                 throwaways += p.throwaways;
857                 catches += p.catches;
858                 drops += p.drops;
859                 was_ds += p.was_ds;
860                 stallouts += p.stallouts;
861         }
862
863         // Globals.
864         let throw_ok = make_binomial_ci(num_throws - throwaways, num_throws, z);
865         let catch_ok = make_binomial_ci(catches, catches + drops + was_ds, z);
866         throw_ok.format = 'percentage';
867         catch_ok.format = 'percentage';
868         throw_ok.desired = 0.9;
869         catch_ok.desired = 0.9;
870
871         let row = document.createElement('tr');
872         add_3cell(row, '');
873         add_3cell(row, '');
874         add_3cell(row, '');
875         add_3cell(row, '');
876         add_3cell(row, num_throws);
877         add_3cell(row, throwaways);
878         add_3cell_ci(row, throw_ok);
879         add_3cell(row, catches);
880         add_3cell(row, drops);
881         add_3cell(row, was_ds);
882         add_3cell_ci(row, catch_ok);
883         add_3cell(row, stallouts);
884         add_3cell(row, '');
885         add_3cell(row, '');
886         rows.push(row);
887
888         return rows;
889 }
890
891 function make_table_defense(players) {
892         let rows = [];
893         {
894                 let header = document.createElement('tr');
895                 add_th(header, 'Player');
896                 add_th(header, 'Ds');
897                 add_th(header, 'Pulls');
898                 add_th(header, 'OOB pulls');
899                 add_th(header, 'OOB%');
900                 add_th(header, 'Avg. hang time (IB)');
901                 add_th(header, 'Soft +/-', 6);
902                 rows.push(header);
903         }
904         for (const [q,p] of get_sorted_players(players)) {
905                 if (q === 'globals') continue;
906                 let sum_time = 0;
907                 for (const t of p.pull_times) {
908                         sum_time += t;
909                 }
910                 let avg_time = 1e-3 * sum_time / (p.pulls - p.oob_pulls);
911                 let oob_pct = 100 * p.oob_pulls / p.pulls;
912
913                 let ci_oob = make_binomial_ci(p.oob_pulls, p.pulls, z);
914                 ci_oob.format = 'percentage';
915                 ci_oob.desired = 0.2;  // Arbitrary.
916                 ci_oob.inverted = true;
917
918                 let row = document.createElement('tr');
919                 add_3cell(row, p.name, 'name');  // TODO: number?
920                 add_3cell(row, p.defenses);
921                 add_3cell(row, p.pulls);
922                 add_3cell(row, p.oob_pulls);
923                 add_3cell_ci(row, ci_oob);
924                 if (p.pulls > p.oob_pulls) {
925                         add_3cell(row, avg_time.toFixed(1) + ' sec');
926                 } else {
927                         add_3cell(row, 'N/A');
928                 }
929                 add_3cell(row, '+' + p.defensive_soft_plus);
930                 add_3cell(row, '-' + p.defensive_soft_minus);
931                 row.dataset.player = q;
932                 rows.push(row);
933         }
934         return rows;
935 }
936
937 function make_table_playing_time(players) {
938         let rows = [];
939         {
940                 let header = document.createElement('tr');
941                 add_th(header, 'Player');
942                 add_th(header, 'Points played');
943                 add_th(header, 'Time played');
944                 add_th(header, 'O time');
945                 add_th(header, 'D time');
946                 add_th(header, 'Time on field');
947                 add_th(header, 'O points');
948                 add_th(header, 'D points');
949                 rows.push(header);
950         }
951
952         for (const [q,p] of get_sorted_players(players)) {
953                 if (q === 'globals') continue;
954                 let row = document.createElement('tr');
955                 add_3cell(row, p.name, 'name');  // TODO: number?
956                 add_3cell(row, p.points_played);
957                 add_3cell(row, Math.floor(p.playing_time_ms / 60000) + ' min');
958                 add_3cell(row, Math.floor(p.offensive_playing_time_ms / 60000) + ' min');
959                 add_3cell(row, Math.floor(p.defensive_playing_time_ms / 60000) + ' min');
960                 add_3cell(row, Math.floor(p.field_time_ms / 60000) + ' min');
961                 add_3cell(row, p.offensive_points_completed);
962                 add_3cell(row, p.defensive_points_completed);
963                 row.dataset.player = q;
964                 rows.push(row);
965         }
966
967         // Globals.
968         let globals = players['globals'];
969         let row = document.createElement('tr');
970         add_3cell(row, '');
971         add_3cell(row, globals.points_played);
972         add_3cell(row, Math.floor(globals.playing_time_ms / 60000) + ' min');
973         add_3cell(row, Math.floor(globals.offensive_playing_time_ms / 60000) + ' min');
974         add_3cell(row, Math.floor(globals.defensive_playing_time_ms / 60000) + ' min');
975         add_3cell(row, Math.floor(globals.field_time_ms / 60000) + ' min');
976         add_3cell(row, globals.offensive_points_completed);
977         add_3cell(row, globals.defensive_points_completed);
978         rows.push(row);
979
980         return rows;
981 }
982
983 function make_table_per_point(players) {
984         let rows = [];
985         {
986                 let header = document.createElement('tr');
987                 add_th(header, 'Player');
988                 add_th(header, 'Goals');
989                 add_th(header, 'Assists');
990                 add_th(header, 'Hockey assists');
991                 add_th(header, 'Ds');
992                 add_th(header, 'Throwaways');
993                 add_th(header, 'Recv. errors');
994                 add_th(header, 'Touches');
995                 rows.push(header);
996         }
997
998         let goals = 0;
999         let assists = 0;
1000         let hockey_assists = 0;
1001         let defenses = 0;
1002         let throwaways = 0;
1003         let receiver_errors = 0;
1004         let touches = 0;
1005         for (const [q,p] of get_sorted_players(players)) {
1006                 if (q === 'globals') continue;
1007
1008                 // Can only happen once per point, so these are binomials.
1009                 let ci_goals = make_binomial_ci(p.goals, p.points_played, z);
1010                 let ci_assists = make_binomial_ci(p.assists, p.points_played, z);
1011                 let ci_hockey_assists = make_binomial_ci(p.hockey_assists, p.points_played, z);
1012                 // Arbitrarily desire at least 10% (not everybody can score or assist).
1013                 ci_goals.desired = 0.1;
1014                 ci_assists.desired = 0.1;
1015                 ci_hockey_assists.desired = 0.1;
1016
1017                 let row = document.createElement('tr');
1018                 add_3cell(row, p.name, 'name');  // TODO: number?
1019                 add_3cell_ci(row, ci_goals);
1020                 add_3cell_ci(row, ci_assists);
1021                 add_3cell_ci(row, ci_hockey_assists);
1022                 add_3cell_ci(row, make_poisson_ci(p.defenses, p.points_played, z));
1023                 add_3cell_ci(row, make_poisson_ci(p.throwaways, p.points_played, z, true));
1024                 add_3cell_ci(row, make_poisson_ci(p.drops + p.was_ds, p.points_played, z, true));
1025                 if (p.points_played > 0) {
1026                         add_3cell(row, p.touches == 0 ? 0 : (p.touches / p.points_played).toFixed(2));
1027                 } else {
1028                         add_3cell(row, 'N/A');
1029                 }
1030                 row.dataset.player = q;
1031                 rows.push(row);
1032
1033                 goals += p.goals;
1034                 assists += p.assists;
1035                 hockey_assists += p.hockey_assists;
1036                 defenses += p.defenses;
1037                 throwaways += p.throwaways;
1038                 receiver_errors += p.drops + p.was_ds;
1039                 touches += p.touches;
1040         }
1041
1042         // Globals.
1043         let globals = players['globals'];
1044         let row = document.createElement('tr');
1045         add_3cell(row, '');
1046         if (globals.points_played > 0) {
1047                 add_3cell_with_filler_ci(row, goals == 0 ? 0 : (goals / globals.points_played).toFixed(2));
1048                 add_3cell_with_filler_ci(row, assists == 0 ? 0 : (assists / globals.points_played).toFixed(2));
1049                 add_3cell_with_filler_ci(row, hockey_assists == 0 ? 0 : (hockey_assists / globals.points_played).toFixed(2));
1050                 add_3cell_with_filler_ci(row, defenses == 0 ? 0 : (defenses / globals.points_played).toFixed(2));
1051                 add_3cell_with_filler_ci(row, throwaways == 0 ? 0 : (throwaways / globals.points_played).toFixed(2));
1052                 add_3cell_with_filler_ci(row, receiver_errors == 0 ? 0 : (receiver_errors / globals.points_played).toFixed(2));
1053                 add_3cell(row, touches == 0 ? 0 : (touches / globals.points_played).toFixed(2));
1054         } else {
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_with_filler_ci(row, 'N/A');
1061                 add_3cell(row, 'N/A');
1062         }
1063         rows.push(row);
1064
1065         return rows;
1066 }
1067
1068 function open_filter_menu() {
1069         document.getElementById('filter-submenu').style.display = 'none';
1070
1071         let menu = document.getElementById('filter-add-menu');
1072         menu.style.display = 'block';
1073         menu.replaceChildren();
1074
1075         // Place the menu directly under the “click to add” label;
1076         // we don't anchor it since that label will move around
1077         // and the menu shouldn't.
1078         let rect = document.getElementById('filter-click-to-add').getBoundingClientRect();
1079         menu.style.left = rect.left + 'px';
1080         menu.style.top = (rect.bottom + 10) + 'px';
1081
1082         add_menu_item(menu, 0, 'match', 'Match (any)');
1083         add_menu_item(menu, 1, 'player_any', 'Player on field (any)');
1084         add_menu_item(menu, 2, 'player_all', 'Player on field (all)');
1085         add_menu_item(menu, 3, 'formation_offense', 'Offense played (any)');
1086         add_menu_item(menu, 4, 'formation_defense', 'Defense played (any)');
1087 }
1088
1089 function add_menu_item(menu, menu_idx, filter_type, title) {
1090         let item = document.createElement('div');
1091         item.classList.add('option');
1092         item.appendChild(document.createTextNode(title));
1093
1094         let arrow = document.createElement('div');
1095         arrow.classList.add('arrow');
1096         arrow.textContent = '▸';
1097         item.appendChild(arrow);
1098
1099         menu.appendChild(item);
1100
1101         item.addEventListener('click', (e) => { show_submenu(menu_idx, null, filter_type); });
1102 }
1103
1104 function show_submenu(menu_idx, pill, filter_type) {
1105         let submenu = document.getElementById('filter-submenu');
1106         let subitems = [];
1107         const filter = find_filter(filter_type);
1108
1109         let choices = [];
1110         if (filter_type === 'match') {
1111                 for (const match of global_json['matches']) {
1112                         choices.push({
1113                                 'title': match['description'],
1114                                 'id': match['match_id']
1115                         });
1116                 }
1117         } else if (filter_type === 'player_any' || filter_type === 'player_all') {
1118                 for (const player of global_json['players']) {
1119                         choices.push({
1120                                 'title': player['name'],
1121                                 'id': player['player_id']
1122                         });
1123                 }
1124         } else if (filter_type === 'formation_offense') {
1125                 choices.push({
1126                         'title': '(None/unknown)',
1127                         'id': 0,
1128                 });
1129                 for (const formation of global_json['formations']) {
1130                         if (formation['offense']) {
1131                                 choices.push({
1132                                         'title': formation['name'],
1133                                         'id': formation['formation_id']
1134                                 });
1135                         }
1136                 }
1137         } else if (filter_type === 'formation_defense') {
1138                 choices.push({
1139                         'title': '(None/unknown)',
1140                         'id': 0,
1141                 });
1142                 for (const formation of global_json['formations']) {
1143                         if (!formation['offense']) {
1144                                 choices.push({
1145                                         'title': formation['name'],
1146                                         'id': formation['formation_id']
1147                                 });
1148                         }
1149                 }
1150         }
1151
1152         for (const choice of choices) {
1153                 let label = document.createElement('label');
1154
1155                 let subitem = document.createElement('div');
1156                 subitem.classList.add('option');
1157
1158                 let check = document.createElement('input');
1159                 check.setAttribute('type', 'checkbox');
1160                 check.setAttribute('id', 'choice' + choice.id);
1161                 if (filter !== null && filter.elements.has(choice.id)) {
1162                         check.setAttribute('checked', 'checked');
1163                 }
1164                 check.addEventListener('change', (e) => { checkbox_changed(e, filter_type, choice.id); });
1165
1166                 subitem.appendChild(check);
1167                 subitem.appendChild(document.createTextNode(choice.title));
1168
1169                 label.appendChild(subitem);
1170                 subitems.push(label);
1171         }
1172         submenu.replaceChildren(...subitems);
1173         submenu.style.display = 'block';
1174
1175         if (pill !== null) {
1176                 let rect = pill.getBoundingClientRect();
1177                 submenu.style.top = (rect.bottom + 10) + 'px';
1178                 submenu.style.left = rect.left + 'px';
1179         } else {
1180                 // Position just outside the selected menu.
1181                 let rect = document.getElementById('filter-add-menu').getBoundingClientRect();
1182                 submenu.style.top = (rect.top + menu_idx * 35) + 'px';
1183                 submenu.style.left = (rect.right - 1) + 'px';
1184         }
1185 }
1186
1187 // Find the right filter, if it exists.
1188 function find_filter(filter_type) {
1189         for (let f of global_filters) {
1190                 if (f.type === filter_type) {
1191                         return f;
1192                 }
1193         }
1194         return null;
1195 }
1196
1197 function checkbox_changed(e, filter_type, id) {
1198         let filter = find_filter(filter_type);
1199         if (e.target.checked) {
1200                 // See if we must add a new filter to the list.
1201                 if (filter === null) {
1202                         filter = {
1203                                 'type': filter_type,
1204                                 'elements': new Set([ id ]),
1205                         };
1206                         filter.pill = make_filter_pill(filter);
1207                         global_filters.push(filter);
1208                         document.getElementById('filters').appendChild(filter.pill);
1209                 } else {
1210                         filter.elements.add(id);
1211                         let new_pill = make_filter_pill(filter);
1212                         document.getElementById('filters').replaceChild(new_pill, filter.pill);
1213                         filter.pill = new_pill;
1214                 }
1215         } else {
1216                 filter.elements.delete(id);
1217                 if (filter.elements.size === 0) {
1218                         document.getElementById('filters').removeChild(filter.pill);
1219                         global_filters = global_filters.filter(f => f !== filter);
1220                 } else {
1221                         let new_pill = make_filter_pill(filter);
1222                         document.getElementById('filters').replaceChild(new_pill, filter.pill);
1223                         filter.pill = new_pill;
1224                 }
1225         }
1226
1227         process_matches(global_json, global_filters);
1228 }
1229
1230 function make_filter_pill(filter) {
1231         let pill = document.createElement('div');
1232         pill.classList.add('filter-pill');
1233         let text;
1234         if (filter.type === 'match') {
1235                 text = 'Match: ';
1236
1237                 let all_names = [];
1238                 for (const match_id of filter.elements) {
1239                         all_names.push(find_match(match_id)['description']);
1240                 }
1241                 let common_prefix = find_common_prefix_of_all(all_names);
1242                 if (common_prefix !== null) {
1243                         text += common_prefix + '(';
1244                 }
1245
1246                 let first = true;
1247                 let sorted_match_id = Array.from(filter.elements).sort((a, b) => a - b);
1248                 for (const match_id of sorted_match_id) {
1249                         if (!first) {
1250                                 text += ', ';
1251                         }
1252                         let desc = find_match(match_id)['description'];
1253                         if (common_prefix === null) {
1254                                 text += desc;
1255                         } else {
1256                                 text += desc.substr(common_prefix.length);
1257                         }
1258                         first = false;
1259                 }
1260
1261                 if (common_prefix !== null) {
1262                         text += ')';
1263                 }
1264         } else if (filter.type === 'player_any') {
1265                 text = 'Player (any): ';
1266                 let sorted_players = Array.from(filter.elements).sort((a, b) => player_pos(a) - player_pos(b));
1267                 let first = true;
1268                 for (const player_id of sorted_players) {
1269                         if (!first) {
1270                                 text += ', ';
1271                         }
1272                         text += find_player(player_id)['name'];
1273                         first = false;
1274                 }
1275         } else if (filter.type === 'player_all') {
1276                 text = 'Players: ';
1277                 let sorted_players = Array.from(filter.elements).sort((a, b) => player_pos(a) - player_pos(b));
1278                 let first = true;
1279                 for (const player_id of sorted_players) {
1280                         if (!first) {
1281                                 text += ' AND ';
1282                         }
1283                         text += find_player(player_id)['name'];
1284                         first = false;
1285                 }
1286         } else if (filter.type === 'formation_offense' || filter.type === 'formation_defense') {
1287                 const offense = (filter.type === 'formation_offense');
1288                 if (offense) {
1289                         text = 'Offense: ';
1290                 } else {
1291                         text = 'Defense: ';
1292                 }
1293
1294                 let all_names = [];
1295                 for (const formation_id of filter.elements) {
1296                         all_names.push(find_formation(formation_id)['name']);
1297                 }
1298                 let common_prefix = find_common_prefix_of_all(all_names);
1299                 if (common_prefix !== null) {
1300                         text += common_prefix + '(';
1301                 }
1302
1303                 let first = true;
1304                 let sorted_formation_id = Array.from(filter.elements).sort((a, b) => a - b);
1305                 for (const formation_id of sorted_formation_id) {
1306                         if (!first) {
1307                                 text += ', ';
1308                         }
1309                         let desc = find_formation(formation_id)['name'];
1310                         if (common_prefix === null) {
1311                                 text += desc;
1312                         } else {
1313                                 text += desc.substr(common_prefix.length);
1314                         }
1315                         first = false;
1316                 }
1317
1318                 if (common_prefix !== null) {
1319                         text += ')';
1320                 }
1321         }
1322
1323         let text_node = document.createElement('span');
1324         text_node.innerText = text;
1325         text_node.addEventListener('click', (e) => show_submenu(null, pill, filter.type));
1326         pill.appendChild(text_node);
1327
1328         pill.appendChild(document.createTextNode(' '));
1329
1330         let delete_node = document.createElement('span');
1331         delete_node.innerText = '✖';
1332         delete_node.addEventListener('click', (e) => {
1333                 // Delete this filter entirely.
1334                 document.getElementById('filters').removeChild(pill);
1335                 global_filters = global_filters.filter(f => f !== filter);
1336                 process_matches(global_json, global_filters);
1337
1338                 let add_menu = document.getElementById('filter-add-menu');
1339                 let add_submenu = document.getElementById('filter-submenu');
1340                 add_menu.style.display = 'none';
1341                 add_submenu.style.display = 'none';
1342         });
1343         pill.appendChild(delete_node);
1344         pill.style.cursor = 'pointer';
1345
1346         return pill;
1347 }
1348
1349 function find_common_prefix(a, b) {
1350         let ret = '';
1351         for (let i = 0; i < Math.min(a.length, b.length); ++i) {
1352                 if (a[i] === b[i]) {
1353                         ret += a[i];
1354                 } else {
1355                         break;
1356                 }
1357         }
1358         return ret;
1359 }
1360
1361 function find_common_prefix_of_all(values) {
1362         if (values.length < 2) {
1363                 return null;
1364         }
1365         let common_prefix = null;
1366         for (const desc of values) {
1367                 if (common_prefix === null) {
1368                         common_prefix = desc;
1369                 } else {
1370                         common_prefix = find_common_prefix(common_prefix, desc);
1371                 }
1372         }
1373         if (common_prefix.length >= 3) {
1374                 return common_prefix;
1375         } else {
1376                 return null;
1377         }
1378 }
1379
1380 function find_match(match_id) {
1381         for (const match of global_json['matches']) {
1382                 if (match['match_id'] === match_id) {
1383                         return match;
1384                 }
1385         }
1386         return null;
1387 }
1388
1389 function find_formation(formation_id) {
1390         for (const formation of global_json['formations']) {
1391                 if (formation['formation_id'] === formation_id) {
1392                         return formation;
1393                 }
1394         }
1395         return null;
1396 }
1397
1398 function find_player(player_id) {
1399         for (const player of global_json['players']) {
1400                 if (player['player_id'] === player_id) {
1401                         return player;
1402                 }
1403         }
1404         return null;
1405 }
1406
1407 function player_pos(player_id) {
1408         let i = 0;
1409         for (const player of global_json['players']) {
1410                 if (player['player_id'] === player_id) {
1411                         return i;
1412                 }
1413                 ++i;
1414         }
1415         return null;
1416 }
1417
1418 function keep_match(match_id, filters) {
1419         for (const filter of filters) {
1420                 if (filter.type === 'match') {
1421                         return filter.elements.has(match_id);
1422                 }
1423         }
1424         return true;
1425 }
1426
1427 function filter_passes(players, formations_used_this_point, filter) {
1428         if (filter.type === 'player_any') {
1429                 for (const p of Array.from(filter.elements)) {
1430                         if (players[p].on_field_since !== null) {
1431                                 return true;
1432                         }
1433                 }
1434                 return false;
1435         } else if (filter.type === 'player_all') {
1436                 for (const p of Array.from(filter.elements)) {
1437                         if (players[p].on_field_since === null) {
1438                                 return false;
1439                         }
1440                 }
1441                 return true;
1442         } else if (filter.type === 'formation_offense' || filter.type === 'formation_defense') {
1443                 for (const f of Array.from(filter.elements)) {
1444                         if (formations_used_this_point.has(f)) {
1445                                 return true;
1446                         }
1447                 }
1448                 return false;
1449         }
1450         return true;
1451 }
1452
1453 function keep_event(players, formations_used_this_point, filters) {
1454         for (const filter of filters) {
1455                 if (!filter_passes(players, formations_used_this_point, filter)) {
1456                         return false;
1457                 }
1458         }
1459         return true;
1460 }
1461
1462 // Heuristic: If we go at least ten seconds without the possession changing
1463 // or the operator specifying some other formation, we probably play the
1464 // same formation as the last point.
1465 function should_reuse_last_formation(events, t) {
1466         for (const e of events) {
1467                 if (e.t <= t) {
1468                         continue;
1469                 }
1470                 if (e.t > t + 10000) {
1471                         break;
1472                 }
1473                 const type = e.type;
1474                 if (type === 'their_goal' || type === 'goal' ||
1475                     type === 'set_defense' || type === 'set_offense' ||
1476                     type === 'throwaway' || type === 'their_throwaway' ||
1477                     type === 'drop' || type === 'was_d' || type === 'stallout' || type === 'defense' || type === 'interception' ||
1478                     type === 'pull' || type === 'pull_landed' || type === 'pull_oob' || type === 'their_pull' ||
1479                     type === 'formation_offense' || type === 'formation_defense') {
1480                         return false;
1481                 }
1482         }
1483         return true;
1484 }
1485
1486 function possibly_close_menu(e) {
1487         if (e.target.closest('#filter-click-to-add') === null &&
1488             e.target.closest('#filter-add-menu') === null &&
1489             e.target.closest('#filter-submenu') === null &&
1490             e.target.closest('.filter-pill') === null) {
1491                 let add_menu = document.getElementById('filter-add-menu');
1492                 let add_submenu = document.getElementById('filter-submenu');
1493                 add_menu.style.display = 'none';
1494                 add_submenu.style.display = 'none';
1495         }
1496 }
1497
1498 let global_sort = {};
1499
1500 function sort_by(th) {
1501         let tr = th.parentElement;
1502         let child_idx = 0;
1503         for (let column_idx = 0; column_idx < tr.children.length; ++column_idx) {
1504                 let element = tr.children[column_idx];
1505                 if (element === th) {
1506                         ++child_idx;  // Pad.
1507                         break;
1508                 }
1509                 if (element.hasAttribute('colspan')) {
1510                         child_idx += parseInt(element.getAttribute('colspan'));
1511                 } else {
1512                         ++child_idx;
1513                 }
1514         }
1515
1516         global_sort = {};
1517         let table = tr.parentElement;
1518         for (let row_idx = 1; row_idx < table.children.length - 1; ++row_idx) {  // Skip header and globals.
1519                 let row = table.children[row_idx];
1520                 let player = parseInt(row.dataset.player);
1521                 let value = row.children[child_idx].textContent;
1522                 global_sort[player] = value;
1523         }
1524 }
1525
1526 function get_sorted_players(players)
1527 {
1528         let p = Object.entries(players);
1529         if (global_sort.length !== 0) {
1530                 p.sort((a,b) => {
1531                         let ai = parseFloat(global_sort[a[0]]);
1532                         let bi = parseFloat(global_sort[b[0]]);
1533                         if (ai == ai && bi == bi) {
1534                                 return bi - ai;  // Reverse numeric.
1535                         } else if (global_sort[a[0]] < global_sort[b[0]]) {
1536                                 return -1;
1537                         } else if (global_sort[a[0]] > global_sort[b[0]]) {
1538                                 return 1;
1539                         } else {
1540                                 return 0;
1541                         }
1542                 });
1543         }
1544         return p;
1545 }