/**
 * Search admin panel JavaScript
 *
 *
 * @version 1.02
 */

/**
 * Prevent table collapse on drag
 * @param {Event} e
 * @param {DOMElement}
 * @return {DOMElement}
 */
var fixHelper = function (e, ui) {
    ui.children().each(function () {
        $(this).width($(this).width());
    });
    return ui;
};

/**
 * Delete a search suggestion request
 * @param {Event} e
 */
var deleteRequest = function (e) {
    var targetRequest = $(e.currentTarget);
    if (confirm('Are you sure you would like to delete this request?')) {
        // XAJAX function delete_request [/intranet/search/xajax/request.php]
        xajax_delete_request(targetRequest.data('id'));
        // Hide tooltip
        targetRequest.tooltip('hide');
        // Remove row
        targetRequest.parent().parent().remove();
    }
};

/**
 * deleteSearchGroup
 * @param {Event} e
 */
var deleteSearchGroup = function (e) {
    var targetGroup = $(e.currentTarget);
    if (confirm('Are you sure you would like to delete this group?')) {
        // XAJAX function delete_group [/intranet/search/xajax/group.php]
        xajax_delete_group(targetGroup.data('id'));
        // Hide tooltip
        targetGroup.tooltip('hide');
        // Remove row
        targetGroup.parent().parent().remove();
    }
};

/**
 * Add value of term input to the list of search terms.
 * @return {Bool}
 */
var addSearchTerm = function () {
    // Text input for adding a term
    var input          = $('#frmSearchTerm');
    // List of terms in this group
    var list           = $('#term_list');
    // Value of input
    var value          = input.val();
    // Cancel button on form
    var cancelButton   = $('#cancelEdit');
    // SearchGroup form
    var frmSearchGroup = $('#frmSearchGroup');
    // Make sure there is a value entered into the input
    if (value.length === 0) {
        return false;
    }
    // Row to be added to list of terms
    var row = $('<tr></tr>');
    // Value cell for row
    row.append($('<td></td>').append($('<a href="/search/?q=' + encodeURIComponent(value) + '" name="restore_term"  target="_blank"></a>').text(value)));
    // Delete cell for row
    row.append($('<td></td>').append($('<a name="term_delete" href="javascript:void(0)" onclick="deleteSearchTerm(this);">').append($('<ion-icon name="trash-outline"></ion-icon>'))));
    // Add hidden input to SearchGroup form
    frmSearchGroup.append($('<input type="hidden" name="frmAddSearchTerm[]" />').val(value));
    // Add the row to the list of terms
    list.append(row);
    // Clear the input
    input.val('');
    // Set cancel button data-modified to true
    cancelButton.data('modified', true);
    /**
     * Check if the term matches a SearchSuggestionRequest
     * - If true matchedRequestDialog is called
     * XAJAX function /intranet/search/xajax/request.php
     */
    xajax_match_request(value);
    return true;
};

/**
 * Mark a search term as deleted
 * @param {DOMElement} el    element that was clicked
 */
var deleteSearchTerm = function (el) {
    // jQuery object of element that was clicked
    var element        = $(el);
    // Target row in the terms list
    var row            = element.parent().parent();
    // SearchGroup form
    var frmSearchGroup = $('#frmSearchGroup');
    // Cancel button on form
    var cancelButton   = $('#cancelEdit');
    // Cell in row with either delete/restore
    var optionsTd      = element.parent();
    // Link in the row with the term value
    var termLink       = $(row).children().find('a').first();
    // Check if data-id is defined. Either add hidden field to delete one that's
    // already in the db or remove the hidden field to add one.
    if (element.data('id') !== undefined) {
        frmSearchGroup.append($('<input type="hidden" name="frmDeleteSearchTerm[]" />').val(element.data('id')));
        cancelButton.data('modified', true);
    } else {
        var value = $(termLink).html();
        $('input:hidden[name="frmAddSearchTerm[]"][value="' + value + '"]').remove();
    }
    // Create a link that will be used to revert a delete action
    var restoreLink = $('<a href="javascript:void(0)"><ion-icon name="arrow-undo-outline"></ion-icon></a>').on('click', function (event) {
        restoreSearchTerm(event);
    });
    // Assign data-id if it's defined
    if (element.data('id') !== undefined) {
        restoreLink.data('id', element.data('id'));
    }
    // Addrestore button to the list
    $(optionsTd).append(restoreLink);
    // Hide tooltip
    element.tooltip('hide');
    // Remove the delete link
    element.remove();
    // Strike through the row
    row.children('td').css('text-decoration', 'line-through');
    return false;
};

