// 중복실행 방지
var dwLayers = {};

var appUiIsHided = false;
var layerPopupStackIndex = 0;

function LayerPopup(id, options) {
    var opt = $.extend({
        popupBackground: '',
        type: '',
        align: '',
        contentBackground: '',
        title: '',
        header: false,
        buttons: [],
        el: '',
        htmlString: '',
        id: id ? id : '_layer_' + new Date().getTime(),
        scrollable: false,
        classlist: [],
        on: {},
        cookie: {
            name: '',
            day: '',
        },
        hideOnBreak: false,
        contentTitle: '',
        alwaysOnTop: false,
        fixedScroll: true,
        addHistory: false,
        toggleAppUi: true
    }, options);

    this.background = opt.popupBackground;
    this.contentBackground = opt.contentBackground;
    this.type = opt.type;
    this.align = opt.align;
    this.title = opt.title;
    this.header = opt.header;
    this.buttons = opt.buttons;
    this.el = opt.el;
    this.htmlString = opt.htmlString;
    this.id = opt.id;
    this.scrollable = opt.scrollable;
    this.classlist = opt.classlist;
    this.on = opt.on;
    this.cookie = opt.cookie;
    this.hideOnBreak = opt.hideOnBreak;
    this.contentTitle = opt.contentTitle;
    this.alwaysOnTop = opt.alwaysOnTop;
    this.fixedScroll = opt.fixedScroll;

    this.addHistory = opt.addHistory;
    this.toggleAppUi = opt.toggleAppUi;

    dwLayers[this.id] = this;

    return this;
};

LayerPopup.prototype.setContent = function(txt) {

    var _obj = $("#"+ this.id);

    _obj.find('.layer-content').html(txt);

    return this;
}

LayerPopup.prototype.makeHtml = function(){
    // make popup 

    var _layerPopup = document.createElement('div');

    if ( this.header ) {
        var _layerHeader = document.createElement('div');
        _layerHeader.setAttribute('class', 'layer-header');
        var _h1 = document.createElement('h1');
        _h1.textContent = this.title;
        var _a = document.createElement('a');
        _a.setAttribute('class', 'layer-close');
        var _i = document.createElement('i');
        _i.setAttribute('class', 'icon icon-close-big black');
        _a.appendChild(_i);

        _layerHeader.appendChild(_h1);
        _layerHeader.appendChild(_a);

        _layerPopup.appendChild(_layerHeader);
    }
    
    if ( this.background ) {
        _layerPopup.style.background = this.background;
    }

    var popup_class = ['layer-popup'];

    if ( this.classlist ) {
        for( var i in this.classlist ) {
            popup_class.push(this.classlist[i]);
        }
    }

    if ( this.align ) {
        popup_class.push(this.align);
    }

    if ( this.scrollable ) {
        popup_class.push('scrollable');
    }
    
    _layerPopup.setAttribute('class', popup_class.join(' '));
    _layerPopup.setAttribute('id', this.id);

    var _layerContent = document.createElement('div');

    if ( this.contentBackground ) {
        _layerContent.style.background = this.contentBackground;
    }

    var content_class = ['layer-content'];

    _layerContent.setAttribute('class', content_class.join(' '));

    if ( this.el ) {
        console.log('el');
        _layerContent.appendChild(document.querySelector(this.el));
    } else if ( this.htmlString ) {
        _layerContent.innerHTML = this.htmlString;
    }

    if ( this.contentTitle ) {
        var _contentTitle = document.createElement('div');
        _contentTitle.setAttribute('class', 'layer-title');
        _contentTitle.innerHTML = `
            <a></a>
            <strong>${this.contentTitle}</strong>
            <a></a>
        `;
        _layerContent.prepend(_contentTitle);

    }



    if ( this.buttons.length > 0 ) {
        var _layerControllers = document.createElement('div');
        _layerControllers.setAttribute('class', 'layer-controllers');
        for ( var i in this.buttons ) {
            var data = this.buttons[i];
            var _button = document.createElement('a');
            _button.setAttribute('class', data.className);
            _button.textContent = data.text;

            _layerControllers.appendChild(_button);

            if ( data.click ) {
                _button.addEventListener('click', data.click);
            }
        }
        _layerContent.appendChild(_layerControllers);
    }

    _layerPopup.appendChild(_layerContent);

    document.querySelector('body').appendChild(_layerPopup);

    this.bindEvents();

    return this;
}

