function setCookie(name, value, days) {
  let expires = "";
  if (days) {
    const date = new Date();
    date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
    expires = "; expires=" + date.toUTCString();
  }
  document.cookie = name + "=" + (value || "") + expires + "; path=/";
}

function getCookie(name) {
  const nameEQ = name + "=";
  const ca = document.cookie.split(';');
  for (let i = 0; i < ca.length; i++) {
    let c = ca[i];
    while (c.charAt(0) === ' ') c = c.substring(1, c.length);
    if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length, c.length);
  }
  return null;
}

$(document).ready(function () {

  const x = getCookie('visited');

  if (x !== 'testcookie') {
    $(".cookies").addClass("active");
  }

  function closeCookies() {
    $(".cookies").removeClass("active");
    setCookie('visited', 'testcookie');
  }

  $('.cookies span').click(closeCookies);
})

function getUrlVars() {
  var vars = {};
  var parts = window.location.href.replace(
    /[?&]+([^=&]+)=([^&]*)/gi,
    function (m, key, value) {
      vars[key] = value;
    }
  );
  return vars;
}

$(function () {
  if (window.location.hash == "#_=_") {
    history.replaceState
      ? history.replaceState(null, null, window.location.href.split("#")[0])
      : (window.location.hash = "");
  }

  // Sort Settings
  var sort = getUrlVars()["sort"];
  if (sort == "new") {
    $("#t1").click();
    filter();
  } else if (sort == "sale") {
    $("#t2").click();
    filter();
  }

  // Wow
  var wow = new WOW({
    boxClass: "wow", // animated element css class (default is wow)
    animateClass: "animated", // animation css class (default is animated)
    offset: 300, // distance to the element when triggering the animation (default is 0)
    mobile: false, // trigger animations on mobile devices (default is true)
    live: true, // act on asynchronously loaded content (default is true)
    callback: function (box) {},
    scrollContainer: null,
  });
  wow.init();

  // Sticky Header

  var lastScrollTop = 0;

  $(window).scroll(function () {
    var stickyNavTop = 100;

    var stickyNav = function () {
      var scrollTop = $(window).scrollTop();
      if (scrollTop > stickyNavTop) {
        $("header").addClass("sticky").addClass("scrolled");
      } else {
        $("header").removeClass("sticky").removeClass("scrolled");
      }
      if (scrollTop < lastScrollTop) {
        $("header").removeClass("sticky");
      }
      lastScrollTop = scrollTop;
    };

    stickyNav();
  });

  // Mobile Menu
  // $('.mob-menu').on('click', function () {
  //   $('.navigation').toggleClass('visible');
  // });

  // Cart
  $(".cart-trigger").on("click", function () {
    $(".modal-overlay").fadeIn(200);
    $(".cart-modal").addClass("visible");
    disableScroll();
  });

  $(".checkout-change-order").on("click", function () {
    $(".modal-overlay").fadeIn(200);
    $(".cart-modal").addClass("visible");
    disableScroll();
  });

  $(".close-cart").on("click", function (e) {
    e.preventDefault();
    $(".cart-modal").removeClass("visible");
    $(".modal-overlay").fadeOut(200);
    enableScroll();
  });

  $(".tabs-menu a").click(function (event) {
    event.preventDefault();
    $(this).parent().addClass("current");
    $(this).parent().siblings().removeClass("current");
    var tab = $(this).attr("href");
    $(".tab-content").not(tab).css("display", "none");
    $(tab).fadeIn();
  });

  // Filter
  // $('.filter-trigger').on('click', function () {
  //     $('.filters-modal').fadeOut(200);
  //     $('#filters_main').fadeToggle(200);
  // });

  window.addEventListener("click", function (e) {
    let cont = document.querySelector("#filters_main");
    if (cont) {
      if (
        !e.target.classList.contains("filter-trigger") &&
        cont.classList.contains("showed")
      ) {
        if (!cont.contains(e.target)) {
          cont.classList.remove("showed");
        }
      } else if (
        e.target.classList.contains("filter-trigger") &&
        cont.classList.contains("showed")
      ) {
        cont.classList.remove("showed");
      } else if (
        e.target.classList.contains("filter-trigger") &&
        !cont.classList.contains("showed")
      ) {
        cont.classList.add("showed");
      }
    }
  });

  // $('.sort').on('click', function () {
  //     $('#filters_sort').fadeToggle(200);
  // });

  $(".close-filters").on("click", function () {
    document.querySelector("#filters_main").classList.remove("showed");
  });

  $(".view-type").on("click", function (argument) {
    $(".catalog-page .pr-col").toggleClass("big");
  });

  // // Size Charts
  // $(".sizes-guide-trigger").on("click", function () {
  //   $(".modal-overlay").fadeIn(200);
  //   $(".size-guide-modal").fadeIn(200);
  // });

  // $(".close-guide").on("click", function () {
  //   $(".modal-overlay").fadeOut(100);
  //   $(".size-guide-modal").fadeOut(100);
  // });

  // $(".modal-overlay").on("click", function () {
  //   $(".modal-overlay").fadeOut(100);
  //   $(".size-guide-modal").fadeOut(100);
  // });

  // Map
  if ($("#map").length) {
    function initialize() {
      var latlng = new google.maps.LatLng(46.48092114, 30.74441484);

      var myOptions = {
        zoom: 17,
        scrollwheel: false,
        navigationControl: false,
        mapTypeControl: false,
        center: latlng,
        mapTypeId: google.maps.MapTypeId.TERRAIN,
        styles: [
          {
            featureType: "administrative",
            elementType: "geometry.stroke",
            stylers: [{ color: "#ffffff" }],
          },
          {
            featureType: "administrative",
            elementType: "labels.text.fill",
            stylers: [{ color: "#bbd4dd" }],
          },
          {
            featureType: "landscape",
            elementType: "all",
            stylers: [{ color: "#f2f2f2" }],
          },
          {
            featureType: "landscape.man_made",
            elementType: "geometry.fill",
            stylers: [{ color: "#eeeeee" }],
          },
          {
            featureType: "landscape.man_made",
            elementType: "labels.text.fill",
            stylers: [{ color: "#ffffff" }],
          },
          {
            featureType: "poi",
            elementType: "all",
            stylers: [{ visibility: "off" }],
          },
          {
            featureType: "road",
            elementType: "all",
            stylers: [{ saturation: -100 }, { lightness: 45 }],
          },
          {
            featureType: "road.highway",
            elementType: "all",
            stylers: [{ visibility: "simplified" }],
          },
          {
            featureType: "road.arterial",
            elementType: "labels.text.fill",
            stylers: [{ color: "#afafaf" }],
          },
          {
            featureType: "road.arterial",
            elementType: "labels.icon",
            stylers: [{ visibility: "off" }],
          },
          {
            featureType: "transit",
            elementType: "all",
            stylers: [{ visibility: "off" }],
          },
          {
            featureType: "water",
            elementType: "all",
            stylers: [{ color: "#46bcec" }, { visibility: "on" }],
          },
          {
            featureType: "water",
            elementType: "geometry.fill",
            stylers: [{ color: "#bbd4dd" }],
          },
          {
            featureType: "water",
            elementType: "labels.text.fill",
            stylers: [{ color: "#ffffff" }],
          },
        ],
      };

      var map = new google.maps.Map(document.getElementById("map"), myOptions);

      var image = "../wp-content/themes/pakhtusova/img/marker.png";
      var myLatLng = new google.maps.LatLng(46.48092114, 30.74441484);
      var beachMarker = new google.maps.Marker({
        position: latlng,
        map: map,
        icon: image,
      });
    }
    google.maps.event.addDomListener(window, "load", initialize);
  }

  // Stuck Product Info
  // if($(window).width() > 767) {
  //     $(window).stuck();
  // }

  // Cabinet tabs
  $(".tabs-menu a").click(function (event) {
    event.preventDefault();
    $(this).parent().addClass("current");
    $(this).parent().siblings().removeClass("current");
    var tab = $(this).attr("href");
    $(".tab-content").not(tab).css("display", "none");
    $(tab).fadeIn();
  });

  // Product, Cart, Checkout Code
  $("[name=delivery-type]").click(function () {
    if ($(this).val() === 'delivery-1') {
      $('#shoproom_address').show();
    } else {
      $('#shoproom_address').hide();
    }
    var shipping =
      $("#country-shipping").val() == 0 ? 0 : $("#region-shipping").val();

    console.log('shipping', shipping)

    var currency = $("[name=currency_symbol]").val();

    if ($(this).val() == "delivery-1") {
      $("#deliveryAddress").hide();
      $("#deliveryStreet").css("display", "block");
//      $("#npCol").remove();
			$("#npCol").hide();

      var total = $("[name=subtotal-cart]").val();
      total = parseFloat(total);
      $(".total td:eq(1)").html(
        "<strong>" + total + " " + currency + "</strong>"
      );
      $(".total tr td:eq(1)").html(
        "<strong>" + total + " " + currency + "</strong>"
      );


      document.getElementsByName("amount")[0].value = total;
      document.getElementsByName("shipping")[0].value = 0;
      $("#shipping_price").html("0 " + currency);
      $("#shoproom_address").show();
      $("#auto_delivery").html("0");
    } else if ($(this).val() == "delivery-3" && $(this).prop("checked")) {
      $("#deliveryAddress").show();
      $("#deliveryStreet").css("display", "none");

      if(!$( "#npCol" ).length){
      	$("#deliveryAddress .f-section").append(
	        '<div class="col" id="npCol"><select class="cell" name="np_num" id="address-shipping" placeholder="Отделение" value=""><div class="options_window"></div></div>'
	      );
			}
			$("#npCol").show();

      /*
	  '<div class="c-select">' +
		  '  <select name="np_num" id="address-shipping" style="display:block;">\n' +
          '    <option id="first-country" value="-1">Выберете страну</option> \n' +
          '  </select>' +
          '</div>'
		*/

      /*'<input type="text" class="cell" name="np_num" placeholder="Номер отделения"></div>'*/
      if ($("[name=np_num]").val() === undefined) $("#shoproom_address").hide();
      $("#auto_delivery").html(shipping);
      console.log(shipping);
    } else {
      // if ($(this).is(':checked')) {
      //   return;
      // }
      $("#deliveryAddress").show();
      $("#deliveryStreet").css("display", "block");
      $("#shoproom_address").hide();
//      $("#npCol").remove();
			$("#npCol").hide();
      var total = $("[name=subtotal-cart]").val();
      // console.log(total, shipping_price);
      if (!shipping) shipping = 0;
      $("#shipping_price").html(shipping + " " + currency);
      $("#auto_delivery").html(shipping);
      total = parseInt(total) + parseInt(shipping);


      console.log('subtotal', total);
      console.log('shipping', shipping);

      $(".total td:eq(1)").html(
        "<strong>" + total + " " + currency + "</strong>"
      );

      $(".total tr td:eq(1)").html(
        "<strong>" + total + " " + currency + "</strong>"
      );

      document.getElementsByName("amount")[0].value = total;
      document.getElementsByName("shipping")[0].value = shipping;
      // $('[name=delivery_zip]').parent().hide();
    }
  });

  $(".reset").click(function () {
    $(this)
      .parent()
      .parent()
      .find("input")
      .each(function () {
        $(this).prop("checked", false);
      });

    filter();
  });

  $(".products-filter input").click(function () {
    filter();
  });

  function filter() {
    var categories = new Array();
    var sizes = new Array();
    var colors = new Array();
    var types = new Array();
    var order = null;

    $(".filters-modal input").each(function () {});

    $("[name=category]").each(function () {
      console.log($(this).val())
      if ($(this).prop("checked")) categories.push($(this).val());
    });

    $("[name=size]").each(function () {
      if ($(this).prop("checked")) sizes.push($(this).val());
    });

    $("[name=color]").each(function () {
      if ($(this).prop("checked")) colors.push($(this).val());
    });

    $("[name=type]").each(function () {
      if ($(this).prop("checked")) types.push($(this).val());
    });

    $("[name=order]").each(function () {
      if ($(this).prop("checked")) order = $(this).val();
    });

    // console.log(categories, sizes, colors, types, order);

    var data = {
      action: "filter_catalog",
      categories: categories,
      sizes: sizes,
      colors: colors,
      types: types,
      order: order,
    };
    jQuery.post(myajax.url, data, function (response) {
      // console.log(response);
      $("#products_catalog").html(response);
    });
  }

  $("#user_tel").mask("+000000000000");
});

