$(document).ready(function () {
  wow();
  webfontloader();
  setupOffcanvas();
  setupHeaderSubmenu();
  popup();
  bodyHeight();
  scrollToTop();
  fixedHeader();
  openSubMenu();

  $(window).on('resize', function() {
    openSubMenu();
  });

  // home slider setting
  $("#main-slide").slick({
    dots: false,
    arrows: false,
    autoplay: true,
    autoplaySpeed: 2000,
    infinite: true,
    speed: 2000,
    slidesToShow: 1,
    adaptiveHeight: true,
  });
  $("#mob-slide").slick({
    dots: false,
    arrows: false,
    autoplay: true,
    autoplaySpeed: 2000,
    infinite: true,
    speed: 2000,
    slidesToShow: 1,
    adaptiveHeight: true,
    fade: true,
    cssEase: "linear",
  });
  $(".boxSlider").slick({
    dots: false,
    arrows: true,
    autoplay: true,
    autoplaySpeed: 2000,
    infinite: true,
    speed: 600,
    slidesToShow: 1,
    adaptiveHeight: true,
    responsive: [
      {
        breakpoint: 576,
        settings: {
          arrows: false,
        },
      },
    ],
  });

  // $(".news-slider").slick({
  //   dots: false,
  //   arrows: true,
  //   autoplay: true,
  //   autoplaySpeed: 800,
  //   infinite: true,
  //   centerMode: false,
  //   slidesToShow: 4,
  //   slidesToScroll: 1,
  //   variableWidth: true,
  //   responsive: [
  //     {
  //       breakpoint: 576,
  //       settings: {
  //         fade: true,
  //         cssEase: "linear",
  //         autoplaySpeed: 1000,
  //         slidesToShow: 1,
  //         arrows: false,
  //         variableWidth: false,
  //       },
  //     },
  //   ],
  // });

  $('.popup').magnificPopup({
    type: 'image',
    gallery: {
      enabled: true,
      navigateByImgClick: true,
      preload: [0,1], // Will preload 0 - before current, and 1 after the current image
      tPrev: '上一張',
      tNext: '下一張'
    },
    image: {
      titleSrc: 'title'
    }
  });

  $(".album-slider").slick({
    autoplay: false,
    pauseOnHover: false,
    infinite: true,
    speed: 800,
    slidesToShow: 1,
    slidesToScroll: 1,
    arrows: true,
    fade: true,
    //asNavFor: ".album-nav",
    responsive: [
      {
        breakpoint: 576,
        settings: {
          arrows: true,
        },
      },
    ],
  });
  $(".album-nav").slick({
    //asNavFor: ".album-slider",
    dots: false,
    infinite: false,
    arrows: false,
    rows: 2,
    slidesPerRow: 2,
    slidesToShow: 1,
  });

  $(".album-slider").on("afterChange", function (event, slick, currentSlide) {
    let skillNum = Math.floor(currentSlide / 4);
    $(".album-nav").slick("slickGoTo", skillNum);
  });

  (function () {
    "use strict";
    window.addEventListener(
      "load",
      function () {
        // Fetch all the forms we want to apply custom Bootstrap validation styles to
        var forms = document.getElementsByClassName("needs-validation");
        // Loop over them and prevent submission
        var validation = Array.prototype.filter.call(forms, function (form) {
          form.addEventListener(
            "submit",
            function (event) {
              if (form.checkValidity() === false) {
                event.preventDefault();
                event.stopPropagation();
              }
              form.classList.add("was-validated");
            },
            false
          );
        });
      },
      false
    );
  })();
});

function wow() {
  // init wow animation
  wow = new WOW({
    boxClass: "wow",
    animateClass: "animated",
    offset: 0,
    mobile: true,
    live: true,
  });
  wow.init();
}

function webfontloader() {
  WebFont.load({
    google: {
      families: [
        "Oswald:300,400,500,600,700",
        "Racing Sans One:400"
      ],
    },
  });
}

function bodyHeight() {
  // set page height
  var topbottomh = $(".footer").outerHeight();
  $(".indexcont").css("min-height", "calc(100vh - " + topbottomh + "px)");
  $(".pagecont").css("min-height", "calc(100vh - " + topbottomh + "px)");
}

function fixedHeader() {
  // scroll functions
  var menuh = $(".topbar").outerHeight() - 1;
  $(".pagebanner").css("margin-top", menuh);

  $(window).on("scroll", function () {
    if ($(window).scrollTop() > menuh) {
      $(".headerwrap").addClass("fixed");
    } else {
      $(".headerwrap").removeClass("fixed");
    }
  });
}