LayerPopup.prototype.bindEvents = function(){        

    return this;
}

LayerPopup.prototype.show = function(opt){
    if ( this.cookie.name ) {
        if ( getCookie(this.cookie.name) ) {
            return;
        }
    }
    var zIndex = 1000 + layerPopupStackIndex;
    if ( this.alwaysOnTop ) {
        zIndex = 99999;
    } else {
        layerPopupStackIndex += 1;
    }
    $("#"+ this.id).addClass('show').css('z-index', zIndex);

    if ( this.fixedScroll ) {
        $("html").addClass('lock-scroll');
    }

    if ( typeof opt?.afterShow == 'function' ) {
        opt.afterShow();
    }

    if (typeof this.on.afterShow == 'function' ) {
        this.on.afterShow();
    }

    if ( isApp == 'Y' && this.toggleAppUi ) {
        // 앱 ui 제거
        appMessage('layer-show');
        appUiIsHided = true;
    }

    return this;
}

LayerPopup.prototype.hide = function(){
    $("#"+ this.id).removeClass('show');


    if (typeof this.on.afterHide == 'function' ) {
        this.on.afterHide();
    }


    if ( $(".layer-popup.show").length == 0 ) {
        $("html").removeClass('lock-scroll');
        // if ( isApp == 'Y' && this.toggleAppUi ) {
        if ( isApp == 'Y' ) {
            // 앱 ui 활성
            appMessage('layer-hide');
            appUiIsHided = false;
        }
    }

    if ( this.hideOnBreak ) {
        this.break();
    } else {
        return this;
    }
}

LayerPopup.prototype.break = function(){
    var _this = this;
    dwLayers[this.id] = null;
    // setTimeout(function(){
        $('#'+ _this.id).remove();
        if ( $(".layer-popup.show").length == 0 ) {
            $("html").removeClass('lock-scroll');
        }
    // }, 500);
    return '';
}

LayerPopup.prototype.alert = function(msg) {
    this.background = 'rgba(51, 51, 51, .7)';
    this.type = 'alert';
    this.align = 'layer-center';
    this.hideOnBreak = true;
    this.alwaysOnTop = true;
    this.toggleAppUi = false;

    this.htmlString = `
    <div class="layer-simple-text">
        ${msg}
    </div>
    `;

    this.buttons = [
        {
            text: '',
            className: 'layer-confirm',
        }
    ]
    
    this.makeHtml().bindEvents().show();
}

LayerPopup.prototype.confirm = function(msg) {
    this.background = 'bg70';
    this.type = 'confirm';
    this.align = 'layer-center';
    this.hideOnBreak = true;
    this.alwaysOnTop = true;
    this.toggleAppUi = false;

    this.htmlString = `
    <div class="layer-simple-text">
        ${msg}
    </div>
    `;

    this.buttons = [
        {
            text: '',
            className: 'layer-cancel',
        },
        {
            text: '',
            className: 'layer-confirm',
        }
    ]
    
    this.makeHtml().bindEvents().show();
}