/**
 *  Restore a search term that has been deleted
 * @param {Event} e
 */
var restoreSearchTerm = function (e) {
    // Stop default event
    e.preventDefault();
    // jQuery object of element that was clicked
    var element        = $(e.currentTarget);
    // Target row in the terms list
    var row            = element.parent().parent();
    // SearchGroup form
    var frmSearchGroup = $('#frmSearchGroup');
    // Restore link in row
    var restoreLink    = element.parent();
    // Link in the row with the term value
    var termLink       = $(row).children().find('a').first();
    // Check if data-id is defined. Either remove hidden field to delete one that's
    // already in the db or remove the hidden field to delete one.
    if (element.data('id') !== undefined) {
        $('input:hidden[name="frmDeleteSearchTerm[]"][value=' + element.data('id') + ']').remove();
        $('#cancelEdit').data('modified', true);
    } else {
        var value = $(termLink).html();
        frmSearchGroup.append($('<input type="hidden" name="frmAddSearchTerm[]" value="' + value + '" />'));
    }
    // Create a delete link
    var deleteLink = $('<a href="javascript:void(0)"><ion-icon name="trash-outline"></ion-icon></a>').on('click', function (event) {
        deleteSearchTerm(this);
    });
    // Set data-id
    if (element.data('id') !== undefined) {
        deleteLink.data('id', element.data('id'));
    }
    // Add delete link to list
    $(restoreLink).append(deleteLink);
    // Hide tooltip
    element.tooltip('hide');
    // Remove restore link
    element.remove();
    // Strike through the row
    row.children('td').css('text-decoration', '');
    return false;
};

/**
 * Add value of suggestio input to the list of search suggestios
 * @return {Bool}
 */
var addSuggestion = function () {
    // Text input for adding a suggestion
    var input          = $('#frmSearchSuggestion');
    // List of suggestions in this group
    var list           = $('#suggestion_list');
    // Value of input
    var value          = input.val();
    // Cancel button on form
    var cancelButton   = $('#cancelEdit');
    // SearchGroup form
    var frmSearchGroup = $('#frmSearchGroup');
    // Make sure there is a value entered into the input
    if (value.length === 0) {
        return false;
    }
    // Row to be added to list of suggestions
    var row = $('<tr></tr>');
    // Value cell for row
    row.append($('<td></td>').append($('<a href="/search/?q=' + encodeURIComponent(value) + '" name="restore_suggestion" target="_blank""></a>').text(value)));
    // Delete cell for row
    row.append($('<td></td>').append($('<a name="suggestion_delete" href="javascript:void(0)" onclick="deleteSearchSuggestion(this);">').append($('<ion-icon name="trash-outline"></ion-icon>'))));
    // Add hidden input to SearchGroup form
    frmSearchGroup.append($('<input type="hidden" name="frmAddSearchSuggestion[]" />').val(value));
    // Add suggestion to suggestions list
    list.append(row);
    // Clear the input
    input.val('');
    // Set cancel button data-modified to true
    cancelButton.data('modified', true);
};

/**
 * deleteSearchSuggestion
 * @param {Object} el
 */
