-
Notifications
You must be signed in to change notification settings - Fork 6
/
pgn4web.js
3459 lines (3046 loc) · 123 KB
/
pgn4web.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* pgn4web javascript chessboard
* copyright (C) 2009, 2011 Paolo Casaschi
* see README file and http://pgn4web.casaschi.net
* for credits, license and more details
*/
var pgn4web_version = '2.23+';
var pgn4web_project_url = 'http://pgn4web.casaschi.net';
var pgn4web_project_author = 'Paolo Casaschi';
// pgn4web_project_email could be preassigned in pgn4web-server-config.js
var pgn4web_project_email;
if (pgn4web_project_email === undefined) { pgn4web_project_email = '[email protected]'; }
var helpWin=null;
function displayHelp(section){
if (!section) { section = "top"; }
if (helpWin && !helpWin.closed) { helpWin.close(); }
helpWin = window.open(detectHelpLocation() + "?" +
(Math.floor(900 * Math.random()) + 100) + "#" + section, "pgn4web_help",
"resizable=yes,scrollbars=yes,toolbar=no,location=no,menubar=no,status=no");
if ((helpWin !== null) && (window.focus)) { helpWin.focus(); }
}
// custom functions executed at the given moments
// to be redefined in the HTML AFTER loading pgn4web.js
function customFunctionOnPgnTextLoad() {}
function customFunctionOnPgnGameLoad() {}
function customFunctionOnMove() {}
function customFunctionOnAlert(msg) {}
function customFunctionOnCheckLiveBroadcastStatus() {}
//custom header tags APIs for customFunctionOnPgnGameLoad()
function customPgnHeaderTag(customTagString, htmlElementIdString, gameNum) {
customTagString = customTagString.replace(/\W+/g, "");
if (gameNum === undefined) { gameNum = currentGame; }
if ((pgnGame[gameNum]) && (tagValues = pgnGame[gameNum].match('\\[\\s*' + customTagString + '\\s*\"([^\"]+)\"\\s*\\]'))) {
tagValue = tagValues[1];
} else { tagValue = ""; }
if ((htmlElementIdString) && (theObject = document.getElementById(htmlElementIdString)) && (theObject.innerHTML !== null)) {
theObject.innerHTML = tagValue;
}
return tagValue;
}
// custom comment tags APIS for customFunctionOnMove()
function customPgnCommentTag(customTagString, htmlElementIdString, plyNum) {
customTagString = customTagString.replace(/\W+/g, "");
if (plyNum === undefined) { plyNum = CurrentPly; }
if ((MoveComments[plyNum]) && (tagValues = MoveComments[plyNum].match('\\[%' + customTagString + '\\s*([^\\]]+)\\s*\\]'))) {
tagValue = tagValues[1];
} else { tagValue = ""; }
if ((htmlElementIdString) && (theObject = document.getElementById(htmlElementIdString)) && (theObject.innerHTML !== null)) {
theObject.innerHTML = tagValue;
}
return tagValue;
}
var basicNAGs = /^[\?!+#\s]*/;
function strippedMoveComment(plyNum) {
if (!MoveComments[plyNum]) { return ""; }
return MoveComments[plyNum].replace(/\[%[^\]]*\]\s*/g,'').replace(basicNAGs, '').replace(/^\s+$/,'');
}
function basicNAGsMoveComment(plyNum) {
if (!MoveComments[plyNum]) { return ""; }
thisBasicNAGs = MoveComments[plyNum].replace(/\[%[^\]]*\]\s*/g,'').match(basicNAGs, '');
return thisBasicNAGs ? thisBasicNAGs[0].replace(/\s+/,'') : '';
}
window.onload = start_pgn4web;
document.onkeydown = handlekey;
function start_pgn4web() {
// keep startup logs at first run
// reset alert log when reloading start_pgn4web
if (alertFirstResetLoadingPgn) { alertFirstResetLoadingPgn = false; }
else { resetAlert(); }
InitImages();
createBoard();
if (LiveBroadcastDelay > 0) { restartLiveBroadcastTimeout(); }
}
var alertLog;
var alertLast;
var alertNum;
var alertNumSinceReset;
var fatalErrorNumSinceReset;
var alertPromptInterval = null;
var alertPromptOn = false;
var alertFirstResetLoadingPgn = true;
resetAlert();
function resetAlert() {
alertLog = new Array(5);
alertLast = alertLog.length - 1;
alertNum = alertNumSinceReset = fatalErrorNumSinceReset = 0;
stopAlertPrompt();
if (!alertFirstResetLoadingPgn) {
boardShortcut(debugShortcutSquare, "pgn4web v" + pgn4web_version + " debug info");
}
}
function myAlert(msg, fatalError) {
alertNum++;
alertNumSinceReset++;
if (fatalError) { fatalErrorNumSinceReset++; }
alertLast = (alertLast + 1) % alertLog.length;
alertLog[alertLast] = msg + "\n" + (new Date()).toLocaleString();
boardShortcut(debugShortcutSquare,
"pgn4web v" + pgn4web_version + " debug info, " + alertNum + " alert" + (alertNum > 1 ? "s" : ""));
if ((LiveBroadcastDelay === 0) || (LiveBroadcastAlert === true)) {
startAlertPrompt();
}
customFunctionOnAlert(msg);
}
function startAlertPrompt() {
if (alertPromptOn) { return; } // dont start flashing twice
if (alertPromptInterval) { clearTimeout(alertPromptInterval); }
alertPromptInterval = setTimeout("alertPromptTick(true);", 500);
}
function stopAlertPrompt() {
if (alertPromptInterval) {
clearTimeout(alertPromptInterval);
alertPromptInterval = null;
}
if (alertPromptOn) { alertPromptTick(false); }
}
function alertPromptTick(restart) {
if (alertPromptInterval) {
clearTimeout(alertPromptInterval);
alertPromptInterval = null;
}
theObject = document.getElementById('tcol0trow0');
if(theObject) {
if (alertPromptOn) {
if ((highlightOption) &&
((lastColFromHighlighted === 0 && lastRowFromHighlighted === 7) ||
(lastColToHighlighted === 0 && lastRowToHighlighted === 7))) {
theObject.className = 'highlightWhiteSquare';
} else { theObject.className = 'whiteSquare'; }
} else { theObject.className = 'blackSquare'; }
alertPromptOn = !alertPromptOn;
if (alertPromptOn) { alertPromptDelay = 500; }
else { alertPromptDelay = 3000; }
} else { alertPromptDelay = 1500; } // for alerts before the baord is drawn
if (restart) { alertPromptInterval = setTimeout("alertPromptTick(true);", alertPromptDelay); }
}
function stopKeyProp(e) {
e.cancelBubble = true;
if (e.stopPropagation) { e.stopPropagation(); }
if (e.preventDefault) { e.preventDefault(); }
return false;
}
// for onFocus and onBlur actions on textboxes, allowing text typing
var shortcutKeysWereEnabled = false;
function disableShortcutKeysAndStoreStatus() {
if ((shortcutKeysWereEnabled = shortcutKeysEnabled) === true) {
SetShortcutKeysEnabled(false);
}
}
function restoreShortcutKeysStatus() {
if (shortcutKeysWereEnabled === true) { SetShortcutKeysEnabled(true); }
shortcutKeysWereEnabled = false;
}
function customShortcutKey_Shift_0() {}
function customShortcutKey_Shift_1() {}
function customShortcutKey_Shift_2() {}
function customShortcutKey_Shift_3() {}
function customShortcutKey_Shift_4() {}
function customShortcutKey_Shift_5() {}
function customShortcutKey_Shift_6() {}
function customShortcutKey_Shift_7() {}
function customShortcutKey_Shift_8() {}
function customShortcutKey_Shift_9() {}
var shortcutKeysEnabled = false;
function handlekey(e) {
var keycode;
if (!e) { e = window.event; }
keycode = e.keyCode;
if (e.altKey || e.ctrlKey || e.metaKey) { return true; }
// escape always enabled: help and toggle shortcut keys
if ((keycode != 27) && (shortcutKeysEnabled === false)) { return true; }
switch(keycode) {
case 8: // backspace
case 9: // tab
case 16: // shift
case 17: // ctrl
case 18: // alt
case 32: // space
case 33: // page-up
case 34: // page-down
case 35: // end
case 36: // home
case 45: // insert
case 46: // delete
case 92: // super
case 93: // menu
return true;
case 27: // escape
if (e.shiftKey) { interactivelyToggleShortcutKeys(); }
else { displayHelp(); }
return stopKeyProp(e);
case 90: // z
if (e.shiftKey) { window.open(pgn4web_project_url); }
else { displayDebugInfo(); }
return stopKeyProp(e);
case 37: // left-arrow
case 74: // j
MoveBackward(1);
return stopKeyProp(e);
case 38: // up-arrow
case 72: // h
GoToMove(StartPly);
return stopKeyProp(e);
case 39: // right-arrow
case 75: // k
MoveForward(1);
return stopKeyProp(e);
case 40: // down-arrow
case 76: // l
GoToMove(StartPly + PlyNumber);
return stopKeyProp(e);
case 85: // u
MoveToPrevComment();
return stopKeyProp(e);
case 73: // i
MoveToNextComment();
return stopKeyProp(e);
case 83: // s
searchPgnGamePrompt();
return stopKeyProp(e);
case 13: // enter
if (e.shiftKey) { searchPgnGame(lastSearchPgnExpression, true); }
else { searchPgnGame(lastSearchPgnExpression); }
return stopKeyProp(e);
case 65: // a
MoveForward(1);
SetAutoPlay(true);
return stopKeyProp(e);
case 48: // 0
if (e.shiftKey) { customShortcutKey_Shift_0(); }
else { SetAutoPlay(false); }
return stopKeyProp(e);
case 49: // 1
if (e.shiftKey) { customShortcutKey_Shift_1(); }
else { SetAutoplayDelayAndStart( 1*1000); }
return stopKeyProp(e);
case 50: // 2
if (e.shiftKey) { customShortcutKey_Shift_2(); }
else { SetAutoplayDelayAndStart( 2*1000); }
return stopKeyProp(e);
case 51: // 3
if (e.shiftKey) { customShortcutKey_Shift_3(); }
else { SetAutoplayDelayAndStart( 3*1000); }
return stopKeyProp(e);
case 52: // 4
if (e.shiftKey) { customShortcutKey_Shift_4(); }
else { SetAutoplayDelayAndStart( 4*1000); }
return stopKeyProp(e);
case 53: // 5
if (e.shiftKey) { customShortcutKey_Shift_5(); }
else { SetAutoplayDelayAndStart( 5*1000); }
return stopKeyProp(e);
case 54: // 6
if (e.shiftKey) { customShortcutKey_Shift_6(); }
else { SetAutoplayDelayAndStart( 6*1000); }
return stopKeyProp(e);
case 55: // 7
if (e.shiftKey) { customShortcutKey_Shift_7(); }
else { SetAutoplayDelayAndStart( 7*1000); }
return stopKeyProp(e);
case 56: // 8
if (e.shiftKey) { customShortcutKey_Shift_8(); }
else { SetAutoplayDelayAndStart( 8*1000); }
return stopKeyProp(e);
case 57: // 9
if (e.shiftKey) { customShortcutKey_Shift_9(); }
else { SetAutoplayDelayAndStart( 9*1000); }
return stopKeyProp(e);
case 81: // q
SetAutoplayDelayAndStart(10*1000);
return stopKeyProp(e);
case 87: // w
SetAutoplayDelayAndStart(20*1000);
return stopKeyProp(e);
case 69: // e
SetAutoplayDelayAndStart(30*1000);
return stopKeyProp(e);
case 82: // r
pauseLiveBroadcast();
return stopKeyProp(e);
case 84: // t
if (e.shiftKey) { LiveBroadcastSteppingMode = !LiveBroadcastSteppingMode; }
else { refreshPgnSource(); }
return stopKeyProp(e);
case 89: // y
resumeLiveBroadcast();
return stopKeyProp(e);
case 70: // f
FlipBoard();
return stopKeyProp(e);
case 71: // g
SetHighlight(!highlightOption);
return stopKeyProp(e);
case 68: // d
if (IsRotated) { FlipBoard(); }
return stopKeyProp(e);
case 88: // x
if (numberOfGames > 1) {
Init(Math.floor(Math.random()*numberOfGames));
GoToMove(StartPly + Math.floor(Math.random()*(StartPly + PlyNumber + 1)));
}
return stopKeyProp(e);
case 67: // c
if (numberOfGames > 1) { Init(Math.floor(Math.random()*numberOfGames)); }
return stopKeyProp(e);
case 86: // v
if (numberOfGames > 1) { Init(0); }
return stopKeyProp(e);
case 66: // b
Init(currentGame - 1);
return stopKeyProp(e);
case 78: // n
Init(currentGame + 1);
return stopKeyProp(e);
case 77: // m
if (numberOfGames > 1) { Init(numberOfGames - 1); }
return stopKeyProp(e);
case 79: // o
SetCommentsOnSeparateLines(!commentsOnSeparateLines);
oldPly = CurrentPly;
Init();
GoToMove(oldPly);
return stopKeyProp(e);
case 80: // p
SetCommentsIntoMoveText(!commentsIntoMoveText);
oldPly = CurrentPly;
Init();
GoToMove(oldPly);
return stopKeyProp(e);
default:
return true;
}
return true;
}
boardOnClick = new Array(8);
boardTitle = new Array(8);
for (col=0; col<8; col++) {
boardOnClick[col] = new Array(8);
boardTitle[col] = new Array(8);
}
clearShortcutSquares("ABCDEFGH", "12345678");
function clearShortcutSquares(cols, rows) {
if ((typeof cols != "string") || (typeof rows != "string")) { return; }
for (c=0; c<cols.length; c++) { for (r=0; r<rows.length; r++) {
boardShortcut(cols.charAt(c).toUpperCase()+rows.charAt(r), "", function(){});
} }
}
function boardShortcut(square, title, functionPointer) {
if (square.charCodeAt === null) { return; }
var col = square.charCodeAt(0) - 65; // 65="A"
if ((col < 0) || (col > 7)) { return; }
var row = 56 - square.charCodeAt(1); // 56="8"
if ((row < 0) || (row > 7)) { return; }
boardTitle[col][row] = title;
if (functionPointer) { boardOnClick[col][row] = functionPointer; }
if (theObject = document.getElementById('link_tcol' + col + 'trow' + row)) {
if (IsRotated) { square = String.fromCharCode(72-col,49+row); }
if (boardTitle[col][row] !== '') { squareTitle = square + ': ' + boardTitle[col][row]; }
else { squareTitle = square; }
theObject.title = squareTitle;
}
}
// PLEASE NOTE: 'boardShortcut' ALWAYS ASSUMES 'square' WITH WHITE ON BOTTOM
debugShortcutSquare = "A8";
// A8
boardShortcut("A8", "pgn4web v" + pgn4web_version + " debug info", function(){ displayDebugInfo(); });
// B8
boardShortcut("B8", "show this position FEN string", function(){ displayFenData(); });
// C8
boardShortcut("C8", "show this game PGN source data", function(){ displayPgnData(false); });
// D8
boardShortcut("D8", "show full PGN source data", function(){ displayPgnData(true); });
// E8
boardShortcut("E8", "search help", function(){ displayHelp("search"); });
// F8
boardShortcut("F8", "shortcut keys help", function(){ displayHelp("keys"); });
// G8
boardShortcut("G8", "shortcut squares help", function(){ displayHelp("squares"); });
// H8
boardShortcut("H8", "pgn4web help", function(){ displayHelp(); });
// A7
boardShortcut("A7", "pgn4web website", function(){ window.open(pgn4web_project_url); });
// B7
boardShortcut("B7", "toggle show comments in game text", function(){ SetCommentsIntoMoveText(!commentsIntoMoveText); oldPly = CurrentPly; Init(); GoToMove(oldPly); });
// C7
boardShortcut("C7", "toggle show comments on separate lines in game text", function(){ SetCommentsOnSeparateLines(!commentsOnSeparateLines); oldPly = CurrentPly; Init(); GoToMove(oldPly); });
// D7
boardShortcut("D7", "toggle highlight last move", function(){ SetHighlight(!highlightOption); });
// E7
boardShortcut("E7", "flip board", function(){ FlipBoard(); });
// F7
boardShortcut("F7", "show white on bottom", function(){ if (IsRotated) { FlipBoard(); } });
// G7
boardShortcut("G7", "toggle autoplay next game", function(){ SetAutoplayNextGame(!autoplayNextGame); });
// H7
boardShortcut("H7", "toggle enabling shortcut keys", function(){ interactivelyToggleShortcutKeys(); });
// A6
boardShortcut("A6", "pause live broadcast automatic refresh", function(){ pauseLiveBroadcast(); });
// B6
boardShortcut("B6", "restart live broadcast automatic refresh", function(){ restartLiveBroadcast(); });
// C6
boardShortcut("C6", "search previous finished game", function(){ searchPgnGame('\\[\\s*Result\\s*"(?!\\*"\\s*\\])', true); });
// D6
boardShortcut("D6", "search previous unfinished game", function(){ searchPgnGame('\\[\\s*Result\\s*"\\*"\\s*\\]', true); });
// E6
boardShortcut("E6", "search next unfinished game", function(){ searchPgnGame('\\[\\s*Result\\s*"\\*"\\s*\\]', false); });
// F6
boardShortcut("F6", "search next finished game", function(){ searchPgnGame('\\[\\s*Result\\s*"(?!\\*"\\s*\\])', false); });
// G6
boardShortcut("G6", "toggle live broadcast stepping", function(){ LiveBroadcastSteppingMode = !LiveBroadcastSteppingMode; });
// H6
boardShortcut("H6", "force games refresh during live broadcast", function(){ refreshPgnSource(); });
// A5
boardShortcut("A5", "repeat last search backward", function(){ searchPgnGame(lastSearchPgnExpression, true); });
// B5
boardShortcut("B5", "search prompt", function(){ searchPgnGamePrompt(); });
// C5
boardShortcut("C5", "repeat last search", function(){ searchPgnGame(lastSearchPgnExpression); });
// D5
boardShortcut("D5", "search previous win result", function(){ searchPgnGame('\\[\\s*Result\\s*"(1-0|0-1)"\\s*\\]', true); });
// E5
boardShortcut("E5", "search next win result", function(){ searchPgnGame('\\[\\s*Result\\s*"(1-0|0-1)"\\s*\\]', false); });
// F5
boardShortcut("F5", "", function(){});
// G5
boardShortcut("G5", "", function(){});
// H5
boardShortcut("H5", "", function(){});
// A4
boardShortcut("A4", "search previous event", function(){ searchPgnGame('\\[\\s*Event\\s*"(?!' + fixRegExp(gameEvent[currentGame]) + '"\\s*\\])', true); });
// B4
boardShortcut("B4", "search previous round of same event", function(){ searchPgnGame('\\[\\s*Event\\s*"' + fixRegExp(gameEvent[currentGame]) + '"\\s*\\].*\\[\\s*Round\\s*"(?!' + fixRegExp(gameRound[currentGame]) + '"\\s*\\])|\\[\\s*Event\\s*"' + fixRegExp(gameEvent[currentGame]) + '"\\s*\\].*\\[\\s*Round\\s*"(?!' + fixRegExp(gameRound[currentGame]) + '"\\s*\\])', true); });
// C4
boardShortcut("C4", "search previous game of same black player", function(){ searchPgnGame('\\[\\s*Black\\s*"' + fixRegExp(gameBlack[currentGame]) + '"\\s*\\]', true); });
// D4
boardShortcut("D4", "search previous game of same white player", function(){ searchPgnGame('\\[\\s*White\\s*"' + fixRegExp(gameWhite[currentGame]) + '"\\s*\\]', true); });
// E4
boardShortcut("E4", "search next game of same white player", function(){ searchPgnGame('\\[\\s*White\\s*"' + fixRegExp(gameWhite[currentGame]) + '"\\s*\\]', false); });
// F4
boardShortcut("F4", "search next game of same black player", function(){ searchPgnGame('\\[\\s*Black\\s*"' + fixRegExp(gameBlack[currentGame]) + '"\\s*\\]', false); });
// G4
boardShortcut("G4", "search next round of same event", function(){ searchPgnGame('\\[\\s*Event\\s*"' + fixRegExp(gameEvent[currentGame]) + '"\\s*\\].*\\[\\s*Round\\s*"(?!' + fixRegExp(gameRound[currentGame]) + '"\\s*\\])|\\[\\s*Event\\s*"' + fixRegExp(gameEvent[currentGame]) + '"\\s*\\].*\\[\\s*Round\\s*"(?!' + fixRegExp(gameRound[currentGame]) + '"\\s*\\])', false); });
// H4
boardShortcut("H4", "search next event", function(){ searchPgnGame('\\[\\s*Event\\s*"(?!' + fixRegExp(gameEvent[currentGame]) + '"\\s*\\])', false); });
// A3
boardShortcut("A3", "load first game", function(){ if (numberOfGames > 1) { Init(0); } });
// B3
boardShortcut("B3", "jump to previous games decile", function(){ if (currentGame > 0) { calculateDeciles(); for(ii=(deciles.length-2); ii>=0; ii--) { if (currentGame > deciles[ii]) { Init(deciles[ii]); break; } } } });
// C3
boardShortcut("C3", "load previous game", function(){ Init(currentGame - 1); });
// D3
boardShortcut("D3", "load random game", function(){ if (numberOfGames > 1) { Init(Math.floor(Math.random()*numberOfGames)); } });
// E3
boardShortcut("E3", "load random game at random position", function(){ Init(Math.floor(Math.random()*numberOfGames)); GoToMove(StartPly + Math.floor(Math.random()*(StartPly + PlyNumber + 1))); });
// F3
boardShortcut("F3", "load next game", function(){ Init(currentGame + 1); });
// G3
boardShortcut("G3", "jump to next games decile", function(){ if (currentGame < numberOfGames - 1) { calculateDeciles(); for(ii=1; ii<deciles.length; ii++) { if (currentGame < deciles[ii]) { Init(deciles[ii]); break; } } } });
// H3
boardShortcut("H3", "load last game", function(){ if (numberOfGames > 1) { Init(numberOfGames - 1); } });
// A2
boardShortcut("A2", "stop autoplay", function(){ SetAutoPlay(false); });
// B2
boardShortcut("B2", "toggle autoplay", function(){ SwitchAutoPlay(); });
// C2
boardShortcut("C2", "autoplay 1 second", function(){ SetAutoplayDelayAndStart( 1*1000); });
// D2
boardShortcut("D2", "autoplay 2 seconds", function(){ SetAutoplayDelayAndStart( 2*1000); });
// E2
boardShortcut("E2", "autoplay 3 seconds", function(){ SetAutoplayDelayAndStart( 3*1000); });
// F2
boardShortcut("F2", "autoplay 5 seconds", function(){ SetAutoplayDelayAndStart( 5*1000); });
// G2
boardShortcut("G2", "autoplay 10 seconds", function(){ SetAutoplayDelayAndStart(10*1000); });
// H2
boardShortcut("H2", "autoplay 30 seconds", function(){ SetAutoplayDelayAndStart(30*1000); });
// A1
boardShortcut("A1", "go to game start", function(){ GoToMove(StartPly); });
// B1
boardShortcut("B1", "go to previous comment", function(){ MoveToPrevComment(); });
// C1
boardShortcut("C1", "move 6 half-moves backward", function(){ MoveBackward(6); });
// D1
boardShortcut("D1", "move backward", function(){ MoveBackward(1); });
// E1
boardShortcut("E1", "move forward", function(){ MoveForward(1); });
// F1
boardShortcut("F1", "move 6 half-moves forward", function(){ MoveForward(6); });
// G1
boardShortcut("G1", "go to next comment", function(){ MoveToNextComment(); });
// H1
boardShortcut("H1", "go to game end", function(){ GoToMove(StartPly + PlyNumber); });
var deciles = new Array(11);
function calculateDeciles() {
for (ii=0; ii<deciles.length; ii++) {
deciles[ii] = Math.round((numberOfGames - 1) * ii / (deciles.length - 1));
}
}
function detectJavascriptLocation() {
jspath = "";
var e = document.getElementsByTagName('script');
for(var i=0; i<e.length; i++) {
if ((e[i].src) && (e[i].src.match(/(pgn4web|pgn4web-compacted)\.js/))) {
jspath = e[i].src;
}
}
return jspath;
}
function detectHelpLocation() {
return detectJavascriptLocation().replace(/(pgn4web|pgn4web-compacted)\.js/, "help.html");
}
function detectBaseLocation() {
base = "";
var e = document.getElementsByTagName('base');
for(var i=0; i<e.length; i++) {
if (e[i].href) { base = e[i].href; }
}
return base;
}
debugWin = null;
function displayDebugInfo() {
stopAlertPrompt();
debugInfo = 'pgn4web: version=' + pgn4web_version + ' homepage=' + pgn4web_project_url + '\n\n' +
'HTMLURL: length=' + location.href.length + ' url=' +
(location.href.length < 100 ? location.href : (location.href.substring(0,99) + '...')) + '\n' +
'BASEURL: url=' + detectBaseLocation() + '\n' +
'JSURL: url=' + detectJavascriptLocation() + '\n\n' +
'PGNURL: url=' + pgnUrl + '\n' +
'PGNTEXT: length=';
if (document.getElementById("pgnText") !== null) {
debugInfo += document.getElementById("pgnText").tagName.toLowerCase() == "textarea" ?
document.getElementById("pgnText").value.length :
document.getElementById("pgnText").innerHTML.length +
' container=' + document.getElementById("pgnText").tagName.toLowerCase();
// pgn4web up to 1.77 used <span> for pgnText
}
debugInfo += '\n\n' +
'GAMES: current=' + (currentGame+1) + ' number=' + numberOfGames + '\n' +
'PLY: start=' + StartPly + ' current=' + CurrentPly + ' number=' + PlyNumber + '\n' +
'AUTOPLAY: ' + (isAutoPlayOn ? 'delay=' + Delay + 'ms' + ' autoplaynext=' + autoplayNextGame : 'off') +
'\n\n' +
'LIVEBROADCAST: ' + (LiveBroadcastDelay > 0 ? 'ticker=' + LiveBroadcastTicker + ' delay=' + LiveBroadcastDelay + 'm' + ' started=' + LiveBroadcastStarted + ' ended=' + LiveBroadcastEnded + ' paused=' + LiveBroadcastPaused + ' demo=' + LiveBroadcastDemo + ' alert=' + LiveBroadcastAlert + ' stepping=' + LiveBroadcastSteppingMode + '\n' + 'refreshed: ' + LiveBroadcastLastRefreshedLocal + '\n' + 'received: ' + LiveBroadcastLastReceivedLocal + '\n' + 'modified (server time): ' + LiveBroadcastLastModified_ServerTime() : 'off') +
'\n\n' +
'ALERTLOG: fatalnew=' + fatalErrorNumSinceReset + ' new=' + alertNumSinceReset +
' shown=' + Math.min(alertNum, alertLog.length) + ' total=' + alertNum + '\n--';
if (alertNum > 0) {
for (ii = 0; ii<alertLog.length; ii++) {
if (alertLog[(alertNum - 1 - ii) % alertLog.length] === undefined) { break; }
else { debugInfo += "\n" + alertLog[(alertNum - 1 - ii) % alertLog.length] + "\n--"; }
}
}
if (confirm(debugInfo + '\n\nclick OK to show this debug info in a browser window for cut and paste')) {
if (debugWin && !debugWin.closed) { debugWin.close(); }
debugWin = window.open("", "debug_data",
"resizable=yes,scrollbars=yes,toolbar=no,location=no,menubar=no,status=no");
if (debugWin !== null) {
text = "<html><head><title>pgn4web debug info</title>" +
"<link rel='shortcut icon' href='pawn.ico' /></head>" +
"<body>\n<pre>\n" + debugInfo + "\n</pre>\n</body></html>";
debugWin.document.open("text/html", "replace");
debugWin.document.write(text);
debugWin.document.close();
if (window.focus) { debugWin.focus(); }
}
}
alertNumSinceReset = fatalErrorNumSinceReset = 0;
}
pgnWin = null;
function displayPgnData(allGames) {
if (allGames === null) { allGames = true; }
if (pgnWin && !pgnWin.closed) { pgnWin.close(); }
pgnWin = window.open("", "pgn_data",
"resizable=yes,scrollbars=yes,toolbar=no,location=no,menubar=no,status=no");
if (pgnWin !== null) {
text = "<html><head><title>pgn4web PGN source</title>" +
"<link rel='shortcut icon' href='pawn.ico' /></head><body>\n<pre>\n";
if (allGames) { for (ii = 0; ii < numberOfGames; ++ii) { text += pgnGame[ii]; } }
else { text += pgnGame[currentGame]; }
text += "\n</pre>\n</body></html>";
pgnWin.document.open("text/html", "replace");
pgnWin.document.write(text);
pgnWin.document.close();
if (window.focus) { pgnWin.focus(); }
}
}
function CurrentFEN() {
currentFEN = "";
emptyCounterFen = 0;
for (row=7; row>=0; row--) {
for (col=0; col<=7; col++) {
if (Board[col][row] === 0) { emptyCounterFen++; }
else {
if (emptyCounterFen > 0) {
currentFEN += "" + emptyCounterFen;
emptyCounterFen = 0;
}
if (Board[col][row] > 0) { currentFEN += FenPieceName.toUpperCase().charAt(Board[col][row]-1); }
else if (Board[col][row] < 0) { currentFEN += FenPieceName.toLowerCase().charAt(-Board[col][row]-1); }
}
}
if (emptyCounterFen > 0) {
currentFEN += "" + emptyCounterFen;
emptyCounterFen = 0;
}
if (row>0) { currentFEN += "/"; }
}
// active color
currentFEN += CurrentPly%2 === 0 ? " w" : " b";
// castling availability
CastlingShortFEN = CastlingShort;
CastlingLongFEN = CastlingLong;
for (var thisPly = StartPly; thisPly < CurrentPly; thisPly++) {
SideToMoveFEN = thisPly%2;
BackrowSideToMoveFEN = SideToMoveFEN * 7;
if (HistType[0][thisPly] == 1) {
CastlingShortFEN[SideToMoveFEN] = CastlingLongFEN[SideToMoveFEN] = -1;
}
if ((HistCol[0][thisPly] == CastlingShortFEN[SideToMoveFEN]) &&
(HistRow[0][thisPly] == BackrowSideToMoveFEN)) {
CastlingShortFEN[SideToMoveFEN] = -1;
}
if ((HistCol[0][thisPly] == CastlingLongFEN[SideToMoveFEN]) &&
(HistRow[0][thisPly] == BackrowSideToMoveFEN)) {
CastlingLongFEN[SideToMoveFEN] = -1;
}
}
CastlingFEN = "";
if (SquareOnBoard(CastlingShortFEN[0], 0)) {
for (ii = 7; ii > CastlingShortFEN[0]; ii--) { if (Board[ii][0] == 3) { break; } }
if (ii == CastlingShortFEN[0]) { CastlingFEN += FenPieceName.toUpperCase().charAt(0); }
else { CastlingFEN += columnsLetters.toUpperCase().charAt(CastlingShortFEN[0]); }
}
if (SquareOnBoard(CastlingLongFEN[0], 0)) {
for (ii = 0; ii < CastlingLongFEN[0]; ii++) { if (Board[ii][0] == 3) { break; } }
if (ii == CastlingLongFEN[0]) { CastlingFEN += FenPieceName.toUpperCase().charAt(1); }
else { CastlingFEN += columnsLetters.toUpperCase().charAt(CastlingLongFEN[0]); }
}
if (SquareOnBoard(CastlingShortFEN[1], 7)) {
for (ii = 7; ii > CastlingShortFEN[1]; ii--) { if (Board[ii][7] == -3) { break; } }
if (ii == CastlingShortFEN[1]) { CastlingFEN += FenPieceName.toLowerCase().charAt(0); }
else { CastlingFEN += columnsLetters.toLowerCase().charAt(CastlingShortFEN[1]); }
}
if (SquareOnBoard(CastlingLongFEN[1], 7)) {
for (ii = 0; ii < CastlingLongFEN[1]; ii++) { if (Board[ii][7] == -3) { break; } }
if (ii == CastlingLongFEN[1]) { CastlingFEN += FenPieceName.toLowerCase().charAt(1); }
else { CastlingFEN += columnsLetters.toLowerCase().charAt(CastlingLongFEN[1]); }
}
if (CastlingFEN === "") { CastlingFEN = "-"; }
currentFEN += " " + CastlingFEN;
// en-passant square
if (HistEnPassant[CurrentPly-1]) {
currentFEN += " " + String.fromCharCode(HistEnPassantCol[CurrentPly-1] + 97);
currentFEN += CurrentPly%2 === 0 ? "6" : "3";
} else { currentFEN += " -"; }
// halfmove clock
HalfMoveClock = InitialHalfMoveClock;
for (thisPly = StartPly; thisPly < CurrentPly; thisPly++) {
if ((HistType[0][thisPly] == 6) || (HistPieceId[1][thisPly] >= 16)) { HalfMoveClock = 0; }
else { HalfMoveClock++; }
}
currentFEN += " " + HalfMoveClock;
// fullmove number
currentFEN += " " + (Math.floor(CurrentPly/2)+1);
return currentFEN;
}
fenWin = null;
function displayFenData() {
if (fenWin && !fenWin.closed) { fenWin.close(); }
currentFEN = CurrentFEN();
currentMovesString = "";
lastLineStart = 0;
for(var thisPly = CurrentPly; thisPly <= StartPly + PlyNumber; thisPly++) {
addToMovesString = "";
if (thisPly == StartPly + PlyNumber) {
if ((gameResult[currentGame]) && (gameResult[currentGame] != "*")) {
addToMovesString = gameResult[currentGame];
}
} else {
if ((thisPly%2) === 0) { addToMovesString = (Math.floor(thisPly/2)+1) + ". "; }
else if (thisPly == CurrentPly) {
addToMovesString = (Math.floor(thisPly/2)+1) + "... ";
}
addToMovesString += Moves[thisPly];
}
if (currentMovesString.length + addToMovesString.length + 1 > lastLineStart + 80) {
lastLineStart = currentMovesString.length;
currentMovesString += "\n" + addToMovesString;
} else {
if (currentMovesString.length > 0) { currentMovesString += " "; }
currentMovesString += addToMovesString;
}
}
fenWin = window.open("", "fen_data",
"resizable=yes,scrollbars=yes,toolbar=no,location=no,menubar=no,status=no");
if (fenWin !== null) {
text = "<html>" +
"<head><title>pgn4web FEN string</title><link rel='shortcut icon' href='pawn.ico' /></head>" +
"<body>\n<b><pre>\n\n" + currentFEN + "\n\n</pre></b>\n<hr>\n<pre>\n\n" +
"[Event \"" + (gameEvent[currentGame] ? gameEvent[currentGame] : "?") + "\"]\n" +
"[Site \"" + (gameSite[currentGame] ? gameSite[currentGame] : "?") + "\"]\n" +
"[Date \"" + (gameDate[currentGame] ? gameDate[currentGame] : "????.??.??") + "\"]\n" +
"[Round \"" + (gameRound[currentGame] ? gameRound[currentGame] : "?") + "\"]\n" +
"[White \"" + (gameWhite[currentGame] ? gameWhite[currentGame] : "?") + "\"]\n" +
"[Black \"" + (gameBlack[currentGame] ? gameBlack[currentGame] : "?") + "\"]\n" +
"[Result \"" + (gameResult[currentGame] ? gameResult[currentGame] : "*") + "\"]\n";
if (currentFEN != FenStringStart) {
text += "[SetUp \"1\"]\n" + "[FEN \"" + CurrentFEN() + "\"]\n";
}
if (gameVariant[currentGame] !== "") { text += "[Variant \"" + gameVariant[currentGame] + "\"]\n"; }
text += "\n" + currentMovesString + "\n</pre>\n</body></html>";
fenWin.document.open("text/html", "replace");
fenWin.document.write(text);
fenWin.document.close();
if (window.focus) { fenWin.focus(); }
}
}
var pgnGame = new Array();
var numberOfGames = -1;
var currentGame = -1;
var firstStart = true;
var gameDate = new Array();
var gameWhite = new Array();
var gameBlack = new Array();
var gameEvent = new Array();
var gameSite = new Array();
var gameRound = new Array();
var gameResult = new Array();
var gameSetUp = new Array();
var gameFEN = new Array();
var gameInitialWhiteClock = new Array();
var gameInitialBlackClock = new Array();
var gameVariant = new Array();
var oldAnchor = -1;
var isAutoPlayOn = false;
var AutoPlayInterval = null;
var Delay = 1000; // milliseconds
var autostartAutoplay = false;
var autoplayNextGame = false;
var initialGame = 1;
var initialHalfmove = 0;
var alwaysInitialHalfmove = false;
var LiveBroadcastInterval = null;
var LiveBroadcastDelay = 0; // minutes
var LiveBroadcastAlert = false;
var LiveBroadcastDemo = false;
var LiveBroadcastStarted = false;
var LiveBroadcastEnded = false;
var LiveBroadcastPaused = false;
var LiveBroadcastTicker = 0;
var LiveBroadcastStatusString = "";
var LiveBroadcastLastModified = new Date(0); // default to epoch start
var LiveBroadcastLastModifiedHeader = LiveBroadcastLastModified.toUTCString();
var LiveBroadcastLastReceivedLocal = 'unavailable';
var LiveBroadcastLastRefreshedLocal = 'unavailable';
var LiveBroadcastPlaceholderEvent = 'live chess broadcast';
var LiveBroadcastPlaceholderPgn = '[Event "' + LiveBroadcastPlaceholderEvent + '"]';
var gameDemoMaxPly = new Array();
var gameDemoLength = new Array();
var LiveBroadcastSteppingMode = false;
var ParseLastMoveError = false;
var MaxMove = 500;
var castleRook = -1;
var mvCapture = 0;
var mvIsCastling = 0;
var mvIsPromotion = 0;
var mvFromCol = -1;
var mvFromRow = -1;
var mvToCol = -1;
var mvToRow = -1;
var mvPiece = -1;
var mvPieceId = -1;
var mvPieceOnTo = -1;
var mvCaptured = -1;
var mvCapturedId = -1;
Board = new Array(8);
for(i=0; i<8; ++i) { Board[i] = new Array(8); }
// HistCol, HistRow: move history up to last replayed ply
// HistCol[0], HistRow[0]: "square from" (0..7, 0..7 from square a1)
// HistCol[1], HistRow[1]: castling/capture
// HistCol[2], HistRow[2]: "square to" (0..7, 0..7 from square a1)
HistCol = new Array(3);
HistRow = new Array(3);
HistPieceId = new Array(2);
HistType = new Array(2);
PieceCol = new Array(2);
PieceRow = new Array(2);
PieceType = new Array(2);
PieceMoveCounter = new Array(2);
for(i=0; i<2; ++i){
PieceCol[i] = new Array(16);
PieceRow[i] = new Array(16);
PieceType[i] = new Array(16);
PieceMoveCounter[i] = new Array(16);
HistType[i] = new Array(MaxMove);
HistPieceId[i] = new Array(MaxMove);
}
for(i=0; i<3; ++i){
HistCol[i] = new Array(MaxMove);
HistRow[i] = new Array(MaxMove);
}
HistEnPassant = new Array(MaxMove);
HistEnPassant[0] = false;
HistEnPassantCol = new Array(MaxMove);
HistEnPassantCol[0] = -1;
var FenPieceName = "KQRBNP";
var PieceCode = new Array(); // IE needs an array to work with [index]
for (i=0; i<6; i++) { PieceCode[i] = FenPieceName.charAt(i); }
var FenStringStart = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1";
var columnsLetters = "ABCDEFGH";
startingSquareSize = -1;
startingImageSize = -1;
PiecePicture = new Array(2);
for(i=0; i<2; ++i) { PiecePicture[i] = new Array(6); }
var ImagePath = '';
var ImagePathOld = null;
var imageType = 'png';
var defaultImagesSize = 40;
var highlightOption = true;
var commentsIntoMoveText = true;
var commentsOnSeparateLines = false;
var pgnUrl = '';
CastlingLong = new Array(2);
CastlingShort = new Array(2);
Moves = new Array(MaxMove);
MoveComments = new Array(MaxMove);
var MoveColor;
var MoveCount;
var PlyNumber;
var StartPly;
var CurrentPly;
var IsRotated = false;
var pgnHeaderTagRegExp = /\[\s*(\w+)\s*"([^"]*)"\s*\]/;
var pgnHeaderTagRegExpGlobal = /\[\s*(\w+)\s*"([^"]*)"\s*\]/g;
var dummyPgnHeader = '[x""]';
var emptyPgnHeader = '[Event ""]\n[Site ""]\n[Date ""]\n[Round ""]\n[White ""]\n[Black ""]\n[Result ""]\n\n';
var templatePgnHeader = '[Event "?"]\n[Site "?"]\n[Date "?"]\n[Round "?"]\n[White "?"]\n[Black "?"]\n[Result "?"]\n';
var alertPgnHeader = '[Event ""]\n[Site ""]\n[Date ""]\n[Round ""]\n[White ""]\n[Black ""]\n[Result ""]\n\n{error: click on the top left chessboard square for debug info}';
var gameSelectorHead = ' ...';
var gameSelectorMono = true;
var gameSelectorNum = false;
var gameSelectorNumLenght = 0;
var gameSelectorChEvent = 0;
var gameSelectorChSite = 0;
var gameSelectorChRound = 0;
var gameSelectorChWhite = 15;
var gameSelectorChBlack = 15;
var gameSelectorChResult = 0;
var gameSelectorChDate = 10;
function CheckLegality(what, plyCount) {
var retVal;
var start;
var end;
var isCheck;
// castling move?
if (what == 'O-O') {
if (!CheckLegalityOO()) { return false; }
start = PieceCol[MoveColor][0];
end = 6;
while (start < end) {
isCheck = IsCheck(start, MoveColor*7, MoveColor);
if (isCheck) { return false; }
++start;
}
StoreMove(plyCount);
return true;
} else if (what == 'O-O-O') {
if (!CheckLegalityOOO()) { return false; }