$(function(){
    if ( window.dwmode == 'publish' ) {
        // 최상단 슬라이드
        if ( $(".product-top-slide .swiper-slide").length > 1 ) {
            // 이미지가 2개 이상인 경우에만 슬라이드
            
        }

        new Swiper(".product-banner .swiper-container", {
            loop: true,
            infinite: true,
            pagination: {
                el: ".product-banner .swiper-paging"
            }
        });
    }

    // 구매하기 팝업 이벤트
    $("#product_buy .bar").on('touchstart', function(e){
        var _obj = $(this).closest('.layer-content');
        var objH = _obj.outerHeight(true);
        var sY = e.originalEvent.touches[0].clientY;
        $("html").addClass("lock-scroll");
        $("#product_buy").on('touchmove', function(ev){
            var mY = ev.originalEvent.touches[0].clientY;
            var moveGap = mY - sY;
            if ( moveGap < 0 ) {
                moveGap = 0;
            }
            _obj.css({
                'margin-bottom': `${moveGap * -1}px`,
                'opacity': 1 - ( 0.5 * (moveGap / objH))
            });
        });
        $("#product_buy").on('touchend', function(e){
            $(this).unbind('touchmove');
            $("html").removeClass("lock-scroll");
            var _obj = $(this).find('.layer-content');
            console.log(e.target, _obj.css('opacity'));
            if(0.8 < ($(this).find('.layer-content').css('opacity') * 1).toFixed(1) * 1) {
                _obj.animate({
                    opacity: 1,
                    marginBottom: '0',
                }, 300, function(){ dwLayers['product_buy'].show() })
            } else {
                dwLayers['product_buy'].hide();
                setTimeout(function(){ _obj.removeAttr('style'); }, 500);
                
            }
            $(this).unbind('touchend');
        });
    });

    $(".toggle-price").on('click', function(e){
        e.preventDefault();
        $(this).closest('.price-row').toggleClass('open');
    });

    $("body").on('click', '.info.toggle',function(e){
        $(this).find('i').toggleClass('down');
        $(this).find('.toggle-content').slideToggle();
    })
    
    $(".photo-reviews a").on('click', function(e){
        e.preventDefault();
        $(".photo-review-all").fadeIn();
    });

    
    var photo_viewer_swiper;
    $(".photo-review-all").on('click', '.photo-reviews a', function(e){
        e.preventDefault();
        var startIndex = $(this).index();
        $(".photo-review-all h2").text('상품평 보기');
        $(".photo-review-all .photo-viewer").fadeIn(function(){
            // $(this).css('display', 'flex');
            photo_viewer_swiper = new Swiper('.photo-viewer .swiper-container', {
                initialSlide: startIndex,
                on: {
                    activeIndexChange: function(){
                        console.log("Photo", this);
                        var page = fillZeroNum(this.realIndex + 1);
                        var max = fillZeroNum(this.slides.length);
                        $(".photo-review-all .photo-viewer > span").html('<strong>'+ page +'</strong>/'+max);
                    },
                }
            });
        });
    }).on('click', '.navigate-close', function(e){
        e.preventDefault();
        console.log(photo_viewer_swiper);
        if ( photo_viewer_swiper ) {
            $(".photo-review-all h2").text('포토 상품평 전체보기');
            $(".photo-review-all .photo-viewer").fadeOut(function(){
                photo_viewer_swiper.destroy();
                photo_viewer_swiper = undefined;
            });
        } else {
            $(".photo-review-all").fadeOut();
        }
    });

    // deal counter
    var deal_counter_interval;
    if ( $(".deal-counter").length > 0 ) {
        var lefttime = $(".deal-counter").data('lefttime') * 1 || 0;
        if ( lefttime > 0 ) {
            var min_sec = 60;
            var hour_sec = min_sec * 60
            var day_sec = hour_sec * 24;
            var timer = 0;

            deal_counter_interval = setInterval(function(){
                var time_string = '';
                var left_sec = lefttime - timer;

                if ( left_sec > 0 ) {
                    if ( left_sec > day_sec ) {
                        var day_num = Math.floor(left_sec / day_sec);
                        left_sec -= day_num * day_sec;
            
                        time_string += fillZeroNum(day_num) + '일 ';
                    }
                    if ( left_sec > hour_sec ) {
                        var hour_num = Math.floor(left_sec / hour_sec);
                        left_sec -= hour_num * hour_sec;
            
                        time_string += fillZeroNum(hour_num) + '시간 ';
                    }
                    if ( left_sec > min_sec ) {
                        var min_num = Math.floor(left_sec / min_sec);
                        left_sec -= min_num * min_sec;
            
                        time_string += fillZeroNum(min_num) + '분 ';
                    }
                    if ( left_sec < 60 ) {
                        time_string += fillZeroNum(left_sec) + '초 ';
                    }
                    // console.log("Time", time_string + '남음');
                    $(".deal-counter strong").text(time_string + '남음');
                    timer++;
                } else {
                    clearInterval(deal_counter_interval);
                    // 종료시
                    var endfunction = $(".deal-counter").attr('ontimerended');
                    if ( endfunction ) {
                        eval(endfunction + '();');
                    }
                    hideDealCounter();
                }
            }, 1000);
        }
    } else {
        hideDealCounter();
    }

        
    // Qna
    $(".product-qna .qna-form a").on('click', function(e){
        e.preventDefault();
        $(".write-qna").fadeIn();
    })
    $(".product-qna").on('click', '.qna-lists > li', function(){
        $(this).find('i').toggleClass('down');
        $(this).find('.reply').slideToggle();
    })
    $(".write-qna .navigate-close").on('click', function(e){
        $(".write-qna").fadeOut();
    })

    // plus toast popup
    $(".prod-plus-toast a").on('click', function(e){
        e.preventDefault();
        $(".prod-plus-toast").fadeOut();
    })

    $(".product-detail-btn").on('click',function(){
        $(this).hide().prev().addClass("open");
    });

    $(".product-delivery-info a").on('click',function(e){
        e.preventDefault();
        $(this).parents(".product-delivery-info").toggleClass("open");
    });
    $(".product-sale-many a").on('click',function(e){
        e.preventDefault();
        $(this).parents(".product-sale-many").toggleClass("open");
    });

    $("body").on('click', '.product-view-more > button', function(e){
        e.preventDefault();
        $(this).parent().prev().addClass('open');
    });

    // $(".product-view-more").each(function(){
    //     var prevElem = $(this).prev();
    //     if ( prevElem.height() <= $(window).width() ) {
    //         prevElem.addClass('open');
    //     }
    // })

    // 탭 스크롤
    bindInfoTabs();    

    // 사은품 증정 팝업
    var gift_layer = $('.product-gift-popup');
    
    if(gift_layer && gift_layer.find('.swiper-slide').length <= 1) {
        gift_layer.find('.swiper-paging').hide();
    }
    
    // 포토후기
    var normalSwiper = new Swiper('.normal', {
        slidesPerView: 4,
        spaceBetween: 7,
        pagination: false,
        navigation: {
            nextEl: '.swiper-button-next',
            prevEl: '.swiper-button-prev',
        },
    });

    // 평점비율
    var graph = $(".usage");
    $.each(graph, function() {    
        var usage = $(this).attr("data-usage");
        $(this).children(".usage-value").css({
            "height": + usage +"%",
        });        
    });

    //후기 탭
    $(".js-tb-ctrl a").click(function(){
        var _idx = $(this).index();
        var _div = $(this).parent(".js-tb-ctrl").parent();
        $(this).addClass("ov").siblings("a").removeClass("ov");
        _div.find(".js-tb-cont").eq(_idx).addClass("ov").siblings(".js-tb-cont").removeClass("ov");
        return false;
    });

    //가로 그래프
    $(".graph-bar").each(function() {
        var dataWidth = $(this).data('value');
        $(this).css("width", dataWidth + "%");
    });

    //모달닫기버튼
    $(".modal-footer .modal-close").on("click", function(){
        $(this).parent().parent().parent().hide();
    });

	//포토리뷰전체보기 팝업 열기
	$(".normal .swiper-slide").last().on("click", function(){
		$(".popup-layer").show();
	});

    //포토상품 상세보기,
    // var mainSlider = $('.main-slider');
    // var innerSlider = $('.inner-slider');

    // mainSlider.slick({
    //     slidesToShow: 1,
    //     dots: false,
    //     adaptiveHeight: true //슬라이더 높이를 현재 슬라이드에 맞춤
    // });
    
    // innerSlider.slick({
    //     slidesToShow: 1
    // });

    /*var mainSlider = new Swiper('.main-slider', {
        slidesPerView: 1,
        spaceBetween: 7,
        pagination: false,
        navigation: false
    });*/

	if( $(".inner-slider").length > 0) {		
	    var innerSlider = new Swiper('.inner-slider', {
	        slidesPerView: 1,
	        spaceBetween: 7,
	        pagination: false,
	        navigation: {
	            nextEl: '.swiper-button-next',
	            prevEl: '.swiper-button-prev',
	            disabledClass: 'disabled_swiper_button'
	        },
	        on: {
		      init: function () {
		        const numberOfSlides2 = this.slides.length;
		        console.log(numberOfSlides2);
		        if (this.slides.length <= 1) {
		          document.querySelector('.swiper-button-prev').style.display = "none";
		          document.querySelector('.swiper-button-next').style.display = "none";
		          document.querySelector('.inner-slider').classList.add('swiper-no-swiping');
		        } else {
		          document.querySelector('.swiper-button-prev').style.display = "block";
		          document.querySelector('.swiper-button-next').style.display = "block";
		        }
		      }
		    }
	    });
    }

    // 펑특가 하단 롤링 배너
    // rolling = setInterval(fnRolling, 3000);

})
function bindInfoTabs(elemRoot) {
    if ( !elemRoot ) {
        elemRoot = '';
    }
    
    var $tabBar = $(`${elemRoot} .info-tabs`);
    var $tabClick = $tabBar.find('> a');

    $tabClick.click(function(e) {
        e.preventDefault();

        var activeIndex = $(this).index();
        var scrollTop = $(elemRoot ? elemRoot : window).scrollTop();

        var offsetRect = document.querySelectorAll(`${elemRoot} .info-item`)[activeIndex].getBoundingClientRect();
        var offsetTop = scrollTop + offsetRect.y - $(this).height();
        
        var _dealSelectSlide = $(".deal-select-slide.active");
        if ( _dealSelectSlide.length > 0 ) {
            offsetTop -= _dealSelectSlide.outerHeight();
        }

        // if ( elemRoot ) {
        //     offsetTop -= $(elemRoot).find('.layer-header').outerHeight(true);
        // } else {
        //     offsetTop -= isApp == 'Y' ? 0 : $("header").outerHeight(true);
        // }

        $(this).addClass('ov').siblings().removeClass('ov');

        // $(elemRoot ? elemRoot : 'html,body').stop().animate({scrollTop : offsetTop + 1},500);
        if ( elemRoot ) {
            document.querySelectorAll(elemRoot).scroll({top: offsetTop - 10, behavior: 'smooth'});
        } else {
			if ( isApp == 'Y') {
            	appMessage($(this).attr("id"));
            }else{
				window.scroll({
                top: offsetTop,
                // behavior: 'smooth'
            	});
			}
        }

        setTimeout(function(){
            $("body").addClass('scroll-down').removeClass('scroll-up');
            $tabBar.css('top', 0);

            var _clickedElem = $tabBar.find('a').eq(activeIndex);
            if ( !$tabBar.find('a').eq(activeIndex).hasClass('ov') ) {
                _clickedElem.addClass('ov').siblings().removeClass('ov');
            }
        }, 50);
    });

    // 팝업 아닐때만
    if ( !elemRoot ) {

        $(window).on('scroll resize', function() {

            var _dealSelectSlide = $(".deal-select-slide.active");
            var dealSelectHeight = 0;
            if ( _dealSelectSlide.length > 0 ) {
                dealSelectHeight = _dealSelectSlide.outerHeight();
            }

            var _tabPosElem = document.querySelector(`${elemRoot} .product-view-info`);
            if ( !_tabPosElem ) {
                return;
            }
            var tabPosRect = _tabPosElem.getBoundingClientRect();
            var tabPos = tabPosRect.y;
            
            var topPos = dealSelectHeight;

            if ( elemRoot ) {
                topPos += $(elemRoot).find('.layer-header').outerHeight(true);
            } else {
                topPos += isApp == 'Y' ? 0 : $("header").outerHeight();
            }

            if ( topPos >= tabPos ) {
                $tabBar.addClass('fixed').css('top', topPos);
            }else{
                $tabBar.removeClass('fixed').removeAttr('style');
            }

            // document.querySelectorAll(`${elemRoot} .info-item`).forEach((elem, i) => {
            //     var elemRect = elem.getBoundingClientRect();

            //     if ( elemRect.y < topPos ) {
            //         $tabClick.eq(i).addClass('ov').siblings().removeClass('ov');
            //     }
            // });
        });
    }

}