function add_to_cart(post_id, variation_id) {
  let btn = event.target;
  let var_id = !variation_id ? variation_id : null;
  let elementArr = btn.parentElement.parentElement.children;
  let spinnerEl = btn.parentElement.parentElement.nextElementSibling;
  let spinnerSecondEl = btn.nextElementSibling;
  let productImageEl =
    btn.parentElement.parentElement.parentElement.children[0].children[0];
  var quantity = $("#Quantity").val() ? $("#Quantity").val() : 1;

  var select1 = "",
    select2 = "";

  select1 = btn.parentNode.parentNode.querySelector(
    '.sizes input[name="size-s"]:checked'
  );
  select1 = select1 ? select1.value : null;

  if (select1 === null) {
    $(".choose-size-tooltip").show();
    setTimeout(function () {
      $(".choose-size-tooltip").hide();
    }, 3000);
    return 0;
  }

  if ($("#select-2").val()) select2 = $("#select-2").val();
  else if (
    $("#select-2").val() == null &&
    typeof $("#select-2").val() != "undefined"
  ) {
    $(".color-size .c-select").last().css("border-color", "red");
    return 0;
  }

  var data = {
    action: "add_to_cart",
    post_id: post_id,
    quantity: quantity,
    select1: select1,
    select2: select2,
    variation_id: var_id,
  };
  if (elementArr && productImageEl && spinnerEl) {
    elementArr[0].classList.add("is-hidden");
    elementArr[1].classList.add("is-hidden");
    elementArr[2].classList.add("is-hidden");
    productImageEl.classList.add("is-hidden");
    spinnerEl.classList.add("is-open");
  }

  if (spinnerSecondEl) {
    btn.classList.add("is-hidden");
    spinnerSecondEl.classList.add("is-open");
  }

  $.post(myajax.url, data, (response) => {
    update_cart();
    setTimeout(() => {
      if (elementArr && productImageEl && spinnerEl) {
        spinnerEl.classList.remove("is-open");
        elementArr[0].classList.remove("is-hidden");
        elementArr[1].classList.remove("is-hidden");
        elementArr[2].classList.remove("is-hidden");
        productImageEl.classList.remove("is-hidden");
      }

      if (spinnerSecondEl) {
        spinnerSecondEl.classList.remove("is-open");
        btn.classList.remove("is-hidden");
      }

      $(".cart-trigger").click();
    }, 1000);
  });
}

