PageSourceSearch

https://www.edituratrei.ro/assets/js/script-v3.js?v=1790273332

js edituratrei.ro collected 2026-09-24 18:09:03 UTC 81,337 bytes, 2,340 lines download raw bytes

1function openWindowPopup( url, target, w, h ) {
2
3    if ( w === '' && h === '' ) {
4        w = 600;
5        h = 600;
6    }
7
8    const dualScreenLeft = window.screenLeft !==  undefined ? window.screenLeft : window.screenX;
9    const dualScreenTop = window.screenTop !==  undefined   ? window.screenTop  : window.screenY;
10
11    const width = window.innerWidth ? window.innerWidth : document.documentElement.clientWidth ? document.documentElement.clientWidth : screen.width;
12    const height = window.innerHeight ? window.innerHeight : document.documentElement.clientHeight ? document.documentElement.clientHeight : screen.height;
13
14    const systemZoom = width / window.screen.availWidth;
15    const left = (width - w) / 2 / systemZoom + dualScreenLeft
16    const top = (height - h) / 2 / systemZoom + dualScreenTop
17
18    window.open(url, target, `width=${w / systemZoom},height=${h / systemZoom},top=${top},left=${left}`);
19}
20
21
22const handleClickOutside = (event) => {
23    let miniCart = $('#header-mini-cart');
24    let miniCartOverlay = $('#mini-cart-overlay');
25    if (!miniCart.is(event.target) && miniCart.has(event.target).length === 0) {
26        miniCart.removeClass('active');
27        miniCartOverlay.removeClass('active');
28
29        $(document).off('click', handleClickOutside);
30    }
31};
32
33function addToCartPopup() {
34    var addToCartPopup = $('.product-add-to-cart-fixed-popup');
35
36    if ( addToCartPopup.length && $('#product-book-add-to-cart').length ) {
37        if ( !isScrolledIntoView('#product-book-add-to-cart') ) {
38            $('.product-add-to-cart-fixed-popup').addClass('active');
39        } else {
40            $('.product-add-to-cart-fixed-popup').removeClass('active');
41        }
42    }
43}
44
45$(document).ready(function () {
46
47
48    $('#newsletter-form').submit(function(event) {
49        event.preventDefault();
50        grecaptcha.ready(function () {
51            grecaptcha.execute(google_site_key, {action: 'newsletter_form'}).then(function (token) {
52                $('#newsletter-form #rechaptcha-token').remove();
53                $('#newsletter-form #rechaptcha-action').remove();
54                $('#newsletter-form').prepend('<input type="hidden" id="rechaptcha-token" name="token" value="' + token + '">');
55                $('#newsletter-form').prepend('<input type="hidden" id="rechaptcha-action" name="gaction" value="newsletter_form">');
56                $('#newsletter-form').unbind('submit').submit();
57            });
58        });
59    });
60
61
62
63    addToCartPopup();
64
65    $(document).on('scroll', function () {
66        addToCartPopup();
67    });
68
69    // cookie consent popup
70    //console.log(getCookie('_cc'));
71    if ( getCookie('_cc') != '1' ) {
72        $('.cookie-compliance-popup').addClass('active');
73    }
74
75    $(document).on('click', '.cookie-button', function (e) {
76        e.preventDefault();
77
78        setCookie('_cc', 1, 365);
79        $('.cookie-compliance-popup').removeClass('active');
80    });
81
82    $(document).on('click', '#large-description-more', function (e) {
83        e.preventDefault();
84
85        $('.large-description-content').toggleClass('active');
86
87        if ( $('.large-description-content').hasClass('active') ) {
88            $('#large-description-more').text('Afișează mai puțin');
89        } else {
90            $('#large-description-more').text('Afișează mai mult');
91        }
92    });
93
94    $(document).on('click', '#product-meta-items-more', function (e) {
95        e.preventDefault();
96
97        $('.product-metas').toggleClass('active');
98        $('#product-meta-items-hidden').toggleClass('show');
99        $('#product-meta-items-hidden-mobile').toggleClass('show');
100
101        if ( $('#product-meta-items-hidden').hasClass('show') ) {
102            $('#product-meta-items-more').text('Afișează mai puțin');
103        } else {
104            $('#product-meta-items-more').text('Afișează mai mult');
105        }
106    });
107
108    $(document).on('click', '#header-mini-cart-button', function () {
109        let miniCart = $('#header-mini-cart');
110        let miniCartOverlay = $('#mini-cart-overlay');
111        miniCart.toggleClass('active');
112       // miniCartOverlay.toggleClass('active');
113
114        if (miniCart.hasClass('active')) {
115            $(document).on('click', handleClickOutside);
116        } else {
117            $(document).off('click', handleClickOutside);
118        }
119    });
120
121
122    $(document).on('click', '#header-mini-cart-close', function () {
123        $('#header-mini-cart').removeClass('active');
124        $('#mini-cart-overlay').removeClass('active');
125        $(document).off('click', handleClickOutside);
126    });
127
128
129    $(document).on('click', 'a[href^="#"]', function(e) {
130        // target element id
131        var id = $(this).attr('href');
132
133        // target element
134        var $id = $(id);
135        if ($id.length === 0) {
136            return;
137        }
138
139        // prevent standard hash navigation (avoid blinking in IE)
140        e.preventDefault();
141
142        // top position relative to the document
143        var pos = $id.offset().top;
144
145        // animated top scrolling
146        $('body, html').animate({scrollTop: pos}, 500);
147    });
148
149
150    $('#phonePrefixInputValue').text($('#phonePrefixInput').val());
151
152    $('#add-book').click(function (e) {
153        $('#add-book-error').removeClass('text-danger');
154        $('#add-book-error').removeClass('text-success');
155        $('#add-book-error').text('').hide();
156        $('#add-book-code').val('');
157        $('#add-book-button').show();
158        $('#close-book-button').hide();
159    });
160
161    $('#add-book-button').on('click', function (e) {
162        e.preventDefault();
163
164        if ( $('#add-book-code').val() === '' || $('#add-book-code').val().length < 6 ) {
165            $('#add-book-error').removeClass('text-danger');
166            $('#add-book-error').removeClass('text-success');
167            $('#add-book-error').text('Codul trebuie să aibă o lungime de 6 caractere').addClass('text-danger').show();
168        } else {
169            $.ajax({
170                type: 'post',
171                url: '/ajax/add-book.php',
172                data: { code: $('#add-book-code').val() },
173                success: function (response) {
174                    let status = parseInt(response.status);
175                    let bookType = parseInt(response.type);
176                    let message = '';
177                    let type = 'text-danger';
178
179                    if ( status === 0 ) {
180                        message = 'Acest cod a fost utilizat!';
181                    }
182
183                    if ( status === 5 ) {
184                        message = 'Codul introdus nu există!';
185                    }
186
187                    if ( status === 1 ) {
188                        message = 'Felicitări! Cartea a fost adaugată cu succes!';
189                        type = 'text-success';
190                        $('#add-book-code').val('');
191                        $('#add-book-button').hide();
192                        $('#close-book-button').show();
193
194                        $('.all-list').prepend(response.html);
195                        if ( bookType === 1 ) {
196                            $('.audiobooks-list').prepend(response.html);
197                        }
198                        if ( bookType === 2 ) {
199                            $('.ebooks-list').prepend(response.html);
200                        }
201                    }
202
203                    if ( status === 2 ) {
204                        message = 'Ceva nu a funcționat bine! Te rugăm să reîncerci puțin mai târziu!';
205                    }
206
207                    if ( status === 3 ) {
208                        window.location.reload();
209                    }
210
211                    if ( status === 4 ) {
212                        message = 'Această carte există deja în cont!';
213                    }
214
215                    $('#add-book-error').removeClass('text-danger');
216                    $('#add-book-error').removeClass('text-success');
217                    $('#add-book-error').text(message).addClass(type).show();
218
219
220                }
221            });
222        }
223    });
224
225    $('#confirm-delete').on('click', function (e) {
226        e.preventDefault();
227
228        $.ajax({
229            type: 'post',
230            url: '/ajax/delete-account.php',
231            data: { delete: 1 },
232            success: function (response) {
233                let status = parseInt(response.status);
234
235                if ( status === 2 ) {
236                    // error message
237                }
238
239                if ( status === 3 || status === 1 ) {
240                    window.location.reload();
241                }
242            }
243        });
244    });
245
246    /**
247     * Handle book preview
248     */
249    $('#bookPreviewClose, .product-book-sample.ebook').click(function (e) {
250        e.preventDefault();
251        $('#bookPreview').toggleClass('show');
252    });
253
254    /**
255     * Listing view
256     */
257    var listingView = getCookie('listing-view');
258
259
260    if ( listingView !== '' ) {
261        if ( listingView === 'compact' ) {
262            $('.listing-display-compact').addClass('active');
263            $('.listing-display-extra').removeClass('active');
264        }
265
266        if ( listingView === 'extra' ) {
267            $('.listing-display-compact').removeClass('active');
268            $('.listing-display-extra').addClass('active');
269        }
270    } else {
271        setCookie("listing-view", "compact", 365);
272        $('.listing-display-compact').addClass('active');
273    }
274
275    $('.listing-display-extra').click(function () {
276        $('.listing-display-compact').removeClass('active');
277        $('.listing-display-extra').addClass('active');
278        setCookie("listing-view", "extra", 365);
279        location.reload();
280    });
281
282    $('.listing-display-compact').click(function () {
283        $('.listing-display-compact').addClass('active');
284        $('.listing-display-extra').removeClass('active');
285        setCookie("listing-view", "compact", 365);
286        location.reload();
287    });
288
289    $('.mobile-option-view').click(function () {
290        const targetElement = $(this).children('.view-mode');
291        const classes = ['view-extra', 'view-compact'];
292        const currentClasses = targetElement.attr("class").split(/\s+/);
293
294        let currentClass;
295        for ( let i = 0; i < currentClasses.length; i++ ) {
296            if( $.inArray(currentClasses[i], classes) !== -1 ) {
297                currentClass = currentClasses[i];
298            }
299        }
300
301        // targetElement.removeClass(currentClass);
302
303        const switchClass = $.grep(classes, function (value) {
304            return value !== currentClass;
305        });
306
307        // targetElement.addClass(switchClass[0]);
308        //
309        // $('.listing-products').removeClass(currentClass.replace('view-', ''));
310        // $('.listing-products').addClass(switchClass[0].replace('view-', ''));
311
312        setCookie("listing-view", switchClass[0].replace('view-', ''), 365);
313        location.reload();
314    });
315
316
317
318    /**
319     * Header menu navigation
320     */
321
322
323    const $window = $(window);
324    if ( $window.width() <= 1024 ) {
325        $('.header-page-navigator > UL > LI').click(function () {
326            $(this).toggleClass('active');
327        });
328    }
329
330    $('.listing-filter-option-delete').on('click',function() {
331        window.location.href = window.location.href.split('?')[0];
332    });
333
334
335
336    /**
337     * Listing filters
338     */
339    $('form#listing-filters').on('submit', function (e) {
340        e.preventDefault();
341        return false;
342    });
343
344    $('form#listing-filters input[name=format]').on('click', function () {
345        var checked = $(this).is(':checked');
346        $('form#listing-filters input[name=format]').prop('checked', false);
347        $(this).prop('checked', checked);
348    });
349
350    $('.header-menu-switcher').click(function () {
351        $('html').toggleClass('overflow-hidden');
352        $('header').toggleClass('submenu');
353    });
354
355
356    /* Carousels ---------------------------------------------------------------------------------------------------- */
357    $('.hero-carousel').owlCarousel({
358        loop:true,
359        margin:10,
360        nav:true,
361        navContainer: '#carousel-controls',
362        dotsContainer: '#carousel-dots-controls',
363        responsive:{
364            0:{
365                items:1
366            }
367        }
368    });
369
370    $('.hero-mobile-carousel').owlCarousel({
371        loop:true,
372        // autoplay:true,
373        autoHeight:true,
374        margin:10,
375        nav:false,
376        responsive:{
377            0:{
378                items:1
379            }
380        }
381    });
382
383
384    var topListingCarousel = $('.top-listing-carousel').owlCarousel({
385        loop:false,
386        margin:30,
387        nav:false,
388        dots: true,
389        autoWidth: true,
390        responsive:{
391            0:{
392                items: 5
393            }
394        }
395    });
396
397    var carouselNoutati = $('.home-audiobooks-carousel').owlCarousel({
398        loop:false,
399        margin:30,
400        nav:true,
401        dots: false,
402        responsive:{
403            0 : {
404                items: 2
405            },
406            600: {
407                items: 3
408            },
409            768: {
410                items: 3
411            },
412
413            1025: {
414                items: 7
415            }
416
417        }
418    });
419
420    var carouselBestSellers = $('.home-ebooks-carousel').owlCarousel({
421        loop:false      ,
422        margin:30,
423        nav:true,
424        dots: false,
425        responsive:{
426            0 : {
427                items: 2
428            },
429            600: {
430                items: 3
431            },
432            768: {
433                items: 3
434            },
435            1025: {
436                items: 7
437            }
438
439        }
440    });
441
442    $( '.product-choices-filters-top' ).on( 'click', '.product-choices-filter', function() {
443        var $item = $(this);
444        var filter = $item.data( 'owl-filter' );
445        $item.addClass( 'active' ).siblings().removeClass( 'active' );
446        topListingCarousel.owlcarousel2_filter( filter );
447    } );
448
449    $( '.product-choices-filters-new' ).on( 'click', '.product-choices-filter', function() {
450        var $item = $(this);
451        var filter = $item.data( 'owl-filter' );
452        $item.addClass( 'active' ).siblings().removeClass( 'active' );
453        carouselNoutati.owlcarousel2_filter( filter );
454    } );
455
456    $( '.product-choices-filters-best' ).on( 'click', '.product-choices-filter', function() {
457        var $item = $(this);
458        var filter = $item.data( 'owl-filter' );
459        $item.addClass( 'active' ).siblings().removeClass( 'active' );
460        carouselBestSellers.owlcarousel2_filter( filter );
461    } );
462
463    setInputFilter(document.getElementsByClassName("qty-input"), function(value) {
464        return /^\d*$/.test(value);
465    }, "Sunt permise doar cifre [0-9]");
466
467    $("#checkoutForm .shipping-method-options").find(':input ').each(function(e) {
468        $(this).attr('disabled', 'disabled');
469    });
470
471
472
473
474});
475
476/* Handle filters --------------------------------------------------------------------------------------------------- */
477$(document).on('change', '.checkbox-filter', function(){
478    $.ajax({
479        type: 'post',
480        url: '/ajax/listing.php',
481        data:  $('form#listing-filters').serialize(),
482        success: function (response) {
483            $('.listing-products').html(response.html_products);
484            $('.listing-filters-wrap').html(response.html_filters);
485            $('.listing-pagination').html(response.html_pagination);
486            $('.category-results').html(response.html_count);
487
488            $('input[name=qs]').val(response.qs_full);
489
490            if ( response.active_filters ) {
491                $('#listing-filter-delete-all').removeClass('listing-filter-hide');
492                $('#listing-filter-delete-all').addClass('listing-filter-show');
493            } else {
494                $('#listing-filter-delete-all').removeClass('listing-filter-show');
495                $('#listing-filter-delete-all').addClass('listing-filter-hide');
496            }
497
498            const url = new URL(window.location.href);
499            // const urlParams = new URLSearchParams(response.qs);
500            //
501            // urlParams.forEach((value, key) => {
502            //     url.searchParams.set(key, value);
503            // });
504
505            // window.location.href = url.pathname + '?' + response.qs;
506            history.pushState({}, "", url.pathname + '?' + decodeURIComponent(response.qs));
507
508            $("html, body").animate({ scrollTop: 0 });
509        },
510        error: function () {
511            console.log('error');
512        }
513    });
514});
515
516/* -- Custom select --------------------------------------------------------------------------------------------- */
517$(document).on('click', '.form-select-option', function (e) {
518    var $selectTarget = $($(this).data('target'));
519    $selectTarget.trigger('click');
520});
521
522$(document).on('change', '.form-select-custom select', function (e) {
523   $($(this).data('target')).text($(this).val());
524})
525
526/* Search filter ------------------------------------------------------------------------------------------------ */
527$(document).on('keyup', '.listing-filter-search-input', function () {
528    var value = $(this).val().toLowerCase();
529    console.log()
530    $($(this).data('filter') + " .listing-filter-option-name").filter(function() {
531        $(this).parents('.listing-filter-option').toggle($(this).text().toLowerCase().indexOf(value) > -1)
532    });
533});
534
535/* Handle ebook sample ---------------------------------------------------------------------------------------------- */
536$(document).on('click', '.ebook-listing-sample', function (e) {
537    e.preventDefault();
538    $('#bookPreview iframe').attr('src', 'https://editura.mybookmag.com/preview-ebook.php?id=' + $(this).data('id'));
539    $('#bookPreview').toggleClass('show');
540});
541
542/* Handle audiobook sample ------------------------------------------------------------------------------------------ */
543var audioPlayer = new Audio();
544
545
546$(document).on('click', '.product-book-sample-control, .audiobook-sample-control', function (e) {
547    e.preventDefault();
548
549    let samplePlayBtn = $(this).children('.product-book-sample-control');
550
551    if ( samplePlayBtn ) {
552        playSample(samplePlayBtn);
553    } else {
554        playSample($(this));
555    }
556});
557
558function playSample( samplePlayBtn ) {
559    var source = samplePlayBtn.data('source');
560
561    if ( source !== audioPlayer.currentSrc ) {
562        audioPlayer.setAttribute('src', source);
563        audioPlayer.addEventListener("canplaythrough", (event) => {
564            audioPlayer.play();
565
566            $('.product-book-sample-control').not($(samplePlayBtn)).removeClass('fa-pause');
567            $('.product-book-sample-control').not($(samplePlayBtn)).addClass('fa-play');
568
569            samplePlayBtn.addClass('fa-pause');
570            samplePlayBtn.removeClass('fa-play');
571        });
572
573        audioPlayer.addEventListener("ended", (event) => {
574            audioPlayer.stop();
575            samplePlayBtn.removeClass('fa-pause');
576            samplePlayBtn.addClass('fa-play');
577        });
578    }
579
580    if ( audioPlayer.paused || audioPlayer.isReady ) {
581        audioPlayer.play();
582        samplePlayBtn.removeClass('fa-play');
583        samplePlayBtn.addClass('fa-pause');
584    } else {
585        audioPlayer.pause();
586        samplePlayBtn.removeClass('fa-pause');
587        samplePlayBtn.addClass('fa-play');
588    }
589}
590
591$(document).on('click', '.add-to-cart', function (e) {
592    e.preventDefault();
593
594    var elem = $(this);
595
596    elem.append('<div class="adding-to-cart"><div class="spinner-grow text-light" role="status"></div></div>');
597
598    $.ajax({
599        method: 'post',
600        url: '/',
601        data: { 'action':'add-to-cart', 'product_id': elem.data('product-id'), 'is_popup' : true },
602        success: function (response) {
603            trackEvent('add-to-cart', {product_id: elem.data('product-id') });
604
605            $('.popup-add-to-cart-product').html('<div class="row">'+response.html+'</div>')
606            $('#add-to-cart-popup').addClass('show');
607            $('#header-mini-cart-content').html(response.html_mini_cart);
608            $('#header-mini-cart-total-amount').html(response.total.total_final.toFixed(2).replace('.', ','));
609
610            let count = parseInt(response.count);
611
612            $('.header-mini-cart-items-count').html(count > 0 ? '('+count+')' : '');
613            $('.header-mini-cart-title-items-count').html(count > 0 ? '('+count+' produs'+(count > 1 ? 'e' : '')+')' : '');
614
615            if ( count > 0 ) {
616                $('#header-mini-cart-actions').addClass('active');
617            } else {
618                $('#header-mini-cart-actions').removeClass('active');
619            }
620
621            send_ga4_event(response.ga4_data.event_name, response.ga4_data.event_params);
622
623            var fbq_data = JSON.parse(response.fb_data);
624            send_fb_event(fbq_data.event_name, fbq_data.event_data);
625
626        },
627        complete: function () {
628            elem.children('.adding-to-cart').remove();
629        }
630    });
631
632});
633
634$(document).on('click', '.add-to-wishlist', function (e) {
635    e.preventDefault();
636
637    // var elem = $(this);
638    var elem = $('.wishlist-' + $(this).data('product-id'));
639
640
641    $.ajax({
642        method: 'post',
643        url: '/',
644        data: { 'action':'add-to-wishlist', 'product_id': elem.data('product-id') },
645        success: function (response) {
646            if ( parseInt(response.success) === 1 ) {
647                elem.removeClass('add-to-wishlist');
648                elem.addClass('remove-from-wishlist');
649
650                let icon = elem.find('.add-to-wishlist-icon');
651                let text = elem.find('.add-to-wishlist-text');
652
653                $(icon).removeClass('fa-regular');
654                $(icon).addClass('fa-solid');
655
656                $(text).html('Șterge de la favorite');
657
658                var fbq_data = JSON.parse(response.fb_data);
659                send_fb_event(fbq_data.event_name, fbq_data.event_data);
660            }
661        }
662    });
663
664});
665
666/*$(document).on('click', '.cart-product-delete', function (e) {
667    e.preventDefault();
668
669    var product_id = $(this).data('product-id');
670    var elem = $('#product-'+product_id);
671
672    $.ajax({
673        method: 'post',
674        url: '/',
675        data: { 'action':'delete-from-cart', 'product_id': product_id },
676        success: function (response) {
677        },
678        complete: function () {
679            window.location.reload();
680        }
681    });
682
683});*/
684
685$(document).on('click', '.remove-from-wishlist', function (e) {
686    e.preventDefault();
687
688    // var elem = $(this);
689    var elem = $('.wishlist-' + $(this).data('product-id'));
690
691
692    $.ajax({
693        method: 'post',
694        url: '/',
695        data: { 'action':'delete-from-wishlist', 'product_id': elem.data('product-id') },
696        success: function (response) {
697            if ( parseInt(response.success) === 1 ) {
698                elem.removeClass('remove-from-wishlist');
699                elem.addClass('add-to-wishlist');
700
701                let icon = elem.find('.add-to-wishlist-icon');
702                let text = elem.find('.add-to-wishlist-text');
703
704                $(icon).removeClass('fa-solid');
705                $(icon).addClass('fa-regular');
706
707                $(text).html('Adaugă la favorite');
708            }
709        }
710    });
711
712});
713
714$(document).on('click', '.cart-product-qty-plus', function (e) {
715    e.preventDefault();
716    var elem = $(this).closest("div.row").find("input[name='product-qty']");
717    var qty = $(this).closest("div.row").find("input[name='product-qty']").val();
718    var pid = $(this).closest("div.row").find("input[name='product-qty']").attr('id');
719    if (qty!=0) {
720        pid = pid.split("-");
721        pid = pid[2];
722        elem.prop('disabled', true);
723        $.ajax({
724            method: 'post',
725            url: '/',
726            data: {'action': 'cart-qty-update', product_id: pid, qty: qty, action_type: 'plus'},
727            success: function (response) {
728                elem.prop('disabled', false);
729                if (response.sucess) {
730                    update_product_prices(pid, response.prices);
731                    elem.val(response.qty);
732                    $.each( response.result, function( key, value ) {
733                        htmlEl = key.replaceAll("_", "-");
734                        if (key =='total_discounts') {
735                            toggle_reducere_box(htmlEl, value);
736                        }
737                        else {
738                            if (key =='total_final') {
739                                $("#"+htmlEl).html(response.result.total_products_no_discounts+' lei');
740                            }
741                            else {
742                                $("#" + htmlEl).html(value + ' lei');
743                            }
744                        }
745
746                    });
747
748                    $('.cart-container .cart-product-list').remove();
749                    $('.cart-container').prepend(response.cart_html);
750
751                    $(".promo-info-cart").html(response.promo_info);
752                }
753                else {
754
755                }
756                send_ga4_event(response.ga4_data.event_name, response.ga4_data.event_params);
757            },
758            complete: function () {
759                elem.prop('disabled', false);
760            },
761            error: function () {
762                elem.prop('disabled', false);
763            }
764        });
765    }
766
767    return false;
768});
769
770$(document).on('click', '.cart-product-qty-minus', function (e) {
771    e.preventDefault();
772    var elem = $(this).closest("div.row").find("input[name='product-qty']");
773    var qty = $(this).closest("div.row").find("input[name='product-qty']").val();
774    var pid = $(this).closest("div.row").find("input[name='product-qty']").attr('id');
775    if (qty!=0) {
776        pid = pid.split("-");
777        pid = pid[2];
778        elem.prop('disabled', true);
779        $.ajax({
780            method: 'post',
781            url: '/',
782            data: {'action': 'cart-qty-update', product_id: pid, qty: qty, action_type: 'minus'},
783            success: function (response) {
784                elem.prop('disabled', false);
785                if (response.sucess) {
786                    update_product_prices(pid, response.prices);
787                    elem.val(response.qty);
788                    $.each( response.result, function( key, value ) {
789                        htmlEl = key.replaceAll("_", "-");
790                        if (key=='total_discounts') {
791                            toggle_reducere_box(htmlEl, value);
792                        }
793                        else {
794                            $("#"+htmlEl).html(value+' lei');
795                        }
796
797                    });
798
799                    $('.cart-container .cart-product-list').remove();
800                    $('.cart-container').prepend(response.cart_html);
801                    $(".promo-info-cart").html(response.promo_info);
802
803                } else {
804
805                }
806            },
807            complete: function () {
808                elem.prop('disabled', false);
809            },
810            error: function () {
811                elem.prop('disabled', false);
812            }
813        });
814    }
815
816    return false;
817});
818
819$(document).on('change', '.qty-input', function (e) {
820    e.preventDefault();
821    var elem = $(this);
822    var qty = $(this).val();
823    var pid = $(this).closest("div.row").find("input[name='product-qty']").attr('id');
824
825
826    if (qty!=0) {
827        pid = pid.split("-");
828        pid = pid[2];
829        elem.prop('disabled', true);
830        $.ajax({
831            method: 'post',
832            url: '/',
833            data: {'action': 'cart-qty-update', product_id: pid, qty: qty, action_type: 'bulk'},
834            success: function (response) {
835                elem.prop('disabled', false);
836                if (response.sucess) {
837                    update_product_prices(pid, response.prices);
838                    elem.val(response.qty);
839                    $.each( response.result, function( key, value ) {
840                        htmlEl = key.replaceAll("_", "-");
841                        if (key=='total_discounts') {
842                            toggle_reducere_box(htmlEl, value);
843                        }
844                        else {
845                            $("#"+htmlEl).html(value+' lei');
846                        }
847
848                    });
849                    $('.cart-container .cart-product-list').remove();
850                    $('.cart-container').prepend(response.cart_html);
851
852                    $(".promo-info-cart").html(response.promo_info);
853
854                } else {
855
856                }
857            },
858            complete: function () {
859                elem.prop('disabled', false);
860            },
861            error: function () {
862                elem.prop('disabled', false);
863            }
864        });
865    }
866
867    return false;
868});
869
870$(document).on('click', '.delete-voucher', function (e) {
871    e.preventDefault();
872    var elem = $(this);
873    elem.prop('disabled', true);
874    elem.append('<span class="cart-aplica-voucher-spinner spinner-border spinner-border-sm"></span>');
875    $.ajax({
876        method: 'post',
877        url: '/',
878        data: {'action': 'delete-cart-voucher'},
879        success: function (response) {
880            $('.cart-aplica-voucher-spinner').remove();
881            elem.prop('disabled', false);
882            if (response.status=='success') {
883                $.each( response.result, function( key, value ) {
884                    htmlEl = key.replaceAll("_", "-");
885                    $("#"+htmlEl).html(value+' lei');
886                });
887
888                $('#voucher-wrapper-form').prepend('<div class="col-12 col-md-8 cupon-wrapper">' +
889                    '<input type="text" class="form-control cart-cupon-wrapper" id="coupon" placeholder="Cupon reducere">' +
890                    '</div>' +
891                    '<div class="col-12 col-md-4 submit-wrapper">' +
892                    '<button type="submit" class="btn btn-primary cart-aplica-voucher d-flex text-left align-left justify-content-center w-100">Aplică</button>' +
893                    '</div>');
894                $(".voucher-name-wrapper").css('display','none');
895                $(".clear-voucher-wrapper").css('display','none');
896            }
897            else {
898                alert('Voucherul nu a putut fi eliminat!');
899            }
900
901            $(".promo-info-cart").html(response.promo_info);
902
903        },
904        complete: function () {
905            elem.prop('disabled', false);
906        },
907        error: function () {
908            elem.prop('disabled', false);
909            $('.cart-aplica-voucher-spinner').remove();
910        }
911    });
912
913    return false;
914});
915
916$(document).on('submit', '#voucher-wrapper-form', function (e) {
917    e.preventDefault();
918    $('.resp-konsole').html('');
919    if ($('#coupon').length) {
920        var cupon_code = '';
921
922        cupon_code = $('#coupon').val().trim();
923        if (cupon_code != '') {
924            var elem = $('.cart-aplica-voucher');
925            elem.prop('disabled', true);
926            elem.append('<span class="cart-aplica-voucher-spinner spinner-border spinner-border-sm"></span>');
927            $.ajax({
928                method: 'post',
929                url: '/',
930                data: {'action': 'apply-cart-voucher', 'cuponcode': cupon_code},
931                success: function (response) {
932                    $('.cart-aplica-voucher-spinner').remove();
933                    elem.prop('disabled', false);
934                    if (response.status=='success') {
935                        $.each( response.result, function( key, value ) {
936                            htmlEl = key.replaceAll("_", "-");
937                            if (key=='total_discounts') {
938                                toggle_reducere_box(htmlEl, value);
939                            }
940                            else {
941                                $("#"+htmlEl).html(value+' lei');
942                            }
943
944                        });
945                        $(".submit-wrapper").css('display','none');
946                        $(".cupon-wrapper").css('display','none');
947                        $('#voucher-wrapper-form').prepend('<div class="col-12 col-md-8 voucher-name-wrapper">' +
948                            '<span>Voucher aplicat </span>\<span class="d-flex align-middle voucher-name-tag text-success">'+cupon_code+'</span>' +
949                            '</div> <div class="col-12 col-md-4 clear-voucher-wrapper">' +
950                            '<a class="btn btn-primary delete-voucher" href="#">Elimina</a>' +
951                            '</div>');
952
953                    }
954                    else {
955                        $('.resp-konsole').html('<p class="text-danger">Voucherul nu a putut fi aplicat</p>');
956                    }
957
958                        $(".promo-info-cart").html(response.promo_info);
959
960
961                },
962                complete: function () {
963                    elem.prop('disabled', false);
964                },
965                error: function () {
966                    elem.prop('disabled', false);
967                    $('.cart-aplica-voucher-spinner').remove();
968                }
969            });
970        }
971    }
972
973});
974
975$(document).on('click', '.cart-product-delete', function (e) {
976    e.preventDefault();
977
978    var product_id = $(this).data('product-id');
979    var elem = $('#product-'+product_id);
980    var is_minicart = ($(this).hasClass("minicart-product-delete")) ? true : false;
981
982
983    $.ajax({
984        method: 'post',
985        url: '/',
986        data: { 'action':'delete-from-cart', 'product_id': product_id, 'is_minicart': is_minicart },
987        success: function (response) {
988
989            if (is_minicart) {
990                $('#header-mini-cart-content').html(response.cart_html);
991                $('#header-mini-cart-total-amount').html(response.result.total_final.toFixed(2).replace('.', ','));
992
993                let count = parseInt(response.count);
994
995                $('.header-mini-cart-items-count').html(count > 0 ? '('+count+')' : '');
996                $('.header-mini-cart-title-items-count').html(count > 0 ? '('+count+' produs'+(count > 1 ? 'e' : '')+')' : '');
997
998                if ( count > 0 ) {
999                    $('#header-mini-cart-actions').addClass('active');
1000                } else {
1001                    $('#header-mini-cart-actions').removeClass('active');
1002                }
1003            }
1004
1005            else {
1006                if (response.cart_empty) {
1007                    $('.cart-container').remove();
1008                    $('.cart-parent-container').append('<p id="sec-parent ">Coșul dvs de cumpărături este gol.</p>');
1009                } else {
1010                    $('.cart-container .cart-product-list').remove();
1011                    $('.cart-container').prepend(response.cart_html);
1012                }
1013
1014                if (response.has_digital_products) {
1015                    $('#digital-products-alert').show();
1016                } else {
1017                    $('#digital-products-alert').hide();
1018                }
1019
1020                $.each(response.result, function (key, value) {
1021                    htmlEl = key.replaceAll("_", "-");
1022                    if (key == 'total_discounts') {
1023                        toggle_reducere_box(htmlEl, value);
1024                    } else {
1025                        $("#" + htmlEl).html(value + ' lei');
1026                    }
1027
1028                });
1029
1030                $(".promo-info-cart").html(response.promo_info);
1031            }
1032
1033
1034        },
1035
1036    });
1037
1038});
1039
1040$(document).on('click', '.continue-as-visitor', function (e) {
1041   e.preventDefault();
1042
1043    $.ajax({
1044        method: 'post',
1045        url: '/',
1046        data: { 'action':'continue-as-visitor', 'register': $(this).data('register') },
1047        success: function (response) {
1048            window.location.href = response.url;
1049        }
1050    });
1051});
1052
1053$(document).on('click', '.checkout-btn-overlay', function (e) {
1054   e.preventDefault();
1055});
1056
1057var formErrors = [];
1058var pendingValidations = 0;
1059var submitPending = false;
1060
1061$(document).on('change', '#checkoutForm input#register', function (e) {
1062    let isChecked = $(this).is(':checked');
1063    let passwordGroup = $('.create-password');
1064    let passwordInput = $('#checkoutForm input#passwordInput')
1065    let passwordConfirmInput = $('#checkoutForm input#passwordConfirmInput')
1066    if ( isChecked ) {
1067        passwordGroup.addClass('active');
1068        passwordInput.attr('required', true);
1069        passwordConfirmInput.attr('required', true);
1070    } else {
1071        passwordGroup.removeClass('active');
1072        passwordInput.removeAttr('required');
1073        passwordConfirmInput.removeAttr('required');
1074    }
1075
1076    $('input[name=register]').val(+isChecked);
1077});
1078
1079$(document).on('keyup', '#checkoutForm input', function (e) {
1080    e.preventDefault();
1081    $(this).trigger('change');
1082});
1083
1084$(document).on('change', '#checkoutForm input, #checkoutForm select', function (e) {
1085    e.preventDefault();
1086    validateCheckoutElement($(this));
1087});
1088
1089$(document).on('change', '#personalDataForm select#countyInput', function (e) {
1090
1091    let judetName = $(this).val();
1092    $.ajax({
1093        method: 'post',
1094        url: '/',
1095        data: {'action': 'get-localities', judetName: judetName},
1096        success: function (response) {
1097            if (response.sucess) {
1098                $('#personalDataForm #localityInput').empty();
1099                $('#personalDataForm #localityInput').append($("<option></option>").attr("value", "").text("Selectează localitatea"));
1100                $.each(response.result, function (key, value) {
1101                    $('#personalDataForm #localityInput').append($("<option></option>").attr("value", value.name).text(value.name));
1102                });
1103
1104                if (judetName == bucharest_label_name) {
1105                    $('#personalDataForm #localityInput').val(bucharest_label_name);
1106                    $('#personalDataForm #localityInput').trigger('change');
1107                    $('#personalDataForm .localityInputBox').addClass('d-none');
1108                    $('#personalDataForm .sectorInputBox').removeClass('d-none');
1109                    $('#personalDataForm #sectorInput').removeClass('is-invalid');
1110                    $('#personalDataForm #sectorInput').val('');
1111                }
1112                else {
1113                    $('#personalDataForm #sectorInput').val('');
1114                    $('#personalDataForm .localityInputBox').removeClass('d-none');
1115                    $('#personalDataForm #localityInput').removeClass('is-valid');
1116                    $('#personalDataForm .sectorInputBox').addClass('d-none');
1117
1118                }
1119
1120            }
1121        },
1122        complete: function () {
1123        },
1124        error: function () {
1125        }
1126    });
1127
1128});
1129
1130$(document).on('change', '#checkoutForm select#countyInput', function (e) {
1131
1132    let judetName = $(this).val();
1133    $.ajax({
1134        method: 'post',
1135        url: '/',
1136        data: {'action': 'get-localities', judetName: judetName},
1137        success: function (response) {
1138            if (response.sucess) {
1139                $('#checkoutForm #localityInput').empty();
1140                $('#checkoutForm #localityInput').append($("<option></option>").attr("value", "").text("Selectează localitatea"));
1141                $.each(response.result, function (key, value) {
1142                    $('#checkoutForm #localityInput').append($("<option></option>").attr("value", value.name).text(value.name + ' (' + value.exteriorKm + ' km)'));
1143                });
1144
1145                    if (judetName == bucharest_label_name) {
1146                        $('#checkoutForm #localityInput').val(bucharest_label_name);
1147                        $('#checkoutForm #localityInput').trigger('change');
1148                        $('#checkoutForm .localityInputBox').addClass('d-none');
1149                        $('#checkoutForm .sectorInputBox').removeClass('d-none');
1150                        $('#checkoutForm #sectorInput').removeClass('is-invalid');
1151                        $('#checkoutForm #sectorInput').val('');
1152                    }
1153                    else {
1154                        $('#checkoutForm #sectorInput').val('');
1155                        $('#checkoutForm .localityInputBox').removeClass('d-none');
1156                        $('#checkoutForm #localityInput').removeClass('is-valid');
1157                        $('#checkoutForm .sectorInputBox').addClass('d-none');
1158
1159                    }
1160
1161            }
1162        },
1163        complete: function () {
1164        },
1165        error: function () {
1166        }
1167    });
1168
1169});
1170
1171$(document).on('change', '#checkoutForm select#localityInput', function (e) {
1172    $('#codPostalInput').trigger('change');
1173});
1174
1175$(document).on('change', '#checkoutForm select#localityInputShipping', function (e) {
1176    $('#codPostalInputShipping').trigger('change');
1177});
1178
1179$(document).on('change', '#isPj', function(e) {
1180    if(this.checked) {
1181        toggle_pj('show');
1182    }
1183    else {
1184        toggle_pj('hide');
1185    }
1186
1187});
1188
1189
1190$(document).on('change', '#isDifferentShipping', function(e) {
1191    if(this.checked) {
1192        toggle_address_titles(true);
1193        toggle_shipping('show', true);
1194    }
1195    else {
1196        toggle_address_titles(false);
1197        toggle_shipping('hide', true);
1198    }
1199
1200});
1201
1202$(document).on('change', '#checkoutForm select#countyInputShipping', function (e) {
1203
1204    let judetName = $(this).val();
1205    $.ajax({
1206        method: 'post',
1207        url: '/',
1208        data: {'action': 'get-localities', judetName: judetName},
1209        success: function (response) {
1210            if (response.sucess) {
1211                $('#checkoutForm #localityInputShipping').empty();
1212                $('#checkoutForm #localityInputShipping').append($("<option></option>").attr("value", "").text("Selectează localitatea"));
1213                $.each(response.result, function (key, value) {
1214                    $('#checkoutForm #localityInputShipping').append($("<option></option>").attr("value", value.name).text(value.name + ' (' + value.exteriorKm + ' km)'));
1215                });
1216            }
1217        },
1218        complete: function () {
1219        },
1220        error: function () {
1221        }
1222    });
1223
1224});
1225
1226
1227$(document).on('submit', '#checkoutForm', async function (e) {
1228    e.preventDefault();
1229
1230    formErrors = [];
1231
1232    $('#submit-checkout')
1233        .prop('disabled', true)
1234        .text('Se validează datele...');
1235
1236    await validateCheckoutForm();
1237
1238    $('#submit-checkout')
1239        .prop('disabled', false)
1240        .text('Comand și plătesc');
1241
1242    if (formErrors.length === 0) {
1243        trackEvent('checkout');
1244        this.submit();
1245    }
1246});
1247
1248$(document).on('change', '.newsletter-page #toate, #newsletter-popup-form #toate', function(e) {
1249    if (this.checked) {
1250        $('.newsletter-page #fictiune').prop("checked", false);
1251        $('.newsletter-page #non-fictiune').prop("checked", false);
1252        $('.newsletter-page #psihologie').prop("checked", false);
1253        $('.newsletter-page #copii').prop("checked", false);
1254
1255        $('#newsletter-popup-form #fictiune').prop("checked", false);
1256        $('#newsletter-popup-form #non-fictiune').prop("checked", false);
1257        $('#newsletter-popup-form #psihologie').prop("checked", false);
1258        $('#newsletter-popup-form #copii').prop("checked", false);
1259    }
1260});
1261
1262$(document).on('change', '.newsletter-page input[type=\'checkbox\'], #newsletter-popup-form input[type=\'checkbox\']', function(e) {
1263    if (this.id != 'toate' && this.id != 'gdpr') {
1264        $('.newsletter-page #toate').prop("checked", false);
1265        $('#newsletter-popup-form #toate').prop("checked", false);
1266
1267    }
1268});
1269
1270function toggle_shipping(action, need_calculate_fan_shipping_tax = false) {
1271    switch (action) {
1272        case 'show':
1273            $('.shipping-global-wrapper').removeClass('d-none');
1274            $('.shipping-global-wrapper').show();
1275            break;
1276
1277        case 'hide':
1278            $('.shipping-global-wrapper').addClass('d-none');
1279            $('.shipping-global-wrapper').hide()
1280            break;
1281        default:
1282            break;
1283
1284    }
1285}
1286
1287function toggle_address_titles(isDifferentShipping) {
1288    if (isDifferentShipping) {
1289       $('.billing-box-label').text('Date de facturare');
1290    }
1291    else {
1292        $('.billing-box-label').text('Date de facturare și livrare');
1293    }
1294}
1295
1296function toggle_pj(action) {
1297    switch (action) {
1298        case 'show':
1299            $('.pj-data-wrapper').removeClass('d-none');
1300            $('.pj-data-wrapper').show();
1301            break;
1302
1303        case 'hide':
1304            $('.pj-data-wrapper').addClass('d-none');
1305            $('.pj-data-wrapper').hide();
1306            break;
1307        default:
1308            break;
1309    }
1310}
1311
1312
1313
1314function set_shipping_method(methodId) {
1315    $.ajax({
1316        method: 'post',
1317        url: '/',
1318        data: {'action': 'set-shipping-method', methodId: methodId},
1319        success: function (response) {
1320            $.each( response.result, function( key, value ) {
1321                htmlEl = key.replaceAll("_", "-");
1322                if (key=='total_discounts' ) {
1323                    //$("#"+htmlEl).html('-'+value+' lei');
1324                    toggle_reducere_box(htmlEl, value);
1325                }
1326                else {
1327                    if (key =='total_final') {
1328                        $("#"+htmlEl).html(response.result.total_products_no_discounts+' lei');
1329                    }
1330                    else {
1331                        $("#" + htmlEl).html(value + ' lei');
1332                    }
1333                }
1334
1335            });
1336        },
1337        complete: function () {
1338        },
1339        error: function () {
1340        }
1341    });
1342}
1343
1344function toggle_payment_method(element_id, switch_to_element, status) {
1345    if (status === 'off') {
1346        $("#checkoutForm #payment-" + switch_to_element).prop("checked", true);
1347        $("#checkoutForm .method-" + switch_to_element).removeClass("d-none");
1348        $("#checkoutForm #payment-" + element_id).prop('checked', false);
1349        $("#checkoutForm #payment-" + element_id).attr("disabled", true);
1350        $("#checkoutForm .method-" + element_id).addClass("d-none");
1351    }
1352    if (status === 'on') {
1353        $("#checkoutForm #payment-" + element_id).attr("disabled", false);
1354        $("#checkoutForm .method-" + element_id).removeClass("d-none");
1355    }
1356}
1357
1358function update_product_prices(productId, prices) {
1359    if ($('#product-'+productId).length > 0) {
1360        $.each( prices, function( key, value ) {
1361            htmlEl = key.replaceAll("_", "-");
1362            $('#product-'+productId+' .'+htmlEl).html(value+' lei');
1363        });
1364    }
1365}
1366
1367async function validateCheckoutForm() {
1368    const validationPromises = [];
1369
1370    $("#checkoutForm").find(':input').each(function() {
1371        const promise = validateCheckoutElement($(this));
1372        if (promise) validationPromises.push(promise);
1373    });
1374
1375    await Promise.all(validationPromises); // așteaptă toate async
1376}
1377
1378async function validateCheckoutElement(target) {
1379    target.removeClass('is-valid');
1380    target.removeClass('is-invalid');
1381
1382    let is_different_shipping =  $('#isDifferentShipping').is(":checked");
1383    let is_pj =  $('#isPj').is(":checked");
1384    let selected_billing_county =  $('#countyInput').val();
1385
1386    const shipping_required_fields = [
1387        'first_name_shipping',
1388        'last_name_shipping',
1389        'phone_shipping',
1390        'address_shipping',
1391        'phone-prefix-shipping',
1392        'street_number_shipping',
1393        'cod_postal_shipping',
1394        'county_shipping',
1395        'locality_shipping',
1396        'country_shipping'
1397    ];
1398
1399    const billing_additional_req_fields = [
1400        'cif',
1401        'company'
1402    ];
1403
1404    const billing_extra_required_fields = [
1405        'sector'
1406    ];
1407
1408
1409
1410    let inputRequired = target.attr('required');
1411    let inputName = target.attr('name');
1412    let inputIndex = $.inArray(inputName, formErrors);
1413    let validateFunction = target.data('validate');
1414
1415
1416    if (billing_extra_required_fields.includes(inputName) && selected_billing_county != bucharest_label_name) {
1417        inputRequired = false;
1418    }
1419
1420    if (shipping_required_fields.includes(inputName) && !is_different_shipping) {
1421        inputRequired = false;
1422    }
1423    if (billing_additional_req_fields.includes(inputName) && !is_pj) {
1424        inputRequired = false;
1425    }
1426
1427    if (inputRequired === 'required' && typeof validateFunction === 'string' && validateFunction !== '') {
1428
1429        validateFunction = validateFunction.replace('-', '_');
1430
1431        if ( typeof window['validate_' +validateFunction] !== 'undefined' ) {
1432
1433            var validator = window['validate_' + validateFunction](target.val());
1434
1435            if (validator.async) {
1436                return new Promise((resolve) => {
1437                    validator.run(function(validate) {
1438                        if (validate.success === false) {
1439                            target.addClass('is-invalid');
1440                            $('.' + inputName + '-feedback').html(validate.feedback);
1441                            if (inputIndex === -1) formErrors.push(inputName);
1442                            target.focus();
1443                        } else {
1444                            target.addClass('is-valid');
1445                            const index = formErrors.indexOf(inputName);
1446                            if (index > -1) formErrors.splice(index, 1);
1447                        }
1448                        resolve(); // semnalează că s-a terminat
1449                    });
1450                });
1451            } else {
1452                if ( validator.success === false ) {
1453                    target.addClass('is-invalid');
1454                    $('.'+inputName+'-feedback').text(validator.feedback);
1455                    if ( inputIndex === -1 ) {
1456                        formErrors.push(inputName);
1457                    }
1458                    target.focus();
1459                } else {
1460                    target.addClass('is-valid');
1461                    index = formErrors.indexOf(inputName);
1462                    if (index > -1) {
1463                        formErrors.splice(index, 1);
1464                    }
1465                    //formErrors.splice(inputIndex, 1);
1466                }
1467            }
1468
1469
1470        }
1471    }
1472}
1473
1474/* Billing */
1475function validate_email( email ) {
1476    var success = false;
1477    var feedback = 'Adresa de email este invalida';
1478    var regex = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
1479
1480    success = regex.test(email);
1481    if ( success ) {
1482        $.post('/', { action: 'check-email-account', email: email }, function (res) {
1483            if ( res.is_account ) {
1484                $('#register').prop('checked', false);
1485                $('.create-account-section').hide();
1486                $('.create-password').removeClass('active');
1487            } else {
1488                $('.create-account-section').show();
1489            }
1490        });
1491
1492        feedback = null;
1493    }
1494
1495    return { success: success, feedback: feedback }
1496}
1497
1498function validate_phone( phone ) {
1499    var success = false;
1500    var feedback = 'Numărul de telefon este incorect';
1501    var regex = /^\+(?:[0-9] ?){6,14}[0-9]$/;
1502
1503    phone = $('#phonePrefixInput').val() + phone;
1504    success = regex.test(phone);
1505    if ( success ) { feedback = null; }
1506
1507    return { success: success, feedback: feedback }
1508}
1509
1510function validate_last_name( last_name ) {
1511
1512    var success = false;
1513    var feedback = 'Numele trebuie sa contina cel putin trei caractere';
1514
1515    if (last_name.length > 0) {
1516        success = true;
1517        feedback = null;
1518    }
1519
1520    return { success: success, feedback: feedback };
1521}
1522
1523function validate_first_name( first_name ) {
1524    var success = false;
1525    var feedback = 'Prenumele trebuie sa contina cel putin trei caractere';
1526
1527    if (first_name.length > 0) {
1528        success = true;
1529        feedback = null;
1530    }
1531    return { success: success, feedback: feedback };
1532}
1533
1534function validate_address( address ) {
1535
1536    var success = false;
1537    var feedback = 'Adresa este invalida';
1538
1539
1540    if ( address.length > 0  ) { success = true, feedback = null; }
1541
1542    return { success: success, feedback: feedback };
1543}
1544
1545function validate_street_number( street_number ) {
1546
1547    var success = false;
1548    var feedback = 'Numărul trebuie să conțină între 1 și 10 caractere';
1549    
1550    if (street_number.length > 0 && street_number.length <= 10) {
1551        success = true;
1552        feedback = null;
1553    }
1554
1555    return {
1556        success: success,
1557        feedback: feedback
1558    };
1559}
1560
1561function validate_locality( locality ) {
1562    var success = false;
1563    var feedback = 'Localitatea este invalida';
1564    locality = locality.trim();
1565    if (locality.length > 0) {
1566        success = true;
1567        feedback = null;
1568    }
1569
1570    return { success: success, feedback: feedback };
1571}
1572
1573function validate_county( county ) {
1574    var success = false;
1575    var feedback = 'Judetul este invalid';
1576    success = county.trim().length > 0;
1577    if ( success ) { feedback = null; }
1578
1579    return { success: success, feedback: feedback };
1580}
1581
1582function validate_cod_postal(cod_postal) {
1583  var success = false;
1584  var feedback = 'Codul poștal trebuie să aibă exact 6 cifre.';
1585  cod_postal = cod_postal.replace(/\s+/g, '');
1586  if (/^\d{6}$/.test(cod_postal)) {
1587    success = true;
1588    feedback = null;
1589  }
1590  return { success: success, feedback: feedback };
1591}
1592
1593function validate_cod_postal_complex(value) {
1594    return {
1595        async: true,
1596        run: function(done) {
1597            var localityName = ($('#localityInput').val() || '').trim();
1598
1599            value = (value || '').replace(/\s+/g, '');
1600
1601            if (!/^\d{6}$/.test(value)) {
1602                return done({
1603                    success: false,
1604                    feedback: 'Codul poștal trebuie să aibă exact 6 cifre.'
1605                });
1606            }
1607
1608            if (!localityName) {
1609                return done({
1610                    success: false,
1611                    feedback: 'Selectează localitatea pentru validare completă.'
1612                });
1613            }
1614
1615            fetch(`/api-couriers/v2/validate-postal-code.php`, {
1616                method: 'POST',
1617                headers: {'Content-Type': 'application/json'},
1618                body: JSON.stringify({
1619                    postalCode: value,
1620                    city: localityName
1621                })
1622            })
1623                .then(r => r.json())
1624                .then(data => {
1625                    done({
1626                        success: !!data.valid,
1627                        feedback: data.valid ? null : 'Cod poștal invalid pentru localitatea selectată. Cauta codul postal corect, <a href="https://www.posta-romana.ro/cauta-cod-postal.html" target="_blank">click aici</a>'
1628                    });
1629                })
1630                .catch(() => {
1631                    done({
1632                        success: false,
1633                        feedback: 'Eroare de rețea.'
1634                    });
1635                });
1636        }
1637    };
1638}
1639
1640function validate_cod_postal_shipping_complex(value) {
1641    return {
1642        async: true,
1643        run: function(done) {
1644            var localityName = ($('#localityInputShipping').val() || '').trim();
1645
1646            value = (value || '').replace(/\s+/g, '');
1647
1648            if (!/^\d{6}$/.test(value)) {
1649                return done({
1650                    success: false,
1651                    feedback: 'Codul poștal trebuie să aibă exact 6 cifre.'
1652                });
1653            }
1654
1655            if (!localityName) {
1656                return done({
1657                    success: false,
1658                    feedback: 'Selectează localitatea pentru validare completă.'
1659                });
1660            }
1661
1662            fetch(`/api-couriers/v2/validate-postal-code.php`, {
1663                method: 'POST',
1664                headers: {'Content-Type': 'application/json'},
1665                body: JSON.stringify({
1666                    postalCode: value,
1667                    city: localityName
1668                })
1669            })
1670                .then(r => r.json())
1671                .then(data => {
1672                    done({
1673                        success: !!data.valid,
1674                        feedback: data.valid ? null : 'Cod poștal invalid pentru localitatea selectată. Caută codul poștal corect, <a href="https://www.posta-romana.ro/cauta-cod-postal.html" target="_blank">click aici</a>'
1675                    });
1676                })
1677                .catch(() => {
1678                    done({
1679                        success: false,
1680                        feedback: 'Eroare de rețea.'
1681                    });
1682                });
1683        }
1684    };
1685}
1686
1687document.getElementById('codPostalInput')?.addEventListener('input', function(e) {
1688  this.value = this.value.replace(/\D/g, '');
1689  if (this.value.length > 6) {
1690    this.value = this.value.slice(0, 6);
1691  }
1692});
1693
1694function validate_sector( sector ) {
1695    var success = false;
1696    var feedback = 'Sector invalid';
1697    if ( sector.trim().length > 0) {
1698        feedback = null;
1699        success = true;
1700    }
1701    return { success: success, feedback: feedback };
1702}
1703
1704
1705/* Shipping */
1706function validate_phone_shipping( phone_shipping ) {
1707    var success = false;
1708    var feedback = 'Numărul de telefon este incorect';
1709    var regex = /^\+(?:[0-9] ?){6,14}[0-9]$/;
1710
1711    phone_shipping = $('#phonePrefixInputShipping').val() + phone_shipping;
1712    success = regex.test(phone_shipping);
1713    if ( success ) { feedback = null; }
1714
1715    return { success: success, feedback: feedback }
1716}
1717
1718function validate_last_name_shipping( last_name_shipping ) {
1719
1720    var success = false;
1721    var feedback = 'Numele trebuie sa contina cel putin trei caractere';
1722
1723    if (last_name_shipping.length > 0) {
1724        success = true;
1725        feedback = null;
1726    }
1727
1728    return { success: success, feedback: feedback };
1729}
1730
1731function validate_first_name_shipping( first_name_shipping ) {
1732    var success = false;
1733    var feedback = 'Prenumele trebuie sa contina cel putin trei caractere';
1734
1735    if (first_name_shipping.length > 0) {
1736        success = true;
1737        feedback = null;
1738    }
1739    return { success: success, feedback: feedback };
1740}
1741
1742function validate_address_shipping( address_shipping ) {
1743
1744    var success = false;
1745    var feedback = 'Adresa este invalida';
1746
1747
1748    if ( address_shipping.length > 0  ) { success = true, feedback = null; }
1749
1750    return { success: success, feedback: feedback };
1751}
1752
1753function validate_street_number_shipping(street_number_shipping) {
1754
1755    var success = false;
1756    var feedback = 'Numărul trebuie să conțină între 1 și 10 caractere';
1757
1758    if (street_number_shipping.length > 0 && street_number_shipping.length <= 10) {
1759        success = true;
1760        feedback = null;
1761    }
1762
1763    return {
1764        success: success,
1765        feedback: feedback
1766    };
1767}
1768
1769function validate_locality_shipping( locality_shipping ) {
1770    var success = false;
1771    var feedback = 'Localitatea este invalida';
1772    locality_shipping = locality_shipping.trim();
1773
1774    if (locality_shipping.length > 0) {
1775        success = true;
1776        feedback = null;
1777    }
1778
1779    return { success: success, feedback: feedback };
1780}
1781
1782function validate_county_shipping( county_shipping ) {
1783    var success = false;
1784    var feedback = 'Judetul este invalid';
1785    success = county_shipping.trim().length > 0;
1786    if ( success ) { feedback = null; }
1787
1788    return { success: success, feedback: feedback };
1789}
1790
1791function validate_cod_postal_shipping(cod_postal_shipping) {
1792  var success = false;
1793  var feedback = 'Codul poștal trebuie să aibă exact 6 cifre.';
1794  cod_postal_shipping = cod_postal_shipping.replace(/\s+/g, '');
1795  if (/^\d{6}$/.test(cod_postal_shipping)) {
1796    success = true;
1797    feedback = null;
1798  }
1799  return { success: success, feedback: feedback };
1800}
1801
1802document.addEventListener('DOMContentLoaded', function () {
1803  const postalInput = document.getElementById('codPostalInputShipping');
1804  if (postalInput) {
1805    postalInput.addEventListener('input', function () {
1806      this.value = this.value.replace(/\D/g, '');
1807      if (this.value.length > 6) {
1808        this.value = this.value.slice(0, 6);
1809      }
1810    });
1811  }
1812});
1813
1814/* PJ */
1815function validate_cif( cif ) {
1816    var success = false;
1817    var feedback = 'CIF este invalid';
1818    if ( cif.trim().length > 0) {
1819        feedback = null;
1820        success = true;
1821    }
1822    return { success: success, feedback: feedback };
1823}
1824
1825function validate_company( company ) {
1826    var success = false;
1827    var feedback = 'Compania este invalida';
1828    if ( company.trim().length > 0) {
1829        feedback = null;
1830        success = true;
1831    }
1832    return { success: success, feedback: feedback };
1833}
1834
1835
1836
1837
1838
1839
1840
1841function validate_county_sediu( county_sediu ) {
1842    currentShippingMethod = $('input[name=shipping-method]:checked', '#checkoutForm').val();
1843    if (currentShippingMethod!=3) {  return {success: true, feedback: null};}
1844    var success = false;
1845    var feedback = 'Judetul este invalid';
1846
1847    success = county_sediu.trim().length > 0;
1848    if ( success ) { feedback = null; }
1849    return { success: success, feedback: feedback };
1850}
1851
1852function validate_locality_sediu( locality_sediu ) {
1853    currentShippingMethod = $('input[name=shipping-method]:checked', '#checkoutForm').val();
1854    if (currentShippingMethod!=3) {  return {success: true, feedback: null};}
1855    var success = false;
1856    var feedback = 'Localitatea este invalidă';
1857
1858    success = locality_sediu.trim().length > 0;
1859    if ( success ) { feedback = null; }
1860    return { success: success, feedback: feedback };
1861}
1862
1863function validate_county_collectpoint( county_collectpoint ) {
1864    currentShippingMethod = $('input[name=shipping-method]:checked', '#checkoutForm').val();
1865    if (currentShippingMethod!=4) {  return {success: true, feedback: null};}
1866    var success = false;
1867    var feedback = 'Judetul este invalid';
1868
1869    success = county_collectpoint.trim().length > 0;
1870    if ( success ) { feedback = null; }
1871    return { success: success, feedback: feedback };
1872}
1873
1874function validate_locality_collectpoint( locality_collectpoint ) {
1875    currentShippingMethod = $('input[name=shipping-method]:checked', '#checkoutForm').val();
1876    if (currentShippingMethod != 4) {  return {success: true, feedback: null};}
1877    var success = false;
1878    var feedback = 'Localitatea este invalidă';
1879
1880    success = locality_collectpoint.trim().length > 0;
1881    if ( success ) { feedback = null; }
1882    return { success: success, feedback: feedback };
1883}
1884
1885function validate_password( password ) {
1886    var success = false;
1887    var feedback = 'Parola ta trebuie să conțină minim 6 caractere, cel puțin o majusculă, o cifră și un caracter special.';
1888    var errors = 0;
1889
1890    if (password.length > 0) {
1891
1892        if (password.length < 6) {
1893            // feedback = 'Parola ta trebuie să conțină minim 6 caractere';
1894            errors++;
1895        } else if (/\d/.test(password) === false) {
1896            // feedback = 'Parola trebuie să conțină cel puțin o cifră';
1897            errors++;
1898        } else if (/[A-Z]/.test(password) === false) {
1899            // feedback = 'Parola trebuie să conțină cel puțin o literă majusculă';
1900            errors++;
1901        } else if (/\W/.test(password) === false) {
1902            // feedback = 'Parola trebuie să conțină cel puțin un caracter special';
1903            errors++;
1904        } else if (/\s/.test(password) === true) {
1905            feedback = 'Parola nu trebuie să conțină niciun spațiu alb';
1906            errors++;
1907        }
1908
1909        if (errors === 0) {
1910            feedback = null;
1911            success = true;
1912        }
1913    }
1914
1915    return { success: success, feedback: feedback };
1916}
1917
1918function validate_passwordconfirm( password ) {
1919    var success = false;
1920    var feedback = 'Câmpul este obligatoriu';
1921
1922    if (password.length > 0 && password !== $('#passwordInput').val()) {
1923        feedback = 'Parolele nu se potrivesc'
1924    } else {
1925        if (password.length == 0) {
1926            feedback = 'Campul confirmare parola este gol.'
1927        } else {
1928            feedback = null;
1929            success = true;
1930        }
1931    }
1932
1933    return { success: success, feedback: feedback };
1934}
1935
1936
1937function toggle_reducere_box(htmlEl, value) {
1938    if (value > 0 ) {
1939        $("#" + htmlEl).html('-' + value + ' lei');
1940        $("#" + htmlEl+'-label').html('Reducere');
1941    }
1942    else {
1943        $("#" + htmlEl).html('');
1944        $("#" + htmlEl+'-label').html('');
1945    }
1946}
1947
1948// Restricts input for the given textbox to the given inputFilter function.
1949function setInputFilter(textboxes, inputFilter, errMsg) {
1950    [ "input", "keydown", "keyup", "mousedown", "mouseup", "select", "contextmenu", "drop", "focusout" ].forEach(function(event) {
1951        for (var i = 0; i < textboxes.length; i++) {
1952            textboxes[i].addEventListener(event, function (e) {
1953                if (inputFilter(this.value)) {
1954                    // Accepted value.
1955                    if (["keydown", "mousedown", "focusout"].indexOf(e.type) >= 0) {
1956                        this.classList.remove("input-error");
1957                        this.setCustomValidity("");
1958                    }
1959
1960                    this.oldValue = this.value;
1961                    this.oldSelectionStart = this.selectionStart;
1962                    this.oldSelectionEnd = this.selectionEnd;
1963                } else if (this.hasOwnProperty("oldValue")) {
1964                    // Rejected value: restore the previous one.
1965                    this.classList.add("input-error");
1966                    this.setCustomValidity(errMsg);
1967                    this.reportValidity();
1968                    this.value = this.oldValue;
1969                    this.setSelectionRange(this.oldSelectionStart, this.oldSelectionEnd);
1970                } else {
1971                    // Rejected value: nothing to restore.
1972                    this.value = "";
1973                }
1974            });
1975        }
1976    });
1977}
1978
1979
1980$(document).on('click', '.popup-header-close', function (e) {
1981    e.preventDefault();
1982    $('.popup-add-to-cart-product').html('');
1983    $('#add-to-cart-popup').removeClass('show');
1984});
1985
1986
1987function setCookie(cname, cvalue, exdays) {
1988    const d = new Date();
1989    d.setTime(d.getTime() + (exdays*24*60*60*1000));
1990    let expires = "expires="+ d.toUTCString();
1991    document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
1992}
1993
1994function getCookie(cname) {
1995    let name = cname + "=";
1996    let decodedCookie = decodeURIComponent(document.cookie);
1997    let ca = decodedCookie.split(';');
1998    for(let i = 0; i <ca.length; i++) {
1999        let c = ca[i];
2000        while (c.charAt(0) == ' ') {
2001            c = c.substring(1);
2002        }
2003        if (c.indexOf(name) == 0) {
2004            return c.substring(name.length, c.length);
2005        }
2006    }
2007    return "";
2008}
2009
2010function deleteCookie(name) {
2011    document.cookie = name + '=;expires=Thu, 01 Jan 1970 00:00:01 GMT;';
2012}
2013
2014function redirectAfterDelay(parent_el, refresh_el, seconds, redirect_url)
2015{
2016    var seconds = 5;
2017    var dvCountDown = document.getElementById(parent_el);
2018    var lblCount = document.getElementById(refresh_el);
2019
2020    lblCount.innerHTML = seconds;
2021    setInterval(function ()
2022    {
2023        seconds--;
2024        lblCount.innerHTML = seconds;
2025        if (seconds == 0)
2026        {
2027            window.location = redirect_url;
2028            dvCountDown.style.display = "none";
2029
2030        }
2031    }, 1000);
2032}
2033
2034function isScrolledIntoView(el)
2035{
2036    var elementTop = $(el).offset().top;
2037    var elementBottom = elementTop + $(el).outerHeight();
2038
2039    var viewportTop = $(window).scrollTop() + 138;
2040    var viewportBottom = viewportTop + $(window).height() - 138;
2041
2042    return elementBottom > viewportTop && elementTop < viewportBottom;
2043}
2044
2045function deviceType() {
2046    const ua = navigator.userAgent;
2047    if (/(tablet|ipad|playbook|silk)|(android(?!.*mobi))/i.test(ua)) {
2048        return "tablet";
2049    }
2050    else if (/Mobile|Android|iP(hone|od)|IEMobile|BlackBerry|Kindle|Silk-Accelerated|(hpw|web)OS|Opera M(obi|ini)/.test(ua)) {
2051        return "mobile";
2052    }
2053    return "desktop";
2054}
2055
2056function uuid_v4() {
2057    return ([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g, c =>
2058        (c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16)
2059    );
2060}
2061
2062/* -- Tracking -------------------------------------------------------------------------------------------------------*/
2063
2064function trackEvent( event , params = {} ) {
2065    if ( getCookie('__i') === '' ) {
2066        setCookie('__i', Date.now() + '.' + uuid_v4(), 1095);
2067    }
2068
2069    $.ajax({
2070        type : 'GET',
2071        url  : '/collect.php',
2072        data: {
2073            d: window.location.hostname,
2074            dv: deviceType(),
2075            a: event,
2076            i: getCookie('__i'),
2077            s: getCookie('PHPSESSID'),
2078            p: window.location.href,
2079            params: params
2080        },
2081        success: function(result) {}
2082    });
2083}
2084
2085async function returnFromPopupToCheckout() {
2086    setCookie('_ei', 'popup-', 1);
2087    await trackEvent('return-from-popup');
2088    window.location.href = '/finalizare-comanda';
2089}
2090
2091window.show_popup = true;
2092var show_ei = false;
2093var show_eic = false;
2094var ei_eic_changed = false;
2095
2096function initTrackingPopup( ei_eic_changed ) {
2097    $.ajax({
2098        type : 'GET',
2099        url  : '/check-cart.php?cc=true&cp='+window.location.pathname+'&host='+window.location.host,
2100        success: function(result) {
2101            var message = result.message;
2102
2103            if ( result.ei === 1 ) {
2104                show_ei = true;
2105                show_eic = false;
2106            }
2107
2108            if (  result.eic === 1 ) {
2109                show_ei = false;
2110                show_eic = true;
2111                message = 'Salut! Am observat că nu ai reușit să finalizezi comanda. Suntem aici pentru tine, contactează-ne la +40 (21) 300 60 90 sau [email protected] și vei putea profita de promoția noastră';
2112            }
2113
2114            document.addEventListener('mouseout', e => {
2115                var mouseY = e.clientY;
2116
2117                if (!e.toElement && !e.relatedTarget && window.show_popup && mouseY < 0) {
2118                    // $(window).on('beforeunload', function (e) {
2119                        const eidn = Date.now();
2120                        const ei = getCookie('ei');
2121                        const eic = getCookie('eic');
2122
2123                        // fill popup with message
2124                        $('#exit-intent-message').html(message);
2125                        $('#exit-intent-logo').html('<img src="' + result.logo + '">');
2126                        $('#exit-intent-product-message').html(result.message_product);
2127
2128                        if (result.image !== null && result.image !== '') {
2129                            $('#exit-intent-product-image').html('<img src="' + result.image 
2129+ '">');
2130                        }
2131
2132                        $('#exit-intent-product-name').html(result.name);
2133
2134                        if (show_ei && result.show_product === 1) { // || result.show_product === 1
2135                            $('#exit-intent-product').css('display', 'flex');
2136                        } else {
2137                            $('#exit-intent-product').hide();
2138                        }
2139
2140                        if (eidn > ei && show_ei) {
2141                            trackEvent('popup-show-ei');
2142                            setCookie('ei', new Date(eidn + 1440 * 60000).getTime(), 1);
2143
2144                            // show popup
2145                            document.querySelector('.exit-intent-popup').classList.add('visible');
2146
2147                        }
2148
2149                        if (eidn > eic && show_eic && ei_eic_changed) {
2150                            trackEvent('popup-show-eic');
2151                            setCookie('eic', new Date(eidn + 1440 * 60000).getTime(), 1);
2152
2153                            // show popup
2154                            document.querySelector('.exit-intent-popup').classList.add('visible');
2155
2156                        }
2157                    // });
2158                }
2159            });
2160
2161        }
2162    });
2163}
2164
2165
2166$(document).ready(function () {
2167    $(document).bind('change', 'form#checkoutForm :input', function (){
2168        if (ei_eic_changed === false) {
2169            ei_eic_changed = true;
2170            initTrackingPopup(ei_eic_changed);
2171        }
2172    });
2173
2174
2175    if  ($(".newsletter-popup").length) {
2176        $(".newsletter-popup-abonare button").prop('disabled', false);
2177        document.querySelector('.newsletter-popup').classList.add('visible');
2178        $(document).on('submit', '#newsletter-popup-form', function (e) {
2179            var elem = $(".newsletter-popup-abonare button");
2180            e.preventDefault();
2181
2182
2183            if ($(".newsletter-popup-spinner").closest("html").length) {
2184                $(".newsletter-popup-spinner").remove();
2185            }
2186            elem.append('<span class="ms-2 newsletter-popup-spinner spinner-border spinner-border-sm"></span>');
2187
2188            if ($('#newsletter-popup-form #newsletter-popup-email').length) {
2189                $(".email-wrapper input").removeClass('is-invalid');
2190                $(".disc-wrapper .gdpr-check").removeClass('is-invalid');
2191                $(".disc-wrapper-first").removeClass('is-invalid');
2192                $('#newsletter-popup-form .newsletter-popup-response').html('');
2193
2194                grecaptcha.ready(function () {
2195                    grecaptcha.execute(g_site_key, {action: 'newsletter_popup_form'}).then(function (token) {
2196                        //elem.prop('disabled', true);
2197
2198                        $('#newsletter-popup-form #rechaptcha-token').remove();
2199                        $('#newsletter-popup-form #rechaptcha-action').remove();
2200                        $('#newsletter-popup-form').prepend('<input type="hidden" id="rechaptcha-token" name="token" value="' + token + '">');
2201                        $('#newsletter-popup-form').prepend('<input type="hidden" id="rechaptcha-action" name="gaction" value="newsletter_popup_form">');
2202
2203
2204                        email = $('#newsletter-popup-form #newsletter-popup-email').val().trim();
2205                        gdpr = $('#newsletter-popup-form .gdpr-check').is(":checked");
2206
2207
2208                        if (email != '' && gdpr) {
2209
2210                            $.ajax({
2211                                method: 'post',
2212                                url: '/ajax/nl_popup_subscribe.php',
2213                                data: $('#newsletter-popup-form').serialize(),
2214                                dataType: "json",
2215                                success: function (response) {
2216                                    elem.prop('disabled', false);
2217                                    $(".newsletter-popup-spinner").remove();
2218                                    if (response.status == 'success') {
2219                                        $(".newsletter-popup .main-cta").text("Înscrierea a fost realizată cu success.\n Va mulțumim!");
2220                                        $(".newsletter-popup .email-wrapper").addClass("d-none");
2221                                        $(".newsletter-popup-response").addClass("d-none");
2222                                        $(".newsletter-popup .disc-wrapper").addClass("d-none");
2223                                        $(".newsletter-popup .lists-wrapper").addClass("d-none");
2224                                        $(".newsletter-popup .newsletter-popup-actions .newsletter-popup-abonare").addClass("d-none");
2225                                        $(".newsletter-popup .newsletter-popup-actions .newsletter-popup-close .btn").text("Închide");
2226
2227                                    } else {
2228                                        if (response.status == 'error') {
2229                                            $.each(response.errors, function (key, value) {
2230                                                $(".newsletter-popup-response").html('<p>' + value + '</p>');
2231                                            });
2232                                        }
2233                                    }
2234                                },
2235                                complete: function () {
2236                                    elem.prop('disabled', false);
2237                                    $('.newsletter-popup-spinner').remove();
2238                                },
2239                                error: function () {
2240                                    elem.prop('disabled', false);
2241                                    $('.newsletter-popup-spinner').remove();
2242                                }
2243                            });
2244                        } else {
2245                            elem.prop('disabled', false);
2246                            $(".newsletter-popup-spinner").remove();
2247                            if (email == '') {
2248                                $(".email-wrapper input").addClass('is-invalid');
2249                            }
2250                            if (!gdpr) {
2251                                $(".disc-wrapper .gdpr-check").addClass('is-invalid');
2252                                $(".disc-wrapper-first ").addClass('is-invalid');
2253                            }
2254                        }
2255
2256
2257                    });
2258
2259
2260                });
2261
2262            }
2263
2264            return false;
2265        });
2266    } else {
2267        if  ($(".holiday-popup").length) {
2268            document.querySelector('.holiday-popup').classList.add('visible');
2269        }
2270    }
2271
2272    $(document).on('click', '.newsletter-popup-close', function () {
2273        document.querySelector('.newsletter-popup').classList.remove('visible');
2274
2275        setTimeout(function () {
2276            if  ($(".holiday-popup").length) {
2277                document.querySelector('.holiday-popup').classList.add('visible');
2278            }
2279        }, 3000);
2280    });
2281
2282
2283
2284
2285
2286    if ($(".checkout-page").length) {
2287  $(document).on('click', '#submit-checkout', function (e) {
2288    e.preventDefault();
2289
2290    const shippingInputs = document.querySelectorAll('input[name="shipping-method"]');
2291    if (shippingInputs.length > 0) {
2292      const selectedMethod = document.querySelector('input[name="shipping-method"]:checked');
2293      if (!selectedMethod) {
2294        alert('Te rog alege o metodă de livrare.');
2295        return;
2296      }
2297
2298      if (selectedMethod.id === 'shipping-locker-unic') {
2299        const pickupPoint = document.querySelector('.pickup-point')?.value.trim() || '';
2300        const countyLocality = document.querySelector('.pickup-county-locality')?.value.trim() || '';
2301        const lockerAddress = document.getElementById('lockerAddressHidden')?.value.trim() || '';
2302
2303        const parts = pickupPoint.split('|||');
2304        const lockerId = parts.at(-1)?.trim() || '';
2305
2306        if (
2307          pickupPoint === '' ||
2308          countyLocality === '' ||
2309          lockerAddress === '' ||
2310          lockerId === '' ||
2311          !/^[a-zA-Z0-9]+$/.test(lockerId)
2312        ) {
2313          alert('Te rugăm selectează locker-ul de pe hartă înainte de a finaliza comanda.');
2314          return;
2315        }
2316      }
2317    }
2318
2319    grecaptcha.ready(function() {
2320      grecaptcha.execute(g_site_key, {action: 'checkout_form'}).then(function(token) {
2321        $('#checkoutForm #rechaptcha-token').remove();
2322        $('#checkoutForm #rechaptcha-action').remove();
2323        $('#checkoutForm').prepend('<input type="hidden" id="rechaptcha-token" name="gtoken" value="' + token + '">');
2324        $('#checkoutForm').prepend('<input type="hidden" id="rechaptcha-action" name="gaction" value="checkout_form">');
2325        $('#checkoutForm').submit();
2326      });
2327    });
2328
2329  });
2330}
2331
2332
2333});
2334
2335
2336
2337initTrackingPopup();
2338
2339trackEvent('ping');
2340

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.