
   // LAZY LOADING BLOCK ELEMENT
  var lazy_load_group = [];
  
  var lazyLoadInstance = new LazyLoad({
   elements_selector: ".lazy"
  });
  
  
   lazy_load_group.push(
          {
              id: 'js-deal-box',
              target: '#js-deal-box',
              loadFn: function () {
               getDealProduct();
              },
          },

 	
    )
  




  //Kiểm tra cú pháp Email
function validateEmail(Email) {
  var regaxEmail =
    /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
  if (regaxEmail.test(Email)) {
    return true;
  } else {
    return false;
  }
}

//Kiếm tra cú pháp Số điện thoại
var number_regex1 = /^[0]\d{9}$/i;
var number_regex2 = /^[0]\d{10}$/i;
var error = "";
  
  
//Kiểm tra tên chứa ký tự đặc biệt
var nameRegex =  /[^a-z0-9A-Z_ÀÁÂÃÈÉÊÌÍÒÓÔÕÙÚĂĐĨŨƠàáâãèéêìíòóôõùúăđĩũơƯĂẠẢẤẦẨẪẬẮẰẲẴẶẸẺẼỀỀỂưăạảấầẩẫậắằẳẵặẹẻẽềềểỄỆỈỊỌỎỐỒỔỖỘỚỜỞỠỢỤỦỨỪễếệỉịọỏốồổỗộớờởỡợụủứừỬỮỰỲỴÝỶỸửữựỳỵỷỹ]/u;
  





    // ADD ITEM TO CART SUCCESS FORM
  var successForm = document.querySelector(".success-form");
  function cartButton(idCart) {
    Hura.Cart.Product.add(idCart, 0, { quantity: 1 }).then(function (
      add_status
    ) {
      if (add_status.status === "error") {
        alert("Đã tồn tại sản phẩm trong giỏ hàng");
      } else {
        modalSuccess();
        change_cart_amount();
      }
    });
  }

  // CALL MODAL SUCCESS
  function modalSuccess() {
    successForm.classList.toggle("hide");
    setTimeout(function () {
      successForm.classList.toggle("hide");
    }, 1200);
  }

  // CHANGE AMOUNT CART HEADER
  function change_cart_amount() {
    Hura.Cart.getSummary().then(function (data) {
      if (data.total_item != 0) {
        $(".header-features-cart-amount").show().html(data.total_item);
  		$(".name-amount-sp").show();
  		$(".amount-sp-in-cart").show().html(""+ data.total_item +"");
      } else {
        $(".header-features-cart-amount").hide();
        $(".name-amount-sp").hide();
      }
    });
  }
 
  




  function debounce(func, wait, immediate) {
    var timeout;
    return function() {
        var context = this, args = arguments;
        var later = function() {
            timeout = null;
            if (!immediate) func.apply(context, args);
        };
        var callNow = immediate && !timeout;
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
        if (callNow) func.apply(context, args);
    };
};  
  
  
  
   // GET SEARCH PRODUCT
  function searchProduct(value) {
    var params = {
      action: "search",
      action_type: "search",
      content: "product",
      q: value,
    };

    Hura.Ajax.get("search", params).then(function (data) {
      //console.log(data.list);

      if (data.list.length > 0) {
        $(".search-results").css("display", "block");
        var html = Hura.Template.parse(searchResultsTpl, data.list);
        Hura.Template.render(".search-results-list", html);
      } else {
        $(".search-results").css("display", "none");
      }
    });
  }


  
   function getSearchValue() {
  $('#js-search-box').keyup(debounce(function(e){
      let value = e.target.value;
      if (value) {
        searchProduct(value);
      } else {
        $(".search-results").css("display", "none");
      }
    },200));
  }
  
  
  // CART HEADER POPUP
  function cartHeaderPopup() {
    $(".cart-header").on("mouseenter", function () {
      var target = ".cart-ttip-item-container";
      Hura.Cart.getCart().then(function (data) {
        if (data == 0) {
          $(target).html("<h5>Có 0 sản phẩm trong giỏ hàng</h5>");
          $(target).find("h5").attr("class", "header-null-cart");
        } else {
          var html = Hura.Template.parse(headerCartTpl, data);
          $(target).html(html);
        }
      });
    });
  }
  
  function totalCartPopup(){
       Hura.Cart.getSummary().then(function (summary_data) {
        $("#js-header-cart-quantity").html(
          "<i>(Số lượng: " + summary_data.total_quantity + " sản phẩm)</i>"
        );
        $("#js-header-cart-total-price").html(
          summary_data.total_value.toLocaleString() + "₫"
        );
        if (summary_data.total_quantity == 0) {
              $("#btn-cart-ttip").addClass( "hide" );
        }

  
      });
  }

  
  
  // FIXED HEADER
  function fixed_header() {
    $(window).scroll(function () {
      var distanceFromTop = $(document).scrollTop();
      
      if (distanceFromTop > 350) {
        $(".header-mid").addClass("fixed-nav");
           
      } else {
        $(".header-mid").removeClass("fixed-nav");
  		
      }
    });
  }
  




  
