/** layout.js
 *  동원몰 공통 스크립트
*/

window.swiper = {};
window.scrollDirection = 'up';
window.dwmode = '';

// 숫자앞에 0 채워넣기
String.prototype.fillZeroNumber = function(length) {
    var str_arr = this.split('').reverse();
    var str_len = this.length;
    if ( !length ) {
        length = 1;
    }

    for ( var i = 1; i < length; i++ ) {
        if ( i >= str_len ) {
            str_arr.push('0');
        }
    } 

    return str_arr.reverse().join('');
}

Number.prototype.fillZeroNumber = function(length) {
    return this.toString().fillZeroNumber(length);
}

// 숫자포메팅 (, 넣기)
Number.prototype.format = function(){
    if(this==0) return 0;
 
    var reg = /(^[+-]?\d+)(\d{3})/;
    var n = (this + '');
 
    while (reg.test(n)) n = n.replace(reg, '$1' + ',' + '$2');
 
    return n;
};
 
String.prototype.format = function(){
    var num = parseFloat(this);
    if( isNaN(num) ) return "0";
 
    return num.format();
};



$(function(){

    DongwonMall.init();
    
    // ajax 관리
    $(document)
    .ajaxStart(function(){
        $("body").addClass('ajax-wait');
        window.ajaxWait = true;
    })
    .ajaxStop(function(){
        $("body").removeClass('ajax-wait');
        window.ajaxWait = false;
    });

    $('.ft-toggle').click(function(){
        var _this = $(this);
        var _cont = _this.siblings('p');

        _this.find('i').toggleClass('down');
        
        if(_cont.is(':visible')) {

            _cont.slideUp();

        } else {

            _cont.slideDown();

        }
    });

    //toggle infomation - ex) 유의사항
    $('.toggle-info .tit').click(function(){
        var $cont = $(this).parent('.toggle-info').find('.cont');
        $(this).find('i').toggleClass('down');
        
        if($cont.hasClass('on')) {
            $(this).removeClass('on');
            $cont.removeClass('on').slideUp();
        } else {
            $(this).addClass('on');
            $cont.addClass('on').slideDown();
        }
    });
    
    //찜버튼 
    $('.like-btn').click(function(){
        if($(this).hasClass('on')) {
            $(this).removeClass('on');
            $(this).find('img').attr('src', '../images/icons/common/icon_like_on.png')
        } else {
            $(this).addClass('on');
            $(this).find('img').attr('src', '../images/icons/common/icon_like.png')
        }
    });

    //카테고리 js 
    $(".category-icons a").on('click', function(e){
        var _href = $(this).attr('href');
        if ( _href && _href == '#' ) {
            e.preventDefault();
            $(this).addClass('ov').siblings().removeClass('ov');
        }
    });

    //cate top menu
    $('.cate-top-menu li').on('click', function(){
        $(this).addClass('on').siblings().removeClass('on');
        $("html, body").animate({ scrollTop: 0 }, "slow");  
        if ( $(".cate-top-menu ul").hasClass('open') ) {
            $(".cate-list-btn").trigger('click');
        } else {
            autoCateTopScroll();
        }
    });

    
    
    //2depth
    if($('.cate-top-menu ul li').length < 5) {
        $('.cate-top-menu .cate-bg').hide();
    }

    $('.cate-depth2 .cate-list li').on('click', function(){
        $(this).addClass('on').siblings().removeClass('on');
    });
    
    $('.cate-list-btn').on('click', function(){
        var $cont = $(this).closest('.cate-top-menu');
        var $list = $(this).siblings('.inner').find('ul');
        var _bg = `<div class="popup-bg"></div>`;

        $(this).find('i').toggleClass('down');

        if($list.hasClass('open')) {
            $list.removeClass('open');
            $('main').find('.popup-bg').remove();
          
            $cont.find('.cate-bg').show();
            setTimeout(function(){
                autoCateTopScroll();
            }, 50);
        } else {
            $list.addClass('open');
            $('main').append(_bg);
            $cont.find('.cate-bg').hide();
        }
    });

    //category-nav
    $('.category-nav .category-gnb .gnb > a').on('click',function(){
        $(this).parent('.category-gnb .gnb').toggleClass('on');
        $(this).siblings('.category-lnb').stop().toggle();
        $(this).parent('.category-gnb .gnb').siblings('.gnb').removeClass('on');
        $(this).parent('.category-gnb .gnb').siblings('.gnb').find('.category-lnb').stop().hide();
    });

    $('.category-wrapper .close-btn').on('click',function(){
        $(this).parents('.category-wrapper').hide();
    });

    //category-depth3
    $('.category-depth3 li').on('click', function(){
        $(this).addClass('active').siblings().removeClass('active');
    });

    //category-depth3 더보기+/접기-
    $('.more-btn').find('button').on('click',function(){
        $(this).parent('.more-btn').siblings('ul').toggleClass('on');
        $(this).parent('.more-btn').toggleClass('on');
        if($(this).parent('.more-btn').hasClass('on')){
            $(this).find('span').text('접기');
            $(this).find('i').removeClass('icon-plus').addClass('icon-minus');
        }else{
            $(this).find('span').text('더보기');
            $(this).find('i').addClass('icon-plus').removeClass('icon-minus');
        }
    });

    

    // auto sibling menu
    $("body").on('click', '[data-index-changed] a', function(e){
        e.preventDefault();
        $(this).addClass('on').siblings().removeClass('on');
        var func = $(this).parent().data('index-changed');
        if ( func ) {
            eval(func + '('+ $(this).index() +')');
        }
    })

    

    // 레이어 팝업
    $(".layer-popup").each(function(){
        if ( $(this).hasClass('ready') ) return;
        initLayerPopup(this);
        var _parent = $(this);

        // 이벤트
        _parent.on('click', function(e){
            var click_target = $(e.target);
            if ( 
                click_target.hasClass('layer-popup') || // 클릭 대상이 자신인 경우
                click_target.hasClass('btn-close') || // 닫기버튼
                click_target.hasClass('layer-cancel') || // 취소버튼
                click_target.hasClass('layer-confirm') // 확인버튼
            ) {
                e.preventDefault();

                if ( 
                    click_target.hasClass('layer-cancel') &&
                    _parent.data('event-cancel')
                ) {
                    eval(_parent.data('event-cancel') + '()');
                }

                if ( 
                    click_target.hasClass('layer-confirm') &&
                    _parent.data('event-confirm')
                ) {
                    eval(_parent.data('event-confirm') + '()');
                }

                _parent.removeClass('show');

                $("html").removeClass('lock-scroll');

		appMessage('layer-hide');
            }

        });
    });

   
    $('body')
    // 제품 목록 클릭
    .on('click', '.product-list', function(e){
        var wrapInLink = $(e.target).closest('a').length > 0 || e.target.tagName == 'A';
        var pbcode = $(this).data('pbcode');
        var search_term = $(this).data('searchterm');
        var isEmployee = $(this).data('employee');
        if ( wrapInLink ) {
            // 링크 진행
        } else if ( pbcode ) {
            e.preventDefault();
            if ( isEmployee == 'Y' ) {
                // 임직원 몰이면..
                var _form = document.createElement('form');
                _form.action = `/employee/detail.do?productId=${pbcode}`;
                _form.method = "POST";
                _form.innerHTML = '<input type="hidden" name="EMPLOYEE_MALL_YN" value="Y" />'

                document.body.appendChild(_form);

                _form.submit();
                
            } else {
                // 후기 개수 클릭 시, 후기로 이동 
                if($(e.target).parent().hasClass('product-grade') || $(e.target).hasClass('product-grade')){
                    $(location).attr("href", `/product/detail_info_review.do?productId=${pbcode}`);
                } else {
                    // 제품상세 이동
                    if ( typeof goPrDetail == 'function' ) {
                        if ( search_term ) {
                            goPrDetail(pbcode, '', '', search_term);
                        } else {
                            goPrDetail(pbcode);
                        }
                    } else {
                        window.location.href = `/product/detail.do?productId=${pbcode}`;
                    }
                }
            }
        }
    });
    
    //찜버튼 
    $('.like-btn').click(function(){
        if($(this).hasClass('on')) {
            $(this).removeClass('on');
            $(this).find('img').attr('src', '../images/icons/common/icon_like_on.png')
        } else {
            $(this).addClass('on');
            $(this).find('img').attr('src', '../images/icons/common/icon_like.png')
        }
    });

    // 푸터 토글
    $(".important-tit").on("click",function(e){
        if ( $(this).closest('label').length > 0 ) {
            // form 요소는 동작안함
            return;
        }
        $(this).toggleClass("on").siblings(".important-content").slideToggle();        
    });

    // .dw-tab-wrapper
    $("body").on('click', '.dw-tab-controller a', function(e){
        var _this = $(this);
        var _wrapper = _this.closest('.dw-tab-wrapper');

        if ( _wrapper.hasClass('style-only') ) {
            // nothing to do...
        } else {
            if ( !_wrapper.hasClass('use-href') ) {
                e.preventDefault();
            }
            var tab_index = _this.index();
            if ( !_this.hasClass('ov') ) {
                _this.addClass('ov').siblings().removeClass('ov');
                _wrapper.find('.dw-tab-content').hide().eq(tab_index).show();
            }

            var changeFunc = _wrapper.attr('ontabchange');
            if ( changeFunc ) {
                try{
                    eval(`${changeFunc}(${tab_index})`);
                }catch(e){

                }
            }
        }
    });
    $(".dw-tab-wrapper").each(function(){
        if ( !$(this).hasClass('style-only') ) {
            let idx = Number($(this).data('index'));
            var hash = window.location.hash;
            let _tabControllerItem = $(this).find(`.dw-tab-controller [href="${hash}"]`);
            if (hash && _tabControllerItem.length > 0) {
                idx = _tabControllerItem.index();
            }
            $(this).find('.dw-tab-controller a').eq(idx ? idx : 0).trigger('click');
        }
    });
    /*
    // 검색에서 리로드 문제 발생 - 일단 주석 처리
    // $(window).on('hashchange', function(){
    //     var currentHash = location.hash;
    //     let _tabControllerItem = $(`.dw-tab-controller [href="${currentHash}"]`);
    //     if(currentHash !== '#enp_mbris') {
    //         if (currentHash && _tabControllerItem.length > 0) {
    //             _tabControllerItem.trigger('click');
    //         } else {
    //             $('.dw-tab-controller a').eq(0).trigger('click');
    //         }
    //     }
    // });
    */
    // function tabHashAction(){

    // }

    //대량견적문의 상품선택
    /*$(".biz-products .product-area a").on('click', function(e){
        e.preventDefault();
        if ( $(this).hasClass('selected') ) {
            $(this).text('상품선택').toggleClass('selected').prepend('<i class="icon-check-b"></i>');
        } else {
            $(this).text('선택완료').toggleClass('selected');
        }
    });*/

    $('.category-icons a').click(function(e){
        e.preventDefault();
        $(this).closest('.category-content').find('.cate-depth2').show();
        if($(this).closest('.category-content').find('.cate-depth2').is(':visible')) {
            $('.category-select').addClass('mg0');
        } else {
            $('.category-select').removeClass('mg0');
        }
        
        //TODO : data-name 카테고리 클릭시 맞는 depth2 나오게하기 - 카테고리 공통 작업
    });


    $("body").on('click', '.toggle-header', function(e){
        e.preventDefault();
        var _wrapper = $(this).closest('.toggle-content');

        $(this).find('i').toggleClass('down');
        _wrapper.toggleClass('show');

        _wrapper.find('.toggle-body').slideToggle();
        
        if ( _wrapper.hasClass('group') ) {
            _wrapper.siblings().removeClass('open');
        }

        if(_wrapper.hasClass('show') && !_wrapper.hasClass('keep-right')) {
            _wrapper.find('.toggle-header .right span').hide();
        } else {
            _wrapper.find('.toggle-header .right span').show();
        }

        if ( _wrapper.attr('onchange') ) {
            eval(_wrapper.attr('onchange') + '('+ _wrapper.hasClass('open') +')');
        }

        if ( _wrapper.hasClass('open') && _wrapper.hasClass('scroll-me') ) {
            setTimeout(function(){
                // $("html, body").animate({scrollTop: _wrapper.offset().top - $("header").height()});
                window.scroll({
                    top: _wrapper.offset().top - $("header").height() - 10,
                    behavior: 'smooth'
                });
            }, 500);
        }
    })    
    
    //gnc 체크박스만 따로
    // $("body").on('click', '.toggle-content .right', function(e){ 
    //     var _content = $(this).closest('.toggle-content').find('.toggle-body');

    //     _content.slideToggle();   
    //     $(this).find('i').toggleClass('down'); 
    // });

	//imageMapResizer
    $("map").imageMapResize();    
});

