
$( document ).ready(function() {
    const sidebarCart = document.querySelector('.sidebar-cart');
    if (sidebarCart) {
        const closeCart = document.getElementById('closeCart');
        const sidebarCartToggler = document.querySelector('.sidebar-cart-toggler');

        if(sidebarCartToggler) {
            sidebarCartToggler.addEventListener('click', ()=> {
              document.body.style.overflow = 'hidden';
                sidebarCart.classList.remove("hidden");
                document.querySelector("body").classList.add('filter');
            });
        }

        const hideCart = () => {
            document.body.style.overflowY = '';
            sidebarCart.classList.add("hidden");
            document.querySelector("body").classList.remove('filter');
        }

        closeCart.addEventListener('click', ()=> {
            hideCart();
        });

        document.addEventListener("click", (e)=>{
            if (!e.target.closest(".sidebar-cart") && !e.target.classList.contains('.sidebar-cart-toggler') && !e.target.closest('.sidebar-cart-toggler')){
                hideCart();
            }
        });

    }


//CART ACTIONS


$(document).ready(function() {
  // Use event delegation to handle click events for dynamically generated elements
  $(document).on('click', '.decrement', function() {
      let quantityElement = $(this).next();
      let amount = parseInt(quantityElement.text());
      if (amount === 2) {
          quantityElement.text('1');
          $(this).addClass('disabled');
      } else if (amount > 1) {
          quantityElement.text((amount - 1).toString());
      }
      // Disable the decrement button when the cart amount is 1
      if (amount === 1) {
          $(this).addClass('disabled');
      }
  });

  $(document).on('click', '.increment', function() {
      let quantityElement = $(this).prev();
      let decrementButton = $(this).siblings('.decrement');
      let amount = parseInt(quantityElement.text());
      quantityElement.text((amount + 1).toString());
      // Enable the decrement button when incrementing
      decrementButton.removeClass('disabled');
  });
});







    const navbarToggler = document.querySelector(".navbar-toggler");
    if (navbarToggler) {
        const sideMenu = document.querySelector(".navbar-collapse");
        const body = document.querySelector("body");
        navbarToggler.addEventListener("click", ()=> {
            navbarToggler.classList.add("hidden");
            body.classList.toggle("no-scroll");
            setTimeout(()=> {
                navbarToggler.classList.remove("hidden");
            }, 200)

        })
    }

    window.addEventListener("resize", () => {
      const sideMenu = document.querySelector(".navbar-collapse");
      const body = document.querySelector("body");
      if (sideMenu) { // Check if sideMenu is not null
          if (window.innerWidth > 1279) {
              body.classList.remove("no-scroll");
          } else if (sideMenu.classList.contains("show")) {
              body.classList.add("no-scroll");
          }
      }
  });


    const readMore = document.querySelector(".read-more-truncate");

    if (readMore) {
        readMore.addEventListener("click", ()=> {

            readMore.style.display = "none";
            document.querySelector(".truncated-text").style.display = "block";
        })
    }


    const favouriteButtons = document.querySelectorAll(".cart-favorite");
    if (favouriteButtons.length) {
        Array.from(favouriteButtons).forEach(button => {
            button.addEventListener("click", ()=> {
                button.classList.toggle("favourite");
            })
        })
    }

      if (document.querySelector(".tippy-tip")) {
        tippy('#tooltip1', {
          content: "<strong>Dėmesio!</strong> Pristatymo terminai yra preliminarūs, kadangi terminai atsinaujina priklausomai nuo faktinio užsakymo pateikimo laiko. Galutinis pristatymo terminas yra pateikiamas užsakymo patvirtinime.",
          allowHTML: true,
          theme: "white-box",
        });

        tippy('#tooltip2', {
          content: `<strong>Dėmesio!</strong> Pristatymo terminai yra preliminarūs, kadangi terminai atsinaujina priklausomai nuo faktinio užsakymo pateikimo laiko. Galutinis pristatymo terminas yra pateikiamas užsakymo patvirtinime.`,
          allowHTML: true,
          theme: "white-box",
        });

        tippy('#tooltip3', {
          content: `<strong>Dėmesio!</strong> Smulkaus krepšelio info.`,
          allowHTML: true,
          theme: "white-box",
        });

        tippy('#tooltip4', {
          content: `<strong>Dėmesio!</strong> Smulkaus krepšelio info.`,
          allowHTML: true,
          theme: "white-box",
        });
      }


    const reviewWraps = document.querySelectorAll(".review-bg");
    const reviewsSwiper = document.querySelector(".review-swiper");
    if(reviewWraps.length) {
        Array.from(reviewWraps).forEach(review => {
            review.style.height = `${reviewsSwiper.clientHeight + 100}px`;
        })
    }



});








const mapContainer = document.getElementById("map");
    if (mapContainer) {
       function initMap() {
           const location =  {
               lat: 54.671760,
               lng: 25.257300
           };
           const map = new google.maps.Map(mapContainer, {
               zoom: 13,
               center: location,
               disableDefaultUI: true,
               mapId: '60d060587d117504',
           });
           const marker = new google.maps.Marker({
               position: {
                   lat: 54.671760,
                   lng: 25.257300
               },
               map:map,
               icon: "/assets/img/location-pointer.svg",
           })
           map.overlayMapTypes.setAt( 0, null);
       }
    }

$( document ).ready(function() {
    const ageSwipers = document.querySelectorAll('.side-age-filter-swiper');
    if (ageSwipers.length) {
        const ageSwipersArr = [];
        Array.from(ageSwipers).forEach(swiper => {
            const swiperID = swiper.id;
            ageSwipersArr.push(
                new Swiper(`#${swiperID} .swiper`, {
                    speed: 400,
                    spaceBetween: 34,
                    slidesPerView: 3,
                    pagination: {
                        el: '.swiper-pagination',
                        type: 'bullets',
                    },
                    navigation: {
                        nextEl:  `#${swiperID} .purple-next`,
                        prevEl:  `#${swiperID} .purple-prev`,
                    },
                    breakpoints: {
                        400: {
                            slidesPerView: 4,
                        },
                    },
                })
            )
        })
    }
});