function plus_minus_item_in_cart(post_id, operator, variation_id, thisis) {
  var quantity = $(thisis).parent().find(".cell").val();
  var data = {
    action: "plus_minus_item_in_cart",
    post_id: post_id,
    operator: operator,
    variation_id: variation_id,
    key: "js",
  };
  jQuery.post(myajax.url, data, function (response) {

    if (operator == "plus")
      $(thisis)
        .parent()
        .find(".cell")
        .val(parseInt(quantity) + 1);
    else if (operator == "minus" && quantity > 1)
      $(thisis)
        .parent()
        .find(".cell")
        .val(parseInt(quantity) - 1);

    update_cart();
  });
}

function change_quantity(post_id, variation_id, thisis) {
  var quantity = $(thisis).val();

  if (quantity <= 0) {
    $(thisis).css("border-color", "red");
    update_cart();
    return;
  }

  var data = {
    action: "change_quantity",
    post_id: post_id,
    quantity: quantity,
    variation_id: variation_id,
    key: "js",
  };

  jQuery.post(myajax.url, data, function (response) {
    update_cart();
  });
}



function del_from_cart(post_id, variation_id) {
  var data = {
    action: "del_from_cart",
    post_id: post_id,
    variation_id: variation_id,
    key: "js",
  };
  event.target.parentElement.parentElement.children[0].classList.add("is-open");
  event.target.parentElement.parentElement.children[1].classList.add(
    "is-hidden"
  );
  jQuery.post(myajax.url, data, function (response) {
    update_cart();
  });
}
function update_cart() {
  var data = {
    action: "update_cart",
    key: "js",
  };

  jQuery.post(myajax.url, data, function (response) {
    var dat = JSON.parse(response);
    // console.log(dat);
    $("#products-cart").html(dat.html);
    $("#basket").html(dat.count);
    update_checkout();
    $(".js-basket-slider").slick({
      infinite: false,
      arrows: true,
      slidesToShow: 4,
      slidesToScroll: 1,
      autoplay: false,
      pauseOnFocus: false,
      pauseOnHover: false,
      speed: 500,
      swipe: true,
      prevArrow: '<button type="button" class="slick-prev"></button>',
      nextArrow: '<button type="button" class="slick-next"></button>',
      responsive: [
        {
          breakpoint: 900,
          settings: {
            swipe: true,
            slidesToShow: 3,
          },
        },
        {
          breakpoint: 600,
          settings: {
            swipe: true,
            slidesToShow: 2,
          },
        },
      ],
    });
  });


  // basket slider
}