// 동원몰 통합 스크립트
var DongwonMall = (function(){

    var isElements = function(elem) {
        return $(elem).length > 0 ? true : false;
    }

    var mergeRootElem = function(elem, root) {
        if ( !root ) {
            root = 'main';
        }

        return `${root} ${elem}`;
    }

    return {
        on: {
            afterInit: function(){},
        },
        init: function(){

            var _this = this;

            // 동원몰 모드.
            var dwmode = /(localhost|127\.0\.0\.1)/.test(location.hostname) ? 'publish' : 'dwmall';
            window.dwmode = dwmode;
            $("body").addClass(dwmode);

            var before_scroll_top = 0;
            var last_header_top = 0;
            $(window).on('scroll', function(){

                var sT = $(this).scrollTop();

                if ( sT < 10 ) {
                    // 스크롤이 10 미만일때는 계속 up ( 아이폰 바운스 )
                    window.scrollDirection = 'up';
                    $("body").addClass('scroll-up').removeClass('scroll-down');
                } else if ( sT > before_scroll_top && window.scrollDirection != 'down' ) {
                    // down
                    window.scrollDirection = 'down';
                    $("body").addClass('scroll-down').removeClass('scroll-up');
                } else if ( sT < before_scroll_top && window.scrollDirection != 'up' ) {
                    // up
                    window.scrollDirection = 'up';
                    $("body").addClass('scroll-up').removeClass('scroll-down');
                }

                before_scroll_top = sT;

                // 스크롤탑 버튼
                if ( $("main").outerHeight() > $(this).height() ) {
                    // 스크롤이 있는 경우
                    if ( window.scrollDirection == 'up' && sT > 140 ) {
                        $("body").addClass('scroll-upable');
                    } else {
                        $("body").removeClass('scroll-upable');
                    }

                    if ( $(".bottom-tab").is(":visible")) {
                        $(".btn-to-top").css('margin-bottom', $(".bottom-tab").height());
                    } else {
                        $(".btn-to-top").removeAttr('style');
                    }

                    if($('.btn.fix').is(':visible')) {
                        $(".btn-to-top").css('margin-bottom', $(".btn.fix").height());
                    }
                }

            });

            // 탑 버튼 강제삽입
            $("body").append(`
                <a href="#" class="btn-to-top box-36 round">
                    <i class="icon icon-arrow-top"></i>
                </a>
            `);

            $(".btn-to-top").on('click', function(e){
                e.preventDefault();
                window.scroll({
                    top: 0,
                    behavior: 'smooth'
                })
            })

            // 별점 스크립트 적용
            if ( isElements('.star-rating') ) {
                this.bindStarRating();
            }

            // 폼 스크립트 적용
            if ( isElements('.dw-form') ) {
                this.bindFormScript();
            }

            // 스와이퍼 적용
            if ( isElements('.swiper-container.auto-bind') ) {
                this.bindAutoSwiper();
            }

            this.on.afterInit();

            this.mutationObserver('body', {
                inserted: function(){
                    _this.bindStarRating();
                    _this.bindAutoSwiper();
                    _this.bindFormScript();
                }
            });
        },
        mutationObserver: function(root_selector, option = {}) {
            // 변경을 감지할 노드 선택
            const targetNode = document.querySelector(root_selector);
            // 감지 옵션 (감지할 변경)
            const config = { childList: true, subtree: true };

            var callDefaultActions;

            // 변경 감지 시 실행할 콜백 함수
            const mcallback = (mutationList, observer) => {
                for (const mutation of mutationList) {
                    if (mutation.type === "childList") {
                        if ( typeof option['inserted'] == 'function' || typeof option['deleted'] == 'function' || typeof option['modified'] == 'function') {
                            //console.log("자식 노드가 추가되거나 제거됐습니다.");
                            if ( callDefaultActions ) {
                                clearTimeout(callDefaultActions);
                                callDefaultActions = null;
                            }

                            callDefaultActions = setTimeout(function(){
                                if ( typeof option['inserted'] == 'function' ) {
                                    option['inserted']();
                                }
                                if ( typeof option['deleted'] == 'function' ) {
                                    option['deleted']();
                                }
                                if ( typeof option['modified'] == 'function' ) {
                                    option['modified']();
                                }
                            }, 500);

                        }
                    }
                }
            };
            // 콜백 함수에 연결된 감지기 인스턴스 생성
            const observer = new MutationObserver(mcallback);
            // 설정한 변경의 감지 시작
            observer.observe(targetNode, config);
        },
        bindAutoSwiper: function(){
            // auto bind swiper
            $(".swiper-container.auto-bind").each(function(e){
                if ( $(this).data('binded') ) {
                    return;
                }

                var options = {
                    slidesPerView: 1,
                    freeMode: false,
                    spaceBetween: 0,
                    slidesOffsetAfter: 0,
                    slidesOffsetBefore: 0,
                    autoHeight : true, //자동높이 사용여부
                    on: {}
                };

                if ( $(this).data('slides-view') ) {
                    if ( $(this).data('slides-view') > 0 ) {
                        options.slidesPerView = $(this).data('slides-view') * 1;
                    } else {
                        options.slidesPerView = $(this).data('slides-view');
                    }
                }

                if ( $(this).data('freemode') ) {
                    options.freeMode = $(this).data('freemode');
                }

                if ( $(this).data('slide-between') ) {
                    options.spaceBetween = $(this).data('slide-between');
                    options.slidesOffsetAfter = $(this).data('slide-between');
                    options.slidesOffsetBefore = $(this).data('slide-between');
                }

                var id = $(this).data('id');

                if ( !id ) {
                    id = $.now();
                    $(this).attr('data-id', id);
                }

                window.swiper[id] = new Swiper('[data-id="'+ id +'"]', options);
                $(this).attr('data-binded', "1");
            });
        },
        bindFormScript: function(root) {

            var _elm = root ? $(root + ' .dw-form') : $(".dw-form");
            
            _elm.each(function(){
                var _this = $(this);
                var _flag = false;
                if ( _this.data('binded') ) {
                    return;
                }

                var printUI = !(_this.hasClass('no-ui'));
                var focus = !(_this.hasClass('no-focus'));

                if ( _this.hasClass('text') ) {

                    if ( printUI ) {

                        _this.find('a').remove();

                        if ( _this.hasClass('disabled') || _this.find('input').prop('disabled') || _this.find('input').prop('readonly') ) {
                            return;
                        }

                        var isPassword = _this.find('input').attr('type') == 'password';
                        _this.append(`
                            <div class="form-ui">
                                <a class="type-reset"><i class="icon icon-close-circle box-32"></i></a>
                                ${isPassword ? '<a class="type-toggle"><i class="icon icon-eye box-32"></i></a>' : ''}
                                ${_this.hasClass('search') ? '<a href="#" class="inner-search"><i class="icon icon-search-default box-32"></i></a>' : ''}
                            </div>
                        `);
                
                        _this.on('click', '.type-toggle', function(e){
                            e.preventDefault();
                            var input_elem = $(this).closest('.dw-form').find("input");
                
                            if ( input_elem.attr('type') == "text" ) {
                                input_elem.attr('type', 'password');
                                $(this).find('i').removeClass('on');
                            } else {
                                input_elem.attr('type', 'text');
                                $(this).find('i').addClass('on');
                            }
                        })
                
                        _this.on('click', '.type-reset', function(e){
                            e.preventDefault();
                            _this.find('input').val('').trigger('keyup').focus();
                            _this.find('input').removeClass('on');
                        });

                        _this.on('click', '.inner-search', function(e){
                            e.preventDefault();
                            var func = _this.attr('onsearch');
                            if ( func ) {
                                eval(`${func}('${_this.find('input').val()}')`);
                            }
                        });
                    }

                     /*
                        input focus in/out effect 
                        class="no-focus" 가 있으면 실행 X
                     */
                     if( focus ) {
                        _this.find('input').on('focus', function(){
                            $(this).closest('.dw-form').addClass('on').removeClass('no');
                        });

                        _this.find('input').on('blur', function(){
                            $(this).closest('.dw-form').removeClass('on');
                        });
                    }

                } 
                if (_this.hasClass('select') ) {
                    _this.find('select').on('change', function(){
                        var val = $(this).val();
                        var txt = $(this).find('option[value="'+ val +'"]').text();
                        //hide option
                        $(this).find('option').hide();
                        $(this).next('span').text(txt);
                    }).trigger('change');
    
                    if ( _this.hasClass('native') ) {
                        // 네이티브 Select 이벤트 
                    } else {
                        
                        _this.on('click', function(e){
                            e.preventDefault();
                            var _select = $(this).find('select');
                            var _installment = $(this).find('installment');
                            var installmentFleg = _installment.prevObject[0].className.includes('installment');
                            var def = _select.val();
                            var _title = $(this).data('title');
                            var data = _select.find('option').map(function(){
                                return {
                                    name: $(this).text(),
                                    value: $(this).attr('value'),
                                    selected: def == $(this).attr('value'),
                                    contentTitle: _title
                                }
                            }).get();

                            if(isApp == "Y" && _select.attr("id") == "productoption"){
                                
                                var appData = {"TYPE" : "세트구성품", "SETLIST" : data};
                                if (window.webkit != undefined) {//iOS
                                     if (window.webkit.messageHandlers.appInterface != undefined) {
                                         window.webkit.messageHandlers.appInterface.postMessage(JSON.stringify(appData));
                                     }
                                 }
                                else if (window.appInterface != undefined) {//Android
                                     window.appInterface.postMessage(JSON.stringify(appData));
                                 }
                            }else{
                                new LayerPopup().select({
                                    data: data,
                                    selected: function(sel) {
                                        _select.val(sel.value).trigger('change');
                                    }, 
                                    canceled: function() {
                                        // console.log("can");
                                    },
                               		installment :installmentFleg
                                });
                            }

                        });
                    }
                } 
                if ( _this.hasClass('area') || _this.hasClass('max')) {
                    var _element = _this.find('textarea, input');
                    var limit = _element.attr('maxlength');
                    var _placeholder = _this.find('.long-placeholder');
                    var _counter = _this.find('.limit-counter');

                    if ( _placeholder.length > 0 || _counter.length > 0 ) {

                        
                        _element.on('keyup', function(){
                            var txt = $(this).val();
                            
                            if ( _placeholder.length > 0 ) {
                                if ( txt.length > 0 ) {
                                    _placeholder.hide();
                                } else {
                                    _placeholder.show();
                                }
                            }
                            
                            if ( limit ) {
                                var _limit = limit.format();
                                
                                if ( _counter.length > 0 && limit ) {
                                    _counter.text(txt.length + ' / ' + _limit + ' 자');
                                }
                            }
                        }).trigger('keyup');
                    }
                }

                _this.attr('data-binded', '1');
            });

            // 전체 체크
            $(".dw-form-agree").each(function(){
                var _agree_form = $(this);
                var max_agree_item = _agree_form.find('input[type=checkbox]').filter(function(){
                    return !$(this).hasClass('agree-all');
                }).length;
                console.log(max_agree_item);
                _agree_form.find('input[type=checkbox]').on('change', function(){
                    if ( $(this).hasClass('agree-all') ){
                        if ( $(this).is(":checked") ) {
                            _agree_form.find('input[type=checkbox]').prop('checked', true);
                        } else {
                            _agree_form.find('input[type=checkbox]').prop('checked', false);
                        }
                    } else {
                        var active_agree_length = _agree_form.find('input[type=checkbox]:checked').filter(function(){
                            return !$(this).hasClass('agree-all');
                        }).length;
                        if(active_agree_length == max_agree_item) {
                            _agree_form.find('.agree-all').prop('checked', true);
                        } else {
                            _agree_form.find('.agree-all').prop('checked', false);
                        }
                    }
                });
            });
        },
        bindStarRating: function(elem) {
            if ( !elem ) {
                elem = "body";
            }
            var starRatingWords = [
                "별점을 선택해주세요",
                "별로예요",
                "그저 그래요",
                "괜찮아요",
                "좋아요",
                "최고예요",
            ];

            $(`${elem} .star-rating`).each(function(){
                if ( $(this).hasClass('binded') ) {
                    // 이미 적용된 별점이 있으면 스킵
                    return 
                }
                // if ( $(this).find('.stars').children().length > 0 ) {
                //     return;
                // }

                var v = $(this).find('input').val();
                var size = $(this).data('size');
                if ( !size ) size = 16;
                
                // 강제 기본값 설정
                $(this).find('input').attr({
                    min: '0',
                    max: '5',
                    step: $(this).data('step') ? $(this).data('step') : '1',
                    value: v,
                    disabled: $(this).hasClass('disabled'),
                }).on('change', function(){
                    // 2021-03-22 0.1 단위 인식으로 변경
                    var rate = ($(this).val() * 1).toFixed(1).split('.');
                    var rate_html = '';
                    for(var i = 0; i < 5; i++) {
                        var cls = `icon icon-star box-${size} gradient`;
                        if ( i < rate[0] ) {
                            cls += '10';
                        } else if ( i == rate[0] ) {
                            cls += rate[1];
                        } else {
                            cls += '0';
                        }
                        rate_html += `<i class="${cls}"></i>`;
                    }
                    $(this).next('.stars').html(rate_html);
                    
                    // 밸류값 자동 인식
                    var auto_value_target = $(this).parent().data('target');
                   
                    if ( auto_value_target ) {
                        $(auto_value_target).text(rate.join('.'));
                    }

                    var rating_value_text_target = $(this).parent().data('word');
                    if ( rating_value_text_target ) {
                       
                        var wordIndex = Math.ceil($(this).val());

                        $(rating_value_text_target).text(`“ ${starRatingWords[wordIndex]} ”`);
                    } 

                    if(rate[0] == 0 || rate[0] == "0" ) {
                        $('.reviewWordPrint').removeClass('on');
                        $(this).closest('.star-rating').removeClass('binded');
                    } else {
                        $('.reviewWordPrint').addClass('on');
                        $(this).closest('.star-rating').addClass('binded');
                    }
                    
                }).trigger('change');

                $(this).addClass('binded');
            });
        }
    }
})();