var deleteSearchSuggestion = function (el) {
    // jQuery object of element that was clicked
    var element        = $(el);
    // Target row in the terms list
    var row            = element.parent().parent();
    // SearchGroup form
    var frmSearchGroup = $('#frmSearchGroup');
    // Cancel button on form
    var cancelButton   = $('#cancelEdit');
    // Cell in row with either delete/restore
    var optionsTd      = element.parent();
    // Link in the row with the term value
    var termLink       = $(row).children().find('a').first();
    if (element.data('id') !== undefined) {
        frmSearchGroup.append($('<input type="hidden" name="frmDeleteSearchSuggestion[]" />').val(element.data('id')));
        cancelButton.data('modified', true);
    } else {
        var value = $(termLink).html();
        $('input:hidden[name="frmAddSearchSuggestion[]"][value="' + value + '"]').remove();
    }
    // Create restore link
    var restoreLink = $('<a href="javascript:void(0)"><ion-icon name="arrow-undo-outline"></ion-icon></a>').on('click', function (event) {
        restoreSearchSuggestion(event);
    });
    // Add data-id if it's defined
    if (element.data('id') !== undefined) {
        restoreLink.data('id', element.data('id'));
    }
    // Add restore link to the row
    $(optionsTd).append(restoreLink);
    // Hide tooltip
    element.tooltip('hide');
    // Remove delete link
    element.remove();
    // Strike through the row
    row.children('td').css('text-decoration', 'line-through');
    return false;
};

/**
 * Revert delete action
 * @param {Event} event
 */
var restoreSearchSuggestion = function (e) {
    // Stop default event
    e.preventDefault();
    // jQuery object of element that was clicked
    var element        = $(e.currentTarget);
    // Target row in the terms list
    var row            = element.parent().parent();
    // SearchGroup form
    var frmSearchGroup = $('#frmSearchGroup');
    // Restore link in row
    var restoreLink    = element.parent();
    // Link in the row with the term value
    var termLink       = $(row).children().find('a').first();
    // Cell in row with either delete/restore
    var optionsTd      = element.parent();
    if (element.data('id') !== undefined) {
        $('input:hidden[name="frmDeleteSearchSuggestion[]"][value=' + element.data('id') + ']').remove();
        $('#cancelEdit').data('modified', true);
    } else {
        var value = $(termLink).html();
        frmSearchGroup.append($('<input type="hidden" name="frmAddSearchSuggestion[]" value="' + value + '" />'));
    }
    // Create delete link
    var deleteLink = $('<a href="javascript:void(0)"><ion-icon name="trash-outline"></ion-icon></a>').on('click', function (event) {
        deleteSearchSuggestion(this);
    });
    // Add data-id if it's defined
    if (element.data('id') !== undefined) {
        deleteLink.data('id', element.data('id'));
    }
    // Add delete link to list
    $(optionsTd).append(deleteLink);
    // Hide tooltip
    element.tooltip('hide');
    // Remove restore link
    element.remove();
    // Strike through the row
    row.children('td').css('text-decoration', '');
    return false;
};

/**
 * Add a best bet, called from modal dialog when save is clicked
 */
var addBestBet = function () {
    xajax_best_bet_submit(xajax.getFormValues('bestBetForm'));
};

/**
 * Add row to best bets table once it's been added to db
 * @param {Integer} id
 * @param {String} bestBetName
 * @param {String} bestBetDescription
 * @param {String} bestBetURL
 */
var addBestBetsRow = function (id, bestBetName, bestBetDescription, bestBetURL) {
    // Row to insert
    var row  = $('<tr></tr>').prop('id', 'bb-' + id);
    // Name link
    var name = $('<a href="#editBestBet" class="editBestBet"></a>').text(bestBetName).data({
        'id': id,
        'name': bestBetName,
        'description': bestBetDescription,
        'url': bestBetURL,
        'toggle': 'modal'
    });
    name.on('click', function () {
        $('#bestBetName').val($(this).data('name'));
        $('#bestBetDescription').val($(this).data('description'));
        $('#bestBetURL').val($(this).data('url'));
        $("#editBestBet").modal("show");
        hideValidation();
    });
    // Draggable/Name cell
    row.append($('<td><span style="cursor: move" class="glyphicons-show-lines glyphicons"></span></td>').append(name));
    // Description cell
    row.append($('<td></td>').text(bestBetDescription));
    // URL cell
    row.append($('<td></td>').append($('<a></a>').text(bestBetURL).attr('href', bestBetURL).attr('target', '_blank')));
    var del = $('<a href="javascript:void(0)"></a>').data('id', id).on('click', function () {
        deleteSearchBestBet(this);
    }).append($('<ion-icon name="trash-outline"></ion-icon>'));
    // Delete cell
    row.append($('<td class="text-center"></td>').append(del));
    // Add row to best bets table
    $('#bestBets').find('tbody').append(row);
};