$( document ).ready(function() {
  const heroSwiper = document.querySelector("#hero-landing-swiper");

  if (heroSwiper) {
      const swiperLandingHero = new Swiper('#hero-landing-swiper', {
          speed: 400,
          spaceBetween: 100,
          pagination: {
              el: '#hero-landing-swiper .swiper-pagination',
              type: 'bullets',
          },
          navigation: {
              nextEl: '.hero-landing-swiper-next',
              prevEl: '.hero-landing-swiper-prev',
          },
      });

      const nextButton = document.querySelector('.hero-landing-swiper-next');
      const prevButton = document.querySelector('.hero-landing-swiper-prev');
      nextButton.style.pointerEvents = 'auto';
      prevButton.style.pointerEvents = 'auto';

      swiperLandingHero.on('slideChange', () => {
          if (swiperLandingHero.isEnd) {
              // Enable clicking when button is disabled
              nextButton.style.pointerEvents = 'auto';
              prevButton.style.pointerEvents = 'auto';
          } else {
              // Restore the original behavior
              nextButton.style.pointerEvents = 'auto';
              prevButton.style.pointerEvents = 'auto';
          }

          // Similarly, you can handle the previous button here if needed.
      });
  }


        const allProductSwipers = document.querySelectorAll(".product-swiper-wrap");
        if(allProductSwipers.length){
           const allProductSwipersArr = [];
           Array.from(allProductSwipers).forEach(swiper => {
               const swiperID = swiper.id;
               const newSwiper = new Swiper(`#${swiperID} .swiper`, {
                   speed: 400,
                   spaceBetween: 28,
                   slidesPerView: 4,
                   navigation: {
                       nextEl: `#${swiperID} .swiper-button-next`,
                       prevEl: `#${swiperID} .swiper-button-prev`,
                   },
                   breakpoints: {
                       0: {
                           slidesPerView: 1,
                       },
                       577: {
                           slidesPerView: 2,
                           spaceBetween: 15,
                       },

                       994: {
                           slidesPerView: 3,
                       },
                       1281: {
                           slidesPerView: 4,
                           spaceBetween: 28,
                       },
                   }
               });
               allProductSwipersArr.push(newSwiper);
           })
        }

        $(document).ready(function () {
                   $('.dropdown').hover(function () {
                       $(this).addClass('show');
                       $(this).find('.dropdown-menu').addClass('show');
                   }, function () {
                       $(this).removeClass('show');
                       $(this).find('.dropdown-menu').removeClass('show');
                   });
               });
    });










    $(document).ready(function () {
    const productInnerSwipers = document.querySelectorAll(".swiper-product-outer-wrap");

    if (productInnerSwipers.length) {
      const productInnerSwipersArr = [];
      const isMobile = () => {
        return innerWidth < 993;
      };

      Array.from(productInnerSwipers).forEach((swiper) => {
        const swiperID = swiper.id;
        let direction, mobileView, mainProductSwiper;
        const slides = swiper.querySelectorAll(".swiper-slide");

        function initSwiper(direction) {
          const newSwiper = new Swiper(`#${swiperID} .swiper`, {
            spaceBetween: 7,
            slidesPerView: 'auto',
            navigation: {
              nextEl: `#${swiperID} .purple-next`,
              prevEl: `#${swiperID} .purple-prev`,
            },
            direction: direction,
            loop: false,
          });
          productInnerSwipersArr.push(newSwiper);
          return newSwiper;
        }

        function changeDirection() {
          mobileView = !mobileView;
          direction = !mobileView ? "vertical" : "horizontal";
          let slideIndex = mainProductSwiper.activeIndex;
          mainProductSwiper.destroy(true, true);
          mainProductSwiper = initSwiper(direction);
          mainProductSwiper.slideTo(slideIndex, 0);

          // Update the main image Swiper's allowed directions based on the number of images
          mainProductSwiper.allowSlidePrev = slideIndex > 0;
          mainProductSwiper.allowSlideNext = slideIndex < slides.length - 1;
          mainProductSwiper.update(); // Update Swiper after changing allowed directions
        }

        var swiper2 = new Swiper(".swiper_large_preview", {
          spaceBetween: 10,
          slidesPerView: 1,
          speed: 300,
          loop: false,
          navigation: {
            nextEl: ".swiper-button-next",
            prevEl: ".swiper-button-prev",
          },
          thumbs: {
            swiper: mainProductSwiper,
          },
          on: {
            slideChange: function () {
              const activeIndex = this.activeIndex;
              Array.from(slides).forEach((slide, index) => {
                if (index === activeIndex) {
                  slide.classList.add("active-slide");
                } else {
                  slide.classList.remove("active-slide");
                }
              });

              mainProductSwiper.slideTo(activeIndex, 300);
            },
          },
        });

        const swiperNext = swiper.querySelector(".purple-next");
        const swiperPrev = swiper.querySelector(".purple-prev");



        swiperPrev.style.display = "flex";
        swiperNext.style.display = "flex";

        mobileView = isMobile();
        direction = !mobileView ? "vertical" : "horizontal";
        mainProductSwiper = initSwiper(direction);





        Array.from(slides).forEach((slide, index) => {
          slide.addEventListener("click", (e) => {
            const image = e.target.querySelector("img");

            Array.from(slides).forEach((slide) => {
              slide.classList.remove("active-slide");
            });
            slide.classList.add("active-slide");

            swiper2.slideTo(index, 300);
          });
        });

        swiper2.on("init", () => {
          const activeIndex = swiper2.activeIndex;
          mainProductSwiper.slideTo(activeIndex, 0);
        });







        const totalSlides = mainProductSwiper.slides.length;




                 swiperNext.addEventListener('click', () => {
                   swiperNext.classList.remove('swiper-button-disabled');
                   const slides = document.querySelectorAll('.swiper-slide');

                   // Find the slide with the active-slide class
                   let currentImageNumber;
                   for (let i = 0; i < slides.length; i++) {
                     if (slides[i].classList.contains('active-slide')) {
                       currentImageNumber = i + 1; // Adding 1 to start counting from 1
                       break; // Stop the loop when the active slide is found
                     }
                   }

                   if(currentImageNumber == totalSlides){
                     swiperNext.classList.add('swiper-button-disabled');
                   }else{

                     swiperNext.classList.remove('swiper-button-disabled');
                   }


             });


             swiperPrev.addEventListener('click', () => {

               const slidesprev = document.querySelectorAll('.swiper-slide');

               // Find the slide with the active-slide class
               let currentImageNumber;
               for (let i = 0; i < slidesprev.length; i++) {
                 if (slidesprev[i].classList.contains('active-slide')) {
                   currentImageNumber = i + 1; // Adding 1 to start counting from 1
                   break; // Stop the loop when the active slide is found
                 }
               }

               if(currentImageNumber == 1){
                 swiperPrev.classList.add('swiper-button-disabled');
               }else{

                 swiperPrev.classList.remove('swiper-button-disabled');
               }


         });






      });
    }
  });



















const sliced = document.querySelectorAll(".sliced-js");
sliced.length && Array.from(sliced).forEach(p => {
    p.innerHTML = p.innerHTML.split("").slice(0, 37).join("") + "...";
    });



$( document ).ready(function() {
   const reviewsSwipers = document.querySelectorAll(".swiper.review-swiper");
   if(reviewsSwipers.length) {
       const reviewsSwiperArr = [];
       Array.from(reviewsSwipers).forEach(swiper => {
           const swiperID = swiper.id;
          const newSwiper = new Swiper(`#${swiperID}`, {
                  speed: 400,
                  spaceBetween: 100,
                  navigation: {
                      nextEl: `#${swiperID} .swiper-button-next`,
                      prevEl: `#${swiperID} .swiper-button-prev`,
                  },
              });
          reviewsSwiperArr.push(newSwiper);

       })
   }
});
//# sourceMappingURL=app.js.map