// TODO: 함수들 통합
function calcContentWidth(elem, offset) {
    var scroll_width = 0;
    elem.children().each(function(){
        scroll_width += $(this).outerWidth(true);
    });
    elem.css('width', Math.ceil(scroll_width) + (offset ? offset : 0));
}

// 레이어 팝업 호출
function callLayerPopup(id) {
    var obj = $("#"+ id);
    if ( obj.length > 0 ) {
        obj.addClass('show');
        $("html").addClass('lock-scroll');
	appMessage("layer-show");
    }
}
// 레이어 팝업 숨김
function hideLayerPopup(id) {
    var obj = $("#"+ id);
    if ( obj.length > 0 ) {
        obj.removeClass('show');
        $("html").removeClass('lock-scroll');
	appMessage("layer-hide");
    }
}

// 레이어 팝업 초기화
function initLayerPopup(obj) {
    if ( $(obj).find('.layer-controllers').length > 0 ) return;
    var div = document.createElement('div');
    div.setAttribute('class', 'layer-controllers');

    switch ($(obj).data('layer-type')) {
        case 'empty':
            return;
        case 'confirm':
            
            var a = document.createElement('a');
            a.setAttribute('class', 'layer-cancel');
            a.setAttribute('href', '#');
            div.appendChild(a);

            var a = document.createElement('a');
            a.setAttribute('class', 'layer-confirm');
            a.setAttribute('href', '#');
            div.appendChild(a);

            break;
        default: // alert
            var a = document.createElement('a');
            a.setAttribute('class', 'layer-confirm');
            a.setAttribute('href', '#');
            div.appendChild(a);
            break;
    }
    
    $(obj).find('.layer-content').append(div).end().addClass('ready');

}


