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