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