script(src="/templates/post/post.js")
script(src="/javascripts/emoji.js")
script.
  emoji.colons_mode = true;

.new
  form
    .input#reply
      input(class="input-input input-text" type="text" placeholder="Type here...")
      .toggle
        | {...}
    .input.is-hidden.textarea
      textarea(class="input-input input-textarea" placeholder="Type here...")
      .toggle
        | { / }
      button(class="input-submit" type="submit")
        | Submit

  if (user && user.id !== 0)
    h2(style="font-weight: normal;")
      a(href='/' style="text-transform: uppercase;") The Forum
      if (bodyClass.match('topics') === null)
        | &nbsp;&mdash;&nbsp;
        = topic.title

  script.
    forum.replyCount = 0;

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

      $posts.each(function(index, element) {
        var $post = $(this);
        var postTimestamp = parseInt(+new Date($post.find('[data-timestamp]').data('timestamp')), 10);
        var lastVisitedTimestamp = parseInt(forum.constants.lastVisited[forum.constants.parent] || 0, 10);

        if (postTimestamp > lastVisitedTimestamp) {
          $post.addClass('is-unread');
        }
      });
    }

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

    socket.on('destroy', function(response){
      $('[data-id=' + response.id + ']').remove();
    });

    socket.on('edit', function(response){
      var locals = {};
      locals.post = response;
      locals.moment = moment;
      locals.marked = marked;
      locals.user = forum.constants.user;
      locals.post.created_at = '';

      $('[data-id=' + response.id + ']').replaceWith(anonymous(locals));

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

    socket.on('post', function(response){
      var locals = {};
      locals.post = response;
      locals.moment = moment;
      locals.marked = marked;
      locals.user = forum.constants.user;

      if (response.parent !== forum.constants.parent) {
        return false;
      }

      if (forum.focus === false) {
        forum.replyCount++;
        favicon.badge(forum.replyCount);
      }

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

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

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

      checkUnread();
    });

    $('body').on('click', '.atom-actions-action--destroy', function(event){
      event.preventDefault();

      socket.emit('destroy', {
        id: $(this).closest('.atom').data('id'),
        user: {
          id: forum.constants.user.id,
          name: forum.constants.user.name
        }
      });
    });

    $('body').on('click touchstart', '.atom-actions-action--quote', function(event){
      event.preventDefault();
      var quoted = $.ajax({
        url:'/post/' + $(this).closest('.atom').data('id'),
        dataType: "json",
        success: function(data){
          var newBody;
          $('#reply.input').addClass('is-hidden');
          $('.input.textarea').removeClass('is-hidden');

          newBody = data.body.replace(/^/, "> ").replace(/\n/g, "\n> ");
          $('.input.textarea textarea').val('> ' +
            data.user.name + ' wrote: ' + '\n\n' + newBody + '\n\n'
          );
          $('.input.textarea textarea').trigger('focus');
        }
      });
    });

    $('body').on('submit', '.atom form.edit', function(event){
      var $input = $(this).find('textarea');

      socket.emit('edit', {
        body: emoji.replace_unified($input.val()),
        id: $(this).closest('.atom').data('id'),
        user: {
          id: forum.constants.user.id,
          name: forum.constants.user.name
        }
      });

      event.preventDefault();
    });

    $('.new form').on('submit', function(event){
      var self = this;
      var $input = $(this).find('.input').not('.is-hidden');

      if ($input.find('.input-input').val() === "") return false;

      event.preventDefault();
      $.ajax({
        type: 'POST',
        contentType: 'application/json;charset=UTF-8',
        dataType: 'json',
        url: '/api/posts',
        data: JSON.stringify({
          parent: forum.constants.parent,
          body: emoji.replace_unified($input.find('.input-input').val())
        }),
        beforeSend: function() {
          $input.find('.input-input').attr('disabled', true);
          $input.find('.input-submit').attr('disabled', true);
          $input.find('.input-input').val('Submitting Post...');
        },
        success: function(result) {
          $(self).find('.input-input').val('');
          $(self).find('> .input').not('.is-hidden').find('.input-input').trigger('focus');

          localStorage.setItem(forum.constants.topicStorageVisitedID, +new Date());
        },
        complete: function() {
          $input.find('.input-input').attr('disabled', false);
          $input.find('.input-submit').attr('disabled', false);
          $input.find('.input-input').val('');
          $(self).find('> .input').not('.is-hidden').find('.input-input').trigger('focus');
        }
      });
    });

    $('textarea, input').on('keyup', function(event){
      $(this).closest('.input').siblings('.input').find('.input-input').val($(this).val());
    });

    $('.input .toggle').on('click', function(){
      $(this).closest('.input').toggleClass('is-hidden');
      $(this).closest('.input').siblings('.input').toggleClass('is-hidden');
    });

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

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