$(document).on('click', '.c-select', function () {
  let placeholder = '';
  switch ($('.multilang span:first').text()) {
    case 'ua':
      placeholder = 'Пошук...';
      break;
    case 'ru':
      placeholder = 'Поиск...';
      break;
    default:
      placeholder = 'Search...';
      break;
  }
  $('.select2-search__field').prop('placeholder', placeholder)
})

function update_checkout() {

  setTimeout(() => {
    $('.woocommerce-message').remove();
  }, 9000);
  let country = $("#country-shipping option:selected").val();
  var data = {
    action: "update_checkout",
    selected_region: $("#region-shipping option:selected").text(),
    selected_country: country == 0 ? 'Ukraine' : country,
    key: "js",
  };
  jQuery.post(myajax.url, data, function (response) {
    var needle = JSON.parse(response);
    $(".items-list").html(needle.html);
    $("#region-shipping").html(needle.shippingHtml);
  });
}

function change_shipping() {

  console.log('updated shipping');
  $('#shoproom_address').hide();
 setTimeout(() =>{

   const countryVal = document.getElementById('select2-country-shipping-container').innerHTML;
   console.log(countryVal);

	 if(is_ukr(countryVal)) {
//   if( countryVal === 'Ukraine' || countryVal === 'Украина' || countryVal === 'Україна') {
     $('.pay-method ul li:last-child').show();
   } else {
     $('.pay-method ul li:last-child').hide();
   }
 }, 500)


  var shipping_value = $('#select2-country-shipping-container').attr('title');

//  if(!['Ukraine', 'Украина', 'Україна'].includes(shipping_value)) {
	if(!is_ukr(shipping_value)) {
    $('.delivery-type label[for="c4"]').trigger('click');
    $('.delivery-type #c4').prop('checked', true);
  }

  if (
    $("#region-shipping option:selected").text() != "Europe" ||
    ($("#region-shipping option:selected").text() == "Europe" &&
      $("#country-shipping option:selected").val() != "0")
  ) {
    $(".d-price").hide();
    $("#shoproom_address_international").show();
    $("#deliveryStreetBlock").css("display", "block");
    $("#deliveryStreet").prependTo("#deliveryStreetBlock");
    $("#deliveryCity").appendTo("#deliveryCityBlock");
    $("#deliveryIndex").css("display", "block");
    $("#deliveryStreet").css("display", "block");
    // $("#npCol").remove();
    $("#npCol").hide();
    $(".delivery-type li").each(function () {
      if (
        $(".delivery-type").find("#c4").parent().parent().css("display") ==
        "block"
      ) {
        console.log('returned false...')
        return false;
      }

      if ($("#region-shipping option:selected").text() != "Europe") {
        $("#country-shipping").val("-1");
      }

      if ($(this).css("display") == "block") $(this).css("display", "none");
      else $(this).css("display", "block");
    });
  } else if (
    $("#region-shipping option:selected").text() == "Europe" &&
    $("#country-shipping option:selected").val() == "0"
  ) {
    $(".d-price").show();
    $("#deliveryStreetBlock").css("display", "none");
    $("#deliveryStreet").prependTo("#deliveryAddress .f-section");
    $("#deliveryCity").prependTo("#deliveryAddress .f-section");
    $("#deliveryIndex").css("display", "none");
    $("#shoproom_address_international").hide();
    $(".delivery-type li").each(function () {
      if ($(this).css("display") == "block") $(this).css("display", "none");
      else $(this).css("display", "block");
    });
  }

  var currency = $("[name=currency_symbol]").val();

  if ($("[name=delivery-type]:checked").val() == "delivery-1") {
    var total = $("[name=subtotal-cart]").val();
    total = parseFloat(total);
    $(".total td:eq(1)").html(
      "<strong>" + total + " " + currency + "</strong>"
    );
    $(".total tr td:eq(1)").html(
      "<strong>" + total + " " + currency + "</strong>"
    );

    document.getElementsByName("amount")[0].value = total;
    document.getElementsByName("shipping")[0].value = 0;

  } else {
    var total = $("[name=subtotal-cart]").val();

    // console.log(total, shipping_price);
    var shipping = $("#region-shipping").val();

    if (!shipping) {
      // shipping = shipping_price; // undefined variable, make default value as zero
      shipping = 0;
    }
    $("#shipping_price").html(shipping + " " + currency);
    total = parseFloat(total) + parseInt(shipping);

    $(".total td:eq(1)").html(
      "<strong>" + total + " " + currency + "</strong>"
    );
    $(".total tr td:eq(1)").html(
      "<strong>" + total + " " + currency + "</strong>"
    );

    document.getElementsByName("amount")[0].value = total;
    document.getElementsByName("shipping")[0].value = shipping;
  }

  update_checkout();
}

