var SITE = SITE || {};

SITE.fileInputs = function() {
	var $this = $(this),
		$val = $this.val(),
		valArray = $val.split('\\'),
		newVal = valArray[valArray.length - 1],
		$button = $this.parents('.file-wrapper').find('.button'),
		$fakeFile = $this.parents('.file-wrapper').find('.file-holder span');
	if (newVal !== '') {
		var reader = new FileReader();
		$('.block-help-image-js').show();
		$button.text($('.file-wrapper label').attr('data-init-text'));
		if ($fakeFile.length === 0) {
			$button.parents('.file-wrapper').find('.file-wrapper-block').append('<span class="file-holder"><span>' + newVal + '</span></span>');
		} else {
			$fakeFile.text(newVal);
		}
	}
};

$(document).on('click', '.js-solar-card-verify', function() {
	var html = $('.solar-card-verify-popup-content').html();
	show_popup(html, 'popup-card-confirm', '', 'popup-card-confirm', true);
	phoneVerifyEnable = true;

	$(".popup").find("#popup_fname, #popup_lname").on("keydown", validateCardFIO);
  $(".popup").find("#popup_fcard").on("keypress", validateCardData);
});

function validateCardFIO(e) {
	// разрешаем вводить только латиницу некоторые символы
	if (e.key != undefined && e.key.match(/[^А-яA-z\s-]/gi)) {
		return false;
	}
}

function validateCardData(e) {
  if (event.keyCode < 48 || event.keyCode > 57)
    event.returnValue= false;
}

