]> git.sesse.net Git - pkanalytics/blob - ultimate.js
Build without QtMultimedia.
[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 let next_filterset_id = 2;  // Arbitrary IDs are fine as long as they never collide.
8
9 addEventListener('hashchange', () => { process_matches(global_json, global_filters); });
10 addEventListener('click', possibly_close_menu);
11 fetch('ultimate.json')
12    .then(response => response.json())
13    .then(response => { global_json = response; process_matches(global_json, global_filters); });
14
15 function format_time(t)
16 {
17         const ms = t % 1000 + '';
18         t = Math.floor(t / 1000);
19         const sec = t % 60 + '';
20         t = Math.floor(t / 60);
21         const min = t % 60 + '';
22         const hour = Math.floor(t / 60) + '';
23         return hour + ':' + min.padStart(2, '0') + ':' + sec.padStart(2, '0') + '.' + ms.padStart(3, '0');
24 }
25
26 function attribute_player_time(player, to, from, offense) {
27         let delta_time;
28         if (player.on_field_since > from) {
29                 // Player came in while play happened (without a stoppage!?).
30                 delta_time = to - player.on_field_since;
31         } else {
32                 delta_time = to - from;
33         }
34         player.playing_time_ms += delta_time;
35         if (offense === true) {
36                 player.offensive_playing_time_ms += delta_time;
37         } else if (offense === false) {
38                 player.defensive_playing_time_ms += delta_time;
39         }
40 }
41
42 function take_off_field(player, t, live_since, offense, keep) {
43         if (keep) {
44                 if (live_since === null) {
45                         // Play isn't live, so nothing to do.
46                 } else {
47                         attribute_player_time(player, t, live_since, offense);
48                 }
49                 if (player.on_field_since !== null) {  // Just a safeguard; out without in should never happen.
50                         player.field_time_ms += t - player.on_field_since;
51                 }
52         }
53         player.on_field_since = null;
54 }
55
56 function add_cell(tr, element_type, text) {
57         let element = document.createElement(element_type);
58         element.textContent = text;
59         tr.appendChild(element);
60         return element;
61 }
62
63 function add_th(tr, text, colspan) {
64         let element = document.createElement('th');
65         let link = document.createElement('a');
66         link.style.cursor = 'pointer';
67         link.addEventListener('click', (e) => {
68                 sort_by(element);
69                 process_matches(global_json, global_filters);
70         });
71         link.textContent = text;
72         element.appendChild(link);
73         tr.appendChild(element);
74
75         if (colspan > 0) {
76                 element.setAttribute('colspan', colspan);
77         } else {
78                 element.setAttribute('colspan', '3');
79         }
80         return element;
81 }
82
83 function add_3cell(tr, text, cls) {
84         let p1 = add_cell(tr, 'td', '');
85         let element = add_cell(tr, 'td', text);
86         let p2 = add_cell(tr, 'td', '');
87
88         p1.classList.add('pad');
89         p2.classList.add('pad');
90         if (cls === undefined) {
91                 element.classList.add('num');
92         } else {
93                 element.classList.add(cls);
94         }
95         return element;
96 }
97
98 function add_3cell_with_filler_ci(tr, text, cls) {
99         let element = add_3cell(tr, text, cls);
100
101         let svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
102         svg.classList.add('fillerci');
103         svg.setAttribute('width', ci_width);
104         svg.setAttribute('height', ci_height);
105         element.appendChild(svg);
106
107         return element;
108 }
109
110 function add_3cell_ci(tr, ci) {
111         if (isNaN(ci.val)) {
112                 add_3cell_with_filler_ci(tr, 'N/A');
113                 return;
114         }
115
116         let text;
117         if (ci.format === 'percentage') {
118                 text = (100 * ci.val).toFixed(0) + '%';
119         } else if (ci.decimals !== undefined) {
120                 text = ci.val.toFixed(ci.decimals);
121         } else {
122                 text = ci.val.toFixed(2);
123         }
124         if (ci.unit !== undefined) {
125                 text += ' '+ ci.unit;
126         }
127         let element = add_3cell(tr, text);
128         let to_x = (val) => { return ci_width * (val - ci.min) / (ci.max - ci.min); };
129
130         // Container.
131         let svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
132         if (ci.inverted === true) {
133                 svg.classList.add('invertedci');
134         } else {
135                 svg.classList.add('ci');
136         }
137         svg.setAttribute('width', ci_width);
138         svg.setAttribute('height', ci_height);
139
140         // The good (green) and red (bad) ranges.
141         let s0 = document.createElementNS('http://www.w3.org/2000/svg', 'rect');
142         s0.classList.add('range');
143         s0.classList.add('s0');
144         s0.setAttribute('width', to_x(ci.desired));
145         s0.setAttribute('height', ci_height);
146         s0.setAttribute('x', '0');
147
148         let s1 = document.createElementNS('http://www.w3.org/2000/svg', 'rect');
149         s1.classList.add('range');
150         s1.classList.add('s1');
151         s1.setAttribute('width', ci_width - to_x(ci.desired));
152         s1.setAttribute('height', ci_height);
153         s1.setAttribute('x', to_x(ci.desired));
154
155         // Confidence bar.
156         let bar = document.createElementNS('http://www.w3.org/2000/svg', 'rect');
157         bar.classList.add('bar');
158         bar.setAttribute('width', to_x(ci.upper_ci) - to_x(ci.lower_ci));
159         bar.setAttribute('height', ci_height / 3);
160         bar.setAttribute('x', to_x(ci.lower_ci));
161         bar.setAttribute('y', ci_height / 3);
162
163         // Marker line for average.
164         let marker = document.createElementNS('http://www.w3.org/2000/svg', 'line');
165         marker.classList.add('marker');
166         marker.setAttribute('x1', to_x(ci.val));
167         marker.setAttribute('x2', to_x(ci.val));
168         marker.setAttribute('y1', ci_height / 6);
169         marker.setAttribute('y2', ci_height * 5 / 6);
170
171         svg.appendChild(s0);
172         svg.appendChild(s1);
173         svg.appendChild(bar);
174         svg.appendChild(marker);
175
176         element.appendChild(svg);
177 }
178
179 function calc_stats(json, filters) {
180         let players = {};
181         for (const player of json['players']) {
182                 players[player['player_id']] = {
183                         'name': player['name'],
184                         'gender': player['gender'],
185                         'number': player['number'],
186
187                         'goals': 0,
188                         'assists': 0,
189                         'hockey_assists': 0,
190                         'catches': 0,
191                         'touches': 0,
192                         'num_throws': 0,
193                         'throwaways': 0,
194                         'drops': 0,
195                         'was_ds': 0,
196                         'stallouts': 0,
197
198                         'defenses': 0,
199                         'callahans': 0,
200                         'points_played': 0,
201                         'playing_time_ms': 0,
202                         'offensive_playing_time_ms': 0,
203                         'defensive_playing_time_ms': 0,
204                         'field_time_ms': 0,
205
206                         // For efficiency.
207                         'offensive_points_completed': 0,
208                         'offensive_points_won': 0,
209                         'defensive_points_completed': 0,
210                         'defensive_points_won': 0,
211
212                         'offensive_soft_plus': 0,
213                         'offensive_soft_minus': 0,
214                         'defensive_soft_plus': 0,
215                         'defensive_soft_minus': 0,
216
217                         'pulls': 0,
218                         'pull_times': [],
219                         'oob_pulls': 0,
220
221                         // Internal.
222                         'last_point_seen': null,
223                         'on_field_since': null,
224                 };
225         }
226
227         // Globals.
228         players['globals'] = {
229                 'points_played': 0,
230                 'playing_time_ms': 0,
231                 'offensive_playing_time_ms': 0,
232                 'defensive_playing_time_ms': 0,
233                 'field_time_ms': 0,
234
235                 'offensive_points_completed': 0,
236                 'offensive_points_won': 0,
237                 'clean_holds': 0,
238
239                 'defensive_points_completed': 0,
240                 'defensive_points_won': 0,
241                 'clean_breaks': 0,
242
243                 'turnovers_won': 0,
244                 'turnovers_lost': 0,
245                 'their_clean_holds': 0,
246                 'their_clean_breaks': 0,
247
248                 'touches_for_turnover': 0,
249                 'touches_for_goal': 0,
250                 'time_for_turnover': [],
251                 'time_for_goal': [],
252                 'their_time_for_turnover': [],
253                 'their_time_for_goal': [],
254         };
255         let globals = players['globals'];
256
257         for (const match of json['matches']) {
258                 if (!keep_match(match['match_id'], filters)) {
259                         continue;
260                 }
261
262                 let our_score = 0;
263                 let their_score = 0;
264                 let between_points = true;
265                 let handler = null;
266                 let handler_got_by_interception = false;  // Only relevant if handler !== null.
267                 let prev_handler = null;
268                 let live_since = null;
269                 let offense = null;  // True/false/null (unknown).
270                 let puller = null;
271                 let pull_started = null;
272                 let last_pull_was_ours = null;  // Effectively whether we're playing an O or D point (not affected by turnovers).
273                 let point_num = 0;
274                 let game_started = null;
275                 let last_goal = null;
276                 let current_predominant_gender = null;
277                 let current_num_players_on_field = null;
278
279                 let we_lost_disc = false;
280                 let they_lost_disc = false;
281                 let touches_this_possession = 0;
282                 let possession_started = null;
283                 let extra_ms_this_possession = 0;  // Used at stoppages.
284
285                 // The last used formations of the given kind, if any; they may be reused
286                 // when the point starts, if nothing else is set.
287                 let last_offensive_formation = null;
288                 let last_defensive_formation = null;
289
290                 // Formations we've set, but haven't really had the chance to use yet
291                 // (e.g., we get a “use zone defense” event while we're still on offense).
292                 let pending_offensive_formation = null;
293                 let pending_defensive_formation = null;
294
295                 // Formations that we have played at least once this point, after all
296                 // heuristics and similar.
297                 let formations_used_this_point = new Set();
298
299                 for (const [q,p] of Object.entries(players)) {
300                         p.on_field_since = null;
301                         p.last_point_seen = null;
302                 }
303                 for (const e of match['events']) {
304                         let t = e['t'];
305                         let type = e['type'];
306                         let p = players[e['player']];
307
308                         // Sub management
309                         let keep = keep_event(players, formations_used_this_point, last_pull_was_ours, filters);
310                         if (type === 'in' && p.on_field_since === null) {
311                                 p.on_field_since = t;
312                                 if (!keep && keep_event(players, formations_used_this_point, last_pull_was_ours, filters)) {
313                                         // A player needed for the filters went onto the field,
314                                         // so pretend people walked on right now (to start their
315                                         // counting time).
316                                         for (const [q,p2] of Object.entries(players)) {
317                                                 if (p2.on_field_since !== null) {
318                                                         p2.on_field_since = t;
319                                                 }
320                                         }
321                                 }
322                         } else if (type === 'out') {
323                                 take_off_field(p, t, live_since, offense, keep);
324                                 if (keep && !keep_event(players, formations_used_this_point, last_pull_was_ours, filters)) {
325                                         // A player needed for the filters went off the field,
326                                         // so we need to attribute time for all the others.
327                                         // Pretend they walked off and then immediately on again.
328                                         //
329                                         // TODO: We also need to take care of this to get the globals right.
330                                         for (const [q,p2] of Object.entries(players)) {
331                                                 if (p2.on_field_since !== null) {
332                                                         take_off_field(p2, t, live_since, offense, keep);
333                                                         p2.on_field_since = t;
334                                                 }
335                                         }
336                                 }
337                         }
338
339                         keep = keep_event(players, formations_used_this_point, last_pull_was_ours, filters);  // Recompute after in/out.
340
341                         if (match['gender_rule_a']) {
342                                 if (type === 'restart' && !between_points) {
343                                         let predominant_gender = find_predominant_gender(players);
344                                         let num_players_on_field = find_num_players_on_field(players);
345                                         if (predominant_gender !== current_predominant_gender && current_predominant_gender !== null) {
346                                                 console.log(match['description'] + ' ' + format_time(t) + ': Stoppage changed predominant gender from ' + current_predominant_gender + ' to ' + predominant_gender);
347                                         }
348                                         if (num_players_on_field !== current_num_players_on_field && current_num_players_on_field !== null) {
349                                                 console.log(match['description'] + ' ' + format_time(t) + ': Stoppage changed number of players on field from ' + current_num_players_on_field + ' to ' + num_players_on_field);
350                                         }
351                                         current_predominant_gender = predominant_gender;
352                                         current_num_players_on_field = num_players_on_field;
353                                 } else if (type === 'pull' || type === 'their_pull') {
354                                         let predominant_gender = find_predominant_gender(players);
355                                         let num_players_on_field = find_num_players_on_field(players);
356                                         let changed = (predominant_gender !== current_predominant_gender);
357                                         if (point_num !== 0) {
358                                                 let should_change = (point_num % 4 == 1 || point_num % 4 == 3);  // ABBA changes on 1 and 3.
359                                                 if (changed && !should_change) {
360                                                         console.log(match['description'] + ' ' + format_time(t) + ': Gender ratio should have stayed the same, changed to predominance of ' + predominant_gender);
361                                                 } else if (!changed && should_change) {
362                                                         console.log(match['description'] + ' ' + format_time(t) + ': Gender ratio should have changed, remained predominantly ' + predominant_gender);
363                                                 }
364                                                 if (num_players_on_field !== current_num_players_on_field && current_num_players_on_field !== null) {
365                                                         console.log(match['description'] + ' ' + format_time(t) + ': Number of players on field changed from ' + current_num_players_on_field + ' to ' + num_players_on_field);
366                                                 }
367                                         }
368                                         current_predominant_gender = predominant_gender;
369                                         current_num_players_on_field = num_players_on_field;
370                                 }
371                         }
372                         if (match['gender_pull_rule']) {
373                                 if (type === 'pull') {
374                                         if (current_predominant_gender !== null &&
375                                             p.gender !== current_predominant_gender) {
376                                                 console.log(match['description'] + ' ' + format_time(t) + ': ' + p.name + ' pulled, should have been ' + current_predominant_gender);
377                                         }
378                                 }
379                         }
380
381                         // Liveness management
382                         if (type === 'pull' || type === 'their_pull' || type === 'restart') {
383                                 live_since = t;
384                                 if (type !== 'restart') {
385                                         between_points = false;
386                                 }
387                         } else if (type === 'catch' && last_pull_was_ours === null) {
388                                 // Someone forgot to add the pull, so we'll need to wing it.
389                                 console.log(match['description'] + ' ' + format_time(t) + ': Missing pull on ' + our_score + '\u2013' + their_score + '; pretending to have one.');
390                                 live_since = t;
391                                 last_pull_was_ours = !offense;
392                                 between_points = false;
393                         } else if (type === 'goal' || type === 'their_goal' || type === 'stoppage') {
394                                 if (type === 'goal') {
395                                         if (keep) ++p.touches;
396                                         ++touches_this_possession;
397                                 }
398                                 for (const [q,p] of Object.entries(players)) {
399                                         if (p.on_field_since === null) {
400                                                 continue;
401                                         }
402                                         if (type !== 'stoppage' && p.last_point_seen !== point_num) {
403                                                 if (keep) {
404                                                         // In case the player did nothing this point,
405                                                         // not even subbing in.
406                                                         p.last_point_seen = point_num;
407                                                         ++p.points_played;
408                                                 }
409                                         }
410                                         if (keep) attribute_player_time(p, t, live_since, offense);
411
412                                         if (type !== 'stoppage') {
413                                                 if (keep) {
414                                                         if (last_pull_was_ours === true) {  // D point.
415                                                                 ++p.defensive_points_completed;
416                                                                 if (type === 'goal') {
417                                                                         ++p.defensive_points_won;
418                                                                 }
419                                                         } else if (last_pull_was_ours === false) {  // O point.
420                                                                 ++p.offensive_points_completed;
421                                                                 if (type === 'goal') {
422                                                                         ++p.offensive_points_won;
423                                                                 }
424                                                         }
425                                                 }
426                                         }
427                                 }
428
429                                 if (keep) {
430                                         if (type !== 'stoppage') {
431                                                 // Update globals.
432                                                 ++globals.points_played;
433                                                 if (last_pull_was_ours === true) {  // D point.
434                                                         ++globals.defensive_points_completed;
435                                                         if (type === 'goal') {
436                                                                 ++globals.defensive_points_won;
437                                                         }
438                                                 } else if (last_pull_was_ours === false) {  // O point.
439                                                         ++globals.offensive_points_completed;
440                                                         if (type === 'goal') {
441                                                                 ++globals.offensive_points_won;
442                                                         }
443                                                 }
444                                         }
445                                         if (live_since !== null) {
446                                                 globals.playing_time_ms += t - live_since;
447                                                 if (offense === true) {
448                                                         globals.offensive_playing_time_ms += t - live_since;
449                                                 } else if (offense === false) {
450                                                         globals.defensive_playing_time_ms += t - live_since;
451                                                 }
452                                         }
453                                 }
454
455                                 live_since = null;
456                         }
457
458                         // Score management
459                         if (type === 'goal') {
460                                 ++our_score;
461                         } else if (type === 'their_goal') {
462                                 ++their_score;
463                         }
464
465                         // Point count management
466                         if (p !== undefined && type !== 'out' && p.last_point_seen !== point_num) {
467                                 if (keep) {
468                                         p.last_point_seen = point_num;
469                                         ++p.points_played;
470                                 }
471                         }
472                         if (type === 'goal' || type === 'their_goal') {
473                                 ++point_num;
474                                 last_goal = t;
475                         }
476                         if (type !== 'out' && game_started === null) {
477                                 game_started = t;
478                         }
479
480                         // Pull management
481                         if (type === 'pull') {
482                                 puller = e['player'];
483                                 pull_started = t;
484                                 keep = keep_event(players, formations_used_this_point, /*last_pull_was_ours=*/true, filters);  // Will change below. This is an ugly hack.
485                                 if (keep) ++p.pulls;
486                         } else if (type === 'in' || type === 'out' || type === 'stoppage' || type === 'restart' || type === 'unknown' || type === 'set_defense' || type === 'set_offense') {
487                                 // No effect on pull.
488                         } else if (type === 'pull_landed' && puller !== null) {
489                                 if (keep) players[puller].pull_times.push(t - pull_started);
490                         } else if (type === 'pull_oob' && puller !== null) {
491                                 if (keep) ++players[puller].oob_pulls;
492                         } else {
493                                 // Not pulling (if there was one, we never recorded its outcome, but still count it).
494                                 puller = pull_started = null;
495                         }
496
497                         // Stats for clean holds or not (must be done before resetting we_lost_disc etc. below).
498                         if (keep) {
499                                 if (type === 'goal' && !we_lost_disc) {
500                                         if (last_pull_was_ours === false) {  // O point.
501                                                 ++globals.clean_holds;
502                                         } else if (last_pull_was_ours === true) {
503                                                 ++globals.clean_breaks;
504                                         }
505                                 } else if (type === 'their_goal' && !they_lost_disc) {
506                                         if (last_pull_was_ours === true) {  // O point for them.
507                                                 ++globals.their_clean_holds;
508                                         } else if (last_pull_was_ours === false) {
509                                                 ++globals.their_clean_breaks;
510                                         }
511                                 }
512                         }
513
514                         // Offense/defense management
515                         let last_offense = offense;
516                         if (type === 'set_defense' || type === 'goal' || type === 'throwaway' || type === 'drop' || type === 'was_d' || type === 'stallout') {
517                                 offense = false;
518                                 we_lost_disc = true;
519                                 if (keep && type !== 'goal' && !(type === 'set_defense' && last_pull_was_ours === null)) {
520                                         ++globals.turnovers_lost;
521                                         globals.touches_for_turnover += touches_this_possession;
522                                         if (possession_started != null) globals.time_for_turnover.push((t - possession_started) + extra_ms_this_possession);
523                                 } else if (keep && type === 'goal') {
524                                         globals.touches_for_goal += touches_this_possession;
525                                         if (possession_started != null) globals.time_for_goal.push((t - possession_started) + extra_ms_this_possession);
526                                 }
527                                 touches_this_possession = 0;
528                                 possession_started = null;
529                                 extra_ms_this_possession = 0;
530                         } else if (type === 'set_offense' || type === 'their_goal' || type === 'their_throwaway' || type === 'defense' || type === 'interception') {
531                                 offense = true;
532                                 they_lost_disc = true;
533                                 if (keep && type !== 'their_goal' && !(type === 'set_offense' && last_pull_was_ours === null)) {
534                                         ++globals.turnovers_won;
535                                         if (possession_started != null) globals.their_time_for_turnover.push((t - possession_started) + extra_ms_this_possession);
536                                 } else if (keep && type === 'their_goal') {
537                                         if (possession_started != null) globals.their_time_for_goal.push((t - possession_started) + extra_ms_this_possession);
538                                 }
539                                 touches_this_possession = 0;
540                                 possession_started = null;
541                                 extra_ms_this_possession = 0;
542                         }
543                         if (type === 'goal' || type === 'their_goal') {
544                                 between_points = true;
545                                 we_lost_disc = false;
546                                 they_lost_disc = false;
547                                 touches_this_possession = 0;
548                         }
549                         if (last_offense !== offense && live_since !== null) {
550                                 // Switched offense/defense status, so attribute this drive as needed,
551                                 // and update live_since to take that into account.
552                                 if (keep) {
553                                         for (const [q,p] of Object.entries(players)) {
554                                                 if (p.on_field_since === null) {
555                                                         continue;
556                                                 }
557                                                 attribute_player_time(p, t, live_since, last_offense);
558                                         }
559                                         globals.playing_time_ms += t - live_since;
560                                         if (offense === true) {
561                                                 globals.offensive_playing_time_ms += t - live_since;
562                                         } else if (offense === false) {
563                                                 globals.defensive_playing_time_ms += t - live_since;
564                                         }
565                                 }
566                                 live_since = t;
567                         }
568                         // The rules for possessions are slightly different; we want to start at pulls,
569                         // not previous goals.
570                         if ((last_offense !== offense && type !== 'goal' && type !== 'their_goal' && live_since !== null) ||
571                             type === 'pull' || type === 'their_pull') {
572                                 possession_started = t;
573                         } else if (type === 'stoppage') {
574                                 if (possession_started !== null) {
575                                         extra_ms_this_possession = t - possession_started;
576                                         possession_started = null;
577                                 }
578                         } else if (type === 'restart' && live_since !== null && !between_points) {
579                                 possession_started = t;
580                         }
581
582                         // O/D-point management.
583                         if (type === 'pull') {
584                                 last_pull_was_ours = true;
585                         } else if (type === 'their_pull') {
586                                 last_pull_was_ours = false;
587                         } else if (type === 'set_offense' && last_pull_was_ours === null) {
588                                 // set_offense could either be “changed to offense for some reason
589                                 // we could not express”, or “we started in the middle of a point,
590                                 // and we are offense”. We assume that if we already saw the pull,
591                                 // it's the former, and if not, it's the latter; thus, the === null
592                                 // test above. (It could also be “we set offense before the pull,
593                                 // so that we get the right button enabled”, in which case it will
594                                 // be overwritten by the next pull/their_pull event anyway.)
595                                 last_pull_was_ours = false;
596                         } else if (type === 'set_defense' && last_pull_was_ours === null) {
597                                 // Similar.
598                                 last_pull_was_ours = true;
599                         } else if (type === 'goal' || type === 'their_goal') {
600                                 last_pull_was_ours = null;
601                         }
602
603                         // Formation management
604                         if (type === 'formation_offense' || type === 'formation_defense') {
605                                 let id = e.formation === null ? 0 : e.formation;
606                                 let for_offense = (type === 'formation_offense');
607                                 if (offense === for_offense) {
608                                         formations_used_this_point.add(id);
609                                 } else if (for_offense) {
610                                         pending_offensive_formation = id;
611                                 } else {
612                                         pending_defensive_formation = id;
613                                 }
614                                 if (for_offense) {
615                                         last_offensive_formation = id;
616                                 } else {
617                                         last_defensive_formation = id;
618                                 }
619                         } else if (last_offense !== offense) {
620                                 if (offense === true && pending_offensive_formation !== null) {
621                                         formations_used_this_point.add(pending_offensive_formation);
622                                         pending_offensive_formation = null;
623                                 } else if (offense === false && pending_defensive_formation !== null) {
624                                         formations_used_this_point.add(pending_defensive_formation);
625                                         pending_defensive_formation = null;
626                                 } else if (offense === true && last_defensive_formation !== null) {
627                                         if (should_reuse_last_formation(match['events'], t)) {
628                                                 formations_used_this_point.add(last_defensive_formation);
629                                         }
630                                 } else if (offense === false && last_offensive_formation !== null) {
631                                         if (should_reuse_last_formation(match['events'], t)) {
632                                                 formations_used_this_point.add(last_offensive_formation);
633                                         }
634                                 }
635                         }
636
637                         if (type !== 'out' && type !== 'in' && p !== undefined && p.on_field_since === null) {
638                                 console.log(match['description'] + ' ' + format_time(t) + ': Event “' + type + '” on subbed-out player ' + p.name);
639                         }
640                         if (type === 'catch' && handler !== null && players[handler].on_field_since === null) {
641                                 // The handler subbed out and was replaced with another handler,
642                                 // so this wasn't a pass.
643                                 handler = null;
644                         }
645
646                         // Event management
647                         if (type === 'goal' && handler === e['player'] && handler_got_by_interception) {
648                                 // Self-pass to goal after an interception; this is not a real pass,
649                                 // just how we represent a Callahan right now -- so don't
650                                 // count the throw, any assists or similar.
651                                 //
652                                 // It's an open question how we should handle a self-pass that is
653                                 // _not_ after an interception, or a self-pass that's not a goal.
654                                 // (It must mean we tipped off someone.) We'll count it as a regular one
655                                 // for the time being, although it will make hockey assists weird.
656                                 if (keep) {
657                                         ++p.goals;
658                                         ++p.callahans;
659                                 }
660                                 handler = prev_handler = null;
661                         } else if (type === 'catch' || type === 'goal') {
662                                 if (handler !== null) {
663                                         if (keep) {
664                                                 ++players[handler].num_throws;
665                                                 ++p.catches;
666                                         }
667                                 }
668
669                                 if (keep) ++p.touches;
670                                 ++touches_this_possession;
671                                 if (type === 'goal') {
672                                         if (keep) {
673                                                 if (prev_handler !== null) {
674                                                         ++players[prev_handler].hockey_assists;
675                                                 }
676                                                 if (handler !== null) {
677                                                         ++players[handler].assists;
678                                                 }
679                                                 ++p.goals;
680                                         }
681                                         handler = prev_handler = null;
682                                 } else {
683                                         // Update hold history.
684                                         prev_handler = handler;
685                                         handler = e['player'];
686                                         handler_got_by_interception = false;
687                                 }
688                         } else if (type === 'throwaway') {
689                                 if (keep) {
690                                         ++p.num_throws;
691                                         ++p.throwaways;
692                                 }
693                                 handler = prev_handler = null;
694                         } else if (type === 'drop') {
695                                 if (keep) ++p.drops;
696                                 handler = prev_handler = null;
697                         } else if (type === 'stallout') {
698                                 if (keep) ++p.stallouts;
699                                 handler = prev_handler = null;
700                         } else if (type === 'was_d') {
701                                 if (keep) ++p.was_ds;
702                                 handler = prev_handler = null;
703                         } else if (type === 'defense') {
704                                 if (keep) ++p.defenses;
705                         } else if (type === 'interception') {
706                                 if (keep) {
707                                         ++p.catches;
708                                         ++p.defenses;
709                                         ++p.touches;
710                                         ++touches_this_possession;
711                                 }
712                                 prev_handler = null;
713                                 handler = e['player'];
714                                 handler_got_by_interception = true;
715                         } else if (type === 'offensive_soft_plus' || type === 'offensive_soft_minus' || type === 'defensive_soft_plus' || type === 'defensive_soft_minus') {
716                                 if (keep) ++p[type];
717                         } else if (type !== 'in' && type !== 'out' && type !== 'pull' &&
718                                    type !== 'their_goal' && type !== 'stoppage' && type !== 'restart' && type !== 'unknown' &&
719                                    type !== 'set_defense' && type !== 'goal' && type !== 'throwaway' &&
720                                    type !== 'drop' && type !== 'was_d' && type !== 'stallout' && type !== 'set_offense' && type !== 'their_goal' &&
721                                    type !== 'pull' && type !== 'pull_landed' && type !== 'pull_oob' && type !== 'their_pull' &&
722                                    type !== 'their_throwaway' && type !== 'defense' && type !== 'interception' &&
723                                    type !== 'formation_offense' && type !== 'formation_defense') {
724                                 console.log(format_time(t) + ": Unknown event “" + e + "”");
725                         }
726
727                         if (type === 'goal' || type === 'their_goal') {
728                                 formations_used_this_point.clear();
729                         }
730                 }
731
732                 // Add field time for all players still left at match end.
733                 const keep = keep_event(players, formations_used_this_point, last_pull_was_ours, filters);
734                 if (keep) {
735                         for (const [q,p] of Object.entries(players)) {
736                                 if (p.on_field_since !== null && last_goal !== null) {
737                                         p.field_time_ms += last_goal - p.on_field_since;
738                                 }
739                         }
740                         if (game_started !== null && last_goal !== null) {
741                                 globals.field_time_ms += last_goal - game_started;
742                         }
743                         if (live_since !== null && last_goal !== null) {
744                                 globals.playing_time_ms += last_goal - live_since;
745                                 if (offense === true) {
746                                         globals.offensive_playing_time_ms += last_goal - live_since;
747                                 } else if (offense === false) {
748                                         globals.defensive_playing_time_ms += last_goal - live_since;
749                                 }
750                         }
751                 }
752         }
753         return players;
754 }
755
756 function recursively_expand_filterset(filterset, base, result)
757 {
758         if (result.length >= 100) {
759                 return;
760         }
761         if (base.length == filterset.length) {
762                 result.push(base);
763                 return;
764         }
765         let filter = filterset[base.length];
766         if (filter.split) {
767                 let elements = filter.elements;
768                 if (elements.size === 0) {
769                         elements = filter.choices;
770                 }
771                 for (const element of elements) {
772                         let split_filter = {
773                                 'type': filter.type,
774                                 'elements': new Set([ element ]),
775                                 'split': false,  // Not used.
776                         };
777                         recursively_expand_filterset(filterset, [...base, split_filter], result);
778                 }
779         } else {
780                 recursively_expand_filterset(filterset, [...base, filter], result);
781         }
782 }
783
784 function expand_filtersets(filtersets) {
785         if (filtersets.length === 0) {
786                 return [[]];
787         }
788
789         let expanded = [];
790         for (const filterset of filtersets) {
791                 recursively_expand_filterset(filterset, [], expanded);
792         }
793         return expanded;
794 }
795
796 function process_matches(json, unexpanded_filtersets) {
797         let chosen_category = get_chosen_category();
798         write_main_menu(chosen_category);
799
800         let filtersets = expand_filtersets(Object.values(unexpanded_filtersets));
801
802         let rowsets = [];
803         for (const filter of filtersets) {
804                 let players = calc_stats(json, filter);
805                 let rows = [];
806                 if (chosen_category === 'general') {
807                         rows = make_table_general(players);
808                 } else if (chosen_category === 'offense') {
809                         rows = make_table_offense(players);
810                 } else if (chosen_category === 'defense') {
811                         rows = make_table_defense(players);
812                 } else if (chosen_category === 'playing_time') {
813                         rows = make_table_playing_time(players);
814                 } else if (chosen_category === 'per_point') {
815                         rows = make_table_per_point(players);
816                 } else if (chosen_category === 'team_wide') {
817                         rows = make_table_team_wide(players);
818                 }
819                 rowsets.push(rows);
820         }
821
822         let merged_rows = [];
823         if (filtersets.length > 1) {
824                 for (let i = 0; i < rowsets.length; ++i) {
825                         let marker = make_filter_marker(filtersets[i]);
826
827                         // Make filter header.
828                         let tr = rowsets[i][0];
829                         let th = document.createElement('th');
830                         th.textContent = '';
831                         tr.insertBefore(th, tr.firstChild);
832
833                         for (let j = 1; j < rowsets[i].length; ++j) {
834                                 let tr = rowsets[i][j];
835
836                                 // Remove the name for cleanness.
837                                 if (i != 0) {
838                                         tr.firstChild.nextSibling.textContent = '';
839                                 }
840
841                                 if (i != 0) {
842                                         tr.style.borderTop = '0px';
843                                 }
844                                 if (i != rowsets.length - 1) {
845                                         tr.style.borderBottom = '0px';
846                                 }
847
848                                 // Make filter marker.
849                                 let td = document.createElement('td');
850                                 td.textContent = marker;
851                                 td.classList.add('filtermarker');
852                                 tr.insertBefore(td, tr.firstChild);
853                         }
854                 }
855
856                 for (let i = 0; i < rowsets[0].length; ++i) {
857                         for (let j = 0; j < rowsets.length; ++j) {
858                                 merged_rows.push(rowsets[j][i]);
859                                 if (i === 0) break;  // Don't merge the headings.
860                         }
861                 }
862         } else {
863                 merged_rows = rowsets[0];
864         }
865         document.getElementById('stats').replaceChildren(...merged_rows);
866 }
867
868 function get_chosen_category() {
869         if (window.location.hash === '#offense') {
870                 return 'offense';
871         } else if (window.location.hash === '#defense') {
872                 return 'defense';
873         } else if (window.location.hash === '#playing_time') {
874                 return 'playing_time';
875         } else if (window.location.hash === '#per_point') {
876                 return 'per_point';
877         } else if (window.location.hash === '#team_wide') {
878                 return 'team_wide';
879         } else {
880                 return 'general';
881         }
882 }
883
884 function write_main_menu(chosen_category) {
885         let elems = [];
886         const categories = [
887                 ['general', 'General'],
888                 ['offense', 'Offense'],
889                 ['defense', 'Defense'],
890                 ['playing_time', 'Playing time'],
891                 ['per_point', 'Per point'],
892                 ['team_wide', 'Team-wide'],
893         ];
894         for (const [id, title] of categories) {
895                 if (chosen_category === id) {
896                         let span = document.createElement('span');
897                         span.innerText = title;
898                         elems.push(span);
899                 } else {
900                         let a = document.createElement('a');
901                         a.appendChild(document.createTextNode(title));
902                         a.setAttribute('href', '#' + id);
903                         elems.push(a);
904                 }
905         }
906
907         document.getElementById('mainmenu').replaceChildren(...elems);
908 }
909
910 // https://en.wikipedia.org/wiki/1.96#History
911 const z = 1.959964;
912
913 const ci_width = 100;
914 const ci_height = 20;
915
916 function make_binomial_ci(val, num, z) {
917         let avg = val / num;
918
919         // https://en.wikipedia.org/wiki/Binomial_proportion_confidence_interval#Wilson_score_interval
920         let low  = (avg + z*z/(2*num) - z * Math.sqrt(avg * (1.0 - avg) / num + z*z/(4*num*num))) / (1 + z*z/num);   
921         let high = (avg + z*z/(2*num) + z * Math.sqrt(avg * (1.0 - avg) / num + z*z/(4*num*num))) / (1 + z*z/num); 
922
923         // Fix the signs so that we don't get -0.00.
924         low = Math.max(low, 0.0);
925         return {
926                 'val': avg,
927                 'lower_ci': low,
928                 'upper_ci': high,
929                 'min': 0.0,
930                 'max': 1.0,
931         };
932 }
933
934 // These can only happen once per point, but you get -1 and +1
935 // instead of 0 and +1. After we rewrite to 0 and 1, it's a binomial,
936 // and then we can rewrite back.
937 function make_efficiency_ci(points_won, points_completed, z)
938 {
939         let ci = make_binomial_ci(points_won, points_completed, z);
940         ci.val = 2.0 * ci.val - 1.0;
941         ci.lower_ci = 2.0 * ci.lower_ci - 1.0;
942         ci.upper_ci = 2.0 * ci.upper_ci - 1.0;
943         ci.min = -1.0;
944         ci.max = 1.0;
945         ci.desired = 0.0;  // Desired = positive efficiency.
946         return ci;
947 }
948
949 // Ds, throwaways and drops can happen multiple times per point,
950 // so they are Poisson distributed.
951 //
952 // Modified Wald (recommended by http://www.ine.pt/revstat/pdf/rs120203.pdf
953 // since our rates are definitely below 2 per point).
954 //
955 // FIXME: z is ignored.
956 function make_poisson_ci(val, num, z, inverted)
957 {
958         let low  = (val == 0) ? 0.0 : ((val - 0.5) - Math.sqrt(val - 0.5)) / num;
959         let high = (val == 0) ? -Math.log(0.025) / num : ((val + 0.5) + Math.sqrt(val + 0.5)) / num;
960
961         // Fix the signs so that we don't get -0.00.
962         low = Math.max(low, 0.0);
963
964         // The display range of 0 to 0.5 is fairly arbitrary. So is the desired 0.05 per point.
965         let avg = val / num;
966         return {
967                 'val': avg,
968                 'lower_ci': low,
969                 'upper_ci': high,
970                 'min': 0.0,
971                 'max': 0.5,
972                 'desired': 0.05,
973                 'inverted': inverted,
974         };
975 }
976
977 // Wilson and Hilferty, again recommended for general use in the PDF above
978 // (anything from their group “G1” works).
979 // https://en.wikipedia.org/wiki/Poisson_distribution#Confidence_interval
980 function make_poisson_ci_large(val, num, z)
981 {
982         let low  = val * Math.pow(1.0 - 1.0 / (9.0 * val) - z / (3.0 * Math.sqrt(val)), 3.0) / num;
983         let high = (val + 1.0) * Math.pow(1.0 - 1.0 / (9.0 * (val + 1.0)) + z / (3.0 * Math.sqrt(val + 1.0)), 3.0) / num;
984
985         // Fix the signs so that we don't get -0.00.
986         low = Math.max(low, 0.0);
987
988         // The display range of 0 to 25.0 is fairly arbitrary. We have no desire here
989         // (this is used for number of touches).
990         let avg = val / num;
991         return {
992                 'val': avg,
993                 'lower_ci': low,
994                 'upper_ci': high,
995                 'min': 0.0,
996                 'max': 25.0,
997                 'desired': 0.0,
998                 'inverted': false,
999         };
1000 }
1001
1002 // We don't really know what to expect for possessions; it appears roughly
1003 // lognormal, but my head doesn't work well enough to extract the CI for
1004 // the estimated sample mean, and now my head spins around whether we do
1005 // this correctly even for Poisson :-) But we do a simple (non-BCa) bootstrap
1006 // here, which should give us what we want.
1007 //
1008 // FIXME: z is ignored.
1009 function make_ci_duration(vals, z)
1010 {
1011         // Bootstrap.
1012         let sample_means = [];
1013         for (let i = 0; i < 300; ++i) {
1014                 let sum = 0.0;
1015                 for (let j = 0; j < vals.length; ++j) {
1016                         sum += vals[Math.floor(Math.random() * vals.length)];
1017                 }
1018                 sample_means.push(sum / vals.length);
1019         }
1020         sample_means.sort();
1021
1022         // Interpolating here would probably be better, but OK.
1023         let low  = sample_means[Math.floor(0.025 * sample_means.length)];
1024         let high = sample_means[Math.floor(0.975 * sample_means.length)];
1025
1026         // Find the point estimate of the mean.
1027         let sum = 0.0;
1028         for (const v of vals) {
1029                 sum += v;
1030         }
1031         let avg = sum / vals.length;
1032
1033         return {
1034                 'val': avg / 1000.0,
1035                 'lower_ci': low / 1000.0,
1036                 'upper_ci': high / 1000.0,
1037                 'min': 0.0,
1038                 'max': 120.0,
1039                 'desired': 0.0,
1040                 'inverted': false,
1041                 'unit': 'sec',
1042                 'decimals': 1,
1043         };
1044 }
1045
1046 function make_table_general(players) {
1047         let rows = [];
1048         {
1049                 let header = document.createElement('tr');
1050                 add_th(header, 'Player');
1051                 add_th(header, '+/-');
1052                 add_th(header, 'Soft +/-');
1053                 add_th(header, 'O efficiency');
1054                 add_th(header, 'D efficiency');
1055                 add_th(header, 'Points played');
1056                 rows.push(header);
1057         }
1058
1059         for (const [q,p] of get_sorted_players(players)) {
1060                 if (q === 'globals') continue;
1061                 let row = document.createElement('tr');
1062                 let pm = p.goals + p.assists + p.hockey_assists + p.defenses - p.throwaways - p.drops - p.was_ds - p.stallouts;
1063                 let soft_pm = p.offensive_soft_plus + p.defensive_soft_plus - p.offensive_soft_minus - p.defensive_soft_minus;
1064                 let o_efficiency = make_efficiency_ci(p.offensive_points_won, p.offensive_points_completed, z);
1065                 let d_efficiency = make_efficiency_ci(p.defensive_points_won, p.defensive_points_completed, z);
1066                 let name = add_3cell(row, p.name, 'name');  // TODO: number?
1067                 add_3cell(row, pm > 0 ? ('+' + pm) : pm);
1068                 add_3cell(row, soft_pm > 0 ? ('+' + soft_pm) : soft_pm);
1069                 add_3cell_ci(row, o_efficiency);
1070                 add_3cell_ci(row, d_efficiency);
1071                 add_3cell(row, p.points_played);
1072                 row.dataset.player = q;
1073                 rows.push(row);
1074         }
1075
1076         // Globals.
1077         let globals = players['globals'];
1078         let o_efficiency = make_efficiency_ci(globals.offensive_points_won, globals.offensive_points_completed, z);
1079         let d_efficiency = make_efficiency_ci(globals.defensive_points_won, globals.defensive_points_completed, z);
1080         let row = document.createElement('tr');
1081         add_3cell(row, '');
1082         add_3cell(row, '');
1083         add_3cell(row, '');
1084         add_3cell_ci(row, o_efficiency);
1085         add_3cell_ci(row, d_efficiency);
1086         add_3cell(row, globals.points_played);
1087         rows.push(row);
1088
1089         return rows;
1090 }
1091
1092 function make_table_team_wide(players) {
1093         let globals = players['globals'];
1094
1095         let rows = [];
1096         {
1097                 let header = document.createElement('tr');
1098                 add_th(header, '');
1099                 add_th(header, 'Our team', 6);
1100                 add_th(header, 'Opponents', 6);
1101                 rows.push(header);
1102         }
1103
1104         // Turnovers.
1105         {
1106                 let row = document.createElement('tr');
1107                 let name = add_3cell(row, 'Turnovers generated', 'name');
1108                 add_3cell(row, globals.turnovers_won);
1109                 add_3cell(row, '');
1110                 add_3cell(row, globals.turnovers_lost);
1111                 add_3cell(row, '');
1112                 rows.push(row);
1113         }
1114
1115         // Clean holds.
1116         {
1117                 let row = document.createElement('tr');
1118                 let name = add_3cell(row, 'Clean holds', 'name');
1119                 let our_clean_holds = make_binomial_ci(globals.clean_holds, globals.offensive_points_completed, z);
1120                 let their_clean_holds = make_binomial_ci(globals.their_clean_holds, globals.defensive_points_completed, z);
1121                 our_clean_holds.desired = 0.3;  // Arbitrary.
1122                 our_clean_holds.format = 'percentage';
1123                 their_clean_holds.desired = 0.3;
1124                 their_clean_holds.format = 'percentage';
1125                 add_3cell(row, globals.clean_holds + ' / ' + globals.offensive_points_completed);
1126                 add_3cell_ci(row, our_clean_holds);
1127                 add_3cell(row, globals.their_clean_holds + ' / ' + globals.defensive_points_completed);
1128                 add_3cell_ci(row, their_clean_holds);
1129                 rows.push(row);
1130         }
1131
1132         // Clean breaks.
1133         {
1134                 let row = document.createElement('tr');
1135                 let name = add_3cell(row, 'Clean breaks', 'name');
1136                 let our_clean_breaks = make_binomial_ci(globals.clean_breaks, globals.defensive_points_completed, z);
1137                 let their_clean_breaks = make_binomial_ci(globals.their_clean_breaks, globals.offensive_points_completed, z);
1138                 our_clean_breaks.desired = 0.3;  // Arbitrary.
1139                 our_clean_breaks.format = 'percentage';
1140                 their_clean_breaks.desired = 0.3;
1141                 their_clean_breaks.format = 'percentage';
1142                 add_3cell(row, globals.clean_breaks + ' / ' + globals.defensive_points_completed);
1143                 add_3cell_ci(row, our_clean_breaks);
1144                 add_3cell(row, globals.their_clean_breaks + ' / ' + globals.offensive_points_completed);
1145                 add_3cell_ci(row, their_clean_breaks);
1146                 rows.push(row);
1147         }
1148
1149         // Touches. We only have information for our team here.
1150         {
1151                 let goals = 0;
1152                 for (const [q,p] of get_sorted_players(players)) {
1153                         if (q === 'globals') continue;
1154                         goals += p.goals;
1155                 }
1156                 let row = document.createElement('tr');
1157                 let name = add_3cell(row, 'Touches per possession (all)', 'name');
1158                 let touches = globals.touches_for_turnover + globals.touches_for_goal;
1159                 let possessions = goals + globals.turnovers_lost;
1160                 add_3cell(row, '');
1161                 add_3cell_ci(row, make_poisson_ci_large(touches, possessions, z));
1162                 add_3cell(row, '');
1163                 add_3cell(row, '');
1164                 rows.push(row);
1165
1166                 row = document.createElement('tr');
1167                 add_3cell(row, 'Touches per possession (goals)', 'name');
1168                 add_3cell(row, '');
1169                 add_3cell_ci(row, make_poisson_ci_large(globals.touches_for_goal, goals, z));
1170                 add_3cell(row, '');
1171                 add_3cell(row, '');
1172                 rows.push(row);
1173
1174                 row = document.createElement('tr');
1175                 add_3cell(row, 'Touches per possession (turnovers)', 'name');
1176                 add_3cell(row, '');
1177                 add_3cell_ci(row, make_poisson_ci_large(globals.touches_for_turnover, globals.turnovers_lost, z));
1178                 add_3cell(row, '');
1179                 add_3cell(row, '');
1180                 rows.push(row);
1181         }
1182
1183         // Time. Here we have (roughly) for both.
1184         {
1185                 let row = document.createElement('tr');
1186                 let name = add_3cell(row, 'Time per possession (all)', 'name');
1187                 let time = globals.time_for_turnover.concat(globals.time_for_goal);
1188                 let their_time = globals.their_time_for_turnover.concat(globals.their_time_for_goal);
1189                 add_3cell(row, '');
1190                 add_3cell_ci(row, make_ci_duration(time, z));
1191                 add_3cell(row, '');
1192                 add_3cell_ci(row, make_ci_duration(their_time, z));
1193                 rows.push(row);
1194
1195                 row = document.createElement('tr');
1196                 add_3cell(row, 'Time per possession (goals)', 'name');
1197                 add_3cell(row, '');
1198                 add_3cell_ci(row, make_ci_duration(globals.time_for_goal, z));
1199                 add_3cell(row, '');
1200                 add_3cell_ci(row, make_ci_duration(globals.their_time_for_goal, z));
1201                 rows.push(row);
1202
1203                 row = document.createElement('tr');
1204                 add_3cell(row, 'Time per possession (turnovers)', 'name');
1205                 add_3cell(row, '');
1206                 add_3cell_ci(row, make_ci_duration(globals.time_for_turnover, z));
1207                 add_3cell(row, '');
1208                 add_3cell_ci(row, make_ci_duration(globals.their_time_for_turnover, z));
1209                 rows.push(row);
1210         }
1211
1212         return rows;
1213 }
1214
1215 function make_table_offense(players) {
1216         let rows = [];
1217         {
1218                 let header = document.createElement('tr');
1219                 add_th(header, 'Player');
1220                 add_th(header, 'Goals');
1221                 add_th(header, 'Assists');
1222                 add_th(header, 'Hockey assists');
1223                 add_th(header, 'Throws');
1224                 add_th(header, 'Throwaways');
1225                 add_th(header, '%OK');
1226                 add_th(header, 'Catches');
1227                 add_th(header, 'Drops');
1228                 add_th(header, 'D-ed');
1229                 add_th(header, '%OK');
1230                 add_th(header, 'Stalls');
1231                 add_th(header, 'Soft +/-', 6);
1232                 rows.push(header);
1233         }
1234
1235         let goals = 0;
1236         let num_throws = 0;
1237         let throwaways = 0;
1238         let catches = 0;
1239         let drops = 0;
1240         let was_ds = 0;
1241         let stallouts = 0;
1242         for (const [q,p] of get_sorted_players(players)) {
1243                 if (q === 'globals') continue;
1244                 let throw_ok = make_binomial_ci(p.num_throws - p.throwaways, p.num_throws, z);
1245                 let catch_ok = make_binomial_ci(p.catches, p.catches + p.drops + p.was_ds, z);
1246
1247                 throw_ok.format = 'percentage';
1248                 catch_ok.format = 'percentage';
1249
1250                 // Desire at least 90% percentage. Fairly arbitrary.
1251                 throw_ok.desired = 0.9;
1252                 catch_ok.desired = 0.9;
1253
1254                 let row = document.createElement('tr');
1255                 add_3cell(row, p.name, 'name');  // TODO: number?
1256                 add_3cell(row, p.goals);
1257                 add_3cell(row, p.assists);
1258                 add_3cell(row, p.hockey_assists);
1259                 add_3cell(row, p.num_throws);
1260                 add_3cell(row, p.throwaways);
1261                 add_3cell_ci(row, throw_ok);
1262                 add_3cell(row, p.catches);
1263                 add_3cell(row, p.drops);
1264                 add_3cell(row, p.was_ds);
1265                 add_3cell_ci(row, catch_ok);
1266                 add_3cell(row, p.stallouts);
1267                 add_3cell(row, '+' + p.offensive_soft_plus);
1268                 add_3cell(row, '-' + p.offensive_soft_minus);
1269                 row.dataset.player = q;
1270                 rows.push(row);
1271
1272                 goals += p.goals;
1273                 num_throws += p.num_throws;
1274                 throwaways += p.throwaways;
1275                 catches += p.catches;
1276                 drops += p.drops;
1277                 was_ds += p.was_ds;
1278                 stallouts += p.stallouts;
1279         }
1280
1281         // Globals.
1282         let throw_ok = make_binomial_ci(num_throws - throwaways, num_throws, z);
1283         let catch_ok = make_binomial_ci(catches, catches + drops + was_ds, z);
1284         throw_ok.format = 'percentage';
1285         catch_ok.format = 'percentage';
1286         throw_ok.desired = 0.9;
1287         catch_ok.desired = 0.9;
1288
1289         let row = document.createElement('tr');
1290         add_3cell(row, '');
1291         add_3cell(row, goals);
1292         add_3cell(row, '');
1293         add_3cell(row, '');
1294         add_3cell(row, num_throws);
1295         add_3cell(row, throwaways);
1296         add_3cell_ci(row, throw_ok);
1297         add_3cell(row, catches);
1298         add_3cell(row, drops);
1299         add_3cell(row, was_ds);
1300         add_3cell_ci(row, catch_ok);
1301         add_3cell(row, stallouts);
1302         add_3cell(row, '');
1303         add_3cell(row, '');
1304         rows.push(row);
1305
1306         return rows;
1307 }
1308
1309 function make_table_defense(players) {
1310         let rows = [];
1311         {
1312                 let header = document.createElement('tr');
1313                 add_th(header, 'Player');
1314                 add_th(header, 'Ds');
1315                 add_th(header, 'Pulls');
1316                 add_th(header, 'OOB pulls');
1317                 add_th(header, 'OOB%');
1318                 add_th(header, 'Avg. hang time (IB)');
1319                 add_th(header, 'Callahans');
1320                 add_th(header, 'Soft +/-', 6);
1321                 rows.push(header);
1322         }
1323
1324         let defenses = 0;
1325         let pulls = 0;
1326         let oob_pulls = 0;
1327         let sum_sum_time = 0;
1328         let callahans = 0;
1329
1330         for (const [q,p] of get_sorted_players(players)) {
1331                 if (q === 'globals') continue;
1332                 let sum_time = 0;
1333                 for (const t of p.pull_times) {
1334                         sum_time += t;
1335                 }
1336                 let avg_time = 1e-3 * sum_time / (p.pulls - p.oob_pulls);
1337                 let oob_pct = 100 * p.oob_pulls / p.pulls;
1338
1339                 let ci_oob = make_binomial_ci(p.oob_pulls, p.pulls, z);
1340                 ci_oob.format = 'percentage';
1341                 ci_oob.desired = 0.2;  // Arbitrary.
1342                 ci_oob.inverted = true;
1343
1344                 let row = document.createElement('tr');
1345                 add_3cell(row, p.name, 'name');  // TODO: number?
1346                 add_3cell(row, p.defenses);
1347                 add_3cell(row, p.pulls);
1348                 add_3cell(row, p.oob_pulls);
1349                 add_3cell_ci(row, ci_oob);
1350                 if (p.pulls > p.oob_pulls) {
1351                         add_3cell(row, avg_time.toFixed(1) + ' sec');
1352                 } else {
1353                         add_3cell(row, 'N/A');
1354                 }
1355                 add_3cell(row, p.callahans);
1356                 add_3cell(row, '+' + p.defensive_soft_plus);
1357                 add_3cell(row, '-' + p.defensive_soft_minus);
1358                 row.dataset.player = q;
1359                 rows.push(row);
1360
1361                 defenses += p.defenses;
1362                 pulls += p.pulls;
1363                 oob_pulls += p.oob_pulls;
1364                 sum_sum_time += sum_time;
1365                 callahans += p.callahans;
1366         }
1367
1368         // Globals.
1369         let ci_oob = make_binomial_ci(oob_pulls, pulls, z);
1370         ci_oob.format = 'percentage';
1371         ci_oob.desired = 0.2;  // Arbitrary.
1372         ci_oob.inverted = true;
1373
1374         let avg_time = 1e-3 * sum_sum_time / (pulls - oob_pulls);
1375         let oob_pct = 100 * oob_pulls / pulls;
1376
1377         let row = document.createElement('tr');
1378         add_3cell(row, '');
1379         add_3cell(row, defenses);
1380         add_3cell(row, pulls);
1381         add_3cell(row, oob_pulls);
1382         add_3cell_ci(row, ci_oob);
1383         if (pulls > oob_pulls) {
1384                 add_3cell(row, avg_time.toFixed(1) + ' sec');
1385         } else {
1386                 add_3cell(row, 'N/A');
1387         }
1388         add_3cell(row, callahans);
1389         add_3cell(row, '');
1390         add_3cell(row, '');
1391         rows.push(row);
1392
1393         return rows;
1394 }
1395
1396 function make_table_playing_time(players) {
1397         let rows = [];
1398         {
1399                 let header = document.createElement('tr');
1400                 add_th(header, 'Player');
1401                 add_th(header, 'Points played');
1402                 add_th(header, 'Time played');
1403                 add_th(header, 'O time');
1404                 add_th(header, 'D time');
1405                 add_th(header, 'Time on field');
1406                 add_th(header, 'O points');
1407                 add_th(header, 'D points');
1408                 rows.push(header);
1409         }
1410
1411         for (const [q,p] of get_sorted_players(players)) {
1412                 if (q === 'globals') continue;
1413                 let row = document.createElement('tr');
1414                 add_3cell(row, p.name, 'name');  // TODO: number?
1415                 add_3cell(row, p.points_played);
1416                 add_3cell(row, Math.floor(p.playing_time_ms / 60000) + ' min');
1417                 add_3cell(row, Math.floor(p.offensive_playing_time_ms / 60000) + ' min');
1418                 add_3cell(row, Math.floor(p.defensive_playing_time_ms / 60000) + ' min');
1419                 add_3cell(row, Math.floor(p.field_time_ms / 60000) + ' min');
1420                 add_3cell(row, p.offensive_points_completed);
1421                 add_3cell(row, p.defensive_points_completed);
1422                 row.dataset.player = q;
1423                 rows.push(row);
1424         }
1425
1426         // Globals.
1427         let globals = players['globals'];
1428         let row = document.createElement('tr');
1429         add_3cell(row, '');
1430         add_3cell(row, globals.points_played);
1431         add_3cell(row, Math.floor(globals.playing_time_ms / 60000) + ' min');
1432         add_3cell(row, Math.floor(globals.offensive_playing_time_ms / 60000) + ' min');
1433         add_3cell(row, Math.floor(globals.defensive_playing_time_ms / 60000) + ' min');
1434         add_3cell(row, Math.floor(globals.field_time_ms / 60000) + ' min');
1435         add_3cell(row, globals.offensive_points_completed);
1436         add_3cell(row, globals.defensive_points_completed);
1437         rows.push(row);
1438
1439         return rows;
1440 }
1441
1442 function make_table_per_point(players) {
1443         let rows = [];
1444         {
1445                 let header = document.createElement('tr');
1446                 add_th(header, 'Player');
1447                 add_th(header, 'Goals');
1448                 add_th(header, 'Assists');
1449                 add_th(header, 'Hockey assists');
1450                 add_th(header, 'Ds');
1451                 add_th(header, 'Throwaways');
1452                 add_th(header, 'Recv. errors');
1453                 add_th(header, 'Touches');
1454                 rows.push(header);
1455         }
1456
1457         let goals = 0;
1458         let assists = 0;
1459         let hockey_assists = 0;
1460         let defenses = 0;
1461         let throwaways = 0;
1462         let receiver_errors = 0;
1463         let touches = 0;
1464         for (const [q,p] of get_sorted_players(players)) {
1465                 if (q === 'globals') continue;
1466
1467                 // Can only happen once per point, so these are binomials.
1468                 let ci_goals = make_binomial_ci(p.goals, p.points_played, z);
1469                 let ci_assists = make_binomial_ci(p.assists, p.points_played, z);
1470                 let ci_hockey_assists = make_binomial_ci(p.hockey_assists, p.points_played, z);
1471                 // Arbitrarily desire at least 10% (not everybody can score or assist).
1472                 ci_goals.desired = 0.1;
1473                 ci_assists.desired = 0.1;
1474                 ci_hockey_assists.desired = 0.1;
1475
1476                 let row = document.createElement('tr');
1477                 add_3cell(row, p.name, 'name');  // TODO: number?
1478                 add_3cell_ci(row, ci_goals);
1479                 add_3cell_ci(row, ci_assists);
1480                 add_3cell_ci(row, ci_hockey_assists);
1481                 add_3cell_ci(row, make_poisson_ci(p.defenses, p.points_played, z));
1482                 add_3cell_ci(row, make_poisson_ci(p.throwaways, p.points_played, z, true));
1483                 add_3cell_ci(row, make_poisson_ci(p.drops + p.was_ds, p.points_played, z, true));
1484                 if (p.points_played > 0) {
1485                         add_3cell(row, p.touches == 0 ? 0 : (p.touches / p.points_played).toFixed(2));
1486                 } else {
1487                         add_3cell(row, 'N/A');
1488                 }
1489                 row.dataset.player = q;
1490                 rows.push(row);
1491
1492                 goals += p.goals;
1493                 assists += p.assists;
1494                 hockey_assists += p.hockey_assists;
1495                 defenses += p.defenses;
1496                 throwaways += p.throwaways;
1497                 receiver_errors += p.drops + p.was_ds;
1498                 touches += p.touches;
1499         }
1500
1501         // Globals.
1502         let globals = players['globals'];
1503         let row = document.createElement('tr');
1504         add_3cell(row, '');
1505         if (globals.points_played > 0) {
1506                 let ci_goals = make_binomial_ci(goals, globals.points_played, z);
1507                 let ci_assists = make_binomial_ci(assists, globals.points_played, z);
1508                 let ci_hockey_assists = make_binomial_ci(hockey_assists, globals.points_played, z);
1509                 ci_goals.desired = 0.5;
1510                 ci_assists.desired = 0.5;
1511                 ci_hockey_assists.desired = 0.5;
1512
1513                 add_3cell_ci(row, ci_goals);
1514                 add_3cell_ci(row, ci_assists);
1515                 add_3cell_ci(row, ci_hockey_assists);
1516
1517                 add_3cell_ci(row, make_poisson_ci(defenses, globals.points_played, z));
1518                 add_3cell_ci(row, make_poisson_ci(throwaways, globals.points_played, z, true));
1519                 add_3cell_ci(row, make_poisson_ci(receiver_errors, globals.points_played, z, true));
1520
1521                 add_3cell(row, touches == 0 ? 0 : (touches / globals.points_played).toFixed(2));
1522         } else {
1523                 add_3cell_with_filler_ci(row, 'N/A');
1524                 add_3cell_with_filler_ci(row, 'N/A');
1525                 add_3cell_with_filler_ci(row, 'N/A');
1526                 add_3cell_with_filler_ci(row, 'N/A');
1527                 add_3cell_with_filler_ci(row, 'N/A');
1528                 add_3cell_with_filler_ci(row, 'N/A');
1529                 add_3cell(row, 'N/A');
1530         }
1531         rows.push(row);
1532
1533         return rows;
1534 }
1535
1536 function open_filter_menu(click_to_add_div) {
1537         document.getElementById('filter-submenu').style.display = 'none';
1538         let filter_div = click_to_add_div.parentElement;
1539         let filter_id = filter_div.dataset.filterId;
1540
1541         let menu = document.getElementById('filter-add-menu');
1542         menu.parentElement.removeChild(menu);
1543         filter_div.appendChild(menu);
1544         menu.style.display = 'block';
1545         menu.replaceChildren();
1546
1547         // Place the menu directly under the “click to add” label;
1548         // we don't anchor it since that label will move around
1549         // and the menu shouldn't.
1550         let rect = click_to_add_div.getBoundingClientRect();
1551         menu.style.left = rect.left + 'px';
1552         menu.style.top = (rect.bottom + 10) + 'px';
1553
1554         let filterset = global_filters[filter_id];
1555         if (filterset === undefined) {
1556                 global_filters[filter_id] = filterset = [];
1557         }
1558
1559         add_menu_item(filter_div, filterset, menu, 0, 'match', 'Match (any)');
1560         add_menu_item(filter_div, filterset, menu, 1, 'player_any', 'Player on field (any)');
1561         add_menu_item(filter_div, filterset, menu, 2, 'player_all', 'Player on field (all)');
1562         add_menu_item(filter_div, filterset, menu, 3, 'formation_offense', 'Offense played (any)');
1563         add_menu_item(filter_div, filterset, menu, 4, 'formation_defense', 'Defense played (any)');
1564         add_menu_item(filter_div, filterset, menu, 5, 'starting_on', 'Starting on');
1565         add_menu_item(filter_div, filterset, menu, 6, 'gender_ratio', 'Gender ratio');
1566 }
1567
1568 function add_menu_item(filter_div, filterset, menu, menu_idx, filter_type, title) {
1569         let item = document.createElement('div');
1570         item.classList.add('option');
1571         item.appendChild(document.createTextNode(title));
1572
1573         let arrow = document.createElement('div');
1574         arrow.classList.add('arrow');
1575         arrow.textContent = '▸';
1576         item.appendChild(arrow);
1577
1578         menu.appendChild(item);
1579
1580         item.addEventListener('click', (e) => { show_submenu(filter_div, filterset, menu_idx, null, filter_type); });
1581 }
1582
1583 function find_all_ratios(json)
1584 {
1585         let ratios = {};
1586         let players = {};
1587         for (const player of json['players']) {
1588                 players[player['player_id']] = {
1589                         'gender': player['gender'],
1590                         'last_point_seen': null,
1591                 };
1592         }
1593         for (const match of json['matches']) {
1594                 for (const [q,p] of Object.entries(players)) {
1595                         p.on_field_since = null;
1596                 }
1597                 for (const e of match['events']) {
1598                         let p = players[e['player']];
1599                         let type = e['type'];
1600                         if (type === 'in') {
1601                                 p.on_field_since = 1;
1602                         } else if (type === 'out') {
1603                                 p.on_field_since = null;
1604                         } else if (type === 'pull' || type == 'their_pull') {  // We assume no cross-gender subs for now.
1605                                 let code = find_gender_ratio_code(players);
1606                                 if (ratios[code] === undefined) {
1607                                         ratios[code] = code;
1608                                         if (code !== '4 F, 3 M' && code !== '4 M, 3 F' && code !== '3 M, 2 F' && code !== '3 F, 2 M') {
1609                                                 console.log('Unexpected gender ratio ' + code + ' first seen at: ' +
1610                                                             match['description'] + ', ' + format_time(e['t']));
1611                                         }
1612                                 }
1613                         }
1614                 }
1615         }
1616         return ratios;
1617 }
1618
1619 function show_submenu(filter_div, filterset, menu_idx, pill, filter_type) {
1620         let submenu = document.getElementById('filter-submenu');
1621
1622         // Move to the same place as the top-level menu.
1623         submenu.parentElement.removeChild(submenu);
1624         document.getElementById('filter-add-menu').parentElement.appendChild(submenu);
1625
1626         let subitems = [];
1627         const filter = find_filter(filterset, filter_type);
1628
1629         let choices = [];
1630         if (filter_type === 'match') {
1631                 for (const match of global_json['matches']) {
1632                         choices.push({
1633                                 'title': match['description'],
1634                                 'id': match['match_id']
1635                         });
1636                 }
1637         } else if (filter_type === 'player_any' || filter_type === 'player_all') {
1638                 for (const player of global_json['players']) {
1639                         choices.push({
1640                                 'title': player['name'],
1641                                 'id': player['player_id']
1642                         });
1643                 }
1644         } else if (filter_type === 'formation_offense') {
1645                 choices.push({
1646                         'title': '(None/unknown)',
1647                         'id': 0,
1648                 });
1649                 for (const formation of global_json['formations']) {
1650                         if (formation['offense']) {
1651                                 choices.push({
1652                                         'title': formation['name'],
1653                                         'id': formation['formation_id']
1654                                 });
1655                         }
1656                 }
1657         } else if (filter_type === 'formation_defense') {
1658                 choices.push({
1659                         'title': '(None/unknown)',
1660                         'id': 0,
1661                 });
1662                 for (const formation of global_json['formations']) {
1663                         if (!formation['offense']) {
1664                                 choices.push({
1665                                         'title': formation['name'],
1666                                         'id': formation['formation_id']
1667                                 });
1668                         }
1669                 }
1670         } else if (filter_type === 'starting_on') {
1671                 choices.push({
1672                         'title': 'Offense',
1673                         'id': false,  // last_pull_was_ours
1674                 });
1675                 choices.push({
1676                         'title': 'Defense',
1677                         'id': true,  // last_pull_was_ours
1678                 });
1679         } else if (filter_type === 'gender_ratio') {
1680                 for (const [title, id] of Object.entries(find_all_ratios(global_json)).sort()) {
1681                         choices.push({
1682                                 'title': title,
1683                                 'id': id,
1684                         });
1685                 }
1686         }
1687
1688         let choice_set = new Set();
1689         for (const choice of choices) {
1690                 choice_set.add(choice.id);
1691         }
1692
1693         for (const choice of choices) {
1694                 let label = document.createElement('label');
1695
1696                 let subitem = document.createElement('div');
1697                 subitem.classList.add('option');
1698
1699                 let check = document.createElement('input');
1700                 check.setAttribute('type', 'checkbox');
1701                 check.setAttribute('id', 'choice' + choice.id);
1702                 if (filter !== null && filter.elements.has(choice.id)) {
1703                         check.setAttribute('checked', 'checked');
1704                 }
1705                 check.addEventListener('change', (e) => { checkbox_changed(filter_div, filterset, e, filter_type, choice.id, choice_set); });
1706
1707                 subitem.appendChild(check);
1708                 subitem.appendChild(document.createTextNode(choice.title));
1709
1710                 label.appendChild(subitem);
1711                 subitems.push(label);
1712         }
1713
1714         // If meaningful (it's not for player_all, since all data for that would be
1715         // the same anyway), show the split checkbox.
1716         if (choices.length > 1 && filter_type !== 'player_all') {
1717                 let label = document.createElement('label');
1718
1719                 let subitem = document.createElement('div');
1720                 subitem.classList.add('option');
1721
1722                 let check = document.createElement('input');
1723                 check.setAttribute('type', 'checkbox');
1724                 check.setAttribute('id', 'choice_split');
1725                 if (filter !== null && filter.split) {
1726                         check.setAttribute('checked', 'checked');
1727                 }
1728                 check.addEventListener('change', (e) => { checkbox_changed(filter_div, filterset, e, filter_type, 'split', choice_set); });
1729
1730                 subitem.appendChild(check);
1731                 let text_span = document.createElement('span');  // So that we can style its disabling later.
1732                 text_span.appendChild(document.createTextNode('Split'));
1733                 subitem.appendChild(text_span);
1734                 subitem.style.borderTop = '1px solid #ddd';
1735
1736                 label.appendChild(subitem);
1737                 subitems.push(label);
1738         }
1739
1740         submenu.replaceChildren(...subitems);
1741         submenu.style.display = 'block';
1742
1743         if (pill !== null) {
1744                 let rect = pill.getBoundingClientRect();
1745                 submenu.style.top = (rect.bottom + 10) + 'px';
1746                 submenu.style.left = rect.left + 'px';
1747         } else {
1748                 // Position just outside the selected menu.
1749                 let rect = document.getElementById('filter-add-menu').getBoundingClientRect();
1750                 submenu.style.top = (rect.top + menu_idx * 35) + 'px';
1751                 submenu.style.left = (rect.right - 1) + 'px';
1752         }
1753 }
1754
1755 // Find the right filter, if it exists.
1756 function find_filter(filterset, filter_type) {
1757         for (let f of filterset) {
1758                 if (f.type === filter_type) {
1759                         return f;
1760                 }
1761         }
1762         return null;
1763 }
1764
1765 // Equivalent to Array.prototype.filter, but in-place.
1766 function inplace_filter(arr, cond) {
1767         let j = 0;
1768         for (let i = 0; i < arr.length; ++i) {
1769                 if (cond(arr[i])) {
1770                         arr[j++] = arr[i];
1771                 }
1772         }
1773         arr.length = j;
1774 }
1775
1776 function add_new_filterset() {
1777         let template = document.querySelector('.filter');  // First one is fine.
1778         let div = template.cloneNode(true);
1779         let add_menu = div.querySelector('#filter-add-menu');
1780         if (add_menu !== null) {
1781                 div.removeChild(add_menu);
1782         }
1783         let submenu = div.querySelector('#filter-submenu');
1784         if (submenu !== null) {
1785                 div.removeChild(submenu);
1786         }
1787         div.querySelector('.filters').replaceChildren();
1788         div.dataset.filterId = next_filterset_id++;
1789         template.parentElement.appendChild(div);
1790 }
1791
1792 function try_gc_filter_menus(cheap) {
1793         let empties = [];
1794         let divs = [];
1795         for (const filter_div of document.querySelectorAll('.filter')) {
1796                 let id = filter_div.dataset.filterId;
1797                 divs.push(filter_div);
1798                 empties.push(global_filters[id] === undefined || global_filters[id].length === 0);
1799         }
1800         let last_div = divs[empties.length - 1];
1801         if (cheap) {
1802                 // See if we have two empty filter lists at the bottom of the list;
1803                 // if so, we can remove one without it looking funny in the UI.
1804                 // If not, we'll have to wait until closing the menu.
1805                 // (The menu is positioned at the second-last one, so we can
1806                 // remove the last one without issue.)
1807                 if (empties.length >= 2 && empties[empties.length - 2] && empties[empties.length - 1]) {
1808                         delete global_filters[last_div.dataset.filterId];
1809                         last_div.parentElement.removeChild(last_div);
1810                 }
1811         } else {
1812                 // This is a different situation from try_cheap_gc(), where we should
1813                 // remove the one _not_ last. We might need to move the menu to the last one,
1814                 // though, so it doesn't get lost.
1815                 for (let i = 0; i < empties.length - 1; ++i) {
1816                         if (!empties[i]) {
1817                                 continue;
1818                         }
1819                         let div = divs[i];
1820                         delete global_filters[div.dataset.filterId];
1821                         let add_menu = div.querySelector('#filter-add-menu');
1822                         if (add_menu !== null) {
1823                                 div.removeChild(add_menu);
1824                                 last_div.appendChild(add_menu);
1825                         }
1826                         let submenu = div.querySelector('#filter-submenu');
1827                         if (submenu !== null) {
1828                                 div.removeChild(submenu);
1829                                 last_div.appendChild(submenu);
1830                         }
1831                         div.parentElement.removeChild(div);
1832                 }
1833         }
1834 }
1835
1836 function checkbox_changed(filter_div, filterset, e, filter_type, id, choices) {
1837         let filter = find_filter(filterset, filter_type);
1838         let pills_div = filter_div.querySelector('.filters');
1839         if (e.target.checked) {
1840                 // See if we must create a new empty filterset (since this went from
1841                 // empty to non-empty).
1842                 if (filterset.length === 0) {
1843                         add_new_filterset();
1844                 }
1845
1846                 // See if we must add a new filter to the list.
1847                 if (filter === null) {
1848                         filter = {
1849                                 'type': filter_type,
1850                                 'elements': new Set(),
1851                                 'choices': choices,
1852                                 'split': false,
1853                         };
1854                         if (id === 'split') {
1855                                 filter.split = true;
1856                         } else {
1857                                 filter.elements.add(id);
1858                         }
1859                         filter.pill = make_filter_pill(filter_div, filterset, filter);
1860                         filterset.push(filter);
1861                         pills_div.appendChild(filter.pill);
1862                 } else {
1863                         if (id === 'split') {
1864                                 filter.split = true;
1865                         } else {
1866                                 filter.elements.add(id);
1867                         }
1868                         let new_pill = make_filter_pill(filter_div, filterset, filter);
1869                         pills_div.replaceChild(new_pill, filter.pill);
1870                         filter.pill = new_pill;
1871                 }
1872         } else {
1873                 if (id === 'split') {
1874                         filter.split = false;
1875                 } else {
1876                         filter.elements.delete(id);
1877                 }
1878                 if (filter.elements.size === 0) {
1879                         pills_div.removeChild(filter.pill);
1880                         inplace_filter(filterset, f => f !== filter);
1881
1882                         if (filterset.length == 0) {
1883                                 try_gc_filter_menus(true);
1884                         }
1885                 } else {
1886                         let new_pill = make_filter_pill(filter_div, filterset, filter);
1887                         pills_div.replaceChild(new_pill, filter.pill);
1888                         filter.pill = new_pill;
1889                 }
1890         }
1891         let choice_split = document.getElementById('choice_split');
1892         if (filter.elements.size === 1) {
1893                 choice_split.nextSibling.style.opacity = 0.2;
1894                 choice_split.setAttribute('disabled', 'disabled');
1895         } else {
1896                 choice_split.nextSibling.style.opacity = 1.0;
1897                 choice_split.removeAttribute('disabled');
1898         }
1899
1900         process_matches(global_json, global_filters);
1901 }
1902
1903 function make_filter_pill(filter_div, filterset, filter) {
1904         let pill = document.createElement('div');
1905         pill.classList.add('filter-pill');
1906         let text;
1907         if (filter.type === 'match') {
1908                 text = 'Match: ';
1909
1910                 let all_names = [];
1911                 for (const match_id of filter.elements) {
1912                         all_names.push(find_match(match_id)['description']);
1913                 }
1914                 let common_prefix = find_common_prefix_of_all(all_names);
1915                 if (common_prefix !== null) {
1916                         text += common_prefix + '(';
1917                 }
1918
1919                 let first = true;
1920                 let sorted_match_id = Array.from(filter.elements).sort((a, b) => a - b);
1921                 for (const match_id of sorted_match_id) {
1922                         if (!first) {
1923                                 text += ', ';
1924                         }
1925                         let desc = find_match(match_id)['description'];
1926                         if (common_prefix === null) {
1927                                 text += desc;
1928                         } else {
1929                                 text += desc.substr(common_prefix.length);
1930                         }
1931                         first = false;
1932                 }
1933
1934                 if (common_prefix !== null) {
1935                         text += ')';
1936                 }
1937         } else if (filter.type === 'player_any') {
1938                 text = 'Player (any): ';
1939                 let sorted_players = Array.from(filter.elements).sort((a, b) => player_pos(a) - player_pos(b));
1940                 let first = true;
1941                 for (const player_id of sorted_players) {
1942                         if (!first) {
1943                                 text += ', ';
1944                         }
1945                         text += find_player(player_id)['name'];
1946                         first = false;
1947                 }
1948         } else if (filter.type === 'player_all') {
1949                 text = 'Players: ';
1950                 let sorted_players = Array.from(filter.elements).sort((a, b) => player_pos(a) - player_pos(b));
1951                 let first = true;
1952                 for (const player_id of sorted_players) {
1953                         if (!first) {
1954                                 text += ' AND ';
1955                         }
1956                         text += find_player(player_id)['name'];
1957                         first = false;
1958                 }
1959         } else if (filter.type === 'formation_offense' || filter.type === 'formation_defense') {
1960                 const offense = (filter.type === 'formation_offense');
1961                 if (offense) {
1962                         text = 'Offense: ';
1963                 } else {
1964                         text = 'Defense: ';
1965                 }
1966
1967                 let all_names = [];
1968                 for (const formation_id of filter.elements) {
1969                         all_names.push(find_formation(formation_id)['name']);
1970                 }
1971                 let common_prefix = find_common_prefix_of_all(all_names);
1972                 if (common_prefix !== null) {
1973                         text += common_prefix + '(';
1974                 }
1975
1976                 let first = true;
1977                 let sorted_formation_id = Array.from(filter.elements).sort((a, b) => a - b);
1978                 for (const formation_id of sorted_formation_id) {
1979                         if (!first) {
1980                                 ktext += ', ';
1981                         }
1982                         let desc = find_formation(formation_id)['name'];
1983                         if (common_prefix === null) {
1984                                 text += desc;
1985                         } else {
1986                                 text += desc.substr(common_prefix.length);
1987                         }
1988                         first = false;
1989                 }
1990
1991                 if (common_prefix !== null) {
1992                         text += ')';
1993                 }
1994         } else if (filter.type === 'starting_on') {
1995                 text = 'Starting on: ';
1996
1997                 if (filter.elements.has(false) && filter.elements.has(true)) {
1998                         text += 'Any';
1999                 } else if (filter.elements.has(false)) {
2000                         text += 'Offense';
2001                 } else {
2002                         text += 'Defense';
2003                 }
2004         } else if (filter.type === 'gender_ratio') {
2005                 text = 'Gender: ';
2006
2007                 let first = true;
2008                 for (const name of Array.from(filter.elements).sort()) {
2009                         if (!first) {
2010                                 text += '; ';
2011                         }
2012                         text += name;  // FIXME
2013                         first = false;
2014                 }
2015         }
2016         if (filter.split && filter.elements.size !== 1) {
2017                 text += ' (split)';
2018         }
2019
2020         let text_node = document.createElement('span');
2021         text_node.innerText = text;
2022         text_node.addEventListener('click', (e) => show_submenu(filter_div, filterset, null, pill, filter.type));
2023         pill.appendChild(text_node);
2024
2025         pill.appendChild(document.createTextNode(' '));
2026
2027         let delete_node = document.createElement('span');
2028         delete_node.innerText = '✖';
2029         delete_node.addEventListener('click', (e) => {
2030                 // Delete this filter entirely.
2031                 pill.parentElement.removeChild(pill);
2032                 inplace_filter(filterset, f => f !== filter);
2033                 if (filterset.length == 0) {
2034                         try_gc_filter_menus(false);
2035                 }
2036                 process_matches(global_json, global_filters);
2037
2038                 let add_menu = document.getElementById('filter-add-menu');
2039                 let add_submenu = document.getElementById('filter-submenu');
2040                 add_menu.style.display = 'none';
2041                 add_submenu.style.display = 'none';
2042         });
2043         pill.appendChild(delete_node);
2044         pill.style.cursor = 'pointer';
2045
2046         return pill;
2047 }
2048
2049 function make_filter_marker(filterset) {
2050         let text = '';
2051         for (const filter of filterset) {
2052                 if (text !== '') {
2053                         text += ',';
2054                 }
2055                 if (filter.type === 'match') {
2056                         let all_names = [];
2057                         for (const match of global_json['matches']) {
2058                                 all_names.push(match['description']);
2059                         }
2060                         let common_prefix = find_common_prefix_of_all(all_names);
2061
2062                         let sorted_match_id = Array.from(filter.elements).sort((a, b) => a - b);
2063                         for (const match_id of sorted_match_id) {
2064                                 let desc = find_match(match_id)['description'];
2065                                 if (common_prefix === null) {
2066                                         text += desc.substr(0, 3);
2067                                 } else {
2068                                         text += desc.substr(common_prefix.length, 3);
2069                                 }
2070                         }
2071                 } else if (filter.type === 'player_any' || filter.type === 'player_all') {
2072                         let sorted_players = Array.from(filter.elements).sort((a, b) => player_pos(a) - player_pos(b));
2073                         for (const player_id of sorted_players) {
2074                                 text += find_player(player_id)['name'].substr(0, 3);
2075                         }
2076                 } else if (filter.type === 'formation_offense' || filter.type === 'formation_defense') {
2077                         let sorted_formation_id = Array.from(filter.elements).sort((a, b) => a - b);
2078                         for (const formation_id of sorted_formation_id) {
2079                                 text += find_formation(formation_id)['name'].substr(0, 3);
2080                         }
2081                 } else if (filter.type === 'starting_on') {
2082                         if (filter.elements.has(false) && filter.elements.has(true)) {
2083                                 // Nothing.
2084                         } else if (filter.elements.has(false)) {
2085                                 text += 'O';
2086                         } else {
2087                                 text += 'D';
2088                         }
2089                 } else if (filter.type === 'gender_ratio') {
2090                         let first = true;
2091                         for (const name of Array.from(filter.elements).sort()) {
2092                                 if (!first) {
2093                                         text += '; ';
2094                                 }
2095                                 text += name.replaceAll(' ', '').substr(0, 2);  // 4 F, 3M -> 4 F.
2096                                 first = false;
2097                         }
2098                 }
2099         }
2100         return text;
2101 }
2102
2103 function find_common_prefix(a, b) {
2104         let ret = '';
2105         for (let i = 0; i < Math.min(a.length, b.length); ++i) {
2106                 if (a[i] === b[i]) {
2107                         ret += a[i];
2108                 } else {
2109                         break;
2110                 }
2111         }
2112         return ret;
2113 }
2114
2115 function find_common_prefix_of_all(values) {
2116         if (values.length < 2) {
2117                 return null;
2118         }
2119         let common_prefix = null;
2120         for (const desc of values) {
2121                 if (common_prefix === null) {
2122                         common_prefix = desc;
2123                 } else {
2124                         common_prefix = find_common_prefix(common_prefix, desc);
2125                 }
2126         }
2127         if (common_prefix.length >= 3) {
2128                 return common_prefix;
2129         } else {
2130                 return null;
2131         }
2132 }
2133
2134 function find_match(match_id) {
2135         for (const match of global_json['matches']) {
2136                 if (match['match_id'] === match_id) {
2137                         return match;
2138                 }
2139         }
2140         return null;
2141 }
2142
2143 function find_formation(formation_id) {
2144         for (const formation of global_json['formations']) {
2145                 if (formation['formation_id'] === formation_id) {
2146                         return formation;
2147                 }
2148         }
2149         return null;
2150 }
2151
2152 function find_player(player_id) {
2153         for (const player of global_json['players']) {
2154                 if (player['player_id'] === player_id) {
2155                         return player;
2156                 }
2157         }
2158         return null;
2159 }
2160
2161 function player_pos(player_id) {
2162         let i = 0;
2163         for (const player of global_json['players']) {
2164                 if (player['player_id'] === player_id) {
2165                         return i;
2166                 }
2167                 ++i;
2168         }
2169         return null;
2170 }
2171
2172 function keep_match(match_id, filters) {
2173         for (const filter of filters) {
2174                 if (filter.type === 'match') {
2175                         return filter.elements.has(match_id);
2176                 }
2177         }
2178         return true;
2179 }
2180
2181 // Returns a map of e.g. F => 4, M => 3.
2182 function find_gender_ratio(players) {
2183         let map = {};
2184         for (const [q,p] of Object.entries(players)) {
2185                 if (p.on_field_since === null) {
2186                         continue;
2187                 }
2188                 let gender = p.gender;
2189                 if (gender === '' || gender === undefined || gender === null) {
2190                         gender = '?';
2191                 }
2192                 if (map[gender] === undefined) {
2193                         map[gender] = 1;
2194 q               } else {
2195                         ++map[gender];
2196                 }
2197         }
2198         return map;
2199 }
2200
2201 function find_gender_ratio_code(players) {
2202         let map = find_gender_ratio(players);
2203         let all_genders = Array.from(Object.keys(map)).sort(
2204                 (a,b) => {
2205                         if (map[a] !== map[b]) {
2206                                 return map[b] - map[a];  // Reverse numeric.
2207                         } else if (a < b) {
2208                                 return -1;
2209                         } else if (a > b) {
2210                                 return 1;
2211                         } else {
2212                                 return 0;
2213                         }
2214                 });
2215         let code = '';
2216         for (const g of all_genders) {
2217                 if (code !== '') {
2218                         code += ', ';
2219                 }
2220                 code += map[g];
2221                 code += ' ';
2222                 code += g;
2223         }
2224         return code;
2225 }
2226
2227 // null if none (e.g., if playing 3–3).
2228 function find_predominant_gender(players) {
2229         let max = 0;
2230         let predominant_gender = null;
2231         for (const [gender, num] of Object.entries(find_gender_ratio(players))) {
2232                 if (num > max) {
2233                         max = num;
2234                         predominant_gender = gender;
2235                 } else if (num == max) {
2236                         predominant_gender = null;  // At least two have the same.
2237                 }
2238         }
2239         return predominant_gender;
2240 }
2241
2242 function find_num_players_on_field(players) {
2243         let num = 0;
2244         for (const [q,p] of Object.entries(players)) {
2245                 if (p.on_field_since !== null) {
2246                         ++num;
2247                 }
2248         }
2249         return num;
2250 }
2251
2252 function filter_passes(players, formations_used_this_point, last_pull_was_ours, filter) {
2253         if (filter.type === 'player_any') {
2254                 for (const p of Array.from(filter.elements)) {
2255                         if (players[p].on_field_since !== null) {
2256                                 return true;
2257                         }
2258                 }
2259                 return false;
2260         } else if (filter.type === 'player_all') {
2261                 for (const p of Array.from(filter.elements)) {
2262                         if (players[p].on_field_since === null) {
2263                                 return false;
2264                         }
2265                 }
2266                 return true;
2267         } else if (filter.type === 'formation_offense' || filter.type === 'formation_defense') {
2268                 for (const f of Array.from(filter.elements)) {
2269                         if (formations_used_this_point.has(f)) {
2270                                 return true;
2271                         }
2272                 }
2273                 return false;
2274         } else if (filter.type === 'starting_on') {
2275                 return filter.elements.has(last_pull_was_ours);
2276         } else if (filter.type === 'gender_ratio') {
2277                 return filter.elements.has(find_gender_ratio_code(players));
2278         }
2279         return true;
2280 }
2281
2282 function keep_event(players, formations_used_this_point, last_pull_was_ours, filters) {
2283         for (const filter of filters) {
2284                 if (!filter_passes(players, formations_used_this_point, last_pull_was_ours, filter)) {
2285                         return false;
2286                 }
2287         }
2288         return true;
2289 }
2290
2291 // Heuristic: If we go at least ten seconds without the possession changing
2292 // or the operator specifying some other formation, we probably play the
2293 // same formation as the last point.
2294 function should_reuse_last_formation(events, t) {
2295         for (const e of events) {
2296                 if (e.t <= t) {
2297                         continue;
2298                 }
2299                 if (e.t > t + 10000) {
2300                         break;
2301                 }
2302                 const type = e.type;
2303                 if (type === 'their_goal' || type === 'goal' ||
2304                     type === 'set_defense' || type === 'set_offense' ||
2305                     type === 'throwaway' || type === 'their_throwaway' ||
2306                     type === 'drop' || type === 'was_d' || type === 'stallout' || type === 'defense' || type === 'interception' ||
2307                     type === 'pull' || type === 'pull_landed' || type === 'pull_oob' || type === 'their_pull' ||
2308                     type === 'formation_offense' || type === 'formation_defense') {
2309                         return false;
2310                 }
2311         }
2312         return true;
2313 }
2314
2315 function possibly_close_menu(e) {
2316         if (e.target.closest('.filter-click-to-add') === null &&
2317             e.target.closest('#filter-add-menu') === null &&
2318             e.target.closest('#filter-submenu') === null &&
2319             e.target.closest('.filter-pill') === null) {
2320                 let add_menu = document.getElementById('filter-add-menu');
2321                 let add_submenu = document.getElementById('filter-submenu');
2322                 add_menu.style.display = 'none';
2323                 add_submenu.style.display = 'none';
2324                 try_gc_filter_menus(false);
2325         }
2326 }
2327
2328 let global_sort = {};
2329
2330 function sort_by(th) {
2331         let tr = th.parentElement;
2332         let child_idx = 0;
2333         for (let column_idx = 0; column_idx < tr.children.length; ++column_idx) {
2334                 let element = tr.children[column_idx];
2335                 if (element === th) {
2336                         ++child_idx;  // Pad.
2337                         break;
2338                 }
2339                 if (element.hasAttribute('colspan')) {
2340                         child_idx += parseInt(element.getAttribute('colspan'));
2341                 } else {
2342                         ++child_idx;
2343                 }
2344         }
2345
2346         global_sort = {};
2347         let table = tr.parentElement;
2348         for (let row_idx = 1; row_idx < table.children.length - 1; ++row_idx) {  // Skip header and globals.
2349                 let row = table.children[row_idx];
2350                 let player = parseInt(row.dataset.player);
2351                 let value = row.children[child_idx].textContent;
2352                 global_sort[player] = value;
2353         }
2354 }
2355
2356 function get_sorted_players(players)
2357 {
2358         let p = Object.entries(players);
2359         if (global_sort.length !== 0) {
2360                 p.sort((a,b) => {
2361                         let ai = parseFloat(global_sort[a[0]]);
2362                         let bi = parseFloat(global_sort[b[0]]);
2363                         if (ai == ai && bi == bi) {
2364                                 return bi - ai;  // Reverse numeric.
2365                         } else if (global_sort[a[0]] < global_sort[b[0]]) {
2366                                 return -1;
2367                         } else if (global_sort[a[0]] > global_sort[b[0]]) {
2368                                 return 1;
2369                         } else {
2370                                 return 0;
2371                         }
2372                 });
2373         }
2374         return p;
2375 }