-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
2119 lines (1952 loc) · 90.6 KB
/
Copy pathapp.js
File metadata and controls
2119 lines (1952 loc) · 90.6 KB
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
// to create documentation execute: jsdoc -r .\ -d .\Documentation
/**
* This module
* - handles the communication with the server
* - updates the GUI elements when necessary
* - handles events of the GUI elements
*/
// call the initialization function after the web page has been loaded
document.addEventListener('DOMContentLoaded', function(event) {
initialize();
} );
var itemUUID_atURL = "";
var GMT_of_last_fetched_Data = ""; // Remembers when the data was fetched. Works in cooperation with a thread-function which checks periodically for new data. Format: "Y-m-d H:i:s". Example: "2023-10-25 11:03:42"
var FetchNewData_Interval_seconds = 120; //
var FetchNewData_IntrevalID = null; // this is the interval id of the thread-function
var theFetchedNewData = null; // stores the latest new data in json format
var AvailableTrenchesCombo;
var TheMainProgressBar;
/**
* This is the first function called upon website loading.
* It initializes various objects, properties, event listeners and fetches data from the server
*/
function initialize() {
//
/*
$(document).ready(function() {
$('.js-example-basic-multiple').select2();
});
*/
// init several properties
AvailableTrenchesCombo = document.getElementById("AvailableTrenchesCombo");
AvailablePlansCombo = document.getElementById("AvailablePlansCombo");
TheMainProgressBar = document.getElementById("MainProgressBar");
if( Utils.Am_I_running_on_mobile_device() ) {
AvailableTrenchesCombo.style.minWidth = "120px";
AvailableTrenchesCombo.style.maxWidth = "120px";
AvailablePlansCombo.style.minWidth = "120px";
AvailablePlansCombo.style.maxWidth = "120px";
document.getElementsByClassName("multiselect-dropdown")[0].style.border = "solid 3px red";
document.getElementsByClassName("multiselect-dropdown")[0].style.backgroundColor = "purple";
}
// init objects
map = new Map( "canvas" );
// read url parameters if any - useful for directly accessing an item
var url_object = new URL( window.location.href );
itemUUID_atURL = url_object.searchParams.get("id");
if( itemUUID_atURL == null ) itemUUID_atURL = "";
itemCategoriesCombo = document.getElementById("itemCategoriesCombo");
itemCategoriesPanel = document.getElementById("itemCategoriesPanel");
itemsList_ul = document.getElementById("itemsList_ul");
// add event listeners for item handling
document.getElementById("itemsList_ul").addEventListener('click',this.ItemList_ClickHandler,false);
document.getElementById("itemCategoriesCombo").addEventListener('change',this.itemCategoriesCombo_ChangeHandler,false);
document.getElementById("itemCategoriesPanel").addEventListener('change',this.itemCategoriesPanel_ChangeHandler,false);
document.getElementById("itemsSearchText").addEventListener('keyup',this.itemsSearchText_KeypressHandler,false);
// add event listeners for combos
AvailableTrenchesCombo.addEventListener('change',this.AvailableTrenchesCombo_ChangeHandler,false);
AvailablePlansCombo.addEventListener('change',this.AvailablePlansCombo_ChangeHandler,false);
// add event listeners for buttons
document.getElementById("item_search_button").addEventListener('click',this.ItemSearchButton_ClickHandler,false);
document.getElementById("InfoBar").addEventListener('click',this.InfoBar_ClickHandler,false);
document.getElementById("ToggleCategoriesPanelButton").addEventListener('click',this.ToggleCategoriesPanelButton_ClickHandler,false);
// add event listeners for window
window.addEventListener("resize", this.WindowResizeHandler );
//////// Fetch uername ////////
$.ajax({
url: phpURL,
type: "POST",
data: { Command: "WhoAmI" },
timeout: 22000,
error: function(xmlhttprequest, textstatus, message) {
alert("Error during username retrieval. Please check your network connection. ("+textstatus+" "+message+")");
}
}).done(function( msg ) {
TheUsername = msg;
TheUsername = TheUsername.replaceAll(" ", "");
TheUsername = TheUsername.replaceAll("\n", "");
TheUsername = TheUsername.replaceAll("\t", "");
if( msg.length > 0 ) {
document.getElementById("user_info_name").textContent = TheUsername;
} else {
document.getElementById("user_info_name").textContent = "Guest";
}
// init the system which informs when there are new data to be fetched from the server
if(TheUsername.length==0 || TheUsername.toLowerCase().localeCompare("guest")==0) {
document.getElementById("new_data_button_img").style.visibility = "hidden";
} else {
FetchNewData_IntrevalID = setInterval(Fetch_NewData_for_currentTrench, FetchNewData_Interval_seconds*1000);
}
// provide administrative menus to the admin user
if( TheUsername.toLowerCase().localeCompare("admin") == 0 ) {
alert("Please change the admin's password in case you have not done so yet, for security reasons.\nAdminisrative functionality can be found by clicking at the user name at the top right.");
} else {
document.getElementById("usermenu_adduser").remove();
document.getElementById("usermenu_userrights").remove();
document.getElementById("usermenu_importdata").remove();
document.getElementById("usermenu_importimages").remove();
}
});
//////// Fetch AccessLevels ////////
$.ajax({
url: phpURL,
type: "POST",
data: { Command: "GetAccessLevels" },
timeout: 22000,
error: function(xmlhttprequest, textstatus, message) {
alert("Error during access rights retrieval. Please check your network connection. ("+textstatus+" "+message+")");
}
}).done(function( msg ) {
TheAccessLevels = msg.trim();
// remove spaces and add commas at the beginning and end of the string if necessary
if( TheAccessLevels.length > 0 ) {
TheAccessLevels = TheAccessLevels.replaceAll( ' ', '' );
TheAccessLevels = TheAccessLevels.replaceAll( '\t', '' );
TheAccessLevels = TheAccessLevels.replaceAll( '\n', '' );
if( TheAccessLevels.charAt(0) != ',' ) TheAccessLevels = "," + TheAccessLevels;
if( TheAccessLevels.charAt(TheAccessLevels.length-1) != ',' ) TheAccessLevels = TheAccessLevels + ",";
}
// hide unautorized GUI elements
if( TheAccessLevels.toLowerCase().includes(",all,") == false ) {
const collection = document.getElementsByClassName("visible-to-admin-only");
for (let i = 0; i < collection.length; i++) {
collection[i].style.display = "None";
}
}
if( TheAccessLevels.length <= 2 ) {
const collection = document.getElementsByClassName("visible-to-users-only");
for (let i = 0; i < collection.length; i++) {
collection[i].style.display = "None";
}
}
// hide coordinate-related buttons for non authorized users
if( TheAccessLevels.toLowerCase().indexOf(",admin,")<0 && TheAccessLevels.toLowerCase().indexOf(",coordinates,")<0) {
document.getElementById("layers_button").style.display = "None";
document.getElementById("alter_a_coordinate_button").style.display = "None";
}
});
//////// Fetch the ReferenceLinks ////////
var Compress = true;
$.ajax({
url: phpURL,
type: "POST",
data: { Command: "GetReferenceLinks", Arg1: Compress.toString() },
timeout: 22000,
error: function(xmlhttprequest, textstatus, message) {
alert("Error during reference links retrieval. Please check your network connection. ("+textstatus+" "+message+")");
}
}).done(function( msg ) {
if( Compress ) {
var strData = atob(msg);
var charData = strData.split('').map(function(x){return x.charCodeAt(0);}); // Convert binary string to character-number array
var binData = new Uint8Array(charData); // Turn number array into byte-array
var data = pako.inflate(binData); // uncompress using pako
var strData = new TextDecoder("utf-8").decode(data); // Convert gunzipped byteArray back to ascii string: //THIS WORKS FOR SMALL STRINGS: var strData = String.fromCharCode.apply(null, new Uint16Array(data));
ReferenceLinks = JSON.parse(strData);
} else {
ReferenceLinks = JSON.parse(msg);
}
});
///////////////////////
get_Excavation_Data_and_Preferences();
///////////////////////
// initialize selection for canvas items
map.activate_Select();
// hide the Define-Coordinates-Manually button. This becomes visible when the user wants to define coordinates from within the ItemInfoDialog. This is for users having access to "All".
document.getElementById("target_button").style.display = "None";
// check periodically if the session is alive in order to inform the user
setInterval(Check_if_Session_is_Alive, 350*1000);
}
/**
* Fetches the excavation's json data from the server
*/
function GetExcavationData() {
document.getElementById("masterContainer").style.cursor = "wait";
var Compress = true;
//////////////////////////// send request to server for data about this trench
$.ajax({
url: phpURL,
type: "POST",
data: { Command: "GetExcavationData", Arg1: Compress.toString() },
xhr: function () {
document.getElementById("MainProgressBar_msg").innerHTML = "Loading. Please wait. Downloading data";
var xhr = new window.XMLHttpRequest();
xhr.addEventListener("progress", function(evt){
if (evt.lengthComputable) {
TheMainProgressBar.style.width = (50 * evt.loaded / evt.total) + "%";
}
}, false);
return xhr;
},
timeout: 62000,
error: function(xmlhttprequest, textstatus, message) {
document.getElementById("canvas").style.cursor = "default";
document.getElementById("masterContainer").style.cursor = "default";
alert("Error during Trench Data retrieval. Please check your network connection. ("+textstatus+" "+message+")");
}
}).done(function( msg ) {
if( msg.length > 10 ) {
// remember when the data is fetched and start checking for new data periodically
GMT_of_last_fetched_Data = Utils.get_GMT_datetime();
// Parse json data from server
if( Compress ) {
var strData = atob(msg);
var charData = strData.split('').map(function(x){return x.charCodeAt(0);}); // Convert binary string to character-number array
var binData = new Uint8Array(charData); // Turn number array into byte-array
var data = pako.inflate(binData); // uncompress using pako
var strData = new TextDecoder("utf-8").decode(data); // Convert gunzipped byteArray back to ascii string: //THIS WORKS FOR SMALL STRINGS: var strData = String.fromCharCode.apply(null, new Uint16Array(data));
ExcData = JSON.parse(strData); // parse json data
} else {
ExcData = JSON.parse(msg); // parse json data
}
if( ExcData.length == 0 ) {
if( TheUsername.localeCompare("admin") == 0 ) {
alert("Welcome to WebDig.\nYou can import data into the application by clicking on your username at the top right.");
} else {
alert("Welcome to WebDig.\nYou have to log in as 'admin' in order to import data into the application.");
}
}
// check and process data - this delays a lot
//var ErrorMsgs = check_TrenchData_forErrors( ExcData );
//if( ErrorMsgs.length > 0 ) alert( "Errors found in Data:\n\n" + ErrorMsgs );
// Process the data in a thread, so that you can refresh the progress bar
document.getElementById("MainProgressBar_msg").innerHTML = "Loading. Please wait. Processing data";
processExcavationData(); // process trench data
var CheckProcessingCompletion_Interval_id = setInterval(CheckProcessingCompletion, 600);
function CheckProcessingCompletion() {
if( I == ExcData.length ) {
clearInterval( CheckProcessingCompletion_Interval_id );
} else {
TheMainProgressBar.style.width = (50 + 50 * I / ExcData.length) + "%";
return;
}
// populate Trench-names list
for( let i=0; i<list_of_all_Trenches.length; i++ ) {
var option = document.createElement('option');
option.value = list_of_all_Trenches[i];
option.innerHTML = list_of_all_Trenches[i];
AvailableTrenchesCombo.appendChild(option);
}
AvailableTrenchesCombo.loadOptions(); // refreshes the multi-select
// automatically display the dialog with item information, if requested to do so (by the user at the url - for citation links).
if( itemUUID_atURL.length > 0 ) {
// set the item's trench as the current one
itemUUID_atURL = "";
var ItemData = getDataBy_UUID( UUID );
if( ItemData.hasOwnProperty("Trench") && ItemData["Trench"].length > 0 ) {
set_current_Trenches( [ItemData["Trench"]] );
}
// set the plan associated with the item's trench as the current one
PopulatePlansList();
item_trenches = ItemData["Trench"].split("\n");;
for( let idx=0; idx<item_trenches.length; idx++ ) {
if( TrenchPlanRelations.hasOwnProperty( item_trenches[idx] ) ) {
AvailablePlansCombo.value = TrenchPlanRelations[item_trenches[idx]][0];
break;
}
}
} else {
// set the default trench (as stored into preferences) as the current one
if( ExcavationPreferences.hasOwnProperty("DefaultTrench") ) {
if( ExcavationPreferences["DefaultTrench"].toLowerCase() === "all" ) {
set_current_Trenches( list_of_all_Trenches );
} else {
set_current_Trenches( [ExcavationPreferences["DefaultTrench"]] );
}
}
// set the default plan (as stored into preferences) as the current one
PopulatePlansList();
if( ExcavationPreferences.hasOwnProperty("DefaultPlan") && ExcavationPreferences["DefaultPlan"].length>0) {
AvailablePlansCombo.value = ExcavationPreferences["DefaultPlan"];
}
}
// resolve the maximum layer depth in order to set the maximum at the select-layer which is displayed when the alter_a_coordinate_button is clicked
var current_num_of_Layers;
for (let idx = 0; idx < ExcData.length; idx++) {
if( ExcData[idx].hasOwnProperty("Location") ) {
current_num_of_Layers = ExcData[idx]["Location"].length;
if( current_num_of_Layers > Max_num_of_Layers ) Max_num_of_Layers = current_num_of_Layers;
}
}
document.getElementById("Layers_slider").max = Max_num_of_Layers;
document.getElementById('Layers_rangeValue').textContent = 0;
document.getElementById('Layers_slider').value = 0;
// display data to user
PopulateCategoriesCombo(); // fill a combobox with all available item categories
if( ExcavationPreferences.hasOwnProperty("ItemsList_SortByFields") && ExcavationPreferences["ItemsList_SortByFields"].length > 0 ) {
sortExcavationData( ExcavationPreferences["ItemsList_SortByFields"] );
console.log("Sorting by " + ExcavationPreferences["ItemsList_SortByFields"][0] + " " +ExcavationPreferences["ItemsList_SortByFields"][1] + " " +ExcavationPreferences["ItemsList_SortByFields"][2] );
}
PopulateItemsList(ExcData, "", ""); // fill a list with all the available items
num_of_selected_items = 0;
updateInfoBar();
updateSelectedItemsOnList();
document.getElementById("itemsList_ul").scrollTop = 0;
map.drawWorld();
// automatically display the dialog with item information, if requested to do so (by the user at the url - for citation links).
if( itemUUID_atURL.length > 0 ) {
Dialog.showItemDataDialog( itemUUID_atURL );
}
// display permissions-of-usage warning to guest users
if( TheUsername.length==0 || TheUsername.toLowerCase().includes("guest") ) { // display permissions-of-usage warning to guest users
if( ExcavationPreferences.hasOwnProperty("Permissions_html") && ExcavationPreferences["Permissions_html"].length>0) {
Dialog.Display_Permissions_Dialog();
}
}
// dismiss the progress bar
document.getElementById("MainProgressBarWindow").style.display = 'none';
}
} else {
alert("Failed to download the excavation data.\nPlease check your Internet connection.");
}
document.getElementById("canvas").style.cursor = "default";
document.getElementById("masterContainer").style.cursor = "default";
map.drawWorld();
});
}
/**
* Fetches the excavation's preferences json file from the server
*/
function get_Excavation_Data_and_Preferences() {
var Compress = true;
//////////////////////////// send request to server for the preferences file
$.ajax({
url: phpURL,
type: "POST",
data: { Command: "GetPreferences", Arg1: Compress.toString() },
timeout: 25000,
error: function(xmlhttprequest, textstatus, message) {
alert("Error during Preferences retrieval. Please check your network connection. ("+textstatus+" "+message+")");
}
}).done(function( msg ) {
if( msg.length > 10 ) {
// Parse json data from server
if( Compress ) {
var strData = atob(msg);
var charData = strData.split('').map(function(x){return x.charCodeAt(0);}); // Convert binary string to character-number array
var binData = new Uint8Array(charData); // Turn number array into byte-array
var data = pako.inflate(binData); // uncompress using pako
var strData = new TextDecoder("utf-8").decode(data); // Convert gunzipped byteArray back to ascii string: //THIS WORKS FOR SMALL STRINGS: var strData = String.fromCharCode.apply(null, new Uint16Array(data));
ExcavationPreferences = JSON.parse(strData); // parse json data
} else {
ExcavationPreferences = JSON.parse(msg); // parse json data
}
// fill in the application's data structures (they are initiated in data.js)
if( ExcavationPreferences.hasOwnProperty("fields") ) {
FieldDefinitions = ExcavationPreferences["fields"];
} else {
FieldDefinitions = [];
}
if( ExcavationPreferences.hasOwnProperty("EditableItemFields") ) {
for(var i=0; i<ExcavationPreferences["EditableItemFields"].length; i++) {
var a_Type = ExcavationPreferences["EditableItemFields"][i]["Type"];
if( ! EditableItemFields.includes(a_Type) ) EditableItemFields.push( a_Type );
EditableItemFields[ a_Type ] = ExcavationPreferences["EditableItemFields"][i]["FieldNames"];
}
}
if( ExcavationPreferences.hasOwnProperty("VisibleItemFields") ) {
for(var i=0; i<ExcavationPreferences["VisibleItemFields"].length; i++) {
var a_Type = ExcavationPreferences["VisibleItemFields"][i]["Type"];
if( ! VisibleItemFields.includes(a_Type) ) VisibleItemFields.push( a_Type );
VisibleItemFields[ a_Type ] = ExcavationPreferences["VisibleItemFields"][i]["FieldNames"];
}
}
if( ExcavationPreferences.hasOwnProperty("Colors") ) {
COLORS = Utils.convert_JSON_keys_to_lowercase( ExcavationPreferences["Colors"] );
if( COLORS.hasOwnProperty("selected") ) COLOR_selected = COLORS["selected"];
if( COLORS.hasOwnProperty("focused") ) COLOR_focused = COLORS["focused"];
if( COLORS.hasOwnProperty("various") ) COLOR_various = COLORS["various"];
if( COLORS.hasOwnProperty("highlight") ) COLOR_highlight = COLORS["highlight"];
if( COLORS.hasOwnProperty("crosssection") ) COLOR_crosssection = COLORS["crosssection"];
if( COLORS.hasOwnProperty("distances") ) COLOR_distances = COLORS["distances"];
if( COLORS.hasOwnProperty("artifact") ) COLOR_artifact = COLORS["artifact"];
if( COLORS.hasOwnProperty("locus") ) COLOR_locus = COLORS["locus"];
if( COLORS.hasOwnProperty("feature") ) COLOR_feature = COLORS["feature"];
if( COLORS.hasOwnProperty("partition") ) COLOR_partition = COLORS["partition"];
}
////////////////////////////////////////////
GetExcavationData();
////////////////////////////////////////////
} else {
alert("Unable to download the Preferences file.");
}
});
}
/**
* Makes certain trenches the current ones. This affects the trenches combobox and the items-list
* @param some_trench_names an array containing some trench names
*/
function set_current_Trenches( some_trench_names ) {
// alter state
currentTrenchNames = some_trench_names;
// alter GUI
var options = AvailableTrenchesCombo.options;
for (let i = 0; i < options.length; i++) {
if (some_trench_names.includes(options[i].text) ) {
options[i].selected = true;
}
}
AvailableTrenchesCombo.loadOptions();
}
/**
* THREAD FUNCTION
* This function is enabled only for registered users. It ensures data consistency.
* Asks the server if there are any new data for the current trench. The server replies by sending the new data in json format.
* If the reply is not empty a warning is displayed to the user. When user clicks on the warning the new data will be used.
* This is a thread-function which is called every several seconds.
*/
function Fetch_NewData_for_currentTrench() {
console.log("Fetching new data. (after " + FetchNewData_Interval_seconds + " sec)" );
if(TheUsername.length==0 || TheUsername.toLowerCase().localeCompare("guest")==0) {
document.getElementById("new_data_button_img").style.visibility = "hidden";
return;
}
document.getElementById("new_data_button_img").style.cursor = "wait";
$.ajax({
url: phpURL,
type: "POST",
data: { Command: "GiveMeAnyNewData", Arg1: GMT_of_last_fetched_Data },
timeout: 25000,
error: function(xmlhttprequest, textstatus, message) {
document.getElementById("new_data_button_img").style.cursor = "pointer";
console.log("Error during new data check. Please check your network connection. ("+textstatus+" "+message+")");
}
}).done(function( msg ) {
msg = msg.trim(); //msg = '[{"Identifier":"AAA111","Title":"tester","Description":"Just testing"}]';
GMT_of_last_fetched_Data = Utils.get_GMT_datetime();
if( msg.length > 20 && msg.startsWith('[') ) {
if(theFetchedNewData == null) {
theFetchedNewData = JSON.parse(msg);
} else { // there are previously fetched data which were not processed yet. So, merge them
var NEWdata = JSON.parse(msg);
for(let i=0; i<NEWdata.length; i++) { // for each new data item
// check if the item already exists in theFetchedNewData
var idx = -1;
for(let j=0; j<theFetchedNewData.length; j++) {
if( NEWdata[i]["IdentifierUUID"].localeCompare( theFetchedNewData[j]["IdentifierUUID"] ) == 0 ) {
idx = j;
break;
}
}
//
if( idx >= 0 ) { // the item data was already fetched before
theFetchedNewData[idx] = NEWdata[i];
} else { // the item data is brand new
theFetchedNewData.push( NEWdata[i] );
}
}
}
// update GUI
document.getElementById("new_data_button_img").src = "images/system/new_data_exclamation.png";
document.getElementById("new_data_button_img").title = "There are new data! Click on me if you want to load them.";
} else { // the reply contains the number of active users (that is those who have logged in recently)
try {
if( Utils.ContainsInteger(msg) ) { // change interval depending on how many users are logged in the system
var num_of_active_users = parseInt(msg);
if(num_of_active_users > 1 && FetchNewData_Interval_seconds != 120) { // count one's self as well
FetchNewData_Interval_seconds = 120; // increase interval
clearInterval( FetchNewData_IntrevalID );
FetchNewData_IntrevalID = setInterval(Fetch_NewData_for_currentTrench, FetchNewData_Interval_seconds*1000);
} else if(num_of_active_users <= 1 && FetchNewData_Interval_seconds != 400) {
FetchNewData_Interval_seconds = 400; // increase interval
clearInterval( FetchNewData_IntrevalID );
FetchNewData_IntrevalID = setInterval(Fetch_NewData_for_currentTrench, FetchNewData_Interval_seconds*1000);
}
}
} catch (ex) {console.log(ex);}
}
document.getElementById("new_data_button_img").style.cursor = "pointer";
});
}
/**
* This function is called when new data have been fetched and the user has pressed the NewData-notification button.
* The data is incorporated into the local json database and the data structures are updated.
*/
function Load_theFetchedNewData() {
var item_identifiers_of_FetchedNewData = "";
if(theFetchedNewData != null) {
for(let i=0; i<theFetchedNewData.length; i++) { // for each FetchedNewData element
var ExistingItemDataIDX = getIndexBy_UUID( theFetchedNewData[i]["IdentifierUUID"] );
if( ExistingItemDataIDX < 0 ) {// this FetchedNewData element describes a newly created item
ExcData.push( theFetchedNewData[i] );
} else { // this FetchedNewData element has the data of an existing altered item
var is_it_visible = ExcData[ExistingItemDataIDX]["Visible"];
var is_it_selected = ExcData[ExistingItemDataIDX]["Selected"];
ExcData[ExistingItemDataIDX] = JSON.parse(JSON.stringify( theFetchedNewData[i] )); // clone
ExcData[ExistingItemDataIDX]["Visible"] = is_it_visible;
ExcData[ExistingItemDataIDX]["Selected"] = is_it_selected;
}
// constuct info for user
if(i>0) item_identifiers_of_FetchedNewData += ", ";
item_identifiers_of_FetchedNewData += theFetchedNewData[i]["Identifier"];
}
// process the new data
var ErrorMsgs = check_TrenchData_forErrors( ExcData );
if( ErrorMsgs.length > 0 ) alert( "Errors found in Data:\n\n" + ErrorMsgs );
QUICK_processExcavationData(); // process trench data
//Update the List of items
for(let i=0; i<theFetchedNewData.length; i++) {
try { // maybe the item is not in the list at that moment
document.getElementById( "LIbottom~"+theFetchedNewData[i]["IdentifierUUID"] ).innerHTML = theFetchedNewData[i]["Type"] + " - " + theFetchedNewData[i]["Title"];
} catch(ex) {}
}
// update GUI and state
PopulateCategoriesCombo();
PopulatePlansList();
updateInfoBar();
document.getElementById("new_data_button_img").src = "images/system/new_data_tick.png";
document.getElementById("new_data_button_img").title = "Click on me to check if there are new data. I also check by myself periodically and become red when there are new data.";
theFetchedNewData = null;
}
return item_identifiers_of_FetchedNewData;
}
/**
* This function is called when the user presses the NewData-notification button.
* If new data have been fetched then they are going to be processed, if not then the server will be asked
*/
function new_data_button_clicked() {
if(theFetchedNewData == null) {
// reset interval
try{ clearInterval( FetchNewData_IntrevalID ); } catch(Ex) {}
FetchNewData_IntrevalID = setInterval(Fetch_NewData_for_currentTrench, FetchNewData_Interval_seconds*1000);
// contact server
Fetch_NewData_for_currentTrench();
} else {
var item_identifiers_of_FetchedNewData = Load_theFetchedNewData();
alert( "Data of the following items have been updated:\n" + item_identifiers_of_FetchedNewData );
}
}
/**
* THREAD FUNCTION
* Called periodically in order to inform user if the sessions has timed-out.
*/
function Check_if_Session_is_Alive() {
$.ajax({
url: phpURL,
type: "POST",
data: { Command: "WhoAmI" },
timeout: 22000,
error: function(xmlhttprequest, textstatus, message) {
console.log("Error during session status check. Please check your network connection. ("+textstatus+" "+message+")");
}
}).done(function( msg ) {
TheUsername = msg;
TheUsername = TheUsername.replaceAll(" ", "");
TheUsername = TheUsername.replaceAll("\n", "");
TheUsername = TheUsername.replaceAll("\t", "");
if( msg.length > 0 ) {
document.getElementById("user_info_name").textContent = TheUsername;
} else {
document.getElementById("user_info_name").textContent = "Guest";
}
});
}
/**
* Called when the user clicks on the add-new-item option of the 3-dots menu.
* It checks the user permissions and if they are ok the new-item-dialog is displayed, which allows the user to create a new item with some basic info.
* Afterwards the item-info-dialog the new item will be automatically displayed for the user to enter the rest of the information.
*/
function AddNewItem() {
// Check for Access Permissions
var AccessGranted = false;
if( TheAccessLevels.toLowerCase().indexOf(",all,") >= 0 ) AccessGranted = true;
if( TheAccessLevels.toLowerCase().indexOf(",addnew,") >= 0 ) AccessGranted = true;
if( AccessGranted == false ) {
alert("You do not have access to add a new item to the system.");
} else {
Dialog.show_NewItem_Dialog();
}
}
/**
* Uploads a photo to the server. The server will create a data record for the photo and link with the item whose IdentifierUUID given as argument
* @param UUID IdentifierUUID of the item to which the photo will be linked to
*/
async function uploadPhoto( UUID ) {
document.getElementById("itemInfoDialog").style.cursor = "wait";
var formData = new FormData();
formData.append("file", photo_upload.files[0]);
formData.append( "Command", "UploadPhoto");
formData.append( "Arg1", UUID );
$.ajax({
url: phpURL,
type: "POST",
contentType: false,
processData: false,
cache: false,
data: formData,
timeout: 180000,
error: function(xmlhttprequest, textstatus, message) {
document.getElementById("itemInfoDialog").style.cursor = "default";
alert("Error during photo upload. Please check your network connection. ("+textstatus+" "+message+")");
}
}).done(function( msg ) {
if( msg.indexOf("Error") < 0 ) {
// ask for the data of the altered item, because it contains server-created information
$.ajax({ url:phpURL, type:"POST", data:{Command:"GetItemData", Arg1:UUID, timeout:22000}
}).done(function( msg2 ) {
// update local copy of the database
itemData = JSON.parse(msg2);
for (let i = 0; i < ExcData.length; i++) {
if( ExcData[i]["IdentifierUUID"].localeCompare( UUID ) == 0 ) {
ExcData[i] = itemData;
break;
}
}
// retreive the UUID of the new photo
var NewPhotoUUID = itemData["RelationIncludesUUID"][0];
if(NewPhotoUUID.indexOf("\n") >= 0) NewPhotoUUID = NewPhotoUUID.substr( NewPhotoUUID.lastIndexOf("\n") + 1 );
NewPhotoUUID = NewPhotoUUID.trim();
// ask for the photograph item
$.ajax({ url:phpURL, type:"POST", data:{Command:"GetItemData", Arg1:NewPhotoUUID, timeout:22000}
}).done(function( msg3 ) {
// update local copy of the database
photoData = JSON.parse(msg3);
ExcData.push( photoData );
QUICK_processExcavationData();
updateInfoBar();
// inform user
Dialog.showItemDataDialog( UUID );
document.getElementById("itemInfoDialog").style.cursor = "default";
alert("The image was uploaded successfuly and linked to item '" + itemData["Identifier"] + "'.");
});
});
} else {
document.getElementById("itemInfoDialog").style.cursor = "default";
alert(msg);
}
});
}
/**
* Exports the data of the selected items in a csv file.
*/
function ExportData_CSV() {
if( ExcData == null ) {
alert( "The Excavation Data has not been loaded yet." );
return;
}
delimeter = "\t";
var FieldsToIgnore = ["Selected", "Visible", "Location", "Type", "DateUTC", "Format", "RelationIncludes", "RelationIncludesUUID", "RelationBelongsToUUID", "RelationIsAboveUUID", "RelationIsBelowUUID", "ThumbnailImageUUID", "RelationIsCoevalWithUUID", "RelationCutsUUID", "RelationIsCutByUUID", "RelationIsNextToUUID", "RelationIsBeforeUUID", "RelationIsAfterUUID"];
var csvHeaders = ["IdentifierUUID", "Identifier", "Title", "Type"];
var fileContent = "";
var num_of_exported_items = 0;
// construct csv file header
for( let i=0; i<ExcData.length; i++ ) {
if( ExcData[i]["Selected"] || num_of_selected_items==0 ) {
num_of_exported_items += 1;
var keys = Object.keys( ExcData[i] );
// add the field name to the header if it is new and it is not an app-specific field
for(j=0; j<keys.length; j++) {
if( csvHeaders.includes(keys[j])==false && FieldsToIgnore.includes(keys[j])==false ) {
csvHeaders.push( keys[j] );
}
}
}
}
// write header to file
for( let i=0; i<csvHeaders.length; i++ ) {
if( i > 0 ) fileContent += delimeter;
fileContent += csvHeaders[i];
}
fileContent += "\n";
// construct csv file contents
for( let i=0; i<ExcData.length; i++ ) {
if( ExcData[i]["Selected"] || num_of_selected_items==0 ) {
for(j=0; j<csvHeaders.length; j++) {
if( j > 0 ) fileContent += delimeter;
if(typeof ExcData[i][csvHeaders[j]] != "undefined") {
var csv_field = ExcData[i][csvHeaders[j]].toString();
csv_field = csv_field.replaceAll("\t", " ");
csv_field = csv_field.replaceAll("\n", " ");
csv_field = csv_field.replaceAll("\r", " ");
fileContent += csv_field;
}
}
fileContent += "\n";
}
}
// zip the csv file
var compressed_fileContent = pako.gzip(fileContent, {to: 'string'});
// construct the filename
const DateObj = new Date();
if( num_of_exported_items==0 ) {
var filename = DateObj.toLocaleString('default',{month:'long'}) + " " + DateObj.getDate() + " " + DateObj.getFullYear() + ", " + "all" + " items.csv.zip";
} else {
var filename = DateObj.toLocaleString('default',{month:'long'}) + " " + DateObj.getDate() + " " + DateObj.getFullYear() + ", " + num_of_exported_items + " items.csv.zip";
}
// let user download the file
var aBlob = new Blob([compressed_fileContent], { type: 'octet/stream' });
var tmp = document.createElement('a');
tmp.download = filename;
tmp.href = window.URL.createObjectURL(aBlob);
tmp.click();
window.URL.revokeObjectURL(tmp);
alert( "Data of " + num_of_exported_items + " items was exported in tab-delimited CSV format inside a compressed ZIP file. Please check your browser's Downloads." );
}
/**
* Commands the server to create a word document containing one page for each item with photos and information about that item.
* When the server is done, the function downloads the document from the server.
*/
function ExportData_MSWORD() {
if( ExcData == null ) {
alert( "The Excavation Data has not been loaded yet." );
return;
}
// construct the string with all selected item UUIDs
var SelectedUUIDs = "";
if( num_of_selected_items > 0 ) {
SelectedUUIDs = ",";
for (let i=0; i < ExcData.length; i++) {
if( ExcData[i]["Selected"] ) {
SelectedUUIDs += ExcData[i]["IdentifierUUID"] + ",";
}
}
}
var currentUnixTime = Math.floor( (new Date()).getTime() / 1000 );
// send request to server
$.ajax({
url: phpURL,
type: "POST",
data: { Command: "ExportMSWord", Arg1: SelectedUUIDs, Arg2: currentUnixTime},
timeout: 65000,
error: function(xmlhttprequest, textstatus, message) {
alert("Error during export. Please check your network connection. ("+textstatus+" "+message+")");
}
}).done(function( msg ) {
msg = msg.trim();
if( msg.length == 0 || msg.length > 0 ) { // the data has been exported. Download the file
DateObj = new Date();
if( num_of_selected_items==0 ) {
var localfilename = DateObj.toLocaleString('default',{month:'long'}) + " " + DateObj.getDate() + " " + DateObj.getFullYear() + ", " + "all" + " items.docx";
} else {
var localfilename = DateObj.toLocaleString('default',{month:'long'}) + " " + DateObj.getDate() + " " + DateObj.getFullYear() + ", " + num_of_selected_items + " items.docx";
}
var tmp_link = document.createElement('a');
console.log( localfilename + " * " + currentUnixTime + '.docx' );
tmp_link.setAttribute('href', ServerURL + "tmp_files/" + currentUnixTime + '.docx');
tmp_link.setAttribute('download', localfilename);
tmp_link.style.display = 'none';
document.body.appendChild(tmp_link);
tmp_link.click();
document.body.removeChild(tmp_link);
}
});
}
/**
* Requests the data-changes file from the server and calls the corresponding dialog to display them.
*/
function getDataChanges_and_DisplayThem() {
document.getElementById("masterContainer").style.cursor = "wait";
var Compress = true;
////////////////////////////send request to server for the preferences file
$.ajax({
url: phpURL,
type: "POST",
data: { Command: "GetDataChanges", Arg1: Compress.toString() },
timeout: 22000,
error: function(xmlhttprequest, textstatus, message) {
document.getElementById("masterContainer").style.cursor = "default";
alert("Error during data change retrieval. Please check your network connection. ("+textstatus+" "+message+")");
}
}).done(function( msg ) {
if( msg.length > 10 ) {
if( Compress ) {
var strData = atob(msg);
var charData = strData.split('').map(function(x){return x.charCodeAt(0);}); // Convert binary string to character-number array
var binData = new Uint8Array(charData); // Turn number array into byte-array
var data = pako.inflate(binData); // uncompress using pako
var strData = new TextDecoder("utf-8").decode(data); // Convert gunzipped byteArray back to ascii string: //THIS WORKS FOR SMALL STRINGS: var strData = String.fromCharCode.apply(null, new Uint16Array(data));
Dialog.Display_TrackChanges_Dialog(strData);
} else {
Dialog.Display_TrackChanges_Dialog(msg);
}
} else {
Dialog.Display_TrackChanges_Dialog(msg);
}
document.getElementById("masterContainer").style.cursor = "default";
});
}
/**
* captures a large size image of the whole map, even the non visible area.
*/
function CaptureMap( DotSize, ColorBrightness, RectangleOpacity, AllItemsColor ) {
// remember current canvas state
var Map_Canvas = document.getElementById("canvas");
var original_ZoomFactor = ZoomFactor;
var original_CanvasOffsetX = CanvasOffsetX;
var original_CanvasOffsetY = CanvasOffsetY;
var original_CanvasWidth = Map_Canvas.width;
var original_CanvasHeight = Map_Canvas.height;
// instruct canvas to display the full-size map
ZoomFactor = 1;
CanvasOffsetX = original_CanvasOffsetX * (1/original_ZoomFactor);
CanvasOffsetY = original_CanvasOffsetY * (1/original_ZoomFactor);
Map_Canvas.style.width = (original_CanvasWidth * (1/original_ZoomFactor)) + "px";
Map_Canvas.style.height = (original_CanvasHeight * (1/original_ZoomFactor)) + "px";
// apply the user Preferences
map.setDotSize( DotSize );
map.setColorBrightness( ColorBrightness );
map.setRectangleOpacity( RectangleOpacity );
map.setAllItemsColor( AllItemsColor );
// draw all
map.drawWorld();
// open the canvas contents in a new tab
var map_image = Map_Canvas.toDataURL('image/png');
window.open(map_image);
// revert to original canvas state
Map_Canvas.style.width = "100%";
Map_Canvas.style.height = "100%";
Map_Canvas.width = original_CanvasWidth;
Map_Canvas.height = original_CanvasHeight;
ZoomFactor = original_ZoomFactor;
CanvasOffsetX = original_CanvasOffsetX;
CanvasOffsetY = original_CanvasOffsetY;
map.setDotSize( 4 );
map.setColorBrightness( 0 );
map.setRectangleOpacity( 20 );
map.setAllItemsColor( "" );
map.drawWorld();
}
/**
* Fill the available plans combo box with the plans of the selected trench. These are described inside the json database.
*/
function PopulatePlansList() {
// remember the currently selected plan if any
var CurrentPlan = AvailablePlansCombo.value;
// clear the plans combo box
var i, L = AvailablePlansCombo.options.length - 1;
for(i = L; i >= 0; i--) {
AvailablePlansCombo.remove(i);
}
// calculate which plans should be available
var available_plans_list = [];
for(plan_name in PlanTrenchRelations) {
for(let j=0; j<PlanTrenchRelations[plan_name].length; j++) {
if( currentTrenchNames.includes(PlanTrenchRelations[plan_name][j]) ) {
if(!available_plans_list.includes(plan_name)) available_plans_list.push( plan_name );
}
}
}
available_plans_list.sort();
// fill the combo with the plans of the selected trench
for (let i = 0; i < available_plans_list.length; i++) {
var option = document.createElement('option');
option.value = available_plans_list[i];
option.innerHTML = available_plans_list[i];
AvailablePlansCombo.appendChild(option);
}
//
if( CurrentPlan != null && CurrentPlan.length > 0 ) { // the user may have changed trench and plans-list are automatically refreshed
if( available_plans_list.includes(CurrentPlan) ) {
AvailablePlansCombo.value = CurrentPlan;
}
}
}
/**
* Fills the Categories combo-box with all the available types and categories that exist in the trench data-set.
*/
function PopulateCategoriesCombo() {
// find all Types and categories defined inside the trench data
var Organization = [];
Organization.push( "" ); Organization[ "" ] = [];
Organization.push( "All" ); Organization[ "All" ] = [];
// init Organization with all types
for (let i=0; i<list_of_all_Types.length; i++) {
Organization.push( list_of_all_Types[i] );
Organization[ list_of_all_Types[i] ] = [];
}
// add Categories to each Type
for (let i = 0; i < ExcData.length; i++) {
if( ExcData[i]["Type"].localeCompare("Image") == 0 ) continue; // << ignore the Image category
if( ExcData[i].hasOwnProperty("Category") && ExcData[i]["Category"].length>0 ) {
var item_type = ExcData[i]["Type"];
var item_category = ExcData[i]["Category"];
if( Organization[item_type].includes(item_category) == false ) { // we found a new category for this type
Organization[ item_type ].push( item_category );
}
}
}
// ---- fill the combo with Types and their respective Categories
$("#itemCategoriesCombo").empty();
var an_option;
for (let i = 0; i < Organization.length; i++) {
var GroupName = Organization[i];
an_option = document.createElement('OPTION');
an_option.value = GroupName;
an_option.innerHTML = GroupName;
an_option.classList.add( "combo_type" );
if( GroupName != "Image" && GroupName != "Plan") itemCategoriesCombo.appendChild( an_option );
for (let j = 0; j < Organization[GroupName].length; j++) {
an_option = document.createElement('OPTION');
an_option.value = Organization[GroupName][j];
an_option.innerHTML = " "+Organization[GroupName][j];
an_option.classList.add( "combo_category" );
if( GroupName != "Image" ) itemCategoriesCombo.appendChild( an_option );
}
}
// ---- fill the Panel with Types and their respective Categories
$("#itemCategoriesPanel").empty();
var an_option;
for (let i = 0; i < Organization.length; i++) {
if( Organization[i].trim().length == 0 ) continue; // <<
var GroupName = Organization[i];
an_option = document.createElement('OPTION');
an_option.value = GroupName;
an_option.text = GroupName;
an_option.innerHTML = GroupName;
an_option.classList.add( "combo_type" );
if( GroupName != "Image" ) itemCategoriesPanel.add(an_option);
for (let j = 0; j < Organization[GroupName].length; j++) {
an_option = document.createElement('OPTION');
an_option.value = Organization[GroupName][j];
an_option.text = Organization[GroupName][j];
an_option.innerHTML = " "+Organization[GroupName][j];
an_option.classList.add( "combo_category" );
if( GroupName != "Image" ) itemCategoriesPanel.add( an_option );
}
}
itemCategoriesPanel.size = itemCategoriesPanel.options.length; // for the itemCategoriesPanel, make all options visible
}
/**
* This function fills the items-list with all the items the user has selected to see.
*/
function PopulateItemsList( JSONdata, Category, SearchString ) {
ItemList_wasPopulatedBy_AdvancedSearch = false;
$(itemsList_ul).empty();
num_of_items_in_list = 0;
var item_belongs_to_selected_trenches;