$(function() {
  $('fieldset.form-plus').addClass('closed');
  $('fieldset.form-plus legend').on('click', function() {
    $(this).parent().toggleClass('closed');
  });
  if ($('form[data-has-draft]').length == 1) {
    var last_auto_save = $('form[data-has-draft]').serialize();
    var timeout_id = null;
    function autosave() {
      var new_auto_save = $('form[data-has-draft]').serialize();
      if (last_auto_save == new_auto_save) {
        timeout_id = window.setTimeout(autosave, 5000);
        return;
      }
      $.ajax({
        type: 'POST',
        url: window.location.pathname + 'autosave',
        data: new_auto_save,
        success: function(json) {
          if (json.result == 'success') {
            last_auto_save = new_auto_save;
          }
        },
        complete: function() {
          timeout_id = window.setTimeout(autosave, 5000);
        }
      });
    }
    timeout_id = window.setTimeout(autosave, 5000);
  }
  $('.date-pick').each(function() {
    var $date_input = $(this);
    var options = Object();
    options.autoclose = true;
    options.weekStart = 1;
    options.format = $date_input.data('date-format');
    options.minView = $date_input.data('min-view');
    options.startView = $date_input.data('start-view');
    if ($date_input.data('start-date')) options.startDate = $date_input.data('start-date');
    if ($date_input.data('end-date')) options.endDate = $date_input.data('end-date');
    $date_input.datetimepicker(options);
  });
  if ($('.widget-with-error').length && $('.global-errors').length == 0) {
    var first_field_with_error = $($('.widget-with-error')[0]).find('input,textarea,select');
    if (first_field_with_error.length) {
      $(first_field_with_error)[0].focus();
    }
  }
});