function getCartIdentifier() {
  const name = 'cart_identifier=';
  const decodedCookie = decodeURIComponent(document.cookie);
  const cookieArray = decodedCookie.split(';');
  for (let i = 0; i < cookieArray.length; i++) {
    let cookie = cookieArray[i].trim();
    if (cookie.indexOf(name) === 0) {
      return cookie.substring(name.length, cookie.length);
    }
  }
  return '';
}


function updatesumcart() {

  const cartIdentifierxc = getCartIdentifier();

  const postDatasumup = {
    cartIdentifierxc: cartIdentifierxc
  };

  $.ajax({
    type: 'POST',
    url: '/service-page/cartsumupdate.php',
    data: postDatasumup,
    success: function(responsesumcart) {
      $('#cartinsum').html(responsesumcart);
    }
  });

}


function updateCartsimplecount() {
  const cartIdentifier = getCartIdentifier();

  // Add a random query parameter to the URL to force a cache refresh
  const url = '/service-page/cartsimplecount.php?cache=' + Date.now();

  $.ajax({
    type: 'post',
    url: url,
    data: 'cartIdentifier=' + cartIdentifier,
    success: function (response) {
      const data = JSON.parse(response);

      // Update the price element
      $('#crtvvima').html(data.price + ' €');

      // Update the quantity element (assuming you have an element with id "quantityElement" to display it)
      $('#qqimat').html(data.quantity);

      // You can access the price and quantity as data.price and data.quantity in your JavaScript
    },
    error: function (e) {
      alert('Error: ' + e);
    }
  });
}








function updateCart() {
  const cartIdentifier = getCartIdentifier();

  $.ajax({
    type: 'post',
    url: '/service-page/get_cart.php',
    data: 'cartIdentifier=' + cartIdentifier,
    success: function (resp) {
      $('#cartin').html(resp);
      updatesumcart();
      lddcart();
    },
    error: function (e) {
      alert('Error: ' + e);
    }
  });
}
updateCart();


window.addEventListener( "pageshow", function ( event ) {
  var historyTraversal = event.persisted ||
                         ( typeof window.performance != "undefined" &&
                              window.performance.navigation.type === 2 );
  if ( historyTraversal ) {
    // Handle page restore.
    updateCartsimplecount();
    updateCart();
    updatesumcart();

  }
});



function lddcart() {




  // Get the cart identifier
  const cartIdentifier = getCartIdentifier();

  // Get all the custom increment, decrement, and remove buttons, and cart amounts
  const incrementButtons = document.querySelectorAll('.inc-btt');
  const decrementButtons = document.querySelectorAll('.dcr-btt');
  const removeButtons = document.querySelectorAll('.rmw-btt');
  const cartAmounts = document.querySelectorAll('.amm-btt');

  // Add click event listeners to the custom increment buttons
  incrementButtons.forEach((button, index) => {
    button.addEventListener('click', () => {
      // Get the current cart amount value
      const currentAmount = parseInt(cartAmounts[index].textContent);

      // Calculate the new cart amount after clicking the "+" button
      const newAmount = currentAmount + 1;

      // Log the updated cart amount, but ensure it's not less than 1
      if (newAmount >= 1) {


        // Send an AJAX POST request to update the cart
        sendAjaxRequest('update', cartAmounts[index].getAttribute('data-amm'), newAmount);
      }
    });
  });

  // Add click event listeners to the custom decrement buttons
  decrementButtons.forEach((button, index) => {
    button.addEventListener('click', () => {
      // Get the current cart amount value
      const currentAmount = parseInt(cartAmounts[index].textContent);

      // Calculate the new cart amount after clicking the "-" button
      const newAmount = currentAmount - 1;

      // Log the updated cart amount, but ensure it's not less than 1
      if (newAmount >= 1) {


        // Send an AJAX POST request to update the cart
        sendAjaxRequest('update', cartAmounts[index].getAttribute('data-amm'), newAmount);
      }
    });
  });

  // Add click event listeners to the custom remove buttons
  removeButtons.forEach((button, index) => {
    button.addEventListener('click', () => {
      // Get the product code from the associated cart amount element's data-amm attribute
      const productCode = cartAmounts[index].getAttribute('data-amm');

      // Send an AJAX POST request to remove the product from the cart
      sendAjaxRequest('remove', productCode);
    });
  });

  // Function to send an AJAX request
  function sendAjaxRequest(action, productCode, newAmount = null) {
    const url = '/service-page/cart_update.php';

    // Create a data object with the cart identifier, action, product code, and new amount (if applicable)
    const data = {
      cartIdentifier: cartIdentifier,
      action: action,
      productCode: productCode
    };

    // Add the new amount to the data object if provided
    if (newAmount !== null) {
      data.newAmount = newAmount;
    }

    $.ajax({
      type: 'POST',
      url: url,
      data: data,
      success: function (response) {
        var akcemlchkpapil = document.getElementById("kdtttsngatga");
        if (akcemlchkpapil) {

  // Remove attributes
  akcemlchkpapil.removeAttribute("data-vvtlcpnk");
  akcemlchkpapil.removeAttribute("data-tppckpdv");

  // Change class from alert-success to alert-danger
  akcemlchkpapil.classList.remove("alert-success");
  akcemlchkpapil.classList.add("alert-danger");
akcemlchkpapil.textContent = "Pakeistas prekių likutis, įveskite kodą iš naujo";
var inputElementxxertw = document.getElementById("txcodennbs");

// Clear the input field by setting its value to an empty string
inputElementxxertw.value = "";
  // Remove the element from the DOM
  akcemlchkpapil.removeAttribute("id");
  akcemlchkpapil.id = "hrrkcdrchkfrdl";
}
        updateCart();
        updateCartchk();
        updateCartsimplecount();
      }
    });
}


}

$('.add-to-cart').click(function() {
  var twoToneButton = document.querySelector('.add-to-cart');
    twoToneButton.setAttribute("disabled", '');
  twoToneButton.setAttribute("data-canvas", "true");
  twoToneButton.setAttribute("data-canvas-options", '{"container":".cart-canvas"}');

        twoToneButton.innerHTML = '<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span>',
'<span class="sr-only">Loading...</span>';

  const model = $(this).data('model');
  const price = $(this).data('price');


  // Get the value from the element with ID "dataquantity"
  const quantity = parseInt($('#dataquantity').text().trim());

  const cartIdentifier = getCartIdentifier();


  // Create an object to hold the data to send
  const postData = {
    model: model,
    quantity: quantity,
    price: price,
    cartIdentifier: cartIdentifier
  };

  $.ajax({
      type: 'POST',
      url: '/service-page/add_to_cart.php',
      data: postData,
      success: function (response) {

          if (response.success) {
              updateCart();
              updateCartsimplecount();
              document.body.style.overflow = 'hidden';
              const sidebarCart = document.querySelector('.sidebar-cart');
              sidebarCart.classList.remove("hidden");
              document.querySelector("body").classList.add('filter');
              twoToneButton.innerHTML = 'Pirkti dabar';
              twoToneButton.removeAttribute('disabled');
          } else {
            twoToneButton.innerHTML = 'Pirkti dabar';
            twoToneButton.removeAttribute('disabled');
              startAnimationsncrt();
          }
      },
      error: function (xhr, status, error) {

      }
  });

});