//Проверка введенных данных
var SettingCheckersModule = (function() {
	var _usernameInput;
	var _usernameErrorField;
	var _nameInput;
	var _nameErrorField;
	var _nameEnInput;
	var _nameEnErrorField;
	var _emailInput;
	var _emailErrorField;

	var _passwordInput;
	var _passwordErrorField;
	var _passwordConfirmInput;
	var _passwordConfirmErrorField;

	var _webmoneyInput;
	var _webmoneyErrorField;
	var _qiwiInput;
	var _qiwiErrorField;
	var _yandexInput;
	var _yandexErrorField;

	var _mainSettingsForm;
	var _passwordSettingsForm;
	var _paymentsSettingsForm;

	var _detailsEnInput;
	var _detailsEnErrorField;

	var _serverSideCheckingMainInProgress;
	var _serverSideCheckingPasswordInProgress;
	var _serverSideCheckingPaymentsInProgress;

	var _mainSettingsNeedSubmit;
	var _passwordSettingsNeedSubmit;
	var _paymentsSettingsNeedSubmit;

	var _isUsernameError;
	var _isNameError;
	var _isNameEnError;
	var _isEmailError;
	var _isPasswordError;
	var _isPasswordConfirmError;
	var _isWebmoneyError;
	var _isQiwiError;
	var _isYandexError;
	var _isDetailsEnError;

	var _init = function(data) {
		_usernameInput = document.querySelector(data["usernameInput"]);
		_usernameErrorField = document.querySelector(data["usernameErrorField"]);
		_nameInput = document.querySelector(data["nameInput"]);
		_nameErrorField = document.querySelector(data["nameErrorField"]);
		_nameEnInput = document.querySelector(data["nameEnInput"]);
		_nameEnErrorField = document.querySelector(data["nameEnErrorField"]);
		_emailInput = document.querySelector(data["emailInput"]);
		_emailErrorField = document.querySelector(data["emailErrorField"]);
		_mainSettingsForm = document.querySelector(data["mainSettingsForm"]);

		_passwordInput = document.querySelector(data["passwordInput"]);
		_passwordErrorField = document.querySelector(data["passwordErrorField"]);
		_passwordConfirmInput = document.querySelector(data["passwordConfirmInput"]);
		_passwordConfirmErrorField = document.querySelector(data["passwordConfirmErrorField"]);
		_passwordSettingsForm = document.querySelector(data["passwordSettingsForm"]);

		_webmoneyInput = document.querySelector(data["webmoneyInput"]);
		_webmoneyErrorField = document.querySelector(data["webmoneyErrorField"]);
		_qiwiInput = document.querySelector(data["qiwiInput"]);
		_qiwiErrorField = document.querySelector(data["qiwiErrorField"]);
		_yandexInput = document.querySelector(data["yandexInput"]);
		_yandexErrorField = document.querySelector(data["yandexErrorField"]);
		_paymentsSettingsForm = document.querySelector(data["paymentsSettingsForm"]);

		_detailsEnInput = document.querySelector(data["detailsEnInput"]);
		_detailsEnErrorField = document.querySelector(data["detailsEnErrorField"]);

		_serverSideCheckingMainInProgress = false;
		_serverSideCheckingPasswordInProgress = false;
		_serverSideCheckingPaymentsInProgress = false;

		_mainSettingsNeedSubmit = false;
		_passwordSettingsNeedSubmit = false;
		_paymentsSettingsNeedSubmit = false;

		_isUsernameError = false;
		_isNameError = false;
		_isNameEnError = false;
		_isEmailError = false;
		_isPasswordError = false;
		_isPasswordConfirmError = false;
		_isWebmoneyError = false;
		_isQiwiError = false;
    _isYandexError = false;
		_isDetailsEnError = false;

		_setEvents();
	};
	var _setEvents = function() {
		_usernameInput.addEventListener("input", _checkUsername);
		_usernameInput.addEventListener("focusout", _serverSideCheckUsername);
		_emailInput.addEventListener("input", _checkEmail);
		_emailInput.addEventListener("focusout", _serverSideCheckEmail);
		if (_nameInput) {
			_nameInput.addEventListener("input", _checkName);
		}
		if (_nameEnInput) {
			_nameEnInput.addEventListener("input", _checkNameEn);
		}
		if (_detailsEnInput) {
			_detailsEnInput.addEventListener("input", _checkDetailsEn);
		}


		_passwordInput.addEventListener("input", _checkPasswords);
		_passwordConfirmInput.addEventListener("input", _checkPasswords);
		_passwordInput.addEventListener("focusout", _serverSideCheckPasswords);
		_passwordConfirmInput.addEventListener("focusout", _serverSideCheckPasswords);

		_webmoneyInput.addEventListener("input", _checkWebmoney);
		_qiwiInput.addEventListener("input", _checkQiwi);
    _yandexInput.addEventListener("input", _checkYandex);
		_webmoneyInput.addEventListener("focusout", _serverSideCheckWebmoney);
		_qiwiInput.addEventListener("focusout", _serverSideCheckQiwi);
    _yandexInput.addEventListener("focusout", _serverSideCheckYandex);

		_mainSettingsForm.onsubmit = _mainSettingsSubmitted;
		_passwordSettingsForm.onsubmit = _passwordSettingsSubmitted;
		_paymentsSettingsForm.onsubmit = _paymentsSettingsSubmitted;
	};
	var _mainSettingsSubmitted = function() {
		if (_isUsernameError || _isEmailError || _isNameError || _isNameEnError || _isDetailsEnError || _serverSideCheckingMainInProgress) {
			if (_serverSideCheckingMainInProgress) _mainSettingsNeedSubmit = true;
			_scrollToError("main");
			return false;
		}
		return true;
	};
	var _passwordSettingsSubmitted = function() {
		if (_isPasswordError || _isPasswordConfirmError || _serverSideCheckingPasswordInProgress) {
			if (_serverSideCheckingPasswordInProgress) _passwordSettingsNeedSubmit = true;
			_scrollToError("password");
			return false;
		}
		return true;
	};
	var _paymentsSettingsSubmitted = function() {
		if (_isWebmoneyError || _isQiwiError || _isYandexError || _serverSideCheckingPaymentsInProgress) {
			if (_serverSideCheckingPaymentsInProgress) _paymentsSettingsNeedSubmit = true;
			_scrollToError("payments");
			return false;
		}
		return true;
	};
	var _setError = function(type, text) {
		switch (type) {
			case "field_username":
				_isUsernameError = true;
				_usernameErrorField.textContent = text;
				_usernameErrorField.classList.remove("hidden");
				break;
			case "field_email":
				_isEmailError = true;
				_emailErrorField.textContent = text;
				_emailErrorField.classList.remove("hidden");
				break;
			case "field_name":
				_isNameError = true;
				_nameErrorField.classList.remove("hidden");
				break;
			case "field_nameen":
				_isNameEnError = true;
				_nameEnErrorField.classList.remove("hidden");
				break;
			case "field_password":
				_isPasswordError = true;
				_passwordErrorField.textContent = text;
				_passwordErrorField.classList.remove("hidden");
				break;
			case "field_passwordConfirm":
				_isPasswordConfirmError = true;
				_passwordConfirmErrorField.textContent = text;
				_passwordConfirmErrorField.classList.remove("hidden");
				break;
			case "field_webmoney":
				_isWebmoneyError = true;
				_webmoneyErrorField.textContent = text;
				_webmoneyErrorField.classList.remove("hidden");
				break;
			case "field_qiwi":
				_isQiwiError = true;
				_qiwiErrorField.textContent = text;
				_qiwiErrorField.classList.remove("hidden");
				break;
			case "field_yandex":
				_isYandexError = true;
				_yandexErrorField.textContent = text;
				_yandexErrorField.classList.remove("hidden");
				break;
			case "field_detailsen":
				_isDetailsEnError = true;
				_detailsEnErrorField.classList.remove("hidden");
				break;
		}
	};
	var _unsetError = function(type) {
		switch (type) {
			case "field_username":
				_isUsernameError = false;
				_usernameErrorField.textContent = "";
				_usernameErrorField.classList.add("hidden");
				break;
			case "field_email":
				_isEmailError = false;
				_emailErrorField.textContent = "";
				_emailErrorField.classList.add("hidden");
				break;
			case "field_name":
				_isNameError = false;
				_nameErrorField.classList.add("hidden");
				break;
			case "field_nameen":
				_isNameEnError = false;
				_nameEnErrorField.classList.add("hidden");
				break;
			case "field_password":
				_isPasswordError = false;
				_passwordErrorField.textContent = "";
				_passwordErrorField.classList.add("hidden");
				break;
			case "field_passwordConfirm":
				_isPasswordConfirmError = false;
				_passwordConfirmErrorField.textContent = "";
				_passwordConfirmErrorField.classList.add("hidden");
				break;
			case "field_webmoney":
				_isWebmoneyError = false;
				_webmoneyErrorField.textContent = "";
				_webmoneyErrorField.classList.add("hidden");
				break;
			case "field_qiwi":
				_isQiwiError = false;
				_qiwiErrorField.textContent = "";
				_qiwiErrorField.classList.add("hidden");
				break;
			case "field_yandex":
				_isYandexError = false;
				_yandexErrorField.textContent = "";
				_yandexErrorField.classList.add("hidden");
				break;
			case "field_detailsen":
				_isDetailsEnError = false;
				_detailsEnErrorField.textContent = "";
				_detailsEnErrorField.classList.remove("hidden");
				break;
		}
	};
	var _scrollToError = function(settingsType) {
		var highestField = false;
		if (settingsType === "main") {
			if (!highestField && _isUsernameError) highestField = "field_username";
			else if (!highestField && _isNameError) highestField = "field_name";
			else if (!highestField && _isNameEnError) highestField = "field_nameen";
			else if (!highestField && _isEmailError) highestField = "field_email";
			else if (!highestField && _isDetailsEnError) highestField = "field_detailsen";
			if (!highestField) highestField = "field_username";
		} else if (settingsType === "password") {
			if (!highestField && _isPasswordError) highestField = "field_password";
			else if (!highestField && _isPasswordConfirmError) highestField = "field_passwordConfirm";
			if (!highestField) highestField = "field_password";
		} else if (settingsType === "payments") {
			if (!highestField && _isWebmoneyError) highestField = "field_webmoney";
			else if (!highestField && _isQiwiError) highestField = "field_qiwi";
      else if (!highestField && _isYandexError) highestField = "field_yandex";
			if (!highestField) highestField = "field_webmoney";
		}
		_scrollTo(highestField);
	};
	var _scrollTo = function(element) {
		var offset = 0;
		switch (element) {
			case "field_username":
				offset = $(_usernameInput).offset().top;
				break;
			case "field_name":
				offset = $(_nameInput).offset().top;
				break;
			case "field_nameen":
				offset = $(_nameEnInput).offset().top;
				break;
			case "field_email":
				offset = $(_emailInput).offset().top;
				break;
			case "field_password":
				offset = $(_passwordInput).offset().top;
				break;
			case "field_passwordConfirm":
				offset = $(_passwordConfirmInput).offset().top;
				break;
			case "field_webmoney":
				offset = $(_webmoneyInput).offset().top;
				break;
			case "field_qiwi":
				offset = $(_qiwiInput).offset().top;
				break;
			case "field_yandex":
				offset = $(_yandexInput).offset().top;
				break;
			case "field_detailsen":
				offset = $(_detailsEnInput).offset().top;
				break;
		}
		$('html, body').animate({
			scrollTop: offset - 120
		}, 200);
	};
	var _checkUsername = function() {
		var username = _usernameInput.value;
		if (username === "") {
			_setError("field_username", 'Введите логин');
			return false;
		}
		if (!username.match(/^[a-zA-Z0-9-_]*$/i)) {
			_setError("field_username", 'Логин может содержать только латинские буквы, цифры и знаки - и _');
			return false;
		}
		if (username.length < 4) {
			_setError("field_username", 'Логин должен быть не короче 4-х символов');
			return false;
		}
		if (username.length > userLoginLength) {
			_setError("field_username", t('Логин не может быть длиннее {{0}} символов', [userLoginLength]));
			return false;
		}
		_unsetError("field_username");
		return true;
	};
	var _serverSideCheckUsername = function() {
		_serverSideCheckingMainInProgress = false;
		if (!_checkUsername()) return false;

    _unsetError("field_username");
		if (_mainSettingsNeedSubmit) {
		  _mainSettingsForm.submit();
			_mainSettingsNeedSubmit = false;
		}
		return true;
	};
	var _serverSideCheckEmail = function() {
		if (!_checkEmail()) return false;
		_serverSideCheckingMainInProgress = false;

		_unsetError("field_email");
		if (_mainSettingsNeedSubmit) {
			_mainSettingsForm.submit();
			_mainSettingsNeedSubmit = false;
		}
		return true;
	};
	var _checkEmail = function() {
		var email = _emailInput.value.trim();
		if (email === "") {
			_setError("field_email", 'Введите E-Mail');
			return false;
		}
		if (!validateEmail(email)) {
			_setError("field_email", 'Адрес электронной почты указан некорректно');
			return false;
		}
		_unsetError("field_email");
		return true;
	};
	var _checkNameEn = function() {
		var enName = _nameEnInput.value;
		if (enName.length > 0) {
			var regular = /[^a-zA-Z ]/g.exec(enName);
			_nameEnInput.value = enName.replace(regular, '');
			if (regular) {
				_setError("field_nameen");
				return false;
			}
			_unsetError("field_nameen");
		}
		return true;
	};

	var _checkName = function() {
		var name = _nameInput.value;
		var res = false;
		if (actor_lang === 'en') {
			res = /[^a-zA-Z ]/g.exec(name);
    } else {
			res = /[^А-Яа-яЁё ]/g.exec(name);
		}
		_nameInput.value = name.replace(res, '');

		if (res) {
			_setError("field_name");
			return false;
		}
		_unsetError("field_name");
		return true;
	};
	var _checkPasswords = function() {
		var password = _passwordInput.value;
		var passwordConfirm = _passwordConfirmInput.value;

		if (!password) {
			_setError("field_password", 'Пожалуйста, введите новый пароль');
			return false;
		}
		if (!passwordConfirm) {
			_setError("field_passwordConfirm", 'Подтвердите новый пароль');
			return false;
		}
		if (password.length < 5) {
			_setError("field_password", 'Длина пароля должна быть не менее 5 символов');
			return false;
		}
		if (passwordConfirm.length < 5) {
			_setError("field_passwordConfirm", 'Длина пароля должна быть не менее 5 символов');
			return false;
		}
		if (password !== passwordConfirm) {
			_setError("field_password", 'Пароль и подтверждение пароля не совпадают');
			_setError("field_passwordConfirm", 'Пароль и подтверждение пароля не совпадают');
			return false;
		}
		_unsetError("field_password");
		_unsetError("field_passwordConfirm");
		return true;
	};
	var _serverSideCheckPasswords = function() {
		if (!_checkPasswords()) return false;
		_serverSideCheckingPasswordInProgress = false;
		var password = _passwordInput.value;
		var passwordConfirm = _passwordConfirmInput.value;

		_unsetError("field_password");
		_unsetError("field_passwordConfirm");
		if (_passwordSettingsNeedSubmit) {
			_passwordSettingsForm.submit();
			_passwordSettingsNeedSubmit = false;
		}
		return true;
	};
	var _checkWebmoney = function() {
		var webmoney = _webmoneyInput.value;
		var webmoneyPattern = /R[0-9]*/i;
		if (!webmoney.match(webmoneyPattern) && webmoney !== "") {
			_setError("field_webmoney", 'Введите данные в формате: Rxxxxxxxxxxxx');
			return false;
		}
		_unsetError("field_webmoney");
		return true;
	};
	var _serverSideCheckWebmoney = function() {
		return true;
	};
	var _checkQiwi = function() {
		var qiwi = _qiwiInput.value;
		var qiwiPattern = /^[0-9]{11,14}$/i;
		if (!qiwi.match(qiwiPattern) && qiwi !== "") {
			_setError("field_qiwi", 'Введите данные в формате: от 11 до 14 цифр');
			return false;
		}
		_unsetError("field_qiwi");
		return true;
	};
	var _serverSideCheckQiwi = function() {
		if (!_checkQiwi()) return false;
		_serverSideCheckingPaymentsInProgress = false;

		_unsetError("field_qiwi");
		if (_paymentsSettingsNeedSubmit) {
			_paymentsSettingsForm.submit();
			_paymentsSettingsNeedSubmit = false;
		}
		return true;
	};
	var _checkYandex = function() {
		var yandex = _yandexInput.value;
		var yandexPattern = /^[0-9]{14,15}$/i;
		if (!yandex.match(yandexPattern) && yandex !== "") {
			_setError("field_yandex", 'Введите данные в формате: от 14 до 15 цифр');
			return false;
		}
		_unsetError("field_yandex");
		return true;
	};
	var _serverSideCheckYandex = function() {
		if (!_checkYandex()) return false;
		_serverSideCheckingPaymentsInProgress = false;

		_unsetError("field_yandex");
		if (_paymentsSettingsNeedSubmit) {
			_paymentsSettingsForm.submit();
			_paymentsSettingsNeedSubmit = false;
		}
		return true;
	};
	var _checkDetailsEn = function() {
		var enDetails = _detailsEnInput.value;
		if (enDetails.length > 0) {
			var regular = /[^a-zA-Z1-90\.,\:\;\s]/g.exec(enDetails);
			_detailsEnInput.value = enDetails.replace(regular, '');
			if (regular) {
				_setError("field_detailsen");
				return false;
			}
			_unsetError("field_detailsen");
		}
		return true;
	};
	return {
		init: _init
	};
})();

