function prepare_page_links() {
  $('#page-links a').click(function() {
    $('form#listing-settings input[name="offset"]').val($(this).data('offset'));
    $('form#listing-settings input[name="limit"]').val($(this).data('limit'));
    refresh_table();
    return false;
  });
}

function prepare_row_links() {
  $('#listing tbody tr a').on('click mouseup', function(event) {
    event.stopPropagation();
  });
  $('#listing tbody tr').on('mouseup', function(event) {
    var $target = $(event.target);
    if ($target.is('input[type=checkbox]')) {
      return false;
    }
    if ($target.is('td.select')) {
      $target.find('input').click();
      return false;
    }
    var data_link = $(this).data('link');
    if (data_link) {
      if (data_link.indexOf('http://') == -1 && data_link.indexOf('https://') == -1) {
        data_link = window.location.pathname + data_link;
      }
      if (event.which == 2) {
        window.open(data_link, '_blank');
      } else {
        window.location = data_link;
      }
      return false;
    }
  });
  if ($('#listing tbody input[type=checkbox]:checked').length == 0) {
    $('form#multi-actions div.buttons').hide();
  } else {
    $('form#multi-actions div.buttons').show();
  }
  $('#listing tbody input[type=checkbox]').each(function() {
    if ($(this).is(':checked')) {
      $(this).parents('tr').addClass('checked');
    } else {
      $(this).parents('tr').removeClass('checked');
    }
  });
  if ($('#page-links .pages a').length < 2) {
    $('#info-all-rows').hide();
  }
  $('#listing input[type=checkbox]').on('change', function() {
    if ($(this).is(':checked')) {
      if ($(this).is('#top-select')) {
        $(this).parents('table').find('tbody td.select input').prop('checked', true);
        $(this).parents('table').find('tbody tr').addClass('checked');
      } else {
        $(this).parents('tr').addClass('checked');
      }
    } else {
      if ($(this).is('#top-select')) {
        $(this).parents('table').find('tbody td.select input').prop('checked', false);
        $(this).parents('table').find('tbody tr').removeClass('checked');
      } else if ($(this).is('[value=_all]')) {
        // do nothing particular when unchecking "all"
      } else {
        $(this).parents('tr').removeClass('checked');
        $('#listing input[type=checkbox][value=_all]').prop('checked', false);
        $('#listing input[type=checkbox]#top-select').prop('checked', false);
      }
    }
    if ($('#listing tbody input[type=checkbox]:checked').length == 0) {
      $('form#multi-actions div.buttons').hide();
      return;
    } else {
      $('form#multi-actions div.buttons button').each(function(idx, elem) {
        var visible = false;
        for (var key in $(elem).first().data()) {
          if (key == 'visible_for_all') {
            visible = true;
            break;
          }
          if ($('input[type=checkbox][data-is_' + key.substr(12) + ']:checked').length) {
            visible = true;
            break;
          }
        }
        if (visible) {
          $(elem).parents('div.widget').show();
        } else {
          $(elem).parents('div.widget').hide();
        }
      });
      $('form#multi-actions div.buttons').show();
    }
  });
}

function prepare_column_headers() {
  if ($('input[name="order_by"]').length == 0) {
    /* if we don't have an order_by field, that means we do not support server
     * side sorting, so we abort here */
    return;
  }
  var current_key = $('input[name="order_by"]').val();
  var sort_key = null;
  var reversed = true;
  if (current_key[0] === '-') {
    sort_key = current_key.substring(1);
    reversed = true;
  } else {
    sort_key = current_key;
    reversed = false;
  }
  if (reversed) {
    $('#listing thead th[data-field-sort-key="' + sort_key + '"]').addClass('headerSortUp');
  } else {
    $('#listing thead th[data-field-sort-key="' + sort_key + '"]').addClass('headerSortDown');
  }
  $('#listing thead th[data-field-sort-key]').addClass('header').click(function() {
    new_key = $(this).data('field-sort-key');
    if (current_key === sort_key) {
      if (reversed === false) {
        new_key = '-' + new_key
      }
    }
    $('input[name="order_by"]').val(new_key);
    refresh_table();
  });
}