function startAnimationsncrt() {
  var animateBlock = document.querySelector(".animate-moving");
  var dataquantity = document.getElementById("dataquantity");

  // Add class to start the moving animation for animate-block
  animateBlock.classList.add("animate-moving-start");

  // Add class to start the glow animation for dataquantity
  dataquantity.classList.add("animate-glow-start");

  // After 2 seconds (2000 milliseconds), remove the classes to stop the animations
  setTimeout(function () {
    animateBlock.classList.remove("animate-moving-start");
    dataquantity.classList.remove("animate-glow-start");
  }, 1000); // Adjust the time as needed (1 second in this example)
}

function shippingupdt() {
  // Store the selected radio button's data-slshpp attribute value
  var ele = document.getElementsByName('shpddvalh');
  var selectedDataSlshppValue;

  for (i = 0; i < ele.length; i++) {
    if (ele[i].checked) {
      selectedDataSlshppValue = ele[i].getAttribute("data-slshpp");
      break; // Stop looping once a checked radio button is found
    }
  }

  const cartIdentifierxcship = getCartIdentifier();

  const postDatasumupship = {
    cartIdentifier: cartIdentifierxcship
  };

  $.ajax({
    type: 'POST',
    url: '/service-page/shippingupdate.php',
    data: postDatasumupship,
    success: function (respnship) {
      // Update the HTML content
      $('#curierfld').html(respnship);
      $('#curierfldmbl').html(respnship);

      // Restore the selected radio button based on the data-slshpp attribute value
      if (selectedDataSlshppValue) {
        ele = document.getElementsByName('shpddvalh');
        for (i = 0; i < ele.length; i++) {
          if (ele[i].getAttribute("data-slshpp") === selectedDataSlshppValue) {
            ele[i].checked = true;
            break;
          }
        }
      }
      updatetotalsumcheck();
    }
  });
}




function paymntpadiphsc() {

  $.ajax({
      type: 'POST',
      url: '/service-page/paymentopr.php',
      success: function (respbizppresp) {
          $('#ppmatvbbtnreik').html(respbizppresp);

      }
  });

}


function shipsllinterr() {



    var ele = document.getElementsByName('shpddvalh');

    for (i = 0; i < ele.length; i++) {
        if (ele[i].checked) {
            // Get the data-slshpp attribute value
            var dataSlshppValue = ele[i].getAttribute("data-slshpp");

            var elemcunkppmyt = document.getElementsByName('payment');
              for (var i = 0; i < elemcunkppmyt.length; i++) {
                elemcunkppmyt[i].checked = false;




               break;
              }

            const postDatasumupshipshipingua = {
              shipidentiff: dataSlshppValue
            };

            $.ajax({
              type: 'POST',
              url: '/service-page/fieldsupdatecheckout.php',
              data: postDatasumupshipshipingua,
              success: function(resshipident) {
                $('#spatvdmna').html(resshipident);

                cckfrcod();
                updatetotalsumcheck();
              }
            });

            break; // Stop looping once a checked radio button is found
        }
    }
}

function indivtypslldetes() {
    var ele = document.getElementsByName('individualtype');

    for (i = 0; i < ele.length; i++) {
        if (ele[i].checked) {
            // Get the data-slshpp attribute value
            var datafiucpasir = ele[i].getAttribute("data-indvintyp");

            const postDapasirnfizbis = {
              valpafizbbs: datafiucpasir
            };

            $.ajax({
              type: 'POST',
              url: '/service-page/fizorbusselect.php',
              data: postDapasirnfizbis,
              success: function(respbizffizsel) {
                $('#fizbissslte').html(respbizffizsel);
              }
            });

            break; // Stop looping once a checked radio button is found
        }
    }
}


function cckfrcod() {

  $.ajax({
      type: 'POST',
      url: '/service-page/paymentopr.php',
      success: function (respbizppresp) {
          $('#ppmatvbbtnreik').html(respbizppresp);
          atnkaipabaship();
      }
  });

   function atnkaipabaship() {

  const selectElement = document.getElementById('sspcdperdmm');
const unnchkonfrqurs = document.getElementById('unccridfrcood');
if (unnchkonfrqurs) {
  dataVvcodxx = unnchkonfrqurs.getAttribute('data-vvcod');
}



    var ele = document.getElementsByName('shpddvalh');

    for (i = 0; i < ele.length; i++) {
        if (ele[i].checked) {
            // Get the data-slshpp attribute value
            var dataSlshppValue = ele[i].getAttribute("data-slshpp");


if (selectElement) {
        selectElement.addEventListener('change', function () {
            const selectedOption = selectElement.options[selectElement.selectedIndex];
            dataVvcod = selectedOption.getAttribute('data-vvcod');

            const postDapappccda = {
              valpakurarpas: dataVvcod,
              padvkridisk: dataSlshppValue,
            };
            cckfrcodxxer(postDapappccda);


        });
      }

if (unnchkonfrqurs) {
  var dataVvcod = dataVvcodxx;
  const postDapappccda = {
    valpakurarpas: dataVvcod,
    padvkridisk: dataSlshppValue,
  };
  cckfrcodxxer(postDapappccda);


}

      break;
  }
}

function cckfrcodxxer(postppmtccda) {
  $.ajax({
      type: 'POST',
      url: '/service-page/paymentopr.php',
      data: postppmtccda,
      success: function (respbizppresptt) {
          $('#ppmatvbbtnreik').html(respbizppresptt);
          updatetotalsumcheck();
      }
  });
}
}
}

function updateCartchk() {
  const cartIdentifier = getCartIdentifier();

  $.ajax({
    type: 'post',
    url: '/service-page/get_cartchk.php',
    data: 'cartIdentifier=' + cartIdentifier,
    success: function (respttsa) {

      if (respttsa == "noproduct") {
          window.location.href = '/emptycart';
      } else {
        $('#cartinchkmbl').html(respttsa);
        $('#cartinchk').html(respttsa);
        updatesumcart();
        lddcart();
        shippingupdt();
      }




    },
    error: function (e) {
      alert('Error: ' + e);
    }
  });
}