function is_ukr(str){
	return ['Ukraine', 'Украина', 'Україна'].includes(str);
}

function show_more(location) {
  var data = {
    action: "show_more",
    count: -1,
    location: location,
  };
  jQuery.post(myajax.url, data, function (response) {
    $("#products_catalog").html(response);
    $(".load-more").fadeOut(200);
  });
}


$(document).on('click', '.wc_coupon_form__button', function () {
  console.log('here');
  setTimeout(() => {
    update_checkout();
  }, 500)
});

function create_order(id) {
  if ($('[name="amount"]').val() == 0) {
    return;
  }
  var data = {
    action: "create_order",
    user_id: id,
    delivery_type: $("[name=delivery-type]:checked").val(),
    user_first_name: $("[name=user_first_name]").val(),
    user_last_name: $("[name=user_last_name]").val(),
    user_email: $("[name=user_email]").val(),
    user_password: $("[name='user_password']").val(),
    user_tel: $("[name=user_tel]").val(),
    payment_type: $("[name=payment-type]:checked").val(),
    delivery_city: $("[name=delivery_city]").val(),
    delivery_address: $("[name=delivery_address]").val(),
    delivery_zip: $("[name=delivery_zip]").val(),
    delivery_region: $("#region-shipping option:selected").text(),
    delivery_country: $("#country-shipping option:selected").val(),
    delivery_space: $("[name=delivery_space]").val(),
    np_num: $("[name=np_num]").val(),
  };
  let spinner = $(".items-list .spin-wrapper");
  // console.log(data);
  if (check_fields() == true) {
    // console.log(check_fields());
    console.log(spinner);
    $(spinner).addClass("is-open");
    // $(spinner).nextSibling().addClass("is-hidden");

    // var spinner = new Spinner({
    //   lines: 12, // The number of lines to draw
    //   length: 7, // The length of each line
    //   width: 5, // The line thickness
    //   radius: 10, // The radius of the inner circle
    //   color: "#44a0ae", // #rbg or #rrggbb
    //   speed: 1, // Rounds per second
    //   trail: 100, // Afterglow percentage
    //   shadow: true, // Whether to render a shadow
    // }).spin(document.getElementById("pay_button"));

    jQuery.post(myajax.url, data, function (response) {
      $("#pay_button").html(response);

      // spinner.spin(false);
      $("[name=btn_text]").click();
    });
  }
}
function checkLogin() {
  if ($("#log").val() == "") {
    $("#log").css("border-color", "red");
    return false;
  } else if ($("#pwd").val() == "") {
    $("#pwd").css("border-color", "red");
    return false;
  } else {
    return true;
  }
}

