$required = $("input[data-val-required], textarea[data-val-required], select[data-val-required], checkbox[data-val-required],radio[data-val-required]");
$.each($required, function (b) {
    var a = $(this).attr("id");
    a = $("label[for\x3d" + a + "]");
    a.addClass("nch-required-label");
    "checkbox" == $(this).attr("type") && (a = $(this).parent(),
        $nchthischeck = $(this).attr("data-val-ischecked"),
        $nchparentlabel = a.prevAll("label").first(),
        $nchthischeck && ($nchparentlabel.parent().is("div.list")
            ? a.prevAll("label").first().addClass("nch-required-label")
            : $(this).closest("label").addClass("nch-required-label")));
    "radio" == $(this).attr("type") && (a = $(this).parent(),
        a.prevAll("label").first().addClass("nch-required-label"));
    1 === b && $(this).closest("form").append("\x3cp\x3eAll fields marked with \x3cspan style\x3d'color:red;'\x3e*\x3c/span\x3e are required\x3c/p\x3e")
});
var open = window.XMLHttpRequest.prototype.open,
  onReadyStateChange,
  requestUrl;
function openReplacement(method, url, async, user, password) {
  if (url.includes('/formbuilder')) {
    changeButtonText();
    if (this.onreadystatechange) {
      this._onreadystatechange = this.onreadystatechange;
    }
    this.requestUrl = url;
    this.onreadystatechange = onReadyStateChangeReplacement;
  }
  return open.apply(this, arguments);
}
function onReadyStateChangeReplacement() {
  if (this.readyState === 4 && this.status >= 300) {
    showError(this.requestUrl, this.statusText, this.error);
  }
  if (this._onreadystatechange) {
    return this._onreadystatechange.apply(this, arguments);
  }
}
window.XMLHttpRequest.prototype.open = openReplacement;
function changeButtonText() {
  var activeElement = $(document.activeElement);
  if ($(activeElement).hasClass("SitecoreFormsSubmit")) {
    $(activeElement).prop("disabled", true)
      .prop("value", "Submitting")
      .addClass("form-button-disable");
  }
}


$(document).ajaxStart(function () {
  var activeElement = $(document.activeElement);

  if ($(activeElement).hasClass("SitecoreFormsSubmit")) {
    $(activeElement).prop("disabled", true)
      .prop("value", "Submitting - please wait")
      .addClass("form-button-disable");
  }
});

$(document).ajaxStop(function () {
  $(".SitecoreFormsSubmit").prop("disabled", false)
    .removeClass("form-button-disable");
});
$(document).ajaxComplete(function (event, jqxhr, settings) {
  //only interested in forms
  if (!settings.url.includes('formbuilder')) {
    return;
  }
  if (jqxhr.status >= 300) {
    showErrorOnForm(settings.url);
    logError(settings.url, jqxhr.statusText, thrownError);
  }
});
$(document).ajaxError(function (event, jqxhr, settings, thrownError) {
  //only interested in forms
  if (!settings.url.includes('formbuilder')) {
    return;
  }
  showErrorOnForm(settings.url);
  logError(settings.url, jqxhr.statusText, thrownError);
});



const getTriggeredForm = function (url) {
  const uniqueFormUrl = `/formbuilder?${url.split("?")[1]}`;
  var form = $(`form[action='${uniqueFormUrl}']`).first();
  return form;
}
const getSessionId = function (url) {
  var form = getTriggeredForm(url);
  var session = $(`#${form.id} input[name*='.FormSessionId']`).first();
  if (!session) {
    return '';
  }
  else {
    return session.val();
  }
}
const showErrorOnForm = function (url) {
  var form = getTriggeredForm(url)[0];
  $(`#${form.id} input.SitecoreFormsSubmit`).after("<div><p style='color: red;'>We’re sorry an error has occurred.</p></div>");
}

const logError = function (url, status, error) {
  $.ajax({
    type: "POST",
    url: `/log/form-error?formUrl=${url}&sessionId=${getSessionId(url)}&pageUrl=${window.location}&message=${status}-${error}`,
  });
}
// Handles floating input labels

var $formInputs = $('.form input, .form textarea');

const checkInputFill = $input => {
    var $label = $input.parent('label');

    if ($label.length > 0) {
        if ($input[0].value) {
            $label.addClass('is-filled-label');
        } else {
            $label.removeClass('is-filled-label');
        }
    }
};

const newFormInput = input => {
    let $input = $(input);
    $input.on('input', function () {
        let $field = $(this).closest('div');
        if ($field.length > 0) {
            if (this.value) {
                $field.addClass('field--not-empty');
            } else {
                $field.removeClass('field--not-empty');
            }
        }
        checkInputFill($input);
    });
};

if (window.getAllAngularTestabilities) {
    $.each($formInputs, (i, input) => {
        newFormInput(input);
        checkInputFill($(input));
    });
}
else if (window['angular']) {
    $.each($formInputs, (i, input) => {
        newFormInput(input);
        checkInputFill($(input));
    });
}
