function Popup (btn) {
    if (!btn) {
        return
    }
    this.btn = $(btn);
    this.popupOverlay = null;
    this.section = this.btn.next();
    this.contentHtml = this.btn.next().html();

    this.init = function() {
        if (!this.section.length) {
            return;
        }

        this.renderModal();
        this.bindListeners();
    };

    this.bindListeners = function () {
        this.onShowBtnClick();
        this.onCloseBtnClick();
        this.onOutsidePopupClick();
    };

    this.renderModal = function () {
        var popupOverlay = $('body > .popup-overlay');
        var popupHtml = "<article class='popup-overlay'>" +
                            "<div class='popup'>" +
                                "<span class='close-popup-btn'>&times;</span>" +
                                "<span class='popup-content'></span>" +
                            "</div>" +
                        "</article>";

        if (popupOverlay.length === 0) {
            $('body').append(popupHtml);
            this.popupOverlay = $('body > .popup-overlay');
        } else {
            this.popupOverlay = popupOverlay;
        }

        this.popupContent = this.popupOverlay.find('.popup-content');
    };

    this.onShowBtnClick = function () {
        var _this = this;

        this.btn.on('click', function () {
            _this.popupContent.html(_this.contentHtml);
            _this.popupOverlay.show();
        });
    };

    this.onCloseBtnClick = function () {
        var _this = this;
        this.closePopupBtn = this.popupOverlay.find('.close-popup-btn');
        this.closePopupBtn.on('click', function () {
            _this.popupOverlay.hide();
        });
    };

    this.onOutsidePopupClick = function () {
        var _this = this;

        this.popupOverlay.on('click', function (e) {
            if (!$(e.target).closest('.popup').length) {
                _this.popupOverlay.hide();
            }
        });
    };
}

window.addEventListener('load', function () {
    var targets = $('.open-popup-btn').toArray();

    targets.forEach(function (el) {
        var popup = new Popup(el);
        popup.init();
    });
});
