-
Notifications
You must be signed in to change notification settings - Fork 0
/
swedbank-script.js
1555 lines (1343 loc) · 51.2 KB
/
swedbank-script.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
//Used to detect when the CTRL key is pressed
var ctrlDown;
//Used to detect when the SHIFT key is pressed
var shiftDown;
//Used to detect when the TAB key is pressed
var tabDown;
//Used to detect a delete button has been pressed
var scrollToElementAddedByAJAX = false;
$(document).ready(function() {
//Remove browser validation
//This is not currently needed to prevent the validation, but it might be
//if digiforms is updated to use submit buttons
//It is however necessary in order to prevent red borders around inputs
//(in some browsers, e.g. firefox)
preventBrowserFormActions();
//Events used to check if control or tab is pressed
initGlobalKeyEventListener();
//Form elements
formControlEventbinding();
//Skip nav
navigateToMainContentEventBinding();
//Adjustments to the auto generated parts of the DOM
adjustAutoGeneratedElements();
//Event bindings that uses external APIs
bindEventsThatCallsExternalAPIs();
//Event bindings used for special validation
validation();
//Scrolls the first input with an error into view
scrollToFirstError();
//Adjust hrefs for file-download links
initFileUpAndDownloads();
//Disables add buttons when maxium number of
//elements has been added
disableAddButtonsWhenMaxIsReached();
//Sets ARIA attributes for delete buttons
setAriaAttributesForDeleteButtons();
//Bind events / adjust eventhandlers to elements
//that triggers ajax update
initAJAXUpdateElements();
});
//Adds the attribute for no validation
function preventBrowserFormActions() {
$("#frm").attr("novalidate", "novalidate");
}
//Initalizes event listeners
//for the CTRL and TAB keys
function initGlobalKeyEventListener() {
//Checks if the CTRL key is pressed
ctrlDown = false;
$(document).on("keydown", function(event) {
var key = event.which || event.keyCode;
if (key == 17) {
ctrlDown = true;
}
});
$(document).on("keyup", function(event) {
var key = event.which || event.keyCode;
if (key == 17) {
ctrlDown = false;
}
});
//Checks if the SHIFT key is pressed
shiftDown = false;
$(document).on("keydown", function(event) {
var key = event.which || event.keyCode;
if (key == 16) {
shiftDown = true;
}
});
$(document).on("keyup", function(event) {
var key = event.which || event.keyCode;
if (key == 16) {
shiftDown = false;
}
});
//Checks if the TAB key is pressed
tabDown = false;
$(document).on("keydown", function(event) {
var key = event.which || event.keyCode;
if (key == 9) {
tabDown = true;
}
});
$(document).on("keyup", function(event) {
var key = event.which || event.keyCode;
if (key == 9) {
tabDown = false;
}
});
}
//Adds event listneres for checkboxes And
//radio buttons
function initCheckBoxesAndRadios() {
//Event listener added to extend the clickable
//area for checkboxes and radio buttons
$(".label_text").on("click", function(e) {
if (e.target.localName != "label") {
var $checkbox = $(this).parent().find("input:checkbox");
$checkbox.trigger("click");
var $radio = $(this).parent().find("input:radio");
$radio.trigger("click");
}
});
//Toggles class for checked/unchecked
//customized checkboxes (styled with pseudo elements)
var toggleCheck = function($input) {
if ($input.is(":checked")) {
$input.parent().siblings(".label_text").addClass("checked");
}
else {
$input.parent().siblings(".label_text").removeClass("checked");
}
};
//Toggle class "checked" for customized checkboxes
$(".control input:checkbox").on("change", function() {
toggleCheck($(this));
});
//To ensure that all customized checkboxes
//are marked as checked when re-visiting a page
var $checkboxes = $(".control input:checkbox:checked");
$.each($checkboxes, function() {
toggleCheck($(this));
});
//Toggle class "checked" for customized radio buttons
$(".control input:radio").on("change", function() {
var $allRadiosInFieldset = $(this).closest("fieldset").find("input:radio");
$.each($allRadiosInFieldset, function() {
toggleCheck($(this));
});
});
//To ensure that all customized radio buttons
//are marked as checked when re-visiting a page
var $radios = $("input:radio");
$.each($radios, function() {
toggleCheck($(this));
});
//Focus - adds class (for accessibility)
$(".control input").on("focus", function() {
$(this).parent().parent().addClass("focused");
});
//Blur - removes class (for accessibility)
$(".control input").on("blur", function() {
$(this).parent().parent().removeClass("focused");
});
//Removes error message when a radio buttons
//or checkbox is selected
$(".control input").on("change", function() {
if($(this).is(":checked")) {
$(this).closest(".control-container").find(".digiforms_validation_message:not(.file-error):first").hide();
}
});
}
//Inits help text Buttons
function initHelptexts() {
//First hide all the help texts
var $helpTexts = $(".help-text").hide();
//Add WAI-ARIA attributes for accessibility
$helpTexts.attr("aria-hidden", "true");
var $helpBtns = $(".btn-help");
if ($("html").attr("lang").toLowerCase() == "se") {
$helpBtns.attr("aria-label", "Vad menas med detta?");
}
else if ($("html").attr("lang").toLowerCase() == "en") {
$helpBtns.attr("aria-label", "What does this mean?");
}
else {
$helpBtns.attr("aria-label", "Hva menes med dette?");
}
$helpBtns.attr("aria-expanded", "false");
$.each($helpBtns, function() {
var $helpElementsForInputs = $(this).closest(".help-elements-for-input").parent();
var $correspondingDescription = "";
if($helpElementsForInputs.length) {
$correspondingDescription = $helpElementsForInputs.find("label:first");
$correspondingDescription.attr("id", $correspondingDescription.attr("for") + "-" + $correspondingDescription.text().split("*")[0].trim())
}
else {
$correspondingDescription = $(this).closest(".help-elements-for-fieldset").parent().find("legend:first");
$correspondingDescription.removeClass("control-container-tight");
}
$(this).attr("aria-describedby", $correspondingDescription.attr("id"));
$(this).attr("aria-controls", $(this).siblings(".help-text:first").attr("id"));
});
//Bind evnts that toggles show/hide for the help text
$helpBtns.on("click", function() {
$(this).toggleClass("active");
var $helpText = $(this).next(".help-text");
$helpText.toggle();
if ($helpText.is(":visible")) {
if ($("html").attr("lang").toLowerCase() == "se") {
$helpBtns.attr("aria-label", "Stäng hjälptext");
}
else if ($("html").attr("lang").toLowerCase() == "en") {
$helpBtns.attr("aria-label", "Close help text");
}
else {
$helpBtns.attr("aria-label", "Lukk hjelpetekst");
}
$helpText.attr("aria-hidden", "false");
$helpBtns.attr("aria-expanded", "true");
}
else {
if ($("html").attr("lang").toLowerCase() == "se") {
$helpBtns.attr("aria-label", "Vad menas med detta?");
}
else if ($("html").attr("lang").toLowerCase() == "en") {
$helpBtns.attr("aria-label", "What does this mean?");
}
else {
$helpBtns.attr("aria-label", "Hva menes med dette?");
}
$helpText.attr("aria-hidden", "true");
$helpBtns.attr("aria-expanded", "false");
}
});
}
//Takes a string and inserts the given
//mask when the function maskHere() returns true
//The parameter x is optional in the function maskHere()
//But is required in this function
function formatAfterInput(str, maxlength, mask, maskHere, x) {
var valTrimmed = removeWhiteSpaces(str);
valTrimmed = removeSubstr(valTrimmed, mask);
var lastSliceIndex = 0;
var newVal = "";
for(var i = x; i < valTrimmed.length; i++) { //Make sure to prevent array out of bounds
if (maskHere(i, x)) {
newVal += valTrimmed.substring(lastSliceIndex, i) + mask;
lastSliceIndex = i;
}
}
newVal += valTrimmed.substring(lastSliceIndex, valTrimmed.length);
return newVal.substring(0, maxlength);
}
//Pads the given string with a space, by x characters
function padBy(x, str, maxlength) {
return formatAfterInput(str, maxlength, " ", function(i, x) { return i % x == 0; }, x);
}
function initInputs() {
//Bring up the numeric keypad for iOS and Android
$("input.numeric-text").attr("inputmode", "numeric"); //Android
$("input.numeric-text").attr("pattern", "[0-9]*"); //iOS
//Sets a mask for some classes:
$("input.numeric-text.no-mask").mask('0#');
$('input[type="tel"]').mask("+099999 000 00 000 000 00 000 00");
$("input.account-mask").mask("0000 00 00000");
$("input.vps-account-mask").mask("00000 0000000");
$("input.org-number-mask").mask("000 000 000");
$("input.date-mask").mask("00.00.0000");
$("input.letteral-text").mask("ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ",
{translation: {"Z": {pattern: /[a-zA-Z ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏàáâãäåæçèéêëìíîïÐÑÒÓÔÕÖØÙÚÛÜÝÞßðñòóôõöøùúûüýþÿ-]/}}});
//Checks if keyCode is numeric
//Allows keycodes are defined by the array "exceptionKeyCodes"
//allowShift makes an exception to allow the SHIFT key to be pressed (e.i for phone numbers)
var isNumericKey = function(keyCode, exceptionKeyCodes, allowShift) {
if (((allowShift || !shiftDown) && keyCode >= 48 && keyCode <= 57) ||
(keyCode >= 96 && keyCode <= 105) ||
(exceptionKeyCodes != undefined && $.inArray(keyCode, exceptionKeyCodes) > -1)) {
return true;
}
return false;
}
var isDeleteKey = function(event) {
var key = event.which || event.keyCode;
//Check if key is delete
if(key == 46) {
return true;
}
return false;
}
var isBackspaceKey = function(event) {
var key = event.which || event.keyCode;
//Check if key is backspace
if(key == 8) {
return true;
}
return false;
}
//Checks if key was delete, backspace, arrows, shift, ctrl, tab, home or end key
var isEditKeyEvent = function(event) {
if (ctrlDown) return true;
var key = event.which || event.keyCode;
if(!isBackspaceKey(event) && key != 9 && !isDeleteKey(event) && key != 13 && key != 16 && key != 17 && key != 19 && (key < 35 || key > 40)) return false;
return true;
}
//Prevents user from entering non-numeric in
//numeric inputs (possible in several browsers, e.g safari, firefox)
$("input.numeric-decimal").on("keydown", function(event) {
var key = event.which || event.keyCode;
//Prevent non numeric characters
//Don't remove characters: "," and ".", don't allow SHIFT key
if (!isEditKeyEvent(event) && !isNumericKey(key, [188, 190], false)) {
event.preventDefault();
}
});
//Validates percentage according to min/max attributes.
//This one is added here and not in the validation() function
//because it is the only validation needed for benifital owners.
//Those are added added dynamically using AJAX which means
//that this parent function (initInputs) must be called again
//when a benifital owner is added
$(".input-percentage").on("change paste", function() {
var val = parseFloat($(this).val());
var max = $(this).attr("max");
var min = $(this).attr("min");
if(val <= max && val >= min) {
$(this).parent().parent().siblings("input[type=hidden]").val("true");
}
else {
$(this).parent().parent().siblings("input[type=hidden]").val("false");
}
$(this).val(val.toString());
});
//Used to set the marker at the end of the prefilled input
//e.i country code for phone numbers
$(".prevent-select-on-tab").on("keyup", function(event) {
var key = event.which || event.keyCode;
if (key == 9) {
$(this).prop("selectionStart", $(this).prop("selectionEnd"));
}
});
$(".prevent-select-on-tab").on("focus", function(event) {
if (tabDown || $(this).prop("selectionStart") != $(this).prop("selectionEnd")) {
$(this).prop("selectionStart", $(this).prop("selectionEnd"));
}
});
}
//Inits all form controls
function formControlEventbinding() {
initCheckBoxesAndRadios();
initHelptexts();
initInputs();
initAccordions();
}
//Scrolles selected element into view
function scrollTo($element, delay) {
if ($element.length > 0) {
$('html, body').animate({
scrollTop: $element.offset().top
}, delay);
}
}
//Toggels WAI-ARIA properties for a given accordion
//(identified by its button)
function toggleARIAPropertiesForAccordion($accBtn) {
var expanded = $accBtn.attr("aria-expanded");
var ariaExpandedAttr = expanded == "false" ? "true" : "false";
$accBtn.attr("aria-expanded", ariaExpandedAttr);
var $correspondingPanel = $accBtn.siblings(".panel:first");
var ariaHiddenAttr = expanded;
$correspondingPanel.attr("aria-hidden", ariaHiddenAttr);
}
//Sets WAI-ARIA properties for a given accordion
//(identified by its button)
function addARIAPropertiesToAccordion($accBtn) {
var $correspondingPanel = $accBtn.siblings(".panel:first");
$accBtn.attr("aria-controls", $correspondingPanel.attr("id"));
$accBtn.attr("aria-expanded", "false");
$correspondingPanel.attr("aria-hidden", "true");
}
//Opens all accordions that have errors
function openAccordionsWithErrors($panels) {
$.each($panels, function() {
if (getFirstError($(this)).length) {
var $correspondingButton = $(this).siblings(".accordion:first");
if (!$correspondingButton.hasClass(".active")) {
$correspondingButton.click();
}
}
});
}
//Scrolls to the last unfinnished accordion if there are no accordions
//with errors (there can only be errors if the forms has been validated)
function scrollToLastUnfinnishedAccordion($panels) {
var $lastAccordionContainer = $(".focus-last-child .accordion-container").last();
var $lastAccordionBtn = $lastAccordionContainer.find(".accordion").first();
if (!$lastAccordionBtn.hasClass("active")) {
var blankFormInputs = false;
$.each($lastAccordionContainer.find("input"), function() {
if (!$(this).val()) {
blankFormInputs = true;
return false;
}
});
if (blankFormInputs) {
$lastAccordionBtn.click();
scrollTo($lastAccordionContainer, 1000);
}
}
}
//Toggle a given accordion (identified by its button)
function toggleAccordion($accBtn) {
$accBtn.toggleClass("active");
var $correspondingPanel = $accBtn.siblings(".panel").first();
$correspondingPanel.toggleClass("hidden");
toggleARIAPropertiesForAccordion($accBtn);
}
//Initalizes accordions that are added dynamically by AJAX
function initAccordionsAddedByAJAX() {
//Add WAI-ARIA attributes
var $accBtns = $(".load-container button.accordion");
$.each($accBtns, function() {
addARIAPropertiesToAccordion($(this));
});
//Appends attributes such as max/min to inputs
//inside the panel of the accordion
appendAttributesToNumberInputs();
//Sets the text of the button to the same as the name of
//the benefitial owner (accordion has class "set-name-accordion")
var setAccordionBtnTitle = function($accordionContainer) {
var prefix = '<span class="chev"></span><span class="desc">';
var suffix = "</span>";
var title = $accordionContainer.find(".accordion-description").first().val();
var $button = $accordionContainer.find("button.accordion");
if (title != "") {
$button.html(prefix + title + suffix);
}
else {
var idSplit = $button.attr("id").split("_");
var text = "Reell rettighetshaver";
if ($("html").attr("lang").toLowerCase() == "se") {
text = "Reell rättighetshavare";
}
else if ($("html").attr("lang").toLowerCase() == "en") {
text = "Beneficial owner";
}
$button.html(prefix + text + " " + (idSplit.length > 0 ? idSplit[idSplit.length - 1] : "") + suffix);
}
};
$.each($(".load-container .set-name-accordion"), function() {
setAccordionBtnTitle($(this));
});
$(".load-container .set-name-accordion .accordion-description").on("change", function() {
setAccordionBtnTitle($(this).closest(".set-name-accordion"));
});
//Init for autofill country phone code and city
bindEventsThatCallsExternalAPIs();
//Init number patterns and percentage validation
initInputs();
//Init delete buttons (to delete accordions)
initDeleteButtons();
//Prevent user from adding more items than allowed
disableAddButtonsWhenMaxIsReached();
//Scrolls to the last unfinnished accordion
//(that has class "focus-last-child")
var $panels = $(".load-container .accordion-container .panel");
if (scrollToElementAddedByAJAX) {
scrollToLastUnfinnishedAccordion($panels);
}
else if (getFirstError($("#main-content_content")).length) {
openAccordionsWithErrors($panels);
}
scrollToElementAddedByAJAX = true;
}
//Initalizes regular accordions
function initAccordions() {
//Panels
var $panels = $(".accordion-container:not(.added-by-AJAX) .panel");
$.each($panels, function() {
if (!$(this).hasClass("hidden")) {
$(this).addClass("hidden");
}
});
//Buttons
var $accBtns = $(".accordion-container:not(.added-by-AJAX) button.accordion");
$.each($accBtns, function() {
addARIAPropertiesToAccordion($(this));
});
$accBtns.on("click", function() {
toggleAccordion($(this));
});
//Set aria attributes for edit buttons (that are inside summary accordions)
$.each($(".accordion-container .summary-container"), function() {
var $changeBtn = $(this).siblings(".btn-primary");
$changeBtn.attr("aria-describedby", $(this).find("table").attr("aria-describedby"));
});
}
//Init skip-links - navigates to main content
function navigateToMainContentEventBinding() {
$("#skip-navigation a").on("click", function() {
var $input = $("#main-content").find(":input[id]:first");
setTimeout(function() {
$input.focus()
}, 100);
});
}
//Appends attributes to number inputs, based on their classes
function appendAttributesToNumberInputs() {
$(".input-decimal-2").attr("step", "0.01");
$(".input-percentage").attr("min", "0");
$(".input-percentage").attr("max", "100");
}
//Adjusts the auto generated error list
function adjustErrorMessageList() {
$(".error-summary").hide();
$.each($(".error-summary > div"), function(index) {
//Adjust the HTML markup
var $firstChild = $(this).children(":first");
var autoGeneratedHeadingSplit = $firstChild.text().split("(");
var pageNumber = autoGeneratedHeadingSplit[0].split("page ").pop().trim();
var heading = pageNumber + ". " + autoGeneratedHeadingSplit[1].split("-")[0];
$firstChild.remove();
$(this).prepend('<h4 id="error-heading-' + pageNumber + '">' + heading + "</h4>");
$(this).addClass("panel panel-danger list-container");
var $container = $(this);
var documentName = "Swedbank_KYC";
if($("title").text().split("-")[1].trim() == "Bedrift") {
documentName += "_Bedrift";
}
//Variables used manipulate error text and style of
//benifital owners (to avoid identical text on links).
//And adjust the layout so it's easier to read
var prefixBenifitialOwners = "";
var prevBenifitialOwner = "1";
var errorsForBenifitialOwnersHasBeenListed = false;
//Adjust the error messages and the links
var sessionTagIndex = window.location.href.indexOf("xsessiontag");
var getUrl = window.location.href.substring(0, sessionTagIndex) + "documentName=" + documentName + "&pageNumber=" + pageNumber;
$.get(getUrl, function(data) {
var trimmedData = data.substring(data.indexOf("<form"), data.indexOf("</form>") + 8);
var $DOM = $($.parseHTML(trimmedData));
//Update the links in the list of errors
$.each($container.find("ul li a"), function(index) {
var fieldID = $(this).attr("href").split("#").pop().replace(".", "\\.");
var $field = $DOM.find("#"+fieldID);
if($field != undefined && $field.hasClass("control-validation")) {
//Update error text
var $correspondingLegend = $field.parent().siblings("legend");
$(this).text($correspondingLegend.text() + " (" + $(this).text() + ")");
//Make an exception for the question about PEP with
//pep-text-container_legend (company only)
if ($correspondingLegend.attr("id") == "pep-text-container_legend") {
var $PEPLegendLink = $(this);
var getXMLUrl = window.location.href.replace("htmlViewer", "xmlData");
//Gets the xml data from the server
//The dataType is set to "text" in order for
//it to work in Internet Explorer (at least IE11)
//The data is later parsed as xml, which works fine.
//Note that "cache" is set to "false"
//Otherwise IE will cache the data returned from this request
$.ajax({
type: "GET",
url: getXMLUrl,
dataType: "text", //IE
cache : false, //IE
xhr: function() {
return window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest();
},
success: function (data) {
var xmlData = $.parseXML(data);
var xmlNode = xmlData.getElementsByTagName("aktorer-i-bedriften")[0];
var aktorerIBedriftenChilds = xmlNode ? xmlNode.childNodes : [];
for (var i=0; i < aktorerIBedriftenChilds.length; i++) {
//Update the text of the error message (the company does not have any benifital owners)
if (aktorerIBedriftenChilds[i].nodeName == "reelle-rettighetshavere" && aktorerIBedriftenChilds[i].getAttribute("har") == "nei") {
$PEPLegendLink.text($PEPLegendLink.text().replace("reelle rettighetshavere, ", ""));
}
}
}
});
}
//Update the href so that the input field (label) can be scrolled into view
$(this).attr("href", $(this).attr("href").split("#")[0] + "#" + $correspondingLegend.attr("id"));
//Add som margin-top if needed
if (errorsForBenifitialOwnersHasBeenListed) {
$(this).parent().css("margin-top", "3em");
errorsForBenifitialOwnersHasBeenListed = false;
}
}
//Adjust link to file upload error
else if (isFileUpload($(this).text())) {
$(this).attr("href", $(this).attr("href").split("#")[0] + "#fullmakt-container");
}
//Adjust text and link for benifital owners
else if (isBenifitialOwners(heading)) {
//Update error text
var currentBenifitialOwner = $(this).attr("href").split("_").pop().trim();
var text = "Reell rettighetshaver";
if ($("html").attr("lang").toLowerCase() == "se") {
text = "Reell rättighetshavare";
}
else if ($("html").attr("lang").toLowerCase() == "en") {
text = "Beneficial owner";
}
prefixBenifitialOwners = text + " " + currentBenifitialOwner + " - ";
$(this).prepend(prefixBenifitialOwners);
//Update the href so that it can be scrolled into view nicely
//By making sure the label of the input is shown
$(this).attr("href", $(this).attr("href").split("#")[0] + "#" + "container-" + $(this).attr("href").split("#").pop());
//Add som margin-top if needed
if (currentBenifitialOwner != prevBenifitialOwner) {
$(this).parent().css("margin-top", "3em");
}
prevBenifitialOwner = currentBenifitialOwner;
errorsForBenifitialOwnersHasBeenListed = true;
}
//Adjust link to input fields (so that the label is also scrolled into view, not just the input itself)
else if ($field.length) {
//Update the href so that it can be scrolled into view nicely
//By making sure the label of the input is shown
var $correspondingLabel = $field.parent().siblings(".label_text");
$(this).attr("href", $(this).attr("href").split("#")[0] + "#" + $correspondingLabel.attr("id"));
}
});
});
});
//Adjust som more auto generated HTML mark-up
var h3Text = "Vi må be deg om å rette opp noen feil";
if ($("html").attr("lang").toLowerCase() == "se") {
h3Text = "Vi måste tyvärr be dig om att rätta några fel";
}
else if ($("html").attr("lang").toLowerCase() == "en") {
h3Text = "We must ask you to correct a couple of errors";
}
$(".error-summary").prepend("<h3>" + h3Text + "</h3>");
$(".error-summary").show();
//Functions used to identify specific nodes in the server response
function isFileUpload(text) {
if ($("html").attr("lang").toLowerCase() == "se") {
return text.toLowerCase().indexOf("ladda upp fullmakt") > -1;
}
else if ($("html").attr("lang").toLowerCase() == "en") {
return text.toLowerCase().indexOf("upload power of attorney") > -1;
}
return text.toLowerCase().indexOf("laste opp fullmakt") > -1;
}
function isBenifitialOwners(text) {
if ($("html").attr("lang").toLowerCase() == "se") {
return text.toLowerCase().indexOf("aktörer i verksamheten") > -1;
}
else if ($("html").attr("lang").toLowerCase() == "en") {
return text.toLowerCase().indexOf("stakeholders") > -1;
}
return text.toLowerCase().indexOf("aktører i bedriften") > -1;
}
}
//Adjusts error messages that has class "trim-errormsg"
//This is to present shorter error messages on submit than in
//the error list presented at the end.
//For example "Name is required" becomes "Required" when
//displayed beneath the input label "Name"
//But is shown as "Name is required" in the error list in the summary
function adjustErrorMessages() {
$.each($(".trim-errormsg .digiforms_validation_message"), function() {
var newText = $(this).text().split("må").pop();
$(this).text("Må" + newText);
});
}
//Appends WAI-ARIA landmarks for autogenerated elements
function appendAriaAttributesForPageSections() {
//Landmarks for header
$(".header").attr("role", "banner");
//Landmarks for main
$("#main-content").attr("role", "main");
var $mainContentLabelledby = $("#main-content_legend");
if ($mainContentLabelledby.length == 0) {
$mainContentLabelledby = $("#main-content_heading");
}
$("#main-content").attr("aria-labelledby", $mainContentLabelledby.attr("id"));
//Bottom nav
$(".next-prev-nav").attr("role", "navigation");
if ($("html").attr("lang").toLowerCase() == "se") {
$(".next-prev-nav").attr("aria-label", "Föregående / Nästa");
}
else if ($("html").attr("lang").toLowerCase() == "en") {
$(".next-prev-nav").attr("aria-label", "Previous / Next");
}
else {
$(".next-prev-nav").attr("aria-label", "Forrige / Neste");
}
}
//Toggles text on change
function changeTextOnChange() {
//Adjusts the (auto generated) HTML for the specific PEP question
var $togglePEPText = $("#pep-text-container").find("fieldset legend:first");
if ($("html").attr("lang").toLowerCase() == "se") {
$togglePEPText.text("Är någon av verksamhetens ");
$togglePEPText.append('<span class="text-toggle">reelle rättighetshavare, </span>styrelseledamöter, vd eller kontaktperson(er) en person i ”Politisk utsatt ställning” (PEP)?');
}
else if ($("html").attr("lang").toLowerCase() == "en") {
$togglePEPText.text("Is any of the ");
$togglePEPText.append('<span class="text-toggle">beneficial owners, </span>board members, CEO or contact person(s) a Politically Exposed Person (PEP)?');
}
else {
$togglePEPText.text("Er noen av foretakets ");
$togglePEPText.append('<span class="text-toggle">reelle rettighetshavere, </span>styremedlemmer, daglig leder eller kontaktperson(er) en Politisk Eksponert Person (PEP)?');
}
$togglePEPText.append('<span class="asterix" aria-hidden="true"> *</span>');
//Toggles text identified by the id suffix of the element itself
var toggle = function($toggleElement) {
var idSplit = $toggleElement.attr("id").split("toggles-");
var toggles = idSplit.pop().trim();
var action = idSplit[0].replace("-", "").trim();
//Toggle text (show/hide)
if ($toggleElement.is(":checked")) {
if (action == "show") {
$("#" + toggles + " .text-toggle").show();
}
else if (action == "hide") {
$("#" + toggles + " .text-toggle").hide();
}
}
}
//Get all elements that should toggle text on change
var $togglesText = $(".toggles-text-on-change");
//Init
$.each($togglesText, function() {
toggle($(this));
});
//Add event handler
$togglesText.on("change", function() {
toggle($(this));
});
}
//Adjusts auto generated HTML mark-up
function adjustAutoGeneratedElements() {
//Fix duplicate id:s
//Recursive function that updates the id of an element and all its children
var updateDuplicateIds = function(elements) {
$.each(elements, function(i) {
$(this).attr("id", $(this).parent().attr("id") + $(this).attr("id") + i)
if ($(this).children().length > 0) {
updateDuplicateIds($(this).children());
}
});
}
//Append asterixes
appendAsterixToMandatoryFields();
//Append attributes to number-inputs
appendAttributesToNumberInputs();
//Make adjustments to the error list on the last page
adjustErrorMessageList();
//Make adjustments to the error list on the last page
adjustErrorMessages();
//Add WAI-aria landmarks to page sections
appendAriaAttributesForPageSections();
//Toggles a text when
changeTextOnChange();
}
//Appends asterixes to mandatory fieldsets
//- labels for checkboxes and radio buttons
function appendAsterixToMandatoryFields() {
$(".mandatory > fieldset > legend").append('<span class="asterix" aria-hidden="true"> *</span>');
}
//Used to format phonenumber
//Determines the index of the auto filled country code
function getSplitIndexForPhoneNumber(val) {
return val.indexOf(") ") < 0 ?
(val.indexOf(")") < 0 ?
0 : val.indexOf(")")) + 1
: val.indexOf(") ") + 2;
}
//Start loading animation in input
function startLoadingAnimation($input) {
$input.attr("disabled", "disabled");
$input.parent().addClass("loading");
}
//End loading animation in input
function endLoadingAnimation($input) {
$input.removeAttr("disabled", "disabled");
$input.parent().removeClass("loading");
}
//Auto fills postal code using the API from bring.no
function autoFillPostalCode() {
//Bind on keyup event, so that city/place is autofilled based on postal code
$(".input-postalcode").on("keyup change", function() {
var $inputPanel = $(this).closest(".input-panel");
var $selectLand = $inputPanel.find(".select-land").first();
if($selectLand) {
var countryCode = $selectLand.val().toLowerCase();
var postalCode = $(this).val();
var $inputPlace = $inputPanel.find(".input-place").first();
$.getJSON("https://fraktguide.bring.no/fraktguide/api/postalCode.json?country=" + countryCode + "&pnr=" + postalCode, function(json){
if(json.valid && json.result) {
//Autofill with result from API
$inputPlace.val(json.result);
}
});
}
});
//Toggles pattern (used to bring up numeric keypad on iOS mobile)
//for the postal code input
var togglePattern = function($sel) {
var $formGroup = $sel.closest(".form-group");
var $postalCodeInputs = $formGroup.find(".input-postalcode");
var countryCode = $sel.val().toUpperCase();
//Here is a manual selction of countries (the ones that we assume are most common)
//that we add the patterns for.
//In reality most countries have numeric postal codes
//But since these tings sometimes change over time
//(it is proposed that all contries start using alpha numerical postal codes)
//It has been done this way for now (just to be safe)
if (countryCode == "NO" || countryCode == "SJ" || countryCode == "SE" || countryCode == "DK" || countryCode == "FI" || countryCode == "DE" || countryCode == "FR" || countryCode == "LI" || countryCode == "EE" || countryCode == "LV") {
$postalCodeInputs.attr("pattern", "[0-9]*"); //iOS
$postalCodeInputs.attr("inputmode", "numeric"); //Android
}
else {
$postalCodeInputs.removeAttr("pattern"); //iOS
$postalCodeInputs.removeAttr("inputmode"); //Android
}
}
//Bind on change event, so that pattern on iOS mobile can be updated according to
//postal code format.
$(".select-land").on("change", function() {
togglePattern($(this));
});
//Toggle according to current country
$.each($(".select-land"), function() {
togglePattern($(this));
});
}
//Auto fills the country calling code using the API provided by restcountries.eu
function autoFillCountryCallingCode() {
var setCountryCode = function($selects) {
if(!$selects.length) return;
$.each($selects, function() {
var $sel = $(this);
var code = $sel.val().toLowerCase();
$.getJSON("https://restcountries.eu/rest/v2/alpha/" + code, function(result){
if (result.status != 400 && result.status != 404) {
//Prepend country code to all phone inputs in the current input-panel
var $formGroup = $sel.closest(".form-group");
var $phoneInputs = $formGroup.find('input[type="tel"]');
$.each($phoneInputs, function() {
var val = $(this).val()
var valSplit = val.split(" ");
var replaceCurrentCode = valSplit.length <= 2 && (valSplit.length == 2 ? valSplit.pop() == "" : true);
//When input is empty or only country code is entered
if (val.length == 0 || replaceCurrentCode) {
$(this).val("+" + result.callingCodes[0] + " ");
}
});
}
});
});
};
//Bind on change event, so that country code is updated
$(".select-land").on("change", function() {
setCountryCode($(this));
});
//Update the country code for the country currently selected
setCountryCode($(".select-land"));
}
//Auto fills the country calling code using the API provided by brreg.no
function checkAndAutoFillFromOrgNr($orgNrInput) {