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