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