PageSourceSearch

https://unblockedbook.com/wp-content/plugins/pixelyoursite/dist/scripts/public.js?ver=11.0.2

js unblockedbook.com collected 2026-09-28 08:02:02 UTC 146,500 bytes, 3,494 lines download raw bytes

1/* global pysOptions */
2
3
4! function ($, options) {
5    if (options.debug) {
6        console.log('PYS:', options);
7    }
8    var uniqueId = {};
9
10    let gtm_variables = {};
11    let gtm_datalayername = "dynamicVariable";
12
13    var domain = '';
14    if(options.hasOwnProperty("track_cookie_for_subdomains") && options.track_cookie_for_subdomains) {
15        domain = getRootDomain(true);
16    }
17
18    var dummyPinterest = function () {
19
20        /**
21         * Public API
22         */
23        return {
24            isEnabled: function () {},
25            disable: function () {},
26            loadPixel: function () {},
27            fireEvent: function (name, data) {
28                return false;
29            },
30            onCommentEvent: function () {},
31            onDownloadEvent: function (params) {},
32            onFormEvent: function (params) {},
33            onWooAddToCartOnButtonEvent: function (product_id) {},
34            onWooAddToCartOnSingleEvent: function (product_id, qty, is_variable, is_external, $form) {},
35            onWooRemoveFromCartEvent: function (cart_item_hash) {},
36            onEddAddToCartOnButtonEvent: function (download_id, price_index, qty) {},
37            onEddRemoveFromCartEvent: function (item) {},
38            onPageScroll: function (event) {},
39            onTime: function (event) {},
40
41        }
42
43    }();
44
45    var dummyBing = function () {
46
47        /**
48         * Public API
49         */
50        return {
51            isEnabled: function () {},
52            disable: function () {},
53            loadPixel: function () {},
54            fireEvent: function (name, data) {
55                return false;
56            },
57            onAdSenseEvent: function () {},
58            onClickEvent: function (params) {},
59            onWatchVideo: function (params) {},
60            onCommentEvent: function () {},
61            onFormEvent: function (params) {},
62            onDownloadEvent: function (params) {},
63            onWooAddToCartOnButtonEvent: function (product_id) {},
64            onWooAddToCartOnSingleEvent: function (product_id, qty, is_variable, is_external, $form) {},
65            onWooRemoveFromCartEvent: function (cart_item_hash) {},
66            onWooAffiliateEvent: function (product_id) {},
67            onWooPayPalEvent: function () {},
68            onEddAddToCartOnButtonEvent: function (download_id, price_index, qty) {},
69            onEddRemoveFromCartEvent: function (item) {},
70            onPageScroll: function (event) {},
71            onTime: function (event) {},
72        }
73
74    }();
75
76    var Utils = function (options) {
77
78        var Pinterest = dummyPinterest;
79
80        var Bing = dummyBing;
81
82        var gtag_loaded = false;
83
84        var gtm_loaded = false;
85
86        let isNewSession = checkSession();
87
88        var utmTerms = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content'];
89
90        var utmId = ['fbadid', 'gadid', 'padid', 'bingid'];
91
92        let dataLayerName = 'dataLayerPYS';
93
94        let GTMdataLayerName = 'dataLayer';
95
96        function validateEmail(email) {
97            var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
98            return re.test(email);
99        }
100        function getDomain(url) {
101
102            url = url.replace(/(https?:\/\/)?(www.)?/i, '');
103
104            if (url.indexOf('/') !== -1) {
105                return url.split('/')[0];
106            }
107
108            return url;
109        }
110        function loadPixels() {
111
112            if (!options.gdpr.all_disabled_by_api) {
113
114                if (!options.gdpr.facebook_disabled_by_api) {
115                    Facebook.loadPixel();
116                }
117
118                if (!options.gdpr.analytics_disabled_by_api) {
119                    Analytics.loadPixel();
120                }
121
122                if (!options.gdpr.analytics_disabled_by_api) {
123                    GTM.loadPixel();
124                }
125
126                if (!options.gdpr.pinterest_disabled_by_api) {
127                    Pinterest.loadPixel();
128                }
129
130                if (!options.gdpr.bing_disabled_by_api) {
131                    Bing.loadPixel();
132                }
133            }
134            if (options.gdpr.consent_magic_integration_enabled && typeof CS_Data !== "undefined") {
135                if (typeof CS_Data.cs_google_analytics_consent_mode !== "undefined" && CS_Data.cs_google_analytics_consent_mode == 1) {
136                    Analytics.loadPixel();
137                }
138            }
139
140        }
141
142        function checkSession() {
143            if( Cookies.get('pys_start_session') === undefined ||
144                Cookies.get('pys_session_limit') === undefined) {
145                firstVisit = true;
146                return true
147            }
148            return false
149
150        }
151
152        function getTrafficSource() {
153
154            try {
155
156                let referrer = document.referrer.toString(),
157                    source;
158
159                let direct = referrer.length === 0;
160                let internal = direct ? false : referrer.indexOf(options.siteUrl) === 0;
161                let external = !direct && !internal;
162
163                if (external === false) {
164                    source = 'direct';
165                } else {
166                    source = referrer;
167                }
168
169                if (source !== 'direct') {
170                    // leave only domain (Issue #70)
171                    return getDomain(source);
172                } else {
173                    return source;
174                }
175
176            } catch (e) {
177                console.error(e);
178                return 'direct';
179            }
180
181        }
182
183        /**
184         * Return query variables object with where property name is query variable
185         * and property value is query variable value.
186         */
187        function getQueryVars() {
188
189            try {
190
191                var result = {},
192                    tmp = [];
193
194                window.location.search
195                    .substr(1)
196                    .split("&")
197                    .forEach(function (item) {
198
199                        tmp = item.split('=');
200
201                        if (tmp.length > 1) {
202                            result[tmp[0]] = tmp[1];
203                        }
204
205                    });
206
207                return result;
208
209            } catch (e) {
210                console.error(e);
211                return {};
212            }
213
214        }
215
216
217        function getLandingPageValue() {
218            let name = "pys_landing_page"
219            if(options.visit_data_model === "last_visit") {
220                name = "last_pys_landing_page"
221            }
222            if(Cookies.get(name) && Cookies.get(name) !== "undefined") {
223                return Cookies.get(name);
224            }
225            else if(options.hasOwnProperty("tracking_analytics") && options.tracking_analytics.TrafficLanding){
226                return options.tracking_analytics.TrafficLanding;
227            } else{
228                return "";
229            }
230        }
231        function getTrafficSourceValue() {
232            let name = "pysTrafficSource"
233            if(options.visit_data_model === "last_visit") {
234                name = "last_pysTrafficSource"
235            }
236            if(Cookies.get(name) && Cookies.get(name) !== "undefined") {
237                return Cookies.get(name);
238            }
239            else if(options.hasOwnProperty("tracking_analytics") && options.tracking_analytics.TrafficSource){
240                return options.tracking_analytics.TrafficSource;
241            } else{
242                return "";
243            }
244        }
245
246        function getUTMId(useLast = false) {
247            try {
248                let cookiePrefix = 'pys_'
249                let terms = [];
250                if (useLast) {
251                    cookiePrefix = 'last_pys_'
252                }
253                $.each(utmId, function (index, name) {
254                    if (Cookies.get(cookiePrefix + name)) {
255                        terms[name] = Cookies.get(cookiePrefix + name)
256                    }
257                    else if(options.hasOwnProperty("tracking_analytics") && options.tracking_analytics.TrafficUtmsId[name]) {
258                        terms[name] = filterEmails(options.tracking_analytics.TrafficUtmsId[name])
259                    }
260                });
261                return terms;
262            } catch (e) {
263                console.error(e);
264                return [];
265            }
266        }
267        /**
268         * Return UTM terms from request query variables or from cookies.
269         */
270        function getUTMs(useLast = false) {
271
272            try {
273                let cookiePrefix = 'pys_'
274                if(useLast) {
275                    cookiePrefix = 'last_pys_'
276                }
277                let terms = [];
278                $.each(utmTerms, function (index, name) {
279                    if (Cookies.get(cookiePrefix + name)) {
280                        let value = Cookies.get(cookiePrefix + name);
281                        terms[name] = filterEmails(value); // do not allow email in request params (Issue #70)
282                    }
283                    else if(options.hasOwnProperty("tracking_analytics") && options.tracking_analytics.TrafficUtms[name]) {
284                        terms[name] = filterEmails(options.tracking_analytics.TrafficUtms[name])
285                    }
286                });
287
288                return terms;
289
290            } catch (e) {
291                console.error(e);
292                return [];
293            }
294
295        }
296
297        function getDateTime() {
298            var dateTime = new Array();
299            var date = new Date(),
300                days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
301                months = ['January', 'February', 'March', 'April', 'May', 'June',
302                    'July', 'August', 'September', 'October', 'November', 'December'
303                ],
304                hours = ['00-01', '01-02', '02-03', '03-04', '04-05', '05-06', '06-07', '07-08',
305                    '08-09', '09-10', '10-11', '11-12', '12-13', '13-14', '14-15', '15-16', '16-17',
306                    '17-18', '18-19', '19-20', '20-21', '21-22', '22-23', '23-24'
307                ];
308            dateTime.push(hours[date.getHours()]);
309            dateTime.push(days[date.getDay()]);
310            dateTime.push(months[date.getMonth()]);
311            return dateTime;
312        }
313
314        function filterEmails(value) {
315            return validateEmail(value) ? undefined : value;
316        }
317
318        /**
319         * PUBLIC API
320         */
321        return {
322            PRODUCT_SIMPLE : 0,
323            PRODUCT_VARIABLE : 1,
324            PRODUCT_BUNDLE : 2,
325            PRODUCT_GROUPED : 3,
326            utmTerms : utmTerms,
327            utmId : utmId,
328            fireEventForAllPixel:function(functionName,events){
329                if (events.hasOwnProperty(Facebook.tag()))
330                    Facebook[functionName](events[Facebook.tag()]);
331                if (events.hasOwnProperty(Analytics.tag()))
332                    Analytics[functionName](events[Analytics.tag()]);
333                if (events.hasOwnProperty(Pinterest.tag()))
334                    Pinterest[functionName](events[Pinterest.tag()]);
335                if (events.hasOwnProperty(Bing.tag()))
336                    Bing[functionName](events[Bing.tag()]);
337
338                if (events.hasOwnProperty(GTM.tag()))
339                    GTM[functionName](events[GTM.tag()]);
340            },
341
342            setupPinterestObject: function () {
343                Pinterest = window.pys.Pinterest || Pinterest;
344                return Pinterest;
345            },
346
347            setupBingObject: function () {
348                Bing = window.pys.Bing || Bing;
349                return Bing;
350            },
351
352            // Clone all object members to another and return it
353            copyProperties: function (from, to) {
354                for (var key in from) {
355                    if("function" == typeof from[key]) {
356                        continue;
357                    }
358                    to[key] = from[key];
359                }
360                return to;
361            },
362
363            manageCookies: function () {
364
365                if (options.gdpr.cookiebot_integration_enabled && typeof Cookiebot !== 'undefined') {
366                    if (Cookiebot.consented === false && !Cookiebot.consent['marketing'] && !Cookiebot.consent['statistics']) {
367                        return;
368                    }
369                }
370                let cm_consent_not_expressed = false;
371                if ( options.gdpr.consent_magic_integration_enabled && window.CS_Data !== undefined && window.CS_Data.cs_refresh_after_consent == 1 ) {
372                    if ( Cookies.get( 'cs_viewed_cookie_policy' ) === undefined ) {
373                        cm_consent_not_expressed = true;
374                    }
375                }
376
377                if( !cm_consent_not_expressed && isNewSession && !options.cookie.disabled_all_cookie && !options.cookie.disabled_start_session_cookie) {
378                    let duration = options.last_visit_duration * 60000
379                    var now = new Date();
380                    now.setTime(now.getTime() + duration);
381                    Cookies.set('pys_session_limit', true,{ expires: now, path: '/',domain: domain })
382                    Cookies.set('pys_start_session', true,{path: '/',domain: domain});
383                }
384
385                if (options.ajaxForServerEvent && !Cookies.get('pbid') && Facebook.isEnabled()) {
386                    jQuery.ajax({
387                        url: options.ajaxUrl,
388                        dataType: 'json',
389                        data: {
390                            action: 'pys_get_pbid'
391                        },
392                        success: function (res) {
393                            if (res.data && res.data.pbid != false && options.send_external_id) {
394                                if(!(options.cookie.disabled_all_cookie || options.cookie.externalID_disabled_by_api)){
395                                    var expires = parseInt(options.external_id_expire || 180);
396                                    Cookies.set('pbid', res.data.pbid, { expires: expires, path: '/',domain: domain });
397                                }
398
399                                if(options.hasOwnProperty('facebook')) {
400                                    options.facebook.advancedMatching = {
401                                        ...options.facebook.advancedMatching,  // распыляем текущие значения advancedMatching
402                                        external_id: res.data.pbid
403                                    };
404                                }
405                            }
406                        }
407                    });
408                } else if (Cookies.get('pbid') && Facebook.isEnabled()){
409                    if(Facebook.advancedMatching() && Facebook.advancedMatching().external_id && !(options.cookie.disabled_all_cookie || options.cookie.externalID_disabled_by_api)){
410                        let expires = parseInt(options.external_id_expire || 180);
411                        Cookies.set('pbid', Facebook.advancedMatching().external_id, { expires: expires, path: '/',domain: domain });
412                    }
413                }
414
415                let expires = parseInt(options.cookie_duration); //  days
416                let queryVars = getQueryVars();
417                let landing = window.location.href.split('?')[0];
418                try {
419                    // save data for first visit
420                    if(Cookies.get('pys_first_visit') === undefined && (!options.cookie.disabled_all_cookie)) {
421
422                        if(!options.cookie.disabled_first_visit_cookie)
423                        {
424                            Cookies.set('pys_first_visit', true, { expires: expires, path: '/',domain: domain });
425                        }
426                        else {
427                            Cookies.remove('pys_first_visit')
428                        }
429
430                        if(!options.cookie.disabled_trafficsource_cookie)
431                        {
432                            Cookies.set('pysTrafficSource', getTrafficSource(), { expires: expires,path: '/',domain: domain });
433                        }
434                        else {
435                            Cookies.remove('pysTrafficSource')
436                        }
437
438                        if(!options.cookie.disabled_landing_page_cookie)
439                        {
440                            Cookies.set('pys_landing_page',landing,{ expires: expires,path: '/',domain: domain });
441                        }
442                        else {
443                            Cookies.remove('pys_landing_page')
444                        }
445
446                        if(!options.cookie.disabled_utmTerms_cookie)
447                        {
448                            $.each(utmTerms, function (index, name) {
449                                if (queryVars.hasOwnProperty(name)) {
450                                    Cookies.set('pys_' + name, queryVars[name], { expires: expires,path: '/',domain: domain });
451                                } else {
452                                    Cookies.remove('pys_' + name)
453                                }
454                            });
455                        }
456                        else {
457                            $.each(utmTerms, function (index, name) {
458                                Cookies.remove('pys_' + name)
459                            });
460                        }
461
462                        if(!options.cookie.disabled_utmId_cookie)
463                        {
464                            $.each(utmId,function(index,name) {
465                                if (queryVars.hasOwnProperty(name)) {
466                                    Cookies.set('pys_' + name, queryVars[name], { expires: expires,path: '/',domain: domain });
467                                } else {
468                                    Cookies.remove('pys_' + name)
469                                }
470                            })
471                        }
472                        else {
473                            $.each(utmId, function (index, name) {
474                                Cookies.remove('pys_' + name)
475                            });
476                        }
477                    }
478
479                    // save data for last visit if it new session
480                    if(isNewSession && (!options.cookie.disabled_all_cookie)) {
481                        if(!options.cookie.disabled_trafficsource_cookie)
482                        {
483                            Cookies.set('last_pysTrafficSource', getTrafficSource(), { expires: expires,path: '/',domain: domain });
484                        }
485                        else {
486                            Cookies.remove('last_pysTrafficSource')
487                        }
488
489                        if(!options.cookie.disabled_landing_page_cookie)
490                        {
491                            Cookies.set('last_pys_landing_page',landing,{ expires: expires,path: '/',domain: domain });
492                        }
493                        else {
494                            Cookies.remove('last_pys_landing_page')
495                        }
496
497                        if(!options.cookie.disabled_utmTerms_cookie)
498                        {
499                            $.each(utmTerms, function (index, name) {
500                                if (queryVars.hasOwnProperty(name)) {
501                                    Cookies.set('last_pys_' + name, queryVars[name], { expires: expires,path: '/',domain: domain });
502                                } else {
503                                    Cookies.remove('last_pys_' + name)
504                                }
505                            });
506                        }
507                        else {
508                            $.each(utmTerms, function (index, name) {
509                                Cookies.remove('last_pys_' + name)
510                            });
511                        }
512
513                        if(!options.cookie.disabled_utmId_cookie)
514                        {
515                            $.each(utmId,function(index,name) {
516                                if (queryVars.hasOwnProperty(name)) {
517                                    Cookies.set('last_pys_' + name, queryVars[name], { expires: expires,path: '/',domain: domain });
518                                } else {
519                                    Cookies.remove('last_pys_' + name)
520                                }
521                            })
522                        }
523                        else {
524                            $.each(utmId, function (index, name) {
525                                Cookies.remove('last_pys_' + name)
526                            });
527                        }
528
529                    }
530                    if(options.cookie.disabled_start_session_cookie) {
531                        Cookies.remove('pys_start_session')
532                        Cookies.remove('pys_session_limit')
533                    }
534                    if(options.cookie.disabled_all_cookie)
535                    {
536                        Cookies.remove('pys_first_visit')
537                        Cookies.remove('pysTrafficSource')
538                        Cookies.remove('pys_landing_page')
539                        Cookies.remove('last_pys_landing_page')
540                        Cookies.remove('last_pysTrafficSource')
541                        Cookies.remove('pys_start_session')
542                        Cookies.remove('pys_session_limit')
543                        $.each(Utils.utmTerms, function (index, name) {
544                            Cookies.remove('pys_' + name)
545                        });
546                        $.each(Utils.utmId,function(index,name) {
547                            Cookies.remove('pys_' + name)
548                        })
549                        $.each(Utils.utmTerms, function (index, name) {
550                            Cookies.remove('last_pys_' + name)
551                        });
552                        $.each(Utils.utmId,function(index,name) {
553                            Cookies.remove('last_pys_' + name)
554                        });
555                    }
556                } catch (e) {
557                    console.error(e);
558                }
559            },
560            /**
561             * Generate unique ID
562             */
563            generateUniqueId : function (event) {
564                if(event.eventID.length == 0 || (event.type == "static" && options.ajaxForServerStaticEvent) || (event.type !== "static" && options.ajaxForServerEvent)) {
565                    let idKey = event.hasOwnProperty('custom_event_post_id') ? event.custom_event_post_id : event.e_id;
566                    if (!uniqueId.hasOwnProperty(idKey)) {
567                        uniqueId[idKey] = pys_generate_token();
568                    }
569                    return uniqueId[idKey];
570                }
571                else if(event.eventID.length !== 0)
572                {
573                    return event.eventID;
574                }
575            },
576            sendServerAjaxRequest : function(url, data) {
577                jQuery.ajax({
578                    type: 'POST',
579                    url: url,
580                    data: data,
581                    headers: {
582                        'Cache-Control': 'no-cache'
583                    },
584                    success: function () {},
585                });
586            },
587            // clone object
588            clone: function(obj) {
589                var copy;
590
591                // Handle the 3 simple types, and null or undefined
592                if (null == obj || "object" != typeof obj) return obj;
593
594                // Handle Date
595                if (obj instanceof Date) {
596                    copy = new Date();
597                    copy.setTime(obj.getTime());
598                    return copy;
599                }
600
601                // Handle Array
602                if (obj instanceof Array) {
603                    copy = [];
604                    for (var i = 0, len = obj.length; i < len; i++) {
605                        if("function" == typeof obj[i]) {
606                            continue;
607                        }
608                        copy[i] = Utils.clone(obj[i]);
609                    }
610                    return copy;
611                }
612
613                // Handle Object
614                if (obj instanceof Object) {
615                    copy = {};
616                    for (var attr in obj) {
617                        if (obj.hasOwnProperty(attr)) {
618                            if("function" == typeof obj[attr]) {
619                                continue;
620                            }
621                            copy[attr] = Utils.clone(obj[attr]);
622                        }
623                    }
624                    return copy;
625                }
626
627                return obj;
628            },
629
630            // Returns array of elements with given tag name
631            getTagsAsArray: function (tag) {
632                return [].slice.call(document.getElementsByTagName(tag));
633            },
634
635            getRequestParams: function () {
636                return [];
637            },
638
639            /**
640             * CUSTOM EVENTS
641             */
642
643            setupMouseOverClickEvents: function (eventId, triggers) {
644
645                // Non-default binding used to avoid situations when some code in external js
646                // stopping events propagation, eg. returns false, and our handler will never called
647                document.addEventListener('mouseover', function(event) {
648                    var matchedElements = Array.from(document.querySelectorAll(triggers));
649                    var clickedElement = event.target;
650                    var closestMatch = clickedElement.closest(triggers);
651                    if (matchedElements.includes(clickedElement) || closestMatch){
652                        if (event.target.classList.contains('pys-mouse-over-' + eventId)) {
653                            return true;
654                        } else {
655                            event.target.classList.add('pys-mouse-over-' + eventId);
656                        }
657
658                        Utils.fireTriggerEvent(eventId);
659                    }
660                });
661
662            },
663
664            setupCSSClickEvents: function (eventId, triggers) {
665                // Non-default binding used to avoid situations when some code in external js
666                // stopping events propagation, eg. returns false, and our handler will never called
667                document.addEventListener('click', function(event) {
668                    let matchedElements = Array.from(document.querySelectorAll(triggers)),
669                        clickedElement = event.target,
670                        closestMatch = clickedElement.closest(triggers);
671
672                    if (matchedElements.includes(clickedElement) || closestMatch){
673                        Utils.fireTriggerEvent(eventId);
674                    }
675                }, true);
676            },
677
678            setupURLClickEvents: function () {
679
680                if( !options.triggerEventTypes.hasOwnProperty('url_click') ) {
681                    return;
682                }
683                // Non-default binding used to avoid situations when some code in external js
684                // stopping events propagation, eg. returns false, and our handler will never called
685                $('a[data-pys-event-id]').onFirst('click', function (evt) {
686
687                    $(this).attr('data-pys-event-id').split(',').forEach(function (eventId) {
688
689                        eventId = parseInt(eventId);
690
691                        if (isNaN(eventId) === false) {
692                            Utils.fireTriggerEvent(eventId);
693                        }
694
695                    });
696
697                });
698
699
700            },
701
702            setupScrollPosEvents: function (eventId, triggers) {
703
704                var scrollPosThresholds = {},
705                    docHeight = $(document).height() - $(window).height();
706
707                // convert % to absolute positions
708                $.each(triggers, function (index, scrollPos) {
709
710                    // convert % to pixels
711                    scrollPos = docHeight * scrollPos / 100;
712                    scrollPos = Math.round(scrollPos);
713
714                    scrollPosThresholds[scrollPos] = eventId;
715
716                });
717
718                $(document).on("scroll",function () {
719
720                    var scrollPos = $(window).scrollTop();
721
722                    $.each(scrollPosThresholds, function (threshold, eventId) {
723
724                        // position has not reached yes
725                        if (scrollPos <= threshold) {
726                            return true;
727                        }
728
729                        // fire event only once
730                        if (eventId === null) {
731                            return true;
732                        } else {
733                            scrollPosThresholds[threshold] = null;
734                        }
735
736                        Utils.fireTriggerEvent(eventId);
737
738                    });
739
740                });
741
742
743            },
744            setupCommentEvents : function (eventId,triggers) {
745                $('form.comment-form').on("submit",function () {
746                    Utils.fireTriggerEvent(eventId);
747                });
748            },
749
750            /**
751             * Events
752             */
753
754            fireTriggerEvent: function (eventId) {
755
756                if (!options.triggerEvents.hasOwnProperty(eventId)) {
757                    return;
758                }
759
760                var event = {};
761                var events = options.triggerEvents[eventId];
762
763                if (events.hasOwnProperty('facebook')) {
764                    event = events.facebook;
765                    Facebook.fireEvent(event.name, event);
766                }
767
768                if (events.hasOwnProperty('ga')) {
769                    event = events.ga;
770                    Analytics.fireEvent(event.name, event);
771                }
772
773                if (events.hasOwnProperty('pinterest')) {
774                    event = events.pinterest;
775                    Pinterest.fireEvent(event.name, event);
776                }
777
778                if (events.hasOwnProperty('bing')) {
779                    event = events.bing;
780                    Bing.fireEvent(event.name, event);
781                }
782
783                if (events.hasOwnProperty('gtm')) {
784                    event = events.gtm;
785                    GTM.fireEvent(event.name, event);
786                }
787            },
788
789            fireStaticEvents: function (pixel) {
790
791                if (options.staticEvents.hasOwnProperty(pixel)) {
792
793                    $.each(options.staticEvents[pixel], function (eventName, events) {
794                        $.each(events, function (index, eventData) {
795
796                            eventData.fired = eventData.fired || false;
797
798                            if (!eventData.fired) {
799
800                                var fired = false;
801
802                                // fire event
803                                if ('facebook' === pixel) {
804                                    fired = Facebook.fireEvent(eventData.name, eventData);
805                                } else if ('ga' === pixel) {
806                                    fired = Analytics.fireEvent(eventData.name, eventData);
807                                } else if ('pinterest' === pixel) {
808                                    fired = Pinterest.fireEvent(eventData.name, eventData);
809                                } else if ('bing' === pixel) {
810                                    fired = Bing.fireEvent(eventData.name, eventData);
811                                } else if ('gtm' === pixel) {
812                                    fired = GTM.fireEvent(eventData.name, eventData);
813                                }
814
815                                // prevent event double event firing
816                                eventData.fired = fired;
817
818                            }
819
820                        });
821                    });
822
823                }
824
825            },
826
827            /**
828             * Load tag's JS
829             *
830             * @link: https://developers.google.com/analytics/devguides/collection/gtagjs/
831             * @link: https://developers.google.com/analytics/devguides/collection/gtagjs/custom-dims-mets
832             */
833            loadGoogleTag: function (id) {
834
835                if (!gtag_loaded) {
836                    let dataLayerName = this.dataLayerName;
837                    if(options.hasOwnProperty('GATags')){
838                        switch (options.GATags.ga_datalayer_type) {
839                            case 'default':
840                                dataLayerName = 'dataLayerPYS';
841                                break;
842                            case 'custom':
843                                dataLayerName = options.GATags.ga_datalayer_name;
844                                break;
845                            default:
846                                dataLayerName = 'dataLayer';
847                        }
848                    }
849                    this.dataLayerName = dataLayerName;
850                    (function (window, document, src) {
851                        var a = document.createElement('script'),
852                            m = document.getElementsByTagName('script')[0];
853                        a.async = 1;
854                        a.src = src;
855                        m.parentNode.insertBefore(a, m);
856                    })(window, document, '//www.googletagmanager.com/gtag/js?id=' + id+'&l='+this.dataLayerName);
857
858                    window[dataLayerName] = window[dataLayerName] || [];
859                    window.gtag = window.gtag || function gtag() {
860                        window[dataLayerName].push(arguments);
861                    };
862
863                    if ( options.google_consent_mode ) {
864                        let data = {};
865                        data[ 'analytics_storage' ] = options.gdpr.analytics_storage.enabled ? options.gdpr.analytics_storage.value : 'granted';
866                        data[ 'ad_storage' ] = options.gdpr.ad_storage.enabled ? options.gdpr.ad_storage.value : 'granted';
867                        data[ 'ad_user_data' ] = options.gdpr.ad_user_data.enabled ? options.gdpr.ad_user_data.value : 'granted';
868                        data[ 'ad_personalization' ] = options.gdpr.ad_personalization.enabled ? options.gdpr.ad_personalization.value : 'granted';
869
870                        this.loadDefaultConsent( 'consent', 'default', data );
871                    }
872
873                    gtag('js', new Date());
874                    gtag_loaded = true;
875
876                }
877
878            },
879
880            loadDefaultConsent: function() {
881                window[ this.dataLayerName ].push( arguments );
882            },
883
884            loadGTMScript: function (id = '') {
885                const domain = options.gtm.gtm_container_domain ?? 'www.googletagmanager.com';
886                const loader = options.gtm.gtm_container_identifier ?? 'gtm';
887                const gtm_auth = options.gtm.gtm_auth ?? ''; // Set this if needed
888                const gtm_preview = options.gtm.gtm_preview ?? ''; // Set this if needed
889                const datalayer_name = options.gtm.gtm_dataLayer_name ?? 'dataLayer';
890
891                window[ datalayer_name ] = window[ datalayer_name ] || [];
892                window.gtag = window.gtag || function gtag() {
893                    window[ datalayer_name ].push( arguments );
894                };
895
896                if ( options.google_consent_mode ) {
897                    let data = {};
898                    data[ 'analytics_storage' ] = options.gdpr.analytics_storage.enabled ? options.gdpr.analytics_storage.value : 'granted';
899                    data[ 'ad_storage' ] = options.gdpr.ad_storage.enabled ? options.gdpr.ad_storage.value : 'granted';
900                    data[ 'ad_user_data' ] = options.gdpr.ad_user_data.enabled ? options.gdpr.ad_user_data.value : 'granted';
901                    data[ 'ad_personalization' ] = options.gdpr.ad_personalization.enabled ? options.gdpr.ad_personalization.value : 'granted';
902
903                    this.GTMdataLayerName = datalayer_name;
904                    this.loadDefaultGTMConsent( 'consent', 'default', data );
905                }
906
907                (function(w, d, s, l, i) {
908                    w[l] = w[l] || [];
909                    w[l].push({ 'gtm.start': new Date().getTime(), event: 'gtm.js' });
910                    const f = d.getElementsByTagName(s)[0];
911                    const j = d.createElement(s);
912                    const dl = l !== 'dataLayer' ? '&l=' + l : '';
913                    j.async = true;
914                    j.src = 'https://' + domain + '/' + loader + '.js?id=' + i + dl;
915                    if (gtm_auth && gtm_preview) {
916                        j.src += '&gtm_auth=' + gtm_auth + '&gtm_preview=' + gtm_preview + '&gtm_cookies_win=x';
917                    }
918                    f.parentNode.insertBefore(j, f);
919                })(window, document, 'script', datalayer_name, id);
920
921            },
922
923            loadDefaultGTMConsent: function() {
924                window[ this.GTMdataLayerName ].push( arguments );
925            },
926
927            /**
928             * GDPR
929             */
930
931            loadPixels: function () {
932
933                if (options.gdpr.ajax_enabled && !options.gdpr.consent_magic_integration_enabled) {
934
935                    // retrieves actual PYS GDPR filters values which allow to avoid cache issues
936                    $.get({
937                        url: options.ajaxUrl,
938                        dataType: 'json',
939                        data: {
940                            action: 'pys_get_gdpr_filters_values'
941                        },
942                        success: function (res) {
943
944                            if (res.success) {
945
946                                options.gdpr.all_disabled_by_api = res.data.all_disabled_by_api;
947                                options.gdpr.facebook_disabled_by_api = res.data.facebook_disabled_by_api;
948                                options.gdpr.analytics_disabled_by_api = res.data.analytics_disabled_by_api;
949                                options.gdpr.google_ads_disabled_by_api = res.data.google_ads_disabled_by_api;
950                                options.gdpr.pinterest_disabled_by_api = res.data.pinterest_disabled_by_api;
951                                options.gdpr.bing_disabled_by_api = res.data.bing_disabled_by_api;
952
953                                options.cookie.externalID_disabled_by_api = res.data.externalID_disabled_by_api;
954                                options.cookie.disabled_all_cookie = res.data.disabled_all_cookie;
955                                options.cookie.disabled_advanced_form_data_cookie = res.data.disabled_advanced_form_data_cookie;
956                                options.cookie.disabled_landing_page_cookie = res.data.disabled_landing_page_cookie;
957                                options.cookie.disabled_first_visit_cookie = res.data.disabled_first_visit_cookie;
958                                options.cookie.disabled_trafficsource_cookie = res.data.disabled_trafficsource_cookie;
959                                options.cookie.disabled_utmTerms_cookie = res.data.disabled_utmTerms_cookie;
960                                options.cookie.disabled_utmId_cookie = res.data.disabled_utmId_cookie;
961                            }
962
963                            loadPixels();
964
965                        }
966                    });
967
968                } else {
969                    loadPixels();
970                }
971
972            },
973
974            consentGiven: function (pixel) {
975
976                /**
977                 * ConsentMagic
978                 */
979                if ( options.gdpr.consent_magic_integration_enabled && typeof CS_Data !== "undefined" ) {
980
981                    let test_prefix = CS_Data.test_prefix;
982                    if (
983                        ( ( typeof CS_Data.cs_google_consent_mode_enabled !== "undefined" && CS_Data.cs_google_consent_mode_enabled == 1 ) && ( pixel == 'analytics' || pixel == 'google_ads' ) )
984                        || ( typeof CS_Data.cs_meta_ldu_mode !== "undefined" && CS_Data.cs_meta_ldu_mode && pixel == 'facebook' )
985                        || ( typeof CS_Data.cs_bing_consent_mode !== "undefined" && CS_Data.cs_bing_consent_mode.ad_storage.enabled && pixel == 'bing' )
986                    ) {
987                        if ( CS_Data.cs_cache_enabled == 0 || ( CS_Data.cs_cache_enabled == 1 && window.CS_Cache && window.CS_Cache.check_status ) ) {
988                            return true;
989                        } else {
990                            return false;
991                        }
992                    }
993
994                    if( pixel == 'facebook' && ( CS_Data.cs_script_cat.facebook == 0 || CS_Data.cs_script_cat.facebook == CS_Data.cs_necessary_cat_id ) ) {
995                        return true;
996                    } else if( pixel == 'bing' && ( CS_Data.cs_script_cat.bing == 0 || CS_Data.cs_script_cat.bing == CS_Data.cs_necessary_cat_id ) ) {
997                        return true;
998                    } else if( pixel == 'analytics' && ( CS_Data.cs_script_cat.analytics == 0 || CS_Data.cs_script_cat.analytics == CS_Data.cs_necessary_cat_id ) ) {
999                        return true;
1000                    } else if( pixel == 'google_ads' && ( CS_Data.cs_script_cat.gads == 0 || CS_Data.cs_script_cat.gads == CS_Data.cs_necessary_cat_id ) ) {
1001                        return true;
1002                    } else if( pixel == 'pinterest' && ( CS_Data.cs_script_cat.pinterest == 0 || CS_Data.cs_script_cat.pinterest == CS_Data.cs_necessary_cat_id ) ) {
1003                        return true;
1004                    } else if( pixel == 'tiktok' && ( CS_Data.cs_script_cat.tiktok == 0 || CS_Data.cs_script_cat.tiktok == CS_Data.cs_necessary_cat_id ) ) {
1005                        return true;
1006                    }
1007
1008                    let substring = "cs_enabled_cookie_term",
1009                        theCookies = document.cookie.split( ';' );
1010
1011                    for ( let i = 1; i <= theCookies.length; i++ ) {
1012                        if ( theCookies[ i - 1 ].indexOf( substring ) !== -1 ) {
1013                            let categoryCookie = theCookies[ i - 1 ].replace( 'cs_enabled_cookie_term' + test_prefix + '_', '' );
1014                            categoryCookie = Number( categoryCookie.replace( /\D+/g, "" ) );
1015                            let cs_cookie_val = Cookies.get( 'cs_enabled_cookie_term' + test_prefix + '_' + categoryCookie );
1016
1017                            if ( categoryCookie === CS_Data.cs_script_cat.facebook && pixel == 'facebook' ) {
1018                                return cs_cookie_val == 'yes';
1019                            } else if ( categoryCookie === CS_Data.cs_script_cat.bing && pixel == 'bing' ) {
1020                                return cs_cookie_val == 'yes';
1021                            } else if ( categoryCookie === CS_Data.cs_script_cat.analytics && pixel == 'analytics' ) {
1022                                return cs_cookie_val == 'yes';
1023                            } else if ( categoryCookie === CS_Data.cs_script_cat.gads && pixel == 'google_ads' ) {
1024                                return cs_cookie_val == 'yes';
1025                            } else if ( categoryCookie === CS_Data.cs_script_cat.pinterest && pixel == 'pinterest' ) {
1026                                return cs_cookie_val == 'yes';
1027                            } else if ( categoryCookie === CS_Data.cs_script_cat.tiktok && pixel == 'tiktok' ) {
1028                                return cs_cookie_val == 'yes';
1029                            }
1030                        }
1031                    }
1032
1033                    return false;
1034                }
1035
1036                /**
1037                 * Real Cookie Banner
1038                 */
1039                if(options.gdpr.real_cookie_banner_integration_enabled) {
1040                    var consentApi = window.consentApi;
1041                    if (consentApi) {
1042                        switch (pixel) {
1043                            case "analytics":
1044                                return consentApi.consentSync("http", "_ga", "*").cookieOptIn;
1045                            case "facebook":
1046                                return consentApi.consentSync("http", "_fbp", "*").cookieOptIn;
1047                            case "pinterest":
1048                                return consentApi.consentSync("http", "_pinterest_sess", ".pinterest.com").cookieOptIn;
1049                            default:
1050                                return true;
1051                        }
1052                    }
1053                }
1054
1055                /**
1056                 * Cookiebot
1057                 */
1058                if (options.gdpr.cookiebot_integration_enabled && typeof Cookiebot !== 'undefined') {
1059
1060                    var cookiebot_consent_category = options.gdpr['cookiebot_' + pixel + '_consent_category'];
1061
1062                    if (options.gdpr[pixel + '_prior_consent_enabled']) {
1063                        if (Cookiebot.consented === true || Cookiebot.consent[cookiebot_consent_category]) {
1064                            return true;
1065                        }
1066                    } else {
1067                        if (Cookiebot.consent[cookiebot_consent_category]) {
1068                            return true;
1069                        }
1070                    }
1071
1072                    return false;
1073
1074                }
1075
1076                /**
1077                 * Cookie Notice
1078                 */
1079                if (options.gdpr.cookie_notice_integration_enabled && typeof cnArgs !== 'undefined') {
1080
1081                    var cn_cookie = Cookies.get(cnArgs.cookieName);
1082
1083                    if (options.gdpr[pixel + '_prior_consent_enabled']) {
1084                        if (typeof cn_cookie === 'undefined' || cn_cookie === 'true') {
1085                            return true;
1086                        }
1087                    } else {
1088                        if (cn_cookie === 'true') {
1089                            return true;
1090                        }
1091                    }
1092
1093                    return false;
1094
1095                }
1096
1097                /**
1098                 * Cookie Law Info
1099                 */
1100                if (options.gdpr.cookie_law_info_integration_enabled) {
1101                    var cli_cookie = Cookies.get('cookieyes-consent') ?? Cookies.get('wt_consent') ?? Cookies.get('viewed_cookie_policy');
1102                    if (options.gdpr[pixel + '_prior_consent_enabled']) {
1103                        if (typeof cli_cookie === 'undefined') return true;
1104                        if (
1105                            cli_cookie &&
1106                            (cli_cookie === Cookies.get('cookieyes-consent') || cli_cookie === Cookies.get('wt_consent'))
1107                        ) {
1108                            if (getCookieYes('analytics') === 'yes') {
1109                                return true;
1110                            }
1111                        } else if (cli_cookie && cli_cookie === Cookies.get('viewed_cookie_policy')) {
1112                            if (Cookies.get('viewed_cookie_policy') === 'yes') {
1113                                return true;
1114                            }
1115                        }
1116                    } else {
1117                        if (
1118                            cli_cookie &&
1119                            (cli_cookie === Cookies.get('cookieyes-consent') || cli_cookie === Cookies.get('wt_consent'))
1120                        ) {
1121                            if (getCookieYes('analytics') === 'yes') {
1122                                return true;
1123                            }
1124                        } else if (cli_cookie && cli_cookie === Cookies.get('viewed_cookie_policy')) {
1125                            if (Cookies.get('viewed_cookie_policy') === 'yes') {
1126                                return true;
1127                            }
1128                        }
1129                    }
1130                    return false;
1131                }
1132
1133                return true;
1134
1135            },
1136
1137            setupGdprCallbacks: function () {
1138                /**
1139                 * ConsentMagic
1140                 */
1141                if (options.gdpr.consent_magic_integration_enabled && typeof CS_Data !== "undefined") {
1142                    let test_prefix = CS_Data.test_prefix,
1143                        cs_refresh_after_consent = false,
1144                        substring = "cs_enabled_cookie_term";
1145
1146                    if (CS_Data.cs_refresh_after_consent == 1) {
1147                        cs_refresh_after_consent = CS_Data.cs_refresh_after_consent;
1148                    }
1149
1150                    let consent_actions = function () {
1151                        let theCookies = document.cookie.split( ';' );
1152
1153                        let consent = {
1154                            facebook: true,
1155                            ga: true,
1156                            google_ads: true,
1157                            tiktok: true,
1158                            bing: true,
1159                            pinterest: true,
1160                            gtm: true,
1161                        };
1162
1163                        for (let i = 1 ; i <= theCookies.length; i++) {
1164                            if (theCookies[i-1].indexOf(substring) !== -1) {
1165                                let categoryCookie = theCookies[i-1].replace('cs_enabled_cookie_term'+test_prefix+'_','');
1166                                categoryCookie = Number(categoryCookie.replace(/\D+/g,""));
1167                                let cs_cookie_val = Cookies.get('cs_enabled_cookie_term'+test_prefix+'_'+categoryCookie);
1168                                if(cs_cookie_val == 'yes') {
1169                                    if ( ( categoryCookie === CS_Data.cs_script_cat.facebook ) || ( typeof CS_Data.cs_meta_ldu_mode !== "undefined" && CS_Data.cs_meta_ldu_mode ) ) {
1170                                        Facebook.loadPixel();
1171                                    }
1172
1173                                    if ( categoryCookie === CS_Data.cs_script_cat.bing || ( typeof CS_Data.cs_bing_consent_mode !== "undefined" && CS_Data.cs_bing_consent_mode.ad_storage.enabled ) ) {
1174                                        Bing.loadPixel();
1175                                    }
1176
1177                                    if (categoryCookie === CS_Data.cs_script_cat.analytics || (typeof CS_Data.cs_google_analytics_consent_mode !== "undefined" && CS_Data.cs_google_analytics_consent_mode == 1)
1177) {
1178
1179                                        Analytics.loadPixel();
1180                                    }
1181
1182                                    if (categoryCookie === CS_Data.cs_script_cat.pinterest) {
1183                                        Pinterest.loadPixel();
1184                                    }
1185                                } else {
1186                                    if ( ( categoryCookie === CS_Data.cs_script_cat.facebook ) && ( typeof CS_Data.cs_meta_ldu_mode == "undefined" || !CS_Data.cs_meta_ldu_mode ) ) {
1187                                        Facebook.disable();
1188                                        consent.facebook = false;
1189                                    }
1190
1191                                    if ( categoryCookie === CS_Data.cs_script_cat.bing && ( typeof CS_Data.cs_bing_consent_mode == "undefined" || !CS_Data.cs_bing_consent_mode.ad_storage.enabled ) ) {
1192                                        Bing.disable();
1193                                        consent.bing = false;
1194                                    }
1195                                    if (categoryCookie === CS_Data.cs_script_cat.analytics && (typeof CS_Data.cs_google_analytics_consent_mode == "undefined" || CS_Data.cs_google_analytics_consent_mode == 0)) {
1196                                        Analytics.disable();
1197                                        consent.ga = false;
1198                                        consent.gtm = false;
1199                                    }
1200
1201                                    if (categoryCookie === CS_Data.cs_script_cat.pinterest) {
1202                                        Pinterest.disable();
1203                                        consent.pinterest = false;
1204                                    }
1205                                }
1206                                if (Cookies.get('cs_enabled_advanced_matching') == 'yes') {
1207                                    Facebook.loadPixel();
1208                                }
1209                            }
1210                        }
1211                        Utils.setupGDPRData( consent );
1212                    }
1213
1214                    if (!cs_refresh_after_consent) {
1215                        consent_actions();
1216
1217                        $(document).on('click','.cs_action_btn',function(e) {
1218                            e.preventDefault();
1219
1220                            let consent = {
1221                                facebook: true,
1222                                ga: true,
1223                                bing: true,
1224                                pinterest: true,
1225                                gtm: true,
1226                            };
1227
1228                            let elm = $(this),
1229                                button_action = elm.attr('data-cs_action');
1230
1231                            if(button_action === 'allow_all') {
1232                                Facebook.loadPixel();
1233                                Bing.loadPixel();
1234                                Analytics.loadPixel();
1235                                Pinterest.loadPixel();
1236
1237                                consent.facebook = true;
1238                                consent.bing = true;
1239                                consent.ga = true;
1240                                consent.pinterest = true;
1241                                consent.gtm = true;
1242
1243                                Utils.setupGDPRData( consent );
1244                            } else if ( button_action === 'disable_all' ) {
1245                                if ( typeof CS_Data.cs_meta_ldu_mode == "undefined" || CS_Data.cs_meta_ldu_mode == 0 ) {
1246                                    Facebook.disable();
1247                                    consent.facebook = false;
1248                                }
1249
1250                                if ( typeof CS_Data.cs_bing_consent_mode == "undefined" || CS_Data.cs_bing_consent_mode.ad_storage.enabled == 0 ) {
1251                                    Bing.disable();
1252                                    consent.bing = false;
1253                                }
1254
1255                                if ( CS_Data.cs_google_analytics_consent_mode == 0 || typeof CS_Data.cs_google_analytics_consent_mode == "undefined" ) {
1256                                    Analytics.disable();
1257                                    consent.ga = false;
1258                                    consent.gtm = false;
1259                                }
1260
1261                                Pinterest.disable();
1262                                consent.pinterest = false;
1263                                Utils.setupGDPRData( consent );
1264                            } else if ( button_action === 'cs_confirm' ) {
1265                                consent_actions();
1266                            }
1267                        });
1268                    }
1269                }
1270                /**
1271                 * Real Cookie Banner
1272                 */
1273                if(options.gdpr.real_cookie_banner_integration_enabled) {
1274                    let consentApi = window.consentApi;
1275                    if (consentApi) {
1276                        consentApi.consent("http", "_ga", "*")
1277                            .then(Analytics.loadPixel.bind(Analytics), Analytics.disable.bind(Analytics));
1278                        consentApi.consent("http", "_fbp", "*")
1279                            .then(Facebook.loadPixel.bind(Facebook), Facebook.disable.bind(Facebook));
1280                        consentApi.consent("http", "_pinterest_sess", ".pinterest.com")
1281                            .then(Pinterest.loadPixel.bind(Pinterest), Pinterest.disable.bind(Pinterest));
1282                        consentApi.consent("http", "_uetsid", "*")
1283                            .then(Bing.loadPixel.bind(Bing), Bing.disable.bind(Bing));
1284
1285                        let consent = {
1286                            facebook: true,
1287                            ga: true,
1288                            bing: true,
1289                            pinterest: true,
1290                            gtm: true,
1291                        };
1292
1293                        if (!consentApi.consentSync("http", "_ga", "*").cookieOptIn) {
1294                            consent.ga = false;
1295                            consent.gtm = false;
1296                        }
1297                        if (!consentApi.consentSync("http", "_fbp", "*").cookieOptIn) {
1298                            consent.facebook = false;
1299                        }
1300                        if (!consentApi.consentSync("http", "_pinterest_sess", ".pinterest.com").cookieOptIn) {
1301                            consent.pinterest = false;
1302                        }
1303                        if (!consentApi.consentSync("http", "_uetsid", "*").cookieOptIn) {
1304                            consent.bing = false;
1305                        }
1306                        Utils.setupGDPRData( consent );
1307                    }
1308                }
1309                /**
1310                 * Cookiebot
1311                 */
1312                if (options.gdpr.cookiebot_integration_enabled && typeof Cookiebot !== 'undefined') {
1313
1314                    window.addEventListener("CookiebotOnConsentReady", function() {
1315
1316                        let consent = {
1317                            facebook: true,
1318                            ga: true,
1319                            bing: true,
1320                            pinterest: true,
1321                            gtm: true,
1322                        };
1323
1324                        Utils.manageCookies();
1325                        if (Cookiebot.consent.marketing) {
1326                            Facebook.loadPixel();
1327                            Bing.loadPixel();
1328                            Pinterest.loadPixel();
1329
1330                            consent.facebook = true;
1331                            consent.bing = true;
1332                            consent.pinterest = true;
1333                        }
1334                        if (Cookiebot.consent.statistics) {
1335                            Analytics.loadPixel();
1336
1337                            consent.ga = true;
1338                            consent.gtm = true;
1339                        }
1340                        if (!Cookiebot.consent.marketing) {
1341                            Facebook.disable();
1342                            Pinterest.disable();
1343                            Bing.disable();
1344
1345                            consent.facebook = false;
1346                            consent.bing = false;
1347                            consent.pinterest = false;
1348                        }
1349                        if (!Cookiebot.consent.statistics) {
1350                            Analytics.disable();
1351
1352                            consent.ga = false;
1353                            consent.gtm = false;
1354                        }
1355
1356                        Utils.setupGDPRData( consent );
1357                    });
1358
1359                }
1360
1361                /**
1362                 * Cookie Notice
1363                 */
1364                if (options.gdpr.cookie_notice_integration_enabled) {
1365
1366                    $(document).onFirst('click', '.cn-set-cookie', function () {
1367
1368                        let consent = {};
1369
1370                        if ($(this).data('cookie-set') === 'accept') {
1371                            Facebook.loadPixel();
1372                            Analytics.loadPixel();
1373                            Pinterest.loadPixel();
1374                            Bing.loadPixel();
1375
1376                            consent = {
1377                                facebook: true,
1378                                ga: true,
1379                                bing: true,
1380                                pinterest: true,
1381                                gtm: true,
1382                            };
1383                        } else {
1384                            Facebook.disable();
1385                            Analytics.disable();
1386                            Pinterest.disable();
1387                            Bing.disable();
1388
1389                            consent = {
1390                                facebook: false,
1391                                ga: false,
1392                                bing: false,
1393                                pinterest: false,
1394                                gtm: false,
1395                            };
1396                        }
1397
1398                        Utils.setupGDPRData( consent );
1399                    });
1400
1401                    $(document).onFirst('click', '.cn-revoke-cookie', function () {
1402                        Facebook.disable();
1403                        Analytics.disable();
1404                        Pinterest.disable();
1405                        Bing.disable();
1406
1407                        let consent = {
1408                            facebook: false,
1409                            ga: false,
1410                            bing: false,
1411                            pinterest: false,
1412                            gtm: false,
1413                        };
1414                        Utils.setupGDPRData( consent );
1415
1416                    });
1417
1418                }
1419
1420                /**
1421                 * Cookie Law Info
1422                 */
1423                if (options.gdpr.cookie_law_info_integration_enabled) {
1424
1425                    $(document).onFirst('click', '#wt-cli-accept-all-btn,#cookie_action_close_header, .cky-btn-accept', function () {
1426                        setTimeout(function (){
1427                            let cli_cookie = Cookies.get('cookieyes-consent') ?? Cookies.get('wt_consent') ?? Cookies.get('viewed_cookie_policy');
1428                            if (typeof cli_cookie !== 'undefined') {
1429                                if (cli_cookie === Cookies.get('cookieyes-consent') || cli_cookie === Cookies.get('wt_consent')) {
1430                                    if (getCookieYes('analytics') === 'yes') {
1431                                        Utils.manageCookies();
1432                                    }
1433                                } else if (cli_cookie === Cookies.get('viewed_cookie_policy') && cli_cookie == 'yes') {
1434                                    Utils.manageCookies();
1435                                }
1436                            }
1437                        },1000)
1438                        Facebook.loadPixel();
1439                        Analytics.loadPixel();
1440                        Pinterest.loadPixel();
1441                        Bing.loadPixel();
1442
1443                        let consent = {
1444                            facebook: true,
1445                            ga: true,
1446                            bing: true,
1447                            pinterest: true,
1448                            gtm: true,
1449                        };
1450                        Utils.setupGDPRData( consent );
1451                    });
1452
1453                    $(document).onFirst('click', '#cookie_action_close_header_reject, .cky-btn-reject', function () {
1454                        Facebook.disable();
1455                        Analytics.disable();
1456                        Pinterest.disable();
1457                        Bing.disable();
1458
1459                        let consent = {
1460                            facebook: false,
1461                            ga: false,
1462                            bing: false,
1463                            pinterest: false,
1464                            gtm: false,
1465                        };
1466                        Utils.setupGDPRData( consent );
1467                    });
1468
1469                }
1470
1471            },
1472
1473            setupGDPRData: function ( consent ) {
1474                consent = window.btoa( JSON.stringify( consent ) );
1475                Cookies.set( 'pys_consent', consent, { expires: 365, path: '/', domain: domain } );
1476            },
1477
1478            /**
1479             * DOWNLOAD DOCS
1480             */
1481
1482            getLinkExtension: function (link) {
1483
1484                // Remove anchor, query string and everything before last slash
1485                link = link.substring(0, (link.indexOf("#") === -1) ? link.length : link.indexOf("#"));
1486                link = link.substring(0, (link.indexOf("?") === -1) ? link.length : link.indexOf("?"));
1487                link = link.substring(link.lastIndexOf("/") + 1, link.length);
1488
1489                // If there's a period left in the URL, then there's a extension
1490                if (link.length > 0 && link.indexOf('.') !== -1) {
1491                    link = link.substring(link.indexOf(".") + 1); // Remove everything but what's after the first period
1492                    return link;
1493                } else {
1494                    return "";
1495                }
1496            },
1497
1498            getLinkFilename: function (link) {
1499
1500                // Remove anchor, query string and everything before last slash
1501                link = link.substring(0, (link.indexOf("#") === -1) ? link.length : link.indexOf("#"));
1502                link = link.substring(0, (link.indexOf("?") === -1) ? link.length : link.indexOf("?"));
1503                link = link.substring(link.lastIndexOf("/") + 1, link.length);
1504
1505                // If there's a period left in the URL, then there's a extension
1506                if (link.length > 0 && link.indexOf('.') !== -1) {
1507                    return link;
1508                } else {
1509                    return "";
1510                }
1511            },
1512            /**
1513             * Enrich
1514             */
1515            isCheckoutPage: function () {
1516                return $('body').hasClass('woocommerce-checkout') || document.querySelector('.woocommerce-checkout') ||
1517                    $('body').hasClass('edd-checkout');
1518            },
1519            addCheckoutFields : function() {
1520                var utm = "";
1521                var utms = getUTMs()
1522
1523                $.each(utmTerms, function (index, name) {
1524                    if(index > 0) {
1525                        utm+="|";
1526                    }
1527                    utm+=name+":"+utms[name];
1528                });
1529                var utmIdList = "";
1530                var utmsIds = getUTMId()
1531                $.each(utmId, function (index, name) {
1532                    if(index > 0) {
1533                        utmIdList+="|";
1534                    }
1535                    utmIdList+=name+":"+utmsIds[name];
1536                });
1537                var utmIdListLast = "";
1538                var utmsIdsLast = getUTMId(true)
1539                $.each(utmId, function (index, name) {
1540                    if(index > 0) {
1541                        utmIdListLast+="|";
1542                    }
1543                    utmIdListLast+=name+":"+utmsIdsLast[name];
1544                });
1545
1546
1547                var utmLast = "";
1548                var utmsLast = getUTMs(true)
1549                $.each(utmTerms, function (index, name) {
1550                    if(index > 0) {
1551                        utmLast+="|";
1552                    }
1553                    utmLast+=name+":"+utmsLast[name];
1554                });
1555
1556                var dateTime = getDateTime();
1557                var landing = getLandingPageValue();
1558                var lastLanding = getLandingPageValue();
1559                var trafic = getTrafficSourceValue();
1560                var lastTrafic = getTrafficSourceValue();
1561
1562                var $form = null;
1563                if($('body').hasClass('woocommerce-checkout')) {
1564                    $form = $("form.woocommerce-checkout");
1565                } else {
1566                    $form = $("#edd_purchase_form");
1567                }
1568                var inputs = {'pys_utm':utm,
1569                    'pys_utm_id':utmIdList,
1570                    'pys_browser_time':dateTime.join("|"),
1571                    'pys_landing':landing,
1572                    'pys_source':trafic,
1573                    'pys_order_type': $(".wcf-optin-form").length > 0 ? "wcf-optin" : "normal",
1574
1575                    'last_pys_landing':lastLanding,
1576                    'last_pys_source':lastTrafic,
1577                    'last_pys_utm':utmLast,
1578                    'last_pys_utm_id':utmIdListLast,
1579                }
1580
1581                Object.keys(inputs).forEach(function(key,index) {
1582                    $form.append("<input type='hidden' name='"+key+"' value='"+inputs[key]+"' /> ");
1583                });
1584
1585
1586            },
1587            getAdvancedFormData: function () {
1588                let dataStr = Cookies.get("pys_advanced_form_data");
1589                if(dataStr === undefined) {
1590                    return {'first_name':"",'last_name':"",'email':"",'phone':""};
1591                } else {
1592                    return JSON.parse(dataStr);
1593                }
1594            }
1595        };
1596
1597    }(options);
1598
1599    var Facebook = function (options) {
1600
1601
1602        var defaultEventTypes = [
1603            'PageView',
1604            'ViewContent',
1605            'Search',
1606            'AddToCart',
1607            'AddToWishlist',
1608            'InitiateCheckout',
1609            'AddPaymentInfo',
1610            'Purchase',
1611            'Lead',
1612
1613            'Subscribe',
1614            'CustomizeProduct',
1615            'FindLocation',
1616            'StartTrial',
1617            'SubmitApplication',
1618            'Schedule',
1619            'Contact',
1620            'Donate'
1621        ];
1622
1623        var initialized = false;
1624        var genereateFbp = function (){
1625            return !Cookies.get('_fbp') ? 'fb.1.'+Date.now()+'.'+Math.floor(1000000000 + Math.random() * 9000000000) : Cookies.get('_fbp');
1626        };
1627        var genereateFbc = function (){
1628            return getUrlParameter('fbclid') ? 'fb.1.'+Date.now()+'.'+getUrlParameter('fbclid') : ''
1629        };
1630        // fire server side event gdpr plugin installed
1631        var isApiDisabled = options.gdpr.all_disabled_by_api ||
1632            options.gdpr.facebook_disabled_by_api ||
1633            options.gdpr.cookiebot_integration_enabled ||
1634            options.gdpr.consent_magic_integration_enabled ||
1635            options.gdpr.cookie_notice_integration_enabled ||
1636            options.gdpr.cookie_law_info_integration_enabled;
1637
1638        /**
1639         *
1640         * @param allData
1641         * @param params
1642         * @returns {string | null}
1643         */
1644        function sendFbServerEvent(allData,name,params) {
1645            let eventId = null;
1646            if(options.facebook.serverApiEnabled) {
1647
1648                if(allData.e_id === "woo_remove_from_cart") {// server event will sended from hook
1649                    Facebook.updateEventId(allData.name);
1650                    allData.eventID = Facebook.getEventId(allData.name);
1651                } else {
1652                    // send event from server if they was bloc by gdpr or need send with delay
1653                    allData.eventID = Utils.generateUniqueId(allData);
1654
1655                    if(Cookies.get('_fbp')){
1656                        params._fbp = Cookies.get('_fbp');
1657                    }
1658                    if(Cookies.get('_fbc')){
1659                        params._fbc = Cookies.get('_fbc');
1660                    }
1661
1662                    if( options.ajaxForServerEvent || isApiDisabled ){
1663                        var json = {
1664                            action: 'pys_api_event',
1665                            pixel: 'facebook',
1666                            event: name,
1667                            data:params,
1668                            ids:options.facebook.pixelIds,
1669                            eventID:allData.eventID,
1670                            url:window.location.href,
1671                            ajax_event:options.ajax_event
1672                        };
1673                        if(allData.hasOwnProperty('woo_order')) {
1674                            json['woo_order'] = allData.woo_order;
1675                        }
1676                        if(allData.hasOwnProperty('edd_order')) {
1677                            json['edd_order'] = allData.edd_order;
1678                        }
1679
1680                        if (allData.e_id === "automatic_event_internal_link" || allData.e_id === "automatic_event_outbound_link") {
1681                            setTimeout(() => Utils.sendServerAjaxRequest(options.ajaxUrl, json), 500);
1682                        } else if (allData.type != 'static') {
1683                            Utils.sendServerAjaxRequest(options.ajaxUrl, json);
1684                        }
1685
1686                        if ( ( allData.type == 'static' && options.ajaxForServerStaticEvent ) || ( allData.hasOwnProperty( 'ajaxFire' ) && allData.ajaxFire ) ) {
1687                            Utils.sendServerAjaxRequest( options.ajaxUrl, json );
1688                        }
1689                    }
1690                }
1691                delete params._fbp;
1692                delete params._fbc;
1693                eventId = allData.eventID
1694            }
1695            return eventId;
1696        }
1697
1698        function fireEvent(name, allData) {
1699
1700            if(typeof window.pys_event_data_filter === "function" && window.pys_disable_event_filter(name,'facebook')) {
1701                return;
1702            }
1703
1704            var actionType = defaultEventTypes.includes(name) ? 'track' : 'trackCustom';
1705            var data = allData.params;
1706            var params = {};
1707            var arg = {};
1708            Utils.copyProperties(data, params);
1709            let eventId = sendFbServerEvent(allData,name,params)
1710
1711
1712            if("hCR" === name) {
1713                return;
1714            }
1715
1716            if (options.debug) {
1717                console.log('[Facebook] ' + name, params,"eventID",eventId);
1718            }
1719
1720            if(eventId != null) {
1721                arg.eventID = eventId;
1722            }
1723
1724            fbq(actionType, name, params, arg);
1725
1726        }
1727
1728        /**
1729         * Public API
1730         */
1731        return {
1732            tag: function() {
1733                return "facebook";
1734            },
1735            isEnabled: function () {
1736                return options.hasOwnProperty('facebook');
1737            },
1738
1739            disable: function () {
1740                initialized = false;
1741            },
1742            advancedMatching: function () {
1743                if(options.facebook.advancedMatchingEnabled) {
1744                    let advancedMatchingForm = Utils.getAdvancedFormData();
1745                    let advancedMatching = {};
1746                    if(Object.keys(options.facebook.advancedMatching).length > 0) {
1747                        advancedMatching = options.facebook.advancedMatching;
1748                    }
1749
1750                    if(!advancedMatching.hasOwnProperty("em")
1751                        && advancedMatchingForm.hasOwnProperty("email") && advancedMatchingForm["email"].length > 0) {
1752                        advancedMatching["em"] = advancedMatchingForm["email"];
1753                    }
1754                    if(!advancedMatching.hasOwnProperty("ph")
1755                        && advancedMatchingForm.hasOwnProperty("phone") && advancedMatchingForm["phone"].length > 0) {
1756                        advancedMatching["ph"] = advancedMatchingForm["phone"];
1757                    }
1758                    if(!advancedMatching.hasOwnProperty("fn")
1759                        && advancedMatchingForm.hasOwnProperty("first_name") && advancedMatchingForm["first_name"].length > 0) {
1760                        advancedMatching["fn"] = advancedMatchingForm["first_name"];
1761                    }
1762                    if(!advancedMatching.hasOwnProperty("ln")
1763                        && advancedMatchingForm.hasOwnProperty("last_name") && advancedMatchingForm["last_name"].length > 0) {
1764                        advancedMatching["ln"] = advancedMatchingForm["last_name"];
1765                    }
1766                    if(!advancedMatching.hasOwnProperty("external_id")){
1767                        if (Cookies.get('pbid') || (options.hasOwnProperty('pbid') && options.pbid)) {
1768                            advancedMatching["external_id"] = Cookies.get('pbid') ? Cookies.get('pbid') : options.pbid;
1769                        }
1770                    }
1771                    else if(advancedMatching.external_id != Cookies.get('pbid'))
1772                    {
1773                        advancedMatching["external_id"] = Cookies.get('pbid') ? Cookies.get('pbid') : advancedMatching.external_id;
1774                    }
1775                    if(Object.keys(advancedMatching).length > 0) {
1776                        return advancedMatching;
1777                    }
1778                }
1779                return false
1780            },
1781            /**
1782             * Load pixel's JS
1783             */
1784            loadPixel: function () {
1785
1786                if (initialized || !this.isEnabled() || !Utils.consentGiven('facebook')) {
1787                    return;
1788                }
1789
1790                !function (f, b, e, v, n, t, s) {
1791                    if (f.fbq) return;
1792                    n = f.fbq = function () {
1793                        n.callMethod ?
1794                            n.callMethod.apply(n, arguments) : n.queue.push(arguments)
1795                    };
1796                    if (!f._fbq) f._fbq = n;
1797                    n.push = n;
1798                    n.loaded = !0;
1799                    n.version = '2.0';
1800                    n.agent = 'dvpixelyoursite';
1801                    n.queue = [];
1802                    t = b.createElement(e);
1803                    t.async = !0;
1804                    t.src = v;
1805                    s = b.getElementsByTagName(e)[0];
1806                    s.parentNode.insertBefore(t, s)
1807                }(window,
1808                    document, 'script', 'https://connect.facebook.net/en_US/fbevents.js');
1809
1810                let expires = parseInt(options.cookie_duration);
1811                if(!Cookies.get('_fbp')) {
1812                    Cookies.set('_fbp',genereateFbp(),  { expires: expires,path: '/',domain: domain });
1813                }
1814
1815                if(getUrlParameter('fbclid')) {
1816                    Cookies.set('_fbc',genereateFbc(),  { expires: expires,path: '/',domain: domain });
1817                }
1818                // initialize pixel
1819                options.facebook.pixelIds.forEach(function (pixelId) {
1820                    if (options.facebook.removeMetadata) {
1821                        fbq('set', 'autoConfig', false, pixelId);
1822                    }
1823                    let advancedMatching = Facebook.advancedMatching();
1824
1825                    if ( +options.facebook.meta_ldu === 1  ) {
1826                        fbq( 'dataProcessingOptions', [ 'LDU' ], 0, 0 );
1827                    }
1828
1829                    if (options.gdpr.consent_magic_integration_enabled && typeof CS_Data !== "undefined") {
1830                        if(!advancedMatching) {
1831                            fbq('init', pixelId);
1832                        } else {
1833                            var test_prefix = CS_Data.test_prefix;
1834                            var cs_advanced_matching = Cookies.get('cs_enabled_advanced_matching'+test_prefix);
1835                            if (jQuery('#cs_enabled_advanced_matching'+test_prefix).length > 0) {
1836                                if (cs_advanced_matching == 'yes') {
1837                                    fbq('init', pixelId, advancedMatching);
1838                                } else {
1839                                    fbq('init', pixelId);
1840                                }
1841                            } else {
1842                                fbq('init', pixelId, advancedMatching);
1843                            }
1844                        }
1845                    } else {
1846                        if(!advancedMatching) {
1847                            fbq('init', pixelId);
1848                        }  else {
1849                            fbq('init', pixelId, advancedMatching);
1850                        }
1851                    }
1852                });
1853
1854                initialized = true;
1855
1856                Utils.fireStaticEvents('facebook');
1857
1858            },
1859
1860            fireEvent: function (name, data) {
1861
1862                if (!initialized || !this.isEnabled()) {
1863                    return false;
1864                }
1865
1866                data.delay = data.delay || 0;
1867                data.params = data.params || {};
1868
1869                if (data.delay === 0) {
1870
1871                    fireEvent(name, data);
1872
1873                } else {
1874
1875                    setTimeout(function (name, params) {
1876                        fireEvent(name, params);
1877                    }, data.delay * 1000, name, data);
1878
1879                }
1880
1881                return true;
1882
1883            },
1884
1885            onCommentEvent: function (event) {
1886                this.fireEvent(event.name, event);
1887            },
1888
1889            onDownloadEvent: function (event) {
1890                this.fireEvent(event.name, event);
1891            },
1892
1893            onFormEvent: function (event) {
1894
1895                this.fireEvent(event.name, event);
1896
1897            },
1898
1899            onWooAddToCartOnButtonEvent: function (product_id) {
1900
1901                if(!options.dynamicEvents.woo_add_to_cart_on_button_click.hasOwnProperty(this.tag()))
1902                    return;
1903                var event = options.dynamicEvents.woo_add_to_cart_on_button_click[this.tag()];
1904                window.pysWooProductData = window.pysWooProductData || [];
1905                if (window.pysWooProductData.hasOwnProperty(product_id)) {
1906                    if (window.pysWooProductData[product_id].hasOwnProperty('facebook')) {
1907                        event = Utils.copyProperties(event, {})
1908                        Utils.copyProperties(window.pysWooProductData[product_id]['facebook'].params, event.params)
1909                        this.fireEvent(event.name, event);
1910                    }
1911                }
1912            },
1913
1914            onWooAddToCartOnSingleEvent: function (product_id, qty, product_type, $form) {
1915
1916                window.pysWooProductData = window.pysWooProductData || [];
1917                if(!options.dynamicEvents.woo_add_to_cart_on_button_click.hasOwnProperty(this.tag()))
1918                    return;
1919                var event = Utils.clone(options.dynamicEvents.woo_add_to_cart_on_button_click[this.tag()]);
1920
1921                if (product_type === Utils.PRODUCT_VARIABLE && !options.facebook.wooVariableAsSimple) {
1922                    product_id = parseInt($form.find('input[name="variation_id"]').val());
1923                }
1924
1925                if (window.pysWooProductData.hasOwnProperty(product_id)) {
1926                    if (window.pysWooProductData[product_id].hasOwnProperty('facebook')) {
1927
1928
1929                        Utils.copyProperties(window.pysWooProductData[product_id]['facebook'].params, event.params);
1930
1931                        var groupValue = 0;
1932                        if(product_type === Utils.PRODUCT_GROUPED ) {
1933                            $form.find(".woocommerce-grouped-product-list .qty").each(function(index){
1934                                var childId = $(this).attr('name').replaceAll("quantity[","").replaceAll("]","");
1935                                var quantity = parseInt($(this).val());
1936                                if(isNaN(quantity)) {
1937                                    quantity = 0;
1938                                }
1939                                var childItem = window.pysWooProductData[product_id]['facebook'].grouped[childId];
1940
1941                                if(quantity == 0) {
1942                                    event.params.content_ids.forEach(function(el,index,array) {
1943                                        if(el == childItem.content_id) {
1944                                            array.splice(index, 1);
1945                                        }
1946                                    });
1947                                }
1948
1949                                if(event.params.hasOwnProperty('contents')) {
1950                                    event.params.contents.forEach(function(el,index,array) {
1951                                        if(el.id == childItem.content_id) {
1952                                            if(quantity > 0){
1953                                                el.quantity = quantity;
1954                                            } else {
1955                                                array.splice(index, 1);
1956                                            }
1957                                        }
1958                                    });
1959                                }
1960
1961
1962                                groupValue += childItem.price * quantity;
1963                            });
1964                            if(groupValue == 0) return;
1964 // skip if no items selected
1965                        }
1966
1967                        // maybe customize value option
1968                        if (options.woo.addToCartOnButtonValueEnabled && options.woo.addToCartOnButtonValueOption !== 'global') {
1969
1970                            if(product_type === Utils.PRODUCT_GROUPED) {
1971                                event.params.value = groupValue;
1972                            } else if(product_type === Utils.PRODUCT_BUNDLE) {
1973                                var data = $(".bundle_form .bundle_data").data("bundle_form_data");
1974                                var items_sum = getBundlePriceOnSingleProduct(data);
1975                                event.params.value = (parseInt(data.base_price) + items_sum )* qty;
1976                            } else {
1977                                event.params.value = event.params.value * qty;
1978                            }
1979                        }
1980
1981                        // only when non Facebook for WooCommerce logic used
1982                        if (event.params.hasOwnProperty('contents') && product_type !== Utils.PRODUCT_GROUPED) {
1983                            event.params.contents[0].quantity = qty;
1984                        }
1985
1986                        this.fireEvent(event.name, event);
1987
1988                    }
1989                }
1990            },
1991
1992            onWooRemoveFromCartEvent: function (event) {
1993                this.fireEvent(event.name, event);
1994            },
1995
1996            onEddAddToCartOnButtonEvent: function (download_id, price_index, qty) {
1997
1998                if(!options.dynamicEvents.edd_add_to_cart_on_button_click.hasOwnProperty(this.tag()))
1999                    return;
2000                var event = Utils.clone(options.dynamicEvents.edd_add_to_cart_on_button_click[this.tag()]);
2001
2002                if (window.pysEddProductData.hasOwnProperty(download_id)) {
2003
2004                    var index;
2005
2006                    if (price_index) {
2007                        index = download_id + '_' + price_index;
2008                    } else {
2009                        index = download_id;
2010                    }
2011
2012                    if (window.pysEddProductData[download_id].hasOwnProperty(index)) {
2013                        if (window.pysEddProductData[download_id][index].hasOwnProperty('facebook')) {
2014
2015
2016                            Utils.copyProperties(window.pysEddProductData[download_id][index]['facebook']["params"], event.params)
2017
2018                            // maybe customize value option
2019                            if (options.edd.addToCartOnButtonValueEnabled && options.edd.addToCartOnButtonValueOption !== 'global') {
2020                                event.params.value = event.params.value * qty;
2021                            }
2022
2023                            // update contents qty param
2024                            var contents = event.params.contents;
2025                            contents[0].quantity = qty;
2026                            event.params.contents = contents;
2027
2028                            this.fireEvent(event.name,event);
2029
2030                        }
2031                    }
2032
2033                }
2034
2035            },
2036
2037            onEddRemoveFromCartEvent: function (event) {
2038                this.fireEvent(event.name, event);
2039            },
2040            onPageScroll: function (event) {
2041                this.fireEvent(event.name, event);
2042            },
2043            onTime: function (event) {
2044                this.fireEvent(event.name, event);
2045            },
2046            initEventIdCookies: function (key) {
2047                var ids = {};
2048                ids[key] = pys_generate_token(36)
2049                Cookies.set('pys_fb_event_id', JSON.stringify(ids));
2050            },
2051            updateEventId:function(key) {
2052                var cooData = Cookies.get("pys_fb_event_id")
2053                if(cooData === undefined) {
2054                    this.initEventIdCookies(key);
2055                } else {
2056                    var data = JSON.parse(cooData);
2057                    data[key] = pys_generate_token(36);
2058                    Cookies.set('pys_fb_event_id', JSON.stringify(data) );
2059                }
2060            },
2061
2062            getEventId:function (key) {
2063                var data = Cookies.get("pys_fb_event_id");
2064                if(data === undefined) {
2065                    this.initEventIdCookies(key);
2066                    data = Cookies.get("pys_fb_event_id");
2067                }
2068                return JSON.parse(data)[key];
2069            },
2070        };
2071
2072    }(options);
2073
2074    var Analytics = function (options) {
2075
2076        var initialized = false;
2077
2078        /**
2079         * Fires event
2080         *
2081         * @link: https://developers.google.com/analytics/devguides/collection/gtagjs/sending-data
2082         * @link: https://developers.google.com/analytics/devguides/collection/gtagjs/events
2083         * @link: https://developers.google.com/gtagjs/reference/event
2084         * @link: https://developers.google.com/gtagjs/reference/parameter
2085         *
2086         * @link: https://developers.google.com/analytics/devguides/collection/gtagjs/custom-dims-mets
2087         *
2088         * @param name
2089         * @param data
2090         */
2091        function fireEvent(name, data) {
2092
2093            if(typeof window.pys_event_data_filter === "function" && window.pys_disable_event_filter(name,'ga')) {
2094                return;
2095            }
2096
2097            var eventParams = Utils.copyProperties(data, {});
2098            var _fireEvent = function (tracking_id,name,params) {
2099
2100                params['send_to'] = tracking_id;
2101
2102                if (options.debug) {
2103                    console.log('[Google Analytics #' + tracking_id + '] ' + name, params);
2104                }
2105
2106                gtag('event', name, params);
2107
2108            };
2109            options.ga.trackingIds.forEach(function (tracking_id) {
2110                var copyParams = Utils.copyProperties(eventParams, {}); // copy params because mapParamsTov4 can modify it
2111                var params = mapParamsTov4(tracking_id,name,copyParams)
2112                _fireEvent(tracking_id,name,params);
2113            });
2114
2115        }
2116        function mapParamsTov4(tag,name,param) {
2117            //GA4 automatically collects a number of parameters for all events
2118            delete param.landing_page;
2119            // end
2120            if(isv4(tag)) {
2121                delete param.traffic_source;
2122                delete param.event_category;
2123                delete param.event_label;
2124                delete param.ecomm_prodid;
2125                delete param.ecomm_pagetype;
2126                delete param.ecomm_totalvalue;
2127                if(name === 'search') {
2128                    param['search'] = param.search_term;
2129                    delete param.search_term;
2130                    delete param.dynx_itemid;
2131                    delete param.dynx_pagetype;
2132                    delete param.dynx_totalvalue;
2133                }
2134            }
2135            return param;
2136        }
2137
2138        function isv4(tag) {
2139            return tag.indexOf('G') === 0;
2140        }
2141
2142        /**
2143         * Public API
2144         */
2145        return {
2146            tag: function() {
2147                return "ga";
2148            },
2149            isEnabled: function () {
2150                return options.hasOwnProperty('ga');
2151            },
2152
2153            disable: function () {
2154                initialized = false;
2155            },
2156
2157            loadPixel: function () {
2158
2159                if (initialized || !this.isEnabled() || !Utils.consentGiven('analytics')) {
2160                    return;
2161                }
2162
2163                Utils.loadGoogleTag(options.ga.trackingIds[0]);
2164                var config = {};
2165                // Cross-Domain tracking
2166                if (options.ga.crossDomainEnabled) {
2167                    config.linker = {
2168                        accept_incoming: options.ga.crossDomainAcceptIncoming,
2169                        domains: options.ga.crossDomainDomains
2170                    };
2171                }
2172                var ids = options.ga.trackingIds;
2173                // configure tracking ids
2174                ids.forEach(function (trackingId,index) {
2175                    var obj = options.ga.isDebugEnabled;
2176                    var searchValue = "index_"+index;
2177                    var config_for_tag = Object.assign({}, options.config);
2178                    config_for_tag.debug_mode = false;
2179                    config_for_tag.send_page_view = !options.ga.custom_page_view_event;
2180                    for (var key in obj) {
2181                        if (obj.hasOwnProperty(key) && obj[key] === searchValue) {
2182                            config_for_tag.debug_mode = true;
2183                            break;
2184                        }
2185                    }
2186                    if(!config_for_tag.debug_mode)
2187                    {
2188                        delete config_for_tag.debug_mode;
2189                    }
2190                    if(isv4(trackingId)) {
2191                        if(options.ga.disableAdvertisingFeatures) {
2192                            config_for_tag.allow_google_signals = false
2193                        }
2194                        if(options.ga.disableAdvertisingPersonalization) {
2195                            config_for_tag.allow_ad_personalization_signals = false
2196                        }
2197                    }
2198                    if(options.ga.hasOwnProperty('additionalConfig')){
2199                        if(options.ga.additionalConfig.hasOwnProperty(trackingId) && options.ga.additionalConfig[trackingId]){
2200                            config_for_tag.first_party_collection = options.ga.additionalConfig[trackingId].first_party_collection;
2201                        }
2202
2203                    }
2204                    if(options.ga.hasOwnProperty('serverContainerUrls')){
2205                        if(options.ga.serverContainerUrls.hasOwnProperty(trackingId) && options.ga.serverContainerUrls[trackingId].enable_server_container != false){
2206                            if(options.ga.serverContainerUrls[trackingId].server_container_url != ''){
2207                                config_for_tag.server_container_url = options.ga.serverContainerUrls[trackingId].server_container_url;
2208                            }
2209                            if(options.ga.serverContainerUrls[trackingId].transport_url != ''){
2210                                config_for_tag.transport_url = options.ga.serverContainerUrls[trackingId].transport_url;
2211                            }
2212                        }
2213                    }
2214                    if (options.gdpr.cookiebot_integration_enabled && typeof Cookiebot !== 'undefined') {
2215
2216                        var cookiebot_consent_category = options.gdpr['cookiebot_analytics_consent_category'];
2217                        if (options.gdpr['analytics_prior_consent_enabled']) {
2218                            if (Cookiebot.consented === true && Cookiebot.consent[cookiebot_consent_category]) {
2219                                gtag('config', trackingId, config_for_tag);
2220                            }
2221                        } else {
2222                            if (Cookiebot.consent[cookiebot_consent_category]) {
2223                                gtag('config', trackingId, config_for_tag);
2224                            }
2225                        }
2226                    }
2227                    else
2228                    {
2229                        gtag('config', trackingId, config_for_tag);
2230                    }
2231                });
2232
2233                initialized = true;
2234
2235                Utils.fireStaticEvents('ga');
2236
2237            },
2238
2239            fireEvent: function (name, data) {
2240
2241                if (!initialized || !this.isEnabled()) {
2242                    return false;
2243                }
2244
2245                data.delay = data.delay || 0;
2246                data.params = data.params || {};
2247                data.params.eventID = Utils.generateUniqueId(data);
2248                if (data.delay === 0) {
2249
2250                    fireEvent(name, data.params);
2251
2252                } else {
2253
2254                    setTimeout(function (name, params) {
2255                        fireEvent(name, params);
2256                    }, data.delay * 1000, name, data.params);
2257
2258                }
2259
2260                return true;
2261
2262            },
2263
2264            onCommentEvent: function (event) {
2265                this.fireEvent(event.name, event);
2266            },
2267
2268            onDownloadEvent: function (event) {
2269                this.fireEvent(event.name, event);
2270            },
2271
2272            onFormEvent: function (event) {
2273                this.fireEvent(event.name, event);
2274            },
2275
2276            onWooAddToCartOnButtonEvent: function (product_id) {
2277
2278                if(!options.dynamicEvents.woo_add_to_cart_on_button_click.hasOwnProperty(this.tag()))
2279                    return;
2280                var event = Utils.clone(options.dynamicEvents.woo_add_to_cart_on_button_click[this.tag()]);
2281
2282                if (window.pysWooProductData.hasOwnProperty(product_id)) {
2283                    if (window.pysWooProductData[product_id].hasOwnProperty('ga')) {
2284                        Utils.copyProperties(window.pysWooProductData[product_id]['ga'].params, event.params)
2285                        this.fireEvent(event.name, event);
2286                    }
2287                }
2288
2289
2290            },
2291
2292            onWooAddToCartOnSingleEvent: function (product_id, qty, product_type, $form) {
2293
2294                window.pysWooProductData = window.pysWooProductData || [];
2295
2296                if(!options.dynamicEvents.woo_add_to_cart_on_button_click.hasOwnProperty(this.tag()))
2297                    return;
2298                var event = Utils.clone(options.dynamicEvents.woo_add_to_cart_on_button_click[this.tag()]);
2299
2300                if (product_type === Utils.PRODUCT_VARIABLE && !options.ga.wooVariableAsSimple) {
2301                    product_id = parseInt($form.find('input[name="variation_id"]').val());
2302                }
2303
2304                if (window.pysWooProductData.hasOwnProperty(product_id)) {
2305                    if (window.pysWooProductData[product_id].hasOwnProperty('ga')) {
2306
2307                        Utils.copyProperties(window.pysWooProductData[product_id]['ga'].params, event.params);
2308                        if(product_type === Utils.PRODUCT_GROUPED ) {
2309                            var groupValue = 0;
2310                            $form.find(".woocommerce-grouped-product-list .qty").each(function(index){
2311                                var childId = $(this).attr('name').replaceAll("quantity[","").replaceAll("]","");
2312                                var quantity = parseInt($(this).val());
2313                                if(isNaN(quantity)) {
2314                                    quantity = 0;
2315                                }
2316                                var childItem = window.pysWooProductData[product_id]['ga'].grouped[childId];
2317                                // update quantity
2318                                event.params.items.forEach(function(el,index,array) {
2319                                    if(el.id == childItem.content_id) {
2320                                        if(quantity > 0){
2321                                            el.quantity = quantity;
2322                                        } else {
2323                                            array.splice(index, 1);
2324                                        }
2325                                    }
2326                                });
2327                                groupValue += childItem.price * quantity;
2328                            });
2329                            if(options.woo.addToCartOnButtonValueEnabled &&
2330                                options.woo.addToCartOnButtonValueOption !== 'global' &&
2331                                event.params.hasOwnProperty('ecomm_totalvalue')) {
2332                                event.params.ecomm_totalvalue = groupValue;
2333                            }
2334
2335                            if(groupValue == 0) return; // skip if no items selected
2336                        } else {
2337                            // update items qty param
2338                            event.params.items[0].quantity = qty;
2339                        }
2340
2341                        // maybe customize value option
2342                        if (options.woo.addToCartOnButtonValueEnabled &&
2343                            options.woo.addToCartOnButtonValueOption !== 'global' &&
2344                            product_type !== Utils.PRODUCT_GROUPED)
2345                        {
2346                            if(event.params.hasOwnProperty('ecomm_totalvalue')) {
2347                                event.params.ecomm_totalvalue = event.params.items[0].price * qty;
2348                            }
2349
2350                        }
2351
2352
2353                        this.fireEvent(event.name, event);
2354                    }
2355                }
2356
2357            },
2358
2359            onWooRemoveFromCartEvent: function (event) {
2360
2361                this.fireEvent(event.name, event);
2362
2363            },
2364
2365            onEddAddToCartOnButtonEvent: function (download_id, price_index, qty) {
2366
2367                if(!options.dynamicEvents.edd_add_to_cart_on_button_click.hasOwnProperty(this.tag()))
2368                    return;
2369                var event = Utils.clone(options.dynamicEvents.edd_add_to_cart_on_button_click[this.tag()]);
2370
2371
2372                if (window.pysEddProductData.hasOwnProperty(download_id)) {
2373
2374                    var index;
2375
2376                    if (price_index) {
2377                        index = download_id + '_' + price_index;
2378                    } else {
2379                        index = download_id;
2380                    }
2381
2382                    if (window.pysEddProductData[download_id].hasOwnProperty(index)) {
2383                        if (window.pysEddProductData[download_id][index].hasOwnProperty('ga')) {
2384
2385                            Utils.copyProperties(window.pysEddProductData[download_id][index]['ga'].params, event.params);
2386
2387                            // update items qty param
2388                            event.params.items[0].quantity = qty;
2389
2390                            this.fireEvent(event.name,event);
2391
2392                        }
2393                    }
2394
2395                }
2396
2397            },
2398
2399            onEddRemoveFromCartEvent: function (event) {
2400                this.fireEvent(event.name, event);
2401            },
2402            onPageScroll: function (event) {
2403                this.fireEvent(event.name, event);
2404            },
2405            onTime: function (event) {
2406                this.fireEvent(event.name, event);
2407            },
2408
2409        };
2410
2411    }(options);
2412
2413    var GTM = function (options) {
2414        var initialized = false;
2415
2416        var datalayer_name = 'dataLayer';
2417        /*
2418         * @param name
2419         * @param data
2420         */
2421        function fireEvent(name, event) {
2422            if(typeof window.pys_event_data_filter === "function" && window.pys_disable_event_filter(name,'gtm')) {
2423                return;
2424            }
2425
2426
2427            var eventParams = event.params;
2428            var data = event.params;
2429            var valuesArray = Object.values(event.trackingIds);
2430            var ids = valuesArray;
2431            Utils.copyProperties(Utils.getRequestParams(), eventParams);
2432            var _fireEvent = function (tracking_id,name,params, event=null) {
2433                var eventData = {};
2434                var ContainerCodeHasTag = !options.gtm.gtm_just_data_layer && tracking_id.length > 0;
2435                if(ContainerCodeHasTag) {
2436                    params['send_to'] = tracking_id;
2437                }
2438                else if(!options.gtm.gtm_just_data_layer){
2439                    return
2440                }
2441
2442                if (params.hasOwnProperty('ecommerce')) {
2443                    eventData.ecommerce = params.ecommerce;
2444                    delete params.ecommerce;
2445                }
2446
2447                var automatedParams = { ...params };
2448                [params['manualName'], 'manualName', 'triggerType'].forEach(key => delete automatedParams[key]);
2449                if(event && (!event.hasOwnProperty('hasAutoParam') || (event.hasOwnProperty('hasAutoParam') && event.hasAutoParam))) {
2450                    eventData.automatedParameters = automatedParams;
2451                }
2452
2453// Move custom parameters to eventData
2454
2455                if (params.hasOwnProperty(params['manualName'])) {
2456                    eventData[params['manualName']] = params[params['manualName']];
2457                    delete params[params['manualName']];
2458                }
2459
2460                ['manualName','triggerType'].forEach(key => {
2461                    if (params.hasOwnProperty(key)) {
2462                        eventData[key] = params[key];
2463                        delete params[key];
2464                    }
2465                });
2466
2467                eventData.manualDataLayer = options.gtm.gtm_dataLayer_name ?? 'dataLayer';
2468
2469                eventData.event = name;
2470
2471                if (options.debug) {
2472                    if (ContainerCodeHasTag){
2473                        console.log('[Google GTM #' + tracking_id + '] ' + name, eventData);
2474                    }
2475                    else {
2476                        console.log('[Google GTM push to "'+datalayer_name+'"] ' + name, eventData);
2477                    }
2478                }
2479                window[datalayer_name].push(eventData);
2480
2481            };
2482
2483            var copyParams = Utils.copyProperties(eventParams, {}); // copy params because mapParamsToGTM can modify it
2484
2485            var params = mapParamsToGTM(ids,name,copyParams)
2486
2487            params.event_id = Utils.generateUniqueId(event);
2488
2489            _fireEvent(ids, name, params, event);
2490        }
2491
2492        function normalizeEventName(eventName) {
2493
2494            var matches = {
2495                ViewContent: 'view_item',
2496                AddToCart: 'add_to_cart',
2497                AddToWishList: 'add_to_wishlist',
2498                InitiateCheckout: 'begin_checkout',
2499                Purchase: 'purchase',
2500                Lead: 'generate_lead',
2501                CompleteRegistration: 'sign_up',
2502                AddPaymentInfo: 'set_checkout_option'
2503            };
2504
2505            return matches.hasOwnProperty(eventName) ? matches[eventName] : eventName;
2506
2507        }
2508
2509        function mapParamsToGTM(tag,name,param) {
2510            //GA4 automatically collects a number of parameters for all events
2511            var hasGTM = false;
2512
2513            // end
2514            if (Array.isArray(tag)) {
2515                hasGTM = tag.some(function (element) {
2516                    return isGTM(element);
2517                });
2518            } else if(isGTM(tag)) {
2519                // tag является строкой и соответствует GTM
2520                hasGTM = true;
2521            }
2522            if(hasGTM) {
2523                delete param.event_category;
2524                delete param.event_label;
2525
2526                delete param.analytics_storage;
2527                delete param.ad_storage;
2528                delete param.ad_user_data;
2529                delete param.ad_personalization;
2530
2531                if(name === 'search') {
2532                    param['search'] = param.search_term;
2533                    delete param.search_term;
2534                    delete param.dynx_itemid;
2535                    delete param.dynx_pagetype;
2536                    delete param.dynx_totalvalue;
2537                }
2538            }
2539            return param;
2540        }
2541
2542        function isGTM(tag) {
2543            return tag.indexOf('GTM') === 0;
2544        }
2545        /**
2546         * Public API
2547         */
2548        return {
2549            tag: function() {
2550                return "gtm";
2551            },
2552            isEnabled: function () {
2553                return options.hasOwnProperty('gtm');
2554            },
2555            disable: function () {
2556                initialized = false;
2557            },
2558            updateEnhancedConversionData : function () {
2559                if (!initialized || !this.isEnabled()) {
2560                    return;
2561                }
2562                if(options.hasOwnProperty("tracking_analytics") && options.tracking_analytics.hasOwnProperty("userDataEnable") && options.tracking_analytics.userDataEnable) {
2563                    var advanced = Utils.getAdvancedFormData();
2564                    if (Object.keys(advanced).length > 0) {
2565                        window[datalayer_name].push({'user_data' : advanced});
2566                    }
2567                }
2568            },
2569            loadPixel: function () {
2570
2571                if (initialized || !this.isEnabled() || !Utils.consentGiven('analytics')) {
2572                    return;
2573                }
2574                datalayer_name = options.gtm.gtm_dataLayer_name ?? 'dataLayer';
2575
2576                for (var i = 0; i < options.gtm.trackingIds.length; i++) {
2577                    var trackingId = options.gtm.trackingIds[i];
2578                    if (!options.gtm.gtm_just_data_layer) {
2579                        console.log('[PYS] Google Tag Manager container code loaded');
2580                        Utils.loadGTMScript(trackingId);
2581                        break;
2582                    }
2583                }
2584                if(options.gtm.gtm_just_data_layer) {
2585                    console.warn && console.warn("[PYS] Google Tag Manager container code placement set to OFF !!!");
2586                    console.warn && console.warn("[PYS] Data layer codes are active but GTM container must be loaded using custom coding !!!");
2587                    if(options.gtm.trackingIds.length == 0){
2588                        Utils.loadGTMScript();
2589                    }
2590                }
2591
2592                if(options.hasOwnProperty("tracking_analytics") && options.tracking_analytics.hasOwnProperty("userDataEnable") && options.tracking_analytics.userDataEnable){
2593                    var advanced = Utils.getAdvancedFormData();
2594                    if(Object.keys(advanced).length > 0){
2595                        window[datalayer_name].push({'user_data' : advanced});
2596                    }
2597                }
2598
2599
2600                var config = {};
2601
2602                if(options.user_id && options.user_id != 0) {
2603                    config.user_id = options.user_id;
2604                }
2605
2606                // Cross-Domain tracking
2607
2608                var ids = options.gtm.trackingIds;
2609
2610
2611                initialized = true;
2612
2613                Utils.fireStaticEvents('gtm');
2614            },
2615
2616            fireEvent: function (name, data) {
2617
2618                if (!initialized || !this.isEnabled()) {
2619                    return false;
2620                }
2621
2622                data.delay = data.delay || 0;
2623                data.params = data.params || {};
2624
2625                if (data.delay === 0) {
2626
2627                    fireEvent(name, data);
2628
2629                } else {
2630
2631                    setTimeout(function (name, params) {
2632                        fireEvent(name, params);
2633                    }, data.delay * 1000, name, data);
2634
2635                }
2636
2637                return true;
2638
2639            },
2640
2641            onCommentEvent: function (event) {
2642                this.fireEvent(event.name, event);
2643            },
2644
2645            onDownloadEvent: function (event) {
2646                this.fireEvent(event.name, event);
2647            },
2648
2649            onFormEvent: function (event) {
2650                this.fireEvent(event.name, event);
2651            },
2652
2653            onWooAddToCartOnButtonEvent: function (product_id, prod_info = null) {
2654                if(!options.dynamicEvents.woo_add_to_cart_on_button_click.hasOwnProperty(this.tag()))
2655                    return;
2656                var event = Utils.clone(options.dynamicEvents.woo_add_to_cart_on_button_click[this.tag()]);
2657
2658                if (window.pysWooProductData.hasOwnProperty(product_id)) {
2659                    if (window.pysWooProductData[product_id].hasOwnProperty('gtm')) {
2660                        Utils.copyProperties(window.pysWooProductData[product_id]['gtm'].params, event.params)
2661                        this.fireEvent(event.name, event);
2662                    }
2663                }
2664
2665            },
2666
2667            onWooAddToCartOnSingleEvent: function (product_id, qty, product_type, is_external, $form, prod_info) {
2668                window.pysWooProductData = window.pysWooProductData || [];
2669
2670                if(!options.dynamicEvents.woo_add_to_cart_on_button_click.hasOwnProperty(this.tag()))
2671                    return;
2672                var event = Utils.clone(options.dynamicEvents.woo_add_to_cart_on_button_click[this.tag()]);
2673
2674                if (product_type === Utils.PRODUCT_VARIABLE && !options.gtm.wooVariableAsSimple) {
2675                    product_id = parseInt($form.find('input[name="variation_id"]').val());
2676                }
2677
2678                if (window.pysWooProductData.hasOwnProperty(product_id)) {
2679                    if (window.pysWooProductData[product_id].hasOwnProperty('gtm')) {
2680
2681                        Utils.copyProperties(window.pysWooProductData[product_id]['gtm'].params, event.params);
2682
2683                        params = event.params.hasOwnProperty('ecommerce') ? event.params.ecommerce : event.params;
2684
2685                        if(product_type === Utils.PRODUCT_GROUPED ) {
2686                            var groupValue = 0;
2687                            $form.find(".woocommerce-grouped-product-list .qty").each(function(index){
2688                                var childId = $(this).attr('name').replaceAll("quantity[","").replaceAll("]","");
2689                                var quantity = parseInt($(this).val());
2690                                if(isNaN(quantity)) {
2691                                    quantity = 0;
2692                                }
2693                                var childItem = window.pysWooProductData[product_id]['gtm'].grouped[childId];
2694                                params.items.forEach(function(el,index,array) {
2695                                    if(el.id == childItem.content_id) {
2696                                        if(quantity > 0){
2697                                            el.quantity = quantity;
2698                                            el.price = childItem.price;
2699                                        } else {
2700                                            array.splice(index, 1);
2701                                        }
2702                                    }
2703                                });
2704                                groupValue += childItem.price * quantity;
2705                            });
2706
2707                            if(options.woo.addToCartOnButtonValueEnabled &&
2708                                options.woo.addToCartOnButtonValueOption !== 'global' &&
2709                                params.hasOwnProperty('value')) {
2710                                params.value = groupValue;
2711                            }
2712
2713                            if(groupValue == 0) return; // skip if no items selected
2714                        } else {
2715                            // update items qty param
2716                            params.items[0].quantity = qty;
2717                        }
2718
2719                        // maybe customize value option
2720                        if (options.woo.addToCartOnButtonValueEnabled &&
2721                            options.woo.addToCartOnButtonValueOption !== 'global' &&
2722                            product_type !== Utils.PRODUCT_GROUPED)
2723                        {
2724                            if(params.hasOwnProperty('value')) {
2725                                params.value = params.items[0].price * qty;
2726                            }
2727
2728                        }
2729
2730
2731                        this.fireEvent(event.name, event);
2732                    }
2733                }
2734
2735            },
2736
2737            onWooRemoveFromCartEvent: function (event) {
2738
2739                this.fireEvent(event.name, event);
2740
2741            },
2742
2743            onEddAddToCartOnButtonEvent: function (download_id, price_index, qty) {
2744                if(!options.dynamicEvents.edd_add_to_cart_on_button_click.hasOwnProperty(this.tag()))
2745                    return;
2746                var event = Utils.clone(options.dynamicEvents.edd_add_to_cart_on_button_click[this.tag()]);
2747
2748
2749                if (window.pysEddProductData.hasOwnProperty(download_id)) {
2750
2751                    var index;
2752
2753                    if (price_index) {
2754                        index = download_id + '_' + price_index;
2755                    } else {
2756                        index = download_id;
2757                    }
2758
2759                    if (window.pysEddProductData[download_id].hasOwnProperty(index)) {
2760                        if (window.pysEddProductData[download_id][index].hasOwnProperty('gtm')) {
2761
2762                            Utils.copyProperties(window.pysEddProductData[download_id][index]['gtm'].params, event.params);
2763                            item = event.params.hasOwnProperty('ecommerce') ? event.params.ecommerce.items[0] : event.params.items[0];
2764                            // update items qty param
2765                            item.quantity = qty;
2766
2767                            this.fireEvent(event.name,event);
2768
2769                        }
2770                    }
2771
2772                }
2773
2774            },
2775
2776            onEddRemoveFromCartEvent: function (event) {
2777                this.fireEvent(event.name, event);
2778            },
2779            onPageScroll: function (event) {
2780                this.fireEvent(event.name, event);
2781            },
2782            onTime: function (event) {
2783                this.fireEvent(event.name, event);
2784            },
2785        };
2786
2787    }(options);
2788
2789    window.pys = window.pys || {};
2790    window.pys.Facebook = Facebook;
2791    window.pys.Analytics = Analytics;
2792    window.pys.GTM = GTM;
2793    window.pys.Utils = Utils;
2794
2795
2796
2797
2798    $(document).ready(function () {
2799
2800        if($("#pys_late_event").length > 0) {
2801            var dirAttr = $("#pys_late_event").attr("dir");
2802            if (dirAttr) {
2803                try {
2804                    var events = JSON.parse(dirAttr);
2805                } catch (e) {
2806                    console.warn("Invalid JSON in pys_late_event dir attribute:", e);
2807                }
2808            } else {
2809                console.warn("pys_late_event dir attribute is undefined or empty");
2810            }
2811            if (events) {
2812                for (var key in events) {
2813                    var event = {};
2814                    event[events[key].e_id] = [events[key]];
2815                    if (options.staticEvents.hasOwnProperty(key)) {
2816                        Object.assign(options.staticEvents[key], event);
2817                    } else {
2818                        options.staticEvents[key] = event;
2819                    }
2820                }
2821            }
2822        }
2823
2824        var Pinterest = Utils.setupPinterestObject();
2825        var Bing = Utils.setupBingObject();
2826
2827        if(options.hasOwnProperty('cookie'))
2828        {
2829            if(options.cookie.externalID_disabled_by_api || options.cookie.disabled_all_cookie)
2830            {
2831                Cookies.remove('pbid')
2832            }
2833            if(options.cookie.disabled_advanced_form_data_cookie || options.cookie.disabled_all_cookie)
2834            {
2835                Cookies.remove('pys_advanced_form_data')
2836            }
2837            if(options.cookie.disabled_landing_page_cookie || options.cookie.disabled_all_cookie)
2838            {
2839                Cookies.remove('pys_landing_page')
2840                Cookies.remove('last_pys_landing_page')
2841            }
2842            if(options.cookie.disabled_trafficsource_cookie || options.cookie.disabled_all_cookie)
2843            {
2844                Cookies.remove('pysTrafficSource')
2845                Cookies.remove('last_pysTrafficSource')
2846            }
2847            if(options.cookie.disabled_first_visit_cookie || options.cookie.disabled_all_cookie)
2848            {
2849                Cookies.remove('pys_first_visit')
2850
2851            }
2852            if(options.cookie.disabled_utmTerms_cookie || options.cookie.disabled_all_cookie)
2853            {
2854                $.each(Utils.utmTerms, function (index, name) {
2855                    Cookies.remove('pys_' + name)
2856                });
2857                $.each(Utils.utmTerms, function (index, name) {
2858                    Cookies.remove('last_pys_' + name)
2859                });
2860            }
2861            if(options.cookie.disabled_utmId_cookie || options.cookie.disabled_all_cookie)
2862            {
2863                $.each(Utils.utmId,function(index,name) {
2864                    Cookies.remove('pys_' + name)
2865                })
2866                $.each(Utils.utmId,function(index,name) {
2867                    Cookies.remove('last_pys_' + name)
2868                });
2869            }
2870        }
2871
2872
2873        if (options.gdpr.cookie_law_info_integration_enabled) {
2874            var cli_cookie = Cookies.get('cookieyes-consent') ?? Cookies.get('viewed_cookie_policy');
2875
2876            if (typeof cli_cookie !== 'undefined') {
2877                if (cli_cookie === Cookies.get('cookieyes-consent') && getCookieYes('analytics') == 'yes') {
2878                    Utils.manageCookies();
2879                } else if (cli_cookie === Cookies.get('viewed_cookie_policy') && cli_cookie == 'yes') {
2880                    Utils.manageCookies();
2881                }
2882            }
2883        }
2884
2885        if ( options.gdpr.consent_magic_integration_enabled && typeof CS_Data !== "undefined" ) {
2886            if ( CS_Data.cs_script_cat.pys == CS_Data.cs_necessary_cat_id || CS_Data.cs_script_cat.pys == 0 ) {
2887                Utils.manageCookies();
2888            } else if ( Cookies.get( 'cs_enabled_cookie_term' + CS_Data.test_prefix + '_' + CS_Data.cs_script_cat.pys ) == 'yes' ) {
2889                Utils.manageCookies();
2890            }
2891        } else {
2892            Utils.manageCookies();
2893        }
2894
2895        Utils.setupGdprCallbacks();
2896        // page scroll event
2897        if ( options.dynamicEvents.hasOwnProperty("automatic_event_scroll")
2898        ) {
2899
2900            var singlePageScroll = function () {
2901
2902
2903                var docHeight = $(document).height() - $(window).height();
2904                var isFired = false;
2905
2906                if (options.dynamicEvents.hasOwnProperty("automatic_event_scroll")) {
2907                    var pixels = Object.keys(options.dynamicEvents.automatic_event_scroll);
2908                    for(var i = 0;i<pixels.length;i++) {
2909                        var event = Utils.clone(options.dynamicEvents.automatic_event_scroll[pixels[i]]);
2910                        var scroll = Math.round(docHeight * event.scroll_percent / 100)// convert % to absolute positions
2911
2912                        if(scroll < $(window).scrollTop()) {
2913                            Utils.copyProperties(Utils.getRequestParams(), event.params);
2914                            getPixelBySlag(pixels[i]).onPageScroll(event);
2915                            isFired = true
2916                        }
2917                    }
2918                }
2919                if(isFired) {
2920                    $(document).off("scroll",singlePageScroll);
2921                }
2922            }
2923            $(document).on("scroll",singlePageScroll);
2924        }
2925
2926
2927        if (options.dynamicEvents.hasOwnProperty("automatic_event_time_on_page")) {
2928            var pixels = Object.keys(options.dynamicEvents.automatic_event_time_on_page);
2929            var time = options.dynamicEvents.automatic_event_time_on_page[pixels[0]].time_on_page; // the same for all pixel
2930            setTimeout(function(){
2931                for(var i = 0;i<pixels.length;i++) {
2932                    var event = Utils.clone(options.dynamicEvents.automatic_event_time_on_page[pixels[i]]);
2933                    Utils.copyProperties(Utils.getRequestParams(), event.params);
2934                    getPixelBySlag(pixels[i]).onTime(event);
2935                }
2936            },time*1000);
2937        }
2938
2939        // setup Click Event
2940        if (options.dynamicEvents.hasOwnProperty("automatic_event_download")) {
2941
2942            $(document).onFirst('click', 'a, button, input[type="button"], input[type="submit"]', function (e) {
2943
2944                var $elem = $(this);
2945
2946                // Download
2947                if(options.dynamicEvents.hasOwnProperty("automatic_event_download")
2948                ) {
2949                    var isFired = false;
2950                    if ($elem.is('a')) {
2951                        var href = $elem.attr('href');
2952                        if (typeof href !== "string") {
2953                            return;
2954                        }
2955                        href = href.trim();
2956                        var extension = Utils.getLinkExtension(href);
2957                        var track_download = false;
2958
2959                        if (extension.length > 0) {
2960
2961                            if(options.dynamicEvents.hasOwnProperty("automatic_event_download") ) {
2962                                var pixels = Object.keys(options.dynamicEvents.automatic_event_download);
2963                                for (var i = 0; i < pixels.length; i++) {
2964                                    var event = Utils.clone(options.dynamicEvents.automatic_event_download[pixels[i]]);
2965                                    var extensions = event.extensions;
2966                                    if (extensions.includes(extension)) {
2967
2968                                        if(pixels[i] == "tiktok") {
2969                                            getPixelBySlag(pixels[i]).fireEvent(tikEvent.name, event);
2970                                        } else {
2971                                            if (options.enable_remove_download_url_param) {
2972                                                href = href.split('?')[0];
2973                                            }
2974                                            event.params.download_url = href;
2975                                            event.params.download_type = extension;
2976                                            event.params.download_name = Utils.getLinkFilename(href);
2977                                            getPixelBySlag(pixels[i]).onDownloadEvent(event);
2978                                        }
2979
2980                                        isFired = true;
2981                                    }
2982                                }
2983                            }
2984                        }
2985                    }
2986                    if(isFired) { // prevent duplicate events on the same element
2987                        return;
2988                    }
2989                }
2990            });
2991        }
2992
2993
2994        // setup Dynamic events
2995        $.each(options.triggerEventTypes, function (triggerType, events) {
2996
2997            $.each(events, function (eventId, triggers) {
2998
2999                switch (triggerType) {
3000                    case 'url_click':
3001                        //@see: Utils.setupURLClickEvents()
3002                        break;
3003
3004                    case 'css_click':
3005                        Utils.setupCSSClickEvents(eventId, triggers);
3006                        break;
3007
3008                    case 'css_mouseover':
3009                        Utils.setupMouseOverClickEvents(eventId, triggers);
3010                        break;
3011
3012                    case 'scroll_pos':
3013                        Utils.setupScrollPosEvents(eventId, triggers);
3014                        break;
3015                    case 'comment':
3016                        Utils.setupCommentEvents(eventId, triggers);
3017                        break;
3018                }
3019
3020            });
3021
3022        });
3023        // setup WooCommerce events
3024        if (options.woo.enabled) {
3025
3026            // WooCommerce AddToCart
3027            if (options.dynamicEvents.hasOwnProperty("woo_add_to_cart_on_button_click")
3028                && options.woo.hasOwnProperty("addToCartCatchMethod")
3029                && options.woo.addToCartCatchMethod === "add_cart_js"
3030            ) {
3031
3032                // Loop, any kind of "simple" product, except external
3033                $('.add_to_cart_button:not(.product_type_variable,.product_type_bundle,.single_add_to_cart_button)').on("click",function (e) {
3034
3035                    var product_id = $(this).data('product_id');
3036                    if (typeof product_id !== 'undefined') {
3037                        if (options.dynamicEvents.hasOwnProperty("woo_add_to_cart_on_button_click")) {
3038                            var tmpEventID = pys_generate_token();
3039                            $.each(options.dynamicEvents.woo_add_to_cart_on_button_click, function (i, tag) {
3040                                tag.eventID = tmpEventID;
3041                            });
3042                        }
3043                        if (typeof product_id !== 'undefined') {
3044                            Facebook.onWooAddToCartOnButtonEvent(product_id);
3045                            Analytics.onWooAddToCartOnButtonEvent(product_id);
3046                            GTM.onWooAddToCartOnButtonEvent(product_id);
3047                            Pinterest.onWooAddToCartOnButtonEvent(product_id);
3048                            Bing.onWooAddToCartOnButtonEvent(product_id);
3049                        }
3050                    }
3051                });
3052
3053                // Single Product
3054                // tap try to https://stackoverflow.com/questions/30990967/on-tap-click-event-firing-twice-how-to-avoid-it
3055                //  $(document) not work
3056                $('body').onFirst('click','button.single_add_to_cart_button,.single_add_to_cart_button',function (e) {
3057
3058                    var $button = $(this);
3059
3060                    if ($button.hasClass('disabled')) {
3061                        return;
3062                    }
3063
3064                    var $form = $button.closest('form');
3065
3066                    var product_type = Utils.PRODUCT_SIMPLE;
3067
3068                    if ($form.length === 0) {
3069                        return ;
3070                    } else if ($form.hasClass('variations_form')) {
3071                        product_type = Utils.PRODUCT_VARIABLE;
3072                    } else if($form.hasClass('bundle_form')) {
3073                        product_type = Utils.PRODUCT_BUNDLE;
3074                    } else if($form.hasClass('grouped_form')) {
3075                        product_type = Utils.PRODUCT_GROUPED;
3076                    }
3077
3078
3079
3080
3081                    var product_id;
3082                    var qty;
3083
3084                    if (product_type === Utils.PRODUCT_GROUPED) {
3085                        qty = 1;
3086                        product_id = parseInt($form.find('*[name="add-to-cart"]').val());
3087                    } else if (product_type === Utils.PRODUCT_VARIABLE) {
3088                        product_id = parseInt($form.find('*[name="add-to-cart"]').val());
3089                        var qtyTag = $form.find('input[name="quantity"]');
3090                        if(qtyTag.length <= 0) {
3091                            qtyTag = $form.find('select[name="quantity"]');
3092                        }
3093                        qty = parseInt(qtyTag.val());
3094                    } else {
3095                        product_id = parseInt($form.find('*[name="add-to-cart"]').val());
3096                        var qtyTag = $form.find('input[name="quantity"]');
3097                        if(qtyTag.length <= 0) {
3098                            qtyTag = $form.find('select[name="quantity"]');
3099                        }
3100                        qty = parseInt(qtyTag.val());
3101                    }
3102
3103                    if(options.dynamicEvents.hasOwnProperty("woo_add_to_cart_on_button_click")){
3104                        var tmpEventID = pys_generate_token();
3105                        $.each(options.dynamicEvents.woo_add_to_cart_on_button_click, function (i, tag) {
3106                            tag.eventID = tmpEventID;
3107                        });
3108                    }
3109
3110                    Facebook.onWooAddToCartOnSingleEvent(product_id, qty, product_type, $form);
3111                    Analytics.onWooAddToCartOnSingleEvent(product_id, qty, product_type, $form);
3112
3113                    GTM.onWooAddToCartOnSingleEvent(product_id, qty, product_type, $form);
3114
3115                    Pinterest.onWooAddToCartOnSingleEvent(product_id, qty, product_type, false, $form);
3116                    Bing.onWooAddToCartOnSingleEvent(product_id, qty, product_type, false, $form);
3117
3118                });
3119
3120            }
3121
3122            // WooCommerce RemoveFromCart
3123            if (options.dynamicEvents.hasOwnProperty("woo_remove_from_cart")) {
3124
3125                $('body').on('click', options.woo.removeFromCartSelector, function (e) {
3126
3127                    var $a = $(e.currentTarget),
3128                        href = $a.attr('href');
3129
3130                    // extract cart item hash from remove button URL
3131                    var regex = new RegExp("[\\?&]remove_item=([^&#]*)"),
3132                        results = regex.exec(href);
3133
3134                    if (results !== null) {
3135
3136                        var item_hash = results[1];
3137
3138                        if (options.dynamicEvents["woo_remove_from_cart"].hasOwnProperty(item_hash)) {
3139                            var events = options.dynamicEvents["woo_remove_from_cart"][item_hash];
3140                            Utils.fireEventForAllPixel("onWooRemoveFromCartEvent",events)
3141                        }
3142
3143                    }
3144
3145                });
3146            }
3147        }
3148
3149        // setup EDD events
3150        if (options.edd.enabled) {
3151
3152            // EDD AddToCart
3153            if (options.dynamicEvents.hasOwnProperty("edd_add_to_cart_on_button_click")) {
3154
3155                $('form.edd_download_purchase_form .edd-add-to-cart').on("click",function (e) {
3156
3157                    var $button = $(this);
3158                    var $form = $button.closest('form');
3159                    var variable_price = $button.data('variablePrice'); // yes/no
3160                    var price_mode = $button.data('priceMode'); // single/multi
3161                    var ids = [];
3162                    var quantities = [];
3163                    var qty;
3164                    var id;
3165
3166                    if (variable_price === 'yes' && price_mode === 'multi') {
3167
3168                        id = $form.find('input[name="download_id"]').val();
3169
3170                        // get selected variants
3171                        $.each($form.find('input[name="edd_options[price_id][]"]:checked'), function (i, el) {
3172                            ids.push(id + '_' + $(el).val());
3173                        });
3174
3175                        // get qty for selected variants
3176                        $.each(ids, function (i, variant_id) {
3177
3178                            var variant_index = variant_id.split('_', 2);
3179                            qty = $form.find('input[name="edd_download_quantity_' + variant_index[1] + '"]').val();
3180
3181                            if (typeof qty !== 'undefined') {
3182                                quantities.push(qty);
3183                            } else {
3184                                quantities.push(1);
3185                            }
3186
3187                        });
3188
3189                    } else if (variable_price === 'yes' && price_mode === 'single') {
3190
3191                        id = $form.find('input[name="download_id"]').val();
3192                        ids.push(id + '_' + $form.find('input[name="edd_options[price_id][]"]:checked').val());
3193
3194                        qty = $form.find('input[name="edd_download_quantity"]').val();
3195
3196                        if (typeof qty !== 'undefined') {
3197                            quantities.push(qty);
3198                        } else {
3199                            quantities.push(1);
3200                        }
3201
3202                    } else {
3203
3204                        ids.push($button.data('downloadId'));
3205
3206                        qty = $form.find('input[name="edd_download_quantity"]').val();
3207
3208                        if (typeof qty !== 'undefined') {
3209                            quantities.push(qty);
3210                        } else {
3211                            quantities.push(1);
3212                        }
3213                    }
3214
3215                    // fire event for each download/variant
3216                    $.each(ids, function (i, download_id) {
3217
3218                        var q = parseInt(quantities[i]);
3219                        var variant_index = download_id.toString().split('_', 2);
3220                        var price_index;
3221
3222                        if (variant_index.length === 2) {
3223                            download_id = variant_index[0];
3224                            price_index = variant_index[1];
3225                        }
3226
3227                        Facebook.onEddAddToCartOnButtonEvent(download_id, price_index, q);
3228                        Analytics.onEddAddToCartOnButtonEvent(download_id, price_index, q);
3229                        GTM.onEddAddToCartOnButtonEvent(download_id, price_index, q);
3230                        Pinterest.onEddAddToCartOnButtonEvent(download_id, price_index, q);
3231                        Bing.onEddAddToCartOnButtonEvent(download_id, price_index, q);
3232
3233                    });
3234
3235                });
3236
3237            }
3238
3239
3240            // EDD RemoveFromCart
3241            if (options.dynamicEvents.hasOwnProperty("edd_remove_from_cart") ) {
3242
3243                $('form#edd_checkout_cart_form .edd_cart_remove_item_btn').on("click",function (e) {
3244
3245                    var href = $(this).attr('href');
3246                    if(href) {
3247                        var key = href.substring(href.indexOf('=') + 1).charAt(0);
3248                        if (options.dynamicEvents.edd_remove_from_cart.hasOwnProperty(key)) {
3249                            var events = options.dynamicEvents.edd_remove_from_cart[key];
3250                            Utils.fireEventForAllPixel("onEddRemoveFromCartEvent",events)
3251                        }
3252                    }
3253                });
3254
3255            }
3256
3257        }
3258
3259        // setup Comment Event
3260        if (options.dynamicEvents.hasOwnProperty("automatic_event_c
3260omment")
3261        ) {
3262
3263            $('form.comment-form').on("submit",function () {
3264                if (options.dynamicEvents.hasOwnProperty("automatic_event_comment")) {
3265                    var pixels = Object.keys(options.dynamicEvents.automatic_event_comment);
3266                    for (var i = 0; i < pixels.length; i++) {
3267                        var event = Utils.clone(options.dynamicEvents.automatic_event_comment[pixels[i]]);
3268                        Utils.copyProperties(Utils.getRequestParams(), event.params);
3269                        getPixelBySlag(pixels[i]).onCommentEvent(event);
3270                    }
3271                }
3272            });
3273
3274        }
3275
3276
3277        // setup Form Event
3278        if ( options.dynamicEvents.hasOwnProperty("automatic_event_form")) {
3279
3280            $(document).onFirst('submit', 'form', function (e) {
3281
3282                var $form = $(this);
3283
3284                // exclude WP forms
3285                if ($form.hasClass('comment-form') || $form.hasClass('search-form') || $form.attr('id') === 'adminbarsearch') {
3286                    return;
3287                }
3288
3289                // exclude Woo forms
3290                if ($form.hasClass('woocommerce-product-search') || $form.hasClass('cart') || $form.hasClass('woocommerce-cart-form') ||
3291                    $form.hasClass('woocommerce-shipping-calculator') || $form.hasClass('checkout') || $form.hasClass('checkout_coupon')) {
3292                    return;
3293                }
3294
3295                // exclude EDD forms
3296                if ($form.hasClass('edd_form') || $form.hasClass('edd_download_purchase_form')) {
3297                    return;
3298                }
3299// exclude CF7 forms
3300                if ($form.hasClass('wpcf7-form')) {
3301                    return;
3302                }
3303                // exclude Forminator forms
3304                if ($form.hasClass('forminator-custom-form') || $form.hasClass('forminator_ajax')) {
3305                    return;
3306                }
3307                // exclude WPforms forms
3308                if ($form.hasClass('wpforms-form') || $form.hasClass('wpforms-ajax-form')) {
3309                    return;
3310                }
3311                // exclude Formidable forms
3312                /*if ($form.hasClass('frm-show-form')) {
3313                    return;
3314                }*/
3315                // exclude Ninja Forms forms
3316                if ($form.parent().hasClass('nf-form-layout')) {
3317                    return;
3318                }
3319                // exclude Fluent forms
3320                if ($form.hasClass('frm-fluent-form')) {
3321                    return;
3322                }
3323                if(!options.enable_success_send_form) {
3324                    var params = {
3325                        form_id: $form.attr('id'),
3326                        form_class: $form.attr('class'),
3327                        text: $form.find('[type="submit"]').is('input') ?
3328                            $form.find('[type="submit"]').val() : $form.find('[type="submit"]').text()
3329                    };
3330
3331                    if (options.dynamicEvents.hasOwnProperty("automatic_event_form")) {
3332                        var pixels = Object.keys(options.dynamicEvents.automatic_event_form);
3333                        for (var i = 0; i < pixels.length; i++) {
3334                            var event = Utils.clone(options.dynamicEvents.automatic_event_form[pixels[i]]);
3335
3336                            if (pixels[i] === "tiktok") {
3337                                getPixelBySlag(pixels[i]).fireEvent(event.name, event);
3338                            } else {
3339                                Utils.copyProperties(params, event.params,)
3340                                Utils.copyProperties(Utils.getRequestParam
3340s(), event.params);
3341                                getPixelBySlag(pixels[i]).onFormEvent(event);
3342                            }
3343                        }
3344                    }
3345                }
3346            });
3347
3348            document.addEventListener( 'wpcf7mailsent', function( event ) {
3349                var form_id = event.detail.contactFormId;
3350                sendFormAction($(event.target), form_id);
3351            }, false );
3352            //Forminator
3353            $(document).on( 'forminator:form:submit:success', function( event ){
3354                var form_id = $(event.target).find('input[name="form_id"]').val();
3355                sendFormAction($(event.target), form_id);
3356            });
3357
3358            //WPForm
3359            $('form.wpforms-form').on('wpformsAjaxSubmitSuccess', (event) => {
3360                var form_id = $(event.target).attr('data-formid');
3361                sendFormAction($(event.target), form_id);
3362            })
3363            $(document).on( 'frmFormComplete', function( event, form, response ) {
3364                const form_id = $(form).find('input[name="form_id"]').val();
3365                sendFormAction($(event.target), form_id);
3366            });
3367            // Ninja Forms
3368            $(document).onFirst('nfFormSubmitResponse', function (event, data) {
3369                const form_id = data.response.data.form_id;
3370                sendFormAction($(event.target), form_id);
3371            });
3372
3373            var fluentForms = $('form.frm-fluent-form');
3374            fluentForms.each(function() {
3375                var $form = $(this);
3376                $form.on('fluentform_submission_success', function(event) {
3377                    var $formItem = $(this);
3378                    var form_id = $formItem.attr('data-form_id');
3379                    sendFormAction($(event.target), form_id);
3380                });
3381            });
3382
3383        }
3384
3385
3386        // load pixel APIs
3387        Utils.loadPixels();
3388        // setup Enrich content
3389        if(Utils.isCheckoutPage()) {
3390            Utils.addCheckoutFields();
3391        }
3392    });
3393
3394    var sendFormAction = function (form_target, formId){
3395        var params = {
3396            form_id: formId,
3397            text: form_target.find('[type="submit"]').is('input') ? form_target.find('[type="submit"]').val() :
3398                form_target.find('.forminator-button-submit').text() != '' ? form_target.find('.forminator-button-submit').text() :
3399                    form_target.find('[type="submit"]').text()
3400        };
3401
3402        if (options.dynamicEvents.hasOwnProperty("automatic_event_form")) {
3403            var pixels = Object.keys(options.dynamicEvents.automatic_event_form);
3404            for (var i = 0; i < pixels.length; i++) {
3405                var event = options.dynamicEvents.automatic_event_form[pixels[i]];
3406                if (pixels[i] === "tiktok") {
3407                    getPixelBySlag(pixels[i]).fireEvent(event.name, event);
3408                } else {
3409                    Utils.copyProperties(params, event.params)
3410                    Utils.copyProperties(Utils.getRequestParams(), event.params);
3411                    getPixelBySlag(pixels[i]).onFormEvent(event);
3412                }
3413            }
3414        }
3415    }
3416
3417}(jQuery, pysOptions);
3418
3419function pys_generate_token() {
3420    return ([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g, c =>
3421        (c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16)
3422    );
3423}
3424
3425function getBundlePriceOnSingleProduct(data) {
3426    var items_sum = 0;
3427    jQuery(".bundle_form .bundled_product").each(function(index){
3428        var id = jQuery(this).find(".cart").data("bundled_item_id");
3429        var item_price = data.prices[id];
3430        var item_quantity = jQuery(this).find(".bundled_qty").val();
3431        if(!jQuery(this).hasClass("bundled_item_optional") ||
3432            jQuery(this).find(".bundled_product_optional_checkbox input").prop('checked')) {
3433            items_sum += item_price*item_quantity;
3434        }
3435    });
3436    return items_sum;
3437}
3438
3439function getPixelBySlag(slug) {
3440    switch (slug) {
3441        case "facebook": return window.pys.Facebook;
3442        case "ga": return window.pys.Analytics;
3443        case "gtm": return window.pys.GTM;
3444        case "bing": return window.pys.Bing;
3445        case "pinterest": return window.pys.Pinterest;
3446    }
3447}
3448function getUrlParameter(sParam) {
3449    var sPageURL = window.location.search.substring(1),
3450        sURLVariables = sPageURL.split('&'),
3451        sParameterName,
3452        i;
3453
3454    for (i = 0; i < sURLVariables.length; i++) {
3455        sParameterName = sURLVariables[i].split('=');
3456
3457        if (sParameterName[0] === sParam) {
3458            return sParameterName[1] === undefined ? true : decodeURIComponent(sParameterName[1]);
3459        }
3460    }
3461    return false;
3462};
3463function getCookieYes(key) {
3464    const cookiesObj = document.cookie
3465        .split(";")
3466        .reduce((ac, cv) => {
3467            const [k, v] = cv.split("=");
3468            if (k && v) ac[k.trim()] = v;
3469            return ac;
3470        }, {});
3471    const consentCookie = cookiesObj["cookieyes-consent"] || cookiesObj["wt_consent"];
3472    if (!consentCookie) return undefined;
3473    const { [key]: value } = consentCookie
3474        .split(",")
3475        .reduce((obj, pair) => {
3476            const [k, v] = pair.split(":");
3477            if (k && v) obj[k] = v;
3478            return obj;
3479        }, {});
3480    return value;
3481}
3482function getRootDomain(useSubdomain = false) {
3483    const hostname = window.location.hostname; // Get the current hostname
3484    // Check if tldjs is defined before using it
3485    if (typeof tldjs === "undefined") {
3486        console.warn("tldjs is not defined");
3487        return hostname; // Return hostname as a fallback
3488    }
3489
3490    const rootDomain = tldjs.getDomain(hostname); // Use tldjs to extract the root domain
3491
3492    // Return the root domain with or without a leading dot based on useSubdomain
3493    return rootDomain ? (useSubdomain ? '.' + rootDomain : rootDomain) : hostname;
3494}

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.