var newFaqModule = (function() {
  var _rfaqparentInput;
	var _rfaqtitleInput;
	var _rfaqtextInput;

	var _rfaqparentErrorField;
  var _rfaqtitleErrorField;
	var _rfaqtextErrorField;

	var _form;

	var _init = function(data) {
		_rfaqparentInput = document.querySelector(data["rfaqparentInput"]);
    _rfaqtitleInput = document.querySelector(data["rfaqtitleInput"]);
		_rfaqtextInput = document.querySelector(data["rfaqtextInput"]);

		_rfaqparentErrorField = document.querySelector(data["rfaqparentErrorField"]);
    _rfaqtitleErrorField = document.querySelector(data["rfaqtitleErrorField"]);
		_rfaqtextErrorField = document.querySelector(data["rfaqtextErrorField"]);

		_form = document.querySelector(data["form"]);

		_setEvents();
	};
	var _setEvents = function() {
		_rfaqparentInput.addEventListener("input", _checkrfaqparent);
    _rfaqtitleInput.addEventListener("input", _checkrfaqtitle);
		_rfaqtextInput.addEventListener("input", _checkrfaqtext);
		_form.onsubmit = _formSubmited;
	};
	var _checkrfaqparent = function() {
		var text = _rfaqparentInput.value;
		_unsetError(_rfaqparentErrorField);
		return true;
	};
	var _checkrfaqtitle = function() {
		var text = _rfaqtitleInput.value;
		if(!text) {
			_setError(_rfaqtitleErrorField, "Введите название вопроса");
			return false;
		}
		_unsetError(_rfaqtitleErrorField);
		return true;
	};
	var _checkrfaqtext = function() {
		var text = _rfaqtextInput.value;
		_unsetError(_rfaqtextErrorField);
		return true;
	};
	var _formSubmited = function() {
		if(!_checkAll()) return false;
		var formData = new FormData(document.sendDodjiRequest);
		formData = formDataFilter(formData);
		var xhr = new XMLHttpRequest();
		xhr.open("post", $('#sendDodjiRequest').attr('action'));
		xhr.send(formData);

		xhr.onreadystatechange = function () {
			if (this.readyState != 4) return;
			try {
				var response = JSON.parse(this.responseText);
				if(response.result === 'success') {
          document.location.href = response.redirectUrl;
				} else {
					if (response.errors !== undefined) {
						for (var field in response.errors) {
							_setError(_getErrorFieldByName(field), response.errors[field]);
						}
					}
				}
			}
			catch (e) {
				console.error('Некорректный ответ json');
				return false;
			}
		};
		return false;
	};
	var _getErrorFieldByName = function(fieldName) {
		switch(fieldName) {
			case "rfaqparent":
				return _rfaqparentErrorField;
			case "rfaqtitle":
				return _rfaqtitleErrorField;
			case "rfaqtext":
				return _rfaqtextErrorField;
		}
	};
	var _checkAll = function() {
		if(!_checkrfaqparent()) {
			_scrollTo(_rfaqparentInput);
			return false;
		}
		if(!_checkrfaqtitle()) {
			_scrollTo(_rfaqtitleInput);
			return false;
		}
		if(!_checkrfaqtext()) {
			_scrollTo(_rfaqtextInput);
			return false;
		}
		return true;
	};
	var _setError = function(errorField, text) {
		errorField.innerText = text;
		errorField.classList.remove("hidden");
	};
	var _unsetError = function(errorField) {
		errorField.innerText = "";
		errorField.classList.add("hidden");
	};
	var _scrollTo = function(field) {
		$('html, body').animate({
			scrollTop: field.offsetTop - 120
		}, 200);
	};
	return {
		init:_init
	}
})();
newFaqModule.init({
	"rfaqparentInput":".js-rfaqparent-input",
  "rfaqtitleInput":".js-rfaqtitle-input",
	"rfaqtextInput":".js-rfaqtext-input",

  "rfaqparentErrorField":".js-rfaqparent-error-field",
	"rfaqtitleErrorField":".js-rfaqtitle-error-field",
	"rfaqtextErrorField":".js-rfaqtext-error-field",

	"form":".js-form"
});

var rfaqtext = $('[name="rfaqtext"]'),
    rfaqtext_string = $('[name="rfaqtextstring"]'),
    auto_faqtext_tostring_chk = $('#auto_faqtext_tostring');

String.prototype.replaceAll = function(str1, str2, ignore)
{
  return this.replace(new RegExp(str1.replace(/([\/\,\!\\\^\$\{\}\[\]\(\)\.\*\+\?\|\<\>\-\&])/g,"\\$&"),(ignore?"gi":"g")),(typeof(str2)=="string")?str2.replace(/\$/g,"$$$$"):str2);
}

function auto_faqtext_tostring() {
  var newval = rfaqtext.val();
  newval = newval.replaceAll('&nbsp;', ' ').replaceAll('<\p><p>', ' ').replaceAll('<br>', ' ').replace(/<[^>]+>/g, '').replaceAll("\n\n\n", '').trim();

  rfaqtext_string.val(newval);
}

$('#copy_faqtext_tostring').click(function() {
  auto_faqtext_tostring();
});

auto_faqtext_tostring_chk.change(function() {
  if($(this).prop('checked')) auto_faqtext_tostring();
});

rfaqtext.change(function() {
  if(auto_faqtext_tostring_chk.prop('checked')) auto_faqtext_tostring();
});