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