LayerPopup.prototype.select = function(opt) {
    this.background = 'rgba(51, 51, 51, .7)';
    this.classlist = ['layer-bottom'];
    this.alwaysOnTop = true;
    this.hideOnBreak = true;
    this.toggleAppUi = false;
    this.type = 'select';

    var html_body = '';
    var _title = opt.data[0].contentTitle;
	
	var totPrice = Number($("#OD_AMT_SHED").val());
	var _installment = opt.installment;
	
    if(true == _installment && totPrice <= 50000){
		var list = opt.data[0];
		html_body += `
			<li class="${list.selected ? 'selected' : ''}">
				<a href="${list.value}">${list.name}</a>
			</li>
			`;
	}else{
	    for ( var i in opt.data ) {
	        var list = opt.data[i];
	        html_body += `
	            <li class="${list.selected ? 'selected' : ''}">
	                <a href="${list.value}" >${list.name}</a>
	            </li>
	        `;
	    }
	}
    console.log(opt.data);
    var html = `
        <div class="layer-select-box">
            <div class="layer-select-head">
                <strong>${!(_title == undefined) ? _title : ''}</strong>
                <a href="#" class="layer-close">
                    <i class="icon icon-close grey w24"></i>
                </a>
            </div>
            <div class="layer-select-lists">
                <ul>
                    ${html_body}
                </ul>
            </div>
        </div>
    `;

    this.htmlString = html;

    this.on['cancel'] = opt.canceled;

    this.makeHtml().show();
    
    if ( isApp == 'Y' ) {
   		appMessage("layer-show");
   	}

    //기획전 상세 전체 상품 보기 제목 넣기
    if($('.plan-pd-list').length > 0) {
        var _title = $('.basic-view-head .tit h6').text();

        $('.layer-select-head strong').text(_title);
    }
    
    
    var _this = this;

    $("#"+ this.id + " .layer-select-lists a").on('click', function(e){
        e.preventDefault();
        opt.selected({
            name: $(this).text(),
            value: $(this).attr('href'),
        }, _this);

        _this.hide();
    })

    return this;
}
LayerPopup.prototype.load = function(url, callback) {
    var _this = this;

    $.get(url, function(r){
        _this.setContent(r).show();
        if ( typeof callback == 'function' ) {
            callback();
        }
    })
}


/**
 * ToastPopup 
 */

function ToastPopup(id, opt) {
    var option = {
        title: opt?.title,
        headerHtml: opt?.headerHtml,
        counter: opt?.counter ? opt.counter : 3,
        content: opt?.content,
        classList: opt?.classList ? opt.classList : [],
        hideOnBreak: opt?.hideOnBreak,
        on: {
            beforeShow: opt?.on?.beforeShow ? opt.on.beforeShow : function(){},
            afterShow: opt?.on?.afterShow ? opt.on.afterShow : function(){},
            beforeHide: opt?.on?.beforeHide ? opt.on.beforeHide : function(){},
            afterHide: opt?.on?.afterHide ? opt.on.afterHide : function(){}
        }
    };
    this.id = id ? id : '_toast_' + new Date().getTime();
    this.title = option.title;
    this.headerHtml = option.headerHtml;
    this.content = option.content;
    this.classlist = option.classList;
    this.counter = option.counter;
    this.timer = null;
    this.on = option.on;
    this.hideOnBreak = option.hideOnBreak;

    return this;
}

ToastPopup.prototype.makeHtml = function() {
    var _toastPopup = document.createElement('div');
    
    var toast_class_lists = ['toast-popup', 'ready'];
    if ( this.classlist.length > 0 ) {
        for( var i in this.classlist ) {
            toast_class_lists.push(this.classlist[i]);
        }
    }

    _toastPopup.setAttribute('class', toast_class_lists.join(' '));

    if ( this.headerHtml ) {
        var _headerDiv = document.createElement('div');
        _headerDiv.innerHTML = this.headerHtml;
        _toastPopup.appendChild(_headerDiv);
    } else if ( this.title ) {
        var _headerDiv = document.createElement('div');
        _headerDiv.setAttribute('class', 'toast-header');
        _headerDiv.innerHTML = `<strong>${this.title}</strong>`;
        _toastPopup.appendChild(_headerDiv);
    }

    var _toastBody = document.createElement('div');
    _toastBody.setAttribute('class', 'toast-body');

    _toastBody.innerHTML = this.content ? this.content : '';

    _toastPopup.appendChild(_toastBody);

    _toastPopup.setAttribute('id', this.id);

    document.body.appendChild(_toastPopup);

    this.bindEvents();

    return this;
}

