extends application

block vars
  - var bodyClass="index posts topics"

block main
  if (user && user.id === 0)
    include login.jade

  else

    if (!posts || posts.length === 0)
      | No threads. Why not contribute to the forum?

    else
      .topics
        each post in posts
          include posts/topic
    form.new.is-hidden
      .input#newtopic-title
        input(class="input-input input-text input-title" type="text" placeholder="Title")
      .input.textarea#newtopic-content
        textarea(class="input-input input-textarea input-body" placeholder="Body")
      button(class="input-submit" type="submit")
        | Submit

block script
  //- index-specific <script> tag(s) go here:
  script(src="/javascripts/emoji.js")
  script(src="/templates/post/topic.js")
  script.
    forum.replyCount = 0;

    var checkUnread = function() {
      var $topics = $('.atom');

      $topics.each(function(index, element) {
        var $topic = $(this);
        var topicTimestamp = parseInt(+new Date($topic.find('[data-timestamp]')[0].dataset.timestamp), 10);
        var lastVisitedTimestamp = parseInt(forum.constants.lastVisited[this.getAttribute('data-id')] || 0, 10);

        if (topicTimestamp > lastVisitedTimestamp) {
          $topic.addClass('is-unread');
        } else {
          $topic.removeClass('is-unread');
        }
      });
    }

    lastVisitedPromise.then(function() {
      checkUnread();
    });

    var updateThreadMetadata = function(response){
      var $topicNode = $('.atom').filter('[data-id=' + response.parent + ']');

      $topicNode.find('.atom-replies-count').text(parseInt($topicNode.find('.atom-replies-count').text()) + 1);

      $topicNode.find('.distance').text(moment(response.created_at).fromNow())

      $topicNode.find('.atom-username').text(response.user.name);

      $topicNode.find('[data-timestamp]')[0].dataset.timestamp = response.created_at;

      checkUnread();
    }

    socket.on('post', function(response){
      if (forum.focus === false) {
        forum.replyCount++;
        favicon.badge(forum.replyCount);
      }

      if (typeof response.parent !== "undefined") {
        return updateThreadMetadata(response);
      }

      var locals = {};
      locals.post = response;
      locals.moment = moment;
      locals.marked = marked;
      locals.user = forum.constants.user;
      locals.post.lastreply = {};
      locals.post.lastreply.user = forum.constants.user;
      locals.post.lastreply.created_at = new Date();
      locals.post.replycount = 0;
      locals.post.children = [];
      locals.getPostDate = function(post){ return post.created_at; };

      $(anonymous(locals)).appendTo('.root .topics');

      embedTwitter($('.atom:last a'));
      embedInstagram($('.atom:last a'));
      embedYouTube($('.atom:last a'));
      embedSoundCloud($('.atom:last a'));
      embedVine($('.atom:last a'));

      $('.atom .distance').text(function(){
        var postTime = moment(this.dataset.timestamp);
        if (postTime.isSame(moment(), 'day') && postTime.fromNow() !== $(this).text()) {
          return postTime.fromNow();
        }
      });

      checkUnread();
    });


    $('[href="#newtopic-content"]').on('click', function(event){
      event.preventDefault();
      $('form.new').removeClass('is-hidden');
      $('#newtopic-title input').trigger('focus');
    });

    $('form.new').on('submit', function(event){
      if ($.trim($(this).find('.input-title').val()).length < 1) {
        return false;
      }
      socket.emit('post', {
        title: $(this).find('.input-title').val(),
        body: emoji.replace_unified($(this).find('.input-body').val()),
        user: {
          id: forum.constants.user.id,
          name: forum.constants.user.name
        }
      }, function(){
        $('form.new, .action.new').remove();
      });

      event.preventDefault();
    });

    $('#markallread').on('click', function(event) {
      event.preventDefault();

      socket.emit('markallread', {
        user: {
          id: forum.constants.user.id,
          name: forum.constants.user.name
        }
      });

      $('.atom').removeClass('is-unread');
    });

    $(window).focus(function(){
      forum.focus = true;
      forum.replyCount = 0;
      favicon.reset();
    });

    $(window).blur(function(){
      forum.focus = false;
    });