var editBestBetsRow = function (id, bestBetName, bestBetDescription, bestBetURL) {
    var el   = $('#bb-' + id);
    var row  = $('<tr></tr>').prop('id', 'bb-' + id);
    // Name link
    var name = $('<a href="#editBestBet" class="editBestBet"></a>').text(bestBetName).data({
        'id': id,
        'name': bestBetName,
        'description': bestBetDescription,
        'url': bestBetURL,
        'toggle': 'modal'
    });
    name.on('click', function () {
        $('#bestBetName').val($(this).data('name'));
        $('#bestBetDescription').val($(this).data('description'));
        $('#bestBetURL').val($(this).data('url'));
        $("#editBestBet").modal("show");
        hideValidation();
    });
    // Draggable/Name cell
    row.append($('<td><span style="cursor: move" class="glyphicons-show-lines glyphicons"></span></td>').append(name));
    // Description cell
    row.append($('<td></td>').text(bestBetDescription));
    // URL cell
    row.append($('<td></td>').append($('<a></a>').text(bestBetURL).attr('href', bestBetURL).attr('target', '_blank')));
    var del = $('<a href="javascript:void(0)"></a>').data('id', id).on('click', function () {
        deleteSearchBestBet(this);
    }).append($('<ion-icon name="trash-outline"></ion-icon>'));
    // Delete cell
    row.append($('<td class="text-center"></td>').append(del));
    // replace existing row
    el.replaceWith(row);
};

/**
 * Mark a best bet as deleted
 * @param {Object} el
 */
var deleteSearchBestBet = function (el) {
    // jQuery object of element that was clicked
    var element        = $(el);
    // Target row in the best bets list
    var row            = element.parent().parent();
    // SearchGroup form
    var frmSearchGroup = $('#frmSearchGroup');
    // Cancel button on form
    var cancelButton   = $('#cancelEdit');
    // Cell in row with either delete/restore
    var optionsTd      = element.parent();
    // Add hidden input to form
    frmSearchGroup.append($('<input type="hidden" name="frmDeleteBestBet[]" />').val(element.data('id')));
    // Create restore link
    var restoreLink = $('<a href="javascript:void(0)"><ion-icon name="arrow-undo-outline"></ion-icon></a>').on('click', function (event) {
        restoreBestBet(event);
    });
    // Add data-id if defined
    if (element.data('id') !== undefined) {
        restoreLink.data('id', element.data('id'));
    }
    // Add delete link to list
    $(optionsTd).append(restoreLink);
    // Hide tooltip
    element.tooltip('hide');
    // Remove restore link
    element.remove();
    // Strike through the row
    row.children('td').css('text-decoration', 'line-through');
    // Set cancel button data-modified to true
    cancelButton.data('modified', true);
    return false;
};

/**
 * Revert delete action
 * @param {Object} e
 */
var restoreBestBet = function (e) {
    // Stop default event
    e.preventDefault();
    // jQuery object of element that was clicked
    var element        = $(e.currentTarget);
    // Target row in the terms list
    var row            = element.parent().parent();
    // SearchGroup form
    var frmSearchGroup = $('#frmSearchGroup');
    // Restore link in row
    var restoreLink    = element.parent();
    // Link in the row with the term value
    var termLink       = $(row).children().find('a').first();
    // Cell in row with either delete/restore
    var optionsTd      = element.parent();
    // Remove hidden input (unlike other restore functions this one doesn't need to
    // check for id)
    $('input:hidden[name="frmDeleteBestBet[]"][value=' + element.data('id') + ']').remove();
    // Create delete link
    var deleteLink = $('<a href="javascript:void(0)"><ion-icon name="trash-outline"></ion-icon></a>').on('click', function (event) {
        deleteSearchBestBet(this);
    });
    // Add data-id if it's defined
    if (element.data('id') !== undefined) {
        deleteLink.data('id', element.data('id'));
    }
    // Add delete link to list
    $(optionsTd).append(deleteLink);
    // Hide tooltip
    element.tooltip('hide');
    // Remove restore link
    element.remove();
    // Strike through the row
    row.children('td').css('text-decoration', '');
    return false;
};