function autorefresh_table() {
  if ($('#multi-actions input:checked').length) {
    // disable autorefresh when multiselection is enabled
    return;
  }
  $(document).trigger('backoffice-filter-change',
      {qs: $('form#listing-settings').serialize(), auto: true});
}

function refresh_table() {
  $(document).trigger('backoffice-filter-change',
      {qs: $('form#listing-settings').serialize(), auto: false});
}

$(document).on('backoffice-filter-change', function(event, listing_settings) {
  /* makes sure it doesn't start with a double slash */
  var pathname = window.location.pathname.replace(/^\/+/, '/');

  $.ajax({
    url: pathname + '?ajax=true&' + listing_settings.qs,
    beforeSend: function() { $('#more-user-links, #listing, #statistics').addClass('activity'); },
    complete: function() { $('#more-user-links, #listing, #statistics').removeClass('activity'); },
    success: function(html) {
      $('#page-links').remove();
      $('#listing').replaceWith(html);
      $('#statistics').replaceWith(html);
      if (typeof(wcs_draw_graphs) !== 'undefined') {
        wcs_draw_graphs();
      }
      prepare_page_links();
      prepare_row_links();
      prepare_column_headers();
      $('a[data-base-href]').each(function(idx, elem) {
        $(elem).attr('href', $(elem).data('base-href') + '?' + listing_settings.qs);
      });
      $('#multi-actions').attr('action', '?' + listing_settings.qs);
      if (window.history) {
        window.history.replaceState(null, null, pathname + '?' + listing_settings.qs);
      }
      /* refresh dynamic filters */
      $('[data-refresh-options]').each(function(idx, elem) {
        var $select = $(elem);
        var current_value = $select.val();
        var filter_path = pathname + 'filter-options?filter_field_id=' + $(elem).data('refresh-options') + '&' + listing_settings.qs;
        $.ajax({
          url: filter_path,
          success: function(data) {
            $select.empty();
            var $option = $('<option></option>', {value: ''});
            $option.appendTo($select);
            for (var i=0; i<data.data.length; i++) {
              var $option = $('<option></option>', {value: data.data[i].id, text: data.data[i].text});
              if (data.data[i].id == current_value) {
                $option.attr('selected', 'selected');
              }
              $option.appendTo($select);
            }
          }
        });
      });

      /* makes sure activity and disabled-during-submit are removed */
      $('#more-user-links, #listing, #statistics').removeClass('activity');
      $('form').removeClass('disabled-during-submit');
    }
  });
});

