$(document).ready(function() {

    var loadingTemplate = _.template('<span class="text-muted">{{- loading_text }}</span>');
    var errorTemplate = _.template('<div class="alert alert-danger">{{- error_text }}</div>');

    // ---------------------------------
    // CALCULATE WIDTH OF PROFILE IMAGE WRAPPER AND ADD 'SEE MORE' BUTTON IF WIDER THAN VIEWPORT
    // ---------------------------------
    function profileWrapper() {
        var userWrapper = $('.chat-users-message .users');
        var profileNumber = $('.chat-users-message .users a.profile').length;
        var profileWidth = 58;
        var totalWidth = profileWidth*profileNumber;
        var wrapperWidth = userWrapper.outerWidth();

        var totalUsers = profileNumber;

        if (userWrapper.attr("data-total-users"))
            totalUsers = parseInt(userWrapper.attr("data-total-users"));

        if(wrapperWidth <= totalWidth || totalUsers > profileNumber) {
            $('.see-more .number-bubble').text(totalUsers);
            $('.chat-users-message .see-more').addClass('show');
        } else {
            $('.chat-users-message .see-more').removeClass('show');
        }
    }

    // The delete action performed from within the messages table.
    var delete_action = null;

    // Store the id for specfic actions from within the message thread.
    var delete_id = null;
    var update_id = null;

    $('.toggle-send-as-options').click(function () {
        if ($(this).attr('value') == 1) {
            $('#send_as_message_options').hide();
            $('#send_as_notification_options').show();

        } else {
            $('#send_as_message_options').show();
            $('#send_as_notification_options').hide();
        }
    });


    // ---------------------------------
    // OPEN DIFFERENT SECTION OF MODAL DEPENDENT ON BUTTON
    // ---------------------------------

    $('#compose-message, #update-message, #delete-message, #delete-selected, #delete-all').click(function () {
        $('.messages-modal .modal-content').hide();
        var buttonId = $(this).attr('id');

        if (buttonId === 'compose-message') {
            $('#modal-new-message').show();
            $('#messages-modal').find('.modal-dialog').addClass('modal-xl');
        } else if (buttonId === 'delete-message') {
            $('#modal-delete-message').show();
            $('#messages-modal .modal-dialog').removeClass('modal-xl');
            // Get the id to delete from the mark-up.
            var element = $(this).closest("[data-delete-id], .message-block");
            delete_id = element.attr('data-delete-id');
        } else if (buttonId === 'update-message') {
            $('#modal-update-message').show();
            $('#messages-modal').find('.modal-dialog').addClass('modal-lg');

            var element = $(this).parent().parent().children("[data-update-id], .message-body");
            update_id = element.attr('data-update-id');

            CKEDITOR.instances["update_message_text"].setData(element.html());
        } else if (buttonId ==="delete-selected" || buttonId ==="delete-all") {

            delete_action = $(this).attr('id');

            $('#modal-table-delete-message').show();
            $('#messages-modal').find('.modal-dialog').removeClass('modal-lg');
        }
        $('#messages-modal').modal();
        return false;
    });

    // Automatically open the compose modal if there's an id on the URL so
    // the message can be quoted in a new message, but only on messages.php
    if (window.location.pathname.search(/\/messages.php|\/imessageread.php$/) >= 0 && window.location.search.search(/\^?(quote_id=\d+)|(compose=1)|(user_id=\d+&compose=1)$/g) >= 0)
    {
        $('#compose-message').click();
    }

    // Confirm delete from within the message thread.
    $('#confirm-delete').click(function () {
        $.ajax({
            type: "POST",
            url: 'thread_delete_message.php',
            data: {'delete_id': delete_id},
            success: function(result) {

                // Close the modal.
                $('#messages-modal').modal('toggle');

                // Remove the message from the thread mark-up.
                if (result == '0') {
                    console.error('There was a problem deleting message with id ' + delete_id);
                } else {
                    var element = $( "div[data-delete-id='" + delete_id + "']");
                    element.addClass('delete-out');
                    element.css("height", element.height() )
                    setTimeout(function () {
                        element.addClass('delete-out-height');
                    }, 300);
                    setTimeout(function () {
                        element.remove();
                    }, 600);
                }
            }
        });

        return false;
    });

    // Update a message within the thread.
    $('#update-message-form').submit(function () {
        var message_text = CKEDITOR.instances["update_message_text"].getData();

        $.ajax({
            type: "POST",
            url: 'thread_update_message.php',
            data: {'update_id': update_id, 'update_message_text': message_text},
            success: function(result) {

                // Close the modal.
                $('#messages-modal').modal('toggle');

                // Update the message in the thread mark-up.
                if (result == '0') {
                    console.error('There was a problem updating message with id ' + update_id);
                } else {
                    var element = $( "div[data-update-id='" + update_id + "']");
                    element.html(message_text);
                    element.parent().find(".message-updated").toggle();
                }
            }
        });

        return false;
    });

    // Confirm delete from within the message thread.
    $('#confirm-table-delete').click(function () {
        // Close the modal.
        $('#messages-modal').modal('toggle');

        if (delete_action == 'delete-selected') {
            var selected = JSON.stringify($("input[name='selected[]']:checked").map(function(){return $(this).val();}).get());
        } else {
            var_selected = '';
        }

        $('#delete-selected').val(selected);
        $('#confirm-table-delete').val(delete_action);

        return true;
    });

    // ---------------------------------
    // SELECT ALL TICKBOXES IN TABLE
    // ---------------------------------

    $('.select_all').change(function () {
        var checkboxes = $(this).closest('form').find(':checkbox');
        checkboxes.prop('checked', $(this).is(':checked'));
    });

    $('.toggle_blockquote').click(function () {
        $(this).parent().next().toggle();
        return false;
    });


    // ---------------------------------
    // IMAGE MODAL/LIGHTBOX
    // ---------------------------------

    $('.text-bubble img').on('click',function() {
        var englargeImage = $(this).attr('src');
        $('.image-lightbox-img').attr('src', englargeImage);
        $('.image-expand-modal').modal('show');
    });

    // ------------
    // IMAGE MODAL/LIGHTBOX - CLOSE ON BODY CLICK
    // ------------

    $('.image-expand-modal .modal-dialog').on('click',function(){
        $('.image-expand-modal').modal('hide');
    });



    // ---------------------------------
    // DISPLAY 'SHOW MORE' BUTTON ON SMALL DISPLAYS
    // ---------------------------------

    profileWrapper();
    var $window = $(window);
    var lastWindowWidth = $window.width();

    $window.resize(function () {
        var windowWidth = $window.width();
        if (lastWindowWidth !== windowWidth) {
            profileWrapper();
            lastWindowWidth = windowWidth;
        }
    });

    // ---------------------------------
    // UPDATE CONTENT OF USER MODAL
    // ---------------------------------

    $('[data-target="#userModal"]').on('click',function() {
        var userModal = $('#userModal .modal-body');
        var messageId = $(this).attr('data-message-id');

        if (userModal.attr('data-loaded') !== messageId)
        {
            userModal.html(
                loadingTemplate({
                        loading_text: lmsg('communication.conversation.loading')
                })
            );
            $.ajax("/communication/messages/" + messageId + "/participants/xhr", {
                success: function(data) {
                    userModal.html(data.html);
                    userModal.attr('data-loaded', messageId);
                },
                error: function() {
                    userModal.html(
                        errorTemplate({
                            error_text: lmsg('communication.conversation.participants_failed')
                        })
                    );
                }

            });
        }
    });


    // ---------------------------------
    // COMPOSE MODAL VALIDATION
    // ---------------------------------

    $('#send-message-modal').on('click',function(){
        var team = $('#my-team:checked').length;
        var ckContent = CKEDITOR.instances['new_message_text'].getData();
        ckContent +=0;

        if ($('#send_as_message:checked').length > 0 || ($('#send_as_message:checked').length == 0 && $('#send_as_notification:checked').length == 0)) {
            var users = $('.messages-modal .select2-selection__choice').length;

            if ((users === 0) && (team === 0)) {
                $('.messages-modal .validation-add-user').removeClass('d-none');
                return false;
            } else {
                $('.messages-modal .validation-add-user').addClass('d-none');
            }
            if (ckContent == 0) {
                $('.messages-modal .validation-add-message').removeClass('d-none');
                return false;
            } else {
                $('.messages-modal .validation-add-message').addClass('d-none');
                setTimeout(function () {
                    $('#send-message-modal').attr('disabled','disabled');
                }, 10);
            }

        } else if ($('#send_as_notification:checked').length > 0) {
            var users = $('#send_as_notification_options select option').length;
            if ((users === 0) && (team === 0)) {
                $('.messages-modal .validation-add-user').removeClass('d-none');
                return false;
            } else {
                $('.messages-modal .validation-add-user').addClass('d-none');
            }

            if (ckContent == 0) {
                $('.messages-modal .validation-add-message').removeClass('d-none');
                return false;
            } else {
                $('.messages-modal .validation-add-message').addClass('d-none');
                setTimeout(function () {
                    $('#send-message-modal').attr('disabled','disabled');
                }, 10);
            }
        }
    });

    // ---------------------------------
    // CHAT MESSAGE VALIDATION
    // ---------------------------------
    $('#message_form #send-message').on('click',function() {
        var ckContent = CKEDITOR.instances['message_text'].getData();
        if (ckContent == 0) {
            $('#message_form .validation-add-message').removeClass('d-none');
            return false;
        } else {
            $('#message_form .validation-add-message').addClass('d-none');
            setTimeout(function () {
                $('#message_form #send-message').attr('disabled','disabled');
            }, 10);
        }
    });


    // ---------------------------------
    // UPDATE MESSAGE VALIDATION
    // ---------------------------------
    $('#save-message').on('click',function() {
        var ckContent = CKEDITOR.instances['update_message_text'].getData();
        if (ckContent == 0) {
            $('#update-message-form .validation-add-message').removeClass('d-none');
            return false;
        } else {
            $('#update-message-form .validation-add-message').addClass('d-none');
        }
    });

    // ---------------------------------
    // MAKE DELETED USER UNCLICKABLE IN CONVERSATION
    // ---------------------------------
  function removeDeletedUserLink() {
      $('.message-from-link').each(function(){
          if($(this).find('.user-name').text() === lmsg('communication.messages.deleted_user_name'))
          {
              $(this).removeAttr("href");
              $(this).hover().css("opacity", "1");
          }
      })
  }
  removeDeletedUserLink();

}); // document ready
