]> git.sesse.net Git - pkanalytics/blob - ultimate.js
87c976ad7e4ac835820587392f14fcd105132ffe
[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', 6);
939                 add_th(header, 'Their team', 6);
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, '');
948                 add_3cell(row, globals.turnovers_won);
949                 add_3cell(row, '');
950                 add_3cell(row, globals.turnovers_lost);
951                 rows.push(row);
952         }
953
954         // Clean holds.
955         {
956                 let row = document.createElement('tr');
957                 let name = add_3cell(row, 'Clean holds', 'name');
958                 let our_clean_holds = make_binomial_ci(globals.clean_holds, globals.offensive_points_completed, z);
959                 let their_clean_holds = make_binomial_ci(globals.their_clean_holds, globals.defensive_points_completed, z);
960                 our_clean_holds.desired = 0.3;  // Arbitrary.
961                 our_clean_holds.format = 'percentage';
962                 their_clean_holds.desired = 0.3;
963                 their_clean_holds.format = 'percentage';
964                 add_3cell(row, globals.clean_holds + ' / ' + globals.offensive_points_completed);
965                 add_3cell_ci(row, our_clean_holds);
966                 add_3cell(row, globals.their_clean_holds + ' / ' + globals.defensive_points_completed);
967                 add_3cell_ci(row, their_clean_holds);
968                 rows.push(row);
969         }
970
971         // Clean breaks.
972         {
973                 let row = document.createElement('tr');
974                 let name = add_3cell(row, 'Clean breaks', 'name');
975                 let our_clean_breaks = make_binomial_ci(globals.clean_breaks, globals.defensive_points_completed, z);
976                 let their_clean_breaks = make_binomial_ci(globals.their_clean_breaks, globals.offensive_points_completed, z);
977                 our_clean_breaks.desired = 0.3;  // Arbitrary.
978                 our_clean_breaks.format = 'percentage';
979                 their_clean_breaks.desired = 0.3;
980                 their_clean_breaks.format = 'percentage';
981                 add_3cell(row, globals.clean_breaks + ' / ' + globals.defensive_points_completed);
982                 add_3cell_ci(row, our_clean_breaks);
983                 add_3cell(row, globals.their_clean_breaks + ' / ' + globals.offensive_points_completed);
984                 add_3cell_ci(row, their_clean_breaks);
985                 rows.push(row);
986         }
987
988         return rows;
989 }
990
991 function make_table_offense(players) {
992         let rows = [];
993         {
994                 let header = document.createElement('tr');
995                 add_th(header, 'Player');
996                 add_th(header, 'Goals');
997                 add_th(header, 'Assists');
998                 add_th(header, 'Hockey assists');
999                 add_th(header, 'Throws');
1000                 add_th(header, 'Throwaways');
1001                 add_th(header, '%OK');
1002                 add_th(header, 'Catches');
1003                 add_th(header, 'Drops');
1004                 add_th(header, 'D-ed');
1005                 add_th(header, '%OK');
1006                 add_th(header, 'Stalls');
1007                 add_th(header, 'Soft +/-', 6);
1008                 rows.push(header);
1009         }
1010
1011         let goals = 0;
1012         let num_throws = 0;
1013         let throwaways = 0;
1014         let catches = 0;
1015         let drops = 0;
1016         let was_ds = 0;
1017         let stallouts = 0;
1018         for (const [q,p] of get_sorted_players(players)) {
1019                 if (q === 'globals') continue;
1020                 let throw_ok = make_binomial_ci(p.num_throws - p.throwaways, p.num_throws, z);
1021                 let catch_ok = make_binomial_ci(p.catches, p.catches + p.drops + p.was_ds, z);
1022
1023                 throw_ok.format = 'percentage';
1024                 catch_ok.format = 'percentage';
1025
1026                 // Desire at least 90% percentage. Fairly arbitrary.
1027                 throw_ok.desired = 0.9;
1028                 catch_ok.desired = 0.9;
1029
1030                 let row = document.createElement('tr');
1031                 add_3cell(row, p.name, 'name');  // TODO: number?
1032                 add_3cell(row, p.goals);
1033                 add_3cell(row, p.assists);
1034                 add_3cell(row, p.hockey_assists);
1035                 add_3cell(row, p.num_throws);
1036                 add_3cell(row, p.throwaways);
1037                 add_3cell_ci(row, throw_ok);
1038                 add_3cell(row, p.catches);
1039                 add_3cell(row, p.drops);
1040                 add_3cell(row, p.was_ds);
1041                 add_3cell_ci(row, catch_ok);
1042                 add_3cell(row, p.stallouts);
1043                 add_3cell(row, '+' + p.offensive_soft_plus);
1044                 add_3cell(row, '-' + p.offensive_soft_minus);
1045                 row.dataset.player = q;
1046                 rows.push(row);
1047
1048                 goals += p.goals;
1049                 num_throws += p.num_throws;
1050                 throwaways += p.throwaways;
1051                 catches += p.catches;
1052                 drops += p.drops;
1053                 was_ds += p.was_ds;
1054                 stallouts += p.stallouts;
1055         }
1056
1057         // Globals.
1058         let throw_ok = make_binomial_ci(num_throws - throwaways, num_throws, z);
1059         let catch_ok = make_binomial_ci(catches, catches + drops + was_ds, z);
1060         throw_ok.format = 'percentage';
1061         catch_ok.format = 'percentage';
1062         throw_ok.desired = 0.9;
1063         catch_ok.desired = 0.9;
1064
1065         let row = document.createElement('tr');
1066         add_3cell(row, '');
1067         add_3cell(row, goals);
1068         add_3cell(row, '');
1069         add_3cell(row, '');
1070         add_3cell(row, num_throws);
1071         add_3cell(row, throwaways);
1072         add_3cell_ci(row, throw_ok);
1073         add_3cell(row, catches);
1074         add_3cell(row, drops);
1075         add_3cell(row, was_ds);
1076         add_3cell_ci(row, catch_ok);
1077         add_3cell(row, stallouts);
1078         add_3cell(row, '');
1079         add_3cell(row, '');
1080         rows.push(row);
1081
1082         return rows;
1083 }
1084
1085 function make_table_defense(players) {
1086         let rows = [];
1087         {
1088                 let header = document.createElement('tr');
1089                 add_th(header, 'Player');
1090                 add_th(header, 'Ds');
1091                 add_th(header, 'Pulls');
1092                 add_th(header, 'OOB pulls');
1093                 add_th(header, 'OOB%');
1094                 add_th(header, 'Avg. hang time (IB)');
1095                 add_th(header, 'Callahans');
1096                 add_th(header, 'Soft +/-', 6);
1097                 rows.push(header);
1098         }
1099
1100         let defenses = 0;
1101         let pulls = 0;
1102         let oob_pulls = 0;
1103         let sum_sum_time = 0;
1104         let callahans = 0;
1105
1106         for (const [q,p] of get_sorted_players(players)) {
1107                 if (q === 'globals') continue;
1108                 let sum_time = 0;
1109                 for (const t of p.pull_times) {
1110                         sum_time += t;
1111                 }
1112                 let avg_time = 1e-3 * sum_time / (p.pulls - p.oob_pulls);
1113                 let oob_pct = 100 * p.oob_pulls / p.pulls;
1114
1115                 let ci_oob = make_binomial_ci(p.oob_pulls, p.pulls, z);
1116                 ci_oob.format = 'percentage';
1117                 ci_oob.desired = 0.2;  // Arbitrary.
1118                 ci_oob.inverted = true;
1119
1120                 let row = document.createElement('tr');
1121                 add_3cell(row, p.name, 'name');  // TODO: number?
1122                 add_3cell(row, p.defenses);
1123                 add_3cell(row, p.pulls);
1124                 add_3cell(row, p.oob_pulls);
1125                 add_3cell_ci(row, ci_oob);
1126                 if (p.pulls > p.oob_pulls) {
1127                         add_3cell(row, avg_time.toFixed(1) + ' sec');
1128                 } else {
1129                         add_3cell(row, 'N/A');
1130                 }
1131                 add_3cell(row, p.callahans);
1132                 add_3cell(row, '+' + p.defensive_soft_plus);
1133                 add_3cell(row, '-' + p.defensive_soft_minus);
1134                 row.dataset.player = q;
1135                 rows.push(row);
1136
1137                 defenses += p.defenses;
1138                 pulls += p.pulls;
1139                 oob_pulls += p.oob_pulls;
1140                 sum_sum_time += sum_time;
1141                 callahans += p.callahans;
1142         }
1143
1144         // Globals.
1145         let ci_oob = make_binomial_ci(oob_pulls, pulls, z);
1146         ci_oob.format = 'percentage';
1147         ci_oob.desired = 0.2;  // Arbitrary.
1148         ci_oob.inverted = true;
1149
1150         let avg_time = 1e-3 * sum_sum_time / (pulls - oob_pulls);
1151         let oob_pct = 100 * oob_pulls / pulls;
1152
1153         let row = document.createElement('tr');
1154         add_3cell(row, '');
1155         add_3cell(row, defenses);
1156         add_3cell(row, pulls);
1157         add_3cell(row, oob_pulls);
1158         add_3cell_ci(row, ci_oob);
1159         if (pulls > oob_pulls) {
1160                 add_3cell(row, avg_time.toFixed(1) + ' sec');
1161         } else {
1162                 add_3cell(row, 'N/A');
1163         }
1164         add_3cell(row, callahans);
1165         add_3cell(row, '');
1166         add_3cell(row, '');
1167         rows.push(row);
1168
1169         return rows;
1170 }
1171
1172 function make_table_playing_time(players) {
1173         let rows = [];
1174         {
1175                 let header = document.createElement('tr');
1176                 add_th(header, 'Player');
1177                 add_th(header, 'Points played');
1178                 add_th(header, 'Time played');
1179                 add_th(header, 'O time');
1180                 add_th(header, 'D time');
1181                 add_th(header, 'Time on field');
1182                 add_th(header, 'O points');
1183                 add_th(header, 'D points');
1184                 rows.push(header);
1185         }
1186
1187         for (const [q,p] of get_sorted_players(players)) {
1188                 if (q === 'globals') continue;
1189                 let row = document.createElement('tr');
1190                 add_3cell(row, p.name, 'name');  // TODO: number?
1191                 add_3cell(row, p.points_played);
1192                 add_3cell(row, Math.floor(p.playing_time_ms / 60000) + ' min');
1193                 add_3cell(row, Math.floor(p.offensive_playing_time_ms / 60000) + ' min');
1194                 add_3cell(row, Math.floor(p.defensive_playing_time_ms / 60000) + ' min');
1195                 add_3cell(row, Math.floor(p.field_time_ms / 60000) + ' min');
1196                 add_3cell(row, p.offensive_points_completed);
1197                 add_3cell(row, p.defensive_points_completed);
1198                 row.dataset.player = q;
1199                 rows.push(row);
1200         }
1201
1202         // Globals.
1203         let globals = players['globals'];
1204         let row = document.createElement('tr');
1205         add_3cell(row, '');
1206         add_3cell(row, globals.points_played);
1207         add_3cell(row, Math.floor(globals.playing_time_ms / 60000) + ' min');
1208         add_3cell(row, Math.floor(globals.offensive_playing_time_ms / 60000) + ' min');
1209         add_3cell(row, Math.floor(globals.defensive_playing_time_ms / 60000) + ' min');
1210         add_3cell(row, Math.floor(globals.field_time_ms / 60000) + ' min');
1211         add_3cell(row, globals.offensive_points_completed);
1212         add_3cell(row, globals.defensive_points_completed);
1213         rows.push(row);
1214
1215         return rows;
1216 }
1217
1218 function make_table_per_point(players) {
1219         let rows = [];
1220         {
1221                 let header = document.createElement('tr');
1222                 add_th(header, 'Player');
1223                 add_th(header, 'Goals');
1224                 add_th(header, 'Assists');
1225                 add_th(header, 'Hockey assists');
1226                 add_th(header, 'Ds');
1227                 add_th(header, 'Throwaways');
1228                 add_th(header, 'Recv. errors');
1229                 add_th(header, 'Touches');
1230                 rows.push(header);
1231         }
1232
1233         let goals = 0;
1234         let assists = 0;
1235         let hockey_assists = 0;
1236         let defenses = 0;
1237         let throwaways = 0;
1238         let receiver_errors = 0;
1239         let touches = 0;
1240         for (const [q,p] of get_sorted_players(players)) {
1241                 if (q === 'globals') continue;
1242
1243                 // Can only happen once per point, so these are binomials.
1244                 let ci_goals = make_binomial_ci(p.goals, p.points_played, z);
1245                 let ci_assists = make_binomial_ci(p.assists, p.points_played, z);
1246                 let ci_hockey_assists = make_binomial_ci(p.hockey_assists, p.points_played, z);
1247                 // Arbitrarily desire at least 10% (not everybody can score or assist).
1248                 ci_goals.desired = 0.1;
1249                 ci_assists.desired = 0.1;
1250                 ci_hockey_assists.desired = 0.1;
1251
1252                 let row = document.createElement('tr');
1253                 add_3cell(row, p.name, 'name');  // TODO: number?
1254                 add_3cell_ci(row, ci_goals);
1255                 add_3cell_ci(row, ci_assists);
1256                 add_3cell_ci(row, ci_hockey_assists);
1257                 add_3cell_ci(row, make_poisson_ci(p.defenses, p.points_played, z));
1258                 add_3cell_ci(row, make_poisson_ci(p.throwaways, p.points_played, z, true));
1259                 add_3cell_ci(row, make_poisson_ci(p.drops + p.was_ds, p.points_played, z, true));
1260                 if (p.points_played > 0) {
1261                         add_3cell(row, p.touches == 0 ? 0 : (p.touches / p.points_played).toFixed(2));
1262                 } else {
1263                         add_3cell(row, 'N/A');
1264                 }
1265                 row.dataset.player = q;
1266                 rows.push(row);
1267
1268                 goals += p.goals;
1269                 assists += p.assists;
1270                 hockey_assists += p.hockey_assists;
1271                 defenses += p.defenses;
1272                 throwaways += p.throwaways;
1273                 receiver_errors += p.drops + p.was_ds;
1274                 touches += p.touches;
1275         }
1276
1277         // Globals.
1278         let globals = players['globals'];
1279         let row = document.createElement('tr');
1280         add_3cell(row, '');
1281         if (globals.points_played > 0) {
1282                 let ci_goals = make_binomial_ci(goals, globals.points_played, z);
1283                 let ci_assists = make_binomial_ci(assists, globals.points_played, z);
1284                 let ci_hockey_assists = make_binomial_ci(hockey_assists, globals.points_played, z);
1285                 ci_goals.desired = 0.5;
1286                 ci_assists.desired = 0.5;
1287                 ci_hockey_assists.desired = 0.5;
1288
1289                 add_3cell_ci(row, ci_goals);
1290                 add_3cell_ci(row, ci_assists);
1291                 add_3cell_ci(row, ci_hockey_assists);
1292
1293                 add_3cell_ci(row, make_poisson_ci(defenses, globals.points_played, z));
1294                 add_3cell_ci(row, make_poisson_ci(throwaways, globals.points_played, z, true));
1295                 add_3cell_ci(row, make_poisson_ci(receiver_errors, globals.points_played, z, true));
1296
1297                 add_3cell(row, touches == 0 ? 0 : (touches / globals.points_played).toFixed(2));
1298         } else {
1299                 add_3cell_with_filler_ci(row, 'N/A');
1300                 add_3cell_with_filler_ci(row, 'N/A');
1301                 add_3cell_with_filler_ci(row, 'N/A');
1302                 add_3cell_with_filler_ci(row, 'N/A');
1303                 add_3cell_with_filler_ci(row, 'N/A');
1304                 add_3cell_with_filler_ci(row, 'N/A');
1305                 add_3cell(row, 'N/A');
1306         }
1307         rows.push(row);
1308
1309         return rows;
1310 }
1311
1312 function open_filter_menu(click_to_add_div) {
1313         document.getElementById('filter-submenu').style.display = 'none';
1314         let filter_div = click_to_add_div.parentElement;
1315         let filter_id = filter_div.dataset.filterId;
1316
1317         let menu = document.getElementById('filter-add-menu');
1318         menu.parentElement.removeChild(menu);
1319         filter_div.appendChild(menu);
1320         menu.style.display = 'block';
1321         menu.replaceChildren();
1322
1323         // Place the menu directly under the “click to add” label;
1324         // we don't anchor it since that label will move around
1325         // and the menu shouldn't.
1326         let rect = click_to_add_div.getBoundingClientRect();
1327         menu.style.left = rect.left + 'px';
1328         menu.style.top = (rect.bottom + 10) + 'px';
1329
1330         let filterset = global_filters[filter_id];
1331         if (filterset === undefined) {
1332                 global_filters[filter_id] = filterset = [];
1333         }
1334
1335         add_menu_item(filter_div, filterset, menu, 0, 'match', 'Match (any)');
1336         add_menu_item(filter_div, filterset, menu, 1, 'player_any', 'Player on field (any)');
1337         add_menu_item(filter_div, filterset, menu, 2, 'player_all', 'Player on field (all)');
1338         add_menu_item(filter_div, filterset, menu, 3, 'formation_offense', 'Offense played (any)');
1339         add_menu_item(filter_div, filterset, menu, 4, 'formation_defense', 'Defense played (any)');
1340         add_menu_item(filter_div, filterset, menu, 5, 'starting_on', 'Starting on');
1341         add_menu_item(filter_div, filterset, menu, 6, 'gender_ratio', 'Gender ratio');
1342 }
1343
1344 function add_menu_item(filter_div, filterset, menu, menu_idx, filter_type, title) {
1345         let item = document.createElement('div');
1346         item.classList.add('option');
1347         item.appendChild(document.createTextNode(title));
1348
1349         let arrow = document.createElement('div');
1350         arrow.classList.add('arrow');
1351         arrow.textContent = '▸';
1352         item.appendChild(arrow);
1353
1354         menu.appendChild(item);
1355
1356         item.addEventListener('click', (e) => { show_submenu(filter_div, filterset, menu_idx, null, filter_type); });
1357 }
1358
1359 function find_all_ratios(json)
1360 {
1361         let ratios = {};
1362         let players = {};
1363         for (const player of json['players']) {
1364                 players[player['player_id']] = {
1365                         'gender': player['gender'],
1366                         'last_point_seen': null,
1367                 };
1368         }
1369         for (const match of json['matches']) {
1370                 for (const [q,p] of Object.entries(players)) {
1371                         p.on_field_since = null;
1372                 }
1373                 for (const e of match['events']) {
1374                         let p = players[e['player']];
1375                         let type = e['type'];
1376                         if (type === 'in') {
1377                                 p.on_field_since = 1;
1378                         } else if (type === 'out') {
1379                                 p.on_field_since = null;
1380                         } else if (type === 'pull' || type == 'their_pull') {  // We assume no cross-gender subs for now.
1381                                 let code = find_gender_ratio_code(players);
1382                                 if (ratios[code] === undefined) {
1383                                         ratios[code] = code;
1384                                         if (code !== '4 F, 3 M' && code !== '4 M, 3 F' && code !== '3 M, 2 F' && code !== '3 F, 2 M') {
1385                                                 console.log('Unexpected gender ratio ' + code + ' first seen at: ' +
1386                                                             match['description'] + ', ' + format_time(e['t']));
1387                                         }
1388                                 }
1389                         }
1390                 }
1391         }
1392         return ratios;
1393 }
1394
1395 function show_submenu(filter_div, filterset, menu_idx, pill, filter_type) {
1396         let submenu = document.getElementById('filter-submenu');
1397
1398         // Move to the same place as the top-level menu.
1399         submenu.parentElement.removeChild(submenu);
1400         document.getElementById('filter-add-menu').parentElement.appendChild(submenu);
1401
1402         let subitems = [];
1403         const filter = find_filter(filterset, filter_type);
1404
1405         let choices = [];
1406         if (filter_type === 'match') {
1407                 for (const match of global_json['matches']) {
1408                         choices.push({
1409                                 'title': match['description'],
1410                                 'id': match['match_id']
1411                         });
1412                 }
1413         } else if (filter_type === 'player_any' || filter_type === 'player_all') {
1414                 for (const player of global_json['players']) {
1415                         choices.push({
1416                                 'title': player['name'],
1417                                 'id': player['player_id']
1418                         });
1419                 }
1420         } else if (filter_type === 'formation_offense') {
1421                 choices.push({
1422                         'title': '(None/unknown)',
1423                         'id': 0,
1424                 });
1425                 for (const formation of global_json['formations']) {
1426                         if (formation['offense']) {
1427                                 choices.push({
1428                                         'title': formation['name'],
1429                                         'id': formation['formation_id']
1430                                 });
1431                         }
1432                 }
1433         } else if (filter_type === 'formation_defense') {
1434                 choices.push({
1435                         'title': '(None/unknown)',
1436                         'id': 0,
1437                 });
1438                 for (const formation of global_json['formations']) {
1439                         if (!formation['offense']) {
1440                                 choices.push({
1441                                         'title': formation['name'],
1442                                         'id': formation['formation_id']
1443                                 });
1444                         }
1445                 }
1446         } else if (filter_type === 'starting_on') {
1447                 choices.push({
1448                         'title': 'Offense',
1449                         'id': false,  // last_pull_was_ours
1450                 });
1451                 choices.push({
1452                         'title': 'Defense',
1453                         'id': true,  // last_pull_was_ours
1454                 });
1455         } else if (filter_type === 'gender_ratio') {
1456                 for (const [title, id] of Object.entries(find_all_ratios(global_json)).sort()) {
1457                         choices.push({
1458                                 'title': title,
1459                                 'id': id,
1460                         });
1461                 }
1462         }
1463
1464         for (const choice of choices) {
1465                 let label = document.createElement('label');
1466
1467                 let subitem = document.createElement('div');
1468                 subitem.classList.add('option');
1469
1470                 let check = document.createElement('input');
1471                 check.setAttribute('type', 'checkbox');
1472                 check.setAttribute('id', 'choice' + choice.id);
1473                 if (filter !== null && filter.elements.has(choice.id)) {
1474                         check.setAttribute('checked', 'checked');
1475                 }
1476                 check.addEventListener('change', (e) => { checkbox_changed(filter_div, filterset, e, filter_type, choice.id); });
1477
1478                 subitem.appendChild(check);
1479                 subitem.appendChild(document.createTextNode(choice.title));
1480
1481                 label.appendChild(subitem);
1482                 subitems.push(label);
1483         }
1484         submenu.replaceChildren(...subitems);
1485         submenu.style.display = 'block';
1486
1487         if (pill !== null) {
1488                 let rect = pill.getBoundingClientRect();
1489                 submenu.style.top = (rect.bottom + 10) + 'px';
1490                 submenu.style.left = rect.left + 'px';
1491         } else {
1492                 // Position just outside the selected menu.
1493                 let rect = document.getElementById('filter-add-menu').getBoundingClientRect();
1494                 submenu.style.top = (rect.top + menu_idx * 35) + 'px';
1495                 submenu.style.left = (rect.right - 1) + 'px';
1496         }
1497 }
1498
1499 // Find the right filter, if it exists.
1500 function find_filter(filterset, filter_type) {
1501         for (let f of filterset) {
1502                 if (f.type === filter_type) {
1503                         return f;
1504                 }
1505         }
1506         return null;
1507 }
1508
1509 // Equivalent to Array.prototype.filter, but in-place.
1510 function inplace_filter(arr, cond) {
1511         let j = 0;
1512         for (let i = 0; i < arr.length; ++i) {
1513                 if (cond(arr[i])) {
1514                         arr[j++] = arr[i];
1515                 }
1516         }
1517         arr.length = j;
1518 }
1519
1520 function add_new_filterset() {
1521         let template = document.querySelector('.filter');  // First one is fine.
1522         let div = template.cloneNode(true);
1523         let add_menu = div.querySelector('#filter-add-menu');
1524         if (add_menu !== null) {
1525                 div.removeChild(add_menu);
1526         }
1527         let submenu = div.querySelector('#filter-submenu');
1528         if (submenu !== null) {
1529                 div.removeChild(submenu);
1530         }
1531         div.querySelector('.filters').replaceChildren();
1532         div.dataset.filterId = next_filterset_id++;
1533         template.parentElement.appendChild(div);
1534 }
1535
1536 function try_gc_filter_menus(cheap) {
1537         let empties = [];
1538         let divs = [];
1539         for (const filter_div of document.querySelectorAll('.filter')) {
1540                 let id = filter_div.dataset.filterId;
1541                 divs.push(filter_div);
1542                 empties.push(global_filters[id] === undefined || global_filters[id].length === 0);
1543         }
1544         let last_div = divs[empties.length - 1];
1545         if (cheap) {
1546                 // See if we have two empty filter lists at the bottom of the list;
1547                 // if so, we can remove one without it looking funny in the UI.
1548                 // If not, we'll have to wait until closing the menu.
1549                 // (The menu is positioned at the second-last one, so we can
1550                 // remove the last one without issue.)
1551                 if (empties.length >= 2 && empties[empties.length - 2] && empties[empties.length - 1]) {
1552                         delete global_filters[last_div.dataset.filterId];
1553                         last_div.parentElement.removeChild(last_div);
1554                 }
1555         } else {
1556                 // This is a different situation from try_cheap_gc(), where we should
1557                 // remove the one _not_ last. We might need to move the menu to the last one,
1558                 // though, so it doesn't get lost.
1559                 for (let i = 0; i < empties.length - 1; ++i) {
1560                         if (!empties[i]) {
1561                                 continue;
1562                         }
1563                         let div = divs[i];
1564                         delete global_filters[div.dataset.filterId];
1565                         let add_menu = div.querySelector('#filter-add-menu');
1566                         if (add_menu !== null) {
1567                                 div.removeChild(add_menu);
1568                                 last_div.appendChild(add_menu);
1569                         }
1570                         let submenu = div.querySelector('#filter-submenu');
1571                         if (submenu !== null) {
1572                                 div.removeChild(submenu);
1573                                 last_div.appendChild(submenu);
1574                         }
1575                         div.parentElement.removeChild(div);
1576                 }
1577         }
1578 }
1579
1580 function checkbox_changed(filter_div, filterset, e, filter_type, id) {
1581         let filter = find_filter(filterset, filter_type);
1582         let pills_div = filter_div.querySelector('.filters');
1583         if (e.target.checked) {
1584                 // See if we must create a new empty filterset (since this went from
1585                 // empty to non-empty).
1586                 if (filterset.length === 0) {
1587                         add_new_filterset();
1588                 }
1589
1590                 // See if we must add a new filter to the list.
1591                 if (filter === null) {
1592                         filter = {
1593                                 'type': filter_type,
1594                                 'elements': new Set([ id ]),
1595                         };
1596                         filter.pill = make_filter_pill(filter_div, filterset, filter);
1597                         filterset.push(filter);
1598                         pills_div.appendChild(filter.pill);
1599                 } else {
1600                         filter.elements.add(id);
1601                         let new_pill = make_filter_pill(filter_div, filterset, filter);
1602                         pills_div.replaceChild(new_pill, filter.pill);
1603                         filter.pill = new_pill;
1604                 }
1605         } else {
1606                 filter.elements.delete(id);
1607                 if (filter.elements.size === 0) {
1608                         pills_div.removeChild(filter.pill);
1609                         inplace_filter(filterset, f => f !== filter);
1610
1611                         if (filterset.length == 0) {
1612                                 try_gc_filter_menus(true);
1613                         }
1614                 } else {
1615                         let new_pill = make_filter_pill(filter_div, filterset, filter);
1616                         pills_div.replaceChild(new_pill, filter.pill);
1617                         filter.pill = new_pill;
1618                 }
1619         }
1620
1621         process_matches(global_json, global_filters);
1622 }
1623
1624 function make_filter_pill(filter_div, filterset, filter) {
1625         let pill = document.createElement('div');
1626         pill.classList.add('filter-pill');
1627         let text;
1628         if (filter.type === 'match') {
1629                 text = 'Match: ';
1630
1631                 let all_names = [];
1632                 for (const match_id of filter.elements) {
1633                         all_names.push(find_match(match_id)['description']);
1634                 }
1635                 let common_prefix = find_common_prefix_of_all(all_names);
1636                 if (common_prefix !== null) {
1637                         text += common_prefix + '(';
1638                 }
1639
1640                 let first = true;
1641                 let sorted_match_id = Array.from(filter.elements).sort((a, b) => a - b);
1642                 for (const match_id of sorted_match_id) {
1643                         if (!first) {
1644                                 text += ', ';
1645                         }
1646                         let desc = find_match(match_id)['description'];
1647                         if (common_prefix === null) {
1648                                 text += desc;
1649                         } else {
1650                                 text += desc.substr(common_prefix.length);
1651                         }
1652                         first = false;
1653                 }
1654
1655                 if (common_prefix !== null) {
1656                         text += ')';
1657                 }
1658         } else if (filter.type === 'player_any') {
1659                 text = 'Player (any): ';
1660                 let sorted_players = Array.from(filter.elements).sort((a, b) => player_pos(a) - player_pos(b));
1661                 let first = true;
1662                 for (const player_id of sorted_players) {
1663                         if (!first) {
1664                                 text += ', ';
1665                         }
1666                         text += find_player(player_id)['name'];
1667                         first = false;
1668                 }
1669         } else if (filter.type === 'player_all') {
1670                 text = 'Players: ';
1671                 let sorted_players = Array.from(filter.elements).sort((a, b) => player_pos(a) - player_pos(b));
1672                 let first = true;
1673                 for (const player_id of sorted_players) {
1674                         if (!first) {
1675                                 text += ' AND ';
1676                         }
1677                         text += find_player(player_id)['name'];
1678                         first = false;
1679                 }
1680         } else if (filter.type === 'formation_offense' || filter.type === 'formation_defense') {
1681                 const offense = (filter.type === 'formation_offense');
1682                 if (offense) {
1683                         text = 'Offense: ';
1684                 } else {
1685                         text = 'Defense: ';
1686                 }
1687
1688                 let all_names = [];
1689                 for (const formation_id of filter.elements) {
1690                         all_names.push(find_formation(formation_id)['name']);
1691                 }
1692                 let common_prefix = find_common_prefix_of_all(all_names);
1693                 if (common_prefix !== null) {
1694                         text += common_prefix + '(';
1695                 }
1696
1697                 let first = true;
1698                 let sorted_formation_id = Array.from(filter.elements).sort((a, b) => a - b);
1699                 for (const formation_id of sorted_formation_id) {
1700                         if (!first) {
1701                                 ktext += ', ';
1702                         }
1703                         let desc = find_formation(formation_id)['name'];
1704                         if (common_prefix === null) {
1705                                 text += desc;
1706                         } else {
1707                                 text += desc.substr(common_prefix.length);
1708                         }
1709                         first = false;
1710                 }
1711
1712                 if (common_prefix !== null) {
1713                         text += ')';
1714                 }
1715         } else if (filter.type === 'starting_on') {
1716                 text = 'Starting on: ';
1717
1718                 if (filter.elements.has(false) && filter.elements.has(true)) {
1719                         text += 'Any';
1720                 } else if (filter.elements.has(false)) {
1721                         text += 'Offense';
1722                 } else {
1723                         text += 'Defense';
1724                 }
1725         } else if (filter.type === 'gender_ratio') {
1726                 text = 'Gender: ';
1727
1728                 let first = true;
1729                 for (const name of Array.from(filter.elements).sort()) {
1730                         if (!first) {
1731                                 text += '; ';
1732                         }
1733                         text += name;  // FIXME
1734                         first = false;
1735                 }
1736         }
1737
1738         let text_node = document.createElement('span');
1739         text_node.innerText = text;
1740         text_node.addEventListener('click', (e) => show_submenu(filter_div, filterset, null, pill, filter.type));
1741         pill.appendChild(text_node);
1742
1743         pill.appendChild(document.createTextNode(' '));
1744
1745         let delete_node = document.createElement('span');
1746         delete_node.innerText = '✖';
1747         delete_node.addEventListener('click', (e) => {
1748                 // Delete this filter entirely.
1749                 pill.parentElement.removeChild(pill);
1750                 inplace_filter(filterset, f => f !== filter);
1751                 if (filterset.length == 0) {
1752                         try_gc_filter_menus(false);
1753                 }
1754                 process_matches(global_json, global_filters);
1755
1756                 let add_menu = document.getElementById('filter-add-menu');
1757                 let add_submenu = document.getElementById('filter-submenu');
1758                 add_menu.style.display = 'none';
1759                 add_submenu.style.display = 'none';
1760         });
1761         pill.appendChild(delete_node);
1762         pill.style.cursor = 'pointer';
1763
1764         return pill;
1765 }
1766
1767 function make_filter_marker(filterset) {
1768         let text = '';
1769         for (const filter of filterset) {
1770                 if (text !== '') {
1771                         text += ',';
1772                 }
1773                 if (filter.type === 'match') {
1774                         let all_names = [];
1775                         for (const match of global_json['matches']) {
1776                                 all_names.push(match['description']);
1777                         }
1778                         let common_prefix = find_common_prefix_of_all(all_names);
1779
1780                         let sorted_match_id = Array.from(filter.elements).sort((a, b) => a - b);
1781                         for (const match_id of sorted_match_id) {
1782                                 let desc = find_match(match_id)['description'];
1783                                 if (common_prefix === null) {
1784                                         text += desc.substr(0, 3);
1785                                 } else {
1786                                         text += desc.substr(common_prefix.length, 3);
1787                                 }
1788                         }
1789                 } else if (filter.type === 'player_any' || filter.type === 'player_all') {
1790                         let sorted_players = Array.from(filter.elements).sort((a, b) => player_pos(a) - player_pos(b));
1791                         for (const player_id of sorted_players) {
1792                                 text += find_player(player_id)['name'].substr(0, 3);
1793                         }
1794                 } else if (filter.type === 'formation_offense' || filter.type === 'formation_defense') {
1795                         let sorted_formation_id = Array.from(filter.elements).sort((a, b) => a - b);
1796                         for (const formation_id of sorted_formation_id) {
1797                                 text += find_formation(formation_id)['name'].substr(0, 3);
1798                         }
1799                 } else if (filter.type === 'starting_on') {
1800                         if (filter.elements.has(false) && filter.elements.has(true)) {
1801                                 // Nothing.
1802                         } else if (filter.elements.has(false)) {
1803                                 text += 'O';
1804                         } else {
1805                                 text += 'D';
1806                         }
1807                 } else if (filter.type === 'gender_ratio') {
1808                         let first = true;
1809                         for (const name of Array.from(filter.elements).sort()) {
1810                                 if (!first) {
1811                                         text += '; ';
1812                                 }
1813                                 text += name.replaceAll(' ', '').substr(0, 2);  // 4 F, 3M -> 4 F.
1814                                 first = false;
1815                         }
1816                 }
1817         }
1818         return text;
1819 }
1820
1821 function find_common_prefix(a, b) {
1822         let ret = '';
1823         for (let i = 0; i < Math.min(a.length, b.length); ++i) {
1824                 if (a[i] === b[i]) {
1825                         ret += a[i];
1826                 } else {
1827                         break;
1828                 }
1829         }
1830         return ret;
1831 }
1832
1833 function find_common_prefix_of_all(values) {
1834         if (values.length < 2) {
1835                 return null;
1836         }
1837         let common_prefix = null;
1838         for (const desc of values) {
1839                 if (common_prefix === null) {
1840                         common_prefix = desc;
1841                 } else {
1842                         common_prefix = find_common_prefix(common_prefix, desc);
1843                 }
1844         }
1845         if (common_prefix.length >= 3) {
1846                 return common_prefix;
1847         } else {
1848                 return null;
1849         }
1850 }
1851
1852 function find_match(match_id) {
1853         for (const match of global_json['matches']) {
1854                 if (match['match_id'] === match_id) {
1855                         return match;
1856                 }
1857         }
1858         return null;
1859 }
1860
1861 function find_formation(formation_id) {
1862         for (const formation of global_json['formations']) {
1863                 if (formation['formation_id'] === formation_id) {
1864                         return formation;
1865                 }
1866         }
1867         return null;
1868 }
1869
1870 function find_player(player_id) {
1871         for (const player of global_json['players']) {
1872                 if (player['player_id'] === player_id) {
1873                         return player;
1874                 }
1875         }
1876         return null;
1877 }
1878
1879 function player_pos(player_id) {
1880         let i = 0;
1881         for (const player of global_json['players']) {
1882                 if (player['player_id'] === player_id) {
1883                         return i;
1884                 }
1885                 ++i;
1886         }
1887         return null;
1888 }
1889
1890 function keep_match(match_id, filters) {
1891         for (const filter of filters) {
1892                 if (filter.type === 'match') {
1893                         return filter.elements.has(match_id);
1894                 }
1895         }
1896         return true;
1897 }
1898
1899 // Returns a map of e.g. F => 4, M => 3.
1900 function find_gender_ratio(players) {
1901         let map = {};
1902         for (const [q,p] of Object.entries(players)) {
1903                 if (p.on_field_since === null) {
1904                         continue;
1905                 }
1906                 let gender = p.gender;
1907                 if (gender === '' || gender === undefined || gender === null) {
1908                         gender = '?';
1909                 }
1910                 if (map[gender] === undefined) {
1911                         map[gender] = 1;
1912 q               } else {
1913                         ++map[gender];
1914                 }
1915         }
1916         return map;
1917 }
1918
1919 function find_gender_ratio_code(players) {
1920         let map = find_gender_ratio(players);
1921         let all_genders = Array.from(Object.keys(map)).sort(
1922                 (a,b) => {
1923                         if (map[a] !== map[b]) {
1924                                 return map[b] - map[a];  // Reverse numeric.
1925                         } else if (a < b) {
1926                                 return -1;
1927                         } else if (a > b) {
1928                                 return 1;
1929                         } else {
1930                                 return 0;
1931                         }
1932                 });
1933         let code = '';
1934         for (const g of all_genders) {
1935                 if (code !== '') {
1936                         code += ', ';
1937                 }
1938                 code += map[g];
1939                 code += ' ';
1940                 code += g;
1941         }
1942         return code;
1943 }
1944
1945 // null if none (e.g., if playing 3–3).
1946 function find_predominant_gender(players) {
1947         let max = 0;
1948         let predominant_gender = null;
1949         for (const [gender, num] of Object.entries(find_gender_ratio(players))) {
1950                 if (num > max) {
1951                         max = num;
1952                         predominant_gender = gender;
1953                 } else if (num == max) {
1954                         predominant_gender = null;  // At least two have the same.
1955                 }
1956         }
1957         return predominant_gender;
1958 }
1959
1960 function find_num_players_on_field(players) {
1961         let num = 0;
1962         for (const [q,p] of Object.entries(players)) {
1963                 if (p.on_field_since !== null) {
1964                         ++num;
1965                 }
1966         }
1967         return num;
1968 }
1969
1970 function filter_passes(players, formations_used_this_point, last_pull_was_ours, filter) {
1971         if (filter.type === 'player_any') {
1972                 for (const p of Array.from(filter.elements)) {
1973                         if (players[p].on_field_since !== null) {
1974                                 return true;
1975                         }
1976                 }
1977                 return false;
1978         } else if (filter.type === 'player_all') {
1979                 for (const p of Array.from(filter.elements)) {
1980                         if (players[p].on_field_since === null) {
1981                                 return false;
1982                         }
1983                 }
1984                 return true;
1985         } else if (filter.type === 'formation_offense' || filter.type === 'formation_defense') {
1986                 for (const f of Array.from(filter.elements)) {
1987                         if (formations_used_this_point.has(f)) {
1988                                 return true;
1989                         }
1990                 }
1991                 return false;
1992         } else if (filter.type === 'starting_on') {
1993                 return filter.elements.has(last_pull_was_ours);
1994         } else if (filter.type === 'gender_ratio') {
1995                 return filter.elements.has(find_gender_ratio_code(players));
1996         }
1997         return true;
1998 }
1999
2000 function keep_event(players, formations_used_this_point, last_pull_was_ours, filters) {
2001         for (const filter of filters) {
2002                 if (!filter_passes(players, formations_used_this_point, last_pull_was_ours, filter)) {
2003                         return false;
2004                 }
2005         }
2006         return true;
2007 }
2008
2009 // Heuristic: If we go at least ten seconds without the possession changing
2010 // or the operator specifying some other formation, we probably play the
2011 // same formation as the last point.
2012 function should_reuse_last_formation(events, t) {
2013         for (const e of events) {
2014                 if (e.t <= t) {
2015                         continue;
2016                 }
2017                 if (e.t > t + 10000) {
2018                         break;
2019                 }
2020                 const type = e.type;
2021                 if (type === 'their_goal' || type === 'goal' ||
2022                     type === 'set_defense' || type === 'set_offense' ||
2023                     type === 'throwaway' || type === 'their_throwaway' ||
2024                     type === 'drop' || type === 'was_d' || type === 'stallout' || type === 'defense' || type === 'interception' ||
2025                     type === 'pull' || type === 'pull_landed' || type === 'pull_oob' || type === 'their_pull' ||
2026                     type === 'formation_offense' || type === 'formation_defense') {
2027                         return false;
2028                 }
2029         }
2030         return true;
2031 }
2032
2033 function possibly_close_menu(e) {
2034         if (e.target.closest('.filter-click-to-add') === null &&
2035             e.target.closest('#filter-add-menu') === null &&
2036             e.target.closest('#filter-submenu') === null &&
2037             e.target.closest('.filter-pill') === null) {
2038                 let add_menu = document.getElementById('filter-add-menu');
2039                 let add_submenu = document.getElementById('filter-submenu');
2040                 add_menu.style.display = 'none';
2041                 add_submenu.style.display = 'none';
2042                 try_gc_filter_menus(false);
2043         }
2044 }
2045
2046 let global_sort = {};
2047
2048 function sort_by(th) {
2049         let tr = th.parentElement;
2050         let child_idx = 0;
2051         for (let column_idx = 0; column_idx < tr.children.length; ++column_idx) {
2052                 let element = tr.children[column_idx];
2053                 if (element === th) {
2054                         ++child_idx;  // Pad.
2055                         break;
2056                 }
2057                 if (element.hasAttribute('colspan')) {
2058                         child_idx += parseInt(element.getAttribute('colspan'));
2059                 } else {
2060                         ++child_idx;
2061                 }
2062         }
2063
2064         global_sort = {};
2065         let table = tr.parentElement;
2066         for (let row_idx = 1; row_idx < table.children.length - 1; ++row_idx) {  // Skip header and globals.
2067                 let row = table.children[row_idx];
2068                 let player = parseInt(row.dataset.player);
2069                 let value = row.children[child_idx].textContent;
2070                 global_sort[player] = value;
2071         }
2072 }
2073
2074 function get_sorted_players(players)
2075 {
2076         let p = Object.entries(players);
2077         if (global_sort.length !== 0) {
2078                 p.sort((a,b) => {
2079                         let ai = parseFloat(global_sort[a[0]]);
2080                         let bi = parseFloat(global_sort[b[0]]);
2081                         if (ai == ai && bi == bi) {
2082                                 return bi - ai;  // Reverse numeric.
2083                         } else if (global_sort[a[0]] < global_sort[b[0]]) {
2084                                 return -1;
2085                         } else if (global_sort[a[0]] > global_sort[b[0]]) {
2086                                 return 1;
2087                         } else {
2088                                 return 0;
2089                         }
2090                 });
2091         }
2092         return p;
2093 }