$(function() {
  var must_reload_page = false;

  /* column settings */
  $('#columns-settings').click(function() {
    var dialog = $('<form>');
    var $dialog_filter = $('#columns-filter').clone().attr('id', null);
    $dialog_filter.appendTo(dialog);
    $dialog_filter.sortable({handle: '.handle'})
    $(dialog).dialog({
            modal: true,
            resizable: false,
            title: $('#columns-settings').attr('title'),
            width: '30em'});
    $(dialog).dialog('option', 'buttons', [
            {text: $('form#listing-settings button.refresh').text(),
             click: function() {
                var $container = $('#columns-filter').parent();
                $('#columns-filter').remove();
                $dialog_filter.attr('id', 'columns-filter');
                $dialog_filter.appendTo($container);
                $('[name="columns-order"]').val($('#columns-filter input:checked').map(function() { return $(this).attr('name'); }).get().join());
                $(this).dialog('close');
                $('form#listing-settings').submit();
              }
            }]);
    return false;
  });

  /* filter settings */
  $('#filter-settings').click(function() {
    var dialog = $('<form>');
    $('#field-filter').clone().appendTo(dialog);
    $(dialog).find('input').each(function(idx, elem) {
      $(this).attr('id', 'dlg-' + $(this).attr('id'));
    });
    $(dialog).find('label').each(function(idx, elem) {
      $(this).attr('for', 'dlg-' + $(this).attr('for'));
    });
    $(dialog).dialog({
            modal: true,
            resizable: false,
            title: $('#filter-settings').parents('h3').find('span:first-child').text(),
            width: '30em'});
    $(dialog).dialog('option', 'buttons', [
            {text: $('form#listing-settings button.refresh').text(),
             click: function() {
                $(this).find('input[type="checkbox"]').each(function(idx, elem) {
                $('form#listing-settings input[name="' + $(elem).attr('name') + '"]').prop('checked',
                        $(elem).prop('checked'));
                });
                $(this).dialog('close');
                must_reload_page = true;
                $('form#listing-settings').submit();
              }
            }]);
    return false;
  });

  /* set filter options from server (select2) */
  $('[data-remote-options]').each(function(idx, elem) {
    var filter_field_id = $(elem).data('remote-options');
    var options = {
      language: {
        errorLoading: function() { return WCS_I18N.s2_errorloading; },
        noResults: function () { return WCS_I18N.s2_nomatches; },
        inputTooShort: function (input, min) { return WCS_I18N.s2_tooshort; },
        loadingMore: function () { return WCS_I18N.s2_loadmore; },
        searching: function () { return WCS_I18N.s2_searching; },
      },
      placeholder: '',
      allowClear: true,
      minimumInputLength: 1,
      ajax: {
        url: function() {
          var pathname = window.location.pathname.replace(/^\/+/, '/');
          var filter_settings = $('form#listing-settings').serialize();
          return pathname + 'filter-options?filter_field_id=' + filter_field_id + '&' + filter_settings;
        },
        dataType: 'json',
        data: function(params) {
          var query = {
            _search: params.term,
          }
          return query;
        },
        processResults: function (data, params) {
          return {results: data.data};
        },
      },
    };
    $(elem).select2(options);
  });

  $('button.pdf').click(function() {
    if (window.location.href.indexOf('?') == -1) {
      window.location = window.location + '?pdf=on';
    } else {
      window.location = window.location + '&pdf=on';
    }
    return false;
  });

  $('button#save-view').on('click', function() {
    var div_dialog = $('<div>');
    $('#save-custom-view').clone().attr('hidden', null).appendTo(div_dialog);
    $(div_dialog).find('[name=qs]').val($('form#listing-settings').serialize());
    $(div_dialog).find('.buttons').hide();
    var dialog = $(div_dialog).dialog({
            modal: true,
            resizable: false,
            title: $(this).text(),
            width: 'auto',
            buttons: [
              {text: $(div_dialog).find('.cancel-button').text(),
               class: 'cancel-button',
               click: function() { $(this).dialog('close'); }
              },
              {text: $(div_dialog).find('.submit-button').text(),
               class: 'submit-button',
               click: function() { $(div_dialog).find('.submit-button button').click(); return false; }
              }
            ]
    });
    return false;
  });

  /* automatically refresh on filter change */
  $('form#listing-settings select').change(function() {
    $('form#listing-settings').submit();
  });
  /* partial table refresh */
  $('form#listing-settings').submit(function(event) {
    $('form#listing-settings input[name="offset"]').val('0');
    if (must_reload_page) {
      return true;
    }
    event.preventDefault();
    $(document).trigger('backoffice-filter-change', {qs: $('form#listing-settings').serialize()});
    return false;
  });

  /* refresh every 30 seconds (idle_id) after any user activity
   * on inactivity for more than 5 minutes (longidle_id), stop refreshing (clear idle_id)
   */
  if ($('#statistics').length == 0) {
    var idle_id = null;
    var longidle_id = null;
    $(window).on('mousemove keydown mousedown touchstart', function() {
      /* if refresh timer exists, clear it */
      if (idle_id) window.clearInterval(idle_id);
      /* if stop refreshing timer exists, clear it */
      if (longidle_id) window.clearTimeout(longidle_id);
      /* launch timer to refresh every 30 seconds */
      idle_id = setInterval(autorefresh_table, 30000);
      /* launch timer to stop refreshing after 5 minutes idle */
      longidle_id = setTimeout(function () {
          if (idle_id) idle_id = window.clearInterval(idle_id);
          longidle_id = undefined;
      }, 300 * 1000);
    });
  }

  prepare_page_links();
  prepare_row_links();
  prepare_column_headers();
});