/**
 * Indicate if data entered for a best bet URL is valid
 * Called from XAJAX function process_url [/intranet/search/xajax/best_bet.php]
 * @param {Object} params
 */
var urlValidity = function (params) {
    var resource_valid, resource_type, resource_perms_supported;
    // Create JSON object from params
    var obj          = jQuery.parseJSON(params);
    // jQuery object for the submit button
    var submitButton = $('#bestBetSubmit');
    // jQuery object for hidden input context
    var context      = $('#frmContext');
    // jQuery object for application hidden input
    var application  = $('#frmApplication');

    $('#bestBetSubmit').prop('disabled', true);

    // name/description if there are no values already set
    if (obj.resource_type !== 'unknown') {
        if ($('#bestBetName').val() === "") {
            $('#bestBetName').val(obj.resource.title);
        }
        if ($('#bestBetDescription').val() === "") {
            $('#bestBetDescription').val(obj.resource.description);
        }
    }
    // Check if resource is a valid (provided by XAJAX function)
    if (obj.resource_valid === true) {
        $('#validation-resource-true').show();
        $('#validation-application-true').show();
        submitButton.prop('disabled', false);
        context.val(obj.context);
        application.val(obj.resource_type);
    } else {
        if (obj.context === 'internal') {
            $('#validation-resource-false').show();
            submitButton.prop('disabled', false);
            context.val(obj.context);
            if (obj.application_valid === true) {
                $('#validation-application-true').show();
                $('#bestBetURLHint').append($('<div class="alert alert-info">' + lmsg('search.admin.resource_not_found') + '</div>'));
            } else {
                $('#validation-application-false').show();
            }
        } else {
            $('#validation-resource-false').show();
            context.val(obj.context);
            submitButton.prop('disabled', false);
        }
    }
    // Show wether permissions are supported
    if (obj.resource_perms_supported === true) {
        $('#validation-permission-true').show();
    } else {
        $('#validation-permission-false').show();
    }
};

/**
 * Hide validation icons
 */
var hideValidation = function () {
    $('#validation-resource-true').hide();
    $('#validation-resource-false').hide();
    $('#validation-application-true').hide();
    $('#validation-application-false').hide();
    $('#validation-permission-true').hide();
    $('#validation-permission-false').hide();
    $('#bestBetURLHint').empty().parents('.control-group').removeClass('error');
};

/**
 * If the URL is an invalid format a notification is shown
 * Called from XAJAX function process_url [/intranet/search/xajax/best_bet.php]
 * @param {Object} error
 */
var urlInvalid = function (error) {
    $('#bestBetURLHint').append($('<div class="text-danger">' + error + '</div>')).parents('.control-group').addClass('error');
};

/**
 * Called from XAJAX function process_url [/intranet/search/xajax/request.php]
 * @param {Object} suggestions
 * @param {Bool} notify_user
 */
var matchedRequestDialog = function (suggestions, notify_user) {
    if ($('#form_group_request').not(':visible')) {
        $('#form_group_request').show();
    }
    suggestions = $.parseJSON(suggestions);
    $.each(suggestions, function (index, suggestion) {
        // Row to add to requests table
        var row = $('<tr></tr>');
        // Suggestions cell
        row.append($('<td></td>').html(suggestion.term));
        // Description cell
        row.append($('<td></td>').html(suggestion.description));
        // User cell
        row.append($('<td></td>').append($('<a></a>').html(suggestion.creator_name).prop('href', '/intranet/people/viewprofile.php?id=' + suggestion.creator)));
        // Notify cell
        row.append($('<td class="text-center"></td>').append($('<input type="checkbox" />').prop('checked', parseInt(notify_user, 10)).data('id', suggestion.id).on('change', function () {
            notifyRequestMatch(this);
        }).change()));
        // Delete cell
        row.append($('<td class="text-center"></td>').append($('<a href="javascript:void(0)" name="deleteRequestMatch"><ion-icon name="trash-outline"></ion-icon></a>').data('id', suggestion.id).on('click', function (event) {
            deleteRequestMatch(this);
        })));
        // Append to table
        $('#requests').append(row);
    });
};