function hideDealCounter(){
    $(".deal-counter").hide();
}

function fillZeroNum(num){
    return num < 10 ? '0' + num : num;
}

if (document.getElementById("product_view") && document.getElementById("myModal1")) {
    // Get the modal
    var modal1 = document.getElementById("myModal1"); //최신순
    var modal2 = document.getElementById("myModal2"); //전체보기
    //var modal3 = document.getElementById("myModal3"); //옵션전체보기
    // Get the button that opens the modal
    var btn1 = document.getElementById("myBtn1");
    var btn2 = document.getElementById("myBtn2");
    //var btn3 = document.getElementById("myBtn3");
    // Get the <span> element that closes the modal
    var span1 = document.getElementsByClassName("close1")[0];
    var span2 = document.getElementsByClassName("close2")[0];
    //var span3 = document.getElementsByClassName("close3")[0];
    // When the user clicks the button, open the modal 
    btn1.onclick = function() {
		if ( isApp == 'Y') {
			appMessage('sort_button_clicked');
		} else {
			modal1.style.display = "block";
		}
    }
    btn2.onclick = function() {
		if ( isApp == 'Y') {
			appMessage('all_button_clicked');
		} else {
			modal2.style.display = "block";
		}
    }
    /*btn3.onclick = function() {
        if ( isApp == 'Y') {
			appMessage('sort2_button_clicked');
		} else {
			modal3.style.display = "block";
		}
    }*/
    // When the user clicks on <span> (x), close the modal
    span1.onclick = function() {
        modal1.style.display = "none";
    }
    span2.onclick = function() {
        modal2.style.display = "none";
    }
    /*span3.onclick = function() {
        modal3.style.display = "none";
    }*/
    // When the user clicks anywhere outside of the modal, close it
    window.onclick = function(event) {
        if (event.target == modal1) {
            modal1.style.display = "none";
        }
        if (event.target == modal2) {
            modal2.style.display = "none";
        }
        /*if (event.target == modal3) {
            modal3.style.display = "none";
        }*/
    }
} else if(document.getElementById("seven") && document.getElementById("myModal1")) {
    // Get the modal
    var modal1 = document.getElementById("myModal1"); //최신순
    // Get the button that opens the modal
    var btn1 = document.getElementById("myBtn1");
    // Get the <span> element that closes the modal
    var span1 = document.getElementsByClassName("close1")[0];
    // When the user clicks the button, open the modal 
    btn1.onclick = function() {
        modal1.style.display = "block";
    }
    // When the user clicks on <span> (x), close the modal
    span1.onclick = function() {
        modal1.style.display = "none";
    }
    // When the user clicks anywhere outside of the modal, close it
    window.onclick = function(event) {
        if (event.target == modal1) {
            modal1.style.display = "none";
        }
    }
}
if (document.getElementById("lounge") && document.getElementById("myModal1")) {
    // Get the modal
    var modal1 = document.getElementById("myModal1"); //최신순
    var modal2 = document.getElementById("myModal2"); //전체보기
    var modal3 = document.getElementById("myModal3"); //옵션전체보기
    // Get the button that opens the modal
    var btn1 = document.getElementById("myBtn1");
    var btn2 = document.getElementById("myBtn2");
    var btn3 = document.getElementById("myBtn3");
    // Get the <span> element that closes the modal
    var span1 = document.getElementsByClassName("close1")[0];
    var span2 = document.getElementsByClassName("close2")[0];
    var span3 = document.getElementsByClassName("close3")[0];
    // When the user clicks the button, open the modal 
    btn1.onclick = function() {
		if ( isApp == 'Y') {
			appMessage('sort_button_clicked');
		} else {
			modal1.style.display = "block";
		}
    }
    btn2.onclick = function() {
		if ( isApp == 'Y') {
			appMessage('all_button_clicked');
		} else {
			modal2.style.display = "block";
		}
    }
    btn3.onclick = function() {
        if ( isApp == 'Y') {
			appMessage('sort2_button_clicked');
		} else {
			modal3.style.display = "block";
		}
    }
    // When the user clicks on <span> (x), close the modal
    span1.onclick = function() {
        modal1.style.display = "none";
    }
    span2.onclick = function() {
        modal2.style.display = "none";
    }
    span3.onclick = function() {
        modal3.style.display = "none";
    }
    // When the user clicks anywhere outside of the modal, close it
    window.onclick = function(event) {
        if (event.target == modal1) {
            modal1.style.display = "none";
        }
        if (event.target == modal2) {
            modal2.style.display = "none";
        }
        if (event.target == modal3) {
            modal3.style.display = "none";
        }
    }
}
if (document.getElementById("collection") && document.getElementById("myModal1")) {
    // Get the modal
    var modal1 = document.getElementById("myModal1"); //최신순
    var modal2 = document.getElementById("myModal2"); //전체보기
    var modal3 = document.getElementById("myModal3"); //옵션전체보기
    // Get the button that opens the modal
    var btn1 = document.getElementById("myBtn1");
    var btn2 = document.getElementById("myBtn2");
    var btn3 = document.getElementById("myBtn3");
    // Get the <span> element that closes the modal
    var span1 = document.getElementsByClassName("close1")[0];
    var span2 = document.getElementsByClassName("close2")[0];
    var span3 = document.getElementsByClassName("close3")[0];
    // When the user clicks the button, open the modal 
    btn1.onclick = function() {
		if ( isApp == 'Y') {
			appMessage('sort_button_clicked');
		} else {
			modal1.style.display = "block";
		}
    }
    btn2.onclick = function() {
		if ( isApp == 'Y') {
			appMessage('all_button_clicked');
		} else {
			modal2.style.display = "block";
		}
    }
    btn3.onclick = function() {
        if ( isApp == 'Y') {
			appMessage('sort2_button_clicked');
		} else {
			modal3.style.display = "block";
		}
    }
    // When the user clicks on <span> (x), close the modal
    span1.onclick = function() {
        modal1.style.display = "none";
    }
    span2.onclick = function() {
        modal2.style.display = "none";
    }
    span3.onclick = function() {
        modal3.style.display = "none";
    }
    // When the user clicks anywhere outside of the modal, close it
    window.onclick = function(event) {
        if (event.target == modal1) {
            modal1.style.display = "none";
        }
        if (event.target == modal2) {
            modal2.style.display = "none";
        }
        if (event.target == modal3) {
            modal3.style.display = "none";
        }
    }
}

