 
     @resizeToSaved()
 
-    $('nav.app .clear a').live 'click', (e) =>
+    $("nav.app .clear a").live "click", (e) =>
       e.preventDefault()
       if confirm "You will lose all your received messages.\n\nAre you sure you want to clear all messages?"
         $.ajax
-          url: '/messages'
-          type: 'DELETE'
+          url: "/messages"
+          type: "DELETE"
           success: =>
             @unselectMessage()
           error: ->
-            alert 'Error while clearing all messages.'
-
-    $('nav.app .quit a').live 'click', (e) =>
+            alert "Error while clearing all messages."
+
+    $("nav.app .quit a").live "click", (e) =>
       e.preventDefault()
       if confirm "You will lose all your received messages.\n\nAre you sure you want to quit?"
         $.ajax
-          type: 'DELETE'
+          type: "DELETE"
           success: ->
-            location.replace $('body > header h1 a').attr('href')
+            location.replace $("body > header h1 a").attr("href")
           error: ->
-            alert 'Error while quitting.'
-
-    key 'up', =>
+            alert "Error while quitting."
+
+    key "up", =>
       if @selectedMessage()
-        @loadMessage $('#messages tr.selected').prev().data('message-id')
+        @loadMessage $("#messages tr.selected").prev().data("message-id")
       else
-        @loadMessage $('#messages tbody tr[data-message-id]:first').data('message-id')
-      false
-
-    key 'down', =>
+        @loadMessage $("#messages tbody tr[data-message-id]:first").data("message-id")
+      false
+
+    key "down", =>
       if @selectedMessage()
-        @loadMessage $('#messages tr.selected').next().data('message-id')
+        @loadMessage $("#messages tr.selected").next().data("message-id")
       else
-        @loadMessage $('#messages tbody tr[data-message-id]:first').data('message-id')
-      false
-
-    key '⌘+up, ctrl+up', =>
-      @loadMessage $('#messages tbody tr[data-message-id]:first').data('message-id')
-      false
-
-    key '⌘+down, ctrl+down', =>
-      @loadMessage $('#messages tbody tr[data-message-id]:last').data('message-id')
-      false
-
-    key 'left', =>
+        @loadMessage $("#messages tbody tr[data-message-id]:first").data("message-id")
+      false
+
+    key "⌘+up, ctrl+up", =>
+      @loadMessage $("#messages tbody tr[data-message-id]:first").data("message-id")
+      false
+
+    key "⌘+down, ctrl+down", =>
+      @loadMessage $("#messages tbody tr[data-message-id]:last").data("message-id")
+      false
+
+    key "left", =>
       @openTab @previousTab()
       false
 
-    key 'right', =>
+    key "right", =>
       @openTab @nextTab()
       false
 
-    key 'backspace, delete', =>
+    key "backspace, delete", =>
       id = @selectedMessage()
       if id?
         $.ajax
-          url: '/messages/' + id
-          type: 'DELETE'
+          url: "/messages/" + id
+          type: "DELETE"
           success: =>
-            messageRow = $("#messages tbody tr[data-message-id='#{id}']")
-            switchTo = messageRow.next().data('message-id') || messageRow.prev().data('message-id')
+            messageRow = $("""#messages tbody tr[data-message-id="#{id}"]""")
+            switchTo = messageRow.next().data("message-id") || messageRow.prev().data("message-id")
             messageRow.remove()
             if switchTo
               @loadMessage switchTo

    date &&= date.toString("dddd, d MMM yyyy h:mm:ss tt")

  messagesCount: ->
    $('#messages tr').length - 1

  tabs: ->
    $('#message ul').children('.tab')

  getTab: (i) =>
    $(@tabs()[i])

  selectedTab: =>
    @tabs().index($('#message li.tab.selected'))

  openTab: (i) =>
    @getTab(i).children('a').click()

  previousTab: (tab)=>
    i = if tab || tab is 0 then tab else @selectedTab() - 1

    if @getTab(i).is(":visible")
      i
    else
      @nextTab(i + 1)

  haveMessage: (message) ->
    message = message.id if message.id?
    $("""#messages tbody tr[data-message-id="#{message}"]""").length > 0

  selectedMessage: ->
    $("#messages tr.selected").data "message-id"

  searchMessages: (query) ->
    selector = (":icontains('#{token}')" for token in query.split /\s+/).join("")
    $rows = $("#messages tbody tr")
    $rows.not(selector).hide()
    $rows.filter(selector).show()

  clearSearch: ->
    $("#messages tbody tr").show()

  addMessage: (message) ->
    $("<tr />").attr("data-message-id", message.id.toString())
      .append($("<td/>").text(message.sender or "No sender").toggleClass("blank", !message.sender))
      .append($("<td/>").text((message.recipients || []).join(", ") or "No receipients").toggleClass("blank", !message.recipients.length))
      .append($("<td/>").text(message.subject or "No subject").toggleClass("blank", !message.subject))
      .append($("<td/>").text(@formatDate(message.created_at)))
      .prependTo($("#messages tbody"))

  scrollToRow: (row) ->
    relativePosition = row.offset().top - $("#messages").offset().top
    if relativePosition < 0
      $("#messages").scrollTop($("#messages").scrollTop() + relativePosition - 20)
    else
      overflow = relativePosition + row.height() - $("#messages").height()
      if overflow > 0
        $("#messages").scrollTop($("#messages").scrollTop() + overflow + 20)

  unselectMessage: ->
    $("#messages tbody, #message .metadata dd").empty()
    $("#message .metadata .attachments").hide()
    $("#message iframe").attr("src", "about:blank")
    null

  loadMessage: (id) ->
    id = id.id if id?.id?
    id ||= $("#messages tr.selected").attr "data-message-id"

    if id?
      $("#messages tbody tr:not([data-message-id='#{id}'])").removeClass("selected")
      messageRow = $("#messages tbody tr[data-message-id='#{id}']")
      messageRow.addClass("selected")
      @scrollToRow(messageRow)

      $.getJSON "/messages/#{id}.json", (message) =>
        $("#message .metadata dd.created_at").text(@formatDate message.created_at)
        $("#message .metadata dd.from").text(message.sender)
        $("#message .metadata dd.to").text((message.recipients || []).join(", "))
        $("#message .metadata dd.subject").text(message.subject)
        $("#message .views .tab.format").each (i, el) ->
          $el = $(el)
          format = $el.attr("data-message-format")
          if $.inArray(format, message.formats) >= 0
            $el.find("a").attr("href", "/messages/#{id}.#{format}")
            $el.show()
          else
            $el.hide()

        if $("#message .views .tab.selected:not(:visible)").length
          $("#message .views .tab.selected").removeClass("selected")
          $("#message .views .tab:visible:first").addClass("selected")

        if message.attachments.length
          $ul = $("<ul/>").appendTo($("#message .metadata dd.attachments").empty())

          $.each message.attachments, (i, attachment) ->
            $ul.append($("<li>").append($("<a>").attr("href", attachment["href"]).addClass(attachment["type"].split("/", 1)[0]).addClass(attachment["type"].replace("/", "-")).text(attachment["filename"])))
          $("#message .metadata .attachments").show()
        else
          $("#message .metadata .attachments").hide()

        $("#message .views .download a").attr("href", "/messages/#{id}.eml")

        if $("#message .views .tab.analysis.selected").length
          @loadMessageAnalysis()
        else
          @loadMessageBody()
