$(function () {
// a link 새 창으로 열림 자동 타이틀	
  $("a[target='_blank']").attr("title", "새 창으로 열림")
  function top_popup() {
    const popup = $(".top-popup"),
      closeBtn = popup.find(".top-popup-close")

    closeBtn.click(function () {
      $(".subvisual").addClass("sub-mobile")
    })
  }
  top_popup()


  function sub_header() {
    var ww = $(window).width()
    var hd = $("#header")

    if (ww < 769) {
      hd.addClass("sub-mobile")
    } else {
      hd.removeClass("sub-mobile")
    }
  }
  sub_header()
  $(window).resize(function () {
    sub_header()
  })


  function scrolltop() { //상단으로 이동
    $('.progress-circle').click(function (e) {
      e.preventDefault()

      $('html, body').animate({
        scrollTop: 0
      }, 500)
      return false;
    })

    var offset = 100,
      scroll_top_duration = 700,
      $go_top = $('.top-btn'),
      $thedial = $('.dial'),
      $progress_circle = $('.progress-circle')

    // Initialize the progress dial
    $thedial.knob({
      'min': 0,
      'max': 90,
      'width': 71,
      'height': 71,
      'fgColor': '#CEBDAB',
      'skin': 'tron',
      'thickness': .06,
      'displayInput': false,
      'displayPreview': false,
      'readOnly': true,
    })

    $(window).scroll(function () {
      // Hide or show the progress bar
      // ($(this).scrollTop() > offset) ? $progress_circle.addClass('visible'): $progress_circle.removeClass('visible');
      // Get the window position and set it to a variale
      var s = $(window).scrollTop(),
        d = $(document).height(),
        c = $(window).height();
      scrollPercent = (s / (d - c)) * 100;

      // Bind the window position to the progress dial
      $('.dial').val(scrollPercent).change()
    })
  }
  scrolltop()


  function contents_title() {
    var title = $(".content-title strong")

    if ($(".subvisual.sub-layout1").length > 0) {
      title.addClass("upper")
    }
  }
  contents_title()


  function reservation_label() { //패키지,이벤트 페이지 상단 라벨 탭
    var allBtn = $(".reservation-box-label .all")
    var checkBox = $(".reservation-box-label input[name='category[]']")

    allBtn.click(function () {
      if ($(this).find("input").is(":checked")) {
        checkBox.prop('checked', true);
      } else {
        checkBox.prop('checked', false);
      }

    })

    checkBox.click(function () {
      var total = checkBox.length
      var checked = $(".reservation-box-label input[name='category[]']:checked").length

      if (total != checked) {
        allBtn.find("input").prop("checked", false);
      } else {
        allBtn.find("input").prop("checked", true);
      }

    })

    var cate_btn = $(".reservation-box-btn")

    cate_btn.click(function () {
      // "cate_btn"과 "reservation-box-label" 요소의 "active" 클래스를 토글(toggle)
      cate_btn.toggleClass("active")
      $(".reservation-box-label").toggleClass("active")

      // "cate_btn"의 클래스 상태에 따라 텍스트 변경
      if (cate_btn.hasClass("active")) {
        cate_btn.find("span").html("Categories <em>close</em> <i class='iconoir'></i>")
      } else {
        cate_btn.find("span").html("Categories <em>open</em> <i class='iconoir'></i>")
      }
    });
  }
  reservation_label()


  function reservation_calendar() {
    var calendar_item = $("input[type=text].calendar")
    var calendar_close = $(".calendar-wrap-close")
    var calendar_input = $(".reservation-box-input .calendar")

    calendar_item.click(function () {
      $(this).next().find(".drp-calendar").addClass("active")

      // 모바일때 키패드 안뜨게
      $(this).prop('readonly', false).blur().prop('readonly', true)
    })

    calendar_input.click(function () {
      $(this).closest(".calendar-wrap").find(".daterangepicker").show()
      $(this).prev(".calendar-wrap-close").addClass("active")
    })

    calendar_close.click(function () {
      $(this).removeClass("active")
      $(this).closest(".calendar-wrap").find(".daterangepicker").hide()
    })

    // $(document).on("click", ".calendar-table td", function () {
    //   $(".calendar-wrap-close").removeClass("active");
    // })

    // $(".calendar-table td").click(function () {
    //   $(".calendar-wrap-close").removeClass("active");
    // })

    if ($(".daterangepicker").css("display") == "none") {
      calendar_close.hide()
      console.log('hi')
    }

    var dateRangePicker1 = $('#date1').daterangepicker({
      singleDatePicker: true, //날짜 하루만 선택
      parentEl: "#datepicker1",
      dateFormat: "yyyy-mm-dd",
      autoUpdateInput: true,
      showAfterMonthYear: true,
      autoApply: true,
      alwaysShowCalendars: true,
      minDate: new Date(),
      startDate: new Date(),
      locale: {
        format: 'YYYY-MM-DD',
        daysOfWeek: ['SUN', 'MON', 'TUE', 'WED', 'THU', 'FRI', 'SAT'],
        monthNames: ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12'],
        showDropdowns: true,
      },
      changeMonth: true,
    })

    var dateRangePicker2 = $('#date2').daterangepicker({
      singleDatePicker: true, //날짜 하루만 선택
      parentEl: "#datepicker2",
      dateFormat: "yyyy-mm-dd",
      autoUpdateInput: true,
      showAfterMonthYear: true,
      autoApply: true,
      alwaysShowCalendars: true,
      minDate: new Date(),
      startDate: new Date(),
      locale: {
        format: 'YYYY-MM-DD',
        daysOfWeek: ['SUN', 'MON', 'TUE', 'WED', 'THU', 'FRI', 'SAT'],
        monthNames: ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12'],
        showDropdowns: true,
      },
      changeMonth: true,
    })
  }
  if ($(".reservation-box").length > 0) {
    // reservation_calendar()
  }


  function list_box() {
    var list_box_title = $(".list-box-title")

    list_box_title.click(function (e) {
      e.preventDefault()

      const $this = $(this);
      $this.parent().toggleClass('active').siblings().removeClass('active')
      $this.next().slideToggle().parent().siblings().find('.list-box-txt').slideUp(500)
    })
  }
  list_box()


  function room_slide() {
    const offer_slide = new Swiper(".offer-slide.swiper", {
      slidesPerView: "auto",
      spaceBetween: 20,
      navigation: {
        nextEl: ".offer-slide-wrap .btn-wrap button.next",
        prevEl: ".offer-slide-wrap .btn-wrap button.prev",
      },
      breakpoints: {
        587: {
          slidesPerView: 2,
        },
        768: {
          slidesPerView: 3,
          spaceBetween: 30,
        },
        1024: {
          slidesPerView: 4,
          speed: 1000,
          spaceBetween: 34,
        }
      }
    })
  }
  room_slide()


  function room_infobox() {
    var sns_btn = $(".share")
    var wrap = $(".share-wrap")

    sns_btn.click(function () {
      if ($(this).next("ul").is(":hidden")) {
        wrap.addClass("active")
      } else {
        if (wrap.hasClass("active")) {
          wrap.removeClass("active")
        }
      }
    })


    var url_copy = $(".share-wrap > ul a.url-copy")

    url_copy.on("click", function (e) {
      e.preventDefault()
      // Get the link element's URL
      var currentUrl = window.location.href
      var tempInput = $("<input>")
      $("body").append(tempInput)

      tempInput.val(currentUrl).select()
      document.execCommand("copy")
      tempInput.remove()
      $(this).ui_toast({
        type: 'success',
        'title': __('Copy URL')
      });
      // alert("URL이 복사되었습니다.")

    });

  }
  room_infobox()


  const labelingFunction = () => {
    const container = $('.privacy-list')
    const item = container.find('li')

    const labelClick = () => {
      item.each(function (idx, item) {

        const $this = $(item).find('a')
        const i = idx

        $this.on('click', e => {
          e.preventDefault()

          const target = $('.privacy-contents > ul > li').eq(i)

          if (target.length) {
            // console.log(target[i]);
            $('html,body').animate({
              scrollTop: target.offset().top - 100
            }, 400)
          }
        })
      })
    }
    labelClick()
  }
  labelingFunction()


  function link_tab() {

    var tab = $(".link_tab");
    var tab_li = tab.find(">ul>li");
    var text = "";

    tab_li.each(function () {
      if ($(this).hasClass("active")) {
        text = $(this).find(">a").text();
      }
    });

    tab.prepend("<button class='mlinktab_btn'>" + text + "</button>");

    $(document).on("click", ".mlinktab_btn", function () {
      if ($(this).next("ul").is(":hidden")) {
        $(this).addClass("active");
        $(this).next("ul").stop().slideDown("fast");
      } else {
        $(this).removeClass("active");
        $(this).next("ul").stop().slideUp("fast");
      }
      return false;
    });
  }
  link_tab()


  function hall_slide() {
    const slide = new Swiper(".hall.swiper", {
      slidesPerView: 1,
      navigation: {
        nextEl: ".hall.swiper .arrow button.next",
        prevEl: ".hall.swiper .arrow button.prev",
      },
      pagination: { //페이징 사용자 설정
        el: ".pagination", //페이징 태그 클래스 설정 
        type: 'fraction'
      }
    })
  }
  hall_slide()


  function select_box() { //게시판 셀렉박스 
    if ($('.board-info').length > 0) {
      $('.board-info-search-select select').chosen()
    }
  }
  select_box()


  function share_btn() {

    var share_warp = $(".share-wrap")
    var offset = 100

    $(window).scroll(function () {

      ($(this).scrollTop() > offset) ? share_warp.addClass('visible'): share_warp.removeClass('visible')

      var scrollDistance = $(window).scrollTop()
      var windowHeight = $(window).height() + $("#footer").height()
      var documentHeight = $(document).height()


      if (scrollDistance + windowHeight >= documentHeight) {
        share_warp.addClass("active2");
      } else {
        share_warp.removeClass("active2");
      }
    })
  }
  share_btn()


  function roommap_slide() { //객실 및 연회장 등 이미지 슬라이드 
    const slide = new Swiper(".room-map-slide.swiper", {
      slidesPerView: 1,
      navigation: {
        nextEl: ".room-map-slide button.next",
        prevEl: ".room-map-slide button.prev",
      },
      pagination: { //페이징 사용자 설정
        el: ".pagination", //페이징 태그 클래스 설정 
        type: 'fraction'
      }
    })
  }
  roommap_slide()


  // 게시판 썸네일 슬라이드
  const boardThumbSlide = () => {
    // 기본 변수 정의
    const thumb = $(".board-view-thumb");
    const thumbMain = $(".board-view-thumb-main");
    const thumbImg = thumbMain.find("img");

    thumbImg.each(function () {
      // 이미지 개수 감지
      if ($(this).length > 1) {
        $(this).wrap('<div class="swiper-slide"></div>');
      } else {
        $(this).wrap('<li class="swiper-slide"></li>');
      }

      const thumbImgW = $(this).width();
      const thumbImgH = $(this).height();

      // 가로 이미지일 때 클래스 추가
      if (thumbImgW > thumbImgH) {
        $(this).addClass("full-sizing");
      }
    });

    // 총 슬라이드 수 감지
    const thumbLength = thumbMain.find(".swiper-slide").length;

    // 감지된 슬라이드가 n개 초과 시 아래 슬라이드 스크립트 실행
    if (thumbLength > 1) {

      thumbMain.wrapInner('<ul class="swiper-wrapper"></ul>');

      // 썸네일 리스트, 페이지네이션 생성
      thumb.append(
        "<div class='board-view-thumb-list'></div>" +
        "<div class='board-view-thumb-pagination'></div>"
      );

      // 썸네일 슬라이드 이전, 다음 버튼 생성
      thumbMain.prepend(
        "<button class='board-view-thumb-move-prev'>" +
        "<i class='icon-nav-arrow-left'></i>" +
        "<span class='sr-only'>이전 이미지 보기</span>" +
        "</button>"
      ).append(
        "<button class='board-view-thumb-move-next'>" +
        "<i class='icon-nav-arrow-right'></i>" +
        "<span class='sr-only'>다음 이미지 보기</span>" +
        "</button>"
      );

      // 썸네일 리스트 변수 정의
      const thumbList = $(".board-view-thumb-list");

      // 슬라이드 일정 개수 미만 시 클래스 추가 / 가운데 정렬을 위한 스타일 분기 처리
      if (thumbLength < 8) {
        thumbList.addClass("board-view-thumb-list-center length" + thumbLength);
      }

      // 생성된 썸네일 리스트 영역 안에 html 소스코드 복제
      const swiperWrapper = thumbMain.find('.swiper-wrapper').html();
      thumbList.html("<ul class='swiper-wrapper'>" + swiperWrapper + "</ul>");

      // 복제된 html 소스코드 내에 버튼 추가
      thumbList.find('.swiper-slide').each(function () {
        var imageSrc = $(this).find('img').attr('src');
        var imageButton = '<button type="button"><img src="' + imageSrc + '" alt=""></button>';
        $(this).html(imageButton);
      });

      // 썸네일 리스트 슬라이드 스크립트
      const thumbListSlide = new Swiper(".board-view-thumb-list", {
        slidesPerView: 'auto',
        freeMode: true,
        watchSlidesVisibility: true,
        watchSlidesProgress: true,
        rewind: true,
      });

      // 썸네일 메인 슬라이드 스크립트 + 리스트와 연동하여 동작
      const thumbMainSlide = new Swiper(".board-view-thumb-main", {
        slidesPerView: "auto",
        rewind: true,
        speed: 750,
        thumbs: {
          swiper: thumbListSlide,
        },
        navigation: {
          prevEl: ".board-view-thumb-move-prev",
          nextEl: ".board-view-thumb-move-next",
        },
        on: {
          init: function () {
            $('.board-view-thumb-pagination').html('<strong>1</strong>/' + '<span>' + thumbLength + '</span>');
          },
          slideChange: function () {
            $('.board-view-thumb-pagination strong').html((this.realIndex + 1));
          }
        },
      });

      // 썸네일 리스트의 버튼 클릭 시 해당 이미지로 이동
      const thumbMove = (slideIndex) => {
        thumbMainSlide.slideTo(slideIndex);
      }
      thumbList.find('button').each(function (index) {
        $(this).on('click', function () {
          thumbMove(index);
        });
      });
    } else {
      thumbMain.wrapInner('<div class="swiper-wrapper"></div>');
    }

    // 로드 완료 후 표시되도록
    setTimeout(function () {
      thumb.css("opacity", "1");
    }, 150)
  }
  boardThumbSlide();


  function inroom_modal() {
    var btn = $(".room .btn-wrap .brown")
    var modal = $(".modal.inroom-dining")
    var modal_close = $(".modal-top-close")

    btn.click(function (e) {
      e.preventDefault()

      $("html").addClass("active")
      $(".blind").show().css("z-index", "11")
      modal.show()
    })

    modal_close.click(function () {
      $("html").removeClass("active")
      $(".blind").hide().css("z-index", "1")
      modal.hide()
    })

    // $(".blind").click(function() {
    //   $("html").removeClass("active")
    //   $(this).hide().css("z-index","1")
    //   modal.hide()
    // })
  }
  inroom_modal()


  function room_btn() {
    var btn = $(".room-topinfo .btn-wrap .btn.bk")



    $(window).on("mousewheel scroll load", function () {
      if (btn.length) {
        var viewTop = $(this).scrollTop(),
          viewHeight = $(this).outerHeight(true),
          viewBottom = viewTop + viewHeight;

        $('#footer').each(function () {
          var elementTop = $(this).offset().top + 56,
            elementHeight = $(this).outerHeight(),
            elementBottom = elementTop + elementHeight;

          if (((elementTop <= viewBottom) && (elementBottom >= viewTop))) {
            btn.addClass("active")
          } else {
            btn.removeClass("active")
          }
        });
      }
    });
  }
  room_btn()



  function roomMapPrepare() {
    var btn = $(".room-map .btn-wrap .btn")

    btn.click(function(e) {
      e.preventDefault()

      $(this).ui_toast({
        type: 'warning',
        'title': '도면 준비중입니다.'
      });
    })
  }
  roomMapPrepare()
});