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