/**
 * deleteRequestMatch
 * @param {Object} el
 */
var deleteRequestMatch = function (el) {
    // jQuery object of element that was clicked
    var element        = $(el);
    // Target row in the best bets list
    var row            = element.parent().parent();
    // SearchGroup form
    var frmSearchGroup = $('#frmSearchGroup');
    // Cancel button on form
    var cancelButton   = $('#cancelEdit');
    // Cell in row with either delete/restore
    var optionsTd      = element.parent();
    // Add hidden input to form
    frmSearchGroup.append($('<input type="hidden" name="frmDeleteRequestMatch[]" />').val(element.data('id')));
    // Create restore link
    var restoreLink = $('<a href="javascript:void(0)"><ion-icon name="arrow-undo-outline"></ion-icon></a>').on('click', function (event) {
        restoreRequestMatch(event);
    });
    // Add data-id if defined
    if (element.data('id') !== undefined) {
        restoreLink.data('id', element.data('id'));
    }
    // Add delete link to list
    $(optionsTd).append(restoreLink);
    // Hide tooltip
    element.tooltip('hide');
    // Remove restore link
    element.remove();
    // Strike through the row
    row.children('td').css('text-decoration', 'line-through');
    // Set cancel button data-modified to true
    cancelButton.data('modified', true);
    return false;
};

/**
 * restoreRequestMatch
 * @param {Object} event
 */
var restoreRequestMatch = function (e) {
    // Stop default event
    e.preventDefault();
    // jQuery object of element that was clicked
    var element        = $(e.currentTarget);
    // Target row in the terms list
    var row            = element.parent().parent();
    // SearchGroup form
    var frmSearchGroup = $('#frmSearchGroup');
    // Restore link in row
    var restoreLink    = element.parent();
    // Link in the row with the term value
    var termLink       = $(row).children().find('a').first();
    // Cell in row with either delete/restore
    var optionsTd      = element.parent();
    // Remove hidden input
    $('input:hidden[name="frmDeleteRequestMatch[]"][value=' + element.data('id') + ']').remove();
    // Create delete link
    var deleteLink = $('<a href="javascript:void(0)"><ion-icon name="trash-outline"></ion-icon></a>').on('click', function (event) {
        deleteSearchTerm(this);
    });
    // Add data-id if it's defined
    if (element.data('id') !== undefined) {
        deleteLink.data('id', element.data('id'));
    }
    // Add delete link to list
    $(optionsTd).append(deleteLink);
    // Hide tooltip
    element.tooltip('hide');
    // Remove restore link
    element.remove();
    // Strike through the row
    row.children('td').css('text-decoration', '');
    return false;
};

var notifyRequestMatch = function (el) {
    // jQuery object of element that was clicked
    var element        = $(el);
    // SearchGroup form
    var frmSearchGroup = $('#frmSearchGroup');
    // Add or remove a notification hidden input
    if (element.prop('checked')) {
        frmSearchGroup.append($('<input type="hidden" name="frmRequestNotifyUser[]" />').val(element.data('id')));
    } else {
        $('input:hidden[name="frmRequestNotifyUser[]"][value=' + element.data('id') + ']').remove();
    }
};

/**
 * Catch return being pressed
 * @param {Object} cb
 */
$.fn.returnPress = function (cb) {
    return this.each(function () {
        jQuery(this).keypress(function (e) {
            if ((e.which && e.which === 13) || (e.keyCode && e.keyCode === 13)) {
                cb();
                return false;
            } else {
                return true;
            }
        });
    });
};

/**
 * Clear all tooltips in url validation span
 */
var clearTooltip = function () {
    $('#bestBetURLValidation span[rel=tooltip]').each(function (i, e) {
        $(e).tooltip('hide');
    });
};

