(function ($) {

    var body = $('body');


    /**
     * MODAL
     */
    body.on('click', '[data-modal]', function () {
        var modal = $(this).data('modal'),
            element = $( '#'+modal );

        $(document).trigger("modal_open", [element]);
        element.fadeIn();
    });


    body.on('click', '[data-close-modal]', function () {
        var modal = $(this).data('close-modal');
        $('#' + modal).fadeOut();
    });


    body.on('click', '.modal', function (event) {
        var node = event.toElement || event.relatedTarget || event.target;
        // console.log('node', node, event);
        while ($(node).length) {
            if ($(node).hasClass('modal-content')) return;
            node = $(node).parent();
            // console.log('node', node);
        }
        $(this).fadeOut();
    });


    /**
     * Escape event Tracking to close Modalsw
     * @param evt
     */
    document.onkeydown = function (evt) {
        evt = evt || window.event;
        var isEscape = false;
        if ("key" in evt) {
            isEscape = (evt.key == "Escape" || evt.key == "Esc");
        } else {
            isEscape = (evt.keyCode == 27);
        }
        if (isEscape) {
            $('.modal').fadeOut();
        }
    };


})(jQuery);