$(document).ready(function() {
  var token = $('body').data('token');

  if ($('#description').length > 0) {
    CKEDITOR.replace('description', {
      filebrowserBrowseUrl: 'index.php?route=common/filemanager&token=' + token,
      filebrowserImageBrowseUrl: 'index.php?route=common/filemanager&token=' + token,
      filebrowserFlashBrowseUrl: 'index.php?route=common/filemanager&token=' + token,
      filebrowserUploadUrl: 'index.php?route=common/filemanager&token=' + token,
      filebrowserImageUploadUrl: 'index.php?route=common/filemanager&token=' + token,
      filebrowserFlashUploadUrl: 'index.php?route=common/filemanager&token=' + token
    });
  }

  function filter() {
    url = 'index.php?route=catalog/information&token=' + token;
    var filter_name = $('input[name=\'filter_name\']').attr('value');
    if (filter_name) {
      url += '&filter_name=' + encodeURIComponent(filter_name);
    }
    location = url;
  }

  $('.js-btn-filter').on('click', function(event) {
    event.preventDefault();
    filter();
  });

  $('input[name=\'filter_name\']').on('keyup',  function(event) {
    if (event.keyCode == 13) {
      filter();
    }
  });

  $('input[name=\'filter_name\']').autocomplete({
    delay: 500,
    source: function(request, response) {
      $.ajax({
        url: 'index.php?route=catalog/information/autocomplete&token=' + token + '&filter_name=' +  encodeURIComponent(request.term),
        dataType: 'json',
        success: function(json) {
          response($.map(json, function(item) {
            return {
              label: item.title,
              value: item.information_id
            }
          }));
        }
      });
    },
    select: function(event, ui) {
      $('input[name=\'filter_name\']').val(ui.item.label);
      return false;
    },
    focus: function(event, ui) {
      return false;
    }
  });

});
