-
Notifications
You must be signed in to change notification settings - Fork 1
/
historical.js
2628 lines (2297 loc) · 81.7 KB
/
historical.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
// global constant for object ID
const momCobaltMap = $('#momCobaltIFrame');
const momCobaltBtn = $("#momCobaltBtn");
const clearFigOptBtn = $("#clearFigOptBtn")
var mapData = {} // parsed html output
// var image_data = '' // png encoding
// global info
var locationData;
var polygonData;
// monthly and daily list for creating the time slider
let freq_list = momCobaltVars();
let monthly_list = [];
let daily_list = [];
for (let i = 0; i < freq_list[2].length; i++) {
if (freq_list[2][i] === "monthly") {
monthly_list.push(freq_list[1][i])
} else if (freq_list[2][i] === "daily") {
daily_list.push(freq_list[1][i])
}
}
// Default time slider related variables
const timeSlider = $("#timeRange");
const tValue = $(".timeValue");
const containerTick = $(".ticks");
var yearValues, rangeValues;
[yearValues, rangeValues] = generateDateList();
timeSlider.attr("min", 0);
timeSlider.attr("max", rangeValues.length - 1);
timeSlider.val(rangeValues.length - 1);
var dateFolium = rangeValues[timeSlider.val()]; // global
tValue.text(dateFolium);
tickSpaceChange();
// Initial region options (for all region options)
createMomCobaltOpt('reg-mom-cobalt',momCobaltRegs);
// Initial variable options based on dataset
createMomCobaltVarOpt('MOMCobalt','varMOMCobalt');
// Initial stat options
createMomCobaltStatOpt();
// Initial depth options based on variable
createMomCobaltDepthOpt('tos','depthMOMCobalt');
// Initial depth block options based on variable
createMomCobaltDepthBlockOpt('tos');
// setup colorbar option
createMomCobaltCbarOpt();
// Initial variable options based on dataset for second TS
createMomCobaltVarOpt('MOMCobalt+Index','varMOMCobaltTS2');
$('#varMOMCobaltTS2').val('');
// Initial depth options based on dataset for second TS
createMomCobaltDepthOpt('tos','depthMOMCobaltTS2');
$('#depthMOMCobaltTS2').val('');
// Initial variable options based on dataset for second TS
createMomCobaltVarOpt('onlyIndexes','indexMOMCobaltTS');
// initialize plotly
$(document).ready(function() {
asyncInitializePlotlyResize('all')
});
// initializePlotly('all');
// plot index
plotIndexes();
/// setup the variable for variable options in the page
let varnamelist = momCobaltVars();
let varind = varnamelist[1].indexOf($("#varMOMCobalt").val())
let varname = varnamelist[0][varind]
let varnamelist2 = momCobaltVars();
let indexlist2 = indexes();
varnamelist2[0] = varnamelist2[0].concat(indexlist2[0]);
varnamelist2[1] = varnamelist2[1].concat(indexlist2[1]);
let varind2 = varnamelist2[1].indexOf($("#varMOMCobaltTS2").val())
let varname2 = varnamelist2[0][varind2]
/////////////// event listener ///////////
// // add the initial time options
// createMomCobaltIniOpt(dataCobaltID);
$(window).resize(function() {
tickSpaceChange();
});
// event listen for variable change
$("#varMOMCobalt").on("change", function(){
// varname
varind = varnamelist[1].indexOf($("#varMOMCobalt").val())
varname = varnamelist[0][varind]
// depth option change
$("#depthMOMCobalt").empty();
createMomCobaltDepthOpt($("#varMOMCobalt").val(),"depthMOMCobalt");
$("#blockMOMCobalt").empty();
createMomCobaltDepthBlockOpt($("#varMOMCobalt").val());
// time slider change
var selectVarIndex = $("#varMOMCobalt").prop('selectedIndex');
if (freq_list[2][selectVarIndex] === 'daily'){
// change if dateFolium is origianly in monthly format
if (dateFolium.length === 7){
[yearValues, rangeValues] = generateDailyDateList();
timeSlider.attr("min", 0);
timeSlider.attr("max", rangeValues.length - 1);
const foundIndex = rangeValues.indexOf(dateFolium+"-01");
timeSlider.val(foundIndex);
dateFolium = rangeValues[timeSlider.val()];
}
} else if (freq_list[2][selectVarIndex] === 'monthly'){
// change if dateFolium is origianly in daily format
if (dateFolium.length === 10){
[yearValues, rangeValues] = generateDateList();
timeSlider.attr("min", 0);
timeSlider.attr("max", rangeValues.length - 1);
const foundIndex = rangeValues.indexOf(dateFolium.slice(0, -3));
timeSlider.val(foundIndex);
dateFolium = rangeValues[timeSlider.val()];
}
};
// console.log(dateFolium)
// if (monthly_list.indexOf($(this).val()) === -1) {
// if (dateFolium.length === 7){
// [yearValues, rangeValues] = generateDailyDateList();
// timeSlider.attr("min", 0);
// timeSlider.attr("max", rangeValues.length - 1);
// const foundIndex = rangeValues.indexOf(dateFolium+"-01");
// timeSlider.val(foundIndex);
// dateFolium = rangeValues[timeSlider.val()];
// }
// } else if (daily_list.indexOf($(this).val()) === -1) {
// if (dateFolium.length === 10){
// [yearValues, rangeValues] = generateDateList();
// timeSlider.attr("min", 0);
// timeSlider.attr("max", rangeValues.length - 1);
// const foundIndex = rangeValues.indexOf(dateFolium.slice(0, -3));
// timeSlider.val(foundIndex);
// dateFolium = rangeValues[timeSlider.val()];
// }
// }
// console.log(dateFolium)
tValue.text(dateFolium);
});
// event listen for analyses dashboard dropdown change with nav pil
$("#analysisMOMCobalt").on("change", function(){
// Related ID name
// dropdown option ID = xxxVal
// content ID = xxx
// navpil ID = xxxPill
// get the dropdown option ID name
var selectedValue = $('#analysisMOMCobalt :selected').val();
// change the active navpil
$("#dashNavHistrun > ul.nav-pills > li.nav-item").removeClass("active");
$("#"+selectedValue.slice(0, -3)+'Pill').addClass("active");
// change the active navtab
$("#dashNavHistrun > ul.nav-tabs > li.nav-item").removeClass("active");
$("#"+selectedValue.slice(0, -3)+'Tab').addClass("active");
// change the active navpil content
$("#dashContentHistrun div.tab-pane").removeClass("active");
$("#"+selectedValue.slice(0, -3)).addClass("active");
// Manually trigger a resize event for triggering plotly resizing
window.dispatchEvent(new Event('resize'));
})
// event listener for navpil being clicked
$("#dashNavHistrun > ul.nav-pills > li.nav-item > .nav-link").on('click',function(){
let hrefID = $(this).attr('href');
let hrefIDText = hrefID.slice(1);
changeDashSelect('analysisMOMCobalt',hrefIDText+'Val');
window.dispatchEvent(new Event('resize'));
});
// event listener for navtab being clicked
$("#dashNavHistrun > ul.nav-tabs > li.nav-item > .nav-link").on('click',function(){
let hrefID = $(this).attr('href');
let hrefIDText = hrefID.slice(1);
changeDashSelect('analysisMOMCobalt',hrefIDText+'Val');
window.dispatchEvent(new Event('resize'));
});
// // event listener for clicking the minitab
// $('input[name="analysestabs"]').click(function() {
// // Check which radio button is clicked
// if ($(this).is(':checked')) {
// var selectedID = $(this).attr('id');
// changeSelectOpt(selectedID.slice(0, -3),'analysisMOMCobalt','view')
// // console.log('Selected option id:', $(this).attr('id'));
// }
// });
// Update the figure (when mouse up the slider handle)
timeSlider.on("mouseup", function() {
$("div.workingTop").removeClass("hidden");
$("div.errorTop").addClass("hidden");
$("div.whiteTop").addClass("hidden");
dateFolium = rangeValues[$(this).val()];
// fetchDataAndPost(dateFolium)
replaceFolium()
});
// Update the current slider value (each time you drag the slider handle)
timeSlider.on("input", function() {
dateFolium = rangeValues[$(this).val()];
tValue.text(dateFolium);
});
// add event listener on create map button
momCobaltBtn.on("click", function () {
// $("div.workingTop").removeClass("hidden");
// $("div.errorTop").addClass("hidden");
// $("div.whiteTop").addClass("hidden");
replaceFolium()
// $('#varMOMCobaltTS2').val('');
// $("#depthMOMCobaltTS2").val('');
});
// add event listener on figure all clear button
clearFigOptBtn.on("click", function () {
$("input.figOpt").val('');
});
// add event listener on reset time series select in plotly
$("#clearTSselectBtn").on("click", function () {
if (locationData !== undefined && locationData !== null) {
if (varFoliumMap !== undefined && varFoliumMap !== null) {
if ($('#varMOMCobaltTS2').val() !== undefined && $('#varMOMCobaltTS2').val() !== null) {
plotTSs(locationData)
} else {
plotTS1(locationData);
}
}
}
});
// add event listener on reset time series select in plotly
$("#clearTS2Btn").on("click", function () {
$('#varMOMCobaltTS2').val('');
$('#depthMOMCobaltTS2').val('');
if (locationData !== undefined && locationData !== null) {
if (varFoliumMap !== undefined && varFoliumMap !== null) {
plotTS1(locationData);
}
}
});
// add event listener for the "message" event using jQuery (location click)
$(window).on("message", receiveMessage);
// add event listener on adding 2nd time series in plotly
$('#varMOMCobaltTS2').on("change", function () {
// depth option change
$("#depthMOMCobaltTS2").empty();
createMomCobaltDepthOpt($("#varMOMCobaltTS2").val(),"depthMOMCobaltTS2");
// varname2
varind2 = varnamelist2[1].indexOf($("#varMOMCobaltTS2").val())
varname2 = varnamelist2[0][varind2]
if (locationData !== undefined && locationData !== null) {
if (varFoliumMap !== undefined && varFoliumMap !== null) {
if ($('#varMOMCobaltTS2').val() !== undefined && $('#varMOMCobaltTS2').val() !== null) {
plotTSs(locationData)
} else {
plotTS1(locationData);
}
}
}
});
// add event listener on selecting depth for 3d 2nd variable
$('#depthMOMCobaltTS2').on("change", function () {
if (locationData !== undefined && locationData !== null) {
if (varFoliumMap !== undefined && varFoliumMap !== null) {
if ($('#varMOMCobaltTS2').val() !== undefined && $('#varMOMCobaltTS2').val() !== null) {
plotTSs(locationData)
} else {
plotTS1(locationData);
}
}
}
});
// add event listener on selecting depth for 3d 2nd variable
$('#indexMOMCobaltTS').on("change", function () {
plotIndexes()
});
///////// functional function start /////////
// intialize the plotly plot
// Initial dashboard plot
function asyncInitializePlotlyResize(flag) {
return initializePlotly(flag)
.then(() => {
window.dispatchEvent(new Event('resize'));
})
.catch(error => {
console.error('Error in async plotly initialization:', error);
});
}
function initializePlotly(flag) {
var trace = {
x: "",
y: "",
type: 'scatter',
mode: 'lines+markers',
marker: { size: 8 },
line: { shape: 'linear' },
name: ""
};
var layoutTS = {
title:
'Click on map for time series',
// autosize: true,
// width: 1000,
// height: 400,
xaxis: { title: 'Date' },
yaxis: { title: 'Variable' },
hovermode: 'closest',
showlegend: false,
// responsive: true
};
var layoutBox = {
title:
'Box plot',
// autosize: true,
// width: 1000,
// height: 400,
hovermode: 'closest',
showlegend: false,
// responsive: true
};
var layoutHist = {
title:
'Histogram',
// autosize: true,
// width: 1000,
// height: 400,
hovermode: 'closest',
showlegend: false,
// responsive: true
};
var layoutProf = {
title:
'Profile',
// autosize: true,
// width: 1000,
// height: 400,
hovermode: 'closest',
showlegend: false,
// responsive: true
};
var layout2 = {
title:
'Draw polyline on map',
// autosize: true,
// width: 1000,
// height: 400,
xaxis: { title: 'Date' },
yaxis: { title: 'Variable' },
hovermode: 'closest',
showlegend: false,
// responsive: true
};
var layoutFcst = {
title:
'Create Forecast Map first<br>& pick point on the shaded area',
// autosize: true,
// width: 1000,
// height: 400,
xaxis: { title: 'Date' },
yaxis: { title: 'Variable' },
hovermode: 'closest',
showlegend: false,
// responsive: true
};
var config = {responsive: true}
if (flag ==='all'){
Plotly.newPlot('plotly-time-series', [trace], layoutTS,config);
// Plotly.newPlot('plotly-box-plot', [trace], layoutBox,config);
// Plotly.newPlot('plotly-histogram', [trace], layoutHist,config);
Plotly.newPlot('plotly-vertical-t', [trace], layoutProf,config);
Plotly.newPlot('plotly-vertical-s', [trace], layoutProf,config);
Plotly.newPlot('plotly-transect', [trace], layout2,config);
// Plotly.newPlot('plotly-index', [trace], layout3)
} else if (flag ==='vertical') {
Plotly.newPlot('plotly-vertical-t', [trace], layoutProf,config);
Plotly.newPlot('plotly-vertical-s', [trace], layoutProf,config);
} else if (flag ==='tseries') {
Plotly.newPlot('plotly-time-series', [trace], layoutTS,config);
} else if (flag ==='transect') {
Plotly.newPlot('plotly-transect', [trace], layout2,config);
} else if (flag ==='forecast') {
Plotly.newPlot('plotly-fcast-spread', [trace], layoutFcst, config);
Plotly.newPlot('plotly-fcast-box', [trace], layoutFcst, config);
} else if (flag ==='mhwForecast') {
Plotly.newPlot('plotly-fcastmhw-prob', [trace], layoutTS,config);
Plotly.newPlot('plotly-fcastmhw-mag', [trace], layoutTS,config);
}
return new Promise(resolve => {
console.log('Initial Plotly created');
resolve();
});
};
// //function for option change due to button/view change at the bottom
// function changeSelectOpt(divId,optionID,tabContentClass) {
// showDiv(divId,tabContentClass);
// // change pick option
// $('#' + optionID).val(divId + 'Val').change();
// }
// function for option change due to nav pill change at the bottom
function changeDashSelect(dashDropDownID,optionVal) {
// change pick option
$('#' + dashDropDownID).val(optionVal).change();
}
// // function for mini navbar in a bootstrap page
// function showDiv(divId,tabContentClass) {
// // Hide all divs
// $('.'+tabContentClass).addClass("hidden")
// // Show the selected div
// $('#' + divId).removeClass("hidden");
// // // Show click button
// // showClick(divId+'Btn');
// }
// // function for minitab in a bootstrap page
// function showClick(buttonId) {
// // Hide all divs
// $('.tablink').removeClass("clicked")
// // Show the selected div
// $('#' + buttonId).addClass("clicked");
// }
// function for changing the tick mark of time slider
function tickSpaceChange() {
if ($(window).width() < 600) {
var result = [];
for (var i = 3; i < yearValues.length; i += 5) {
result.push(yearValues[i]);
}
generateTick(result);
} else if ($(window).width() < 1200) {
var result = [];
for (var i = 2; i < yearValues.length; i += 2) {
result.push(yearValues[i]);
}
generateTick(result);
} else {
generateTick(yearValues);
};
};
// function for create option
function optionList(listname,listval) {
let df = document.createDocumentFragment(); // create a document fragment to hold the options created later
for (let i = 0; i < listname.length; i++) { // loop
let option = document.createElement('option'); // create the option element
option.value = listval[i]; // set the value property
option.appendChild(document.createTextNode(listname[i])); // set the textContent in a safe way.
df.appendChild(option); // append the option to the document fragment
}
return df;
};
// function for create option with subgroup
function optionSubgroupList(listname,listval,listsubgroup) {
let df = document.createDocumentFragment(); // create a document fragment to hold the options created later
// object subgroup
const monthlyGroup = document.createElement('optgroup');
monthlyGroup.label = 'Monthly variables';
const dailyGroup = document.createElement('optgroup');
dailyGroup.label = 'Daily variables';
const monthlyIndexGroup = document.createElement('optgroup');
monthlyIndexGroup.label = 'Monthly indexes';
const annualIndexGroup = document.createElement('optgroup');
annualIndexGroup.label = 'Annual indexes';
var mvflag = false
var dvflag = false
var miflag = false
var aiflag = false
for (let i = 0; i < listname.length; i++) {
let option = document.createElement('option'); // create the option element
option.value = listval[i]; // set the value property
option.appendChild(document.createTextNode(listname[i])); // set the textContent in a safe way.
if (listsubgroup[i].indexOf("monthly")!==-1){
monthlyGroup.appendChild(option);
mvflag = true
} else if (listsubgroup[i].indexOf("daily")!==-1){
dailyGroup.appendChild(option);
dvflag = true
} else if (listsubgroup[i].indexOf("mon_index")!==-1){
monthlyIndexGroup.appendChild(option);
miflag = true
} else if (listsubgroup[i].indexOf("ann_index")!==-1){
annualIndexGroup.appendChild(option);
aiflag = true
}
}
// append the subgroup in the desired order
if (aiflag) {
df.appendChild(annualIndexGroup);
}
if (mvflag) {
df.appendChild(monthlyGroup);
}
// df.appendChild(monthlyGroup); // append the option to the document fragment
if (miflag) {
df.appendChild(monthlyIndexGroup);
}
// df.appendChild(dailyGroup);
if (dvflag) {
df.appendChild(dailyGroup);
}
return df;
};
// function for create option for general options (single ID)
function createMomCobaltOpt_singleID(selectID,optionListFunc) {
let elm = document.getElementById(selectID);
let optlist = optionListFunc();
df = optionList(optlist[0],optlist[1]);
elm.appendChild(df);
};
// function for create option for general options
function createMomCobaltOpt(selectClass,optionListFunc) {
let elms = document.getElementsByClassName(selectClass);
let optlist = optionListFunc();
df = optionList(optlist[0],optlist[1]);
// loop through all region dropdown with the selectClassName
for(let i = 0; i < elms.length; i++) {
let clonedf = df.cloneNode(true); // Clone the child element
elms[i].appendChild(clonedf); // Append the cloned child to the current element
}
};
// function for create option for variables (optimized for different purposes)
function createMomCobaltVarOpt(dataCobaltID,selectID) {
let elm = document.getElementById(selectID);
let varlist = momCobaltVars();
if (dataCobaltID == "MOMCobalt") {
// for historical run var
varlist = momCobaltVars();
} else if (dataCobaltID == "MOMCobalt+Index") {
// for second time series comp
varlist = momCobaltVars();
indexlist = indexes();
varlist[0] = varlist[0].concat(indexlist[0]);
varlist[1] = varlist[1].concat(indexlist[1]);
varlist[2] = varlist[2].concat(indexlist[2]);
} else if (dataCobaltID == "onlyIndexes") {
// for index
indexlist = indexes("onlyIndex");
varlist[0] = indexlist[0];
varlist[1] = indexlist[1];
varlist[2] = indexlist[2];
};
// df = optionList(varlist[0],varlist[1]);
df = optionSubgroupList(varlist[0],varlist[1],varlist[2]);
elm.appendChild(df); // append the document fragment to the DOM. this is the better way rather than setting innerHTML a bunch of times (or even once with a long string)
};
// function for create option for statistics
function createMomCobaltStatOpt() {
let elm = document.getElementById('statMOMCobalt');
let list_stat = momCobaltStats()
let df = optionList(list_stat,list_stat);
elm.appendChild(df);
};
// function for create option for depth
function createMomCobaltDepthOpt(variable,selectID) {
let elm = document.getElementById(selectID);
let list_3d = momCobalt3D()
const found = list_3d.some(element => element === variable);
if (found) {
let depthlist = momCobaltDepth();
let df = optionList(depthlist,depthlist);
elm.appendChild(df);
} else {
let df = document.createDocumentFragment();
let option = document.createElement('option');
option.value = 'single_layer';
option.appendChild(document.createTextNode('single layer'));
df.appendChild(option);
elm.appendChild(df);
}
};
// function for create option for bottom depth block
function createMomCobaltDepthBlockOpt(variable,blockOptID='blockMOMCobalt') {
let elm = document.getElementById(blockOptID);
let list_bottom = momCobaltBottom()
const found = list_bottom.some(element => element === variable);
if (found) {
let depthlist = momCobaltDepth();
let df = optionList(depthlist,depthlist);
elm.appendChild(df);
elm.options[0].disabled = true;
elm.selectedIndex = depthlist.indexOf(6250);
} else {
let df = document.createDocumentFragment();
let option = document.createElement('option');
option.value = 'not_applicable';
option.appendChild(document.createTextNode('not applicable'));
df.appendChild(option);
elm.appendChild(df);
}
};
// function for create option for depth
function createMomCobaltCbarOpt(cbarOptID='cbarOpts',defaultCbar='RdBu_r') {
let elm = document.getElementById(cbarOptID);
let list_cbar = colorbarOpt()
let df = optionList(list_cbar,list_cbar);
return new Promise((resolve) => {
elm.appendChild(df); // append the document fragment to the DOM. this is the better way rather than setting innerHTML a bunch of times (or even once with a long string)
elm.selectedIndex = list_cbar.indexOf(defaultCbar);
// console.log("Async work completed!");
resolve(); // Resolve the promise when done
});
};
// function for replace folium overlap info (image and colorbar)
let varFoliumMap;
let statMap;
let depthMap;
function replaceFolium() {
showLoadingSpinner("loading-spinner-map");
varFoliumMap = $("#varMOMCobalt").val();
statMap = $("#statMOMCobalt").val();
depthMap = $("#depthMOMCobalt").val();
let block = $("#blockMOMCobalt");
let cbar = $("#cbarOpts")
let maxval = $("#maxval");
let minval = $("#minval");
let nlevel = $("#nlevel");
var ajaxGet = "/cgi-bin/cefi_portal/mom_folium.py"
+"?variable="+varFoliumMap
+"®ion="+$("#regMOMCobalt").val()
+"&date="+dateFolium
+"&stat="+statMap
+"&depth="+depthMap
+"&block="+block.val()
+"&cbar="+cbar.val()
+"&maxval="+maxval.val()
+"&minval="+minval.val()
+"&nlevel="+nlevel.val()
console.log('https://webtest.psd.esrl.noaa.gov/'+ajaxGet)
fetch(ajaxGet) // Replace with the URL you want to request
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.text();
})
.then(data => {
// Process the response data here
// console.log(data)
//replace image
var regexImg = /^\s*"data:image\/png;base64,[^,\n]*,\n/gm;
var matcheImg = data.match(regexImg);
var image = matcheImg[0].match(/"([^"]+)"/)[0].slice(1,-1)
// var image = extractText(matcheImg[0]);
//replace colorbar
var regexDom = /^\s*\.domain\([^)]*\)\n/gm;
var matchDoms = data.match(regexDom);
var domainArray1 = text2Array(matchDoms[0]);
var domainArray2 = text2Array(matchDoms[1]);
var regexRange = /^\s*\.range\([^)]*\);\n/gm;
var matchRanges = data.match(regexRange);
var rangeArray = text2Array(matchRanges[0].replace(/'/g, '"'));
//replace tickmark
var regexTickVal = /^\s*\.tickValues\([^)]*\);\n/gm;
var matchTickVal = data.match(regexTickVal);
var tickValArray = text2Array(matchTickVal[0]);
//replace colorbar label
var regexCLabel = /^\s*\.text\([^)]*\);\n/gm;
var matchCLabel = data.match(regexCLabel);
var textVal = extractText(matchCLabel[0]);
mapData = {
type: 'mapData',
image: image,
domain1: domainArray1,
domain2: domainArray2,
range: rangeArray,
tick: tickValArray,
label: textVal
};
// console.log(mapData)
momCobaltMap[0].contentWindow.postMessage(mapData, "*")
// get same point time series when points and variable are defined
if (locationData !== undefined && locationData !== null) {
if (varFoliumMap !== undefined && varFoliumMap !== null) {
if ($('#varMOMCobaltTS2').val() !== undefined && $('#varMOMCobaltTS2').val() !== null) {
plotTSs(locationData)
} else {
plotTS1(locationData);
}
}
//// current function only allowed in monthly data
if (dateFolium.length === 7){
plotVertProfs(locationData);
} else {
// initialize plotly
initializePlotly('vertical');
}
}
// get same polyline transect when polyline and variable are defined
if (polygonData !== undefined && polygonData !== null) {
if (varFoliumMap !== undefined && varFoliumMap !== null) {
//// current function only allowed in monthly data
if (dateFolium.length === 7){
plotTransect(polygonData);
} else {
// initialize plotly
initializePlotly('transect');
}
}
}
// if (document.getElementById('plotly-time-series').data.length===1) {
// momCobaltMap[0].contentWindow.postMessage(data, "*")
// momCobaltMap.attr("srcdoc", data)
$("div.workingTop").addClass("hidden");
$("div.errorTop").addClass("hidden");
$("div.whiteTop").removeClass("hidden");
hideLoadingSpinner("loading-spinner-map");
})
.catch(error => {
// Handle errors here
console.error('Fetch folium map error:', error);
$("div.workingTop").addClass("hidden");
$("div.errorTop").removeClass("hidden");
$("div.whiteTop").addClass("hidden");
});
// momCobaltMap.attr("src", ajaxGet)
}
// function for decomposing the html code
function text2Array(string) {
var stringRegex = /\[.*\]/;
var array = string.match(stringRegex);
array = JSON.parse(array);
return array;
}
// function for decomposing the html code
function extractText(string) {
var stringRegex =/\.text\("([^"]+)"\)/;
var text = string.match(stringRegex);
return text[1];
}
// function for plotting 2 TS with Promise to make sure the plotting order
function plotTSs(infoLonLat) {
showLoadingSpinner("loading-spinner-ts");
const promiseTS1 = new Promise((resolve, reject) => {
getTimeSeries(infoLonLat, false)
.then(parsedTS => {
// console.log(parsedTS);
resolve(parsedTS);
})
.catch(error => {
// Handle errors here
console.error('Error in create PromiseTS1:', error);
reject(error);
});
});
const promiseTS2 = new Promise((resolve, reject) => {
if (indexes()[1].indexOf($("#varMOMCobaltTS2").val()) === -1) {
getTimeSeries(infoLonLat, true)
.then(parsedTS => {
// console.log(parsedTS);
resolve(parsedTS);
})
.catch(error => {
// Handle errors here
console.error('Error in create PromiseTS2:', error);
reject(error);
});
} else {
getIndex('#varMOMCobaltTS2')
.then(parsedTS => {
// console.log(parsedTS);
resolve(parsedTS);
})
.catch(error => {
// Handle errors here
console.error('Error in create PromiseTS2 for indexes:', error);
reject(error);
});
}
});
Promise.all([promiseTS1,promiseTS2])
.then(([firstTS,secondTS]) => {
plotlyTS(firstTS.tsDates,firstTS.tsValues,firstTS.lonValues,firstTS.latValues,firstTS.tsUnit,firstTS.yformat)
plotlyBox(firstTS.tsValues,firstTS.yformat)
plotlyHist(firstTS.tsValues,firstTS.tsUnit,firstTS.yformat)
return new Promise((resolve) => {
resolve([firstTS,secondTS])
});
})
.then(([firstTS,secondTS])=>{
if (indexes()[1].indexOf($("#varMOMCobaltTS2").val()) === -1) {
// plotting the variable time series
plotlyTSadd(secondTS.tsDates,secondTS.tsValues,secondTS.lonValues,secondTS.latValues,secondTS.tsUnit,secondTS.yformat)
plotlyBoxadd(secondTS.tsValues,secondTS.yformat)
plotlyHistadd(secondTS.tsValues,secondTS.tsUnit,secondTS.yformat)
} else {
// plotting the first index (make it always the first one as observed value)
plotlyTSadd(secondTS.tsDates[0],secondTS.tsValues[0],firstTS.lonValues,firstTS.latValues,secondTS.tsUnit[0],secondTS.yformat[0])
plotlyBoxadd(secondTS.tsValues[0],secondTS.yformat[0])
plotlyHistadd(secondTS.tsValues[0],secondTS.tsUnit[0],secondTS.yformat[0])
}
hideLoadingSpinner("loading-spinner-ts");
})
.catch((error)=>{
console.error(error);
})
};
// function for plotting first TS with Promise for data fetch complete
function plotTS1(infoLonLat) {
showLoadingSpinner("loading-spinner-ts");
const promiseTS = new Promise((resolve, reject) => {
getTimeSeries(infoLonLat, false)
.then(parsedTS => {
// console.log(parsedTS);
resolve(parsedTS);
})
.catch(error => {
// Handle errors here
console.error('Error in createPromiseForTimeSeries:', error);
reject(error);
});
});
promiseTS
.then((firstTS)=>{
plotlyTS(firstTS.tsDates,firstTS.tsValues,firstTS.lonValues,firstTS.latValues,firstTS.tsUnit,firstTS.yformat)
plotlyBox(firstTS.tsValues,firstTS.yformat)
plotlyHist(firstTS.tsValues,firstTS.tsUnit,firstTS.yformat)
hideLoadingSpinner("loading-spinner-ts");
})
.catch((error)=>{
console.error(error);
})
};
// function for plotting first TS with Promise for data fetch complete
function plotVertProfs(infoLonLat) {
showLoadingSpinner("loading-spinner-vprof");
const promiseVPs = new Promise((resolve, reject) => {
getVerticalProfile(infoLonLat)
.then(parsedVP => {
// console.log(parsedTS);
resolve(parsedVP);
})
.catch(error => {
// Handle errors here
console.error('Error in createPromiseForVerticalProfile:', error);
reject(error);
});
});
promiseVPs
.then((parsedVP)=>{
plotlyVP(parsedVP.tDepth,parsedVP.tValues,parsedVP.tlonValues,parsedVP.tlatValues,parsedVP.tUnit,parsedVP.tformat,"plotly-vertical-t","Potential Temperature","rgba(113, 29, 176, 0.7)")
plotlyVP(parsedVP.sDepth,parsedVP.sValues,parsedVP.slonValues,parsedVP.slatValues,parsedVP.sUnit,parsedVP.sformat,"plotly-vertical-s","Salinity","rgb(239, 64, 64)")
hideLoadingSpinner("loading-spinner-vprof");
})
.catch((error)=>{
console.error(error);
})
};
// function for plotting first TS with Promise for data fetch complete
function plotTransect(infoLine) {
showLoadingSpinner("loading-spinner-tsect");
const promiseTran = new Promise((resolve, reject) => {
getTransect(infoLine)
.then(parsedTran => {
resolve(parsedTran);
})
.catch(error => {
// Handle errors here
console.error('Error in createPromiseForTransect:', error);
reject(error);
});
});
promiseTran
.then((parsedTran)=>{
if (varname.includes('(3D)')) {
plotlyContour("plotly-transect",parsedTran)
} else {
plotlyTransectLine("plotly-transect",parsedTran)
}
hideLoadingSpinner("loading-spinner-tsect");
})
.catch((error)=>{
console.error(error);
})
};
// function for plotting first TS with Promise for data fetch complete
function plotIndexes() {
showLoadingSpinner("loading-spinner-index");
const indexName = $('#indexMOMCobaltTS').val();
const promiseIndex = new Promise((resolve, reject) => {
getIndex('#indexMOMCobaltTS')
.then(parsedIndex => {
// console.log(parsedTS);
resolve(parsedIndex);
})
.catch(error => {
// Handle errors here
console.error('Error in createPromiseForIndexes:', error);
reject(error);
});
});
promiseIndex
.then((parsedIndex)=>{
numberOfIndexes = parsedIndex.tsDates.length
var i = 0 ;
plotlyIndex(parsedIndex.tsDates[i],parsedIndex.tsValues[i],parsedIndex.tsUnit[i],parsedIndex.yformat[i],parsedIndex.tsName[i],indexName)
for (let i = 1; i < numberOfIndexes; i++) {
plotlyIndexAdd(parsedIndex.tsDates[i],parsedIndex.tsValues[i],parsedIndex.tsName[i])
}