require(['jquery'], function($) {
  var appNameInput = $('input[name="appName"]');
  var appParentInput = $('input[name="appParentReference"]');
  var preview = $('.appName-preview');
  var submitButton = $('#wizard-next').prop('disabled', true);

  var errorMessage = appNameInput.closest('dd').prev('dt').find('.xErrorMsg');
  if (!errorMessage.length) {
    errorMessage = $(document.createElement('span')).addClass('xErrorMsg').hide().appendTo(errorMessage.addBack());
  }

  var toggleValidationError = function(message) {
    if (message) {
      appNameInput.addClass('xErrorField').focus();
      errorMessage.text(message).show();
    } else {
      appNameInput.removeClass('xErrorField');
      errorMessage.hide();
    }
  };

  var updatePreview = function(content) {
    preview.removeClass('loading').html(content);
    var error = preview.find('.xErrorMsg');
    submitButton.prop('disabled', error.length);
    toggleValidationError(error.remove().text());
  };

  var fetchPreviewUpdate = function() {
    if (appNameInput.val() == '') {
      updatePreview('<span class="xErrorMsg">Please enter the application name.</span>');
    } else {
      preview.addClass('loading');
      $.get(XWiki.currentDocument.getURL('get'), submitButton.closest('form').serialize(), updatePreview);
    }
  };

  var previewTimeout;
  var schedulePreviewUpdate = function() {
    clearTimeout(previewTimeout);
    submitButton.prop('disabled', true);
    setTimeout(fetchPreviewUpdate, 500);
  };

  appNameInput.add(appParentInput)
    .on('input', schedulePreviewUpdate)
    .on('keyup', function(event) {
      // Show the error message if the user presses Enter before typing anything.
      if (event.which == 13 && appNameInput.val() == '' && !appNameInput.hasClass('xErrorField')) {
        fetchPreviewUpdate();
      }
    });
  submitButton.closest('form').on('submit', function (event) {
    if (appNameInput.hasClass('xErrorField')) {
      event.preventDefault();
    }
  });
});