// 외부영역 클릭 시 팝업 닫기
$(document).click(function (e){
    var LayerPopup = $(".modal");
    if(LayerPopup.has(e.target).length === 0){
      LayerPopup.removeClass("show");
    }
});

// auto width 스와이퍼 
$.fn.autoWidthSwiper = function () {
    var swiperArr = [];
    return this.each(function (i) {
        swiperArr[i] = new Swiper('.view-auto-swiper[data-swiper-index="' + i + '"]', {
        slidesPerView: "auto",
        spaceBetween: 10,
        freeMode: true,
        a11y: false,
        observer: true,	
  		observeParents: true,	
        });
    });
}

// ui.js auto width 스와이퍼 
$('.view-auto-swiper').autoWidthSwiper();

// 추천 페어링 선택
var checked = $('.tjm-c .suitable .option-check input');

if( checked.is(':checked') == false ) {
    $('.tjm-c .suitable figure').removeClass('on');		
} else {
    $('.tjm-c .suitable figure').addClass('on');
}
checked.on('click', function(){
    if( $(this).is(':checked') == false ) {
        $(this).parent().parent().find('figure').removeClass('on');			
    } else {
        $(this).parent().parent().find('figure').addClass('on');
    }
});

$(window).on("scroll", function(){
    if($(document).scrollTop() > 140) {
        $(".total-quantity").addClass("open");
    } else {
        $(".total-quantity").removeClass("open");
    }	
});