SettingCheckersModule.init({
	"usernameInput": ".js-username-input",
	"usernameErrorField": ".js-username-error-field",
	"nameInput": ".js-name-input",
	"nameErrorField": ".js-name-error-field",
	"nameEnInput": ".js-nameen-input",
	"nameEnErrorField": ".js-nameen-error-field",
	"emailInput": ".js-email-input",
	"emailErrorField": ".js-email-error-field",
	"mainSettingsForm": ".js-main-settings-form",
	"passwordInput": ".js-password-input",
	"passwordErrorField": ".js-password-error-field",
	"passwordConfirmInput": ".js-password-confirm-input",
	"passwordConfirmErrorField": ".js-password-confirm-error-field",
	"passwordSettingsForm": ".js-password-settings-form",
	"webmoneyInput": ".js-webmoney-input",
	"webmoneyErrorField": ".js-webmoney-error-field",
	"qiwiInput": ".js-qiwi-input",
	"qiwiErrorField": ".js-qiwi-error-field",
	"yandexInput": ".js-yandex-input",
	"yandexErrorField": ".js-yandex-error-field",
	"paymentsSettingsForm": ".js-payments-settings-form",
	"detailsEnInput": ".js-detailsen-input",
	"detailsEnErrorField": ".js-detailsen-error-field"
});