// FORMAT PRICE
function formatCurrency(a) {
  var b = parseFloat(a)
    .toFixed(2)
    .replace(/(\d)(?=(\d{3})+\.)/g, "$1.")
    .toString();
  var len = b.length;
  b = b.substring(0, len - 3);
  return b;
}

// CONVERT STRING TO NUMBER
function strToNumber(str) {
  str += "";
  while (str.indexOf(".") > 0) {
    str = str.replace(".", "");
  }
  var result = parseFloat(str);
  return isNaN(result) ? 0 : result;
}

 function checkSummary(productSummary) {
    var summary = [];
    if (productSummary) {
      var splitSummary = productSummary.split("\r\n");
      splitSummary.forEach(function (value, item) {
        if (item < 10 && 1 < 2) {
          summary.push(splitSummary[item]);
        }
      })
    }
    return summary.join("\r\n");
  }
  
  // REWORK SPECIAL OFFER PRODUCT
  function checkKhuyenMai(specialOffer) {
    var offer = [];
    if (specialOffer) {
      var splitOffer = specialOffer.split("\n");
      splitOffer.forEach(function (value, item) {
        if (item < 10 && 1 < 2) {
          offer.push(`<div class="item">` + splitOffer[item] + `</div>`);
        }
      })
    }
    return offer.join('');
  }





   // DEAL TIME DOWN
  function saleTimeDown() {
    // SET TIMER
    let timeDealLeft = parseInt($(".box-deal-home .p-item").first().attr("data-time"));
    const timer = setInterval(timeDown, 1000);

    function timeDown() {
      // GET TIME LEFT PER SECOND
      let timeLeft = timeDealLeft;
      timeDealLeft = timeLeft - 1;

      if ($(".global-time-deal").length) $(".global-time-deal").html(renderTimeLeft(timeLeft));

      if (timeLeft === 0) {
        clearInterval(timer);
      }
    }
  }

  // RENDER HOMEPAGE TIME LEFT
  function renderTimeLeft(timeLeft) {
    const sec = String(timeLeft % 60).padStart(2, 0);
    const min = String(Math.trunc((timeLeft / 60) % 60)).padStart(2, 0);
    const hour = String(Math.trunc(timeLeft / 3600) % 24).padStart(2, 0);
  	const day = String(Math.trunc(timeLeft / 86400) % 3600).padStart(2, 0);

    const firstLetterSec = Math.floor(sec / 10);
    const secondLetterSec = sec % 10;
    const firstLetterMin = Math.floor(min / 10);
    const secondLetterMin = min % 10;
    const firstLetterHour = Math.floor(hour / 10);
    const secondLetterHour = hour % 10;
  	const firstLetterDay = Math.floor(day / 10);
    const secondLetterDay = day % 10;

    return `
  		   <p>${day}</p>
           <span>:</span>
           <p>${hour}</p>
           <span>:</span>
           <p>${min}</p>
           <span>:</span>
           <p>${sec}</p>    
         `;
  }
  
  
  
  // GET HOT-DEAL PRODUCT
  function getDealProduct() {
    let params = {
      action_type: "list",
      type: "active",
      show: 20,
    }

    let target = "#js-deal-box";

    Hura.Ajax.get("deal", params).then(function (data) {
      //console.log(data.list);
      let html = Hura.Template.parse(productDealTpl, data.list);
      Hura.Template.render(target, html);

      saleTimeDown();
      dealLineWidth();
  
  	  resetImagePageDeal();
    });
  } 
  
  
  // RESET IMAGE IN PAGE DEAL
  function resetImagePageDeal() {
  	if ($(".page-deal").length > 0) {
  		$(".p-item .p-img").each(function(){
  			let firstChild = $(this).children(":first");
  			let lastChild = $(this).find(".swiper-lazy-preloader");
  			let imageDataSrc = firstChild.attr("data-src");
  			firstChild.attr("src", imageDataSrc);
  			lastChild.css("display","none");
  		})
  	}
  }
	
  // CUSTOM BOTTOM LINE PRODUCT DEAL
  function dealLineWidth() {
    $(".js-line-deal-left").each(function () {
      let quantitySaleLeft = parseInt($(this).parent().attr("data-quantity-left"));
      let quantitySaleTotal = parseInt($(this).parent().attr("data-quantity-sale-total"));

      if (quantitySaleLeft >= 0) {
        let lineDealWidth = quantitySaleLeft / quantitySaleTotal * 100 + "%";
        $(this).css("width", lineDealWidth);
      } else {
        $(this).css("width", 0);
      }
    })
  }
  
  


  


    // SORT SELECT BOX
  function sortSelect() {
    var href = window.location.href;

    $(".js-select-sort-item").each(function () {
      if ($(this).val() === href) {
        $(this).attr("selected", "selected");
      }
    });
  }
  sortSelect();
