PageSourceSearch

https://mtp.aklaborers.com/MTPweb/js/site.js?v=9qhDb_Kn4F8d9l3TStDm0T6TlOhUr27KXiUc5Bqqon0

js aklaborers.com collected 2026-09-28 10:04:34 UTC 207,577 bytes, 4,935 lines download raw bytes

1var elapsedSecondsForAutoLogout = 0;
2var elapsedSecondsForClearingLoginForm = 0;
3var autoLogoutTimeInSeconds = 0;
4var maximumTimeInSecondsBeforeClearingLoginForm = 0;
5var timeAtStartOfWaitOperation = 0;
6var isScrolling = false;
7
8window.dataLayer = window.dataLayer || [];
9
10(function ($) {
11    $.fn.clearForm = function (options) {
12        // This is the easiest way to have default options.
13        var settings = $.extend({
14            // These are the defaults.
15            formId: this.closest('form')
16
17        }, options);
18
19        var $form = $(settings.formId);
20
21        //reset jQuery Validate's internals
22        $form.validate().resetForm();
23
24        //reset unobtrusive validation summary, if it exists
25        $form.find("[data-valmsg-summary=true]")
26            .removeClass("validation-summary-errors")
27            .addClass("validation-summary-valid")
28            .find("ul").empty();
29
30        //reset unobtrusive field level, if it exists
31        $form.find("[data-valmsg-replace]")
32            .removeClass("field-validation-error")
33            .addClass("field-validation-valid")
34            .empty();
35
36        return $form;
37    };
38}(jQuery));
39
40(function(){
41    var originalAddClassMethod = jQuery.fn.addClass;
42
43    jQuery.fn.addClass = function(){
44        // Execute the original method.
45        var result = originalAddClassMethod.apply( this, arguments );
46
47        // trigger a custom event
48        jQuery(this).trigger('cssClassChanged');
49
50        // return the original result
51        return result;
52    }
53
54    var originalRemoveClassMethod = jQuery.fn.removeClass;
55
56    jQuery.fn.removeClass = function(){
57        // Execute the original method.
58        var result = originalRemoveClassMethod.apply( this, arguments );
59
60        // trigger a custom event
61        jQuery(this).trigger('cssClassChanged');
62
63        // return the original result
64        return result;
65    }
66})();
67
68function nth(n){return['st','nd','rd'][((n+90)%100-10)%10-1]||'th'}
69
70function isEmptyOrSpaces(str){
71    return str === null || str == undefined || str.match(/^ *$/) !== null;
72}
73
74function getAntiForgeryToken() {
75    return $('input[name="AntiforgeryToken"]').val();
76};
77
78$.ajaxSetup({
79    beforeSend: function (xhr) {
80        var token = getAntiForgeryToken();
81        if (token) {
82            xhr.setRequestHeader('X-CSRF-TOKEN', token);
83        }
84    }
85});
86
87function recaptchaCallback(token) {
88    $('#captcha-validation-shim').val(token);
89 
90    if (token && token.length > 0) {
91        $('#captcha-validation-shim').removeClass('input-validation-error');
92    } else {
93        $('#captcha-validation-shim').addClass('input-validation-error');
94    }
95};
96
97function isValidHttpUrl(string) {
98  let url;
99  
100  try {
101    url = new URL(string);
102  } catch (_) {
103    return false;  
104  }
105
106  return url.protocol === "http:" || url.protocol === "https:";
107}
108
109function recaptchaExpiredCallback() {
110    $('#captcha-validation-shim').val('');
111    $('#captcha-validation-shim').addClass('input-validation-error');
112}
113
114function gtag() { dataLayer.push(arguments); }
115
116var qs = (function(a) {
117    if (a === '') return {};
118    var b = {};
119    for (var i = 0; i < a.length; ++i)
120    {
121        var p=a[i].split('=', 2);
122        if (p.length === 1)
123            b[p[0]] = '';
124        else
125            b[p[0]] = decodeURIComponent(p[1].replace(/\+/g, ' '));
126    }
127    return b;
128})(window.location.search.substring(1).split('&'));
129
130$.fn.scrollView = function(offset) {
131    return this.each(function() {
132        $('html, body').animate({
133                scrollTop: $(this).offset().top + (offset || 0)
134            },
135            400);
136    });
137};
138
139function isElementInViewport (el) {
140
141    // Special bonus for those using jQuery
142    if (typeof jQuery === "function" && el instanceof jQuery) {
143        el = el[0];
144    }
145
146    var rect = el.getBoundingClientRect();
147
148    return (
149        rect.top >= 0 &&
150            rect.left >= 0 &&
151            rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /* or $(window).height() */
152            rect.right <= (window.innerWidth || document.documentElement.clientWidth) /* or $(window).width() */
153    );
154}
155
156var scrollTimer = null;
157$(window).scroll(function () {
158    isScrolling = true;
159    if (scrollTimer !== null) {
160        clearTimeout(scrollTimer);
161    }
162    scrollTimer = setTimeout(function () {
163        isScrolling = false;
164    }, 500);
165});
166
167function parseQueryString(str) {
168    const vars = [];
169    const arr = str.split('&');
170    var pair;
171    for (let i = 0; i < arr.length; i++) {
172        pair = arr[i].split('=');
173        vars.push(pair[0]);
174        vars[pair[0]] = decodeURIComponent(pair[1]);
175    }
176    return vars;
177}
178
179function addParam(urlString, param, value) {
180    try {
181        const url = new URL(urlString, window.location.origin);
182        url.searchParams.set(param, value);
183        return url.toString();
184    } catch (e) {
185        console.error("Invalid URL:", e);
186        return urlString;
187    }
188}
189
190function FormatAsBytes(value) {
191    if (value < 1024)
192        return value + " bytes";
193    if (value < 1024 * 1024)
194        return (value / 1024).toFixed(1) + " KB";
195    if (value < 1024 * 1024 * 1024)
196        return (value / (1024 * 1024)).toFixed(1) + " MB";
197    if (value < 1024 * 1024 * 1024 * 1024)
198        return (value / (1024 * 1024 * 1024)).toFixed(1) + " GB";
199
200    return value < 1024 * 1024 * 1024 * 1024 * 1024 ?
201        ((value / (1024 * 1024 * 1024 * 1024)).toFixed(1) + " GB") :
202        (value + " bytes");
203}
204
205$(document)
206    .bind("pageshow",
207        function() {
208            $(":text:visible:enabled:first").focus();
209
210
211        });
212
213$(document)
214    .bind("pageinit",
215        function() {
216          
217            $("[data-enter-clicks-id]")
218                .each(function() {
219                    var button = $("#" + $(this).attr("data-enter-clicks-id"));
220
221                    if (button !== undefined) {
222                        $(this)
223                            .keydown(function(event) {
224                                if (event.which === 13)
225                                    button.click();
226                            });
227                    }
228                });
229
230            
231        });
232
233$(document)
234    .ready(function () {
235        $("a[data-button-id]").each(function() {
236            var link = $(this);
237            var button = $("#" + $(link).attr("data-button-id"));
238            if (button !== undefined) {
239                $(link).on('click', function(event) {
240                    event.preventDefault();
241
242                    $(this).clone(true).insertAfter($(this));
243                    $(this).remove();
244
245                    $(button).trigger('click');
246                });
247            }
248        });
249
250        $('#class-calendar').each(function () {
251            $(this).data("selected-course-type", qs['courseType']);
252
253            window.history.replaceState({}, document.title, window.location.href.split('?')[0]);
254        });
255
256        var lastWindowWidth = $(window).width();
257
258
259        autoLogoutTimeInSeconds = parseInt($("#auto-logout-time-in-seconds").val());
260        maximumTimeInSecondsBeforeClearingLoginForm = parseInt($("#maximum-time-in-seconds-before-clearing-login-form")
261            .val());
262
263        $("#login-username-field").keypress(function () { resetClearingLoginFormCounter(); });
264        $("#login-password-field").keypress(function () { resetClearingLoginFormCounter(); });
265        $("#one-digit").click(function (event) {
266            event.preventDefault();
267            loginUsernameAddDigit("1");
268        });
269        $("#two-digit").click(function (event) {
270            event.preventDefault();
271            loginUsernameAddDigit("2");
272        });
273        $("#three-digit").click(function (event) {
274            event.preventDefault();
275            loginUsernameAddDigit("3");
276        });
277        $("#four-digit").click(function (event) {
278            event.preventDefault();
279            loginUsernameAddDigit("4");
280        });
281        $("#five-digit").click(function (event) {
282            event.preventDefault();
283            loginUsernameAddDigit("5");
284        });
285        $("#six-digit").click(function (event) {
286            event.preventDefault();
287            loginUsernameAddDigit("6");
288        });
289        $("#seven-digit").click(function (event) {
290            event.preventDefault();
291            loginUsernameAddDigit("7");
292        });
293        $("#eight-digit").click(function (event) {
294            event.preventDefault();
295            loginUsernameAddDigit("8");
296        });
297        $("#nine-digit").click(function (event) {
298            event.preventDefault();
299            loginUsernameAddDigit("9");
300        });
301        $("#zero-digit").click(function (event) {
302            event.preventDefault();
303            loginUsernameAddDigit("0");
304        });
305        $("#dash-digit").click(function (event) {
306            event.preventDefault();
307            loginUsernameAddDigit("-");
308        });
309        $("#back-digit").click(function (event) {
310            event.preventDefault();
311            loginUsernameBack();
312        });
313
314        $("#review-balances-due-link")
315            .click(function (event) {
316                event.preventDefault();
317
318                var url = $(this).attr("data-url");
319                if (url !== null) {
320                    window.open(url,
321                        "mtpmybalances",
322                        "toolbar=0, location=0, directories=0, status=0, menubar=0,scrollbars=1,copyhistory=0, resizable=1, width=980, height=325");
323                }
324            });
325
326        $("#monthly-apprentice-report-table input.mtp-hours-field")
327            .change(function () {
328                var val = filterFloat($(this).val());
329                if (!isNaN(val)) {
330                    var s = val.toFixed(3);
331                    $(this).val(s);
332                }
333            });
334
335        $("#monthly-apprentice-report-table input.mtp-hours-field")
336            .blur(function () {
337                var process = $(this).data("process");
338
339                var sum = 0.0;
340                $("#monthly-apprentice-report-table input.mtp-hours-field[data-process='" + process + "']")
341                    .each(function () {
342                        var val = filterFloat($(this).val());
343                        if (!isNaN(val)) {
344                            sum += val;
345                        }
346                    });
347
348                $("#monthly-apprentice-report-table input.mtp-hours-total[data-process='" + process + "']")
349                    .each(function () {
350                        var s = sum.toFixed(3);
351                        $(this).val(s);
352                    });
353
354                $("#monthly-apprentice-report-table input.mtp-hours-total[data-day]")
355                    .each(function () {
356                        var s = 0;
357                        $("#monthly-apprentice-report-table input.mtp-hours-field[data-day='" + $(this).data('day') + "']")
358                            .each(function () {
359                                var val = filterFloat($(this).val());
360                                if (!isNaN(val)) {
361                                    s += val;
362                                }
363                            });
364                        $(this).val(s.toFixed(3));
365                    });
366
367                var grandTotal = 0.0;
368                $("#monthly-apprentice-report-table input.mtp-hours-field[data-process]")
369                    .each(function () {
370                        var val = filterFloat($(this).val());
371                        if (!isNaN(val)) {
372                            grandTotal += val;
373                        }
374                    });
375
376                $("#edit-monthly-apprentice-report-form input.mtp-hours-total[data-process='all']")
377                    .each(function () {
378                        var s = grandTotal.toFixed(3);
379                        $(this).val(s);
380                    });
381
382            });
383
384        $('#monthlyApprenticeReportAddEditMemberCommentsDialog #buttonAddEdit').click(function (e) {
385            e.preventDefault();
386
387            let comments = $('#addEditMemberComments').val();
388            let button = $('#monthlyApprenticeReportAddEditMemberCommentsDialog').data('source-button');
389            let id = $(button).data('member-comments-input-id');
390
391            $(button).data('member-comments', comments);
392            $('#' + id).val(comments);
393
394            var hasComment = (comments && comments.trim());
395
396            if (hasComment) {
397                $(button).find("[data-member-comments-icon='edit']").removeClass('d-none');
398                $(button).find($("[data-member-comments-icon='add']")).addClass('d-none');
399            }
400            else {
401                $(button).find("[data-member-comments-icon='edit']").addClass('d-none');
402                $(button).find($("[data-member-comments-icon='add']")).removeClass('d-none');
403            }
404
405            $('#monthlyApprenticeReportAddEditMemberCommentsDialog').modal('hide');
406        });
407
408        $('#monthly-apprentice-report-table button.mtp-monthly-apprentice-report-edit-member-comment').click(function (e) {
409            e.preventDefault();
410
411            let comments = $(this).data('member-comments');
412
413            $('#addEditMemberComments').val(comments);
414            $('#monthlyApprenticeReportAddEditMemberCommentsDialog').data("source-button", $(this));
415            $('#monthlyApprenticeReportAddEditMemberCommentsDialog').modal('show');
416
417        });
418
419        $('#monthly-apprentice-report-table .mtp-monthly-apprentice-report-view-member-comment').click(function (event) {
420            event.preventDefault();
421
422            $('#monthlyApprenticeReportViewMemberCommentsDialog .modal
422-body').text($(this).data('member-comments'))
423            $('#monthlyApprenticeReportViewMemberCommentsDialog').modal('show');
424        });
425
426        $('.mtp-mobile-list li a').addClass("flex-grow-1 align-self-center").after(function () {
427            var a = document.createElement("a");
428            $(a).attr("href", $(this).attr("href"));
429            Object.assign(a.dataset, this.dataset);
430            $(a).addClass("d-block d-md-none align-self-center ml-1 py-3");
431            $(a).append("<div ><span class='fas fa-chevron-circle-right'></span></div>");
432            return a;
433        });
434        $('.mtp-mobile-list li').addClass("mtp-d-mtp-list-item px-3 p-md-0 ")
435            .wrapInner("<div class='d-flex flex-row'></div>");
436        $('.mtp-mobile-list').addClass("d-block");
437        $('.mtp-mobile').addClass("d-block");
438
439        $('#mtp-main-menu').on('show.bs.collapse',
440            function () {
441                $(window).scrollTop(0);
442
443                $('body').removeClass("mtp-adjust-padding-for-mobile-page-navigator");
444
445                $('#mtp-content-overlay').css("display", "block");
446
447                $('#mtp-content-overlay').fadeTo("fast", 0.5);
448
449                $('.mtp-mobile-page-navigator').animate({ opacity: 0 },
450                    "fast",
451                    function () {
452                        $('.mtp-mobile-page-navigator').addClass("mtp-d-none");
453                    });
454
455            });
456
457        $('#mtp-main-menu').on('hide.bs.collapse',
458            function () {
459                $(window).scrollTop(0);
460
461                $('.mtp-mobile-page-navigator').removeClass("mtp-d-none");
462                $('.mtp-mobile-page-navigator').animate({ opacity: 1 },
463                    "fast",
464                    function () {
465                        $('body').addClass("mtp-adjust-padding-for-mobile-page-navigator");
466                    });
467
468                $('#mtp-content-overlay').fadeTo("fast", 0);
469
470                $('#mtp-content-overlay').css("display", "none");
471            });
472
473        if ($('.mtp-mobile-page-navigator').length > 0) {
474            $('body').addClass("mtp-adjust-padding-for-mobile-page-navigator");
475        }
476
477        $('#mtp-content-overlay').click(function () {
478            $('#mtp-main-menu').collapse('hide');
479        });
480
481        $('.mtp-hide-on-click').click(function () {
482            $(window).scrollTop(0);
483
484            $($(this).data("hide-target")).fadeOut("fast");
485            $($(this).data("show-target")).removeClass("d-none");
486
487            $('.mtp-mobile-page-navigator').animate({ opacity: 0 },
488                "fast",
489                function () {
490                    $('.mtp-mobile-page-navigator').addClass("mtp-d-none");
491                    $('body').removeClass("mtp-adjust-padding-for-mobile-page-navigator");
492                });
493        });
494
495        $(window).on('resize',
496            function () {
497                var currentWindowWidth = $(window).width();
498
499                if (currentWindowWidth > lastWindowWidth) {
500                    $('#mtp-main-menu').collapse('hide');
501                }
502
503                lastWindowWidth = currentWindowWidth;
504
505                resizeElements();
506            });
507
508        $(".modal.mtp-dialog-show-onload").modal('show');
509
510        $("a[data-content-type^='audio/']").after(function () {
511        });
512
513        $("a[data-content-type^='audio/']")
514            .each(function () {
515                var contentType = $(this).attr("data-content-type");
516                var myAudio = document.createElement('audio');
517
518                if (myAudio.canPlayType(contentType)) {
519                    var src = $(this).attr("href");
520
521                    $(this)
522                        .click(function (event) {
523                            event.preventDefault();
524
525                            $("audio").removeAttr('src');
526                            myAudio.load();
527
528                            $(".inline-audio-control").closest("li").find(".fa-chevron-circle-down")
529                                .removeClass("fa-chevron-circle-down").addClass("fa-chevron-circle-right");
530                            $(".inline-audio-control").remove();
531
532                            $(this).closest("li").find(".fa-chevron-circle-right")
533                                .removeClass("fa-chevron-circle-right")
534                                .addClass("fa-chevron-circle-down");
535
536                            myAudio.setAttribute('src', src);
537                            myAudio.setAttribute('preload', 'metadata');
538                            myAudio.setAttribute('controls', 'controls');
539
540                            var myDiv = document.createElement('div');
541                            $(myDiv).addClass("inline-audio-control");
542                            $(myDiv).append($(myAudio));
543
544                            $(myDiv).insertAfter($(this).parent());
545                            myAudio.play();
546                        });
547                }
548            });
549
550        $(".mtp-alert-auto-close").each(function () {
551            var element = $(this);
552
553            setTimeout(function () {
554                element.alert('close');
555            },
556                5000);
557        });
558
559        $(".mtp-scroll-to-target").click(function (event) {
560            event.preventDefault();
561            event.stopImmediatePropagation();
562
563            $($(this).data("target")).first().scrollView(-$('#mtp-site-header').height() - 24);
564        });
565
566        $(".mtp-mobile-header-button:not(.mtp-mobile-header-button-placed)").each(function () {
567            var element = $(this);
568            $('#' + $(this).data("target-id")).first().each(function () {
569                var target = $(this);
570
571                element.addClass("mtp-mobile-header-button-placed");
572                element.removeClass("d-none");
573
574                target.prepend(element);
575            });
576        });
577
578        $(".mtp-mobile-header-button-placed").each(function () {
579            var totalButtonsOnLeft = $(this).parent().children().filter(function () {
580                return $(this).hasClass("order-1") ||
581                    $(this).hasClass("order-2") ||
582                    $(this).hasClass("order-3") ||
583                    $(this).hasClass("order-4") ||
584                    $(this).hasClass("order-5");
585            }).length;
586            var totalButtonsOnRight = $(this).parent().children().filter(function () {
587                return $(this).hasClass("order-7") ||
588                    $(this).hasClass("order-8") ||
589                    $(this).hasClass("order-9") ||
590                    $(this).hasClass("order-10") ||
591                    $(this).hasClass("order-11") ||
592                    $(this).hasClass("order-12");
593            }).length;
594
595            while (totalButtonsOnLeft < totalButtonsOnRight) {
596                ++totalButtonsOnLeft;
597                const clone = $(this).clone();
598                clone.css("visibility", "hidden");
599                clone.removeClass(
600                    "order-1 order-2 order-3 order-4 order-5 order-6 order-7 order-8 order-9 order-10 order-11 order-12");
601                clone.addClass("order-5");
602                $(this).after(clone);
603            }
604
605            while (totalButtonsOnRight < totalButtonsOnLeft) {
606                ++totalButtonsOnRight;
607                const clone = $(this).clone();
608                clone.css("visibility", "hidden");
609                clone.removeClass(
610                    "order-1 order-2 order-3 order-4 order-5 order-6 order-7 order-8 order-9 order-10 order-11 order-12");
611                clone.addClass("order-7");
612                $(this).after(clone);
613            }
614        });
615
616        // Add extra padding when trade changes 
617        $("#availability-list-grid").each(function () {
618            var lastTrade = $("tbody tr td:nth-child(3)", $(this)).first().text();
619            $("tbody tr", $(this)).each(function () {
620                var thisTrade = $("td:nth-child(3)", $(this)).first().text();
621                if (thisTrade !== lastTrade) {
622                    lastTrade = thisTrade;
623                    $("td", $(this)).removeClass("p-md-1").addClass("pt-md-4 px-md-1 pb-md-1");
624                }
625            });
626        });
627
628        $(".mtp-print-button").click(function (event) {
629            event.preventDefault();
630
631            printPage($(this).data('print-url'));
632        });
633
634        $("[data-click-target-id]").click(function (event) {
635            event.preventDefault();
636            $('#' + $(this).data("click-target-id")).click();
637        });
638
639        $(".mtp-payment-types-list").change(function () {
640            var paymentTypeId = $(this).val();
641
642            let supportedPaymentTypeIds = String($('#make-payment-form').data('supported-payment-type-ids-for-number-of-months-calculation') || '');
643            var isSupported = supportedPaymentTypeIds.split(',').includes(paymentTypeId);
644
645            var target = $($(this).data('calculator-target'));
646
647            if (isSupported)
648                target.removeClass("d-none");
649            else
650                target.addClass("d-none");
651        });
652
653        $(".mtp-payment-type-amount").on('change keyup paste', function () {
654            var control = $(this);
655
656            var isDisabled = $(control).prop('disabled');
657
658            if (!isDisabled) {
659                var formRow = $(control).closest('.form-row');
660
661                var container = $(formRow).parent();
662
663                var form = $(control).closest('form');
664
665                if ($(formRow).next('.form-row').filter(function () {
666                    return $(this).find('.mtp-payment-type-amount').length > 0;
667                }).length == 0) {
668                    var formRowCopy = $(formRow).clone(true, true);
669                    var paymentIndex = parseInt(formRowCopy.data('payment-index'));
670                    var paymentIndexCopy = paymentIndex + 1;
671
672                    $(formRowCopy).find('input.mtp-payment-type-amount, select.mtp-payment-types-list').each(function () {
673                        $(this).attr('name', $(this).attr('name').replace(paymentIndex.toString(), paymentIndexCopy.toString()));
674                        $(this).attr('id', $(this).attr('id').replace(paymentIndex.toString(), paymentIndexCopy.toString()));
675                        $(this).attr('tabindex', 0);
676                    });
677
678                    $(formRowCopy).find('select.mtp-payment-types-list').each(function () {
679                        $(this).attr('data-calculator-target', $(this).attr('data-calculator-target').replace(paymentIndex.toString(), paymentIndexCopy.toString()));
680
681                        $('option:selected', $(this)).prop("selected", false);
682                        $('option:selected', $(this)).prop("selected", "selected");
683                    });
684
685                    $(formRowCopy).find('input.mtp-payment-type-amount').each(function () {
686                        $(this).val('', '');
687                    });
688
689                    $(formRowCopy).find('.mtp-calculate-dues-button').each(function () {
690                        $(this).attr('id', $(this).attr('id').replace(paymentIndex.toString(), paymentIndexCopy.toString()));
691                        $(this).attr('data-amount-target', $(this).attr('data-amount-target').replace(paymentIndex.toString(), paymentIndexCopy.toString()));
692                        $(this).attr('data-type-target', $(this).attr('data-type-target').replace(paymentIndex.toString(), paymentIndexCopy.toString()));
693                    });
694
695                    $(formRowCopy).find('[data-valmsg-for]').each(function () {
696                        $(this).attr('data-valmsg-for', $(this).attr('data-valmsg-for').replace(paymentIndex.toString(), paymentIndexCopy.toString()));
697                    });
698
699                    formRowCopy.data('payment-index', paymentIndexCopy);
700                    formRowCopy.attr('data-payment-index', paymentIndexCopy);
701
702                    formRowCopy.appendTo(container);
703
704                    $(form)
705                        .removeData("validator")
706                        .removeData("unobtrusiveValidation");
707
708                    $.validator
709                        .unobtrusive
710                        .parse(form);
711
712                    $(formRowCopy).find('select.mtp-payment-types-l
712ist').trigger('change');
713                }
714            }
715        });
716
717        $("#make-payment-form input[name='EstimatePaymentTypesWithMonthlyBillingFrequencyWhenEstimatingMonthlyDues'][value='True']:first").each(function () { 
718            if($("#make-payment-form[data-is-post='False']").length > 0) {
719                setTimeout(function() {
720                    $('.mtp-calculate-dues-button:first').trigger('click');
721                }, 50);
722            }
723        });
724
725        $(".mtp-calculate-dues-button").click(function (event) {
726            event.preventDefault();
727
728            $('#calculate-months-selected').val("1");
729            $('#calculate-dues-dialog').data("payment-type-id", $($(this).data("type-target")).val());
730            $('#calculate-dues-dialog').data("amount-target", $(this).data("amount-target"));
731
732            $('#calculate-dues-dialog').find("button").prop("disabled", false);
733            $('#calculate-months-selected').prop("disabled", false);
734
735            $('#calculate-dues-dialog').find('.mtp-wait-message').addClass("d-none");
736            $('#calculate-dues-dialog').find('.mtp-input-message').removeClass("d-none");
737            $('#calculate-dues-dialog').find('.mtp-buttons').removeClass("d-none");
738
739            $('#calculate-dues-dialog').modal();
740        });
741
742        $("#calculate-dues-ok-button").click(function (event) {
743            event.preventDefault();
744            var months = $('#calculate-months-selected').val();
745            var paymentTypeId = $('#calculate-dues-dialog').data("payment-type-id");
746            var amountTarget = $($('#calculate-dues-dialog').data("amount-target"));
747
748            var timeAtStartOfWaitOperation = Date.now();
749
750            $('#calculate-dues-dialog').find("button").prop("disabled", true);
751            $('#calculate-months-selected').prop("disabled", true);
752            $('#calculate-dues-dialog').find('.mtp-wait-message').removeClass("d-none");
753            $('#calculate-dues-dialog').find('.mtp-input-message').addClass("d-none");
754            $('#calculate-dues-dialog').find('.mtp-buttons').addClass("d-none");
755
756            let isEstimateForPaymentTypesWithMonthlyBillingFrequency = $("#make-payment-form input[name='EstimatePaymentTypesWithMonthlyBillingFrequencyWhenEstimatingMonthlyDues'][value='True']:first").length > 0;
757            
758            let url = $('#make-payment-form').data("calculate-url");
759
760            url = addParam(url, "monthsToPay", months);
761
762            if (!isEstimateForPaymentTypesWithMonthlyBillingFrequency) { 
763                url = addParam(url, "paymentTypeId", paymentTypeId);
764            }
765
766            $.post(url,function (data) {
767                const minWaitTime = 1500;
768                const remainingTime = Math.max(minWaitTime - (Date.now() - timeAtStartOfWaitOperation), 0);
769
770                setTimeout(function () {
771                    if (isEstimateForPaymentTypesWithMonthlyBillingFrequency) {
772                        $('.mtp-payment-type-amount').val('');
773                        $('.mtp-payment-amount-hidden').val('');
774
775                        data.result.forEach(function (result) {
776                            $(".mtp-payment-types-hidden[value='" + result.paymentTypeId + "']").parents('.form-row').find('.mtp-payment-type-amount, .mtp-payment-amount-hidden').val(result.amount).trigger('change');
777                        });
778                    }
779                    else {
780                        amountTarget.val(data.result);
781                        amountTarget.trigger('change');
782                    }
783                    $('#calculate-dues-dialog').modal('hide');
784                },
785                    remainingTime);
786            });
787        });
788
789        $("#northern-california-apprenticeship-application-form #PostalCode").blur(function () {
790            var postalCode = $(this).val().trim();
791            var url = $(this).data("url") + "?postalCode=" + encodeURIComponent(postalCode);
792
793            $.ajax({
794                type: "GET",
795                url: url,
796                dataType: "json",
797                contentType: "application/json; charset=utf-8",
798                success: function (data) {
799                    if (data.City)
800                        $("#northern-california-apprenticeship-application-form #City").val(data.City);
801                    if (data.County)
802                        $("#northern-california-apprenticeship-application-form #County").val(data.County);
803                }
804            });
805        });
806
807        $("#northern-california-apprenticeship-application-form #SSN").blur(function () {
808            var ssn = $(this).val().trim();
809
810            // Format a 9 digit number as xxx-xx-xxxx
811            if (/^\d{9}$/.test(ssn)) {
812                ssn = ssn.replace(/\D/g, '');
813                ssn = ssn.replace(/^(\d{3})/, '$1-');
814                ssn = ssn.replace(/-(\d{2})/, '-$1-');
815                ssn = ssn.replace(/(\d)-(\d{4}).*/, '$1-$2');
816
817                $(this).val(ssn);
818            }
819
820            const url = $(this).data("url") + "?ssn=" + encodeURIComponent(ssn);
821
822            $.ajax({
823                type: "GET",
824                url: url,
825                dataType: "json",
826                contentType: "application/json; charset=utf-8",
827                success: function (data) {
828                    if (data.IsDuplicate)
829                        $("#northern-california-apprenticeship-application-form #duplicate-ssn-warning-container").html(
830                            '<div class="alert alert-warning fade show" role="alert" id="duplicate-ssn-warning"><i class="fas fa-exclamation-triangle mr-2"></i>This social security number is already on file with the training center.</div>');
831                    else
832                        $(
833                            "#northern-california-apprenticeship-application-form #duplicate-ssn-warning-container #duplicate-ssn-warning")
834                            .alert("close");
835                }
836            });
837        });
838
839        $(
840            "#northern-california-apprenticeship-application-form, #northern-california-apprenticeship-application-confirm-form")
841            .submit(function () {
842                const form = $(this);
843
844                if (!form.valid())
845                    return false;
846
847                $("button[type='submit']", this).each(function () {
848                    $(this).attr('disabled', true)
849                        .css({ minWidth: $(this).width() + 'px' })
850                        .html("Please Wait...");
851                });
852
853                return true;
854            });
855
856        $("#gtag-info").each(function () {
857            const trackingId = $(this).data("tracking-id");
858            const pageTitle = $(this).data("page-title");
859            const localName = $(this).data("local-name");
860            const areaName = $(this).data("area-name");
861            const actionName = $(this).data("action-name");
862            const isDemo = $(this).data("is-demo");
863
864            gtag('js', new Date());
865
866            if (trackingId.length > 0) {
867                gtag('config', trackingId);
868            }
869
870            if (!isDemo) {
871                gtag('config',
872                    'G-5DY89QNZCH',
873                    {
874                        'page_title': pageTitle,
875                        'local_name': localName,
876                        'area': areaName,
877                        'action_name': actionName
878                    });
879            }
880
881            if (!isDemo) {
882                gtag('event',
883                    'load_page',
884                    {
885                        'local_name': localName,
886                        'area': areaName,
887                        'action_name': actionName
888                    });
889            }
890        });
891
892        $("#gtag-exception-event").each(function () {
893            gtag('event',
894                'exception',
895                {
896                    'description': 'An error occurred while processing your request.',
897                    'fatal': true
898                });
899        });
900
901        $("#gtag-purchase-event").each(function () {
902            gtag('event', 'purchase', $(this).data("event-data"));
903        });
904
905        $("#gtag-add-to-cart-event").each(function () {
906            gtag('event', 'add_to_cart', $(this).data("event-data"));
907        });
908
909        $(".gtag-begin-checkout-event-click").click(function () {
910            var eventData = $("#gtag-add-to-cart-event").data("event-data");
911            if (typeof eventData !== 'undefined') {
912                gtag('event', 'begin_checkout', eventData);
913            }
914        });
915
916        $(".gtag-remove-from-cart-event-click").click(function () {
917            var eventData = $("#gtag-add-to-cart-event").data("event-data");
918            if (typeof eventData !== 'undefined') {
919                gtag('event', 'remove_from_cart', eventData);
920            }
921        });
922
923        $("#global-prompt-for-member-email-address-dialog").on('shown.bs.modal',
924            function () {
925                $('#global-prompt-for-member-email-address-control').trigger('focus');
926            });
927
928        $("#global-prompt-for-member-email-address-form").submit(function (e) {
929            e.preventDefault();
930            const form = $(this);
931
932            $("#global-prompt-for-member-email-address-control-validation-error").addClass("d-none");
933            $("#global-prompt-for-member-email-address-control").removeClass("input-validation-error");
934
935            if (!form.valid())
936                return false;
937
938            $("button[type='submit']", form).each(function () {
939                $(this).attr('disabled', true);
940                //.css({ minWidth: $(this).width() + 'px' })
941                //.html("Please Wait...");
942            });
943
944            const url = $(this).data("url");
945
946            $.ajax({
947                type: "POST",
948                url: url,
949                dataType: "json",
950                contentType: "application/json; charset=utf-8",
951                data: JSON.stringify({ emailAddress: $("#global-prompt-for-member-email-address-control").val() }),
952                success: function (data) {
953
954                    if (data.isSuccessful === true) {
955                        $("#global-prompt-for-member-email-address-dialog").on('hidden.bs.modal',
956                            function () {
957                                window.location.reload(true);
958                            });
959
960                        $("#global-prompt-for-member-email-address-dialog").modal('hide');
961                    } else {
962                        $("#global-prompt-for-member-email-address-control-validation-error").text(data.errorMessage);
963                        $("#global-prompt-for-member-email-address-control-validation-error").removeClass("d-none");
964                        $("#global-prompt-for-member-email-address-control").addClass("input-validation-error");
965                        $('#global-prompt-for-member-email-address-control').trigger('focus');
966                    }
967
968                    $("button[type='submit']", form).each(function () {
969                        $(this).removeAttr("disabled");
970                    });
971                }
972            });
973
974            return false;
975        });
976
977        $('#cancel-contractor-worker-request-dialog .mtp-yes-dialog-button').click(function (e) {
978            e.preventDefault();
979
980            $(this).attr('disabled', true);
981
982            const request = $.ajax({
983                type: "POST",
984                url: $('#cancel-contractor-worker-request-dialog').data("url"),
985                contentType: "application/json; charset=utf-8"
986            });
987
988            request.done(function () {
989                const tr = $('#cancel-contractor-worker-request-dialog').data("row");
990
991                $(".mtp-contractor-worker-request-request-status", tr).text("CANCELED");
992                $(".mtp-edit-contractor-worker-request-button", tr).remove();
993                $(".mtp-cancel-contractor-worker-request-button", tr).remove();
994
995                $('#cancel-contractor-worker-request-dialog').modal('hide');
996            });
997
998            request.fail(function () {
999                $('#cancel-contractor-worker-request-dialog').data("has-error", true);
1000                $('#cancel-contractor-worker-request-dialog').modal('hide');
1001            });
1002        });
1003
1004        $('#cancel-contractor-worker-request-dialog').on('show.bs.modal',
1005            function () {
1006                $(this).data("has-error", false);
1007
1008                $("button", $(this)).each(function () {
1009                    $(this).removeAttr("disabled");
1010                });
1011            });
1012
1013        $('#cancel-contractor-worker-request-dialog').on('hidden.bs.modal',
1014            function () {
1015                if ($(this).data("has-error") === true) {
1016                    $("#cancel-contractor-worker-request-error-dialog").modal();
1017                }
1018            });
1019
1020        $(".mtp-cancel-contractor-worker-request-button").click(function (event) {
1021            event.preventDefault();
1022            const url = $(this).closest("a").prop("href");
1023            const tr = $(this).closest("tr");
1024
1025            $('#cancel-contractor-worker-request-dialog').data('url', url);
1026            $('#cancel-contractor-worker-request-dialog').data('row', tr);
1027
1028            $('#cancel-contractor-worker-request-dialog').modal();
1029        });
1030
1031
1032        $('#delete-contractor-worker-request-worker-type-dialog .mtp-yes-dialog-button').click(function (e) {
1033            e.preventDefault();
1034
1035            $(this).attr('disabled', true);
1036
1037            const request = $.ajax({
1038                type: "POST",
1039                url: $('#delete-contractor-worker-request-worker-type-dialog').data("url"),
1040                contentType: "application/json; charset=utf-8"
1041            });
1042
1043            request.done(function () {
1044                window.location.reload(true);
1045            });
1046
1047            request.fail(function () {
1048                $('#delete-contractor-worker-request-worker-type-
1048dialog').data("has-error", true).modal('hide');
1049            });
1050        });
1051
1052        $('#delete-contractor-worker-request-worker-type-dialog').on('show.bs.modal',
1053            function () {
1054                $(this).data("has-error", false);
1055
1056                $("button", $(this)).each(function () {
1057                    $(this).removeAttr("disabled");
1058                });
1059            });
1060
1061        $('#delete-contractor-worker-request-worker-type-dialog').on('hidden.bs.modal',
1062            function () {
1063                if ($(this).data("has-error") === true) {
1064                    $("#delete-contractor-worker-request-worker-type-error-dialog").modal();
1065                }
1066            });
1067
1068        $(".mtp-delete-contractor-worker-request-worker-type-button").click(function (event) {
1069            event.preventDefault();
1070            const url = $(this).closest("a").prop("href");
1071
1072            $('#delete-contractor-worker-request-worker-type-dialog').data('url', url).modal();
1073        });
1074
1075
1076        $('#confirm-submit-contractor-worker-request-dialog .mtp-yes-dialog-button').click(function (e) {
1077            e.preventDefault();
1078
1079            $(this).attr('disabled', true);
1080
1081            const request = $.ajax({
1082                type: "POST",
1083                url: $('#confirm-submit-contractor-worker-request-dialog').data("postUrl"),
1084                contentType: "application/json; charset=utf-8"
1085            });
1086
1087            request.done(function () {
1088                window.location.href = $('#confirm-submit-contractor-worker-request-dialog').data("success-url");
1089            });
1090
1091            request.fail(function () {
1092                $('#confirm-submit-contractor-worker-request-dialog').data("has-error", true).modal('hide');
1093            });
1094        });
1095
1096        $('#confirm-submit-contractor-worker-request-dialog').on('show.bs.modal',
1097            function () {
1098                $(this).data("has-error", false);
1099
1100                $("button", $(this)).each(function () {
1101                    $(this).removeAttr("disabled");
1102                });
1103            });
1104
1105        $('#confirm-submit-contractor-worker-request-dialog').on('hidden.bs.modal',
1106            function () {
1107                if ($(this).data("has-error") === true) {
1108                    $("#submit-contractor-worker-request-dialog-error-dialog").modal();
1109                }
1110            });
1111
1112        $(".mtp-submit-contractor-worker-request").click(function (event) {
1113            event.preventDefault();
1114            const postUrl = $(this).closest("a").prop("href");
1115            const successUrl = $(this).closest("a").data("success-url");
1116
1117            $('#confirm-submit-contractor-worker-request-dialog')
1118                .data('post-url', postUrl)
1119                .data('success-url', successUrl)
1120                .modal();
1121        });
1122
1123        $("#add-edit-contractor-worker-request-worker-type-form").each(function () {
1124            const page = $(this);
1125
1126            var removeFunction = function (e) {
1127                e.preventDefault();
1128
1129                $("#remove-member-dialog").data("element-to-remove", $(this)).modal("show");
1130            };
1131
1132            $("#add-member-dialog", page).keydown(function (event) {
1133                if (event.keyCode === 13) {
1134                    event.preventDefault();
1135                    $("#search-for-members").click();
1136                    return false;
1137                }
1138                return true;
1139            });
1140
1141            $("#add-member-dialog", page)
1142                .on('show.bs.modal',
1143                    function () {
1144                        $("#search-results").addClass("d-none");
1145                        $("#search-criteria-last-name").val("");
1146                        $("#search-criteria-first-name").val("");
1147                        $('#find-member-by-qr-code-app').addClass('d-none');
1148                        $('#add-member-dialog-fields').removeClass('d-none');
1149                        $('#search-for-members').removeClass('d-none');
1150
1151                        hideFindMemberByQrCodeAppVue();
1152                    })
1153                .on('shown.bs.modal',
1154                    function () {
1155                        $("#search-criteria-last-name").focus();
1156                    });
1157
1158            var addToListFunc = function (memberId, name) {
1159                if ($("#member-list ").find('[data-member-id="' + memberId + '"]').length === 0) {
1160
1161                    const lst = $("#member-list-group-item-template")
1162                        .clone()
1163                        .removeAttr("id")
1164                        .attr("data-member-id", memberId);
1165
1166                    $(".mtp-member-name", lst).text(name);
1167
1168                    $("<input/>", { type: "hidden", name: "SelectedMemberIds", value: memberId })
1169                        .appendTo(lst);
1170
1171                    $("#member-list").append(lst);
1172
1173                    $(lst).click(removeFunction);
1174                }
1175            }
1176
1177            $("#MemberID").change(function () {
1178                const memberId = parseInt($(this).val());
1179
1180                if (!isNaN(memberId)) {
1181                    $('#add-member-dialog').modal('hide');
1182                    addToListFunc(memberId, $(this).data("member-full-name"));
1183                }
1184            });
1185
1186            $("#search-for-members", page).click(function (e) {
1187                e.preventDefault();
1188
1189                const btn = $(this);
1190                btn.attr('disabled', true);
1191
1192                const request = $.ajax({
1193                    type: "GET",
1194                    url: $(this).data("url"),
1195                    data: {
1196                        lastName: $("#search-criteria-last-name").val(),
1197                        firstName: $("#search-criteria-first-name").val()
1198                    },
1199                    contentType: "application/json; charset=utf-8"
1200                });
1201
1202                request.done(function (data) {
1203                    $("#search-results > *").remove();
1204
1205                    if (data.results.length < 1) {
1206                        $("#search-results").append('<div>No members were found.</div>');
1207                    } else {
1208
1209                        if (data.results.length > 25) {
1210                            $("#search-results")
1211                                .append(
1212                                    '<div class="pb-1"><div class="alert alert-warning" role="alert">More than 25 results were found.  Only the first 25 results are shown.</div></div>');
1213                        }
1214
1215                        $("#search-results")
1216                            .append('<div class="list-group-item list-group-item-secondary">Results</div>');
1217
1218                        for (let i = 0; i < Math.min(data.results.length); ++i) {
1219                            const name = data.results[i].Fullname;
1220                            const memberId = data.results[i].MemberID;
1221                            const industryCode = data.results[i].IndustryCode;
1222
1223                            const el = $('<span></span>');
1224                            $(el).append($('<span></span>', { class: "text-decoration-underline" }).text(name));
1225
1226                            if (industryCode !== null)
1227                                $(el).append($(' <span class="mtp-smaller-font text-muted></span>')
1228                                    .text(" (" + industryCode + ")"));
1229
1230                            $('<a></a>', { class: "list-group-item text-decoration-none", href: "#" })
1231                                .html(el.html())
1232                                .click(function (ev) {
1233                                    ev.preventDefault();
1234
1235                                    addToListFunc(memberId, name);
1236
1237                                    $("#add-member-dialog").modal('hide');
1238                                })
1239                                .appendTo("#search-results");
1240                        }
1241                    }
1242
1243
1244                    $("#search-results").removeClass("d-none");
1245                });
1246
1247                request.always(function () {
1248                    btn.attr('disabled', false);
1249                });
1250            });
1251
1252            $('#add-member-dialog-find-member-by-qr-code-button').click(function () {
1253
1254                $('#add-member-dialog-fields').addClass('d-none');
1255                $('#search-for-members').addClass('d-none');
1256                $('#search-results').addClass('d-none');
1257
1258                showFindMemberByQrCodeAppVue();
1259
1260                $('#find-member-by-qr-code-app').removeClass('d-none');
1261            });
1262
1263            $(".mtp-remove-member").click(removeFunction);
1264
1265            $("#remove-member-dialog  .mtp-yes-dialog-button").click(function (e) {
1266                e.preventDefault();
1267
1268                $($("#remove-member-dialog").data("element-to-remove")).slideUp("fast",
1269                    function () {
1270                        $(this).remove();
1271                    });
1272
1273                $("#remove-member-dialog").modal("hide");
1274            });
1275        });
1276
1277        $("#add-edit-agent-tracking-entry-page").each(function () {
1278            const page = $(this);
1279
1280            $("#select-contractor-dialog", page).keydown(function (event) {
1281                if (event.keyCode === 13) {
1282                    event.preventDefault();
1283                    $("#search-for-contractors").click();
1284                    return false;
1285                }
1286                return true;
1287            });
1288
1289            $("#select-contractor-dialog", page)
1290                .on('show.bs.modal',
1291                    function () {
1292                        $("#contractor-search-results").addClass("d-none");
1293                        $("#contractor-search-criteria").val("");
1294                    })
1295                .on('shown.bs.modal',
1296                    function () {
1297                        $("#contractor-search-criteria").focus();
1298                    });
1299
1300            $("#search-for-contractors", page).click(function (e) {
1301                e.preventDefault();
1302
1303                const btn = $(this);
1304                btn.attr('disabled', true);
1305
1306                const request = $.ajax({
1307                    type: "GET",
1308                    url: $(this).data("url"),
1309                    data: {
1310                        searchCriteria: $("#contractor-search-criteria").val()
1311                    },
1312                    contentType: "application/json; charset=utf-8"
1313                });
1314
1315                request.done(function (data) {
1316                    $("#contractor-search-results > *").remove();
1317
1318                    if (data.results.length < 1) {
1319                        $("#contractor-search-results").append('<div>No contractors were found.</div>');
1320                    } else {
1321
1322                        if (data.results.length > 25) {
1323                            $("#contractor-search-results")
1324                                .append(
1325                                    '<div class="pb-1"><div class="alert alert-warning" role="alert">More than 25 results were found.  Only the first 25 results are shown.</div></div>');
1326                        }
1327
1328                        $("#contractor-search-results")
1329                            .append('<div class="list-group-item list-group-item-secondary">Results</div>');
1330
1331                        for (let i = 0; i < Math.min(data.results.length, 25); ++i) {
1332                            const contractorId = data.results[i].ContractorId;
1333                            const name = data.results[i].ContractorName;
1334                            const contractorNumber = data.results[i].ContractorNumber;
1335
1336                            const el = $('<span></span>');
1337                            $(el).append($('<span></span>', { class: "text-decoration-underline" }).text(name));
1338
1339                            if (contractorNumber !== null)
1340                                $(el).append($(' <span class="mtp-smaller-font text-muted"></span>')
1341                                    .text(" (" + contractorNumber + ")"));
1342
1343                            $('<a></a>', { class: "list-group-item text-decoration-none", href: "#" })
1344                                .html(el.html())
1345                                .click(function (ev) {
1346                                    ev.preventDefault();
1347
1348                                    const lookupRequest = $.ajax({
1349                                        type: "GET",
1350                                        url: $(page).data("get-contractor-info-for-agent-tracking-url"),
1351                                        data: {
1352                                            contractorId: contractorId
1353                                        },
1354                                        contentType: "application/json; charset=utf-8"
1355                                    });
1356
1357                                    lookupRequest.done(function (lookupData) {
1358
1359                                        if ($("#ContractorID").val() !== contractorId.toString()) {
1360                                            $("#ContractorID").val(contractorId);
1361                                            $("#ContractorDispatchID").val("");
1362
1363                                            $("#DispatchRequest").val("");
1364                                            $("#dispatch-request").removeClass("d-none");
1365                                        }
1366
1367                                        $("#Company").val(name);
1368                                        $("#CompanyAddress").val(lookupData.CompanyAddress);
1369                                        $("#CompanyPhoneNumber").val(lookupData.CompanyPhoneNumber);
1370                                        $("#AgreementType").val(lookupData.AgreementType);
1371
1372                                        $("#select-contractor-dialog").modal('hide');
1373                                    });
1374                                })
1375                                .appendTo("#contractor-search-results");
1376                        }
1377                    }
1378
1379                    $("#contractor-search-results").removeClass("d-none");
1380                });
1381
1382                request.always(function () {
1383                    btn.attr('disabled', false);
1384                });
1385            });
1386
1387            $("#select-contractor-dispatch-dialog", page).keydown(function (event) {
1388                if (event.keyCode === 13) {
1389                    event.preventDefault();
1390                    $("#search-for-contractor-dispatches").click();
1391                    return false;
1392                }
1393                return true;
1394            });
1395
1396            $("#select-contractor-dispatch-dialog", page)
1397                .on('show.bs.modal',
1398                    function () {
1399                        $("#contractor-dispatch-search-results").addClass("d-none");
1400                        $("#contractor-dispatch-search-criteria").val("");
1401                    })
1402                .on('shown.bs.modal',
1403                    function () {
1404                        $("#contractor-dispatch-search-criteria").focus();
1405                    });
1406
1407            $("#search-for-contractor-dispatches", page).click(function (e) {
1408                e.preventDefault();
1409
1410                const btn = $(this);
1411                btn.attr('disabled', true);
1412
1413                const request = $.ajax({
1414                    type: "GET",
1415                    url: $(this).data("url"),
1416                    data: {
1417                        searchCriteria: $("#contractor-dispatch-search-criteria").val(),
1418                        contractorId: $("#ContractorID").val()
1419                    },
1420                    contentType: "application/json; charset=utf-8"
1421                });
1422
1423                request.done(function (data) {
1424                    $("#contractor-dispatch-search-results > *").remove();
1425
1426                    if (data.results.length < 1) {
1427                        $("#contractor-dispatch-search-results")
1428                            .append('<div>No contractor dispatches were found.</div>');
1429                    } else {
1430
1431                        if (data.results.length > 25) {
1432                            $("#contractor-dispatch-search-results").append(
1433                                '<div class="pb-1"><div class="alert alert-warning" role="alert">More than 25 results were found.  Only the first 25 results are shown.</div></div>');
1434                        }
1435
1436                        $("#contractor-dispatch-search-results")
1437                            .append('<div class="list-group-item list-group-item-secondary">Results</div>');
1438
1439                        for (let i = 0; i < Math.min(data.results.length, 25); ++i) {
1440                            const contractorDispatchId = data.results[i].ContractorDispatchId;
1441                            const name = data.results[i].JobName;
1442                            const dodgeJobNumber = data.results[i].DodgeJobNumber;
1443                            const startDateTimeFormatted = data.results[i].StartDateTimeFormatted;
1444
1445                            const el = $('<span></span>');
1446                            $(el).append($('<span></span>', { class: "text-decoration-underline" }).text(name));
1447
1448                            if (dodgeJobNumber !== null)
1449                                $(el).append($(' <span class="mtp-smaller-font text-muted"></span>')
1450                                    .text(" (" + dodgeJobNumber + ")"));
1451
1452                            if (startDateTimeFormatted !== null)
1453                                $(el).append($(' <div class="mtp-smaller-font text-muted"></div>')
1454                                    .text("Starts " + startDateTimeFormatted));
1455
1456                            $('<a></a>', { class: "list-group-item text-decoration-none", href: "#" })
1457                                .html(el.html())
1458                                .click(function (ev) {
1459                                    ev.preventDefault();
1460
1461                                    const lookupRequest = $.ajax({
1462                                        type: "GET",
1463                                        url: $(page).data("get-contractor-dispatch-info-for-agent-tracking-url"),
1464                                        data: {
1465                                            contractorDispatchId: contractorDispatchId
1466                                        },
1467                                        contentType: "application/json; charset=utf-8"
1468                                    });
1469
1470                                    lookupRequest.done(function (lookupData) {
1471
1472                                        $("#ContractorDispatchID").val(contractorDispatchId);
1473
1474                                        $("#JobsiteAddress").val(lookupData.JobsiteAddress);
1475                                        $("#JobsiteContact").val(lookupData.JobsiteContact);
1476                                        $("#Location").val(lookupData.Location);
1477                                        $("#DispatchRequest").val(name);
1478
1479                                        $("#select-contractor-dispatch-dialog").modal('hide');
1480                                    });
1481                                })
1482                                .appendTo("#contractor-dispatch-search-results");
1483                        }
1484                    }
1485
1486                    $("#contractor-dispatch-search-results").removeClass("d-none");
1487                });
1488
1489                request.always(function () {
1490                    btn.attr('disabled', false);
1491                });
1492            });
1493        });
1494
1495        $('#confirm-save-dialog .mtp-yes-dialog-button').click(function (e) {
1496            e.preventDefault();
1497
1498            var name = $("#confirm-save-dialog").data("button-name");
1499            var value = $("#confirm-save-dialog").data("button-value");
1500
1501            var form = $(this).closest("form");
1502
1503            $('<input>').attr({
1504                type: 'hidden',
1505                name: name,
1506                value: value
1507            }).appendTo(form);
1508
1509            form[0].submit();
1510        });
1511
1512        $('#confirm-save-button').click(function (e) {
1513            e.preventDefault();
1514
1515            var form = $(this).closest("form");
1516
1517            if (!form.valid()) {
1518                $(".input-validation-error:first", form).focus();
1519            } else {
1520                form.clearForm();
1521
1522                $("#confirm-save-dialog")
1523                    .data("button-name", $(this).prop("name"))
1524                    .data("button-value", $(this).prop("value"))
1525                    .modal();
1526            }
1527        });
1528
1529        $('#confirm-member-web-disclaimers-dialog .mtp-yes-dialog-button').click(function (e) {
1530            e.preventDefault();
1531
1532            const form = $(this).closest("form");
1533
1534            form[0].submit();
1535        });
1536
1537
1538        $('#confirm-member-web-disclaimers-dialog').on('shown.bs.modal',
1539            function () {
1540                $(this).removeClass("fade");
1541            });
1542
1543        $('#confirm-member-web-disclaimers-dialog').on('hide.bs.modal',
1544            function () {
1545
1546                window.location.href = $(this).data("logoff-url");
1547            });
1548
1549        $('.mtp-date-time-picker').each(function (e) {
1550            $(this).datetimepicker({
1551                icons: {
1552                    time: "far fa-clock",
1553                    date: "far fa-calendar-alt",
1554                    up: "fas fa-arrow-up",
1555                    down: "fas fa-arrow-down"
1556                }
1557            });
1558        });
1559
1560        $('.mtp-date-picker').each(function (e) {
1561            $(this).datetimepicker({
1562                format: 'L',
1563                icons: {
1564                    time: "far fa-clock",
1565                    date: "far fa-calendar-alt",
1566                    up: "fas fa-arrow-up",
1567                    down: "fas fa-arrow-down"
1568                }
1569            });
1570        });
1571
1572        $('.mtp-hide-overflow:has(.mtp-date-picker), .mtp-hide-overflow:has(.mtp-date-time-picker)').each(function () {
1573            $(this).css("overflow", "visible");
1574        });
1575
1576        $('input:radio').change(function () {
1577            const value = $(this).val();
1578
1579            $('input[name=' + $(this).attr("name") + ']:radio').each(function () {
1580                const isSelected = $(this).val() === value;
1581                const selector = $(this).data('toggle-visibility-selector');
1582
1583                if (isSelected)
1584                    $(selector).slideDown();
1585                else
1586                    $(selector).slideUp();
1587            });
1588        });
1589
1590        $('#apprenticeship-application-form').each(function () {
1591            var form = $(this);
1592
1593            $('button:submit', form).click(function () {
1594                $(form).data('wasSubmitted', true);
1595            });
1596
1597            $(form).data('serialize', $(form).serialize());
1598
1599            $(window).bind('beforeunload', function () {
1600                if ($(form).data('wasSubmitted') === true)
1601                    return undefined;
1602
1603                if ($(form).data('is-post') === true)
1604                    return true;
1605
1606                if ($(form).serialize() !== $(form).data('serialize'))
1607                    return true;
1608
1609                return undefined;
1610            });
1611
1612            $('#apprenticeship-application-coordinator-review-button').click(function () {
1613                if ($(form).valid()) {
1614                    $('*[data-valmsg-summary="true"]').removeClass('validation-summary-errors').addClass('validation-summary-valid');
1615
1616                    $('#apprenticeship-application-coordinator-approval-dialog').modal('show');
1617                }
1618            });
1619
1620            $('#apprenticeship-application-coordinator-approval-dialog-submit-button').click(function () {
1621                const dialog = $('#apprenticeship-application-coordinator-approval-dialog');
1622                const username = $('#DialogCoordinatorUsername').val();
1623                const password = $('#DialogCoordinatorPassword').val();
1624
1625                const coordinatorSelectedContractorId = $('#DialogCoordinatorSelectedContractorID').val();
1626                const coordinatorSelectedContractor = $('#DialogCoordinatorSelectedContractor').val();
1627                const coordinatorSelectedLocalId = $('#DialogCoordinatorSelectedLocalID').val();
1628
1629                $('#CoordinatorUsername').val(username);
1630                $('#CoordinatorPassword').val(password);
1631                $('#CoordinatorSelectedContractorID').val(coordinatorSelectedContractorId);
1632                $('#CoordinatorSelectedContractor').val(coordinatorSelectedContractor);
1633                $('#CoordinatorSelectedLocalID').val(coordinatorSelectedLocalId);
1634
1635                $('#DialogCoordinatorUsername').removeClass('input-validation-error');
1636                $('#DialogCoordinatorSelectedContractorID').removeClass('input-validation-error');
1637                $('#DialogCoordinatorSelectedContractor').removeClass('input-validation-error');
1638                $('#DialogCoordinatorSelectedLocalID').removeClass('input-validation-error');
1639
1640                if (username.trim() === '') {
1641                    $('#DialogCoordinatorUsername').addClass('input-validation-error');
1642                }
1643                if (coordinatorSelectedContractorId.trim() === '') {
1644                    $('#DialogCoordinatorSelectedContractorID').addClass('input-validation-error');
1645                    $('#DialogCoordinatorSelectedContractor').addClass('input-validation-error');
1646                }
1647                if (coordinatorSelectedLocalId.trim() === '') {
1648                    $('#DialogCoordinatorSelectedLocalID').addClass('input-validation-error');
1649                }
1650
1651                if ($('.input-validation-error', dialog).length === 0) {
1652                    $('.validation-summary-errors', dialog).addClass('d-none');
1653
1654                    $('#apprenticeship-application-coordinator-approval-dialog').modal('hide');
1655                    $('#apprenticeship-application-submit-button').click();
1656                } else {
1657                    $('.validation-summary-errors', dialog).removeClass('d-none');
1658                }
1659            });
1660        });
1661
1662        $('#apprenticeship-application-coordinator-approval-dialog').on('hidden.bs.modal',
1663            function () {
1664                $('#DialogCoordinatorUsername').removeClass('input-validation-error');
1665                $('#DialogCoordinatorSelectedContractorID').removeClass('input-validation-error');
1666                $('#DialogCoordinatorSelectedContractor').removeClass('input-validation-error');
1667                $('#DialogCoordinatorSelectedLocalID').removeClass('input-validation-error');
1668            });
1669
1670        $('.mtp-file-upload-question').each(function () {
1671            let question = $(this);
1672
1673            $(question).find('button').click(function (e) {
1674                e.preventDefault();
1675
1676                var button = $(this);
1677
1678                $(button).blur();
1679
1680                var id = $(question).data('item-id');
1681
1682                var input = document.getElementById(id);
1683
1684                if (input == null) {
1685                    input = document.createElement('input');
1686                    $(input).attr('type', 'file');
1687                    $(input).attr('id', id);
1688                    $(input).attr('name', id);
1689                    $(input).attr('accept', $(question).data('accept'));
1690                    $(input).attr('class', 'd-none');
1691
1692                    input.addEventListener('change', (event) => {
1693                        const target = event.target;
1694                        if (target.files && target.files[0]) {
1695                            const maxAllowedSize = parseInt($(question).data('max-file-size'));
1696                            if (target.files[0].size > maxAllowedSize) {
1697                                $('.input-group', $(question)).addClass('input-validation-error');
1698                                target.value = '';
1699                                $(question).data('is-file-selected', false);
1700                                $(question).find('.mtp-file-upload-too-large').removeClass('d-none');
1701                            }
1702                            else {
1703                                $('.input-group', $(question)).removeClass('input-validation-error');
1704                                $(question).find('.mtp-file-upload-too-large').addClass('d-none');
1705
1706                                $(question).data('is-file-selected', true);
1707                                $(button).text('Clear');
1708
1709                                $(question).find('input[type=text]').each(function () {
1710                                    $(this).val(target.files[0].name + " (" + FormatAsBytes(target.files[0].size) + ")");
1711                                });
1712                            }
1713                        }
1714
1715                    });
1716
1717                    $(question).append($(input));
1718                }
1719
1720                $(question).data('is-file-selected', $(question).data('is-file-selected') == true || /^true$/i.test($(question).data('is-file-selected')))
1721
1722                //   $(question).removeClass('input-validation-error');
1723                //   $(question).find('.mtp-file-upload-too-large').addClass('d-none');
1724
1725                if ($(question).data('is-file-selected')) {
1726                    input.value = '';
1727                    $('.input-group', $(question)).removeClass('input-validation-error');
1728                    $(question).find('.mtp-file-upload-too-large').addClass('d-none');
1729                    $(question).data('is-file-selected', false);
1730                    $(button).text('Choose File');
1731                    $(button).blur();
1732                    $(question).find('input[type=text]').each(function () {
1733                        $(this).val('None Selected');
1734                    });
1735                }
1736                else {
1737                    $(input).trigger('click');
1738                }
1739            });
1740        });
1741
1742        $('input.mtp-ssn-field').blur(function () {
1743            var ssn = $(this).val().trim();
1744
1745            var formatAsCanadian = $(this).data('format-ssn-as-canadian-sin') === "true";
1746
1747            // Format a 9 digit number as xxx-xx-xxxx or xxx-xxx-xxx
1748            if (/^\d{9}$/.test(ssn)) {
1749
1750                if (formatAsCanadian) {
1751                    ssn = ssn.replace(/\D/g, '');
1752                    ssn = ssn.replace(/^(\d{3})/, '$1-');
1753                    ssn = ssn.replace(/-(\d{3})/, '-$1-');
1754                    ssn = ssn.replace(/(\d)-(\d{4}).*/, '$1-$2');
1755                } else {
1756                    ssn = ssn.replace(/\D/g, '');
1757                    ssn = ssn.replace(/^(\d{3})/, '$1-');
1758                    ssn = ssn.replace(/-(\d{2})/, '-$1-');
1759                    ssn = ssn.replace(/(\d)-(\d{4}).*/, '$1-$2');
1760                }
1761
1762                $(this).val(ssn);
1763            }
1764
1765            const baseUrl = $(this).data('ssn-validate-url');
1766
1767            if (baseUrl && baseUrl.length > 0) {
1768                const url = `${baseUrl}?ssn=${encodeURIComponent(ssn)}`;
1769                const containerSelector = $(`#${$(this).data('ssn-validate-alert-container-id')}`);
1770                const messageHtml = $(this).data('ssn-validate-alert-message');
1771
1772                $.ajax({
1773                    type: "GET",
1774                    url: url,
1775                    dataType: "json",
1776                    contentType: "application/json; charset=utf-8",
1777                    success: function (data) {
1778                        if (data.IsDuplicate) {
1779                            $(containerSelector).html(
1780                                '<div class="alert alert-warning fade show" role="alert"><div class="row no-gutters"><div class="col-auto"><i class="fas fa-exclamation-triangle mr-2"></i></div><div class="col">' +
1781                                messageHtml +
1782                                '</div></div></div>');
1783                            $("div > div > div:nth-child(2) > *", containerSelector).last().addClass("mb-0");
1784                        } else
1785                            $('.alert', $(containerSelector)).alert("close");
1786                    }
1787                });
1788            }
1789
1790        });
1791
1792        $('input.mtp-card-number-field').blur(function () {
1793            var cardNumber = $(this).val().trim();
1794
1795            const baseUrl = $(this).data('card-number-validate-url');
1796
1797            if (baseUrl && baseUrl.length > 0) {
1798                const url = `${baseUrl}?cardNumber=${encodeURIComponent(cardNumber)}`;
1799                const containerSelector = $(`#${$(this).data('card-number-validate-alert-container-id')}`);
1800                const messageHtml = $(this).data('card-number-validate-alert-message');
1801
1802                $.ajax({
1803                    type: "GET",
1804                    url: url,
1805                    dataType: "json",
1806                    contentType: "application/json; charset=utf-8",
1807                    success: function (data) {
1808                        if (data.IsDuplicate) {
1809                            $(containerSelector).html(
1810                                '<div class="alert alert-warning fade show" role="alert"><div class="row no-gutters"><div class="col-auto"><i class="fas fa-exclamation-triangle mr-2"></i></div><div class="col">' +
1811                                messageHtml +
1812                                '</div></div></div>');
1813                            $("div > div > div:nth-child(2) > *", containerSelector).last().addClass("mb-0");
1814                        } else
1815                            $('.alert', $(containerSelector)).alert("close");
1816                    }
1817                });
1818            }
1819        });
1820
1821        $('form.mtp-disable-submit-buttons-when-submitting').submit(function () {
1822            const form = $(this);
1823
1824            if ($(document.activeElement).attr('formnovalidate') !== 'formnovalidate' && !form.valid())
1825                return false;
1826
1827            $("button[type='submit']", form).each(function () {
1828                var clone = $(this).clone();
1829                $(clone).attr('disabled', 'disabled');
1830                $(clone).removeAttr('id');
1831
1832                $(this).hide();
1833                $(clone).insertAfter($(this));
1834            });
1835
1836            return true;
1837        });
1838
1839        $('form[data-is-postal-code-lookup-enabled="true"]').each(function () {
1840            const form = $(this);
1841
1842            $(`#${form.data('postal-code-lookup-postal-code-field-id')}`).blur(function () {
1843                const postalCodeField = $(this);
1844                const postalCode = postalCodeField.val().trim();
1845                const baseUrl = $(form).data("postal-code-lookup-url");
1846
1847                if (baseUrl && postalCode && baseUrl.length > 0 && postalCode.length > 0) {
1848                    const url = `${baseUrl}?postalCode=${encodeURIComponent(postalCode)}`;
1849
1850                    $.ajax({
1851                        type: "GET",
1852                        url: url,
1853                        dataType: "json",
1854                        contentType: "application/json; charset=utf-8",
1855                        success: function (data) {
1856                            if (data.City && form.data('postal-code-lookup-city-field-id'))
1857                                $(`#${form.data('postal-code-lookup-city-field-id')}`).val(data.City);
1858                            if (data.County && form.data('postal-code-lookup-county-field-id'))
1859                                $(`#${form.data('postal-code-lookup-county-field-id')}`).val(data.County);
1860                            if (data.State && form.data('postal-code-lookup-state-field-id'))
1861                                $(`#${form.data('postal-code-lookup-state-field-id')}`).val(data.State);
1862                        }
1863                    });
1864                }
1865            });
1866        });
1867
1868        $('#signature-choose-file').click(function () {
1869            $('#signature-file').click();
1870        });
1871
1872        $('#signature-container button').click(function (e) {
1873            e.preventDefault();
1874        });
1875
1876        $('#signature-file').change(function (event) {
1877
1878            if (event.target && event.target.files && event.target.files[0]) {
1879
1880                var reader = new FileReader();
1881                reader.onload = function () {
1882                    setSignatureImage(reader.result);
1883                };
1884                reader.readAsDataURL(event.target.files[0]);
1885            }
1886        });
1887
1888        var signatureCanvas = document.getElementById('signature-capture-canvas');
1889
1890        if (signatureCanvas) {
1891
1892            $("#SignatureImageData").bind('cssClassChanged', function () {
1893                if ($(this).hasClass('input-validation-error'))
1894                    $(this).parent().addClass('input-validation-error');
1895                else
1896                    $(this).parent().removeClass('input-validation-error');
1897            });
1898
1899            var signaturePad = new SignaturePad(signatureCanvas, {
1900                minWidth: 2.5,
1901                maxWidth: 4
1902            });
1903
1904            function resizeSignatureCanvas() {
1905                signaturePad.clear();
1906                signatureCanvas.width = 1;
1907                signatureCanvas.height = 1;
1908                $('#signature-capture-canvas-container').width(1);
1909                $('#signature-capture-canvas-container').height(1);
1910
1911                $('#signature-capture-canvas-container').width($('#signature-capture-canvas-container').parent().width());
1912                $('#signature-capture-canvas-container').height($('#signature-capture-canvas-container').parent().height());
1913
1914                $(signatureCanvas).width($('#signature-capture-canvas-container').width());
1915                $(signatureCanvas).height($('#signature-capture-canvas-container').height());
1916
1917                signatureCanvas.width = signatureCanvas.offsetWidth;
1918                signatureCanvas.height = signatureCanvas.offsetHeight;
1919
1920                signaturePad.clear();
1921            }
1922
1923            window.addEventListener("resize", resizeSignatureCanvas);
1924
1925            $('#signature-capture-modal-save').click(function () {
1926                $('#signature-capture-modal').modal('hide');
1927
1928                if (!signaturePad.isEmpty()) {
1929                    const data = signaturePad.getCroppedImage().toDataURL("image/png");
1930                    setSignatureImage(data);
1931                }
1932            });
1933
1934            var url = $('#signature').attr('src');
1935
1936            if (url && url.length > 0) {
1937                signaturePad.fromDataURL($('#signature').attr('src'));
1938            }
1939
1940            $('#signature-capture-modal').on('show.bs.modal',
1941                function () {
1942                    signaturePad.clear();
1943
1944                });
1945
1946            $('#signature-capture-modal').on('shown.bs.modal',
1947                function () {
1948                    resizeSignatureCanvas();
1949                });
1950        }
1951
1952        $('#captcha-validation-shim').bind('cssClassChanged', function () {
1953            if ($(this).hasClass('input-validation-error'))
1954                $(this).parent().addClass('input-validation-error');
1955            else
1956                $(this).parent().removeClass('input-validation-error');
1957        });
1958
1959        $("#apprenticeship-application-form").bind("invalid-form.validate",
1960            function (form, validator) {
1961                $('[data-valmsg-summary="true"] ul').each(function () {
1962                    $(this).empty();
1963
1964                    const messages = Array.from(new Set(validator.errorList.map(c => c.message)));
1965
1966                    for (let i = 0; i < messages.length; i++) {
1967                        const message = messages[i];
1968                        const li = $('<li>');
1969
1970                        li.text(message);
1971
1972                        $(this).append(li);
1973                    }
1974                });
1975            });
1976
1977        $('#class-calendar-view-class-dialog')
1978            .on('show.bs.modal',
1979                function (e) {
1980                    const classId = $(e.relatedTarget).data('class-id');
1981                    let data = $('#class-data-' + classId);
1982
1983                    $('#class-calendar-view-class-dialog-title').text($(data).data('course-title'));
1984                    $('#class-calendar-view-class-dialog-course-description').text($(data).data('course-description'));
1985                    $('#class-calendar-view-class-dialog-start-date').text($(data).data('class-start-date'));
1986                    $('#class-calendar-view-class-dialog-end-date').text($(data).data('class-end-date'));
1987                    $('#class-calendar-view-class-dialog-location').text($(data).data('class-location'));
1988                    $('#class-calendar-view-class-dialog-language').text($(data).data('class-language'));
1989                    $('#class-calendar-view-class-dialog-instructor').text($(data).data('class-instructor'));
1990                    $('#class-calendar-view-class-dialog-enrollment-stats').text($(data).data('class-enrollment-stats'));
1991                    $('#class-calendar-view-class-dialog-session-groups').html($(".session-group-table-container", data).html());
1992
1993                    if ($(data).data('class-is-enrollment-closed')) {
1994
1995                        $('#class-calendar-view-class-dialog-enroll-button').addClass('d-none');
1996                        $('#class-calendar-view-class-dialog-enrollment-closed-alert').removeClass('d-none');
1997                    } else {
1998
1999                        $('#class-calendar-view-class-dialog-enroll-button').removeClass('d-none');
2000                        $('#class-calendar-view-class-dialog-enrollment-closed-alert').addClass('d-none');
2001                    }
2002
2003                    $('input[name=classID]', '#class-calendar-view-class-dialog').val(classId);
2004                })
2005            .on('shown.bs.modal',
2006                function () {
2007
2008                });
2009
2010        $('#courseType', $('#class-calendar')).change(function () {
2011            const courseType = $(this).val();
2012
2013            $('button[data-course-type]').removeClass("bg-warning");
2014
2015            $('a', $('#class-calendar')).each(function () {
2016                var href = $(this).data('original-href');
2017
2018                if (!href) {
2019                    href = $(this).attr('href');
2020                    $(this).data('original-href', href);
2021                }
2022
2023                if (href) {
2024                    if (courseType.length > 0)
2025                        $(this).attr("href", href.split('?')[0] + '?courseType=' + encodeURIComponent(courseType));
2026                    else
2027                        $(this).attr("href", href.split('?')[0]);
2028
2029
2030                }
2031            });
2032
2033            if (courseType.length > 0) {
2034                $('button[data-course-type]').filter(function () {
2035                    return $(this).data('course-type') === courseType;
2036                }).addClass("bg-warning");
2037            }
2038        });
2039
2040        $('#courseType', $('#class-calendar')).each(function () {
2041            const courseType = $('#class-calendar').data('selected-course-type');
2042
2043            if (courseType && courseType.length > 0) {
2044                $(this).val(courseType).change();
2045            }
2046        });
2047
2048        $('#navigate-browser-history-back').each(function () {
2049            history.back();
2050        });
2051
2052        $('#show-password, #hide-password').click(function () {
2053            const password = document.querySelector('#login-password-field');
2054
2055            if (password.type === 'password') {
2056                password.type = 'text';
2057                $('#show-password').addClass('d-none');
2058                $('#hide-password').removeClass('d-none');
2059            } else {
2060                password.type = 'password';
2061                $('#hide-password').addClass('d-none');
2062                $('#show-password').removeClass('d-none');
2063            }
2064
2065            password.focus();
2066        });
2067
2068        $('#add-edit-contractor-worker-request-form').each(function () {
2069            $('.custom-file-input').on('change',
2070                function (e) {
2071                    var fileName = e.target.files[0].name;
2072                    $(this).parent().next('.input-group-append').removeClass('d-none');
2073                    $(this).next('.custom-file-label').text(fileName);
2074                    $('#ClearDocument').val(false);
2075                });
2076
2077            $('#ClearDocumentButton').on('click',
2078                function () {
2079
2080                    $('#ClearDocument').val(true);
2081                    $('#Document').val('');
2082                });
2083
2084            $('#ClearExistingDocumentButton').on('click',
2085                function () {
2086
2087                    $('#ClearDocumentButton').click();
2088                    $('#DocumentUploadContainer').removeClass('d-none');
2089                    $('#ClearExistingDocumentContainer').remove();
2090                });
2091
2092            $('#ClearExistingDocumentContainer > button[data-url]').on('click',
2093                function () {
2094                    window.open($(this).data('url'));
2095                });
2096        });
2097
2098        $('#search-for-skills-form').each(function () {
2099            $('#ShowListNumberAndPosition').change(function () {
2100                if (this.checked) {
2101                    $('#SortByListNumberAndPosition').removeAttr('disabled');
2102                } else {
2103                    $('#SortByListNumberAndPosition').attr('disabled', true);
2104                }
2105            });
2106
2107            $('#ShowListNumberAndPosition').change();
2108        });
2109
2110        $('input[data-mask]').each(function () {
2111            const input = $(this);
2112
2113            const container = $("<div></div>").css('position', 'relative');
2114
2115            $(input).wrap(container);
2116
2117            const placeholder = $(input).data('mask-placeholder');
2118
2119            var mask = $('<div></div>').css({
2120                'position': 'absolute',
2121                'left': '0',
2122                'top': '0',
2123                'pointer-events': 'none',
2124                'z-index': '-1',
2125                'width': '100%'
2126            });
2127            $(mask).css('padding', $(input).css('padding'));
2128            $(mask).css('background', $(input).css('background'));
2129            $(mask).css('color', $(input).css('color'));
2130            $(mask).css('border', $(input).css('border'));
2131            $(mask).css('border-color', 'transparent');
2132            $(input).css('background', 'transparent');
2133            $(input).css('position', 'relative');
2134            $(input).css('z-index', '1');
2135
2136            if ($(input).val().length === 0)
2137                $(mask).text(placeholder);
2138
2139            $(input).after(mask);
2140
2141            $(input).on('blur',
2142                function () {
2143                    if ($(input).val() === '' && $(input).attr('placeholder')) {
2144                        $(mask).text('');
2145                    }
2146                });
2147
2148            $(input).blur();
2149
2150            $(input).on('input',
2151                function () {
2152
2153                    if ($(input).val() === '' && $(input).attr('placeholder')) {
2154                        $(mask).text('');
2155                    } else {
2156                        const value = $(input).val();
2157                        let text = placeholder;
2158                        for (let i = 0; i < value.length; ++i) {
2159                            text = setCharAt(text, i, value[i]);
2160                        }
2161
2162                        $(mask).text(text);
2163                    }
2164
2165                    function setCharAt(str, index, chr) {
2166                        if (index > str.length - 1) return str;
2167                        return str.substring(0, index) + chr + str.substring(index + 1);
2168                    }
2169                });
2170        });
2171
2172        var findMemberByQrCodeAppVue = null;
2173
2174        function createFindMemberByQrCodeAppVue() {
2175            return new Vue({
2176                el: '#find-member-by-qr-code-app',
2177
2178                data() {
2179                    return {
2180                        state: undefined,
2181                        enabled: true,
2182                        camera: 'auto',
2183                        errorMessage: '',
2184                        hasCamera: undefined,
2185                        targetElement: ''
2186                    }
2187                },
2188
2189                computed: {
2190                    showInstructions() {
2191                        return this.state !== 'Error' && this.state !== 'Initializing';
2192                    }
2193                },
2194
2195                methods: {
2196                    async onInit(promise) {
2197                        const start = Date.now();
2198                        var minDuration = 0;
2199                        if (this.hasCamera !== true && this.state !== 'Error') {
2200                            minDuration = 1500;
2201                            this.state = 'Initializing';
2202                        }
2203
2204                        try {
2205                            await promise.then(async () => {
2206
2207                                if (this.enabled === true)
2208                                    await this.waitAtLeast(minDuration, start);
2209
2210                                if (this.state !== 'Searching') {
2211                                    this.state = 'Running';
2212                                    this.hasCamera = true;
2213                                }
2214                            },
2215                                async (error) => {
2216                                    if (this.enabled === true)
2217                                        await this.waitAtLeast(minDuration, start);
2218
2219                                    this.state = 'Error';
2220                                    this.hasCamera = false;
2221
2222                                    if (error.name === 'NotAllowedError') {
2223                                        this.errorMessage = 'Permission to use the camera was not granted.';
2224                                    } else if (error.name === 'NotFoundError') {
2225                                        this.errorMessage = 'A camera could not be found on this device.';
2226                                    } else if (error.name === 'NotSupportedError') {
2227                                        this.errorMessage = 'The camera could not be accessed.';
2228                                    } else if (error.name === 'NotReadableError') {
2229                                        this.errorMessage = 'The camera could not be accessed.';
2230                                    } else {
2231                                        this.errorMessage = 'UNKNOWN ERROR: ' + error.message;
2232                                    }
2233                                }).then(() => { this.onInitRunning = false; });
2234                        } catch (e) {
2235                            console.error(e);
2236                        }
2237                    },
2238
2239                    async onDecode(content) {
2240                        if (this.enabled !== true || this.hasCamera !== true) {
2241                            return;
2242                        }
2243                        const component = this;
2244
2245                        component.state = 'Searching';
2246                        component.memberId = null;
2247                        component.errorMessage = '';
2248                        component.turnCameraOff();
2249
2250                        const start = Date.now();
2251                        const minDuration = 1500;
2252                        const url = content.substring(0, 1024);
2253
2254                        $("#find-member-by-qr-code-app").data('qr-content', url);
2255
2256                        $.ajax({
2257                            type: "GET",
2258                            url: $("#find-member-by-qr-code-app").data('url') + "?url=" + encodeURIComponent(url),
2259                            dataType: "json",
2260                            contentType: "application/json; charset=utf-8",
2261                            success: async data => {
2262                                if (this.enabled === true)
2263                                    await component.waitAtLeast(minDuration, start);
2264
2265                                if (data && data.memberId && !isNaN(parseInt(data.memberId))) {
2266                                    component.state = 'Found';
2267
2268                                    if (this.enabled === true)
2269                                        await component.timeout(500);
2270
2271                                    if (this.enabled === true) {
2272                                        if (data.fullName)
2273                                            $(component.targetElement).data("member-full-name", data.fullName);
2274
2275                                        $(component.targetElement).val(data.memberId).trigger("change");
2276                                    }
2277                                } else {
2278                                    component.state = 'NotFound';
2279
2280                                    if (this.enabled === true)
2281                                        await component.timeout(2000);
2282
2283                                    component.turnCameraOn();
2284                                }
2285                            },
2286
2287                            error: async function (jqXhr) {
2288                                if (component.enabled === true)
2289                                    await component.waitAtLeast(minDuration, start);
2290
2291                                if (jqXhr.status === 404) {
2292                                    component.state = 'NotFound';
2293                                } else {
2294                                    component.state = 'Error';
2295                                    component.errorMessage =
2296                                        'An unexpected error occurred while trying to check the QR code.';
2297
2298                                    return;
2299                                }
2300
2301                                if (component.enabled === true)
2302                                    await component.timeout(2000);
2303
2304                                component.turnCameraOn();
2305                            }
2306                        });
2307                    },
2308
2309                    turnCameraOn: function () {
2310                        if (this.hasCamera === true)
2311                            this.camera = 'auto';
2312                    },
2313
2314                    turnCameraOff() {
2315                        if (this.hasCamera === true)
2316                            this.camera = 'off';
2317                    },
2318
2319                    timeout(ms) {
2320                        return new Promise(resolve => {
2321                            window.setTimeout(resolve, ms);
2322                        });
2323                    },
2324
2325                    resetInitializationState() {
2326                        if (this.hasCamera !== false) {
2327                            this.errorMessage = '';
2328                            this.state = undefined;
2329                        }
2330                        if (this.state !== 'Error') {
2331                            this.state = undefined;
2332                        }
2333                        this.enabled = false;
2334                    },
2335
2336                    async waitAtLeast(ms, fromDate) {
2337                        const duration = Date.now() - fromDate;
2338
2339                        if (duration < ms)
2340                            await this.timeout(ms - duration);
2341                    },
2342
2343                    setTargetElement(el) {
2344                        this.targetElement = el;
2345                    },
2346
2347                    start() {
2348                        this.resetInitializationState();
2349                        this.enabled = true;
2350                        this.turnCameraOn();
2351                    },
2352
2353                    stop() {
2354                        this.turnCameraOff();
2355                        this.resetInitializationState();
2356                    }
2357                }
2358            });
2359        }
2360
2361        function showFindMemberByQrCodeAppVue() {
2362            if (!findMemberByQrCodeAppVue) {
2363                findMemberByQrCodeAppVue = createFindMemberByQrCodeAppVue();
2364            }
2365            else {
2366                findMemberByQrCodeAppVue.$root.start();
2367            }
2368
2369            findMemberByQrCodeAppVue.$root.setTargetElement("#MemberID");
2370        }
2371
2372        function hideFindMemberByQrCodeAppVue() {
2373            if (findMemberByQrCodeAppVue) {
2374                findMemberByQrCodeAppVue.$root.stop();
2375            }
2376        }
2377
2378        $('#find-member-by-qr-code-dialog').each(function () {
2379            $("#MemberID").change(function () {
2380                $('#find-member-by-qr-code-dialog').modal('hide');
2381                let searchTrainingCenter = $("input[name='SearchTrainingCenter']:checked").val() === "True";
2382
2383                if (searchTrainingCenter) {
2384                    let url = $('#find-member-by-qr-code-app').data('qr-content');
2385
2386                    $('#find-member-by-qr-code-app').removeData('qr-content');
2387
2388                    if (isValidHttpUrl(url)) {
2389                        window.open(url, '_blank');
2390                        return;
2391                    }
2392                }
2393
2394                const memberId = parseInt($(this).val());
2395
2396                if (!isNaN(memberId)) {
2397                    $(this).closest("form").submit();
2398                }
2399            });
2400        });
2401
2402
2403        $('#find-member-by-qr-code-dialog').on('shown.bs.modal',
2404            function () {
2405                $('#find-member-by-qr-code-app').removeClass('d-none');
2406            });
2407
2408        $('#find-member-by-qr-code-dialog').on('show.bs.modal',
2409            function () {
2410                showFindMemberByQrCodeAppVue();
2411            });
2412
2413        $('#find-member-by-qr-code-dialog').on('hidden.bs.modal',
2414            function () {
2415                hideFindMemberByQrCodeAppVue();
2416                $('#find-member-by-qr-code-app').addClass('d-none');
2417            });
2418
2419        $('#find-member-by-qr-code-button').click(function () {
2420            $('#find-member-by-qr-code-dialog').modal('show');
2421        });
2422
2423        setTimeout(function () { tick(); }, 1000);
2424
2425        resizeElements();
2426
2427        $('.mtp-mobile-hide-until-loaded').removeClass("mtp-mobile-hide-until-loaded");
2428
2429        $(window)
2430            .scroll(updateFixedScrollableDataGridHeaders)
2431            .trigger("scroll");
2432
2433        $(window).resize(updateFixedScrollableDataGridHeaders);
2434
2435        $('#apprenticeship-application-form').each(function () {
2436            const form = $(this);
2437
2438            const input = $('.input-validation-error, .field-validation-error', form).first();
2439
2440            if (input.length > 0) {
2441                input.get(0).scrollIntoView();
2442                input.focus();
2443            } else
2444                $(':input:enabled:visible:first', form).focus();
2445        });
2446
2447        $("#process-payment-page").each(function () {
2448            $('.mtp-full-page-wait-overlay-container').removeClass('d-none');
2449
2450            setTimeout(function () { document.processForm.submit(); }, 1500);
2451        });
2452
2453        $("#global-prompt-for-member-email-address-dialog").each(function () {
2454
2455            setTimeout(function () {
2456                if ($('body').hasClass("modal-open"))
2457                    return;
2458
2459                $("#global-prompt-for-member-email-address-dialog").modal('show');
2460            }, 500);
2461        });
2462
2463        $('#confirm-cancel-dispatch-request-dialog .mtp-yes-dialog-button').click(function (e) {
2464            e.preventDefault();
2465
2466            $('#confirm-cancel-dispatch-request-dialog button').attr('disabled', true);
2467            $('#confirm-cancel-dispatch-request-dialog-form').submit();
2468        });
2469
2470        $("#cancel-dispatch-request").click(function (e) {
2471            e.preventDefault();
2472
2473            $('#confirm-cancel-dispatch-request-dialog').modal();
2474        });
2475
2476        $("#add-edit-contractor-dispatch-request-form").each(function () {
2477
2478            configureForPostalCodeChanges();
2479            configureForContractorDispatchStatusChanges();
2480            configureForJobNameChanges();
2481
2482            function configureForPostalCodeChanges() {
2483                const template = $('#PostalCodeItemTemplate > *').first().clone();
2484
2485                $('#PostalCodeItemTemplate').remove();
2486
2487                const deleteClickFunction = function (e) {
2488                    e.preventDefault();
2489
2490                    const item = $(this).parent();
2491                    $(item).remove('input');
2492                    $(item).fadeOut(function () {
2493                        $(item).remove();
2494
2495                        if ($('#PostalCodeItemsContainer > *').length < 1) {
2496                            $('#PostalCodeItemsContainer').addClass('d-none').removeClass('d-flex');
2497                        }
2498                    });
2499                };
2500
2501                $('#PostalCodeItemsContainer .delete-postal-code').click(deleteClickFunction);
2502
2503                $('#PostalCodeTextBox').on('keydown', function (e) {
2504                    if (e.key === 'Enter' || e.keyCode === 13) {
2505                        e.preventDefault();
2506                    }
2507                });
2508
2509                $('#PostalCodeTextBox').on('keyup', function (e) {
2510                    if (e.key === 'Enter' || e.keyCode === 13) {
2511                        e.preventDefault();
2512                        $('#AddPostalCodeButton').click();
2513                    }
2514                });
2515
2516                $('#AddPostalCodeButton').click(function (e) {
2517                    e.preventDefault();
2518
2519                    const postalCode = $('#PostalCodeTextBox').val().trim().toUpperCase();
2520
2521                    $('#PostalCodeTextBox').val('');
2522
2523                    if (postalCode.length > 0 && $('#PostalCodeItemsContainer input').filter(function () { return $(this).val() === postalCode }).length < 1) {
2524                        const item = template.clone();
2525
2526                        $('.delete-postal-code', item).click(deleteClickFunction);
2527
2528                        $('.text', item).text(postalCode);
2529                        $('input', item).val(postalCode);
2530
2531                        item.css('display', 'none');
2532
2533                        const itemToInsertAfter = $('#PostalCodeItemsContainer > *')
2534                            .filter(function () { return $('input', this).val() < postalCode }).last();
2535
2536                        if (itemToInsertAfter.length > 0) {
2537                            item.insertAfter(itemToInsertAfter);
2538                        } else {
2539                            $('#PostalCodeItemsContainer').prepend(item);
2540                        }
2541
2542                        $('#PostalCodeItemsContainer').addClass('d-flex').removeClass('d-none');
2543
2544                        $(item).fadeIn();
2545                    }
2546                });
2547            }
2548
2549            function configureForContractorDispatchStatusChanges() {
2550                $('#ContractorDispatchStatusID').change(function () {
2551                    if (($(this).val() === $(this).attr('data-open-contractor-dispatch-status-id'))) {
2552                        $('#contractor-dispatch-status-not-open-warning').addClass('d-none');
2553                        $('#SaveAndDispatch').removeClass('disabled');
2554                        $('#SaveAndDispatch').removeAttr('disabled');
2555                    } else {
2556                        $('#contractor-dispatch-status-not-open-warning').removeClass('d-none');
2557                        $('#SaveAndDispatch').addClass('disabled');
2558                        $('#SaveAndDispatch').attr('disabled', 'disabled');
2559                    }
2560                }).change();
2561            }
2562
2563            function configureForJobNameChanges() {
2564                var jobNameChanged = false;
2565
2566                $("#JobName").change(function () {
2567                    jobNameChanged = true;
2568                });
2569
2570                const updateJobNameNotFoundWarningFunc = function () {
2571                    const jobId = parseInt($('#JobID').val());
2572
2573                    if (!isNaN(jobId) || $("#JobName").val().trim().length < 1)
2574                        $('#job-not-found-warning').addClass('d-none');
2575                    else
2576                        $('#job-not-found-warning').removeClass('d-none');
2577                }
2578
2579                $("#job-name-autocomplete-container").focusout(function () {
2580                    if (!jobNameChanged)
2581                        return;
2582
2583                    updateJobNameNotFoundWarningFunc();
2584
2585                    jobNameChanged = false;
2586                });
2587
2588                $("#JobName").each(function () {
2589                    const findJobsUrl = $(this).data("find-jobs-url");
2590
2591                    const lookupFunc = function (text, callback) {
2592                        const lookupRequest = $.ajax({
2593                            type: "GET",
2594                            url: findJobsUrl,
2595                            data: {
2596                                jobName: text
2597                            },
2598                            contentType: "application/json; charset=utf-8"
2599                        });
2600
2601                        lookupRequest.done(function (lookupData) {
2602                            callback(function () {
2603                                return lookupData.results;
2604                            },
2605                                item => item.JobName);
2606                        });
2607                    };
2608
2609                    const beforeLookupFunc = function () {
2610                        $('#JobID').val('');
2611                    }
2612
2613                    const selectedFunc = function (selection) {
2614                        $('#JobID').val(selection.JobID);
2615                        updateJobNameNotFoundWarningFunc();
2616                    };
2617
2618                    autocomplete(document.getElementById("JobName"), beforeLookupFunc, lookupFunc, selectedFunc);
2619                });
2620            }
2621        });
2622
2623        $('a.mtp-post-link').click(function (e) {
2624            e.preventDefault();
2625
2626            const frm = document.createElement('FORM');
2627            frm.id = 'frm_' + Math.random() + "_" + Math.random();
2628            frm.method = 'POST';
2629            frm.action = e.target.href;
2630            document.body.appendChild(frm);
2631            frm.submit();
2632        });
2633
2634        $('#session-heartbeat').each(function () {
2635            var sessionHeartbeatUrl = $(this).attr('data-url');
2636
2637            if (sessionHeartbeatUrl !== null) {
2638                setInterval(function () {
2639                    $.ajax({
2640                        type: 'GET',
2641                        url: sessionHeartbeatUrl
2642                    });
2643                },
2644                    2 * 60 * 1000); // Every 2 minutes
2645            }
2646        });
2647
2648        $('#add-call-contractor-dispatch-request-form').each(function () {
2649            const id = 'add-call-contractor-dispatch-request-form';
2650            const yOffset = -150;
2651            const element = document.getElementById(id);
2652            const y = element.getBoundingClientRect().top + window.scrollY + yOffset;
2653
2654            window.scrollTo({ top: y });
2655
2656            $('input[type=radio][name=Option]').change(function () {
2657                $('#submit').removeClass('d-none').text($(this).siblings('.form-check-label').text());
2658
2659                $(this).closest('.form-check').append($('#call-fields'));
2660
2661                if ($(this).data('has-call-fields') === 'True') {
2662                    $('#call-fields').removeClass('d-none');
2663                } else {
2664                    $('#call-fields').addClass('d-none');
2665                }
2666            });
2667
2668
2669            $('input[type=radio][name=Option]:checked').trigger('change');
2670        });
2671
2672        $('#edit-monthly-apprentice-report-form').each(function () {
2673            let dialogOpen = false;
2674
2675            $(this).submit(function (e) {
2676                if (dialogOpen)
2677                    e.preventDefault();
2678            });
2679
2680            const modelInput = $('input[type=hidden][name=modelJson]');
2681
2682            const json = modelInput.val();
2683
2684            if (json && json.length > 0) {
2685                const data = JSON.parse(json);
2686
2687                const processDict = {};
2688
2689                for (const element of data.processes) {
2690                    if (element.visible) {
2691                        $('#addEditProcessNumber').append($('<option>').val(element.processNumber).attr('data-description', element.description).text(element.name));
2692                    }
2693
2694                    processDict[element.processNumber] = element;
2695                }
2696
2697                const dayDict = {};
2698
2699                for (const day of data.days) {
2700                    const dayOfWeek =
2701                        new Date(data.year, data.month - 1, day).toLocaleString('en-us', { weekday: 'long' });
2702                    $('#addEditDay').append($('<option>').val(day).text(`${day} - ${dayOfWeek}`));
2703
2704                    dayDict[day] = dayOfWeek;
2705                }
2706
2707                const updateDayContainerVisibility = function (dayContainer, processList) {
2708                    processList = processList || dayContainer.children('[data-template-process-list]').first();
2709
2710                    if ($(processList).children('[data-template-process-list-item=true]').filter(function () { return !$(this).hasClass('d-none'); }).length > 0) {
2711                        dayContainer.removeClass('d-none');
2712                    }
2713                    else {
2714                        dayContainer.addClass('d-none');
2715                    }
2716                }
2717
2718                const addEditEntry = function (entry) {
2719                    var dayContainer = $(`#item-container > [data-template=true][data-day="${entry.day}"]`).first();
2720
2721                    if (dayContainer.length < 1) {
2722                        dayContainer = $('#templates > [data-template=true]').clone().attr('data-day', entry.day);
2723
2724                        const insertAfter = $('#item-container > [data-template=true][data-day]').filter(function () {
2725                            return parseInt($(this).attr('data-day')) < entry.day;
2726                        }).last();
2727
2728                        if (insertAfter.length > 0) {
2729                            dayContainer.insertAfter(insertAfter);
2730                        } else {
2731                            dayContainer.appendTo('#item-container');
2732                        }
2733
2734                        $('[data-template-day-name]', dayContainer).text(new Date(data.year, data.month - 1, entry.day).toLocaleString('en-us', { weekday: 'long' }));
2735                        $('[data-template-day-number]', dayContainer).text(entry.day + nth(entry.day));
2736                        $('[data-template-header]', dayContainer).attr('data-day', entry.day);
2737                        $('.mtp-day-total', dayContainer).attr('data-day', entry.day);
2738                    }
2739
2740                    const processList = $(dayContainer).children('[data-template-process-list]').first();
2741
2742                    var processContainer = $(processList).children(`[data-template-process-list-item=true][data-process-number="${entry.processNumber}"]`).first();
2743
2744                    if (processContainer.length < 1 && entry.hours > 0) {
2745                        processContainer = $('#templates > [data-template-process-list-item=true]').clone()
2746                            .attr('data-day', entry.day)
2747                            .attr('data-process-number', entry.processNumber)
2748                            .attr('data-hours', entry.hours)
2749                            .attr('data-member-comments', entry.memberComments);
2750
2751                        if (!processDict[entry.processNumber].visible || dayDict[entry.day] === undefined) {
2752                            processContainer.addClass('d-none');
2753                        }
2754
2755                        const insertAfter = $(processList)
2756                            .children('[data-template-process-list-item=true][data-process-number]').filter(function () {
2757                                return parseInt($(this).attr('data-process-number')) < entry.processNumber;
2758                            }
2758).last();
2759
2760                        if (insertAfter.length > 0) {
2761                            processContainer.insertAfter(insertAfter);
2762                        } else {
2763                            processContainer.appendTo(processList);
2764                        }
2765
2766                        const process = processDict[entry.processNumber];
2767
2768                        $('[data-template-process-name]', processContainer).text(process.name);
2769                        $('[data-template-process-description]', processContainer).text(process.description);
2770                        $('[data-template-process-hours]', processContainer).text(entry.hours);
2771                        $('[data-template-process-member-comments]', processContainer).text(entry.memberComments);
2772                    } else {
2773                        let existingHours = parseFloat(processContainer.attr('data-hours'));
2774
2775                        if (isNaN(existingHours))
2776                            existingHours = 0;
2777
2778                        let existingMemberComments = processContainer.attr('data-member-comments')
2779
2780                        var newMemberComments = (existingMemberComments + ' ' + entry.memberComments).trim();
2781
2782                        processContainer.attr('data-hours', entry.hours + existingHours);
2783                        processContainer.attr('data-member-comments', newMemberComments);
2784
2785                        $('[data-template-process-hours]', processContainer).text(entry.hours + existingHours);
2786                        $('[data-template-process-member-comments]', processContainer).text(newMemberComments);
2787
2788                        if (entry.hours + existingHours <= 0) {
2789                            processContainer.remove();
2790                            processContainer = $(processContainer).filter(function () { return false }).first();
2791                        }
2792                    }
2793
2794                    updateDayContainerVisibility(dayContainer);
2795
2796                    return processContainer.length > 0 ? processContainer[0] : null;
2797                }
2798
2799                const deleteEntry = function (day, processNumber) {
2800                    $(`#item-container [data-template-process-list-item=true][data-day=${day}][data-process-number=${processNumber}]`).remove();
2801
2802                    $('#item-container > [data-template=true]').filter(function () {
2803                        updateDayContainerVisibility($(this));
2804
2805                        return ($(this)).children('[data-template-process-list=true]').children().length < 1;
2806                    }).remove();
2807                }
2808
2809                const updateTotals = function () {
2810                    const hours = {};
2811
2812                    const dayHours = {};
2813
2814                    $('#item-container [data-template-process-list-item=true][data-day][data-process-number][data-hours]').each(function () {
2815                        if (!$(this).hasClass('d-none')) {
2816                            const processNumber = $(this).attr('data-process-number');
2817                            const day = $(this).attr('data-day');
2818                            const existingHours = hours[processNumber] || 0;
2819                            const existingDayHours = dayHours[day] || 0;
2820
2821                            hours[processNumber] = existingHours + parseFloat($(this).attr('data-hours'));
2822                            dayHours[day] = existingDayHours + parseFloat($(this).attr('data-hours'));
2823                        }
2824                    });
2825
2826                    $('.mtp-day-total[data-day]').each(function () {
2827
2828                        const day = $(this).attr('data-day');
2829                        const existingDayHours = dayHours[day] || 0;
2830
2831                        $(this).text(existingDayHours);
2832                    });
2833
2834                    $('#grand-total-list').empty();
2835
2836                    var grandTotal = 0;
2837                    for (const element of data.processes) {
2838                        const total = hours[element.processNumber] || 0;
2839
2840                        if (total !== 0) {
2841                            const line = $('#templates > [data-template-process-total-line]').clone();
2842
2843                            $('[data-template-process-name]', line).text(processDict[element.processNumber].name);
2844                            $('[data-template-process-hours]', line).text(total);
2845
2846                            $('#grand-total-list').append(line);
2847                        }
2848
2849                        grandTotal += total;
2850                    }
2851
2852                    $('#grandTotal').text(grandTotal);
2853                }
2854
2855                const updateModelData = function () {
2856                    const hours = [];
2857                    const memberComments = [];
2858
2859                    $('#item-container [data-template-process-list-item=true][data-day][data-process-number][data-hours][data-member-comments]').each(function () {
2860                        hours.push({
2861                            day: $(this).attr('data-day'),
2862                            processNumber: $(this).attr('data-process-number'),
2863                            hours: $(this).attr('data-hours'),
2864                            memberComments: $(this).attr('data-member-comments')
2865                        });
2866                    });
2867
2868                    data.hours = hours;
2869                    data.memberComments = memberComments;
2870
2871                    modelInput.val(JSON.stringify(data));
2872                }
2873
2874                $('#deleteEntryDialog').on('show.bs.modal', function (e) {
2875                    dialogOpen = true;
2876
2877                    $(this).attr('data-day', $(e.relatedTarget).closest('[data-day]').attr('data-day'));
2878                    $(this).attr('data-process-number', $(e.relatedTarget).closest('[data-process-number]').attr('data-process-number'));
2879                });
2880
2881                $('#deleteEntryDialog').on('hidden.bs.modal', function () {
2882                    dialogOpen = false;
2883
2884                    $(this).removeAttr('data-day');
2885                    $(this).removeAttr('data-process-number');
2886                });
2887
2888                $('#deleteEntryDialog .mtp-yes-dialog-button').click(function () {
2889                    const day = parseInt($('#deleteEntryDialog').attr('data-day'));
2890                    const processNumber = parseInt($('#deleteEntryDialog').attr('data-process-number'));
2891
2892                    deleteEntry(day, processNumber);
2893                    updateModelData();
2894                    updateTotals();
2895
2896                    $('#deleteEntryDialog').modal('hide');
2897                });
2898
2899                $('#addEditModal select, #addEditModal input').change(function () {
2900                    $(this).removeClass('is-invalid');
2901                });
2902
2903                $('#addEditModal').on('show.bs.modal', function (e) {
2904                    dialogOpen = true;
2905
2906                    $(this).removeAttr('data-day');
2907                    $(this).removeAttr('data-process-number');
2908                    $(this).removeAttr('data-hours');
2909                    $(this).removeAttr('data-member-comments');
2910
2911                    $(this).attr('data-day', $(e.relatedTarget).closest('[data-day]').attr('data-day'));
2912                    $(this).attr('data-process-number', $(e.relatedTarget).closest('[data-process-number]').attr('data-process-number'));
2913                    $(this).attr('data-hours', $(e.relatedTarget).closest('[data-hours]').attr('data-hours'));
2914                    $(this).attr('data-member-comments', $(e.relatedTarget).closest('[data-member-comments]').attr('data-member-comments'));
2915
2916                    const day = parseInt($(this).attr('data-day'));
2917                    if (!isNaN(day)) {
2918                        $('#addEditDay').val(day).change();
2919                    }
2920
2921                    const processNumber = parseInt($(this).attr('data-process-number'));
2922                    if (!isNaN(processNumber)) {
2923                        $('#addEditProcessNumber').val(processNumber);
2924                    }
2925
2926                    const hours = parseFloat($(this).attr('data-hours'));
2927                    if (!isNaN(hours)) {
2928                        $('#addEditHours').val(hours);
2929                    }
2930
2931                    const memberComments = $(this).attr('data-member-comments')
2932                    $('#addEditMemberComments').val(memberComments);
2933
2934                    const isEdit = !isNaN(day) && !isNaN(processNumber) && !isNaN(hours);
2935
2936                    $(this).attr('data-is-edit', isEdit);
2937
2938                    $('#addEditModalLabel').text(isEdit ? 'Edit Entry' : 'Add Entry');
2939
2940                    if (isEdit) {
2941                        $('#buttonAdd').addClass('d-none');
2942                        $('#buttonEdit').removeClass('d-none');
2943                        $('#buttonDelete').removeClass('d-none');
2944                    } else {
2945                        $('#buttonAdd').removeClass('d-none');
2946                        $('#buttonEdit').addClass('d-none');
2947                        $('#buttonDelete').addClass('d-none');
2948                    }
2949                });
2950
2951                $('#addEditModal').on('hidden.bs.modal', function () {
2952                    $('#addEditProcessNumber option').removeAttr('selected');
2953                    $('#addEditProcessNumber option:first').attr('selected', 'selected');
2954                    $('#addEditEditDay option').removeAttr('selected');
2955                    $('#addEditDay option:first').attr('selected', 'selected');
2956                    $('#addEditHours').val('');
2957                    $('#addEaddEditMemberCommentsditHours').val('');
2958                    $('#addEditModal .is-invalid').removeClass('is-invalid');
2959                    $('#addEditDayPicker').datetimepicker('hide');
2960                    dialogOpen = false;
2961                });
2962
2963                $('#addEditModal').on('shown.bs.modal', function () {
2964                    $('#addEditProcessNumber').focus();
2965                });
2966
2967                $('#addEditDayPicker').each(function () {
2968                    $(this).datetimepicker('minDate', new Date(data.year, data.month - 1, data.days[0]));
2969                    $(this).datetimepicker('maxDate', new Date(data.year, data.month - 1, data.days[data.days.length - 1]));
2970                    $(this).on('change.datetimepicker', function (e) {
2971                        const day = new Date(e.date).getDate();
2972                        if (day) {
2973                            $('#addEditDay').val(new Date(e.date).getDate());
2974                            $('#addEditDay').removeClass('is-invalid');
2975                        }
2976                    });
2977                });
2978
2979                $('#addEditDay').change(function () {
2980                    const day = parseInt($(this).val());
2981
2982                    if (!isNaN(day)) {
2983                        $('#addEditDayPicker').datetimepicker('date', new Date(data.year, data.month - 1, day));
2984                    }
2985                });
2986
2987                $('#addEditProcessNumber').change(function () {
2988                    const description = $('#addEditProcessNumber option:selected').attr('data-description') || '';
2989
2990                    if (description.length > 0)
2991                        $('#addEditProcessDescription').removeClass('d-none').html($('<small/>').text(description));
2992                    else
2993                        $('#addEditProcessDescription').addClass('d-none').text();
2994                }).change();
2995
2996
2997                $('#buttonAddEdit').click(function (e) {
2998                    e.preventDefault();
2999
3000                    const hoursString = $('#addEditHours').val() || '';
3001                    const processNumber = parseInt($('#addEditProcessNumber').val());
3002                    const day = parseInt($('#addEditDay').val());
3003                    const hours = parseFloat(hoursString);
3004                    const memberComments = $('#addEditMemberComments').val() || '';
3005
3006                    if (!isNaN(day) && !isNaN(processNumber) && !isNaN(hours) && hours >= 0 && hours.toFixed(3) == hours) {
3007
3008                        $('#addEditModal').modal('hide');
3009
3010                        if ($('#addEditModal').attr('data-is-edit')) {
3011                            deleteEntry(parseInt($('#addEditModal').attr('data-day')), parseInt($('#addEditModal').attr('data-process-number')));
3012                        }
3013
3014                        const entryElement = addEditEntry({ day, processNumber, hours, memberComments });
3015
3016                        updateModelData();
3017                        updateTotals();
3018
3019                        if (entryElement && !isElementInViewport(entryElement)) {
3020                            $(entryElement).scrollView(-$('#mtp-site-header').height());
3021                        }
3022                    } else {
3023                        if (isNaN(processNumber))
3024                            $('#addEditProcessNumber').addClass('is-invalid');
3025                        else
3026                            $('#addEditProcessNumber').removeClass('is-invalid');
3027
3028                        if (isNaN(day))
3029                            $('#addEditDay').addClass('is-invalid');
3030                        else
3031                            $('#addEditDay').removeClass('is-invalid');
3032
3033                        if (isNaN(hours) || hours < 0 || hours.toFixed(3) != hours) {
3034                            if (hours < 0)
3035                                $('#addEditHoursError').text('The hours entered cannot be negative.');
3036                            else if (hours.toFixed(3) != hours && !isNaN(hours))
3037                                $('#addEditHoursError').text('The hours entered cannot have more than 3 decimal points.');
3038                            else if (isEmptyOrSpaces(hoursString))
3039                                $('#addEditHoursError').text('Enter your hours.');
3040                            else
3041                                $('#addEditHoursError').text('Enter a valid number for your hours.');
3042
3043                            $('#addEditHours').addClass('is-invalid');
3044                        }
3045                        else
3046                            $('#addEditHours').removeClass('is-invalid');
3047                    }
3048                });
3049
3050            }
3051        });
3052
3053        $('#confirm-class-accept-dialog, #confirm-class-decline-dialog').each(function () {
3054            const dialog = $(this);
3055            var href;
3056            var confirmationCode;
3057
3058            $(dialog).on('show.bs.modal',
3059                function (event) {
3060                    href = $(event.relatedTarget).attr('href');
3061                    confirmationCode = $(event.relatedTarget).data('confirmation-code');
3062                });
3063
3064            $('.mtp-yes-dialog-button', dialog).click(function () {
3065                const request = $.ajax({
3066                    type: 'POST',
3067                    url: href + '?confirmationCode=' + encodeURIComponent(confirmationCode),
3068                    contentType: 'application/json; charset=utf-8'
3069                });
3070
3071                request.always(function () {
3072
3073                    $(dialog).on('hidden.bs.modal',
3074                        function () {
3075                            window.location.reload(true);
3076                        });
3077
3078                    $(dialog).modal('hide');
3079                });
3080            });
3081        });
3082
3083        function AuthorizeNetAcceptHostIFrameLoadFailure() {
3084            if (!$('#authorize-net-accept-hosted-iframe-load-failure').hasClass('mtp-iframe-loaded')) {
3085                $('#authorize-net-accept-hosted-iframe-loading').addClass('d-none');
3086                $('#authorize-net-accept-hosted-iframe-load-failure').addClass('alert alert-danger');
3087                $('#authorize-net-accept-hosted-iframe-load-failure').text('There was a failure loading the payment form.  Please try again later.');
3088                $('#authorize-net-accept-hosted-iframe-load-failure').removeClass('d-none');
3089            }
3090
3091            if ($('#authorize-net-accept-hosted-iframe-load-failure').hasClass('mtp-iframe-loaded')) {
3092                $('#authorize-net-accept-hosted-iframe-load-failure').addClass('d-none');
3093                $('#authorize-net-accept-hosted-iframe-loading').addClass('d-none');
3094            }
3095        }
3096
3097        $('#submit-authorize-net-accept-hosted-payment').each(function () {
3098
3099            var perfEntries = performance.getEntriesByType("navigation");
3100
3101            if (perfEntries[0].type === 'back_forward') {
3102                location.reload(true);
3103                return;
3104            }
3105
3106            if (!window.AuthorizeNetIFrame) window.AuthorizeNetIFrame = {};
3107            AuthorizeNetIFrame.onReceiveCommunication = function (qryStr) {
3108                const iframe = document.getElementById('authorize-net-accept-hosted-iframe');
3109
3110                $('#authorize-net-accept-hosted-iframe-load-failure').addClass('mtp-iframe-loaded');
3111                $('#authorize-net-accept-hosted-iframe-load-failure, #authorize-net-accept-hosted-iframe-loading').addClass('d-none');
3112
3113                const params = parseQueryString(qryStr);
3114                switch (params['action']) {
3115                    case 'successfulSave':
3116                        break;
3117                    case 'cancel':
3118                        $('#authorize-net-accept-hosted-response-cancel-form').submit();
3119                        break;
3120                    case 'resizeWindow':
3121                        var h = parseInt(params['height']);
3122                        iframe.style.height = h.toString() + 'px';
3123                        break;
3124                    case 'transactResponse':
3125                        $('#authorize-net-accept-hosted-response').val(params['response']);
3126                        $('#authorize-net-accept-hosted-response-form').submit();
3127                        break;
3128                }
3129            };
3130
3131            $('#authorize-net-accept-hosted-iframe-submit-form').submit();
3132
3133            setTimeout(AuthorizeNetAcceptHostIFrameLoadFailure, 10000);
3134        });
3135
3136        $('#add-edit-authorize-net-payment-method-dialog').each(function () {
3137            const dialog = $(this);
3138            var targetForm;
3139            var timeoutId;
3140
3141            $(dialog).on('hidden.bs.modal',
3142                function () {
3143                    $("#authorize-net-accept-hosted-iframe").attr('src', 'about:blank').height("25%");
3144                });
3145
3146            $(dialog).on('hidden.bs.modal', function () {
3147                clearTimeout(timeoutId);
3148            });
3149
3150            $(dialog).on('show.bs.modal',
3151                function (event) {
3152
3153                    const iframe = document.getElementById('authorize-net-accept-hosted-iframe');
3154                    iframe.style.height = 0;
3155
3156                    $('#authorize-net-accept-hosted-iframe-load-failure').removeClass('mtp-iframe-loaded');
3157                    $('#authorize-net-accept-hosted-iframe-load-failure').addClass('d-none');
3158                    $('#authorize-net-accept-hosted-iframe-loading').removeClass('d-none');
3159
3160                    if ($(event.relatedTarget).data('is-edit'))
3161                        $(dialog).find('.modal-title').text('Edit Payment Profile');
3162                    else
3163                        $(dialog).find('.modal-title').text('Add Payment Profile');
3164
3165                    let selector = $(event.relatedTarget).data('success-form-target');
3166
3167                    if (selector)
3168                        targetForm = $(selector);
3169
3170                    timeoutId = setTimeout(AuthorizeNetAcceptHostIFrameLoadFailure, 10000);
3171                });
3172
3173            var perfEntries = performance.getEntriesByType("navigation");
3174
3175            if (perfEntries[0].type === 'back_forward') {
3176                location.reload(true);
3177                return;
3178            }
3179
3180            if (!window.AuthorizeNetIFrame) window.AuthorizeNetIFrame = {};
3181            AuthorizeNetIFrame.onReceiveCommunication = function (qryStr) {
3182                const iframe = document.getElementById('authorize-net-accept-hosted-iframe');
3183
3184                $('#authorize-net-accept-hosted-iframe-load-failure').addClass('mtp-iframe-loaded');
3185                $('#authorize-net-accept-hosted-iframe-load-failure, #authorize-net-accept-hosted-iframe-loading').addClass('d-none');
3186
3187                const params = parseQueryString(qryStr);
3188                switch (params['action']) {
3189                    case 'successfulSave':
3190
3191                        $(dialog).on('hidden.bs.modal',
3192                            function () {
3193                                $('.mtp-full-page-wait-overlay-container').removeClass("d-none");
3194
3195                                setTimeout(() => {
3196                                    if (targetForm) {
3197                                        $(targetForm).submit();
3198                                    }
3199                                    else {
3200                                        window.location.reload(true);
3201                                    }
3202                                }, 1000);
3203                            });
3204
3205                        $('a[data-toggle],form[data-toggle]').removeAttr('data-toggle');
3206                        $(dialog).removeClass('fade');
3207                        $(dialog).modal('hide');
3208                        break;
3209                    case 'cancel':
3210                        $(dialog).modal('hide');
3211                        break;
3212                    case 'resizeWindow':
3213                        var h = parseInt(params['height']);
3214                        iframe.style.height = h.toString() + 'px';
3215
3216                        break;
3217                }
3218            };
3219        });
3220
3221        $('#confirm-remove-payment-method-dialog').each(function () {
3222            const dialog = $(this);
3223            var url;
3224            var item;
3225
3226            $(dialog).on('show.bs.modal',
3227                function (event) {
3228                    url = $(event.relatedTarget).data('url');
3229                    item = $(event.relatedTarget).parents('.mtp-payment-method');
3230
3231                });
3232
3233            $('.mtp-yes-dialog-button', dialog).click(function () {
3234                const request = $.ajax({
3235                    type: 'POST',
3236                    url: url,
3237                    contentType: 'application/json; charset=utf-8'
3238                });
3239
3240                request.always(function () {
3241                    $(item).fadeOut();
3242
3243                    $(dialog).on('hidden.bs.modal',
3244                        function () {
3245                            $('.mtp-full-page-wait-overlay-container').removeClass("d-none");
3246
3247                            setTimeout(() => {
3248                                window.location.reload(true);
3249                            }, 1000);
3250                        });
3251
3252                    $(dialog).removeClass('fade');
3253                    $(dialog).modal('hide');
3254                });
3255            });
3256        });
3257
3258        $('input.authorize-net-default-payment-method').click(function (e) {
3259            e.preventDefault();
3260        });
3261
3262        $('#confirm-make-default-payment-method-dialog').each(function () {
3263            const dialog = $(this);
3264            var url;
3265            var check;
3266
3267            $(dialog).on('show.bs.modal',
3268                function (event) {
3269                    url = $(event.relatedTarget).data('url');
3270                    check = $(event.relatedTarget);
3271                });
3272
3273            $('.mtp-yes-dialog-button', dialog).click(function () {
3274                const request = $.ajax({
3275                    type: 'POST',
3276                    url: url,
3277                    contentType: 'application/json; charset=utf-8'
3278                });
3279
3280                request.always(function () {
3281                    $(check).prop('checked', 'checked');
3282
3283                    $(dialog).on('hidden.bs.modal',
3284                        function () {
3285                            $('.mtp-full-page-wait-overlay-container').removeClass("d-none");
3286
3287                            setTimeout(() => {
3288                                window.location.reload(true);
3289                            }, 1000);
3290                        });
3291
3292                    $(dialog).removeClass('fade');
3293                    $(dialog).modal('hide');
3294                });
3295            });
3296        });
3297
3298        $('#cancel-contractor-emergency-worker-request-dialog .mtp-yes-dialog-button').click(function (e) {
3299            e.preventDefault();
3300
3301            $(this).attr('disabled', true);
3302
3303            const request = $.ajax({
3304                type: "POST",
3305                url: $('#cancel-contractor-emergency-worker-request-dialog').data("url"),
3306                contentType: "application/json; charset=utf-8"
3307            });
3308
3309            request.done(function () {
3310                const tr = $('#cancel-contractor-emergency-worker-request-dialog').data("row");
3311
3312                $(".mtp-contractor-emergency-worker-request-request-status", tr).text("CANCELED");
3313                $(".mtp-edit-contractor-emergency-worker-request-button", tr).remove();
3314                $(".mtp-cancel-contractor-emergency-worker-request-button", tr).remove();
3315
3316                $('#cancel-contractor-emergency-worker-request-dialog').modal('hide');
3317            });
3318
3319            request.fail(function () {
3320                $('#cancel-contractor-emergency-worker-request-dialog').data("has-error", true);
3321                $('#cancel-contractor-emergency-worker-request-dialog').modal('hide');
3322            });
3323        });
3324
3325        $('#cancel-contractor-emergency-worker-request-dialog').on('show.bs.modal',
3326            function () {
3327                $(this).data("has-error", false);
3328
3329                $("button", $(this)).each(function () {
3330                    $(this).removeAttr("disabled");
3331                });
3332            });
3333
3334        $('#cancel-contractor-emergency-worker-request-dialog').on('hidden.bs.modal',
3335            function () {
3336                if ($(this).data("has-error") === true) {
3337                    $("#cancel-contractor-emergency-worker-request-error-dialog").modal();
3338                }
3339            });
3340
3341        $(".mtp-cancel-contractor-emergency-worker-request-button").click(function (event) {
3342            event.preventDefault();
3343            const url = $(this).closest("a").prop("href");
3344            const tr = $(this).closest("tr");
3345
3346            $('#cancel-contractor-emergency-worker-request-dialog').data('url', url);
3347            $('#cancel-contractor-emergency-worker-request-dialog').data('row', tr);
3348
3349            $('#cancel-contractor-emergency-worker-request-dialog').modal();
3350        });
3351
3352        $('#confirm-submit-contractor-emergency-worker-request-dialog .mtp-yes-dialog-button').click(function (e) {
3353            e.preventDefault();
3354
3355            $(this).attr('disabled', true);
3356
3357            const request = $.ajax({
3358                type: "POST",
3359                url: $('#confirm-submit-contractor-emergency-worker-request-dialog').data("postUrl"),
3360                contentType: "application/json; charset=utf-8"
3361            });
3362
3363            request.done(function () {
3364                window.location.href = $('#confirm-submit-contractor-emergency-worker-request-dialog').data("success-url");
3365            });
3366
3367            request.fail(function () {
3368                $('#confirm-submit-contractor-emergency-worker-request-dialog').data("has-error", true).modal('hide');
3369            });
3370        });
3371
3372        $('#confirm-submit-contractor-emergency-worker-request-dialog').on('show.bs.modal',
3373            function () {
3374                $(this).data("has-error", false);
3375
3376                $("button", $(this)).each(function () {
3377                    $(this).removeAttr("disabled");
3378                });
3379            });
3380
3381        $('#confirm-submit-contractor-emergency-worker-request-dialog').on('hidden.bs.modal',
3382            function () {
3383                if ($(this).data("has-error") === true) {
3384                    $("#submit-contractor-emergency-worker-request-dialog-error-dialog").modal();
3385                }
3386            });
3387
3388        $(".mtp-submit-contractor-emergency-worker-request").click(function (event) {
3389            event.preventDefault();
3390            const postUrl = $(this).closest("a").prop("href");
3391            const successUrl = $(this).closest("a").data("success-url");
3392
3393            $('#confirm-submit-contractor-emergency-worker-request-dialog')
3394                .data('post-url', postUrl)
3395                .data('success-url', successUrl)
3396                .modal();
3397        });
3398
3399        $('#force-page-reload-on-back-or-forward-navigation').each(function () {
3400            var perfEntries = performance.getEntriesByType("navigation");
3401
3402            if (perfEntries[0].type === 'back_forward') {
3403                location.reload(true);
3404                return;
3405            }
3406        });
3407
3408        $('#member-emergency-work-request-accept-button').click(function (e) {
3409            e.preventDefault();
3410
3411            $('#confirm-accept-member-emergency-work-request-dialog').modal();
3412        });
3413
3414        $('#confirm-accept-member-emergency-work-request-dialog .mtp-yes-dialog-button').click(function (e) {
3415            e.preventDefault();
3416
3417            $('#confirm-accept-member-emergency-work-request-dialog').modal('hide');
3418
3419            var form = $('<form></form>');
3420
3421            form.attr("method", "post");
3422            form.attr("action", $('#member-emergency-work-request-accept-button').attr("href"));
3423
3424            $('<input>', {
3425                type: 'hidden',
3426                name: 'AntiforgeryToken',
3427                value: getAntiForgeryToken()
3428            }).appendTo(form);
3429
3430            $(document.body).append(form);
3431            form.submit();
3432        });
3433
3434        $('#member-emergency-work-request-refuse-button').click(function (e) {
3435            e.preventDefault();
3436
3437            $('#confirm-refuse-member-emergency-work-request-dialog').modal();
3438        });
3439
3440        $('#confirm-refuse-member-emergency-work-request-dialog .mtp-yes-dialog-button').click(function (e) {
3441            e.preventDefault();
3442
3443            $('#confirm-refuse-member-emergency-work-request-dialog').modal('hide');
3444
3445            var form = $('<form></form>');
3446
3447            form.attr("method", "post");
3448            form.attr("action", $('#member-emergency-work-request-refuse-button').attr("href"));
3449
3450            $('<input>', {
3451                type: 'hidden',
3452                name: 'AntiforgeryToken',
3453                value: getAntiForgeryToken()
3454            }).appendTo(form);
3455
3456            $(document.body).append(form);
3457            form.submit();
3458        });
3459
3460        $('#request-work-form #IsRemoveFromReferralListsRequested').change(function () {
3461            if (this.checked) {
3462                $('#IsCheckIntoReferralListRequested').prop('checked', false);
3463                $('#IsCheckIntoReferralListRequested').attr("disabled", true);
3464            }
3465            else {
3466                $('#IsCheckIntoReferralListRequested').removeAttr("disabled");
3467            }
3468        });
3469
3470        $('#request-work-form #IsCheckIntoReferralListRequested').change(function () {
3471            if (this.checked) {
3472                $('#IsRemoveFromReferralListsRequested').prop('checked', false);
3473                $('#IsRemoveFromReferralListsRequested').attr("disabled", true);
3474            }
3475            else {
3476                $('#IsRemoveFromReferralListsRequested').removeAttr("disabled");
3477            }
3478        });
3479
3480        $('a.add-job-termination-request').click(function () {
3481            $('#MemberReferralCallID').val($(this).data("member-referral-call-id"));
3482        });
3483
3484        $('#contractor-members-working-terminate-employment-dialog').on('hidden.bs.modal',
3485            function () {
3486                $('form').trigger("reset");
3487                $('input, select').removeClass('input-validation-error')
3488            });
3489
3490        $('#addMemberCommentDialog').each(function () {
3491            const dialog = $(this);
3492            let firstTime = true;
3493            var form = $("form", $(dialog));
3494
3495            $(dialog).on('show.bs.modal',
3496                function () {
3497                    if (firstTime) {
3498                        firstTime = false;
3499
3500                        const request = $.ajax({
3501                            type: 'GET',
3502                            url: $('#addMemberCommentCategory').data("url"),
3503                            contentType: 'application/json; charset=utf-8'
3504                        });
3505                        request.done(function (data) {
3506                            $.each(data, function (index) {
3507                                $("#addMemberCommentCategory").append('<option value=' + (data[index].id || '') + '>' + data[index].description + '</option>');
3508                            });
3509                        });
3510                    }
3511
3512                    $('#addMemberCommentCategory', $(form)).val('');
3513                    $('#addMemberCommentHours', $(form)).val('');
3514
3515                    $('#addMemberCommentDateTimePicker').datetimepicker('date', new Date());
3516                    $('input[name="IsShownWithAlert"]', $(form)).prop('checked', false);
3517                });
3518
3519            $("#buttonOk").click(function (event) {
3520                event.preventDefault();
3521                let button = $(this);
3522                let url = $(form).attr('action');
3523
3524                $('#addMemberError').addClass('d-none');
3525        
3526                if ($('#addMemberCommentDateTimePicker').datetimepicker('date') == null) {
3527                    $('#addMemberError').removeClass('d-none');
3528                    $('#addMemberError').text("A valid ate/time is required.");
3529                    return;
3530                }
3531                
3532                var comment = $('#addMemberCommentHours', $(form)).val();
3533
3534                if (comment.match(/^\s*$/)) {
3535                    $('#addMemberError').removeClass('d-none');
3536                    $('#addMemberError').text("A comment is required.");
3537                    return;
3538                }
3539
3540                $(button).attr('disabled', true);
3541                
3542                var formValues = $(form).serialize();
3543
3544                const request = $.ajax({
3545                    type: "POST",
3546                    url: url,
3547                    data: formValues
3548                });
3549
3550                request.done(function () {
3551                    window.location.reload(true);
3552                });
3553
3554                request.fail(function (jqXHR) {
3555                    $(button).removeAttr('disabled');
3556
3557                    $('#addMemberError').removeClass('d-none');
3558                    $('#addMemberError').text(jqXHR.statusText);
3559                });
3560            });
3561        });
3562                       
3563        $('#send-member-text-message-dialog-message, #send-members-text-messages-dialog-message').on('paste', function() {
3564            var el = $(this);
3565            setTimeout(function () {
3566                let value = el.val().replace(/\s+/g, ' ');
3567
3568                if (el.val() != value) {
3569                    el.val(value)
3570                }
3571           });
3572        });
3573
3574        $('#send-member-text-message-dialog-message, #send-members-text-messages-dialog-message').on('keydown', function(event){
3575            if(event.key === 'Enter' || event.key === 'NumpadEnter') {
3576                event.preventDefault();
3577                return false;
3578            }
3579        });
3580
3581        $('#send-member-text-message-dialog').each(function () {
3582            const accountInfoUrl = $(this).data("account-info-url");
3583            const validateMessageUrl = $(this).data("validate-url");
3584            const sendMessageUrl = $(this).data("send-url");
3585
3586            var creditSchedule = null;
3587            var maxMessageLength = null;
3588            var termsOfUsageText = null;
3589            var memberId = null;
3590            var phoneNumberField = null;
3591            var wasSendSuccessful = false;
3592            var anchor = null;
3593            var contactAction = null;
3594
3595            $('#contact-member-by-phone-number-call-button').on("click", function() {
3596                contactAction = 'call';
3597            });
3598
3599            $('#contact-member-by-phone-number-text-button').on("click", function() {
3600                contactAction = 'text';
3601            });
3602
3603            $('#contact-member-by-phone-number-dialog').on('show.bs.modal', function () {
3604                $('#contact-member-by-phone-number-wait-container').removeClass('d-none');
3605                contactAction = null;
3606            });
3607
3608            $('#contact-member-by-phone-number-dialog').on('hidden.bs.modal', function () {
3609                if (contactAction == 'call') {
3610                    $('#contact-member-by-phone-number-wait-container').addClass('d-none');
3611                    performCallContactAction();
3612                } else if (contactAction == 'text') {
3613                    performTextContactAction();
3614                }
3615                else {
3616                    $('#contact-member-by-phone-number-wait-container').addClass('d-none');
3617                }
3618            });
3619
3620            $('a[data-member-id][data-phone-number-field]').on("click", function( event ) {
3621                event.preventDefault();
3622                anchor = $(this);
3623
3624                memberId = $(this).data('member-id');
3625                phoneNumberField = $(this).data('phone-number-field');
3626              
3627                $('#contact-member-by-phone-number-dialog').modal('show');
3628            });
3629
3630            function performCallContactAction() { 
3631                window.location = $(anchor).attr('href');
3632            }
3633
3634            function performTextContactAction() {
3635                wasSendSuccessful = false;
3636
3637                $.ajax({
3638                    type: "GET",
3639                    url: accountInfoUrl
3640                })
3641                .done(function (accountInfo) {
3642                    const creditBalance = accountInfo.CreditBalance;
3643                    termsOfUsageText = accountInfo.TermsOfUsageText;
3644                    creditSchedule = new Map(accountInfo.CreditSchedule.map(obj => [obj.MessageLength, obj.CreditsRequired]));
3645                    maxMessageLength = accountInfo.MaxMessageLength;
3646
3647                    if (creditBalance < 1) {
3648                        showErrorDialog('You do not have any text messaging credits.');
3649                    }
3650                    else {
3651                        $.ajax({
3652                            type: "GET",
3653                            url: validateMessageUrl,
3654                            data: { memberId, phoneNumberField }
3655                        })  
3656                        .done(function (validateResult) {
3657                            if (validateResult.IsSuccessful) {
3658                                resetForm();
3659                                $('#send-member-text-message-dialog').modal('show');
3660                            }
3661                            else {
3662                                showErrorDialog(validateResult.ErrorMessage);
3663                            }
3664                        })
3665                        .fail(function (_jqXHR, textStatus, errorThrown) {
3666                            showErrorDialog('An unexpected error occurred.  Please try again later.');
3667                            console.error(textStatus);
3668                            if (errorThrown) {
3669                                console.error(errorThrown);
3670                            }
3671                        });
3672                    }
3673                })
3674                .fail(function (_jqXHR, textStatus, errorThrown) {
3675                    showErrorDialog('An unexpected error occurred.  Please try again later.');
3676                    console.error(textStatus);
3677                    if (errorThrown) {
3678                        console.error(errorThrown);
3679                    }
3680                });
3681            };
3682                        
3683            $('#send-member-text-message-dialog-message').on('input', function() {
3684                updateMessageLengthLabel();
3685                updateMessageSendButton();
3686            });
3687
3688            $('#send-member-text-message-dialog-terms-of-service-checkbox').on('input', function() {
3689                updateMessageLengthLabel();
3690                updateMessageSendButton();
3691            });
3692
3693            $('#send-member-text-message-dialog').on('shown.bs.modal', function() {
3694                $('#send-member-text-message-dialog-terms-of-service-textarea').scrollTop(0);
3695                $('#send-member-text-message-dialog-message').trigger("focus");
3696            });
3697
3698            $('#send-member-text-message-dialog').on('show.bs.modal', function () {
3699                if (phoneNumberField == 'MobilePhone') {
3700                    $('#send-member-text-message-dialog-non-mobile-phone-number-warning').addClass('d-none');
3701                }
3702                else { 
3703                    $('#send-member-text-message-dialog-non-mobile-phone-number-warning').removeClass('d-none');
3704                }
3705            });
3706
3707            $('#send-member-text-message-dialog').on('hidden.bs.modal', function() {
3708                if (wasSendSuccessful) {
3709                    $('#send-member-text-message-success-dialog').modal('show');
3710                } else {
3711                    $('#contact-member-by-phone-number-wait-container').addClass('d-none');
3712                }
3713            });
3714            
3715            function resetForm() {
3716                $('#send-member-text-message-dialog-close-window-button').removeClass('d-none');
3717                $('#send-member-text-message-dialog-cancel-button').prop('disabled', false);
3718                $('#send-member-text-message-dialog-message').prop('disabled', false);
3719                $('#send-member-text-message-dialog-terms-of-service-checkbox').prop('disabled', false);
3720                $('#send-member-text-message-dialog-terms-of-service-checkbox').prop('checked', false);
3721                $('#send-member-text-message-dialog-send-button').text('Send');
3722
3723                $('#send-member-text-message-dialog-message').val('');
3724                $('#send-member-text-message-dialog-message').prop('maxLength', maxMessageLength);
3725                $('#send-member-text-message-dialog-terms-of-service-textarea').text(termsOfUsageText);
3726                
3727                $('#send-member-text-message-dialog-error-message').text('');
3728                
3729                updateMessageLengthLabel();
3730                updateMessageSendButton();
3731            }
3732
3733            function updateMessageSendButton() {
3734                const disabled = $('#send-member-text-message-dialog-message').val().trim().length < 1 || $('#send-member-text-message-dialog-terms-of-service-checkbox').prop('checked') == false;
3735
3736                $('#send-member-text-message-dialog-send-button').prop('disabled', disabled);
3737            }
3738
3739            function updateMessageLengthLabel() {
3740                const message = $('#send-member-text-message-dialog-message').val().trim();
3741
3742                const messageLength = message.length;
3743                const charactersRemaining = maxMessageLength - messageLength;
3744                const credits = creditSchedule.get(messageLength);
3745
3746                if (message.length < 1) {
3747                    $('#send-member-text-message-dialog-message-length').text(' ');
3748                } else {
3749                    $('#send-member-text-message-dialog-message-length').text(`${messageLength} character${messageLength==1 ? '' : 's'}, ${credits} credit${credits==1 ? '' : 's'}. (${charactersRemaining} character${charactersRemaining==1 ? '' : 's'} remaining)`);
3750                }
3751            }
3752
3753            function showError(message) {
3754                $('#send-member-text-message-dialog-close-window-button').removeClass('d-none');
3755                $('#send-member-text-message-dialog-cancel-button').prop('disabled', false);
3756                $('#send-member-text-message-dialog-message').prop('disabled', false);
3757                $('#send-member-text-message-dialog-terms-of-service-checkbox').prop('disabled', false);
3758                $('#send-member-text-message-dialog-send-button').text('Send');
3759                $('#send-member-text-message-dialog-error-message').text(message);
3760
3761                updateMessageSendButton();
3762            }
3763            
3764            $('#send-member-text-message-dialog-send-button').on('click', function (event) {
3765                event.preventDefault();
3766                                
3767                $('#send-member-text-message-dialog-send-button').prop('disabled', true);
3768                $('#send-member-text-message-dialog-send-button').text('Sending...');
3769                $('#send-member-text-message-dialog-cancel-button').prop('disabled', true);
3770                $('#send-member-text-message-dialog-message').prop('disabled', true);
3771                $('#send-member-text-message-dialog-terms-of-service-checkbox').prop('disabled', true);
3772                
3773                $('#send-member-text-message-dialog-close-window-button').addClass('d-none');
3774
3775                const message = $('#send-member-text-message-dialog-message').val().trim();
3776
3777                $.ajax({
3778                    type: "POST",
3779                    url: sendMessageUrl,
3780                    data: { memberId, phoneNumberField, message }
3781                })
3782                .done(function (sendResult) {
3783                    if (sendResult.IsSuccessful) {
3784                        wasSendSuccessful = true;
3785                        $('#send-member-text-message-dialog').modal('hide');
3786                    }
3787                    else {
3788                        showError('Your message was not sent. ' + sendResult.ErrorMessage);
3789                    }
3790                })                
3791                .fail(function (_jqXHR, textStatus, errorThrown) {
3792                    showError('An unexpected error occurred.  Please try');
3793                    console.error(textStatus);
3794                    if (errorThrown) {
3795                        console.error(errorThrown);
3796                    }
3797                });
3798            });
3799
3800            function showErrorDialog(message) {
3801                $('#send-member-text-message-error-dialog .modal-body').text(message);
3802                $('#send-member-text-message-error-dialog').modal('show');
3803            }
3804
3805            $('#send-member-text-message-error-dialog').on('hidden.bs.modal', function() {
3806               $('#contact-member-by-phone-number-wait-container').addClass('d-none');
3807            });
3808            
3809            $('#send-member-text-message-success-dialog').on('hidden.bs.modal', function() {
3810               $('#contact-member-by-phone-number-wait-container').addClass('d-none');
3811            });
3812        });
3813
3814        if ($('#send-members-text-messages-dialog').length > 0) {
3815            var accountInfoUrl = null;
3816            var validateCanCreateBatchUrl = null;
3817            var calculateNumberOfMessagesUrl = null;
3818            var sendMessageUrl = null;
3819            var creditSchedule = null;
3820            var maxMessageLength = null;
3821            var termsOfUsageText = null;
3822            var wasSendSuccessful = false;
3823            var totalMessageCount = 0;
3824            var isCalculatingTotalMessageCount =  false;
3825            var calculateTotalMessageCountRequest = null;
3826
3827            $('#send-members-text-messages-button').on('click', function(event) {
3828                event.preventDefault();
3829                $('#send-members-text-messages-wait-container').removeClass('d-none');
3830
3831                accountInfoUrl = $(this).data("account-info-url");
3832                validateCanCreateBatchUrl = $(this).data("validate-can-create-batch-url");
3833                calculateNumberOfMessagesUrl = $(this).data("calculate-number-of-messages-url");
3834                sendMessageUrl = $(this).data("send-url");
3835                totalMessageCount = 0;
3836                isCalculatingTotalMessageCount =  false;
3837                wasSendSuccessful = false;
3838
3839                $.ajax({
3840                    type: "GET",
3841                    url: accountInfoUrl
3842                })
3843                .done(function (accountInfo) {
3844                    const creditBalance = accountInfo.CreditBalance;
3845                    termsOfUsageText = accountInfo.TermsOfUsageText;
3846                    creditSchedule = new Map(accountInfo.CreditSchedule.map(obj => [obj.MessageLength, obj.CreditsRequired]));
3847                    maxMessageLength = accountInfo.MaxMessageLength;
3848
3849                    if (creditBalance < 1) {
3850                        showErrorDialog('You do not have any text messaging credits.');
3851                    }
3852                    else {
3853                        $.ajax({
3854                            type: "GET",
3855                            url: validateCanCreateBatchUrl
3856                        })  
3857                        .done(function (validateResult) {
3858                            if (validateResult.IsSuccessful) {
3859                                resetForm();
3860                                $('#send-members-text-messages-dialog-message-scheduled-date-time').datetimepicker('minDate', new Date());
3861                                $('#send-members-text-messages-dialog-message-scheduled-date-time').datetimepicker('date', new Date());
3862                                $('#send-members-text-messages-dialog').modal('show');
3863                            }
3864                            else {
3865                                showErrorDialog(validateResult.ErrorMessage);
3866                            }
3867                        })
3868                        .fail(function (_jqXHR, textStatus, errorThrown) {
3869                            showErrorDialog('An unexpected error occurred.  Please try again later.');
3870                            console.error(textStatus);
3871                            if (errorThrown) {
3872                                console.error(errorThrown);
3873                            }
3874                        });
3875                    }
3876                })
3877                .fail(function (_jqXHR, textStatus, errorThrown) {
3878                    showErrorDialog('An unexpected error occurred.  Please try again later.');
3879                    console.error(textStatus);
3880                    if (errorThrown) {
3881                        console.error(errorThrown);
3882                    }
3883                });
3884            });
3885
3886            let startCalculateTotalMessageCount = Date.now();
3887
3888            function calculateTotalMessageCount() {
3889                if (!isCalculatingTotalMessageCount) {
3890                    startCalculateTotalMessageCount = Date.now();
3891                    isCalculatingTotalMessageCount = true;
3892                }
3893
3894                if (calculateTotalMessageCountRequest) {
3895                    calculateTotalMessageCountRequest.abort();
3896                }
3897
3898                calculateTotalMessageCountRequest = $.ajax({
3899                    type: "GET",
3900                    url: calculateNumberOfMessagesUrl,
3901                    data: 
3902                    { 
3903                        sendToPrimaryPhone: $('#send-members-text-messages-dialog-primary-phone-checkbox').prop('checked'),
3904                        sendToSecondaryPhone: $('#send-members-text-messages-dialog-secondary-phone-checkbox').prop('checked'),
3905                        sendToMobilePhone: $('#send-members-text-messages-dialog-mobile-phone-checkbox').prop('checked')
3906                    }
3907                }) 
3908                .done(function (calculateResult) {
3909                    totalMessageCount = calculateResult.MessageCount;
3910                    isCalculatingTotalMessageCount = false;
3911                })
3912                .always(function () {
3913                    const end = Date.now();
3914                    const elapsed = end - startCalculateTotalMessageCount;
3915                    const minDelay = 500;
3916                    const delay = elapsed < minDelay ? minDelay-elapsed : 0;
3917                    
3918                    setTimeout(function () {
3919                        updateMessageLengthLabel();
3920                        updateMessageSendButton();
3921                    }, delay);
3922                });
3923            }
3924
3925            $('#send-members-text-messages-dialog-message').on('input', function() {
3926                updateMessageLengthLabel();
3927                updateMessageSendButton();
3928            });
3929
3930            $('#send-members-text-messages-dialog-terms-of-service-checkbox').on('input', function() {
3931                updateMessageLengthLabel();
3932                updateMessageSendButton();
3933            });
3934
3935            $('#send-members-text-messages-dialog-primary-phone-checkbox').on('input', function() {
3936                calculateTotalMessageCount();
3937                updateMessageLengthLabel();
3938                updateMessageSendButton();
3939            });
3940
3941            $('#send-members-text-messages-dialog-secondary-phone-checkbox').on('input', function() {
3942                calculateTotalMessageCount();
3943                updateMessageLengthLabel();
3944                updateMessageSendButton();
3945            });
3946                                
3947            $('#send-members-text-messages-dialog-mobile-phone-checkbox').on('input', function() {
3948                calculateTotalMessageCount();
3949                updateMessageLengthLabel();
3950                updateMessageSendButton();
3951            });
3952
3953            $('#send-members-text-messages-dialog').on('shown.bs.modal', function() {
3954                $('#send-members-text-messages-dialog-terms-of-service-textarea').scrollTop(0);
3955                $('#send-members-text-messages-dialog-message').trigger("focus");
3956            });
3957
3958            $('#send-members-text-messages-dialog').on('hidden.bs.modal', function() {
3959                if (wasSendSuccessful) {
3960                    $('#send-members-text-messages-success-dialog').modal('show');
3961                } else {
3962                    $('#send-members-text-messages-wait-container').addClass('d-none');
3963                }
3964            });
3965            
3966            function resetForm() {
3967                $('#send-members-text-messages-dialog-close-window-button').removeClass('d-none');
3968                $('#send-members-text-messages-dialog-cancel-button').prop('disabled', false);
3969                $('#send-members-text-messages-dialog-message').prop('disabled', false);
3970                $('#send-members-text-messages-dialog-terms-of-service-checkbox').prop('disabled', false);
3971                $('#send-members-text-messages-dialog-terms-of-service-checkbox').prop('checked', false);
3972                $('#send-members-text-messages-dialog-send-button').text('Send');
3973
3974                $('#send-members-text-messages-dialog-message').val('');
3975                $('#send-members-text-messages-dialog-message').prop('maxLength', maxMessageLength);
3976                $('#send-members-text-messages-dialog-terms-of-service-textarea').text(termsOfUsageText);
3977
3978                $('#send-members-text-messages-dialog-calculate-total-credits').addClass('d-none');
3979                $('#send-members-text-messages-dialog-total-credits').addClass('d-none');
3980                $('#send-members-text-messages-dialog-primary-phone-checkbox').prop('disabled', false);
3981                $('#send-members-text-messages-dialog-secondary-phone-checkbox').prop('disabled', false);
3982                $('#send-members-text-messages-dialog-mobile-phone-checkbox').prop('disabled', false);
3983                $('#send-members-text-messages-dialog-primary-phone-checkbox').prop('checked', false);
3984                $('#send-members-text-messages-dialog-secondary-phone-checkbox').prop('checked', false);
3985                $('#send-members-text-messages-dialog-mobile-phone-checkbox').prop('checked', false);
3986                                    
3987                $('#send-members-text-messages-dialog-error-message').text('');
3988                
3989                updateMessageLengthLabel();
3990                updateMessageSendButton();
3991            }
3992
3993            function updateMessageSendButton() {
3994                var anyPhoneNumbersChecked = $('#send-members-text-messages-dialog-primary-phone-checkbox').prop('checked') || $('#send-members-text-messages-dialog-secondary-phone-checkbox').prop('checked') || $('#send-members-text-messages-dialog-mobile-phone-checkbox').prop('checked');
3995
3996                const disabled = $('#send-members-text-messages-dialog-message').val().trim().length < 1 || $('#send-members-text-messages-dialog-terms-of-service-checkbox').prop('checked') == false || !anyPhoneNumbersChecked || isCalculatingTotalMessageCount || totalMessageCount < 1;
3997
3998                $('#send-members-text-messages-dialog-send-button').prop('disabled', disabled);
3999            }
4000
4001            function updateMessageLengthLabel() {
4002                const message = $('#send-members-text-messages-dialog-message').val().trim();
4003
4004                const messageLength = message.length;
4005                const charactersRemaining = maxMessageLength - messageLength;
4006                const creditsPerMessage = creditSchedule.get(messageLength);
4007
4008                if (message.length < 1) {
4009                    $('#send-members-text-messages-dialog-message-length').text(' ');
4010                } else {
4011                    $('#send-members-text-messages-dialog-message-length').text(`${messageLength} character${messageLength==1 ? '' : 's'}, ${creditsPerMessage} credit${creditsPerMessage==1 ? '' : 's'}. (${charactersRemaining} character${charactersRemaining==1 ? '' : 's'} remaining)`);
4012                }
4013
4014                var anyPhoneNumbersChecked = $('#send-members-text-messages-dialog-primary-phone-checkbox').prop('checked') || $('#send-members-text-messages-dialog-secondary-phone-checkbox').prop('checked') || $('#send-members-text-messages-dialog-mobile-phone-checkbox').prop('checked');
4015
4016                if (($('#send-members-text-messages-dialog-primary-phone-checkbox').prop('checked') || $('#send-members-text-messages-dialog-secondary-phone-checkbox').prop('checked')) && messageLength > 0) {
4017                    $('#send-members-text-messages-dialog-non-mobile-phone-number-warning').removeClass('d-none');
4018                } else {
4019                    $('#send-members-text-messages-dialog-non-mobile-phone-number-warning').addClass('d-none');
4020                }
4021
4022                if (anyPhoneNumbersChecked && messageLength > 0) {
4023                    if (isCalculatingTotalMessageCount) {
4024                        $('#send-members-text-messages-dialog-calculate-total-credits').removeClass('d-none');
4025                        $('#send-members-text-messages-dialog-total-credits').addClass('d-none');
4026                    } else {
4027                        $('#send-members-text-messages-dialog-calculate-total-credits').addClass('d-none');
4028                        
4029                        if (message.length < 1) {
4030                            $('#send-members-text-messages-dialog-total-credits').addClass('d-none');
4031                        } else {
4032                            $('#send-members-text-messages-dialog-total-credits').removeClass('d-none');
4033                        }
4034
4035                        if (totalMessageCount > 0) {
4036                            const totalBatchCredits = creditsPerMessage * totalMessageCount;
4037                            $('#send-members-text-messages-dialog-total-credits').text(`This request requires ${totalBatchCredits} credit${totalBatchCredits==1 ? '' : 's'} and will send ${totalMessageCount} message${totalMessageCount==1 ? '' : 's'}.`);
4038                        } else {
4039                            $('#send-members-text-messages-dialog-total-credits').text('There are no eligible phone numbers for the phone field(s) you selected.');
4040                        }
4041                    }
4042                }
4043                else {
4044                    $('#send-members-text-messages-dialog-calculate-total-credits').addClass('d-none');
4045                    $('#send-members-text-messages-dialog-total-credits').addClass('d-none');
4046                }
4047            }
4048
4049            function showError(message) {
4050                $('#send-members-text-messages-dialog-close-window-button').removeClass('d-none');
4051                $('#send-members-text-messages-dialog-cancel-button').prop('disabled', false);
4052                $('#send-members-text-messages-dialog-message').prop('disabled', false);
4053                $('#send-members-text-messages-dialog-terms-of-service-checkbox').prop('disabled', false);
4054                $('#send-members-text-messages-dialog-primary-phone-checkbox').prop('disabled', false);
4055                $('#send-members-text-messages-dialog-secondary-phone-checkbox').prop('disabled', false);
4056                $('#send-members-text-messages-dialog-mobile-phone-checkbox').prop('disabled', false);
4057                $('#send-members-text-messages-dialog-send-button').text('Send');
4058                $('#send-members-text-messages-dialog-error-message').text(message);
4059
4060                updateMessageSendButton();
4061            }
4062            
4063            $('#send-members-text-messages-dialog-send-button').on('click', function (event) {
4064                event.preventDefault();
4065                                
4066                $('#send-members-text-messages-dialog-send-button').prop('disabled', true);
4067                $('#send-members-text-messages-dialog-send-button').text('Sending...');
4068                $('#send-members-text-messages-dialog-cancel-button').prop('disabled', true);
4069                $('#send-members-text-messages-dialog-message').prop('disabled', true);
4070                $('#send-members-text-messages-dialog-terms-of-service-checkbox').prop('disabled', true);
4071                $('#send-members-text-messages-dialog-primary-phone-checkbox').prop('disabled', true);
4072                $('#send-members-text-messages-dialog-secondary-phone-checkbox').prop('disabled', true);
4073                $('#send-members-text-messages-dialog-mobile-phone-checkbox').prop('disabled', true);
4074                
4075                $('#send-members-text-messages-dialog-close-window-button').addClass('d-none');
4076
4077                const message = $('#send-members-text-messages-dialog-message').val().trim();
4078
4079                const startDateTimeOffset = $('#send-members-text-messages-dialog-message-scheduled-date-time').datetimepicker('viewDate').format();
4080
4081                $.ajax({
4082                    type: "POST",
4083                    url: sendMessageUrl,
4084                    data: 
4085                    { 
4086                        message,
4087                        sendToPrimaryPhone: $('#send-members-text-messages-dialog-primary-phone-checkbox').prop('checked'),
4088                        sendToSecondaryPhone: $('#send-members-text-messages-dialog-secondary-phone-checkbox').prop('checked'),
4089                        sendToMobilePhone: $('#send-members-text-messages-dialog-mobile-phone-checkbox').prop('checked'),
4090                        startDateTimeOffset
4091                    }
4092                })
4093                .done(function (sendResult) {
4094                    if (sendResult.IsSuccessful) {
4095                        wasSendSuccessful = true;
4096                        $('#send-members-text-messages-dialog').modal('hide');
4097                    }
4098                    else {
4099                        showError('Your message was not sent. ' + sendResult.ErrorMessage);
4100                    }
4101                })                
4102                .fail(function (_jqXHR, textStatus, errorThrown) {
4103                    showError('An unexpected error occurred.  Please try');
4104                    console.error(textStatus);
4105                    if (errorThrown) {
4106                        console.error(errorThrown);
4107                    }
4108                });
4109            });
4110
4111            function showErrorDialog(message) {
4112                $('#send-members-text-messages-error-dialog .modal-body').text(message);
4113                $('#send-members-text-messages-error-dialog').modal('show');
4114            }
4115
4116            $('#send-members-text-messages-error-dialog').on('hidden.bs.modal', function() {
4117                $('#send-members-text-messages-wait-container').addClass('d-none');
4118            });
4119            
4120            $('#send-members-text-messages-success-dialog').on('hidden.bs.modal', function() {
4121                $('#send-members-text-messages-wait-container').addClass('d-none');
4122            });
4123        }
4124
4125        $('#warn-user-before-unloading-page').each(function () {
4126            let isSubmittingForm = false;
4127            
4128            $('form').on('submit', function() {
4129                isSubmittingForm = true;
4130                return true;
4131            });
4132
4133            $.validator.unobtrusive.options = {
4134                invalidHandler: function() {
4135                    isSubmittingForm = false;
4136                }
4137            };
4138            
4139            window.addEventListener("beforeunload", function (e) {
4140                if (isSubmittingForm) {
4141
4142                    isSubmittingForm = false;
4143
4144                    if ($('.input-validation-error').toArray().length == 0 && $('[data-valmsg-summary] ul > li').toArray().length) {
4145                        return null;
4146                    }
4147                };
4148
4149                var confirmationMessage = "HEY!  You have unsaved changes that will be lost if you leave the page";
4150                e.returnValue = confirmationMessage;     // Gecko, Trident, Chrome 34+
4151                return confirmationMessage;              // Gecko, WebKit, Chrome <34
4152            });
4153        });
4154
4155        $('.auto-redirect-timer').each(function () {
4156            let element = $(this);
4157            let seconds = $(this).data("seconds");
4158            let url = $(this).data("url");
4159
4160            var secondsRemaining = parseInt(seconds);
4161
4162            var interval = setInterval(countDownToRedirect, 1000);
4163
4164            function countDownToRedirect() {
4165                --secondsRemaining;
4166
4167                if (secondsRemaining <= 0) {
4168                    $(element).text("0");
4169                    clearInterval(interval);
4170                    window.location.href = url;
4171                    return;
4172                    }
4173
4174                $(element).text(secondsRemaining);
4175            };
4176        });
4177
4178        $('.mtp-development-mode-tag').click(function () {
4179            $('.mtp-development-mode-tag').each(function () {
4180                $(this).addClass('d-none');
4181            });
4182        });
4183
4184        $('#member-email-travelers-profile-form').on('submit', function() {
4185            const form = $(this);
4186
4187            if (!form.valid())
4188                return false;
4189            
4190            $('.mtp-full-page-wait-overlay-container').removeClass("d-none");
4191        });
4192
4193        $('.mtp-insert-apprenticeship-application-check-in-history-form .mtp-yes-dialog-button').on('click', function() {
4194            const form = $(this).closest('form');
4195
4196            $("input[name='IsWithdrawal']", form).val("false");
4197        });
4198
4199        $('.mtp-insert-apprenticeship-application-check-in-history-form .mtp-no-dialog-button').on('click', function() {
4200            const form = $(this).closest('form');
4201
4202            $("input[name='IsWithdrawal']", form).val("true");
4203        });
4204    });
4205
4206function updateFixedScrollableDataGridHeaders() {
4207   
4208    $('.mtp-data-grid-header-fixed-scrollable').each(function() {
4209        var fixedHeader = $(this);
4210        var header = $(this).prev('tr');
4211
4212        if ($(window).width() <= 767.98)
4213            return;
4214
4215        fixedHeader.removeClass('d-none');
4216        var fixedHeaderHeight = $(fixedHeader).outerHeight();
4217        
4218        var scrollTop = $(window).scrollTop();
4219        fixedHeader.css('width', header.outerWidth() + 1);
4220        fixedHeader.css('position', 'fixed');
4221        fixedHeader.css('top', '0');
4222
4223       
4224        $("th", header).each(function(index, el) {
4225            $($("th", fixedHeader)[index]).css('width', $(el).outerWidth());
4226        });
4227
4228        var table = $(header).parents("table").first();
4229      
4230        var fixedPageHeaderOffset = 0;
4231        if ($(window).width() <= 991.98)
4232            fixedPageHeaderOffset += $("#mtp-site-header").outerHeight();
4233
4234        if (scrollTop > header.offset().top + header.outerHeight() - fixedHeaderHeight - fixedPageHeaderOffset && scrollTop < table.offset().top + table.outerHeight() -  $(fixedHeader).innerHeight() - fixedPageHeaderOffset) {
4235            fixedHeader.removeClass('d-none');
4236        } else {
4237            fixedHeader.addClass('d-none');
4238        }
4239    });
4240}
4241
4242function resizeElements() {
4243    $('.mtp-full-page-wait-overlay-content').each(function() {
4244        $(this).width($('#mtp-site-header').width()-40);
4245    });
4246}
4247
4248function tick() {
4249    elapsedSecondsForAutoLogout++;
4250
4251    if (autoLogoutTimeInSeconds > 0 && elapsedSecondsForAutoLogout >= autoLogoutTimeInSeconds) {
4252        var url = $("#logoff-link").attr("href");
4253        if (url !== undefined) {
4254            window.location = url;
4255        }
4256    }
4257
4258    elapsedSecondsForClearingLoginForm++;
4259
4260    if (maximumTimeInSecondsBeforeClearingLoginForm > 0 &&
4261        elapsedSecondsForClearingLoginForm >= maximumTimeInSecondsBeforeClearingLoginForm) {
4262        $("#login-username-field").val("");
4263        $("#login-password-field").val("");
4264
4265        resetClearingLoginFormCounter();
4266    }
4267
4268    setTimeout(function () { tick(); }, 1000);
4269}
4270
4271function resetClearingLoginFormCounter() {
4272    elapsedSecondsForClearingLoginForm = 0;
4273}
4274
4275function loginUsernameAddDigit(digit) {
4276    document.getElementById("login-username-field").value += digit;
4277    resetClearingLoginFormCounter();
4278}
4279
4280function loginUsernameBack() {
4281    var field = document.getElementById("login-username-field");
4282    if (field.value.length > 0) {
4283        field.value = field.value.substr(0, field.value.length - 1);
4284        resetClearingLoginFormCounter();
4285    }
4286}
4287
4288$("#submit-payment-form")
4289    .submit(function() {
4290        if ($(this).valid()) {
4291            $("#submit-button").attr("disabled", true).val("Submitting payment.  Please wait...");
4292        }
4293    });
4294
4295var filterFloat = function(value) {
4296    if (/^(\-|\+)?([0-9]+(\.[0-9]+)?|Infinity)$/
4297        .test(value))
4298        return Number(value);
4299    return NaN;
4300};
4301$(function() {
4302    if ($.isFunction($.fn.dialog)) {
4303        $("#dialog-message")
4304            .dialog({
4305                modal: true,
4306                draggable: false,
4307                resizable: false,
4308                minWidth: 900,
4309                minHeight: 300,
4310                dialogClass: "dialogClass",
4311                buttons: {
4312                    Ok: function() {
4313                        $(this).dialog("close");
4314                    }
4315                }
4316            });
4317    }
4318});
4319
4320$(function () {
4321    if ($.isFunction($.fn.dialog)) {
4322        $("#dialog-error")
4323            .dialog({
4324                modal: true,
4325                draggable: false,
4326                resizable: false,
4327                minWidth: 600,
4328                dialogClass: "dialogClass",
4329                buttons: {
4330                    Ok: function () {
4331                        $(this).dialog("close");
4332                    }
4333                }
4334            });
4335    }
4336});
4337
4338$("#class-registration-fieldset #CourseID").change(function () {
4339    var text = $('#course-description-' + $(this).find('option:selected').val()).data("description");
4340
4341    if (text === undefined)
4342        text = '';
4343
4344    $("#class-registration-fieldset #selected-class-description").text(text);
4345
4346}).change();
4347
4348function autocomplete(inp, beforeLookupFunc, lookupFunc, selectedFunc) {
4349  var currentFocusItemIndex;
4350  inp.addEventListener("input", function() {
4351      var searchValue = this.value;
4352      closeAllLists();
4353      beforeLookupFunc(this);
4354      if (!searchValue) { return false;}
4355      const container = this;
4356      lookupFunc(searchValue,
4357          function(getItemsFunc, getDescFunc) {
4358              const items = getItemsFunc();
4359              currentFocusItemIndex = -1;
4360              const listContainer = document.createElement("DIV");
4361              listContainer.setAttribute("id", container.id + "mtp-autocomplete-list");
4362              listContainer.setAttribute("class", "mtp-autocomplete-items list-group shadow");
4363              container.parentNode.appendChild(listContainer);
4364              for (let i = 0; i < items.length; i++) {
4365                  const desc = getDescFunc(items[i]);
4366                  const listItem = document.createElement("div");
4367                  listItem.setAttribute("class", "list-group-item list-group-item-action p-2");
4368
4369                  const startPos = desc.toLowerCase().indexOf(searchValue.toLowerCase());
4370
4371                  if (startPos >= 0) {
4372                      listItem.innerHTML =  $('<div/>').text(desc.substr(0, startPos)).html();
4373                      listItem.innerHTML += "<strong>" + $('<div/>').text(desc.substr(startPos, searchValue.length)).html() + "</strong>";
4374                      listItem.innerHTML += $('<div/>').text(desc.substr(searchValue.length + startPos)).html();
4375                  } else {
4376                      $(listItem).text(desc);
4377                  }
4378                  const item = items[i];
4379                  listItem.addEventListener("click",
4380                      function(e) {
4381                          e.preventDefault();
4382                          inp.value = getDescFunc(item);
4383                          selectedFunc(item);
4384                          closeAllLists();
4385                      });
4386                  listContainer.appendChild(listItem);
4387              }
4388          });
4389    
4390      return true;
4391  });
4392  
4393  inp.addEventListener("keydown", function(e) {
4394      var x = document.getElementById(this.id + "mtp-autocomplete-list");
4395      if (x) x = x.getElementsByTagName("div");
4396      if (e.keyCode === 9 /* Tab */) {
4397          if (currentFocusItemIndex > -1) {
4398              if (x) x[currentFocusItemIndex].click();
4399          } else {
4400              closeAllLists();
4401          }
4402          return;
4403      }
4404      if (e.keyCode === 40 /* Down */) {
4405        currentFocusItemIndex++;
4406        addActive(x);
4407      } else if (e.keyCode === 38 /* Up */) {
4408        currentFocusItemIndex--;
4409        addActive(x);
4410      } else if (e.keyCode === 13 /* Enter */) {
4411        e.preventDefault();
4412        if (currentFocusItemIndex > -1) {
4413          if (x) x[currentFocusItemIndex].click();
4414        }
4415      }
4416  });
4417
4418  function addActive(x) {
4419    if (!x) return false;
4420    removeActive(x);
4421    if (currentFocusItemIndex >= x.length) currentFocusItemIndex = 0;
4422    if (currentFocusItemIndex < 0) currentFocusItemIndex = (x.length - 1);
4423    //x[currentFocusItemIndex].classList.add("mtp-autocomplete-active");
4424    $(x[currentFocusItemIndex]).addClass("mtp-autocomplete-active active");
4425    return true;
4426  }
4427
4428  function removeActive(x) {
4429    for (let i = 0; i < x.length; i++) {
4430        $(x[i]).removeClass("mtp-autocomplete-active active");
4431        //x[i].classList.remove("mtp-autocomplete-active");
4432    }
4433  }
4434  function closeAllLists(except) {
4435    const x = document.getElementsByClassName("mtp-autocomplete-items");
4436    for (let i = 0; i < x.length; i++) {
4437      if (except !== x[i] && except !== inp) {
4438        x[i].parentNode.removeChild(x[i]);
4439      }
4440    }
4441  }
4442  
4443  document.addEventListener("click", function (e) {
4444      closeAllLists(e.target);
4445  });
4446}
4447
4448var addEditContractorWorkerRequestFormProjectNameChanged = false;
4449
4450$("#add-edit-contractor-worker-request-form #ProjectName").change(function() {
4451    addEditContractorWorkerRequestFormProjectNameChanged = true;
4452});
4453
4454const updateProjectNameNotFoundWarningFunc = function() {
4455    const jobId = parseInt($('#JobID').val());
4456
4457    if(!isNaN(jobId) || $("#ProjectName").val().trim().length < 1)
4458        $('#project-not-found-warning').addClass('d-none');
4459    else 
4460        $('#project-not-found-warning').removeClass('d-none');
4461}
4462
4463
4464$("#add-edit-contractor-worker-request-form #project-name-autocomplete-container").focusout(function() {
4465    if (!addEditContractorWorkerRequestFormProjectNameChanged)
4466        return;
4467
4468    updateProjectNameNotFoundWarningFunc();
4469
4470    addEditContractorWorkerRequestFormProjectNameChanged = false;
4471});
4472
4473$("#add-edit-contractor-worker-request-form #ProjectName").each(function() {
4474    var url = $(this).data("find-jobs-url");
4475
4476    const lookupFunc = function(text, callback) {
4477        const lookupRequest = $.ajax({
4478            type: "GET",
4479            url: url,
4480            data: {
4481                jobName: text
4482            },
4483            contentType: "application/json; charset=utf-8"
4484        });
4485
4486        lookupRequest.done(function(lookupData) {
4487            callback(function() {
4488                    return lookupData.results;
4489                },
4490                item => item.JobName);
4491        });
4492    };
4493
4494    const beforeLookupFunc = function() {
4495        $('#JobID').val('');
4496    }
4497
4498    const selectedFunc = function(selection) {
4499        $('#JobID').val(selection.JobID);
4500        updateProjectNameNotFoundWarningFunc();
4501    };
4502
4503    autocomplete(document.getElementById("ProjectName"), beforeLookupFunc, lookupFunc, selectedFunc);
4504});
4505
4506$("#add-edit-contractor-worker-request-worker-type-form #ContractorWorkerRequestWorkerTypeTypeId").change(function() {
4507    if ($(this).find('option:selected').text() === 'APPRENTICE')
4508        $('#apprentice-specific').removeClass("d-none");
4509    else
4510        $('#apprentice-specific').addClass("d-none");
4511}).change();
4512
4513$("#add-edit-contractor-worker-request-worker-type-form #ContractorAgreementTypeId").change(function() {
4514    const contractorAgreementTypeId = parseInt($(this).find('option:selected').val());
4515
4516    if (!isNaN(contractorAgreementTypeId)) {
4517        $("#skill-container").each(function() {
4518            const skillContainer = $(this);
4519
4520            const lookupRequest = $.ajax({
4521                type: "GET",
4522                url: $(skillContainer).data("skill-lookup-url"),
4523                data: {
4524                    contractorAgreementTypeId: contractorAgreementTypeId
4525                },
4526                contentType: "application/json; charset=utf-8"
4527            });
4528
4529            lookupRequest.done(function(lookupData) {
4530                $(skillContainer).removeClass("d-none");
4531                
4532                $("#SelectedSkillIds").empty();
4533
4534                for (let i = 0; i < lookupData.results.length; i++) {
4535                    const option = $("<option></option>").text(lookupData.results[i].Name)
4536                        .attr("value", lookupData.results[i].SkillID);
4537
4538                    $("#SelectedSkillIds").append(option);
4539                }
4540
4541            });
4542        });
4543    }
4544});
4545
4546$("#form").submit(function () {
4547    $('.mtp-full-page-wait-overlay-container').removeClass("d-none");
4548
4549    return true;
4550});
4551
4552$("#button-use-card-on-file-true").click(function() {
4553    $('.validation-summary-errors').hide();
4554    $('.mtp-full-page-wait-overlay-container').removeClass("d-none");
4555});
4556
4557var showCardFailureMessage = function() {
4558    $('.validation-summary-errors').hide();
4559    $('.mtp-full-page-wait-overlay-container').addClass("d-none");
4560    $(window).scrollTop(0);
4561    $("#card-not-accepted-failure-dialog").modal('show');
4562}
4563
4564$("#apprenticeship-application-coordinator-approval-dialog").each(function() {
4565    const updateContractorNotFoundWarningFunc = function() {
4566        const contractorId = parseInt($('#DialogCoordinatorSelectedContractorID').val());
4567
4568        if (!isNaN(contractorId) || $("#DialogCoordinatorSelectedContractor").val().trim().length < 1)
4569            $('#contractor-not-found-warning').addClass('d-none');
4570        else
4571            $('#contractor-not-found-warning').removeClass('d-none');
4572    }
4573
4574    let lastContractorLookupResults = null;
4575
4576    var findContractorNameChanged = false;
4577
4578    $("#DialogCoordinatorSelectedContractor").change(
4579        function() {
4580            findContractorNameChanged = true;
4581        });
4582
4583    $("#contractor-autocomplete-container").focusout(
4584        function() {
4585            if (!findContractorNameChanged)
4586                return;
4587
4588            updateContractorNotFoundWarningFunc();
4589
4590            findContractorNameChanged = false;
4591
4592            if (!lastContractorLookupResults)
4593                return;
4594
4595            if (lastContractorLookupResults.length !== 1)
4596                return;
4597
4598            $("#DialogCoordinatorSelectedContractor").val(lastContractorLookupResults[0].ContractorName);
4599            $("#DialogCoordinatorSelectedContractorID").val(lastContractorLookupResults[0].ContractorID);
4600
4601            updateContractorNotFoundWarningFunc();
4602        });
4603
4604    $("#DialogCoordinatorSelectedContractor").each(function() {
4605        var url = $(this).data("find-contractors-url");
4606
4607        const lookupFunc = function(text, callback) {
4608            const lookupRequest = $.ajax({
4609                type: "GET",
4610                url: url,
4611                data: {
4612                    searchString: text
4613                },
4614                contentType: "application/json; charset=utf-8"
4615            });
4616
4617            lookupRequest.done(function(lookupData) {
4618                callback(function() {
4619                        return lastContractorLookupResults = lookupData.results;
4620                    },
4621                    item => item.ContractorName + " [" + item.ContractorNumber + "]");
4622            });
4623        };
4624
4625        const beforeLookupFunc = function() {
4626            $('#DialogCoordinatorSelectedContractorID').val('');
4627        }
4628
4629        const selectedFunc = function(selection) {
4630            $('#DialogCoordinatorSelectedContractorID').val(selection.ContractorID);
4631
4632            updateContractorNotFoundWarningFunc();
4633        };
4634
4635        autocomplete(document.getElementById("DialogCoordinatorSelectedContractor"),
4636            beforeLookupFunc,
4637            lookupFunc,
4638            selectedFunc);
4639    });
4640});
4641
4642
4643
4644function closePrint() {
4645    document.body.removeChild(this.__container__);
4646}
4647
4648function setPrint() {
4649    this.contentWindow.__container__ = this;
4650    this.contentWindow.onbeforeunload = closePrint;
4651    this.contentWindow.onafterprint = closePrint;
4652    this.contentWindow.focus(); // Required for IE
4653    this.contentWindow.print();
4654}
4655
4656function printPage(url) {
4657    var oHiddFrame = document.createElement("iframe");
4658    oHiddFrame.onload = setPrint;
4659    oHiddFrame.style.visibility = "hidden";
4660    oHiddFrame.style.position = "fixed";
4661    oHiddFrame.style.width = "1024px";
4662    oHiddFrame.src = url;
4663    document.body.appendChild(oHiddFrame);
4664}
4665
4666function setSignatureImage(image) {
4667    $('#signature-tap-to-sign-container').addClass("d-none");
4668    $('#signature').attr('src', image);
4669    $('#signature-container').removeClass("d-none");
4670    $('#SignatureImageData').val(image);
4671    $('#SignatureImageData').valid();
4672    $('#SignatureImageData').parent().removeClass('input-validation-error');
4673};
4674
4675SignaturePad.prototype.getCroppedImage = function () {
4676    var imgWidth = this._ctx.canvas.width;
4677    var imgHeight = this._ctx.canvas.height;
4678    var imageData = this._ctx.getImageData(0, 0, imgWidth, imgHeight),
4679        data = imageData.data,
4680        getAlpha = function(x, y) {
4681            return data[(imgWidth * y + x) * 4 + 3];
4682        },
4683        scanY = function (fromTop) {
4684            var offset = fromTop ? 1 : -1;
4685
4686            // loop through each row
4687            for(var y = fromTop ? 0 : imgHeight - 1; fromTop ? (y < imgHeight) : (y > -1); y += offset) {
4688
4689                // loop through each column
4690                for(var x = 0; x < imgWidth; x++) {
4691                    if (getAlpha(x, y)) {
4692                        return y;                        
4693                    }      
4694                }
4695            }
4696            return null; // all image is white
4697        },
4698        scanX = function (fromLeft) {
4699            var offset = fromLeft? 1 : -1;
4700
4701            // loop through each column
4702            for(var x = fromLeft ? 0 : imgWidth - 1; fromLeft ? (x < imgWidth) : (x > -1); x += offset) {
4703
4704                // loop through each row
4705                for(var y = 0; y < imgHeight; y++) {
4706                    if (getAlpha(x, y)) {
4707                        return x;                        
4708                    }      
4709                }
4710            }
4711            return null; // all image is white
4712        };
4713
4714    var cropTop = scanY(true),
4715        cropBottom = scanY(false),
4716        cropLeft = scanX(true),
4717        cropRight = scanX(false);
4718
4719    imageData = this._ctx.getImageData(cropLeft, cropTop, cropRight-cropLeft, cropBottom-cropTop);
4720
4721    var croppedCanvas = document.createElement('canvas'),
4722        croppedCtx    = croppedCanvas.getContext('2d');
4723    
4724    croppedCanvas.width= cropRight-cropLeft;
4725    croppedCanvas.height = cropBottom-cropTop;
4726    croppedCtx.putImageData(imageData, 0, 0);
4727
4728    return croppedCanvas;
4729};
4730
4731/**********************************************************************
4732 Out Of Work List Functions
4733 ***********************************************************************/
4734    
4735function outOfWorkListCreateCarouselItemContainer(list) {
4736    const container = $("#container-template").first().clone().removeAttr("id").removeClass("d-none")
4737        .addClass("carousel-item active mtp-measure-mode");
4738    container.find("#item-container-template").empty();
4739    container.find(".referral-list-name-value").text(list.listName);
4740    container.appendTo("#out-of-work-list-carousel-inner");
4741
4742    return container;
4743}
4744
4745function outOfWorkListGetItemParent(container) {
4746    return container.find("#item-container-template").first();
4747}
4748
4749var outOfWorkListMaxHeight = 0;
4750var outOfWorkListCurrentCarouselData = null;
4751
4752function outOfWorkListConstructCarouselItems(data) {
4753    for (let i in data) {
4754        if (data.hasOwnProperty(i)) {
4755            const list = data[i];
4756
4757            let item = $("#container-template").find("#item-template").first().clone().removeAttr("id");
4758
4759            let container = outOfWorkListCreateCarouselItemContainer(list);
4760            let itemParent = outOfWorkListGetItemParent(container);
4761
4762            for (let j in list.entries) {
4763                if (list.entries.hasOwnProperty(j)) {
4764                    const entry = list.entries[j];
4765
4766                    item = item.clone();
4767                    item.find(".position-value").text(entry.position);
4768                    item.find(".name-value").text(entry.name);
4769                    item.find(".date-time-inserted-value").text(entry.dateTimeInserted);
4770                    item.find(".status-value").text(entry.status);
4771
4772                    item.appendTo(itemParent);
4773
4774                    if (container.position().top + container.height() > $(window).height()) {
4775                        item.remove();
4776
4777                        if (outOfWorkListMaxHeight < container.height()) {
4778                            outOfWorkListMaxHeight = container.height();
4779                        }
4780
4781                        container.removeClass("active mtp-measure-mode");
4782
4783                        container = outOfWorkListCreateCarouselItemContainer(list);
4784                        itemParent = outOfWorkListGetItemParent(container);
4785
4786                        item.appendTo(itemParent);
4787                    }
4788                }
4789            }
4790
4791            if (outOfWorkListMaxHeight < container.height()) {
4792                outOfWorkListMaxHeight = container.height();
4793            }
4794        }
4795    }
4796
4797    $(".carousel-item").removeClass("active mtp-measure-mode").height(outOfWorkListMaxHeight);
4798}
4799
4800function outOfWorkListReconstructCarousel() {
4801    outOfWorkListMaxHeight = 0;
4802    $("#out-of-work-list-carousel-inner").empty();
4803
4804    if (outOfWorkListCurrentCarouselData !== null)
4805        outOfWorkListSetCarouselData(outOfWorkListCurrentCarouselData);
4806    else
4807        outOfWorkListReloadCarousel();
4808}
4809
4810function outOfWorkListReloadCarousel() {
4811    const url = $("#out-of-work-list-carousel").data("url");
4812    
4813    if (url.length > 0) {
4814        $.ajax({
4815            method: "GET",
4816            url: url
4817        })
4818            .done(function (data) {
4819                outOfWorkListSetCarouselData(data);
4820            });
4821    }
4822}
4823
4824function outOfWorkListSetCarouselData(data) {
4825    $('.carousel').carousel('pause');
4826    $("#out-of-work-list-carousel-inner > .carousel-item:not(:last)").remove();
4827
4828    outOfWorkListConstructCarouselItems(data);
4829
4830    $(".carousel-item").first().addClass("active");
4831
4832    if ($(".carousel-item").length <= 1) {
4833        setTimeout(outOfWorkListReloadCarousel, $("#out-of-work-list-carousel").first().data("interval"));
4834    } else {
4835        $('#out-of-work-list-carousel').carousel('cycle');
4836    }
4837};
4838
4839$('#out-of-work-list-carousel').on('slid.bs.carousel', function (e) {
4840    if (e.to === $("#out-of-work-list-carousel-inner > .carousel-item").length - 1) {
4841        outOfWorkListReloadCarousel();
4842    }
4843});
4844
4845$(document).ready(function () {
4846    $("#out-of-work-list-page-container").each(function () {
4847        outOfWorkListCurrentCarouselData = $("#out-of-work-list-carousel").data("initial-data");
4848
4849        outOfWorkListReconstructCarousel();
4850    });
4851
4852});
4853
4854var outOfWorkListResizeCarouselFunc;
4855$(window).resize(function () {
4856    $("#out-of-work-list-page-container").each(function () {
4857        $('.carousel').carousel('pause');
4858
4859        clearTimeout(outOfWorkListResizeCarouselFunc);
4860        outOfWorkListResizeCarouselFunc = setTimeout(outOfWorkListReconstructCarousel, 500);
4861    });
4862});
4863
4864/**********************************************************************
4865 End of Out Of Work List Functions
4866 ***********************************************************************/
4867
4868
4869/**********************************************************************
4870 Online Classes Functions
4871 ***********************************************************************/
4872$(document).ready(function () {
4873    $("#main-online-classes").hide(); // ide the grid div to reduce flicker
4874
4875    var size = $("#main-online-classes #grid-classes > thead > tr >th").length; // get total column
4876    $("#main-online-classes #grid-classes > thead > tr >th").last().remove(); // remove last column
4877    $("#main-online-classes #grid-classes > thead > tr").prepend("<th></th>"); // add one column at first for collapsible column
4878    $("#main-online-classes #grid-classes > tbody > tr").each(function (i, el) {
4879        var activitycount = $("#grid-sub-activities tr", this).length;  // number of rows in activity grid
4880        if (activitycount > 1) { // if more then one row than activities exist so show toggle button
4881            $(this).prepend(
4882                $("<td><button></button></td>")
4883                    .addClass("gridExpand")
4884                    .addClass("hoverEff")
4885                    .attr('title', "click to show/hide activities")
4886            );
4887        } else {
4888            $(this).prepend(
4889                $("<td></td>") // otherwise add placeholder
4890            );
4891        }
4892
4893        //Now get sub activities table from last column and add this to the next new added row
4894        var table = $("table", this).parent().html();
4895
4896        //add new row to this sub table
4897        if (activitycount > 1) {
4898            $(this).after("<tr><td></td><td colspan='" + (size - 1) + "'>" + table + "</td></tr>");
4899        }
4900
4901        $("table", this).parent().remove();  // remove the grid cell that contained the activities grid
4902
4903        //make subtable collapsable
4904        $(".hoverEff", this).on("click", function () {
4905            $(this).parent().closest("tr").next().slideToggle(100);
4906        });
4907        $("td", this).last().remove()
4908
4909    });
4910
4911    //by default collapse all activity sub grids
4912    $("#main-online-classes #grid-classes > tbody > tr td.gridExpand").each(function (i, el) {
4913        $(this).parent().closest("tr").next().slideToggle(100);
4914    });
4915
4916    $("#main-online-classes").show(); //show the table div
4917});
4918
4919/**********************************************************************
4920 End of Online Classes Functions
4921 ***********************************************************************/
4922
4923$(document).ready(function () {
4924    $('.mtp-button-post').on('click', function () {
4925        var url = $(this).data('url');
4926
4927        $.post(url, '', function (response) {
4928            console.log('Server response:', response);
4929            window.location.href = window.location.href;
4930        }).fail(function () {
4931            console.error('Error sending data.');
4932            window.location.href = window.location.href;
4933        });
4934    });
4935});

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.