]> git.sesse.net Git - pkanalytics/blob - ultimate.js
Count interceptions towards (successful) catches.
[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
8 addEventListener('hashchange', () => { process_matches(global_json, global_filters); });
9 addEventListener('click', possibly_close_menu);
10 fetch('ultimate.json')
11    .then(response => response.json())
12    .then(response => { global_json = response; process_matches(global_json, global_filters); });
13
14 function attribute_player_time(player, to, from, offense) {
15         let delta_time;
16         if (player.on_field_since > from) {
17                 // Player came in while play happened (without a stoppage!?).
18                 delta_time = to - player.on_field_since;
19         } else {
20                 delta_time = to - from;
21         }
22         player.playing_time_ms += delta_time;
23         if (offense === true) {
24                 player.offensive_playing_time_ms += delta_time;
25         } else if (offense === false) {
26                 player.defensive_playing_time_ms += delta_time;
27         }
28 }
29
30 function take_off_field(player, t, live_since, offense, keep) {
31         if (keep) {
32                 if (live_since === null) {
33                         // Play isn't live, so nothing to do.
34                 } else {
35                         attribute_player_time(player, t, live_since, offense);
36                 }
37                 if (player.on_field_since !== null) {  // Just a safeguard; out without in should never happen.
38                         player.field_time_ms += t - player.on_field_since;
39                 }
40         }
41         player.on_field_since = null;
42 }
43
44 function add_cell(tr, element_type, text) {
45         let element = document.createElement(element_type);
46         element.textContent = text;
47         tr.appendChild(element);
48         return element;
49 }
50
51 function add_th(tr, text, colspan) {
52         let element = document.createElement('th');
53         let link = document.createElement('a');
54         link.style.cursor = 'pointer';
55         link.addEventListener('click', (e) => {
56                 sort_by(element);
57                 process_matches(global_json, global_filters);
58         });
59         link.textContent = text;
60         element.appendChild(link);
61         tr.appendChild(element);
62
63         if (colspan > 0) {
64                 element.setAttribute('colspan', colspan);
65         } else {
66                 element.setAttribute('colspan', '3');
67         }
68         return element;
69 }
70
71 function add_3cell(tr, text, cls) {
72         let p1 = add_cell(tr, 'td', '');
73         let element = add_cell(tr, 'td', text);
74         let p2 = add_cell(tr, 'td', '');
75
76         p1.classList.add('pad');
77         p2.classList.add('pad');
78         if (cls === undefined) {
79                 element.classList.add('num');
80         } else {
81                 element.classList.add(cls);
82         }
83         return element;
84 }
85
86 function add_3cell_with_filler_ci(tr, text, cls) {
87         let element = add_3cell(tr, text, cls);
88
89         let svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
90         svg.classList.add('fillerci');
91         svg.setAttribute('width', ci_width);
92         svg.setAttribute('height', ci_height);
93         element.appendChild(svg);
94
95         return element;
96 }
97
98 function add_3cell_ci(tr, ci) {
99         if (isNaN(ci.val)) {
100                 add_3cell_with_filler_ci(tr, 'N/A');
101                 return;
102         }
103
104         let text;
105         if (ci.format === 'percentage') {
106                 text = (100 * ci.val).toFixed(0) + '%';
107         } else {
108                 text = ci.val.toFixed(2);
109         }
110         let element = add_3cell(tr, text);
111         let to_x = (val) => { return ci_width * (val - ci.min) / (ci.max - ci.min); };
112
113         // Container.
114         let svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
115         if (ci.inverted === true) {
116                 svg.classList.add('invertedci');
117         } else {
118                 svg.classList.add('ci');
119         }
120         svg.setAttribute('width', ci_width);
121         svg.setAttribute('height', ci_height);
122
123         // The good (green) and red (bad) ranges.
124         let s0 = document.createElementNS('http://www.w3.org/2000/svg', 'rect');
125         s0.classList.add('range');
126         s0.classList.add('s0');
127         s0.setAttribute('width', to_x(ci.desired));
128         s0.setAttribute('height', ci_height);
129         s0.setAttribute('x', '0');
130
131         let s1 = document.createElementNS('http://www.w3.org/2000/svg', 'rect');
132         s1.classList.add('range');
133         s1.classList.add('s1');
134         s1.setAttribute('width', ci_width - to_x(ci.desired));
135         s1.setAttribute('height', ci_height);
136         s1.setAttribute('x', to_x(ci.desired));
137
138         // Confidence bar.
139         let bar = document.createElementNS('http://www.w3.org/2000/svg', 'rect');
140         bar.classList.add('bar');
141         bar.setAttribute('width', to_x(ci.upper_ci) - to_x(ci.lower_ci));
142         bar.setAttribute('height', ci_height / 3);
143         bar.setAttribute('x', to_x(ci.lower_ci));
144         bar.setAttribute('y', ci_height / 3);
145
146         // Marker line for average.
147         let marker = document.createElementNS('http://www.w3.org/2000/svg', 'line');
148         marker.classList.add('marker');
149         marker.setAttribute('x1', to_x(ci.val));
150         marker.setAttribute('x2', to_x(ci.val));
151         marker.setAttribute('y1', ci_height / 6);
152         marker.setAttribute('y2', ci_height * 5 / 6);
153
154         svg.appendChild(s0);
155         svg.appendChild(s1);
156         svg.appendChild(bar);
157         svg.appendChild(marker);
158
159         element.appendChild(svg);
160 }
161
162 function process_matches(json, filters) {
163         let players = {};
164         for (const player of json['players']) {
165                 players[player['player_id']] = {
166                         'name': player['name'],
167                         'number': player['number'],
168
169                         'goals': 0,
170                         'assists': 0,
171                         'hockey_assists': 0,
172                         'catches': 0,
173                         'touches': 0,
174                         'num_throws': 0,
175                         'throwaways': 0,
176                         'drops': 0,
177                         'was_ds': 0,
178                         'stallouts': 0,
179
180                         'defenses': 0,
181                         'points_played': 0,
182                         'playing_time_ms': 0,
183                         'offensive_playing_time_ms': 0,
184                         'defensive_playing_time_ms': 0,
185                         'field_time_ms': 0,
186
187                         // For efficiency.
188                         'offensive_points_completed': 0,
189                         'offensive_points_won': 0,
190                         'defensive_points_completed': 0,
191                         'defensive_points_won': 0,
192
193                         'offensive_soft_plus': 0,
194                         'offensive_soft_minus': 0,
195                         'defensive_soft_plus': 0,
196                         'defensive_soft_minus': 0,
197
198                         'pulls': 0,
199                         'pull_times': [],
200                         'oob_pulls': 0,
201
202                         // Internal.
203                         'last_point_seen': null,
204                         'on_field_since': null,
205                 };
206         }
207
208         // Globals.
209         players['globals'] = {
210                 'points_played': 0,
211                 'playing_time_ms': 0,
212                 'offensive_playing_time_ms': 0,
213                 'defensive_playing_time_ms': 0,
214                 'field_time_ms': 0,
215
216                 'offensive_points_completed': 0,
217                 'offensive_points_won': 0,
218                 'defensive_points_completed': 0,
219                 'defensive_points_won': 0,
220         };
221         let globals = players['globals'];
222
223         for (const match of json['matches']) {
224                 if (!keep_match(match['match_id'], filters)) {
225                         continue;
226                 }
227
228                 let our_score = 0;
229                 let their_score = 0;
230                 let handler = null;
231                 let prev_handler = null;
232                 let live_since = null;
233                 let offense = null;  // True/false/null (unknown).
234                 let puller = null;
235                 let pull_started = null;
236                 let last_pull_was_ours = null;  // Effectively whether we're playing an O or D point (not affected by turnovers).
237                 let point_num = 0;
238                 let game_started = null;
239                 let last_goal = null;
240
241                 // The last used formations of the given kind, if any; they may be reused
242                 // when the point starts, if nothing else is set.
243                 let last_offensive_formation = null;
244                 let last_defensive_formation = null;
245
246                 // Formations we've set, but haven't really had the chance to use yet
247                 // (e.g., we get a “use zone defense” event while we're still on offense).
248                 let pending_offensive_formation = null;
249                 let pending_defensive_formation = null;
250
251                 // Formations that we have played at least once this point, after all
252                 // heuristics and similar.
253                 let formations_used_this_point = new Set();
254
255                 for (const [q,p] of Object.entries(players)) {
256                         p.on_field_since = null;
257                         p.last_point_seen = null;
258                 }
259                 for (const e of match['events']) {
260                         let t = e['t'];
261                         let type = e['type'];
262                         let p = players[e['player']];
263
264                         // Sub management
265                         let keep = keep_event(players, formations_used_this_point, filters);
266                         if (type === 'in' && p.on_field_since === null) {
267                                 p.on_field_since = t;
268                                 if (!keep && keep_event(players, formations_used_this_point, filters)) {
269                                         // A player needed for the filters went onto the field,
270                                         // so pretend people walked on right now (to start their
271                                         // counting time).
272                                         for (const [q,p2] of Object.entries(players)) {
273                                                 if (p2.on_field_since !== null) {
274                                                         p2.on_field_since = t;
275                                                 }
276                                         }
277                                 }
278                         } else if (type === 'out') {
279                                 take_off_field(p, t, live_since, offense, keep);
280                                 if (keep && !keep_event(players, formations_used_this_point, filters)) {
281                                         // A player needed for the filters went off the field,
282                                         // so we need to attribute time for all the others.
283                                         // Pretend they walked off and then immediately on again.
284                                         //
285                                         // TODO: We also need to take care of this to get the globals right.
286                                         for (const [q,p2] of Object.entries(players)) {
287                                                 if (p2.on_field_since !== null) {
288                                                         take_off_field(p2, t, live_since, offense, keep);
289                                                         p2.on_field_since = t;
290                                                 }
291                                         }
292                                 }
293                         }
294
295                         keep = keep_event(players, formations_used_this_point, filters);  // Recompute after in/out.
296
297                         // Liveness management
298                         if (type === 'pull' || type === 'their_pull' || type === 'restart') {
299                                 live_since = t;
300                         } else if (type === 'catch' && last_pull_was_ours === null) {
301                                 // Someone forgot to add the pull, so we'll need to wing it.
302                                 console.log('Missing pull on ' + our_score + '\u2013' + their_score + ' in ' + match['description'] + '; pretending to have one.');
303                                 live_since = t;
304                                 last_pull_was_ours = !offense;
305                         } else if (type === 'goal' || type === 'their_goal' || type === 'stoppage') {
306                                 for (const [q,p] of Object.entries(players)) {
307                                         if (p.on_field_since === null) {
308                                                 continue;
309                                         }
310                                         if (type !== 'stoppage' && p.last_point_seen !== point_num) {
311                                                 if (keep) {
312                                                         // In case the player did nothing this point,
313                                                         // not even subbing in.
314                                                         p.last_point_seen = point_num;
315                                                         ++p.points_played;
316                                                 }
317                                         }
318                                         if (keep) attribute_player_time(p, t, live_since, offense);
319
320                                         if (type !== 'stoppage') {
321                                                 if (keep) {
322                                                         if (last_pull_was_ours === true) {  // D point.
323                                                                 ++p.defensive_points_completed;
324                                                                 if (type === 'goal') {
325                                                                         ++p.defensive_points_won;
326                                                                 }
327                                                         } else if (last_pull_was_ours === false) {  // O point.
328                                                                 ++p.offensive_points_completed;
329                                                                 if (type === 'goal') {
330                                                                         ++p.offensive_points_won;
331                                                                 }
332                                                         }
333                                                 }
334                                         }
335                                 }
336
337                                 if (keep) {
338                                         if (type !== 'stoppage') {
339                                                 // Update globals.
340                                                 ++globals.points_played;
341                                                 if (last_pull_was_ours === true) {  // D point.
342                                                         ++globals.defensive_points_completed;
343                                                         if (type === 'goal') {
344                                                                 ++globals.defensive_points_won;
345                                                         }
346                                                 } else if (last_pull_was_ours === false) {  // O point.
347                                                         ++globals.offensive_points_completed;
348                                                         if (type === 'goal') {
349                                                                 ++globals.offensive_points_won;
350                                                         }
351                                                 }
352                                         }
353                                         if (live_since !== null) {
354                                                 globals.playing_time_ms += t - live_since;
355                                                 if (offense === true) {
356                                                         globals.offensive_playing_time_ms += t - live_since;
357                                                 } else if (offense === false) {
358                                                         globals.defensive_playing_time_ms += t - live_since;
359                                                 }
360                                         }
361                                 }
362
363                                 live_since = null;
364                         }
365
366                         // Score management
367                         if (type === 'goal') {
368                                 ++our_score;
369                         } else if (type === 'their_goal') {
370                                 ++their_score;
371                         }
372
373                         // Point count management
374                         if (p !== undefined && type !== 'out' && p.last_point_seen !== point_num) {
375                                 if (keep) {
376                                         p.last_point_seen = point_num;
377                                         ++p.points_played;
378                                 }
379                         }
380                         if (type === 'goal' || type === 'their_goal') {
381                                 ++point_num;
382                                 last_goal = t;
383                         }
384                         if (type !== 'out' && game_started === null) {
385                                 game_started = t;
386                         }
387
388                         // Pull management
389                         if (type === 'pull') {
390                                 puller = e['player'];
391                                 pull_started = t;
392                                 if (keep) ++p.pulls;
393                         } else if (type === 'in' || type === 'out' || type === 'stoppage' || type === 'restart' || type === 'unknown' || type === 'set_defense' || type === 'set_offense') {
394                                 // No effect on pull.
395                         } else if (type === 'pull_landed' && puller !== null) {
396                                 if (keep) players[puller].pull_times.push(t - pull_started);
397                         } else if (type === 'pull_oob' && puller !== null) {
398                                 if (keep) ++players[puller].oob_pulls;
399                         } else {
400                                 // Not pulling (if there was one, we never recorded its outcome, but still count it).
401                                 puller = pull_started = null;
402                         }
403
404                         // Offense/defense management
405                         let last_offense = offense;
406                         if (type === 'set_defense' || type === 'goal' || type === 'throwaway' || type === 'drop' || type === 'was_d' || type === 'stallout') {
407                                 offense = false;
408                         } else if (type === 'set_offense' || type === 'their_goal' || type === 'their_throwaway' || type === 'defense' || type === 'interception') {
409                                 offense = true;
410                         }
411                         if (last_offense !== offense && live_since !== null) {
412                                 // Switched offense/defense status, so attribute this drive as needed,
413                                 // and update live_since to take that into account.
414                                 if (keep) {
415                                         for (const [q,p] of Object.entries(players)) {
416                                                 if (p.on_field_since === null) {
417                                                         continue;
418                                                 }
419                                                 attribute_player_time(p, t, live_since, last_offense);
420                                         }
421                                         globals.playing_time_ms += t - live_since;
422                                         if (offense === true) {
423                                                 globals.offensive_playing_time_ms += t - live_since;
424                                         } else if (offense === false) {
425                                                 globals.defensive_playing_time_ms += t - live_since;
426                                         }
427                                 }
428                                 live_since = t;
429                         }
430
431                         if (type === 'pull') {
432                                 last_pull_was_ours = true;
433                         } else if (type === 'their_pull') {
434                                 last_pull_was_ours = false;
435                         } else if (type === 'set_offense' && last_pull_was_ours === null) {
436                                 // set_offense could either be “changed to offense for some reason
437                                 // we could not express”, or “we started in the middle of a point,
438                                 // and we are offense”. We assume that if we already saw the pull,
439                                 // it's the former, and if not, it's the latter; thus, the === null
440                                 // test above. (It could also be “we set offense before the pull,
441                                 // so that we get the right button enabled”, in which case it will
442                                 // be overwritten by the next pull/their_pull event anyway.)
443                                 last_pull_was_ours = false;
444                         } else if (type === 'set_defense' && last_pull_was_ours === null) {
445                                 // Similar.
446                                 last_pull_was_ours = true;
447                         } else if (type === 'goal' || type === 'their_goal') {
448                                 last_pull_was_ours = null;
449                         }
450
451                         // Formation management
452                         if (type === 'formation_offense' || type === 'formation_defense') {
453                                 let id = e.formation === null ? 0 : e.formation;
454                                 let for_offense = (type === 'formation_offense');
455                                 if (offense === for_offense) {
456                                         formations_used_this_point.add(id);
457                                 } else if (for_offense) {
458                                         pending_offensive_formation = id;
459                                 } else {
460                                         pending_defensive_formation = id;
461                                 }
462                                 if (for_offense) {
463                                         last_offensive_formation = id;
464                                 } else {
465                                         last_defensive_formation = id;
466                                 }
467                         } else if (last_offense !== offense) {
468                                 if (offense === true && pending_offensive_formation !== null) {
469                                         formations_used_this_point.add(pending_offensive_formation);
470                                         pending_offensive_formation = null;
471                                 } else if (offense === false && pending_defensive_formation !== null) {
472                                         formations_used_this_point.add(pending_defensive_formation);
473                                         pending_defensive_formation = null;
474                                 } else if (offense === true && last_defensive_formation !== null) {
475                                         if (should_reuse_last_formation(match['events'], t)) {
476                                                 formations_used_this_point.add(last_defensive_formation);
477                                         }
478                                 } else if (offense === false && last_offensive_formation !== null) {
479                                         if (should_reuse_last_formation(match['events'], t)) {
480                                                 formations_used_this_point.add(last_offensive_formation);
481                                         }
482                                 }
483                         }
484
485                         // Event management
486                         if (type === 'catch' || type === 'goal') {
487                                 if (handler !== null) {
488                                         if (keep) {
489                                                 ++players[handler].num_throws;
490                                                 ++p.catches;
491                                         }
492                                 }
493
494                                 if (keep) ++p.touches;
495                                 if (type === 'goal') {
496                                         if (keep) {
497                                                 if (prev_handler !== null) {
498                                                         ++players[prev_handler].hockey_assists;
499                                                 }
500                                                 if (handler !== null) {
501                                                         ++players[handler].assists;
502                                                 }
503                                                 ++p.goals;
504                                         }
505                                         handler = prev_handler = null;
506                                 } else {
507                                         // Update hold history.
508                                         prev_handler = handler;
509                                         handler = e['player'];
510                                 }
511                         } else if (type === 'throwaway') {
512                                 if (keep) {
513                                         ++p.num_throws;
514                                         ++p.throwaways;
515                                 }
516                                 handler = prev_handler = null;
517                         } else if (type === 'drop') {
518                                 if (keep) ++p.drops;
519                                 handler = prev_handler = null;
520                         } else if (type === 'stallout') {
521                                 if (keep) ++p.stallouts;
522                                 handler = prev_handler = null;
523                         } else if (type === 'was_d') {
524                                 if (keep) ++p.was_ds;
525                                 handler = prev_handler = null;
526                         } else if (type === 'defense') {
527                                 if (keep) ++p.defenses;
528                         } else if (type === 'interception') {
529                                 if (keep) {
530                                         ++p.catches;
531                                         ++p.defenses;
532                                         ++p.touches;
533                                 }
534                                 prev_handler = null;
535                                 handler = e['player'];
536                         } else if (type === 'offensive_soft_plus' || type === 'offensive_soft_minus' || type === 'defensive_soft_plus' || type === 'defensive_soft_minus') {
537                                 if (keep) ++p[type];
538                         } else if (type !== 'in' && type !== 'out' && type !== 'pull' &&
539                                    type !== 'their_goal' && type !== 'stoppage' && type !== 'restart' && type !== 'unknown' &&
540                                    type !== 'set_defense' && type !== 'goal' && type !== 'throwaway' &&
541                                    type !== 'drop' && type !== 'was_d' && type !== 'stallout' && type !== 'set_offense' && type !== 'their_goal' &&
542                                    type !== 'pull' && type !== 'pull_landed' && type !== 'pull_oob' && type !== 'their_pull' &&
543                                    type !== 'their_throwaway' && type !== 'defense' && type !== 'interception' &&
544                                    type !== 'formation_offense' && type !== 'formation_defense') {
545                                 console.log("Unknown event:", e);
546                         }
547
548                         if (type === 'goal' || type === 'their_goal') {
549                                 formations_used_this_point.clear();
550                         }
551                 }
552
553                 // Add field time for all players still left at match end.
554                 const keep = keep_event(players, formations_used_this_point, filters);
555                 if (keep) {
556                         for (const [q,p] of Object.entries(players)) {
557                                 if (p.on_field_since !== null && last_goal !== null) {
558                                         p.field_time_ms += last_goal - p.on_field_since;
559                                 }
560                         }
561                         if (game_started !== null && last_goal !== null) {
562                                 globals.field_time_ms += last_goal - game_started;
563                         }
564                         if (live_since !== null && last_goal !== null) {
565                                 globals.playing_time_ms += last_goal - live_since;
566                                 if (offense === true) {
567                                         globals.offensive_playing_time_ms += last_goal - live_since;
568                                 } else if (offense === false) {
569                                         globals.defensive_playing_time_ms += last_goal - live_since;
570                                 }
571                         }
572                 }
573         }
574
575         let chosen_category = get_chosen_category();
576         write_main_menu(chosen_category);
577
578         let rows = [];
579         if (chosen_category === 'general') {
580                 rows = make_table_general(players);
581         } else if (chosen_category === 'offense') {
582                 rows = make_table_offense(players);
583         } else if (chosen_category === 'defense') {
584                 rows = make_table_defense(players);
585         } else if (chosen_category === 'playing_time') {
586                 rows = make_table_playing_time(players);
587         } else if (chosen_category === 'per_point') {
588                 rows = make_table_per_point(players);
589         }
590         document.getElementById('stats').replaceChildren(...rows);
591 }
592
593 function get_chosen_category() {
594         if (window.location.hash === '#offense') {
595                 return 'offense';
596         } else if (window.location.hash === '#defense') {
597                 return 'defense';
598         } else if (window.location.hash === '#playing_time') {
599                 return 'playing_time';
600         } else if (window.location.hash === '#per_point') {
601                 return 'per_point';
602         } else {
603                 return 'general';
604         }
605 }
606
607 function write_main_menu(chosen_category) {
608         let elems = [];
609         if (chosen_category === 'general') {
610                 let span = document.createElement('span');
611                 span.innerText = 'General';
612                 elems.push(span);
613         } else {
614                 let a = document.createElement('a');
615                 a.appendChild(document.createTextNode('General'));
616                 a.setAttribute('href', '#general');
617                 elems.push(a);
618         }
619
620         if (chosen_category === 'offense') {
621                 let span = document.createElement('span');
622                 span.innerText = 'Offense';
623                 elems.push(span);
624         } else {
625                 let a = document.createElement('a');
626                 a.appendChild(document.createTextNode('Offense'));
627                 a.setAttribute('href', '#offense');
628                 elems.push(a);
629         }
630
631         if (chosen_category === 'defense') {
632                 let span = document.createElement('span');
633                 span.innerText = 'Defense';
634                 elems.push(span);
635         } else {
636                 let a = document.createElement('a');
637                 a.appendChild(document.createTextNode('Defense'));
638                 a.setAttribute('href', '#defense');
639                 elems.push(a);
640         }
641
642         if (chosen_category === 'playing_time') {
643                 let span = document.createElement('span');
644                 span.innerText = 'Playing time';
645                 elems.push(span);
646         } else {
647                 let a = document.createElement('a');
648                 a.appendChild(document.createTextNode('Playing time'));
649                 a.setAttribute('href', '#playing_time');
650                 elems.push(a);
651         }
652
653         if (chosen_category === 'per_point') {
654                 let span = document.createElement('span');
655                 span.innerText = 'Per point';
656                 elems.push(span);
657         } else {
658                 let a = document.createElement('a');
659                 a.appendChild(document.createTextNode('Per point'));
660                 a.setAttribute('href', '#per_point');
661                 elems.push(a);
662         }
663
664         document.getElementById('mainmenu').replaceChildren(...elems);
665 }
666
667 // https://en.wikipedia.org/wiki/1.96#History
668 const z = 1.959964;
669
670 const ci_width = 100;
671 const ci_height = 20;
672
673 function make_binomial_ci(val, num, z) {
674         let avg = val / num;
675
676         // https://en.wikipedia.org/wiki/Binomial_proportion_confidence_interval#Wilson_score_interval
677         let low  = (avg + z*z/(2*num) - z * Math.sqrt(avg * (1.0 - avg) / num + z*z/(4*num*num))) / (1 + z*z/num);   
678         let high = (avg + z*z/(2*num) + z * Math.sqrt(avg * (1.0 - avg) / num + z*z/(4*num*num))) / (1 + z*z/num); 
679
680         // Fix the signs so that we don't get -0.00.
681         low = Math.max(low, 0.0);
682         return {
683                 'val': avg,
684                 'lower_ci': low,
685                 'upper_ci': high,
686                 'min': 0.0,
687                 'max': 1.0,
688         };
689 }
690
691 // These can only happen once per point, but you get -1 and +1
692 // instead of 0 and +1. After we rewrite to 0 and 1, it's a binomial,
693 // and then we can rewrite back.
694 function make_efficiency_ci(points_won, points_completed, z)
695 {
696         let ci = make_binomial_ci(points_won, points_completed, z);
697         ci.val = 2.0 * ci.val - 1.0;
698         ci.lower_ci = 2.0 * ci.lower_ci - 1.0;
699         ci.upper_ci = 2.0 * ci.upper_ci - 1.0;
700         ci.min = -1.0;
701         ci.max = 1.0;
702         ci.desired = 0.0;  // Desired = positive efficiency.
703         return ci;
704 }
705
706 // Ds, throwaways and drops can happen multiple times per point,
707 // so they are Poisson distributed.
708 //
709 // Modified Wald (recommended by http://www.ine.pt/revstat/pdf/rs120203.pdf
710 // since our rates are definitely below 2 per point).
711 function make_poisson_ci(val, num, z, inverted)
712 {
713         let low  = (val == 0) ? 0.0 : ((val - 0.5) - Math.sqrt(val - 0.5)) / num;
714         let high = (val == 0) ? -Math.log(0.025) / num : ((val + 0.5) + Math.sqrt(val + 0.5)) / num;
715
716         // Fix the signs so that we don't get -0.00.
717         low = Math.max(low, 0.0);
718
719         // The display range of 0 to 0.25 is fairly arbitrary. So is the desired 0.05 per point.
720         let avg = val / num;
721         return {
722                 'val': avg,
723                 'lower_ci': low,
724                 'upper_ci': high,
725                 'min': 0.0,
726                 'max': 0.25,
727                 'desired': 0.05,
728                 'inverted': inverted,
729         };
730 }
731
732 function make_table_general(players) {
733         let rows = [];
734         {
735                 let header = document.createElement('tr');
736                 add_th(header, 'Player');
737                 add_th(header, '+/-');
738                 add_th(header, 'Soft +/-');
739                 add_th(header, 'O efficiency');
740                 add_th(header, 'D efficiency');
741                 add_th(header, 'Points played');
742                 rows.push(header);
743         }
744
745         for (const [q,p] of get_sorted_players(players)) {
746                 if (q === 'globals') continue;
747                 let row = document.createElement('tr');
748                 let pm = p.goals + p.assists + p.hockey_assists + p.defenses - p.throwaways - p.drops - p.was_ds - p.stallouts;
749                 let soft_pm = p.offensive_soft_plus + p.defensive_soft_plus - p.offensive_soft_minus - p.defensive_soft_minus;
750                 let o_efficiency = make_efficiency_ci(p.offensive_points_won, p.offensive_points_completed, z);
751                 let d_efficiency = make_efficiency_ci(p.defensive_points_won, p.defensive_points_completed, z);
752                 let name = add_3cell(row, p.name, 'name');  // TODO: number?
753                 add_3cell(row, pm > 0 ? ('+' + pm) : pm);
754                 add_3cell(row, soft_pm > 0 ? ('+' + soft_pm) : soft_pm);
755                 add_3cell_ci(row, o_efficiency);
756                 add_3cell_ci(row, d_efficiency);
757                 add_3cell(row, p.points_played);
758                 row.dataset.player = q;
759                 rows.push(row);
760         }
761
762         // Globals.
763         let globals = players['globals'];
764         let o_efficiency = make_efficiency_ci(globals.offensive_points_won, globals.offensive_points_completed, z);
765         let d_efficiency = make_efficiency_ci(globals.defensive_points_won, globals.defensive_points_completed, z);
766         let row = document.createElement('tr');
767         add_3cell(row, '');
768         add_3cell(row, '');
769         add_3cell(row, '');
770         add_3cell_ci(row, o_efficiency);
771         add_3cell_ci(row, d_efficiency);
772         add_3cell(row, globals.points_played);
773         rows.push(row);
774
775         return rows;
776 }
777
778 function make_table_offense(players) {
779         let rows = [];
780         {
781                 let header = document.createElement('tr');
782                 add_th(header, 'Player');
783                 add_th(header, 'Goals');
784                 add_th(header, 'Assists');
785                 add_th(header, 'Hockey assists');
786                 add_th(header, 'Throws');
787                 add_th(header, 'Throwaways');
788                 add_th(header, '%OK');
789                 add_th(header, 'Catches');
790                 add_th(header, 'Drops');
791                 add_th(header, 'D-ed');
792                 add_th(header, '%OK');
793                 add_th(header, 'Stalls');
794                 add_th(header, 'Soft +/-', 6);
795                 rows.push(header);
796         }
797
798         let num_throws = 0;
799         let throwaways = 0;
800         let catches = 0;
801         let drops = 0;
802         let was_ds = 0;
803         let stallouts = 0;
804         for (const [q,p] of get_sorted_players(players)) {
805                 if (q === 'globals') continue;
806                 let throw_ok = make_binomial_ci(p.num_throws - p.throwaways, p.num_throws, z);
807                 let catch_ok = make_binomial_ci(p.catches, p.catches + p.drops + p.was_ds, z);
808
809                 throw_ok.format = 'percentage';
810                 catch_ok.format = 'percentage';
811
812                 // Desire at least 90% percentage. Fairly arbitrary.
813                 throw_ok.desired = 0.9;
814                 catch_ok.desired = 0.9;
815
816                 let row = document.createElement('tr');
817                 add_3cell(row, p.name, 'name');  // TODO: number?
818                 add_3cell(row, p.goals);
819                 add_3cell(row, p.assists);
820                 add_3cell(row, p.hockey_assists);
821                 add_3cell(row, p.num_throws);
822                 add_3cell(row, p.throwaways);
823                 add_3cell_ci(row, throw_ok);
824                 add_3cell(row, p.catches);
825                 add_3cell(row, p.drops);
826                 add_3cell(row, p.was_ds);
827                 add_3cell_ci(row, catch_ok);
828                 add_3cell(row, p.stallouts);
829                 add_3cell(row, '+' + p.offensive_soft_plus);
830                 add_3cell(row, '-' + p.offensive_soft_minus);
831                 row.dataset.player = q;
832                 rows.push(row);
833
834                 num_throws += p.num_throws;
835                 throwaways += p.throwaways;
836                 catches += p.catches;
837                 drops += p.drops;
838                 was_ds += p.was_ds;
839                 stallouts += p.stallouts;
840         }
841
842         // Globals.
843         let throw_ok = make_binomial_ci(num_throws - throwaways, num_throws, z);
844         let catch_ok = make_binomial_ci(catches, catches + drops + was_ds, z);
845         throw_ok.format = 'percentage';
846         catch_ok.format = 'percentage';
847         throw_ok.desired = 0.9;
848         catch_ok.desired = 0.9;
849
850         let row = document.createElement('tr');
851         add_3cell(row, '');
852         add_3cell(row, '');
853         add_3cell(row, '');
854         add_3cell(row, '');
855         add_3cell(row, num_throws);
856         add_3cell(row, throwaways);
857         add_3cell_ci(row, throw_ok);
858         add_3cell(row, catches);
859         add_3cell(row, drops);
860         add_3cell(row, was_ds);
861         add_3cell_ci(row, catch_ok);
862         add_3cell(row, stallouts);
863         add_3cell(row, '');
864         add_3cell(row, '');
865         rows.push(row);
866
867         return rows;
868 }
869
870 function make_table_defense(players) {
871         let rows = [];
872         {
873                 let header = document.createElement('tr');
874                 add_th(header, 'Player');
875                 add_th(header, 'Ds');
876                 add_th(header, 'Pulls');
877                 add_th(header, 'OOB pulls');
878                 add_th(header, 'OOB%');
879                 add_th(header, 'Avg. hang time (IB)');
880                 add_th(header, 'Soft +/-', 6);
881                 rows.push(header);
882         }
883         for (const [q,p] of get_sorted_players(players)) {
884                 if (q === 'globals') continue;
885                 let sum_time = 0;
886                 for (const t of p.pull_times) {
887                         sum_time += t;
888                 }
889                 let avg_time = 1e-3 * sum_time / (p.pulls - p.oob_pulls);
890                 let oob_pct = 100 * p.oob_pulls / p.pulls;
891
892                 let ci_oob = make_binomial_ci(p.oob_pulls, p.pulls, z);
893                 ci_oob.format = 'percentage';
894                 ci_oob.desired = 0.2;  // Arbitrary.
895                 ci_oob.inverted = true;
896
897                 let row = document.createElement('tr');
898                 add_3cell(row, p.name, 'name');  // TODO: number?
899                 add_3cell(row, p.defenses);
900                 add_3cell(row, p.pulls);
901                 add_3cell(row, p.oob_pulls);
902                 add_3cell_ci(row, ci_oob);
903                 if (p.pulls > p.oob_pulls) {
904                         add_3cell(row, avg_time.toFixed(1) + ' sec');
905                 } else {
906                         add_3cell(row, 'N/A');
907                 }
908                 add_3cell(row, '+' + p.defensive_soft_plus);
909                 add_3cell(row, '-' + p.defensive_soft_minus);
910                 row.dataset.player = q;
911                 rows.push(row);
912         }
913         return rows;
914 }
915
916 function make_table_playing_time(players) {
917         let rows = [];
918         {
919                 let header = document.createElement('tr');
920                 add_th(header, 'Player');
921                 add_th(header, 'Points played');
922                 add_th(header, 'Time played');
923                 add_th(header, 'O time');
924                 add_th(header, 'D time');
925                 add_th(header, 'Time on field');
926                 add_th(header, 'O points');
927                 add_th(header, 'D points');
928                 rows.push(header);
929         }
930
931         for (const [q,p] of get_sorted_players(players)) {
932                 if (q === 'globals') continue;
933                 let row = document.createElement('tr');
934                 add_3cell(row, p.name, 'name');  // TODO: number?
935                 add_3cell(row, p.points_played);
936                 add_3cell(row, Math.floor(p.playing_time_ms / 60000) + ' min');
937                 add_3cell(row, Math.floor(p.offensive_playing_time_ms / 60000) + ' min');
938                 add_3cell(row, Math.floor(p.defensive_playing_time_ms / 60000) + ' min');
939                 add_3cell(row, Math.floor(p.field_time_ms / 60000) + ' min');
940                 add_3cell(row, p.offensive_points_completed);
941                 add_3cell(row, p.defensive_points_completed);
942                 row.dataset.player = q;
943                 rows.push(row);
944         }
945
946         // Globals.
947         let globals = players['globals'];
948         let row = document.createElement('tr');
949         add_3cell(row, '');
950         add_3cell(row, globals.points_played);
951         add_3cell(row, Math.floor(globals.playing_time_ms / 60000) + ' min');
952         add_3cell(row, Math.floor(globals.offensive_playing_time_ms / 60000) + ' min');
953         add_3cell(row, Math.floor(globals.defensive_playing_time_ms / 60000) + ' min');
954         add_3cell(row, Math.floor(globals.field_time_ms / 60000) + ' min');
955         add_3cell(row, globals.offensive_points_completed);
956         add_3cell(row, globals.defensive_points_completed);
957         rows.push(row);
958
959         return rows;
960 }
961
962 function make_table_per_point(players) {
963         let rows = [];
964         {
965                 let header = document.createElement('tr');
966                 add_th(header, 'Player');
967                 add_th(header, 'Goals');
968                 add_th(header, 'Assists');
969                 add_th(header, 'Hockey assists');
970                 add_th(header, 'Ds');
971                 add_th(header, 'Throwaways');
972                 add_th(header, 'Recv. errors');
973                 add_th(header, 'Touches');
974                 rows.push(header);
975         }
976
977         let goals = 0;
978         let assists = 0;
979         let hockey_assists = 0;
980         let defenses = 0;
981         let throwaways = 0;
982         let receiver_errors = 0;
983         let touches = 0;
984         for (const [q,p] of get_sorted_players(players)) {
985                 if (q === 'globals') continue;
986
987                 // Can only happen once per point, so these are binomials.
988                 let ci_goals = make_binomial_ci(p.goals, p.points_played, z);
989                 let ci_assists = make_binomial_ci(p.assists, p.points_played, z);
990                 let ci_hockey_assists = make_binomial_ci(p.hockey_assists, p.points_played, z);
991                 // Arbitrarily desire at least 10% (not everybody can score or assist).
992                 ci_goals.desired = 0.1;
993                 ci_assists.desired = 0.1;
994                 ci_hockey_assists.desired = 0.1;
995
996                 let row = document.createElement('tr');
997                 add_3cell(row, p.name, 'name');  // TODO: number?
998                 add_3cell_ci(row, ci_goals);
999                 add_3cell_ci(row, ci_assists);
1000                 add_3cell_ci(row, ci_hockey_assists);
1001                 add_3cell_ci(row, make_poisson_ci(p.defenses, p.points_played, z));
1002                 add_3cell_ci(row, make_poisson_ci(p.throwaways, p.points_played, z, true));
1003                 add_3cell_ci(row, make_poisson_ci(p.drops + p.was_ds, p.points_played, z, true));
1004                 if (p.points_played > 0) {
1005                         add_3cell(row, p.touches == 0 ? 0 : (p.touches / p.points_played).toFixed(2));
1006                 } else {
1007                         add_3cell(row, 'N/A');
1008                 }
1009                 row.dataset.player = q;
1010                 rows.push(row);
1011
1012                 goals += p.goals;
1013                 assists += p.assists;
1014                 hockey_assists += p.hockey_assists;
1015                 defenses += p.defenses;
1016                 throwaways += p.throwaways;
1017                 receiver_errors += p.drops + p.was_ds;
1018                 touches += p.touches;
1019         }
1020
1021         // Globals.
1022         let globals = players['globals'];
1023         let row = document.createElement('tr');
1024         add_3cell(row, '');
1025         if (globals.points_played > 0) {
1026                 add_3cell_with_filler_ci(row, goals == 0 ? 0 : (goals / globals.points_played).toFixed(2));
1027                 add_3cell_with_filler_ci(row, assists == 0 ? 0 : (assists / globals.points_played).toFixed(2));
1028                 add_3cell_with_filler_ci(row, hockey_assists == 0 ? 0 : (hockey_assists / globals.points_played).toFixed(2));
1029                 add_3cell_with_filler_ci(row, defenses == 0 ? 0 : (defenses / globals.points_played).toFixed(2));
1030                 add_3cell_with_filler_ci(row, throwaways == 0 ? 0 : (throwaways / globals.points_played).toFixed(2));
1031                 add_3cell_with_filler_ci(row, receiver_errors == 0 ? 0 : (receiver_errors / globals.points_played).toFixed(2));
1032                 add_3cell(row, touches == 0 ? 0 : (touches / globals.points_played).toFixed(2));
1033         } else {
1034                 add_3cell_with_filler_ci(row, 'N/A');
1035                 add_3cell_with_filler_ci(row, 'N/A');
1036                 add_3cell_with_filler_ci(row, 'N/A');
1037                 add_3cell_with_filler_ci(row, 'N/A');
1038                 add_3cell_with_filler_ci(row, 'N/A');
1039                 add_3cell_with_filler_ci(row, 'N/A');
1040                 add_3cell(row, 'N/A');
1041         }
1042         rows.push(row);
1043
1044         return rows;
1045 }
1046
1047 function open_filter_menu() {
1048         document.getElementById('filter-submenu').style.display = 'none';
1049
1050         let menu = document.getElementById('filter-add-menu');
1051         menu.style.display = 'block';
1052         menu.replaceChildren();
1053
1054         // Place the menu directly under the “click to add” label;
1055         // we don't anchor it since that label will move around
1056         // and the menu shouldn't.
1057         let rect = document.getElementById('filter-click-to-add').getBoundingClientRect();
1058         menu.style.left = rect.left + 'px';
1059         menu.style.top = (rect.bottom + 10) + 'px';
1060
1061         add_menu_item(menu, 0, 'match', 'Match (any)');
1062         add_menu_item(menu, 1, 'player_any', 'Player on field (any)');
1063         add_menu_item(menu, 2, 'player_all', 'Player on field (all)');
1064         add_menu_item(menu, 3, 'formation_offense', 'Offense played (any)');
1065         add_menu_item(menu, 4, 'formation_defense', 'Defense played (any)');
1066 }
1067
1068 function add_menu_item(menu, menu_idx, filter_type, title) {
1069         let item = document.createElement('div');
1070         item.classList.add('option');
1071         item.appendChild(document.createTextNode(title));
1072
1073         let arrow = document.createElement('div');
1074         arrow.classList.add('arrow');
1075         arrow.textContent = '▸';
1076         item.appendChild(arrow);
1077
1078         menu.appendChild(item);
1079
1080         item.addEventListener('click', (e) => { show_submenu(menu_idx, null, filter_type); });
1081 }
1082
1083 function show_submenu(menu_idx, pill, filter_type) {
1084         let submenu = document.getElementById('filter-submenu');
1085         let subitems = [];
1086         const filter = find_filter(filter_type);
1087
1088         let choices = [];
1089         if (filter_type === 'match') {
1090                 for (const match of global_json['matches']) {
1091                         choices.push({
1092                                 'title': match['description'],
1093                                 'id': match['match_id']
1094                         });
1095                 }
1096         } else if (filter_type === 'player_any' || filter_type === 'player_all') {
1097                 for (const player of global_json['players']) {
1098                         choices.push({
1099                                 'title': player['name'],
1100                                 'id': player['player_id']
1101                         });
1102                 }
1103         } else if (filter_type === 'formation_offense') {
1104                 choices.push({
1105                         'title': '(None/unknown)',
1106                         'id': 0,
1107                 });
1108                 for (const formation of global_json['formations']) {
1109                         if (formation['offense']) {
1110                                 choices.push({
1111                                         'title': formation['name'],
1112                                         'id': formation['formation_id']
1113                                 });
1114                         }
1115                 }
1116         } else if (filter_type === 'formation_defense') {
1117                 choices.push({
1118                         'title': '(None/unknown)',
1119                         'id': 0,
1120                 });
1121                 for (const formation of global_json['formations']) {
1122                         if (!formation['offense']) {
1123                                 choices.push({
1124                                         'title': formation['name'],
1125                                         'id': formation['formation_id']
1126                                 });
1127                         }
1128                 }
1129         }
1130
1131         for (const choice of choices) {
1132                 let label = document.createElement('label');
1133
1134                 let subitem = document.createElement('div');
1135                 subitem.classList.add('option');
1136
1137                 let check = document.createElement('input');
1138                 check.setAttribute('type', 'checkbox');
1139                 check.setAttribute('id', 'choice' + choice.id);
1140                 if (filter !== null && filter.elements.has(choice.id)) {
1141                         check.setAttribute('checked', 'checked');
1142                 }
1143                 check.addEventListener('change', (e) => { checkbox_changed(e, filter_type, choice.id); });
1144
1145                 subitem.appendChild(check);
1146                 subitem.appendChild(document.createTextNode(choice.title));
1147
1148                 label.appendChild(subitem);
1149                 subitems.push(label);
1150         }
1151         submenu.replaceChildren(...subitems);
1152         submenu.style.display = 'block';
1153
1154         if (pill !== null) {
1155                 let rect = pill.getBoundingClientRect();
1156                 submenu.style.top = (rect.bottom + 10) + 'px';
1157                 submenu.style.left = rect.left + 'px';
1158         } else {
1159                 // Position just outside the selected menu.
1160                 let rect = document.getElementById('filter-add-menu').getBoundingClientRect();
1161                 submenu.style.top = (rect.top + menu_idx * 35) + 'px';
1162                 submenu.style.left = (rect.right - 1) + 'px';
1163         }
1164 }
1165
1166 // Find the right filter, if it exists.
1167 function find_filter(filter_type) {
1168         for (let f of global_filters) {
1169                 if (f.type === filter_type) {
1170                         return f;
1171                 }
1172         }
1173         return null;
1174 }
1175
1176 function checkbox_changed(e, filter_type, id) {
1177         let filter = find_filter(filter_type);
1178         if (e.target.checked) {
1179                 // See if we must add a new filter to the list.
1180                 if (filter === null) {
1181                         filter = {
1182                                 'type': filter_type,
1183                                 'elements': new Set([ id ]),
1184                         };
1185                         filter.pill = make_filter_pill(filter);
1186                         global_filters.push(filter);
1187                         document.getElementById('filters').appendChild(filter.pill);
1188                 } else {
1189                         filter.elements.add(id);
1190                         let new_pill = make_filter_pill(filter);
1191                         document.getElementById('filters').replaceChild(new_pill, filter.pill);
1192                         filter.pill = new_pill;
1193                 }
1194         } else {
1195                 filter.elements.delete(id);
1196                 if (filter.elements.size === 0) {
1197                         document.getElementById('filters').removeChild(filter.pill);
1198                         global_filters = global_filters.filter(f => f !== filter);
1199                 } else {
1200                         let new_pill = make_filter_pill(filter);
1201                         document.getElementById('filters').replaceChild(new_pill, filter.pill);
1202                         filter.pill = new_pill;
1203                 }
1204         }
1205
1206         process_matches(global_json, global_filters);
1207 }
1208
1209 function make_filter_pill(filter) {
1210         let pill = document.createElement('div');
1211         pill.classList.add('filter-pill');
1212         let text;
1213         if (filter.type === 'match') {
1214                 text = 'Match: ';
1215
1216                 let all_names = [];
1217                 for (const match_id of filter.elements) {
1218                         all_names.push(find_match(match_id)['description']);
1219                 }
1220                 let common_prefix = find_common_prefix_of_all(all_names);
1221                 if (common_prefix !== null) {
1222                         text += common_prefix + '(';
1223                 }
1224
1225                 let first = true;
1226                 let sorted_match_id = Array.from(filter.elements).sort((a, b) => a - b);
1227                 for (const match_id of sorted_match_id) {
1228                         if (!first) {
1229                                 text += ', ';
1230                         }
1231                         let desc = find_match(match_id)['description'];
1232                         if (common_prefix === null) {
1233                                 text += desc;
1234                         } else {
1235                                 text += desc.substr(common_prefix.length);
1236                         }
1237                         first = false;
1238                 }
1239
1240                 if (common_prefix !== null) {
1241                         text += ')';
1242                 }
1243         } else if (filter.type === 'player_any') {
1244                 text = 'Player (any): ';
1245                 let sorted_players = Array.from(filter.elements).sort((a, b) => player_pos(a) - player_pos(b));
1246                 let first = true;
1247                 for (const player_id of sorted_players) {
1248                         if (!first) {
1249                                 text += ', ';
1250                         }
1251                         text += find_player(player_id)['name'];
1252                         first = false;
1253                 }
1254         } else if (filter.type === 'player_all') {
1255                 text = 'Players: ';
1256                 let sorted_players = Array.from(filter.elements).sort((a, b) => player_pos(a) - player_pos(b));
1257                 let first = true;
1258                 for (const player_id of sorted_players) {
1259                         if (!first) {
1260                                 text += ' AND ';
1261                         }
1262                         text += find_player(player_id)['name'];
1263                         first = false;
1264                 }
1265         } else if (filter.type === 'formation_offense' || filter.type === 'formation_defense') {
1266                 const offense = (filter.type === 'formation_offense');
1267                 if (offense) {
1268                         text = 'Offense: ';
1269                 } else {
1270                         text = 'Defense: ';
1271                 }
1272
1273                 let all_names = [];
1274                 for (const formation_id of filter.elements) {
1275                         all_names.push(find_formation(formation_id)['name']);
1276                 }
1277                 let common_prefix = find_common_prefix_of_all(all_names);
1278                 if (common_prefix !== null) {
1279                         text += common_prefix + '(';
1280                 }
1281
1282                 let first = true;
1283                 let sorted_formation_id = Array.from(filter.elements).sort((a, b) => a - b);
1284                 for (const formation_id of sorted_formation_id) {
1285                         if (!first) {
1286                                 text += ', ';
1287                         }
1288                         let desc = find_formation(formation_id)['name'];
1289                         if (common_prefix === null) {
1290                                 text += desc;
1291                         } else {
1292                                 text += desc.substr(common_prefix.length);
1293                         }
1294                         first = false;
1295                 }
1296
1297                 if (common_prefix !== null) {
1298                         text += ')';
1299                 }
1300         }
1301
1302         let text_node = document.createElement('span');
1303         text_node.innerText = text;
1304         text_node.addEventListener('click', (e) => show_submenu(null, pill, filter.type));
1305         pill.appendChild(text_node);
1306
1307         pill.appendChild(document.createTextNode(' '));
1308
1309         let delete_node = document.createElement('span');
1310         delete_node.innerText = '✖';
1311         delete_node.addEventListener('click', (e) => {
1312                 // Delete this filter entirely.
1313                 document.getElementById('filters').removeChild(pill);
1314                 global_filters = global_filters.filter(f => f !== filter);
1315                 process_matches(global_json, global_filters);
1316
1317                 let add_menu = document.getElementById('filter-add-menu');
1318                 let add_submenu = document.getElementById('filter-submenu');
1319                 add_menu.style.display = 'none';
1320                 add_submenu.style.display = 'none';
1321         });
1322         pill.appendChild(delete_node);
1323         pill.style.cursor = 'pointer';
1324
1325         return pill;
1326 }
1327
1328 function find_common_prefix(a, b) {
1329         let ret = '';
1330         for (let i = 0; i < Math.min(a.length, b.length); ++i) {
1331                 if (a[i] === b[i]) {
1332                         ret += a[i];
1333                 } else {
1334                         break;
1335                 }
1336         }
1337         return ret;
1338 }
1339
1340 function find_common_prefix_of_all(values) {
1341         if (values.length < 2) {
1342                 return null;
1343         }
1344         let common_prefix = null;
1345         for (const desc of values) {
1346                 if (common_prefix === null) {
1347                         common_prefix = desc;
1348                 } else {
1349                         common_prefix = find_common_prefix(common_prefix, desc);
1350                 }
1351         }
1352         if (common_prefix.length >= 3) {
1353                 return common_prefix;
1354         } else {
1355                 return null;
1356         }
1357 }
1358
1359 function find_match(match_id) {
1360         for (const match of global_json['matches']) {
1361                 if (match['match_id'] === match_id) {
1362                         return match;
1363                 }
1364         }
1365         return null;
1366 }
1367
1368 function find_formation(formation_id) {
1369         for (const formation of global_json['formations']) {
1370                 if (formation['formation_id'] === formation_id) {
1371                         return formation;
1372                 }
1373         }
1374         return null;
1375 }
1376
1377 function find_player(player_id) {
1378         for (const player of global_json['players']) {
1379                 if (player['player_id'] === player_id) {
1380                         return player;
1381                 }
1382         }
1383         return null;
1384 }
1385
1386 function player_pos(player_id) {
1387         let i = 0;
1388         for (const player of global_json['players']) {
1389                 if (player['player_id'] === player_id) {
1390                         return i;
1391                 }
1392                 ++i;
1393         }
1394         return null;
1395 }
1396
1397 function keep_match(match_id, filters) {
1398         for (const filter of filters) {
1399                 if (filter.type === 'match') {
1400                         return filter.elements.has(match_id);
1401                 }
1402         }
1403         return true;
1404 }
1405
1406 function filter_passes(players, formations_used_this_point, filter) {
1407         if (filter.type === 'player_any') {
1408                 for (const p of Array.from(filter.elements)) {
1409                         if (players[p].on_field_since !== null) {
1410                                 return true;
1411                         }
1412                 }
1413                 return false;
1414         } else if (filter.type === 'player_all') {
1415                 for (const p of Array.from(filter.elements)) {
1416                         if (players[p].on_field_since === null) {
1417                                 return false;
1418                         }
1419                 }
1420                 return true;
1421         } else if (filter.type === 'formation_offense' || filter.type === 'formation_defense') {
1422                 for (const f of Array.from(filter.elements)) {
1423                         if (formations_used_this_point.has(f)) {
1424                                 return true;
1425                         }
1426                 }
1427                 return false;
1428         }
1429         return true;
1430 }
1431
1432 function keep_event(players, formations_used_this_point, filters) {
1433         for (const filter of filters) {
1434                 if (!filter_passes(players, formations_used_this_point, filter)) {
1435                         return false;
1436                 }
1437         }
1438         return true;
1439 }
1440
1441 // Heuristic: If we go at least ten seconds without the possession changing
1442 // or the operator specifying some other formation, we probably play the
1443 // same formation as the last point.
1444 function should_reuse_last_formation(events, t) {
1445         for (const e of events) {
1446                 if (e.t <= t) {
1447                         continue;
1448                 }
1449                 if (e.t > t + 10000) {
1450                         break;
1451                 }
1452                 const type = e.type;
1453                 if (type === 'their_goal' || type === 'goal' ||
1454                     type === 'set_defense' || type === 'set_offense' ||
1455                     type === 'throwaway' || type === 'their_throwaway' ||
1456                     type === 'drop' || type === 'was_d' || type === 'stallout' || type === 'defense' || type === 'interception' ||
1457                     type === 'pull' || type === 'pull_landed' || type === 'pull_oob' || type === 'their_pull' ||
1458                     type === 'formation_offense' || type === 'formation_defense') {
1459                         return false;
1460                 }
1461         }
1462         return true;
1463 }
1464
1465 function possibly_close_menu(e) {
1466         if (e.target.closest('#filter-click-to-add') === null &&
1467             e.target.closest('#filter-add-menu') === null &&
1468             e.target.closest('#filter-submenu') === null &&
1469             e.target.closest('.filter-pill') === null) {
1470                 let add_menu = document.getElementById('filter-add-menu');
1471                 let add_submenu = document.getElementById('filter-submenu');
1472                 add_menu.style.display = 'none';
1473                 add_submenu.style.display = 'none';
1474         }
1475 }
1476
1477 let global_sort = {};
1478
1479 function sort_by(th) {
1480         let tr = th.parentElement;
1481         let child_idx = 0;
1482         for (let column_idx = 0; column_idx < tr.children.length; ++column_idx) {
1483                 let element = tr.children[column_idx];
1484                 if (element === th) {
1485                         ++child_idx;  // Pad.
1486                         break;
1487                 }
1488                 if (element.hasAttribute('colspan')) {
1489                         child_idx += parseInt(element.getAttribute('colspan'));
1490                 } else {
1491                         ++child_idx;
1492                 }
1493         }
1494
1495         global_sort = {};
1496         let table = tr.parentElement;
1497         for (let row_idx = 1; row_idx < table.children.length - 1; ++row_idx) {  // Skip header and globals.
1498                 let row = table.children[row_idx];
1499                 let player = parseInt(row.dataset.player);
1500                 let value = row.children[child_idx].textContent;
1501                 global_sort[player] = value;
1502         }
1503 }
1504
1505 function get_sorted_players(players)
1506 {
1507         let p = Object.entries(players);
1508         if (global_sort.length !== 0) {
1509                 p.sort((a,b) => {
1510                         let ai = parseFloat(global_sort[a[0]]);
1511                         let bi = parseFloat(global_sort[b[0]]);
1512                         if (ai == ai && bi == bi) {
1513                                 return bi - ai;  // Reverse numeric.
1514                         } else if (global_sort[a[0]] < global_sort[b[0]]) {
1515                                 return -1;
1516                         } else if (global_sort[a[0]] > global_sort[b[0]]) {
1517                                 return 1;
1518                         } else {
1519                                 return 0;
1520                         }
1521                 });
1522         }
1523         return p;
1524 }