jQuery(function($) {

  var update_saved_text = function(func, name)
  {
    $('#saved').html('Document auto saved at ' + new Date());
    var t = setTimeout(func + "('" + name + "')", 30000);
  };

  $.auto_save = function(name)
  {
    if ($('#story_text').length != 0 && tinyMCE.getInstanceById('story_text') != null)
    {
      var atok = $('input[name=authenticity_token]')[0].value;
      var ed = tinyMCE.get('story_text');
      var text_to_save = ed.getContent() == '' ? $('#story_text').val() : ed.getContent();
      //noinspection JSUnusedLocalSymbols,JSDeprecatedSymbols
      $.ajax({
        type: "POST",
        url: $('form[id*=edit_story]')[0].action,
        data: "story[text]=" + escape(text_to_save) + '&authenticity_token=' + atok + '&_method=put',
        cache: false,
        success: function(message)
        {
          $('#story_text').val(text_to_save);
          update_saved_text("jQuery.auto_save", name);
        }
      });

    } else {
      $('#' + name).ajaxSubmit(function()
      {
        update_saved_text("jQuery.auto_save", name);
      });
    }
  };

  $('a.step').each(function()
  {
    $(this).click(function()
    {
      $.auto_save($('#saved').attr('class'));
    });
  });

  $("#saved").each(function() {
    $.auto_save($(this).attr("class"));
  });

});