function nncodepad() {
  const discascente = document.getElementById("txcodennbs");
  const applkaipanme = document.getElementById("subtxdnns");

  // Variable to store the last submitted discount code
  let lastSubmittedCode = null;

  // Add a click event listener to the button
  applkaipanme.addEventListener("click", function() {
    // Get the value of the input field when the button is clicked
    const clsgtknispadtl = document.getElementById("padttismmtaa");
    dgtipdvcn = clsgtknispadtl.getAttribute('data-pcrthxcontro');

    const discogalutbe = discascente.value;

   const clmohskaweiq = document.getElementById("hrrkcdrchkfrdl");

    if (clmohskaweiq) {

    } else {

    // Check if the discount code is the same as the last submitted code
    if (discogalutbe === lastSubmittedCode) {
      // Discount code has already been submitted

      return;
    }

  }

    const postschknlcs = {
      ttlpdicontla: dgtipdvcn,
      nncdspadmekit: discogalutbe
    };

    $.ajax({
      type: 'post',
      url: '/service-page/discountccd.php',
      data: postschknlcs,
      success: function (respttsanuolk) {
        $('#atvkodjerrr').html(respttsanuolk);
        updatetotalsumcheck();

        // Update the last submitted discount code
        lastSubmittedCode = discogalutbe;
      },
      error: function (e) {
        alert('Error: ' + e);
      }
    });
  });
}





function updatetotalsumcheck() {

  var gtelminakc = document.getElementById("kdtttsngatga");

  if (gtelminakc) {

    var sumkkiakcc = gtelminakc.getAttribute("data-vvtlcpnk");
    var kkstpsbusakc = gtelminakc.getAttribute("data-tppckpdv");

  }

  var elettse = document.getElementsByName('shpddvalh');

if (elettse) {
  for (i = 0; i < elettse.length; i++) {
      if (elettse[i].checked) {
          // Get the data-slshpp attribute value
          var dashpprice = elettse[i].getAttribute("data-shipppcr");


        }
      }
    }


    var elemccdpaslglhf = document.getElementsByName('payment');
    var padimaskncd = null; // Initialize padimaskncd as null

    if (elemccdpaslglhf) {
      for (i = 0; i < elemccdpaslglhf.length; i++) {
        if (elemccdpaslglhf[i].checked && elemccdpaslglhf[i].getAttribute("data-cdknpdikn") !== null) {
          padimaskncd = elemccdpaslglhf[i].getAttribute("data-cdknpdikn");

          break; // Exit the loop once a valid value is found
        }
      }
    }


  const cartIdentifierxcch = getCartIdentifier();

  const postDatasumupch = {
    cartIdentifierxc: cartIdentifierxcch,
    shpprcpad: dashpprice,
    kncdprirantn: padimaskncd,
    smmtipsiup: sumkkiakcc,
    kkstipbbs: kkstpsbusakc
  };

  $.ajax({
    type: 'POST',
    url: '/service-page/totalsumcheckout.php',
    data: postDatasumupch,
    success: function(responsesumcartch) {
      $('#chtotalsmcnt').html(responsesumcartch);
      var tmspcrrtkixx = document.getElementById("padttismmtaa");
       var trsmbdkksmyl = document.getElementById("mblsmmtttlgaunne");


       if (tmspcrrtkixx && trsmbdkksmyl) {

           var textToCopy = tmspcrrtkixx.textContent;

           trsmbdkksmyl.textContent = textToCopy;
       } else {

       }
    }
  });

}



function validateRadio() {
  var elettse = document.getElementsByName('shpddvalh');
  var isChecked = false; // Initialize a variable to track if any radio button is checked
  var firstUncheckedRadioButton = null; // Initialize a variable to track the first unchecked radio button

  if (elettse) {
    for (i = 0; i < elettse.length; i++) {
      if (elettse[i].checked) {
        isChecked = true; // Set isChecked to true if any radio button is checked
      } else {
        // This radio button is not checked
        if (!firstUncheckedRadioButton) {
          firstUncheckedRadioButton = elettse[i]; // Store the first unchecked radio button
        }
      }
    }
  }

  if (!isChecked && firstUncheckedRadioButton) {
    // No radio buttons are checked, and there's at least one unchecked radio button
    // Scroll to a position just above the first unchecked radio button
    var scrollPosition = firstUncheckedRadioButton.offsetTop - 20; // Adjust 20 pixels as needed
    window.scrollTo({
      top: scrollPosition,
      behavior: 'smooth'
    });

    // Add a red border to the element with id "rddgaunship" and make it blink 5 times
    var deliveryCollapseElement = document.getElementById('rddgaunship');
    if (deliveryCollapseElement) {
      var originalBorderStyle = deliveryCollapseElement.style.border;
      var blinkCount = 0;

      var blinkFunction = function() {
        if (blinkCount < 5) {
          deliveryCollapseElement.style.border = '1px solid red';
          setTimeout(function() {
            deliveryCollapseElement.style.border = originalBorderStyle;
            setTimeout(function() {
              blinkCount++;
              blinkFunction(); // Call the function recursively for the next blink
            }, 250); // Wait for 500 milliseconds before the next blink
          }, 250); // Keep the red border for 500 milliseconds
        }
      };

      blinkFunction();
    }
  } else {

    validateInputs();
  }
}

function applyBlinkingEffect(element) {
  var originalBorderStyle = element.style.border;
  var blinkCount = 0;

  var blinkFunction = function() {
    if (blinkCount < 5) {
      element.style.border = '1px solid red';
      setTimeout(function() {
        element.style.border = originalBorderStyle;
        setTimeout(function() {
          blinkCount++;
          blinkFunction();
        }, 250);
      }, 250);
    }
  };

  blinkFunction();
}


function validateInputs() {
  var inputIds = ['firstname', 'lastname', 'desktop-email', 'telephone'];
  var isEmpty = false; // Flag to track if any input is empty

  ['immpavas', 'immkodas', 'vvcity', 'vvaddress', 'vvpostcode', 'sspcdperdmm'].forEach(function(id) {
    var inputElement = document.getElementById(id);
    if (inputElement) {
      inputIds.push(id);
    }
  });

  for (var i = 0; i < inputIds.length; i++) {
    var inputId = inputIds[i];
    var inputElement = document.getElementById(inputId);

    if (inputElement && inputElement.value.trim() === '') {
      isEmpty = true; // Set the flag to true if any input is empty

      var inputPosition = inputElement.getBoundingClientRect();
      var scrollPosition = window.scrollY + inputPosition.top - 200;
      window.scrollTo({
        top: scrollPosition,
        behavior: 'smooth'
      });

      // Apply the blinking effect to the input field
      applyBlinkingEffect(inputElement);
    }
  }

  // Check if any input is empty and display a message accordingly
  if (isEmpty) {

  } else {
    validateRadioppmt();
  }
}


