/* global BP_Messages */
var BPBMJQ = jQuery.noConflict();
var BPBMEvent = Event;
BPBMJQ.fn.bpbmtooltip = jQuery.fn.tooltip;
var BPBMOnlineUsers = [];
var urlSeparator = (BP_Messages['url'].split('?')[1] ? '&':'?');

(function ($) {
    var checkerTimer, // Timer variable
        thread,  // Current thread_id or false
        socket,
        threads, // True if we are on thread list screen or false
        openThreads = {},
        miniChats = {},
        miniMessages = false,
        bpMessagesWrap,
        online = [],
        onlineFetched = false,
        loadingMore = {},
        unread = {},
        reIniting = false,
        blockScroll = false,
        isRtl = $('html[dir="rtl"]').length !== 0,
        RTCPeerConnection = window.RTCPeerConnection || window.webkitRTCPeerConnection,
        RTCSessionDescription = window.mozRTCSessionDescription || window.RTCSessionDescription,
        isInCall = false,
        blockSelect = false,
        originalTitle = document.title,
        loadingHtml = '<div class="loading-messages"><div class="bounce1"></div><div class="bounce2"></div><div class="bounce3"></div></div>',
        badWords    = false;


    if( typeof( BP_Messages['badWordList'] ) !== 'undefined' ){
        try {
            badWords = JSON.parse(atob(BP_Messages['badWordList']));
        } catch (e){}
    }

    var incomingSelector = '.bp-messages-wrap .list .messages-stack.incoming .content .messages-list li .message-content';
    var outgoingSelector = '.bp-messages-wrap .list .messages-stack.outgoing .content .messages-list li .message-content';
    var threadsSelector  = '.bp-messages-wrap .threads-list .thread';

    if( store.enabled && BP_Messages['realtime'] == "1" ){
        var lastUnread = store.get('bp-better-messages-last-unread');

        if( typeof lastUnread !== 'undefined' ){
            if(parseInt(BP_Messages['total_unread']) !== parseInt(lastUnread)){
                BPBMUpdateUnreadCount(lastUnread);
            }
        }
    }

    ifvisible.setIdleDuration(3);

    var status_icons = {};
    var icons = {
        'gif' : '<svg xmlns="http://www.w3.org/2000/svg" viewBox="5.002 9.969 23.017 13.042">\n' +
            '<g stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">\n' +
            '<g fill="currentColor">\n' +
            '<path d="M8.00684834,10 C6.34621185,10 5,11.3422643 5,12.9987856 L5,20.0012144 C5,21.6573979 6.33599155,23 8.00684834,23 L24.9931517,23 C26.6537881,23 28,21.6577357 28,20.0012144 L28,12.9987856 C28,11.3426021 26.6640085,10 24.9931517,10 L8.00684834,10 L8.00684834,10 Z M7.99456145,11 C6.89299558,11 6,11.9001762 6,12.992017 L6,20.007983 C6,21.1081436 6.90234375,22 7.99456145,22 L25.0054385,22 C26.1070044,22 27,21.0998238 27,20.007983 L27,12.992017 C27,11.8918564 26.0976562,11 25.0054385,11 L7.99456145,11 L7.99456145,11 Z M13,17 L13,19 L10.9998075,19 C10.4437166,19 10,18.5523709 10,18.0001925 L10,14.9998075 C10,14.4437166 10.4476291,14 10.9998075,14 L14,14 L14,13 L11.0048815,13 C9.89761602,13 9,13.8865548 9,15.0059191 L9,17.9940809 C9,19.1019194 9.8938998,20 11.0048815,20 L14,20 L14,19.25 L14,19.25 L14,17 L14,16 L11,16 L11,17 L13,17 L13,17 Z M16,14 L16,19 L15,19 L15,20 L18,20 L18,19 L17,19 L17,14 L18,14 L18,13 L15,13 L15,14 L16,14 L16,14 Z M20,16 L20,14 L24,14 L24,13 L19,13 L19,20 L20,20 L20,17 L23,17 L23,16 L20,16 L20,16 Z"/>\n' +
            '</g>\n' +
            '</g>\n' +
            '</svg>'
    }

    /* <fs_premium_only> */
    status_icons = {
        'seen' : '<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"\n' +
            'viewBox="0 0 25 16" style="enable-background:new 0 0 25 16;" xml:space="preserve"><g>\n' +
            '<path fill="currentColor" d="M1.5,9.4c0.1-0.2,0.2-0.5,0.4-0.6C2.3,8.6,2.7,8.6,3,8.9c0.7,0.7,1.5,1.5,2.2,2.2c0.6,0.6,1.2,1.2,1.9,1.9\n' +
            '\t\tc0,0,0,0,0.1,0.1c0.2-0.3,0.4-0.5,0.7-0.8c1-1.2,1.9-2.3,2.9-3.5c1.5-1.8,3-3.7,4.5-5.5c0.6-0.7,1.2-1.4,1.8-2.1\n' +
            '\t\tc0.4-0.5,1.3-0.5,1.5,0.2c0.1,0.3,0.1,0.6-0.1,0.9c-0.6,0.8-1.3,1.5-1.9,2.3c-0.9,1.1-1.8,2.2-2.7,3.2c-0.9,1.1-1.8,2.1-2.6,3.2\n' +
            '\t\tc-0.9,1.1-1.9,2.2-2.8,3.4c-0.2,0.2-0.4,0.4-0.5,0.7C7.6,15.3,7,15.4,6.6,15c-0.6-0.6-1.2-1.2-1.8-1.8c-0.9-0.9-1.8-1.8-2.8-2.8\n' +
            '\t\tc-0.1-0.1-0.2-0.2-0.3-0.3C1.7,10,1.6,9.9,1.5,9.7C1.5,9.6,1.5,9.5,1.5,9.4z"/>' +
            '<path fill="currentColor"  d="M23.5,1.7c0,0.3-0.3,0.5-0.4,0.7c-1.4,1.7-2.7,3.3-4.1,5c-1.4,1.7-2.9,3.5-4.3,5.2c-0.6,0.7-1.2,1.5-1.8,2.2\n' +
            '\t\tc-0.4,0.5-0.9,0.5-1.4,0.1c-0.3-0.3-0.6-0.6-0.8-0.8c-0.3-0.3-0.3-0.6-0.2-1c0.1-0.4,0.4-0.5,0.8-0.6c0.2,0,0.5,0.1,0.6,0.2\n' +
            '\t\tc0.1,0.1,0.1,0.1,0.2,0.2c0.2-0.2,0.3-0.4,0.4-0.5c1-1.2,2-2.4,2.9-3.5c1.3-1.6,2.7-3.2,4-4.8c0.8-1,1.7-2,2.5-3.1\n' +
            '\t\tc0.2-0.3,0.5-0.4,0.9-0.3c0.4,0.1,0.6,0.3,0.7,0.7c0,0,0,0,0,0C23.5,1.6,23.5,1.7,23.5,1.7z"/>' +
            '</g>' +
            '</svg>',
        'delivered' : '<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"\n' +
            '\t viewBox="0 0 25 16" style="enable-background:new 0 0 25 16;" xml:space="preserve">\n' +
            '<g>\n' +
            '\t<path fill="currentColor" d="M1.5,9.4c0.1-0.2,0.2-0.5,0.4-0.6C2.3,8.6,2.7,8.6,3,8.9c0.7,0.7,1.5,1.5,2.2,2.2c0.6,0.6,1.2,1.2,1.9,1.9\n' +
            '\t\tc0,0,0,0,0.1,0.1c0.2-0.3,0.4-0.5,0.7-0.8c1-1.2,1.9-2.3,2.9-3.5c1.5-1.8,3-3.7,4.5-5.5c0.6-0.7,1.2-1.4,1.8-2.1\n' +
            '\t\tc0.4-0.5,1.3-0.5,1.5,0.2c0.1,0.3,0.1,0.6-0.1,0.9c-0.6,0.8-1.3,1.5-1.9,2.3c-0.9,1.1-1.8,2.2-2.7,3.2c-0.9,1.1-1.8,2.1-2.6,3.2\n' +
            '\t\tc-0.9,1.1-1.9,2.2-2.8,3.4c-0.2,0.2-0.4,0.4-0.5,0.7C7.6,15.3,7,15.4,6.6,15c-0.6-0.6-1.2-1.2-1.8-1.8c-0.9-0.9-1.8-1.8-2.8-2.8\n' +
            '\t\tc-0.1-0.1-0.2-0.2-0.3-0.3C1.7,10,1.6,9.9,1.5,9.7C1.5,9.6,1.5,9.5,1.5,9.4z"/>\n' +
            '\t<path fill="currentColor" d="M23.5,1.7c0,0.3-0.3,0.5-0.4,0.7c-1.4,1.7-2.7,3.3-4.1,5c-1.4,1.7-2.9,3.5-4.3,5.2c-0.6,0.7-1.2,1.5-1.8,2.2\n' +
            '\t\tc-0.4,0.5-0.9,0.5-1.4,0.1c-0.3-0.3-0.6-0.6-0.8-0.8c-0.3-0.3-0.3-0.6-0.2-1c0.1-0.4,0.4-0.5,0.8-0.6c0.2,0,0.5,0.1,0.6,0.2\n' +
            '\t\tc0.1,0.1,0.1,0.1,0.2,0.2c0.2-0.2,0.3-0.4,0.4-0.5c1-1.2,2-2.4,2.9-3.5c1.3-1.6,2.7-3.2,4-4.8c0.8-1,1.7-2,2.5-3.1\n' +
            '\t\tc0.2-0.3,0.5-0.4,0.9-0.3c0.4,0.1,0.6,0.3,0.7,0.7c0,0,0,0,0,0C23.5,1.6,23.5,1.7,23.5,1.7z"/>\n' +
            '</g>\n' +
            '</svg>',
        'sent' : '<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"\n' +
            '\t viewBox="0 0 25 16" style="enable-background:new 0 0 25 16;" xml:space="preserve">\n' +
            '<path fill="currentColor" d="M3.9,9.4C4,9.2,4.1,8.9,4.3,8.8c0.4-0.2,0.8-0.2,1.1,0.1c0.7,0.7,1.5,1.5,2.2,2.2c0.6,0.6,1.2,1.2,1.9,1.9\n' +
            '\tc0,0,0,0,0.1,0.1c0.2-0.3,0.4-0.5,0.7-0.8c1-1.2,1.9-2.3,2.9-3.5c1.5-1.8,3-3.7,4.5-5.5c0.6-0.7,1.2-1.4,1.8-2.1\n' +
            '\tc0.4-0.5,1.3-0.5,1.5,0.2c0.1,0.3,0.1,0.6-0.1,0.9C20.2,3,19.6,3.7,19,4.5c-0.9,1.1-1.8,2.2-2.7,3.2c-0.9,1.1-1.8,2.1-2.6,3.2\n' +
            '\tc-0.9,1.1-1.9,2.2-2.8,3.4c-0.2,0.2-0.4,0.4-0.5,0.7C10,15.3,9.4,15.4,9,15c-0.6-0.6-1.2-1.2-1.8-1.8c-0.9-0.9-1.8-1.8-2.8-2.8\n' +
            '\tc-0.1-0.1-0.2-0.2-0.3-0.3C4.1,10,4,9.9,3.9,9.7C3.9,9.6,3.9,9.5,3.9,9.4z"/>\n' +
            '</svg>'
    };
    /* </fs_premium_only> */

    var sounds = {};

    if( BP_Messages['soundLevels']['notification'] > 0 ) {
        sounds['notification'] = new Howl({
            src: [ BP_Messages.assets + 'notification.mp3', BP_Messages.assets + 'notification.ogg'],
            loop: false,
            volume: BP_Messages['soundLevels']['notification']
        });
    }

    if( BP_Messages['soundLevels']['sent'] > 0 ) {
        sounds['sent'] = new Howl({
            src: [BP_Messages.assets + 'sent.mp3', BP_Messages.assets + 'sent.ogg'],
            loop: false,
            volume: BP_Messages['soundLevels']['sent']
        });
    }

    /* <fs_premium_only> */
    if( BP_Messages['soundLevels']['calling'] > 0 ) {
        sounds['calling'] = new Howl({
            src: [BP_Messages.assets + 'calling.mp3', BP_Messages.assets + 'notification.ogg'],
            loop: true,
            volume: BP_Messages['soundLevels']['calling']
        });
    }
    /* </fs_premium_only> */

    $.fn.BPBMremoveAttributes = function() {
        return this.each(function() {
            var attributes = $.map(this.attributes, function(item) {
                return item.name;
            });
            var img = $(this);
            $.each(attributes, function(i, item) {
                img.removeAttr(item);
            });
        });
    }

    function BPBMUpdateUnreadCount( unread ){
        var _unread = parseInt( unread );
        if( isNaN(_unread) ) _unread = 0;

        document.dispatchEvent(new CustomEvent('bp-better-messages-update-unread', {
            detail: {
                unread: _unread
            }
        }));

        BP_Messages.total_unread = _unread;

        if( _unread === 0 ){
            $('.bp-messages-wrap .threads-list .thread .unread-count').html('');
        }

        if( BP_Messages['titleNotifications'] === '1' ){
            if( isNaN(_unread) || _unread <= 0 ){
                document.title = originalTitle;
            } else {
                document.title = '(' + unread +  ') ' + originalTitle;
            }
        }
    }

    function BPBMformatTextArea(textarea){
        if ( typeof textarea[0].BPemojioneArea !== 'undefined' ){
            textarea[0].BPemojioneArea.trigger('change');
        }

        var message = textarea.val();

        if( $(textarea).next('.bp-emojionearea').length === 0 ) return message;

        var new_html = BPBMformatMessage(message);

        textarea.val(new_html);

        return new_html;
    }

    function BPBMformatMessage(message){
        message = message.replace(/<p><\/p>/g, '');

        if( message.substring(0, 3) !== '<p>' ) {
            message = '<p>' + message;
        }

        if( message.substring(message.length - 4) !== '</p>' ) {
            message = message + '</p>';
        }


        var message_html = $.parseHTML( message );

        $.each( message_html, function( i, el ) {
            var element = $(this);

            $.each(element.find('img.emojioneemoji,img.emojione'), function () {
                var emojiicon = $(this);
                emojiicon.replaceWith(emojiicon.attr('alt'));
            });

            element.BPBMremoveAttributes();
            element.find('*').BPBMremoveAttributes();

        });

        var new_html = '';
        $.each( message_html, function(){
            new_html += this.outerHTML;
        } );

        if(new_html === '<p></p>') new_html = '';

        new_html = new_html.replace(/&amp;/g, '&');

        return new_html;
    }

    $(window).on('focus',function() {
        ifvisible.focus();
    });

    $(window).on('blur', function() {
        ifvisible.blur();
    });

    $(window).on('click', function(){
        $('.bp-messages-wrap .expandingButtons.expandingButtonsOpen').removeClass('expandingButtonsOpen');
    })

    var isMobile = false; //initiate as false
    if( /iPad|iPhone|iPod/.test(navigator.userAgent)
        || /(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|Android|Silk|lge |maemo|midp|mmp|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i.test(navigator.userAgent)
        || /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(navigator.userAgent.substr(0,4))) isMobile = true;

    //if( BP_Messages['mobileFullScreen'] === '0' ) isMobile = false;

    if( BP_Messages['forceMobile'] === '1' ) isMobile = true;

    var isTapped = false;
    if( isMobile ) {
        $(window).on('touchstart', function () {
            isTapped = true;
        });

        $(window).on('touchend', function () {
            isTapped = false;
        });

        BP_Messages['miniChats'] = '0';
    }

    var holderClass = 'bp-better-messages-mobile-holder';
    var fullScreenHolderClass = 'bp-better-messages-mobile-holder';

    function initImagesPopup() {
        if (typeof $.fn.BPBMmagnificPopup === 'function') {
            $('.bp-messages-wrap .list .messages-stack .content .messages-list li .images').each(function(){
                var images = $(this);
                var message = images.closest('li');

                images.BPBMmagnificPopup({
                    delegate : 'a',
                    key      : message.attr('data-id'),
                    type     : 'image',
                    gallery  : {
                        enabled:true
                    }
                });
            });


        }
    }

    function openMobile( wrap ){
        if( wrap.length === 0 ) return false;

        if( $('.' + holderClass ).length === 0 ){
            $('<div class="' + holderClass + '"></div>').insertBefore(wrap);
        }

        var source = wrap;
        source.addClass('bp-messages-mobile');
        source.attr('id', 'bp-better-messages-mobile-view-container');

        var windowHeight = window.innerHeight;
        $('html').addClass('bp-messages-mobile').css('overflow', 'hidden');
        $('body').addClass('bp-messages-mobile').css('min-height', windowHeight);

        var _mobileViewContainer = source.appendTo( $('body') );
        _mobileViewContainer.show();

        var usedHeight = 0;
        var chatHeaderHeight = _mobileViewContainer.find('.chat-header').outerHeight();
        usedHeight = usedHeight + chatHeaderHeight;
        if( _mobileViewContainer.find('.chat-footer:visible').length > 0 ) {
            usedHeight = usedHeight + _mobileViewContainer.find('.chat-footer:visible').outerHeight();
        }

        if( _mobileViewContainer.find('.reply').length > 0 ) {
            usedHeight = usedHeight + _mobileViewContainer.find('.reply').outerHeight();
        }

        bpMessagesWrap.find('.bpbm-chat-content').css('max-height', 'calc( 100% - ' + chatHeaderHeight + 'px )');

        var resultHeight = windowHeight - usedHeight;

        _mobileViewContainer.find('.scroller').css({
            'max-height': '',
            'height': resultHeight
        });

        calculateTitle(_mobileViewContainer);
        scrollBottom();

        hidePossibleBreakingElements();

        $(document).trigger("bp-better-messages-mobile-open");

        blockScroll = true;
    }

    if (store.enabled) {
        openThreads = store.get('bp-better-messages-open-threads') || {};
        miniChats = store.get('bp-better-messages-mini-chats') || {};
        miniMessages = store.get('bp-better-messages-mini-messages') || false;
        setInterval(updateOpenThreads, 1000);
    }

    /* <fs_premium_only> */
    if (BP_Messages['realtime'] == "1") {
        realTimeInit();
    }
    /* </fs_premium_only> */

    $(document).ready(function (){
        initialInit();
    });

    function initialInit() {
        isRtl = $('html[dir="rtl"]').length !== 0;
        bpMessagesWrap          = $(".bp-messages-wrap:not(.bp-better-messages-list, .bm-threads-list, #bp-better-messages-mini-mobile-open)");
        var miniMobileContainer = $('#bp-better-messages-mini-mobile-container');
        var mobileViewContainer = '#bp-better-messages-mobile-view-container';
        var mobileOpenButton    = $('#bp-better-messages-mini-mobile-open');

        if( ! isMobile ){
            mobileOpenButton.hide();
        }

        if(isMobile && BP_Messages['mobileFullScreen'] !== '0'){
            var iOS = /iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream;

            $(document).on('touchmove', '.bp-messages-wrap .chat-header,.bp-messages-wrap .reply', function(event) {
                if(blockScroll){
                    event.preventDefault();
                }
            });

            $(document).on('focus blur', '.bp-messages-wrap textarea, .bp-messages-wrap input', function( event ){
                setTimeout(function(){
                    mobileResize();
                    scrollBottom();
                }, 300);
            });

            $( window ).resize(function() {
                if( bpMessagesWrap.hasClass('bp-messages-mobile') ){
                    mobileResize();
                }
            });

            function mobileResize(){
                if( iOS ) {
                    return false;
                }
            }

            bpMessagesWrap.addClass('mobile-ready');

            var touchmoved;
            var blockOpen = false;

            if( BP_Messages['disableTapToOpen'] === '0' ){
                bpMessagesWrap.find('.bp-messages-mobile-tap').css('line-height', bpMessagesWrap.height() + 'px');

                bpMessagesWrap.on('touchend', '.bp-messages-mobile-tap', function(event){

                    if(touchmoved != true && blockOpen === false){
                        var wrap = BPBMJQ(event.target).closest('.bp-messages-wrap');

                        if( ! wrap.hasClass('bp-messages-mobile') ){
                            event.preventDefault();
                            event.stopImmediatePropagation();
                            openMobile( wrap );
                        }
                    }
                }).on('touchmove', function(e){
                    touchmoved = true;
                }).on('touchstart', function(e){
                    touchmoved = false;
                });
            } else {
                bpMessagesWrap.on('touchend', function(event){
                    if(touchmoved != true && blockOpen === false){
                        var wrap = BPBMJQ(event.target).closest('.bp-messages-wrap');
                        if( ! wrap.hasClass('bp-messages-mobile') ){
                            event.preventDefault();
                            event.stopImmediatePropagation();
                            openMobile( wrap );

                            var clickedElement = $(event.originalEvent.target);
                            var threadClicked = clickedElement.closest('.thread');

                            if( threadClicked.length > 0 ){
                                threadClicked.click();
                            }

                        }
                    }
                }).on('touchmove', function(e){
                    touchmoved = true;
                }).on('touchstart', function(e){
                    touchmoved = false;
                });
            }
        }

        $(document).on('click', '.bp-messages-wrap .bpbm-gif .bpbm-gif-play', function(event){
            blockSelect = true;
            var gifPlay = $(this);
            var gif = $(this).parent();
            var video = gif.find('video');

            gifPlay.remove();
            video[0].play();
            setTimeout(function(){
                blockSelect = false;
            }, 500);
        });

        $(document).on('click', '.bp-messages-wrap .mobileClose', function(event){
            var wrap = BPBMJQ(event.target).closest('.bp-messages-wrap');
            if( wrap.hasClass('bp-messages-mobile') ){
                event.preventDefault();
                event.stopImmediatePropagation();

                blockOpen = true;
                $('html').removeClass('bp-messages-mobile').css('overflow', 'auto');
                wrap.removeClass('bp-messages-mobile').css('min-height', '');
                $('body').removeClass('bp-messages-mobile').css('min-height', '');

                /*wrap.find('.scroller').css({
                    'max-height' : height,
                    'height'     : ''
                });*/
                blockScroll = false;

                wrap.find('.bp-messages-mobile-tap').css('line-height', wrap.height() + 'px');

                if( wrap.is(miniMobileContainer) ){
                    miniMobileContainer.hide();
                }

                if( wrap.is(mobileViewContainer) ){
                    var source = wrap;
                    source.removeClass('bp-messages-mobile');
                    source.removeAttr('id');

                    var holder = $('.' + holderClass );
                    source.insertBefore( holder );
                    holder.remove();
                }

                $(window).trigger('resize');

                setTimeout(function () {
                    blockOpen = false;
                }, 100);
            }
        });


        $(document).on('click', '.bp-messages-wrap .expandingButtons', function(event){
            event.stopPropagation();
            $(this).toggleClass('expandingButtonsOpen');
        });

        mobileOpenButton.on('click', function(event){
            event.preventDefault();

            if( ! mobileOpenButton.hasClass('loading') ) {
                mobileOpenButton.addClass('loading');

                openMobileFullScreen( BP_Messages['baseUrl'] );
            }
        });

        var __thread = false;
        var __threads = false

        if ($(".bp-messages-wrap:not(.bp-better-messages-mini,.bp-better-messages-list) .thread.scroller[data-users-json]").length > 0) {
            __thread = $(".bp-messages-wrap:not(.bp-better-messages-mini,.bp-better-messages-list) .thread.scroller[data-users-json]").attr('data-id');
        } else if ($(".bp-messages-wrap:not(.bp-better-messages-mini,.bp-better-messages-list,#bp-better-messages-mini-mobile-container,.bm-threads-list) .threads-list").length > 0) {
            __threads = true;
        }

        if( isMobile ) {
            if( BP_Messages['autoFullScreen'] === '1' ) {
                if (__thread || __threads) {

                    $('#bp-better-messages-mini-mobile-open, #bp-better-messages-mini-mobile-container').remove();
                    var wrap = $('.bp-messages-wrap.mobile-ready.bp-messages-wrap-main, .bp-messages-wrap.mobile-ready.bp-messages-group-thread');
                    openMobile(wrap);
                } else {
                    var wrap = $('.bp-messages-wrap.bp-messages-wrap-bulk.mobile-ready');
                    if (wrap.length > 0) {
                        openMobile(wrap);
                    }
                }

                var times = 0;
                bbAppFix();
                function bbAppFix(){
                    times++;
                    $('.bp-messages-wrap.bbapp_hide_all, .bp-messages-wrap.bbapp_hide_all *').removeClass('bbapp_hide_all');
                    if(times < 10){
                        setTimeout(function(){
                            bbAppFix();
                        }, 500);
                    }
                }
            } else {
                if (__thread || __threads) {
                    $('#bp-better-messages-mini-mobile-open, #bp-better-messages-mini-mobile-container').remove();
                }
            }
        }

        /**
         * Disable scroll page when scrolling chats
         */
        if( BP_Messages['blockScroll'] === '1' ){
            $('.bp-messages-wrap').on( 'mousewheel DOMMouseScroll', '.bpbm-os-viewport', function (e) {
                var e0 = e.originalEvent;
                var delta = e0.wheelDelta || -e0.detail;
                var max = e.currentTarget.scrollHeight - $(e.currentTarget).height();

                //this.scrollTop += ( delta < 0 ? 1 : -1 ) * 5;

                if( delta > 0 ) {
                    if( this.scrollTop < 5 ){
                        e.preventDefault();
                    }
                } else {
                    if( (max - this.scrollTop) < 5){
                        e.preventDefault();
                    }
                }
            });
        }

        reInit();

        if(typeof BP_Messages['socket_server'] === 'undefined' ) {
            setInterval(function () {
                updateLastActivity()
            }, 60000 * 5);

            function updateLastActivity() {
                $.post(BP_Messages.ajaxUrl, {
                    'action': 'bp_messages_last_activity_refresh'
                });
            }
        }

        /**
         * Go to thread from thread list
         */
        bpMessagesWrap.on('click', '.threads-list .thread:not(.blocked)', function (event) {
            if ( $(event.target).closest('.pic').length === 0 &&  $(event.target).closest('.delete').length === 0 && $(event.target).closest('.deleted').length === 0 ) {
                event.preventDefault();
                var href = $(this).attr('data-href');
                var container = $(this).closest('.bp-messages-wrap');
                ajaxRefresh(href, container);
            }
        });

        /**
         * Delete thread! :)
         */
        $(document).on('click', threadsSelector + ' span.delete', function (event) {
            event.preventDefault();
            event.stopPropagation();

            var thread = $(this).parent().parent();
            var scroller = thread.parent().parent();
            var thread_id = $(thread).attr('data-id');
            var height = $(thread).height();

            var nonce = $(this).attr('data-nonce');

            $.post(BP_Messages.ajaxUrl, {
                'action': 'bp_messages_delete_thread',
                'thread_id': thread_id,
                'nonce': nonce
            }, function (data) {
                if (!data.result) {
                    BBPMShowError(data['errors'][0]);
                } else {
                    var top = thread.position().top;
                    //top = top + scroller.scrollTop();

                    $(thread).addClass('blocked');
                    $(thread).find('.deleted').show().css({
                        'height': height,
                        'line-height': height + 'px',
                        'top': top + 'px'
                    });
                }
            });
        });

        /**
         * UnDelete thread! :)
         */
        $(document).on('click', threadsSelector + ' a.undelete', function (event) {
            event.preventDefault();
            event.stopPropagation();

            var thread = $(this).parent().parent();
            var thread_id = $(thread).attr('data-id');
            $(thread).removeClass('blocked');

            var nonce = $(this).attr('data-nonce');

            $.post(BP_Messages.ajaxUrl, {
                'action': 'bp_messages_un_delete_thread',
                'thread_id': thread_id,
                'nonce': nonce
            }, function (data) {
                if (!data.result) {
                    BBPMShowError(data['errors'][0]);
                } else {
                    $(thread).removeClass('blocked');
                    $(thread).find('.deleted').hide();
                }
            });
        });

        /**
         * Messages actions
         */
        bpMessagesWrap.on('click', '.messages-list li .favorite', function (event) {
            event.preventDefault();
            event.stopPropagation();

            var message_id = $(this).parentsUntil('.messages-list', 'li').attr('data-id');
            var type = 'star';
            if ($(this).hasClass('active')) type = 'unstar';

            $(this).toggleClass('active');

            $.post(BP_Messages.ajaxUrl, {
                'action': 'bp_messages_favorite',
                'message_id': message_id,
                'thread_id': thread,
                'type': type
            }, function (bool) {});
        });

        bpMessagesWrap.on('click', '.messages-list li .bpbm-reply', function (event) {
            event.preventDefault();
            event.stopPropagation();

            var message    = $(this).closest('li');
            var stack      = message.closest('.messages-stack');
            var wrap       = stack.closest('.bp-messages-threads-wrapper');
            var message_id = message.attr('data-id');
            var name    = stack.find('.content .info .name a').text();

            var content = '';
            var html_content = '';

            var reply = message.find('.bpbm-replied-message-reply');
            if( reply.length > 0 ){
                content += reply.text();
            } else {
                content += message.find('.message-content').text();
            }

            var descs = message.find('.message-content > [data-desc]');
            if (descs.length > 0 ) {
                descs.each(function(){
                    var _desc = $(this).attr('data-desc');
                    if (typeof _desc !== 'undefined') {
                        html_content += '<span class="bpbm-preview-desc">' + atob(_desc) + '</span>';
                    }
                });
            }


            var html = '<div class="bpbm-preview-message bpbm-reply-message" style="display:none" data-message-id="' + message_id + '">' +
                '<div class="bpbm-preview-message-cancel"><i class="far fa-times-circle"></i></div>' +
                '<div class="bpbm-preview-message-content">' +
                '<span class="bpbm-preview-message-name"></span>' +
                '<div class="bpbm-preview-message-text"></div>' +
                '</div>' +
                '</div>';

            var previewMessage = wrap.find('.bpbm-preview-message');
            if( previewMessage.length > 0 ){
                previewMessage = previewMessage.replaceWith(html);
                previewMessage = wrap.find('.bpbm-preview-message')
                previewMessage.show();
                updateWritingPosition();
            } else {
                previewMessage = $(html).insertBefore(wrap.find('.reply'));
                previewMessage.slideDown(100, function (){
                    updateWritingPosition();
                });
            }
            previewMessage.find('.bpbm-preview-message-name').text(name);
            previewMessage.find('.bpbm-preview-message-text').text(content);
            previewMessage.find('.bpbm-preview-message-text').append(html_content);

            previewMessage.find('.bpbm-gifs-icon').html(icons.gif);
        });

        bpMessagesWrap.on('click', '.bpbm-preview-message-cancel', function (event) {
            event.preventDefault();
            event.stopPropagation();

            var previewMessage = $(this).closest('.bpbm-preview-message');
            previewMessage.slideUp(100, function (){
                previewMessage.remove();
                updateWritingPosition();
            });
        });


        var sendingMessage = false;
        var lastForm = '';
        var lastFormTimeout;

        /*
         * Reply submit
         */
        bpMessagesWrap.on('submit', '.reply > form', function (event) {
            event.preventDefault();
            event.stopImmediatePropagation();

            ifvisible.focus();

            if( sendingMessage === true ) return;

            var _form = $(this);
            if(_form.serialize() === lastForm) return false;
            var textarea = $(this).find('textarea[name="message"]');

            var message = BPBMformatTextArea(textarea);

            var form = $(this).serialize();

            $(this).find('textarea, .bp-emojionearea-editor').html('').val('');
            //sendingMessage = true;
            var _thread = _form.find('input[name="thread_id"]').val();

            var isEdit     =  false;
            var isReply    =  false;

            var container = $(this).parent().parent();
            var threadDiv = container.find('.thread.scroller[data-users-json]');
            var reply     = container.find('.bpbm-preview-message.bpbm-reply-message');
            if( reply.length > 0 ){
                isReply = true;
                form += '&reply=1&message_id=' + parseInt(reply.attr('data-message-id'));
            }

            var edit     = container.find('.bpbm-preview-message.bpbm-edit-message');
            if( edit.length > 0 ){
                isEdit = true;
                form += '&edit=1&message_id=' + parseInt(edit.attr('data-message-id'));
            }

            var usersJson = atob(threadDiv.attr('data-users-json'));
            var recipients = Object.keys($.parseJSON(usersJson));
            var maybeMini = $(this).closest('.bp-better-messages-mini').length > 0;
            if(maybeMini) _thread = $(this).closest('.chat').attr('data-thread');


            var sendFast = BP_Messages['realtime'] === "1";

            if( badWords !== false ) {
                if (badWords.some(function(v) { return message.indexOf(v) >= 0; })) {
                    sendFast = false;
                }
            }

            if( BP_Messages['encryption'] === '1' ){
                var secret_key = threadDiv.data('secret');
                message = BPBMAES256.encrypt(message, secret_key);
            }

            if( _thread && sendFast && ! isEdit && ! isReply ) {

                socket.emit( 'fast_message', _thread, message, '', function(response){
                    lastForm = form;

                    clearInterval(lastFormTimeout);
                    lastFormTimeout = setInterval(function(){ lastForm = ''; }, 3000);

                    $(document).trigger("bp-better-messages-message-sent");
                    if( typeof sounds.sent !== 'undefined' ) {
                        sounds.sent.play();
                    }

                    scrollBottom('.bp-messages-wrap[data-thread-id="' +  _thread + '"]');
                    scrollBottom('.bp-better-messages-mini .chats .chat[data-thread="' +  _thread + '"]');

                    form += '&tempID=' + response;
                    $.post(BP_Messages.ajaxUrl, form, function (data) {
                        if (typeof data.result == 'undefined') return;

                        $.each(data['errors'], function(){
                            BBPMShowError(this);
                        });

                        if( typeof data.redirect !== 'undefined' ){
                            if( data.redirect === 'refresh' ){
                                var wrap = _form.closest('.bp-messages-wrap');
                                if( wrap.hasClass('bp-better-messages-mini') ){
                                    $('.bp-better-messages-mini .chats .chat[data-thread="' + _thread + '"]').remove();
                                    openMiniChat( _thread, true );
                                } else {
                                    ajaxRefresh(location.href, _form.closest('.bp-messages-wrap'));
                                }
                            }
                        }
                    }).always(function() {
                        sendingMessage = false;
                    });
                });
            } else {
                $.post(BP_Messages.ajaxUrl, form, function (data) {
                    if (typeof data.result == 'undefined') return;
                    if (data.result !== false) {
                        refreshThread();
                        $(document).trigger("bp-better-messages-message-sent");

                        if( ! isEdit ) {

                            if( typeof sounds.sent !== 'undefined' ) {
                                sounds.sent.play();
                            }

                            scrollBottom('.bp-messages-wrap[data-thread-id="' + _thread + '"]');
                            scrollBottom('.bp-better-messages-mini .chats .chat[data-thread="' + _thread + '"]');
                        }

                        lastForm = form;
                        clearInterval(lastFormTimeout);
                        lastFormTimeout = setInterval(function(){lastForm = ''}, 3000);

                        if( isReply ){
                            reply.find('.bpbm-preview-message-cancel').click();
                        }

                        if( isEdit ){
                            edit.find('.bpbm-preview-message-cancel').click();
                            if ( BP_Messages['realtime'] != "1" ) {
                                ajaxRefresh(location.href, _form.closest('.bp-messages-wrap'));
                            }
                        }

                    } else {
                        $.each(data['errors'], function(){
                            BBPMShowError(this);
                        });

                        if( typeof data.redirect !== 'undefined' ){
                            if( data.redirect === 'refresh' ){
                                ajaxRefresh(location.href, _form.closest('.bp-messages-wrap'));
                            }
                        }

                    }
                }).always(function() {
                    sendingMessage = false;
                });
            }

            $(document).trigger("bp-better-messages-message-sent-end");
        });

        bpMessagesWrap.on('click ', '.bpbm-stickers-selector .bpbm-stickers-selector-sticker', function (event) {
            event.preventDefault();
            event.stopPropagation();

            var sticker  = $(this);
            var stickersDiv = sticker.closest('.bpbm-stickers-selector');
            var container   = stickersDiv.parent();
            var formEl      = container.find('.reply form');

            var stickerId  = sticker.data('sticker-id');
            var stickerImg = sticker.find('img').attr('src');
            var threadId   = formEl.find('input[name="thread_id"]').val();
            var nonce      = formEl.find('input[name="_wpnonce"]').val();

            stickersDiv.hide();
            makeHeightBeautiful();

            $.post(BP_Messages.ajaxUrl, {
                'action'      : 'bpbm_messages_send_sticker',
                'thread_id'   : threadId,
                'sticker_id'  : stickerId,
                'sticker_img' : stickerImg,
                '_wpnonce'    : nonce,
            }, function (data) {
            });
        });

        bpMessagesWrap.on('click ', '.bpbm-gifs-selector .bpbm-gifs-selector-gif', function (event) {
            event.preventDefault();
            event.stopPropagation();

            var gif        = $(this);
            var gifsDiv    = gif.closest('.bpbm-gifs-selector');
            var container  = gifsDiv.parent();
            var formEl     = container.find('.reply form');

            var gifId      = gif.data('gif-id');
            var threadId   = formEl.find('input[name="thread_id"]').val();
            var nonce      = formEl.find('input[name="_wpnonce"]').val();

            gifsDiv.hide();
            makeHeightBeautiful();

            $.post(BP_Messages.ajaxUrl, {
                'action'      : 'bpbm_messages_send_gif',
                'thread_id'   : threadId,
                'gif_id'      : gifId,
                '_wpnonce'    : nonce,
            }, function (data) {});
        });

        bpMessagesWrap.on('click touchstart', '.reply .bpbm-stickers-btn', function (event) {
            event.preventDefault();
            event.stopPropagation();

            var replyDiv = $(this).closest('.reply');
            var wrapper  = replyDiv.parent();
            var formEl   = replyDiv.find('form');
            var textarea = formEl.find('textarea');
            var stickersDiv = wrapper.find('.bpbm-stickers-selector');
            textarea.blur();

            if( ! stickersDiv.is(':visible') ){
                stickersDiv.show();
                //makeHeightBeautiful();
            }
        });

        bpMessagesWrap.on('click touchstart', '.reply .bpbm-gifs-btn', function (event) {
            event.preventDefault();
            event.stopPropagation();

            var replyDiv = $(this).closest('.reply');
            var wrapper  = replyDiv.parent();
            var formEl   = replyDiv.find('form');
            var textarea = formEl.find('textarea');
            var gifDiv = wrapper.find('.bpbm-gifs-selector');
            textarea.blur();

            if( ! gifDiv.is(':visible') ){
                gifDiv.show();
                gifDiv.find('.bpbm-gifs-tabs span[data-package-id="trending"]').click();
                //makeHeightBeautiful();
            }
        });

        bpMessagesWrap.on('click', '.bpbm-gifs-selector .bpbm-gifs-close', function (event) {
            event.preventDefault();
            event.stopPropagation();
            var gifDiv = $(this).closest('.bpbm-gifs-selector');
            gifDiv.hide();
            gifDiv.find('.bpbm-gifs-tabs .bpbm-gifs-tabs-active').removeClass('bpbm-gifs-tabs-active');
            gifDiv.find('.bpbm-gifs-selector-gif-list').html('');
        });

        bpMessagesWrap.on('click', '.bpbm-gifs-selector .bpbm-gifs-head .bpbm-gifs-tabs span', function(event){
            event.preventDefault();
            event.stopPropagation();

            var activeClass  = 'bpbm-gifs-tabs-active';
            var tab          = $(this);
            var gifDiv       = tab.closest('.bpbm-gifs-selector');
            var gifContainer = gifDiv.find('.bpbm-gifs-selector-gif-container');
            if( ! tab.hasClass(activeClass) ){
                gifDiv.find('.bpbm-gifs-tabs span').removeClass(activeClass);
                tab.addClass(activeClass);
                gifContainer.html(loadingHtml);


                var selected = tab.data('package-id');
                $.post(BP_Messages.ajaxUrl, {
                    'action'  : 'bpbm_messages_get_gif_tab',
                    'package' : selected,
                }, function (data) {
                    gifContainer.html( data );

                    if( selected === 'trending' ) {
                        var loadingClass = 'bpbm-loading-gifs';

                        gifContainer.on('scroll', function (event){
                            event.stopImmediatePropagation();
                            var elem = $(event.currentTarget);
                            var height = elem.outerHeight() + 150;

                            if(elem[0].scrollHeight - elem.scrollTop() <= height){
                                var gifsList = gifContainer.find('.bpbm-gifs-selector-gif-list');
                                if ( ! gifsList.hasClass(loadingClass) ) {
                                    var maxPages   = gifsList.data('pages');
                                    var pageToLoad = gifsList.data('pages-loaded') + 1;

                                    if( pageToLoad < maxPages ) {
                                        gifsList.addClass(loadingClass);
                                        gifsSearchLoading = $.post(BP_Messages.ajaxUrl, {
                                            'action'  : 'bpbm_messages_get_gif_tab',
                                            'package' : selected,
                                            'page': pageToLoad
                                        }, function (response) {
                                            gifsList.data('pages-loaded', pageToLoad);
                                            $(response).appendTo(gifsList);
                                            gifsList.removeClass(loadingClass);
                                        });
                                    }
                                }
                            }
                        });
                    }
                });
            }
        });

        bpMessagesWrap.on('click', '.bpbm-stickers-selector .bpbm-stickers-close', function (event) {
            event.preventDefault();
            event.stopPropagation();

            var stickersDiv = $(this).closest('.bpbm-stickers-selector');
            var container   = stickersDiv.parent();

            stickersDiv.hide();
        });

        bpMessagesWrap.on('click', '.bpbm-stickers-selector .bpbm-stickers-head .bpbm-stickers-tabs span', function(event){
            event.preventDefault();
            event.stopPropagation();

            var tab      = $(this);
            var stickersDiv = tab.closest('.bpbm-stickers-selector');
            var stickersContainer = stickersDiv.find('.bpbm-stickers-selector-sticker-container');

            stickersDiv.find('.bpbm-stickers-tabs span').removeClass('bpbm-stickers-tabs-active');
            tab.addClass('bpbm-stickers-tabs-active');
            stickersContainer.html(loadingHtml);

            var selected = tab.data('package-id');
            $.post(BP_Messages.ajaxUrl, {
                'action'  : 'bpbm_messages_get_sticker_tab',
                'package' : selected,
            }, function (data) {
                stickersContainer.html( data );
            });
        });

        var gifsSearchLoading;

        bpMessagesWrap.on('keyup change', '.bpbm-gifs-tabs input[name="search"]', function(event){
            event.preventDefault();
            event.stopPropagation();

            var input         = $(this);
            var gifsDiv       = input.closest('.bpbm-gifs-selector');
            var gifsContainer = gifsDiv.find('.bpbm-gifs-selector-gif-container');
            var gifsList      = gifsDiv.find('.bpbm-gifs-selector-gif-list');

            var loadingSearch = input.data('search-term');
            var newSearch = input.val();

            if( loadingSearch !== newSearch ) {
                input.data('search-term', newSearch);
                if (gifsSearchLoading) {
                    gifsSearchLoading.abort();
                }

                var loadingClass = 'bpbm-loading-gifs';

                gifsList.addClass(loadingClass);
                gifsSearchLoading = $.post(BP_Messages.ajaxUrl, {
                    'action': 'bpbm_messages_search_gifs',
                    'search': newSearch
                }, function (data) {
                    gifsList.replaceWith(data);

                    gifsContainer.on('scroll', function (event){
                        event.stopImmediatePropagation();
                        var elem = $(event.currentTarget);
                        var height = elem.outerHeight() + 150;

                        if(elem[0].scrollHeight - elem.scrollTop() <= height){
                            gifsList = gifsDiv.find('.bpbm-gifs-selector-gif-list');
                            if ( ! gifsList.hasClass(loadingClass) ) {
                                var maxPages   = gifsList.data('pages');
                                var pageToLoad = gifsList.data('pages-loaded') + 1;

                                if( pageToLoad < maxPages ) {
                                    gifsList.addClass(loadingClass);
                                    gifsSearchLoading = $.post(BP_Messages.ajaxUrl, {
                                        'action': 'bpbm_messages_search_gifs',
                                        'search': newSearch,
                                        'page': pageToLoad
                                    }, function (response) {
                                        gifsList.data('pages-loaded', pageToLoad);
                                        $(response).appendTo(gifsList);
                                        gifsList.removeClass(loadingClass);
                                    });
                                }
                            }
                        }
                    });
                });
            }
        });

        var stickersSearchLoading;

        bpMessagesWrap.on('keyup change', '.bpbm-stickers-selector .bpbm-stickers-search input', function(event){
            event.preventDefault();
            event.stopPropagation();

            var input        = $(this);
            var searchDiv    = input.closest('.bpbm-stickers-search');
            var stickersDiv  = input.closest('.bpbm-stickers-selector');
            var stickersList = stickersDiv.find('.bpbm-stickers-selector-sticker-list');

            var loadingSearch = searchDiv.data('search-term');
            var newSearch = input.val();

            if( loadingSearch !== newSearch ) {
                searchDiv.data('search-term', newSearch);
                if (stickersSearchLoading) {
                    stickersSearchLoading.abort();
                }

                stickersSearchLoading = $.post(BP_Messages.ajaxUrl, {
                    'action': 'bpbm_messages_search_stickers',
                    'search': newSearch
                }, function (data) {
                    stickersList.replaceWith(data);
                    stickersList = stickersDiv.find('.bpbm-stickers-selector-sticker-list');

                    stickersList.BPBMoverlayScrollbars({
                        'sizeAutoCapable': false,
                        callbacks : {
                            onScroll : function( arg1 ){
                                var position  = this.scroll();
                                var scroll    = position.position.y;
                                var height    = position.max.y;

                                if( height - scroll <= 10 ) {
                                    var elements     = this.getElements();
                                    var host         = BPBMJQ(elements.host);
                                    var loadingClass = 'bpbm-loading-stickers';
                                    if( ! host.hasClass(loadingClass) ){
                                        var maxPages   = host.data('pages');
                                        var pageToLoad = host.data('pages-loaded') + 1;
                                        if( pageToLoad <= maxPages ){
                                            host.addClass(loadingClass);
                                            $.post(BP_Messages.ajaxUrl, {
                                                'action' : 'bpbm_messages_search_stickers',
                                                'search' : newSearch,
                                                'page'   : pageToLoad
                                            }, function(response){
                                                host.data('pages-loaded', pageToLoad);
                                                $(response).appendTo( BPBMJQ(elements.content) );
                                                host.removeClass(loadingClass);
                                            });
                                        }
                                    }

                                }
                            }
                        }
                    });
                });
            }
        });


        /**
         * New Thread Submit
         */
        bpMessagesWrap.on('submit', '.new-message form', function (event) {
            event.preventDefault();
            event.stopPropagation();

            var container = BPBMJQ(event.target).closest('.bp-messages-wrap');

            showPreloader(container);
            //$('.bp-messages-wrap:not(.bp-better-messages-mini,.bp-better-messages-list) .preloader').show();

            var textarea = $(this).find('textarea[name="message"]');

            BPBMformatTextArea(textarea);

            var form = $(this);
            var data = form.serialize();

            $(document).trigger("bp-better-messages-new-thread-start");

            $.post(BP_Messages.ajaxUrl, data, function (data) {
                if (data.result) {
                    $(document).trigger("bp-better-messages-new-thread-created");
                    ajaxRefresh(BP_Messages.threadUrl + data['result'], container);
                } else {
                    $(document).trigger("bp-better-messages-new-thread-error");
                    form.closest('.bp-messages-wrap').find('.preloader').hide();

                    $.each(data['errors'], function(){
                        BBPMShowError(this);
                    });
                }

                $(document).trigger("bp-better-messages-new-thread-end");
            }).fail(function() {
                form.closest('.bp-messages-wrap').find('.preloader').hide();

                $(document).trigger("bp-better-messages-new-thread-end");
            });
        });

        /**
         * Switches screens without page reloading
         */
        bpMessagesWrap.on('click', 'a.ajax', function (event) {
            event.preventDefault();
            event.stopPropagation();

            var href = $(this).attr('href');
            var container = $(this).closest('.bp-messages-wrap');

            ajaxRefresh(href, container);
        });

        /**
         *  Search form functions
         */
        bpMessagesWrap.on('click', '.bpbm-search a.search', function (event) {
            event.preventDefault();
            event.stopPropagation();

            $(this).hide();
            $('.bpbm-search form').show();
            $('.bpbm-search form input').trigger('focus');

            if( isMobile ){
                $('.bp-messages-wrap .chat-header .settings').hide();
            }
        });

        bpMessagesWrap.on('click', '.bpbm-search form span.close', function (event) {
            event.preventDefault();
            event.stopPropagation();

            var form = $(this).closest('.bpbm-search');
            var input = form.find('form input');
            if( form.closest('.bp-messages-side-threads').length > 0 ){
                input.val('');
                input.trigger('change');
                form.find('form .close').hide();
            } else {
                form.find('form').hide();
                form.find('a.search').show();
                input.val('');
            }

        });


        bpMessagesWrap.on('submit', '.bpbm-search form', function (event) {
            event.preventDefault();
            var container = $(this).closest('.bp-messages-wrap');
            ajaxRefresh(BP_Messages['url'] + urlSeparator + $(this).serialize(), container );
        });

        /**
         * Send message on Enter
         */
        if( (BP_Messages['disableEnterForTouch'] === '1' && isMobile || BP_Messages['disableEnterForDesktop'] === '1' && !isMobile) === false ){

            bpMessagesWrap.on('keydown', '.reply .bp-emojionearea-editor', function (event) {
                if ( ! event.shiftKey && event.keyCode == 13 ) {
                    event.preventDefault();
                    event.stopImmediatePropagation();
                    $(this).trigger('blur')
                    $(this).parent().parent().trigger("submit");
                    $(this).trigger('focus');
                }
            });

            bpMessagesWrap.on('keyup', '.reply .bp-emojionearea-editor', function (event) {
                if ( ! event.shiftKey && event.keyCode == 13 ) {
                    event.preventDefault();
                    event.stopImmediatePropagation();
                }
            });
        }

        bpMessagesWrap.on('change', '.new-message .send-to-input', function (event) {
            event.preventDefault();
            event.stopPropagation();

            var href = $(this).attr('href');
            var container = $(this).closest('.bp-messages-wrap');

            ajaxRefresh(href, container);
        });


        if( isMobile ){
            bpMessagesWrap.on('touchend', '.scroller.starred .messages-list li, .scroller.search .messages-list li', function(event){
                if(touchmoved != true && blockOpen === false){
                    event.preventDefault();
                    event.stopPropagation();

                    var thread_id = $(this).attr('data-thread');
                    var message_id = $(this).attr('data-id');
                    ajaxRefresh(BP_Messages.threadUrl + thread_id + '&message_id=' + message_id, $(this).closest('.bp-messages-wrap'));
                }
            }).on('touchmove', function(e){
                touchmoved = true;
            }).on('touchstart', function(e){
                touchmoved = false;
            });
        } else {
            bpMessagesWrap.on('click', '.scroller.starred .messages-list li, .scroller.search .messages-list li', function (event) {
                event.preventDefault();
                event.stopPropagation();

                var thread_id = $(this).attr('data-thread');
                var message_id = $(this).attr('data-id');
                ajaxRefresh(BP_Messages.threadUrl + thread_id + '&message_id=' + message_id, $(this).closest('.bp-messages-wrap'));
            });
        }

        /**
         * Remove users from group thread
         */
        bpMessagesWrap.on('click', '.participants-panel .bp-messages-user-list .user .actions a.remove-from-thread', function (event) {
            event.preventDefault();
            var container = $(this).closest('.bp-messages-wrap');
            var user = $(this).parent().parent();
            var user_id = user.data('id');
            var thread_id = user.data('thread-id');
            var username = user.find('.name').text();

            var excl_msg = BP_Messages['strings']['exclude'];
            if( container.hasClass('bp-messages-wrap-chat') ){
                excl_msg = BP_Messages['strings']['exclude_chat'];
            }
            excl_msg = excl_msg.replace('%s', username);

            var exclude = confirm(excl_msg);

            if(exclude){
                $.post(BP_Messages.ajaxUrl, {
                    action: 'bp_better_messages_exclude_user_from_thread',
                    user_id: user_id,
                    thread_id: thread_id,
                    nonce: BP_Messages['userNonce']
                }, function(response){
                    if(response.result === true){
                        var url = BP_Messages['url'] + urlSeparator + $.param({thread_id: thread_id, participants: "1"});
                        ajaxRefresh(url, container);
                    }
                });
            }
        });

        /**
         * Mute thread
         */
        bpMessagesWrap.on('click', '.bpbm-mute-thread', function (event) {
            event.preventDefault();

            var container = $(this).closest('.bp-messages-wrap');
            var isMini = $(this).closest('.bp-better-messages-mini').length > 0;
            var url = location.href;
            var thread_id;

            if(isMini) {
                thread_id = $(this).closest('.chat').attr('data-thread');
            } else {
                thread_id = container.attr('data-thread-id');

                if (container.is('#bp-better-messages-mini-mobile-container')) {
                    thread_id = container.attr('data-thread');
                    url = BP_Messages['baseUrl'] + '?thread_id=' + thread_id;
                }
            }

            if( typeof thread_id === 'undefined' ) return false;

            if(url.indexOf('?thread_id=') === -1) {
                url = BP_Messages['baseUrl'] + '?thread_id=' + thread_id;
            }

            var confirmDelete = confirm(BP_Messages['strings']['mute_thread']);

            if( confirmDelete ){

                if( isMini ) {
                    showPreloader($(this).closest('.chat'));
                } else {
                    showPreloader(container);
                }

                $.post( BP_Messages[ 'ajaxUrl' ], {
                    'action'       : 'bp_messages_mute_thread',
                    'thread_id'    : thread_id,
                    nonce          : BP_Messages['userNonce']
                }, function (response) {
                    if( isMini ){
                        openMiniChat( thread_id, true, true );
                    } else {
                        ajaxRefresh(url, container);
                    }
                    var counterRow = $(threadsSelector + '[data-id="' + thread_id + '"] .bpbm-counter-row');
                    counterRow.prepend('<span class="bpbm-thread-muted"><i class="fas fa-bell-slash"></i></span>');

                    BP_Messages.mutedThreads[ thread_id ] = Date.now();
                }).always(function() {
                });
            }
        });

        /**
         * Leave thread
         */
        bpMessagesWrap.on('click', '.bpbm-leave-thread', function (event) {
            event.preventDefault();
            var container = $(this).closest('.bp-messages-wrap');
            var isMini = $(this).closest('.bp-better-messages-mini').length > 0;
            var url = location.href;
            var thread_id;

            if(isMini) {
                thread_id = $(this).closest('.chat').attr('data-thread');
            } else {
                thread_id = container.attr('data-thread-id');

                if (container.is('#bp-better-messages-mini-mobile-container')) {
                    thread_id = container.attr('data-thread');
                    url = BP_Messages['baseUrl'] + '?thread_id=' + thread_id;
                }
            }

            if( typeof thread_id === 'undefined' ) return false;

            var confirmDelete = confirm(BP_Messages['strings']['leave_thread']);

            if( confirmDelete ){
                if( isMini ) {
                    showPreloader($(this).closest('.chat'));
                } else {
                    showPreloader(container);
                }

                $.post( BP_Messages[ 'ajaxUrl' ], {
                    'action'       : 'bp_messages_leave_thread',
                    'thread_id'    : thread_id,
                    nonce: BP_Messages['userNonce']
                }, function (response) {
                    if( response ){
                        if(typeof socket !== 'undefined') {
                            socket.emit('threadOpen', thread_id);
                        }
                        $(threadsSelector + '[data-id="' + thread_id + '"]').remove();

                        if( isMini ){
                            $('.bp-better-messages-mini .chats .chat[data-thread="' + thread_id + '"] > .head .close').click();
                        } else {
                            ajaxRefresh(BP_Messages['baseUrl'], container);
                        }
                    } else {
                        container.find('.preloader').hide();
                    }
                });
            }
        });

        bpMessagesWrap.on('click', '.bpbm-delete-thread', function (event) {
            event.preventDefault();

            var container = $(this).closest('.bp-messages-wrap');
            var isMini = $(this).closest('.bp-better-messages-mini').length > 0;
            var url = location.href;
            var thread_id;

            if(isMini) {
                thread_id = $(this).closest('.chat').attr('data-thread');
            } else {
                thread_id = container.attr('data-thread-id');

                if (container.is('#bp-better-messages-mini-mobile-container')) {
                    thread_id = container.attr('data-thread');
                    url = BP_Messages['baseUrl'];
                }
            }

            if( typeof thread_id === 'undefined' ) return false;

            if(url.indexOf('?thread_id=') === -1) {
                url = BP_Messages['baseUrl'];
            }

            var confirmDelete = confirm(BP_Messages['strings']['delete_thread']);

            if( confirmDelete ){

                if( isMini ) {
                    showPreloader($(this).closest('.chat'));
                } else {
                    showPreloader(container);
                }

                $.post( BP_Messages[ 'ajaxUrl' ], {
                    'action'    : 'bp_messages_erase_thread',
                    'thread_id' : thread_id,
                    '_wpnonce'  : BP_Messages['userNonce']
                }, function (response) {
                    $('.bp-messages-wrap .threads-list .thread[data-id="' + thread_id + '"]').remove();
                    $('.bp-better-messages-mini .chats .chat[data-thread="' + thread_id + '"] .head span.close').click();
                    if( ! isMini ){
                        ajaxRefresh(url, container);
                    }
                }).always(function() {
                });
            }
        });


        bpMessagesWrap.on('click', '.bpbm-clear-thread', function (event) {
            event.preventDefault();

            var container = $(this).closest('.bp-messages-wrap');
            var isChat   = container.hasClass('bp-messages-wrap-chat');
            var isGroup   = container.hasClass('bp-messages-group-thread');
            var isMini = $(this).closest('.bp-better-messages-mini').length > 0;
            var url = location.href;
            var thread_id;

            if(isMini) {
                thread_id = $(this).closest('.chat').attr('data-thread');
            } else {
                thread_id = container.attr('data-thread-id');

                if (container.is('#bp-better-messages-mini-mobile-container')) {
                    thread_id = container.attr('data-thread');
                    url = BP_Messages['baseUrl'];
                }
            }

            if( typeof thread_id === 'undefined' ) return false;

            if(url.indexOf('?thread_id=') === -1) {
                url = BP_Messages['baseUrl'];
            }

            if( isChat || isGroup ){
                url = BP_Messages['baseUrl'] + '?thread_id=' + thread_id;
            }

            var confirmDelete = confirm(BP_Messages['strings']['clear_chat_thread']);

            if( confirmDelete ){

                if( isMini ) {
                    showPreloader($(this).closest('.chat'));
                } else {
                    showPreloader(container);
                }

                $.post(BP_Messages['ajaxUrl'], {
                    'action': 'bp_messages_clear_thread',
                    'thread_id': thread_id,
                    '_wpnonce': BP_Messages['userNonce']
                }, function (response) {
                    if (isMini) {
                        openMiniChat(thread_id, true, true);
                    } else {
                        ajaxRefresh(url, container);
                    }
                }).always(function () {
                });
            }
        });

        bpMessagesWrap.on('click', '.chat-header .bpbm-invite-thread', function (event) {
            event.preventDefault();
            var container = $(this).closest('.bp-messages-wrap');

            var addUserPanel = container.find('.add-user-panel');
            var threadScroll = container.find('.scroller.thread');
            var participants = container.find('.participants-panel');

            if( ! addUserPanel.hasClass('open') ){
                addUserPanel.addClass('open');
                participants.removeClass('open');
                threadScroll.hide();
            }
        });

        bpMessagesWrap.on('click', '.chat-header .participants', function (event) {
            event.preventDefault();
            var container = $(this).closest('.bp-messages-wrap');

            var participants = container.find('.participants-panel');
            var threadScroll = container.find('.scroller.thread');
            var addUserPanel = container.find('.add-user-panel');
            var thread_id = parseInt(container.attr('data-thread-id'));

            if(isNaN(thread_id)){
                thread_id = parseInt(container.attr('data-thread'));
            }

            if( ! participants.hasClass('participants-loaded') ){
                participants.addClass('participants-loaded');

                $.post( BP_Messages[ 'ajaxUrl' ], {
                    'action'       : 'bp_messages_load_thread_participants',
                    'thread_id'    : thread_id
                }, function (response) {
                    participants.find('.bp-messages-user-list').html(response);
                }).always(function() {
                });
            }

            if( ! participants.hasClass('open') ){
                participants.addClass('open');
                addUserPanel.removeClass('open');
                threadScroll.hide();
            } else {
                participants.removeClass('open');
                threadScroll.show();
            }
        });


        /**
         * Mute thread
         */
        bpMessagesWrap.on('click', '.bpbm-unmute-thread', function (event) {
            event.preventDefault();
            var container = $(this).closest('.bp-messages-wrap');
            var isMini = $(this).closest('.bp-better-messages-mini').length > 0;
            var url = location.href;
            var thread_id;

            if(isMini) {
                thread_id = $(this).closest('.chat').attr('data-thread');
            } else {
                thread_id = container.attr('data-thread-id');

                if (container.is('#bp-better-messages-mini-mobile-container')) {
                    thread_id = container.attr('data-thread');
                    url = BP_Messages['baseUrl'] + '?thread_id=' + thread_id;
                }
            }

            var confirmDelete = confirm(BP_Messages['strings']['unmute_thread']);

            if( confirmDelete ){

                if( isMini ) {
                    showPreloader($(this).closest('.chat'));
                } else {
                    showPreloader(container);
                }

                $.post( BP_Messages[ 'ajaxUrl' ], {
                    'action'       : 'bp_messages_unmute_thread',
                    'thread_id'    : thread_id,
                    nonce          : BP_Messages['userNonce']
                }, function (response) {
                    if( typeof BP_Messages.mutedThreads[ thread_id ] !== 'undefined' ){
                        delete BP_Messages.mutedThreads[ thread_id ];
                    }

                    $(threadsSelector + '[data-id="' + thread_id + '"] .bpbm-counter-row .bpbm-thread-muted').remove();

                    if( isMini ){
                        openMiniChat( thread_id, true, true );
                    } else {
                        ajaxRefresh(url, container);
                    }
                }).always(function() {
                });
            }
        });

        /**
         * Add new users to group thread
         */
        bpMessagesWrap.on('click', '.add-user button[type="submit"]', function (event) {
            event.preventDefault();
            var container = $(this).closest('.bp-messages-wrap');
            var form      = $(this).closest('.add-user');
            var thread_id = form.data('thread-id');
            var users = [];

            form.find( 'input[name="recipients[]"]' ).each(function(){
                users.push( $(this).val() );
            });

            showPreloader( container );

            $.post(BP_Messages.ajaxUrl, {
                action: 'bp_better_messages_add_user_to_thread',
                users: users,
                thread_id: thread_id,
                nonce: BP_Messages['userNonce']
            }, function(response){
                var url = BP_Messages['url'] + urlSeparator + $.param( { thread_id: thread_id, participants: "1" });
                ajaxRefresh(url, container);
            });
        });

        bpMessagesWrap.on('click', '.add-user button.bpbm-close', function (event){
            event.preventDefault();
            var container = $(this).closest('.bp-messages-wrap');

            var addUserPanel = container.find('.add-user-panel');
            var threadScroll = container.find('.scroller.thread');

            if( addUserPanel.hasClass('open') ){
                addUserPanel.removeClass('open');
                threadScroll.show();
            }
        });

        bpMessagesWrap.on('click', '.bpbm-join-to-chat-button', function (event){
            event.preventDefault();
            var container = $(this).closest('.bp-messages-wrap');
            var chat_id = container.data('chat-id');
            var thread_id = container.data('thread-id');
            showPreloader( container );

            $.post(BP_Messages.ajaxUrl, {
                action: 'bp_better_messages_join_chat',
                chat_id: chat_id,
                nonce: BP_Messages['userNonce']
            }, function(response){
                var url = BP_Messages['url'] + urlSeparator + $.param( { thread_id: thread_id });
                ajaxRefresh(url, container);
            });
        });

        bpMessagesWrap.on('click', '.bpbm-leave-chat-room', function (event){
            event.preventDefault();
            var container = $(this).closest('.bp-messages-wrap');
            var chat_id = container.data('chat-id');
            var thread_id = container.data('thread-id');
            showPreloader( container );

            $.post(BP_Messages.ajaxUrl, {
                action: 'bp_better_messages_leave_chat',
                chat_id: chat_id,
                nonce: BP_Messages['userNonce']
            }, function(response){
                var url = BP_Messages['url'] + urlSeparator + $.param( { thread_id: thread_id });
                ajaxRefresh(url, container);
            });
        });





        /* <fs_premium_only> */
        if(BP_Messages['miniChats'] == '1') {
            // Mini Chats
            $(document).on('click', '.bp-better-messages-mini .chats .chat > .head', function (event) {
                var chat = $(this).parent();
                var thread_id = chat.attr('data-thread');
                var state = chat.toggleClass('open');

                if (state.hasClass('open')) {
                    miniChats[thread_id] = true;
                    scrollBottom('.bp-messages-wrap.bp-better-messages-mini .chats .chat[data-thread="' + thread_id + '"]');
                    if (BP_Messages['realtime'] == '1') {
                        reInit();

                        var unreadMessages = $('.bp-messages-wrap.bp-better-messages-mini .chats .chat[data-thread="' + thread_id + '"] .list .messages-stack .content .messages-list li.unread:not(.fast)');
                        var messagesIds = [];

                        unreadMessages.each(function () {
                            var message_id = $(this).data('id');
                            var thread_id = $(this).data('thread');
                            var date = $(this).attr('data-time');
                            messagesIds.push(message_id);
                            $(this).removeClass('unread');
                        });

                        socket.emit('threadOpen', thread_id);
                        if(messagesIds.length > 0) socket.emit('seen', messagesIds);
                    }
                } else {
                    miniChats[thread_id] = false;
                }

                store.set('bp-better-messages-mini-chats', miniChats);
            });

            $(document).on('click', '.bp-better-messages-mini .chats .chat > .head .video-call', function (event) {
                event.stopPropagation();
                event.stopImmediatePropagation();

                var user_id = BPBMJQ(this).data('user-id');
                if( online.indexOf(user_id.toString()) === -1 ){
                    BBPMShowError(BP_Messages['strings']['call_offline']);
                } else {
                    var chat = $(this).parent().parent().parent();
                    var thread_id = chat.attr('data-thread');
                    chat.fadeOut();

                    var url = BP_Messages.threadUrl + thread_id + '&videoCall';
                    var mainContainer = $('.bp-messages-wrap.bp-messages-wrap-main');
                    if (mainContainer.length > 0) {
                        ajaxRefresh(url, mainContainer);
                    } else {
                        location.href = url;
                    }
                }
            });

            $(document).on('click', '.bp-better-messages-mini .chats .chat > .head .audio-call', function (event) {
                event.stopPropagation();
                event.stopImmediatePropagation();
                var user_id = BPBMJQ(this).data('user-id');
                if( online.indexOf(user_id.toString()) === -1 ){
                    BBPMShowError(BP_Messages['strings']['call_offline']);
                } else {
                    var chat = $(this).parent().parent().parent();
                    var thread_id = chat.attr('data-thread');
                    chat.fadeOut();

                    var url = BP_Messages.threadUrl + thread_id + '&audioCall';
                    var mainContainer = $('.bp-messages-wrap.bp-messages-wrap-main');
                    if (mainContainer.length > 0) {
                        ajaxRefresh(url, mainContainer);
                    } else {
                        location.href = url;
                    }
                }
            });

            $(document).on('click', '.bp-better-messages-mini .chats .chat > .head .open', function (event) {
                event.stopImmediatePropagation();
                var chat = $(this).parent().parent().parent();
                var thread_id = chat.attr('data-thread');
                chat.fadeOut();

                var url = BP_Messages.threadUrl + thread_id + '&scrollToContainer';
                var mainContainer = $('.bp-messages-wrap.bp-messages-wrap-main');
                if( mainContainer.length > 0 ){
                    ajaxRefresh(url, mainContainer);
                } else {
                    location.href = url;
                }
            });

            $(document).on('click', '.bp-better-messages-mini .chats .chat > .head .close', function (event) {
                event.stopImmediatePropagation();
                var chat = $(this).parent().parent().parent();
                var thread_id = chat.attr('data-thread');
                chat.slideUp(function () {
                    chat.remove();
                });

                if (typeof(miniChats[thread_id]) !== 'undefined') delete miniChats[thread_id];
                store.set('bp-better-messages-mini-chats', miniChats);
            });

            $('.bp-messages-wrap:not(.bp-better-messages-mini,.bp-better-messages-list)').on('click', '.chat-header > .mini-chat', function (event) {
                var button    = $(this);
                var chat      = button.closest('.bp-messages-wrap');
                var thread_id = chat.attr('data-thread-id');

                if (typeof miniChats[thread_id] !== 'undefined') delete miniChats[thread_id];

                if( button.hasClass('group-redirect')) {
                    miniChats[thread_id] = true;
                    store.set('bp-better-messages-mini-chats', miniChats);
                } else {
                    openMiniChat(thread_id, true);
                }
            });
        }
        /* </fs_premium_only> */

        /* <fs_premium_only> */
        if(BP_Messages['miniMessages'] == '1') {

            $(document).on('click', '.bp-better-messages-list .threads-list .thread:not(.blocked)', function (event) {
                event.preventDefault();

                var thread = $(this);
                var thread_id = thread.data('id');
                if (BP_Messages['miniChats'] == '1') {
                    var scroller = thread.parent().parent();
                    var height = $(thread).height();
                    var top = thread.position().top;
                    top = top + scroller.scrollTop();

                    thread.addClass('blocked loading');

                    $(thread).find('.loading').css({
                        'height': height,
                        'line-height': height + 'px',
                        'top': top + 'px'
                    });

                    openMiniChat(thread_id, true).always(function (done) {
                        reInit();
                        thread.removeClass('blocked loading');
                    });
                } else {
                    var url = BP_Messages['threadUrl'] + thread_id + '&scrollToContainer';
                    var mainContainer = $('.bp-messages-wrap.bp-messages-wrap-main');
                    if( mainContainer.length > 0 ){
                        ajaxRefresh(url, mainContainer);
                    } else {
                        location.href = url;
                    }
                }
            });
        }
        /* </fs_premium_only> */


        $(document).on('click', '.bm-threads-list .threads-list .thread:not(.blocked)', function (event) {
            event.preventDefault();

            var thread = $(this);
            var thread_id = thread.data('id');
            if (BP_Messages['miniChats'] == '1') {
                var scroller = thread.parent().parent();
                var height = $(thread).height();
                var top = thread.position().top;
                top = top + scroller.scrollTop();

                thread.addClass('blocked loading');

                $(thread).find('.loading').css({
                    'height': height,
                    'line-height': height + 'px',
                    'top': top + 'px'
                });

                openMiniChat(thread_id, true).always(function (done) {
                    reInit();
                    thread.removeClass('blocked loading');
                });
            } else {
                var url = BP_Messages['threadUrl'] + thread_id + '&scrollToContainer';

                if( isMobile ){
                    var mobilePopup = $('#bp-better-messages-mini-mobile-open');
                    if( mobilePopup.length > 0 ){
                        var originalUrl = BP_Messages['baseUrl'];
                        BP_Messages['baseUrl'] = BP_Messages['threadUrl'] + thread_id;
                        mobilePopup.click();
                        BP_Messages['baseUrl'] = originalUrl;
                    } else {
                        location.href = url;
                    }
                } else {
                    var mainContainer = $('.bp-messages-wrap.bp-messages-wrap-main');

                    if (mainContainer.length > 0) {
                        ajaxRefresh(url, mainContainer);
                    } else {
                        location.href = url;
                    }
                }
            }
        });

        $(document).on('click', '.bp-messages-wrap .chat-tabs > div', function (event) {
            event.preventDefault();
            var tab  = $(this);
            var tabs = tab.closest('.chat-tabs');
            var container = tabs.parent();
            var currentTab = tab.data('tab');

            if (! $(this).hasClass('active') ) {
                tabs.find('> div').removeClass('active');
                tab.addClass('active');

                tabs.find('> div').each(function(){
                    var tabData = $(this).data('tab');
                    container.find('.' + tabData).hide();
                });

                var newTabContent = container.find('.' + currentTab);

                chatAdditionalTab( newTabContent );
            }
        });

        function chatAdditionalTab( currentTab ){
            if( currentTab.hasClass('bpbm-friends-list') ) {
                if( ! currentTab.hasClass('bpbm-loaded') ) {
                    currentTab.addClass('bpbm-loaded');
                    $.post(BP_Messages['ajaxUrl'], {
                        'action': 'bp_messages_load_friends_list',
                        'nonce': BP_Messages['userNonce'],
                    }, function (response) {
                        currentTab.html(response);
                        onlineInit();
                        sortOnlineFriends();
                    });
                }
            }

            if( currentTab.hasClass('bpbm-groups-list') ) {
                if( ! currentTab.hasClass('bpbm-loaded') ) {
                    currentTab.addClass('bpbm-loaded');

                    $.post(BP_Messages['ajaxUrl'], {
                        'action': 'bp_messages_load_groups_list',
                        'nonce': BP_Messages['userNonce'],
                    }, function (response) {
                        currentTab.html(response);
                    });
                }
            }

            currentTab.show();
        }

        $(document).on('click', '.bp-better-messages-list .tabs > div', function (event) {
            event.preventDefault();
            var tab = $(this).data('tab');

            if( tab === 'bpbm-close' ){
                $('.bp-better-messages-list .tabs > div, .bp-better-messages-list .tabs-content > div').removeClass('active');
                $('.bp-better-messages-list .tabs > div[data-tab="bpbm-close"]').hide();
                miniMessages = false;
            } else if (! $(this).hasClass('active') ) {
                $('.bp-better-messages-list .tabs > div, .bp-better-messages-list .tabs-content > div').removeClass('active');
                $(this).addClass('active');
                $('.bp-better-messages-list .tabs-content .' + tab).addClass('active');
                miniMessages = tab;
                $('.bp-better-messages-list .tabs > div[data-tab="bpbm-close"]').show();
            } else {
                $(this).removeClass('active');
                $('.bp-better-messages-list .tabs-content .' + tab).removeClass('active');
                $('.bp-better-messages-list .tabs > div[data-tab="bpbm-close"]').hide();
                miniMessages = false;
            }

            store.set('bp-better-messages-mini-messages', miniMessages);
        });


        $(document).on('click', '.bpbm-deleted-user-link', function (event) {
            event.preventDefault();
        });

        $(document).on('click', '.bp-better-messages-list .new-message', function(event) {
            var mainContainer = $('.bp-messages-wrap.bp-messages-wrap-main');
            if( mainContainer.length > 0 ){
                event.preventDefault();
                ajaxRefresh($(this).attr('href'), mainContainer);
            }
        });

        $(document).on('click', '.bp-messages-group-list .group:not(.blocked)', function(event){
            if($(event.target).is('div')){
                event.preventDefault();
                var group     = $(this);

                if( group.hasClass('bpbm-messages-disabled') ) {
                    location.href = group.find('.open-group').attr('href');
                } else {
                    var insideColumnView = group.closest('.bp-messages-column').length > 0 || group.closest('.bp-messages-side-threads').length > 0;
                    var group_id = group.data('group-id');
                    var thread_id = group.data('thread-id');
                    var url = group.find('.actions .open-group').attr('href');
                    if (BP_Messages['enableGroups'] === '1') url += BP_Messages['groupsSlug'] + '/?scrollToContainer';
                    var scroller = group.parent().parent();
                    var height = group.height();
                    var top = group.position().top;
                    top = top + scroller.scrollTop();
                    group.find('.loading').css({
                        'height': height,
                        'line-height': height + 'px',
                        'top': top + 'px'
                    });

                    if( insideColumnView ){
                        var mainContainer = group.closest('.bp-messages-wrap');
                        if( mainContainer.length > 0 ) {
                            ajaxRefresh(BP_Messages['threadUrl'] + thread_id, mainContainer);
                        }
                    } else if (BP_Messages['enableGroups'] === '1' && BP_Messages['miniChats'] == '1' && !!thread_id) {
                        group.addClass('blocked loading');
                        openMiniChat(thread_id, true).always(function (done) {
                            group.removeClass('blocked loading');
                        });

                    } else {
                        group.addClass('blocked loading');
                        location.href = url;
                    }
                }
            }
        });

        $(document).on('click', '.bp-messages-user-list .user:not(.blocked)', function(event){
            if($(event.target).is('div')){
                event.preventDefault();
                var user = $(this);
                var user_id = $(this).data('id');
                var username = $(this).data('username');

                var insideColumnView = user.closest('.bp-messages-column').length > 0 || user.closest('.bp-messages-side-threads').length > 0;

                if( insideColumnView ){
                    var redirect = BP_Messages['url'] + urlSeparator + 'new-message&to=' + username;
                    if(BP_Messages['fastStart'] == '1') redirect += '&fast=1';

                    var mainContainer = user.closest('.bp-messages-wrap');
                    if( mainContainer.length > 0 ) {
                        ajaxRefresh(redirect, mainContainer);
                    }
                } else if ( BP_Messages['miniChats'] == '1' && BP_Messages['fastStart'] == '1' ) {
                    var scroller = user.parent().parent();
                    var height = $(user).height();
                    var top = user.position().top;
                    top = top + scroller.scrollTop();
                    $(user).find('.loading').css({
                        'height': height,
                        'line-height': height + 'px',
                        'top': top + 'px'
                    });

                    user.addClass('blocked loading');

                    openPrivateThread(user_id).always(function (done) {
                        user.removeClass('blocked loading');
                    });
                } else {
                    var redirect = BP_Messages['url'] + urlSeparator + 'new-message&to=' + username;
                    if(BP_Messages['fastStart'] == '1') redirect += '&fast=1&scrollToContainer';

                    var mainContainer = $('.bp-messages-wrap.bp-messages-wrap-main');
                    if( mainContainer.length > 0 ){
                        ajaxRefresh(redirect, mainContainer);
                    } else {
                        location.href = redirect;
                    }
                }
            }
        });

        /* <fs_premium_only> */
        if(BP_Messages['enablePushNotifications'] === '1') {
            if ('serviceWorker' in navigator && 'PushManager' in window) {
                var asked = store.get('bpbm-browser-push-proposal-clicked', false);
                if (asked === false) {
                    navigator.serviceWorker
                        .register('/bpbm-worker.js', {scope: '/'})
                        .then(function (registration) {
                            registration.pushManager.getSubscription().then(function (pushSubscription) {
                                if (pushSubscription === null) {
                                    BPBMJQ.amaran({
                                        'theme': 'colorful',
                                        'content': {
                                            bgcolor: 'black',
                                            color: '#fff',
                                            message: '<span class="bpbm-browser-push-proposal">' +
                                                '<span class="bpbm-browser-push-proposal-text">' + BP_Messages['strings']['push_request'] + '</span>' +
                                                '<span class="bpbm-browser-push-proposal-controls"><button class="BPBMenablePushNotifications">' + BP_Messages['strings']['enable'] + '</button><button class="BPBMdismissPushProposal">' + BP_Messages['strings']['dismiss'] + '</button></span>' +
                                                '</span>'
                                        },
                                        'sticky': true,
                                        'closeOnClick': true,
                                        'closeButton': false,
                                        'position': 'bottom right',
                                        onClick: function () {
                                            store.set('bpbm-browser-push-proposal-clicked', true);
                                        }
                                    });
                                }
                            });
                        });
                }
            }
        }
        /* </fs_premium_only> */

        $(document).on('click', '.bp-messages-wrap .bpbm-user-me', function (event){
            event.preventDefault();

            $(this).toggleClass('bpbm-open');
        });

        $(document).on('click', '.bp-messages-wrap .bpbm-user-me .bpbm-user-me-popup .bpbm-user-me-popup-list-item', function (event){
            event.stopImmediatePropagation();
            var elem = $(this);

            if( ! elem.is('a') ) {
                event.preventDefault();

                /* <fs_premium_only> */
                var userPopup = elem.closest('.bpbm-user-me-popup');
                var userMe = userPopup.closest('.bpbm-user-me');
                var newStatus = elem.attr('data-status');

                userMe.removeClass('bpbm-open');
                BPBMJQ.post(BP_Messages['ajaxUrl'], {
                    'action'    : 'bp_messages_change_user_option',
                    'option'    : 'online_status',
                    'user_id'   : BP_Messages['user_id'],
                    'value'     : newStatus,
                    '_wpnonce'  : userPopup.attr('data-nonce')
                }, function (response) {
                    if( response.result === true ){
                        $('.bpbm-user-me .current-status').html( response.message );
                    } else {
                        BBPMShowError( response.errors.join("\n") );
                    }
                });
                /* </fs_premium_only> */
            }
        });

    }

    function deleteMessage( messages_ids ){
        $.each(messages_ids, function(){
            var message_id = this;

            var li = $('.bp-messages-wrap .list .messages-stack .content .messages-list li[data-id="' + message_id + '"]');
            var stack = li.closest('.messages-stack');
            li.remove();
            var messages = stack.find('.messages-list > li');
            if( messages.length === 0 ){
                stack.remove();
            }

            $(threadsSelector + '[data-message="' + message_id + '"] .info p').text('...');
        });
    }

    function changeMaxHeight(){
        var height = $( window ).height() - 50;
        var admin_bar = $('#wpadminbar');
        if( admin_bar.length > 0 ){
            if( admin_bar.is(':visible') ){
                height = height - admin_bar.height();
            }
        }

        var windowHeight = height;

        var min_height = BP_Messages['min_height'];

        if(height > BP_Messages['max_height']) {
            height = BP_Messages['max_height'];
        }

        if( BP_Messages['fixedHeaderHeight'] > 0 ){
            height = height - BP_Messages['fixedHeaderHeight'];
        }

        height = parseInt(height);

        if( height < min_height ) height = min_height;

        BPBMJQ('.bp-messages-wrap .scroller').each(function(){
            var scroller = $(this);

            var bpMessagesColumn = scroller.closest('.bp-messages-column');
            var wrap             = scroller.closest('.bp-messages-wrap');

            if( wrap.hasClass('bp-better-messages-mini') ){
                var miniChatsHeight = BP_Messages['miniChatsHeight'];

                var replyHeight = wrap.find('.reply').outerHeight();

                if( miniChatsHeight > windowHeight ){
                    miniChatsHeight = windowHeight - replyHeight - 10;
                }

                scroller.css( 'max-height', miniChatsHeight );
                scroller.css( 'height', miniChatsHeight );
            } else if( wrap.hasClass('bp-better-messages-list') ){
                var miniWindowsHeight = BP_Messages['miniWindowsHeight'];
                if( miniWindowsHeight > windowHeight ){
                    miniWindowsHeight = windowHeight - 10;

                    var messages = scroller.closest('.messages');
                    if( messages.length > 0) {
                        var additionalHeight = messages.find('.chat-header');
                        if( additionalHeight.length > 0 ){
                            miniWindowsHeight = miniWindowsHeight - additionalHeight.outerHeight();
                        }
                    }
                }

                scroller.css( 'max-height', miniWindowsHeight );
                scroller.css( 'height', miniWindowsHeight );
            } else if( bpMessagesColumn.length > 0 && bpMessagesColumn.parent().find('.bp-messages-side-threads').is(':visible') ){
                var el = scroller.closest('.bp-messages-threads-wrapper');
                el.css( 'max-height', height );
                el.css( 'height', height );
            } else {
                var el = scroller.closest('.bp-messages-threads-wrapper');

                el.css( 'max-height', height );
                el.css( 'height', height );
            }
        });

        BPBMJQ('.bp-messages-wrap.bp-better-messages-list .scroller').css( 'max-height', height - 50 );
        BPBMJQ('.bp-messages-wrap.bp-better-messages-mini .scroller').css( 'max-height', height - 50 );
    }

    function makeHeightBeautiful(){
        $.each(bpMessagesWrap, function( index, item ){
            var wrap = $(item);
            if( wrap.hasClass('bp-messages-wrap-main') ) {
                var sideThreads = wrap.find('> .bp-messages-threads-wrapper .bp-messages-side-threads');
                if (sideThreads.length > 0) {
                    var threadWrapper = sideThreads.closest('.bp-messages-threads-wrapper');
                    var neededWidth = sideThreads.width() * 2;
                    if( neededWidth < 800 ) neededWidth = 800;

                    if( wrap.width() < neededWidth ){
                        threadWrapper.addClass('threads-hidden');
                        sideThreads.hide();
                    } else {
                        threadWrapper.removeClass('threads-hidden');
                        sideThreads.show();
                    }
                }
            }

            if( wrap.hasClass('bp-messages-mobile') ) {
                var windowHeight = window.innerHeight;
                var usedHeight = 0;
                var headerHeight = wrap.find('.chat-header').outerHeight();
                usedHeight = usedHeight + headerHeight;

                if( wrap.find('.chat-footer:visible').length > 0 ) {
                    usedHeight = usedHeight + wrap.find('.chat-footer:visible').outerHeight();
                }

                if( wrap.find('.reply').length > 0 ) {
                    usedHeight = usedHeight + wrap.find('.reply').outerHeight();
                }

                wrap.find('.scroller').css({
                    'height': windowHeight - usedHeight,
                });

                //bpMessagesWrap.find('.bp-messages-threads-wrapper').css('maxHeight', 'calc( 100% - ' + headerHeight + 'px )')
            } else {
                changeMaxHeight();
            }
        });


    }

    BPBMJQ(document).on('click', '.bp-messages-wrap .chat-header .bpbm-maximize', function (event){
        event.preventDefault();

        var wrap = BPBMJQ(this).closest('.bp-messages-wrap');

        if( $('.' + fullScreenHolderClass ).length === 0 ){
            $('<div class="' + fullScreenHolderClass + '"></div>').insertBefore(wrap);
        }

        var source = wrap;
        source.addClass('bp-messages-full-screen');

        var windowHeight = window.innerHeight;
        $('html').addClass('bp-messages-full-screen').css('overflow', 'hidden');
        $('body').addClass('bp-messages-full-screen').css('min-height', windowHeight);
        $('.bp-better-messages-mini .chats .chat.open').removeClass('open');
        var fullScreenViewContainer = source.appendTo( $('body') );
        fullScreenViewContainer.find('.user-scrolled').removeClass('user-scrolled');
        fullScreenViewContainer.show();
        calculateTitle(fullScreenViewContainer);

        $(window).trigger('resize');

        blockScroll = true;
    });


    BPBMJQ(document).on('click', '.bp-messages-wrap .chat-header .bpbm-minimize', function (event){
        event.preventDefault();

        var wrap = BPBMJQ(this).closest('.bp-messages-wrap');

        if( wrap.hasClass('bp-messages-full-screen') ){
            event.preventDefault();
            event.stopImmediatePropagation();

            $('html').removeClass('bp-messages-full-screen').css('overflow', 'auto');
            wrap.removeClass('bp-messages-full-screen').css('min-height', '');
            $('body').removeClass('bp-messages-full-screen').css('min-height', '');

            blockScroll = false;

            var source = wrap;
            source.removeClass('bp-messages-full-screen');
            source.removeAttr('id');

            var holder = $('.' + fullScreenHolderClass );
            source.insertBefore( holder );
            source.find('.user-scrolled').removeClass('user-scrolled');
            holder.remove();

            $(window).trigger('resize');

            calculateTitle(source);
            //scrollBottom(source);
        }

        blockScroll = false;
    });

    BPBMJQ(document).on('bp-better-messages-update-unread', function( event ) {
        var _unread = BPBMJQ('.bp-better-messages-unread');

        unread = parseInt(event.originalEvent.detail.unread);
        if( isNaN ( unread ) || unread < 0 ) unread = 0;

        store.set('bp-better-messages-last-unread', unread);

        _unread.each(function(){
            var __unread = BPBMJQ(this);
            var is_shortcode = __unread.hasClass('bpbmuc');

            __unread.text(unread);

            if( ! is_shortcode ) {
                if (unread === 0) {
                    __unread.addClass('no-count');
                } else {
                    __unread.removeClass('no-count');
                }
            } else {
                __unread.attr('data-count', unread);
            }

        });

        if( BPBMJQ('body').hasClass('my-account') ) {
            var tab = BPBMJQ('#user-bp_better_messages_tab');
            if (tab.length > 0) {
                var count = tab.find('span.count');

                if (unread > 0) {
                    if (count.length > 0) {
                        count.text(unread);
                    } else {
                        BPBMJQ('<span class="count">' + unread + '</span>').appendTo(tab);
                    }
                } else {
                    count.remove();
                }
            }
        }

    });

    /* <fs_premium_only> */
    var forceReconnectTimeout;

    function realTimeInit() {
        try {

            BPBMJQ(document).trigger('bp-better-messages-before-realtime-connect');

            socket = bpbmio.connect(BP_Messages['socket_server'], {
                upgrade: true,
                rememberUpgrade: true,
                secure: true,
                timeout: 7000,
                transports: ["websocket"],
                auth: [
                    BP_Messages['site_id'],
                    BP_Messages['user_id'],
                    BP_Messages['secret_key']
                ]
            });
        } catch (e) {
            console.error('Error connecting to the WebSocket Server. Please contact plugin developer. https://www.wordplus.org/contact/');
            BP_Messages['realtime'] = '0';
            clearTimeout(forceReconnectTimeout);
            forceReconnectTimeout = setTimeout(forceReconnect, 10000);
            return false;
        }

        socket.on("connect_error", function (err) {
            console.debug('Error while connecting to WebSocket messaging server. AJAX mode enabled.');
            BP_Messages['realtime'] = '0';
            clearTimeout(forceReconnectTimeout);
            forceReconnectTimeout = setTimeout(forceReconnect, 10000);
        });

        /**
         * Trying to connect
         */
        socket.on('connect', function () {
            console.debug('You was connected to WebSocket messaging server. WebSocket mode enabled.');
            BP_Messages['realtime'] = '1';
            clearTimeout(forceReconnectTimeout);

            subscribeToThreads(1);
        });

        function subscribeToThreads(tries){
            var threadIds = [];

            var mainThreadId = BPBMJQ('.bp-messages-wrap-main').attr('data-thread-id');
            if( typeof mainThreadId !== 'undefined' ) {
                threadIds.push( parseInt( mainThreadId ) );
            }

            BPBMJQ('.bp-messages-wrap .threads-list .thread').each(function(){
                threadIds.push( parseInt( BPBMJQ(this).attr('data-id') ) );
            });

            threadIds = unique( threadIds );

            if( threadIds.length > 0 ) {
                socket.emit('subscribeToThreads', threadIds);
            } else {
                if( tries <= 4 ){
                    tries++;
                    setTimeout(function(){
                        subscribeToThreads(tries);
                    }, 500);
                }
            }
        }

        socket.on('reconnect', function () {
            console.debug('You was reconnected to WebSocket messaging server. WebSocket mode enabled.');
            BP_Messages['realtime'] = '1';
            clearTimeout(forceReconnectTimeout);
        });

        socket.on('disconnect', function () {
            console.debug('You was disconnected from WebSocket messaging server. AJAX mode enabled.');
            BP_Messages['realtime'] = '0';

            clearTimeout(forceReconnectTimeout);
            forceReconnectTimeout = setTimeout(forceReconnect, 10000);
        });

        function forceReconnect(){
            socket.disconnect();
            socket.connect();
        }

        socket.on('userStatus', function (user_id, status) {
            if (BP_Messages['user_id'] === user_id) {
                BP_Messages['userStatus'] = status.slug;
            }

            if (BP_Messages['userStatus'] !== '0') {
                $('.bbpm-avatar[data-user-id="' + user_id + '"]').css('color', status.color);

                var threadDivs = $('.bp-messages-wrap .thread.scroller[data-users-json]');
                if( threadDivs.length > 0 ) {
                    threadDivs.each(function(){
                        var threadDiv = BPBMJQ(this);
                        var usersJson = atob(threadDiv.attr('data-users-json'));
                        var recipients = $.parseJSON(usersJson);

                        try {
                            if (typeof recipients[user_id] !== 'undefined') {
                                var avatar = BPBMJQ(recipients[user_id]['avatar']);
                                avatar.attr('data-bpbm-status-color', status.color);
                                recipients[user_id]['avatar'] = avatar[0].outerHTML;
                                threadDiv.attr('data-users-json', btoa(JSON.stringify(recipients)));
                            }
                        } catch (e){}
                    });
                }
            }
        });

        socket.on('endCall', function(args){

            var container = BPBMJQ('.bp-messages-wrap.bp-messages-wrap-main');
            var thread_id = parseInt(container.attr('data-thread-id'));

            if( parseInt(args['thread_id']) === thread_id ) {
                if (isInCall) {
                    BPBMJQ(document).trigger('bpbm-end-call', endCall);
                }

                if (args['message'].length > 0) {
                    BBPMNotice(args['message']);
                }
                var url = BP_Messages['threadUrl'] + thread_id;
                ajaxRefresh(url, container);
            }
        });

        /** CALL FUNCTIONALITY **/
        var peer = false;
        var myStream = false;
        var originalStream = false;
        var myVideo = false;
        var myAudio = false;
        var remoteStream = false;
        var remoteDescriptionSet = false;
        var peersConnected = false;
        var calling = false;

        BPBMJQ(document).on('bpbm-end-call', endCall);
        BPBMJQ(document).on('bpbm-end-group-call', groupCallEnd);

        BPBMJQ(window).on('beforeunload', function () {
            if (isInCall) {
                return BP_Messages['strings']['you_are_in_call'];
            }
        });

        function endCall() {
            var callView    = BPBMJQ('.bp-messages-wrap.bpbm-call-view');
            var sideThreads = BPBMJQ('.bpbm-call-view .bp-messages-side-threads');

            if( callView.length > 0 && sideThreads.length > 0 ){
                sideThreads.css('overflow', 'hidden');
                callView.removeClass('bpbm-call-view');
                BPBMJQ('.bp-messages-wrap .bpbm-chat-content.bpbm-call-view').removeClass('bpbm-call-view');
                BPBMJQ('.bp-messages-wrap .bpbm-chat-content.bpbm-call-audio-view').removeClass('bpbm-call-audio-view');

                setTimeout(function (){
                    hideCallContainer();
                }, 300);
            } else {
                hideCallContainer();
            }

            function hideCallContainer(){
                BPBMJQ('.bp-messages-wrap .bpbm-chat-content.bpbm-call-view').removeClass('bpbm-call-view');
                BPBMJQ('.bp-messages-wrap .bpbm-chat-content.bpbm-call-audio-view').removeClass('bpbm-call-audio-view');

                BPBMJQ('.bp-messages-wrap .bp-messages-video-container, .bp-messages-wrap .bp-messages-audio-container').hide();

                var main_video = BPBMJQ('.bp-messages-wrap .bp-messages-video-container .bp-messages-main-video');
                var small_video = BPBMJQ('.bp-messages-wrap .bp-messages-video-container .bp-messages-small-video');
                main_video.hide();
                main_video.html('');
                small_video.hide();
                small_video.html('');


                BPBMJQ('.bp-messages-wrap .reply').show();
                BPBMJQ('.bp-messages-call-controls').hide();

                BPBMJQ('.bp-messages-call-controls .bpbm-enable-mic').hide();
                BPBMJQ('.bp-messages-call-controls .bpbm-disable-mic').show();

                BPBMJQ('.bp-messages-call-controls .bpbm-enable-video').hide();
                BPBMJQ('.bp-messages-call-controls .bpbm-disable-video').show();
                sideThreads.css('overflow', '');
            }

            clearInterval(calling);

            if (myStream !== false) {
                myStream.getTracks().forEach(function (track) {
                    try {
                        myStream.removeTrack(track);
                        track.stop();
                    } catch (e) {
                    }
                });
            }

            if( remoteStream !== false ){
                remoteStream.getTracks().forEach(function (track) {
                    try {
                        remoteStream.removeTrack(track);
                        track.stop();
                    } catch (e) {}
                });
            }

            if (peer !== false) {
                peer.destroy();
            }

            originalStream = false;
            myStream       = false;
            remoteStream   = false;
            myVideo        = false;
            myAudio        = false;
            peer           = false;
            isInCall       = false;
            remoteDescriptionSet = false;
            peersConnected = false;

            streamShared = false;
            cameraId = false;
            currentCameraId = false;

            microphoneId = false;
            currentMicrophoneId = false;

            stopVideoCallSound();

            BPBMFinishCallRecording();
        }

        function playVideoCallSound() {
            if (typeof sounds.calling === 'undefined') return false;
            if (BP_Messages['userStatus'] === 'dnd') return false;
            if (!sounds.calling.playing()) {
                sounds.calling.play();
            }
        }

        function stopVideoCallSound() {
            if (typeof sounds.calling === 'undefined') return false;
            if (sounds.calling.playing()) {
                sounds.calling.stop();
            }
        }

        function getUserMedia(hints, onsuccess, onfailure) {
            if (!hints) hints = {audio: true, video: true};
            if (!onsuccess) throw 'Second argument is mandatory. navigator.getUserMedia(hints,onsuccess,onfailure)';

            navigator.mediaDevices.getUserMedia(hints).then(_onsuccess).catch(_onfailure);

            function _onsuccess(stream) {
                onsuccess(stream);
            }

            function _onfailure(e) {
                if (onfailure) {
                    onfailure(e);
                } else {
                    throw Error('getUserMedia failed: ' + JSON.stringify(e, null, '\t'));
                }
            }
        }

        var justRejected = {};
        var justCalled = {};
        var shouldFaceUser = true;
        var cameraId = false;
        var audioId = false;
        var microphoneId = false;


        var streamShared = false;
        var currentCameraId = false;
        var currentAudioId = false;
        var currentMicrophoneId = false;

        var speakerId = false;
        var microId = false;
        var endCallTimeout;

        function startPeerIfNotStarted( user_id, type, initiator ) {
            if (peer !== false) return false;

            if( typeof initiator === 'undefined' ) {
                initiator = false;
            }

            try {
                var turn_server = BP_Messages['turn_server'];

                var servers = [
                    {
                        urls: 'stun:' + turn_server + ':80'
                    },
                    {
                        urls: ['turn:' + turn_server + ':80','turns:' + turn_server + ':443'],
                        username: "wordplus",
                        credential: "password"
                    },
                    {
                        urls: 'stun:stun.l.google.com:19302'
                    }
                ];

                peer = new BPBMSimplePeer({
                    initiator: initiator,
                    config: {
                        iceServers: servers
                    }
                });

                peer.participant = user_id;

                peer.on('error', function(err){
                    console.error('error', err);
                    endCall();
                    endCallTimeout = setTimeout(function () {
                        BBPMNotice(BP_Messages['strings']['connection_drop']);
                    }, 3000);
                });

                peer.on('signal', function(data){
                    socket.emit('mediaEvent', {
                        event : 'peer_signal',
                        to    : peer.participant,
                        data  : JSON.stringify(data)
                    });
                });

                peer.on('connect', function() {
                    showOrHideSwitchButton();
                    originalStream = myStream;
                    peersConnected = true;
                })

                peer.on('data', function(data) {
                });

                peer.on('close', function() {
                    showOrHideSwitchButton();
                    endCall();
                })

                peer.on('track', function(track, stream){
                    showOrHideSwitchButton();
                    var src = stream;

                    if (track.kind === 'video') {
                        playStream(src);
                    }

                    if (track.kind === 'audio') {
                        playAudioStream(src);
                    }
                });


            } catch (error) {
                console.error(error);
            }
        }

        function playAudioStream(stream) {
            var audio = document.createElement('audio');
            audio.setAttribute('playsinline', 'true');
            var container = $('.bp-messages-audio-element');
            container.html(audio);
            audio.srcObject = stream;
            audio.muted = false;
            audio.controls = false;
            audio.playsinline = true;
            audio.autoplay = true;
            audio.play();
        }

        function playStream(stream) {
            var video = document.createElement('video');
            video.setAttribute('playsinline', 'true');
            var container = $('.bp-messages-video-container');
            container.find('.bp-messages-main-video').html(video);
            container.show();
            video.srcObject = stream;
            video.muted = false;
            video.controls = false;
            video.playsinline = true;
            video.play();

            videoSizeFit(container);
        }

        function playSmallStream(stream) {
            var video = document.createElement('video');
            video.setAttribute('playsinline', 'true');
            var container = $('.bp-messages-video-container');
            container.find('.bp-messages-small-video').show();
            container.find('.bp-messages-small-video').html(video);
            container.show();
            video.srcObject = stream;
            video.controls = true;
            video.muted = true;
            video.controls = false;
            video.playsinline = true;
            video.play();
        }


        socket.on('mediaEvent', function (message) {
            var container = $('.bp-messages-video-container');
            var wrap = container.closest('.bp-messages-wrap');

            switch (message.event) {
                case 'peer_signal':
                    peer.signal(JSON.parse(message.data));
                    break;
                case 'answered':
                    clearInterval(calling);
                    if( !! myStream ) {
                        wrap.find('.bp-messages-main-placeholder').hide();
                        wrap.find('.bp-messages-main-placeholder .bp-messages-placeholder-video').html('');
                        wrap.find('.bp-messages-main-video').show();

                        container.find('.bp-messages-call-controls > *').hide();
                        container.find('.bp-messages-call-controls').show();
                        container.find('.bp-messages-call-controls > .bpbm-call-in-progress').show();

                        playSmallStream(myStream);
                        isInCall = true;
                        BPBMTryCallSuccesfull();
                    }
                    break;
                case 'answered_call':
                    clearInterval(calling);

                    if( !! myStream ) {
                        container = $('.bp-messages-audio-container');
                        wrap = container.closest('.bp-messages-wrap');
                        wrap.find('.bp-messages-placeholder-incoming-text, .bp-messages-placeholder-outgoing-text').hide();

                        var timer = wrap.find('.bp-messages-timer');
                        timer.show();
                        timer.runner({
                            format: function (value) {
                                return msToTime(value);
                            },
                            milliseconds: false
                        });

                        timer.runner('start');

                        container.find('.bp-messages-call-controls > *').hide();
                        container.find('.bp-messages-call-controls').show();
                        container.find('.bp-messages-call-controls > .bpbm-call-in-progress').show();

                        container.find('.bp-messages-call-controls > *').hide();
                        container.find('.bp-messages-call-controls').show();
                        container.find('.bp-messages-call-controls > .bpbm-call-in-progress').show();

                        isInCall = true;
                        BPBMTryCallSuccesfull();
                    }
                    break;
                case 'rejected':
                    BBPMNotice(BP_Messages['strings']['call_reject']);
                    clearInterval(calling);
                    isInCall = false;
                    BPBMTryCallFailed();
                    endCall();
                    break;
                case 'calling':
                    if (isInCall) return false;
                    if (typeof justRejected[message.from] !== 'undefined') return false;

                    playVideoCallSound();

                    if (thread && message.thread_id === thread.toString()) {
                        if( container.is(':hidden') ) {
                            wrap.addClass('bpbm-call-view');
                            var chatContent = container.closest('.bpbm-chat-content');
                            chatContent.addClass('bpbm-call-view');

                            if( isMobile ) {
                                chatContent.addClass('bpbm-hide-chat');
                            }

                            container.show();
                            container.find('.bp-messages-placeholder-message > *').hide();
                            container.find('.bp-messages-placeholder-message > .bp-messages-placeholder-incoming-text').show();

                            container.find('.bp-messages-call-controls > *').hide();
                            container.find('.bp-messages-call-controls').show();
                            container.find('.bp-messages-call-controls > .bpbm-call-in').show();
                            container.find('.bp-messages-main-placeholder').show();

                            var mobileWrap = $('.bp-messages-wrap.bp-messages-wrap-main.mobile-ready:not(.bp-messages-mobile)');

                            if (mobileWrap.length > 0) {
                                openMobile(wrap);
                                mediaContainerHeight(wrap);
                            }

                            if (myVideo === false) {
                                getUserVideo(function (stream, video, error) {
                                    if (error !== false) {
                                        console.error(error);
                                        var _error = error.toString().split(':');
                                        BBPMShowError(BP_Messages['strings']['cam_not_works'] + ': ' + _error[1]);
                                    } else {
                                        myStream = stream;
                                        myVideo = video;
                                        container.find('.bp-messages-placeholder-video').html(myVideo);
                                        myVideo.controls = false;
                                        myVideo.play();

                                        showOrHideSwitchButton();
                                    }
                                });
                            } else {
                                container.find('.bp-messages-placeholder-video').html(myVideo);
                                myVideo.controls = false;
                                myVideo.play();
                            }
                        }
                    } else {
                        var popupExist = $('.amaran.incoming_call.thread_' + message.thread_id);
                        if (popupExist.length === 0) {
                            $.amaran({
                                'theme': 'user message thread_' + message.thread_id + ' incoming_call',
                                'content': {
                                    img: message.avatar,
                                    user: message.name,
                                    message: '' +
                                        '<div style="float: left;height: 35px;line-height: 35px;">' + BP_Messages['strings']['incoming_call'] + '</div>' +
                                        '<div class="bp-messages-wrap bp-messages-popup">' +
                                        '<div class="bpbm-call-in">' +
                                        '<span class="bpbm-answer" data-thread-id="' + message.thread_id + '"  data-user-id="' + message.from + '" title="' + BP_Messages['strings']['answer_call'] + '"><i class="fas fa-phone"></i></span>' +
                                        '<span class="bpbm-reject" data-thread-id="' + message.thread_id + '"  data-user-id="' + message.from + '" title="' + BP_Messages['strings']['reject_call'] + '"><i class="fas fa-phone"></i></span>' +
                                        '</div>' +
                                        '</div>'
                                },
                                'sticky': true,
                                'closeOnClick': false,
                                'closeButton': false,
                                'delay': 999999,
                                'thread_id': message.thread_id,
                                'position': 'bottom right',
                                onClick: function () {
                                }
                            });
                        }
                    }

                    if (typeof justCalled[message.from] !== 'undefined') {
                        clearTimeout(justCalled[message.from]);
                    }

                    justCalled[message.from] = setTimeout(function () {
                        stopVideoCallSound();

                        endCall();
                        var popupExist = $('.amaran.incoming_call');
                        if (popupExist.length > 0) {
                            popupExist.remove();
                        }
                    }, 3000);

                    break;
                case 'calling_audio':
                    if (isInCall) return false;
                    if (typeof justRejected[message.from] !== 'undefined') return false;

                    container = $('.bp-messages-audio-container');

                    playVideoCallSound();

                    if (thread && message.thread_id === thread.toString()) {
                        wrap.addClass('bpbm-call-view');
                        var chatContent = container.closest('.bpbm-chat-content');
                        chatContent.addClass('bpbm-call-audio-view');

                        if( isMobile ) {
                            chatContent.addClass('bpbm-hide-chat');
                        }

                        container.show();
                        container.find('.bp-messages-placeholder-message > *').hide();
                        container.find('.bp-messages-placeholder-message > .bp-messages-placeholder-incoming-text').show();

                        container.find('.bp-messages-call-controls > *').hide();
                        container.find('.bp-messages-call-controls').show();
                        container.find('.bp-messages-call-controls > .bpbm-call-in').show();
                        container.find('.bp-messages-main-placeholder').show();

                        var mobileWrap = $('.bp-messages-wrap.bp-messages-wrap-main.mobile-ready');

                        if (mobileWrap.length > 0) {
                            openMobile(wrap);
                        }

                        if (myStream === false) {
                            getUserAudio(function (stream, error) {
                                if (error !== false) {
                                    console.error(error);
                                    var _error = error.toString().split(':');
                                    BBPMShowError(BP_Messages['strings']['cam_not_works'] + ': ' + _error[1]);
                                } else {
                                    myStream = stream;

                                    showOrHideSwitchButton();
                                }
                            });
                        }
                    } else {
                        var popupExist = $('.amaran.incoming_call.thread_' + message.thread_id);
                        if (popupExist.length === 0) {
                            $.amaran({
                                'theme': 'user message thread_' + message.thread_id + ' incoming_call',
                                'content': {
                                    img: message.avatar,
                                    user: message.name,
                                    message: '' +
                                        '<div style="float: left;height: 35px;line-height: 35px;">' + BP_Messages['strings']['incoming_call'] + '</div>' +
                                        '<div class="bp-messages-wrap bp-messages-popup">' +
                                        '<div class="bpbm-call-in">' +
                                        '<span class="bpbm-answer" data-thread-id="' + message.thread_id + '"  data-user-id="' + message.from + '" title="' + BP_Messages['strings']['answer_call'] + '"><i class="fas fa-phone"></i></span>' +
                                        '<span class="bpbm-reject" data-thread-id="' + message.thread_id + '"  data-user-id="' + message.from + '" title="' + BP_Messages['strings']['reject_call'] + '"><i class="fas fa-phone"></i></span>' +
                                        '</div>' +
                                        '</div>'
                                },
                                'sticky': true,
                                'closeOnClick': false,
                                'closeButton': false,
                                'delay': 999999,
                                'thread_id': message.thread_id,
                                'position': 'bottom right',
                                onClick: function () {
                                }
                            });
                        }
                    }

                    if (typeof justCalled[message.from] !== 'undefined') {
                        clearTimeout(justCalled[message.from]);
                    }

                    justCalled[message.from] = setTimeout(function () {
                        stopVideoCallSound();

                        endCall();
                        var popupExist = $('.amaran.incoming_call');
                        if (popupExist.length > 0) {
                            popupExist.remove();
                        }
                    }, 3000);

                    break;
                case 'self_reject':
                    stopVideoCallSound();

                    var popupExist = $('.amaran.incoming_call');
                    if (popupExist.length > 0) {
                        popupExist.remove();
                    }

                    justRejected[message.from] = '1';
                    setTimeout(function () {
                        delete justRejected[message.from];
                    }, 3000);
                    break;
                case 'call_cancelled':
                    stopVideoCallSound();

                    var popupExist = $('.amaran.incoming_call.thread_' + message.thread_id);
                    if (popupExist.length > 0) {
                        popupExist.remove();
                    }

                    justRejected[message.from] = '1';
                    setTimeout(function () {
                        delete justRejected[message.from];
                    }, 3000);

                    endCall();
                    break;
                case 'call_end':
                    clearTimeout(endCallTimeout);
                    endCall();
                    break;
            }
        });

        var callingRequestLimit = BP_Messages['callRequestTimeLimit'] * 1000;
        var callingRequestLimitSeconds = 0;

        var callingRequestLimitTimer;
        var callingRequestLimitSecondsTimer;

        function BPBMTryCallStart() {

            callingRequestLimitTimer = setTimeout(function () {
                BPBMTryCallFailed();
            }, callingRequestLimit);

            callingRequestLimitSecondsTimer = setInterval(function () {
                callingRequestLimitSeconds++;
            }, 1000);

        }

        function BPBMTryCallFailed() {
            clearTimeout(callingRequestLimitTimer);
            clearInterval(callingRequestLimitSecondsTimer);

            if (callingRequestLimitSeconds === 0) return false;

            var duration = callingRequestLimitSeconds + 1;
            callingRequestLimitSeconds = 0;

            var container = BPBMJQ(peer.container);

            var type = false;

            if (container.hasClass('bp-messages-audio-container')) {
                type = 'audio';
            } else if (container.hasClass('bp-messages-video-container')) {
                type = 'video';
            }

            var thread_id = container.closest('[data-thread-id]').attr('data-thread-id');

            var button = container.find('.bpbm-cancel');
            if (button.hasClass('bpbm-blocked')) {
                button.removeClass('bpbm-blocked');
            } else {
                button.click();
            }

            $.post(BP_Messages['ajaxUrl'], {
                'action': 'bp_better_messages_record_missed_call',
                'thread_id': thread_id,
                'type': type,
                'duration': duration
            });
        }

        var callLengthTimer;
        var callLengthTimerRecorder;
        var callLengthTimerRecorderFrequency = 5;
        var callLengthTimerSeconds = 0;

        function BPBMTryCallSuccesfull() {
            clearTimeout(callingRequestLimitTimer);
            clearInterval(callingRequestLimitSecondsTimer);
            callingRequestLimitSeconds = 0;
            callLengthTimerSeconds = 0;

            callLengthTimer = setInterval(function () {
                callLengthTimerSeconds++;
            }, 1000);

            var container = BPBMJQ(peer.container);

            var type = false;

            if (container.hasClass('bp-messages-audio-container')) {
                type = 'audio';
            } else if (container.hasClass('bp-messages-video-container')) {
                type = 'video';
            }

            var thread_id = container.closest('[data-thread-id]').attr('data-thread-id');

            $.post(BP_Messages['ajaxUrl'], {
                'action': 'bp_better_messages_register_started_call',
                'thread_id': thread_id,
                'type': type
            }, function (message_id) {
                peer.call_message_id = message_id;
            });

            callLengthTimerRecorder = setInterval(function () {
                $.post(BP_Messages['ajaxUrl'], {
                    'action': 'bp_better_messages_register_call_usage',
                    'call_message_id': peer.call_message_id,
                    'duration': callLengthTimerSeconds
                });
            }, callLengthTimerRecorderFrequency * 1000);

        }

        function BPBMFinishCallRecording() {
            clearInterval(callLengthTimer);
            clearInterval(callLengthTimerRecorder);
        }

        function BPBMTryCallOfflineNotification(type, thread_id, user_id) {
            BBPMShowError(BP_Messages['strings']['call_offline']);

            if (BP_Messages['offlineCallsNotifications'] === '1') {
                $.post(BP_Messages['ajaxUrl'], {
                    'action': 'bp_better_messages_record_offline_call',
                    'type': type,
                    'thread_id': thread_id,
                    'user_id': user_id
                });
            }
        }

        BPBMJQ(document).on('click', '.bp-messages-wrap .chat-header .video-call', function (event) {
            event.preventDefault();
            event.stopImmediatePropagation();

            BPBMStartVideoCall(this);
        });

        BPBMJQ(document).on('click', '.bp-messages-wrap .chat-header .audio-call', function (event) {
            event.preventDefault();
            event.stopImmediatePropagation();

            BMBMStartAudioCall(this);
        });

        BPBMJQ(document).on('click', '#bpbm-audio-call .bpbm-audio-call, .bpbm-pm-button.audio-call', function (event) {

            var user_id = BPBMJQ(this).data('user-id');
            if (online.indexOf(user_id.toString()) === -1) {
                event.preventDefault();
                event.stopImmediatePropagation();

                BBPMShowError(BP_Messages['strings']['call_offline']);
            }
        });

        BPBMJQ(document).on('click', '#bpbm-audio-call .bpbm-audio-call, .bpbm-pm-button.open-mini-chat', function (event) {
            var button  = BPBMJQ(this);
            var user_id = button.data('user-id');

            BBPMOpenPrivateThread( user_id );
        });

        BPBMJQ(document).on('click', '#bpbm-video-call .bpbm-video-call, .bpbm-pm-button.video-call', function (event) {
            var user_id = BPBMJQ(this).data('user-id');
            if (online.indexOf(user_id.toString()) === -1) {
                event.preventDefault();
                event.stopImmediatePropagation();

                BBPMShowError(BP_Messages['strings']['call_offline']);
            }
        });


        function BPBMStartVideoCall(button) {
            var user_id = BPBMJQ(button).data('user-id');

            if (!socket.connected) {
                BBPMNotice(BP_Messages['strings']['websocket_not_connected']);
            } else if (isInCall) {
                return false;
            } else if (typeof navigator.mediaDevices === 'undefined') {
                BBPMShowError(BP_Messages['strings']['no_webrtc']);
            } else if (online.indexOf(user_id.toString()) === -1) {
                if (!onlineFetched) {
                    setTimeout(function () {
                        BPBMStartVideoCall(button);
                    }, 500);
                } else {
                    BPBMTryCallOfflineNotification('video', thread, user_id);
                }
            } else {
                showOrHideSwitchButton();

                getUserVideo(function (stream, video, error) {
                    if (error !== false) {
                        console.error(error);
                        var _error = error.toString().split(':');
                        BBPMShowError(BP_Messages['strings']['cam_not_works'] + ': ' + _error[1]);
                    } else {
                        var container = $('.bp-messages-video-container');
                        var avatar = container.data('my-avatar');
                        var name = container.data('my-name');
                        var wrap = container.closest('.bp-messages-wrap');
                        wrap.addClass('bpbm-call-view');
                        var chatContentContainer = container.closest('.bpbm-chat-content');
                        chatContentContainer.addClass('bpbm-call-view');
                        if( isMobile ){
                            chatContentContainer.addClass('bpbm-hide-chat');
                        }
                        container.show();

                        myStream = stream;
                        myVideo = video;
                        video.controls = false;
                        video.autoplay = true;
                        video.muted = true;
                        video.playsinline = true;
                        video.onplaying = function () {
                            videoSizeFit(container);
                        };
                        //myStream.getAudioTracks()[0].enabled = false;
                        container.find('.bp-messages-placeholder-video').html(video);
                        video.play().catch(function (error) {});

                        isInCall = true;
                        BPBMTryCallStart();
                        startPeerIfNotStarted( user_id, 'video', false );

                        peer.addStream(myStream);
                        streamShared = true;
                        peer.container = container;

                        container.find('.bp-messages-placeholder-message > *').hide();
                        container.find('.bp-messages-placeholder-message > .bp-messages-placeholder-outgoing-text').show();

                        container.find('.bp-messages-call-controls > *').hide();
                        container.find('.bp-messages-call-controls').show();
                        container.find('.bp-messages-call-controls > .bpbm-call-out').show();
                        container.find('.bp-messages-main-placeholder').show();

                        socket.emit('mediaEvent', {
                            event: 'calling',
                            to: user_id,
                            thread_id: thread,
                            avatar: avatar,
                            name: name
                        });

                        calling = setInterval(function () {
                            socket.emit('mediaEvent', {
                                event: 'calling',
                                to: user_id,
                                thread_id: thread,
                                avatar: avatar,
                                name: name
                            });
                        }, 2500);

                        videoSizeFit(container);

                        showOrHideSwitchButton();
                    }
                });
            }
        }

        function BMBMStartAudioCall(button) {
            var user_id = BPBMJQ(button).data('user-id');

            if (!socket.connected) {
                BBPMNotice(BP_Messages['strings']['websocket_not_connected']);
            } else if (isInCall) {
                return false;
            } else if (typeof navigator.mediaDevices === 'undefined') {
                BBPMShowError(BP_Messages['strings']['no_webrtc'])
            } else if (online.indexOf(user_id.toString()) === -1) {
                if (!onlineFetched) {
                    setTimeout(function () {
                        BMBMStartAudioCall(button);
                    }, 500);
                } else {
                    BPBMTryCallOfflineNotification('audio', thread, user_id);
                }
            } else {
                showOrHideSwitchButton();

                getUserAudio(function (stream, error) {
                    if (error !== false) {
                        console.error(error);
                        var _error = error.toString().split(':');
                        BBPMShowError(BP_Messages['strings']['mic_not_works'] + ': ' + _error[1]);
                    } else {
                        BPBMTryCallStart();
                        isInCall = true;
                        startPeerIfNotStarted(user_id, 'audio');
                        var container = $('.bp-messages-audio-container');
                        peer.container = container;
                        myStream = stream;
                        peer.addStream(myStream);
                        streamShared = true;

                        var wrap = container.closest('.bp-messages-wrap');

                        wrap.addClass('bpbm-call-view');
                        var chatContentContainer = container.closest('.bpbm-chat-content');
                        chatContentContainer.addClass('bpbm-call-audio-view');
                        if( isMobile ){
                            chatContentContainer.addClass('bpbm-hide-chat');
                        }

                        var avatar = container.data('my-avatar');
                        var name = container.data('my-name');

                        container.find('.bp-messages-placeholder-message > *').hide();
                        container.find('.bp-messages-placeholder-message > .bp-messages-placeholder-outgoing-text').show();
                        container.find('.bp-messages-call-controls > *').hide();
                        container.find('.bp-messages-call-controls').show();
                        container.find('.bp-messages-call-controls > .bpbm-call-out').show();
                        container.find('.bp-messages-main-placeholder').show();

                        container.show();

                        socket.emit('mediaEvent', {
                            event: 'calling_audio',
                            to: user_id,
                            thread_id: thread,
                            avatar: avatar,
                            name: name
                        });

                        calling = setInterval(function () {
                            socket.emit('mediaEvent', {
                                event: 'calling_audio',
                                to: user_id,
                                thread_id: thread,
                                avatar: avatar,
                                name: name
                            });
                        }, 2500);

                        showOrHideSwitchButton();
                    }
                });
            }
        }

        BPBMJQ(document).on('click', '.bp-messages-call-wrap:not(.bp-messages-call-wrap-group) .bpbm-switch-chat', function (event) {
            event.preventDefault();
            BPBMJQ(this).closest('.bpbm-chat-content').toggleClass('bpbm-hide-chat');
        });

        BPBMJQ(document).on('click', '.bp-messages-wrap .bp-messages-call-controls .bpbm-configure-call', function (event) {
            event.preventDefault();
            event.stopImmediatePropagation();

            var controls = BPBMJQ(this).closest('.bp-messages-call-controls');
            controls.find('.bpbm-call-settings').toggle();
        });

        BPBMJQ(document).on('click', '.bp-messages-wrap .bp-messages-call-controls .bpbm-switch-full-screen', function (event) {
            event.preventDefault();
            event.stopImmediatePropagation();

            if (myStream === false) return;

            var button = BPBMJQ(this);
            var callContainer = button.closest('.bp-messages-video-container');
            var fullScreenContainer = BPBMJQ('<div class="bp-messages-wrap bp-messages-full-screen-call"></div>').appendTo(BPBMJQ('body'));

            callContainer.appendTo(fullScreenContainer);

            hidePossibleBreakingElements();
        });

        BPBMJQ(document).on('change', '.bp-messages-wrap .bp-messages-video-container .bp-messages-call-controls .bpbm-switch-camera-select', function (event) {
            event.preventDefault();
            event.stopImmediatePropagation();

            var element = BPBMJQ(this);
            cameraId = element.val();

            BPBMUpdateCameraSettings( element.closest('.bp-messages-video-container') );
        });

        BPBMJQ(document).on('change', '.bp-messages-wrap .bp-messages-video-container .bp-messages-call-controls .bpbm-switch-mic-select', function (event) {
            event.preventDefault();
            event.stopImmediatePropagation();

            var element = BPBMJQ(this);
            microphoneId = element.val();

            BPBMUpdateCameraSettings( element.closest('.bp-messages-video-container') );
        });

        BPBMJQ(document).on('change', '.bp-messages-wrap .bp-messages-audio-container .bp-messages-call-controls .bpbm-switch-mic-select', function (event) {
            event.preventDefault();
            event.stopImmediatePropagation();

            var element = BPBMJQ(this);
            microphoneId = element.val();

            BPBMUpdateCameraSettings( element.closest('.bp-messages-audio-container'), 'audio' );
        });

        /*
        BPBMJQ(document).on('change', '.bp-messages-wrap .bp-messages-call-controls .bpbm-switch-audio-select', function (event) {
            event.preventDefault();
            event.stopImmediatePropagation();

            var element = BPBMJQ(this);
            audioId = element.val();

            BPBMUpdateCameraSettings( element.closest('.bp-messages-video-container') );
            BPBMSaveCameraSettings( element.closest('.bp-messages-video-container') );
        }); */

        function mediaContainerHeight( wrap ){
            return;
            var thread = wrap.find('.scroller.thread');

            var height = thread.height();
            var reply  = wrap.find('.reply');
            height     += reply.outerHeight();

            var max_height = height;

            if( thread.parent().hasClass('bp-messages-column') ) {
                //height = thread.parent().height();
                height = wrap.height() - wrap.find('.chat-header').height();
                max_height = height;
            }

            if( height > max_height ) height = max_height;

            //reply.hide();
            //wrap.find('.bp-messages-call-container').css( 'min-height', height );
            //wrap.find('.bp-messages-main-placeholder').css( 'height', height );
        }

        function videoSizeFit( container ){
            //if( ! isMobile ) return false;
        }

        BPBMJQ(document).on('click', '.bp-messages-call-controls .bpbm-disable-video', function( event ){
            event.preventDefault();

            myStream.getVideoTracks()[0].enabled = false;
            BPBMJQ('.bp-messages-call-controls .bpbm-disable-video').hide();
            BPBMJQ('.bp-messages-call-controls .bpbm-enable-video').show();
        });

        BPBMJQ(document).on('click', '.bp-messages-call-controls .bpbm-enable-video', function( event ){
            event.preventDefault();

            myStream.getVideoTracks()[0].enabled = true;
            BPBMJQ('.bp-messages-call-controls .bpbm-enable-video').hide();
            BPBMJQ('.bp-messages-call-controls .bpbm-disable-video').show();
        });

        BPBMJQ(document).on('click', '.bp-messages-call-controls .bpbm-disable-mic', function( event ){
            event.preventDefault();

            myStream.getAudioTracks()[0].enabled = false;
            myStream.getAudioTracks()[0].muted = true;
            BPBMJQ('.bp-messages-call-controls .bpbm-disable-mic').hide();
            BPBMJQ('.bp-messages-call-controls .bpbm-enable-mic').show();
        });

        BPBMJQ(document).on('click', '.bp-messages-call-controls .bpbm-enable-mic', function( event ){
            event.preventDefault();

            myStream.getAudioTracks()[0].enabled = true;
            myStream.getAudioTracks()[0].muted = false;
            BPBMJQ('.bp-messages-call-controls .bpbm-enable-mic').hide();
            BPBMJQ('.bp-messages-call-controls .bpbm-disable-mic').show();
        });

        BPBMJQ(document).on('click', '.bp-messages-video-container .bp-messages-call-controls .bpbm-answer', function( event ){
            event.preventDefault();
            if( typeof navigator.mediaDevices === 'undefined' ){
                BBPMShowError(BP_Messages['strings']['no_webrtc'])
            } else if ( ! myStream ) {
                setTimeout(function () {
                    BPBMJQ(this).trigger('click');
                }, 500);
            } else {
                var user_id = BPBMJQ(this).data( 'user-id' );
                startPeerIfNotStarted( user_id, 'video',true );
                peer.addStream(myStream);
                streamShared = true;
                peer.container = BPBMJQ(this).closest('.bp-messages-call-container');
                isInCall = true;

                if( typeof justCalled[user_id] !== 'undefined' ){
                    clearTimeout(justCalled[user_id]);
                }

                socket.emit('mediaEvent', {
                    event: 'answered',
                    to   : user_id
                });

                socket.emit('mediaEvent', {
                    event: 'self_reject',
                    to   : BP_Messages['user_id']
                });

                justRejected[user_id] = '1';
                setTimeout(function(){
                    delete justRejected[user_id];
                }, 3000);

                stopVideoCallSound();

                var container = $('.bp-messages-video-container');
                var wrap = container.closest('.bp-messages-wrap');

                wrap.addClass('bpbm-call-view');
                wrap.find('.bp-messages-main-placeholder').hide();
                wrap.find('.bp-messages-main-placeholder .bp-messages-placeholder-video').html('');
                wrap.find('.bp-messages-main-video').show();

                container.find('.bp-messages-call-controls > *').hide();
                container.find('.bp-messages-call-controls').show();
                container.find('.bp-messages-call-controls > .bpbm-call-in-progress').show();

                playSmallStream(myStream);
            }
        });

        BPBMJQ(document).on('click', '.bp-messages-audio-container .bp-messages-call-controls .bpbm-answer', function( event ){
            event.preventDefault();
            if( typeof navigator.mediaDevices === 'undefined' ){
                BBPMShowError(BP_Messages['strings']['no_webrtc'])
            } else {
                var user_id = BPBMJQ(this).data( 'user-id' );
                startPeerIfNotStarted( user_id, 'audio',true );
                peer.addStream(myStream);
                streamShared = true;
                peer.container = BPBMJQ(this).closest('.bp-messages-call-container');

                isInCall = true;

                if( typeof justCalled[user_id] !== 'undefined' ){
                    clearTimeout(justCalled[user_id]);
                }

                socket.emit('mediaEvent', {
                    event: 'answered_call',
                    to   : user_id
                });

                socket.emit('mediaEvent', {
                    event: 'self_reject',
                    to   : BP_Messages['user_id']
                });

                justRejected[user_id] = '1';
                setTimeout(function(){
                    delete justRejected[user_id];
                }, 3000);

                stopVideoCallSound();

                var container = $('.bp-messages-audio-container');
                var wrap = container.closest('.bp-messages-wrap');

                wrap.find('.bp-messages-placeholder-incoming-text, .bp-messages-placeholder-outgoing-text').hide();
                var timer = wrap.find('.bp-messages-timer');
                timer.show();
                timer.runner({
                    format: function(value) {
                        return msToTime(value);
                    },
                    milliseconds : false
                });
                timer.runner('start');

                container.find('.bp-messages-call-controls > *').hide();
                container.find('.bp-messages-call-controls').show();
                container.find('.bp-messages-call-controls > .bpbm-call-in-progress').show();
            }
        });

        BPBMJQ(document).on('click', '.bp-messages-call-controls .bpbm-reject', function( event ){
            event.preventDefault();
            var user_id = BPBMJQ(this).data( 'user-id' );

            stopVideoCallSound();

            socket.emit('mediaEvent', {
                event: 'rejected',
                to   : user_id
            });

            socket.emit('mediaEvent', {
                event: 'self_reject',
                to   : BP_Messages['user_id']
            });

            justRejected[user_id] = '1';
            setTimeout(function(){
                delete justRejected[user_id];
            }, 3000);
            endCall();
        });

        BPBMJQ(document).on('click', '.bp-messages-video-container .bp-messages-call-controls .bpbm-cancel', function( event ){
            event.preventDefault();

            var button    = $(this);
            button.addClass('bpbm-blocked');

            var container = button.closest('.bp-messages-video-container');

            socket.emit('mediaEvent', {
                event     : 'call_cancelled',
                to        : peer.participant,
                thread_id : container.data('thread-id')
            });

            BPBMTryCallFailed();

            endCall();

        });

        BPBMJQ(document).on('click', '.bp-messages-audio-container .bp-messages-call-controls .bpbm-cancel', function( event ){
            event.preventDefault();

            var button    = $(this);
            button.addClass('bpbm-blocked');

            var container = button.closest('.bp-messages-audio-container');

            socket.emit('mediaEvent', {
                event     : 'call_cancelled',
                to        : peer.participant,
                thread_id : container.data('thread-id')
            });

            BPBMTryCallFailed();
            endCall();
        });

        BPBMJQ(document).on('click', '.bp-messages-video-container .bp-messages-call-controls .bpbm-call-end', function( event ){
            event.preventDefault();

            socket.emit('mediaEvent', {
                event: 'call_end',
                to   : peer.participant
            });

            endCall();
        });

        BPBMJQ(document).on('click', '.bp-messages-audio-container .bp-messages-call-controls .bpbm-call-end', function( event ){
            event.preventDefault();

            socket.emit('mediaEvent', {
                event: 'call_end',
                to   : peer.participant
            });

            endCall();
        });

        BPBMJQ(document).on('click', '.bp-messages-wrap.bp-messages-popup .bpbm-answer', function( event ){
            event.preventDefault();
            var thread_id = BPBMJQ(this).data( 'thread-id' );
            var url = BP_Messages['threadUrl'] + thread_id + '&acceptCall';
            var mainContainer = $('.bp-messages-wrap.bp-messages-wrap-main');
            if (mainContainer.length > 0) {
                ajaxRefresh(url, mainContainer);
            } else {
                location.href = url;
            }

            $(this).closest('.amaran.incoming_call').remove();
        });

        BPBMJQ(document).on('click', '.bp-messages-wrap.bp-messages-popup .bpbm-reject', function( event ){
            event.preventDefault();
            var user_id    = BPBMJQ(this).data( 'user-id' );
            $(this).closest('.amaran.incoming_call').remove();

            stopVideoCallSound();

            socket.emit('mediaEvent', {
                event: 'rejected',
                to   : user_id
            });

            socket.emit('mediaEvent', {
                event: 'self_reject',
                to   : BP_Messages['user_id']
            });

            justRejected[user_id] = '1';
            setTimeout(function(){
                delete justRejected[user_id];
            }, 3000);

            endCall();
        });

        function BPBMUpdateCameraSettings( container, type, force ){
            if (myStream === false) return;

            if( typeof force === 'undefined' ) {
                force = false;
            }

            if( typeof type === 'undefined' ) {
                type = 'video';
            }

            var changeCamera = false;
            var changeMicrophone = false;

            var oldVideoTrack = false;
            var oldAudioTrack = false;

            var micEnabled = container.find('.bpbm-disable-mic').is(':visible')
            if( cameraId.trim === '' ) cameraId = false;

            if( (cameraId !== currentCameraId && type === 'video') ){
                changeCamera = true;
                changeMicrophone = true;
            }

            if( microphoneId.trim === '' ) microphoneId = false;

            if( microphoneId !== currentMicrophoneId ){
                changeMicrophone = true;
            }

            if( force ){
                if( cameraId === false ){
                    changeCamera = true;
                }

                if( microphoneId === false ){
                    changeMicrophone = true;
                }
            }

            myStream.getTracks().forEach(function (track) {
                if( track['kind'] === 'video' && changeCamera ){
                    oldVideoTrack = track;
                    track.stop();
                }

                if( track['kind'] === 'audio' && changeMicrophone ){
                    oldAudioTrack = track;
                    track.stop();
                }
            });

            //shouldFaceUser = !shouldFaceUser;
            if( ! changeMicrophone && ! changeCamera ) return false;

            if( type === 'video' ) {
                getUserVideo(function (stream, video, error) {
                    if (error !== false) {
                        console.error(error);
                        var _error = error.toString().split(':');
                        BBPMShowError(BP_Messages['strings']['cam_not_works'] + ': ' + _error[1]);
                    } else {
                        if (peersConnected || peer === false ) {
                            myStream = stream;
                        } else {
                            peer.removeStream(myStream);
                            myStream = stream;
                            peer.addStream(myStream);
                        }

                        myVideo = video;

                        var placeholder = container.find('.bp-messages-placeholder-video');

                        if (changeCamera) {
                            if (placeholder.is(':visible')) {
                                video.controls = false;
                                video.autoplay = true;
                                video.muted = true;
                                video.playsinline = true;
                                //myStream.getAudioTracks()[0].enabled = false;

                                container.find('.bp-messages-placeholder-video').html(video);
                                video.play();

                            } else {
                                playSmallStream(myStream);
                            }
                        }

                        currentCameraId = cameraId;
                        currentMicrophoneId = microphoneId;


                        if (peersConnected) {
                            if (changeCamera) {
                                var newVideoTrack = stream.getTracks().find(function (_track) {
                                    return _track.kind === 'video'
                                });

                                peer.replaceTrack(oldVideoTrack, newVideoTrack, originalStream);
                            }

                            if (changeMicrophone) {
                                var newAudioTrack = stream.getTracks().find(function (_track) {
                                    return _track.kind === 'audio'
                                });

                                peer.replaceTrack(oldAudioTrack, newAudioTrack, originalStream);
                            }

                            if (micEnabled) {
                                myStream.getAudioTracks()[0].enabled = true;
                            } else {
                                myStream.getAudioTracks()[0].enabled = false;
                            }
                        }
                    }
                });
            }

            if( type === 'audio' ) {
                getUserAudio(function (stream, error) {
                    if (error !== false) {
                        console.error(error);
                        var _error = error.toString().split(':');
                        BBPMShowError(BP_Messages['strings']['cam_not_works'] + ': ' + _error[1]);
                    } else {
                        if (peersConnected || peer === false) {
                            myStream = stream;
                        } else {
                            peer.removeStream(myStream);
                            myStream = stream;
                            peer.addStream(myStream);
                        }

                        currentMicrophoneId = microphoneId;

                        if (peersConnected) {
                            if (changeMicrophone) {
                                var newAudioTrack = stream.getTracks().find(function (_track) {
                                    return _track.kind === 'audio'
                                });

                                peer.replaceTrack(oldAudioTrack, newAudioTrack, originalStream);
                            }

                            if (micEnabled) {
                                myStream.getAudioTracks()[0].enabled = true;
                            } else {
                                myStream.getAudioTracks()[0].enabled = false;
                            }
                        }
                    }
                });
            }

        }

        function showOrHideSwitchButton(){
            var cogButton = BPBMJQ('.bp-messages-wrap .bpbm-configure-call');

            navigator.mediaDevices.enumerateDevices().then(function( devices ){
                var videoInputs = [];

                var cameraSelect = '<select class="bpbm-switch-camera-select"><option value="">Default</option>';
                var audioSelect = '<select class="bpbm-switch-audio-select"><option value="">Default</option>';
                var microSelect = '<select class="bpbm-switch-mic-select"><option value="">Default</option>';

                var cameraInputs = 0;
                var audioInputs  = 0;
                var microInputs  = 0;

                BPBMJQ.each( devices, function( index, item ){

                    if( item['deviceId'] !== '' ) {
                        var label = '';
                        var selected = '';

                        if (item['deviceId'] === 'default') {
                            label += 'Same as system - ';
                        }

                        if (item['deviceId'] === 'communications') {
                            label += 'Communications - ';
                        }

                        label += item['label'];

                        if (item.kind === 'videoinput') {

                            if (cameraId === item['deviceId']) {
                                selected = 'selected'
                            }

                            videoInputs.push(item);
                            cameraInputs++;
                            cameraSelect += '<option value="' + item['deviceId'] + '" data-label="' + label + '" ' + selected + '>' + label + '</option>';
                        }

                        if (item.kind === 'audiooutput') {
                            if (audioId === false) {
                                audioId = item['deviceId'];
                            }

                            if (audioId === item['deviceId']) {
                                selected = 'selected'
                            }

                            //audioInputs++;
                            //audioSelect += '<option value="' + item['deviceId'] + '" data-label="' + label + '" ' + selected + '>' + label + '</option>';
                        }

                        if (item.kind === 'audioinput') {
                            if (microphoneId === item['deviceId']) {
                                selected = 'selected'
                            }
                            microInputs++;
                            microSelect += '<option value="' + item['deviceId'] + '" data-label="' + label + '" ' + selected + '>' + label + '</option>';
                        }
                    }
                });

                cameraSelect += '</select>';
                audioSelect  += '</select>';
                microSelect  += '</select>';

                var showCog = false;

                if( cameraInputs > 0 ){
                    BPBMJQ('.bpbm-switch-camera').show();
                    BPBMJQ('.bpbm-switch-camera-select-wrap').html(cameraSelect);
                    showCog = true;
                } else {
                    BPBMJQ('.bpbm-switch-camera').hide();
                }

                if( audioInputs > 0 ){
                    BPBMJQ('.bpbm-switch-audio').show();
                    BPBMJQ('.bpbm-switch-audio-select-wrap').html(audioSelect);
                    showCog = true;
                } else {
                    BPBMJQ('.bpbm-switch-audio').hide();
                }

                if( microInputs > 0 ){
                    BPBMJQ('.bpbm-switch-mic').show();
                    BPBMJQ('.bpbm-switch-mic-select-wrap').html(microSelect);
                    showCog = true;
                } else {
                    BPBMJQ('.bpbm-switch-mic').hide();
                }

                if( showCog ) {
                    cogButton.show();
                } else {
                    cogButton.hide();
                }

            }).catch(function(error){
                console.error(error);
            });
        }

        function getUserVideo(callback) {
            var facingMode = shouldFaceUser ? 'user' : 'environment';

            var constraints = {
                audio: {
                    echoCancellation: true,
                    noiseSuppression: true
                },
                video: {
                    minWidth: 480,
                    minHeight: 240,
                    maxWidth: 1920,
                    maxHeight: 1080,
                    //facingMode : facingMode
                }
            };

            if( cameraId !== false && cameraId !== currentCameraId ){
                constraints['video']['deviceId'] = cameraId;
            }

            if( microphoneId !== false && microphoneId !== currentMicrophoneId ){
                constraints['audio']['deviceId'] = microphoneId;
            }

            var error = false;

            getUserMedia(constraints, function (stream) {
                showOrHideSwitchButton();

                var video = document.createElement('video');
                video.srcObject = stream;
                video.controls = true;
                video.muted = true;
                video.setAttribute('playsinline', 'true');

                callback(stream, video, error);
            }, function( _error ){
                if( _error ){
                    console.error( _error );
                    callback(null, null, _error);
                }
            });
        }

        function getUserAudio(callback) {

            var constraints = {
                audio: {
                    echoCancellation: true,
                    noiseSuppression: true,
                },
                video: false
            };

            if( microphoneId !== false && microphoneId !== currentMicrophoneId ){
                constraints['audio']['deviceId'] = microphoneId;
            }


            var error = false;

            getUserMedia(constraints, function (stream) {
                callback(stream, error);
            }, function( _error ){
                if( _error ){
                    callback(null, null, _error);
                }
            });
        }

        /**
         * Group calls start
        */
        const LivekitClient = require('livekit-client');
        var videoRoom = false;
        var liveKitToken = false;
        var localVideoTrack = false;
        var localVideoTrackInput = false;
        var localAudioTrack = false;
        var localAudioTrackInput = false;
        var videoGrid = false;

        function updateVideoGrid(){
            var videoGridContainer = BPBMJQ('.bp-messages-group-call-videos-grid');
            var videoTiles = BPBMJQ('.bp-messages-group-call-input-video');
            var videoCallWrap = videoGridContainer.closest('.bp-messages-call-wrap')
            var videoCount = videoTiles.length;

            var videoGridContainerWidth   = videoCallWrap.width();
            var videoGridContainerHeight  = videoCallWrap.height();

            var videoWidth  = 400;
            var videoHeight = false;
            var maxVideoHeight = false;

            if( videoGridContainerWidth < 400 || isMobile ) {
                if (videoCount === 1) {
                    videoWidth = videoGridContainerWidth;
                    videoHeight = videoCallWrap.height();
                } else if (videoCount === 2) {
                    videoWidth = videoGridContainerWidth;
                    videoHeight = videoGridContainerHeight / 2;
                } else if (videoCount <= 3) {
                    videoWidth = videoGridContainerWidth;
                    videoHeight = videoGridContainerHeight / videoCount;
                } else if (videoCount <= 4) {
                    videoWidth = videoGridContainerWidth / 2;
                    videoHeight = videoGridContainerHeight / 2;
                } else if (videoCount <= 6) {
                    videoWidth = videoGridContainerWidth / 2;
                    videoHeight = videoGridContainerHeight / 3;
                } else if (videoCount <= 9) {
                    videoWidth = videoGridContainerWidth / 3;
                    videoHeight = videoGridContainerHeight / 3;
                }
            } else {
                if (videoCount === 1) {
                    videoWidth = videoGridContainerWidth;
                    videoHeight = videoCallWrap.height();
                } else if (videoCount === 2) {
                    videoWidth = videoGridContainerWidth;
                    videoHeight = videoGridContainerHeight / 2;
                } else if (videoCount <= 4) {
                    videoWidth = videoGridContainerWidth / 2;
                    videoHeight = videoGridContainerHeight / 2;
                } else if (videoCount <= 6) {
                    videoWidth = videoGridContainerWidth / 3;
                    videoHeight = videoGridContainerHeight / 2;
                } else if (videoCount <= 9) {
                    videoWidth = videoGridContainerWidth / 3;
                    videoHeight = videoGridContainerHeight / 3;
                }
            }


            if( videoHeight === false ) {
                videoHeight = videoWidth * 0.65;
            }

            videoTiles.each(function (){
                var tile = BPBMJQ(this);
                var isMine = tile.hasClass('bpbm-mine-stream');

                var width  = tile.data('video-width');
                var height = tile.data('video-height');

                var ratio = height / width;

                if( ratio < 0.8 ){}

                tile.css({
                    'width': videoWidth,
                    'height': videoHeight,
                    'maxHeight' : maxVideoHeight
                });

                if( ! tile.hasClass('muuri-item') ){
                    var gridItem = videoGrid.add(tile[0]);
                    if( tile.hasClass('muuri-item-hidden') ) {
                        videoGrid.show(gridItem);
                    }
                }
            });

            videoGrid.move(videoGridContainer.find('.bpbm-mine-stream')[0], videoCount - 1, {
                layout: false
            });

            setTimeout(function (){
                videoGrid.refreshItems();
                videoGrid.layout();
            }, 100);
        }

        socket.on('groupMediaEvent', function(message){
            updateGroupCallStatus( message.thread_id );
        });

        function createParticipantTile( participant ){
            var user_id = participant.identity.split('_')[1];
            var user = BPBMJQ.parseJSON(participant.metadata);
            var callElement = BPBMJQ('.bp-messages-group-call-input-video[data-user-id="' + user_id + '"]');
            var wrap = BPBMJQ('.bp-messages-group-call-videos-grid').closest('.bp-messages-wrap');

            var isAdmin = wrap.find('.list.can-moderate').length > 0;

            if( callElement.length === 0 ) {
                var adminButtons = isAdmin ? '<span class="bpbm-admin-controls"><span class="bpbm-kick" title="Kick User"><i class="fas fa-user-slash"></i></span></span>' : '';

                callElement = BPBMJQ('<div class="bp-messages-group-call-input-video bpbm-no-video bpbm-no-audio" data-user-id="' + user_id + '">' +
                    '<div class="bp-messages-group-call-input-video-inner">' +
                    '<div class="bpbm-group-call-input-video-inner-info">' +
                    '<span class="bpbm-caller-info">' +
                    '<span class="bpbm-info-name"><span class="bpbm-name">' + user['name'] + '</span>'  + adminButtons + '</span>' +
                    '<span class="bpbm-caller-status">' +
                    '<span class="bpbm-mic-disabled"><i class="fas fa-microphone-slash"></i></span>' +
                    '<span class="bpbm-camera-disabled"><i class="fas fa-video-slash"></i></span>' +
                    '</span> ' +
                    '</span> ' +
                    '</div>' +
                    '<div class="bpbm-media-container">' +
                    '<video autoplay playsinline></video>' +
                    '<audio autoplay></audio>' +
                    '</div>' +
                    '</div>' +
                    '</div>');

                callElement.attr('data-avatar', user['avatar'])
                callElement.appendTo('.bp-messages-group-call-videos-grid');

                updateCallElement( callElement );
                updateVideoGrid();
            }
        }


        BPBMJQ(document).on('click', '.bpbm-group-call-in-progress-join button', function( event ){
            event.preventDefault();

            var wrap = BPBMJQ(this).closest('.bp-messages-wrap');
            wrap.find('.chat-header .group-call').click();
        });

        /** Call start */
        BPBMJQ(document).on('click', '.bp-messages-wrap .chat-header .group-call', function (event) {
            event.preventDefault();
            event.stopImmediatePropagation();

            var button = BPBMJQ(this);
            var thread_id = button.attr('data-thread-id');
            var wrap = button.closest('.bp-messages-wrap');
            var threadDiv    = $('.bp-messages-wrap .thread.scroller[data-id="' + thread_id + '"][data-users-json]');
            var chatContentContainer = wrap.find('.bpbm-chat-content');

            wrap.addClass('bpbm-call-view');
            chatContentContainer.addClass('bpbm-call-view');

            if( isMobile ) {
                chatContentContainer.addClass('bpbm-hide-chat');
            }

            videoGrid = new BPBMMuuri('.bp-messages-group-call-videos-grid', {
                dragEnabled: false,
                layout: {
                    fillGaps: false,
                    horizontal: false,
                    alignRight: false,
                    alignBottom: false,
                    rounding: false
                },
            });

            $(window).resize(function(){
                updateVideoGrid();
            });

            setInterval(function (){
                //updateVideoGrid();
            }, 1000);

            var mineStream = BPBMJQ('.bp-messages-group-call-input-video.bpbm-mine-stream');

            if( mineStream.length === 0 ) {
                var user_id   = BP_Messages['user_id'];
                var usersJson = atob(threadDiv.attr('data-users-json'));
                var recipients = $.parseJSON(usersJson);

                if (typeof recipients[user_id] !== 'undefined') {
                    var avatar = BPBMJQ(recipients[user_id]['avatar']);
                }

                mineStream = BPBMJQ(
                    '<div class="bp-messages-group-call-input-video bpbm-mine-stream bpbm-no-video bpbm-no-audio" style="display: none" data-avatar="' + avatar.attr('src') + '" data-user-id="' + user_id + '">' +
                    '<div class="bp-messages-group-call-input-video-inner">' +
                    '<div class="bpbm-group-call-input-video-inner-info">' +
                    '<span class="bpbm-caller-info">' +
                    '<span class="bpbm-info-name"><span class="bpbm-name">' + BP_Messages['strings']['me'] + '</span></span>' +
                    '<span class="bpbm-caller-status">' +
                    '<span class="bpbm-mic-disabled"><i class="fas fa-microphone-slash"></i></span>' +
                    '<span class="bpbm-camera-disabled"><i class="fas fa-video-slash"></i></span>' +
                    '</span>' +
                    '</span>' +
                    '</div>' +
                    '<div class="bpbm-media-container"></div>' +
                    '</div>' +
                    '</div>'
                );

                mineStream.appendTo('.bp-messages-group-call-videos-grid');

                var groupControls = chatContentContainer.find('.bp-messages-group-call-controls');

                groupControls.clone().prependTo('.bpbm-mine-stream .bpbm-group-call-input-video-inner-info').show();

                showOrHideGroupSwitchButton();

                updateCallElement( mineStream );
            }

            setTimeout(function(){
                updateVideoGrid();
            }, 300);

            $.post(BP_Messages['ajaxUrl'], {
                'action'    : 'bp_better_messages_get_thread_group_call_access_key',
                'thread_id' : thread_id,
                'nonce'     : BP_Messages['userNonce']
            }, function(response){
                var token = response;
                liveKitToken = token;

                LivekitClient.connect('wss://video-cloud.bpbettermessages.com', token, {}).then(function (room) {
                    isInCall = true;

                    videoRoom = room;

                    updateVideoGrid();

                    socket.emit('groupMediaEvent', {
                        event     : 'user_connected',
                        thread_id : thread_id,
                    });

                    var updateAudioLevelsTimeout;
                    function updateAudioLevels(){
                        clearTimeout( updateAudioLevelsTimeout );

                        var _participants = videoRoom.participants;
                        _participants.set(videoRoom.localParticipant.sid, videoRoom.localParticipant);

                        _participants.forEach( function (participant){
                            var user_id = participant.identity.split('_')[1];
                            var callElement = BPBMJQ('.bp-messages-group-call-input-video[data-user-id="' + user_id + '"]');
                            var innerElement = callElement.find('.bp-messages-group-call-input-video-inner');

                            if( participant.isSpeaking ){
                                var audioLevel = ( participant.audioLevel ) * 100 * 4;
                                if( audioLevel > 100 ) audioLevel = 100;
                                innerElement.addClass('bpbm-active-speaker');
                                innerElement.css( 'box-shadow', '0 1px 5px 1px rgb( 33 117 155 / ' + audioLevel + '%)');
                            } else {
                                innerElement.removeClass('bpbm-active-speaker');
                                innerElement.css( 'box-shadow', 'none');
                            }
                        } );

                        setTimeout(function(){
                            updateAudioLevels();
                        }, 1000);
                    }

                    room.participants.forEach(function(participant){
                        createParticipantTile( participant );
                    });

                    room.on(LivekitClient.RoomEvent.ParticipantConnected, function ( participant ) {
                        createParticipantTile( participant );
                    });

                    room.on(LivekitClient.RoomEvent.ParticipantDisconnected, function ( participant ) {
                        var user_id = participant.identity.split('_')[1];
                        var callElement = BPBMJQ('.bp-messages-group-call-input-video[data-user-id="' + user_id + '"]');
                        callElement.remove();
                        updateVideoGrid();
                    });

                    room.on(LivekitClient.RoomEvent.TrackSubscribed, function ( track, publication, participant ) {
                            var user_id = participant.identity.split('_')[1];
                            createParticipantTile( participant );

                            if (track.kind === LivekitClient.Track.Kind.Video || track.kind === LivekitClient.Track.Kind.Audio) {
                                const element = track.attach();
                                var callElement = BPBMJQ('.bp-messages-group-call-input-video[data-user-id="' + user_id + '"]');

                                if( track.kind === LivekitClient.Track.Kind.Video ) {
                                    if( track.isMuted ){
                                        callElement.addClass('bpbm-no-video');
                                    } else {
                                        callElement.removeClass('bpbm-no-video');
                                    }

                                    LivekitClient.attachToElement( track.mediaStreamTrack, callElement.find('video')[0] )

                                } else {
                                    if( track.isMuted ){
                                        callElement.addClass('bpbm-no-audio');
                                    } else {
                                        callElement.removeClass('bpbm-no-audio');
                                    }

                                    LivekitClient.attachToElement( track.mediaStreamTrack, callElement.find('audio')[0] )
                                }

                                if( participant.isSpeaking ){
                                    var audioLevel = ( participant.audioLevel ) * 100 * 3;
                                    if( audioLevel > 100 ) audioLevel = 100;
                                    callElement.addClass('bpbm-active-speaker');
                                    callElement.css( 'box-shadow', '0 1px 5px 1px rgb( 255 255 255 / ' + audioLevel + '%)');
                                } else {
                                    callElement.removeClass('bpbm-active-speaker');
                                    callElement.css( 'box-shadow', 'none');
                                }

                                updateCallElement( callElement );
                            }
                        }
                    );

                    room.on(LivekitClient.RoomEvent.TrackUnsubscribed, function ( track, publication, participant ) {
                        /*
                        var user_id = participant.identity.split('_')[1];
                        track.detach();
                        var callElement = BPBMJQ('.bp-messages-group-call-input-video[data-user-id="' + user_id + '"]');
                        callElement.remove();

                        updateVideoGrid(); */
                    });

                    room.on(LivekitClient.RoomEvent.TrackMuted, function ( track, participant ) {
                        var user_id = participant.identity.split('_')[1];
                        var callElement = BPBMJQ('.bp-messages-group-call-input-video[data-user-id="' + user_id + '"]');

                        if (track.kind === LivekitClient.Track.Kind.Video ) {
                            callElement.addClass('bpbm-no-video');
                        }

                        if (track.kind === LivekitClient.Track.Kind.Audio ) {
                            callElement.addClass('bpbm-no-audio');
                        }

                        updateCallElement( callElement );
                    });


                    room.on(LivekitClient.RoomEvent.TrackUnmuted, function ( track, participant ) {
                        var user_id = participant.identity.split('_')[1];
                        var callElement = BPBMJQ('.bp-messages-group-call-input-video[data-user-id="' + user_id + '"]');

                        if (track.kind === LivekitClient.Track.Kind.Video ) {
                            callElement.removeClass('bpbm-no-video');
                        }

                        if (track.kind === LivekitClient.Track.Kind.Audio ) {
                            callElement.removeClass('bpbm-no-audio');
                        }

                        updateCallElement( callElement );
                    });


                    room.on(LivekitClient.RoomEvent.ActiveSpeakersChanged, function (participants) {
                        updateAudioLevels();
                    });

                    room.on(LivekitClient.RoomEvent.Disconnected, function () {
                        groupCallEnd();

                        groupCallEndInProgress = false;
                    });
                }).catch(function (error){
                    console.error( error );
                });

                });
            });

        function updateCallElement( callElement ){
                var videoActive = callElement.hasClass('bpbm-no-video') === false;
                var audioActive = callElement.hasClass('bpbm-no-audio') === false;

                var inner = callElement.find('.bp-messages-group-call-input-video-inner');

                var videoEl   = callElement.find('video')
                var avatarSrc = callElement.attr('data-avatar');

                inner.css('background-image', 'url(' + avatarSrc + ')');

                if( ! videoActive ){
                    videoEl.hide();
                    inner.css('background-image', 'url(' + avatarSrc + ')');
                } else {
                    videoEl.show();
                    inner.css('background-image', 'none');
                }

        }

        BPBMJQ(document).on('click', '.bp-messages-wrap .bp-messages-group-call-controls .bpbm-configure-call', function (event) {
            event.preventDefault();

            var controls = BPBMJQ(this).closest('.bp-messages-group-call-controls');
            controls.find('.bpbm-call-settings').toggle();
        });

        BPBMJQ(document).on('change', '.bp-messages-wrap .bp-messages-group-call-controls .bpbm-switch-camera-select', function (event) {
            event.preventDefault();
            event.stopImmediatePropagation();

            var element = BPBMJQ(this);
            localVideoTrackInput = element.val();

            if( localVideoTrack !== false ) {
                localVideoTrack.restartTrack({
                    deviceId: localVideoTrackInput
                });
            }

        });

        BPBMJQ(document).on('change', '.bp-messages-wrap .bp-messages-group-call-controls .bpbm-switch-mic-select', function (event) {
            event.preventDefault();
            event.stopImmediatePropagation();

            var element = BPBMJQ(this);

            localAudioTrackInput = element.val();

            if( localAudioTrack !== false ) {
                localAudioTrack.restartTrack({
                    deviceId: localAudioTrackInput
                });
            }
        });

        function showOrHideGroupSwitchButton(){
            var controls  = BPBMJQ('.bp-messages-group-call-input-video.bpbm-mine-stream .bp-messages-group-call-controls');
            var cogButton = controls.find('.bpbm-configure-call');

            navigator.mediaDevices.enumerateDevices().then(function( devices ){
                var videoInputs = [];

                var cameraSelect = '<select class="bpbm-switch-camera-select"><option value="">Default</option>';
                var audioSelect = '<select class="bpbm-switch-audio-select"><option value="">Default</option>';
                var microSelect = '<select class="bpbm-switch-mic-select"><option value="">Default</option>';

                var cameraInputs = 0;
                var audioInputs  = 0;
                var microInputs  = 0;

                BPBMJQ.each( devices, function( index, item ){
                    var label = '';
                    var selected = '';

                    if( item['deviceId'] !== '' && item['label'] !== '' ) {

                        if (item['deviceId'] === 'default') {
                            label += 'Same as system - ';
                        }

                        if (item['deviceId'] === 'communications') {
                            label += 'Communications - ';
                        }

                        label += item['label'];

                        if (item.kind === 'videoinput') {

                            if (cameraId === item['deviceId']) {
                                selected = 'selected'
                            }

                            videoInputs.push(item);
                            cameraInputs++;
                            cameraSelect += '<option value="' + item['deviceId'] + '" data-label="' + label + '" ' + selected + '>' + label + '</option>';
                        }

                        if (item.kind === 'audiooutput') {
                            if (audioId === false) {
                                audioId = item['deviceId'];
                            }

                            if (audioId === item['deviceId']) {
                                selected = 'selected'
                            }

                            //audioInputs++;
                            //audioSelect += '<option value="' + item['deviceId'] + '" data-label="' + label + '" ' + selected + '>' + label + '</option>';
                        }

                        if (item.kind === 'audioinput') {
                            if (microphoneId === item['deviceId']) {
                                selected = 'selected'
                            }
                            microInputs++;
                            microSelect += '<option value="' + item['deviceId'] + '" data-label="' + label + '" ' + selected + '>' + label + '</option>';
                        }
                    }
                });

                cameraSelect += '</select>';
                audioSelect  += '</select>';
                microSelect  += '</select>';

                var showCog = false;

                if( cameraInputs > 0 ){
                    controls.find('.bpbm-switch-camera').show();
                    controls.find('.bpbm-switch-camera-select-wrap').html(cameraSelect);
                    showCog = true;
                } else {
                    controls.find('.bpbm-switch-camera').hide();
                }

                if( audioInputs > 0 ){
                    controls.find('.bpbm-switch-audio').show();
                    controls.find('.bpbm-switch-audio-select-wrap').html(audioSelect);
                    showCog = true;
                } else {
                    controls.find('.bpbm-switch-audio').hide();
                }

                if( microInputs > 0 ){
                    controls.find('.bpbm-switch-mic').show();
                    controls.find('.bpbm-switch-mic-select-wrap').html(microSelect);
                    showCog = true;
                } else {
                    controls.find('.bpbm-switch-mic').hide();
                }

                if( showCog ) {
                    cogButton.show();
                } else {
                    cogButton.hide();
                }

            }).catch(function(error){
                console.error(error);
            });
        }

        function AdminListParticipants( token, thread_id ){
            $.post(BP_Messages['ajaxUrl'], {
                'action'    : 'bp_better_messages_thread_group_call_admin',
                'token'     : token,
                'thread_id' : thread_id,
                'act'       : 'list_participant',
                'nonce'     : BP_Messages['userNonce']
            }, function( response ) {
            });
        }

        function AdminRemoveParticipant( token, thread_id, user_id ){
            $.post(BP_Messages['ajaxUrl'], {
                'action'    : 'bp_better_messages_thread_group_call_admin',
                'token'     : token,
                'thread_id' : thread_id,
                'act'       : 'remove_participant',
                'user_id'   : user_id,
                'nonce'     : BP_Messages['userNonce']
            }, function( response ) {
            });
        }

        BPBMJQ(document).on('click', '.bp-messages-group-call-input-video .bpbm-kick', function(event){
            event.preventDefault();
            var callElement = BPBMJQ(this).closest('.bp-messages-group-call-input-video');
            var wrap = callElement.closest('.bp-messages-wrap[data-thread-id]');
            var thread_id = wrap.attr('data-thread-id');
            AdminRemoveParticipant( liveKitToken, thread_id, callElement.attr('data-user-id') );
        })

        BPBMJQ(document).on('click', '.bp-messages-group-call-controls .bpbm-call-end', function( event ){
            event.preventDefault();
            groupCallEnd();
        });

        BPBMJQ(document).on('click', '.bp-messages-call-wrap.bp-messages-call-wrap-group .bpbm-switch-chat', function (event) {
            event.preventDefault();
            event.stopImmediatePropagation();

            BPBMJQ(this).closest('.bpbm-chat-content').toggleClass('bpbm-hide-chat');
            setTimeout(function(){
                updateVideoGrid();
            }, 300);
        });


        function getLocalVideoTrack(){
            return new Promise(function(resolve, reject) {
                if (localVideoTrack === false) {
                    LivekitClient.createLocalVideoTrack({
                        deviceId: localVideoTrackInput
                    }).then(function (track) {
                        localVideoTrack = track;
                        var mineStream = BPBMJQ('.bp-messages-group-call-input-video.bpbm-mine-stream');
                        const element = track.attach();
                        mineStream.find('.bpbm-media-container')[0].appendChild(element);
                        mineStream.find('video').hide();

                        showOrHideGroupSwitchButton();
                        videoRoom.localParticipant.publishTrack(localVideoTrack, {
                            name: 'video',
                            simulcast: true,
                        }).then(function(){
                            resolve(localVideoTrack);
                        });

                    }).catch(function (error) {
                        var _error = error.toString().split(':');
                        BBPMShowError(BP_Messages['strings']['cam_not_works'] + ': ' + _error[1]);
                        reject(error);
                    });
                } else {
                    resolve(localVideoTrack);
                }
            });
        }


        BPBMJQ(document).on('click', '.bp-messages-group-call-controls .bpbm-enable-video', function( event ){
            event.preventDefault();

            getLocalVideoTrack().then(function (){
                BPBMJQ('.bp-messages-group-call-controls .bpbm-enable-video').hide();
                BPBMJQ('.bp-messages-group-call-controls .bpbm-disable-video').show();

                localVideoTrack.unmute();

                var mineStream = BPBMJQ('.bp-messages-group-call-input-video.bpbm-mine-stream');
                mineStream.removeClass('bpbm-no-video');
                updateCallElement( mineStream );
            });
        });

        BPBMJQ(document).on('click', '.bp-messages-group-call-controls .bpbm-disable-video', function( event ){
            event.preventDefault();

            getLocalVideoTrack().then(function (){
                BPBMJQ('.bp-messages-group-call-controls .bpbm-disable-video').hide();
                BPBMJQ('.bp-messages-group-call-controls .bpbm-enable-video').show();

                localVideoTrack.mute();

                var mineStream = BPBMJQ('.bp-messages-group-call-input-video.bpbm-mine-stream');
                mineStream.addClass('bpbm-no-video');
                updateCallElement( mineStream );
            });
        });

        function getLocalAudioTrack(){
            return new Promise(function(resolve, reject) {
                if (localAudioTrack === false) {
                    LivekitClient.createLocalAudioTrack({
                        deviceId: localAudioTrackInput
                    }).then(function (track) {
                        localAudioTrack = track;
                        videoRoom.localParticipant.publishTrack(localAudioTrack, {
                            name: 'audio',
                            simulcast: true,
                        }).then(function(){
                            resolve(localAudioTrack);
                        });

                        showOrHideGroupSwitchButton();
                    }).catch(function (error) {
                        var _error = error.toString().split(':');
                        BBPMShowError(BP_Messages['strings']['mic_not_works'] + ': ' + _error[1]);
                        reject(error);
                    });
                } else {
                    resolve(localAudioTrack);
                }
            });
        }

        BPBMJQ(document).on('click', '.bp-messages-group-call-controls .bpbm-enable-mic', function( event ){
            event.preventDefault();

            getLocalAudioTrack().then(function (){
                BPBMJQ('.bp-messages-group-call-controls .bpbm-enable-mic').hide();
                BPBMJQ('.bp-messages-group-call-controls .bpbm-disable-mic').show();

                localAudioTrack.unmute();

                var mineStream = BPBMJQ('.bp-messages-group-call-input-video.bpbm-mine-stream');
                mineStream.removeClass('bpbm-no-audio');
                updateCallElement( mineStream );
            });
        });

        BPBMJQ(document).on('click', '.bp-messages-group-call-controls .bpbm-disable-mic', function( event ){
            event.preventDefault();

            getLocalAudioTrack().then(function (){
                BPBMJQ('.bp-messages-group-call-controls .bpbm-disable-mic').hide();
                BPBMJQ('.bp-messages-group-call-controls .bpbm-enable-mic').show();
                localAudioTrack.mute();

                var mineStream = BPBMJQ('.bp-messages-group-call-input-video.bpbm-mine-stream');
                mineStream.addClass('bpbm-no-audio');
                updateCallElement( mineStream );
            });

        });

        var groupCallEndInProgress = false;
        function groupCallEnd(){
            if( groupCallEndInProgress || videoRoom === false ) return false;
            groupCallEndInProgress = true;
            var wrap      = BPBMJQ('.bp-messages-wrap');
            var thread_id = wrap.attr('data-thread-id');
            wrap.removeClass('bpbm-call-view');
            var chatContentContainer = wrap.find('.bpbm-chat-content');
            chatContentContainer.removeClass('bpbm-call-view');


            socket.emit('groupMediaEvent', {
                event     : 'user_disconnected',
                thread_id : thread_id,
            });

            videoRoom.disconnect();
            BPBMJQ('.bp-messages-group-call-controls .bpbm-disable-video').hide();
            BPBMJQ('.bp-messages-group-call-controls .bpbm-enable-video').show();
            BPBMJQ('.bp-messages-group-call-controls .bpbm-disable-mic').hide();
            BPBMJQ('.bp-messages-group-call-controls .bpbm-enable-mic').show();

            isInCall = localAudioTrack = localVideoTrack = liveKitToken = false;

            videoGrid.destroy(true);
        }


        /**
         * Group calls end
         */

        socket.on('getUnread', function (_unread) {
            var messagesTab = $('.bp-better-messages-list > .tabs > div[data-tab="messages"]');
            var total = 0;
            var unreadThreads = 0;
            var wraps = $('.bp-messages-wrap .threads-list').length;

            if(Object.keys(_unread['threads']).length > 0){
                $.each(_unread['threads'], function( index ){
                    updateUnreadCounters(index, this);
                    unread[index] = this;
                    total = total + parseInt(this);
                    unreadThreads++;

                    if(wraps > 0){
                        if($(threadsSelector + '[data-id="' + index + '"]').length === 0){
                            socket.emit('threadOpen', index);
                        }
                    }
                });

                if(wraps > 0){
                    $(threadsSelector + '[data-id]').each(function(){
                        var thread_id = $(this).data('id');
                        if(typeof _unread['threads'][thread_id] === 'undefined'){
                            updateUnreadCounters(thread_id, 0);
                        }
                    });
                }
            } else {
                total = 0;
                $('.threads-list .thread, .bp-better-messages-mini .chat').removeClass('unread');
                $('.threads-list .thread .time .unread-count').text('');
                $('.bp-better-messages-mini .chat .unread-count').attr('class', 'unread-count count-0').text('');
                unread = {};
            }

            if(total > 0){
                messagesTab.find('.fas').hide();
                messagesTab.find('.unread-count').text(total).show();
            } else {
                messagesTab.find('.fas').show();
                messagesTab.find('.unread-count').text('').hide();
            }

            BPBMUpdateUnreadCount(unreadThreads);
        });

        socket.on('message_deleted', function(message_id){
            deleteMessage([message_id]);
        });
        /**
         * Online users
         */
        socket.on('onlineUsers', function (user_ids) {
            onlineFetched = true;
            online = user_ids;
            BPBMOnlineUsers = online;
            onlineInit();

            document.dispatchEvent(new CustomEvent('bp-better-messages-online-fetched'));

        });

        socket.on('userOnline', function (user_id) {
            if (online.indexOf(user_id) === -1) {
                online.push(user_id);
                $('.bbpm-avatar[data-user-id="' + user_id + '"]').addClass('online');

                sortOnlineFriends();
                BPBMOnlineUsers = online;

                document.dispatchEvent(new CustomEvent('bp-better-messages-user-online', {
                    detail: {
                        user_id: user_id
                    }
                }));
            }
        });

        socket.on('userOffline', function (user_id) {
            if (online.indexOf(user_id) > -1) {
                online.splice(online.indexOf(user_id), 1);
                $('.bbpm-avatar[data-user-id="' + user_id + '"]').removeClass('online');

                BPBMOnlineUsers = online;

                sortOnlineFriends();

                document.dispatchEvent(new CustomEvent('bp-better-messages-user-offline', {
                    detail: {
                        user_id: user_id
                    }
                }));
            }
        });

        /**
         * Messaging
         */
        socket.on('message', function (message) {
            var miniChat = '.bp-better-messages-mini .chats .chat[data-thread="'+ message.thread_id +'"]';
            var chat = $(miniChat);
            var openChat = $('.bp-better-messages-mini .chats .chat[data-thread="'+ message.thread_id +'"].open');

            var thread_id = message.thread_id;

            if( BP_Messages['encryption'] === '1' ) {
                var threadDiv = $('.bp-messages-wrap .thread.scroller[data-id="' + thread_id + '"][data-secret]');
                var threadSecret = threadDiv.data('secret');
                var userSecret   = BP_Messages['encrypt_key'];

                if( message.fast && threadDiv.length > 0 ) {
                    var _message = BPBMAES256.decrypt(message.message, threadSecret);

                    _message = BPBMJQ('<div />').text(_message).html();

                    var allowed_tags = [
                        'p', 'b', 'i', 'u', 'strike', 'sub', 'sup', 'br'
                    ];

                    allowed_tags.forEach(function(tag, index) {
                        var start = new RegExp('&lt;' + tag + '&gt;', 'g');
                        var end   = new RegExp('&lt;/' + tag + '&gt;', 'g');
                        _message = _message.replace(start, '<' + tag + '>', _message);
                        _message = _message.replace(end, '</' + tag + '>', _message);
                    });

                    _message = _message.replace(/ style=\"\"/g, '', _message);
                    _message = _message.replace(/<br>/g, "\n", _message);
                    _message = _message.replace(/&nbsp;/g, ' ', _message);
                    _message = _message.replace(/&amp;nbsp;/g, ' ', _message);

                    _message = _message.trim();

                    if( _message.substring(0, 3) === '<p>' ) {
                        _message = _message.substring(3);
                    }

                    if( _message.substring(_message.length - 4) === '</p>' ) {
                        _message = _message.substring( 0, ( _message.length - 4) );
                    }

                    _message = _message.replace(/&amp;lt;/g, '&lt;', _message);
                    _message = _message.replace(/&amp;gt;/g, '&gt;', _message);

                    _message = _message.replace(/\n/g, '<br>', _message);

                    _message = emojione.toImage(_message);

                    if(_message === '<br>') _message = '';

                    message.message = _message;
                } else if( ! message.fast ){
                    if( typeof message.content_site !== 'undefined' ) {
                        message.content_site = BPBMAES256.decrypt(message.content_site, userSecret);
                    }
                    if( typeof message.html !== 'undefined' ) {
                        message.html         = BPBMAES256.decrypt(message.html,         userSecret);
                    }
                    message.avatar       = BPBMAES256.decrypt(message.avatar,       userSecret);
                    message.name         = BPBMAES256.decrypt(message.name,         userSecret);
                    if( threadDiv.length > 0 ){
                        message.message     = BPBMAES256.decrypt(message.message, threadSecret);
                        message.link        = BPBMAES256.decrypt(message.link,    threadSecret);
                    }
                }
            }

            if( message.fast ) {
                var _threadDiv    = $('.bp-messages-wrap .thread.scroller[data-id="' + thread_id + '"][data-users-json]');
                if( _threadDiv.length > 0 ) {
                    var usersJson = atob(_threadDiv.attr('data-users-json'));
                    var recipients = $.parseJSON(usersJson);

                    if (typeof (recipients[message.user_id]) !== 'undefined') {
                        message.avatar = recipients[message.user_id].avatar;
                        message.link = recipients[message.user_id].link;
                        message.name = recipients[message.user_id].name;
                    } else {
                        return false;
                    }
                }
            }


            if( ! message.fast && BP_Messages['realtime'] == '1') {
                if ( BP_Messages['user_id'] != message.user_id ) {
                    var read = false;
                    var threadMatch = parseInt(message['thread_id']) === parseInt(thread);
                    var openInMobileView = $('body').hasClass('bp-messages-mobile');

                    if( openInMobileView ){
                        if( threadMatch ){
                            read = true;
                        }
                    } else {
                        if( ! isMobile ) {
                            if (ifvisible.now('active')) {
                                if (threadMatch) {
                                    read = true;
                                }

                                if (openChat.length > 0) {
                                    read = true;
                                }
                            }
                        } else {
                            if( threadMatch ){
                                read = true;
                            }
                        }
                    }

                    if ( read ) {
                        socket.emit('seen', [message.id]);
                        socket.emit('threadOpen', message['thread_id']);;
                    } else {
                        socket.emit('delivered', message.id);
                    }
                } else {
                }

                var message_id = message.id;
                var message_to_replace = $('.bp-messages-wrap .list .messages-stack .content .messages-list li[data-id="' + message_id + '"]');
                if( message_to_replace.length > 0 ){
                    message_to_replace.find('.message-content').html(message.message);
                }
            }

            updateThreads( message );

            renderMessage(message, '.bp-messages-wrap[data-thread-id="'+ message.thread_id +'"]');
            renderMessage(message, '#bp-better-messages-mini-mobile-container.bp-messages-wrap[data-thread="'+ message.thread_id +'"]');

            if (thread == message['thread_id']) {
                //renderMessage(message);
            } else if (threads) {
                if(chat.length > 0){
                    renderMessage(message, miniChat);
                }
            } else {
                if(chat.length > 0){
                    renderMessage(message, miniChat);
                } else if (typeof message.content_site !== 'undefined' && BP_Messages['user_id'] != message.user_id && ! message.fast) {
                    showMessage(message.thread_id, message.content_site, message.name, message.avatar);
                }
            }
        });


        socket.on('onSiteNotification', function (data) {
            if( BP_Messages['encryption'] === '1' ) {
                var userSecret = BP_Messages['encrypt_key'];
                data.image     = BPBMAES256.decrypt(data.image, userSecret);
                data.text      = BPBMAES256.decrypt(data.text, userSecret);
                data.url       = BPBMAES256.decrypt(data.url, userSecret);
                data.title     = BPBMAES256.decrypt(data.title, userSecret);
            }

            var image    = data.image;
            var findSrc  = image.match(/src\="([^\s]*)"\s/);
            var findSrc2 = image.match(/src\='([^\s]*)'\s/);

            if (findSrc != null) {
                image = findSrc[1];
            }

            if (findSrc2 != null) {
                image = findSrc2[1];
            }

            var content =  {
                img: image,
                user: data.title,
                message: data.text
            };

            $.amaran({
                'theme': 'user message',
                'content': content,
                'sticky': true,
                'closeOnClick': false,
                'closeButton': true,
                'delay': 10000,
                'position': 'bottom right',
                onClick: function () {
                    location.href = data.url;
                }
            });

            if( typeof sounds.notification !== 'undefined' ) {
                sounds.notification.play();
            }
        });

        if(BP_Messages['realtime'] == '1') {
            socket.on('delivered', function (message_id, user_id) {
                var message = $('.bp-messages-wrap .list .messages-stack .content .messages-list li[data-id="' + message_id + '"]');
                message.removeClass('sent');
                message.addClass('delivered');
                message.find('.status').attr('title', BP_Messages['strings']['delivered']);
                updateMessagesStatus(message);
            });

            socket.on('seen', function (message_id, user_id) {
                var message = $('.bp-messages-wrap .list .messages-stack .content .messages-list li[data-id="' + message_id + '"]');
                message.removeClass('delivered sent');
                message.addClass('seen');
                message.find('.status').attr('title', BP_Messages['strings']['seen']);
                updateMessagesStatus(message);
            });
        }

        /**
         * Writing notifications
         */
        var writers = {};

        socket.on('writing', function (writing) {
            if (typeof writing == 'object') {
                $.each(writing, function (thread_id) {
                    if( typeof writers[thread_id] === 'undefined') writers[thread_id] = {};
                    var usersDiv  = $('.bp-messages-wrap .thread[data-id="' + thread_id + '"][data-users-json]');

                    if( usersDiv.length > 0 ) {
                        var usersJson = usersDiv.attr('data-users-json');
                        var participants = $.parseJSON(atob(usersJson));
                        if (typeof participants === 'object') {
                            if( typeof participants[this] !== 'undefined' ) {
                                writers[thread_id][participants[this]['name']] = Date.now();
                            }
                        }
                    }
                });

                updateWriting();
            }
        });

        function updateWriting(){
            $.each(writers, function(thread_id, typers){
                if( Object.keys(typers).length > 0 ) {
                    updateWritingPosition();

                    var usernames = [];
                    $.each(typers, function(username, timestamp){
                        usernames.push( username );
                    });

                    if( usernames.length > 0 ){
                        var wrap = $('.bp-messages-wrap .thread[data-id="' + thread_id + '"]').parents(".bp-messages-wrap");
                        if (wrap.hasClass('bp-better-messages-mini')) {
                            var writing = wrap.find('.chat[data-thread="' + thread_id + '"] span.writing[data-thread-id="' + thread_id + '"]');
                        } else {
                            var writing = wrap.find('span.writing[data-thread-id="' + thread_id + '"]');
                        }

                        writing.attr('data-time', Date.now());
                        writing.addClass('shown');
                        writing.html(usernames.join(', ') + ' ' + BP_Messages['strings']['writing']);
                        writing.show();
                    }
                }
            });

            $.each(writers, function(thread_id){
                var threadDiv = $(threadsSelector + '[data-id="' + thread_id + '"]');
                if( threadDiv.length > 0 ){
                    var p = threadDiv.find('.info p');
                    var reserved = p.html();
                    if( typeof p.attr('writing-reserved') === 'undefined' ) {
                        p.attr('writing-reserved', reserved);
                    }

                    p.attr('writing-time', Date.now());
                    threadDiv.addClass('bpbm-writing');
                    p.html('<span class="bpbm-typing">' + BP_Messages['strings']['writing'] + '</span>');
                }
            });
        }

        setInterval(clearWriting, 1000);

        function clearWriting() {
            var writing = $('span.writing.shown');

            var now = Date.now();
            if( Object.keys(writers) > 0 ) {
                $.each(writers, function (thread_id, typers) {
                    if (Object.keys(typers).length > 0) {
                        
                        $.each(typers, function (username, timestamp) {
                            if(now - timestamp > 5000){
                                delete writers[ thread_id ][ username ];
                            }
                        });
                    }
                });
            }


            if(writing.length > 0) {
                writing.each(function () {
                    var time = parseInt($(this).attr('data-time'));
                    if ((time + 3000) < Date.now()) $(this).hide().removeClass('shown');
                });
            }

            var writingThreads = $(threadsSelector + '.bpbm-writing');
            if(writingThreads.length > 0) {
                writingThreads.each(function () {
                    var writingThread = $(this);
                    var thread_id = writingThread.attr('data-id');
                    var p = writingThread.find('.info p');
                    var time = parseInt(p.attr('writing-time'));
                    if ((time + 3000) < Date.now()) {
                        delete writers[ thread_id ];
                        var oldHtml = p.attr('writing-reserved');
                        p.removeAttr('writing-reserved');
                        p.removeAttr('writing-time');
                        p.html(oldHtml);
                        writingThread.removeClass('bpbm-writing');

                    }
                });
            }
        }

        var writing = {};

        $(document).on('keyup touchend', '.bp-messages-wrap .reply .bp-emojionearea-editor', function (event) {
            //event.stopImmediatePropagation();
            var wrap = $(this).closest('.bp-messages-wrap');

            var thread_id = wrap.attr('data-thread-id');

            if( ! thread_id ) {
                thread_id = wrap.find('.thread[data-id]').data('id');
            }

            if(typeof writing[thread_id] === 'undefined') writing[thread_id] = 0;

            if (event.which <= 90 && event.which >= 48) {
                ifvisible.focus();

                if (writing[thread_id] === 0 || ( writing[thread_id] + 1000 ) < Date.now()) {
                    writing[thread_id] = Date.now();
                    socket.emit('writing', thread_id, '');
                }
            }
        });

        $(document).on('pointermove', '.bp-messages-wrap .reply', function (event) {
            event.stopImmediatePropagation();
        });

        $(document).on('pointerover', '.bp-messages-wrap .reply', function (event) {
            event.stopImmediatePropagation();
        });

        $(document).on('keyup touchend', '.bp-messages-wrap .reply textarea', function (event) {
            //event.stopImmediatePropagation();
            var wrap = $(this).closest('.bp-messages-wrap');
            var thread_id = wrap.find('.thread[data-id]').data('id');
            if(typeof writing[thread_id] === 'undefined') writing[thread_id] = 0;

            if (event.which <= 90 && event.which >= 48) {
                if (writing[thread_id] === 0 || ( writing[thread_id] + 1000 ) < Date.now()) {
                    writing[thread_id] = Date.now();
                    socket.emit('writing', thread_id, wrap.find('.thread[data-users]').attr('data-users'));
                }
            }
        });


        if(BP_Messages['realtime'] == '1'){
            ifvisible.on("wakeup", wakeUp);
            $(document).on('bp-better-messages-mobile-open', wakeUp);

            function wakeUp() {
                var unreadMessages = $(
                    '.bp-messages-wrap:not(.bp-better-messages-mini) .list .messages-stack .content .messages-list li.unread:not(.fast),' +
                    '.bp-messages-wrap.bp-better-messages-mini .chat.open .list .messages-stack .content .messages-list li.unread:not(.fast)'
                );

                var messagesIds = [];
                var threadsIds = [];

                if( typeof thread !== "boolean" ){
                    threadsIds.push(thread);
                }

                unreadMessages.each(function () {
                    var message = $(this);
                    if (message.is(':visible')) {
                        var message_id = message.data('id');
                        var thread_id = message.data('thread');
                        var date = message.attr('data-time');
                        messagesIds.push(message_id);
                        threadsIds.push(thread_id);
                        message.removeClass('unread');
                    }

                });

                if (messagesIds.length > 0) {
                    socket.emit('seen', messagesIds);
                }

                threadsIds = unique(threadsIds);
                $.each(threadsIds, function (index, item) {
                    if (typeof item !== 'undefined') {
                        socket.emit('threadOpen', item);
                    }
                });
            }
        }


    }
    /* </fs_premium_only> */

    function unique(list) {
        var result = [];
        $.each(list, function(i, e) {
            if ($.inArray(e, result) === -1) result.push(e);
        });
        return result;
    }

    /* <fs_premium_only> */
    function updateGroupCallStatus(thread_id){
        var currentThread = BPBMJQ('.bp-messages-wrap[data-thread-id="' + thread_id + '"]');
        if ( currentThread.find('.chat-header .group-call').length > 0 ){
            socket.emit('groupCallStatus', thread_id, function ( count ) {
                var callBanner = currentThread.find('.bpbm-group-call-in-progress');
                callBanner.find('.bpbm-group-call-participant-count').text( count );
                if( count > 0 ){
                    callBanner.slideDown();
                } else {
                    callBanner.slideUp();
                }
            });
        }
    }
    /* </fs_premium_only> */

    function updateMessagesStatus( li ){
        /* <fs_premium_only> */
        if( BP_Messages['messagesStatus'] === '1' ) {
            var li = $(li);

            if (li.hasClass('my')) {
                var status = li.find('.status');
                if (li.hasClass('seen')) {
                    status.html(status_icons['seen']);
                } else if (li.hasClass('delivered')) {
                    status.html(status_icons['delivered']);
                } else {
                    status.html(status_icons['sent']);
                }
            }

            initTooltips(li);
        }
        /* </fs_premium_only> */
    }


    jQuery(document).on('bp-better-messages-reinit', function (event) {
         reInit();
    });

    /**
     * Function to determine where we now and what we need to do
     */
    function reInit() {
        thread = false;
        threads = false;
        reIniting = true;
        clearTimeout(checkerTimer);

        // Only initialize new media elements.

        /*
        if( typeof $.fn.mediaelementplayer === 'function') {
            $( '.bp-messages-wrap .wp-audio-shortcode, .bp-messages-wrap .wp-video-shortcode' )
                .not( '.mejs-container' )
                .filter(function () {
                    return ! $( this ).parent().hasClass( '.mejs-mediaelement' );
                }).mediaelementplayer();
        }*/

        if( BP_Messages.realtime !== '1' ) {
            BPBMUpdateUnreadCount(BP_Messages.total_unread);
        }

        document.dispatchEvent(new BPBMEvent('bp-better-messages-reinit-start'));

        updateOpenThreads();

        onlineInit();

        if ($(".bp-messages-wrap:not(.bp-better-messages-mini,.bp-better-messages-list) .thread.scroller[data-users-json]").length > 0) {
            thread = $(".bp-messages-wrap:not(.bp-better-messages-mini,.bp-better-messages-list) .thread.scroller[data-users-json]").attr('data-id');
        } else if ($(".bp-messages-wrap:not(.bp-better-messages-mini,.bp-better-messages-list,#bp-better-messages-mini-mobile-container) .threads-list").length > 0) {
            threads = true;
        }

        if (thread) {
            checkerTimer = setTimeout(refreshThread, BP_Messages.threadRefresh);
        } else {
            checkerTimer = setTimeout(refreshSite, BP_Messages.siteRefresh);
        }

        /* <fs_premium_only> */
        if(BP_Messages['miniChats'] == '1') {
            $.each(miniChats, function (index) {
                if (index !== thread) {
                    openMiniChat(index, this);
                } else {
                    $('.bp-messages-wrap.bp-better-messages-mini .chats .chat[data-thread="' + thread + '"]').remove();
                }
            });
        }

        if(miniMessages !== false){
            $('.bp-better-messages-list').addClass('bp-better-messages-list-open');
            $('.bp-better-messages-list .tabs > div[data-tab="' + miniMessages + '"]').addClass('active');
            $('.bp-better-messages-list .tabs-content .' + miniMessages).addClass('active');
            $('.bp-better-messages-list .tabs > div[data-tab="bpbm-close"]').show();
        } else {
            $('.bp-better-messages-list').removeClass('bp-better-messages-list-open');
            $('.bp-better-messages-list .tabs > div[data-tab="bpbm-close"]').hide();
        }
        /* </fs_premium_only> */

        var direction = 'ltr';
        if( isRtl ) direction = 'rtl';

        var isEmojiEnabledOnMobile = BP_Messages['mobileEmojiEnable'] === '1';

        if( isEmojiEnabledOnMobile || ( ! isMobile && ! $('body').hasClass('bp-messages-mobile') ) ) {
            var selector = ".bp-messages-wrap .reply .message textarea, " +
                ".bp-messages-wrap .new-message #message-input, " +
                ".bp-messages-wrap .bulk-message #message-input";

            initializeEmojiArea(selector);
        } else {
            var selector = ".bp-better-messages-mini .chats .chat .reply .message textarea";

            initializeEmojiArea(selector);

            $.fn.BPBMloadEmojione(123);
            makeHeightBeautiful();
        }

        function initializeEmojiArea(selector){
            var emojioneareas = $(selector).BPemojioneArea({
                tones: true,
                tonesStyle: 'bullet',
                saveEmojisAs : "unicode",
                autocomplete: false,
                stayFocused: false,
                attributes: {
                    dir: direction
                }
            });

            emojioneareas.each(function(){
                var emojionearea = $(this);

                if( typeof emojionearea[0] !== 'undefined' ) {
                    emojionearea.closest('form').addClass('bp-emoji-enabled');

                    var areaLoaded = false;

                    try {
                        emojionearea[0].BPemojioneArea.on("onLoad", function () {
                            afterAreaLoaded();
                        });
                    } catch (e){}

                    setTimeout(afterAreaLoaded, 333);

                    function afterAreaLoaded(){
                        if( areaLoaded === true ) {
                            return false;
                        }

                        var areaExists = emojionearea.next('.bp-emojionearea').length > 0;

                        if( areaExists ) {
                            areaLoaded = true;
                            makeHeightBeautiful();

                            var opts = {
                                toolbar: {
                                    allowMultiParagraphSelection: false,
                                    buttons: ['bold', 'italic', 'underline', 'strikethrough', 'subscript', 'superscript', 'removeFormat'],
                                    diffLeft: 0,
                                    diffTop: -10,
                                    firstButtonClass: 'medium-editor-button-first',
                                    lastButtonClass: 'medium-editor-button-last',
                                    relativeContainer: null,
                                    standardizeSelectionStart: false,
                                    static: false,
                                    align: 'center',
                                    sticky: false,
                                    updateOnEmptySelection: true,
                                },
                                placeholder: false,
                                imageDragging: false
                            };

                            var media_editor = new BPBM_MediumEditor(document.querySelectorAll('.bp-emojionearea-editor'), opts);

                            media_editor.subscribe('editableInput', function( data, editable ){
                                var element = $(editable);

                                if( ! element.hasClass('bpbm-interacted') ){
                                    setTimeout(function (){
                                        element.addClass('bpbm-interacted');
                                    }, 100);
                                }
                            });

                            media_editor.subscribe('editablePaste', function ( data, editable ){
                                var editor = $( editable );
                                var reply  = editor.closest('.reply');
                                if( ! reply.find('form > .message').hasClass('file-uploader-enabled') ) return;
                                var files = toArray(event.clipboardData.items);

                                var filesToUpload = [];

                                files.forEach(function (file) {
                                    if (file.kind !== 'file') return;

                                    var blob = file.getAsFile();
                                    if ( ! blob ) {
                                        return;
                                    }

                                    filesToUpload.push({
                                        name: file.name,
                                        type: file.type,
                                        data: blob
                                    });
                                });

                                if( filesToUpload.length > 0 ){
                                    var thread_id = reply.find('input[name="thread_id"]').val();

                                    reply.find('.upload-btn').click();

                                    var uppy = $('body > .uppy.uppy-thread-' + thread_id);
                                    if( uppy.length > 0 ) {
                                        uppy = uppy[0].uppy;
                                        filesToUpload.forEach(function (file) {
                                            var args = {
                                                source: uppy.id,
                                                type: file.type,
                                                data: file.data
                                            };

                                            if( typeof file.name !== 'undefined' && file.name  !== 'undefined' ) {
                                                args['name'] = file.name;
                                            } else {
                                                args['name'] = '';
                                            }

                                            uppy.addFile(args).catch(function () {
                                                // Ignore
                                            });
                                        });
                                    }
                                }
                            });

                            $(emojionearea).html('<p></p>');
                        } else {
                            setTimeout(afterAreaLoaded, 333);
                        }
                    }
                }
            });
        }

        if( typeof $.fn.BPBMoverlayScrollbars === 'function' ) {

            $(document).on("bp-better-messages-init-scrollers", function(){
                BPBMJQ('.bp-better-messages-list .tabs-content .friends .scroller,.bp-better-messages-list .tabs-content .bpbm-groups .scroller,.scroller.search, .scroller.starred').BPBMoverlayScrollbars({
                    'sizeAutoCapable': false,
                    overflowBehavior: {
                        x: 'hidden'
                    },
                });

                BPBMJQ('.bpbm-users-avatars-list').BPBMoverlayScrollbars({
                    'sizeAutoCapable': true,
                    overflowBehavior: {
                        x: 'scroll',
                        y: 'hidden'
                    },
                    scrollbars: {
                        clickScrolling: true,
                        autoHide: 'leave'
                    }
                });

                BPBMJQ('.bpbm-stickers-selector .bpbm-stickers-head .bpbm-stickers-tabs').BPBMoverlayScrollbars({
                    'sizeAutoCapable': false,
                    overflowBehavior : {
                        y: 'hidden'
                    }
                });


                var scrolling = false;
                var sizeAutoCapable = false;
                BPBMJQ('.scroller.thread').BPBMoverlayScrollbars({
                    'sizeAutoCapable': sizeAutoCapable,
                    'autoUpdate' : true,
                    overflowBehavior: {
                        x: 'hidden'
                    },
                    callbacks : {
                        onInitialized: function(){
                            var elements   = this.getElements();
                            var position   = this.scroll();
                            var height     = position.max.y;

                            var message_to = false;

                            if (getParameterByName('message_id').length > 0) {
                                var message_id = getParameterByName('message_id');
                                var message = $(elements.content).find( ".messages-list li[data-id='" + message_id + "']");

                                if (message.length > 0) {
                                    message_to = message;
                                }
                            }

                            if( message_to !== false ){
                                BPBMJQ(this.getElements().host).addClass('user-scrolled');
                                this.scroll({ el : message_to, scroll : "ifneeded", margin : 20 });
                            } else if( BPBMJQ(elements.host).is(':visible') && height === 0 ){
                                loadMoreMessages(this, true);
                            } else {
                                this.scrollStop();
                                this.scroll({y: '100%'});
                            }
                        },
                        onScroll : function( arg1 ){
                            var scroller  = this;
                            var position  = this.scroll();
                            var scroll    = position.position.y;
                            var height    = position.max.y;

                            if( height === 0 ){
                                loadMoreMessages(this, true);
                                BPBMJQ(scroller.getElements().host).addClass('user-scrolled');
                            } else if( scroll === 0 ) {
                                loadMoreMessages(this);
                                BPBMJQ(scroller.getElements().host).addClass('user-scrolled');
                            } else if( scroll >= height ){
                                setTimeout(function(){
                                    scroll    = position.position.y;
                                    height    = position.max.y;
                                    if( scroll >= height ) {
                                        BPBMJQ(scroller.getElements().host).removeClass('user-scrolled');
                                    }
                                }, 300);
                            }
                        },
                        onContentSizeChanged : function( arg1 ){
                            var elements    = this.getElements();
                            var position    = this.scroll();
                            var height      = position.max.y;
                            var scroll      = position.position.y;
                            var host        = BPBMJQ(elements.host);
                            var content     = BPBMJQ(elements.content);
                            var last        = content.find('.list .messages-stack:last .content .messages-list li:last')
                            var last_height = last.outerHeight();
                            if( last_height < 100 ) last_height = 100;
                            var _this = this;

                            if( ! host.hasClass('user-scrolled') || ( height - scroll ) < last_height + 50 ){
                                if( ! isTapped ) {
                                    scrolling = true;
                                    _this.scrollStop();
                                    _this.scroll({y: '100%'}, 100, undefined, function(){
                                        scrolling = false;
                                    });
                                }
                            }

                            setTimeout(function(){
                                if( ! host.hasClass('user-scrolled') ){
                                    if( ! isTapped ) {
                                        scrolling = true;
                                        _this.scrollStop();
                                        _this.scroll({y: '100%'}, 100, undefined, function(){
                                            scrolling = false;
                                        });
                                    }
                                }
                            }, 100);
                        },
                        onHostSizeChanged: function (){
                            var scroller  = this;
                            var position  = this.scroll();
                            var scroll    = position.position.y;
                            var height    = position.max.y;

                            if( ! BPBMJQ(scroller.getElements().host).hasClass('user-scrolled') && ! $('body').hasClass('bpbm-os-dragging') ){
                                this.scrollStop();
                                this.scroll({y: '100%'}, 0);
                            } else if( scroll >= height ){
                                setTimeout(function(){
                                    scroll    = position.position.y;
                                    height    = position.max.y;
                                    if( scroll >= height ) {
                                        BPBMJQ(scroller.getElements().host).removeClass('user-scrolled');
                                    }
                                }, 300);
                            }
                        }
                    }
                });


                BPBMJQ('.scroller.threads-list-wrapper').BPBMoverlayScrollbars({
                    'sizeAutoCapable': false,
                    overflowBehavior: {
                        x: 'hidden'
                    },
                    callbacks : {
                        onInitialized: function(){},
                        onScroll : function( arg1 ){
                            var elements  = this.getElements();
                            var position  = this.scroll();
                            var scroll    = position.position.y;
                            var height    = position.max.y;
                            var host      = BPBMJQ(elements.host);

                            if(height - scroll <= 100 ) {
                                loadMoreThreads(host);
                            }
                        },
                        onContentSizeChanged : function( arg1 ){
                        }
                    }
                });
            });

            $(document).trigger("bp-better-messages-init-scrollers");
        }

        BPBMJQ('.scrollbar-inner').on('touchstart click mousewheel DOMMouseScroll', function( event ){
            var clicked =  BPBMJQ( event.target );

            if( clicked.closest('.bpbm-reply').length === 0 ) {
                BPBMJQ(this).addClass('user-scrolled');
            }
        });

        initImagesPopup();

        if(BP_Messages['realtime'] == '1') {

            // Load Statuses
            var messages_ids = [];
            var threadsIds   = [];
            $(  '.bp-messages-wrap:not(.bp-better-messages-mini,.bp-better-messages-list) .list .messages-stack .content .messages-list li:not(.seen), ' +
                '.bp-messages-wrap.bp-better-messages-mini .chat.open .list .messages-stack .content .messages-list li:not(.seen)'
            ).each(function () {
                var id = $(this).data('id');
                var thread_id = $(this).data('thread');
                messages_ids.push(id);
                threadsIds.push(thread_id);
            });

            if(thread) {
                socket.emit('threadOpen', thread);
                updateGroupCallStatus( thread );
            }


            if( BP_Messages['messagesStatus'] === '1') {
                if( messages_ids.length > 0 ) {
                    socket.emit('getStatuses', messages_ids, function (statuses) {
                        var requestedIds = {};
                        $.each(messages_ids, function () {
                            requestedIds[this] = true;
                        });

                        $.each(statuses, function (index) {
                            delete requestedIds[index];
                            var message = $('.bp-messages-wrap .list .messages-stack .content .messages-list li[data-id="' + index + '"]');
                            message.removeClass('sent delivered seen');
                            if (!message.hasClass('my') && !message.hasClass('fast')) {
                                if (this.toString() !== 'seen') {
                                    socket.emit('seen', [index]);
                                }
                            } else {
                                var status = 'sent';
                                $.each(this, function () {
                                    if (status == 'seen') return false;
                                    if (this == 'delivered' && status != 'seen') status = 'delivered';
                                    if (this == 'seen') status = 'seen';
                                });

                                message.addClass(status);
                                var statusTitle = '';
                                switch (status) {
                                    case 'sent':
                                        statusTitle = BP_Messages['strings']['sent'];
                                        break;
                                    case 'delivered':
                                        statusTitle = BP_Messages['strings']['delivered'];
                                        break;
                                    case 'seen':
                                        statusTitle = BP_Messages['strings']['seen'];
                                        break;
                                }

                                message.find('.status').attr('title', statusTitle);
                                updateMessagesStatus(message);
                            }
                        });

                        $.each(requestedIds, function (message_id) {
                            var message = $('.bp-messages-wrap .list .messages-stack .content .messages-list li[data-id="' + message_id + '"]');
                            message.removeClass('sent delivered seen');
                            message.addClass('seen');
                            message.find('.status').attr('title', BP_Messages['strings']['seen']);
                            updateMessagesStatus(message);
                        });
                    });
                }
            }

            threadsIds = unique(threadsIds);
            $.each(threadsIds, function (index, item) {
                if(typeof item !== 'undefined'){
                    socket.emit('threadOpen', item);
                }
            });

            socket.emit('requestUnread');
        }


        function loadMoreThreads(element, loadUntilScroll) {
            if( typeof loadUntilScroll === 'undefined' ) loadUntilScroll = false;
            var wrapper = $( element );
            if( wrapper.hasClass('loading-more') || wrapper.hasClass('all-loaded') ) return false;

            wrapper.addClass('loading-more');
            wrapper.find('.loading-messages').show();

            var loadedThreads = [];
            var loader = wrapper.find('.loading-messages');

            wrapper.find('.threads-list > .thread').each(function () {
                loadedThreads.push( $(this).data('id') );
            });

            var args = {
                'action'         : 'bp_messages_get_more_threads',
                'loaded_threads' : loadedThreads,
                'user_id'        : BP_Messages['displayed_user_id']
            };

            if( wrapper.closest('.bp-messages-wrap').hasClass('bp-better-messages-list') ){
                args.user_id = BP_Messages['user_id']
            }

            $.post(
                BP_Messages.ajaxUrl,
                args
                , function (html) {
                    $(html).insertBefore( loader );
                    wrapper.removeClass('loading-more');
                    wrapper.find('.loading-messages').hide();

                    if( html.trim() === '' ){
                        wrapper.addClass('all-loaded');
                    } else {
                        if( loadUntilScroll && Math.ceil(element.get(0).scrollHeight) <= Math.ceil(element.innerHeight()) ) {
                            loadMoreThreads(element, true);
                        }
                    }

                }
            );

        }


        makeHeightBeautiful();

        $( window ).on('resize', function() {
            makeHeightBeautiful();
        });

        if ($('.bp-messages-wrap #send-to:not(.ready)').length > 0) {
            var cache = [];

            var sentTo = new Taggle('send-to', {
                placeholder: '',
                tabIndex: 2,
                hiddenInputName: 'recipients[]'
            });
            var container = sentTo.getContainer();
            var input     = sentTo.getInput();

            var to = $('input[name="to"]');

            if (to.length > 0) {
                $(to).each(function () {
                    var img   = $(this).data('img');
                    var label =  $(this).data('label');
                    sentTo.add($(this).val());
                    $(container).find('.taggle_sizer').text('');
                    $('#send-to li.taggle:last .taggle_text').html('<span class="bpbm-avatar"><img src="' + img + '" class="avatar photo" width="50" height="50"></span><span class="bpbm-name">' + label + '</span>');
                    $(this).remove();
                });

                $('#send-to').removeClass('active');
                $('#send-to input').css('width', '10px');
            }

            $(input).on( 'blur', function( event ) {
                var placeholder = $(container).find('.taggle_sizer').text();
                sentTo.add( placeholder );
            });

            if(BP_Messages['disableUsersSearch'] === '0') {

                $('.bpbm-users-avatars-list .bpbm-users-avatars-list-item').click(function(event){
                    event.preventDefault();

                    var el = $(this);
                    var name  = el.find('.bpbm-users-avatars-list-item-name').text();
                    var image = el.find('.bpbm-users-avatars-list-item-avatar img').parent().html();
                    var nicename = el.attr('data-nicename');
                    sentTo.add(nicename);
                    $(container).find('.taggle_sizer').text('');
                    $('#send-to li.taggle:last .taggle_text').html('<span class="bpbm-avatar">' + image + '</span><span class="bpbm-name">' + name + '</span>');
                });

                $(input).autocomplete({
                    source: function (request, response) {
                        var term = request.term;
                        if (term in cache) {
                            response(cache[term]);
                            return;
                        }

                        $.getJSON(BP_Messages.ajaxUrl + "?q=" + term + "&limit=10&action=bp_messages_autocomplete&cookie=" + getAutocompleteCookies(), request, function (data, status, xhr) {
                            cache[term] = data;
                            response(data);
                        });
                    },
                    minLength: 2,
                    appendTo: container,
                    position: {at: "left bottom", of: container},
                    open: function (event, ui) {
                        var autocomplete = $(".bp-messages-wrap #send-to .ui-autocomplete");
                        var oldTop = parseInt(autocomplete.css('top'));
                        var newTop = oldTop - 3;
                        autocomplete.css("top", newTop);
                    },
                    select: function (event, data) {
                        event.preventDefault();
                        //Add the tag if user clicks
                        if (event.which === 1) {
                            sentTo.add(data.item.value);
                            $(container).find('.taggle_sizer').text('');
                            $('#send-to li.taggle:last .taggle_text').html('<span class="bpbm-avatar">' + data.item.img + '</span><span class="bpbm-name">' + data.item.label + '</span>');
                        }
                    },
                    response: function( event, data ){
                        $('.ui-helper-hidden-accessible').hide()
                    }
                }).autocomplete( "instance" )._renderItem = function( ul, item ) {
                    return $( "<li>" )
                        .attr( "data-value", item.value )
                        .attr( "data-label", item.label )
                        .append( '<span class="bpbm-avatar">' + item.img + '</span><span class="bpbm-name">' + item.label + '</span>' )
                        .appendTo( ul );
                };
            }

            $('#send-to').addClass('ready');
        }

        if( typeof bpMessagesWrap !== 'undefined' ) {
            bpMessagesWrap.find('.bp-messages-mobile-tap').css('line-height', bpMessagesWrap.height() + 'px');
        }

        $('.bp-messages-side-threads .threads-list .thread.bp-messages-active-thread').removeClass('bp-messages-active-thread');
        if( thread ){
            $('.bp-messages-side-threads .threads-list .thread[data-id="' + thread + '"]').addClass('bp-messages-active-thread');
        }

        var outgoingItems = {};
        var incomingItems = {};
        var menuEvents = {
            show : function(options){
                options.$trigger.closest('li').addClass('selected');
            },
            hide : function(options){
                options.$trigger.closest('li').removeClass('selected');
            }
        };

        outgoingItems['copy']  = {name: BP_Messages['strings']['copy_text'], icon: "fas fa-copy", callback: function(key, opt){
                var trigger = opt.$trigger;

                var reply = trigger.find('.bpbm-replied-message-reply');
                if( reply.length > 0 ){
                    copyToClipboard(reply.text());
                } else {
                    copyToClipboard(trigger.text());
                }
            }};
        incomingItems['copy']  = {name: BP_Messages['strings']['copy_text'], icon: "fas fa-copy", callback: function(key, opt){
                var trigger = opt.$trigger;

                var reply = trigger.find('.bpbm-replied-message-reply');
                if( reply.length > 0 ){
                    copyToClipboard(reply.text());
                } else {
                    copyToClipboard(trigger.text());
                }

            }};

        if( BP_Messages['allowEditMessages'] === '1' ) {
            outgoingItems['edit'] = {
                name: BP_Messages['strings']['edit'],
                icon: "fas fa-pen",
                callback: function (key, opt) {
                    var trigger = opt.$trigger;
                    var nonce = BP_Messages['userNonce'];
                    var message = trigger.closest('li');
                    var stack = message.closest('.messages-stack');
                    var wrap = stack.closest('.bp-messages-threads-wrapper');
                    var message_id = message.attr('data-id');

                    var content = '';
                    var html_content = '';
                    var reply = message.find('.bpbm-replied-message-reply');
                    if (reply.length > 0) {
                        content += reply.text()
                    } else {
                        content += message.find('.message-content').text()
                    }

                    var descs = message.find('.message-content > [data-desc]');
                    if (descs.length > 0) {
                        descs.each(function () {
                            var _desc = $(this).attr('data-desc');
                            if (typeof _desc !== 'undefined') {
                                html_content += '<span class="bpbm-preview-desc">' + atob(_desc) + '</span>';
                            }
                        });
                    }


                    var html = '<div class="bpbm-preview-message bpbm-edit-message" style="display:none" data-message-id="' + message_id + '">' +
                        '<div class="bpbm-preview-message-cancel"><i class="far fa-times-circle"></i></div>' +
                        '<div class="bpbm-preview-message-content">' +
                        '<span class="bpbm-preview-message-name">' + BP_Messages['strings']['edit_message'] + '</span>' +
                        '<div class="bpbm-preview-message-text"></div>' +
                        '</div>' +
                        '</div>';


                    var previewMessage = wrap.find('.bpbm-preview-message');
                    if( previewMessage.length > 0 ){
                        previewMessage = previewMessage.replaceWith(html);
                        previewMessage = wrap.find('.bpbm-preview-message')
                        previewMessage.show();
                        updateWritingPosition();
                    } else {
                        previewMessage = $(html).insertBefore(wrap.find('.reply'));
                        previewMessage.slideDown(100, function (){
                            updateWritingPosition();
                        });
                    }

                    previewMessage.find('.bpbm-preview-message-text').text(content);
                    previewMessage.find('.bpbm-preview-message-text').append(html_content);

                    previewMessage.find('.bpbm-gifs-icon').html(icons.gif);

                    $.post(BP_Messages['ajaxUrl'], {
                        'action': 'bp_messages_get_edit_message',
                        'message_id': message_id,
                        '_wpnonce': nonce
                    }, function (response) {
                        if( typeof response.errors !== 'undefined' ){
                            BBPMShowError(response.errors[0]);
                            previewMessage.find('.bpbm-preview-message-cancel').click();
                        } else {
                            var emojieditor = wrap.find('.bp-emojionearea-editor');
                            if (emojieditor.length > 0) {
                                emojieditor.html(emojione.toImage(response));
                            } else {
                                wrap.find('.reply .message textarea').val(response);
                            }
                        }
                    });
                },
                visible: function(key, opt){
                    if( opt.$trigger.closest('.bp-messages-threads-wrapper').find('.reply').length > 0 )
                    {
                        return true;
                    } else {
                        return false;
                    }
                }
            };
        }

        var deleteButton = {
            name: BP_Messages['strings']['delete'],
            icon: "fas fa-trash",
            callback: function (key, opt) {
                var trigger = opt.$trigger;
                var nonce = BP_Messages['userNonce'];
                var string = BP_Messages['strings']['confirm_delete'];
                var message = trigger.closest('li');

                var confirmDelete = confirm(string);

                if (confirmDelete) {
                    var messages_ids = [
                        message.attr('data-id')
                    ];

                    var thread = message.attr('data-thread');

                    $.post(BP_Messages['ajaxUrl'], {
                        'action': 'bp_messages_delete_message',
                        'thread_id': thread,
                        'messages_ids': messages_ids,
                        '_wpnonce': nonce
                    }, function (response) {
                        if (response.result) {
                            BBPMNotice(response.message);
                            deleteMessage(messages_ids);
                        } else {
                            BBPMShowError(response.errors[0]);
                        }
                    });
                }
            },
            visible: function(key, opt){


                if( opt.$trigger.closest('.bp-messages-threads-wrapper').find('.reply').length > 0 )
                {

                    if( BP_Messages['allowDeleteMessages'] === '1' ) {
                        if (opt.$trigger.closest('.messages-stack').hasClass('outgoing')) {
                            return true;
                        }
                    }

                    if( opt.$trigger.closest('.list').hasClass('can-moderate') ){
                        return true;
                    }

                    return false;
                } else {
                    return false;
                }
            }
        };


        if( BP_Messages['enableReplies'] === '1') {
            incomingItems['reply'] = {
                name: BP_Messages['strings']['reply'],
                icon: "fas fa-reply",
                callback: function (key, opt) {
                    opt.$trigger.closest('li').find('.bpbm-reply').click();
                },
                visible: function(key, opt){
                    if( opt.$trigger.closest('.bp-messages-threads-wrapper').find('.reply').length > 0 )
                    {
                        return true;
                    } else {
                        return false;
                    }
                }
            };
        }

        outgoingItems['delete'] = deleteButton;
        incomingItems['delete'] = deleteButton;

        if( BP_Messages['user_id'] !== '0' ) {

            $.BPBMcontextMenu({
                // define which elements trigger this menu
                selector: outgoingSelector,
                events: menuEvents,
                items: outgoingItems,
                autoHide: false,
                zIndex: 10,
                position: function (opt, x, y) {
                    var maxLeft = window.innerWidth - opt.$menu.width() - 100;
                    if (x > maxLeft) x = maxLeft;

                    opt.$menu.css({left: x, top: y});
                }
            });

            $.BPBMcontextMenu({
                // define which elements trigger this menu
                selector: incomingSelector,
                events: menuEvents,
                items: incomingItems,
                autoHide: false,
                zIndex: 10,
                position: function (opt, x, y) {
                    var maxLeft = window.innerWidth - opt.$menu.width() - 100;
                    if (x > maxLeft) x = maxLeft;

                    opt.$menu.css({left: x, top: y});
                }
            });

            var threadsMenuItems = {};

            threadsMenuItems['open'] = {
                name: BP_Messages['strings']['open'],
                icon: "fas fa-external-link-square-alt",
                callback: function (key, opt) {
                    opt.$trigger.closest('.thread').click();
                }
            };

            threadsMenuItems['delete'] = {
                name: BP_Messages['strings']['delete'],
                icon: "fas fa-trash",
                callback: function (key, opt) {
                    opt.$trigger.closest('.thread').find('span.delete').click();
                },
                visible: function (key, opt) {
                    if (opt.$trigger.closest('.thread').find('span.delete').length > 0) {
                        return true;
                    } else {
                        return false;
                    }
                }
            };


            $.BPBMcontextMenu({
                // define which elements trigger this menu
                selector: threadsSelector,
                events: menuEvents,
                items: threadsMenuItems,
                autoHide: false,
                zIndex: 10,
                position: function (opt, x, y) {
                    var maxLeft = window.innerWidth - opt.$menu.width() - 100;
                    if (x > maxLeft) x = maxLeft;

                    opt.$menu.css({left: x, top: y});
                }
            });

            initMobileSwipes();
            /**
             * JetPack Lazy Load
             */

            //document.body.dispatchEvent(new BPBMEvent('post-load'));

            /* <fs_premium_only> */
            if( BP_Messages['enablePushNotifications'] === '1' ) {
                if ($('.BPBMpushNotifications').length > 0) {
                    BPBMcheckPushWorkerStatus();
                }
            } else {
                BPBMJQ('.BPBMpushNotifications').hide();
            }
            /* </fs_premium_only> */

        }

        /* <fs_premium_only> */
        if( BP_Messages['messagesStatus'] === '1' ) {
            $('.bp-messages-wrap .list .messages-stack .content .messages-list li').each(function () {
                updateMessagesStatus(this);
            });
        }
        /* </fs_premium_only> */

        calculateTitle(bpMessagesWrap);

        $('.bpbm-gifs-icon').html(icons.gif);
        addIframeClasses();

        /* <fs_premium_only> */
        BPBMAutoStartCall();
        /* </fs_premium_only> */

        initTooltips();

        if( isMobile && typeof bpMessagesWrap !== 'undefined' ) {
            bpMessagesWrap.find('.bpbm-chat-content').css('max-height', 'calc( 100% - ' + bpMessagesWrap.find('.chat-header').outerHeight() + 'px )');
        }

        document.dispatchEvent(new BPBMEvent('bp-better-messages-reinit-end'));

        reIniting = false;
    }


    function initTooltips( wrap ){
        if (typeof wrap === 'undefined') wrap = BPBMJQ('.bp-messages-wrap');

        if( ! isMobile ) {
            wrap.find( '.bpbm-users-avatars-list-item[title], .status[title], .bpbm-reply[title], .chat-header [title], .chat-footer [title], .threads-list [title], .chats .chat .head .controls [title]').each(function () {
                var el = BPBMJQ(this);

                if (el.is('strong') || el.is('input') ) {

                } else {
                    if( typeof (el[0]._tippy) !== 'undefined' ){
                        el[0]._tippy.destroy();
                    }

                    bpbmtippy(el[0], {
                        placement: 'top',
                        content: el.attr('title'),
                        allowHTML: true,
                        arrow: false,
                        offset: [0, 5],
                        onShow: function(instance) {
                            var reference = BPBMJQ(instance.reference);
                            if( reference.is('.expandingButtons') && reference.hasClass('expandingButtonsOpen') ){
                                return false;
                            }
                        },
                    });

                    el[0].removeAttribute('title');
                }

            });
        }
    }

    function addIframeClasses(){
        $('.bp-messages-iframe-container').each(function(){
            var iframeContainer = $(this);
            var msgContent = iframeContainer.closest('.message-content');

            msgContent.addClass('has-iframe');
        });
    }

    function initMobileSwipes(){
        if( isMobile ){
            $(incomingSelector).BPBMswipe("destroy");
            $(incomingSelector).BPBMswipe({
                longTap : function(event, target) {
                    $(this).contextMenu({
                        x: event.changedTouches[0].screenX,
                        y: event.changedTouches[0].screenY,
                    });
                },
            });
            $(outgoingSelector).BPBMswipe("destroy");
            $(outgoingSelector).BPBMswipe({
                longTap : function(event, target) {
                    $(this).contextMenu({
                        x: event.changedTouches[0].screenX,
                        y: event.changedTouches[0].screenY,
                    });
                },
            });

            $(threadsSelector).BPBMswipe("destroy");
            $(threadsSelector).BPBMswipe({
                longTap : function(event, target) {
                    $(this).contextMenu({
                        x: event.changedTouches[0].screenX,
                        y: event.changedTouches[0].screenY,
                    });
                },
            });

        }
    }

    function copyToClipboard(text) {
        var $temp = $("<input>");
        $("body").append($temp);
        $temp.val(text).select();
        document.execCommand("copy");
        $temp.remove();
    }

    /* <fs_premium_only> */
    var BPBMAutoStartCallStarted = false;

    function BPBMAutoStartCall(){
        if( BPBMAutoStartCallStarted ) {
            return false;
        }

        BPBMAutoStartCallStarted = true;

        BPBMAutoStartCallAction();
    }

    function BPBMScrollToCallContainer(container){
        var container = $(container);

        if ( isMobile ) {
            if( BP_Messages['autoFullScreen'] === '1' ) {
                openMobile(container);
            }
        } else {
            var offset = 80 + parseInt(BP_Messages['fixedHeaderHeight']);
            $('html, body').animate({
                scrollTop: container.offset().top - offset
            }, 500);
        }
    }

    function BPBMAutoStartCallAction(){
        if( typeof socket === 'undefined' ) return false;

        if( ! socket.connected ){
            setTimeout(BPBMAutoStartCallAction, 500);
        } else {
            var queryString = window.location.search;

            var urlParams = new URLSearchParams(queryString);
            var videoCallParam  = 'videoCall';
            var audioCallParam  = 'audioCall';
            var acceptCallParam = 'acceptCall';
            var scrollToParam   = 'scrollToContainer';
            var videoCall       = urlParams.get(videoCallParam);
            var audioCall       = urlParams.get(audioCallParam);
            var acceptCall      = urlParams.get(acceptCallParam);
            var scrollTo        = urlParams.get(scrollToParam);

            var container = $('.bp-messages-wrap.bp-messages-wrap-main');
            if (container.length > 0) {
                var cleanParams = false;
                if (typeof videoCall === 'string') {
                    container.find('.chat-header .video-call').click();
                    BPBMScrollToCallContainer(container);
                    cleanParams = true;
                } else if (typeof audioCall === 'string') {
                    container.find('.chat-header .audio-call').click();
                    BPBMScrollToCallContainer(container);
                    cleanParams = true;
                } else if (typeof acceptCall === 'string') {
                    BPBMScrollToCallContainer(container);
                    cleanParams = true;
                } else if (typeof scrollTo === 'string') {
                    BPBMScrollToCallContainer(container);
                    cleanParams = true;
                }

                if( cleanParams ){
                    urlParams.delete(videoCallParam);
                    urlParams.delete(audioCallParam);
                    urlParams.delete(acceptCallParam);
                    urlParams.delete(scrollToParam);
                    window.history.pushState("", "", '?' + urlParams.toString());
                }

            }

            setTimeout(function(){
                BPBMAutoStartCallStarted = false;
            }, 1000);
        }
    }
    /* </fs_premium_only> */

    function loadMoreMessages(scroller, loadUntilScroll) {
        if( typeof loadUntilScroll === 'undefined' ){
            loadUntilScroll = false;
        }

        var elements = scroller.getElements();
        var wrap = BPBMJQ(elements.host);

        if( wrap.hasClass('loadingAtTheMoment')
            || wrap.hasClass('allMessagesWasLoaded')
        ) return false;


        var thread_id = wrap.data('id');

        wrap.find('.loading-messages').show();
        wrap.addClass('loadingAtTheMoment');
        var last_message = wrap.find('.messages-stack:first-child .messages-list li:first-child');
        var last_message_id = last_message.attr('data-id');

        $.post(
            BP_Messages.ajaxUrl,
            {
                'action'     : 'bp_messages_thread_load_messages',
                'thread_id'  : thread_id,
                'message_id' : last_message_id
            }, function (data) {
                wrap.find('.loading-messages').hide();
                if(data.trim() === '') wrap.addClass('allMessagesWasLoaded');

                $(data).prependTo( wrap.find('.list') );
                wrap.addClass('hasLoadedMessages');


                scroller.scroll( { el: last_message.closest('.messages-stack'), margin : 15 } );

                reInit();
                wrap.removeClass('loadingAtTheMoment');


                if( loadUntilScroll ){
                    if( scroller.scroll().max.y === 0){
                        loadMoreMessages(scroller, true);
                    }
                }
            }
        );
    }

    function scrollBottom(target) {
        if(typeof target == 'undefined') target = '.bp-messages-wrap:not(.bp-better-messages-mini,.bp-better-messages-list)';
        if($(target + " .list").length == 0) return;

        var scroller = $(target + ' .scroller[data-id]');
        var thread_id = scroller.data('id');
        if(typeof loadingMore[thread_id] !== 'undefined') return false;

        var list = $(target + " .list");
        var scroll = list[0].offsetHeight;

        if (getParameterByName('message_id').length > 0) {
            var message_id = getParameterByName('message_id');
            var message = $(target + " .messages-list li[data-id='" + message_id + "']");

            if (message.length > 0) {
                scroll = message[0].offsetTop - message[0].offsetHeight - 100;
            }
        }

        var scrollWrapper = list.closest('.scroller');
        var userScrolled  = scrollWrapper.hasClass('user-scrolled');

        var currentScroll = scrollWrapper[0].scrollHeight - scrollWrapper.scrollTop() - scrollWrapper.height();
        //if(  scrollWrapper.scrollTop() === 0 ) currentScroll = 0;

        if(scroll < scrollWrapper.outerHeight()) return;
        if( ! userScrolled || (100 >= currentScroll)){
            var scrollbar = scroller.BPBMoverlayScrollbars();
            if(typeof scrollbar !== 'undefined'){
                scrollbar.update();
                scrollbar.scroll({y: '100%'});
            }
        }
    }

    /**
     * Check for new messages on all sites page
     */
    var refreshSiteRunning = false;
    function refreshSite() {
        clearInterval(checkerTimer);
        checkerTimer = setTimeout(refreshSite, BP_Messages.siteRefresh);

        if (BP_Messages['realtime'] == "1" || refreshSiteRunning) return;

        var last_check = readCookie('bp-messages-last-check');
        refreshSiteRunning = true;
        $.post(BP_Messages.ajaxUrl, {
            'action': 'bp_messages_check_new',
            'last_check': last_check
        }, function (response) {

            if (response.threads.length > 0) {
                $.each(response.threads, function () {
                    var message = this;

                    if(typeof message['avatar'] !== 'undefined' ) {
                        message['avatar'] = message['avatar'].replace("loading='lazy'", '').replace('loading="lazy"', '');
                    }

                    if (threads) {
                        updateThreads(message);
                    } else {
                        showMessage(message.thread_id, message['message'], message['name'], message['avatar']);
                    }
                });
            }

            BPBMUpdateUnreadCount(response.total_unread);

            refreshSiteRunning = false;
        });
    }

    /**
     * Check for new messages on open thread screen
     */
    var refreshThreadRunning = false;

    BPBMJQ(document).on('bp-better-messages-refresh-thread', function (event) {
        refreshThread();
    });

    function refreshThread() {
        if( BP_Messages['user_id'] === '0' ) return false;

        clearInterval(checkerTimer);
        checkerTimer = setTimeout(refreshThread, BP_Messages.threadRefresh);
        if (BP_Messages['realtime'] == "1" || refreshThreadRunning) return;

        var last_check = readCookie('bp-messages-last-check');
        var last_message = $('.messages-stack:last-child .messages-list li:last-child').attr('data-time');
        refreshThreadRunning = true;
        $.post(BP_Messages.ajaxUrl, {
            'action': 'bp_messages_thread_check_new',
            'last_check': last_check,
            'thread_id': thread,
            'last_message': last_message
        }, function (response) {
            $.each(response.messages, function () {
                if(typeof this['avatar'] === 'string' ) {
                    this['avatar'] = this['avatar'].replace("loading='lazy'", '').replace('loading="lazy"', '');
                }
                renderMessage(this);
            });

            $.each(response.threads, function () {
                if(typeof this['avatar'] === 'string' ) {
                    this['avatar'] = this['avatar'].replace("loading='lazy'", '').replace('loading="lazy"', '');
                }
                showMessage(this.thread_id, this['message'], this['name'], this['avatar']);
            });

            BPBMUpdateUnreadCount(response.total_unread);

            refreshThreadRunning = false;
        });
    }

    function updateOpenThreads() {
        if ( ! store.enabled )  return false;

        openThreads = store.get('bp-better-messages-open-threads') || {};

        if (thread !== false) {
            openThreads[thread] = Date.now();
        }

        $.each(openThreads, function (index) {
            if ((this + 2000) < Date.now()) delete openThreads[index];
        });

        store.set('bp-better-messages-open-threads', openThreads);
    }


    jQuery(document).on('bp-better-messages-ajax-refresh', function(event){
        var url       = event.originalEvent.detail.url;
        var container = event.originalEvent.detail.container;

        ajaxRefresh(url, container);
    });
    
    /**
     * Simple function to avoid page reloading
     *
     * @param url
     */
    function ajaxRefresh(url, container) {
        if( typeof container === 'undefined' ){
            var target = BPBMJQ(event.target);
            if( target.hasClass('bp-messages-wrap') ){
                container = target;
            } else {
                container = target.closest('.bp-messages-wrap');
            }
        }

        if( isInCall ){
            if ( confirm(BP_Messages['strings']['you_are_in_call']) === false ) {
                return false;
            } else {
                BPBMJQ(document).trigger('bpbm-end-call');
                BPBMJQ(document).trigger('bpbm-end-group-call');
            }
        }

        if( container.hasClass('bp-messages-wrap-main') && ! container.hasClass('bp-messages-group-thread') ){
            try {
                window.history.pushState("", "", url);
            } catch(e){}
        }

        showPreloader(container);

        var containerHeight = container.height();
        container.css('min-height', containerHeight);

        $(window).off( ".bp-messages" );


        var target_url = '';
        var question_added = false;

        if( typeof BP_Messages['ajaxUrl'].split('?')[1] !== 'undefined' ){
            question_added = true;
        }

        if( question_added ){
            target_url += '&';
        } else {
            question_added = true;
            target_url += '?';
        }

        if( typeof url.split('?')[1] !== 'undefined' ){
            target_url += url.split('?')[1] + '&action=bp_messages_load_via_ajax';
        } else {
            target_url += 'action=bp_messages_load_via_ajax';
        }

        var side_threads = container.find('.bp-messages-side-threads');
        var ajax_url = BP_Messages['ajaxUrl'] + target_url;

        if( side_threads.length > 0 ){
            ajax_url += '&ignore_threads';
        }

        $('.bpbm-notice').remove();

        $(document).trigger("bp-better-messages-ajax-refresh-start");

        $.ajax({
            method: "GET",
            url: ajax_url,
            dataType: 'json',
            cache: false,
            success: function (json) {
                if( typeof json['total_unread'] !== 'undefined'){
                    BPBMUpdateUnreadCount(json['total_unread']);
                }

                if( typeof json['errors'] !== 'undefined'){
                    $.each(json['errors'], function(){
                        BBPMShowError(this);
                    });
                }

                var _html = json['html'];
                var html = $( _html );

                var side_threads_in_return = html.find('.bp-messages-side-threads');

                if( side_threads.length > 0 && side_threads_in_return.length > 0 ) {
                    container.find('.bp-messages-threads-wrapper .bp-messages-column').html(html.find('.bp-messages-threads-wrapper .bp-messages-column').html());
                    container.find('.bp-messages-threads-wrapper').closest('.bp-messages-wrap').find('.chat-header:not(.side-header)').html(html.find('.bp-messages-threads-wrapper').closest('.bp-messages-wrap').find('.chat-header:not(.side-header)').html());
                } else {
                    container.html( $(html).html() );
                }

                if( container.hasClass('bp-messages-wrap-main') ){
                    var newThreadId = html.attr('data-thread-id');
                    if( !! newThreadId ) {
                        container.attr('data-thread-id', html.attr('data-thread-id'));
                    } else {
                        container.removeAttr('data-thread-id');
                    }
                    if( typeof json.errors !== 'undefined' ){
                        $(json.errors.join('')).insertBefore(container);
                    }
                }

                if(container.is('#bp-better-messages-mini-mobile-container')){
                    container.attr('data-thread', html.attr('data-thread-id') );
                }

                if( container.hasClass('bp-messages-wrap-chat') ) {
                    container.find('.chat-header .back').remove();
                }

                reInit();

                container.removeClass('bpbm-call-view');

                container.css('min-height', '');

                $(document).trigger("bp-better-messages-ajax-refresh-end");
            }
        });
    }

    /**
     * Online avatars init
     */
    function onlineInit() {
        $('.bp-messages-wrap img.avatar[data-user-id]').each(function () {
            var img = $(this);
            var user_id = img.attr('data-user-id');
            var color   = img.attr('data-bpbm-status-color');
            var parent = false;

            if (img.parent().hasClass('bbpm-avatar')) parent = img.parent();

            if (!parent) {
                var data_width   = img.data('size');
                var data_height  = img.data('size');
                var width        = img.height();
                var height       = img.height();

                if(data_width < width ){
                    width  = data_width;
                }

                if(data_height < height ){
                    height = data_height;
                }

                var marginTop    = img.css('marginTop');
                var marginLeft   = img.css('marginLeft');
                var marginBottom = img.css('marginBottom');
                var marginRight  = img.css('marginRight');
                $(this).css({
                    marginTop: 0,
                    marginLeft: 0,
                    marginRight: 0,
                    marginBottom: 0
                });

                var wrap = '<span class="avatar bbpm-avatar" data-user-id="' + user_id + '"';
                if( BP_Messages['userStatus'] !== '0') {
                    if (typeof color !== 'undefined') {
                        wrap += 'style="color:' + color + '"';
                    }
                }
                wrap += '></span>';

                img.wrap(wrap);
                parent = img.parent();

                parent.css({
                    marginTop: marginTop,
                    marginLeft: marginLeft,
                    marginRight: marginRight,
                    marginBottom: marginBottom,
                    minWidth: width,
                    minHeight: height
                });
            }

            if (online.indexOf(user_id) > -1) {
                $(parent).addClass('online');
            } else {
                $(parent).removeClass('online');
            }
        });

        sortOnlineFriends();
    }

    function sortOnlineFriends(){
        var friendsWidgets = $('.bp-better-messages-list .tabs-content .friends, .bpbm-friends-list');
        if( friendsWidgets.length > 0 ){
            friendsWidgets.each(function (){
                var friendsWidget = $(this);
                var friendsList = friendsWidget.find('.bp-messages-user-list');
                if( friendsList.length > 0 ){
                    var toOffline = [];
                    var friends = friendsList.find(' > .user');
                    friends.each(function (){
                        var friend    = $(this);
                        var user_id   = friend.attr('data-id');
                        var prevOnline = friend.prev().hasClass('online');

                        if (online.indexOf(user_id) > -1) {
                            friend.addClass('online');
                            if( ! prevOnline ){
                                friend.prependTo(friendsList);
                            }
                        } else {
                            toOffline.push(friend);
                            friend.removeClass('online');
                        }
                    });

                    if( toOffline.length > 0 ){
                        $.each(toOffline, function(){
                            var friend = $(this);
                            var nextOnline = friend.next().hasClass('online');

                            if( nextOnline ){
                                friend.insertAfter(friendsList.find(' > .user.online:last'));
                            }
                        });
                    }

                }
            });
        }
    }

    /**
     * Refreshes threads on thread list screen
     * @param message
     */
    function updateThreads(message) {
        if( typeof message['html'] === 'undefined' ) return false;
        if( message.fast || message.edit == '1' ) return false;
        $(".bp-messages-wrap .threads-list .empty").remove();
        $(".bp-messages-wrap .bp-messages-threads-wrapper.no-threads").removeClass('no-threads');

        var thread_id = message['thread_id'];

        var html = message['html'];
        html = html.replace('loading="lazy"', '');
        var exist = $(threadsSelector + "[data-id='" + thread_id + "']");

        if( exist.length > 0 ){
            var message_content = message.content_site;
            exist.each(function(){
                var __thread = $(this);
                var _p = __thread.find('.info p');
                var __container = __thread.closest('.threads-list');
                __container.removeClass('empty');
                _p.html( message_content );

                if( typeof _p.attr('writing-reserved') !== 'undefined' ) {
                    _p.attr('writing-reserved', message_content )
                }

                __thread.attr('data-message', message.id);
                __thread.prependTo(__container);

                if( BP_Messages['realtime'] === '1' ){
                    var livestamp = __thread.find('.time-wrapper');
                    var timestamp = parseInt(message.timestamp);
                    livestamp.livestamp( new Date(timestamp * 1000) );
                } else if( BP_Messages['realtime'] !== '1' && typeof message.html !== 'undefined' ){
                    __thread.replaceWith( message.html );
                }
            });
        } else {

            $(".bp-messages-wrap .threads-list").each(function(){
                if( $(this).closest('.bpbm-search-results-section').length === 0 ) {
                    $(this).removeClass('empty');
                    $(html).prependTo($(this));
                }
            });
        }

        if (typeof BP_Messages.mutedThreads[thread_id] === 'undefined' && BP_Messages.user_id != message.user_id) {
            if( typeof message.count_unread !== 'undefined' ){
                if( message.count_unread !== '0' ) {
                    playSound(message.id);
                }
            } else {
                playSound( message.id );
            }
        }

        onlineInit();
    }

    /**
     * Properly placing new message on thread screen
     * @param message
     */
    function renderMessage(message, selector) {
        if( typeof BP_Messages['fast'] === 'string' ) {
            if (message.fast && BP_Messages['fast'] !== '1') {
                return false;
            }
        }

        var replaceTemp = false;
        var firstMessage = false;
        if(typeof selector === 'undefined') selector = '.bp-messages-wrap:not(.bp-better-messages-mini,.bp-better-messages-list)';

        if( message.message.trim() == '' ) return false;
        var isEdit = (message['edit'] == '1') ? true : false;


        if( BP_Messages['realtime'] == "1" && message.fast ){
            var messageAlreadyExist = $(selector + ' .messages-list li[data-temp-id="' + message.id + '"]');
            if( messageAlreadyExist.length > 0 ){
                return false;
            }
        }

        var avatar;
        if( typeof message.avatar !== 'string' || BP_Messages['showAvatars'] !== '1' ){
            avatar = '';
        } else {
            avatar = '<div class="pic">' + message.avatar.replace("loading='lazy'", '').replace('loading="lazy"', '') + '</div>';
        }

        if( BP_Messages['realtime'] == "1" && ! message.fast ) {
            if( isEdit ){
                replaceTemp = true;
                message.temp_id = message.id;
            } else if ( ! message.temp_id ) {
                //return false;
            } else {
                replaceTemp = true;
            }
        }

        var readableDate = moment(newTime).format('YYYY-MM-DD HH:mm:ss').toString();
        var stack = $(selector + ' .messages-stack:last-child');
        var container = stack.closest('.bp-messages-wrap');

        var tmpl = 'standard';

        if( container.hasClass('bpbm-template-modern') ){
            tmpl = 'modern';
        }

        if(stack.length === 0 && $(selector + ' .empty-thread').length > 0) {
            firstMessage = true;
        }
        var same_message = $(selector + ' .messages-list li[data-id="' + message.id + '"]');
        var className = '';
        var openInMobileView = $('body').hasClass('bp-messages-mobile') && parseInt(message['thread_id']) === parseInt(thread);
        if( ! openInMobileView && ! ifvisible.now('active') && BP_Messages['realtime'] == "1" && message.user_id !== BP_Messages['user_id'] ) className += ' unread';
        if(message.user_id == BP_Messages['user_id']) className += ' my';
        if( !! message.fast ) className += ' fast';
        if(message.user_id == BP_Messages['user_id'] && BP_Messages['realtime'] == "1") className += ' sent';
        className = className.trim();
        var findMessage = $(selector + ' .messages-list li[data-id="' + message.temp_id + '"]');
        if(isEdit && findMessage.length > 0) className = findMessage.attr('class');

        var dataTempId  = '';
        if (replaceTemp){
            dataTempId = ' data-temp-id="' + message.temp_id + '"';
        }
        var messageHtml = '<li class="' + className + '" data-thread="' + message.thread_id + '" title="' + readableDate + '" data-time="' + message.timestamp + '" data-id="' + message.id + '" ' + dataTempId + '>';

        var actionsHtml = '';
        var replyHtml = '';
        var favoriteHtml = '';
        var contentClass = 'message-content';


        if( BP_Messages['enableReplies'] === '1' ) {
            if( message.user_id != BP_Messages['user_id'] ) {
                replyHtml = '<span class="bpbm-reply" title="' + BP_Messages['strings']['reply'] + '"><i class="fas fa-reply"></i></span>';
            }
            contentClass += ' reply-enabled';
        }

        if(BP_Messages['messagesStatus'] === '1' && message.user_id == BP_Messages['user_id']) {
            actionsHtml += '<span class="status" title="' + BP_Messages['strings']['sent'] + '"></span>';
        }

        if( BP_Messages['disableFavoriteMessages'] !== '1' ) {
            favoriteHtml += '<span class="favorite"><i class="fas" aria-hidden="true"></i></span>';
        }

        if(tmpl === 'standard'){
            messageHtml += actionsHtml;
            messageHtml += favoriteHtml;
            messageHtml += replyHtml;
        }

        messageHtml += '<span class="' + contentClass + '">';

        if(tmpl === 'modern'){
            messageHtml += replyHtml;
            messageHtml += actionsHtml;
            messageHtml += favoriteHtml;
        }

        messageHtml += message.message;
        messageHtml += '</span></li>';

        if(replaceTemp){
            if(findMessage.length > 0){
                if(message.message !== findMessage.find('.message-content').html()){
                    findMessage.replaceWith(messageHtml);
                    $('.bp-messages-wrap .list .messages-stack .content .messages-list li[data-id="' + message.id + '"]').each(function(){
                        updateMessagesStatus( this );
                        initTooltips( BPBMJQ(this) );
                    });
                } else {
                    findMessage.attr('data-id', message.id);
                    findMessage.removeClass('fast');
                    updateMessagesStatus( findMessage );
                }

                initMobileSwipes();
                addIframeClasses();

                return true;
            }
        }

        if (same_message.length === 0 && (stack.length > 0 || firstMessage)) {
            if(firstMessage == true) $(selector + ' .empty-thread').remove();
            var newStack = true;
            var lastTime = new Date( stack.find('.messages-list > li:last-child').attr('data-time') * 1000 );
            var lastTimeString = lastTime.getFullYear() + '-' + lastTime.getMonth() + '-' + lastTime.getDate() + '-' + lastTime.getHours() + '-' + lastTime.getMinutes();
            var newTime = new Date( message.timestamp * 1000 );
            var newTimeString = newTime.getFullYear() + '-' + newTime.getMonth() + '-' + newTime.getDate() + '-' + newTime.getHours() + '-' + newTime.getMinutes();

            if (stack.attr('data-user-id') === message.user_id) newStack = false;
            if (lastTimeString !== newTimeString) newStack = true;

            if ( newStack === false ) {
                stack.find('.messages-list').append(messageHtml);
            } else {
                var stackClass = 'messages-stack';
                if(message.user_id == BP_Messages['user_id']) {
                    stackClass += ' outgoing';
                } else {
                    stackClass += ' incoming';
                }

                var link = '<a href="' + message.link + '">' + message.name + '</a>';
                if( message.link === false ){
                    link = '<span>' + message.name + '</span>';
                }

                var newStackHtml = '<div class="' + stackClass + '" data-user-id="' + message.user_id + '">';

                newStackHtml += avatar;
                newStackHtml += '<div class="content">' +
                    '<div class="info">' +
                    '<div class="name">' +
                    link +
                    '</div>' +
                    '<div class="time" title="' + readableDate + '" data-livestamp="' + message.timestamp + '"></div>' +
                    '</div>' +
                    '<ul class="messages-list">' +
                    '</ul>' +
                    '</div>' +
                    '</div>';

                $(selector + ' .list').append(newStackHtml);

                $(selector + ' .messages-stack:last-child .messages-list').append(messageHtml);
            }

            /* <fs_premium_only> */
            if( !! message.fast ){
                $('.bp-messages-wrap .list .messages-stack .content .messages-list li[data-id="' + message.id  + '"]').each(function () {
                    updateMessagesStatus(this);
                });
            }
            /* </fs_premium_only> */

            //$(selector + " .wp-audio-shortcode, " + selector + " .wp-video-shortcode").not(".mejs-container").filter(function(){return!$(this).parent().hasClass(".mejs-mediaelement")}).mediaelementplayer();

            if( typeof $.fn.BPBMmagnificPopup === 'function') {
                $('.bp-messages-wrap .list .messages-stack .content .messages-list li .images').BPBMmagnificPopup({
                    delegate: 'a',
                    type: 'image'
                });
            }

            if ( typeof BP_Messages.mutedThreads[message.thread_id] === 'undefined' && BP_Messages.user_id != message.user_id) {
                if( typeof message.count_unread !== 'undefined' ){
                    if( message.count_unread !== '0' ) {
                        playSound(message.id);
                    }
                } else {
                    playSound( message.id );
                }
            }
        }

        var createdMessage = $('.bp-messages-wrap .list .messages-stack .content .messages-list li[data-id="' + message.id + '"]');
        if( ! isMobile ) {
            createdMessage.find('.bpbm-gif').each(function () {
                var gif = $(this);
                gif.find('.bpbm-gif-play').remove();
                var video = gif.find('video');
                video[0].play();
            });
        }

        $('.bpbm-gifs-icon').html(icons.gif);

        updateMessagesStatus( createdMessage );

        initImagesPopup();
        onlineInit();
        initMobileSwipes();
        addIframeClasses();

        initTooltips( createdMessage );

        document.dispatchEvent(new BPBMEvent('bp-better-messages-message-render-end'));

    }

    /**
     * Show message notification popup
     *
     * @param thread_id
     * @param message
     * @param name
     * @param avatar
     */
    function showMessage(thread_id, message, name, avatar) {
        if (BP_Messages['disableOnSiteNotification'] === '1') return;

        if (typeof openThreads[thread_id] !== 'undefined') return;
        if( typeof BP_Messages.mutedThreads[thread_id] !== 'undefined' ) return;

        if( $('body').hasClass('bp-messages-mobile') ) return;

        var findVisibleThread = $(threadsSelector + '[data-id="' + thread_id + '"]:visible');
        if(findVisibleThread.length > 0 ) return false;

        var findSrc = avatar.match(/src\="([^\s]*)"\s/);
        var findSrc2 = avatar.match(/src\='([^\s]*)'\s/);

        if (findSrc != null) {
            avatar = findSrc[1];
        }

        if (findSrc2 != null) {
            avatar = findSrc2[1];
        }

        var popupExist = $('.amaran.thread_' + thread_id);
        if(popupExist.length > 0){
            popupExist.find('.icon > img').attr('src', avatar);
            var msg  = '<b>'+ name +'</b>';
            msg += message;
            popupExist.find('.info').html(msg);
            return true;
        }

        if(BP_Messages['miniMessages'] == '1' && miniMessages === 'messages'){
            // add animation here later
        } else {
            $.amaran({
                'theme': 'user message thread_' + thread_id,
                'content': {
                    img: avatar,
                    user: name,
                    message: message
                },
                'sticky': true,
                'closeOnClick': false,
                'closeButton': true,
                'delay': 10000,
                'thread_id': thread_id,
                'position': 'bottom right',
                onClick: function () {
                    /* <fs_premium_only> */
                    if (BP_Messages['realtime'] == "1" && BP_Messages['miniChats'] == '1' && ! isMobile ) {
                        openMiniChat(this.thread_id, true);
                        $('.amaran.user.message.thread_' + thread_id).remove();
                    } else {
                        /* </fs_premium_only> */
                        if( isMobile ){
                            var mobilePopup = $('#bp-better-messages-mini-mobile-open');
                            if( mobilePopup.length > 0 ){
                                var originalUrl = BP_Messages['baseUrl'];
                                BP_Messages['baseUrl'] = BP_Messages['threadUrl'] + this.thread_id;
                                mobilePopup.click();
                                BP_Messages['baseUrl'] = originalUrl;
                                $('.amaran.user.message.thread_' + thread_id).remove();
                            } else {
                                location.href = BP_Messages.threadUrl + this.thread_id;
                            }
                        } else {
                            var url = location.href = BP_Messages.threadUrl + this.thread_id + '&acceptCall';
                            var mainContainer = $('.bp-messages-wrap.bp-messages-wrap-main');
                            if (mainContainer.length > 0) {
                                ajaxRefresh(url, mainContainer);
                            } else {
                                location.href = url;
                            }
                        }
                        /* <fs_premium_only> */
                    }
                    /* </fs_premium_only> */
                }
            });


            $('.bpbm-gifs-icon').html(icons.gif);
        }

        if( typeof message.count_unread !== 'undefined' ){
            if( message.count_unread !== '0' ) {
                playSound(message.id);
            }
        } else {
            playSound( message.id );
        }
    }

    function hidePossibleBreakingElements(){
        if( BP_Messages['hPBE'] !== '1' ) return false;

        var fixed_elements = $('*:not(.bp-messages-hide-on-full-screen)').filter(function () {
            return ( $(this).css('position') === 'fixed' || $(this).css('position') === 'absolute' )
                && ! $(this).hasClass('bp-messages-wrap')
                && $(this).closest('.uppy').length === 0
                && $(this).closest('.bp-messages-wrap').length === 0;
        });

        fixed_elements.addClass('bp-messages-hide-on-full-screen');
    }

    function openMobileFullScreen( url ) {
        var _miniMobileContainer = $('#bp-better-messages-mini-mobile-container');
        _miniMobileContainer.addClass('bp-messages-mobile');
        _miniMobileContainer.find('.bp-messages-mobile-tap').remove();

        var windowHeight = window.innerHeight;
        $('html').addClass('bp-messages-mobile').css('overflow', 'hidden');
        $('body').addClass('bp-messages-mobile').css('min-height', windowHeight);
        bpMessagesWrap.addClass('bp-messages-mobile').css('min-height', windowHeight);

        var usedHeight = 0;
        var chatHeaderHeight = bpMessagesWrap.find('.chat-header').outerHeight();
        usedHeight           = usedHeight + chatHeaderHeight;
        usedHeight           = usedHeight + bpMessagesWrap.find('.reply').outerHeight();

        var resultHeight = windowHeight - usedHeight;

        $('.scroller').css({
            'max-height': '',
            'height': resultHeight
        });

        bpMessagesWrap.find('.bpbm-chat-content').css('max-height', 'calc( 100% - ' + chatHeaderHeight + 'px )');

        hidePossibleBreakingElements();

        _miniMobileContainer.show().html(
            '<div class="loading-messages" style="display: block;line-height: ' + resultHeight + 'px">\n' +
            '<div class="bounce1"></div>\n' +
            '<div class="bounce2"></div>\n' +
            '<div class="bounce3"></div>\n' +
            '</div>'
        );

        var target_url = '?action=bp_messages_load_via_ajax&mobileFullScreen=1';
        if( typeof url.split('?')[1] !== 'undefined' ){
            target_url = '?' + url.split('?')[1] + '&action=bp_messages_load_via_ajax&mobileFullScreen=1';
        }

        var ajax_url = BP_Messages['ajaxUrl'] + target_url;


        $.get(ajax_url, function (json) {
            if( typeof json['total_unread'] !== 'undefined'){
                BPBMUpdateUnreadCount(json['total_unread']);
            }
            if( typeof json['errors'] !== 'undefined'){
                $.each(json['errors'], function(){
                    BBPMShowError(this);
                });
            }
            var html = json['html'];
            var newWrapper = $(html).filter('.bp-messages-wrap').html();
            _miniMobileContainer.html(newWrapper).show();
            blockScroll = true;

            reInit();

            $('#bp-better-messages-mini-mobile-open').removeClass('loading');
        }, 'json');
    }

    $(document).on("submit", '.side-header > .bpbm-search form', function(event){
        event.preventDefault();
        event.stopImmediatePropagation();
    });

    var loadingSearch = false;

    $(document).on("change keyup", '.side-header > .bpbm-search input[name="search"]', function (event) {
        var input     = $(this);
        var search    = input.val().trim();

        var form = input.closest('form');
        var close = form.find('.close');
        var column = input.closest('.bp-messages-side-threads');
        var results = column.find('.bpbm-search-results');
        var threads = column.find('.threads-list');

        var loadingSearchTerm = input.data('search-term');

        if( loadingSearchTerm !== search ) {
            if( search === '' ) {
                threads.show();
                results.hide();
                close.hide();
                input.data('search-term', search);
            } else {
                results.show();
                close.show();
                threads.hide();

                if (loadingSearch) {
                    loadingSearch.abort();
                }

                if( results.find('.loading-messages').length === 0 ) {
                    results.html(loadingHtml);
                }

                input.data('search-term', search);

                loadingSearch = $.post(BP_Messages.ajaxUrl, {
                    action: 'bp_messages_thread_search',
                    search: search
                }, function (response) {
                    results.html(response);
                    loadingSearch = false;
                    onlineInit();
                    $('.bpbm-gifs-icon').html(icons.gif);
                });
            }
        }
    });

    $(document).on("change keyup", '.bpbm-search-in-list > input', function (event) {
        var input     = $(this);
        var search    = input.val().trim().toLowerCase();
        var searchDiv = input.parent();
        var searchIn  = searchDiv.next();

        if( searchIn.hasClass('threads-list') ) {

        } else {
            searchIn.find('> div').each(function () {
                var item = $(this);
                var name = item.find('.name').text().toLowerCase();

                if ( name.indexOf(search) === -1 ) {
                    item.hide();
                } else {
                    item.show();
                }
            });
        }
    });

    $(document).on('click', '.bpbm-send-files.bpbm-has-files', function(event){
        var button = $(this);
        var uppy = button.closest('.uppy-Dashboard');
        var thread_id = parseInt(uppy.attr('data-thread-id'));

        var uploadButton = $('#bpbm-upload-btn-' + thread_id);
        uppy.find('.uppy-Dashboard-close').click();
        var form = uploadButton.closest('form');
        form.submit();
    });

    /* <fs_premium_only> */
    $(document).on("bp-better-messages-open-mini-chat", function (event, thread_id, open) {
        openMiniChat(thread_id, open);
    });

    $(document).on("bp-better-messages-open-private-thread", function (event, user_id) {
        openPrivateThread(user_id);
    });

    function openPrivateThread(user_id){
        var dfd = new $.Deferred();

        $.post(BP_Messages.ajaxUrl, {
            action: 'bp_messages_get_pm_thread',
            user_id: user_id
        }, function(thread_id){
            if( isMobile && BP_Messages['mobileFullScreen'] === '1' ){
                var url = BP_Messages.threadUrl + thread_id;
            } else {
                openMiniChat(thread_id, true).always(function (done) {
                    dfd.resolve(true);
                });
            }
        });

        return dfd.promise();
    }

    var loadingThreads = [];

    function openMiniChat(thread_id, open, reload) {
        var dfd = new $.Deferred();

        if( typeof reload === 'undefined' ) reload = false;

        if(BP_Messages['miniChats'] != '1' || loadingThreads.indexOf(thread_id) > -1) {
            dfd.reject(false);
        } else {
            var check = $('.bp-messages-wrap.bp-better-messages-mini .chats .chat[data-thread="' + thread_id + '"]');
            if( check.length > 0 && ! reload ) {
                if( ! reIniting ){
                    /**
                     * Blinking if minichat already exists
                     */
                    var head = check.find('.head');
                    check.addClass('open');
                    check.removeClass('blink');

                    var times = 0;
                    var intervalID = setInterval(function () {
                        head.toggleClass('blink');
                        times++;
                        if(times >= 6) clearInterval(intervalID);
                    }, 500);
                }

                dfd.reject(false);
            } else {
                loadingThreads.push(thread_id);
                var target_url = '?action=bp_messages_load_via_ajax&thread_id=' + thread_id + '&mini=1';
                var ajax_url = BP_Messages['ajaxUrl'] + target_url;

                $.ajax({
                    method: "GET",
                    url: ajax_url,
                    dataType: "json",
                    cache: false,
                    success: function (json) {
                        if( typeof json['total_unread'] !== 'undefined'){
                            BPBMUpdateUnreadCount(json['total_unread']);
                        }

                        if( typeof json['errors'] !== 'undefined'){
                            $.each(json['errors'], function(){
                                BBPMShowError(this);
                            });
                        }

                        var html = json['html'];
                        var chat = $(html);
                        var head = chat.find('.chat-header');

                        var extraControls = '';

                        var expandingButtons = head.find('.expandingButtons');
                        if(expandingButtons.length > 0) {
                            extraControls += expandingButtons[0].outerHTML.replace('fa-ellipsis-v', 'fa-ellipsis-h');
                            expandingButtons.remove();
                        }

                        var groupCall = head.find('.group-call');
                        if(groupCall.length > 0) {
                            groupCall.remove();
                        }

                        var videoCall = head.find('.video-call');
                        if(videoCall.length > 0) {
                            extraControls += '<span class="video-call" data-user-id="' + videoCall.data('user-id') + '" title="' + BP_Messages['strings']['video_call'] + '"><i class="fas fa-video"></i></span>';
                            videoCall.remove();
                        }

                        var audioCall = head.find('.audio-call');
                        if(audioCall.length > 0) {
                            extraControls += '<span class="audio-call" data-user-id="' + audioCall.data('user-id') + '" title="' + BP_Messages['strings']['audio_call'] + '"><i class="fas fa-phone"></i></span>';
                            audioCall.remove();
                        }

                        head = head.html().trim();
                        chat.find('.chat-header').remove();
                        var chatClass = 'chat';
                        var visibility = 'visibility: hidden';
                        if( open == true ) {
                            chatClass += ' open';
                            visibility = '';
                        }

                        if(BP_Messages['disableEnterForDesktop'] === '1' ){
                            chatClass += ' enter-disabled'
                        }

                        var content = '<div class="' + chatClass + '" data-thread="' + thread_id + '" style="' + visibility + '">';
                        content += '<div class="head"><span class="unread-count count-0"></span><span class="title">' + head + '</span>';
                        content += '<div class="controls">\n' +
                            extraControls +
                            '<span class="open" title="' + BP_Messages['strings']['maximize'] + '"><i class="fas fa-window-maximize" aria-hidden="true"></i></span>\n' +
                            '<span class="close" title="' + BP_Messages['strings']['close'] + '"><i class="fas fa-times" aria-hidden="true"></i></span>\n' +
                            '</div>' +
                            '</div>';
                        content += chat.html();
                        content += '</div>';

                        var chatExist = $('.bp-better-messages-mini .chats .chat[data-thread="' + thread_id + '"]');
                        if( chatExist.length > 0 ){
                            chatExist.replaceWith(content);
                        } else {
                            $(content).appendTo('.bp-messages-wrap.bp-better-messages-mini .chats');
                        }



                        miniChats[thread_id] = open;
                        store.set('bp-better-messages-mini-chats', miniChats);

                        delete loadingThreads[loadingThreads.indexOf(thread_id)];
                        reInit();

                        if(open == true) {
                            socket.emit('threadOpen', thread_id);
                        }

                        closeExcessChats();
                        dfd.resolve(true);
                    },
                    statusCode: {
                        403: function(response) {
                            if(typeof response.responseJSON === 'object') {
                                $.each(response.responseJSON, function(){
                                    BBPMShowError(this);
                                });
                            }

                            delete loadingThreads[loadingThreads.indexOf(thread_id)];
                            delete miniChats[thread_id];
                            store.set('bp-better-messages-mini-chats', miniChats);
                            dfd.resolve(true);
                        }
                    }
                });
            }
        }

        return dfd.promise();
    }

    var excessTimeout;

    $(window).resize(closeExcessChats);

    function closeExcessChats(){
        clearTimeout(excessTimeout);
        excessTimeout = setTimeout(function(){
            $('.bp-messages-wrap.bp-better-messages-mini .chats .chat').each(function(){
                var thread_id = $(this).data('thread');
                var bottom = parseInt($('.bp-messages-wrap.bp-better-messages-mini').outerHeight()) - parseInt($(this).position().top + $(this).outerHeight());
                if(bottom > 1) {
                    $(this).remove();
                    if (typeof(miniChats[thread_id]) !== 'undefined') delete miniChats[thread_id];
                    store.set('bp-better-messages-mini-chats', miniChats);
                }
            });

            $('.bp-messages-wrap.bp-better-messages-mini .chats .chat').css('visibility', 'visible');
        }, 100);
    }
    /* </fs_premium_only> */

    function updateWritingPosition() {
        var writingSpans = $('span.writing');
        writingSpans.each(function() {
            var writingSpan = $(this);
            var wrap = writingSpan.closest('.bp-messages-threads-wrapper');
            var height = wrap.find('.reply').outerHeight();
            var previewHeight = wrap.find('.bpbm-preview-message').outerHeight();

            if (typeof previewHeight !== 'undefined') {
                height += previewHeight;
            }

            writingSpan.css('bottom', height);
        });
    }

    function updateUnreadCounters(thread_id, unread){
        var unreadText;

        if(unread < 1) {
            unreadText = '';
            $('.threads-list .thread[data-id="' + thread_id + '"], .bp-better-messages-mini .chat[data-thread="' + thread_id + '"]').removeClass('unread');
            $('.bp-messages-wrap .messages-list li[data-thread="' + thread_id + '"]').removeClass('unread');
        } else {
            unreadText = '+' + unread;
            $('.threads-list .thread[data-id="' + thread_id + '"], .bp-better-messages-mini .chat[data-thread="' + thread_id + '"]').addClass('unread');
        }
        $('.threads-list .thread[data-id="' + thread_id + '"] .time .unread-count').text(unreadText);
        $('.bp-better-messages-mini .chat[data-thread="' + thread_id + '"] .unread-count').attr('class', 'unread-count count-' + unread).text(unread);
    }

    /**
     * Playing notification sound!
     */
    function playSound( message_id ) {
        if( BP_Messages['enableSound'] !== '1' || BP_Messages['userStatus'] === 'dnd' ) return false;
        if( typeof message_id === 'string' && message_id.substr(0, 4) !== 'tmp_' ){
            if( typeof sounds.notification !== 'undefined' ) {
                sounds.notification.play();
            }
        }
    }

    function createCookie(name, value, days) {
        if (days) {
            var date = new Date();
            date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
            var expires = "; expires=" + date.toUTCString();
        }
        else var expires = "";
        document.cookie = name + "=" + value + expires + "; path=/";
    }

    function readCookie(name) {
        var nameEQ = name + "=";
        var ca = document.cookie.split(';');
        for (var i = 0; i < ca.length; i++) {
            var c = ca[i];
            while (c.charAt(0) == ' ') c = c.substring(1, c.length);
            if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
        }
        return null;
    }


    function getAutocompleteCookies() {
        var allCookies = document.cookie.split(';'),  // get all cookies and split into an array
            bpCookies = {},
            cookiePrefix = 'bp-',
            i, cookie, delimiter, name, value;

        // loop through cookies
        for (i = 0; i < allCookies.length; i++) {
            cookie = allCookies[i];
            delimiter = cookie.indexOf('=');
            name = BPBMJQ.trim(unescape(cookie.slice(0, delimiter)));
            value = unescape(cookie.slice(delimiter + 1));

            // if BP cookie, store it
            if (name.indexOf(cookiePrefix) === 0) {
                bpCookies[name] = value;
            }
        }

        // returns BP cookies as querystring
        return encodeURIComponent(BPBMJQ.param(bpCookies));
    }

    function getParameterByName(name) {
        name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
        var regexS = "[\\?&]" + name + "=([^&#]*)";
        var regex = new RegExp(regexS);
        var results = regex.exec(window.location.search);
        if (results == null)
            return "";
        else
            return decodeURIComponent(results[1].replace(/\+/g, " "));
    }

    function msToTime(duration) {
        var milliseconds = parseInt((duration % 1000) / 100),
            seconds = Math.floor((duration / 1000) % 60),
            minutes = Math.floor((duration / (1000 * 60)) % 60),
            hours = Math.floor((duration / (1000 * 60 * 60)) % 24);

        hours = (hours < 10) ? "0" + hours : hours;
        minutes = (minutes < 10) ? "0" + minutes : minutes;
        seconds = (seconds < 10) ? "0" + seconds : seconds;

        if( hours !== '00' ) {
            return hours + ":" + minutes + ":" + seconds;
        } else {
            return minutes + ":" + seconds;
        }
    }
    /* <fs_premium_only> */
    if( BP_Messages['enablePushNotifications'] === '1' ) {
        BPBMJQ(document).on('click', '.BPBMenablePushNotifications', function (event) {
            BPBMregisterPushWorker();
        });

        BPBMJQ(document).on('click', '.BPBMdisablePushNotifications', function (event) {
            BPBMunregisterPushWorker();
        });
    }
    /* </fs_premium_only> */

    function calculateTitle(wraps){
        if( typeof wraps === 'undefined' ) return false;
        wraps.each(function(){
            var wrap = BPBMJQ(this);

            if( ! wrap.is(':visible') ){
                setTimeout(function(){
                    calculateTitle(wrap);
                }, 100);
            } else {
                var head       = wrap.find('.chat-header:not(.side-header)');
                var title      = head.find('> strong');
                var user       = head.find('> .user');

                var iconsWidth = 0;

                head.find('> a:visible:not(.user),> div:visible').each(function () {
                    iconsWidth = iconsWidth + $(this).width();
                });

                var resultWidth = iconsWidth + 10;

                if( title.length > 0 ) {
                    title.css( 'width', 'calc(100% - ' + resultWidth + 'px)' )
                }

                if( user.length > 0 ){
                    user.css( 'max-width', 'calc(100% - ' + resultWidth + 'px)' );
                }

                wrap.find('.chats .chat').each(function(){
                    var chat  = BPBMJQ(this);
                    var head  = chat.find('> .head');
                    var title = head.find('> .title');

                    var iconsWidth = 0;

                    head.find('> div.controls').each(function () {
                        iconsWidth = iconsWidth + $(this).width();
                    });

                    var resultWidth = iconsWidth + 40;


                    if( title.length > 0 ) {
                        title.css( 'max-width', 'calc(100% - ' + resultWidth + 'px)' )
                    }

                });
            }
        })

    }

    function showPreloader(container){
        var headerHeight = container.find('.chat-header').height();
        var preloader    = container.find('.preloader');
        preloader.show();
        if( ! preloader.parent().hasClass('bp-messages-column') ){
            preloader.css('top', headerHeight);
            preloader.css('height', 'calc(100% - ' + headerHeight + 'px)')
        }
    }

    function toArray(list, index) {
        var array = []

        index = index || 0

        for (var i = index || 0; i < list.length; i++) {
            array[i - index] = list[i]
        }

        return array
    }
})(BPBMJQ);
/* <fs_premium_only> */
function BPBMcheckPushWorkerStatus(){
    if ('serviceWorker' in navigator && 'PushManager' in window) {
        checkWorker();
    } else {
        BPBMJQ('.BPBMpushNotifications').hide();
    }

    function checkWorker() {
        navigator.serviceWorker
            .register('/bpbm-worker.js', {scope: '/'})
            .then(function(registration){
                registration.pushManager.getSubscription().then(function(pushSubscription) {
                    if( pushSubscription === null ){
                        BPBMJQ('.BPBMenablePushNotifications').show();
                        BPBMJQ('.BPBMdisablePushNotifications').hide();
                    } else {
                        BPBMJQ('.BPBMenablePushNotifications').hide();
                        BPBMJQ('.BPBMdisablePushNotifications').show();

                        BPBMJQ.post(BP_Messages['ajaxUrl'], {
                            action : 'bp_better_messages_save_user_push_subscription',
                            nonce  : BP_Messages['savePushNotificationsNonce'],
                            sub    : JSON.stringify(pushSubscription)
                        });
                    }
                } );
            });
    }
}

function BPBMregisterPushWorker(){
    if ('serviceWorker' in navigator && 'PushManager' in window) {
        registerWorker();
    }

    function registerWorker() {
        navigator.serviceWorker
            .register('/bpbm-worker.js', {scope: '/'})
            .then(function(registration){
                registration.pushManager.getSubscription().then(function(pushSubscription) {
                    if( pushSubscription === null ){
                        registration.pushManager.subscribe({
                            userVisibleOnly: true,
                            applicationServerKey: BPBMurlBase64ToUint8Array(BP_Messages['vapidPublicKey'])
                        }).then(function(pushSubscription) {
                            BPBMJQ.post(BP_Messages['ajaxUrl'], {
                                action : 'bp_better_messages_save_user_push_subscription',
                                nonce  : BP_Messages['savePushNotificationsNonce'],
                                sub    : JSON.stringify(pushSubscription)
                            });

                            BPBMJQ('.BPBMenablePushNotifications').hide();
                            BPBMJQ('.BPBMdisablePushNotifications').show();
                        }).catch(function( error ){
                            BBPMShowError( error );
                        });
                    }
                } );
            });
    }
}

function BPBMunregisterPushWorker(){
    if ('serviceWorker' in navigator && 'PushManager' in window) {
        unregisterWorker();
    }

    function unregisterWorker() {
        navigator.serviceWorker
            .register('/bpbm-worker.js', {scope: '/'})
            .then(function(registration){
                registration.pushManager.getSubscription().then(function(pushSubscription) {
                    if( pushSubscription !== null ){
                        pushSubscription.unsubscribe().then(function(successful) {
                            BPBMJQ.post(BP_Messages['ajaxUrl'], {
                                action : 'bp_better_messages_delete_user_push_subscription',
                                nonce  : BP_Messages['savePushNotificationsNonce'],
                                sub    : JSON.stringify(pushSubscription)
                            });
                            BPBMJQ('.BPBMenablePushNotifications').show();
                            BPBMJQ('.BPBMdisablePushNotifications').hide();
                        }).catch(function(e) {
                            // Unsubscription failed
                        })
                    }
                });
            });
    }
}
/* </fs_premium_only> */

function BPBMurlBase64ToUint8Array( base64String ) {
    var padding = '='.repeat((4 - base64String.length % 4) % 4);
    var base64 = (base64String + padding)
        .replace(/\-/g, '+')
        .replace(/_/g, '/');

    var rawData = window.atob(base64);
    var outputArray = new Uint8Array(rawData.length);

    for (var i = 0; i < rawData.length; ++i) {
        outputArray[i] = rawData.charCodeAt(i);
    }

    return outputArray;
}

/**
 * Show notice popup
 */
function BBPMNotice(notice) {
    if( typeof window.BMAppNoticeToast === 'function' ){
        window.BMAppNoticeToast('', notice, 10000);
    } else {
        BPBMJQ.amaran({
            'theme': 'colorful',
            'content': {
                bgcolor: 'black',
                color: '#fff',
                message: notice
            },
            'sticky': false,
            'closeOnClick': true,
            'closeButton': true,
            'delay': 10000,
            'position': 'bottom right'
        });
    }
}

/**
 * Show error popup
 */
function BBPMShowError(error) {
    if( typeof window.BMAppErrorToast === 'function' ){
        window.BMAppErrorToast('', error, 10000);
    } else {
        BPBMJQ.amaran({
            'theme': 'colorful',
            'content': {
                bgcolor: '#c0392b',
                color: '#fff',
                message: error
            },
            'sticky': false,
            'closeOnClick': true,
            'closeButton': true,
            'delay': 10000,
            'position': 'bottom right'
        });
    }
}

function BBPMOpenMiniChat(thread_id, open) {
    BPBMJQ(document).trigger("bp-better-messages-open-mini-chat", [thread_id, open]);
}

function BBPMOpenPrivateThread(user_id) {
    BPBMJQ(document).trigger("bp-better-messages-open-private-thread", [user_id]);
}

function BPBMGetOnlineUsers(){
    return BPBMOnlineUsers;
}
