define [
  'prism'
  'jade!templates/index'
  'jade!templates/json'
], (Prism, IndexTemplate, JsonTemplate) ->

  class IndexView extends Backbone.View

    el: "#{{ project }}"
    page: 1

    events:
      'click button#more': 'nextPage'

    hnAPI: ->
      "http://aitchennjuzapi.herokuapp.com/hacker/news/#{@page++}"

    initialize: (@options) ->
      @debouncedPreview =  _.debounce @previewJSON, 200
      @hnAPIGithub = 'http://github.com/geekjuice/aitchennjuzapi'

    render: ->
      content = """
        Hacker News API from <a href="#{@hnAPIGithub}" target="_blank">AitchEnNjuzAPI</a>
      """
      @$el.html IndexTemplate(content: content)
      @renderJson()
      @

    renderJson: ->
      $preview = @$('#preview')
      $preview.html("""
        <pre class="preview centered">Fetching Hacker News data...</pre>
      """).addClass('loaded')

      $.getJSON @hnAPI(), (resp) =>
        @previewJSON(resp.data)

    cleanJSON: (str) ->
      str.replace(/\"([^(\")"]+)\":/g,"$1:")

    previewJSON: (data) ->
      fadeDelay = 300
      $preview = @$('#preview')
      tmpl = ''

      if not _.isEmpty(data)
        json = @cleanJSON JSON.stringify(data, null, 4)
        tmpl = JsonTemplate(json: json, nextPage: @page)

      $preview.removeClass('loaded')
      setTimeout =>
        $preview.html(tmpl).addClass('loaded')
        Prism.highlightAll()
      , fadeDelay

    nextPage: (e) =>
      $body = $('body')
      scrollIncrement = ($body.scrollTop() / 60) * (1000 / 200)

      do scrollToTop = =>
        scroll = $body.scrollTop()
        if scroll > 0
          $body.scrollTop(scroll - scrollIncrement)
          requestAnimationFrame(scrollToTop)
        else
          @renderJson()