function fnRolling(){
	var _this = $(".total-quantity ul");
	var _first = $(".total-quantity li:nth-child(-n+1)");
    var _height = $(".total-quantity").outerHeight();
    
	_this.append(_first.clone());

	_this.animate({marginTop: "0"}, 500, "swing", function() {
		_this.css("margin-top", _height);
        _first.remove();
	});
}

// lottie.js - json 불러오기
// 사용법 - https://velog.io/@ooo3289/lottie.js-htmljs-%EC%82%AC%EC%9A%A9%EB%B2%95-%EC%8B%9C%EC%9E%91%ED%95%98%EA%B8%B0
var lottieAni = bodymovin.loadAnimation({
    container: document.getElementById('lottie-pop'), // 필수, 애니메이션 들어가는 곳 
    path: 'https://lottie.host/ca032ae2-7c59-42f6-801f-edb214a73406/TgcvzOhcPY.json', // 필수(url 또는 json파일 다운로드 경로)
    renderer: 'svg', // 필수
    loop: false, // Optional
    autoplay: false // Optional
});

// 펑!특가 애니메이션
function countdownBombing() {    
    const countdownElement = document.querySelector(".countdown-wrap");
    const bombElement = document.querySelector(".bomb");
    const fireworkElement = document.querySelector(".firework");

    countdownElement.classList.add("show");
    bombElement.classList.add("ani");
    lottieAni.stop();
    
    setTimeout(() => {
        fireworkElement.classList.add("show");
        lottieAni.play();
        setTimeout(() => {
            countdownElement.classList.remove("show");
        }, 1000);
    }, 2000);
}