function initAdmin() {

    // Highlight admin menu item
    highlightAdminMenu();

    $('.reindexCheck').on('change', reindexCheck);

    // Check all reindex checkboxes
    $('.js-check-all').on('click', function () {
        $('.js-modules-table input[type=checkbox].js-reindex').prop('checked', true);
    });

    // Uncheck all reindex checkboxes
    $('.js-uncheck-all').on('click', function () {
        $('.js-modules-table input[type=checkbox].js-reindex').prop('checked', false);
    });

    // Sortable list in search Application Settings page
    $('[data-sortable="true"]').sortable({
        // handle : '.glyphicons glyphicons-list',
        items: 'tr',
        helper: function (e, tr) {
            var $originals = tr.children();
            var $helper    = tr.clone();
            $helper.children().each(function (index) {
                // Set helper cell sizes to match the original sizes
                $(this).width($originals.eq(index).width());
            });
            return $helper;
        }
    });
    $('[data-sortable="true"]').disableSelection();

    // 'Add Term' button
    $('#addTerm').on('click', function (e) {
        addSearchTerm();
    });
    // Return pressed while term input is focused
    $('#frmSearchTerm').returnPress(addSearchTerm);
    // 'Add Suggestions' button
    $('#addSuggestion').on('click', function () {
        addSuggestion();
    });
    // Return pressed while suggestion input is focused
    $('#frmSearchSuggestion').returnPress(addSuggestion);
    // Delete clicked in search admin groups list
    $('a[name="group_delete"]').on('click', function (event) {
        deleteSearchGroup(event);
    });
    // Delete request clicked in search admin request list
    $('a[name="request_delete"]').on('click', function (event) {
        deleteRequest(event);
    });
    // Delete request clicked in best bet admin request list
    $('a[name="deleteRequestMatch"]').on('click', function (event) {
        deleteRequestMatch(this);
    });
    // Notify checkbox changed in best bet admin request list
    $('input:checkbox[name="request_notify"]').on('change', function () {
        notifyRequestMatch(this);
    }).change();
    // Delete clicked in best bet admin term list
    $('a[name="term_delete"]').on('click', function () {
        deleteSearchTerm(this);
    });
    // Delete clicked in best bet admin suggestion list
    $('a[name="suggestion_delete"]').on('click', function () {
        deleteSearchSuggestion(this);
    });
    // Edit best bet link (name) clicked in best bets admin best bet list
    $(document).on('click', '.editBestBet', function () {
        var $this = $(this);
        $('#bestBetName').val($this.data('name'));
        $('#bestBetDescription').val($this.data('description'));
        $('#bestBetURL').val($this.data('url'));
        $('#frmBestBetId').val($this.data('id'));
        hideValidation();
        if ($(this).data('url') !== '') {
            $('#bestBetURL').trigger('keyup');
        }
    });
    // Delete clicked in best bets admin best bet list
    $('a[name="best_bet_delete"]').on('click', function () {
        $('#cancelEdit').data('modified', true);
        deleteSearchBestBet(this);
    });
    // Cancel button clicked in best bets admin
    $('#cancelEdit').on('click', function () {
        if ($('#cancelEdit').data('modified') === true) {
            return !!confirm('Modifications to search group will be lost, really cancel?');
        } else {
            return true;
        }
    });
    // URL input in best bet modal
    var url_timer;
    $('#bestBetURL').on('keyup blur paste', function () {
        var self = this;
        clearTimeout(url_timer);
        url_timer = setTimeout(function () {
            var val = $(self).val();

            clearTooltip();
            hideValidation();
            if (val.length !== 0) {
                xajax_process_url(val);
            }
        }, 1500);
    });

    // Best bets modal form
    if ($('#bestBetForm').length > 0) {
        $('#bestBetForm').validate({
            rules: {
                bestBetURL: "required",
                bestBetName: "required"
            },
            messages: {
                bestBetURL: lmsg('search.admin.invalid_url'),
                bestBetName: lmsg('search.admin.empty_title')
            },
            errorPlacement: function (error, element) {
                error.insertAfter(element).parents(".control-group").addClass('error');
            },
            errorClass: 'text-danger',
            submitHandler: function (form) {
                addBestBet();
            }
        });
    }

    // Search group form
    if ($('#frmSearchGroup').length > 0) {
        $('#frmSearchGroup').validate({
            rules: {
                frmGroupName: {
                    required: true,
                    maxlength: 255
                }
            }
        });
    }

    // Make best bets table sortable
    $("#bestBets tbody").sortable({
        handle: 'td:first',
        axis: 'y',
        helper: fixHelper,
        update: function (event, ui) {
            var order = $("#bestBets tbody").sortable('toArray');
            order     = JSON.stringify(order);
            var input = $('#frmBestBetOrder');
            input.val(order);
        }
    }).disableSelection();
}

