// Based on http://www.germanforblack.com/javascript-sleeping-keypress-delays-and-bashing-bad-articles
Function.prototype.onlyEvery = function (millisecond_delay) {
  if (!window.only_every_func)
  {
    var function_object = this;
    window.only_every_func = setTimeout(function() { function_object(); window.only_every_func = null}, millisecond_delay);
   }
};
// jQuery extensions
jQuery.prototype.any = function(callback) { 
  return (this.filter(callback).length > 0)
}

$(function () {
  var form = $('#complete-stage-form');
  var input_elements = $('#completed_stage_max, #completed_stage_comment')

  function fetchPreview() {
    jQuery.ajax({
      data: form.serialize(),
      url: '/twitter_preview',
      timeout: 2000,
      error: function() {
        console.log("Failed to submit");
      },
      success: function(r) { 
        $('#twitter-preview').text(r);
      }
    })
  }

  input_elements.keyup(function () {
    fetchPreview.onlyEvery(400);
  });
  if (input_elements.any(function() { return $(this).val().length > 0 }))
    fetch_comment_preview();
});