function checkRegister() {
  if ($("#reg_email").val() == "") {
    $("#reg_email").css("border-color", "red");
    return false;
  } else if ($("#reg_pass").val() == "") {
    $("#reg_pass").css("border-color", "red");
    return false;
  } else if ($("#reg_pass2").val() == "") {
    $("#reg_pass2").css("border-color", "red");
    return false;
  } else {
    return true;
  }
}

function check_select() {
  if ($("#region-shipping option:selected").val() == "-1") {
    $("#region").text("empty region");
    $("#region")
      .parent()
      .find(".message-non-valid")
      .css("display", "inline-block");
    return false;
  } else if ($("#country-shipping option:selected").val() == "-1") {
    $("#country").text("empty country");
    $("#country")
      .parent()
      .find(".message-non-valid")
      .css("display", "inline-block");
    return false;
  } else {
    return true;
  }
}

function check_fields() {
  var check = true;
  $(".checkout-page").find(".message-non-valid").css("display", "none");

  if ($("input[name='user_first_name']").val() < 1) {
    $("input[name='user_first_name']")
      .next()
      .css("display", "inline-block")
      .text("Empty name");
    check = false;
  } else if ($("input[name='user_last_name']").val() < 1) {
    $("input[name='user_last_name']")
      .next()
      .css("display", "inline-block")
      .text("Empty name");
    check = false;
  } else if ($("input[name='user_email']").val() < 1) {
    $("input[name='user_email']")
      .next()
      .css("display", "inline-block")
      .text("Empty email");
    check = false;
  } else if ($("input[name='user_tel']").val().length < 10) {
    $("input[name='user_tel']")
      .next()
      .css("display", "inline-block")
      .text("Empty or wrong phone");
    check = false;
  } else {
    check = true;
  }
  console.log(check);
  if (check == true) {
    return true;
  } else {
    return false;
  }
}