ToastPopup.prototype.bindEvents = function() {
    var _this = this;
    var id = _this.id;

    $("#"+id).on('click', '.toast-close', function(e){
        e.preventDefault();
        _this.hide();
    })

}

ToastPopup.prototype.append = function(elem) {
    var _this = this;
    var _this_elem = $("#"+ this.id + ' .toast-body');
    _this_elem.append(elem);

    _this_elem.children().last().delay(this.counter * 300).slideUp(function(){
        $(this).remove();
    });

    if ( this.timer ) {
        clearTimeout(this.timer);
    }

    this.timer = setTimeout(function(){
       _this.hide().break();
    }, this.counter * 300);

    return this;
}

ToastPopup.prototype.show = function() {

    this.on.beforeShow(this);
    
    // 토스트 하단 여백 
    var bottomGap = 0;
    if ( $(".bottom-tab").length > 0 && isApp == 'N' ) {
        bottomGap += $(".bottom-tab").height();
    }
    if ( $(".btn-buy").length > 0 ) {
        bottomGap += $(".btn-buy").height();
    }

    $("#"+ this.id).addClass('show').css('bottom', bottomGap);

    this.on.afterShow(this);
    
    return this;
}

ToastPopup.prototype.hide = function() {
    this.on.beforeHide(this);

    $("#"+ this.id).removeClass('show');
    
    this.on.afterHide(this);

    if ( this.hideOnBreak ) {
        $("#" + this.id).remove();
    }

    return this;
}

ToastPopup.prototype.break = function() {
    var _this = this;
    // 애니메이션이 이상해서 일단 바로 제거
    // setTimeout(function(){
        $("#"+ _this.id).remove();
    // }, 500);
}
/**
 * opt 값
 *  (string) type: band, cool, etc
 *  (string) name: 좌측 텍스트
 *  (string) desc: 우측 텍스트
 *  (int) width: 0 ~ 100 
 */
ToastPopup.prototype.addCart = function(opt) {

    if ( dwLayers['product_buy'] ) {
        // 상품구매 팝업이 있다면 끈다!
        dwLayers['product_buy'].hide();
    }

    if ( opt.title ) {
        this.title = opt.title;
    }

    if ( typeof opt?.afterHide == 'function' ) {
        this.on.afterHide = opt.afterHide;
    }

    if( opt.classList ) {
        this.classlist = opt.classList;
    }

    if ( opt.type == 'etc' ) {
        var _cartItem = document.createDocumentFragment();
        var cart_class = 'toast-cart-item etc';
        if ( $("#"+ this.id).length > 0 ) {

        } else {
            this.makeHtml().show().append(_cartItem);
        }
    } else {
        var _toastItem = $(".toast-cart-item."+ opt.type);
        var _cartItem = document.createElement('div');

        if ( _toastItem.length > 0 ) {
            // 만들지 않음
            _toastItem
            .find('i').width(opt.width + '%').end()
            .find('strong').html(opt.name).end()
            .find('span').html(opt.desc);

        } else {
            var cart_class = 'toast-cart-item';
            if ( opt.type ) {
                cart_class += ' ' + opt.type;
            }
            _cartItem.setAttribute('class', cart_class);
        
            if ( opt.width ) {
                _cartItem.setAttribute('data-cart-width', opt.width);
            }
        
            var cartHtml = `
                <h4>
                    <strong>${opt.name}</strong>
                    <span>${opt.desc}</span>
                </h4>
                <div><i></i></div>
            `;
        
            _cartItem.innerHTML = cartHtml;

            if ( $("#"+ this.id).length > 0 ) {
                this.append(_cartItem);
            } else {
                this.makeHtml().show().append(_cartItem);
            }
        
            setTimeout(function(){
                $(".toast-cart-item[data-cart-width]").each(function(){
                    var w = $(this).data('cart-width');
                    $(this).removeAttr('data-cart-width')
                        .find('i').css('width', w + '%');
                })
            }, 100);
        }
    }


    return this;
}

