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');
    }
  });
  $('#listing input[type=checkbox]').on('change', function() {
    if ($(this).is(':checked')) {
      if ($(this).is('[value=_all]')) {
        $(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('[value=_all]')) {
        $(this).parents('table').find('tbody td.select input').prop('checked', false);
        $(this).parents('table').find('tbody tr').removeClass('checked');
      } else {
        $(this).parents('tr').removeClass('checked');
        $('#listing input[type=checkbox][value=_all]').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);
      });
      if (window.history) {
        window.history.replaceState(null, null, pathname + '?' + listing_settings.qs);
      }
      /* 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>');
    $('#columns-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: $('#columns-settings').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) {
                  var checked = $(elem).prop('checked');
                  $('form#listing-settings input[name="' + $(elem).attr('name') + '"]').attr('checked', checked);
                  $('form#listing-settings input[name="' + $(elem).attr('name') + '"]').prop('checked', checked);
                });
                $(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;
  });

  $('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;
  });

  /* 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();
});