// 상품선택 탭 변경
function layerProductTabChanged(idx, target){
    $(".layer-product-content").eq(idx).show().siblings().hide();
}

var setCookie = function(name, value, day) {
    var date = new Date();
    date.setTime(date.getTime() + day * 60 * 60 * 24 * 1000);
    document.cookie = name + '=' + value + ';expires=' + date.toUTCString() + ';path=/';
};

var getCookie = function(name) {
    var value = document.cookie.match('(^|;) ?' + name + '=([^;]*)(;|$)');
    return value? value[2] : null;
};
var deleteCookie = function(name) {
    var date = new Date();
    document.cookie = name + "= " + "; expires=" + date.toUTCString() + "; path=/";
}

// get params
function getParameters(custom) {
    var searchData = window.location.search;
    if ( custom ) {
        searchData = custom.split('?').pop();
    }

    var params = {};
    if ( searchData ) {
        searchData.slice(1).split('&').forEach(function(v){
            var data = v.split('=');
            params[data[0]] = data[1] ? data[1] : null;
        });
    }
    return params;
}

function scrollIsPassed(_selector, opt = {}) {
    if ( !callback ) callback = function(){};

    var _elem = $(_selector);
    var isPassed = false;

    var option = {
        gap: opt?.gap ? opt.gap : 0,
        callback: opt?.callback ? opt.callback : function(){},
    };

    $(window).on('scroll', function(e){
        var elemOffset = _elem.get(0).getClientRects();
        var elemTop = elemOffset[0]?.top;
        var elemHeight = elemOffset[0]?.height;

        var isElementPassed = elemTop + elemHeight + option.gap < 0;

        if ( isElementPassed !== isPassed ) {
            option.callback(isElementPassed);
        }
    });
}
function scrollAjaxLoader(_selector, opt = {}) {
    var _elem = $(_selector);
    var stopLoader = false;

    var option = {
        gap: opt?.gap ? opt.gap : 0,
        callback: opt?.callback ? opt.callback : function(){},
        showLoading: opt?.showLoading ? opt.showLoading : false
    };

    if ( option.showLoading ) {
        _elem.addClass('ajax-loading');
    }

    if ( _elem.length > 0 ) {
        // console.log("Scroll Loader Start!", _selector);
        $(window).on('scroll', function(e){
            if ( stopLoader ) {
                // console.log("Scroll Loader Stopped...", _selector);
                $(this).unbind(e);
            }

            var elemOffset = _elem.get(0).getClientRects();
            var elemTop = elemOffset[0]?.top;
            var elemHeight = elemOffset[0]?.height;
            var windowHeight = window.innerHeight;

            var isEndLineShow = elemTop + elemHeight - windowHeight + option.gap < 0;
           
            if ( isEndLineShow && !window.ajaxWait ) {
                option.callback();
            }
        })
    }

    return {
        break: function(){
            stopLoader = true;
        }
    }
}



  // 카테고리 위치 셋업 - 스크롤 위치
