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