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