function autoCateTopScroll() {
    var scrollElem = $(".cate-top-menu .inner");
    var scrollElemPos = scrollElem.position();
    var nowScrollPos = scrollElem.scrollLeft();

    var activePos = $(".cate-top-menu ul .on").position();

    scrollElem.animate({scrollLeft: (nowScrollPos + activePos?.left) - scrollElemPos?.left - 10});
}

//카테고리 선택 시 화면 위치 이동
function autoCatePosition() {
    var scrollPos = $('.band-pd-list').offset().top - 150;
    
    $(window).scrollTop(scrollPos);
}

// 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,
        autoHeight:true,
        observer: true,	
  		observeParents: true,
        });
    });
}

// 2024.07.11 펑특가
document.addEventListener("mouseup", function(e) {
    var layerPopup = document.querySelector(".layer-popup");
    if (layerPopup && !layerPopup.contains(e.target)) {
        layerPopup.classList.remove("show");
    }

    var popupApp = document.querySelector(".popup-app");
    if (popupApp && !popupApp.contains(e.target)) {
        popupApp.classList.remove("active");
    }
});

window.addEventListener("scroll", function() {
    const stickyBanner = document.querySelector(".sticky-banner");
    if (stickyBanner) {
        if(window.scrollY > 0) {
            stickyBanner.classList.add("fixed");
        } else {
            stickyBanner.classList.remove("fixed");
        }
    }
});

