PageSourceSearch

https://cdn.ca.yapla.com/js/hpjorg/utils.js?v=v6.285.0&v=v6.285.0&…=bb655a442a6d4ce51f271bae2b14fc4455e1bd8d

js yapla.com collected 2026-09-24 08:53:29 UTC 47,045 bytes, 1,382 lines download raw bytes

1var HPJUtils = {
2    /**
3     * Display a loading box
4     * @param [inside] if set will render the loading into it
5     * @param [mode]
6     */
7    displayLoadingBox: function (inside, mode) {
8        // In case old loader.js
9        var load = $("#loadingBox");
10
11        if (!load.length) {
12            load = $("<div id='loadingBox'></div>");
13        }
14
15        if (typeof inside !== "undefined") {
16            if (typeof inside === "string") {
17                inside = $(inside);
18            }
19
20            mode = mode ? mode : "prepend";
21
22            if (mode === "prepend") {
23                inside.prepend(load);
24            } else if (mode === "html") {
25                inside.html(load);
26            }
27
28            load.css({
29                position: "static",
30                visibility: "visible",
31            }).show();
32        } else {
33            var loadWrapper = $("#backgroundBox");
34
35            if (!loadWrapper.length) {
36                loadWrapper = $("<div id='backgroundBox'></div>");
37                $(document.body).prepend(loadWrapper);
38            }
39
40            loadWrapper.html(load);
41
42            var windowSize = getWindowSize(),
43                coordinates = getCenteredCoordinates(windowSize, "loadingBox");
44
45            load.css({
46                visibility: "visible",
47                top: coordinates.top + "px",
48                left: coordinates.left + "px",
49            }).show();
50
51            loadWrapper
52                .css({
53                    visibility: "visible",
54                    width: windowSize.width + "px",
55                    height: windowSize.height + "px",
56                })
57                .show();
58        }
59    },
60    showSpinner: function (text) {
61        // In case old loader.js
62        $("#backgroundBox").remove();
63        $(document.body).prepend($("<div id='backgroundBox'><div id='loadingBox'></div></div>"));
64
65        $("#loadingBox")
66            .css({
67                display: "inline-block",
68                position: "unset",
69                visibility: "visible",
70            })
71            .show();
72
73        $("#backgroundBox")
74            .css({
75                alignItems: "center",
76                background: "rgba(255, 255, 255, 0.8)",
77                display: "flex",
78                height: "100%",
79                justifyContent: "center",
80                textAlign: "center",
81                visibility: "visible",
82                width: "100%",
83            })
84            .show();
85
86        if (text) {
87            $("#loadingBox")
88                .html('<span style="top: 40px;position: relative;font-size: 1.8rem; font-weight: bold;">
88' + text + "</span>")
89                .css({ width: "80%" });
90        }
91    },
92    hideLoadingBox: function () {
93        var loadWrapper = $("#backgroundBox");
94        if (loadWrapper.length) {
95            loadWrapper.hide();
96        }
97        $("#loadingBox").hide();
98    },
99    /**
100     * Ajax call class
101     */
102    call: function (c) {
103        this.c = ".main-page";
104        this.modeC = "";
105
106        if (typeof c !== "undefined" && c !== "") {
107            this.c = c;
108        }
109
110        this.mode = function (mode) {
111            this.modeC = mode;
112            return this;
113        };
114
115        this.action = function (url, confirm) {
116            var res = true,
117                self = this;
118
119            if (typeof this.c !== "object") {
120                this.c = $(this.c);
121            }
122
123            if (typeof confirm !== "undefined" && confirm !== "") {
124                res = confirm(confirm);
125            }
126
127            if (res) {
128                $.ajax({
129                    url: url,
130                    success: function (d) {
131                        if (d.mesg) {
132                            $("#message_box").html(d.mesg);
133                        }
134
135                        if (d.html) {
136                            if (self.modeC === "replaceWith") {
137                                self.c.replaceWith(d.html);
138                            } else {
139                                self.c.html(d.html);
140                            }
141                        }
142
143                        if (d.js) {
144                            eval(d.js);
145                        }
146                    },
147                    complete: HPJUtils.hideLoadingBox,
148                    error: function (jqXHR) {},
149                });
150            }
151        };
152    },
153    /**
154     * Bind function to an array (click_to_edit, ...)
155     *
156     * @param {string} table [optional] - selector of the table
157     */
158    tableNavig: function (table) {
159        this.table = typeof table !== "undefined" ? table : "table";
160        var t = this;
161
162        this.classToIgnore;
163        this.useInspector = false;
164        this.inspectorContextList = [];
165
166        /**
167         * If set <td> with those CSS class will not have the 'click_to_edit' function
168         * @param {string} classToIgnore
169         */
170        this.setClassToIgnore = function (classToIgnore) {
171            this.classToIgnore = classToIgnore;
172            return this;
173        };
174
175        /**
176         * Enable inspector panel mode - clicks will open the inspector panel
177         * instead of navigating to the detail page
178         * The first context describes the entities in the current table.
179         * @param {Array} contextList - Inspector contexts, with the current context first
180         */
181        this.enableInspector = function (contextList) {
182            this.inspectorContextList = Array.isArray(contextList) ? contextList : [];
183            this.useInspector = this.inspectorContextList.length > 0;
184            return this;
185        };
186
187        this.init = function () {
188            if (!table.length) {
189                return false;
190            }
191            this.initClickToAction();
192        };
193
194        /**
195         * Init redirection on table line click
196         *
197         * @param clickToUrl ; If known base Url for the action, otherwise use data
198         * @param params : @deprecated used to indicate which params is what, use data now
199         */
200        this.initClickToAction = function (clickToUrl, params, method) {
201            // Remove the cursor-click-css if no need
202            var tr = $("tbody tr", this.table).first();
203
204            if (typeof tr.attr("id") === "undefined" && typeof tr.attr("data") === "undefined" && typeof tr.data("click") === "undefined") {
205                $(this.table).removeClass("table-hover");
206            }
207
208            $("body").on(
209                "click",
210                this.table + " .click_to_edit td:not(._actionTd" + (t.classToIgnore ? "," + t.classToIgnore : "") + ")",
211                function (event) {
212                    if ($(event.target).closest(".disable-default-click").length) {
213                        return;
214                    }
215
216                    event.preventDefault();
217                    event.stopPropagation();
218
219                    var id = $(this).closest("tr").attr("id"),
220                        data = $(this).closest("tr").data("click"),
221                        url = "";
222
223                    if (typeof id !== "undefined") {
224                        // Couvrir les cas comme:
225                        // 1. id="billing-detail_571"
226                        // 2. id="billing-detail-stripe_in_123456789"
227                        const parts = id.split("_");
228                        id = [parts[0], parts.slice(1).join("_")]; // Reconstruire les deux parties
229                    } else {
230                        id = "";
231                    }
232
233                    // No id = no good url to go
234                    if (!id && typeof data === "undefined") {
235                        return false;
236                    }
237
238                    if (typeof clickToUrl !== "undefined") {
239                        url = clickToUrl;
240                    } else {
241                        if (typeof window.location.origin === "undefined") {
242                            window.location.origin = window.location.protocol + "//" + window.location.host;
243                        }
244
245                        var action = "",
246                            param = window.location.href.replace(window.location.origin + "/", "").split("/"),
247                            module = typeof param[0] !== "undefined" ? param[0] : "",
248                            locale = typeof param[1] !== "undefined" ? param[1] : "",
249                            controller = typeof param[2] !== "undefined" ? param[2] : "";
250
251                        url = window.location.origin + "/" + (module ? module + "/" : "") + (locale ? locale + "/" : "");
252
253                        // If data redefine the action
254                        if (data) {
255                            if (typeof data.module !== "undefined") {
256                                url = window.location.origin + "/" + data.module + "/" + (locale ? locale + "/" : "");
257                            }
258
259                            if (typeof data.action !== "undefined") {
260                                action = data.action;
261                            }
262                            // Old data
263                            else if (typeof data === "string") {
264                                action = data;
265                            }
266                        }
267
268                        if (action) {
269                            url += action;
270                        }
271                        // Default use the id attribute
272                        else {
273                            url += (controller ? controller + "/" : "") + id[0];
274                        }
275                    }
276
277                    if (data && typeof data.ids !== "undefined") {
278                        var separator = "/",
279                            first = "/",
280                            glue = "/";
281
282                        if (typeof method !== "undefined" && method === "GET") {
283                            separator = "=";
284                            first = "?";
285                            glue = "&";
286                        }
287
288                        url += first;
289
290                        for (var k in data.ids) {
291                            // eslint-disable-next-line no-prototype-builtins
292                            if (data.ids.hasOwnProperty(k)) {
293                                url += k + separator + data.ids[k] + glue;
294                            }
295                        }
296                    }
297                    // @deprecated
298                    else if (typeof params !== "undefined" && params !== null) {
299                        for (var i in params) {
300                            var ii = parseInt(i) + 1;
301                            url += "/" + params[i] + "/" + id[ii];
302                        }
303                    }
304                    // Default use the id attribute
305                    else {
306                        url += "/id/" + id[1];
307                    }
308
309                    // Inspector Panel Integration - intercept configured table row clicks
310                    if (t.useInspector && id[1]) {
311                        const entityId = id[1];
312                        const contextList = t.inspectorContextList;
313                        const currentContext = contextList[0] || {};
314
315                        window.dispatchEvent(
316                            new CustomEvent("inspector:open", {
317                                detail: {
318                                    ...currentContext,
319                                    id: entityId,
320                                    relatedContextList: contextList,
321                                },
322                            })
323                        );
324                        return;
325                    }
326
327                    window.location.href = url;
328                }
329            );
330
331            return this;
332        };
333
334        /**
335         * Create the 'delete' action on .deleteLink
336         * If the delete link has no URL, it directly display the modal, otherwise it will load the result of this URL into the modal content
337         *
338         * @param urlD : Delete URL
339         * @param modalId
340         * @returns {HPJUtils}
341         */
342        this.initClickToDelete = function (urlD, modalId) {
343            var modalValid = null,
344                tD = this;
345            modalId = typeof modalId !== "undefined" ? modalId : "#modal-doc";
346
347            $("body").on("click", t.table + " .deleteLink", function (e) {
348                e.preventDefault();
349                var id = $(this).attr("id").split("_")[1],
350                    url = $(this).attr("href");
351
352                tD.initModal(url);
353                modalValid.setAction(".modal-yes", function () {
354                    HPJUtils.displayLoadingBox();
355
356                    $.ajax({
357                        url: urlD + "/id/" + id,
358                        dataType: "json",
359                        success: function (data) {
360                            var mesgWrapper = $("#message_box");
361                            mesgWrapper.html("");
362
363                            if (data.mesg) {
364                                mesgWrapper.html(data.mesg);
365                                $("html, body").animate({ scrollTop: mesgWrapper.position().top - 50 }, 500, "easeInSine");
366                            }
367
368                            if (!data.error) {
369                                if (data.redirect_url) {
370                                    window.location.href = data.redirect_url;
371                                } else {
372                                    var line = $("#item_" + id);
373
374                                    if (!line.length) {
375                                        line = $("#edit_" + id);
376                                        if (!line.length) {
377                                            line = $('[id$="-edit_' + id + '"]');
378                                        }
379                                    }
380
381                                    line.fadeOut(1000, function () {
382                                        $(this).remove();
383                                    });
384
385                                    // No more line : reload the page (-1 because the current line is not yet removed)
386                                    if (!($(t.table + " ._actionTd").length - 1)) {
387                                        window.location.reload();
388                                    } else {
389                                        var nbItemW = $(".paginatorNbRow span", t.table);
390
391                                        if (nbItemW.length) {
392                                            nbItemW.html(nbItemW.html() - 1);
393                                        }
394
395                                        HPJUtils.hideLoadingBox();
396                                    }
397                                }
398                            }
399
400                            if (data.reload) {
401                                location.reload();
402                            }
403                        },
404                        complete: function () {
405                            HPJUtils.hideLoadingBox();
406                            modalValid.close();
407                        },
408                    });
409                });
410            });
411
412            this.initModal = function (url) {
413                modalValid = new HPJUtils.modal(modalId);
414
415                if (typeof url === "undefined" || !url) {
416                    modalValid.open();
417                    return true;
418                }
419
420                $.ajax({
421                    url: url,
422                    dataType: "json",
423                    success: function (data) {
424                        if (data.content) {
425                            tD.modalCallback(data);
426                            modalValid.open(data.content);
427                        }
428
429                        //Disable and hide the validation button if something went wrong
430                        if (data.error) {
431                            $(modalId).find(".modal-yes").attr("disabled", true).addClass("d-none");
432                        } else {
433                            $(modalId).find(".modal-yes").attr("disabled", false).removeAttr("disabled").removeClass("d-none");
434                        }
435                    },
436                });
437            };
438
439            // Client defined callback after modal opening
440            this.modalCallback = function () {};
441
442            this.setModalCallback = function (callBack) {
443                this.modalCallback = callBack;
444                return this;
445            };
446
447            return this;
448        };
449        this.initDuplicate = function () {
450            $(document).on("click", t.table + " .duplicate", function (e) {
451                e.preventDefault();
452                HPJUtils.displayLoadingBox();
453                $(".priority-messages").remove();
454                $.ajax({
455                    url: $(this).attr("href"),
456                    dataType: "json",
457                    success: function (data) {
458                        if (data.result) {
459                            window.location.href = data.url;
460                        } else {
461                            $(t.table).closest(".list-result-wrapper").before(data.error);
462                        }
463                    },
464                    complete: function () {
465                        HPJUtils.hideLoadingBox();
466                    },
467                });
468            });
469
470            return this;
471        };
472    },
473    tableUX: function () {
474        var table = $(".table-responsive > .table");
475
476        if (!table.length || typeof table.floatThead !== "function") {
477            return false;
478        }
479
480        table.floatThead({
481            scrollContainer: function ($t) {
482                return $t.closest(".table-responsive");
483            },
484            zIndex: 999,
485        });
486    },
487    tableStickyHeaderRefresh: function () {
488        var table = $(".table-responsive > .table");
489
490        if (!table.length) {
491            return false;
492        }
493
494        table.trigger("reflow");
495    },
496    modal: function (modal) {
497        this.open = function (content) {
498            if (typeof content !== "undefined") {
499                if ($(modal).hasClass("modalux4")) {
500                    $(".modal-body > div", modal).html(content);
501                } else {
502                    $(".modal-body", modal).html(content);
503                }
504            }
505
506            $(modal).modal();
507
508            return this;
509        };
510        this.close = function () {
511            $(modal).modal("hide");
512            return this;
513        };
514        this.setTitle = function (title) {
515            if ($(modal).hasClass("modalux4")) {
516                if ($("#defaultModalTitle", modal).length) {
517                    $("#defaultModalTitle", modal).html(title);
518                } else {
519                    $(".modal-body", modal).prepend('<h3 id="defaultModalTitle">' + title + "</h3>");
520                }
521            } else {
522                $(".modal-title", $(modal)).html(title);
523            }
524
525            return this;
526        };
527        this.setContent = function (content) {
528            if ($(modal).hasClass("modalux4")) {
529                $(".modal-body > div", modal).html(content);
530            } else {
531                $(modal).find(".modal-body").html(content);
532            }
533
534            return this;
535        };
536        this.setFooter = function (content) {
537            $(modal).find(".modal-footer").html(content);
538            return this;
539        };
540        this.getContentWrapper = function () {
541            return $(".modal-body", $(modal));
542        };
543        this.getElement = function () {
544            return $(modal);
545        };
546        /**
547         * To hide or show an element in the Modal scope
548         */
549        this.hide = function (c, hide) {
550            if (typeof hide === "undefined") {
551                hide = true;
552            }
553
554            if (hide) {
555                $(c, $(modal)).hide();
556            } else {
557                $(c, $(modal)).show();
558            }
559
560            return this;
561        };
562        this.hideYes = function (hide) {
563            return this.hide(".modal-yes", hide);
564        };
565        this.hideCancel = function (hide) {
566            return this.hide(".modal-cancel", hide);
567        };
568        this.hideClose = function (hide) {
569            if ($(modal).hasClass("modalux4")) {
570                this.hide(".modal-header .close", hide);
571            }
572
573            return this.hide(".js-modal-close", hide);
574        };
575        this.show = function (context, show) {
576            show = show ? "show" : "hide";
577
578            switch (context) {
579                case "header":
580                    $(modal).find(".modal-header")[show]();
581                    break;
582                case "body":
583                    $(modal).find(".modal-body")[show]();
584                    break;
585                case "footer":
586                    $(modal).find(".modal-footer")[show]();
587                    break;
588            }
589        };
590        /**
591         * Bind the function 'doThis' to the element 'on'
592         */
593        this.setAction = function (on, doThis) {
594            if (typeof doThis !== "function") {
595                return false;
596            }
597
598            $("body")
599                .off("click", modal + " " + on)
600                .on("click", modal + " " + on, function (e) {
601                    doThis(e, this);
602                });
603
604            return this;
605        };
606    },
607    dragDrop: function (callUrl, maxDepth) {
608        this.callUrl = callUrl;
609        this.maxDepth = typeof maxDepth !== "undefined" ? maxDepth : 2;
610        this.currentPos = "";
611        this.init = function (id) {
612            var self = this,
613                n = $(id),
614                fake_item = $(".dd-item.dd-fake");
615
616            n.nestable({
617                maxDepth: this.maxDepth,
618                expandBtnHTML: "",
619                collapseBtnHTML: "",
620            });
621
622            // Keep last order to prevent useless update
623            this.currentPos = window.JSON.stringify(n.nestable("serialize"));
624
625            n.on("change", function (e) {
626                fake_item.appendTo($(".dd > .dd-list"));
627                self.update(e);
628            });
629        };
630        this.update = function (e) {
631            var list = e.length ? e : $(e.target),
632                data = list.nestable("serialize");
633            data = window.JSON.stringify(data);
634
635            if (this.currentPos != data) {
636                $.ajax({
637                    type: "POST",
638                    data: { list: data },
639                    url: this.callUrl,
640                    dataType: "json",
641                    success: function (data) {
642                        // Reload on error
643                        if (data.error) {
644                            location.reload();
645                        }
646                    },
647                });
648            }
649
650            this.currentPos = data;
651        };
652    },
653    /**
654     * Handle status update on Ajax
655     * Any DOM element of class this.target will trigger the update on change
656     */
657    status: function (url, afterSuccess) {
658        this.url = url;
659        this.wrapper = "";
660        this.wrapperUpdate = "";
661        this.loading = "";
662        this.target = ".status-update";
663        this.type = "";
664        this.listen = "click";
665
666        this.beforeCall = function () {
667            return true;
668        };
669
670        this.callBack = function () {};
671
672        this.setWrapper = function (wrapper) {
673            this.wrapper = wrapper;
674            this.target = this.wrapper + " " + this.target;
675
676            var test = $(this.target).first();
677
678            if (test.length) {
679                this.type = test.attr("type");
680                if (this.type) {
681                    this.listen = "change";
682                }
683            }
684
685            return this;
686        };
687
688        this.setLoading = function (loading) {
689            if (loading === "default" || loading === "mini") {
690                this.loading = loading;
691            }
692
693            return this;
694        };
695
696        /**
697         * @param wrapperUpdate : selector of an element to update after callback
698         */
699        this.setWrapperUpdate = function (wrapperUpdate) {
700            this.wrapperUpdate = wrapperUpdate;
701            return this;
702        };
703
704        this.setCallBack = function (callBack) {
705            this.callBack = callBack;
706            return this;
707        };
708
709        this.init = function (wrapperCall, wrapperUpdate) {
710            this.setWrapper(wrapperCall);
711            this.setWrapperUpdate(wrapperUpdate);
712            var self = this;
713
714            $("body")
715                .off(this.listen, self.target)
716                .on(this.listen, self.target, function () {
717                    self.call(this);
718                });
719        };
720
721        this.call = function (e) {
722            var that = this;
723
724            if (this.loading === "default") {
725                HPJUtils.displayLoadingBox();
726            }
727
728            // If before call condition is not met, stop request
729            if (!this.beforeCall({ self: e })) {
730                return false;
731            }
732
733            e = $(e);
734            var v = e.val(),
735                id = e.data("id"),
736                self = this;
737
738            if (this.type === "checkbox") {
739                v = e.is(":checked") ? 1 : 0;
740            }
741
742            var previousState = !v;
743
744            $.ajax({
745                type: "POST",
746                data: {
747                    id: id,
748                    value: v,
749                },
750                url: this.url,
751                dataType: "json",
752                success: function (data) {
753                    var mesgWrapper = $("#message_box").html("");
754
755                    if (data.error) {
756                        e.prop("checked", previousState);
757                    }
758
759                    if (data.mesg) {
760                        mesgWrapper.html(data.mesg);
761                    } else {
762                        mesgWrapper.html("");
763                    }
764
765                    if (!data.error && self.wrapperUpdate && data.update) {
766                        $(self.wrapperUpdate).html(data.update);
767                    }
768
769                    data.value = v;
770                    self.callBack(data);
771
772                    if (typeof afterSuccess == "function") {
773                        afterSuccess(data);
774                    }
775                },
776                complete: function () {
777                    if (self.loading === "default") {
778                        HPJUtils.hideLoadingBox();
779                    }
780                },
781            });
782        };
783    },
784
785    simpleTableNavig: function () {
786        this.initClickTo = function () {
787            $(".click_to td").each(function () {
788                $(this).click(function (event) {
789                    if ($(this).attr("class") !== "_actionTd") {
790                        var url = $(this).closest("tr").attr("click_to");
791                        window.location.href = url;
792                    }
793                });
794            });
795        };
796    },
797
798    slug: function (str) {
799        str = str.replace(/^\s+|\s+$/g, "");
800        str = str.toLowerCase();
801        var from = "ãàáäâẽèéëêìíïîõòóöôùúüûñç·/_,:;";
802        var to = "aaaaaeeeeeiiiiooooouuuunc------";
803
804        for (var i = 0, l = from.length; i < l; i++) {
805            str = str.replace(new RegExp(from.charAt(i), "g"), to.charAt(i));
806        }
807
808        return str
809            .replace(/[^a-z0-9 -]/g, "")
810            .replace(/\s+/g, "-")
811            .replace(/-+/g, "-");
812    },
813
814    getUrlVars: function () {
815        var vars = [];
816        var parts = window.location.search.substring(1).split("&");
817
818        for (var i = 0; i < parts.length; i++) {
819            var pair = parts[i].split("=");
820            vars[pair[0]] = pair[1];
821        }
822
823        return vars;
824    },
825
826    show: function (that) {
827        $(that).removeClass("d-none");
828    },
829
830    hide: function (that) {
831        $(that).addClass("d-none");
832    },
833};
834
835var HPJForm = {
836    /**
837     * Toggle the visibility of forms elements based on elem value
838     *
839     * @param elem | element triggering the toggle
840     * @param toggleThat | element to be toggled
841     * @param valShow | value or list of values of the 'elem' that will show toggleThat
842     */
843    toggle: function (elem, toggleThat, valShow) {
844        valShow = typeof valShow !== "undefined" ? valShow : 1;
845
846        if (typeof valShow !== "object") {
847            valShow = [valShow.toString()];
848        }
849
850        if ($.isArray(toggleThat)) {
851            var toggleOther = toggleThat[1];
852            toggleThat = toggleThat[0];
853        }
854
855        var getVal = ":checked";
856
857        if ($(elem).is("select")) {
858            getVal = "";
859        }
860
861        if (typeof $(elem + getVal).val() === "undefined" || $.inArray($(elem + getVal).val(), valShow) === -1) {
862            $(toggleThat).hide();
863        } else if (typeof toggleOther !== "undefined" && $.inArray($(elem + getVal).val(), valShow) !== -1) {
864            $(toggleOther).hide();
865        }
866
867        $("body")
868            .off("change", elem)
869            .on("change", elem, function () {
870                var show = $.inArray($(elem + getVal).val(), valShow) !== -1;
871                $(toggleThat)[show ? "show" : "hide"]();
872                $(toggleOther)[!show ? "show" : "hide"]();
873            });
874    },
875    /**
876     * Clear a field (even input type=file)
877     */
878    clear: function (on, clearThat) {
879        if (typeof on === "undefined") {
880            on = $(".btn-clear-file");
881        } else if (typeof on !== "object") {
882            on = $(on);
883        }
884
885        if (typeof clearThat === "undefined") {
886            clearThat = $("#" + on.data("id"));
887        } else if (typeof clearThat !== "object") {
888            clearThat = $(clearThat);
889        }
890
891        on.click(function (event) {
892            clearThat.val("");
893            //clearThat.replaceWith( clearThat = clearThat.clone( true ) );
894        });
895    },
896    getStates: function () {
897        let countryField = $(".js-select-country");
898
899        if (!countryField.length) {
900            return null;
901        }
902
903        countryField.each(function () {
904            const form = $(this).closest("form");
905
906            let stateField = form.find(".js-select-state");
907
908            if (this.closest("[data-state-alias]")) {
909                const countryStateAlias = this.closest("[data-state-alias]").dataset.stateAlias;
910                stateField = countryStateAlias ? form.find("#" + countryStateAlias) : null;
911            }
912
913            if (!stateField.length) return;
914
915            if (stateField.length > 1) {
916                // Only the event registration form with registration manager can have multiple country fields (and therefore states)
917                stateField = $(this).closest(".section").find(".js-select-state");
918
919                if (!stateField.length || stateField.length === 0) {
920                    // If for some reason the layout has changed, give up on the state field
921                    return null;
922                }
923            }
924
925            let defaultCountry = $(this).find("option:selected").val();
926            let defaultState = stateField.find("option:selected").val();
927            let defaultStateInWrapper = $(this).closest(".section").find(".js-state-wrapper").attr("data-default");
928
929            if (!["CA", "US", "IT"].includes(defaultCountry)) {
930                HPJForm.clearStates(stateField);
931            }
932
933            $(this)
934                .off(".countryGetStates")
935                .on("change.countryGetStates", function () {
936                    if (["CA", "US", "IT"].includes($(this).val())) {
937                        let url = "/form/" + language + "/form/getstates/country/" + $(this).val() + "/empty/1";
938
939                        $.ajax({
940                            url: url,
941                            dataType: "json",
942                            success: function (data) {
943                                stateField.empty();
944
945                                $.each(data, function (key, value) {
946                                    value = key == "" ? value + "..." : value;
947                                    stateField.append('<option value="' + key + '">' + value + "</option>");
948                                });
949
950                                stateField.closest(".js-state-wrapper").show();
951                            },
952                            complete: function () {
953                                const priorities = [stateField.get(0).dataset?.targetValue ?? "", defaultState, defaultStateInWrapper, ""];
954
955                                const targetValue = priorities.find(
956                                    (value) =>
957                                        typeof value === "string" && value.trim() !== "" && stateField.find(`option[value="${value}"]`).length > 0
958                                );
959
960                                if (targetValue !== undefined) {
961                                    stateField.find(`option[value="${targetValue}"]`).prop("selected", true);
962                                }
963                            },
964                        });
965                    } else {
966                        HPJForm.clearStates(stateField);
967                    }
968                });
969        });
970
971        $(document).ready(function () {
972            $(".js-select-country").trigger("change.countryGetStates");
973        });
974    },
975    getFiscalcode: function (countryField) {
976        if (typeof countryField === "undefined" || !countryField) {
977            countryField = "#country";
978        }
979
980        const initCountryVal = $(countryField + " option:selected").val();
981
982        if (!["IT"].includes(initCountryVal)) {
983            this.clearFiscalcode();
984        }
985
986        const self = this;
987
988        $(document).on("change", countryField, function () {
989            if (["IT"].includes($(this).val())) {
990                $(".js-fiscalcode-wrapper").show();
991            } else {
992                self.clearFiscalcode();
993            }
994        });
995
996        $(document).ready(function () {
997            $(countryField).trigger("change");
998        });
999    },
1000    getIntracommunityvat: function (countryField) {
1001        if (typeof countryField === "undefined" || !countryField) {
1002            countryField = "#country";
1003        }
1004
1005        const initCountryVal = $(countryField + " option:selected").val();
1006
1007        if (!["BE", "IT"].includes(initCountryVal)) {
1008            this.clearIntracommunityvat();
1009        }
1010
1011        const self = this;
1012
1013        $(document).on("change", countryField, function () {
1014            if (["BE", "IT"].includes($(this).val())) {
1015                $(".js-intracommunityvat-wrapper").show();
1016            } else {
1017                self.clearIntracommunityvat();
1018            }
1019        });
1020
1021        $(document).ready(function () {
1022            $(countryField).trigger("change");
1023        });
1024    },
1025    clearStates: function (stateField) {
1026        stateField.closest(".js-state-wrapper").hide();
1027
1028        stateField
1029            .empty()
1030            // Set empty value to update DB last value
1031            .append('<option value=""></option>');
1032    },
1033    clearFiscalcode: function () {
1034        $(".js-fiscalcode-wrapper").hide();
1035    },
1036    clearIntracommunityvat: function () {
1037        $(".js-intracommunityvat-wrapper").hide();
1038    },
1039    // Default add mechanism
1040    getOptions: function (urlOptAdd, field) {
1041        if (typeof field === "undefined") {
1042            field = "option";
1043        }
1044
1045        // option delete
1046        $("body").on("click", "." + field + "-moins", function (e) {
1047            var id = $(this).data("id"),
1048                wrapper = $("#" + field + "-select-wrapper" + id),
1049                name = $("#" + field + "-name" + id).html();
1050
1051            // restore option to select
1052            var option = '<option label="' + name + '" value="' + id + '">' + name + "</option>";
1053            $("#" + field + "_select").append(option);
1054
1055            wrapper.remove();
1056        });
1057
1058        // option add
1059        $("#" + field + "-plus").click(function () {
1060            var option = $("#" + field + "_select").val(),
1061                name = $("#" + field + "_select option:selected").text();
1062
1063            if (option != 0) {
1064                HPJUtils.displayLoadingBox();
1065
1066                $.ajax({
1067                    url: urlOptAdd,
1068                    data: { option: option, name: name },
1069                    dataType: "json",
1070                    success: function (data) {
1071                        if (data.error) {
1072                            $("#" + field + "-mesg").html(data.error);
1073                        } else {
1074                            $("#" + field + '_select option[value="' + option + '"]').remove();
1075                            $("#" + field + "-select-wrapper").before(data.item);
1076                        }
1077                    },
1078                    complete: function () {
1079                        HPJUtils.hideLoadingBox();
1080                    },
1081                });
1082            }
1083        });
1084    },
1085    addHelpBlock: function (element, content, position) {
1086        position = position || "";
1087        var className = position.length > 0 ? "help-block-" + position : position;
1088        $(element)
1089            .find("p" + (className.length ? "." + className : "help-block"))
1090            .remove();
1091
1092        if (typeof content != "undefined" && content.length) {
1093            $(element).append('<p class="help-block ' + className + '">' + content + "</p>");
1094        }
1095    },
1096    //TODO Uniformiser l'application pour utiliser cette function a l'avenir
1097    datePicker: function () {
1098        $(".datePicker").each(function () {
1099            var config = { dateFormat: "yy-mm-dd" };
1100
1101            if ($(this).data("max-date") && $(this).data("max-date").length) {
1102                config.maxDate = $(this).data("max-date");
1103            }
1104
1105            if ($(this).data("min-date") && $(this).data("min-date").length) {
1106                config.minDate = $(this).data("min-date");
1107
1108                if (typeof config.maxDate != "undefined") {
1109                    var y1 = parseInt(/(\d{4})/.exec(config.maxDate)[0]),
1110                        y2 = parseInt(/(\d{4})/.exec(config.minDate)[0]);
1111
1112                    if (y1 < y2) {
1113                        config.minDate = "";
1114                    }
1115                }
1116            }
1117
1118            if ($(this).data("year-range") && $(this).data("year-range").length) {
1119                config.yearRange = $(this).data("year-range");
1120            }
1121
1122            if ($(this).data("format")) {
1123                config.dateFormat = $(this).data("format");
1124            } else if ($(this).hasClass("dateFormatfr")) {
1125                config.dateFormat = "dd-mm-yy";
1126            }
1127
1128            if ($(this).data("default-year-shift")) {
1129                config.defaultDate = $(this).data("default-year-shift") + "y";
1130            }
1131
1132            $(this).datepicker(config);
1133        });
1134    },
1135    errorJump: function (form, next) {
1136        var offset = 20;
1137
1138        $(form).find(".has-error").closest(".section").find(".section-title__collapsed").removeClass("section-title__collapsed");
1139
1140        if ($(".app__header").length) {
1141            offset += $(".app__header").innerHeight();
1142        }
1143
1144        $(form)
1145            .find(".has-error:first")
1146            .each(function () {
1147                $([document.documentElement, document.body]).animate(
1148                    {
1149                        scrollTop: $(this).offset().top - offset - 20,
1150                    },
1151                    2000
1152                );
1153                $(this).find("select:visible,input:visible,text:visible,textarea:visible").focus();
1154            });
1155
1156        if (next) {
1157            $(form).on("change", "select,input,text,textarea", function () {
1158                $(this).closest(".has-error").find(".errors").remove().removeClass("has-error");
1159                $(this).closest(".has-error").removeClass("has-error");
1160                $(form)
1161                    .find(".has-error:first")
1162                    .each(function () {
1163                        $([document.documentElement, document.body]).animate(
1164                            {
1165                                scrollTop: $(this).offset().top - offset - 20,
1166                            },
1167                            1000
1168                        );
1169                        $(this).find("select:visible,input:visible,text:visible,textarea:visible").focus();
1170                    });
1171            });
1172        }
1173    },
1174    multiSelect: function () {
1175        $(document)
1176            .off("click", "[data-chosen-init]")
1177            .off("click", "[data-chosen-all]")
1178            .on("click", "[data-chosen-all]", function (e) {
1179                $($(this).data("chosen-all")).find("option").prop("selected", true);
1180                $($(this).data("chosen-all")).trigger("chosen:updated").trigger("change");
1181                e.preventDefault();
1182                e.stopPropagation();
1183            })
1184            .on("click", "[data-chosen-init]", function (e) {
1185                $($(this).data("chosen-init")).val("").trigger("chosen:updated").trigger("change");
1186                e.preventDefault();
1187                e.stopPropagation();
1188            });
1189    },
1190    afterLoad: function (form) {
1191        var ckeditorInit = true;
1192
1193        if (!form) {
1194            form = $(document);
1195            ckeditorInit = false;
1196        }
1197
1198        form.find("label.required").each(function (index) {
1199            if ($(this).text().indexOf("*") == -1) {
1200                var html = $(this).html();
1201                if (html.indexOf("<") !== -1) {
1202                    html = html.slice(0, html.indexOf("<")) + '<span class="control-label--required">&nbsp;*</span>' + html.slice(html.indexOf("<"));
1203                    $(this).html(html);
1204                } else {
1205                    $(this).append('<span class="control-label--required">&nbsp;*</span>');
1206                }
1207            }
1208        });
1209
1210        form.find(".select-country").find("select").trigger("change");
1211        this.datePicker();
1212
1213        form.find("[data-conditional-field]").trigger("change");
1214
1215        form.find("[data-display-conditions]").trigger("change");
1216
1217        try {
1218            memboGo.Field.Autocomplete.init();
1219        } catch (e) {
1220            memboGo.core.dispatchException(e);
1221        }
1222
1223        ckeditorInit && memboGo.core.ckeditor.init(form);
1224
1225        HPJForm.getStates();
1226    },
1227    addResetBtn: function (element, form) {
1228        $(document)
1229            .off("click", element)
1230            .on("click", element, function (e) {
1231                e.preventDefault();
1232                e.stopPropagation();
1233                $(form)
1234                    .find("input,textarea,select")
1235                    .each(function (e) {
1236                        if ($(this).attr("type") !== "submit") {
1237                            $(this).val("");
1238                        }
1239                    });
1240                $(form).find("input:radio, input:checkbox").removeAttr("checked").removeAttr("selected");
1241
1242                $('select[multiple="multiple"]').each(function () {
1243                    $(this).val("").trigger("chosen:updated");
1244                });
1245                // @NOTE -100 of the headers
1246                $("html,body").animate({ scrollTop: $("form").offset().top - 100 }, "fast");
1247            });
1248    },
1249};
1250
1251var HPJMath = {
1252    toFloat: function (n) {
1253        return typeof n === "number" ? n : parseFloat(n.replace(",", "."));
1254    },
1255    toInt: function (n) {
1256        return typeof n === "number" ? n : parseInt(n.replace(",", "."));
1257    },
1258};
1259
1260/**
1261 * Used to submit generated form
1262 */
1263var clickCount = 0;
1264
1265/**
1266 * Collision detection for a table's option menu
1267 */
1268function tableOptionsMenu() {
1269    var row_opt_btn = $("table .btn-group");
1270
1271    if (!row_opt_btn.length) {
1272        return false;
1273    }
1274
1275    row_opt_btn.on("shown.bs.dropdown", function () {
1276        var menu = $(this).find(".dropdown-menu"),
1277            toggle = $(this).find(".dropdown-toggle"),
1278            table_container = $(this).closest(".table-responsive, .table-simple");
1279
1280        if (toggle != null && toggle.length == 1) {
1281            toggle.addClass("table-option");
1282        }
1283
1284        if (menu != null && menu.length == 1) {
1285            var btn = menu.parent();
1286
1287            menu.addClass("table-option");
1288            menu.position({
1289                my: "right center",
1290                at: "left-25px center",
1291                of: btn,
1292                collision: "none fit",
1293                within: table_container,
1294            });
1295        }
1296    });
1297
1298    row_opt_btn.on("hidden.bs.dropdown", function () {
1299        var menu = $(this).find(".dropdown-menu");
1300
1301        if (menu != null && menu.length == 1) {
1302            menu.css({ top: "", left: "" });
1303        }
1304    });
1305}
1306
1307$(document).ready(function () {
1308    /**
1309     * Init Bootstrap tooltip
1310     */
1311    $(document.body).tooltip({
1312        selector: '[data-toggle="tooltip"]',
1313    });
1314
1315    $(".form-submit").bind("click", function (e) {
1316        e.preventDefault();
1317
1318        if (clickCount == 0) {
1319            var element = $(this).data("form") || ".js-form-bind form";
1320            var href = $(this).attr("href");
1321            if (href) {
1322                $(element).attr("action", href);
1323            }
1324            $(element).submit();
1325        }
1326
1327        clickCount++;
1328    });
1329
1330    /**
1331     * Component selector
1332     */
1333    $('select[name="componentSelect"]').change(function () {
1334        if ($(this).val() != "") {
1335            window.location.href = $(this).val();
1336        }
1337    });
1338
1339    /**
1340     * Account selector
1341     */
1342    $('select[name="accountSelect"]').change(function () {
1343        if ($(this).val() != "") {
1344            var userId = $(this).val();
1345            var url = "/profile/" + language + "/authentication/autologin/id/" + userId;
1346            window.location.href = url;
1347        }
1348    });
1349
1350    HPJForm.getStates();
1351});
1352
1353$(document).on("click", "[data-modal]", function () {
1354    if ($(this).find(".body").length) {
1355        var id = $(this).data("modal"),
1356            text = "<p>" + $(this).find(".body").html() + "</p>";
1357
1358        if ($("#" + id).length) {
1359            $("#" + id)
1360                .find(".modal-body")
1361                .html(text);
1362        } else {
1363            var html =
1364                '<div id="' +
1365                id +
1366                '" class="modal fade" aria-hidden="true" style="display: none;"><div class="modal-dialog"><div class="modal-content">';
1367
1368            if ($(this).find(".header").length) {
1369                html += '<div class="modal-header">';
1370                html +=
1371                    '<button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button>';
1372                html += '<h4 class="modal-title">' + $(this).find(".header").html() + "</h4></div>";
1373            }
1374
1375            html += '<div class="modal-body">' + text + "</div>";
1376            html += "</div></div></div>";
1377            $("body").append(html);
1378        }
1379
1380        $(this).find(".header,.body").remove();
1381    }
1382});

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.