function validateRadioppmt() {
  var elemccdpaslglhf = document.getElementsByName('payment');
  var isChecked = false; // Initialize a variable to track if any radio button is checked
  var firstUncheckedRadioButton = null; // Initialize a variable to track the first unchecked radio button

  if (elemccdpaslglhf) {
    for (i = 0; i < elemccdpaslglhf.length; i++) {
      if (elemccdpaslglhf[i].checked) {
        isChecked = true; // Set isChecked to true if any radio button is checked
      } else {
        // This radio button is not checked
        if (!firstUncheckedRadioButton) {
          firstUncheckedRadioButton = elemccdpaslglhf[i]; // Store the first unchecked radio button
        }
      }
    }
  }

  if (!isChecked && firstUncheckedRadioButton) {
    // No radio buttons are checked, and there's at least one unchecked radio button
    // Scroll to a position just above the first unchecked radio button
    var radioGroupPosition = firstUncheckedRadioButton.getBoundingClientRect();
    var scrollPosition = window.scrollY + radioGroupPosition.top - 200; // Adjust 150 pixels as needed
    window.scrollTo({
      top: scrollPosition,
      behavior: 'smooth'
    });

    // Add a red border to the element with id "ckhbspaymentarhr" and make it blink 5 times
    var deliveryCollapseElement = document.getElementById('ckhbspaymentarhr');
    if (deliveryCollapseElement) {
      var originalBorderStyle = deliveryCollapseElement.style.border;
      var blinkCount = 0;

      var blinkFunction = function() {
        if (blinkCount < 5) {
          deliveryCollapseElement.style.border = '1px solid red';
          setTimeout(function() {
            deliveryCollapseElement.style.border = originalBorderStyle;
            setTimeout(function() {
              blinkCount++;
              blinkFunction(); // Call the function recursively for the next blink
            }, 250); // Wait for 250 milliseconds before the next blink
          }, 250); // Keep the red border for 250 milliseconds
        }
      };

      blinkFunction();
    }
  } else {

   rulerchkkkr();
  }
}



function rulerchkkkr() {
  var checkboxId = 'terms-form-test';
  var checkboxElement = document.getElementById(checkboxId);

  if (checkboxElement && !checkboxElement.checked) {
    // The checkbox is not checked
    // Apply the blinking effect to the checkmark
    var checkmarkElement = document.querySelector('label[for="' + checkboxId + '"] .checkmark');
    if (checkmarkElement) {
      applyBlinkingEffect(checkmarkElement);
    }

    // Scroll to the checkbox label
    var labelElement = document.querySelector('label[for="' + checkboxId + '"]');
    if (labelElement) {
      var labelPosition = labelElement.getBoundingClientRect();
      var scrollPosition = window.scrollY + labelPosition.top - 200; // Adjust as needed
      window.scrollTo({
        top: scrollPosition,
        behavior: 'smooth'
      });
    }
  } else {
pttorderpatefn();
  }
}