function popup() {
  $('.popup').magnificPopup({
    type: 'image',
    gallery: {
      enabled: true,
      navigateByImgClick: true,
      preload: [0,1], // Will preload 0 - before current, and 1 after the current image
      tPrev: '上一張',
      tNext: '下一張'
    },
    image: {
      titleSrc: 'title'
    }
  });
}

function scrollToTop(){
  $(".scrollToTop").on("click", function (e) {
    e.preventDefault();
    $("html, body").animate({ scrollTop: 0 }, 800);
    return false;
  });
}

function trimSpaces(str) {
  var result;
  result = str.replace(/(^\s+)|(\s+$)/g, "");
  result = result.replace(/\s/g, "");
  result = result.replace(/(^ *)|( *$)/g, "");
  result = result.replace(/ /g, "");
  return result;
}

// 從 Local Storage 取得 favorites 陣列資料
function getFavorites() {
  let favorites = localStorage.getItem('favorites');
  if (favorites) {
      return JSON.parse(favorites);
  } else {
      return [];
  }
}

// 新增資料到 favorites 陣列
function addFavorite(item) {
  let favorites = getFavorites();
  favorites.push(item);
  localStorage.setItem('favorites', JSON.stringify(favorites));
}

// 移除 favorites 陣列中的資料
function removeFavorite(item) {
  let favorites = getFavorites();
  favorites = favorites.filter(favorite => favorite !== item);
  localStorage.setItem('favorites', JSON.stringify(favorites));
}

// 確認某個 id 是否存在於 favorites 中
function isFavorite(item) {
  let favorites = getFavorites();
  return favorites.includes(item);
}

// 取得 Cookie 的值
function getCookie(name) {
  var value = "; " + document.cookie;
  var parts = value.split("; " + name + "=");
  if (parts.length === 2) return decodeURIComponent(parts.pop().split(";").shift());
  return null;
}

// 判斷特定值是否已存在於 Cookie 的 Array 中
function isValueInCookieArray(cookieName, value) {
  var cookieValue = getCookie(cookieName);

  if (cookieValue) {
      var array = JSON.parse(cookieValue);
      return array.includes(value); // 檢查 value 是否存在於 Array 中
  }
  
  return false; // 如果 Cookie 不存在或 Array 中不包含該值,則返回 false
}

// 設定 Cookie 的值
function setCookie(name, value, expires) {
  document.cookie = name + "=" + encodeURIComponent(value) + "; expires=" + expires.toUTCString() + "; path=/";
}

// 添加值到 Cookie 的 Array 中
function addValueToCookieArray(cookieName, value) {
  if (!isValueInCookieArray(cookieName, value)) {
      var cookieValue = getCookie(cookieName);
      var array = cookieValue ? JSON.parse(cookieValue) : [];
      
      array.push(value);

      var now = new Date();
      var expire = new Date(now.getFullYear(), now.getMonth(), now.getDate() + 1, 0, 0, 0);

      setCookie(cookieName, JSON.stringify(array), expire);
  }
}

// 側選單功能
function setupOffcanvas() {
  // 獲取相關元素
  const menuBtn = document.querySelector('.menu-btn');
  const offcanvas = document.querySelector('.offcanvas');
  const backdrop = document.querySelector('.offcanvas-backdrop');
  const closeBtn = document.querySelector('.offcanvas .close-btn');

  // 切換測選單狀態
  function toggleOffcanvas() {
    offcanvas.classList.toggle('show');
    if (offcanvas.classList.contains('show')) {
      document.body.style.overflow = "hidden";
      document.body.appendChild(backdrop);
      setTimeout(() => {
        backdrop.classList.add('show');
      }, 0);
    } else {
      document.body.style.overflow = "";
      backdrop.classList.remove('show');
      setTimeout(() => {
        backdrop.remove();
      }, 300);
    }
  }

  // 添加點擊事件監聽器
  menuBtn.addEventListener('click', toggleOffcanvas);
  backdrop.addEventListener('click', toggleOffcanvas);
  closeBtn.addEventListener('click', toggleOffcanvas);
}

// 側選單展開子選單
function setupHeaderSubmenu() {
  $(".offcanvas .has_submenu > .nav-link").on("click", function (e) {
    e.preventDefault();
    $(this).siblings(".submenu").slideToggle();
    $(this).toggleClass("active");
  });
}

//
function openSubMenu() {
    if (window.matchMedia('(max-width: 767px)').matches) {
      $('.has_submenu .nav-link').off('click').on('click', function(e) {
        if($(e.target).is('.arrow-down')) {
          e.preventDefault();
          $(this).closest('.has_submenu').toggleClass('active');
        }
      });
    } else {
      $('.has_submenu .nav-link').off('click');
    }
}