PageSourceSearch

https://redesurftank.com.br/themes/wc_surf/wc_js/recharge.js?v=1790699681

js redesurftank.com.br collected 2026-10-02 01:18:37 UTC 52,679 bytes, 1,277 lines download raw bytes

1BASE = $("link[rel='base']").attr("href");
2var selectUserID;
3var selectAreaID;
4
5// GTM dataLayer: guarda o item atualmente selecionado no fluxo de recarga pra reutilizar
6// entre etapas (select_item -> add_to_cart -> begin_checkout -> add_payment_info -> purchase).
7// O order_id só existe a partir do begin_checkout; antes disso é null.
8var currentRechargeItem = null;
9// Carrinho de pacotes: array de itens do GTM (add_to_cart/begin_checkout/purchase).
10// Espelha o carrinho do servidor; nos fluxos legados (avulso/passe) carrega 1 item.
11var currentRechargeItems = [];
12var currentRechargeOrder = null;
13
14function dlPush(payload) {
15    try {
16        window.dataLayer = window.dataLayer || [];
17        // GA4/GTM: limpa o objeto ecommerce anterior antes de cada push de ecommerce
18        if (payload && Object.prototype.hasOwnProperty.call(payload, 'ecommerce')) {
19            window.dataLayer.push({ 'ecommerce': null });
20        }
21        window.dataLayer.push(payload);
22    } catch (e) {}
23}
24
25// Dados de compra devolvidos pelo payment.php (order_code, order_value = valor final pago,
26// is_first_purchase, track, user_id), por order_id.
27var rechargeTrackInfo = {};
28function rememberTrackInfo(orderId, data) {
29    if (!orderId || !data || !data.order_code) return;
30    rechargeTrackInfo[String(orderId)] = {
31        'order_code': data.order_code,
32        'order_value': data.order_value,
33        'is_first_purchase': !!data.is_first_purchase,
34        'track': data.track !== false,
35        'user_id': data.user_id || null
36    };
37}
38
39var verifyPayment = {
40    _timersByOrder: {},
41    _abortByOrder: {},
42    _activeByOrder: {},
43    stopAll: function () {
44        var self = this;
45        Object.keys(self._timersByOrder).forEach(function (k) {
46            clearTimeout(self._timersByOrder[k]);
47            delete self._timersByOrder[k];
48        });
49        Object.keys(self._abortByOrder).forEach(function (k) {
50            try { self._abortByOrder[k].abort(); } catch (e) {}
51            delete self._abortByOrder[k];
52        });
53        Object.keys(self._activeByOrder).forEach(function (k) {
54            delete self._activeByOrder[k];
55        });
56    },
57    stop: function (orderId) {
58        var key = String(orderId || '');
59        if (!key) return;
60        if (this._timersByOrder[key]) {
61            clearTimeout(this._timersByOrder[key]);
62            delete this._timersByOrder[key];
63        }
64        if (this._abortByOrder[key]) {
65            try { this._abortByOrder[key].abort(); } catch (e) {}
66            delete this._abortByOrder[key];
67        }
68        delete this._activeByOrder[key];
69    },
70    init: function (config) {
71        var self = this;
72
73        var orderKey = String(config.order_id || '');
74        if (!orderKey) return;
75
76        self._activeByOrder[orderKey] = true;
77
78        if (self._timersByOrder[orderKey]) {
79            clearTimeout(self._timersByOrder[orderKey]);
80        }
81        if (self._abortByOrder[orderKey]) {
82            try { self._abortByOrder[orderKey].abort(); } catch (e) {}
83        }
84
85        var controller = null;
86        try { controller = new AbortController(); } catch (e) {}
87        if (controller) self._abortByOrder[orderKey] = controller;
88
89        self._timersByOrder[orderKey] = setTimeout(function () {
90            if (!self._activeByOrder[orderKey]) return;
91
92            $.ajax({
93                url: '/_cdn/widgets/pay/payment.php',
94                data: "payment=" + config.payment + "&order_id=" + config.order_id + "&automatic=" + config.automatic,
95                type: 'POST',
96                dataType: 'json',
97                signal: controller ? controller.signal : undefined,
98                success: function (data) {
99                    if (!self._activeByOrder[orderKey]) return;
100                    if (data && data.aproved) {
101                        self.stop(orderKey);
102                        config.success(data);
103                    }
104                },
105                error: function () {
106                    if (!self._activeByOrder[orderKey]) return;
107                    if ($('#recharge').is(':visible') && $('.jwc_pay').attr('data-order-id') == config.order_id && $("a#title-back-id").attr("data-back") == 3) {
108                        verifyPayment.init(config);
109                    }
110                }
111            });
112        }, config.timeout || 1000);
113    }
114};
115
116function initRecharge(areaID, userID) {
117    var load = $(".ajax_load");
118
119    load.fadeIn(200).css("display", "flex");
120    $(".modal-recharge .part-1").show();
121    $(".modal-recharge .part-2").hide();
122    $(".modal-recharge .part-3").hide();
123    $('#recharge').modal('show');
124    load.fadeOut();
125
126    $('#pix-discount').show();
127
128    // GTM dataLayer: view_item_list — varre os botões .coupon-select-input dentro do
129    // modal de recarga e monta o array de items. Como os produtos são renderizados
130    // server-side no template (product.php / product-only-cps.php / product-battle-pass.php),
131    // esse é o único ponto natural de emitir view_item_list.
132    try {
133        var items = [];
134        $('#recharge .coupon-select-input').each(function () {
135            var $b = $(this);
136            var id = $b.attr('id') || '';
137            var priceAttr = $b.attr('data-price');
138            var price = priceAttr ? parseFloat(priceAttr) : 0;
139            var name = $b.attr('data-name') || '';
140            var onlyCps = $b.attr('data-only-cps');
141            var isBp = String($b.attr('data-battle-pass') || '').toLowerCase() === 'true';
142            var itemId;
143            var category = 'recharge';
144            if (isBp) {
145                itemId = 'battle_pass';
146                category = 'battle_pass';
147            } else if (onlyCps) {
148                itemId = 'only_cps_' + onlyCps;
149            } else {
150                itemId = String(id);
151            }
152            if (name || price) {
153                items.push({
154                    'item_id': itemId,
155                    'item_name': name || itemId,
156                    'price': price,
157                    'item_category': category
158                });
159            }
160        });
161        if (items.length) {
162            dlPush({
163                'event': 'view_item_list',
164                'ecommerce': {
165                    'currency': 'BRL',
166                    'item_list_name': 'Recarga de Cupons',
167                    'items': items
168                }
169            });
170        }
171    } catch (e) {}
172
173    if (areaID) {
174        selectAreaID = areaID;
175        $('#server').val(areaID).change();
176        if (userID) {
177            selectUserID = userID;
178        }
179    }
180}
181
182$(function () {
183    $('.verify_pix_manual').click(function () {
184        var order_id = $(this).attr('data-order');
185        verifyPayment.init({
186            payment: 'verify_paymentpix',
187            order_id: order_id,
188            automatic: 0,
189            timeout: 100,
190            success: function (data) {
191                alert('Pagamento Confirmado');
192                window.location.reload();
193            }
194        });
195    });
196
197    if ($('*[rel*="shadowbox"]').length) {
198        $("head").append('<link rel="stylesheet" href="' + BASE + '/_cdn/shadowbox/sh
198adowbox.css">');
199        $.getScript(BASE + '/_cdn/shadowbox/shadowbox.js', function () {
200            Shadowbox.init();
201        });
202    }
203
204    var base = $('link[rel="base"]').attr('href') + "/_cdn/widgets/ddtanksystem/account";
205    var action = $('link[rel="base"]').attr('href') + "/_cdn/widgets/ecommerce/cart.ajax.php";
206    BASE = $("link[rel='base']").attr("href");
207
208    function wcCartTrigger(Message) {
209        if (Message) {
210            $('.wc_cart_callback').html('').fadeOut(1).css('right', '-400px');
211
212            $('.wc_cart_callback').html(Message).fadeIn(400);
213            $('.wc_cart_callback').animate({ 'right': '0' }, 100);
214
215            $('.wc_cart_callback').click(function () {
216                $(this).fadeOut(400, function () {
217                    $(this).html('').css('right', '-400px');
218                });
219            });
220        } else {
221            $('.wc_cart_callback').fadeOut(1, function () {
222                $(this).html('').css('right', '-400px');
223            });
224        }
225    }
226
227    function openOverlay(overlayId, onConfirm, onCancel) {
228        var overlay = document.getElementById(overlayId);
229        if (!overlay) {
230            if (confirm('Deseja continuar?')) {
231                if (onConfirm) onConfirm();
232            } else {
233                if (onCancel) onCancel();
234            }
235            return;
236        }
237
238        overlay.style.display = 'flex';
239        overlay.setAttribute('aria-hidden', 'false');
240        document.body.style.overflow = 'hidden';
241
242        function close() {
243            overlay.style.display = 'none';
244            overlay.setAttribute('aria-hidden', 'true');
245            document.body.style.overflow = '';
246            overlay.removeEventListener('click', onOverlayClick, true);
247            document.removeEventListener('keydown', onKeyDown, true);
248            confirmBtn && confirmBtn.removeEventListener('click', onConfirmClick, true);
249            cancelBtn && cancelBtn.removeEventListener('click', onCancelClick, true);
250            closeBtns.forEach(function (b) { b.removeEventListener('click', onCancelClick, true); });
251        }
252
253        function onConfirmClick(e) {
254            e.preventDefault();
255            close();
256            if (onConfirm) onConfirm();
257        }
258
259        function onCancelClick(e) {
260            e.preventDefault();
261            close();
262            if (onCancel) onCancel();
263        }
264
265        function onOverlayClick(e) {
266            if (e.target === overlay) {
267                onCancelClick(e);
268            }
269        }
270
271        function onKeyDown(e) {
272            if (e.key === 'Escape') {
273                onCancelClick(e);
274            }
275        }
276
277        var confirmBtn = overlay.querySelector('[data-ovl-confirm]');
278        var cancelBtn = overlay.querySelector('[data-ovl-cancel]');
279        var closeBtns = Array.prototype.slice.call(overlay.querySelectorAll('[data-ovl-close]'));
280
281        overlay.addEventListener('click', onOverlayClick, true);
282        document.addEventListener('keydown', onKeyDown, true);
283        if (confirmBtn) confirmBtn.addEventListener('click', onConfirmClick, true);
284        if (cancelBtn) cancelBtn.addEventListener('click', onCancelClick, true);
285        closeBtns.forEach(function (b) { b.addEventListener('click', onCancelClick, true); });
286    }
287
288    function togglePixDiscount(shouldShow) {
289        if ($('#pix-discount').length) {
290            if (shouldShow) $('#pix-discount').show();
291            else $('#pix-discount').hide();
292        }
293    }
294
295    // GTM dataLayer: purchase — disparado quando o client observa a confirmação
296    // do pagamento (via polling de verifyPayment). Idempotente: garante que não
297    // dispara 2x pro mesmo order_id. transaction_id = event_id = order_code (o mesmo
298    // event_id do evento server-side em Recharge::ApproveRecharge) e value = valor final pago.
299    // Não dispara quando o servidor marca track=false (servidor/conta de teste).
300    // Primeira compra da conta: também empurra first_purchase (event_id firstpurchase_{user_id}).
301    var _purchaseFiredFor = {};
302    function fireRechargePurchase(orderId, paymentType, verifyData) {
303        try {
304            var key = String(orderId || '');
305            if (!key || _purchaseFiredFor[key]) return;
306            if (!currentRechargeOrder || String(currentRechargeOrder.order_id) !== key) return;
307            rememberTrackInfo(key, verifyData);
308            var info = rechargeTrackInfo[key];
309            if (!info || !info.order_code) return;
310            if (info.track === false) return;
311            _purchaseFiredFor[key] = true;
312            var paidValue = (typeof info.order_value === 'number') ? info.order_value : (currentRechargeOrder.value || 0
312);
313            var items = (currentRechargeItems && currentRechargeItems.length) ? currentRechargeItems : [currentRechargeItem || {
314                'item_id': 'recharge',
315                'item_name': currentRechargeOrder.desc || 'Recarga',
316                'price': currentRechargeOrder.value || 0,
317                'item_category': 'recharge',
318                'quantity': 1
319            }];
320            dlPush({
321                'event': 'purchase',
322                'event_id': info.order_code,
323                'user_id': info.user_id,
324                'value': paidValue,
325                'currency': 'BRL',
326                'transaction_id': info.order_code,
327                'platform': 'WEB',
328                'ecommerce': {
329                    'transaction_id': info.order_code,
330                    'currency': 'BRL',
331                    'value': paidValue,
332                    'payment_type': paymentType || 'unknown',
333                    'items': items
334                }
335            });
336            if (info.is_first_purchase && info.user_id) {
337                dlPush({ 'ecommerce': null });
338                dlPush({
339                    'event': 'first_purchase',
340                    'event_id': 'firstpurchase_' + info.user_id,
341                    'user_id': info.user_id,
342                    'value': paidValue,
343                    'currency': 'BRL',
344                    'transaction_id': info.order_code,
345                    'platform': 'WEB'
346                });
347            }
348        } catch (e) {}
349    }
350
351    function handleCouponSelect($btn) {
352        var id = $btn.attr('id');
353        var isCart = String($btn.attr('data-cart') || '') === '1';
354
355        var onlyCps = parseInt(String($btn.attr('data-only-cps') || '-1'), 10);
356        if (isNaN(onlyCps)) onlyCps = -1;
357
358        var bpAttr = String($btn.attr('data-battle-pass') || '').toLowerCase();
359        var isBattlePass = (bpAttr === 'true' || bpAttr === '1');
360
361        var shouldShowPixDiscount = !(onlyCps > 0 || isBattlePass);
362        togglePixDiscount(shouldShowPixDiscount);
363
364        // GTM dataLayer: select_item (clique no botão Selecionar) — lê do DOM antes
365        // do POST porque esse é o momento em que o user "selecionou" o item.
366        try {
367            var priceAttr = $btn.attr('data-price');
368            var clickPrice = priceAttr ? parseFloat(priceAttr) : 0;
369            var clickName = $btn.attr('data-name') || '';
370            var clickItemId;
371            var clickCategory = 'recharge';
372            if (isBattlePass) {
373                clickItemId = 'battle_pass';
374                clickCategory = 'battle_pass';
375            } else if (onlyCps > 0) {
376                clickItemId = 'only_cps_' + onlyCps;
377            } else {
378                clickItemId = String(id);
379            }
380            dlPush({
381                'event': 'select_item',
382                'ecommerce': {
383                    'item_list_name': 'Recarga de Cupons',
384                    'items': [{
385                        'item_id': clickItemId,
386                        'item_name': clickName || clickItemId,
387                        'price': clickPrice,
388                        'item_category': clickCategory
389                    }]
390                }
391            });
392        } catch (e) {}
393
394        // Pacotes de recarga (data-cart): adiciona ao carrinho e re-renderiza a mini-lista,
395        // SEM pular pra Part 2. Avulso/passe seguem o fluxo legado abaixo (com o pulo).
396        if (isCart) {
397            var qty = parseInt($btn.closest('.card-body').find('.cart-qty-input').val(), 10);
398            if (isNaN(qty) || qty < 1) qty = 1;
399            if (qty > 99) qty = 99;
400
401            $.post(action, "pdt_id=" + id + "&qty=" + qty + "&action=wc_cart_add", function (resp) {
402                if (resp.trigger) {
403                    showCartNotice(resp.trigger);
404                    if (resp.cart) renderCart(resp.cart);
405                    return;
406                }
407                clearCartNotice();
408                if (resp.cart) {
409                    renderCart(resp.cart);
410                }
411                if (typeof resp.cart_amount !== 'undefined') {
412                    $('.cart_count').html(resp.cart_amount);
413                }
414                // GTM dataLayer: add_to_cart do item recem-adicionado (com a quantidade escolhida)
415                if (resp.item_id && typeof resp.item_price !== 'undefined') {
416                    var addedQty = parseInt(resp.item_qty, 10) || 1;
417                    var gtmItem = {
418                        'item_id': String(resp.item_id),
419                        'item_name': resp.item_name,
420                        'price': parseFloat(resp.item_price) || 0,
421                        'item_category': resp.item_category || 'recharge',
422                        'quantity': addedQty
423                    };
424                    dlPush({
425                        'event': 'add_to_cart',
426                        'ecommerce': {
427                            'currency': 'BRL',
428                            'value': gtmItem.price * addedQty,
429                            'items': [gtmItem]
430                        }
431                    });
432                }
433            }, 'json');
434            return;
435        }
436
437        var data = "pdt_id=" + id + "&action=wc_cart_add";
438        if (onlyCps > 0) {
439            data += "&only_cps_value=" + onlyCps;
440        } else if (isBattlePass) {
441            data += "&is_battle_pass=1";
442        }
443
444        $.post(action, data, function (data) {
445            if (data.cart_amount) {
446                $('.cart_count').html(data.cart_amount);
447            }
448            if (data.cart_product) {
449                $(".modal-recharge .part-1").hide();
450                $(".modal-recharge .part-2").show();
451                $(".title-back").show();
452                $("a#title-back-id").attr("data-back", 2);
453                $('.cupom').text(data.cart_money);
454                $('.value').text(data.cart_price);
455                $('#pricetag').val(data.cart_price1);
456                $('.NickName').val(data.NickName);
457                $('.Server').val(data.Server);
458
459                // GTM dataLayer: add_to_cart + view_item (a resposta do wc_cart_add
460                // confirma o produto escolhido e a part-2 do modal mostra os detalhes).
461                // Campos crus (data.item_id, data.item_price, data.item_name) foram
462                // adicionados em cart.ajax.php especificamente pro dataLayer.
463                if (data.item_id && typeof data.item_price !== 'undefined') {
464                    var gtmItem = {
465                        'item_id': String(data.item_id),
466                        'item_name': data.item_name || data.cart_product,
467                        'price': parseFloat(data.item_price) || 0,
468                        'item_category': data.item_category || 'recharge',
469                        'quantity': 1
470                    };
471                    currentRechargeItem = gtmItem;
472                    var itemValue = gtmItem.price;
473                    dlPush({
474                        'event': 'add_to_cart',
475                        'ecommerce': {
476                            'currency': 'BRL',
477                            'value': itemValue,
478                            'items': [gtmItem]
479                        }
480                    });
481                    dlPush({
482                        'event': 'view_item',
483                        'ecommerce': {
484                            'currency': 'BRL',
485                            'value': itemValue,
486                            'items': [gtmItem]
487                        }
488                    });
489                }
490            }
491
492            if (data.trigger) {
493                wcCartTrigger(data.trigger);
494            }
495        }, 'json');
496    }
497
498    // ===== Carrinho de pacotes (mini-cart na Part 1) =====
499    function escapeHtml(str) {
500        return String(str == null ? '' : str)
501            .replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')
502            .replace(/"/g, '&quot;').replace(/'/g, '&#39;');
503    }
504
505    // Aviso/erro do carrinho na Part 1. O .wc_cart_callback (usado por wcCartTrigger) NAO e
506    // renderizado nesta pagina, entao os erros do add/update vao pro #rcgCartNotice (visivel).
507    function showCartNotice(html) {
508        var $n = $('#rcgCartNotice');
509        if (!$n.length) { wcCartTrigger(html); return; }
510        $n.html(html).show();
511    }
512
513    function clearCartNotice() {
514        $('#rcgCartNotice').hide().html('');
515    }
516
517    function renderCart(cart) {
518        var $cart = $('#rcgCart');
519        var $items = $('#rcgCartItems');
520        if (!$cart.length) return;
521
522        if (!cart || !cart.items || !cart.items.length) {
523            $items.html('');
524            $cart.hide();
525            currentRechargeItems = [];
526            $('.cart_count').html(cart && typeof cart.total_qty !== 'undefined' ? cart.total_qty : 0);
527            return;
528        }
529
530        var html = '';
531        cart.items.forEach(function (it) {
532            html += '<div class="rcg-cart-row" data-cart-row="' + it.pdt_id + '">' +
533                '<div class="rcg-cart-row__info">' +
534                    '<div class="rcg-cart-row__name">' + escapeHtml(it.title) + '</div>' +
535                    '<div class="rcg-cart-row__meta">' + it.unit_price_fmt + ' un. &middot; ' + it.line_money_fmt + ' &middot; ' + it.line_bonus_fmt + '</div>' +
536                '</div>' +
537                '<div class="rcg-cart-row__controls">' +
538                    '<div class="rcg-stepper rcg-stepper--sm" data-cart-stepper="' + it.pdt_id + '">' +
539                        '<button type="button" class="rcg-stepper__btn" data-cart-step="-1" aria-label="Diminuir">&minus;</button>' +
540                        '<input type="text" inputmode="numeric" class="rcg-stepper__input rcg-cart-qty" value="' + it.qty + '" data-pdt="' + it.pdt_id + '" aria-label="Quantidade">' +
541                        '<button type="button" class="rcg-stepper__btn" data-cart-step="1" aria-label="Aumentar">+</button>' +
542                    '</div>' +
543                    '<div class="rcg-cart-row__total">
543' + it.line_price_fmt + '</div>' +
544                '</div>' +
545                '<a href="#" class="rcg-cart-row__remove" data-cart-remove="' + it.pdt_id + '" aria-label="Remover">&times;</a>' +
546            '</div>';
547        });
548        $items.html(html);
549        $('#rcgCartTotalPrice').text(cart.total_price_fmt);
550        $('#rcgCartTotalMoney').text(cart.total_money_fmt);
551        $('#rcgCartTotalBonus').text(cart.total_bonus_fmt);
552        $cart.show();
553
554        // espelha o carrinho no array do GTM
555        currentRechargeItems = cart.items.map(function (it) {
556            return {
557                'item_id': String(it.pdt_id),
558                'item_name': it.title,
559                'price': it.unit_price,
560                'quantity': it.qty,
561                'item_category': 'recharge'
562            };
563        });
564        $('.cart_count').html(cart.total_qty);
565    }
566
567    function cartPost(actionName, extra) {
568        var payload = $.extend({ action: actionName }, extra || {});
569        $.post(action, payload, function (resp) {
570            if (resp && resp.trigger) showCartNotice(resp.trigger);
571            else clearCartNotice();
572            if (resp && resp.cart) renderCart(resp.cart);
573        }, 'json');
574    }
575
576    function cartUpdate(pdtId, qty) { cartPost('wc_cart_update', { pdt_id: pdtId, qty: qty }); }
577    function loadCart() { cartPost('wc_cart_list', {}); }
578
579    function goToAccountStep() {
580        $(".modal-recharge .part-1").hide();
581        $(".modal-recharge .part-2").show();
582        $(".title-back").show();
583        $("a#title-back-id").attr("data-back", 2);
584    }
585
586    // stepper nos CARDS de pacote (product.php): so ajusta o input local
587    $(document).on('click', '.rcg-stepper__btn[data-step]', function (e) {
588        e.preventDefault();
589        var $input = $(this).closest('.rcg-stepper').find('.rcg-stepper__input');
590        var step = parseInt($(this).attr('data-step'), 10) || 0;
591        var val = (parseInt($input.val(), 10) || 1) + step;
592        if (val < 1) val = 1;
593        if (val > 99) val = 99;
594        $input.val(val);
595    });
596
597    // sanitiza digitacao nos inputs de quantidade (so digitos)
598    $(document).on('input', '.cart-qty-input, .rcg-cart-qty', function () {
599        this.value = String(this.value).replace(/\D/g, '');
600    });
601
602    // stepper nas LINHAS do carrinho: persiste via wc_cart_update
603    $(document).on('click', '.rcg-stepper__btn[data-cart-step]', function (e) {
604        e.preventDefault();
605        var $stepper = $(this).closest('[data-cart-stepper]');
606        var pdtId = $stepper.attr('data-cart-stepper');
607        var $input = $stepper.find('.rcg-cart-qty');
608        var step = parseInt($(this).attr('data-cart-step'), 10) || 0;
609        var val = (parseInt($input.val(), 10) || 1) + step;
610        if (val < 1) val = 1;
611        if (val > 99) val = 99;
612        cartUpdate(pdtId, val);
613    });
614
615    // digitacao direta na quantidade da linha do carrinho
616    $(document).on('change', '.rcg-cart-qty', function () {
617        var pdtId = $(this).attr('data-pdt');
618        var val = parseInt(String(this.value).replace(/\D/g, ''), 10);
619        if (isNaN(val) || val < 1) val = 1;
620        if (val > 99) val = 99;
621        cartUpdate(pdtId, val);
622    });
623
624    // remover item do carrinho
625    $(document).on('click', '[data-cart-remove]', function (e) {
626        e.preventDefault();
627        cartPost('wc_cart_remove', { pdt_id: $(this).attr('data-cart-remove') });
628    });
629
630    // limpar carrinho
631    $(document).on('click', '#rcgCartClear', function (e) {
632        e.preventDefault();
633        cartPost('wc_cart_clear', {});
634    });
635
636    // "Ir para a conta" -> avanca pra Part 2 (so com carrinho nao-vazio)
637    $(document).on('click', '#rcgCartCheckout', function (e) {
638        e.preventDefault();
639        if (!currentRechargeItems.length) return;
640        goToAccountStep();
641    });
642
643    // reidrata o mini-carrinho ao abrir o modal
644    $('#recharge').off('shown.bs.modal.cart').on('shown.bs.modal.cart', function () {
645        loadCart();
646    });
647
648    $('.coupon-select-input').off('click.confirmOverlay').on('click.confirmOverlay', function (e) {
649        e.preventDefault();
650
651        var $btn = $(this);
652
653        var show = String($btn.attr('data-show-confirm-overlay') || '').toLowerCase() === 'true';
654        var overlayId = $btn.attr('data-overlay-id') || '';
655
656        if (show && overlayId) {
657            openOverlay(overlayId, function () {
658                handleCouponSelect($btn);
659            }, function () { });
660            return false;
661        }
662
663        handleCouponSelect($btn);
664        return false;
665    });
666
667    $('.selectsrv').change(function () {
668        var srv = $(this).val();
669
670        $.post(base + '.ajax.php', {
671            action: 'selectchange',
672            'select': srv,
673        }, function (data) {
674            if (data.result) {
675                $('.searchittem').html(data.result);
676                $('.paginator').fadeIn();
677            }
678
679            if (data.return) {
680                $('.selects').html(data.return);
681            } else {
682                $('.selects').html('');
683            }
684
685            if (data.trigger) {
686                $(".account_form_callback").fadeOut(function () {
687                    $(".account_form_callback").html(data.trigger).fadeIn();
688                });
689            }
690
691            if (data.pag) {
692                $('.paginator').html(data.pag);
693            }
694        }, 'json');
695    });
696
697    $('.selectsrvs').change(function () {
698        var srv = $(this).val();
699
700        $.post(action, {
701            action: 'selectrecharge',
702            'select': srv,
703        }, function (data) {
704            if (data.result) {
705                $('.searchittem').html(data.result);
706                $('.paginator').fadeIn();
707            }
708
709            if (data.return) {
710                $('.emma').show();
711                $('.options').html(data.return);
712                if (selectUserID) {
713                    $('#character').val(selectUserID).change();
714                }
715            } else {
716                $('.options').html('');
717            }
718
719            if (data.trigger) {
720                $(".account_form_callback").fadeOut(function () {
721                    $(".account_form_callback").html(data.trigger).fadeIn();
722                });
723            } else {
724                $(".account_form_callback").hide();
725            }
726
727            if (data.pag) {
728                $('.paginator').html(data.pag);
729            }
730        }, 'json');
731    });
732
733    $('.recharge').click(function () {
734        var srv = $('select#server option:checked').val();
735        var usr = $('#character').val();
736        var pdt = $('#pricetag').val();
737
738        var Data = "pdt=" + pdt + "&UserID=" + usr + "&order_server=" + srv + "&action=wc_order_create";
739        $.post(action, Data, function (data) {
740            if (data.form_error) {
741                if (data.field) {
742                    Form.find("input[name='" + data.field + "']").after(data.form_error);
743                } else {
744                    var Inputs = Form.find('input[type="text"][required]');
745                    Inputs.each(function (index, elem) {
746                        if (!elem.value) {
747                            $(this).after(data.form_error);
748                        }
749                    });
750                }
751                $('.wc_order_error').fadeIn();
752            }
753            if (data.step3) {
754                $(".modal-recharge .part-2").hide();
755                $(".modal-recharge .part-3").show();
756                $("a#title-back-id").attr("data-back", 3);
757
758                $('.NickName').text(data.NickName);
759                $('.UserID').text(data.UserID);
760                $('.Server').text(data.Server);
761                $('.jwc_pay').attr('data-order-id', data.order_id);
762
763                // fluxo carrinho: preenche o resumo Valor/Cupom na Part 3 (o fluxo legado ja
764                // preenche esses labels na Part 2 via cart_product, que o carrinho nao usa).
765                if (data.order_price_fmt) $('.value').text(data.order_price_fmt);
766                if (data.order_money_fmt) $('.cupom').text(data.order_money_fmt);
767
768                $('#back-link-2').hide();
769                $('#back-link-3').show();
770
771                // GTM dataLayer: begin_checkout — user confirmou o item e tem um order_id.
772                // A partir daqui o transaction_id do purchase vai ser o order_id (o server-side
773                // emite event_id 'purchase_{order_code}' mas o order_id é o ponto de amarração
774                // natural do funil no browser).
775                try {
776                    var boValue = parseFloat(data.order_price) || 0;
777                    var boItems;
778                    if (data.items && data.items.length) {
779                        // fluxo carrinho: o server devolve o array de itens do pedido
780                        boItems = data.items.map(function (it) {
781                            return {
782                                'item_id': String(it.item_id),
783                                'item_name': it.item_name,
784                                'price': parseFloat(it.price) || 0,
785                                'quantity': parseInt(it.quantity, 10) || 1,
786                                'item_category': it.item_category || 'recharge'
787                            };
788                        });
789                    } else {
790                        // fluxo legado (pacote unico / avulso / passe)
791                        var boItem = currentRechargeItem || {
792                            'item_id': data.item_id ? String(data.item_id) : 'recharge',
793                            'item_name': data.order_desc || 'Recarga',
794                            'price': boValue,
795                            'item_category': data.item_category || 'recharge',
796                            'quantity': 1
797                        };
798                        boItem.price = boValue || boItem.price;
799                        boItems = [boItem];
800                    }
801                    if (!boValue) {
802                        boValue = boItems.reduce(function (s, i) { return s + (i.price * (i.quantity || 1)); }, 0);
803                    }
804                    currentRechargeItems = boItems;
805                    currentRechargeItem = boItems[0];
806                    currentRechargeOrder = {
807                        'order_id': data.order_id,
808                        'value': boValue,
809                        'desc': data.order_desc || (boItems[0] && boItems[0].item_name)
810                    };
811                    dlPush({
812                        'event': 'begin_checkout',
813                        'ecommerce': {
814                            'currency': 'BRL',
815                            'value': boValue,
816                            'items': boItems
817                        }
818                    });
819                } catch (e) {}
820            }
821
822            if (data.redirect) {
823                window.location.href = data.redirect;
824            }
825
826            if (data.trigger) {
827                $(".account_form_callback").fadeOut(function () {
828                    $(".account_form_callback").html(data.trigger).fadeIn();
829                });
830            } else {
831                $(".account_form_callback").hide();
832            }
833
834        }, 'json');
835        return false;
836    });
837
838    $('.modal').modal({
839        backdrop: 'static',
840        keyboard: false,
841        show: false,
842        focus: true
843    });
844
845    $('#recharge').off('hidden.bs.modal.stopVerify').on('hidden.bs.modal.stopVerify', function () {
846        verifyPayment.stopAll();
847    });
848
849    $('#recharge').off('hide.bs.modal.stopVerify').on('hide.bs.modal.stopVerify', function () {
850        verifyPayment.stopAll();
851    });
852
853    $(".refund").click(function (e) {
854        e.preventDefault();
855        var form = $(this);
856        var action = form.attr("data-action");
857        var id = form.attr("id");
858        var load = $(".ajax_load");
859
860        $.post(base + '.ajax.php', {
861            action: action,
862            'id': id,
863        }, function (data) {
864
865            if (data.trigger) {
866                $(".account_form_callback").fadeOut(function () {
867                    $(".account_form_callback").html(data.trigger).fadeIn();
868                });
869            }
870
871            if (data.idresult) {
872                $('td#' + id).html("<span class='btn btn-danger btn-sm'>Resgatado</span>").fadeIn();
873            }
874        }, 'json');
875    });
876
877    // Consentimento crédito imediato: habilitar/desabilitar gateways
878    $(document).on('change', '#consent-immediate-credit', function() {
879        var grid = document.getElementById('pay-grid');
880        var box = document.getElementById('consent-box');
881        var hint = document.getElementById('consent-unlock-hint');
882        if (this.checked) {
883            if (grid) { grid.style.opacity = ''; grid.style.pointerEvents = ''; }
884            if (box) { box.style.opacity = '0.6'; box.classList.add('accepted'); box.style.borderColor = 'rgba(255,255,255,0.08)'; box.style.background = 'rgba(255,255,255,0.04)'; }
885            if (hint) { $(hint).slideUp(200); }
886            // Salvar cookie 90 dias
887            var d = new Date(); d.setTime(d.getTime() + 90*24*60*60*1000);
888            document.cookie = 'consent_immediate_credit=1;expires=' + d.toUTCString() + ';path=/;SameSite=Lax';
889        } else {
890            if (grid) { grid.style.opacity = '0.3'; grid.style.pointerEvents = 'none'; }
891            if (box) { box.style.opacity = ''; box.classList.remove('accepted'); box.style.borderColor = '#f59e0b'; box.style.background = 'rgba(245,158,11,0.08)'; }
892            if (hint) { $(hint).slideDown(200); }
893        }
894    });
895
896    // Interceptar clique no grid desabilitado - shake no checkbox pra chamar atenção
897    $(document).on('click', '.qrcode', function(e) {
898        var grid = document.getElementById('pay-grid');
899        var box = document.getElementById('consent-box');
900        if (grid && grid.style.pointerEvents === 'none') {
901            if (box) {
902                box.style.transition = 'none';
903                box.style.transform = 'translateX(-8px)';
904                setTimeout(function() { box.style.transition = 'transform 0.1s'; box.style.transform = 'translateX(8px)'; }, 50);
905                setTimeout(function() { box.style.transform = 'translateX(-4px)'; }, 150);
906                setTimeout(function() { box.style.transform = 'translateX(4px)'; }, 250);
907                setTimeout(function() { box.style.transform = 'translateX(0)'; }, 350);
908            }
909        }
910    });
911
912    $('.jwc_pay').click(function (data) {
913        data = $(this);
914
915        var order_id = $(this).attr('data-order-id');
916        var order_platform = $(this).attr('data-platform');
917        var Data = "payment=" + order_platform + '&order_id=' + order_id;
918
919        // GTM dataLayer: add_payment_info — user escolheu um método de pagamento
920        // (pix, picpay, stripe, mercadopago, paypal, etc). Disparado na resposta do payment.php,
921        // que já traz o valor final (com desconto do método) em order_value.
922        function pushAddPaymentInfo(resp) {
923            try {
924                if (!currentRechargeOrder || String(currentRechargeOrder.order_id) !== String(order_id)) return;
925                if (resp && resp.track === false) return;
926                var apValue = (resp && typeof resp.order_value === 'number') ? resp.order_value : (currentRechargeOrder.value || 0
926);
927                var apItems = (currentRechargeItems && currentRechargeItems.length) ? currentRechargeItems : [currentRechargeItem || {
928                    'item_id': 'recharge',
929                    'item_name': currentRechargeOrder.desc || 'Recarga',
930                    'price': apValue,
931                    'item_category': 'recharge',
932                    'quantity': 1
933                }];
934                dlPush({
935                    'event': 'add_payment_info',
936                    'ecommerce': {
937                        'currency': 'BRL',
938                        'value': apValue,
939                        'payment_type': order_platform || 'unknown',
940                        'items': apItems
941                    }
942                });
943            } catch (e) {}
944        }
945
946        $.ajax({
947            url: '/_cdn/widgets/pay/payment.php',
948            data: Data,
949            type: 'POST',
950            dataType: 'json',
951            beforeSend: function () {
952                $('.await-load').show();
953                $('.qrcode').hide();
954            },
955            success: function (data) {
956                $('.await-load').hide();
957                $('.qrcode').show();
958                if (data.alert) {
959                    alert(data.alert);
960                }
961
962                if (data.order_code) {
963                    rememberTrackInfo(order_id, data);
964                }
965                if (!data.reset && !data.alert && !data.trigger) {
966                    pushAddPaymentInfo(data);
967                }
968
969                if (data.state == 'created') {
970                    window.location.href = data.link;
971                }
972
973                if (data.reset) {
974                    initRecharge(selectAreaID, selectUserID);
975                    return;
976                }
977
978                if (data.pix) {
979                    $('.qrcode').hide();
980                    $('.dados-deposito').html(data.pix).fadeTo('300', '1');
981
982                }
983                if (data.discount) {
984                    $('.value').html(data.discount);
985                }
986                if (data.caixa) {
987                    $("#modalcaixa").modal({
988                        show: true,
989                        backdrop: 'static'
990                    });
991                }
992
993                // GTM dataLayer: captura o método de pagamento escolhido pro evento purchase
994                // (order_platform vem do escopo externo do handler do click).
995                var gtmPaymentType = order_platform;
996
997                if (data.link_open) {
998
999                    $('.qrcode').hide();
1000                    $('.await-payment').show();
1001                    verifyPayment.init({
1002                        payment: 'verify_payment',
1003                        order_id: data.order_id,
1004                        automatic: 0,
1005                        success: function (data) {
1006                            $('.await-payment').hide();
1007                            $('.payment').hide();
1008                            $('.textreturnpic').html(data.aproved).fadeTo('300', '1');
1009                            fireRechargePurchase(order_id, gtmPaymentType, data);
1010                        }
1011                    });
1012                    window.open(data.link_open)
1013                }
1014
1015                if (data.verify_pix) {
1016                    verifyPayment.init({
1017                        payment: 'verify_paymentpix',
1018                        order_id: data.order_id,
1019                        automatic: 1,
1020                        timeout: 100,
1021                        success: function (data) {
1022                            $('.await-payment').hide();
1023                            $('.payment').hide();
1024                            $('.textreturnpic').html(data.aproved).fadeTo('300', '1');
1025                            fireRechargePurchase(order_id, gtmPaymentType, data);
1026                        }
1027                    });
1028                }
1029
1030                if (data.qrpic) {
1031                    $('.qrcode').hide();
1032                    $('.dados-deposito').fadeIn(function () {
1033                        $(this).html(data.qrpic).fadeTo('300', '1');
1034                    });
1035
1036                    verifyPayment.init({
1037                        payment: 'verify_payment',
1038                        order_id: data.order_id,
1039                        automatic: 0,
1040                        success: function (data) {
1041                            $('.await-payment').hide();
1042                            $('.payment').hide();
1043                            $('.textreturnpic').html(data.aproved).fadeTo('300', '1');
1044                            fireRechargePurchase(order_id, gtmPaymentType, data);
1045                        }
1046                    });
1047                }
1048
1049                if (data.content) {
1050                    if (typeof (data.content) === 'string') {
1051                        $('.recharge-wrapper').fadeTo('300', '0.5', function () {
1052                            $(this).html(data.content).fadeTo('300', '1');
1053                        });
1054                    } else if (typeof (data.content) === 'object') {
1055                        $.each(data.content, function (key, value) {
1056                            $(key).fadeTo('300', '0.5', function () {
1057                                $(this).html(value).fadeTo('300', '1');
1058                            });
1059                        });
1060                    }
1061
1062                    if (data.redirect) {
1063                        setTimeout(function () {
1064                            window.location.href = data.redirect;
1065                        }, 3000);
1066                    }
1067                }
1068
1069            }
1070        });
1071
1072        return false;
1073    });
1074
1075    $('.ticket').click(function (data) {
1076        data = $(this);
1077
1078        var order_id = $(this).attr('data-id');
1079        var order_platform = $(this).attr('data-platform');
1080        var Data = "action=check_ticket&tkt_id=" + order_id;
1081
1082        var load = $(".spinner-border");
1083        $.ajax({
1084            url: '/_cdn/widgets/ddtanksystem/tickets/tickets.ajax.php',
1085            data: Data,
1086            type: 'POST',
1087            dataType: 'json',
1088            beforeSend: function () {
1089                load.fadeIn(200).css("display", "flex");
1090
1091            },
1092            success: function (data) {
1093                load.fadeOut(200);
1094                if (data.alert) {
1095                    alert(data.alert);
1096                }
1097
1098                if (data.t_result) {
1099                    $('.table-hover').fadeOut();
1100                    $('.t_result').html(data.t_result);
1101                }
1102                $('#exampleModal').modal('toggle');
1103
1104                if (data.state == 'created') {
1105                    window.location.href = data.link;
1106                }
1107
1108                if (data.redirect) {
1109                    window.open(data.redirect)
1110                } else {
1111                    load.fadeOut(200);
1112                }
1113
1114                if (data.qrpic) {
1115                    $('.card-finish').fadeIn(function () {
1116                        $(this).html(data.qrpic).fadeTo('300', '1');
1117                    });
1118
1119                    var ord = "payment=verify_payment&order_id=" + data.order_id;
1120                    var interval;
1121
1122                    playinterval();
1123
1124                    function returnStatus() {
1125                        $.ajax({
1126                            url: '/_cdn/widgets/pay/payment.php',
1127                            data: ord,
1128                            type: 'POST',
1129                            dataType: 'json',
1130                            success: function (data) {
1131
1132                                $('.card-finish').html(data.aproved).fadeTo('300', '1');
1133                                stopinterval();
1134                            }
1135                        });
1136                    }
1137
1138                    function playinterval() {
1139                        returnStatus();
1140                        interval = setInterval(function () {
1141                            returnStatus();
1142                        }, 3000);
1143                        return false;
1144                    }
1145
1146                    function stopinterval() {
1147                        clearInterval(interval);
1148                        return false;
1149                    }
1150                }
1151
1152                if (data.content) {
1153                    if (typeof (data.content) === 'string') {
1154                        $('.recharge-wrapper').fadeTo('300', '0.5', function () {
1155                            $(this).html(data.content).fadeTo('300', '1');
1156                        });
1157                    } else if (typeof (data.content) === 'object') {
1158                        $.each(data.content, function (key, value) {
1159                            $(key).fadeTo('300', '0.5', function () {
1160                                $(this).html(value).fadeTo('300', '1');
1161                            });
1162                        });
1163                    }
1164
1165                    if (data.redirect) {
1166                        setTimeout(function () {
1167                            window.location.href = data.redirect;
1168                        }, 3000);
1169                    }
1170                }
1171
1172            }
1173        });
1174
1175        return false;
1176    });
1177
1178    if ($('*[rel*="shadowbox"]').length) {
1179        $("head").append('<link rel="stylesheet" href="' + BASE + '/_cdn/shadowbox/shadowbox.css">');
1180        $.getScript(BASE + '/_cdn/shadowbox/shadowbox.js', function () {
1181            Shadowbox.init();
1182        });
1183    }
1184
1185    $(document).on('click', '.recarregar', function () {
1186        // Gate 18+ - Compliance ECA Digital (Lei 15.211/2025)
1187        if (typeof window.SurfTankUser !== 'undefined') {
1188            if (!window.SurfTankUser.hasDateOfBirth) {
1189                showAgeGateModal('Dados Incompletos', 'Você precisa informar sua data de nascimento antes de recarregar.', 'Atualizar Dados', function(){ location.reload(); });
1190                return;
1191            }
1192            if (window.SurfTankUser.isMinor) {
1193                showAgeGateModal('Recargas 18+', 'Recargas de cupons são permitidas apenas para maiores de 18 anos, conforme Lei 15.211/2025 (ECA Digital).', null, null);
1194                return;
1195            }
1196            if (!window.SurfTankUser.ageVerified) {
1197                var isLogger = navigator.userAgent.indexOf('Logger') !== -1;
1198                showAgeGateModal('Verificação Necessária', 'Para realizar recargas, é necessário verificar sua idade. Isso leva menos de 2 minutos.', 'Verificar Agora', function(){
1199                    if (isLogger) {
1200                        window.open(window.location.origin + '/recarga', 'Recarregar Cupons');
1201                        $('#age-gate-modal').modal('hide');
1202                    } else {
1203                        window.location.href = window.location.origin + '/verificar-idade';
1204                    }
1205                });
1206                return;
1207            }
1208        }
1209        initRecharge();
1210    });
1211
1212    function showAgeGateModal(title, msg, btnText, btnAction) {
1213        $('#age-gate-modal').remove();
1214        var actionBtn = '';
1215        if (btnText) actionBtn = '<button class="btn btn-primary" id="age-gate-action" style="border-radius:999px;font-weight:700;padding:10px 24px;">' + btnText + '</button>';
1216        $('body').append(
1217            '<div class="modal fade" id="age-gate-modal" tabindex="-1">' +
1218            '<div class="modal-dialog modal-dialog-centered" style="max-width:420px;">' +
1219            '<div class="modal-content" style="border:0;border-radius:22px;box-shadow:0 25px 65px rgba(0,0,0,.25);overflow:hidden;">' +
1220            '<div class="modal-body" style="padding:28px;text-align:center;">' +
1221            '<div style="width:52px;height:52px;border-radius:16px;background:linear-gradient(135deg,#1E90FF,#4AA8FF);display:flex;align-items:center;justify-content:center;margin:0 auto 14px;color:#fff;font-weight:900;font-size:18px;box-shadow:0 6px 20px rgba(30,144,255,.3);">18+</div>' +
1222            '<h3 style="font-weight:900;font-size:18px;margin:0 0 8px;color:#fff;">' + title + '</h3>' +
1223            '<p style="color:rgba(255,255,255,.6);font-size:14px;line-height:1.5;margin:0 0 20px;">' + msg + '</p>' +
1224            '<div style="display:flex;gap:10px;justify-content:center;">' + actionBtn +
1225            '<button class="btn" data-dismiss="modal" style="border-radius:999px;font-weight:700;padding:10px 24px;border:none;background:#333;color:#fff;">Fechar</button>' +
1226            '</div></div></div></div></div>'
1227        );
1228        $('#age-gate-modal').modal('show');
1229        if (btnAction) $('#age-gate-action').on('click', btnAction);
1230    }
1231
1232    $(".modal-recharge label.select-checkbox").change(function () {
1233        var backRecharge = $("a#title-back-id").attr("data-back");
1234        if (backRecharge == 1) {
1235            $(".modal-recharge .part-1").hide();
1236            $(".modal-recharge .part-2").show();
1237            $(".title-back").show();
1238            $("a#title-back-id").attr("data-back", 2);
1239        }
1240    });
1241
1242    $("a#title-back-id").click(function (e) {
1243        e.preventDefault();
1244        var backRecharge = $("a#title-back-id").attr("data-back");
1245
1246        if (backRecharge == 2) {
1247            $(".modal-recharge .part-2").hide();
1248            $(".modal-recharge .part-1").show();
1249            $(".title-back").hide();
1250            $("a#title-back-id").attr("data-back", 1);
1251            togglePixDiscount(true);
1252            loadCart();
1253            verifyPayment.stopAll();
1254        } else if (backRecharge == 3) {
1255            $(".modal-recharge .part-3").hide();
1256            $(".modal-recharge .part-2").show();
1257            $("a#title-back-id").attr("data-back", 2);
1258            $('.qrcode').show();
1259            $('.dados-deposito').hide();
1260            $('.await-payment').hide();
1261            $('.returnpic').show();
1262            $('.payment').show();
1263            $('.textreturnpic').hide();
1264            verifyPayment.stopAll();
1265        }
1266    });
1267
1268    $("#next-part2-recharge").click(function () {
1269        var backRecharge = $("a#title-back-id").attr("data-back");
1270        if (backRecharge == 2) {
1271            $(".modal-recharge .part-2").hide();
1272            $(".modal-recharge .part-3").show();
1273            $("a#title-back-id").attr("data-back", 3);
1274
1275        }
1276    });
1277});

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.