function pttorderpatefn() {
  var elettse = document.getElementsByName('shpddvalh');
  var shppstid = null; // Initialize the variable to store the selected shipping value

  if (elettse) {
    for (var i = 0; i < elettse.length; i++) {
      if (elettse[i].checked) {
        shppstid = elettse[i].getAttribute("data-slshpp");
        break; // Exit the loop once a checked radio button is found
      }
    }
  }


  var ele = document.getElementsByName('individualtype');
  var datafiucpasir = null; // Initialize the variable to store the selected type value

  for (var i = 0; i < ele.length; i++) {
    if (ele[i].checked) {
      datafiucpasir = ele[i].getAttribute("data-indvintyp");
      break; // Exit the loop once a checked radio button is found
    }
  }

  // Check if a type (individual or business) was selected
  if (datafiucpasir === null) {
    alert("Please select an individual or business type before proceeding.");
    return; // Exit the function if no type is selected
  }

  // Retrieve values from inputs with IDs "vvcity," "vvaddress," and "vvpostcode" if they exist
  var vvcityInput = document.getElementById("vvcity");
  var vvaddressInput = document.getElementById("vvaddress");
  var vvpostcodeInput = document.getElementById("vvpostcode");

  // Initialize variables to store the values
  var vvcityValue = '';
  var vvaddressValue = '';
  var vvpostcodeValue = '';

  // Check if all required inputs exist
  if (vvcityInput && vvaddressInput && vvpostcodeInput) {
    // Retrieve their values
    vvcityValue = vvcityInput.value;
    vvaddressValue = vvaddressInput.value;
    vvpostcodeValue = vvpostcodeInput.value;
  }

  // Retrieve values from inputs with IDs "firstname," "lastname," "desktop-email," and "telephone"
  var firstnameValue = document.getElementById("firstname").value;
  var lastnameValue = document.getElementById("lastname").value;
  var desktopEmailValue = document.getElementById("desktop-email").value;
  var telephoneValue = document.getElementById("telephone").value;

  // Retrieve the payment value
  var elemccdpaslglhf = document.getElementsByName('payment');
  var psttpaymentpp = null; // Initialize psttpaymentpp as null

  if (elemccdpaslglhf) {
    for (var i = 0; i < elemccdpaslglhf.length; i++) {
      if (elemccdpaslglhf[i].checked && elemccdpaslglhf[i].getAttribute("data-paymentbc") !== null) {
        psttpaymentpp = elemccdpaslglhf[i].getAttribute("data-paymentbc");
        break; // Exit the loop once a valid value is found
      }
    }
  }

  // Retrieve attributes from the div with ID "kdtttsngatga"
  var dataPttcodeins = '';
  var dataTppckpdv = '';
  var kdtttsngatgaDiv = document.getElementById("kdtttsngatga");

  if (kdtttsngatgaDiv) {
    dataPttcodeins = kdtttsngatgaDiv.getAttribute("data-pttcodeins");
    dataTppckpdv = kdtttsngatgaDiv.getAttribute("data-tppckpdv");
  }

  // Retrieve values from inputs with IDs "immpavas," "immkodas," and "immpvmkodas" if they exist
  var immpavasInput = document.getElementById("immpavas");
  var immkodasInput = document.getElementById("immkodas");
  var immpvmkodasInput = document.getElementById("immpvmkodas");

  // Initialize variables to store their values
  var immpavasValue = '';
  var immkodasValue = '';
  var immpvmkodasValue = '';

  // Check if all optional inputs exist
  if (immpavasInput && immkodasInput && immpvmkodasInput) {
    // Retrieve their values
    immpavasValue = immpavasInput.value;
    immkodasValue = immkodasInput.value;
    immpvmkodasValue = immpvmkodasInput.value;
  }

  // Retrieve values from inputs with IDs "pdichtarpn," "pdichpvmsm," "pdichsmlkkrepmok," "pdichprismoks," "pdichatsisprmokes," "pdichprtknldbba," and "pdichprtdvnkpsma" if they exist
  var pdichtarpnInput = document.getElementById("pdichtarpn");
  var pdichpvmsmInput = document.getElementById("pdichpvmsm");
  var pdichsmlkkrepmokInput = document.getElementById("pdichsmlkkrepmok");
  var pdichprismoksInput = document.getElementById("pdichprismoks");
  var pdichatsisprmokesInput = document.getElementById("pdichatsisprmokes");
  var pdichprtknldbbaInput = document.getElementById("pdichprtknldbba");
  var pdichprtdvnkpsmaInput = document.getElementById("pdichprtdvnkpsma");

  // Initialize variables to store their values
  var pdichtarpnValue = '';
  var pdichpvmsmValue = '';
  var pdichsmlkkrepmokValue = '';
  var pdichprismoksValue = '';
  var pdichatsisprmokesValue = '';
  var pdichprtknldbbaValue = '';
  var pdichprtdvnkpsmaValue = '';

  // Check if all optional inputs exist
  if (pdichtarpnInput) {
    pdichtarpnValue = pdichtarpnInput.getAttribute("data-pdichtarpn");
  }
  if (pdichpvmsmInput) {
    pdichpvmsmValue = pdichpvmsmInput.getAttribute("data-pdichpvmsm");
  }
  if (pdichsmlkkrepmokInput) {
    pdichsmlkkrepmokValue = pdichsmlkkrepmokInput.getAttribute("data-pdichsmlkkrepmok");
  }
  if (pdichprismoksInput) {
    pdichprismoksValue = pdichprismoksInput.getAttribute("data-pdichprismoks");
  }
  if (pdichatsisprmokesInput) {
    pdichatsisprmokesValue = pdichatsisprmokesInput.getAttribute("data-pdichatsisprmokes");
  }
  if (pdichprtknldbbaInput) {
    pdichprtknldbbaValue = pdichprtknldbbaInput.getAttribute("data-pdichprtknldbba");
  }
  if (pdichprtdvnkpsmaInput) {
    pdichprtdvnkpsmaValue = pdichprtdvnkpsmaInput.getAttribute("data-pdichprtdvnkpsma");
  }

  // Retrieve the data-pcrthxcontro attribute from an element with ID "padttismmtaa"
  var padttismmtaaElement = document.getElementById("padttismmtaa");
  var dataPcrthxcontro = null; // Initialize dataPcrthxcontro as null

  if (padttismmtaaElement) {
    dataPcrthxcontro = padttismmtaaElement.getAttribute("data-pcrthxcontro");
  }

  cartIdentifierxcchpadichk = getCartIdentifier();

  var sslportpadas = '';
  var pastmmtpasrirk = document.getElementById("sspcdperdmm");
  if (pastmmtpasrirk) {
    sslportpadas = pastmmtpasrirk.value;
  }

  var twoToneButtonx = document.querySelector('.chkbtttnipl');
    twoToneButtonx.setAttribute("disabled", '');
  twoToneButtonx.setAttribute("data-canvas", "true");
  twoToneButtonx.setAttribute("data-canvas-options", '{"container":".cart-canvas"}');

        twoToneButtonx.innerHTML = '<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span>',
'<span class="sr-only">Loading...</span>';

  // Now you can use all these values in your AJAX request
  // Example AJAX request (you can customize this as needed):
  var xhr = new XMLHttpRequest();
  var url = '/service-page/sendpttord.php'; // Replace with the actual path to your PHP script
  xhr.open('POST', url, true);
  xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
  xhr.onreadystatechange = function () {
      if (xhr.readyState === 4) {
          if (xhr.status === 200) {
              // Handle the AJAX response here
              var response = JSON.parse(xhr.responseText);

              if (response.redirect_url) {
                  // If a redirect URL is present, perform the redirect
                  window.location.href = response.redirect_url;
              } else {
                  // Handle other aspects of the response as needed

              }
          } else {
              // Handle errors if the AJAX request fails
              console.error('Error:', xhr.status);
          }
      }
  };

  // Define the data to send in the AJAX request
  var data = 'shppstid=' + encodeURIComponent(shppstid) + '&datafiucpasir=' + encodeURIComponent(datafiucpasir) +
             '&firstname=' + encodeURIComponent(firstnameValue) + '&lastname=' + encodeURIComponent(lastnameValue) +
             '&desktop-email=' + encodeURIComponent(desktopEmailValue) + '&telephone=' + encodeURIComponent(telephoneValue) +
             '&vvcity=' + encodeURIComponent(vvcityValue) +
             '&vvaddress=' + encodeURIComponent(vvaddressValue) +
             '&vvpostcode=' + encodeURIComponent(vvpostcodeValue) +
             '&psttpaymentpp=' + encodeURIComponent(psttpaymentpp) +
             '&data-pttcodeins=' + encodeURIComponent(dataPttcodeins) + // Add the data-pttcodeins attribute
             '&data-tppckpdv=' + encodeURIComponent(dataTppckpdv) + // Add the data-tppckpdv attribute
             '&immpavas=' + encodeURIComponent(immpavasValue) + // Add the immpavas value
             '&immkodas=' + encodeURIComponent(immkodasValue) + // Add the immkodas value
             '&immpvmkodas=' + encodeURIComponent(immpvmkodasValue) + // Add the immpvmkodas value
             '&pdichtarpn=' + encodeURIComponent(pdichtarpnValue) + // Add the pdichtarpn value
             '&pdichpvmsm=' + encodeURIComponent(pdichpvmsmValue) + // Add the pdichpvmsm value
             '&pdichsmlkkrepmok=' + encodeURIComponent(pdichsmlkkrepmokValue) + // Add the pdichsmlkkrepmok value
             '&pdichprismoks=' + encodeURIComponent(pdichprismoksValue) + // Add the pdichprismoks value
             '&pdichatsisprmokes=' + encodeURIComponent(pdichatsisprmokesValue) + // Add the pdichatsisprmokes value
             '&pdichprtknldbba=' + encodeURIComponent(pdichprtknldbbaValue) + // Add the pdichprtknldbba value
             '&pdichprtdvnkpsma=' + encodeURIComponent(pdichprtdvnkpsmaValue) + // Add the pdichprtdvnkpsma value
             '&data-pcrthxcontro=' + encodeURIComponent(dataPcrthxcontro) + // Add the data-pcrthxcontro attribute
             '&pasrinpstmtkksr=' + encodeURIComponent(sslportpadas) + // Add the data-pcrthxcontro attribute
             '&idnfchkkrepid=' + encodeURIComponent(cartIdentifierxcchpadichk); // Add the data-pcrthxcontro attribute

  // Send the AJAX request
  xhr.send(data);
}


function handleFileUpload() {
    const fileInput = document.getElementById('photo-upload');
    const uploadedImagesContainer = document.getElementById('uploaded-images-container');
    const errorContainer = document.getElementById('errtttdipsl'); // Update this line

    const files = fileInput.files;

    // Create a FormData object to send the files via AJAX
    const formData = new FormData();

    for (let i = 0; i < files.length; i++) {
        formData.append('images[]', files[i]);
    }

    // Send an AJAX request to /service-page/garansccrrtat.php
    const xhr = new XMLHttpRequest();
    xhr.open('POST', '/service-page/garansccrrtat.php', true);

    xhr.onload = function() {
        if (xhr.status === 200) {
            // The request was successful
            const response = JSON.parse(xhr.responseText);

            if (response.success) {
                // Images were uploaded successfully
                for (let i = 0; i < response.uploadedImages.length; i++) {
                    const imageWrap = document.createElement('div');
                    imageWrap.className = 'upload-img-wrap';

                    const deleteButton = document.createElement('button');
                    deleteButton.className = 'delete-img';
                    // Set the button content to an icon (e.g., using FontAwesome)
                    deleteButton.innerHTML = '<i class="fas fa-trash-alt"></i>';

                    // Add an event listener to delete the image container
                    deleteButton.addEventListener('click', function() {
                        uploadedImagesContainer.removeChild(imageWrap);
                    });

                    const image = document.createElement('img');
                    image.src = response.uploadedImages[i];
                    // You can also set alt text for the image here

                    imageWrap.appendChild(deleteButton);
                    imageWrap.appendChild(image);

                    uploadedImagesContainer.appendChild(imageWrap);
                }

                // Clear the file input to allow re-uploading the same files
                fileInput.value = '';

                // Clear any previous error messages
                errorContainer.innerHTML = '';
            } else {
                // Handle errors here
                const errorMessages = response.errors.join('<br>');
                errorContainer.innerHTML = errorMessages;
            }
        }
    };

    xhr.send(formData);
}

