]> git.sesse.net Git - pkanalytics/blob - ultimate.js
Two decimals is a bit too hardcore for possession times.
[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                                 if (keep) ++p.pulls;
485                         } else if (type === 'in' || type === 'out' || type === 'stoppage' || type === 'restart' || type === 'unknown' || type === 'set_defense' || type === 'set_offense') {
486                                 // No effect on pull.
487                         } else if (type === 'pull_landed' && puller !== null) {
488                                 if (keep) players[puller].pull_times.push(t - pull_started);
489                         } else if (type === 'pull_oob' && puller !== null) {
490                                 if (keep) ++players[puller].oob_pulls;
491                         } else {
492                                 // Not pulling (if there was one, we never recorded its outcome, but still count it).
493                                 puller = pull_started = null;
494                         }
495
496                         // Stats for clean holds or not (must be done before resetting we_lost_disc etc. below).
497                         if (keep) {
498                                 if (type === 'goal' && !we_lost_disc) {
499                                         if (last_pull_was_ours === false) {  // O point.
500                                                 ++globals.clean_holds;
501                                         } else if (last_pull_was_ours === true) {
502                                                 ++globals.clean_breaks;
503                                         }
504                                 } else if (type === 'their_goal' && !they_lost_disc) {
505                                         if (last_pull_was_ours === true) {  // O point for them.
506                                                 ++globals.their_clean_holds;
507                                         } else if (last_pull_was_ours === false) {
508                                                 ++globals.their_clean_breaks;
509                                         }
510                                 }
511                         }
512
513                         // Offense/defense management
514                         let last_offense = offense;
515                         if (type === 'set_defense' || type === 'goal' || type === 'throwaway' || type === 'drop' || type === 'was_d' || type === 'stallout') {
516                                 offense = false;
517                                 we_lost_disc = true;
518                                 if (keep && type !== 'goal' && !(type === 'set_defense' && last_pull_was_ours === null)) {
519                                         ++globals.turnovers_lost;
520                                         globals.touches_for_turnover += touches_this_possession;
521                                         if (possession_started != null) globals.time_for_turnover.push((t - possession_started) + extra_ms_this_possession);
522                                 } else if (keep && type === 'goal') {
523                                         globals.touches_for_goal += touches_this_possession;
524                                         if (possession_started != null) globals.time_for_goal.push((t - possession_started) + extra_ms_this_possession);
525                                 }
526                                 touches_this_possession = 0;
527                                 possession_started = null;
528                                 extra_ms_this_possession = 0;
529                         } else if (type === 'set_offense' || type === 'their_goal' || type === 'their_throwaway' || type === 'defense' || type === 'interception') {
530                                 offense = true;
531                                 they_lost_disc = true;
532                                 if (keep && type !== 'their_goal' && !(type === 'set_offense' && last_pull_was_ours === null)) {
533                                         ++globals.turnovers_won;
534                                         if (possession_started != null) globals.their_time_for_turnover.push((t - possession_started) + extra_ms_this_possession);
535                                 } else if (keep && type === 'their_goal') {
536                                         if (possession_started != null) globals.their_time_for_goal.push((t - possession_started) + extra_ms_this_possession);
537                                 }
538                                 touches_this_possession = 0;
539                                 possession_started = null;
540                                 extra_ms_this_possession = 0;
541                         }
542                         if (type === 'goal' || type === 'their_goal') {
543                                 between_points = true;
544                                 we_lost_disc = false;
545                                 they_lost_disc = false;
546                                 touches_this_possession = 0;
547                         }
548                         if (last_offense !== offense && live_since !== null) {
549                                 // Switched offense/defense status, so attribute this drive as needed,
550                                 // and update live_since to take that into account.
551                                 if (keep) {
552                                         for (const [q,p] of Object.entries(players)) {
553                                                 if (p.on_field_since === null) {
554                                                         continue;
555                                                 }
556                                                 attribute_player_time(p, t, live_since, last_offense);
557                                         }
558                                         globals.playing_time_ms += t - live_since;
559                                         if (offense === true) {
560                                                 globals.offensive_playing_time_ms += t - live_since;
561                                         } else if (offense === false) {
562                                                 globals.defensive_playing_time_ms += t - live_since;
563                                         }
564                                 }
565                                 live_since = t;
566                         }
567                         // The rules for possessions are slightly different; we want to start at pulls,
568                         // not previous goals.
569                         if ((last_offense !== offense && type !== 'goal' && type !== 'their_goal' && live_since !== null) ||
570                             type === 'pull' || type === 'their_pull') {
571                                 possession_started = t;
572                         } else if (type === 'stoppage') {
573                                 if (possession_started !== null) {
574                                         extra_ms_this_possession = t - possession_started;
575                                         possession_started = null;
576                                 }
577                         } else if (type === 'restart' && live_since !== null && !between_points) {
578                                 possession_started = t;
579                         }
580
581                         if (type === 'pull') {
582                                 last_pull_was_ours = true;
583                         } else if (type === 'their_pull') {
584                                 last_pull_was_ours = false;
585                         } else if (type === 'set_offense' && last_pull_was_ours === null) {
586                                 // set_offense could either be “changed to offense for some reason
587                                 // we could not express”, or “we started in the middle of a point,
588                                 // and we are offense”. We assume that if we already saw the pull,
589                                 // it's the former, and if not, it's the latter; thus, the === null
590                                 // test above. (It could also be “we set offense before the pull,
591                                 // so that we get the right button enabled”, in which case it will
592                                 // be overwritten by the next pull/their_pull event anyway.)
593                                 last_pull_was_ours = false;
594                         } else if (type === 'set_defense' && last_pull_was_ours === null) {
595                                 // Similar.
596                                 last_pull_was_ours = true;
597                         } else if (type === 'goal' || type === 'their_goal') {
598                                 last_pull_was_ours = null;
599                         }
600
601                         // Formation management
602                         if (type === 'formation_offense' || type === 'formation_defense') {
603                                 let id = e.formation === null ? 0 : e.formation;
604                                 let for_offense = (type === 'formation_offense');
605                                 if (offense === for_offense) {
606                                         formations_used_this_point.add(id);
607                                 } else if (for_offense) {
608                                         pending_offensive_formation = id;
609                                 } else {
610                                         pending_defensive_formation = id;
611                                 }
612                                 if (for_offense) {
613                                         last_offensive_formation = id;
614                                 } else {
615                                         last_defensive_formation = id;
616                                 }
617                         } else if (last_offense !== offense) {
618                                 if (offense === true && pending_offensive_formation !== null) {
619                                         formations_used_this_point.add(pending_offensive_formation);
620                                         pending_offensive_formation = null;
621                                 } else if (offense === false && pending_defensive_formation !== null) {
622                                         formations_used_this_point.add(pending_defensive_formation);
623                                         pending_defensive_formation = null;
624                                 } else if (offense === true && last_defensive_formation !== null) {
625                                         if (should_reuse_last_formation(match['events'], t)) {
626                                                 formations_used_this_point.add(last_defensive_formation);
627                                         }
628                                 } else if (offense === false && last_offensive_formation !== null) {
629                                         if (should_reuse_last_formation(match['events'], t)) {
630                                                 formations_used_this_point.add(last_offensive_formation);
631                                         }
632                                 }
633                         }
634
635                         if (type !== 'out' && type !== 'in' && p !== undefined && p.on_field_since === null) {
636                                 console.log(match['description'] + ' ' + format_time(t) + ': Event “' + type + '” on subbed-out player ' + p.name);
637                         }
638                         if (type === 'catch' && handler !== null && players[handler].on_field_since === null) {
639                                 // The handler subbed out and was replaced with another handler,
640                                 // so this wasn't a pass.
641                                 handler = null;
642                         }
643
644                         // Event management
645                         if (type === 'goal' && handler === e['player'] && handler_got_by_interception) {
646                                 // Self-pass to goal after an interception; this is not a real pass,
647                                 // just how we represent a Callahan right now -- so don't
648                                 // count the throw, any assists or similar.
649                                 //
650                                 // It's an open question how we should handle a self-pass that is
651                                 // _not_ after an interception, or a self-pass that's not a goal.
652                                 // (It must mean we tipped off someone.) We'll count it as a regular one
653                                 // for the time being, although it will make hockey assists weird.
654                                 if (keep) {
655                                         ++p.goals;
656                                         ++p.callahans;
657                                 }
658                                 handler = prev_handler = null;
659                         } else if (type === 'catch' || type === 'goal') {
660                                 if (handler !== null) {
661                                         if (keep) {
662                                                 ++players[handler].num_throws;
663                                                 ++p.catches;
664                                         }
665                                 }
666
667                                 if (keep) ++p.touches;
668                                 ++touches_this_possession;
669                                 if (type === 'goal') {
670                                         if (keep) {
671                                                 if (prev_handler !== null) {
672                                                         ++players[prev_handler].hockey_assists;
673                                                 }
674                                                 if (handler !== null) {
675                                                         ++players[handler].assists;
676                                                 }
677                                                 ++p.goals;
678                                         }
679                                         handler = prev_handler = null;
680                                 } else {
681                                         // Update hold history.
682                                         prev_handler = handler;
683                                         handler = e['player'];
684                                         handler_got_by_interception = false;
685                                 }
686                         } else if (type === 'throwaway') {
687                                 if (keep) {
688                                         ++p.num_throws;
689                                         ++p.throwaways;
690                                 }
691                                 handler = prev_handler = null;
692                         } else if (type === 'drop') {
693                                 if (keep) ++p.drops;
694                                 handler = prev_handler = null;
695                         } else if (type === 'stallout') {
696                                 if (keep) ++p.stallouts;
697                                 handler = prev_handler = null;
698                         } else if (type === 'was_d') {
699                                 if (keep) ++p.was_ds;
700                                 handler = prev_handler = null;
701                         } else if (type === 'defense') {
702                                 if (keep) ++p.defenses;
703                         } else if (type === 'interception') {
704                                 if (keep) {
705                                         ++p.catches;
706                                         ++p.defenses;
707                                         ++p.touches;
708                                         ++touches_this_possession;
709                                 }
710                                 prev_handler = null;
711                                 handler = e['player'];
712                                 handler_got_by_interception = true;
713                         } else if (type === 'offensive_soft_plus' || type === 'offensive_soft_minus' || type === 'defensive_soft_plus' || type === 'defensive_soft_minus') {
714                                 if (keep) ++p[type];
715                         } else if (type !== 'in' && type !== 'out' && type !== 'pull' &&
716                                    type !== 'their_goal' && type !== 'stoppage' && type !== 'restart' && type !== 'unknown' &&
717                                    type !== 'set_defense' && type !== 'goal' && type !== 'throwaway' &&
718                                    type !== 'drop' && type !== 'was_d' && type !== 'stallout' && type !== 'set_offense' && type !== 'their_goal' &&
719                                    type !== 'pull' && type !== 'pull_landed' && type !== 'pull_oob' && type !== 'their_pull' &&
720                                    type !== 'their_throwaway' && type !== 'defense' && type !== 'interception' &&
721                                    type !== 'formation_offense' && type !== 'formation_defense') {
722                                 console.log(format_time(t) + ": Unknown event “" + e + "”");
723                         }
724
725                         if (type === 'goal' || type === 'their_goal') {
726                                 formations_used_this_point.clear();
727                         }
728                 }
729
730                 // Add field time for all players still left at match end.
731                 const keep = keep_event(players, formations_used_this_point, last_pull_was_ours, filters);
732                 if (keep) {
733                         for (const [q,p] of Object.entries(players)) {
734                                 if (p.on_field_since !== null && last_goal !== null) {
735                                         p.field_time_ms += last_goal - p.on_field_since;
736                                 }
737                         }
738                         if (game_started !== null && last_goal !== null) {
739                                 globals.field_time_ms += last_goal - game_started;
740                         }
741                         if (live_since !== null && last_goal !== null) {
742                                 globals.playing_time_ms += last_goal - live_since;
743                                 if (offense === true) {
744                                         globals.offensive_playing_time_ms += last_goal - live_since;
745                                 } else if (offense === false) {
746                                         globals.defensive_playing_time_ms += last_goal - live_since;
747                                 }
748                         }
749                 }
750         }
751         return players;
752 }
753
754 function process_matches(json, filtersets) {
755         let chosen_category = get_chosen_category();
756         write_main_menu(chosen_category);
757
758         let filterset_values = Object.values(filtersets);
759         if (filterset_values.length === 0) {
760                 filterset_values = [[]];
761         }
762
763         let rowsets = [];
764         for (const filter of filterset_values) {
765                 let players = calc_stats(json, filter);
766                 let rows = [];
767                 if (chosen_category === 'general') {
768                         rows = make_table_general(players);
769                 } else if (chosen_category === 'offense') {
770                         rows = make_table_offense(players);
771                 } else if (chosen_category === 'defense') {
772                         rows = make_table_defense(players);
773                 } else if (chosen_category === 'playing_time') {
774                         rows = make_table_playing_time(players);
775                 } else if (chosen_category === 'per_point') {
776                         rows = make_table_per_point(players);
777                 } else if (chosen_category === 'team_wide') {
778                         rows = make_table_team_wide(players);
779                 }
780                 rowsets.push(rows);
781         }
782
783         let merged_rows = [];
784         if (filterset_values.length > 1) {
785                 for (let i = 0; i < rowsets.length; ++i) {
786                         let marker = make_filter_marker(filterset_values[i]);
787
788                         // Make filter header.
789                         let tr = rowsets[i][0];
790                         let th = document.createElement('th');
791                         th.textContent = '';
792                         tr.insertBefore(th, tr.firstChild);
793
794                         for (let j = 1; j < rowsets[i].length; ++j) {
795                                 let tr = rowsets[i][j];
796
797                                 // Remove the name for cleanness.
798                                 if (i != 0) {
799                                         tr.firstChild.nextSibling.textContent = '';
800                                 }
801
802                                 if (i != 0) {
803                                         tr.style.borderTop = '0px';
804                                 }
805                                 if (i != rowsets.length - 1) {
806                                         tr.style.borderBottom = '0px';
807                                 }
808
809                                 // Make filter marker.
810                                 let td = document.createElement('td');
811                                 td.textContent = marker;
812                                 td.classList.add('filtermarker');
813                                 tr.insertBefore(td, tr.firstChild);
814                         }
815                 }
816
817                 for (let i = 0; i < rowsets[0].length; ++i) {
818                         for (let j = 0; j < rowsets.length; ++j) {
819                                 merged_rows.push(rowsets[j][i]);
820                                 if (i === 0) break;  // Don't merge the headings.
821                         }
822                 }
823         } else {
824                 merged_rows = rowsets[0];
825         }
826         document.getElementById('stats').replaceChildren(...merged_rows);
827 }
828
829 function get_chosen_category() {
830         if (window.location.hash === '#offense') {
831                 return 'offense';
832         } else if (window.location.hash === '#defense') {
833                 return 'defense';
834         } else if (window.location.hash === '#playing_time') {
835                 return 'playing_time';
836         } else if (window.location.hash === '#per_point') {
837                 return 'per_point';
838         } else if (window.location.hash === '#team_wide') {
839                 return 'team_wide';
840         } else {
841                 return 'general';
842         }
843 }
844
845 function write_main_menu(chosen_category) {
846         let elems = [];
847         const categories = [
848                 ['general', 'General'],
849                 ['offense', 'Offense'],
850                 ['defense', 'Defense'],
851                 ['playing_time', 'Playing time'],
852                 ['per_point', 'Per point'],
853                 ['team_wide', 'Team-wide'],
854         ];
855         for (const [id, title] of categories) {
856                 if (chosen_category === id) {
857                         let span = document.createElement('span');
858                         span.innerText = title;
859                         elems.push(span);
860                 } else {
861                         let a = document.createElement('a');
862                         a.appendChild(document.createTextNode(title));
863                         a.setAttribute('href', '#' + id);
864                         elems.push(a);
865                 }
866         }
867
868         document.getElementById('mainmenu').replaceChildren(...elems);
869 }
870
871 // https://en.wikipedia.org/wiki/1.96#History
872 const z = 1.959964;
873
874 const ci_width = 100;
875 const ci_height = 20;
876
877 function make_binomial_ci(val, num, z) {
878         let avg = val / num;
879
880         // https://en.wikipedia.org/wiki/Binomial_proportion_confidence_interval#Wilson_score_interval
881         let low  = (avg + z*z/(2*num) - z * Math.sqrt(avg * (1.0 - avg) / num + z*z/(4*num*num))) / (1 + z*z/num);   
882         let high = (avg + z*z/(2*num) + z * Math.sqrt(avg * (1.0 - avg) / num + z*z/(4*num*num))) / (1 + z*z/num); 
883
884         // Fix the signs so that we don't get -0.00.
885         low = Math.max(low, 0.0);
886         return {
887                 'val': avg,
888                 'lower_ci': low,
889                 'upper_ci': high,
890                 'min': 0.0,
891                 'max': 1.0,
892         };
893 }
894
895 // These can only happen once per point, but you get -1 and +1
896 // instead of 0 and +1. After we rewrite to 0 and 1, it's a binomial,
897 // and then we can rewrite back.
898 function make_efficiency_ci(points_won, points_completed, z)
899 {
900         let ci = make_binomial_ci(points_won, points_completed, z);
901         ci.val = 2.0 * ci.val - 1.0;
902         ci.lower_ci = 2.0 * ci.lower_ci - 1.0;
903         ci.upper_ci = 2.0 * ci.upper_ci - 1.0;
904         ci.min = -1.0;
905         ci.max = 1.0;
906         ci.desired = 0.0;  // Desired = positive efficiency.
907         return ci;
908 }
909
910 // Ds, throwaways and drops can happen multiple times per point,
911 // so they are Poisson distributed.
912 //
913 // Modified Wald (recommended by http://www.ine.pt/revstat/pdf/rs120203.pdf
914 // since our rates are definitely below 2 per point).
915 //
916 // FIXME: z is ignored.
917 function make_poisson_ci(val, num, z, inverted)
918 {
919         let low  = (val == 0) ? 0.0 : ((val - 0.5) - Math.sqrt(val - 0.5)) / num;
920         let high = (val == 0) ? -Math.log(0.025) / num : ((val + 0.5) + Math.sqrt(val + 0.5)) / num;
921
922         // Fix the signs so that we don't get -0.00.
923         low = Math.max(low, 0.0);
924
925         // The display range of 0 to 0.5 is fairly arbitrary. So is the desired 0.05 per point.
926         let avg = val / num;
927         return {
928                 'val': avg,
929                 'lower_ci': low,
930                 'upper_ci': high,
931                 'min': 0.0,
932                 'max': 0.5,
933                 'desired': 0.05,
934                 'inverted': inverted,
935         };
936 }
937
938 // Wilson and Hilferty, again recommended for general use in the PDF above
939 // (anything from their group “G1” works).
940 // https://en.wikipedia.org/wiki/Poisson_distribution#Confidence_interval
941 function make_poisson_ci_large(val, num, z)
942 {
943         let low  = val * Math.pow(1.0 - 1.0 / (9.0 * val) - z / (3.0 * Math.sqrt(val)), 3.0) / num;
944         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;
945
946         // Fix the signs so that we don't get -0.00.
947         low = Math.max(low, 0.0);
948
949         // The display range of 0 to 25.0 is fairly arbitrary. We have no desire here
950         // (this is used for number of touches).
951         let avg = val / num;
952         return {
953                 'val': avg,
954                 'lower_ci': low,
955                 'upper_ci': high,
956                 'min': 0.0,
957                 'max': 25.0,
958                 'desired': 0.0,
959                 'inverted': false,
960         };
961 }
962
963 // We don't really know what to expect for possessions; it appears roughly
964 // lognormal, but my head doesn't work well enough to extract the CI for
965 // the estimated sample mean, and now my head spins around whether we do
966 // this correctly even for Poisson :-) But we do a simple (non-BCa) bootstrap
967 // here, which should give us what we want.
968 //
969 // FIXME: z is ignored.
970 function make_ci_duration(vals, z)
971 {
972         // Bootstrap.
973         let sample_means = [];
974         for (let i = 0; i < 300; ++i) {
975                 let sum = 0.0;
976                 for (let j = 0; j < vals.length; ++j) {
977                         sum += vals[Math.floor(Math.random() * vals.length)];
978                 }
979                 sample_means.push(sum / vals.length);
980         }
981         sample_means.sort();
982
983         // Interpolating here would probably be better, but OK.
984         let low  = sample_means[Math.floor(0.025 * sample_means.length)];
985         let high = sample_means[Math.floor(0.975 * sample_means.length)];
986
987         // Find the point estimate of the mean.
988         let sum = 0.0;
989         for (const v of vals) {
990                 sum += v;
991         }
992         let avg = sum / vals.length;
993
994         return {
995                 'val': avg / 1000.0,
996                 'lower_ci': low / 1000.0,
997                 'upper_ci': high / 1000.0,
998                 'min': 0.0,
999                 'max': 120.0,
1000                 'desired': 0.0,
1001                 'inverted': false,
1002                 'unit': 'sec',
1003                 'decimals': 1,
1004         };
1005 }
1006
1007 function make_table_general(players) {
1008         let rows = [];
1009         {
1010                 let header = document.createElement('tr');
1011                 add_th(header, 'Player');
1012                 add_th(header, '+/-');
1013                 add_th(header, 'Soft +/-');
1014                 add_th(header, 'O efficiency');
1015                 add_th(header, 'D efficiency');
1016                 add_th(header, 'Points played');
1017                 rows.push(header);
1018         }
1019
1020         for (const [q,p] of get_sorted_players(players)) {
1021                 if (q === 'globals') continue;
1022                 let row = document.createElement('tr');
1023                 let pm = p.goals + p.assists + p.hockey_assists + p.defenses - p.throwaways - p.drops - p.was_ds - p.stallouts;
1024                 let soft_pm = p.offensive_soft_plus + p.defensive_soft_plus - p.offensive_soft_minus - p.defensive_soft_minus;
1025                 let o_efficiency = make_efficiency_ci(p.offensive_points_won, p.offensive_points_completed, z);
1026                 let d_efficiency = make_efficiency_ci(p.defensive_points_won, p.defensive_points_completed, z);
1027                 let name = add_3cell(row, p.name, 'name');  // TODO: number?
1028                 add_3cell(row, pm > 0 ? ('+' + pm) : pm);
1029                 add_3cell(row, soft_pm > 0 ? ('+' + soft_pm) : soft_pm);
1030                 add_3cell_ci(row, o_efficiency);
1031                 add_3cell_ci(row, d_efficiency);
1032                 add_3cell(row, p.points_played);
1033                 row.dataset.player = q;
1034                 rows.push(row);
1035         }
1036
1037         // Globals.
1038         let globals = players['globals'];
1039         let o_efficiency = make_efficiency_ci(globals.offensive_points_won, globals.offensive_points_completed, z);
1040         let d_efficiency = make_efficiency_ci(globals.defensive_points_won, globals.defensive_points_completed, z);
1041         let row = document.createElement('tr');
1042         add_3cell(row, '');
1043         add_3cell(row, '');
1044         add_3cell(row, '');
1045         add_3cell_ci(row, o_efficiency);
1046         add_3cell_ci(row, d_efficiency);
1047         add_3cell(row, globals.points_played);
1048         rows.push(row);
1049
1050         return rows;
1051 }
1052
1053 function make_table_team_wide(players) {
1054         let globals = players['globals'];
1055
1056         let rows = [];
1057         {
1058                 let header = document.createElement('tr');
1059                 add_th(header, '');
1060                 add_th(header, 'Our team', 6);
1061                 add_th(header, 'Opponents', 6);
1062                 rows.push(header);
1063         }
1064
1065         // Turnovers.
1066         {
1067                 let row = document.createElement('tr');
1068                 let name = add_3cell(row, 'Turnovers generated', 'name');
1069                 add_3cell(row, globals.turnovers_won);
1070                 add_3cell(row, '');
1071                 add_3cell(row, globals.turnovers_lost);
1072                 add_3cell(row, '');
1073                 rows.push(row);
1074         }
1075
1076         // Clean holds.
1077         {
1078                 let row = document.createElement('tr');
1079                 let name = add_3cell(row, 'Clean holds', 'name');
1080                 let our_clean_holds = make_binomial_ci(globals.clean_holds, globals.offensive_points_completed, z);
1081                 let their_clean_holds = make_binomial_ci(globals.their_clean_holds, globals.defensive_points_completed, z);
1082                 our_clean_holds.desired = 0.3;  // Arbitrary.
1083                 our_clean_holds.format = 'percentage';
1084                 their_clean_holds.desired = 0.3;
1085                 their_clean_holds.format = 'percentage';
1086                 add_3cell(row, globals.clean_holds + ' / ' + globals.offensive_points_completed);
1087                 add_3cell_ci(row, our_clean_holds);
1088                 add_3cell(row, globals.their_clean_holds + ' / ' + globals.defensive_points_completed);
1089                 add_3cell_ci(row, their_clean_holds);
1090                 rows.push(row);
1091         }
1092
1093         // Clean breaks.
1094         {
1095                 let row = document.createElement('tr');
1096                 let name = add_3cell(row, 'Clean breaks', 'name');
1097                 let our_clean_breaks = make_binomial_ci(globals.clean_breaks, globals.defensive_points_completed, z);
1098                 let their_clean_breaks = make_binomial_ci(globals.their_clean_breaks, globals.offensive_points_completed, z);
1099                 our_clean_breaks.desired = 0.3;  // Arbitrary.
1100                 our_clean_breaks.format = 'percentage';
1101                 their_clean_breaks.desired = 0.3;
1102                 their_clean_breaks.format = 'percentage';
1103                 add_3cell(row, globals.clean_breaks + ' / ' + globals.defensive_points_completed);
1104                 add_3cell_ci(row, our_clean_breaks);
1105                 add_3cell(row, globals.their_clean_breaks + ' / ' + globals.offensive_points_completed);
1106                 add_3cell_ci(row, their_clean_breaks);
1107                 rows.push(row);
1108         }
1109
1110         // Touches. We only have information for our team here.
1111         {
1112                 let goals = 0;
1113                 for (const [q,p] of get_sorted_players(players)) {
1114                         if (q === 'globals') continue;
1115                         goals += p.goals;
1116                 }
1117                 let row = document.createElement('tr');
1118                 let name = add_3cell(row, 'Touches per possession (all)', 'name');
1119                 let touches = globals.touches_for_turnover + globals.touches_for_goal;
1120                 let possessions = goals + globals.turnovers_lost;
1121                 add_3cell(row, '');
1122                 add_3cell_ci(row, make_poisson_ci_large(touches, possessions, z));
1123                 add_3cell(row, '');
1124                 add_3cell(row, '');
1125                 rows.push(row);
1126
1127                 row = document.createElement('tr');
1128                 add_3cell(row, 'Touches per possession (goals)', 'name');
1129                 add_3cell(row, '');
1130                 add_3cell_ci(row, make_poisson_ci_large(globals.touches_for_goal, goals, z));
1131                 add_3cell(row, '');
1132                 add_3cell(row, '');
1133                 rows.push(row);
1134
1135                 row = document.createElement('tr');
1136                 add_3cell(row, 'Touches per possession (turnovers)', 'name');
1137                 add_3cell(row, '');
1138                 add_3cell_ci(row, make_poisson_ci_large(globals.touches_for_turnover, globals.turnovers_lost, z));
1139                 add_3cell(row, '');
1140                 add_3cell(row, '');
1141                 rows.push(row);
1142         }
1143
1144         // Time. Here we have (roughly) for both.
1145         {
1146                 let row = document.createElement('tr');
1147                 let name = add_3cell(row, 'Time per possession (all)', 'name');
1148                 let time = globals.time_for_turnover.concat(globals.time_for_goal);
1149                 let their_time = globals.their_time_for_turnover.concat(globals.their_time_for_goal);
1150                 add_3cell(row, '');
1151                 add_3cell_ci(row, make_ci_duration(time, z));
1152                 add_3cell(row, '');
1153                 add_3cell_ci(row, make_ci_duration(their_time, z));
1154                 rows.push(row);
1155
1156                 row = document.createElement('tr');
1157                 add_3cell(row, 'Time per possession (goals)', 'name');
1158                 add_3cell(row, '');
1159                 add_3cell_ci(row, make_ci_duration(globals.time_for_goal, z));
1160                 add_3cell(row, '');
1161                 add_3cell_ci(row, make_ci_duration(globals.their_time_for_goal, z));
1162                 rows.push(row);
1163
1164                 row = document.createElement('tr');
1165                 add_3cell(row, 'Time per possession (turnovers)', 'name');
1166                 add_3cell(row, '');
1167                 add_3cell_ci(row, make_ci_duration(globals.time_for_turnover, z));
1168                 add_3cell(row, '');
1169                 add_3cell_ci(row, make_ci_duration(globals.their_time_for_turnover, z));
1170                 rows.push(row);
1171         }
1172
1173         return rows;
1174 }
1175
1176 function make_table_offense(players) {
1177         let rows = [];
1178         {
1179                 let header = document.createElement('tr');
1180                 add_th(header, 'Player');
1181                 add_th(header, 'Goals');
1182                 add_th(header, 'Assists');
1183                 add_th(header, 'Hockey assists');
1184                 add_th(header, 'Throws');
1185                 add_th(header, 'Throwaways');
1186                 add_th(header, '%OK');
1187                 add_th(header, 'Catches');
1188                 add_th(header, 'Drops');
1189                 add_th(header, 'D-ed');
1190                 add_th(header, '%OK');
1191                 add_th(header, 'Stalls');
1192                 add_th(header, 'Soft +/-', 6);
1193                 rows.push(header);
1194         }
1195
1196         let goals = 0;
1197         let num_throws = 0;
1198         let throwaways = 0;
1199         let catches = 0;
1200         let drops = 0;
1201         let was_ds = 0;
1202         let stallouts = 0;
1203         for (const [q,p] of get_sorted_players(players)) {
1204                 if (q === 'globals') continue;
1205                 let throw_ok = make_binomial_ci(p.num_throws - p.throwaways, p.num_throws, z);
1206                 let catch_ok = make_binomial_ci(p.catches, p.catches + p.drops + p.was_ds, z);
1207
1208                 throw_ok.format = 'percentage';
1209                 catch_ok.format = 'percentage';
1210
1211                 // Desire at least 90% percentage. Fairly arbitrary.
1212                 throw_ok.desired = 0.9;
1213                 catch_ok.desired = 0.9;
1214
1215                 let row = document.createElement('tr');
1216                 add_3cell(row, p.name, 'name');  // TODO: number?
1217                 add_3cell(row, p.goals);
1218                 add_3cell(row, p.assists);
1219                 add_3cell(row, p.hockey_assists);
1220                 add_3cell(row, p.num_throws);
1221                 add_3cell(row, p.throwaways);
1222                 add_3cell_ci(row, throw_ok);
1223                 add_3cell(row, p.catches);
1224                 add_3cell(row, p.drops);
1225                 add_3cell(row, p.was_ds);
1226                 add_3cell_ci(row, catch_ok);
1227                 add_3cell(row, p.stallouts);
1228                 add_3cell(row, '+' + p.offensive_soft_plus);
1229                 add_3cell(row, '-' + p.offensive_soft_minus);
1230                 row.dataset.player = q;
1231                 rows.push(row);
1232
1233                 goals += p.goals;
1234                 num_throws += p.num_throws;
1235                 throwaways += p.throwaways;
1236                 catches += p.catches;
1237                 drops += p.drops;
1238                 was_ds += p.was_ds;
1239                 stallouts += p.stallouts;
1240         }
1241
1242         // Globals.
1243         let throw_ok = make_binomial_ci(num_throws - throwaways, num_throws, z);
1244         let catch_ok = make_binomial_ci(catches, catches + drops + was_ds, z);
1245         throw_ok.format = 'percentage';
1246         catch_ok.format = 'percentage';
1247         throw_ok.desired = 0.9;
1248         catch_ok.desired = 0.9;
1249
1250         let row = document.createElement('tr');
1251         add_3cell(row, '');
1252         add_3cell(row, goals);
1253         add_3cell(row, '');
1254         add_3cell(row, '');
1255         add_3cell(row, num_throws);
1256         add_3cell(row, throwaways);
1257         add_3cell_ci(row, throw_ok);
1258         add_3cell(row, catches);
1259         add_3cell(row, drops);
1260         add_3cell(row, was_ds);
1261         add_3cell_ci(row, catch_ok);
1262         add_3cell(row, stallouts);
1263         add_3cell(row, '');
1264         add_3cell(row, '');
1265         rows.push(row);
1266
1267         return rows;
1268 }
1269
1270 function make_table_defense(players) {
1271         let rows = [];
1272         {
1273                 let header = document.createElement('tr');
1274                 add_th(header, 'Player');
1275                 add_th(header, 'Ds');
1276                 add_th(header, 'Pulls');
1277                 add_th(header, 'OOB pulls');
1278                 add_th(header, 'OOB%');
1279                 add_th(header, 'Avg. hang time (IB)');
1280                 add_th(header, 'Callahans');
1281                 add_th(header, 'Soft +/-', 6);
1282                 rows.push(header);
1283         }
1284
1285         let defenses = 0;
1286         let pulls = 0;
1287         let oob_pulls = 0;
1288         let sum_sum_time = 0;
1289         let callahans = 0;
1290
1291         for (const [q,p] of get_sorted_players(players)) {
1292                 if (q === 'globals') continue;
1293                 let sum_time = 0;
1294                 for (const t of p.pull_times) {
1295                         sum_time += t;
1296                 }
1297                 let avg_time = 1e-3 * sum_time / (p.pulls - p.oob_pulls);
1298                 let oob_pct = 100 * p.oob_pulls / p.pulls;
1299
1300                 let ci_oob = make_binomial_ci(p.oob_pulls, p.pulls, z);
1301                 ci_oob.format = 'percentage';
1302                 ci_oob.desired = 0.2;  // Arbitrary.
1303                 ci_oob.inverted = true;
1304
1305                 let row = document.createElement('tr');
1306                 add_3cell(row, p.name, 'name');  // TODO: number?
1307                 add_3cell(row, p.defenses);
1308                 add_3cell(row, p.pulls);
1309                 add_3cell(row, p.oob_pulls);
1310                 add_3cell_ci(row, ci_oob);
1311                 if (p.pulls > p.oob_pulls) {
1312                         add_3cell(row, avg_time.toFixed(1) + ' sec');
1313                 } else {
1314                         add_3cell(row, 'N/A');
1315                 }
1316                 add_3cell(row, p.callahans);
1317                 add_3cell(row, '+' + p.defensive_soft_plus);
1318                 add_3cell(row, '-' + p.defensive_soft_minus);
1319                 row.dataset.player = q;
1320                 rows.push(row);
1321
1322                 defenses += p.defenses;
1323                 pulls += p.pulls;
1324                 oob_pulls += p.oob_pulls;
1325                 sum_sum_time += sum_time;
1326                 callahans += p.callahans;
1327         }
1328
1329         // Globals.
1330         let ci_oob = make_binomial_ci(oob_pulls, pulls, z);
1331         ci_oob.format = 'percentage';
1332         ci_oob.desired = 0.2;  // Arbitrary.
1333         ci_oob.inverted = true;
1334
1335         let avg_time = 1e-3 * sum_sum_time / (pulls - oob_pulls);
1336         let oob_pct = 100 * oob_pulls / pulls;
1337
1338         let row = document.createElement('tr');
1339         add_3cell(row, '');
1340         add_3cell(row, defenses);
1341         add_3cell(row, pulls);
1342         add_3cell(row, oob_pulls);
1343         add_3cell_ci(row, ci_oob);
1344         if (pulls > oob_pulls) {
1345                 add_3cell(row, avg_time.toFixed(1) + ' sec');
1346         } else {
1347                 add_3cell(row, 'N/A');
1348         }
1349         add_3cell(row, callahans);
1350         add_3cell(row, '');
1351         add_3cell(row, '');
1352         rows.push(row);
1353
1354         return rows;
1355 }
1356
1357 function make_table_playing_time(players) {
1358         let rows = [];
1359         {
1360                 let header = document.createElement('tr');
1361                 add_th(header, 'Player');
1362                 add_th(header, 'Points played');
1363                 add_th(header, 'Time played');
1364                 add_th(header, 'O time');
1365                 add_th(header, 'D time');
1366                 add_th(header, 'Time on field');
1367                 add_th(header, 'O points');
1368                 add_th(header, 'D points');
1369                 rows.push(header);
1370         }
1371
1372         for (const [q,p] of get_sorted_players(players)) {
1373                 if (q === 'globals') continue;
1374                 let row = document.createElement('tr');
1375                 add_3cell(row, p.name, 'name');  // TODO: number?
1376                 add_3cell(row, p.points_played);
1377                 add_3cell(row, Math.floor(p.playing_time_ms / 60000) + ' min');
1378                 add_3cell(row, Math.floor(p.offensive_playing_time_ms / 60000) + ' min');
1379                 add_3cell(row, Math.floor(p.defensive_playing_time_ms / 60000) + ' min');
1380                 add_3cell(row, Math.floor(p.field_time_ms / 60000) + ' min');
1381                 add_3cell(row, p.offensive_points_completed);
1382                 add_3cell(row, p.defensive_points_completed);
1383                 row.dataset.player = q;
1384                 rows.push(row);
1385         }
1386
1387         // Globals.
1388         let globals = players['globals'];
1389         let row = document.createElement('tr');
1390         add_3cell(row, '');
1391         add_3cell(row, globals.points_played);
1392         add_3cell(row, Math.floor(globals.playing_time_ms / 60000) + ' min');
1393         add_3cell(row, Math.floor(globals.offensive_playing_time_ms / 60000) + ' min');
1394         add_3cell(row, Math.floor(globals.defensive_playing_time_ms / 60000) + ' min');
1395         add_3cell(row, Math.floor(globals.field_time_ms / 60000) + ' min');
1396         add_3cell(row, globals.offensive_points_completed);
1397         add_3cell(row, globals.defensive_points_completed);
1398         rows.push(row);
1399
1400         return rows;
1401 }
1402
1403 function make_table_per_point(players) {
1404         let rows = [];
1405         {
1406                 let header = document.createElement('tr');
1407                 add_th(header, 'Player');
1408                 add_th(header, 'Goals');
1409                 add_th(header, 'Assists');
1410                 add_th(header, 'Hockey assists');
1411                 add_th(header, 'Ds');
1412                 add_th(header, 'Throwaways');
1413                 add_th(header, 'Recv. errors');
1414                 add_th(header, 'Touches');
1415                 rows.push(header);
1416         }
1417
1418         let goals = 0;
1419         let assists = 0;
1420         let hockey_assists = 0;
1421         let defenses = 0;
1422         let throwaways = 0;
1423         let receiver_errors = 0;
1424         let touches = 0;
1425         for (const [q,p] of get_sorted_players(players)) {
1426                 if (q === 'globals') continue;
1427
1428                 // Can only happen once per point, so these are binomials.
1429                 let ci_goals = make_binomial_ci(p.goals, p.points_played, z);
1430                 let ci_assists = make_binomial_ci(p.assists, p.points_played, z);
1431                 let ci_hockey_assists = make_binomial_ci(p.hockey_assists, p.points_played, z);
1432                 // Arbitrarily desire at least 10% (not everybody can score or assist).
1433                 ci_goals.desired = 0.1;
1434                 ci_assists.desired = 0.1;
1435                 ci_hockey_assists.desired = 0.1;
1436
1437                 let row = document.createElement('tr');
1438                 add_3cell(row, p.name, 'name');  // TODO: number?
1439                 add_3cell_ci(row, ci_goals);
1440                 add_3cell_ci(row, ci_assists);
1441                 add_3cell_ci(row, ci_hockey_assists);
1442                 add_3cell_ci(row, make_poisson_ci(p.defenses, p.points_played, z));
1443                 add_3cell_ci(row, make_poisson_ci(p.throwaways, p.points_played, z, true));
1444                 add_3cell_ci(row, make_poisson_ci(p.drops + p.was_ds, p.points_played, z, true));
1445                 if (p.points_played > 0) {
1446                         add_3cell(row, p.touches == 0 ? 0 : (p.touches / p.points_played).toFixed(2));
1447                 } else {
1448                         add_3cell(row, 'N/A');
1449                 }
1450                 row.dataset.player = q;
1451                 rows.push(row);
1452
1453                 goals += p.goals;
1454                 assists += p.assists;
1455                 hockey_assists += p.hockey_assists;
1456                 defenses += p.defenses;
1457                 throwaways += p.throwaways;
1458                 receiver_errors += p.drops + p.was_ds;
1459                 touches += p.touches;
1460         }
1461
1462         // Globals.
1463         let globals = players['globals'];
1464         let row = document.createElement('tr');
1465         add_3cell(row, '');
1466         if (globals.points_played > 0) {
1467                 let ci_goals = make_binomial_ci(goals, globals.points_played, z);
1468                 let ci_assists = make_binomial_ci(assists, globals.points_played, z);
1469                 let ci_hockey_assists = make_binomial_ci(hockey_assists, globals.points_played, z);
1470                 ci_goals.desired = 0.5;
1471                 ci_assists.desired = 0.5;
1472                 ci_hockey_assists.desired = 0.5;
1473
1474                 add_3cell_ci(row, ci_goals);
1475                 add_3cell_ci(row, ci_assists);
1476                 add_3cell_ci(row, ci_hockey_assists);
1477
1478                 add_3cell_ci(row, make_poisson_ci(defenses, globals.points_played, z));
1479                 add_3cell_ci(row, make_poisson_ci(throwaways, globals.points_played, z, true));
1480                 add_3cell_ci(row, make_poisson_ci(receiver_errors, globals.points_played, z, true));
1481
1482                 add_3cell(row, touches == 0 ? 0 : (touches / globals.points_played).toFixed(2));
1483         } else {
1484                 add_3cell_with_filler_ci(row, 'N/A');
1485                 add_3cell_with_filler_ci(row, 'N/A');
1486                 add_3cell_with_filler_ci(row, 'N/A');
1487                 add_3cell_with_filler_ci(row, 'N/A');
1488                 add_3cell_with_filler_ci(row, 'N/A');
1489                 add_3cell_with_filler_ci(row, 'N/A');
1490                 add_3cell(row, 'N/A');
1491         }
1492         rows.push(row);
1493
1494         return rows;
1495 }
1496
1497 function open_filter_menu(click_to_add_div) {
1498         document.getElementById('filter-submenu').style.display = 'none';
1499         let filter_div = click_to_add_div.parentElement;
1500         let filter_id = filter_div.dataset.filterId;
1501
1502         let menu = document.getElementById('filter-add-menu');
1503         menu.parentElement.removeChild(menu);
1504         filter_div.appendChild(menu);
1505         menu.style.display = 'block';
1506         menu.replaceChildren();
1507
1508         // Place the menu directly under the “click to add” label;
1509         // we don't anchor it since that label will move around
1510         // and the menu shouldn't.
1511         let rect = click_to_add_div.getBoundingClientRect();
1512         menu.style.left = rect.left + 'px';
1513         menu.style.top = (rect.bottom + 10) + 'px';
1514
1515         let filterset = global_filters[filter_id];
1516         if (filterset === undefined) {
1517                 global_filters[filter_id] = filterset = [];
1518         }
1519
1520         add_menu_item(filter_div, filterset, menu, 0, 'match', 'Match (any)');
1521         add_menu_item(filter_div, filterset, menu, 1, 'player_any', 'Player on field (any)');
1522         add_menu_item(filter_div, filterset, menu, 2, 'player_all', 'Player on field (all)');
1523         add_menu_item(filter_div, filterset, menu, 3, 'formation_offense', 'Offense played (any)');
1524         add_menu_item(filter_div, filterset, menu, 4, 'formation_defense', 'Defense played (any)');
1525         add_menu_item(filter_div, filterset, menu, 5, 'starting_on', 'Starting on');
1526         add_menu_item(filter_div, filterset, menu, 6, 'gender_ratio', 'Gender ratio');
1527 }
1528
1529 function add_menu_item(filter_div, filterset, menu, menu_idx, filter_type, title) {
1530         let item = document.createElement('div');
1531         item.classList.add('option');
1532         item.appendChild(document.createTextNode(title));
1533
1534         let arrow = document.createElement('div');
1535         arrow.classList.add('arrow');
1536         arrow.textContent = '▸';
1537         item.appendChild(arrow);
1538
1539         menu.appendChild(item);
1540
1541         item.addEventListener('click', (e) => { show_submenu(filter_div, filterset, menu_idx, null, filter_type); });
1542 }
1543
1544 function find_all_ratios(json)
1545 {
1546         let ratios = {};
1547         let players = {};
1548         for (const player of json['players']) {
1549                 players[player['player_id']] = {
1550                         'gender': player['gender'],
1551                         'last_point_seen': null,
1552                 };
1553         }
1554         for (const match of json['matches']) {
1555                 for (const [q,p] of Object.entries(players)) {
1556                         p.on_field_since = null;
1557                 }
1558                 for (const e of match['events']) {
1559                         let p = players[e['player']];
1560                         let type = e['type'];
1561                         if (type === 'in') {
1562                                 p.on_field_since = 1;
1563                         } else if (type === 'out') {
1564                                 p.on_field_since = null;
1565                         } else if (type === 'pull' || type == 'their_pull') {  // We assume no cross-gender subs for now.
1566                                 let code = find_gender_ratio_code(players);
1567                                 if (ratios[code] === undefined) {
1568                                         ratios[code] = code;
1569                                         if (code !== '4 F, 3 M' && code !== '4 M, 3 F' && code !== '3 M, 2 F' && code !== '3 F, 2 M') {
1570                                                 console.log('Unexpected gender ratio ' + code + ' first seen at: ' +
1571                                                             match['description'] + ', ' + format_time(e['t']));
1572                                         }
1573                                 }
1574                         }
1575                 }
1576         }
1577         return ratios;
1578 }
1579
1580 function show_submenu(filter_div, filterset, menu_idx, pill, filter_type) {
1581         let submenu = document.getElementById('filter-submenu');
1582
1583         // Move to the same place as the top-level menu.
1584         submenu.parentElement.removeChild(submenu);
1585         document.getElementById('filter-add-menu').parentElement.appendChild(submenu);
1586
1587         let subitems = [];
1588         const filter = find_filter(filterset, filter_type);
1589
1590         let choices = [];
1591         if (filter_type === 'match') {
1592                 for (const match of global_json['matches']) {
1593                         choices.push({
1594                                 'title': match['description'],
1595                                 'id': match['match_id']
1596                         });
1597                 }
1598         } else if (filter_type === 'player_any' || filter_type === 'player_all') {
1599                 for (const player of global_json['players']) {
1600                         choices.push({
1601                                 'title': player['name'],
1602                                 'id': player['player_id']
1603                         });
1604                 }
1605         } else if (filter_type === 'formation_offense') {
1606                 choices.push({
1607                         'title': '(None/unknown)',
1608                         'id': 0,
1609                 });
1610                 for (const formation of global_json['formations']) {
1611                         if (formation['offense']) {
1612                                 choices.push({
1613                                         'title': formation['name'],
1614                                         'id': formation['formation_id']
1615                                 });
1616                         }
1617                 }
1618         } else if (filter_type === 'formation_defense') {
1619                 choices.push({
1620                         'title': '(None/unknown)',
1621                         'id': 0,
1622                 });
1623                 for (const formation of global_json['formations']) {
1624                         if (!formation['offense']) {
1625                                 choices.push({
1626                                         'title': formation['name'],
1627                                         'id': formation['formation_id']
1628                                 });
1629                         }
1630                 }
1631         } else if (filter_type === 'starting_on') {
1632                 choices.push({
1633                         'title': 'Offense',
1634                         'id': false,  // last_pull_was_ours
1635                 });
1636                 choices.push({
1637                         'title': 'Defense',
1638                         'id': true,  // last_pull_was_ours
1639                 });
1640         } else if (filter_type === 'gender_ratio') {
1641                 for (const [title, id] of Object.entries(find_all_ratios(global_json)).sort()) {
1642                         choices.push({
1643                                 'title': title,
1644                                 'id': id,
1645                         });
1646                 }
1647         }
1648
1649         for (const choice of choices) {
1650                 let label = document.createElement('label');
1651
1652                 let subitem = document.createElement('div');
1653                 subitem.classList.add('option');
1654
1655                 let check = document.createElement('input');
1656                 check.setAttribute('type', 'checkbox');
1657                 check.setAttribute('id', 'choice' + choice.id);
1658                 if (filter !== null && filter.elements.has(choice.id)) {
1659                         check.setAttribute('checked', 'checked');
1660                 }
1661                 check.addEventListener('change', (e) => { checkbox_changed(filter_div, filterset, e, filter_type, choice.id); });
1662
1663                 subitem.appendChild(check);
1664                 subitem.appendChild(document.createTextNode(choice.title));
1665
1666                 label.appendChild(subitem);
1667                 subitems.push(label);
1668         }
1669         submenu.replaceChildren(...subitems);
1670         submenu.style.display = 'block';
1671
1672         if (pill !== null) {
1673                 let rect = pill.getBoundingClientRect();
1674                 submenu.style.top = (rect.bottom + 10) + 'px';
1675                 submenu.style.left = rect.left + 'px';
1676         } else {
1677                 // Position just outside the selected menu.
1678                 let rect = document.getElementById('filter-add-menu').getBoundingClientRect();
1679                 submenu.style.top = (rect.top + menu_idx * 35) + 'px';
1680                 submenu.style.left = (rect.right - 1) + 'px';
1681         }
1682 }
1683
1684 // Find the right filter, if it exists.
1685 function find_filter(filterset, filter_type) {
1686         for (let f of filterset) {
1687                 if (f.type === filter_type) {
1688                         return f;
1689                 }
1690         }
1691         return null;
1692 }
1693
1694 // Equivalent to Array.prototype.filter, but in-place.
1695 function inplace_filter(arr, cond) {
1696         let j = 0;
1697         for (let i = 0; i < arr.length; ++i) {
1698                 if (cond(arr[i])) {
1699                         arr[j++] = arr[i];
1700                 }
1701         }
1702         arr.length = j;
1703 }
1704
1705 function add_new_filterset() {
1706         let template = document.querySelector('.filter');  // First one is fine.
1707         let div = template.cloneNode(true);
1708         let add_menu = div.querySelector('#filter-add-menu');
1709         if (add_menu !== null) {
1710                 div.removeChild(add_menu);
1711         }
1712         let submenu = div.querySelector('#filter-submenu');
1713         if (submenu !== null) {
1714                 div.removeChild(submenu);
1715         }
1716         div.querySelector('.filters').replaceChildren();
1717         div.dataset.filterId = next_filterset_id++;
1718         template.parentElement.appendChild(div);
1719 }
1720
1721 function try_gc_filter_menus(cheap) {
1722         let empties = [];
1723         let divs = [];
1724         for (const filter_div of document.querySelectorAll('.filter')) {
1725                 let id = filter_div.dataset.filterId;
1726                 divs.push(filter_div);
1727                 empties.push(global_filters[id] === undefined || global_filters[id].length === 0);
1728         }
1729         let last_div = divs[empties.length - 1];
1730         if (cheap) {
1731                 // See if we have two empty filter lists at the bottom of the list;
1732                 // if so, we can remove one without it looking funny in the UI.
1733                 // If not, we'll have to wait until closing the menu.
1734                 // (The menu is positioned at the second-last one, so we can
1735                 // remove the last one without issue.)
1736                 if (empties.length >= 2 && empties[empties.length - 2] && empties[empties.length - 1]) {
1737                         delete global_filters[last_div.dataset.filterId];
1738                         last_div.parentElement.removeChild(last_div);
1739                 }
1740         } else {
1741                 // This is a different situation from try_cheap_gc(), where we should
1742                 // remove the one _not_ last. We might need to move the menu to the last one,
1743                 // though, so it doesn't get lost.
1744                 for (let i = 0; i < empties.length - 1; ++i) {
1745                         if (!empties[i]) {
1746                                 continue;
1747                         }
1748                         let div = divs[i];
1749                         delete global_filters[div.dataset.filterId];
1750                         let add_menu = div.querySelector('#filter-add-menu');
1751                         if (add_menu !== null) {
1752                                 div.removeChild(add_menu);
1753                                 last_div.appendChild(add_menu);
1754                         }
1755                         let submenu = div.querySelector('#filter-submenu');
1756                         if (submenu !== null) {
1757                                 div.removeChild(submenu);
1758                                 last_div.appendChild(submenu);
1759                         }
1760                         div.parentElement.removeChild(div);
1761                 }
1762         }
1763 }
1764
1765 function checkbox_changed(filter_div, filterset, e, filter_type, id) {
1766         let filter = find_filter(filterset, filter_type);
1767         let pills_div = filter_div.querySelector('.filters');
1768         if (e.target.checked) {
1769                 // See if we must create a new empty filterset (since this went from
1770                 // empty to non-empty).
1771                 if (filterset.length === 0) {
1772                         add_new_filterset();
1773                 }
1774
1775                 // See if we must add a new filter to the list.
1776                 if (filter === null) {
1777                         filter = {
1778                                 'type': filter_type,
1779                                 'elements': new Set([ id ]),
1780                         };
1781                         filter.pill = make_filter_pill(filter_div, filterset, filter);
1782                         filterset.push(filter);
1783                         pills_div.appendChild(filter.pill);
1784                 } else {
1785                         filter.elements.add(id);
1786                         let new_pill = make_filter_pill(filter_div, filterset, filter);
1787                         pills_div.replaceChild(new_pill, filter.pill);
1788                         filter.pill = new_pill;
1789                 }
1790         } else {
1791                 filter.elements.delete(id);
1792                 if (filter.elements.size === 0) {
1793                         pills_div.removeChild(filter.pill);
1794                         inplace_filter(filterset, f => f !== filter);
1795
1796                         if (filterset.length == 0) {
1797                                 try_gc_filter_menus(true);
1798                         }
1799                 } else {
1800                         let new_pill = make_filter_pill(filter_div, filterset, filter);
1801                         pills_div.replaceChild(new_pill, filter.pill);
1802                         filter.pill = new_pill;
1803                 }
1804         }
1805
1806         process_matches(global_json, global_filters);
1807 }
1808
1809 function make_filter_pill(filter_div, filterset, filter) {
1810         let pill = document.createElement('div');
1811         pill.classList.add('filter-pill');
1812         let text;
1813         if (filter.type === 'match') {
1814                 text = 'Match: ';
1815
1816                 let all_names = [];
1817                 for (const match_id of filter.elements) {
1818                         all_names.push(find_match(match_id)['description']);
1819                 }
1820                 let common_prefix = find_common_prefix_of_all(all_names);
1821                 if (common_prefix !== null) {
1822                         text += common_prefix + '(';
1823                 }
1824
1825                 let first = true;
1826                 let sorted_match_id = Array.from(filter.elements).sort((a, b) => a - b);
1827                 for (const match_id of sorted_match_id) {
1828                         if (!first) {
1829                                 text += ', ';
1830                         }
1831                         let desc = find_match(match_id)['description'];
1832                         if (common_prefix === null) {
1833                                 text += desc;
1834                         } else {
1835                                 text += desc.substr(common_prefix.length);
1836                         }
1837                         first = false;
1838                 }
1839
1840                 if (common_prefix !== null) {
1841                         text += ')';
1842                 }
1843         } else if (filter.type === 'player_any') {
1844                 text = 'Player (any): ';
1845                 let sorted_players = Array.from(filter.elements).sort((a, b) => player_pos(a) - player_pos(b));
1846                 let first = true;
1847                 for (const player_id of sorted_players) {
1848                         if (!first) {
1849                                 text += ', ';
1850                         }
1851                         text += find_player(player_id)['name'];
1852                         first = false;
1853                 }
1854         } else if (filter.type === 'player_all') {
1855                 text = 'Players: ';
1856                 let sorted_players = Array.from(filter.elements).sort((a, b) => player_pos(a) - player_pos(b));
1857                 let first = true;
1858                 for (const player_id of sorted_players) {
1859                         if (!first) {
1860                                 text += ' AND ';
1861                         }
1862                         text += find_player(player_id)['name'];
1863                         first = false;
1864                 }
1865         } else if (filter.type === 'formation_offense' || filter.type === 'formation_defense') {
1866                 const offense = (filter.type === 'formation_offense');
1867                 if (offense) {
1868                         text = 'Offense: ';
1869                 } else {
1870                         text = 'Defense: ';
1871                 }
1872
1873                 let all_names = [];
1874                 for (const formation_id of filter.elements) {
1875                         all_names.push(find_formation(formation_id)['name']);
1876                 }
1877                 let common_prefix = find_common_prefix_of_all(all_names);
1878                 if (common_prefix !== null) {
1879                         text += common_prefix + '(';
1880                 }
1881
1882                 let first = true;
1883                 let sorted_formation_id = Array.from(filter.elements).sort((a, b) => a - b);
1884                 for (const formation_id of sorted_formation_id) {
1885                         if (!first) {
1886                                 ktext += ', ';
1887                         }
1888                         let desc = find_formation(formation_id)['name'];
1889                         if (common_prefix === null) {
1890                                 text += desc;
1891                         } else {
1892                                 text += desc.substr(common_prefix.length);
1893                         }
1894                         first = false;
1895                 }
1896
1897                 if (common_prefix !== null) {
1898                         text += ')';
1899                 }
1900         } else if (filter.type === 'starting_on') {
1901                 text = 'Starting on: ';
1902
1903                 if (filter.elements.has(false) && filter.elements.has(true)) {
1904                         text += 'Any';
1905                 } else if (filter.elements.has(false)) {
1906                         text += 'Offense';
1907                 } else {
1908                         text += 'Defense';
1909                 }
1910         } else if (filter.type === 'gender_ratio') {
1911                 text = 'Gender: ';
1912
1913                 let first = true;
1914                 for (const name of Array.from(filter.elements).sort()) {
1915                         if (!first) {
1916                                 text += '; ';
1917                         }
1918                         text += name;  // FIXME
1919                         first = false;
1920                 }
1921         }
1922
1923         let text_node = document.createElement('span');
1924         text_node.innerText = text;
1925         text_node.addEventListener('click', (e) => show_submenu(filter_div, filterset, null, pill, filter.type));
1926         pill.appendChild(text_node);
1927
1928         pill.appendChild(document.createTextNode(' '));
1929
1930         let delete_node = document.createElement('span');
1931         delete_node.innerText = '✖';
1932         delete_node.addEventListener('click', (e) => {
1933                 // Delete this filter entirely.
1934                 pill.parentElement.removeChild(pill);
1935                 inplace_filter(filterset, f => f !== filter);
1936                 if (filterset.length == 0) {
1937                         try_gc_filter_menus(false);
1938                 }
1939                 process_matches(global_json, global_filters);
1940
1941                 let add_menu = document.getElementById('filter-add-menu');
1942                 let add_submenu = document.getElementById('filter-submenu');
1943                 add_menu.style.display = 'none';
1944                 add_submenu.style.display = 'none';
1945         });
1946         pill.appendChild(delete_node);
1947         pill.style.cursor = 'pointer';
1948
1949         return pill;
1950 }
1951
1952 function make_filter_marker(filterset) {
1953         let text = '';
1954         for (const filter of filterset) {
1955                 if (text !== '') {
1956                         text += ',';
1957                 }
1958                 if (filter.type === 'match') {
1959                         let all_names = [];
1960                         for (const match of global_json['matches']) {
1961                                 all_names.push(match['description']);
1962                         }
1963                         let common_prefix = find_common_prefix_of_all(all_names);
1964
1965                         let sorted_match_id = Array.from(filter.elements).sort((a, b) => a - b);
1966                         for (const match_id of sorted_match_id) {
1967                                 let desc = find_match(match_id)['description'];
1968                                 if (common_prefix === null) {
1969                                         text += desc.substr(0, 3);
1970                                 } else {
1971                                         text += desc.substr(common_prefix.length, 3);
1972                                 }
1973                         }
1974                 } else if (filter.type === 'player_any' || filter.type === 'player_all') {
1975                         let sorted_players = Array.from(filter.elements).sort((a, b) => player_pos(a) - player_pos(b));
1976                         for (const player_id of sorted_players) {
1977                                 text += find_player(player_id)['name'].substr(0, 3);
1978                         }
1979                 } else if (filter.type === 'formation_offense' || filter.type === 'formation_defense') {
1980                         let sorted_formation_id = Array.from(filter.elements).sort((a, b) => a - b);
1981                         for (const formation_id of sorted_formation_id) {
1982                                 text += find_formation(formation_id)['name'].substr(0, 3);
1983                         }
1984                 } else if (filter.type === 'starting_on') {
1985                         if (filter.elements.has(false) && filter.elements.has(true)) {
1986                                 // Nothing.
1987                         } else if (filter.elements.has(false)) {
1988                                 text += 'O';
1989                         } else {
1990                                 text += 'D';
1991                         }
1992                 } else if (filter.type === 'gender_ratio') {
1993                         let first = true;
1994                         for (const name of Array.from(filter.elements).sort()) {
1995                                 if (!first) {
1996                                         text += '; ';
1997                                 }
1998                                 text += name.replaceAll(' ', '').substr(0, 2);  // 4 F, 3M -> 4 F.
1999                                 first = false;
2000                         }
2001                 }
2002         }
2003         return text;
2004 }
2005
2006 function find_common_prefix(a, b) {
2007         let ret = '';
2008         for (let i = 0; i < Math.min(a.length, b.length); ++i) {
2009                 if (a[i] === b[i]) {
2010                         ret += a[i];
2011                 } else {
2012                         break;
2013                 }
2014         }
2015         return ret;
2016 }
2017
2018 function find_common_prefix_of_all(values) {
2019         if (values.length < 2) {
2020                 return null;
2021         }
2022         let common_prefix = null;
2023         for (const desc of values) {
2024                 if (common_prefix === null) {
2025                         common_prefix = desc;
2026                 } else {
2027                         common_prefix = find_common_prefix(common_prefix, desc);
2028                 }
2029         }
2030         if (common_prefix.length >= 3) {
2031                 return common_prefix;
2032         } else {
2033                 return null;
2034         }
2035 }
2036
2037 function find_match(match_id) {
2038         for (const match of global_json['matches']) {
2039                 if (match['match_id'] === match_id) {
2040                         return match;
2041                 }
2042         }
2043         return null;
2044 }
2045
2046 function find_formation(formation_id) {
2047         for (const formation of global_json['formations']) {
2048                 if (formation['formation_id'] === formation_id) {
2049                         return formation;
2050                 }
2051         }
2052         return null;
2053 }
2054
2055 function find_player(player_id) {
2056         for (const player of global_json['players']) {
2057                 if (player['player_id'] === player_id) {
2058                         return player;
2059                 }
2060         }
2061         return null;
2062 }
2063
2064 function player_pos(player_id) {
2065         let i = 0;
2066         for (const player of global_json['players']) {
2067                 if (player['player_id'] === player_id) {
2068                         return i;
2069                 }
2070                 ++i;
2071         }
2072         return null;
2073 }
2074
2075 function keep_match(match_id, filters) {
2076         for (const filter of filters) {
2077                 if (filter.type === 'match') {
2078                         return filter.elements.has(match_id);
2079                 }
2080         }
2081         return true;
2082 }
2083
2084 // Returns a map of e.g. F => 4, M => 3.
2085 function find_gender_ratio(players) {
2086         let map = {};
2087         for (const [q,p] of Object.entries(players)) {
2088                 if (p.on_field_since === null) {
2089                         continue;
2090                 }
2091                 let gender = p.gender;
2092                 if (gender === '' || gender === undefined || gender === null) {
2093                         gender = '?';
2094                 }
2095                 if (map[gender] === undefined) {
2096                         map[gender] = 1;
2097 q               } else {
2098                         ++map[gender];
2099                 }
2100         }
2101         return map;
2102 }
2103
2104 function find_gender_ratio_code(players) {
2105         let map = find_gender_ratio(players);
2106         let all_genders = Array.from(Object.keys(map)).sort(
2107                 (a,b) => {
2108                         if (map[a] !== map[b]) {
2109                                 return map[b] - map[a];  // Reverse numeric.
2110                         } else if (a < b) {
2111                                 return -1;
2112                         } else if (a > b) {
2113                                 return 1;
2114                         } else {
2115                                 return 0;
2116                         }
2117                 });
2118         let code = '';
2119         for (const g of all_genders) {
2120                 if (code !== '') {
2121                         code += ', ';
2122                 }
2123                 code += map[g];
2124                 code += ' ';
2125                 code += g;
2126         }
2127         return code;
2128 }
2129
2130 // null if none (e.g., if playing 3–3).
2131 function find_predominant_gender(players) {
2132         let max = 0;
2133         let predominant_gender = null;
2134         for (const [gender, num] of Object.entries(find_gender_ratio(players))) {
2135                 if (num > max) {
2136                         max = num;
2137                         predominant_gender = gender;
2138                 } else if (num == max) {
2139                         predominant_gender = null;  // At least two have the same.
2140                 }
2141         }
2142         return predominant_gender;
2143 }
2144
2145 function find_num_players_on_field(players) {
2146         let num = 0;
2147         for (const [q,p] of Object.entries(players)) {
2148                 if (p.on_field_since !== null) {
2149                         ++num;
2150                 }
2151         }
2152         return num;
2153 }
2154
2155 function filter_passes(players, formations_used_this_point, last_pull_was_ours, filter) {
2156         if (filter.type === 'player_any') {
2157                 for (const p of Array.from(filter.elements)) {
2158                         if (players[p].on_field_since !== null) {
2159                                 return true;
2160                         }
2161                 }
2162                 return false;
2163         } else if (filter.type === 'player_all') {
2164                 for (const p of Array.from(filter.elements)) {
2165                         if (players[p].on_field_since === null) {
2166                                 return false;
2167                         }
2168                 }
2169                 return true;
2170         } else if (filter.type === 'formation_offense' || filter.type === 'formation_defense') {
2171                 for (const f of Array.from(filter.elements)) {
2172                         if (formations_used_this_point.has(f)) {
2173                                 return true;
2174                         }
2175                 }
2176                 return false;
2177         } else if (filter.type === 'starting_on') {
2178                 return filter.elements.has(last_pull_was_ours);
2179         } else if (filter.type === 'gender_ratio') {
2180                 return filter.elements.has(find_gender_ratio_code(players));
2181         }
2182         return true;
2183 }
2184
2185 function keep_event(players, formations_used_this_point, last_pull_was_ours, filters) {
2186         for (const filter of filters) {
2187                 if (!filter_passes(players, formations_used_this_point, last_pull_was_ours, filter)) {
2188                         return false;
2189                 }
2190         }
2191         return true;
2192 }
2193
2194 // Heuristic: If we go at least ten seconds without the possession changing
2195 // or the operator specifying some other formation, we probably play the
2196 // same formation as the last point.
2197 function should_reuse_last_formation(events, t) {
2198         for (const e of events) {
2199                 if (e.t <= t) {
2200                         continue;
2201                 }
2202                 if (e.t > t + 10000) {
2203                         break;
2204                 }
2205                 const type = e.type;
2206                 if (type === 'their_goal' || type === 'goal' ||
2207                     type === 'set_defense' || type === 'set_offense' ||
2208                     type === 'throwaway' || type === 'their_throwaway' ||
2209                     type === 'drop' || type === 'was_d' || type === 'stallout' || type === 'defense' || type === 'interception' ||
2210                     type === 'pull' || type === 'pull_landed' || type === 'pull_oob' || type === 'their_pull' ||
2211                     type === 'formation_offense' || type === 'formation_defense') {
2212                         return false;
2213                 }
2214         }
2215         return true;
2216 }
2217
2218 function possibly_close_menu(e) {
2219         if (e.target.closest('.filter-click-to-add') === null &&
2220             e.target.closest('#filter-add-menu') === null &&
2221             e.target.closest('#filter-submenu') === null &&
2222             e.target.closest('.filter-pill') === null) {
2223                 let add_menu = document.getElementById('filter-add-menu');
2224                 let add_submenu = document.getElementById('filter-submenu');
2225                 add_menu.style.display = 'none';
2226                 add_submenu.style.display = 'none';
2227                 try_gc_filter_menus(false);
2228         }
2229 }
2230
2231 let global_sort = {};
2232
2233 function sort_by(th) {
2234         let tr = th.parentElement;
2235         let child_idx = 0;
2236         for (let column_idx = 0; column_idx < tr.children.length; ++column_idx) {
2237                 let element = tr.children[column_idx];
2238                 if (element === th) {
2239                         ++child_idx;  // Pad.
2240                         break;
2241                 }
2242                 if (element.hasAttribute('colspan')) {
2243                         child_idx += parseInt(element.getAttribute('colspan'));
2244                 } else {
2245                         ++child_idx;
2246                 }
2247         }
2248
2249         global_sort = {};
2250         let table = tr.parentElement;
2251         for (let row_idx = 1; row_idx < table.children.length - 1; ++row_idx) {  // Skip header and globals.
2252                 let row = table.children[row_idx];
2253                 let player = parseInt(row.dataset.player);
2254                 let value = row.children[child_idx].textContent;
2255                 global_sort[player] = value;
2256         }
2257 }
2258
2259 function get_sorted_players(players)
2260 {
2261         let p = Object.entries(players);
2262         if (global_sort.length !== 0) {
2263                 p.sort((a,b) => {
2264                         let ai = parseFloat(global_sort[a[0]]);
2265                         let bi = parseFloat(global_sort[b[0]]);
2266                         if (ai == ai && bi == bi) {
2267                                 return bi - ai;  // Reverse numeric.
2268                         } else if (global_sort[a[0]] < global_sort[b[0]]) {
2269                                 return -1;
2270                         } else if (global_sort[a[0]] > global_sort[b[0]]) {
2271                                 return 1;
2272                         } else {
2273                                 return 0;
2274                         }
2275                 });
2276         }
2277         return p;
2278 }