]> git.sesse.net Git - pkanalytics/blob - ultimate.js
5642c73ef4175d47561ef622f6154e2b7a2d7112
[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.5 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.5,
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 goals = 0;
836         let num_throws = 0;
837         let throwaways = 0;
838         let catches = 0;
839         let drops = 0;
840         let was_ds = 0;
841         let stallouts = 0;
842         for (const [q,p] of get_sorted_players(players)) {
843                 if (q === 'globals') continue;
844                 let throw_ok = make_binomial_ci(p.num_throws - p.throwaways, p.num_throws, z);
845                 let catch_ok = make_binomial_ci(p.catches, p.catches + p.drops + p.was_ds, z);
846
847                 throw_ok.format = 'percentage';
848                 catch_ok.format = 'percentage';
849
850                 // Desire at least 90% percentage. Fairly arbitrary.
851                 throw_ok.desired = 0.9;
852                 catch_ok.desired = 0.9;
853
854                 let row = document.createElement('tr');
855                 add_3cell(row, p.name, 'name');  // TODO: number?
856                 add_3cell(row, p.goals);
857                 add_3cell(row, p.assists);
858                 add_3cell(row, p.hockey_assists);
859                 add_3cell(row, p.num_throws);
860                 add_3cell(row, p.throwaways);
861                 add_3cell_ci(row, throw_ok);
862                 add_3cell(row, p.catches);
863                 add_3cell(row, p.drops);
864                 add_3cell(row, p.was_ds);
865                 add_3cell_ci(row, catch_ok);
866                 add_3cell(row, p.stallouts);
867                 add_3cell(row, '+' + p.offensive_soft_plus);
868                 add_3cell(row, '-' + p.offensive_soft_minus);
869                 row.dataset.player = q;
870                 rows.push(row);
871
872                 goals += p.goals;
873                 num_throws += p.num_throws;
874                 throwaways += p.throwaways;
875                 catches += p.catches;
876                 drops += p.drops;
877                 was_ds += p.was_ds;
878                 stallouts += p.stallouts;
879         }
880
881         // Globals.
882         let throw_ok = make_binomial_ci(num_throws - throwaways, num_throws, z);
883         let catch_ok = make_binomial_ci(catches, catches + drops + was_ds, z);
884         throw_ok.format = 'percentage';
885         catch_ok.format = 'percentage';
886         throw_ok.desired = 0.9;
887         catch_ok.desired = 0.9;
888
889         let row = document.createElement('tr');
890         add_3cell(row, '');
891         add_3cell(row, goals);
892         add_3cell(row, '');
893         add_3cell(row, '');
894         add_3cell(row, num_throws);
895         add_3cell(row, throwaways);
896         add_3cell_ci(row, throw_ok);
897         add_3cell(row, catches);
898         add_3cell(row, drops);
899         add_3cell(row, was_ds);
900         add_3cell_ci(row, catch_ok);
901         add_3cell(row, stallouts);
902         add_3cell(row, '');
903         add_3cell(row, '');
904         rows.push(row);
905
906         return rows;
907 }
908
909 function make_table_defense(players) {
910         let rows = [];
911         {
912                 let header = document.createElement('tr');
913                 add_th(header, 'Player');
914                 add_th(header, 'Ds');
915                 add_th(header, 'Pulls');
916                 add_th(header, 'OOB pulls');
917                 add_th(header, 'OOB%');
918                 add_th(header, 'Avg. hang time (IB)');
919                 add_th(header, 'Callahans');
920                 add_th(header, 'Soft +/-', 6);
921                 rows.push(header);
922         }
923
924         let defenses = 0;
925         let pulls = 0;
926         let oob_pulls = 0;
927         let sum_sum_time = 0;
928         let callahans = 0;
929
930         for (const [q,p] of get_sorted_players(players)) {
931                 if (q === 'globals') continue;
932                 let sum_time = 0;
933                 for (const t of p.pull_times) {
934                         sum_time += t;
935                 }
936                 let avg_time = 1e-3 * sum_time / (p.pulls - p.oob_pulls);
937                 let oob_pct = 100 * p.oob_pulls / p.pulls;
938
939                 let ci_oob = make_binomial_ci(p.oob_pulls, p.pulls, z);
940                 ci_oob.format = 'percentage';
941                 ci_oob.desired = 0.2;  // Arbitrary.
942                 ci_oob.inverted = true;
943
944                 let row = document.createElement('tr');
945                 add_3cell(row, p.name, 'name');  // TODO: number?
946                 add_3cell(row, p.defenses);
947                 add_3cell(row, p.pulls);
948                 add_3cell(row, p.oob_pulls);
949                 add_3cell_ci(row, ci_oob);
950                 if (p.pulls > p.oob_pulls) {
951                         add_3cell(row, avg_time.toFixed(1) + ' sec');
952                 } else {
953                         add_3cell(row, 'N/A');
954                 }
955                 add_3cell(row, p.callahans);
956                 add_3cell(row, '+' + p.defensive_soft_plus);
957                 add_3cell(row, '-' + p.defensive_soft_minus);
958                 row.dataset.player = q;
959                 rows.push(row);
960
961                 defenses += p.defenses;
962                 pulls += p.pulls;
963                 oob_pulls += p.oob_pulls;
964                 sum_sum_time += sum_time;
965                 callahans += p.callahans;
966         }
967
968         // Globals.
969         let ci_oob = make_binomial_ci(oob_pulls, pulls, z);
970         ci_oob.format = 'percentage';
971         ci_oob.desired = 0.2;  // Arbitrary.
972         ci_oob.inverted = true;
973
974         let avg_time = 1e-3 * sum_sum_time / (pulls - oob_pulls);
975         let oob_pct = 100 * oob_pulls / pulls;
976
977         let row = document.createElement('tr');
978         add_3cell(row, '');
979         add_3cell(row, defenses);
980         add_3cell(row, pulls);
981         add_3cell(row, oob_pulls);
982         add_3cell_ci(row, ci_oob);
983         if (pulls > oob_pulls) {
984                 add_3cell(row, avg_time.toFixed(1) + ' sec');
985         } else {
986                 add_3cell(row, 'N/A');
987         }
988         add_3cell(row, callahans);
989         add_3cell(row, '');
990         add_3cell(row, '');
991         rows.push(row);
992
993         return rows;
994 }
995
996 function make_table_playing_time(players) {
997         let rows = [];
998         {
999                 let header = document.createElement('tr');
1000                 add_th(header, 'Player');
1001                 add_th(header, 'Points played');
1002                 add_th(header, 'Time played');
1003                 add_th(header, 'O time');
1004                 add_th(header, 'D time');
1005                 add_th(header, 'Time on field');
1006                 add_th(header, 'O points');
1007                 add_th(header, 'D points');
1008                 rows.push(header);
1009         }
1010
1011         for (const [q,p] of get_sorted_players(players)) {
1012                 if (q === 'globals') continue;
1013                 let row = document.createElement('tr');
1014                 add_3cell(row, p.name, 'name');  // TODO: number?
1015                 add_3cell(row, p.points_played);
1016                 add_3cell(row, Math.floor(p.playing_time_ms / 60000) + ' min');
1017                 add_3cell(row, Math.floor(p.offensive_playing_time_ms / 60000) + ' min');
1018                 add_3cell(row, Math.floor(p.defensive_playing_time_ms / 60000) + ' min');
1019                 add_3cell(row, Math.floor(p.field_time_ms / 60000) + ' min');
1020                 add_3cell(row, p.offensive_points_completed);
1021                 add_3cell(row, p.defensive_points_completed);
1022                 row.dataset.player = q;
1023                 rows.push(row);
1024         }
1025
1026         // Globals.
1027         let globals = players['globals'];
1028         let row = document.createElement('tr');
1029         add_3cell(row, '');
1030         add_3cell(row, globals.points_played);
1031         add_3cell(row, Math.floor(globals.playing_time_ms / 60000) + ' min');
1032         add_3cell(row, Math.floor(globals.offensive_playing_time_ms / 60000) + ' min');
1033         add_3cell(row, Math.floor(globals.defensive_playing_time_ms / 60000) + ' min');
1034         add_3cell(row, Math.floor(globals.field_time_ms / 60000) + ' min');
1035         add_3cell(row, globals.offensive_points_completed);
1036         add_3cell(row, globals.defensive_points_completed);
1037         rows.push(row);
1038
1039         return rows;
1040 }
1041
1042 function make_table_per_point(players) {
1043         let rows = [];
1044         {
1045                 let header = document.createElement('tr');
1046                 add_th(header, 'Player');
1047                 add_th(header, 'Goals');
1048                 add_th(header, 'Assists');
1049                 add_th(header, 'Hockey assists');
1050                 add_th(header, 'Ds');
1051                 add_th(header, 'Throwaways');
1052                 add_th(header, 'Recv. errors');
1053                 add_th(header, 'Touches');
1054                 rows.push(header);
1055         }
1056
1057         let goals = 0;
1058         let assists = 0;
1059         let hockey_assists = 0;
1060         let defenses = 0;
1061         let throwaways = 0;
1062         let receiver_errors = 0;
1063         let touches = 0;
1064         for (const [q,p] of get_sorted_players(players)) {
1065                 if (q === 'globals') continue;
1066
1067                 // Can only happen once per point, so these are binomials.
1068                 let ci_goals = make_binomial_ci(p.goals, p.points_played, z);
1069                 let ci_assists = make_binomial_ci(p.assists, p.points_played, z);
1070                 let ci_hockey_assists = make_binomial_ci(p.hockey_assists, p.points_played, z);
1071                 // Arbitrarily desire at least 10% (not everybody can score or assist).
1072                 ci_goals.desired = 0.1;
1073                 ci_assists.desired = 0.1;
1074                 ci_hockey_assists.desired = 0.1;
1075
1076                 let row = document.createElement('tr');
1077                 add_3cell(row, p.name, 'name');  // TODO: number?
1078                 add_3cell_ci(row, ci_goals);
1079                 add_3cell_ci(row, ci_assists);
1080                 add_3cell_ci(row, ci_hockey_assists);
1081                 add_3cell_ci(row, make_poisson_ci(p.defenses, p.points_played, z));
1082                 add_3cell_ci(row, make_poisson_ci(p.throwaways, p.points_played, z, true));
1083                 add_3cell_ci(row, make_poisson_ci(p.drops + p.was_ds, p.points_played, z, true));
1084                 if (p.points_played > 0) {
1085                         add_3cell(row, p.touches == 0 ? 0 : (p.touches / p.points_played).toFixed(2));
1086                 } else {
1087                         add_3cell(row, 'N/A');
1088                 }
1089                 row.dataset.player = q;
1090                 rows.push(row);
1091
1092                 goals += p.goals;
1093                 assists += p.assists;
1094                 hockey_assists += p.hockey_assists;
1095                 defenses += p.defenses;
1096                 throwaways += p.throwaways;
1097                 receiver_errors += p.drops + p.was_ds;
1098                 touches += p.touches;
1099         }
1100
1101         // Globals.
1102         let globals = players['globals'];
1103         let row = document.createElement('tr');
1104         add_3cell(row, '');
1105         if (globals.points_played > 0) {
1106                 let ci_goals = make_binomial_ci(goals, globals.points_played, z);
1107                 let ci_assists = make_binomial_ci(assists, globals.points_played, z);
1108                 let ci_hockey_assists = make_binomial_ci(hockey_assists, globals.points_played, z);
1109                 ci_goals.desired = 0.5;
1110                 ci_assists.desired = 0.5;
1111                 ci_hockey_assists.desired = 0.5;
1112
1113                 add_3cell_ci(row, ci_goals);
1114                 add_3cell_ci(row, ci_assists);
1115                 add_3cell_ci(row, ci_hockey_assists);
1116
1117                 add_3cell_ci(row, make_poisson_ci(defenses, globals.points_played, z));
1118                 add_3cell_ci(row, make_poisson_ci(throwaways, globals.points_played, z, true));
1119                 add_3cell_ci(row, make_poisson_ci(receiver_errors, globals.points_played, z, true));
1120
1121                 add_3cell(row, touches == 0 ? 0 : (touches / globals.points_played).toFixed(2));
1122         } else {
1123                 add_3cell_with_filler_ci(row, 'N/A');
1124                 add_3cell_with_filler_ci(row, 'N/A');
1125                 add_3cell_with_filler_ci(row, 'N/A');
1126                 add_3cell_with_filler_ci(row, 'N/A');
1127                 add_3cell_with_filler_ci(row, 'N/A');
1128                 add_3cell_with_filler_ci(row, 'N/A');
1129                 add_3cell(row, 'N/A');
1130         }
1131         rows.push(row);
1132
1133         return rows;
1134 }
1135
1136 function open_filter_menu() {
1137         document.getElementById('filter-submenu').style.display = 'none';
1138
1139         let menu = document.getElementById('filter-add-menu');
1140         menu.style.display = 'block';
1141         menu.replaceChildren();
1142
1143         // Place the menu directly under the “click to add” label;
1144         // we don't anchor it since that label will move around
1145         // and the menu shouldn't.
1146         let rect = document.getElementById('filter-click-to-add').getBoundingClientRect();
1147         menu.style.left = rect.left + 'px';
1148         menu.style.top = (rect.bottom + 10) + 'px';
1149
1150         add_menu_item(global_filters, menu, 0, 'match', 'Match (any)');
1151         add_menu_item(global_filters, menu, 1, 'player_any', 'Player on field (any)');
1152         add_menu_item(global_filters, menu, 2, 'player_all', 'Player on field (all)');
1153         add_menu_item(global_filters, menu, 3, 'formation_offense', 'Offense played (any)');
1154         add_menu_item(global_filters, menu, 4, 'formation_defense', 'Defense played (any)');
1155         add_menu_item(global_filters, menu, 5, 'starting_on', 'Starting on');
1156         add_menu_item(global_filters, menu, 6, 'gender_ratio', 'Gender ratio');
1157 }
1158
1159 function add_menu_item(filterset, menu, menu_idx, filter_type, title) {
1160         let item = document.createElement('div');
1161         item.classList.add('option');
1162         item.appendChild(document.createTextNode(title));
1163
1164         let arrow = document.createElement('div');
1165         arrow.classList.add('arrow');
1166         arrow.textContent = '▸';
1167         item.appendChild(arrow);
1168
1169         menu.appendChild(item);
1170
1171         item.addEventListener('click', (e) => { show_submenu(filterset, menu_idx, null, filter_type); });
1172 }
1173
1174 function find_all_ratios(json)
1175 {
1176         let ratios = {};
1177         let players = {};
1178         for (const player of json['players']) {
1179                 players[player['player_id']] = {
1180                         'gender': player['gender'],
1181                         'last_point_seen': null,
1182                 };
1183         }
1184         for (const match of json['matches']) {
1185                 for (const [q,p] of Object.entries(players)) {
1186                         p.on_field_since = null;
1187                 }
1188                 for (const e of match['events']) {
1189                         let p = players[e['player']];
1190                         let type = e['type'];
1191                         if (type === 'in') {
1192                                 p.on_field_since = 1;
1193                         } else if (type === 'out') {
1194                                 p.on_field_since = null;
1195                         } else if (type === 'pull' || type == 'their_pull') {  // We assume no cross-gender subs for now.
1196                                 let code = find_gender_ratio_code(players);
1197                                 if (ratios[code] === undefined) {
1198                                         ratios[code] = code;
1199                                         if (code !== '4 F, 3 M' && code !== '4 M, 3 F' && code !== '3 M, 2 F' && code !== '3 F, 2 M') {
1200                                                 console.log('Unexpected gender ratio ' + code + ' first seen at: ' +
1201                                                             match['description'] + ', ' + format_time(e['t']));
1202                                         }
1203                                 }
1204                         }
1205                 }
1206         }
1207         return ratios;
1208 }
1209
1210 function show_submenu(filterset, menu_idx, pill, filter_type) {
1211         let submenu = document.getElementById('filter-submenu');
1212         let subitems = [];
1213         const filter = find_filter(filterset, filter_type);
1214
1215         let choices = [];
1216         if (filter_type === 'match') {
1217                 for (const match of global_json['matches']) {
1218                         choices.push({
1219                                 'title': match['description'],
1220                                 'id': match['match_id']
1221                         });
1222                 }
1223         } else if (filter_type === 'player_any' || filter_type === 'player_all') {
1224                 for (const player of global_json['players']) {
1225                         choices.push({
1226                                 'title': player['name'],
1227                                 'id': player['player_id']
1228                         });
1229                 }
1230         } else if (filter_type === 'formation_offense') {
1231                 choices.push({
1232                         'title': '(None/unknown)',
1233                         'id': 0,
1234                 });
1235                 for (const formation of global_json['formations']) {
1236                         if (formation['offense']) {
1237                                 choices.push({
1238                                         'title': formation['name'],
1239                                         'id': formation['formation_id']
1240                                 });
1241                         }
1242                 }
1243         } else if (filter_type === 'formation_defense') {
1244                 choices.push({
1245                         'title': '(None/unknown)',
1246                         'id': 0,
1247                 });
1248                 for (const formation of global_json['formations']) {
1249                         if (!formation['offense']) {
1250                                 choices.push({
1251                                         'title': formation['name'],
1252                                         'id': formation['formation_id']
1253                                 });
1254                         }
1255                 }
1256         } else if (filter_type === 'starting_on') {
1257                 choices.push({
1258                         'title': 'Offense',
1259                         'id': false,  // last_pull_was_ours
1260                 });
1261                 choices.push({
1262                         'title': 'Defense',
1263                         'id': true,  // last_pull_was_ours
1264                 });
1265         } else if (filter_type === 'gender_ratio') {
1266                 for (const [title, id] of Object.entries(find_all_ratios(global_json)).sort()) {
1267                         choices.push({
1268                                 'title': title,
1269                                 'id': id,
1270                         });
1271                 }
1272         }
1273
1274         for (const choice of choices) {
1275                 let label = document.createElement('label');
1276
1277                 let subitem = document.createElement('div');
1278                 subitem.classList.add('option');
1279
1280                 let check = document.createElement('input');
1281                 check.setAttribute('type', 'checkbox');
1282                 check.setAttribute('id', 'choice' + choice.id);
1283                 if (filter !== null && filter.elements.has(choice.id)) {
1284                         check.setAttribute('checked', 'checked');
1285                 }
1286                 check.addEventListener('change', (e) => { checkbox_changed(filterset, e, filter_type, choice.id); });
1287
1288                 subitem.appendChild(check);
1289                 subitem.appendChild(document.createTextNode(choice.title));
1290
1291                 label.appendChild(subitem);
1292                 subitems.push(label);
1293         }
1294         submenu.replaceChildren(...subitems);
1295         submenu.style.display = 'block';
1296
1297         if (pill !== null) {
1298                 let rect = pill.getBoundingClientRect();
1299                 submenu.style.top = (rect.bottom + 10) + 'px';
1300                 submenu.style.left = rect.left + 'px';
1301         } else {
1302                 // Position just outside the selected menu.
1303                 let rect = document.getElementById('filter-add-menu').getBoundingClientRect();
1304                 submenu.style.top = (rect.top + menu_idx * 35) + 'px';
1305                 submenu.style.left = (rect.right - 1) + 'px';
1306         }
1307 }
1308
1309 // Find the right filter, if it exists.
1310 function find_filter(filterset, filter_type) {
1311         for (let f of filterset) {
1312                 if (f.type === filter_type) {
1313                         return f;
1314                 }
1315         }
1316         return null;
1317 }
1318
1319 // Equivalent to Array.prototype.filter, but in-place.
1320 function inplace_filter(arr, cond) {
1321         let j = 0;
1322         for (let i = 0; i < arr.length; ++i) {
1323                 if (cond(arr[i])) {
1324                         arr[j++] = arr[i];
1325                 }
1326         }
1327         arr.length = j;
1328 }
1329
1330 function checkbox_changed(filterset, e, filter_type, id) {
1331         let filter = find_filter(filterset, filter_type);
1332         if (e.target.checked) {
1333                 // See if we must add a new filter to the list.
1334                 if (filter === null) {
1335                         filter = {
1336                                 'type': filter_type,
1337                                 'elements': new Set([ id ]),
1338                         };
1339                         filter.pill = make_filter_pill(filterset, filter);
1340                         filterset.push(filter);
1341                         document.getElementById('filters').appendChild(filter.pill);
1342                 } else {
1343                         filter.elements.add(id);
1344                         let new_pill = make_filter_pill(filterset, filter);
1345                         document.getElementById('filters').replaceChild(new_pill, filter.pill);
1346                         filter.pill = new_pill;
1347                 }
1348         } else {
1349                 filter.elements.delete(id);
1350                 if (filter.elements.size === 0) {
1351                         document.getElementById('filters').removeChild(filter.pill);
1352                         inplace_filter(filterset, f => f !== filter);
1353                 } else {
1354                         let new_pill = make_filter_pill(filterset, filter);
1355                         document.getElementById('filters').replaceChild(new_pill, filter.pill);
1356                         filter.pill = new_pill;
1357                 }
1358         }
1359
1360         process_matches(global_json, global_filters);
1361 }
1362
1363 function make_filter_pill(filterset, filter) {
1364         let pill = document.createElement('div');
1365         pill.classList.add('filter-pill');
1366         let text;
1367         if (filter.type === 'match') {
1368                 text = 'Match: ';
1369
1370                 let all_names = [];
1371                 for (const match_id of filter.elements) {
1372                         all_names.push(find_match(match_id)['description']);
1373                 }
1374                 let common_prefix = find_common_prefix_of_all(all_names);
1375                 if (common_prefix !== null) {
1376                         text += common_prefix + '(';
1377                 }
1378
1379                 let first = true;
1380                 let sorted_match_id = Array.from(filter.elements).sort((a, b) => a - b);
1381                 for (const match_id of sorted_match_id) {
1382                         if (!first) {
1383                                 text += ', ';
1384                         }
1385                         let desc = find_match(match_id)['description'];
1386                         if (common_prefix === null) {
1387                                 text += desc;
1388                         } else {
1389                                 text += desc.substr(common_prefix.length);
1390                         }
1391                         first = false;
1392                 }
1393
1394                 if (common_prefix !== null) {
1395                         text += ')';
1396                 }
1397         } else if (filter.type === 'player_any') {
1398                 text = 'Player (any): ';
1399                 let sorted_players = Array.from(filter.elements).sort((a, b) => player_pos(a) - player_pos(b));
1400                 let first = true;
1401                 for (const player_id of sorted_players) {
1402                         if (!first) {
1403                                 text += ', ';
1404                         }
1405                         text += find_player(player_id)['name'];
1406                         first = false;
1407                 }
1408         } else if (filter.type === 'player_all') {
1409                 text = 'Players: ';
1410                 let sorted_players = Array.from(filter.elements).sort((a, b) => player_pos(a) - player_pos(b));
1411                 let first = true;
1412                 for (const player_id of sorted_players) {
1413                         if (!first) {
1414                                 text += ' AND ';
1415                         }
1416                         text += find_player(player_id)['name'];
1417                         first = false;
1418                 }
1419         } else if (filter.type === 'formation_offense' || filter.type === 'formation_defense') {
1420                 const offense = (filter.type === 'formation_offense');
1421                 if (offense) {
1422                         text = 'Offense: ';
1423                 } else {
1424                         text = 'Defense: ';
1425                 }
1426
1427                 let all_names = [];
1428                 for (const formation_id of filter.elements) {
1429                         all_names.push(find_formation(formation_id)['name']);
1430                 }
1431                 let common_prefix = find_common_prefix_of_all(all_names);
1432                 if (common_prefix !== null) {
1433                         text += common_prefix + '(';
1434                 }
1435
1436                 let first = true;
1437                 let sorted_formation_id = Array.from(filter.elements).sort((a, b) => a - b);
1438                 for (const formation_id of sorted_formation_id) {
1439                         if (!first) {
1440                                 ktext += ', ';
1441                         }
1442                         let desc = find_formation(formation_id)['name'];
1443                         if (common_prefix === null) {
1444                                 text += desc;
1445                         } else {
1446                                 text += desc.substr(common_prefix.length);
1447                         }
1448                         first = false;
1449                 }
1450
1451                 if (common_prefix !== null) {
1452                         text += ')';
1453                 }
1454         } else if (filter.type === 'starting_on') {
1455                 text = 'Starting on: ';
1456
1457                 if (filter.elements.has(false) && filter.elements.has(true)) {
1458                         text += 'Any';
1459                 } else if (filter.elements.has(false)) {
1460                         text += 'Offense';
1461                 } else {
1462                         text += 'Defense';
1463                 }
1464         } else if (filter.type === 'gender_ratio') {
1465                 text = 'Gender: ';
1466
1467                 let first = true;
1468                 for (const name of Array.from(filter.elements).sort()) {
1469                         if (!first) {
1470                                 text += '; ';
1471                         }
1472                         text += name;
1473                         first = false;
1474                 }
1475         }
1476
1477         let text_node = document.createElement('span');
1478         text_node.innerText = text;
1479         text_node.addEventListener('click', (e) => show_submenu(filterset, null, pill, filter.type));
1480         pill.appendChild(text_node);
1481
1482         pill.appendChild(document.createTextNode(' '));
1483
1484         let delete_node = document.createElement('span');
1485         delete_node.innerText = '✖';
1486         delete_node.addEventListener('click', (e) => {
1487                 // Delete this filter entirely.
1488                 document.getElementById('filters').removeChild(pill);
1489                 inplace_filter(filterset, f => f !== filter);
1490                 process_matches(global_json, global_filters);
1491
1492                 let add_menu = document.getElementById('filter-add-menu');
1493                 let add_submenu = document.getElementById('filter-submenu');
1494                 add_menu.style.display = 'none';
1495                 add_submenu.style.display = 'none';
1496         });
1497         pill.appendChild(delete_node);
1498         pill.style.cursor = 'pointer';
1499
1500         return pill;
1501 }
1502
1503 function find_common_prefix(a, b) {
1504         let ret = '';
1505         for (let i = 0; i < Math.min(a.length, b.length); ++i) {
1506                 if (a[i] === b[i]) {
1507                         ret += a[i];
1508                 } else {
1509                         break;
1510                 }
1511         }
1512         return ret;
1513 }
1514
1515 function find_common_prefix_of_all(values) {
1516         if (values.length < 2) {
1517                 return null;
1518         }
1519         let common_prefix = null;
1520         for (const desc of values) {
1521                 if (common_prefix === null) {
1522                         common_prefix = desc;
1523                 } else {
1524                         common_prefix = find_common_prefix(common_prefix, desc);
1525                 }
1526         }
1527         if (common_prefix.length >= 3) {
1528                 return common_prefix;
1529         } else {
1530                 return null;
1531         }
1532 }
1533
1534 function find_match(match_id) {
1535         for (const match of global_json['matches']) {
1536                 if (match['match_id'] === match_id) {
1537                         return match;
1538                 }
1539         }
1540         return null;
1541 }
1542
1543 function find_formation(formation_id) {
1544         for (const formation of global_json['formations']) {
1545                 if (formation['formation_id'] === formation_id) {
1546                         return formation;
1547                 }
1548         }
1549         return null;
1550 }
1551
1552 function find_player(player_id) {
1553         for (const player of global_json['players']) {
1554                 if (player['player_id'] === player_id) {
1555                         return player;
1556                 }
1557         }
1558         return null;
1559 }
1560
1561 function player_pos(player_id) {
1562         let i = 0;
1563         for (const player of global_json['players']) {
1564                 if (player['player_id'] === player_id) {
1565                         return i;
1566                 }
1567                 ++i;
1568         }
1569         return null;
1570 }
1571
1572 function keep_match(match_id, filters) {
1573         for (const filter of filters) {
1574                 if (filter.type === 'match') {
1575                         return filter.elements.has(match_id);
1576                 }
1577         }
1578         return true;
1579 }
1580
1581 function find_gender_ratio_code(players) {
1582         let map = {};
1583         for (const [q,p] of Object.entries(players)) {
1584                 if (p.on_field_since === null) {
1585                         continue;
1586                 }
1587                 let gender = p.gender;
1588                 if (gender === '' || gender === undefined || gender === null) {
1589                         gender = '?';
1590                 }
1591                 if (map[gender] === undefined) {
1592                         map[gender] = 1;
1593 q               } else {
1594                         ++map[gender];
1595                 }
1596         }
1597         let all_genders = Array.from(Object.keys(map)).sort(
1598                 (a,b) => {
1599                         if (map[a] !== map[b]) {
1600                                 return map[b] - map[a];  // Reverse numeric.
1601                         } else if (a < b) {
1602                                 return -1;
1603                         } else if (a > b) {
1604                                 return 1;
1605                         } else {
1606                                 return 0;
1607                         }
1608                 });
1609         let code = '';
1610         for (const g of all_genders) {
1611                 if (code !== '') {
1612                         code += ', ';
1613                 }
1614                 code += map[g];
1615                 code += ' ';
1616                 code += g;
1617         }
1618         return code;
1619 }
1620
1621 function filter_passes(players, formations_used_this_point, last_pull_was_ours, filter) {
1622         if (filter.type === 'player_any') {
1623                 for (const p of Array.from(filter.elements)) {
1624                         if (players[p].on_field_since !== null) {
1625                                 return true;
1626                         }
1627                 }
1628                 return false;
1629         } else if (filter.type === 'player_all') {
1630                 for (const p of Array.from(filter.elements)) {
1631                         if (players[p].on_field_since === null) {
1632                                 return false;
1633                         }
1634                 }
1635                 return true;
1636         } else if (filter.type === 'formation_offense' || filter.type === 'formation_defense') {
1637                 for (const f of Array.from(filter.elements)) {
1638                         if (formations_used_this_point.has(f)) {
1639                                 return true;
1640                         }
1641                 }
1642                 return false;
1643         } else if (filter.type === 'starting_on') {
1644                 return filter.elements.has(last_pull_was_ours);
1645         } else if (filter.type === 'gender_ratio') {
1646                 return filter.elements.has(find_gender_ratio_code(players));
1647         }
1648         return true;
1649 }
1650
1651 function keep_event(players, formations_used_this_point, last_pull_was_ours, filters) {
1652         for (const filter of filters) {
1653                 if (!filter_passes(players, formations_used_this_point, last_pull_was_ours, filter)) {
1654                         return false;
1655                 }
1656         }
1657         return true;
1658 }
1659
1660 // Heuristic: If we go at least ten seconds without the possession changing
1661 // or the operator specifying some other formation, we probably play the
1662 // same formation as the last point.
1663 function should_reuse_last_formation(events, t) {
1664         for (const e of events) {
1665                 if (e.t <= t) {
1666                         continue;
1667                 }
1668                 if (e.t > t + 10000) {
1669                         break;
1670                 }
1671                 const type = e.type;
1672                 if (type === 'their_goal' || type === 'goal' ||
1673                     type === 'set_defense' || type === 'set_offense' ||
1674                     type === 'throwaway' || type === 'their_throwaway' ||
1675                     type === 'drop' || type === 'was_d' || type === 'stallout' || type === 'defense' || type === 'interception' ||
1676                     type === 'pull' || type === 'pull_landed' || type === 'pull_oob' || type === 'their_pull' ||
1677                     type === 'formation_offense' || type === 'formation_defense') {
1678                         return false;
1679                 }
1680         }
1681         return true;
1682 }
1683
1684 function possibly_close_menu(e) {
1685         if (e.target.closest('#filter-click-to-add') === null &&
1686             e.target.closest('#filter-add-menu') === null &&
1687             e.target.closest('#filter-submenu') === null &&
1688             e.target.closest('.filter-pill') === null) {
1689                 let add_menu = document.getElementById('filter-add-menu');
1690                 let add_submenu = document.getElementById('filter-submenu');
1691                 add_menu.style.display = 'none';
1692                 add_submenu.style.display = 'none';
1693         }
1694 }
1695
1696 let global_sort = {};
1697
1698 function sort_by(th) {
1699         let tr = th.parentElement;
1700         let child_idx = 0;
1701         for (let column_idx = 0; column_idx < tr.children.length; ++column_idx) {
1702                 let element = tr.children[column_idx];
1703                 if (element === th) {
1704                         ++child_idx;  // Pad.
1705                         break;
1706                 }
1707                 if (element.hasAttribute('colspan')) {
1708                         child_idx += parseInt(element.getAttribute('colspan'));
1709                 } else {
1710                         ++child_idx;
1711                 }
1712         }
1713
1714         global_sort = {};
1715         let table = tr.parentElement;
1716         for (let row_idx = 1; row_idx < table.children.length - 1; ++row_idx) {  // Skip header and globals.
1717                 let row = table.children[row_idx];
1718                 let player = parseInt(row.dataset.player);
1719                 let value = row.children[child_idx].textContent;
1720                 global_sort[player] = value;
1721         }
1722 }
1723
1724 function get_sorted_players(players)
1725 {
1726         let p = Object.entries(players);
1727         if (global_sort.length !== 0) {
1728                 p.sort((a,b) => {
1729                         let ai = parseFloat(global_sort[a[0]]);
1730                         let bi = parseFloat(global_sort[b[0]]);
1731                         if (ai == ai && bi == bi) {
1732                                 return bi - ai;  // Reverse numeric.
1733                         } else if (global_sort[a[0]] < global_sort[b[0]]) {
1734                                 return -1;
1735                         } else if (global_sort[a[0]] > global_sort[b[0]]) {
1736                                 return 1;
1737                         } else {
1738                                 return 0;
1739                         }
1740                 });
1741         }
1742         return p;
1743 }