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