/**
 * 
 * foryouToastPopup
 */
function foryouToast(data) {
    new ToastPopup('recommend_for_you', {
        headerHtml: `
            <div class="toast-header recommend_foryou">
                <span>${data.name}님,</span>
                <strong>한 분만을 위한 오늘의 추천!</strong>
                <a class="toast-close">
                    <i class="icon icon-close white box-24"></i>
                </a>
            </div>
        `,
        content: `
            <a href="${data.link}" class="recommend_foryou_content">
                <div class="thumb" style="background-image: url(${data.image})"></div>
                <div class="info">
                    <p>${data.title}</p>
                    <span>
                        ${data.rate > 0 ? '<strong>'+ data.rate +'%</strong>' : ''}
                        ${data.price}원
                    </span>
                </div>
            </a>
        `,
        classList: ['recommend-foryou', 'none-shadow'],
        on: {
            afterHide: typeof data.afterHide == 'function' ? data.afterHide : function(){}
        },
        hideOnBreak: true
    }).makeHtml().show();
}

//  Events
$(function(){

    var qtyLayerObj;

    // 수량변경 프리셋
    $("body").on('click', '.quantity input', function(){

        var _this = $(this);

        _this.blur();

        var current_value = _this.val();
        var stockable = _this.data('stock') ? Number(_this.data('stock')) : 999999;

		//다중배송지 상품수량 셀렉트박스 미노출
		if (!($("#multiOrder").length > 0)) {
			if ( current_value > 10 ) {
				openInputQty();
			} else {
				openSelectQty();
			}
		}

        function openSelectQty() {
            
            qtyLayerObj?.break();
            qtyLayerObj = null;

            var selectLists = [];

            for ( var i = 0; i < stockable; i++ ) {
                var nowNum = i + 1;
                selectLists.push({
                    name: nowNum,
                    value: nowNum,
                    selected: nowNum == current_value
                });

                if  (i == 9) {
                    break;
                }
            }

            if ( stockable > 10 ) {
                selectLists.push({
                    name: '11 +',
                    value: 'custom'
                });
            }

            qtyLayerObj = new LayerPopup('quantity_select').select({
                data: selectLists,
                selected: function(sel, selector) {
                    if ( sel.value == 'custom' ) {
                        setTimeout(function(){
                            openInputQty()
                        }, 100);
                    } else if ( current_value !== sel.value ) {
                        _this.val(sel.value).focus();
                        eval(_this.attr('onchange'));
                    }
                }
            })
        }

        function openInputQty() {
            
            qtyLayerObj?.break();
            qtyLayerObj = null;

            qtyLayerObj = new LayerPopup('quantity_change', {
                align: 'layer-center',
                popupBackground: 'rgba(50, 50, 50, .7)',
                hideOnBreak: true,
                alwaysOnTop: true,
                toggleAppUi: false,
                type: 'confirm',
                buttons: [
                    {
                        text: '',
                        className: 'layer-cancel',
                    },
                    {
                        text: '',
                        className: 'layer-confirm',
                    }
                ],
                on: {
                    confirm: function(){
                        var result = $("#quantity_change input").val();
                        if ( !result ) {
                            alert('수량을 입력 해 주세요');
                        } else if ( result < 1 ) {
                            alert('최소 수량은 1개 이상입니다.');
                        } else if ($("#pageNm").val() == "bizOrder" && result < 100 ) {
                            // 대량견적 페이지의 경우
                            alert('최소 수량은 100개 이상입니다.');
                        } else if ( result > stockable ) {
                            alert(`주문가능 수량은 ${stockable.format()}개 입니다.`)
                        } else {
                            _this.val(result);
                            if ( _this.attr('onchange') ) {
                                eval(_this.attr('onchange'));
                            }
                        }
                        dwLayers['quantity_change'].hide();
                    }
                },
                htmlString: `
                <div class="layer-title typeA">
                    <h2>수량변경</ht>
                </div>
                <div class="dw-form-wrapper pd14">
                    <label class="dw-form text">
                        <input type="number" oninput="validateProductCnt(this)">
                    </label>
                    ${stockable != 999999 ? '<span>최대 가능 수량 ' + stockable.format() +'개</span>' : ''}
                </div>
                `
            }).makeHtml().show({
                afterShow: function(){
                    $(`#quantity_change input`).val(current_value).focus();
                }
            })
        }

    })
    // 레이어 팝업
    .on('click', '[data-layer-popup-call]', function(e){
        var popup_id = $(this).data('layer-popup-call');
        var popup_option = dwLayers[popup_id];

        if(popup_id){
        	   e.preventDefault();
               new LayerPopup(popup_id, popup_option).bindEvents().show()
        }
     
    })
    .on('click', '.layer-popup', function(e){
        //  레이어 자체 클릭시 닫기 & 풀팝업은 제외
        if ( $(e.target).hasClass('layer-popup') && !$(e.target).hasClass('scrollable') ) {
            var id = $(this).attr('id');
            if ( dwLayers[id] ) {
                dwLayers[id].hide();
            }
        }
    })
    .on('click', '.layer-confirm', function(e){
        e.preventDefault();
        var _layer = $(this).closest('.layer-popup');
        if ( _layer.length > 0 ) {
            var id = _layer.attr('id');
            var _layerObj = dwLayers[id];
            if ( _layerObj && typeof _layerObj.on?.confirm == 'function' ) {
                _layerObj.on.confirm(_layerObj);
            }
            _layerObj.hide();
        }
    })
    .on('click', '.layer-close, .layer-cancel', function(e){
        e.preventDefault();
        var _layer = $(this).closest('.layer-popup');
        if ( _layer.length > 0 ) {
            var id = _layer.attr('id');
            var _layerObj = dwLayers[id];
            if ( _layerObj ) {
                if ( _layerObj.on.close  ) {
                    _layerObj.on.close(_layerObj);
                }
            }
            _layerObj.hide();
        }
    })
    .on('click', '.layer-after', function(e){
        e.preventDefault();
        var _layer = $(this).closest('.layer-popup');
        if ( _layer.length > 0 ) {
            var id = _layer.attr('id');
            var _layerObj = dwLayers[id];
            if ( _layerObj ) {
                if ( _layerObj.on.after  ) {
                    _layerObj.on.after(_layerObj);
                }
                _layerObj.hide();
            }
        }
    })
    .on('click', '.layer-close-with-cookie', function(e){
        e.preventDefault();
        var _layer = $(this).closest('.layer-popup');
        if ( _layer.length > 0 ) {
            var id = _layer.attr('id');
            var _layerObj = dwLayers[id];
            if ( _layerObj ) {
                if ( _layerObj.on.cookie  ) {
                    _layerObj.on.cookie(_layerObj);
                }
                setCookie(_layerObj.cookie.name, _layerObj.cookie.day);
                _layerObj.hide();
            }
        }
    })
})
// Events

// 숫자 외 값 입력 시 제거
function validateProductCnt(input) {
    if (!/^\d+$/.test(input.value)) {
        input.value = input.value.replace(/[^\d]/g, '');
    }
}

function layer_common_close(){
    var _layer = $(".layer-popup.show");
    if ( _layer.length > 0 ) {
        var id = _layer.attr('id');
        var _layerObj = dwLayers[id];
        if ( _layerObj ) {
            if ( _layerObj.on.close  ) {
                _layerObj.on.close(_layerObj);
            }
        }
        _layerObj.hide();
    }
}

