PageSourceSearch

https://zeronaldo.com.br/wp-content/plugins/pixelyoursite-pro/dist/scripts/public.js?ver=9.8.0

js zeronaldo.com.br collected 2026-10-02 23:30:10 UTC 206,962 bytes, 5,048 lines download raw bytes

1/* global pysOptions */
2
3// https://bitbucket.org/pixelyoursite/pys_pro_7/issues/7/possible-ie-11-error
4// https://tc39.github.io/ecma262/#sec-array.prototype.includes
5if (!Array.prototype.includes) {
6    Object.defineProperty(Array.prototype, 'includes', {
7        value: function (searchElement, fromIndex) {
8
9            if (this == null) {
10                throw new TypeError('"this" is null or not defined');
11            }
12
13            // 1. Let O be ? ToObject(this value).
14            var o = Object(this);
15
16            // 2. Let len be ? ToLength(? Get(O, "length")).
17            var len = o.length >>> 0;
18
19            // 3. If len is 0, return false.
20            if (len === 0) {
21                return false;
22            }
23
24            // 4. Let n be ? ToInteger(fromIndex).
25            //    (If fromIndex is undefined, this step produces the value 0.)
26            var n = fromIndex | 0;
27
28            // 5. If n ≥ 0, then
29            //  a. Let k be n.
30            // 6. Else n < 0,
31            //  a. Let k be len + n.
32            //  b. If k < 0, let k be 0.
33            var k = Math.max(n >= 0 ? n : len - Math.abs(n), 0);
34
35            function sameValueZero(x, y) {
36                return x === y || (typeof x === 'number' && typeof y === 'number' && isNaN(x) && isNaN(y));
37            }
38
39            // 7. Repeat, while k < len
40            while (k < len) {
41                // a. Let elementK be the result of ? Get(O, ! ToString(k)).
42                // b. If SameValueZero(searchElement, elementK) is true, return true.
43                if (sameValueZero(o[k], searchElement)) {
44                    return true;
45                }
46                // c. Increase k by 1.
47                k++;
48            }
49
50            // 8. Return false
51            return false;
52        }
53    });
54}
55
56if (!String.prototype.startsWith) {
57    Object.defineProperty(String.prototype, 'startsWith', {
58        enumerable: false,
59        configurable: false,
60        writable: false,
61        value: function (searchString, position) {
62            position = position || 0;
63            return this.indexOf(searchString, position) === position;
64        }
65    });
66}
67
68if (!String.prototype.trim) {
69    (function () {
70        String.prototype.trim = function () {
71            return this.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
72        };
73    })();
74}
75
76! function ($, options) {
77
78    if (options.debug) {
79        console.log('PYS:', options);
80    }
81
82
83
84    var dummyPinterest = function () {
85
86        /**
87         * Public API
88         */
89        return {
90            tag: function() {
91                return "pinterest";
92            },
93            isEnabled: function () {},
94
95            disable: function () {},
96
97            loadPixel: function () {},
98
99            fireEvent: function (name, data) {
100                return false;
101            },
102
103            onAdSenseEvent: function (event) {},
104
105            onClickEvent: function (params) {},
106
107            onWatchVideo: function (params) {},
108
109            onCommentEvent: function (event) {},
110
111            onFormEvent: function (params) {},
112
113            onDownloadEvent: function (params) {},
114
115
116
117            onWooAddToCartOnButtonEvent: function (product_id) {},
118
119            onWooAddToCartOnSingleEvent: function (product_id, qty, product_type, is_external, $form) {},
120
121            onWooRemoveFromCartEvent: function (cart_item_hash) {},
122
123            onWooAffiliateEvent: function (product_id) {},
124
125            onWooPayPalEvent: function (event) {},
126
127            onEddAddToCartOnButtonEvent: function (download_id, price_index, qty) {},
128
129            onEddRemoveFromCartEvent: function (item) {},
130
131            onPageScroll: function (event) {},
132            onTime: function (event) {
133
134            },
135
136        }
137
138    }();
139
140    var dummyBing = function () {
141
142        /**
143         * Public API
144         */
145        return {
146            tag: function() {
147                return "bing";
148            },
149            isEnabled: function () {},
150
151            disable: function () {},
152
153            loadPixel: function () {},
154
155            fireEvent: function (name, data) {
156                return false;
157            },
158
159            onAdSenseEvent: function (event) {},
160
161            onClickEvent: function (params) {},
162
163            onWatchVideo: function (params) {},
164
165            onCommentEvent: function (event) {},
166
167            onFormEvent: function (params) {},
168
169            onDownloadEvent: function (params) {},
170
171
172            onWooAddToCartOnButtonEvent: function (product_id) {},
173
174            onWooAddToCartOnSingleEvent: function (product_id, qty, product_type, is_external, $form) {},
175
176            onWooRemoveFromCartEvent: function (cart_item_hash) {},
177
178            onWooAffiliateEvent: function (product_id) {},
179
180            onWooPayPalEvent: function (event) {},
181
182            onEddAddToCartOnButtonEvent: function (download_id, price_index, qty) {},
183
184            onEddRemoveFromCartEvent: function (item) {},
185            onPageScroll: function (event) {},
186            onTime: function (event) {
187
188            },
189        }
190
191    }();
192
193    var Utils = function (options) {
194
195
196        var Pinterest = dummyPinterest;
197
198        var Bing = dummyBing;
199
200        var gtag_loaded = false;
201        let isNewSession = checkSession();
202
203
204        function loadPixels() {
205
206            if (!options.gdpr.all_disabled_by_api) {
207                if (!options.gdpr.tiktok_disabled_by_api) {
208                    TikTok.loadPixel();
209                }
210
211                if (!options.gdpr.facebook_disabled_by_api) {
212                    Facebook.loadPixel();
213                }
214
215                if (!options.gdpr.analytics_disabled_by_api) {
216                    Analytics.loadPixel();
217                }
218
219                if (!options.gdpr.google_ads_disabled_by_api) {
220                    GAds.loadPixel();
221                }
222
223                if (!options.gdpr.pinterest_disabled_by_api) {
224                    Pinterest.loadPixel();
225                }
226
227                if (!options.gdpr.bing_disabled_by_api) {
228                    Bing.loadPixel();
229                }
230
231            }
232            if (options.gdpr.consent_magic_integration_enabled && typeof CS_Data !== "undefined") {
233                if (typeof CS_Data.cs_google_analytics_consent_mode !== "undefined" && CS_Data.cs_google_analytics_consent_mode == 1) {
234                    Analytics.loadPixel();
235                }
236
237                if (typeof CS_Data.cs_google_ads_consent_mode !== "undefined" && CS_Data.cs_google_ads_consent_mode == 1 ) {
238                    GAds.loadPixel();
239                }
240            }
241
242
243        }
244
245        /**
246         * WATCHVIDEO UTILS
247         */
248
249        function isJSApiAttrEnabled(url) {
250            return url.indexOf('enablejsapi') > -1;
251        }
252
253        function isOriginAttrEnabled(url) {
254            return url.indexOf('origin') > -1;
255        }
256
257        // Returns key/value pairs of percentages: number of seconds to achieve
258        function getVideoCompletionMarks(duration) {
259
260            var marks = {};
261            var points = [0, 10, 50, 90, 100];
262
263            for (var i = 0; i < points.length; i++) {
264
265                var _point = points[i];
266                var _mark = _point + '%';
267                var _time = duration * _point / 100;
268
269                if (_point === 100) {
270                    _time = _time - 1;
271                }
272
273                // 10% => 123
274                marks[_mark] = Math.floor(_time);
275
276            }
277
278            return marks;
279
280        }
281
282        // Determine if the element is a YouTube video or not
283        function tagIsYouTubeVideo(tag) {
284            var src = tag.src || '';
285            return src.indexOf('youtube.com/embed/') > -1 || src.indexOf('youtube.com/v/') > -1;
286        }
287
288        function tagIsYouTubeAsyncVideo(tag) {
289            if(tag.src && tag.src.indexOf("data:image") !== -1) return false; // video is loaded
290            var keys = Object.keys(tag.dataset);
291            for(var i = 0;i<keys.length;i++) {
292                if(keys[i].toLowerCase().indexOf("src") > -1) {
293                    var src = tag.dataset[keys[i]];
294                    return src.indexOf('youtube.com/embed/') > -1 || src.indexOf('youtube.com/v/') > -1;
295                }
296            }
297            return false; //not find src
298        }
299
300        // Turn embed objects into iframe objects and ensure they have the right parameters
301        function normalizeYouTubeIframe(tag) {
302
303            var loc = window.location;
304            var a = document.createElement('a');
305            a.href = tag.src;
306            a.hostname = 'www.youtube.com';
307            a.protocol = loc.protocol;
308            var tmpPathname = a.pathname.charAt(0) === '/' ? a.pathname : '/' + a.pathname; // IE10 shim
309
310            if (!isJSApiAttrEnabled(a.search)) {
311                a.search = (a.search.length > 0 ? a.search + '&' : '') + 'enablejsapi=1';
312            }
313
314            // for security reasons, YouTube wants an origin parameter set that matches our hostname
315            if (!isOriginAttrEnabled(a.search) && loc.hostname.indexOf('localhost') === -1) {
316
317                var port = loc.port ? ':' + loc.port : '';
318                var origin = loc.protocol + '%2F%2F' + loc.hostname + port;
319
320                a.search = a.search + '&origin=' + origin;
321
322            }
323
324            if (tag.type === 'application/x-shockwave-flash') {
325
326                var newIframe = document.createElement('iframe');
327                newIframe.height = tag.height;
328                newIframe.width = tag.width;
329                tmpPathname = tmpPathname.replace('/v/', '/embed/');
330
331                tag.parentNode.parentNode.replaceChild(newIframe, tag.parentNode);
332
333                tag = newIframe;
334
335            }
336
337            a.pathname = tmpPathname;
338
339            if (tag.src !== a.href + a.hash) {
340                tag.src = a.href + a.hash;
341            }
342
343            return tag;
344
345        }
346
347        // Add event handlers for events emitted by the YouTube API
348        function addYouTubeEvents(iframe) {
349
350            var player = YT.get(iframe.id);
351
352            if (!player) {
353                player = new YT.Player(iframe, {});
354            }
355
356            if (typeof iframe.pauseFlag === 'undefined') {
357
358                iframe.pauseFlag = false;
359                player.addEventListener('onStateChange', function (evt) {
360                    onYouTubePlayerStateChange(evt, iframe);
361                });
362
363            }
364
365        }
366
367        function addDynYouTubeVideos(el) {
368            // We only bind to iFrames with a YouTube URL with the enablejsapi=1 and
369            // origin=<<hostname>> parameters
370            if (el.tagName === 'IFRAME'
371                && tagIsYouTubeVideo(el)
372                && isJSApiAttrEnabled(el.src)
373                && isOriginAttrEnabled(el.src))
374            {
375                addYouTubeEvents(el);
376            }
377        }
378
379        // Event handler for events emitted from the YouTube API
380        function onYouTubePlayerStateChange(evt, iframe) {
381
382            var stateIndex = evt.data;
383            var player = evt.target;
384            var targetVideoUrl = player.getVideoUrl();
385            var targetVideoId = targetVideoUrl.match(/[?&]v=([^&#]*)/)[1]; // Extract the ID
386            var playerState = player.getPlayerState();
387            var marks = getVideoCompletionMarks(player.getDuration());
388
389            iframe.playTracker = iframe.playTracker || {};
390
391            if (playerState === YT.PlayerState.PLAYING && !iframe.timer) {
392
393                clearInterval(iframe.timer);
394
395                // check every second to see if we've hit any of our percentage viewed marks
396                iframe.timer = setInterval(function () {
397                    checkYouTubeCompletion(player, marks, iframe.videoId);
398                }, 1000);
399
400            } else {
401
402                clearInterval(iframe.timer);
403                iframe.timer = false;
404
405            }
406
407            // playlist edge-case handler
408            if (stateIndex === YT.PlayerState.PLAYING) {
409                iframe.playTracker[targetVideoId] = true;
410                iframe.videoId = targetVideoId;
411                iframe.pauseFlag = false;
412            }
413
414            if (!iframe.playTracker[iframe.videoId]) {
415                return false; // this video hasn't started yet, so this is spam
416            }
417
418            if (stateIndex === YT.PlayerState.PAUSED) {
419
420                if (!iframe.pauseFlag) {
421                    iframe.pauseFlag = true;
422                } else {
423                    return false; // we don't want to fire consecutive pause events
424                }
425
426            }
427
428        }
429
430        // Trigger event if YouTube video mark was reached
431        function checkYouTubeCompletion(player, marks, videoId) {
432
433            var currentTime = player.getCurrentTime();
434
435            player[videoId] = player[videoId] || {};
436
437            for (var key in marks) {
438
439                if (marks[key] <= currentTime && !player[videoId][key]) {
440                    player[videoId][key] = true;
441
442                    var data = player.getVideoData();
443
444                    if (key === '0%') {
445                        key = 'play';
446                    }
447
448                    var params = {
449                        video_type: 'youtube',
450                        video_id: videoId,
451                        video_title: data.title,
452                    };
453
454                    // Auto
455                    if(options.automatic.enable_video
456                        && options.automatic.enable_youtube
457                        && options.dynamicEvents.hasOwnProperty("automatic_event_video")
458                    ) {
459                        var pixels = Object.keys(options.dynamicEvents.automatic_event_video);
460
461                        for (var i = 0; i < pixels.length; i++) {
462                            var event = Utils.clone(options.dynamicEvents.automatic_event_video[pixels[i]]);
463                            event.params["progress"] = key
464                            Utils.copyProperties(params, event.params)
465                            Utils.copyProperties(Utils.getRequestParam
465s(), event.params);
466                            getPixelBySlag(pixels[i]).onWatchVideo(event);
467                        }
468                    }
469
470                    if(key == "play") {
471
472                        $.each(options.triggerEventTypes, function (triggerType, events) {
473                            $.each(events, function (eventId, triggers) {
474                                switch (triggerType) {
475                                    case 'video_play':
476                                        Utils.fireTriggerEvent(eventId);
477                                        break;
478                                }
479
480                            });
481                        });
482                    }
483
484                }
485
486            }
487
488        }
489
490        // Determine if the element is a Vimeo video or not
491        function tagIsVimeoVideo(tag) {
492            var src = tag.src || '';
493            return src.indexOf('player.vimeo.com/video/') > -1;
494        }
495
496        function tagIsAsincVimeoVideo(tag) {
497            if(tag.src) return false; // video is loaded
498            var keys = Object.keys(tag.dataset);
499            for(var i = 0;i<keys.length;i++) {
500                if(keys[i].toLowerCase().indexOf("src") > -1) {
501                    var src = tag.dataset[keys[i]];
502                    return src.indexOf('player.vimeo.com/video/') > -1;
503                }
504            }
505            return false; //not find src
506        }
507
508        function attachVimeoPlayerToTag(tag) {
509            var player = new Vimeo.Player(tag);
510
511            player.getDuration().then(function (pl,seconds) {
512                pl.pysMarks = getVideoCompletionMarks(seconds);
513            }.bind(null,player));
514
515            player.getVideoTitle().then(function (pl,title) {
516                pl.pysVideoTitle = title;
517            }.bind(null,player));
518
519            player.getVideoId().then(function (pl,id) {
520                pl.pysVideoId = id;
521            }.bind(null,player));
522
523            player.pysCompletedMarks = {};
524
525            player.on('play', function () {
526
527                if (this.pysTimer) {
528                    return;
529                }
530
531                clearInterval(this.pysTimer);
532
533                var player = this;
534
535                this.pysTimer = setInterval(function () {
536                    checkVimeoCompletion(player);
537                }, 1000);
538
539            });
540
541            player.on('pause', function () {
542                clearInterval(this.pysTimer);
543                this.pysTimer = false;
544            });
545
546            player.on('ended', function () {
547                clearInterval(this.pysTimer);
548                this.pysTimer = false;
549            });
550        }
551
552        // Trigger event if Vimeo video mark was reached
553        function checkVimeoCompletion(player) {
554
555            player.getCurrentTime().then(function (seconds) {
556
557                for (var key in player.pysMarks) {
558
559                    if (player.pysMarks[key] <= seconds && !player.pysCompletedMarks[key]) {
560
561                        player.pysCompletedMarks[key] = true;
562
563                        if (key === '0%') {
564                            key = 'play';
565                        }
566
567                        var params = {
568                            video_type: 'vimeo',
569                            video_id: player.pysVideoId,
570                            video_title: player.pysVideoTitle,
571                        };
572
573                        // Auto
574                        if(options.automatic.enable_video
575                            && options.automatic.enable_vimeo
576                            && options.dynamicEvents.hasOwnProperty("automatic_event_video")
577                        ) {
578                            var pixels = Object.keys(options.dynamicEvents.automatic_event_video);
579
580                            for (var i = 0; i < pixels.length; i++) {
581                                var event = Utils.clone(options.dynamicEvents.automatic_event_video[pixels[i]]);
582                                event.params["progress"] = key
583                                Utils.copyProperties(params, event.params,);
584                                Utils.copyProperties(Utils.getRequestParam
584s(), event.params);
585                                getPixelBySlag(pixels[i]).onWatchVideo(event);
586                            }
587                        }
588
589                        if(key == "play") {
590                            $.each(options.triggerEventTypes, function (triggerType, events) {
591                                $.each(events, function (eventId, triggers) {
592                                    switch (triggerType) {
593                                        case 'video_play':
594                                            Utils.fireTriggerEvent(eventId);
595                                            break;
596                                    }
597
598                                });
599                            });
600                        }
601                    }
602
603                }
604
605            });
606
607        }
608
609        /**
610         * COOKIES UTILS
611         */
612
613        var utmTerms = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_content' ,'utm_term'];
614        var utmId = ['fbadid', 'gadid', 'padid', 'bingid'];
615        var requestParams = [];
616
617
618        function getDomain(url) {
619
620            url = url.replace(/(https?:\/\/)?(www.)?/i, '');
621
622            if (url.indexOf('/') !== -1) {
623                return url.split('/')[0];
624            }
625
626            return url;
627        }
628
629        function checkSession() {
630            let duration = options.last_visit_duration * 60000
631            if( Cookies.get('pys_start_session') === undefined ||
632                Cookies.get('pys_session_limit') === undefined) {
633                var now = new Date();
634                now.setTime(now.getTime() + duration);
635                Cookies.set('pys_session_limit', true,{ expires: now })
636                Cookies.set('pys_start_session', true)
637                return true
638            }
639            return false
640
641        }
642
643        function getTrafficSource() {
644
645            try {
646
647                let referrer = document.referrer.toString(),
648                    source;
649
650                let direct = referrer.length === 0;
651                let internal = direct ? false : referrer.indexOf(options.siteUrl) === 0;
652                let external = !direct && !internal;
653
654                if (external === false) {
655                    source = 'direct';
656                } else {
657                    source = referrer;
658                }
659
660                if (source !== 'direct') {
661                    // leave only domain (Issue #70)
662                    return getDomain(source);
663                } else {
664                    return source;
665                }
666
667            } catch (e) {
668                console.error(e);
669                return 'direct';
670            }
671
672        }
673
674        /**
675         * Return query variables object with where property name is query variable
676         * and property value is query variable value.
677         */
678        function getQueryVars() {
679
680            try {
681
682                var result = {},
683                    tmp = [];
684
685                window.location.search
686                    .substr(1)
687                    .split("&")
688                    .forEach(function (item) {
689
690                        tmp = item.split('=');
691
692                        if (tmp.length > 1) {
693                            result[tmp[0]] = tmp[1];
694                        }
695
696                    });
697
698                return result;
699
700            } catch (e) {
701                console.error(e);
702                return {};
703            }
704
705        }
706
707        function getLandingPageValue() {
708            let name = "pys_landing_page"
709            if(options.visit_data_model === "last_visit") {
710                name = "last_pys_landing_page"
711            }
712            if(Cookies.get(name) === 'undefined') {
713                return "";
714            } else {
715                return Cookies.get(name);
716            }
717        }
718        function getTrafficSourceValue() {
719            let name = "pysTrafficSource"
720            if(options.visit_data_model === "last_visit") {
721                name = "last_pysTrafficSource"
722            }
723            if(Cookies.get(name) === 'undefined') {
724                return "";
725            } else {
726                return Cookies.get(name);
727            }
728        }
729
730        function getUTMId(useLast = false) {
731            try {
732                let cookiePrefix = 'pys_'
733                let terms = [];
734                if (useLast) {
735                    cookiePrefix = 'last_pys_'
736                }
737                $.each(utmId, function (index, name) {
738                    if (Cookies.get(cookiePrefix + name)) {
739                        terms[name] = Cookies.get(cookiePrefix + name)
740                    }
741                });
742                return terms;
743            } catch (e) {
744                console.error(e);
745                return [];
746            }
747        }
748        /**
749         * Return UTM terms from request query variables or from cookies.
750         */
751        function getUTMs(useLast = false) {
752
753            try {
754                let cookiePrefix = 'pys_'
755                if(useLast) {
756                    cookiePrefix = 'last_pys_'
757                }
758                let terms = [];
759                $.each(utmTerms, function (index, name) {
760                    if (Cookies.get(cookiePrefix + name)) {
761                        let value = Cookies.get(cookiePrefix + name);
762                        terms[name] = filterEmails(value); // do not allow email in request params (Issue #70)
763                    }
764                });
765
766                return terms;
767
768            } catch (e) {
769                console.error(e);
770                return [];
771            }
772
773        }
774
775        function getDateTime() {
776            var dateTime = new Array();
777            var date = new Date(),
778                days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
779                months = ['January', 'February', 'March', 'April', 'May', 'June',
780                    'July', 'August', 'September', 'October', 'November', 'December'
781                ],
782                hours = ['00-01', '01-02', '02-03', '03-04', '04-05', '05-06', '06-07', '07-08',
783                    '08-09', '09-10', '10-11', '11-12', '12-13', '13-14', '14-15', '15-16', '16-17',
784                    '17-18', '18-19', '19-20', '20-21', '21-22', '22-23', '23-24'
785                ];
786            dateTime.push(hours[date.getHours()]);
787            dateTime.push(days[date.getDay()]);
788            dateTime.push(months[date.getMonth()]);
789            return dateTime;
790        }
791
792        function filterEmails(value) {
793            return Utils.validateEmail(value) ? undefined : value;
794        }
795
796        /**
797         * PUBLIC API
798         */
799        return {
800
801            PRODUCT_SIMPLE : 0,
802            PRODUCT_VARIABLE : 1,
803            PRODUCT_BUNDLE : 2,
804            PRODUCT_GROUPED : 3,
805            utmTerms : utmTerms,
806            utmId : utmId,
807            validateEmail: function (email) {
808                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,}))$/;
809                return re.test(email);
810            },
811             fireEventForAllPixel:function(functionName,events){
812                if (events.hasOwnProperty(Facebook.tag()))
813                    Facebook[functionName](events[Facebook.tag()]);
814                if (events.hasOwnProperty(Analytics.tag()))
815                    Analytics[functionName](events[Analytics.tag()]);
816                if (events.hasOwnProperty(GAds.tag()))
817                    GAds[functionName](events[GAds.tag()]);
818                if (events.hasOwnProperty(Pinterest.tag()))
819                    Pinterest[functionName](events[Pinterest.tag()]);
820                if (events.hasOwnProperty(Bing.tag()))
821                    Bing[functionName](events[Bing.tag()]);
822                 if (events.hasOwnProperty(TikTok.tag()))
823                     TikTok[functionName](events[TikTok.tag()]);
824            },
825
826            getQueryValue:function (name){
827                return getQueryVars()[name];
828            },
829
830            filterEmails: function (value) {
831                return filterEmails(value);
832            },
833
834            setupPinterestObject: function () {
835                Pinterest = window.pys.Pinterest || Pinterest;
836                return Pinterest;
837            },
838
839            setupBingObject: function () {
840                Bing = window.pys.Bing || Bing;
841                return Bing;
842            },
843
844            // Clone all object members to another and return it
845            copyProperties: function (from, to) {
846                for (var key in from) {
847                    if("function" == typeof from[key]) {
848                        continue;
849                    }
850                    to[key] = from[key];
851                }
852                return to;
853            },
854
855            clone: function(obj) {
856                var copy;
857
858                // Handle the 3 simple types, and null or undefined
859                if (null == obj || "object" != typeof obj) return obj;
860
861                // Handle Date
862                if (obj instanceof Date) {
863                    copy = new Date();
864                    copy.setTime(obj.getTime());
865                    return copy;
866                }
867
868                // Handle Array
869                if (obj instanceof Array) {
870                    copy = [];
871                    for (var i = 0, len = obj.length; i < len; i++) {
872                        if("function" == typeof obj[i]) {
873                            continue;
874                        }
875                        copy[i] = Utils.clone(obj[i]);
876                    }
877                    return copy;
878                }
879
880                // Handle Object
881                if (obj instanceof Object) {
882                    copy = {};
883                    for (var attr in obj) {
884                        if (obj.hasOwnProperty(attr)) {
885                            if("function" == typeof obj[attr]) {
886                                continue;
887                            }
888                            copy[attr] = Utils.clone(obj[attr]);
889                        }
890                    }
891                    return copy;
892                }
893
894                return obj;
895            },
896
897            // Returns array of elements with given tag name
898            getTagsAsArray: function (tag) {
899                return [].slice.call(document.getElementsByTagName(tag));
900            },
901
902            /**
903             * Load and initialize YouTube API
904             *
905             * @link: https://developers.google.com/youtube/iframe_api_reference
906             */
907            initYouTubeAPI: function () {
908
909                // maybe load YouTube JS API
910                if (typeof window.YT === 'undefined') {
911                    var tag = document.createElement('script');
912                    tag.src = '//www.youtube.com/iframe_api';
913                    var firstScriptTag = document.getElementsByTagName('script')[0];
914                    firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
915                }
916
917                // initialize when API is ready
918                window.onYouTubeIframeAPIReady = function () {
919
920                    // collect all possible YouTube tags
921                    var potentialVideos = Utils.getTagsAsArray('iframe').concat(Utils.getTagsAsArray('embed'));
922
923                    // turn videos into trackable videos with events
924                    for (var i = 0; i < potentialVideos.length; i++) {
925                        var video = potentialVideos[i];
926                        if (tagIsYouTubeVideo(video)) {
927                            var iframe = normalizeYouTubeIframe(video);
928                            addYouTubeEvents(iframe);
929                        } else {
930                            if(tagIsYouTubeAsyncVideo(video)) {
931                                video.addEventListener("load", function(evt) {
932                                    var iframe = normalizeYouTubeIframe(evt.currentTarget);
933                                    addYouTubeEvents(iframe);
934                                });
935                            }
936                        }
937                    }
938
939
940
941                    var targets = document.querySelectorAll('.elementor-widget-video .elementor-wrapper');
942
943                    const config = {
944                        attributes: false,
945                        childList: true,
946                        subtree: true
947                    };
948
949                    const callback = function(mutationsList, observer) {
950                        for (let mutation of mutationsList) {
951                            if (mutation.type === 'childList') {
952                                for(var m = 0;m<mutation.addedNodes.length;m++) {
953                                    addDynYouTubeVideos(mutation.addedNodes[m]);
954                                }
955                            }
956                        }
957                    };
958                    // observe elementator widget-video and add event when it add iframe
959                    for(var i=0;i<targets.length;i++) {
960                        const observer = new MutationObserver(callback);
961                        observer.observe(targets[i], config);//maybe remove before add
962                    }
963
964
965                };
966
967            },
968
969            /**
970             * Load and initialize Vimeo API
971             *
972             * @link: https://github.com/vimeo/player.js
973             */
974            initVimeoAPI: function () {
975
976              
977                $(document).ready(function () {
978
979                    var potentialVideos = Utils.getTagsAsArray('iframe').concat(Utils.getTagsAsArray('embed'));
980
981                    for (var i = 0; i < potentialVideos.length; i++) {
982                        var tag = potentialVideos[i];
983                        if (tagIsVimeoVideo(tag)) {
984                            attachVimeoPlayerToTag(tag);
985                        } else {
986                            if (tagIsAsincVimeoVideo(tag)) {
987                                tag.addEventListener("load", function(evt) {
988                                    attachVimeoPlayerToTag(evt.currentTarget);
989                                });
990                            }
991                        }
992                    }
993
994                });
995
996            },
997
998            manageCookies: function () {
999                let expires = parseInt(options.cookie_duration); //  days
1000                let queryVars = getQueryVars();
1001                let landing = window.location.href.split('?')[0];
1002                try {
1003                    // save data for first visit
1004                    if(Cookies.get('pys_first_visit') === undefined && (!options.cookie.disabled_all_cookie)) {
1005
1006                        if(!options.cookie.disabled_first_visit_cookie)
1007                        {
1008                            Cookies.set('pys_first_visit', true, { expires: expires });
1009                        }
1010                        else {
1011                            Cookies.remove('pys_first_visit')
1012                        }
1013
1014                        if(!options.cookie.disabled_trafficsource_cookie)
1015                        {
1016                            Cookies.set('pysTrafficSource', getTrafficSource(), { expires: expires });
1017                        }
1018                        else {
1019                            Cookies.remove('pysTrafficSource')
1020                        }
1021
1022                        if(!options.cookie.disabled_landing_page_cookie)
1023                        {
1024                            Cookies.set('pys_landing_page',landing,{ expires: expires });
1025                        }
1026                        else {
1027                            Cookies.remove('pys_landing_page')
1028                        }
1029
1030                        if(!options.cookie.disabled_utmTerms_cookie)
1031                        {
1032                            $.each(utmTerms, function (index, name) {
1033                                if (queryVars.hasOwnProperty(name)) {
1034                                    Cookies.set('pys_' + name, queryVars[name], { expires: expires });
1035                                } else {
1036                                    Cookies.remove('pys_' + name)
1037                                }
1038                            });
1039                        }
1040                        else {
1041                            $.each(utmTerms, function (index, name) {
1042                                Cookies.remove('pys_' + name)
1043                            });
1044                        }
1045
1046                        if(!options.cookie.disabled_utmId_cookie)
1047                        {
1048                            $.each(utmId,function(index,name) {
1049                                if (queryVars.hasOwnProperty(name)) {
1050                                    Cookies.set('pys_' + name, queryVars[name], { expires: expires });
1051                                } else {
1052                                    Cookies.remove('pys_' + name)
1053                                }
1054                            })
1055                        }
1056                        else {
1057                            $.each(utmId, function (index, name) {
1058                                Cookies.remove('pys_' + name)
1059                            });
1060                        }
1061
1062                    }
1063
1064                    // save data for last visit if it new session
1065                    if(isNewSession && (!options.cookie.disabled_all_cookie)) {
1066                        if(!options.cookie.disabled_trafficsource_cookie)
1067                        {
1068                            Cookies.set('last_pysTrafficSource', getTrafficSource(), { expires: expires });
1069                        }
1070                        else {
1071                            Cookies.remove('last_pysTrafficSource')
1072                        }
1073
1074                        if(!options.cookie.disabled_landing_page_cookie)
1075                        {
1076                            Cookies.set('last_pys_landing_page',landing,{ expires: expires });
1077                        }
1078                        else {
1079                            Cookies.remove('last_pys_landing_page')
1080                        }
1081
1082                        if(!options.cookie.disabled_utmTerms_cookie)
1083                        {
1084                            $.each(utmTerms, function (index, name) {
1085                                if (queryVars.hasOwnProperty(name)) {
1086                                    Cookies.set('last_pys_' + name, queryVars[name], { expires: expires });
1087                                } else {
1088                                    Cookies.remove('last_pys_' + name)
1089                                }
1090                            });
1091                        }
1092                        else {
1093                            $.each(utmTerms, function (index, name) {
1094                                Cookies.remove('last_pys_' + name)
1095                            });
1096                        }
1097
1098                        if(!options.cookie.disabled_utmId_cookie)
1099                        {
1100                            $.each(utmId,function(index,name) {
1101                                if (queryVars.hasOwnProperty(name)) {
1102                                    Cookies.set('last_pys_' + name, queryVars[name], { expires: expires });
1103                                } else {
1104                                    Cookies.remove('last_pys_' + name)
1105                                }
1106                            })
1107                        }
1108                        else {
1109                            $.each(utmId, function (index, name) {
1110                                Cookies.remove('last_pys_' + name)
1111                            });
1112                        }
1113
1114                    }
1115                    if(options.cookie.disabled_all_cookie)
1116                    {
1117                        Cookies.remove('pys_first_visit')
1118                        Cookies.remove('pysTrafficSource')
1119                        Cookies.remove('pys_landing_page')
1120                        Cookies.remove('last_pys_landing_page')
1121                        Cookies.remove('last_pysTrafficSource')
1122                        Cookies.remove('pys_start_session')
1123                        Cookies.remove('pys_session_limit')
1124                        $.each(Utils.utmTerms, function (index, name) {
1125                            Cookies.remove('pys_' + name)
1126                        });
1127                        $.each(Utils.utmId,function(index,name) {
1128                            Cookies.remove('pys_' + name)
1129                        })
1130                        $.each(Utils.utmTerms, function (index, name) {
1131                            Cookies.remove('last_pys_' + name)
1132                        });
1133                        $.each(Utils.utmId,function(index,name) {
1134                            Cookies.remove('last_pys_' + name)
1135                        });
1136                    }
1137                } catch (e) {
1138                    console.error(e);
1139                }
1140            },
1141
1142            initializeRequestParams: function () {
1143
1144                if (options.trackTrafficSource) {
1145                    requestParams.traffic_source = getTrafficSourceValue();
1146                }
1147
1148                if (options.trackUTMs) {
1149
1150                    var utms = getUTMs(options.visit_data_model === "last_visit");
1151
1152                    $.each(utmTerms, function (index, term) {
1153                        if (term in utms) {
1154                            requestParams[term] = utms[term];
1155                        }
1156                    });
1157
1158                }
1159
1160
1161                var dateTime = getDateTime();
1162                if(options.enable_event_time_param) {
1163                    requestParams.event_time = dateTime[0];
1164                }
1165
1166                if(options.enable_event_day_param) {
1167                    requestParams.event_day = dateTime[1];
1168                }
1169                if(options.enable_event_month_param) {
1170                    requestParams.event_month = dateTime[2];
1171                }
1172
1173                if(options.enable_lading_page_param){
1174                    requestParams.landing_page = getLandingPageValue();
1175                }
1176            },
1177
1178            getRequestParams: function () {
1179                return requestParams;
1180            },
1181
1182            /**
1183             * DOWNLOAD DOCS
1184             */
1185
1186            getLinkExtension: function (link) {
1187
1188                // Remove anchor, query string and everything before last slash
1189                link = link.substring(0, (link.indexOf("#") === -1) ? link.length : link.indexOf("#"));
1190                link = link.substring(0, (link.indexOf("?") === -1) ? link.length : link.indexOf("?"));
1191                link = link.substring(link.lastIndexOf("/") + 1, link.length);
1192
1193                // If there's a period left in the URL, then there's a extension
1194                if (link.length > 0 && link.indexOf('.') !== -1) {
1195                    link = link.substring(link.lastIndexOf(".") + 1); // Remove everything but what's after the first period
1196                    return link;
1197                } else {
1198                    return "";
1199                }
1200            },
1201
1202            getLinkFilename: function (link) {
1203
1204                // Remove anchor, query string and everything before last slash
1205                link = link.substring(0, (link.indexOf("#") === -1) ? link.length : link.indexOf("#"));
1206                link = link.substring(0, (link.indexOf("?") === -1) ? link.length : link.indexOf("?"));
1207                link = link.substring(link.lastIndexOf("/") + 1, link.length);
1208
1209                // If there's a period left in the URL, then there's a extension
1210                if (link.length > 0 && link.indexOf('.') !== -1) {
1211                    return link;
1212                } else {
1213                    return "";
1214                }
1215            },
1216
1217            /**
1218             * CUSTOM EVENTS
1219             */
1220
1221            setupMouseOverClickEvents: function (eventId, triggers) {
1222
1223                // Non-default binding used to avoid situations when some code in external js
1224                // stopping events propagation, eg. returns false, and our handler will never called
1225                document.addEventListener('mouseover', function(event) {
1226                    var matchedElements = Array.from(document.querySelectorAll(triggers));
1227                    var clickedElement = event.target;
1228                    var closestMatch = clickedElement.closest(triggers);
1229                    if (matchedElements.includes(clickedElement) || closestMatch){
1230                        if (event.target.classList.contains('pys-mouse-over-' + eventId)) {
1231                            return true;
1232                        } else {
1233                            event.target.classList.add('pys-mouse-over-' + eventId);
1234                        }
1235
1236                        Utils.fireTriggerEvent(eventId);
1237                    }
1238                });
1239
1240
1241            },
1242
1243            setupCSSClickEvents: function (eventId, triggers) {
1244                // Non-default binding used to avoid situations when some code in external js
1245                // stopping events propagation, eg. returns false, and our handler will never called
1246                // add event to document to support dyn class
1247                document.addEventListener('click', function(event) {
1248                    var matchedElements = Array.from(document.querySelectorAll(triggers));
1249                    var clickedElement = event.target;
1250                    var closestMatch = clickedElement.closest(triggers);
1251                    if (matchedElements.includes(clickedElement) || closestMatch){
1252                        Utils.fireTriggerEvent(eventId);
1253                    }
1254                }, true);
1255            },
1256
1257            setupURLClickEvents: function () {
1258
1259                if( !options.triggerEventTypes.hasOwnProperty('url_click') ) {
1260                    return;
1261                }
1262                // Non-default binding used to avoid situations when some code in external js
1263                // stopping events propagation, eg. returns false, and our handler will never called
1264                document.addEventListener('click', function(event) {
1265                    if (event.target.matches('a')) {
1266                        var url = event.target.getAttribute('href');
1267                        if (url) {
1268                            Object.entries(options.triggerEventTypes.url_click).forEac
1268h(function ([eventId, triggers]) {
1269                                triggers.forEach(function (trigger) {
1270                                    if (Utils.compareUrl(url, trigger.value, trigger.rule)) {
1271                                        Utils.fireTriggerEvent(eventId);
1272                                    }
1273                                });
1274                            });
1275                        }
1276                    }
1277                }, true);
1278
1279            },
1280
1281            removeUrlDomain(url) {
1282                if(url.indexOf("/#") > -1) {
1283                    url = url.substring(0, url.indexOf("/#"));
1284                }
1285                return url.replace('http://','')
1286                    .replace('https://','')
1287                    .replace('www.','')
1288                    .trim()
1289                    .replace(/^\/+/g, '')
1290
1291            },
1292
1293            compareUrl: function(base,url,rule){
1294
1295                if(url == "*" || url == '') return true;
1296
1297                base = Utils.removeUrlDomain(base)
1298                url = Utils.removeUrlDomain(url)
1299
1300                if(rule == 'match') {
1301                    return url == base;
1302                } else {
1303                    return base.indexOf(url) > -1
1304                }
1305
1306            },
1307
1308            setupScrollPosEvents: function (eventId, triggers) {
1309
1310                var scrollPosThresholds = {},
1311                    docHeight = $(document).height() - $(window).height();
1312
1313                // convert % to absolute positions
1314                $.each(triggers, function (index, scrollPos) {
1315
1316                    // convert % to pixels
1317                    scrollPos = docHeight * scrollPos / 100;
1318                    scrollPos = Math.round(scrollPos);
1319
1320                    scrollPosThresholds[scrollPos] = eventId;
1321
1322                });
1323
1324                $(document).on("scroll",function () {
1325
1326                    var scrollPos = $(window).scrollTop();
1327
1328                    $.each(scrollPosThresholds, function (threshold, eventId) {
1329
1330                        // position has not reached yes
1331                        if (scrollPos <= threshold) {
1332                            return true;
1333                        }
1334
1335                        // fire event only once
1336                        if (eventId === null) {
1337                            return true;
1338                        } else {
1339                            scrollPosThresholds[threshold] = null;
1340                        }
1341
1342                        Utils.fireTriggerEvent(eventId);
1343
1344                    });
1345
1346                });
1347
1348            },
1349            setupCommentEvents : function (eventId,triggers) {
1350                $('form.comment-form').on("submit",function () {
1351                    Utils.fireTriggerEvent(eventId);
1352                });
1353            },
1354            /**
1355             * Events
1356             */
1357
1358            isEventInTimeWindow: function (eventName, event, prefix) {
1359
1360                if(event.hasOwnProperty("hasTimeWindow") && event.hasTimeWindow) {
1361                    var cookieName = prefix+"_"+eventName;
1362                    var now = new Date().getTime();
1363
1364                    if(Cookies.get(cookieName) !== undefined) {
1365
1366                        var lastTimeFire = Cookies.get(cookieName);
1367                        var fireTime = event.timeWindow * 60*60*1000;
1368
1369                        if( now - lastTimeFire > fireTime) {
1370                            Cookies.set(cookieName,now, { expires: event.timeWindow / 24.0} );
1371                        } else {
1372                            return false;
1373                        }
1374                    } else {
1375                        Cookies.set(cookieName,now, { expires: event.timeWindow / 24.0} );
1376                    }
1377                }
1378                return true
1379            },
1380
1381            fireTriggerEvent: function (eventId) {
1382
1383                if (!options.triggerEvents.hasOwnProperty(eventId)) {
1384                    return;
1385                }
1386
1387                var event = {};
1388                var events = options.triggerEvents[eventId];
1389
1390                if (events.hasOwnProperty('facebook')) {
1391                    event = events.facebook;
1392                    if(Utils.isEventInTimeWindow(event.name,event,"dyn_facebook_"+eventId)) {
1393                        Facebook.fireEvent(event.name, event);
1394                    }
1395                }
1396
1397                if (events.hasOwnProperty('ga')) {
1398                    event = events.ga;
1399                    if(Utils.isEventInTimeWindow(event.name,event,"dyn_ga_"+eventId)) {
1400                        Analytics.fireEvent(event.name, event);
1401                    }
1402                }
1403
1404                if (events.hasOwnProperty('google_ads')) {
1405                    event = events.google_ads;
1406                    if(Utils.isEventInTimeWindow(event.name,event,"dyn_google_ads_"+eventId)) {
1407                        GAds.fireEvent(event.name, event);
1408                    }
1409                }
1410
1411                if (events.hasOwnProperty('pinterest')) {
1412                    event = events.pinterest;
1413                    if(Utils.isEventInTimeWindow(event.name,event,"dyn_pinterest_"+eventId)) {
1414                        Pinterest.fireEvent(event.name, event);;
1415                    }
1416                }
1417
1418                if (events.hasOwnProperty('bing')) {
1419                    event = events.bing;
1420                    if(Utils.isEventInTimeWindow(event.name,event,"dyn_bing_"+eventId)) {
1421                        Bing.fireEvent(event.name, event);;
1422                    }
1423                }
1424                if (events.hasOwnProperty('tiktok')) {
1425                    event = events.tiktok;
1426                    if(Utils.isEventInTimeWindow(event.name,event,"dyn_bing_"+eventId)) {
1427                        TikTok.fireEvent(event.name, event);
1428                    }
1429                }
1430
1431
1432            },
1433
1434            isFirstPurchaseFire: function ($eventName,orderId,pixel) {
1435
1436                if(Cookies.get("pys_"+$eventName+"_order_id_"+pixel) == orderId) {
1437                    return false;
1438                } else {
1439                    Cookies.set("pys_"+$eventName+"_order_id_"+pixel, orderId, { expires: 1 });
1440                }
1441                return true;
1442            },
1443
1444            fireStaticEvents: function (pixel) {
1445
1446                if (options.staticEvents.hasOwnProperty(pixel)) {
1447
1448                    $.each(options.staticEvents[pixel], function (eventId, events) {
1449
1450                        //skip purchase event if this order was fired
1451                        if( options.woo.hasOwnProperty('woo_purchase_on_transaction') &&
1452                            options.woo.woo_purchase_on_transaction &&
1453                            (eventId === "woo_purchase" || eventId === "woo_purchase_category") ) {
1454                            if(!Utils.isFirstPurchaseFire(eventId,events[0].woo_order,pixel)) {
1455                                return;
1456                            }
1457                        }
1458
1459                        if( options.edd.hasOwnProperty('edd_purchase_on_transaction') &&
1460                            options.edd.edd_purchase_on_transaction &&
1461                            (eventId === "edd_purchase" || eventId === "edd_purchase_category") ) {
1462                            if(!Utils.isFirstPurchaseFire(eventId,events[0].edd_order,pixel)) {
1463                                return;
1464                            }
1465                        }
1466
1467
1468                        $.each(events, function (index, event) {
1469
1470                            event.fired = event.fired || false;
1471
1472                            if (!event.fired && Utils.isEventInTimeWindow(event.name,event,'static_' + pixel+"_")) {
1473
1474
1475                                var fired = false;
1476
1477                                // fire event
1478                                getPixelBySlag(pixel).fireEvent(event.name, event);
1479
1480                                // prevent event double event firing
1481                                event.fired = fired;
1482                            }
1483
1484                        });
1485                    });
1486
1487                }
1488
1489            },
1490
1491            /**
1492             * Load tag's JS
1493             *
1494             * @link: https://developers.google.com/analytics/devguides/collection/gtagjs/
1495             * @link: https://developers.google.com/analytics/devguides/collection/gtagjs/custom-dim
1495s-mets
1496             */
1497            loadGoogleTag: function (id) {
1498
1499                if (!gtag_loaded) {
1500
1501                    (function (window, document, src) {
1502                        var a = document.createElement('script'),
1503                            m = document.getElementsByTagName('script')[0];
1504                        a.async = 1;
1505                        a.src = src;
1506                        m.parentNode.insertBefore(a, m);
1507                    })(window, document, '//www.googletagmanager.com/gtag/js?id=' + id);
1508
1509                    window.dataLayer = window.dataLayer || [];
1510                    window.gtag = window.gtag || function gtag() {
1511                        dataLayer.push(arguments);
1512                    };
1513
1514                    gtag('js', new Date());
1515
1516                    gtag_loaded = true;
1517
1518                }
1519
1520            },
1521
1522            /**
1523             * GDPR
1524             */
1525
1526            loadPixels: function () {
1527
1528                if (options.gdpr.ajax_enabled && !options.gdpr.consent_magic_integration_enabled) {
1529
1530                    // retrieves actual PYS GDPR filters values which allow to avoid cache issues
1531                    $.get({
1532                        url: options.ajaxUrl,
1533                        dataType: 'json',
1534                        data: {
1535                            action: 'pys_get_gdpr_filters_values'
1536                        },
1537                        success: function (res) {
1538
1539                            if (res.success) {
1540
1541                                options.gdpr.all_disabled_by_api = res.data.all_disabled_by_api;
1542                                options.gdpr.facebook_disabled_by_api = res.data.facebook_disabled_by_api;
1543                                options.gdpr.tiktok_disabled_by_api = res.data.tiktok_disabled_by_api;
1544                                options.gdpr.analytics_disabled_by_api = res.data.analytics_disabled_by_api;
1545                                options.gdpr.google_ads_disabled_by_api = res.data.google_ads_disabled_by_api;
1546                                options.gdpr.pinterest_disabled_by_api = res.data.pinterest_disabled_by_api;
1547                                options.gdpr.bing_disabled_by_api = res.data.bing_disabled_by_api;
1548
1549                            }
1550
1551                            loadPixels();
1552
1553                        }
1554                    });
1555
1556                } else {
1557                    loadPixels();
1558                }
1559
1560            },
1561
1562            consentGiven: function (pixel) {
1563
1564                /**
1565                 * Cookiebot
1566                 */
1567                if (options.gdpr.cookiebot_integration_enabled && typeof Cookiebot !== 'undefined') {
1568
1569                    var cookiebot_consent_category = options.gdpr['cookiebot_' + pixel + '_consent_category'];
1570
1571                    if (options.gdpr[pixel + '_prior_consent_enabled']) {
1572                        if (Cookiebot.consented === false || Cookiebot.consent[cookiebot_consent_category]) {
1573                            return true;
1574                        }
1575                    } else {
1576                        if (Cookiebot.consent[cookiebot_consent_category]) {
1577                            return true;
1578                        }
1579                    }
1580
1581                    return false;
1582
1583                }
1584
1585                /**
1586                 * Cookie Notice
1587                 */
1588                if (options.gdpr.cookie_notice_integration_enabled && typeof cnArgs !== 'undefined') {
1589
1590                    var cn_cookie = Cookies.get(cnArgs.cookieName);
1591
1592                    if (options.gdpr[pixel + '_prior_consent_enabled']) {
1593                        if (typeof cn_cookie === 'undefined' || cn_cookie === 'true') {
1594                            return true;
1595                        }
1596                    } else {
1597                        if (cn_cookie === 'true') {
1598                            return true;
1599                        }
1600                    }
1601
1602                    return false;
1603
1604                }
1605
1606                /**
1607                 * Cookie Law Info
1608                 */
1609                if (options.gdpr.cookie_law_info_integration_enabled) {
1610
1611                    var cli_cookie = Cookies.get('viewed_cookie_policy');
1612
1613                    if (options.gdpr[pixel + '_prior_consent_enabled']) {
1614                        if (typeof cli_cookie === 'undefined' || cli_cookie === 'yes') {
1615                            return true;
1616                        }
1617                    } else {
1618                        if (cli_cookie === 'yes') {
1619                            return true;
1620                        }
1621                    }
1622
1623                    return false;
1624
1625                }
1626
1627                /**
1628                 * ConsentMagic
1629                 */
1630                if (options.gdpr.consent_magic_integration_enabled && typeof CS_Data !== "undefined" ) {
1631
1632                    var test_prefix = CS_Data.test_prefix;
1633                    if ((typeof CS_Data.cs_google_analytics_consent_mode !== "undefined" && CS_Data.cs_google_analytics_consent_mode == 1) && pixel == 'analytics') {
1634                        return true;
1635                    }
1636                    if ((typeof CS_Data.cs_google_ads_consent_mode !== "undefined" && CS_Data.cs_google_ads_consent_mode == 1) && pixel == 'google_ads') {
1637                        return true;
1638                    }
1639
1640                    if ( CS_Data.cs_cache_enabled == 1 ) {
1641                        var substring = "cs_enabled_cookie_term";
1642                        var theCookies = document.cookie.split(';');
1643
1644                        for (var i = 1 ; i <= theCookies.length; i++) {
1645                            if ( theCookies[ i - 1 ].indexOf( substring ) !== -1 ) {
1646                                var categoryCookie = theCookies[ i - 1 ].replace( 'cs_enabled_cookie_term' + test_prefix + '_', '' );
1647                                categoryCookie = Number( categoryCookie.replace( /\D+/g, "" ) );
1648                                var cs_cookie_val = Cookies.get( 'cs_enabled_cookie_term' + test_prefix + '_' + categoryCookie );
1649
1650                                if ( categoryCookie === CS_Data.cs_script_cat.facebook && pixel == 'facebook' ) {
1651                                    if ( cs_cookie_val == 'yes' ) {
1652                                        return true;
1653                                    } else {
1654                                        return false;
1655                                    }
1656                                } else if ( categoryCookie === CS_Data.cs_script_cat.bing && pixel == 'bing' ) {
1657                                    if ( cs_cookie_val == 'yes' ) {
1658                                        return true;
1659                                    } else {
1660                                        return false;
1661                                    }
1662                                } else if ( categoryCookie === CS_Data.cs_script_cat.analytics && pixel == 'analytics' ) {
1663                                    if ( cs_cookie_val == 'yes' ) {
1664                                        return true;
1665                                    } else {
1666                                        return false;
1667                                    }
1668                                } else if ( categoryCookie === CS_Data.cs_script_cat.gads && pixel == 'google_ads' ) {
1669                                    if ( cs_cookie_val == 'yes' ) {
1670                                        return true;
1671                                    } else {
1672                                        return false;
1673                                    }
1674                                } else if ( categoryCookie === CS_Data.cs_script_cat.pinterest && pixel == 'pinterest' ) {
1675                                    if ( cs_cookie_val == 'yes' ) {
1676                                        return true;
1677                                    } else {
1678                                        return false;
1679                                    }
1680                                } else if ( categoryCookie === CS_Data.cs_script_cat.tiktok && pixel == 'tiktok' ) {
1681                                    if ( cs_cookie_val == 'yes' ) {
1682                                        return true;
1683                                    } else {
1684                                        return false;
1685                                    }
1686                                }
1687                            }
1688                        }
1689                    } else {
1690                        var cs_cookie = Cookies.get('cs_viewed_cookie_policy'+test_prefix);
1691                        if (typeof cs_cookie === 'undefined' || cs_cookie === 'yes') {
1692                            return true;
1693                        }
1694                    }
1695
1696                    return false;
1697
1698                }
1699
1700
1701                /**
1702                 * Real Cookie Banner
1703                 */
1704                if (options.gdpr.real_cookie_banner_integration_enabled) {
1705                    var consentApi = window.consentApi;
1706                    if (consentApi) {
1707                        switch (pixel) {
1708                            case "analytics":
1709                                return consentApi.consentSync("http", "_ga", "*").cookieOptIn;
1710                            case "facebook":
1711                                return consentApi.consentSync("http", "_fbp", "*").cookieOptIn;
1712                            case "pinterest":
1713                                return consentApi.consentSync("http", "_pinterest_sess", ".pinterest.com").cookieOptIn;
1714                            case "bing":
1715                                return consentApi.consentSync("http", "_uetsid", "*").cookieOptIn;
1716                            case "google_ads":
1717                                return consentApi.consentSync("http", "1P_JAR", ".google.com").cookieOptIn;
1718                            case 'tiktok':
1719                                return consentApi.consentSync("http", "tt_webid_v2", ".tiktok.com").cookieOptIn;
1720                            default:
1721                                return true;
1722                        }
1723                    }
1724                }
1725
1726                return true;
1727
1728            },
1729
1730            setupGdprCallbacks: function () {
1731
1732                /**
1733                 * Cookiebot
1734                 */
1735                if (options.gdpr.cookiebot_integration_enabled && typeof Cookiebot !== 'undefined') {
1736
1737                    window.addEventListener("CookiebotOnConsentReady", function() {
1738                        if (Cookiebot.consent.marketing) {
1739                            Facebook.loadPixel();
1740                            Bing.loadPixel();
1741                            Pinterest.loadPixel();
1742                            GAds.loadPixel();
1743                            TikTok.loadPixel();
1744                        }
1745                        if (Cookiebot.consent.statistics) {
1746                            Analytics.loadPixel();
1747                        }
1748                        if (!Cookiebot.consent.marketing) {
1749                            Facebook.disable();
1750                            Pinterest.disable();
1751                            Bing.disable()
1752                            GAds.disable();
1753                            TikTok.disable();
1754                        }
1755                        if (!Cookiebot.consent.statistics) {
1756                            Analytics.disable();
1757                        }
1758                    });
1759                }
1760
1761                /**
1762                 * Cookie Notice
1763                 */
1764                if (options.gdpr.cookie_notice_integration_enabled) {
1765
1766                    $(document).onFirst('click', '.cn-set-cookie', function () {
1767
1768                        if ($(this).data('cookie-set') === 'accept') {
1769                            Facebook.loadPixel();
1770                            Analytics.loadPixel();
1771                            GAds.loadPixel();
1772                            Pinterest.loadPixel();
1773                            Bing.loadPixel();
1774                            TikTok.loadPixel();
1775                        } else {
1776                            Facebook.disable();
1777                            Analytics.disable();
1778                            GAds.disable();
1779                            Pinterest.disable();
1780                            Bing.disable();
1781                            TikTok.disable();
1782                        }
1783
1784                    });
1785
1786                    $(document).onFirst('click', '.cn-revoke-cookie', function () {
1787                        Facebook.disable();
1788                        Analytics.disable();
1789                        GAds.disable();
1790                        Pinterest.disable();
1791                        Bing.disable();
1792                        TikTok.disable();
1793                    });
1794
1795                }
1796
1797                /**
1798                 * Cookie Law Info
1799                 */
1800                if (options.gdpr.cookie_law_info_integration_enabled) {
1801
1802                    $(document).onFirst('click', '#cookie_action_close_header', function () {
1803                        Facebook.loadPixel();
1804                        Analytics.loadPixel();
1805                        GAds.loadPixel();
1806                        Pinterest.loadPixel();
1807                        Bing.loadPixel();
1808                        TikTok.loadPixel();
1809                    });
1810
1811                    $(document).onFirst('click', '#cookie_action_close_header_reject', function () {
1812                        Facebook.disable();
1813                        Analytics.disable();
1814                        GAds.disable();
1815                        Pinterest.disable();
1816                        Bing.disable();
1817                        TikTok.disable();
1818                    });
1819
1820                }
1821
1822                /**
1823                 * ConsentMagic
1824                 */
1825                if (options.gdpr.consent_magic_integration_enabled && typeof CS_Data !== "undefined") {
1826                    var test_prefix = CS_Data.test_prefix,
1827                        cs_refresh_after_consent = false,
1828                        substring = "cs_enabled_cookie_term";
1829
1830                    if (CS_Data.cs_refresh_after_consent == 1) {
1831                        cs_refresh_after_consent = CS_Data.cs_refresh_after_consent;
1832                    }
1833
1834                    if (!cs_refresh_after_consent) {
1835                        var theCookies = document.cookie.split(';');
1836                        for (var i = 1 ; i <= theCookies.length; i++) {
1837                            if (theCookies[i-1].indexOf(substring) !== -1) {
1838                                var categoryCookie = theCookies[i-1].replace('cs_enabled_cookie_term'+test_prefix+'_','');
1839                                categoryCookie = Number(categoryCookie.replace(/\D+/g,""));
1840                                var cs_cookie_val = Cookies.get('cs_enabled_cookie_term'+test_prefix+'_'+categoryCookie);
1841                                if(cs_cookie_val == 'yes') {
1842                                    if (categoryCookie === CS_Data.cs_script_cat.facebook) {
1843                                        Facebook.loadPixel();
1844                                    }
1845
1846                                    if (categoryCookie === CS_Data.cs_script_cat.bing) {
1847                                        Bing.loadPixel();
1848                                    }
1849                                    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)
1849) {
1850
1851                                        Analytics.loadPixel();
1852                                    }
1853
1854                                    if (categoryCookie === CS_Data.cs_script_cat.gads || (typeof CS_Data.cs_google_ads_consent_mode !== "undefined" && CS_Data.cs_google_ads_consent_mode == 1)) {
1855                                        GAds.loadPixel();
1856                                    }
1857
1858                                    if (categoryCookie === CS_Data.cs_script_cat.pinterest) {
1859                                        Pinterest.loadPixel();
1860                                    }
1861
1862                                    if (categoryCookie === CS_Data.cs_script_cat.tiktok) {
1863                                        TikTok.loadPixel();
1864                                    }
1865                                } else {
1866                                    if (categoryCookie === CS_Data.cs_script_cat.facebook) {
1867                                        Facebook.disable();
1868                                    }
1869
1870                                    if (categoryCookie === CS_Data.cs_script_cat.bing) {
1871                                        Bing.disable();
1872                                    }
1873
1874                                    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)) {
1875                                        Analytics.disable();
1876                                    }
1877
1878                                    if (categoryCookie === CS_Data.cs_script_cat.gads && (typeof CS_Data.cs_google_ads_consent_mode == "undefined" || CS_Data.cs_google_ads_consent_mode == 0)) {
1879                                        GAds.disable();
1880                                    }
1881
1882                                    if (categoryCookie === CS_Data.cs_script_cat.pinterest) {
1883                                        Pinterest.disable();
1884                                    }
1885
1886                                    if (categoryCookie === CS_Data.cs_script_cat.tiktok) {
1887                                        TikTok.disable();
1888                                    }
1889                                }
1890                                if (Cookies.get('cs_enabled_advanced_matching') == 'yes') {
1891                                    Facebook.loadPixel();
1892                                }
1893                            }
1894                        }
1895
1896                        $(document).on('click','.cs_action_btn',function(e) {
1897                            e.preventDefault();
1898                            var elm = $(this),
1899                                button_action = elm.attr('data-cs_action');
1900
1901                            if(button_action === 'allow_all') {
1902                                Facebook.loadPixel();
1903                                Bing.loadPixel();
1904                                Analytics.loadPixel();
1905                                GAds.loadPixel();
1906                                Pinterest.loadPixel();
1907                                TikTok.loadPixel();
1908                            } else if(button_action === 'disable_all') {
1909
1910                                Facebook.disable();
1911                                Bing.disable();
1912                                if(CS_Data.cs_google_analytics_consent_mode == 0 || typeof CS_Data.cs_google_analytics_consent_mode == "undefined")
1913                                {
1914                                    Analytics.disable();
1915                                }
1916                                if(CS_Data.cs_google_ads_consent_mode == 0 || typeof CS_Data.cs_google_ads_consent_mode == "undefined")
1917                                {
1918                                    GAds.disable();
1919                                }
1920                                Pinterest.disable();
1921                                TikTok.disable();
1922                            }
1923                        });
1924                    }
1925                }
1926
1927                /**
1928                 * Real Cookie Banner
1929                 */
1930                if (options.gdpr.real_cookie_banner_integration_enabled) {
1931                    var consentApi = window.consentApi;
1932                    if (consentApi) {
1933                        consentApi.consent("http", "_ga", "*")
1934                            .then(Analytics.loadPixel.bind(Analytics), Analytics.disable.bind(Analytics));
1935
1936                        consentApi.consent("http", "_fbp", "*")
1937                            .then(Facebook.loadPixel.bind(Facebook), Facebook.disable.bind(Facebook));
1938
1939                        consentApi.consent("http", "_pinterest_sess", ".pinterest.com")
1940                            .then(Pinterest.loadPixel.bind(Pinterest), Pinterest.disable.bind(Pinterest));
1941
1942                        consentApi.consent("http", "_uetsid", "*")
1943                            .then(Bing.loadPixel.bind(Bing), Bing.disable.bind(Bing));
1944
1945                        consentApi.consent("http", "1P_JAR", ".google.com")
1946                            .then(GAds.loadPixel.bind(GAds), GAds.disable.bind(GAds));
1947                        consentApi.consent("http", "tt_webid_v2", ".tiktok.com")
1948                            .then(TikTok.loadPixel.bind(TikTok), TikTok.disable.bind(TikTok));
1949                    }
1950                }
1951
1952            },
1953
1954            /**
1955             * Enrich
1956             */
1957            isCheckoutPage: function () {
1958                return $('body').hasClass('woocommerce-checkout') || document.querySelector('.woocommerce-checkout') ||
1959                    $('body').hasClass('edd-checkout');
1960            },
1961            addCheckoutFields : function() {
1962                var utm = "";
1963                var utms = getUTMs()
1964                $.each(utmTerms, function (index, name) {
1965                    if(index > 0) {
1966                        utm+="|";
1967                    }
1968                    utm+=name+":"+utms[name];
1969                });
1970                var utmIdList = "";
1971                var utmsIds = getUTMId()
1972                $.each(utmId, function (index, name) {
1973                    if(index > 0) {
1974                        utmIdList+="|";
1975                    }
1976                    utmIdList+=name+":"+utmsIds[name];
1977                });
1978                var utmIdListLast = "";
1979                var utmsIdsLast = getUTMId(true)
1980                $.each(utmId, function (index, name) {
1981                    if(index > 0) {
1982                        utmIdListLast+="|";
1983                    }
1984                    utmIdListLast+=name+":"+utmsIdsLast[name];
1985                });
1986
1987
1988                var utmLast = "";
1989                var utmsLast = getUTMs(true)
1990                $.each(utmTerms, function (index, name) {
1991                    if(index > 0) {
1992                        utmLast+="|";
1993                    }
1994                    utmLast+=name+":"+utmsLast[name];
1995                });
1996
1997                var dateTime = getDateTime();
1998                var landing = Cookies.get('pys_landing_page');
1999                var lastLanding = Cookies.get('last_pys_landing_page');
2000                var trafic = Cookies.get('pysTrafficSource');
2001                var lastTrafic = Cookies.get('last_pysTrafficSource');
2002
2003                var $form = null;
2004                if($('body').hasClass('woocommerce-checkout')) {
2005                    $form = $("form.woocommerce-checkout");
2006                } else {
2007                    $form = $("#edd_purchase_form");
2008                }
2009                var inputs = {'pys_utm':utm,
2010                    'pys_utm_id':utmIdList,
2011                    'pys_browser_time':dateTime.join("|"),
2012                    'pys_landing':landing,
2013                    'pys_source':trafic,
2014                    'pys_order_type': $(".wcf-optin-form").length > 0 ? "wcf-optin" : "normal",
2015
2016                    'last_pys_landing':lastLanding,
2017                    'last_pys_source':lastTrafic,
2018                    'last_pys_utm':utmLast,
2019                    'last_pys_utm_id':utmIdListLast,
2020                }
2021
2022                Object.keys(inputs).forEach(function(key,index) {
2023                    $form.append("<input type='hidden' name='"+key+"' value='"+inputs[key]+"' /> ");
2024                });
2025
2026
2027            },
2028
2029            /**
2030             * Advanced From Data
2031             */
2032            saveAdvancedFormData: function (email,phone,firstName,lastName) {
2033                let data = Utils.getAdvancedFormData();
2034
2035                if(email != null) {
2036                    data["email"] = email;
2037                }
2038                if(phone != null) {
2039                    data["phone"] = phone;
2040                }
2041                if(firstName != null) {
2042                    data["first_name"] = firstName;
2043                }
2044                if(lastName != null) {
2045                    data["last_name"] = lastName;
2046                }
2047                if(!options.cookie.disabled_advanced_form_data_cookie)
2048                {
2049                    Cookies.set('pys_advanced_form_data', JSON.stringify(data),{ expires: 300 } );
2050                }
2051                else {
2052                    Cookies.remove('pys_advanced_form_data')
2053                }
2054                GAds.updateEnhancedConversionData()
2055
2056            },
2057
2058            getAdvancedFormData: function () {
2059                let dataStr = Cookies.get("pys_advanced_form_data");
2060                if(dataStr === undefined) {
2061                    return {'first_name':"",'last_name':"",'email':"",'phone':""};
2062                } else {
2063                    return JSON.parse(dataStr);
2064                }
2065            }
2066
2067        };
2068
2069    }(options);
2070
2071    var TikTok = function (options) {
2072
2073        var initialized = false;
2074
2075        function fireEvent(name, event) {
2076
2077            if(typeof window.pys_event_data_filter === "function" && window.pys_disable_event_filter(name,'tiktok')) {
2078                return;
2079            }
2080            var params = Utils.copyProperties(event.params, {});
2081
2082                event.pixelIds.forEach(function(pixelId){
2083                    if (options.debug) {
2084                        console.log('[TikTok] ' + name, params,"pixel_id",pixelId);
2085                    }
2086                    ttq.instance(pixelId).track(name,params)
2087                });
2088        }
2089
2090        return {
2091            tag: function() {
2092                return "tiktok";
2093            },
2094            isEnabled: function () {
2095                return options.hasOwnProperty('tiktok');
2096            },
2097            disable: function () {
2098                initialized = false;
2099            },
2100
2101            loadPixel:function () {
2102                if (initialized || !this.isEnabled() || !Utils.consentGiven('tiktok')) {
2103                    return;
2104                }
2105                !function (w, d, t) {
2106                    w.TiktokAnalyticsObject=t;
2107                    var ttq=w[t]=w[t]||[];
2108                    ttq.methods=["page","track","identify","instances","debug","on","off","once","ready","alias","group","enableCookie","disableCookie"];
2109                    ttq.setAndDefer=function(t,e){t[e]=function(){t.push([e].concat(Array.prototype.slice.call(arguments,0)))}};
2110                    for(var i=0;i<ttq.methods.length;i++)
2111                        ttq.setAndDefer(ttq,ttq.methods[i]);
2112                    ttq.instance=function(t){for(var e=ttq._i[t]||[],n=0;n<ttq.methods.length;n++)ttq.setAndDefer(e,ttq.methods[n]);return e};
2113                    ttq.load=function(e,n){var i="https://analytics.tiktok.com/i18n/pixel/events.js";ttq._i=ttq._i||{},ttq._i[e]=[],ttq._i[e]._u=i,ttq._t=ttq._t||{},ttq._t[e]=+new Date,ttq._o=ttq._o||{},ttq._o[e]=n||{};var o=document.createElement("script");o.type="text/javascript",o.async=!0,o.src=i+"?sdkid="+e+"&lib="+t;var a=document.getElementsByTagName("script")[0];a.parentNode.insertBefore(o,a)};
2114
2115                    //ttq.load('C60QSCQRVDG9JAKNPK2G');
2116                    //ttq.page();
2117                }(window, document, 'ttq');
2118
2119                options.tiktok.pixelIds.forEach(function (pixelId) {
2120
2121                    ttq.load(pixelId);
2122                    ttq.page();
2123                    let advancedMatching = {};
2124                    if(options.tiktok.hasOwnProperty('advanced_matching')
2125                        && Object.keys(options.tiktok.advanced_matching).length > 0) {
2126                        advancedMatching = options.tiktok.advanced_matching;
2127                        if(!advancedMatching.hasOwnProperty("external_id")){
2128                            if (Cookies.get('pbid')) {
2129                                advancedMatching["external_id"] = Cookies.get('pbid');
2130                            }
2131                        }
2132                        ttq.instance(pixelId).identify(advancedMatching)
2133                    }
2134                });
2135                initialized = true;
2136
2137                if (options.staticEvents.hasOwnProperty('tiktok')) {
2138                    setTimeout(function () {
2139                        Utils.fireStaticEvents('tiktok');
2140                    }, 1500)
2141                }
2142            },
2143
2144            fireEvent: function (name, data) {
2145                if (!initialized || !this.isEnabled()) {
2146                    return false;
2147                }
2148                data.delay = data.delay || 0;
2149
2150                if (data.delay === 0) {
2151                    fireEvent(name, data);
2152                } else {
2153                    setTimeout(function (name, params) {
2154                        fireEvent(name, params);
2155                    }, data.delay * 1000, name, data);
2156                }
2157                return true;
2158            },
2159
2160            onClickEvent: function (event) {
2161                this.fireEvent(event.name, event);
2162            },
2163
2164            onWooAddToCartOnSingleEvent: function (product_id, qty, product_type, is_external, $form) {
2165
2166                window.pysWooProductData = window.pysWooProductData || [];
2167                if (!options.dynamicEvents.woo_add_to_cart_on_button_click.hasOwnProperty(this.tag()))
2168                    return;
2169
2170                if (window.pysWooProductData.hasOwnProperty(product_id)) {
2171                    if (window.pysWooProductData[product_id].hasOwnProperty(this.tag())) {
2172
2173                        var event = Utils.clone(options.dynamicEvents.woo_add_to_cart_on_button_click[this.tag()]);
2174
2175                        Utils.copyProperties(window.pysWooProductData[product_id][this.tag()]['params'], event.params);
2176
2177                        // maybe customize value option
2178                        if (options.woo.addToCartOnButtonValueEnabled && options.woo.addToCartOnButtonValueOption !== 'global') {
2179
2180                            if (product_type === Utils.PRODUCT_BUNDLE) {
2181                                var data = $(".bundle_form .bundle_data").data("bundle_form_data");
2182                                var items_sum = getBundlePriceOnSingleProduct(data);
2183                                event.params.value = (parseFloat(data.base_price) + items_sum) * qty;
2184                            } else {
2185                                event.params.value = event.params.value * qty;
2186                            }
2187                        }
2188
2189                        event.params.quantity = qty;
2190
2191                        this.fireEvent(event.name, event);
2192
2193                    }
2194                }
2195            },
2196
2197            onWooAddToCartOnButtonEvent: function (product_id) {
2198                if(!options.dynamicEvents.woo_add_to_cart_on_button_click.hasOwnProperty(this.tag()))
2199                    return;
2200
2201                if (window.pysWooProductData.hasOwnProperty(product_id)) {
2202                    if (window.pysWooProductData[product_id].hasOwnProperty(this.tag())) {
2203                        var productData = window.pysWooProductData[product_id][this.tag()]
2204                        var event = Utils.clone(options.dynamicEvents.woo_add_to_cart_on_button_click[this.tag()])
2205
2206                        Utils.copyProperties(productData['params'], event.params)
2207                        event.pixelIds = productData['pixelIds'];
2208                        this.fireEvent(event.name, event);
2209                    }
2210                }
2211            },
2212
2213            onEddAddToCartOnButtonEvent : function (download_id, price_index, qty) {
2214                if(!options.dynamicEvents.edd_add_to_cart_on_button_click.hasOwnProperty(this.tag()))
2215                    return;
2216                var event = Utils.clone(options.dynamicEvents.edd_add_to_cart_on_button_click[this.tag()]);
2217
2218
2219                if (window.pysEddProductData.hasOwnProperty(download_id)) {
2220
2221                    var index;
2222
2223                    if (price_index) {
2224                        index = download_id + '_' + price_index;
2225                    } else {
2226                        index = download_id;
2227                    }
2228
2229                    if (window.pysEddProductData[download_id].hasOwnProperty(index)) {
2230                        if (window.pysEddProductData[download_id][index].hasOwnProperty(this.tag())) {
2231
2232                            Utils.copyProperties(window.pysEddProductData[download_id][index][this.tag()].params, event.params);
2233                            this.fireEvent(event.name,event);
2234
2235                        }
2236                    }
2237
2238                }
2239            }
2240        }
2241    }(options);
2242
2243    var Facebook = function (options) {
2244
2245        var defaultEventTypes = [
2246            'PageView',
2247            'ViewContent',
2248            'Search',
2249            'AddToCart',
2250            'AddToWishlist',
2251            'InitiateCheckout',
2252            'AddPaymentInfo',
2253            'Purchase',
2254            'Lead',
2255
2256            'Subscribe',
2257            'CustomizeProduct',
2258            'FindLocation',
2259            'StartTrial',
2260            'SubmitApplication',
2261            'Schedule',
2262            'Contact',
2263            'Donate'
2264        ];
2265
2266        var notCachedEventsIds = new Array();
2267        var isAddToCartFromJs =  options.woo.hasOwnProperty("addToCartCatchMethod")
2268                                && options.woo.addToCartCatchMethod === "add_cart_js";
2269        if(!isAddToCartFromJs) {
2270            notCachedEventsIds.push('woo_add_to_cart_on_button_click')
2271        }
2272        var initialized = false;
2273        var configuredPixels = new Array();
2274        function fireEvent(name, event) {
2275
2276
2277            if(typeof window.pys_event_data_filter === "function" && window.pys_disable_event_filter(name,'facebook')) {
2278                return;
2279            }
2280
2281            var data = event.params;
2282            var ids = event.pixelIds;
2283            var actionType = defaultEventTypes.includes(name) ? 'trackSingle' : 'trackSingleCustom';
2284
2285            var params = {};
2286
2287            Utils.copyProperties(data, params);
2288            Utils.copyProperties(Utils.getRequestParams(), params);
2289
2290
2291            if(options.facebook.serverApiEnabled) {
2292                if(event.e_id === "woo_remove_from_cart" ) {
2293                    Facebook.updateEventId(event.name);
2294                    event.eventID = Facebook.getEventId(event.name);
2295                } else if(isAddToCartFromJs && event.e_id === "woo_add_to_cart_on_button_click" ) {
2296                    Facebook.updateEventId(event.name);
2297                    event.eventID = Facebook.getEventId(event.name);
2298                } else if(!notCachedEventsIds.includes(event.e_id)) {
2299                    var isApiDisabled = options.gdpr.all_disabled_by_api ||
2300                        options.gdpr.facebook_disabled_by_api ||
2301                        options.gdpr.tiktok_disabled_by_api ||
2302                        options.gdpr.cookiebot_integration_enabled ||
2303                        options.gdpr.cookie_notice_integration_enabled ||
2304                        options.gdpr.consent_magic_integration_enabled ||
2305                        options.gdpr.cookie_law_info_integration_enabled;
2306                    // Update eventID
2307
2308                    if( options.ajaxForServerEvent || event.type !== "static") {
2309                        event.eventID = pys_generate_token(36);
2310                    }
2311
2312                    // send event from server if they was bloc by gdpr or need send with delay
2313                    if( options.ajaxForServerEvent || isApiDisabled || event.delay > 0 || event.type !== "static" ){
2314
2315                        var json = {
2316                            action: 'pys_api_event',
2317                            pixel: 'facebook',
2318                            event: name,
2319                            ids: ids,
2320                            data:params,
2321                            url:window.location.href,
2322                            eventID:event.eventID,
2323                            ajax_event:options.ajax_event
2324                        };
2325
2326                        if(event.hasOwnProperty('woo_order')) {
2327                            json['woo_order'] = event.woo_order;
2328                        }
2329
2330                        if(event.hasOwnProperty('edd_order')) {
2331                            json['edd_order'] = event.edd_order;
2332                        }
2333                        if(event.e_id === "automatic_event_internal_link"
2334                            || event.e_id === "automatic_event_outbound_link"
2335                        ) {
2336                            setTimeout(function(){
2337                                jQuery.ajax( {
2338                                    type: 'POST',
2339                                    url: options.ajaxUrl,
2340                                    data: json,
2341                                    headers: {
2342                                        'Cache-Control': 'no-cache'
2343                                    },
2344                                    success: function(){},
2345                                });
2346                            },500)
2347                        } else if(name == 'PageView') {
2348                            let expires = parseInt(options.cookie_duration);
2349                            var currentTimeInSeconds=Date.now();
2350                            var randomNum = Math.floor(1000000000 + Math.random() * 9000000000);
2351                            timeoutDelay = 0;
2352
2353                            if(!Cookies.get('_fbp'))
2354                            {
2355                                timeoutDelay = 100;
2356                            }
2357                            if(getUrlParameter('fbclid') && !Cookies.get('_fbc'))
2358                            {
2359                                timeoutDelay = 100;
2360                            }
2361                            setTimeout(function(){
2362                                if(!Cookies.get('_fbp'))
2363                                {
2364                                    Cookies.set('_fbp','fb.1.'+currentTimeInSeconds+'.'+randomNum,  { expires: expires })
2365                                }
2366                                if(getUrlParameter('fbclid') && !Cookies.get('_fbc'))
2367                                {
2368                                    Cookies.set('_fbc', 'fb.1.'+currentTimeInSeconds+'.'+getUrlParameter('fbclid'),  { expires: expires })
2369                                }
2370                                jQuery.ajax( {
2371                                    type: 'POST',
2372                                    url: options.ajaxUrl,
2373                                    data: json,
2374                                    headers: {
2375                                        'Cache-Control': 'no-cache'
2376                                    },
2377                                    success: function(){},
2378                                });
2379                            },timeoutDelay)
2380                        }
2381                        else
2382                        {
2383                            jQuery.ajax( {
2384                                type: 'POST',
2385                                url: options.ajaxUrl,
2386                                data: json,
2387                                headers: {
2388                                    'Cache-Control': 'no-cache'
2389                                },
2390                                success: function(){},
2391                            });
2392                        }
2393
2394
2395                    }
2396
2397                    if( event.e_id !== "automatic_event_signup" && name == "CompleteRegistration" && options.facebook.wooCRSendFromServer ) {
2398                        return;
2399                    }
2400                }
2401
2402            }
2403
2404
2405
2406            if (options.debug) {
2407                console.log('[Facebook] ' + name, params,"pixel_ids",ids,"eventID",event.eventID);
2408            }
2409            // fire event for each pixel id
2410            ids.forEach(function (pixelId) {
2411                // add eventID for deduplicate events @see https://developers.facebook.com/docs/marketing-api/conversions-api/deduplicate-pixel-and-server-events/
2412                var args = {};
2413                if(options.facebook.serverApiEnabled && event.hasOwnProperty('eventID')) {
2414                    args.eventID = pixelId+event.eventID;
2415                }
2416
2417                Facebook.maybeInitPixel(pixelId);
2418                fbq(actionType,pixelId, name, params,args);
2419            });
2420
2421        }
2422
2423        /**
2424         * Public API
2425         */
2426        return {
2427            tag: function() {
2428              return "facebook";
2429            },
2430            isEnabled: function () {
2431                return options.hasOwnProperty('facebook');
2432            },
2433
2434            initEventIdCookies: function (key) {
2435                var ids = {};
2436                ids[key] = pys_generate_token(36)
2437                Cookies.set('pys_fb_event_id', JSON.stringify(ids));
2438            },
2439
2440            updateEventId:function(key) {
2441                var cooData = Cookies.get("pys_fb_event_id")
2442                if(cooData === undefined) {
2443                    this.initEventIdCookies(key);
2444                } else {
2445                    var data = JSON.parse(cooData);
2446                    data[key] = pys_generate_token(36);
2447                    Cookies.set('pys_fb_event_id', JSON.stringify(data) );
2448                }
2449            },
2450
2451            getEventId:function (key) {
2452                var data = Cookies.get("pys_fb_event_id");
2453                if(data === undefined) {
2454                    this.initEventIdCookies(key);
2455                    data = Cookies.get("pys_fb_event_id");
2456                }
2457                return JSON.parse(data)[key];
2458            },
2459
2460            disable: function () {
2461                initialized = false;
2462            },
2463
2464            /**
2465             * Load pixel's JS
2466             */
2467            loadPixel: function () {
2468
2469                if (initialized || !this.isEnabled() || !Utils.consentGiven('facebook')) {
2470                    return;
2471                }
2472
2473                ! function (f, b, e, v, n, t, s) {
2474                    if (f.fbq) return;
2475                    n = f.fbq = function () {
2476                        n.callMethod ?
2477                            n.callMethod.apply(n, arguments) : n.queue.push(arguments)
2478                    };
2479                    if (!f._fbq) f._fbq = n;
2480                    n.push = n;
2481                    n.loaded = !0;
2482                    n.version = '2.0';
2483                    n.agent = 'dvpixelyoursite';
2484                    n.queue = [];
2485                    t = b.createElement(e);
2486                    t.async = !0;
2487                    t.src = v;
2488                    s = b.getElementsByTagName(e)[0];
2489                    s.parentNode.insertBefore(t, s)
2490                }(window,
2491                    document, 'script', 'https://connect.facebook.net/en_US/fbevents.js');
2492
2493                // initialize default pixel
2494                options.facebook.pixelIds.forEach(function (pixelId) {
2495                    Facebook.maybeInitPixel(pixelId);
2496                });
2497                initialized = true;
2498
2499                Utils.fireStaticEvents('facebook');
2500
2501            },
2502            advancedMatching: function () {
2503                if(options.facebook.advancedMatchingEnabled) {
2504                    let advancedMatchingForm = Utils.getAdvancedFormData();
2505                    let advancedMatching = {};
2506                    if(Object.keys(options.facebook.advancedMatching).length > 0) {
2507                        advancedMatching = options.facebook.advancedMatching;
2508                    }
2509
2510                    if(!advancedMatching.hasOwnProperty("em")
2511                        && advancedMatchingForm.hasOwnProperty("email") && advancedMatchingForm["email"].length > 0) {
2512                        advancedMatching["em"] = advancedMatchingForm["email"];
2513                    }
2514                    if(!advancedMatching.hasOwnProperty("ph")
2515                        && advancedMatchingForm.hasOwnProperty("phone") && advancedMatchingForm["phone"].length > 0) {
2516                        advancedMatching["ph"] = advancedMatchingForm["phone"];
2517                    }
2518                    if(!advancedMatching.hasOwnProperty("fn")
2519                        && advancedMatchingForm.hasOwnProperty("first_name") && advancedMatchingForm["first_name"].length > 0) {
2520                        advancedMatching["fn"] = advancedMatchingForm["first_name"];
2521                    }
2522                    if(!advancedMatching.hasOwnProperty("ln")
2523                        && advancedMatchingForm.hasOwnProperty("last_name") && advancedMatchingForm["last_name"].length > 0) {
2524                        advancedMatching["ln"] = advancedMatchingForm["last_name"];
2525                    }
2526                    if(!advancedMatching.hasOwnProperty("external_id")){
2527                        if (Cookies.get('pbid')) {
2528                            advancedMatching["external_id"] = Cookies.get('pbid');
2529                        }
2530                    }
2531
2532                    if(Object.keys(advancedMatching).length > 0) {
2533                        return advancedMatching;
2534                    }
2535                }
2536                return false
2537            },
2538            maybeInitPixel: function(pixelId) {
2539
2540                if(configuredPixels.includes(pixelId)) return;
2541
2542                if (options.facebook.removeMetadata) {
2543                    fbq('set', 'autoConfig', false, pixelId);
2544                }
2545                let advancedMatching = Facebook.advancedMatching();
2546
2547                if (options.gdpr.consent_magic_integration_enabled && typeof CS_Data !== "undefined") {
2548                    if(!advancedMatching) {
2549                        fbq('init', pixelId);
2550                    } else {
2551                        var cs_advanced_matching = Cookies.get('cs_enabled_advanced_matching'+test_prefix);
2552                        if (jQuery('#cs_enabled_advanced_matching'+test_prefix).length > 0) {
2553                            if (cs_advanced_matching == 'yes') {
2554                                fbq('init', pixelId, advancedMatching);
2555                            } else {
2556                                fbq('init', pixelId);
2557                            }
2558                        } else {
2559                            fbq('init', pixelId, advancedMatching);
2560                        }
2561                    }
2562                } else {
2563                    if(!advancedMatching) {
2564                        fbq('init', pixelId);
2565                    }  else {
2566                        fbq('init', pixelId, advancedMatching);
2567                    }
2568                }
2569                configuredPixels.push(pixelId);
2570            },
2571
2572            fireEvent: function (name, data) {
2573
2574                if (!initialized || !this.isEnabled()) {
2575                    return false;
2576                }
2577
2578                data.delay = data.delay || 0;
2579                data.params = data.params || {};
2580
2581                if (data.delay === 0) {
2582
2583                    fireEvent(name, data);
2584
2585                } else {
2586
2587                    setTimeout(function (name, params) {
2588                        fireEvent(name, params);
2589                    }, data.delay * 1000, name, data);
2590
2591                }
2592
2593                return true;
2594
2595            },
2596
2597            onAdSenseEvent: function (event) {
2598                this.fireEvent(event.name, event);
2599            },
2600
2601            onClickEvent: function (event) {
2602                this.fireEvent(event.name, event);
2603            },
2604
2605            onWatchVideo: function (event) {
2606                this.fireEvent(event.name, event);
2607            },
2608
2609            onCommentEvent: function (event) {
2610                this.fireEvent(event.name, event);
2611            },
2612
2613            onFormEvent: function (event) {
2614                this.fireEvent(event.name, event);
2615            },
2616
2617            onDownloadEvent: function (event) {
2618                this.fireEvent(event.name, event);
2619
2620            },
2621
2622
2623            onWooAddToCartOnButtonEvent: function (product_id) {
2624                if(!options.dynamicEvents.woo_add_to_cart_on_button_click.hasOwnProperty(this.tag()))
2625                    return;
2626
2627                if (window.pysWooProductData.hasOwnProperty(product_id)) {
2628                    if (window.pysWooProductData[product_id].hasOwnProperty('facebook')) {
2629
2630                        var event = Utils.clone(options.dynamicEvents.woo_add_to_cart_on_button_click[this.tag()])
2631
2632                        Utils.copyProperties(window.pysWooProductData[product_id]['facebook']['params'], event.params)
2633                        event.pixelIds = window.pysWooProductData[product_id]['facebook']['pixelIds'];
2634                        this.fireEvent(event.name, event);
2635                    }
2636                }
2637            },
2638
2639            onWooAddToCartOnSingleEvent: function (product_id, qty, product_type, is_external, $form) {
2640
2641                window.pysWooProductData = window.pysWooProductData || [];
2642                if(!options.dynamicEvents.woo_add_to_cart_on_button_click.hasOwnProperty(this.tag()))
2643                    return;
2644
2645                if (product_type === Utils.PRODUCT_VARIABLE && !options.facebook.wooVariableAsSimple) {
2646                    product_id = parseInt($form.find('input[name="variation_id"]').val());
2647                }
2648
2649                if (window.pysWooProductData.hasOwnProperty(product_id)) {
2650                    if (window.pysWooProductData[product_id].hasOwnProperty('facebook')) {
2651
2652                        var event = Utils.clone(options.dynamicEvents.woo_add_to_cart_on_button_click.facebook);
2653
2654
2655                        Utils.copyProperties(window.pysWooProductData[product_id]['facebook']['params'], event.params);
2656
2657                        var groupValue = 0;
2658                        if(product_type === Utils.PRODUCT_GROUPED ) {
2659                            $form.find(".woocommerce-grouped-product-list .qty").each(function(index){
2660                                var childId = $(this).attr('name').replaceAll("quantity[","").replaceAll("]","");
2661                                var quantity = parseInt($(this).val());
2662                                if(isNaN(quantity)) {
2663                                    quantity = 0;
2664                                }
2665                                var childItem = window.pysWooProductData[product_id]['facebook'].grouped[childId];
2666
2667                                if(quantity == 0) {
2668                                    event.params.content_ids.forEach(function(el,index,array) {
2669                                        if(el == childItem.content_id) {
2670                                            array.splice(index, 1);
2671                                        }
2672                                    });
2673                                }
2674
2675                                if(event.params.hasOwnProperty('contents')) {
2676                                    event.params.contents.forEac
2676h(function(el,index,array) {
2677                                        if(el.id == childItem.content_id) {
2678                                            if(quantity > 0){
2679                                                el.quantity = quantity;
2680                                            } else {
2681                                                array.splice(index, 1);
2682                                            }
2683                                        }
2684                                    });
2685                                }
2686
2687
2688                                groupValue += childItem.price * quantity;
2689                            });
2690                            if(groupValue == 0) return; // skip if no items selected
2691                        }
2692
2693
2694
2695                        // maybe customize value option
2696                        if (options.woo.addToCartOnButtonValueEnabled && options.woo.addToCartOnButtonValueOption !== 'global') {
2697
2698                            if(product_type === Utils.PRODUCT_GROUPED) {
2699                                    event.params.value = groupValue;
2700                            } else if(product_type === Utils.PRODUCT_BUNDLE) {
2701                                var data = $(".bundle_form .bundle_data").data("bundle_form_data");
2702                                var items_sum = getBundlePriceOnSingleProduct(data);
2703                                event.params.value = (parseFloat(data.base_price) + items_sum )* qty;
2704                            } else {
2705                                event.params.value = event.params.value * qty;
2706                            }
2707                        }
2708
2709                        // only when non Facebook for WooCommerce logic used
2710                        if (event.params.hasOwnProperty('contents') && product_type !== Utils.PRODUCT_GROUPED) {
2711                            event.params.contents[0].quantity = qty;
2712
2713                        }
2714
2715                        var event_name = is_external ? options.woo.affiliateEventName : event.name;
2716
2717                        this.fireEvent(event_name, event);
2718
2719                    }
2720                }
2721
2722            },
2723
2724            onWooRemoveFromCartEvent: function (event) {
2725                this.fireEvent(event.name, event);
2726            },
2727
2728            onWooAffiliateEvent: function (product_id) {
2729                if(!options.dynamicEvents.woo_affiliate.hasOwnProperty(this.tag()))
2730                    return;
2731                var event = Utils.clone(options.dynamicEvents.woo_affiliate[this.tag()]);
2732
2733
2734                if (window.pysWooProductData.hasOwnProperty(product_id)) {
2735                    if (window.pysWooProductData[product_id].hasOwnProperty('facebook')) {
2736
2737                        Utils.copyProperties(window.pysWooProductData[product_id][this.tag()].params, event.params)
2738                        this.fireEvent(options.woo.affiliateEventName, event);
2739
2740                    }
2741                }
2742
2743            },
2744
2745            onWooPayPalEvent: function (event) {
2746                this.fireEvent(event.name, event);
2747            },
2748
2749            onEddAddToCartOnButtonEvent: function (download_id, price_index, qty) {
2750                if(!options.dynamicEvents.edd_add_to_cart_on_button_click.hasOwnProperty(this.tag()))
2751                    return;
2752                var event = Utils.clone(options.dynamicEvents.edd_add_to_cart_on_button_click[this.tag()]);
2753
2754                if (window.pysEddProductData.hasOwnProperty(download_id)) {
2755
2756                    var index;
2757
2758                    if (price_index) {
2759                        index = download_id + '_' + price_index;
2760                    } else {
2761                        index = download_id;
2762                    }
2763
2764                    if (window.pysEddProductData[download_id].hasOwnProperty(index)) {
2765                        if (window.pysEddProductData[download_id][index].hasOwnProperty('facebook')) {
2766
2767
2768                            Utils.copyProperties(window.pysEddProductData[download_id][index]['facebook']["params"], event.params)
2769
2770                            // maybe customize value option
2771                            if (options.edd.addToCartOnButtonValueEnabled && options.edd.addToCartOnButtonValueOption !== 'global') {
2772                                event.params.value = event.params.value * qty;
2773                            }
2774
2775                            // update contents qty param
2776                            var contents = event.params.contents;
2777                            contents[0].quantity = qty;
2778                            event.params.contents = JSON.stringify(contents);
2779
2780                            this.fireEvent(event.name,event);
2781
2782                        }
2783                    }
2784
2785                }
2786
2787            },
2788
2789            onEddRemoveFromCartEvent: function (event) {
2790                this.fireEvent(event.name, event);
2791            },
2792            onPageScroll: function (event) {
2793                this.fireEvent(event.name, event);
2794            },
2795            onTime: function (event) {
2796                this.fireEvent(event.name, event);
2797            },
2798        };
2799
2800    }(options);
2801
2802    var Analytics = function (options) {
2803
2804        var initialized = false;
2805
2806        /**
2807         * Fires event
2808         *
2809         * @link: https://developers.google.com/analytics/devguides/collection/gtagjs/sending-data
2810         * @link: https://developers.google.com/analytics/devguides/collection/gtagjs/events
2811         * @link: https://developers.google.com/gtagjs/reference/event
2812         * @link: https://developers.google.com/gtagjs/reference/parameter
2813         *
2814         * @link: https://developers.google.com/analytics/devguides/collection/gtagjs/custom-dim
2814s-mets
2815         *
2816         * @param name
2817         * @param data
2818         */
2819        function fireEvent(name, data) {
2820            if(typeof window.pys_event_data_filter === "function" && window.pys_disable_event_filter(name,'ga')) {
2821                return;
2822            }
2823
2824            var eventParams = Utils.copyProperties(data.params, {});
2825            Utils.copyProperties(Utils.getRequestParams(), eventParams);
2826
2827            var _fireEvent = function (tracking_id,name,params) {
2828
2829                params['send_to'] = tracking_id;
2830                if (options.debug) {
2831                    console.log('[Google Analytics #' + tracking_id + '] ' + name, params);
2832                }
2833
2834                gtag('event', name, params);
2835
2836            };
2837
2838            data.trackingIds.forEach(function (tracking_id) {
2839                var copyParams = Utils.copyProperties(eventParams, {}); // copy params because mapParamsTov4 can modify it
2840                var params = mapParamsTov4(tracking_id,name,copyParams)
2841                _fireEvent(tracking_id, name, params);
2842            });
2843
2844        }
2845
2846        function normalizeEventName(eventName) {
2847
2848            var matches = {
2849                ViewContent: 'view_item',
2850                AddToCart: 'add_to_cart',
2851                AddToWishList: 'add_to_wishlist',
2852                InitiateCheckout: 'begin_checkout',
2853                Purchase: 'purchase',
2854                Lead: 'generate_lead',
2855                CompleteRegistration: 'sign_up',
2856                AddPaymentInfo: 'set_checkout_option'
2857            };
2858
2859            return matches.hasOwnProperty(eventName) ? matches[eventName] : eventName;
2860
2861        }
2862
2863        function mapParamsTov4(tag,name,param) {
2864            //GA4 automatically collects a number of parameters for all events
2865            delete param.page_title;
2866            delete param.event_url;
2867            delete param.landing_page;
2868            // end
2869            if(isv4(tag)) {
2870                delete param.traffic_source;
2871                delete param.event_category;
2872                delete param.event_label;
2873                delete param.ecomm_prodid;
2874                delete param.ecomm_pagetype;
2875                delete param.ecomm_totalvalue;
2876                delete param.non_interaction;
2877                if(name === 'search') {
2878                    param['search'] = param.search_term;
2879                    delete param.search_term;
2880                    delete param.non_interaction;
2881                    delete param.dynx_itemid;
2882                    delete param.dynx_pagetype;
2883                    delete param.dynx_totalvalue;
2884                }
2885            } else {
2886
2887                switch (name) {
2888                    case 'OutboundClick':
2889                    case 'InternalClick': {
2890                        let params = {
2891                            event_category: "Key Actions",
2892                            event_action: name,
2893                            non_interaction: param.non_interaction,
2894                        }
2895                        if(param.hasOwnProperty("target_url")) {
2896                            params['event_label'] = param.target_url
2897                        }
2898                        if(options.trackTrafficSource) {
2899                            params['traffic_source'] = param.traffic_source
2900                        }
2901                        return params;
2902                    }
2903
2904                    case 'AdSense' :
2905                    case 'Comment' :
2906                    case 'login' :
2907                    case 'sign_up' :
2908                    case 'EmailClick' :
2909                    case 'TelClick' : {
2910                        let params = {
2911                            event_category: "Key Actions",
2912                            event_action: name,
2913                              non_interaction: param.non_interaction,
2914                        }
2915                        return params;
2916                    }
2917                    case 'Form' : {
2918                        let params = {
2919                            event_category: "Key Actions",
2920                            event_action: name,
2921                              non_interaction: param.non_interaction,
2922                        }
2923                        var formClass = (typeof param.form_class != 'undefined') ? 'class: ' + param.form_class : '';
2924                        if(formClass != "") {
2925                            params["event_label"] = formClass;
2926                        }
2927                        return params;
2928                    }
2929                    case 'Download' : {
2930                        let params = {
2931                            event_category: "Key Actions",
2932                            event_action: name,
2933                            event_label: param.download_name,
2934                              non_interaction: param.non_interaction,
2935                        }
2936                        return params;
2937                    }
2938                    case 'TimeOnPage' :
2939                    case 'PageScroll' : {
2940                        let params = {
2941                            event_category: "Key Actions",
2942                            event_action: name,
2943                            event_label: document.title,
2944                              non_interaction: param.non_interaction,
2945                        }
2946                        return params;
2947                    }
2948                    case 'search' : {
2949                        let params = {
2950                            event_category: "Key Actions",
2951                            event_action: name,
2952                            event_label: param.search_term,
2953                              non_interaction: param.non_interaction,
2954                        }
2955                        return params;
2956                    }
2957                }
2958
2959                //delete standard params
2960
2961                delete param.post_type;
2962                delete param.post_id;
2963                delete param.plugin;
2964                delete param.user_role;
2965                delete param.cartlows;
2966                delete param.cartflows_flow;
2967                delete param.cartflows_step;
2968            }
2969            return param;
2970        }
2971
2972        function isv4(tag) {
2973            return tag.indexOf('G') === 0;
2974        }
2975
2976        /**
2977         * Public API
2978         */
2979        return {
2980            tag: function() {
2981                return "ga";
2982            },
2983            isEnabled: function () {
2984                return options.hasOwnProperty('ga');
2985            },
2986
2987            disable: function () {
2988                initialized = false;
2989            },
2990
2991            loadPixel: function () {
2992
2993                if (initialized || !this.isEnabled() || !Utils.consentGiven('analytics')) {
2994                    return;
2995                }
2996
2997                Utils.loadGoogleTag(options.ga.trackingIds[0]);
2998
2999                var cd = {
3000                    'dimension1': 'event_hour',
3001                    'dimension2': 'event_day',
3002                    'dimension3': 'event_month'
3003                };
3004
3005                // configure Dynamic Remarketing CDs
3006                if (options.ga.retargetingLogic === 'ecomm') {
3007                    cd.dimension4 = 'ecomm_prodid';
3008                    cd.dimension5 = 'ecomm_pagetype';
3009                    cd.dimension6 = 'ecomm_totalvalue';
3010                } else {
3011                    cd.dimension4 = 'dynx_itemid';
3012                    cd.dimension5 = 'dynx_pagetype';
3013                    cd.dimension6 = 'dynx_totalvalue';
3014                }
3015
3016                var config = {
3017                    'link_attribution': options.ga.enhanceLinkAttr,
3018                    'anonymize_ip': options.ga.anonimizeIP,
3019                    'custom_map': cd
3020                };
3021
3022                if(options.user_id && options.user_id != 0) {
3023                    config.user_id = options.user_id;
3024                }
3025
3026                // Cross-Domain tracking
3027                if (options.ga.crossDomainEnabled) {
3028                    config.linker = {
3029                        accept_incoming: options.ga.crossDomainAcceptIncoming,
3030                        domains: options.ga.crossDomainDomains
3031                    };
3032                }
3033
3034
3035
3036                // configure tracking ids
3037
3038                options.ga.trackingIds.forEach(function (trackingId,index) {
3039
3040                    var obj = options.ga.isDebugEnabled;
3041                    var searchValue = "index_"+index;
3042                    config.debug_mode = false;
3043
3044                    for (var key in obj) {
3045                        if (obj.hasOwnProperty(key) && obj[key] === searchValue) {
3046                            config.debug_mode = true;
3047                            break;
3048                        }
3049                    }
3050                    if(isv4(trackingId)) {
3051                        if(options.ga.disableAdvertisingFeatures) {
3052                            config.allow_google_signals = false
3053                        }
3054                        if(options.ga.disableAdvertisingPersonalization) {
3055                            config.allow_ad_personalization_signals = false
3056                        }
3057                    }
3058
3059                    if (options.gdpr.cookiebot_integration_enabled && typeof Cookiebot !== 'undefined') {
3060
3061                        var cookiebot_consent_category = options.gdpr['cookiebot_analytics_consent_category'];
3062                        if (options.gdpr['analytics_prior_consent_enabled']) {
3063                            if (Cookiebot.consented === true && Cookiebot.consent[cookiebot_consent_category]) {
3064                                gtag('config', trackingId, config);
3065                            }
3066                        } else {
3067                            if (Cookiebot.consent[cookiebot_consent_category]) {
3068                                gtag('config', trackingId, config);
3069                            }
3070                        }
3071
3072                    }
3073                    else
3074                    {
3075                        gtag('config', trackingId, config);
3076                    }
3077
3078                });
3079
3080                initialized = true;
3081
3082                Utils.fireStaticEvents('ga');
3083                $( document).trigger( "analytics_initialized")
3084            },
3085
3086            fireEvent: function (name, data) {
3087
3088                if (!initialized || !this.isEnabled()) {
3089                    return false;
3090                }
3091
3092                data.delay = data.delay || 0;
3093                data.params = data.params || {};
3094
3095                if (data.delay === 0) {
3096
3097                    fireEvent(name, data);
3098
3099                } else {
3100
3101                    setTimeout(function (name, params) {
3102                        fireEvent(name, params);
3103                    }, data.delay * 1000, name, data);
3104
3105                }
3106
3107                return true;
3108
3109            },
3110
3111            onAdSenseEvent: function (event) {
3112                this.fireEvent(event.name, event);
3113            },
3114
3115            onClickEvent: function (event) {
3116                this.fireEvent(event.name, event);
3117            },
3118
3119            onWatchVideo: function (event) {
3120                if(!event.hasOwnProperty("youtube_disabled")
3121                    || !event.youtube_disabled
3122                    || event.params.video_type !== "youtube") {
3123                    this.fireEvent(event.name, event);
3124                }
3125            },
3126
3127            onCommentEvent: function (event) {
3128
3129                this.fireEvent(event.name, event);
3130
3131            },
3132
3133            onFormEvent: function (event) {
3134
3135                this.fireEvent(event.name, event);
3136
3137            },
3138
3139            onDownloadEvent: function (event) {
3140
3141                this.fireEvent(event.name, event);
3142
3143            },
3144
3145            onWooAddToCartOnButtonEvent: function (product_id, prod_info = null) {
3146                if(!options.dynamicEvents.woo_add_to_cart_on_button_click.hasOwnProperty(this.tag()))
3147                    return;
3148
3149                if (window.pysWooProductData.hasOwnProperty(product_id)) {
3150                    if (window.pysWooProductData[product_id].hasOwnProperty('ga')) {
3151                        var event = Utils.clone(options.dynamicEvents.woo_add_to_cart_on_button_click[this.tag()]);
3152                        Utils.copyProperties(window.pysWooProductData[product_id]['ga'].params, event.params)
3153                        event.trackingIds = window.pysWooProductData[product_id]['ga']['trackingIds'];
3154                        if(prod_info)
3155                        {
3156                            if(prod_info['pys_list_name_productlist_id'])
3157                            {
3158                                event.params.items[0]['item_list_id'] = prod_info['pys_list_name_productlist_id']
3159                            }
3160                            if(prod_info['pys_list_name_productlist_name'])
3161                            {
3162                                event.params.items[0]['item_list_name'] =prod_info['pys_list_name_productlist_name']
3163                            }
3164                        }
3165                        this.fireEvent(event.name, event);
3166                    }
3167                }
3168
3169            },
3170
3171            onWooAddToCartOnSingleEvent: function (product_id, qty, product_type, is_external, $form) {
3172
3173                window.pysWooProductData = window.pysWooProductData || [];
3174
3175                if(!options.dynamicEvents.woo_add_to_cart_on_button_click.hasOwnProperty(this.tag()))
3176                    return;
3177                var event = Utils.clone(options.dynamicEvents.woo_add_to_cart_on_button_click[this.tag()]);
3178
3179                if (product_type === Utils.PRODUCT_VARIABLE && !options.ga.wooVariableAsSimple) {
3180                    product_id = parseInt($form.find('input[name="variation_id"]').val());
3181                }
3182
3183                if (window.pysWooProductData.hasOwnProperty(product_id)) {
3184                    if (window.pysWooProductData[product_id].hasOwnProperty('ga')) {
3185
3186                        Utils.copyProperties(window.pysWooProductData[product_id]['ga'].params, event.params);
3187
3188
3189                        if(product_type === Utils.PRODUCT_GROUPED ) {
3190                            var groupValue = 0;
3191                            $form.find(".woocommerce-grouped-product-list .qty").each(function(index){
3192                                var childId = $(this).attr('name').replaceAll("quantity[","").replaceAll("]","");
3193                                var quantity = parseInt($(this).val());
3194                                if(isNaN(quantity)) {
3195                                    quantity = 0;
3196                                }
3197                                var childItem = window.pysWooProductData[product_id]['ga'].grouped[childId];
3198                                event.params.items.forEach(function(el,index,array) {
3199                                    if(el.id == childItem.content_id) {
3200                                        if(quantity > 0){
3201                                            el.quantity = quantity;
3202                                            el.price = childItem.price;
3203                                        } else {
3204                                            array.splice(index, 1);
3205                                        }
3206                                    }
3207                                });
3208                                groupValue += childItem.price * quantity;
3209                            });
3210
3211                            if(options.woo.addToCartOnButtonValueEnabled &&
3212                                options.woo.addToCartOnButtonValueOption !== 'global' &&
3213                                event.params.hasOwnProperty('ecomm_totalvalue')) {
3214                                event.params.ecomm_totalvalue = groupValue;
3215                            }
3216
3217                            if(groupValue == 0) return; // skip if no items selected
3218                        } else {
3219                            // update items qty param
3220                            event.params.items[0].quantity = qty;
3221                        }
3222
3223                        // maybe customize value option
3224                        if (options.woo.addToCartOnButtonValueEnabled &&
3225                            options.woo.addToCartOnButtonValueOption !== 'global' &&
3226                            product_type !== Utils.PRODUCT_GROUPED)
3227                        {
3228                            if(event.params.hasOwnProperty('ecomm_totalvalue')) {
3229                                event.params.ecomm_totalvalue = event.params.items[0].price * qty;
3230                            }
3231                        }
3232
3233
3234
3235                        var eventName = is_external ? options.woo.affiliateEventName : event.name;
3236                        eventName = normalizeEventName(eventName);
3237
3238                        this.fireEvent(eventName, event);
3239
3240                    }
3241                }
3242
3243            },
3244
3245            onWooCheckoutProgressStep: function (event) {
3246                this.fireEvent(event.name, event);
3247            },
3248
3249            onWooSelectContent: function (event) {
3250                const select_prod_list = {};
3251
3252                if (event.params.items[0].item_list_name !== undefined) {
3253                    select_prod_list.list_name = event.params.items[0].item_list_name;
3254                }
3255
3256                if (event.params.items[0].item_list_id !== undefined) {
3257                    select_prod_list.list_id = event.params.items[0].item_list_id;
3258                }
3259                Cookies.set('select_prod_list', select_prod_list, { expires: 1 });
3260                this.fireEvent(event.name, event);
3261            },
3262
3263            onWooRemoveFromCartEvent: function (event) {
3264                this.fireEvent(event.name, event);
3265            },
3266
3267            onWooAffiliateEvent: function (product_id) {
3268                if(!options.dynamicEvents.woo_affiliate.hasOwnProperty(this.tag()))
3269                    return;
3270                var event = options.dynamicEvents.woo_affiliate[this.tag()];
3271
3272                if (window.pysWooProductData.hasOwnProperty(product_id)) {
3273                    if (window.pysWooProductData[product_id].hasOwnProperty('ga')) {
3274
3275                        event = Utils.clone(event );
3276                        Utils.copyProperties(window.pysWooProductData[product_id][this.tag()], event.params)
3277                        this.fireEvent(normalizeEventName(options.woo.affiliateEventName), event);
3278
3279                    }
3280                }
3281
3282            },
3283
3284            onWooPayPalEvent: function (event) {
3285                this.fireEvent(event.name, event);
3286            },
3287
3288            onEddAddToCartOnButtonEvent: function (download_id, price_index, qty) {
3289                if(!options.dynamicEvents.edd_add_to_cart_on_button_click.hasOwnProperty(this.tag()))
3290                    return;
3291                var event = Utils.clone(options.dynamicEvents.edd_add_to_cart_on_button_click[this.tag()]);
3292
3293
3294                if (window.pysEddProductData.hasOwnProperty(download_id)) {
3295
3296                    var index;
3297
3298                    if (price_index) {
3299                        index = download_id + '_' + price_index;
3300                    } else {
3301                        index = download_id;
3302                    }
3303
3304                    if (window.pysEddProductData[download_id].hasOwnProperty(index)) {
3305                        if (window.pysEddProductData[download_id][index].hasOwnProperty('ga')) {
3306
3307                            Utils.copyProperties(window.pysEddProductData[download_id][index]['ga'].params, event.params);
3308
3309                            // update items qty param
3310                            event.params.items[0].quantity = qty;
3311
3312                            this.fireEvent(event.name,event);
3313
3314                        }
3315                    }
3316
3317                }
3318
3319            },
3320
3321            onEddRemoveFromCartEvent: function (event) {
3322                this.fireEvent(event.name, event);
3323            },
3324
3325            onPageScroll: function (event) {
3326                if (initialized && this.isEnabled()) {
3327                    this.fireEvent(event.name, event);
3328                }
3329            },
3330            onTime: function (event) {
3331                if (initialized && this.isEnabled()) {
3332                    this.fireEvent(event.name, event);
3333                }
3334            },
3335        };
3336
3337    }(options);
3338
3339    var GAds = function (options) {
3340
3341        var initialized = false;
3342        var isAllowEnhancedConversions = false
3343        /**
3344         * Fires event
3345         *
3346         * @link: https://developers.google.com/analytics/devguides/collection/gtagjs/sending-data
3347         * @link: https://developers.google.com/analytics/devguides/collection/gtagjs/events
3348         * @link: https://developers.google.com/gtagjs/reference/event
3349         * @link: https://developers.google.com/gtagjs/reference/parameter
3350         */
3351        function fireEvent(name, data) {
3352
3353            if(typeof window.pys_event_data_filter === "function" && window.pys_disable_event_filter(event_name,'google_ads')) {
3354                return;
3355            }
3356
3357            var _params = Utils.copyProperties(data.params,{});
3358            var ids = data.ids;
3359
3360            var conversion_labels = data.conversion_labels;
3361            Utils.copyProperties(Utils.getRequestParams(), _params);
3362            var _fireEvent = function (conversion_id,event_name) {
3363
3364                params = Utils.copyProperties(_params, { send_to: conversion_id });
3365
3366                if("conversion" === event_name) {
3367                    delete params.items;
3368                    delete params.ecomm_pagetype;
3369                    delete params.ecomm_prodid;
3370                    delete params.ecomm_totalvalue;
3371                }
3372
3373                if (options.debug) {
3374                    console.log('[Google Ads #' + conversion_id + '] ' + event_name, params);
3375                }
3376
3377                gtag('event', event_name, params);
3378
3379            };
3380
3381            if(conversion_labels.length > 0) {  // if custom event have conversion_label
3382                conversion_labels.forEach(function (conversion_id) {
3383                    _fireEvent(conversion_id,name);
3384                });
3385            } else { // if normal event have conversion_label or custom without conversion_label
3386
3387                data.conversion_ids.forEach(function (conversion_id) { // send main event
3388                    _fireEvent(conversion_id,name);
3389                });
3390
3391                if (ids.length) {
3392                    ids.forEach(function (conversion_id) {  // send conversion event next to main(not use for custom events)
3393                        _fireEvent(conversion_id,"conversion");
3394                    });
3395                }
3396            }
3397        }
3398
3399        function normalizeEventName(eventName) {
3400
3401            var matches = {
3402                ViewContent: 'view_item',
3403                AddToCart: 'add_to_cart',
3404                AddToWishList: 'add_to_wishlist',
3405                InitiateCheckout: 'begin_checkout',
3406                Purchase: 'purchase',
3407                Lead: 'generate_lead',
3408                CompleteRegistration: 'sign_up',
3409                AddPaymentInfo: 'set_checkout_option'
3410            };
3411
3412            return matches.hasOwnProperty(eventName) ? matches[eventName] : eventName;
3413
3414        }
3415
3416        /**
3417         * Public API
3418         */
3419        return {
3420            tag: function() {
3421                return "google_ads";
3422            },
3423            isEnabled: function () {
3424                return options.hasOwnProperty('google_ads');
3425            },
3426
3427            disable: function () {
3428                initialized = false;
3429            },
3430
3431            updateEnhancedConversionData : function () {
3432
3433                if(isAllowEnhancedConversions) {
3434                    var advanced = Utils.getAdvancedFormData()
3435                    if(Object.keys(options.google_ads.user_data).length == 0) {
3436                        if(advanced["email"].length > 0) {
3437                            gtag('set', 'user_data', {"email":advanced["email"]});
3438                        }
3439                    }
3440                }
3441            },
3442
3443            loadPixel: function () {
3444
3445                if (initialized || !this.isEnabled() || !Utils.consentGiven('google_ads')) {
3446                    return;
3447                }
3448
3449                Utils.loadGoogleTag(options.google_ads.conversion_ids[0]);
3450
3451                // configure conversion ids
3452                options.google_ads.conversion_ids.forEach(function (conversion_id,index) {
3453
3454                    gtag('config', conversion_id);
3455
3456                    if(options.google_ads.enhanced_conversion.includes("index_"+index)) {
3457                        isAllowEnhancedConversions = true
3458                        gtag('config', conversion_id,{ 'allow_enhanced_conversions':true });
3459                    }
3460
3461                    if(isAllowEnhancedConversions) {
3462                        var advanced = Utils.getAdvancedFormData()
3463                        if(Object.keys(options.google_ads.user_data).length > 0) {
3464                            gtag('set', 'user_data', options.google_ads.user_data);
3465                        } else if(advanced["email"].length > 0) {
3466                            gtag('set', 'user_data', {"email":advanced["email"]});
3467                        }
3468                    }
3469
3470                });
3471
3472                initialized = true;
3473
3474                Utils.fireStaticEvents('google_ads');
3475
3476            },
3477
3478            fireEvent: function (name, data) {
3479
3480                if (!initialized || !this.isEnabled()) {
3481                    return false;
3482                }
3483
3484                data.delay = data.delay || 0;
3485                data.params = data.params || {};
3486                data.ids = data.ids || [];
3487                data.conversion_labels = data.conversion_labels || [];
3488
3489                if (data.delay === 0) {
3490                    fireEvent(name, data);
3491                } else {
3492                    setTimeout(function (name, data) {
3493                        fireEvent(name, data);
3494                    }, data.delay * 1000, name, data);
3495                }
3496
3497                return true;
3498
3499            },
3500
3501            onAdSenseEvent: function (event) {
3502                this.fireEvent(event.name, event);
3503            },
3504
3505            onClickEvent: function (action, params) {
3506                //disabled
3507            },
3508
3509            onWatchVideo: function (event) {
3510                this.fireEvent(event.name, event);
3511            },
3512
3513            onCommentEvent: function (event) {
3514                this.fireEvent(event.name, event);
3515            },
3516
3517            onFormEvent: function (event) {
3518                this.fireEvent(event.name, event);
3519            },
3520
3521            onDownloadEvent: function (event) {
3522                this.fireEvent(event.name, event);
3523            },
3524
3525
3526
3527
3528            onWooAddToCartOnButtonEvent: function (product_id) {
3529
3530                if(!options.dynamicEvents.woo_add_to_cart_on_button_click.hasOwnProperty(this.tag()))
3531                    return;
3532
3533                if (window.pysWooProductData.hasOwnProperty(product_id)) {
3534                    if (window.pysWooProductData[product_id].hasOwnProperty('google_ads')) {
3535
3536                        var event = Utils.clone(options.dynamicEvents.woo_add_to_cart_on_button_click[this.tag()])
3537                        Utils.copyProperties(window.pysWooProductData[product_id]['google_ads']['params'].params, event.params)
3538                        event["ids"] = window.pysWooProductData[product_id]['google_ads']['ids']
3539                        event["conversion_labels"] = window.pysWooProductData[product_id]['google_ads']['conversion_labels']
3540                        this.fireEvent(event.name, event);
3541                    }
3542                }
3543
3544            },
3545
3546            onWooAddToCartOnSingleEvent: function (product_id, qty, product_type, is_external, $form) {
3547
3548                window.pysWooProductData = window.pysWooProductData || [];
3549                if(!options.dynamicEvents.woo_add_to_cart_on_button_click.hasOwnProperty(this.tag()))
3550                    return;
3551                var event = Utils.clone(options.dynamicEvents.woo_add_to_cart_on_button_click[this.tag()]);
3552
3553                if (product_type === Utils.PRODUCT_VARIABLE && !options.google_ads.wooVariableAsSimple) {
3554                    product_id = parseInt($form.find('input[name="variation_id"]').val());
3555                }
3556
3557                if (window.pysWooProductData.hasOwnProperty(product_id)) {
3558                    if (window.pysWooProductData[product_id].hasOwnProperty('google_ads')) {
3559
3560                        Utils.copyProperties(window.pysWooProductData[product_id]['google_ads']["params"], event.params);
3561                        event["ids"] = window.pysWooProductData[product_id]['google_ads']['ids']
3562                        event["conversion_labels"] = window.pysWooProductData[product_id]['google_ads']['conversion_labels']
3563
3564                        var groupValue = 0;
3565                        if(product_type === Utils.PRODUCT_GROUPED ) {
3566                            $form.find(".woocommerce-grouped-product-list .qty").each(function(index){
3567                                var childId = $(this).attr('name').replaceAll("quantity[","").replaceAll("]","");
3568                                var quantity = parseInt($(this).val());
3569                                if(isNaN(quantity)) {
3570                                    quantity = 0;
3571                                }
3572
3573                                var childItem = window.pysWooProductData[product_id]['google_ads'].grouped[childId];
3574
3575                                if(options.woo.addToCartOnButtonValueEnabled &&
3576                                    options.woo.addToCartOnButtonValueOption !== 'global') {
3577
3578                                    event.params.items.forEach(function(el,index,array) {
3579                                        if(el.id == childItem.content_id) {
3580                                            if(quantity > 0){
3581                                                el.quantity = quantity;
3582                                                el.price = childItem.price;
3583                                            } else {
3584                                                array.splice(index, 1);
3585                                            }
3586                                        }
3587                                    });
3588                                }
3589                                groupValue += childItem.price * quantity;
3590                            });
3591                            if(groupValue == 0) return;
3592                            event.params.value = groupValue;
3593                        } else {
3594                            // update items qty param
3595                            event.params.items[0].quantity = qty;
3596                        }
3597
3598
3599
3600                        // maybe customize value option
3601                        if (options.woo.addToCartOnButtonValueEnabled &&
3602                            options.woo.addToCartOnButtonValueOption !== 'global' &&
3603                            product_type !== Utils.PRODUCT_GROUPED) {
3604                            event.params.value =  event.params.value * qty;
3605                        }
3606
3607
3608
3609                        var eventName = is_external ? options.woo.affiliateEventName : event.name;
3610                        eventName = normalizeEventName(eventName);
3611
3612                        this.fireEvent(eventName, event);
3613
3614                    }
3615                }
3616
3617            },
3618
3619            onWooRemoveFromCartEvent: function (event) {
3620                this.fireEvent(event.name, event);
3621            },
3622
3623            onWooAffiliateEvent: function (product_id) {
3624                if(!options.dynamicEvents.woo_affiliate.hasOwnProperty(this.tag()))
3625                    return;
3626                var event = options.dynamicEvents.woo_affiliate[this.tag()];
3627
3628                if (window.pysWooProductData.hasOwnProperty(product_id)) {
3629                    if (window.pysWooProductData[product_id].hasOwnProperty('google_ads')) {
3630
3631                        event = Utils.clone(event)
3632                        Utils.copyProperties(window.pysWooProductData[product_id][this.tag()], event.params)
3633                        this.fireEvent(normalizeEventName(options.woo.affiliateEventName), event);
3634
3635                    }
3636                }
3637
3638            },
3639
3640            onWooPayPalEvent: function (event) {
3641                this.fireEvent(event.name, event);
3642            },
3643
3644            onEddAddToCartOnButtonEvent: function (download_id, price_index, qty) {
3645                if(!options.dynamicEvents.edd_add_to_cart_on_button_click.hasOwnProperty(this.tag()))
3646                    return;
3647                var event = options.dynamicEvents.edd_add_to_cart_on_button_click[this.tag()];
3648
3649
3650                if (window.pysEddProductData.hasOwnProperty(download_id)) {
3651
3652                    var index;
3653
3654                    if (price_index) {
3655                        index = download_id + '_' + price_index;
3656                    } else {
3657                        index = download_id;
3658                    }
3659
3660                    if (window.pysEddProductData[download_id].hasOwnProperty(index)) {
3661                        if (window.pysEddProductData[download_id][index].hasOwnProperty('google_ads')) {
3662
3663                            event = Utils.clone(event)
3664                            Utils.copyProperties(window.pysEddProductData[download_id][index]['google_ads']['params'], event.params);
3665                            event.ids = window.pysEddProductData[download_id][index]['google_ads']['ids']
3666                            // update items qty param
3667                            //params.items[0].quantity = qty;
3668
3669                            this.fireEvent(event.name, event);
3670
3671                        }
3672                    }
3673
3674                }
3675
3676            },
3677
3678            onEddRemoveFromCartEvent: function (event) {
3679                this.fireEvent(event.name, event);
3680            },
3681            onPageScroll: function (event) {
3682                if (initialized && this.isEnabled()) {
3683                    this.fireEvent(event.name, event);
3684                }
3685            },
3686            onTime: function (event) {
3687                if (initialized && this.isEnabled()) {
3688                    this.fireEvent(event.name, event);
3689                }
3690            },
3691
3692        };
3693
3694    }(options);
3695
3696    window.pys = window.pys || {};
3697    window.pys.Facebook = Facebook;
3698    window.pys.Analytics = Analytics;
3699    window.pys.GAds = GAds;
3700    window.pys.Utils = Utils;
3701    window.pys.TikTok = TikTok;
3702
3703
3704
3705    $(document).ready(function () {
3706
3707        if(Cookies.get('form_track'))
3708        {
3709            Cookies.remove('form_track')
3710        }
3711
3712        if($("#pys_late_event").length > 0) {
3713            var events =  JSON.parse($("#pys_late_event").attr("dir"));
3714            for(var key in events) {
3715                var event = {};
3716                event[events[key].e_id] = [events[key]];
3717                if(options.staticEvents.hasOwnProperty(key)) {
3718                    Object.assign(options.staticEvents[key], event);
3719                } else {
3720                    options.staticEvents[key] = event;
3721                }
3722
3723            }
3724        }
3725
3726        var Pinterest = Utils.setupPinterestObject();
3727        var Bing = Utils.setupBingObject();
3728        if(options.hasOwnProperty('cookie'))
3729        {
3730            if(options.cookie.externalID_disabled_by_api || options.cookie.disabled_all_cookie)
3731            {
3732                Cookies.remove('pbid')
3733            }
3734            if(options.cookie.disabled_advanced_form_data_cookie || options.cookie.disabled_all_cookie)
3735            {
3736                Cookies.remove('pys_advanced_form_data')
3737            }
3738            if(options.cookie.disabled_landing_page_cookie || options.cookie.disabled_all_cookie)
3739            {
3740                Cookies.remove('pys_landing_page')
3741                Cookies.remove('last_pys_landing_page')
3742            }
3743            if(options.cookie.disabled_trafficsource_cookie || options.cookie.disabled_all_cookie)
3744            {
3745                Cookies.remove('pysTrafficSource')
3746                Cookies.remove('last_pysTrafficSource')
3747            }
3748            if(options.cookie.disabled_first_visit_cookie || options.cookie.disabled_all_cookie)
3749            {
3750                Cookies.remove('pys_first_visit')
3751
3752            }
3753            if(options.cookie.disabled_utmTerms_cookie || options.cookie.disabled_all_cookie)
3754            {
3755                $.each(Utils.utmTerms, function (index, name) {
3756                    Cookies.remove('pys_' + name)
3757                });
3758                $.each(Utils.utmTerms, function (index, name) {
3759                    Cookies.remove('last_pys_' + name)
3760                });
3761            }
3762            if(options.cookie.disabled_utmId_cookie || options.cookie.disabled_all_cookie)
3763            {
3764                $.each(Utils.utmId,function(index,name) {
3765                    Cookies.remove('pys_' + name)
3766                })
3767                $.each(Utils.utmId,function(index,name) {
3768                    Cookies.remove('last_pys_' + name)
3769                });
3770            }
3771        }
3772
3773
3774        Utils.manageCookies();
3775
3776        Utils.initializeRequestParams();
3777        Utils.setupGdprCallbacks();
3778
3779
3780        //Setup Advanced Form Data
3781        if(options.enable_auto_save_advance_matching) {
3782            $(document).on("blur","input[type='email']",function () {
3783                let email = $(this).val().trim().toLowerCase();
3784                if(Utils.validateEmail(email)) {
3785                    Utils.saveAdvancedFormData(email,null,null,null);
3786                }
3787            })
3788            $(document).on("blur","input[type='tel']",function () {
3789                let phone = $(this).val().trim().replace(/\D/g, "");
3790                if(phone.length > 5) {
3791                    Utils.saveAdvancedFormData(null,phone,null,null);
3792                }
3793            })
3794            $(document).on("blur","input[type='text']",function () {
3795                let name;
3796                if($(this).attr("name") && $(this).attr("name") != '')
3797                {
3798                    name = $(this).attr("name").trim()
3799                }
3800                if(name && options.advance_matching_fn_names.includes(name)) {
3801                    let value = $(this).val().trim();
3802                    if(value.length > 0) {
3803                        Utils.saveAdvancedFormData(null,null,value,null);
3804                    }
3805                }
3806                if(name && options.advance_matching_ln_names.includes(name)) {
3807                    let value = $(this).val().trim();
3808                    if(value.length > 0) {
3809                        Utils.saveAdvancedFormData(null,null,null,value);
3810                    }
3811                }
3812                if(name && options.advance_matching_tel_names.includes(name)) {
3813                    let value = $(this).val().trim();
3814                    if(value.length > 0) {
3815                        Utils.saveAdvancedFormData(null,value,null,null);
3816                    }
3817                }
3818
3819            })
3820        }
3821
3822
3823
3824
3825        // setup Click Event
3826        if (
3827            options.dynamicEvents.hasOwnProperty("automatic_event_internal_link") ||
3828            options.dynamicEvents.hasOwnProperty("automatic_event_outbound_link") ||
3829            options.dynamicEvents.hasOwnProperty("automatic_event_tel_link") ||
3830            options.dynamicEvents.hasOwnProperty("automatic_event_email_link") ||
3831            options.dynamicEvents.hasOwnProperty("automatic_event_download")
3832        ) {
3833
3834            $(document).onFirst('click', 'a, button, input[type="button"], input[type="submit"]', function (e) {
3835
3836                var $elem = $(this);
3837
3838
3839                // Download
3840                if(options.dynamicEvents.hasOwnProperty("automatic_event_download")) {
3841                    var isFired = false;
3842                    if ($elem.is('a')) {
3843                        var href = $elem.attr('href');
3844                        if (typeof href !== "string") {
3845                            return;
3846                        }
3847                        href = href.trim();
3848                        var extension = Utils.getLinkExtension(href);
3849                        var track_download = false;
3850
3851                        if (extension.length > 0) {
3852
3853                            if(options.dynamicEvents.hasOwnProperty("automatic_event_download") ) {
3854                                var pixels = Object.keys(options.dynamicEvents.automatic_event_download);
3855                                for (var i = 0; i < pixels.length; i++) {
3856                                    var event = Utils.clone(options.dynamicEvents.automatic_event_download[pixels[i]]);
3857                                    var extensions = event.extensions;
3858                                    if (extensions.includes(extension)) {
3859
3860                                        if(pixels[i] == "tiktok") {
3861                                            getPixelBySlag(pixels[i]).fireEvent(event.name, event);
3862                                        } else {
3863                                            if (options.enable_remove_download_url_param) {
3864                                                href = href.split('?')[0];
3865                                            }
3866                                            event.params.download_url = href;
3867                                            event.params.download_type = extension;
3868                                            event.params.download_name = Utils.getLinkFilename(href);
3869                                            getPixelBySlag(pixels[i]).onDownloadEvent(event);
3870                                        }
3871
3872                                        isFired = true;
3873                                    }
3874                                }
3875                            }
3876                        }
3877                    }
3878                    if(isFired) { // prevent duplicate events on the same element
3879                        return;
3880                    }
3881                }
3882
3883
3884                if (!e.hasOwnProperty('originalEvent')) {
3885                    return;
3886                }
3887                if($elem.hasClass("add_to_cart_button") ||
3888                    $elem.hasClass("single_add_to_cart_button") ) { // add_to_cart_button fire in woo
3889                    return;
3890                }
3891
3892                if(options.dynamicEvents.hasOwnProperty("wcf_add_to_cart_on_next_step_click")
3893                    && $elem.hasClass("wcf-next-step-link")) {
3894                    return;// add_to_cart_button fire in woo cf
3895                }
3896                if(options.dynamicEvents.hasOwnProperty("wcf_add_to_cart_on_bump_click")
3897                    && $elem.hasClass("wcf-bump-order-cb")) {
3898                    return;// add_to_cart_button fire in woo cf
3899                }
3900
3901                if($elem.hasClass("remove_from_cart_button") ) { // cancel remove from cart
3902                    return;
3903                }
3904                if($elem.hasClass("remove") ) { // cancel remove from cart
3905                    if($elem.parents('.cart_item').length || $elem.parents('.mini_cart_item').length)
3906                    return;
3907                }
3908                if($elem.attr("name") == "update_cart" || $elem.attr("name") == "apply_coupon") { // cancel update  c
3908art or coupon button
3909                    return;
3910                }
3911
3912
3913                if ($elem.hasClass('pys_block')) {
3914                    return; // avoiding fake double clicks from Affiliate event
3915                }
3916                var text = "";
3917                var target_url = "";
3918                var linkType = "Internal Click";
3919
3920                if ($elem.is('a')) {
3921                    var href = $elem.attr('href');
3922
3923                    // fixes #112
3924                    if (typeof href !== "string") {
3925                        return;
3926                    }
3927                    href = href.trim();
3928
3929                    text = $elem.text();
3930                    if(options.enable_remove_target_url_param) {
3931                        target_url = href.split('?')[0];
3932                    } else {
3933                        target_url = href
3934                    }
3935
3936
3937                    //Email Event
3938                    if (href.startsWith('mailto:')) {
3939                        if(options.dynamicEvents.hasOwnProperty("automatic_event_email_link")) {
3940                            var pixels = Object.keys(options.dynamicEvents.automatic_event_email_link);
3941                            for(var i = 0;i<pixels.length;i++) {
3942                                var event = Utils.clone(options.dynamicEvents.automatic_event_email_link[pixels[i]]);
3943                                Utils.copyProperties(Utils.getRequestParam
3943s(), event.params);
3944                                getPixelBySlag(pixels[i]).fireEvent(event.name, event);
3945                            }
3946                        }
3947
3948                        return; // not fire next
3949                    }
3950
3951                    // Phone
3952                    if (href.startsWith('tel:')) {
3953                        if(options.dynamicEvents.hasOwnProperty("automatic_event_tel_link")) {
3954                            var pixels = Object.keys(options.dynamicEvents.automatic_event_tel_link);
3955                            for(var i = 0;i<pixels.length;i++) {
3956                                var event = Utils.clone(options.dynamicEvents.automatic_event_tel_link[pixels[i]]);
3957                                Utils.copyProperties(Utils.getRequestParams(), event.params);
3958                                getPixelBySlag(pixels[i]).fireEvent(event.name, event);
3959                            }
3960                        }
3961                        return; // not fire next
3962                    }
3963
3964                    if (href.startsWith('http')) {
3965                        // link type
3966                        var host = $elem.context != undefined ? $elem.context.host : $elem[0].host;
3967                        if (document.location.host != host) {
3968                            linkType = 'External Click';
3969                        }
3970                    }
3971                } else if ($elem.is('button')) {
3972                    if( $elem.hasClass("forminator-button-submit")) {
3973                        //disable duplicate events
3974                        return;
3975                    }
3976                    text = $elem.text();
3977                } else if ($elem.is('input[type="button"]')) {
3978                    text = $elem.val();
3979                } else if ($elem.is('input[type="submit"]')) {
3980                    if ( $elem.parents("form.comment-form")) {
3981                        //disable duplicate events
3982                        return;
3983                    }
3984                    if ($elem.parents("form")) {
3985                        //disable duplicate events
3986                        return;
3987                    }
3988                    text = $elem.val();
3989                } else {
3990                    return;
3991                }
3992
3993
3994
3995                text = Utils.filterEmails(text);
3996
3997
3998                if( linkType === "Internal Click"
3999                    && options.dynamicEvents.hasOwnProperty("automatic_event_internal_link")
4000                ) {
4001                    var pixels = Object.keys(options.dynamicEvents.automatic_event_internal_link);
4002
4003                    for(var i = 0;i<pixels.length;i++) {
4004                        var event = Utils.clone(options.dynamicEvents.automatic_event_internal_link[pixels[i]]);
4005
4006                        if(pixels[i] !== "tiktok") { // TT doesn't support custom parameters
4007                            event.params["text"] = text;
4008                            if(target_url){
4009                                event.params["target_url"] = target_url;
4010                            }
4011                            Utils.copyProperties(Utils.getRequestParam
4011s(), event.params);
4012                        }
4013
4014
4015                        getPixelBySlag(pixels[i]).fireEvent(event.name, event);
4016                    }
4017                }
4018
4019                if( linkType === "External Click"
4020                    && options.dynamicEvents.hasOwnProperty("automatic_event_outbound_link")
4021                ) {
4022                    var pixels = Object.keys(options.dynamicEvents.automatic_event_outbound_link);
4023
4024                    for(var i = 0;i<pixels.length;i++) {
4025                        var event = Utils.clone(options.dynamicEvents.automatic_event_outbound_link[pixels[i]]);
4026
4027                        if(pixels[i] !== "tiktok") { // TT doesn't support custom parameters
4028                            event.params["text"] = text;
4029                            if(target_url){
4030                                event.params["target_url"] = target_url;
4031                            }
4032                            Utils.copyProperties(Utils.getRequestParams(), event.params);
4033                        }
4034
4035
4036                        getPixelBySlag(pixels[i]).fireEvent(event.name, event);
4037                    }
4038                }
4039
4040
4041
4042
4043            });
4044
4045        }
4046
4047        // setup AdSense Event
4048        if (options.dynamicEvents.hasOwnProperty("automatic_event_adsense")) {
4049
4050            var isOverGoogleAd = false;
4051
4052            $(document)
4053                .on('mouseover', 'ins iframe', function () { //class adsbygoogle adsbygoogle-noablate ??
4054                    isOverGoogleAd = true;
4055                })
4056                .on('mouseout', 'iframe', function () {
4057                    isOverGoogleAd = false;
4058                });
4059
4060            $(window)
4061                .on( "blur",function () {
4062                    if (isOverGoogleAd) {
4063                        console.log('automatic_event_adsense')
4064                        if(options.dynamicEvents.hasOwnProperty("automatic_event_adsense")) {
4065                            var pixels = Object.keys(options.dynamicEvents.automatic_event_adsense);
4066                            for (var i = 0; i < pixels.length; i++) {
4067                                var event = Utils.clone(options.dynamicEvents.automatic_event_adsense[pixels[i]]);
4068                                Utils.copyProperties(Utils.getRequestParam
4068s(), event.params);
4069                                getPixelBySlag(pixels[i]).onAdSenseEvent(event);
4070                            }
4071                        }
4072
4073                        $.each(options.triggerEventTypes, function (triggerType, events) {
4074                            $.each(events, function (eventId, triggers) {
4075                                switch (triggerType) {
4076                                    case 'ad_sense_click':
4077                                        Utils.fireTriggerEvent(eventId);
4078                                        break;
4079                                }
4080                            });
4081                        });
4082                    }
4083                })
4084                .trigger("focus");
4085
4086        }
4087
4088        //setup adsense for custom events
4089        var dynamicAdsenseEventsTriggers = 0
4090        $.each(options.triggerEventTypes, function (triggerType, events) {
4091            if(triggerType == "ad_sense_click") {
4092                dynamicAdsenseEventsTriggers++;
4093            }
4094        });
4095        if (dynamicAdsenseEventsTriggers > 0) {
4096
4097            var isOverGoogleAd = false;
4098
4099            $(document)
4100                .on('mouseover', 'ins > ins > iframe', function () {
4101                    isOverGoogleAd = true;
4102                })
4103                .on('mouseout', 'iframe', function () {
4104                    isOverGoogleAd = false;
4105                });
4106
4107            $(window)
4108                .on( "blur",function () {
4109                    if (isOverGoogleAd) {
4110
4111                        $.each(options.triggerEventTypes, function (triggerType, events) {
4112                            $.each(events, function (eventId, triggers) {
4113                                switch (triggerType) {
4114                                    case 'ad_sense_click':
4115                                        Utils.fireTriggerEvent(eventId);
4116                                        break;
4117                                }
4118                            });
4119                        });
4120                    }
4121                })
4122                .trigger("focus");
4123
4124        }
4125
4126
4127        // page scroll event
4128        if (options.dynamicEvents.hasOwnProperty("automatic_event_scroll")
4129        ) {
4130
4131            var singlePageScroll = function () {
4132
4133
4134                var docHeight = $(document).height() - $(window).height();
4135                var isFired = false;
4136
4137                if (options.dynamicEvents.hasOwnProperty("automatic_event_scroll")) {
4138                    var pixels = Object.keys(options.dynamicEvents.automatic_event_scroll);
4139                    for(var i = 0;i<pixels.length;i++) {
4140                        var event = Utils.clone(options.dynamicEvents.automatic_event_scroll[pixels[i]]);
4141                        var scroll = Math.round(docHeight * event.scroll_percent / 100)// convert % to absolute positions
4142
4143                        if(scroll < $(window).scrollTop()) {
4144                            Utils.copyProperties(Utils.getRequestParam
4144s(), event.params);
4145                            getPixelBySlag(pixels[i]).onPageScroll(event);
4146                            isFired = true
4147                        }
4148                    }
4149                }
4150                if(isFired) {
4151                    $(document).off("scroll",singlePageScroll);
4152                }
4153            }
4154            $(document).on("scroll",singlePageScroll);
4155        }
4156
4157
4158        if (options.dynamicEvents.hasOwnProperty("automatic_event_time_on_page")) {
4159            var pixels = Object.keys(options.dynamicEvents.automatic_event_time_on_page);
4160            var time = options.dynamicEvents.automatic_event_time_on_page[pixels[0]].time_on_page; // the same for all pixel
4161            setTimeout(function(){
4162                for(var i = 0;i<pixels.length;i++) {
4163                    var event = Utils.clone(options.dynamicEvents.automatic_event_time_on_page[pixels[i]]);
4164                    Utils.copyProperties(Utils.getRequestParams(), event.params);
4165                    getPixelBySlag(pixels[i]).onTime(event);
4166                }
4167            },time*1000);
4168        }
4169
4170        // setup Dynamic events
4171
4172        $.each(options.triggerEventTypes, function (triggerType, events) {
4173
4174            $.each(events, function (eventId, triggers) {
4175                switch (triggerType) {
4176                    case 'url_click':
4177                        //@see: Utils.setupURLClickEvents()
4178                        break;
4179
4180                    case 'css_click':
4181                        Utils.setupCSSClickEvents(eventId, triggers);
4182                        break;
4183
4184                    case 'css_mouseover':
4185                        Utils.setupMouseOverClickEvents(eventId, triggers);
4186                        break;
4187
4188                    case 'scroll_pos':
4189                        Utils.setupScrollPosEvents(eventId, triggers);
4190                        break;
4191                    case 'comment':
4192                        Utils.setupCommentEvents(eventId, triggers);
4193                        break;
4194                }
4195
4196            });
4197
4198        });
4199
4200        // setup WooCommerce events
4201        if (options.woo.enabled) {
4202
4203            // Woo CartFlow AddToCart
4204            if (options.dynamicEvents.hasOwnProperty("wcf_add_to_cart_on_next_step_click")) {
4205                $("body").on("click",'.wcf-next-step-link',function () {
4206                    var pixels = Object.keys(options.dynamicEvents.wcf_add_to_cart_on_next_step_click);
4207                    for(var i = 0;i<pixels.length;i++) {
4208                        var event = Utils.clone(options.dynamicEvents.wcf_add_to_cart_on_next_step_click[pixels[i]])
4209                        getPixelBySlag(pixels[i]).fireEvent(event.name, event);
4210                    }
4211                });
4212            }
4213            // Woo CartFlow Bump AddToCart
4214            if(options.dynamicEvents.hasOwnProperty("wcf_add_to_cart_on_bump_click") ||
4215                options.dynamicEvents.hasOwnProperty("wcf_bump")) {
4216                $("body").on('change','.wcf-bump-order-cb',function () {
4217
4218                    if(this.checked) {
4219                        if(options.dynamicEvents.hasOwnProperty("wcf_add_to_cart_on_bump_click")) {
4220                            var pixels = Object.keys(options.dynamicEvents.wcf_add_to_cart_on_bump_click);
4221                            for(var i = 0;i<pixels.length;i++) {
4222                                var event = Utils.clone(options.dynamicEvents.wcf_add_to_cart_on_bump_click[pixels[i]]);
4223                                getPixelBySlag(pixels[i]).fireEvent(event.name, event);
4224                            }
4225                        }
4226
4227
4228                        if(options.dynamicEvents.hasOwnProperty("wcf_bump")) {
4229                            var pixels = Object.keys(options.dynamicEvents.wcf_bump);
4230                            for(var i = 0;i<pixels.length;i++) {
4231                                var event = Utils.clone(options.dynamicEvents.wcf_bump[pixels[i]]);
4232                                getPixelBySlag(pixels[i]).fireEvent(event.name, event);
4233                            }
4234                        }
4235
4236                    } else {
4237                        if(options.dynamicEvents.hasOwnProperty("wcf_remove_from_cart_on_bump_click")) {
4238                            var pixels = Object.keys(options.dynamicEvents.wcf_remove_from_cart_on_bump_click);
4239                            for(var i = 0;i<pixels.length;i++) {
4240                                var event = Utils.clone(options.dynamicEvents.wcf_remove_from_cart_on_bump_click[pixels[i]]);
4241                                getPixelBySlag(pixels[i]).fireEvent(event.name, event);
4242                            }
4243                        }
4244
4245                    }
4246
4247
4248                });
4249            }
4250
4251
4252            // WooCommerce AddToCart
4253            if (options.dynamicEvents.hasOwnProperty("woo_add_to_cart_on_button_click")
4254                && options.woo.hasOwnProperty("addToCartCatchMethod")
4255                && options.woo.addToCartCatchMethod === "add_cart_js"
4256            ) {
4257
4258                // Loop, any kind of "simple" product, except external
4259                $('.add_to_cart_button:not(.product_type_variable,.product_type_bundle,.single_add_to_cart_button)').on("click",function (e) {
4260                    var $button = $(this);
4261                    var $prod_info = $button.siblings('.pys_list_name_productdata').data();
4262                    var product_id = $(this).data('product_id');
4263                    Cookies.set('productlist', $prod_info, { expires: 1 })
4264                    var product_id = $(this).data('product_id');
4265
4266                    if (typeof product_id !== 'undefined') {
4267                        Facebook.onWooAddToCartOnButtonEvent(product_id,$(this));
4268                        Analytics.onWooAddToCartOnButtonEvent(product_id, $prod_info);
4269                        GAds.onWooAddToCartOnButtonEvent(product_id);
4270                        Pinterest.onWooAddToCartOnButtonEvent(product_id);
4271                        Bing.onWooAddToCartOnButtonEvent(product_id);
4272                        TikTok.onWooAddToCartOnButtonEvent(product_id);
4273                    }
4274
4275                });
4276
4277                // Single Product
4278                // tap try to https://stackoverflow.com/questions/30990967/on-tap-click-event-firing-twice-how-to-avoid-it
4279                //  $(document) not work
4280                $('body').onFirst('click','button.single_add_to_cart_button,.single_add_to_cart_button',function (e) {
4281
4282                    var $button = $(this);
4283                    var $prod_info = $button.siblings('.pys_list_name_productdata').data();
4284                    var product_id = $(this).data('product_id');
4285                    Cookies.set('productlist', $prod_info, { expires: 1 })
4286                    if ($button.hasClass('disabled')) {
4287                        return;
4288                    }
4289
4290                    var $form = $button.closest('form');
4291
4292                    var product_type = Utils.PRODUCT_SIMPLE;
4293                    var is_external = false;
4294
4295                    if ($form.length === 0) {
4296                        is_external = true;
4297                    } else if ($form.hasClass('variations_form')) {
4298                        product_type = Utils.PRODUCT_VARIABLE;
4299                    } else if($form.hasClass('bundle_form')) {
4300                        product_type = Utils.PRODUCT_BUNDLE;
4301                    } else if($form.hasClass('grouped_form')) {
4302                        product_type = Utils.PRODUCT_GROUPED;
4303                    }
4304
4305
4306
4307                    var product_id;
4308                    var qty;
4309                    if (product_type === Utils.PRODUCT_GROUPED) {
4310                        qty = 1;
4311                        product_id = parseInt($form.find('*[name="add-to-cart"]').val());
4312                    } else if (product_type === Utils.PRODUCT_VARIABLE) {
4313                        product_id = parseInt($form.find('*[name="add-to-cart"]').val());
4314                        var qtyTag = $form.find('input[name="quantity"]');
4315                        if(qtyTag.length <= 0) {
4316                            qtyTag = $form.find('select[name="quantity"]');
4317                        }
4318                        qty = parseInt(qtyTag.val());
4319                    } else if (is_external) {
4320                        product_id = options.woo.singleProductId;
4321                        qty = 1;
4322                    } else {
4323                        product_id = parseInt($form.find('*[name="add-to-cart"]').val());
4324                        var qtyTag = $form.find('input[name="quantity"]');
4325                        if(qtyTag.length <= 0) {
4326                            qtyTag = $form.find('select[name="quantity"]');
4327                        }
4328                        qty = parseInt(qtyTag.val());
4329                    }
4330
4331                    Facebook.onWooAddToCartOnSingleEvent(product_id, qty, product_type, is_external, $form);
4332                    Analytics.onWooAddToCartOnSingleEvent(product_id, qty, product_type, is_external, $form);
4333                    GAds.onWooAddToCartOnSingleEvent(product_id, qty, product_type, is_external, $form);
4334                    Pinterest.onWooAddToCartOnSingleEvent(product_id, qty, product_type, is_external, $form);
4335                    Bing.onWooAddToCartOnSingleEvent(product_id, qty, product_type, is_external, $form);
4336                    TikTok.onWooAddToCartOnSingleEvent(product_id, qty, product_type, is_external, $form);
4337                });
4338
4339            } else {
4340                $('.add_to_cart_button:not(.product_type_variable,.product_type_bundle,.single_add_to_cart_button)').on("click",function (e) {
4341                    var $button = $(this);
4342                    var $prod_info = $button.siblings('.pys_list_name_productdata').data();
4343                    var product_id = $(this).data('product_id');
4344                    Cookies.set('productlist', $prod_info, { expires: 1 })
4345                });
4346
4347                // Single Product
4348                // tap try to https://stackoverflow.com/questions/30990967/on-tap-click-event-firing-twice-how-to-avoid-it
4349                //  $(document) not work
4350                $('body').onFirst('click','button.single_add_to_cart_button,.single_add_to_cart_button',function (e) {
4351
4352                    var $button = $(this);
4353                    var $prod_info = $button.siblings('.pys_list_name_productdata').data();
4354                    Cookies.set('productlist', $prod_info, { expires: 1 })
4355                });
4356            }
4357
4358            // WooCommerce Affiliate
4359            if (options.dynamicEvents.hasOwnProperty("woo_affiliate")) {
4360
4361                // Loop, external
4362                $('.product_type_external').on("click",function (e) {
4363
4364                    var product_id = $(this).data('product_id');
4365
4366                    if (typeof product_id !== 'undefined') {
4367                        Facebook.onWooAffiliateEvent(product_id);
4368                        Analytics.onWooAffiliateEvent(product_id);
4369                        GAds.onWooAffiliateEvent(product_id);
4370                        Pinterest.onWooAffiliateEvent(product_id);
4371                        Bing.onWooAffiliateEvent(product_id);
4372                    }
4373
4374                });
4375
4376            }
4377
4378            // WooCommerce RemoveFromCart
4379            if (options.dynamicEvents.hasOwnProperty("woo_remove_from_cart")) {
4380
4381                $('body').on('click', options.woo.removeFromCartSelector, function (e) {
4382
4383                    var $a = $(e.currentTarget),
4384                        href = $a.attr('href');
4385
4386                    // extract cart item hash from remove button URL
4387                    var regex = new RegExp("[\\?&]remove_item=([^&#]*)"),
4388                        results = regex.exec(href);
4389
4390                    if (results !== null) {
4391
4392                        var item_hash = results[1];
4393
4394                        if (options.dynamicEvents["woo_remove_from_cart"].hasOwnProperty(item_hash)) {
4395                            var events = options.dynamicEvents["woo_remove_from_cart"][item_hash];
4396                            Utils.fireEventForAllPixel("onWooRemoveFromCartEvent",events)
4397                        }
4398
4399                    }
4400
4401                });
4402
4403            }
4404
4405            // WooCommerce PayPal
4406            if (options.dynamicEvents.hasOwnProperty("woo_paypal")) {
4407
4408                // Non-default binding used to avoid situations when some code in external js
4409                // stopping events propagation, eg. returns false, and our handler will never called
4410                $(document).onFirst('submit click', '#place_order', function (e) {
4411
4412                    var method = $('form[name="checkout"] input[name="payment_method"]:checked').val();
4413
4414                    if (method !== 'paypal') {
4415                        return;
4416                    }
4417                    var events = options.dynamicEvents.woo_paypal;
4418                    Utils.fireEventForAllPixel("onWooPayPalEvent",events)
4419
4420                });
4421
4422            }
4423
4424            // WooCommerce checkout progress
4425            if(options.dynamicEvents.hasOwnProperty("woo_initiate_checkout_progress_f") ) {
4426
4427                $(document).on("change",".woocommerce-validated #billing_first_name",function () {
4428                    Analytics.onWooCheckoutProgressStep(options.dynamicEvents.woo_initiate_checkout_progress_f[Analytics.tag()]);
4429                });
4430            }
4431            if(options.dynamicEvents.hasOwnProperty("woo_initiate_checkout_progress_l")) {
4432
4433                $(document).on("change",".woocommerce-validated #billing_last_name",function () {
4434                    Analytics.onWooCheckoutProgressStep(options.dynamicEvents.woo_initiate_checkout_progress_l[Analytics.tag()]);
4435                });
4436            }
4437
4438            if(options.dynamicEvents.hasOwnProperty("woo_initiate_checkout_progress_e")) {
4439
4440                $(document).on("change",".woocommerce-validated #billing_email",function () {
4441                    Analytics.onWooCheckoutProgressStep(options.dynamicEvents.woo_initiate_checkout_progress_e[Analytics.tag()]);
4442                });
4443            }
4444            if(options.dynamicEvents.hasOwnProperty("woo_initiate_checkout_progress_o")) {
4445                $(document).onFirst('submit click', '#place_order', function () {
4446                    Analytics.onWooCheckoutProgressStep(options.dynamicEvents.woo_initiate_checkout_progress_o[Analytics.tag()]);
4447                });
4448            }
4449
4450
4451            // WooCommerce
4452            if(options.dynamicEvents.hasOwnProperty("woo_select_content_search") ||
4453                options.dynamicEvents.hasOwnProperty("woo_select_content_shop") ||
4454                options.dynamicEvents.hasOwnProperty("woo_select_content_tag") ||
4455                options.dynamicEvents.hasOwnProperty("woo_select_content_single") ||
4456                options.dynamicEvents.hasOwnProperty("woo_select_content_category")
4457            ) {
4458                $('.product.type-product a.woocommerce-loop-product__link').onFirst('click', function (evt) {
4459                    var productId = $(this).parent().find("a.add_to_cart_button").attr("data-product_id");
4460                    if(options.dynamicEvents.hasOwnProperty("woo_select_content_search") &&
4461                        options.dynamicEvents.woo_select_content_search.hasOwnProperty(productId)) {
4462                        Analytics.onWooSelectContent(options.dynamicEvents.woo_select_content_search[productId][Analytics.tag()]);
4463                    } else if(options.dynamicEvents.hasOwnProperty("woo_select_content_shop") &&
4464                        options.dynamicEvents.woo_select_content_shop.hasOwnProperty(productId)) {
4465                        Analytics.onWooSelectContent(options.dynamicEvents.woo_select_content_shop[productId][Analytics.tag()]);
4466                    } else if(options.dynamicEvents.hasOwnProperty("woo_select_content_tag") &&
4467                        options.dynamicEvents.woo_select_content_tag.hasOwnProperty(productId)) {
4468                        Analytics.onWooSelectContent(options.dynamicEvents.woo_select_content_tag[productId][Analytics.tag()]);
4469                    } else if(options.dynamicEvents.hasOwnProperty("w
4469oo_select_content_single") &&
4470                        options.dynamicEvents.woo_select_content_single.hasOwnProperty(productId)) {
4471                        Analytics.onWooSelectContent(options.dynamicEvents.woo_select_content_single[productId][Analytics.tag()]);
4472                    } else if(options.dynamicEvents.hasOwnProperty("woo_select_content_category") &&
4473                        options.dynamicEvents.woo_select_content_category.hasOwnProperty(productId)) {
4474                        Analytics.onWooSelectContent(options.dynamicEvents.woo_select_content_category[productId][Analytics.tag()]);
4475                    }
4476                });
4477            }
4478        }
4479
4480        // setup EDD events
4481        if (options.edd.enabled) {
4482
4483            // EDD AddToCart
4484            if (options.dynamicEvents.hasOwnProperty("edd_add_to_cart_on_button_click")) {
4485
4486                $('form.edd_download_purchase_form .edd-add-to-cart').on("click",function (e) {
4487
4488                    var $button = $(this);
4489                    var $form = $button.closest('form');
4490                    var variable_price = $button.data('variablePrice'); // yes/no
4491                    var price_mode = $button.data('priceMode'); // single/multi
4492                    var ids = [];
4493                    var quantities = [];
4494                    var qty;
4495                    var id;
4496
4497                    if (variable_price === 'yes' && price_mode === 'multi') {
4498
4499                        id = $form.find('input[name="download_id"]').val();
4500
4501                        // get selected variants
4502                        $.each($form.find('input[name="edd_options[price_id][]"]:checked'), function (i, el) {
4503                            ids.push(id + '_' + $(el).val());
4504                        });
4505
4506                        // get qty for selected variants
4507                        $.each(ids, function (i, variant_id) {
4508
4509                            var variant_index = variant_id.split('_', 2);
4510                            qty = $form.find('input[name="edd_download_quantity_' + variant_index[1] + '"]').val();
4511
4512                            if (typeof qty !== 'undefined') {
4513                                quantities.push(qty);
4514                            } else {
4515                                quantities.push(1);
4516                            }
4517
4518                        });
4519
4520                    } else if (variable_price === 'yes' && price_mode === 'single') {
4521
4522                        id = $form.find('input[name="download_id"]').val();
4523                        ids.push(id + '_' + $form.find('input[name="edd_options[price_id][]"]:checked').val());
4524
4525                        qty = $form.find('input[name="edd_download_quantity"]').val();
4526
4527                        if (typeof qty !== 'undefined') {
4528                            quantities.push(qty);
4529                        } else {
4530                            quantities.push(1);
4531                        }
4532
4533                    } else {
4534
4535                        ids.push($button.data('downloadId'));
4536
4537                        qty = $form.find('input[name="edd_download_quantity"]').val();
4538
4539                        if (typeof qty !== 'undefined') {
4540                            quantities.push(qty);
4541                        } else {
4542                            quantities.push(1);
4543                        }
4544                    }
4545
4546                    // fire event for each download/variant
4547                    $.each(ids, function (i, download_id) {
4548
4549                        var q = parseInt(quantities[i]);
4550                        var variant_index = download_id.toString().split('_', 2);
4551                        var price_index;
4552
4553                        if (variant_index.length === 2) {
4554                            download_id = variant_index[0];
4555                            price_index = variant_index[1];
4556                        }
4557
4558                        Facebook.onEddAddToCartOnButtonEvent(download_id, price_index, q);
4559                        Analytics.onEddAddToCartOnButtonEvent(download_id, price_index, q);
4560                        GAds.onEddAddToCartOnButtonEvent(download_id, price_index, q);
4561                        Pinterest.onEddAddToCartOnButtonEvent(download_id, price_index, q);
4562                        Bing.onEddAddToCartOnButtonEvent(download_id, price_index, q);
4563                        TikTok.onEddAddToCartOnButtonEvent(download_id, price_index, q);
4564
4565                    });
4566
4567                });
4568
4569            }
4570
4571            // EDD RemoveFromCart
4572            if (options.dynamicEvents.hasOwnProperty("edd_remove_from_cart") ) {
4573
4574                $('form#edd_checkout_cart_form .edd_cart_remove_item_btn').on("click",function (e) {
4575
4576                    var href = $(this).attr('href');
4577                    var key = href.substring(href.indexOf('=') + 1).charAt(0);
4578
4579                    if (options.dynamicEvents.edd_remove_from_cart.hasOwnProperty(key)) {
4580                        var events = options.dynamicEvents.edd_remove_from_cart[key];
4581                        Utils.fireEventForAllPixel("onEddRemoveFromCartEvent",events)
4582                    }
4583
4584                });
4585
4586            }
4587
4588        }
4589
4590        Utils.setupURLClickEvents();
4591
4592        // setup Comment Event
4593        if (options.dynamicEvents.hasOwnProperty("automatic_event_comment")
4594        ) {
4595
4596            $('form.comment-form').on("submit",function () {
4597                if (options.dynamicEvents.hasOwnProperty("automatic_event_comment")) {
4598                    var pixels = Object.keys(options.dynamicEvents.automatic_event_comment);
4599                    for (var i = 0; i < pixels.length; i++) {
4600                        var event = Utils.clone(options.dynamicEvents.automatic_event_comment[pixels[i]]);
4601                        Utils.copyProperties(Utils.getRequestParams(), event.params);
4602                        getPixelBySlag(pixels[i]).onCommentEvent(event);
4603                    }
4604                }
4605            });
4606
4607        }
4608
4609        // setup Form Event
4610        if ( options.dynamicEvents.hasOwnProperty("automatic_event_form")) {
4611
4612            $(document).onFirst('submit', 'form', function (e) {
4613
4614                var $form = $(this);
4615
4616                // exclude WP forms
4617                if ($form.hasClass('comment-form') || $form.hasClass('search-form') || $form.attr('id') === 'adminbarsearch') {
4618                    return;
4619                }
4620
4621                // exclude Woo forms
4622                if ($form.hasClass('woocommerce-product-search') || $form.hasClass('cart') || $form.hasClass('woocommerce-cart-form') ||
4623                    $form.hasClass('woocommerce-shipping-calculator') || $form.hasClass('checkout') || $form.hasClass('checkout_coupon')) {
4624                    return;
4625                }
4626
4627                // exclude EDD forms
4628                if ($form.hasClass('edd_form') || $form.hasClass('edd_download_purchase_form')) {
4629                    return;
4630                }
4631                // exclude CF7 forms
4632                if ($form.hasClass('wpcf7-form')) {
4633                    return;
4634                }
4635                // exclude Gravity forms
4636                if ($form.attr('id') && $form.attr('id').includes('gform')) {
4637                    var target = $form.attr('target');
4638                    if (target && target.indexOf('gform_ajax_frame') !== -1) {
4639                        return;
4640                    }
4641                }
4642                // exclude Forminator forms
4643                if ($form.hasClass('forminator-custom-form') || $form.hasClass('forminator_ajax')) {
4644                    return;
4645                }
4646                // exclude WPforms forms
4647                if ($form.hasClass('wpforms-form') || $form.hasClass('wpforms-ajax-form')) {
4648                    return;
4649                }
4650                // exclude Formidable forms
4651                /*if ($form.hasClass('frm-show-form')) {
4652                    return;
4653                }*/
4654                // exclude Ninja Forms forms
4655                if ($form.parent().hasClass('nf-form-layout')) {
4656                    return;
4657                }
4658                // exclude Fluent forms
4659                if ($form.hasClass('frm-fluent-form')) {
4660                    return;
4661                }
4662                if(!options.enable_success_send_form) {
4663                    var params = {
4664                        form_id: $form.attr('id'),
4665                        form_class: $form.attr('class') ? $form.attr('class') : $form.attr('id'),
4666                        text: $form.find('[type="submit"]').is('input') ?
4667                            $form.find('[type="submit"]').val() : $form.find('[type="submit"]').text()
4668                    };
4669
4670                    if (options.dynamicEvents.hasOwnProperty("automatic_event_form")) {
4671                        var pixels = Object.keys(options.dynamicEvents.automatic_event_form);
4672                        for (var i = 0; i < pixels.length; i++) {
4673                            var event = Utils.clone(options.dynamicEvents.automatic_event_form[pixels[i]]);
4674
4675                            if (pixels[i] === "tiktok") {
4676                                getPixelBySlag(pixels[i]).fireEvent(event.name, event);
4677                            } else {
4678                                Utils.copyProperties(params, event.params,)
4679                                Utils.copyProperties(Utils.getRequestParam
4679s(), event.params);
4680                                getPixelBySlag(pixels[i]).onFormEvent(event);
4681                            }
4682                        }
4683                    }
4684                }
4685            });
4686
4687
4688        }
4689
4690        jQuery(document).on('elementor/popup/show', function(event) {
4691            for (var i = 0; i < jQuery(".wpcf7-form").length; i++) {
4692                wpcf7.init(jQuery(".wpcf7-form")[i]);
4693            }
4694        });
4695        document.addEventListener( 'wpcf7mailsent', function( event ) {
4696            var form_id = event.detail.contactFormId;
4697            var sendEventId = null;
4698            var disabled_form_action = false;
4699            if(options.triggerEventTypes.hasOwnProperty('CF7'))
4700            {
4701                key_event = Object.keys(options.triggerEventTypes.CF7)[0];
4702                if(options.triggerEventTypes.CF7[key_event].hasOwnProperty('disabled_form_action'))
4703                {
4704                    disabled_form_action = options.triggerEventTypes.CF7[key_event].disabled_form_action;
4705                }
4706                $.each(options.triggerEventTypes.CF7, function (eventId, triggers) {
4707                    $.each(triggers.forms, function (index, value) {
4708                        if(value == form_id) {
4709                            sendEventId=eventId;
4710                        };
4711                    });
4712                });
4713            }
4714            if(sendEventId != null)
4715            {
4716                Utils.fireTriggerEvent(sendEventId);
4717
4718                if(!disabled_form_action)
4719                {
4720                    sendFormAction($(event.target), form_id);
4721                }
4722            }
4723            else {
4724                sendFormAction($(event.target), form_id);
4725            }
4726        }, false );
4727
4728
4729        //GravityForm
4730        jQuery(document).on('gform_confirmation_loaded', function(event, formId){
4731            var form_id = formId;
4732            var sendEventId = null;
4733            var disabled_form_action = false;
4734            if(options.triggerEventTypes.hasOwnProperty('gravity'))
4735            {
4736                key_event = Object.keys(options.triggerEventTypes.gravity)[0];
4737                if(options.triggerEventTypes.gravity[key_event].hasOwnProperty('disabled_form_action'))
4738                {
4739                    disabled_form_action = options.triggerEventTypes.gravity[key_event].disabled_form_action;
4740                }
4741                $.each(options.triggerEventTypes.gravity, function (eventId, triggers) {
4742                    $.each(triggers.forms, function (index, value) {
4743                        if(value == form_id) {
4744                            sendEventId=eventId;
4745                        };
4746                    });
4747                });
4748            }
4749            if(sendEventId != null)
4750            {
4751                Utils.fireTriggerEvent(sendEventId);
4752
4753                if(!disabled_form_action)
4754                {
4755                    sendFormAction($(event.target), form_id);
4756                }
4757            }
4758            else {
4759                sendFormAction($(event.target), form_id);
4760            }
4761        });
4762        //Forminator
4763        $(document).on( 'forminator:form:submit:success', function( event ){
4764            var form_id = $(event.target).find('input[name="form_id"]').val();
4765            var sendEventId = null;
4766            var disabled_form_action = false;
4767            if(options.triggerEventTypes.hasOwnProperty('forminator'))
4768            {
4769                key_event = Object.keys(options.triggerEventTypes.forminator)[0];
4770                if(options.triggerEventTypes.forminator[key_event].hasOwnProperty('disabled_form_action'))
4771                {
4772                    disabled_form_action = options.triggerEventTypes.forminator[key_event].disabled_form_action;
4773                }
4774                $.each(options.triggerEventTypes.forminator, function (eventId, triggers) {
4775                    $.each(triggers.forms, function (index, value) {
4776                        if(value == form_id) {
4777                            sendEventId=eventId;
4778                        };
4779                    });
4780                });
4781            }
4782            if(sendEventId != null)
4783            {
4784                Utils.fireTriggerEvent(sendEventId);
4785
4786                if(!disabled_form_action)
4787                {
4788                    sendFormAction($(event.target), form_id);
4789                }
4790            }
4791            else {
4792                sendFormAction($(event.target), form_id);
4793            }
4794
4795        });
4796
4797        //WPForm
4798        $('form.wpforms-form').on('wpformsAjaxSubmitSuccess', (event) => {
4799            var form_id = $(event.target).attr('data-formid');
4800            var sendEventId = null;
4801            var disabled_form_action = false;
4802            if(options.triggerEventTypes.hasOwnProperty('wpforms'))
4803            {
4804                key_event = Object.keys(options.triggerEventTypes.wpforms)[0];
4805                if(options.triggerEventTypes.wpforms[key_event].hasOwnProperty('disabled_form_action'))
4806                {
4807                    disabled_form_action = options.triggerEventTypes.wpforms[key_event].disabled_form_action;
4808                }
4809                $.each(options.triggerEventTypes.wpforms, function (eventId, triggers) {
4810                    $.each(triggers.forms, function (index, value) {
4811                        if(value == form_id) {
4812                            sendEventId=eventId;
4813                        };
4814                    });
4815                });
4816            }
4817            if(sendEventId != null)
4818            {
4819                Utils.fireTriggerEvent(sendEventId);
4820
4821                if(!disabled_form_action)
4822                {
4823                    sendFormAction($(event.target), form_id);
4824                }
4825            }
4826            else {
4827                sendFormAction($(event.target), form_id);
4828            }
4829        })
4830        $(document).on( 'frmFormComplete', function( event, form, response ) {
4831            const form_id = $(form).find('input[name="form_id"]').val();
4832            var sendEventId = null;
4833            var disabled_form_action = false;
4834            if(options.triggerEventTypes.hasOwnProperty('formidable'))
4835            {
4836                key_event = Object.keys(options.triggerEventTypes.formidable)[0];
4837                if(options.triggerEventTypes.formidable[key_event].hasOwnProperty('disabled_form_action'))
4838                {
4839                    disabled_form_action = options.triggerEventTypes.formidable[key_event].disabled_form_action;
4840                }
4841                $.each(options.triggerEventTypes.formidable, function (eventId, triggers) {
4842                    $.each(triggers.forms, function (index, value) {
4843                        if(value == form_id) {
4844                            sendEventId=eventId;
4845                        };
4846                    });
4847                });
4848            }
4849            if(sendEventId != null)
4850            {
4851                Utils.fireTriggerEvent(sendEventId);
4852
4853                if(!disabled_form_action)
4854                {
4855                    sendFormAction($(event.target), form_id);
4856                }
4857            }
4858            else {
4859                sendFormAction($(event.target), form_id);
4860            }
4861        });
4862        // Ninja Forms
4863        $(document).onFirst('nfFormSubmitResponse', function (event, data) {
4864            const form_id = data.response.data.form_id;
4865            var sendEventId = null;
4866            var disabled_form_action = false;
4867            if(options.triggerEventTypes.hasOwnProperty('ninjaform'))
4868            {
4869                key_event = Object.keys(options.triggerEventTypes.ninjaform)[0];
4870                if(options.triggerEventTypes.ninjaform[key_event].hasOwnProperty('disabled_form_action'))
4871                {
4872                    disabled_form_action = options.triggerEventTypes.ninjaform[key_event].disabled_form_action;
4873                }
4874                $.each(options.triggerEventTypes.ninjaform, function (eventId, triggers) {
4875                    $.each(triggers.forms, function (index, value) {
4876                        if(value == form_id) {
4877                            sendEventId=eventId;
4878                        };
4879                    });
4880                });
4881            }
4882            if(sendEventId != null)
4883            {
4884                Utils.fireTriggerEvent(sendEventId);
4885
4886                if(!disabled_form_action)
4887                {
4888                    sendFormAction($(event.target), form_id);
4889                }
4890            }
4891            else {
4892                sendFormAction($(event.target), form_id);
4893            }
4894        });
4895
4896        var fluentForms = $('form.frm-fluent-form');
4897        fluentForms.each(function() {
4898            var $form = $(this);
4899            $form.on('fluentform_submission_success', function(event) {
4900                var $formItem = $(this);
4901                var form_id = $formItem.attr('data-form_id');
4902                var sendEventId = null;
4903                var disabled_form_action = false;
4904                if(options.triggerEventTypes.hasOwnProperty('fluentform'))
4905                {
4906                    key_event = Object.keys(options.triggerEventTypes.fluentform)[0];
4907                    if(options.triggerEventTypes.fluentform[key_event].hasOwnProperty('disabled_form_action'))
4908                    {
4909                        disabled_form_action = options.triggerEventTypes.fluentform[key_event].disabled_form_action;
4910                    }
4911                    $.each(options.triggerEventTypes.fluentform, function (eventId, triggers) {
4912                        $.each(triggers.forms, function (index, value) {
4913                            if(value == form_id) {
4914                                sendEventId=eventId;
4915                            };
4916                        });
4917                    });
4918                }
4919                if(sendEventId != null)
4920                {
4921                    Utils.fireTriggerEvent(sendEventId);
4922
4923                    if(!disabled_form_action)
4924                    {
4925                        sendFormAction($(event.target), form_id);
4926                    }
4927                }
4928                else {
4929                    sendFormAction($(event.target), form_id);
4930                }
4931            });
4932        });
4933        // load pixel APIs
4934        Utils.loadPixels();
4935
4936        // setup Enrich content
4937        if(Utils.isCheckoutPage()) {
4938            Utils.addCheckoutFields();
4939        }
4940    });
4941
4942
4943    // load WatchVideo event APIs for Auto
4944    if (options.automatic.enable_video) {
4945        /**
4946         * Real Cookie Banner.
4947         */
4948        var consentApi = window.consentApi;
4949        if (consentApi && options.gdpr.real_cookie_banner_integration_enabled) {
4950            if (options.automatic.enable_youtube && options.enable_event_video && options.enable_automatic_events) {
4951                window.consentApi.consent("http", "CONSENT", ".youtube.com").then(Utils.initYouTubeAPI);
4952            }
4953            if (options.automatic.enable_vimeo && options.enable_event_video && options.enable_automatic_events) {
4954                window.consentApi.consent("http", "player", ".vimeo.com").then(Utils.initVimeoAPI);
4955            }
4956        }else{
4957            if (options.automatic.enable_youtube && options.enable_event_video && options.enable_automatic_events) {
4958                Utils.initYouTubeAPI();
4959            }
4960            if (options.automatic.enable_vimeo && options.enable_event_video && options.enable_automatic_events) {
4961                Utils.initVimeoAPI();
4962            }
4963        }
4964    }
4965
4966    var sendFormAction = function (form_target, formId){
4967        var params = {
4968                form_id: formId,
4969                text: form_target.find('[type="submit"]').is('input') ? form_target.find('[type="submit"]').val() :
4970                    form_target.find('.forminator-button-submit').text() != '' ? form_target.find('.forminator-button-submit').text() :
4971                    form_target.find('[type="submit"]').text()
4972            };
4973
4974            if (options.dynamicEvents.hasOwnProperty("automatic_event_form")) {
4975                var pixels = Object.keys(options.dynamicEvents.automatic_event_form);
4976                for (var i = 0; i < pixels.length; i++) {
4977                    var event = options.dynamicEvents.automatic_event_form[pixels[i]];
4978                    if (pixels[i] === "tiktok") {
4979                        getPixelBySlag(pixels[i]).fireEvent(event.name, event);
4980                    } else {
4981                        Utils.copyProperties(params, event.params)
4982                        Utils.copyProperties(Utils.getRequestParam
4982s(), event.params);
4983                        getPixelBySlag(pixels[i]).onFormEvent(event);
4984                    }
4985                }
4986            }
4987    }
4988
4989
4990}(jQuery, pysOptions);
4991
4992function pys_generate_token(length){
4993    //edit the token allowed characters
4994    var a = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890".split("");
4995    var b = [];
4996    for (var i=0; i<length; i++) {
4997        var j = (Math.random() * (a.length-1)).toFixed(0);
4998        b[i] = a[j];
4999    }
5000    return b.join("");
5001}
5002
5003function getBundlePriceOnSingleProduct(data) {
5004    var items_sum = 0;
5005    jQuery(".bundle_form .bundled_product").each(function(index){
5006        var id = jQuery(this).find(".cart").data("bundled_item_id");
5007        var item_price = data.prices[id];
5008        var item_quantity = jQuery(this).find(".bundled_qty").val();
5009        if(!jQuery(this).hasClass("bundled_item_optional") ||
5010            jQuery(this).find(".bundled_product_optional_checkbox input").prop('checked')) {
5011            items_sum += item_price*item_quantity;
5012        }
5013    });
5014    return items_sum;
5015}
5016
5017function getPixelBySlag(slug) {
5018    switch (slug) {
5019        case "facebook": return window.pys.Facebook;
5020        case "ga": return window.pys.Analytics;
5021        case "google_ads": return window.pys.GAds;
5022        case "bing": return window.pys.Bing;
5023        case "pinterest": return window.pys.Pinterest;
5024        case "tiktok": return window.pys.TikTok;
5025    }
5026}
5027var getUrlParameter = function getUrlParameter(sParam) {
5028    var sPageURL = window.location.search.substring(1),
5029        sURLVariables = sPageURL.split('&'),
5030        sParameterName,
5031        i;
5032
5033    for (i = 0; i < sURLVariables.length; i++) {
5034        sParameterName = sURLVariables[i].split('=');
5035
5036        if (sParameterName[0] === sParam) {
5037            return sParameterName[1] === undefined ? true : decodeURIComponent(sParameterName[1]);
5038        }
5039    }
5040    return false;
5041};
5042function inArray(needle, haystack) {
5043    var length = haystack.length;
5044    for(var i = 0; i < length; i++) {
5045        if(haystack[i] == needle) return true;
5046    }
5047    return false;
5048}

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.