function highlightAdminMenu() {
    var target = $("input[name='activeMenu']").val();
    $('[data-highlight="' + target + '"]').addClass('active');
}

function reindexCheck() {
    var remapCheckbox = $(this);
    remapCheckbox.closest('.js-checkbox-container').find('.js-reindex').prop('checked', checkb.prop('checked'));
    // note - This doesn't automatically change the cache clear checkbox. It is good that it survives remapping so should not be linked
}

        $(document).ready(function () {
            require(["moment"], function (moment) {
                $("#emptysearch_datatable table").on('draw.dt', function () {
                    // clear the select-all check-box
                    $("input.js-select-all-empty-searches").prop("checked", false);

                    // attach click event to select-all check-box {check/uncheck row check-boxes}
                    $("input.js-select-all-empty-searches").on("click", function () {
                        $("input.js-select-empty-search").prop("checked", this.checked);
                    });

                    // attach click event to select-all and row check-boxes {enable/disable Delete button}
                    $("input.js-select-empty-search").add("input.js-select-all-empty-searches").on("click", function () {
                        var enable = true;
                        $("input.js-select-empty-search").each(function () {
                            if (this.checked) {
                                return enable = false;
                            }
                        });
                        // enable/disable the Delete button
                        $("button[name='do_delete']").prop("disabled", enable);
                    });

                    // restore the Update button background colour
                    $("button[name='do_update']").removeClass('disabled').removeAttr('disabled');
                });

                // attach click event to Update button {redraw the table}
                $("button[name='do_update']").on("click", function () {
                    // grey-out the button while rows are being refreshed
                    $("button[name='do_update']").addClass('disabled').attr('disabled', 'disabled');

                    // initiate the refresh
                    $("#emptysearch_datatable table").DataTable().draw();
                });

                setDefaultDates();

                var date_from;
                var date_to;

                $('#download_csv_btn').on("click", function () {
                    window.location = "admin_topsearch_export_csv.php?date_to=" + date_to + "&date_from=" + date_from + "&keywords=" + $('#table-search').val();
                });

                function setDefaultDates() {
                    var today = new Date();
                    date_to   = moment(today).format(cla_locale.date_format);
                    date_from = moment(today).subtract(1, 'months').format(cla_locale.date_format);
                    $('#date_to').val(date_to);
                    $('#date_from').val(date_from);
                }

                $("#topsearch_datatable table").on('draw.dt', function () {
                    // restore the Update button background colour
                    $("button[name='filter_btn']").removeClass('disabled').removeAttr('disabled');
                    $("button[name='reset_btn']").removeClass('disabled').removeAttr('disabled');
                });

                // attach click event to Update button {redraw the table}
                $("button[name='filter_btn']").on("click", function () {
                    // grey-out the button while rows are being refreshed
                    $("button[name='filter_btn']").addClass('disabled').attr('disabled', 'disabled');
                    $("button[name='reset_btn']").addClass('disabled').attr('disabled', 'disabled');

                    // initiate the refresh
                    $("#topsearch_datatable table").DataTable().draw();
                });

                $("button[name='reset_btn']").on("click", function () {
                    // grey-out the button while rows are being refreshed
                    $("button[name='filter_btn']").addClass('disabled').attr('disabled', 'disabled');
                    $("button[name='reset_btn']").addClass('disabled').attr('disabled', 'disabled');

                    setDefaultDates();
                    // initiate the refresh
                    $("#topsearch_datatable table").DataTable().draw();
                });

                $('#topsearch_datatable table')
                    .on('preXhr.dt', function (e, settings, data) {
                        date_from    = $('#date_from').val();
                        date_to      = $('#date_to').val();
                        data.filters = [date_from, date_to];
                    });
            });
        });