document.addEventListener("DOMContentLoaded", function() {
    //showSearchingPopup();    
    //showHideRecommend();
    //countdownBombing();
});

//추천 팝업(애니메이션 N초간 노출)
function showSearchingPopup(){
    var searchingPopup = document.getElementById('searching_popup');
    if (searchingPopup) {
        searchingPopup.classList.add('show');
        setTimeout(function(){
            searchingPopup.classList.remove('show');
            setTimeout(showRecommendPopup, 1000);
        }, 1000);
    
        moveProgressBar();
    } else {
        console.error("error");
    }
}

//추천 팝업
function showRecommendPopup(){
    document.getElementById('recommend_popup').classList.add('show');
}

//애니메이션 N초간 노출
function moveProgressBar(){
    var inputElement = document.querySelector('.free-bar input');
    if (inputElement) {
        var getPercent = inputElement.value;
        document.querySelector('.free-bar i').style.width = getPercent + "%";
    }
}

//추천 구좌 노출
function showHideRecommend(){    
    const rcmdCard = document.querySelector(".rcmd-card");
    const rcmdPrd = document.querySelector(".rcmd-prd");

    setTimeout(() => {
        rcmdCard.classList.remove("show");
        rcmdPrd.classList.add("show");
    }, 2000);

    moveProgressBar();
}

// 펑!특가 그만보기 토스트 팝업
function showToast(message) {
    // Create a toast element
    const toastElement = document.createElement("div");
    toastElement.classList.add("toast-message");
    toastElement.textContent = message;
    document.body.appendChild(toastElement);

    setTimeout(() => {
        toastElement.classList.add("show");

        setTimeout(() => {
            toastElement.classList.remove("show");
            toastElement.classList.add("hide");

            toastElement.addEventListener("transitionend", () => {
                if (toastElement.classList.contains("hide")) {
                    toastElement.remove();
                }
            });
        }, 2000);
    }, 0);
}