$ ->
  # let us know when javascript is running.
  console.log('Ready.')

  lastColumn = null
  ascending  = true

  tableHeaders = $('th')
  tableHeaders.click (e) ->
    column = $(this).index()
    table = $(this).closest('table')

    if column is lastColumn
      ascending = not ascending
    else
      ascending = true

    lastColumn = column
    sortTable(table, column, ascending)

sortTable = (table, column, ascending) ->
  rows = table.find('tbody tr').get()

  compareFunction = (a, b) ->
    res = a.cells[column].textContent.localeCompare b.cells[column].textContent
    if ascending then res else -res

  rows.sort compareFunction
  $(rows).detach().appendTo(table.find('tbody'))
  return

averageResults = (results, decimals = 2) ->
  avgScore = 0
  minScore = Infinity
  maxScore = -Infinity

  factor = (10 ^ decimals)

  for result in results
    avgScore += result.avg_score
    minScore = Math.min(minScore, result.min_score)
    maxScore = Math.max(maxScore, result.max_score)

  return {
    avgScore: Math.round((avgScore / results.length) * factor) / factor,
    minScore: minScore,
    maxScore: maxScore,
  }