function smmtfncisrv() {
  const checkbox = document.getElementById('terms-form-test');
      const isCheckboxChecked = checkbox.checked;

      // Get the container where you want to display error messages
      const errorDisplay = document.getElementById('errtttdipsl');
      errorDisplay.innerHTML = ''; // Clear previous error messages

      // If the checkbox is not checked, display an error message
      if (!isCheckboxChecked) {
          const errorMessage = '<span class="error">Jūs nesutikote su garantinio aptarnavimo ir prekių grąžinimo sąlygomis!</span>';
          errorDisplay.innerHTML = errorMessage;
          return false; // Prevent form submission
      }
    // Collect data
    const orderNumber = document.getElementById('order-number').value;
    const description = document.getElementById('description').value;
    let name = document.getElementById('name').value;
    let surname = document.getElementById('surname').value;
    let phoneNumber = document.getElementById('phone-number').value;

    if (!name) {
 name = document.getElementById('name1').value;
    }
    if (!surname) {
 surname = document.getElementById('surname1').value;
    }
    if (!phoneNumber) {
 phoneNumber = document.getElementById('phone-number1').value;
    }

    const ctrpadiktniikf = document.querySelector('.return-card.active');

    // Check if the element exists and has a "data-atpasiritipp" attribute
    if (ctrpadiktniikf) {
       dataAtpasiritipp = ctrpadiktniikf.getAttribute('data-atpasiritipp');
    }

    const orderEmail = document.getElementById('order-email').value; // New input field
    const uploadedImages = [];

    // Collect uploaded image file names
    const uploadedImagesElements = document.querySelectorAll('.upload-img-wrap img');
    uploadedImagesElements.forEach((imageElement) => {
        uploadedImages.push(imageElement.getAttribute('src'));
    });

    // Create data to send via AJAX
    const formData = new FormData();
    formData.append('orderNumber', orderNumber);
    formData.append('description', description);
    formData.append('name', name);
    formData.append('surname', surname);
    formData.append('phoneNumber', phoneNumber);
    formData.append('orderEmail', orderEmail);
    formData.append('dataAtpasiritipp', dataAtpasiritipp); // Add to form data

    // Append uploaded image file names
    for (let i = 0; i < uploadedImages.length; i++) {
        formData.append('uploadedImages[]', uploadedImages[i]);
    }

    // Send an AJAX request to garantsubmmt.php
    const xhr = new XMLHttpRequest();
    xhr.open('POST', '/service-page/garantsubmmt.php', true);

    xhr.onload = function() {
        if (xhr.status === 200) {
            // Handle the response from garantsubmmt.php (e.g., display a success message)
            const response = JSON.parse(xhr.responseText);
            if (response.success) {
              var applyHere = document.getElementById("apply-here");
  applyHere.innerHTML = ""; // Remove existing HTML content

  // Create a new h3 element
  var newH3 = document.createElement("h3");
  newH3.className = "subsection-title w-100 mb-5";
  newH3.textContent = "Puiku! Forma pateikta artimiausiu metu su jumis susisieksime.";
  newH3.style.color = "coral"; // Add the color style

  // Append the new h3 element to the div
  applyHere.appendChild(newH3);

            } else {
                // Handle the error response
                const errorMessages = response.errors;
                let errorMessage = 'Klaida pateikiant formą!';
                const errorDisplay = document.getElementById('errtttdipsl');
                errorDisplay.innerHTML = ''; // Clear previous error messages

                if (errorMessages.hasOwnProperty('orderNumber')) {
                    errorMessage += '<br><span class="error">' + errorMessages.orderNumber + '</span>';
                }

                if (errorMessages.hasOwnProperty('description')) {
                    errorMessage += '<br><span class="error">' + errorMessages.description + '</span>';
                }

                if (errorMessages.hasOwnProperty('name')) {
                    errorMessage += '<br><span class="error">' + errorMessages.name + '</span>';
                }

                if (errorMessages.hasOwnProperty('surname')) {
                    errorMessage += '<br><span class="error">' + errorMessages.surname + '</span>';
                }

                if (errorMessages.hasOwnProperty('phoneNumber')) {
                    errorMessage += '<br><span class="error">' + errorMessages.phoneNumber + '</span>';
                }

                if (errorMessages.hasOwnProperty('orderEmail')) {
                    errorMessage += '<br><span class="error">' + errorMessages.orderEmail + '</span>';
                }

                if (errorMessages.hasOwnProperty('uploadedImages')) {
                  errorMessage += '<br><span class="error">' + errorMessages.uploadedImages + '</span>';
                }

                if (errorMessages.hasOwnProperty('sscorderis')) {
                  errorMessage += '<br><span class="error">' + errorMessages.sscorderis + '</span>';
                }

                if (errorMessages.hasOwnProperty('sscorderjauapdor')) {
                  errorMessage += '<br><span class="error">' + errorMessages.sscorderjauapdor + '</span>';
                }

                // Display error messages in the "errtttdipsl" div element
                errorDisplay.innerHTML = errorMessage;
            }
        } else {
            // Handle other errors here (e.g., network error)

        }
    };

    xhr.onerror = function() {
        // Handle network errors here

    };

    // Send the form data to garantsubmmt.php
    xhr.send(formData);

    return false; // Prevent form submission
}


function frmpstgtinfisrw() {

  var vardasppt = document.getElementById("name-padfrm").value;
  var emailasppt = document.getElementById("email-padfrm").value;
  var tekstasppt = document.getElementById("message-padfrm").value;
  var formisktea = document.getElementById("ttformmailsend");

var data = {
    vardss: vardasppt,
    emailss: emailasppt,
    tekstspad: JSON.stringify($("#message-padfrm").val()),

};

$.ajax({
    type: "POST",
    url: "/service-page/havquestsnd.php",
    data: data,
    success: function (response) {
        if (response === "success") {

          formisktea.innerHTML = '';
          formisktea.style = 'align-self: center;';
          formisktea.innerHTML = '<h2>Jūsų užklausa gauta, atsakysime kaip įmanoma greičiau.</h2>';

        }
    },
    error: function (xhr, status, error) {
        console.error("AJAX Error:", error);
    }
});


}