var develop = true;
var regexp_email = /^[0-9a-z-\.]+\@[0-9a-z-]{2,}\.[a-z]{2,}$/i;
var regexp_first_last_name = /^[a-zA-Z'][a-zA-Z-' ]+[a-zA-Z']?$/;
// var regexp_address =
function isEmpty(str) {
  if (str.trim() == "") return true;
  return false;
}
function log(message) {
  if (develop) {
    console.log(message);
  }
}

function add_subscriber() {
  var email = $("#email_subscriber").val();
  if (!email) {
    $("#email_subscriber").css("border-color", "red");
    return;
  }
  var data = {
    action: "add_subscriber",
    email_subscriber: email,
  };
  jQuery.post(myajax.url, data, function (response) {
    console.log(data, response);
    alert("Отправленно");
  });
}

function new_pass() {
  var old_pass = $("[name=old_password]").val();
  var new_pass1 = $("[name=new_password1]").val();
  var new_pass2 = $("[name=new_password2]").val();

  // console.log(old_pass + '.', new_pass1+ '.', new_pass2+ '.');

  if (
    old_pass == "" ||
    new_pass1 != new_pass2 ||
    new_pass1 == "" ||
    new_pass2 == ""
  ) {
    return false;
  } else {
    return true;
  }
}

function onSignIn(googleUser) {
  var profile = googleUser.getBasicProfile();
  console.log("ID: " + profile.getId()); // Do not send to your backend! Use an ID token instead.
  console.log("Name: " + profile.getName());
  console.log("Image URL: " + profile.getImageUrl());
  console.log("Email: " + profile.getEmail()); // This is null if the 'email' scope is not present.
}

function disableScroll(target = false) {
  document.body.style.top = `-${window.scrollY}px`;
  document.body.style.width = "100%";
  document.body.style.position = "fixed";
  if (target) {
    target.style.overflow = "auto";
  }
}
function enableScroll() {
  const scrollY = document.body.style.top;
  document.body.style.position = "";
  document.body.style.top = "";
  document.body.style.width = "auto";
  window.scrollTo(0, parseInt(scrollY || "0") * -1);
}

$(document).on("click", ".custom-option.multicurrency", function (i, e) {
  let content = $(this).attr("data-value");
  let search = location.search;
  let hash = location.hash;
  let pathname = location.pathname;

  search = search.replace(/custom_currency\=\w{3}&?/, "");
  search = search.replace(/\?/, "");
  search += search ? "&" : "?";
  search += "custom_currency=" + content;
  search = search.replace(/&+/, "&");

  href = pathname + "?" + search + hash;

  window.location.href = href;

  return false;
});

$(document).on("click", ".custom-option.multilang", function (i, e) {
  let content = $(this).attr("data-value");
  let href = location.pathname + location.search;

  href = href.replace(/^\/(\S\S\/)?/g, "/");
  href = "/" + content + href;

  window.location.href = href;

  return false;
});


$(document).on('change', '[name="user_email"]', function () {
  let data = {
    action: 'does_user_exist',
    email: $(this).val()
  };
  $.post(myajax.url, data, function (response) {
    let data = JSON.parse(response);
    if (data.user_exists) {
      $('[name="user_password"]').hide();
    } else {
      $('[name="user_password"]').show();
    }
  });
});


