$(document).ready(function() {
  var preview = $('#preview');
  var usertext = preview.find('.usertext');
  var scroller = document.body.parentNode;
  var timeout;
  var needs_update = '';
  var delay = 500;

  function updatePreview(cont) {
    var textarea = $('#id_text').get(0);
    $.post('/markup/preview/', {
        filter: textarea.form.text_filter.value,
        text: textarea.value,
      },
      function(value, status) {
        if (status == 'success' && value) {
          preview.toggle(!!textarea.value);
          var offset = scroller.scrollHeight - scroller.scrollTop;
          usertext.html(value);
          scroller.scrollTop = scroller.scrollHeight - offset;
          usertext.find('pre code').each(function() {
            hljs.highlightBlock(this);
          });
        }
        cont();
      },
      'html'
    );
  }

  function scheduleUpdate(source) {
    if (source.nodeName == 'TEXTAREA') {
      if (needs_update == source.value)
        return;
      var textarea = source;
    } else {
      var textarea = $('#id_text').get(0);
    }
    needs_update = textarea.value;
    clearTimeout(timeout);
    timeout = setTimeout(function() {
      clearTimeout(timeout);
      updatePreview(function() {
        preview.removeClass('updating');
        if (needs_update != textarea.value && !timeout)
          scheduleUpdate(textarea);
      });
    }, delay);
    preview.show();
    preview.addClass('updating');
  }

  $('#id_text').keyup(function(e) {
    scheduleUpdate(this);
  });

  $('#id_text_filter').change(function(e) {
    scheduleUpdate(this);
  });
});
