var timer,

last_content;

function auto_save(cb) {

var form = $('#post-form');

// only auto save existing posts, otherwise there's nowhere to write!
if (!form[0] || form.hasClass('new-post')) {
  if (timer) clearTimeout(timer);
  return cb && cb();
}

var current  = form[0].content.value;

if (last_content && current != last_content) {
  $.ajax({
    type: 'POST',
    url: form.attr('action'),
    data: form.serialize(),
    success: function() {
      console.log('Auto-saved.');
      cb && cb();
    }
  });
} else {
  cb && cb();
}

last_content = current;

};

$(function() {

$(document).on('keyup', '#search-input', function() {
  var q = $(this).val().trim();

  if (q != '' && q.length < 3) return;

  $.get($(this.form).attr('action'), { q: q }, function(data) {
    $('#posts-list').html(data);
  });
});

timer = setInterval(auto_save, 30000);

$(document).on('click', '.insert-image', function(el) {
  var url = $(this).data('url');
  var str = '![' + $(this).data('name') + '](' + url + ')\n';
  $('#post-content').insertAtCursor(str);
  setTimeout(function() { $('#uploads-bar').hide(); }, 500);
});

$(document).on('click', '#show-meta', function(e) {
  e.preventDefault();
  $('#post-meta').toggle();
})

$(document).on('blur', '.new-attribute', function() {
  var input = $(this),
      key_input = $(this).parent().prev().children().first(),
      key   = key_input.val().trim(),
      row   = $(this).parent().parent();

  if (input.val().trim() == '' || key == '')
    return;

  var delete_link = '<button class="btn btn-danger delete-attribute">Remove</a>';

  // add a new row to insert more stuff
  $('<tr>' + row.html() + '</tr>')
    .appendTo(row.parent())
    .find('input:first').focus();

  // set the input's name so it gets saved
  input.attr('name', 'meta[' + key + ']');
  row.find('td:last').html(delete_link);
  input.removeClass('new-attribute');
  key_input.attr('disabled', true); // new key has already been written down
});

$(document).on('click', '.delete-attribute', function() {
  var row = $(this).parent().parent();
  row.remove();
});

$(document).on('click', '#back-button', function(e) {
  if (typeof auto_save == 'function') {
    e.preventDefault();
    var link = $(this).attr('href');
    auto_save(function() {
      window.location = link;
    })
  }
})

});

// helper functions

(function($) {

$.fn.insertAtCursor = function (myValue) {
  return this.each(function() {
    if (document.selection) { // explorer
      this.focus();
      sel = document.selection.createRange();
      sel.text = myValue;
      this.focus();
    } else if (this.selectionStart || this.selectionStart == '0') { // firefox
        var startPos  = this.selectionStart;
        var endPos    = this.selectionEnd;
        var scrollTop = this.scrollTop;
        this.value = this.value.substring(0, startPos)
                  + myValue
                  + this.value.substring(endPos, this.value.length);
        this.focus();
        this.selectionStart = startPos + myValue.length;
        this.selectionEnd = startPos + myValue.length;
        this.scrollTop = scrollTop;
    } else {
      this.value += myValue;
      this.focus();
    }
  });
};

})(jQuery);