import * as formsApi from './tilda-forms-api.module'; /** * Скрипт сбрасывает все стандартные обрабочики формы и полей ввода и добавляет собственные слушатели и обработчкики. * Для всех полей форм устанавливается валидация в соответствии с типом поля. * * Все обработчики работают через делегирование и вещаются на rec блок. Такая особенность необходима для сохранения * пользовательского ввода в случае ре-рендеринга формы при таких событиях как, например, resize или orientationchange. * * Скрипт содержит словарь с переводами сообщений об ошибках или успехе на русском и английских языках. По необходимости * загружается словарь с другими языками. * * При отправке формы, проверяется валидность введённых данных. По необходимости вызывается проверка Google Captha. * * После отправки формы срабатывают кастомные события, например "tildaforms:aftersuccess", которые триггерят * пользовательские функции, если такие есть. В скрипте также формируются данные для пользовательских функций. * * После отправки формы триггерятся кастомные события для вызова пользовательских функций. * * Скрипт отвечает за платёжные системы cloudpayments, stripe, wayforpay, banktransfer и универсальную платёжную систему. */ // #region Typings /** * @typedef {'promocode' | 'deliveryreq' | 'unauthorized_order' | 'minorder' | 'minquantity'} CartValidationError */ /** * @typedef {'req' | 'email' | 'url' | 'phone' | 'number' | 'date' | 'time' | 'name' | 'nameeng' | 'namerus' | 'string' | * 'chosevalue'} FieldValidationError */ /** * @typedef {'emptyfill'} FormValidationError */ /** * @typedef {CartValidationError | FieldValidationError | FormValidationError} ValidationError */ /** * @typedef {Object} FormError * @property {'none' | Element} obj * @property {ValidationError[]} type */ // #endregion Typings window.t_forms__lang = (window.navigator.userLanguage || window.navigator.language).toUpperCase().slice(0, 2); window.scriptSysPayment = {}; window.handlerSysPayment = {}; window.isInitEventsZB = {}; window.isInitEventsCustomMask = {}; window.initForms = {}; window.tildaForm = { versionLib: '02.001', endpoint: 'forms.tildacdn.com', isRecaptchaScriptInit: false, currentFormProccessing: false, }; window.t_forms__clearForm = formsApi.t_formsApi__clearForm; window.t_forms__updateAllVariables = t_forms__updateAllVariables; window.t_forms__fieldApi = formsApi.t_formsApi__initTildaField; /** * Run the main script and determine whether to load * payment systems and additional languages */ t_onReady(function () { var allrecords = document.getElementById('allrecords'); if (allrecords) { var projectLang = allrecords.getAttribute('data-tilda-project-lang'); if (projectLang) { window.t_forms__lang = projectLang; } var rootzoneapi = allrecords.getAttribute('data-tilda-root-zone'); if (rootzoneapi) { window.tildaForm.endpoint = 'forms.tildaapi.' + rootzoneapi; } } t_forms__initForms(); t_forms__processGetParameters(); const zeroForms = Array.from( document.querySelectorAll('.t396__elem[data-elem-type="form"]:not(.zero-form-rendered)') ); zeroForms.forEach(form => form.addEventListener('render', t_forms__processGetParameters)); var isST100 = !!document.querySelector('.t706'); var isST105 = !!document.querySelector('.js-payment-systembox'); var isExistsPay = !!document.querySelector('input[name=tld_product]'); if (isST100 || isST105 || isExistsPay) { var tildaFormPaymentsFileName = 'tilda-forms-payments-1.0'; if (!document.head.querySelector('script[src*="' + tildaFormPaymentsFileName + '"]')) { var tildaFormPaymentsScript = document.createElement('script'); tildaFormPaymentsScript.type = 'text/javascript'; tildaFormPaymentsScript.src = 'https://static.tildacdn.' + t_forms__getRootZone() + '/js/' + tildaFormPaymentsFileName + '.min.js'; tildaFormPaymentsScript.onerror = function () { console.error('Failed to load tilda-forms-payments: ', this.src); }; document.head.appendChild(tildaFormPaymentsScript); } } var lang = window.t_forms__lang; if (lang !== 'RU' && lang !== 'EN') { var fileName = 'tilda-forms-dict-1.0'; if (!document.head.querySelector('script[src*="' + fileName + '"]')) { var script = document.createElement('script'); script.type = 'text/javascript'; script.src = 'https://static.tildacdn.' + t_forms__getRootZone() + '/js/' + fileName + '.min.js'; script.onerror = function () { console.error('Failed to load tilda-forms-dictionary: ', this.src); }; document.head.appendChild(script); } } }); /** * ALL GLOBAL FUNTIONS EXPRESSION ARE DECLARED AT THE BEGINNING OF THE SCRIPT BECAUSE * THEY ARE CALLED LATER IN THE CODE AND OTHERS SCRIPTS (tilda-cart, tilda-zero-forms). * IF YOU TRY TO CALL SUCH A FUNCTION BEFORE ITS DECLARATION, AN ERROR WILL OCCUR. * TO START READING THE SCRIPT SCROLL TO t_forms__initForms FUNCTION */ window.tildaForm.captchaCallback = function () { if (!window.tildaForm.currentFormProccessing || !window.tildaForm.currentFormProccessing.form) { return; } window.tildaForm.send( window.tildaForm.currentFormProccessing.form, window.tildaForm.currentFormProccessing.btn, window.tildaForm.currentFormProccessing.formtype, window.tildaForm.currentFormProccessing.formskey ); window.tildaForm.currentFormProccessing = false; }; /* Load script custom mask */ window.tildaForm_customMasksLoad = function () { if (window.isInitEventsCustomMask === true) return; var script = document.createElement('script'); script.type = 'text/javascript'; script.src = 'https://static.tildacdn.' + t_forms__getRootZone() + '/js/tilda-forms-custommask-1.0.min.js'; document.head.appendChild(script); script.onload = function () { window.isInitEventsCustomMask = true; }; }; /* Init custom mask */ window.tildaForm_initMasks = function () { var inputsCustomMask = document.querySelectorAll('.js-tilda-mask'); if (inputsCustomMask.length && window.isInitEventsCustomMask !== true) { window.tildaForm_customMasksLoad(); window.setTimeout(function () { window.tildaForm_initMasks(); }, 100); return; } if (window.isInitEventsCustomMask !== true) return; Array.prototype.forEach.call(inputsCustomMask, function (input) { t_asyncLoad(input); }); }; t_onReady(function () { window.tildaForm_initMasks(); }); /** * Init validate input in form * @param {Node} formNode - block form * @returns {Object} - validation input args */ window.tildaForm.validate = function (formNode) { const form = t_forms__getElement(formNode); var inputs = form.querySelectorAll('.js-tilda-rule'); var arrError = []; var isEmptyValue = true; var dataFormCart = form.getAttribute('data-formcart'); const { isHiddenByCondition } = t_forms__getConditionCheckHandler(form); for (var i = 0; i < inputs.length; i++) { var input = inputs[i]; // Если поле скрыто за условием, то не валидируем его // Такие поля не используются при отправке формы if (isHiddenByCondition(input)) continue; var isReq = !!parseInt(input.getAttribute('data-tilda-req') || 0, 10); var dataRule = input.getAttribute('data-tilda-rule') || 'none'; var regExp; var strValue; var minLength = input.getAttribute('data-tilda-rule-minlength') || 0; var maxLength = input.getAttribute('data-tilda-rule-maxlength') || 0; var inputObjError = {}; var value = input.value; var valueNoSpace = ''; var inputType = input.getAttribute('type'); var inputName = input.getAttribute('name'); inputObjError.obj = input; inputObjError.type = []; if (value && value.length) { /* eslint no-control-regex: */ valueNoSpace = value.replace(/[\s\u0000—\u001F\u2000-\u200F\uFEFF\u2028-\u202F\u205F-\u206F]/gi, ''); value = value.trim(); } if (minLength) { minLength = parseInt(minLength, 10); } if (maxLength) { maxLength = parseInt(maxLength, 10); } var isEmpty = !value.length && !valueNoSpace.length; var isCheckBoxOrRadio = inputType === 'checkbox' || inputType === 'radio'; var isChecked = form.querySelectorAll('[name="' + inputName + '"]:checked').length; const isCheckbox = input.classList.contains('t-checkboxes__hiddeninput'); if (isCheckbox || inputType === 'radio') { const currentInputType = isCheckbox ? 'checkbox' : 'radio'; const checkboxListWrapper = input.closest('.t-input-block'); const ownVariantInput = checkboxListWrapper && checkboxListWrapper.querySelector(`.t-input__own-answer-input, .t-${currentInputType}-ownanswer`); if (ownVariantInput && ownVariantInput.checked) { const ownVariantTextField = checkboxListWrapper.querySelector( '.t-input__own-answer, .t-input-ownanswer' ); const isEmptyOwnVariant = ownVariantTextField && !ownVariantTextField.value.trim(); if (isEmptyOwnVariant) { t_forms__validateOwnVariant(ownVariantTextField); isEmpty = true; } } } if ((value.length && !isCheckBoxOrRadio) || (isCheckBoxOrRadio && isChecked)) { isEmptyValue = false; } if (isReq && (isEmpty || (isCheckBoxOrRadio && !isChecked))) { inputObjError.type.push('req'); } else { switch (dataRule) { case 'email': regExp = /^(?!\.)(?!.*\.\.)[a-zA-Zёа-яЁА-Я0-9\u2E80-\u2FD5\u3190-\u319f\u3400-\u4DBF\u4E00-\u9FCC\uF900-\uFAAD_\.\-\+]{0,63}[a-zA-Zёа-яЁА-Я0-9\u2E80-\u2FD5\u3190-\u319f\u3400-\u4DBF\u4E00-\u9FCC\uF900-\uFAAD_\-\+]@[a-zA-Zёа-яЁА-ЯЁёäöüÄÖÜßèéû0-9][a-zA-Zёа-яЁА-ЯЁёäöüÄÖÜßèéû0-9\.\-]{0,253}\.[a-zA-Zёа-яЁА-Я]{2,11}$/gi; if (value.length && !value.match(regExp)) { inputObjError.type.push('email'); } break; case 'url': regExp = /^((https?|ftp):\/\/)?[a-zA-Zёа-яЁА-ЯЁёäöüÄÖÜßèéûşç0-9][a-zA-Zёа-яЁА-ЯЁёäöüÄÖÜßèéûşç0-9_\.\-]{0,253}\.[a-zA-Zёа-яЁА-Я0-9][a-zA-Zёа-яЁА-Я\-0-9]{1,10}\/?$/gi; if (value.length) { strValue = value.split('//'); if (strValue && strValue.length > 1) { strValue = strValue[1]; } else { strValue = strValue[0]; } strValue = strValue.split('/'); if (strValue && strValue.length && strValue[0]) { strValue = strValue[0]; if (!strValue.match(regExp)) { // регулярное выражение для поддержки Punycode (xn--) и IDN const idnRegExp = /^[a-zA-Zёа-яЁА-ЯЁёäöüÄÖÜßèéûşç0-9]([a-zA-Zёа-яЁА-ЯЁёäöüÄÖÜßèéûşç0-9_\-]|xn--)*(\.[a-zA-Zёа-яЁА-ЯЁёäöüÄÖÜßèéûşç0-9][a-zA-Zёа-яЁА-ЯЁёäöüÄÖÜßèéûşç0-9\-]+)+$/i; const hasIdnOrPunycode = /xn--/.test(strValue) || /[^\x00-\x7F]/.test(strValue); if (!hasIdnOrPunycode || !strValue.match(idnRegExp)) { inputObjError.type.push('url'); } } } else { if (!strValue || strValue[0]) { inputObjError.type.push('url'); } } } break; case 'phone': var phoneMask = input.getAttribute('data-tilda-mask'); var strRegExp = '^[0-9()+-'; if (phoneMask) { if (phoneMask.indexOf('*') !== -1) { strRegExp += 'a-zёа-я'; } else { if (phoneMask.indexOf('a') !== -1) strRegExp += 'a-z'; if (phoneMask.indexOf('а') !== -1) strRegExp += 'а-яё'; } } strRegExp += ']+$'; regExp = new RegExp(strRegExp, 'gi'); if (valueNoSpace.length && !valueNoSpace.match(regExp)) { inputObjError.type.push('phone'); } else { strValue = valueNoSpace.replace(/[^0-9]+/g, ''); if ( strValue.indexOf('000') == 1 || (strValue.indexOf('111') == 1 && strValue.substring(0, 1) != '9') || (strValue.indexOf('222') == 1 && strValue.substring(0, 1) != '5') || strValue.indexOf('333') == 1 || strValue.indexOf('444') == 1 || (strValue.indexOf('5555') == 1 && strValue.substring(0, 1) != '0') || (strValue.indexOf('666') == 1 && strValue.substring(0, 1) != '0') || (strValue.indexOf('8888') == 1 && strValue.substring(0, 1) != '4') ) { inputObjError.type.push('phone'); } } break; case 'number': regExp = /^[0-9]+$/gi; if (valueNoSpace.length > 0 && !valueNoSpace.match(regExp)) { inputObjError.type.push('number'); } break; case 'date': t_onFuncLoad('t_datepicker__readDateFromInput', function () { var date = t_datepicker__readDateFromInput(input); if (valueNoSpace.length > 0 && !window.t_datepicker__isDateValid(date)) { inputObjError.type.push('date'); } }); break; case 'time': regExp = /^[0-9]{2}[:\.][0-9]{2}$/gi; //! TODO: 00:00 - 23:59. Заменить на // /^([0-1][0-9]|2[0-3])[:\.][0-5][0-9]$/gi if (valueNoSpace.length > 0 && !valueNoSpace.match(regExp)) { inputObjError.type.push('time'); } break; case 'name': regExp = /^([ЁёäöüÄÖÜßèéûҐґЄєІіЇїӐӑЙйК̆к̆Ӄ̆ӄ̆Ԛ̆ԛ̆Г̆г̆Ҕ̆ҕ̆ӖӗѢ̆ѣ̆ӁӂꚄ̆ꚅ̆ҊҋО̆о̆Ө̆ө̆Ꚍ̆ꚍ̆ЎўХ̆х̆Џ̆џ̆Ꚏ̆ꚏ̆Ꚇ̆ꚇ̆Ҽ̆ҽ̆Ш̆ш̆Ꚗ̆ꚗ̆Щ̆щ̆Ы̆ы̆Э̆э̆Ю̆ю̆Я̆я̆А́а́ЃѓД́д́Е́е́Ё́ёӘ́ә́З́з́И́и́І́і́Ї́ї́ЌќЛ́л́Н́н́О́о́Р́р́С́с́Т́т́У́у́Ӱ́ӱ́Ү́ү́Х́х́Ц́ц́Ы́ы́Э́э́Ӭ́ӭ́Ю́ю́Ю̈́ю̈́Я́я́Ѣ́ѣ́ҒғӺӻҒ̌ғ̌Ј̵ј̵ҞҟҜҝԞԟӨөҎҏҰұӾӿҸҹҌҍҢңҚқҒғӘәҺһІіҰұҮүӨөȺⱥꜺꜻƂƃɃƀȻȼꞒꞓƋƌĐđɆɇǤǥꞠꞡĦħƗɨƗ́ɨ́Ɨ̀ɨ̀Ɨ̂ɨ̂Ɨ̌ɨ̌Ɨ̃ɨ̃Ɨ̄ɨ̄Ɨ̈ɨ̈Ɨ̋ɨ̋Ɨ̏ɨ̏Ɨ̧ɨ̧Ɨ̧̀ɨ̧̀Ɨ̧̂ɨ̧̂Ɨ̧̌ɨ̧̌ᵼɈɉɟɟ̟ʄʄ̊ʄ̥K̵k̵ꝀꝁꝂꝃꝄꝅꞢꞣŁłł̓Ł̣ł̣ᴌȽƚⱠⱡꝈꝉƛƛ̓ꞤꞥꝊꝋØøǾǿØ̀ø̀Ø̂øØ̌ø̌Ø̄ø̄Ø̃ø̃Ø̨ø̨Ø᷎ø᷎ᴓⱣᵽꝐꝑꝖꝗꝘꝙɌɍꞦꞧꞨꞩẜẝŦŧȾⱦᵺꝤꝥꝦꝧɄʉɄ́ʉ́Ʉ̀ʉ̀Ʉ̂ʉ̂Ʉ̌ʉ̌Ʉ̄ʉ̄Ʉ̃ʉ̃Ʉ̃́ʉ̃́Ʉ̈ʉ̈ʉ̞ᵾU̸u̸ᵿꝞꝟw̸ɎɏƵƶA-Za-z\u00C0\u00C0-\u00C3\u00C8-\u00CA\u00CC\u00CD\u00D2-\u00D9\u00DA\u00DD\u00E0-\u00E3\u00E8\u00E9\u00EA\u00EC\u00ED\u00F2-\u00F5\u00F9\u00FA\u00FD\u0102\u0103\u0110\u0111\u0128\u0129\u0168\u0169\u01A0\u01A1\u01AF\u01B0\u1EA0\u1EA1-\u1EF9\u0027\u2019\u0300-\u03FF\u0400-\u04FF\u0500-\u05FF\u0600-\u06FF\u3040-\u30FF\u0041-\u007A\u00C0-\u02B8\uFB1D-\uFB1F\uFB2A-\uFB4E\u0E00-\u0E7F\u10A0-\u10FF\u3040-\u309F\u30A0-\u30FF\u2E80-\u2FD5\u3190-\u319f\u3400-\u4DBF\u4E00-\u9FCC\uF900-\uFAAD]{1,})([ЁёäöüÄÖÜßèéûҐґЄєІіЇїӐӑЙйК̆к̆Ӄ̆ӄ̆Ԛ̆ԛ̆Г̆г̆Ҕ̆ҕ̆ӖӗѢ̆ѣ̆ӁӂꚄ̆ꚅ̆ҊҋО̆о̆Ө̆ө̆Ꚍ̆ꚍ̆ЎўХ̆х̆Џ̆џ̆Ꚏ̆ꚏ̆Ꚇ̆ꚇ̆Ҽ̆ҽ̆Ш̆ш̆Ꚗ̆ꚗ̆Щ̆щ̆Ы̆ы̆Э̆э̆Ю̆ю̆Я̆я̆А́а́ЃѓД́д́Е́е́Ё́ёӘ́ә́З́з́И́и́І́і́Ї́ї́ЌќЛ́л́Н́н́О́о́Р́р́С́с́Т́т́У́у́Ӱ́ӱ́Ү́ү́Х́х́Ц́ц́Ы́ы́Э́э́Ӭ́ӭ́Ю́ю́Ю̈́ю̈́Я́я́Ѣ́ѣ́ҒғӺӻҒ̌ғ̌Ј̵ј̵ҞҟҜҝԞԟӨөҎҏҰұӾӿҸҹҌҍҢңҚқҒғӘәҺһІіҰұҮүӨөȺⱥꜺꜻƂƃɃƀȻȼꞒꞓƋƌĐđɆɇǤǥꞠꞡĦħƗɨƗ́ɨ́Ɨ̀ɨ̀Ɨ̂ɨ̂Ɨ̌ɨ̌Ɨ̃ɨ̃Ɨ̄ɨ̄Ɨ̈ɨ̈Ɨ̋ɨ̋Ɨ̏ɨ̏Ɨ̧ɨ̧Ɨ̧̀ɨ̧̀Ɨ̧̂ɨ̧̂Ɨ̧̌ɨ̧̌ᵼɈɉɟɟ̟ʄʄ̊ʄ̥K̵k̵ꝀꝁꝂꝃꝄꝅꞢꞣŁłł̓Ł̣ł̣ᴌȽƚⱠⱡꝈꝉƛƛ̓ꞤꞥꝊꝋØøǾǿØ̀ø̀Ø̂øØ̌ø̌Ø̄ø̄Ø̃ø̃Ø̨ø̨Ø᷎ø᷎ᴓⱣᵽꝐꝑꝖꝗꝘꝙɌɍꞦꞧꞨꞩẜẝŦŧȾⱦᵺꝤꝥꝦꝧɄʉɄ́ʉ́Ʉ̀ʉ̀Ʉ̂ʉ̂Ʉ̌ʉ̌Ʉ̄ʉ̄Ʉ̃ʉ̃Ʉ̃́ʉ̃́Ʉ̈ʉ̈ʉ̞ᵾU̸u̸ᵿꝞꝟw̸ɎɏƵƶA-Za-z\u00C0\u00C0-\u00C3\u00C8-\u00CA\u00CC\u00CD\u00D2-\u00D9\u00DA\u00DD\u00E0-\u00E3\u00E8\u00E9\u00EA\u00EC\u00ED\u00F2-\u00F5\u00F9\u00FA\u00FD\u0102\u0103\u0110\u0111\u0128\u0129\u0168\u0169\u01A0\u01A1\u01AF\u01B0\u1EA0\u1EA1-\u1EF9\u0041-\u007A\u00C0-\u02B8\u0300-\u03FF\u0400-\u04FF\u0500-\u05FF\u0600-\u06FF\u3040-\u30FF\uFB1D-\uFB1F\uFB2A-\uFB4E\u0E00-\u0E7F\u10A0-\u10FF\u3040-\u309F\u30A0-\u30FF\u2E80-\u2FD5\u3190-\u319f\u3400-\u4DBF\u4E00-\u9FCC\uF900-\uFAAD\-\'\‘\ʼ\s\.]{0,})$/gi; if (value.length && !value.match(regExp)) { inputObjError.type.push('name'); } break; case 'nameeng': regExp = /^([A-Za-z\s]{1,}((\-)?[A-Za-z\.\s](\')?){0,})*$/i; if (value.length && !value.match(regExp)) { inputObjError.type.push('nameeng'); } break; case 'namerus': regExp = /^([А-Яа-яЁё\s]{1,}((\-)?[А-Яа-яЁё\.\s](\')?){0,})*$/i; if (value.length && !value.match(regExp)) { inputObjError.type.push('namerus'); } break; case 'string': /* eslint no-misleading-character-class: */ regExp = /^[A-Za-zА-Яа-я0-9ЁёЁёäöüÄÖÜßèéûӐӑЙйК̆к̆Ӄ̆ӄ̆Ԛ̆ԛ̆Г̆г̆Ҕ̆ҕ̆ӖӗѢ̆ѣ̆ӁӂꚄ̆ꚅ̆ҊҋО̆о̆Ө̆ө̆Ꚍ̆ꚍ̆ЎўХ̆х̆Џ̆џ̆Ꚏ̆ꚏ̆Ꚇ̆ꚇ̆Ҽ̆ҽ̆Ш̆ш̆Ꚗ̆ꚗ̆Щ̆щ̆Ы̆ы̆Э̆э̆Ю̆ю̆Я̆я̆А́а́ЃѓД́д́Е́е́Ё́ёӘ́ә́З́з́И́и́І́і́Ї́ї́ЌќЛ́л́Н́н́О́о́Р́р́С́с́Т́т́У́у́Ӱ́ӱ́Ү́ү́Х́х́Ц́ц́Ы́ы́Э́э́Ӭ́ӭ́Ю́ю́Ю̈́ю̈́Я́я́Ѣ́ѣ́ҒғӺӻҒ̌ғ̌Ј̵ј̵ҞҟҜҝԞԟӨөҎҏҰұӾӿҸҹҌҍҢңҚқҒғӘәҺһІіҰұҮүӨөȺⱥꜺꜻƂƃɃƀȻȼꞒꞓƋƌĐđɆɇǤǥꞠꞡĦħƗɨƗ́ɨ́Ɨ̀ɨ̀Ɨ̂ɨ̂Ɨ̌ɨ̌Ɨ̃ɨ̃Ɨ̄ɨ̄Ɨ̈ɨ̈Ɨ̋ɨ̋Ɨ̏ɨ̏Ɨ̧ɨ̧Ɨ̧̀ɨ̧̀Ɨ̧̂ɨ̧̂Ɨ̧̌ɨ̧̌ᵼɈɉɟɟ̟ʄʄ̊ʄ̥K̵k̵ꝀꝁꝂꝃꝄꝅꞢꞣŁłł̓Ł̣ł̣ᴌȽƚⱠⱡꝈꝉƛƛ̓ꞤꞥꝊꝋØøǾǿØ̀ø̀Ø̂øØ̌ø̌Ø̄ø̄Ø̃ø̃Ø̨ø̨Ø᷎ø᷎ᴓⱣᵽꝐꝑꝖꝗꝘꝙɌɍꞦꞧꞨꞩẜẝŦŧȾⱦᵺꝤꝥꝦꝧɄʉɄ́ʉ́Ʉ̀ʉ̀Ʉ̂ʉ̂Ʉ̌ʉ̌Ʉ̄ʉ̄Ʉ̃ʉ̃Ʉ̃́ʉ̃́Ʉ̈ʉ̈ʉ̞ᵾU̸u̸ᵿꝞꝟw̸ɎɏƵƶ\u0041-\u007A\u00C0-\u02B8\u0300-\u03FF\u0400-\u04FF\u0500-\u05FF\u0600-\u06FF\u3040-\u30FF\uFB1D-\uFB1F\uFB2A-\uFB4E\u0E00-\u0E7F\u10A0-\u10FF\u3040-\u309F\u30A0-\u30FF\u2E80-\u2FD5\u3190-\u319f\u3400-\u4DBF\u4E00-\u9FCC\uF900-\uFAAD,\.:;\"\'\`\-\_\+\?\!\%\$\@\*\&\^\s+]+$/i; if (value.length && !value.match(regExp)) { inputObjError.type.push('string'); } break; case 'chosevalue': const isNativeSelectbox = input?.tagName.toUpperCase() === 'SELECT'; if (isNativeSelectbox) { const isNativeOptionSelected = input?.value.length > 0; if (!isNativeOptionSelected) { inputObjError.type.push('chosevalue'); } } else { const isOptionSelected = input?.getAttribute('data-option-selected') === 'true'; if (!isOptionSelected) { inputObjError.type.push('chosevalue'); } } break; case 'promocode': if ( dataFormCart === 'y' && valueNoSpace.length && window.tcart && (!window.tcart.promocode || !window.tcart.prodamount_discountsum) ) { inputObjError.type.push('promocode'); } break; case 'deliveryreq': inputObjError.type.push('deliveryreq'); break; case 'unauthorized_order': inputObjError.type.push('unauthorized_order'); break; default: break; } if (minLength > 0 && value.length && value.length < minLength) { inputObjError.type.push('minlength'); } if (maxLength > 0 && value.length && value.length > maxLength) { inputObjError.type.push('maxlength'); } } if (inputObjError.type && inputObjError.type.length) { arrError[arrError.length] = inputObjError; } } /* validation in cart for minimum order cost and minimum items quantity */ if (dataFormCart === 'y') { var isMinOrderSetted = window.tcart_minorder > 0; var isMinQuantitySetted = window.tcart_mincntorder > 0; if (isMinOrderSetted) { var prodAmount; if (window.tcart.prodamount_withdiscount > 0) { prodAmount = window.tcart.prodamount_withdiscount; } else if ( typeof window.tcart.prodamount_withdyndiscount !== 'undefined' && window.t_cart__discounts && window.t_cart__discounts.length > 0 ) { prodAmount = window.tcart.prodamount_withdyndiscount; } else if ( typeof window.tcart.prodamount_withdiscount !== 'undefined' && window.tcart.promocode && window.tcart.promocode.message === 'OK' ) { prodAmount = window.tcart.prodamount_withdiscount; } else { prodAmount = window.tcart.prodamount; } if (prodAmount < window.tcart_minorder) { var prodAmountObjError = {}; prodAmountObjError.obj = {}; prodAmountObjError.type = []; prodAmountObjError.type.push('minorder'); arrError.push(prodAmountObjError); } } if (isMinQuantitySetted && window.tcart.total < window.tcart_mincntorder) { var objError = {}; objError.obj = {}; objError.type = []; objError.type.push('minquantity'); arrError.push(objError); } } if (isEmptyValue && !arrError.length && inputs.length) { arrError = [ { obj: 'none', type: ['emptyfill'], }, ]; } return arrError; }; /* Hide error in form */ window.tildaForm.hideErrors = function (formNode) { if (typeof formNode === 'object' && !formNode.length) { return; } const form = t_forms__getElement(formNode); var errorBoxes = form.querySelectorAll('.js-errorbox-all'); var errorRule = form.querySelectorAll('.js-rule-error'); var errorRuleAll = form.querySelectorAll('.js-error-rule-all'); var successBox = form.querySelectorAll('.js-successbox'); var errorControlBox = form.querySelectorAll('.js-error-control-box'); var errorControlInput = form.querySelectorAll('.js-error-control-box .t-input-error'); var errorPopup = document.getElementById('tilda-popup-for-error'); Array.prototype.forEach.call(errorBoxes, function (error) { error.style.display = 'none'; }); Array.prototype.forEach.call(errorRule, function (error) { error.style.display = 'none'; }); Array.prototype.forEach.call(errorRuleAll, function (error) { error.innerHTML = ''; }); Array.prototype.forEach.call(successBox, function (success) { success.style.display = 'none'; }); Array.prototype.forEach.call(errorControlInput, function (error) { error.innerHTML = ''; }); Array.prototype.forEach.call(errorControlBox, function (error) { t_removeClass(error, 'js-error-control-box'); }); t_removeClass(form, 'js-send-form-error'); t_removeClass(form, 'js-send-form-success'); if (errorPopup) t_fadeOut(errorPopup); }; /** * Show error popup for ZB * @param {Node} formNode - block form * @param {Obxect} arrErrors - obj data errors * @returns */ window.tildaForm.showErrorInPopup = function (formNode, arrErrors) { const form = t_forms__getElement(formNode); if (!arrErrors || !arrErrors.length) { return false; } var formId = form.getAttribute('id'); var inputBoxClassName = form.getAttribute('data-inputbox'); if (!inputBoxClassName) inputBoxClassName = '.blockinput'; var inputGroup = ''; var isErrorBox = false; var isShowErrors = true; var errorItem; var errorInputs = ''; var strError = ''; var strCommonError = ''; var popupError = document.getElementById('tilda-popup-for-error'); if (!popupError) { document.body.insertAdjacentHTML( 'beforeend', '' ); popupError = document.getElementById('tilda-popup-for-error'); t_addEventListener(popupError, 'click', function (event) { var clickEvent = event || window.event; var target = clickEvent.target || clickEvent.srcElement; var closeBtn = target.closest('.js-errorbox-close'); if (!closeBtn) return; clickEvent.preventDefault ? clickEvent.preventDefault() : (clickEvent.returnValue = false); t_fadeOut(popupError); }); } for (var i = 0; i < arrErrors.length; i++) { if (!arrErrors[i] || !arrErrors[i].obj) continue; if (i === 0 && arrErrors[i].obj === 'none') { strCommonError = '

' + t_forms__getMsg('emptyfill') + '

'; break; } var el = t_forms__getElement(arrErrors[i].obj); if (el) { inputGroup = el.closest(inputBoxClassName); } if (inputGroup) { errorInputs = inputGroup.querySelectorAll('.t-input-error'); t_addClass(inputGroup, 'js-error-control-box'); if (errorInputs.length) { isErrorBox = true; } } for (var j = 0; j < arrErrors[i].type.length; j++) { var error = arrErrors[i].type[j]; var localizedError = t_forms__getMsg(error); strError = ''; if (isShowErrors) { errorItem = form.querySelector('.js-rule-error-' + error); if (errorItem) { if ( (!errorItem.textContent || !errorItem.innerText) && localizedError && strCommonError.indexOf(localizedError) === -1 ) { strCommonError = strCommonError + '

' + localizedError + '

'; } else { strError = errorItem.textContent || errorItem.innerText; if (strCommonError.indexOf(strError) === -1) { strCommonError = strCommonError + '

' + strError + '

'; } } } else if (localizedError && strCommonError.indexOf(localizedError) === -1) { strCommonError = strCommonError + '

' + localizedError + '

'; } } if (isErrorBox) { if (!strError && t_forms__getMsg(error + 'field')) { strError = t_forms__getMsg(error + 'field'); } if (!strError && localizedError) { strError = localizedError; } if (strError && inputGroup) { errorInputs = inputGroup.querySelectorAll('.t-input-error'); Array.prototype.forEach.call(errorInputs, function (input) { input.innerHTML = strError; t_fadeIn(input); }); } } } } if (strCommonError) { popupError.querySelector('.t-form__errorbox-text').innerHTML = strCommonError; var errorsText = popupError.querySelectorAll('.t-form__errorbox-item'); Array.prototype.forEach.call(errorsText, function (text) { text.style.display = 'block'; }); // фикс для зеро-попапа, который может иметь кастомный z-index if (document.querySelector('.t1093 [data-elem-type="form"]')) { var activeZeroPopupHookList = window.tPopupObj && window.tPopupObj.openPopUpList; if (activeZeroPopupHookList && activeZeroPopupHookList.length) { var activeZeroPopupHook = activeZeroPopupHookList[activeZeroPopupHookList.length - 1]; var activePopupSelector = '.t1093 .t-popup[data-tooltip-hook="' + activeZeroPopupHook + '"]'; var activeZeroPopup = document.querySelector(activePopupSelector); var currentZIndex = activeZeroPopup ? getComputedStyle(activeZeroPopup).zIndex : 0; var defaultErrorPopupZIndex = 10000; if (currentZIndex > defaultErrorPopupZIndex) popupError.style.zIndex = currentZIndex + 1; } else { popupError.style.zIndex = ''; } } t_fadeIn(popupError); } if (window.t_forms__errorTimerID) { window.clearTimeout(window.t_forms__errorTimerID); } window.t_forms__errorTimerID = window.setTimeout(function () { t_fadeOut(popupError); errorInputs = form.querySelectorAll('.t-input-error'); Array.prototype.forEach.call(errorInputs, function (input) { input.innerHTML = ''; t_fadeOut(input); }); window.t_forms__errorTimerID = 0; }, 10000); var rec; /** * Hide popup input error in ZB * * @param {MouseEvent} event - event * @returns {undefined} - exit function */ function t_forms__hidePopup(event) { var mouseEvent = event || window.event; var input = mouseEvent.target || mouseEvent.srcElement; if (input.tagName !== 'INPUT' || !rec) return; var errorInputs = rec.querySelectorAll('form .t-input-error'); t_fadeOut(popupError); Array.prototype.forEach.call(errorInputs, function (input) { input.innerHTML = ''; t_fadeOut(input); }); if (window.t_forms__errorTimerID) { window.clearTimeout(window.t_forms__errorTimerID); window.t_forms__errorTimerID = 0; } window.isInitEventsZB[formId] = true; } if (!window.isInitEventsZB[formId]) { rec = form.closest('.r'); var eventFocus = 'focus'; if (!document.addEventListener) { eventFocus = 'focusin'; } t_removeEventListener(rec, eventFocus, t_forms__hidePopup); t_addEventListener(rec, eventFocus, t_forms__hidePopup, true); t_removeEventListener(rec, 'change', t_forms__hidePopup); t_addEventListener(rec, 'change', t_forms__hidePopup, true); } t_triggerEvent(form, 'tildaform:aftererror'); return true; }; /** * @typedef {Object} ShowErrorsParams * @property {string} [inputBoxSelector] */ /** * Show error in form * @param {Node} formNode * @param {Array} arrErrors * @param {ShowErrorsParams} [params] * @returns {boolean} Returns true if arrErrors is not empty and errors have been shown */ window.tildaForm.showErrors = function (formNode, arrErrors, params) { const form = t_forms__getElement(formNode); if (!arrErrors || !arrErrors.length) { return false; } if (form.getAttribute('data-error-popup') === 'y') { return window.tildaForm.showErrorInPopup(form, arrErrors); } const { inputBoxSelector = form.getAttribute('data-inputbox') || '.blockinput' } = params || {}; const inputBoxClassName = inputBoxSelector; const focusListeners = t_forms__createErrorFocusHash(); for (var i = 0; i < arrErrors.length; i++) { const isFirstError = i === 0; const errorItem = arrErrors[i]; if (!errorItem || !errorItem.obj) continue; const errorObj = errorItem.obj; if (errorObj === 'none' && isFirstError) { t_forms__showEmptyFormError(form); break; } const errorItemElement = t_forms__getElement(errorObj); if (errorItemElement && errorItemElement instanceof Element) { const inputGroup = errorItemElement.closest(inputBoxClassName); t_forms__showInputErrors(form, inputGroup, errorItem); } t_forms__showFormErrors(form, errorItem, focusListeners); } t_forms__scrollToInputWithError(arrErrors[0]); t_forms__showFormErrorsContainers(form); t_triggerEvent(form, 'tildaform:aftererror'); return true; }; /** * Add block for our own captcha * @param {Node} formNode - block form * @param {string} formKey - form key */ window.tildaForm.addTildaCaptcha = function (formNode, formKey) { const form = t_forms__getElement(formNode); const formCaptchaBox = document.getElementById('tildaformcaptchabox'); const tildaCaptcha = document.getElementById('js-tildaspec-captcha'); if (formCaptchaBox) t_removeEl(formCaptchaBox); if (tildaCaptcha) t_removeEl(tildaCaptcha); form.insertAdjacentHTML( 'beforeend', '' ); let randomKey; try { randomKey = '' + new Date().getTime() + '=' + parseInt(Math.random() * 8, 10); } catch (e) { randomKey = 'rnd=' + parseInt(Math.random() * 8, 10); } const captchaBox = document.createElement('div'); captchaBox.id = 'tildaformcaptchabox'; captchaBox.tabIndex = -1; captchaBox.style.cssText = 'z-index: 99999999999; position: fixed; text-align: center; top: 0; left: 0; right: 0; bottom: 0; background: rgba(255,255,255,0.97);'; const iframe = document.createElement('iframe'); iframe.id = 'captchaIframeBox'; iframe.setAttribute('frameborder', '0'); iframe.style.cssText = 'display: block; border: 0; width: 100%; height: 100%;'; // В Chrome на iOS iframe с высотой 100% перезагружается, когда адресная строка меняет высоту экрана. if (/CriOS/.test(navigator.userAgent)) { const frameWidth = window.innerWidth + 'px'; const frameHeight = window.innerHeight + 'px'; captchaBox.style.right = 'auto'; captchaBox.style.bottom = 'auto'; captchaBox.style.width = frameWidth; captchaBox.style.height = frameHeight; captchaBox.style.overflow = 'hidden'; iframe.style.width = frameWidth; iframe.style.height = frameHeight; } captchaBox.appendChild(iframe); document.body.appendChild(captchaBox); iframe.src = `//${window.tildaForm.endpoint}/procces/captcha/?tildaspec-formid=${form.id}&tildaspec-formskey=${formKey}&${randomKey}`; window.removeEventListener('message', checkVerifyTildaCaptcha); window.addEventListener('message', checkVerifyTildaCaptcha); captchaBox.focus(); }; /** * Add information on members * @param {Node} formNode - block form * @returns {boolean} - return true/false */ window.tildaForm.addMembersInfoToForm = function (formNode) { const form = t_forms__getElement(formNode); if (!form) return; try { var mauserInfo = form.querySelector('.js-tilda-mauserinfo'); if (mauserInfo) t_removeEl(mauserInfo); if (!window.mauser) return; window.tildaForm.tildamember = {}; if (window.mauser.name) { window.tildaForm.tildamember['name'] = window.mauser.name; } // code и email должны быть заполнены вместе if (window.mauser.code && window.mauser.email) { window.tildaForm.tildamember['email'] = window.mauser.email; window.tildaForm.tildamember['code'] = window.mauser.code; } // phonecode и phone должны быть заполнены вместе if (window.mauser.phonecode && window.mauser.phone) { window.tildaForm.tildamember['phone'] = window.mauser.phone; window.tildaForm.tildamember['phonecode'] = window.mauser.phonecode; } if (window.mauser.token) { window.tildaForm.tildamember['token'] = window.mauser.token; } } catch (error) { console.error('addMembersInfoToForm exception: ', error); } }; /* Close success popup for ZB */ window.tildaForm.closeSuccessPopup = function () { const newSuccessPopup = document.getElementById('tildaformsuccesspopup-new'); const oldSuccessPopup = document.getElementById('tildaformsuccesspopup'); const isOldPopupVisible = oldSuccessPopup && getComputedStyle(oldSuccessPopup).display === 'block'; const successPopup = isOldPopupVisible ? oldSuccessPopup : newSuccessPopup; if (!successPopup) return; t_removeClass(document.body, 't-body_success-popup-showed'); if (t_forms__isIOS()) { window.tildaForm.unlockBodyScroll(); } t_fadeOut(successPopup); if (successPopup.classList.contains('t-form-success-popup_new')) { successPopup.classList.remove('t-popup_show'); } // если есть тег style со стилями из формы в попапе, // удаляем после закрытия попапа с сообщением об успехе const styleElement = document.querySelector('style.t-success-popup'); if (styleElement) { styleElement.remove(); } }; /* Locked scroll document for iPhone/iPad/iPod */ window.tildaForm.lockBodyScroll = function () { var body = document.body; if (t_hasClass(body, 't-body_scroll-locked')) return; var bodyScrollTop = typeof window.pageYOffset !== 'undefined' ? window.pageYOffset : (document.documentElement || document.body.parentNode || document.body).scrollTop; t_addClass(body, 't-body_scroll-locked'); body.style.top = '-' + bodyScrollTop + 'px'; body.setAttribute('data-popup-scrolltop', bodyScrollTop); }; /* Unlocked scroll document for iPhone/iPad/iPod */ window.tildaForm.unlockBodyScroll = function () { var body = document.body; if (!t_hasClass(body, 't-body_scroll-locked')) return; var bodyScrollTop = body.getAttribute('data-popup-scrolltop'); t_removeClass(body, 't-body_scroll-locked'); body.style.top = null; body.removeAttribute('data-popup-scrolltop'); document.documentElement.scrollTop = parseInt(bodyScrollTop); }; /** * Show success popup for ZB * @param {string} message - str message */ window.tildaForm.showSuccessPopup = function (message) { var strHtml = ''; var successPopup = document.getElementById('tildaformsuccesspopup'); var successPopupText = document.getElementById('tildaformsuccesspopuptext'); var body = document.body; if (!successPopup) { strHtml += ''; strHtml += ''; body.insertAdjacentHTML('beforeend', strHtml); successPopup = document.getElementById('tildaformsuccesspopup'); successPopupText = document.getElementById('tildaformsuccesspopuptext'); var successPopupCloseBtn = successPopup.querySelector('.t-form-success-popup__close-icon'); t_addEventListener(successPopup, 'click', function (event) { var clickEvent = event || window.event; var target = clickEvent.target || clickEvent.srcElement; if (target === this) { window.tildaForm.closeSuccessPopup(); } }); t_addEventListener(successPopupCloseBtn, 'click', function () { window.tildaForm.closeSuccessPopup(); }); t_addEventListener(body, 'keydown', function (event) { var keyDownEvent = event || window.event; var keyCode = keyDownEvent.keyCode || keyDownEvent.which; if (keyCode == 27) { window.tildaForm.closeSuccessPopup(); } }); } successPopupText.innerHTML = message; t_fadeIn(successPopup); t_addClass(body, 't-body_success-popup-showed'); if (t_forms__isIOS()) { setTimeout(function () { window.tildaForm.lockBodyScroll(); }, 500); } }; /** * /** * Show new version of success message in popup * @param {string} text - text in success popup * @param {string} title – title of success popup * @param {string} btn – text in button in success popup */ window.tildaForm.showSuccessPopupNew = function (form, text, title, btn) { const popupId = 'tildaformsuccesspopup-new'; const body = document.body; const successUrl = form.getAttribute('data-success-url'); const isRedirect = !!successUrl; // если есть редирект, нет ошибки при редиректе, не заполненны заголовок и текст – не показываем попап if (!window.isRedirectError && isRedirect && !text && !title) return; // редирект не произошёл из-за ошибки, текст и заголовок не заполнены const isPopupAfterRedirectError = window.isRedirectError && isRedirect && !text && !title; const isEmptyContent = !title && !text; const successPopup = initPopup(); updatePopupContent(); restartIconAnimation(); t_forms__setupCloseHandlers(successPopup, isRedirect); showPopup(); // a11y ловушка фокуса setTimeout(function () { successPopup.focus(); t_forms__trapFocus(successPopup); }, 50); function initPopup() { let popup = document.getElementById(popupId); if (!popup) { body.insertAdjacentHTML('beforeend', t_forms__drawNewSuccessPopup()); popup = document.getElementById(popupId); } return popup; } function showPopup() { t_fadeIn(successPopup); t_addClass(body, 't-body_success-popup-showed'); successPopup.classList.add('t-popup_show'); resizeSuccessPopup(successPopup); if (t_forms__isIOS()) { setTimeout(function () { window.tildaForm.lockBodyScroll(); }, 500); } } function resizeSuccessPopup() { const STATIC_POPUP_VERTICAL_PADDING = 120; const availableWindowHeight = window.innerHeight - STATIC_POPUP_VERTICAL_PADDING; const popupContainer = successPopup.querySelector('.t-form-success-popup__wrapper'); const popupContainerStyle = getComputedStyle(popupContainer, null); const popupContainerPaddingTop = parseInt(popupContainerStyle.paddingTop) || 0; const popupContainerPaddingBottom = parseInt(popupContainerStyle.paddingBottom) || 0; const popupContainerHeight = popupContainer.clientHeight - (popupContainerPaddingTop + popupContainerPaddingBottom); const height = popupContainerHeight; // Проверяем, помещается ли попап в доступное пространство окна const fitsInWindow = height <= availableWindowHeight; if (fitsInWindow) { popupContainer.classList.remove('t-popup__container-static'); } else { popupContainer.classList.add('t-popup__container-static'); } } // Собираем объект из элементы в попапе сообщения об успехе, // которые могут меняться в зависимости от условий function createElementsData() { return { title: { element: document.getElementById('tildaformsuccesspopuptitle-new'), content: isEmptyContent ? t_forms__getMsg('success_title') : title, show: isEmptyContent ? true : !!title, }, text: { element: document.getElementById('tildaformsuccesspopuptext-new'), content: isEmptyContent ? t_forms__getMsg('success_text') : text, show: isEmptyContent ? true : !!text, }, linkButton: { element: document.getElementById('tildaformsuccesspopuplink-new'), content: btn || (isRedirect ? t_forms__getMsg('success_btn_redirect') : t_forms__getMsg('success_btn')), show: isRedirect, }, closeButton: { element: document.getElementById('tildaformsuccesspopupbtn-new'), content: btn || (isRedirect ? t_forms__getMsg('success_btn_redirect') : t_forms__getMsg('success_btn')), show: !isRedirect, }, info: { element: document.getElementById('tildaformsuccesspopupinfo-new'), content: null, show: isRedirect, }, infoText: { element: document.getElementById('tildaformsuccesspopupinfotext-new'), content: isPopupAfterRedirectError ? t_forms__getMsg('success_info_redirect_error') : t_forms__getMsg('success_info'), show: isRedirect, }, infoDigit: { element: document.getElementById('tildaformsuccesspopupinfodigit-new'), content: isPopupAfterRedirectError ? '' : '3', show: isRedirect, }, closeIcon: { element: document.getElementById('tildaformsuccesspopupclose-new'), content: null, show: !isRedirect, }, }; } function updatePopupContent() { const elementsData = createElementsData(); Object.keys(elementsData).forEach(key => { const { element, content, show } = elementsData[key]; if (!element) return; element.classList.toggle('t-form-success-popup_hidden', !show); if (show && content) { element.innerHTML = content; } if (key === 'linkButton' && isRedirect) { element.setAttribute('href', successUrl); } }); } function restartIconAnimation() { const icon = document.querySelector('.t-form-success-popup__content-icon'); if (!icon) return; const newIcon = icon.cloneNode(true); icon.parentNode.replaceChild(newIcon, icon); } }; window.tildaForm.handleClosePopup = function () { window.tildaForm.closeSuccessPopup(); if ( window.tildaForm.currentRemoveCloseHandlers && typeof window.tildaForm.currentRemoveCloseHandlers === 'function' ) { window.tildaForm.currentRemoveCloseHandlers(); } }; function t_forms__setupCloseHandlers(successPopup, isRedirect) { const body = document.body; const closeBtnIcon = successPopup.querySelector('.t-form-success-popup__close-icon'); const closeBtn = document.getElementById('tildaformsuccesspopupbtn-new'); function removeCloseHandlers() { if (closeBtnIcon) closeBtnIcon.removeEventListener('click', window.tildaForm.handleClosePopup); if (closeBtn) closeBtn.removeEventListener('click', window.tildaForm.handleClosePopup); body.removeEventListener('keydown', handleKeydown); successPopup.removeEventListener('click', handleOutsideClick); } window.tildaForm.currentRemoveCloseHandlers = removeCloseHandlers; if (closeBtnIcon) { closeBtnIcon.addEventListener('click', window.tildaForm.handleClosePopup); } if (closeBtn) { closeBtn.addEventListener('click', window.tildaForm.handleClosePopup); } if (!isRedirect) { body.addEventListener('keydown', handleKeydown); successPopup.addEventListener('click', handleOutsideClick); } function handleKeydown(event) { if (event.key === 'Escape' || event.keyCode == 27) { window.tildaForm.handleClosePopup(); } } function handleOutsideClick(event) { if (event.target === successPopup) { window.tildaForm.handleClosePopup(); } } } /** * Success end form. The function call order is crucial. * First, we must handle success callbacks and then clear out the form data. * @param {Node} formNode - block form * @param {string} successUrl - link on successful submission * @param {string} successCallback - function on successful submission */ window.tildaForm.successEnd = function (formNode, successUrl, successCallback) { const form = t_forms__getElement(formNode); t_addClass(form, 'js-send-form-success'); t_forms__updateAllSystemVariables(form); const popup = form.closest('.t-popup'); const isZeroPopup = form.closest('.t1093'); const isFormInPopup = t_forms__isNewSuccessBox(form) && popup && !isZeroPopup; const zeroWithSuccessPopup = form.getAttribute('data-success-popup') === 'y'; function callOnSuccess() { t_forms__handleSuccess(form, { successCallback, successUrl }); window.tildaForm.clearTCart(form); t_forms__clearFormInputs(form); t_forms__clearFormData(form); if (t_forms__isNewSuccessBox(form) || zeroWithSuccessPopup) { window.t_forms__clearForm(form); } } function showSuccessbox() { t_forms__showSuccessbox(form).finally(() => { callOnSuccess(); }); } if (isFormInPopup) { // вызываем сооющение успеха с небольшой задержкой, чтобы не было конфликта с закрытием попапа с формой const SUCCESS_POPUP_DELAY = 320; t_forms__processFormsInPopup(popup, form); setTimeout(showSuccessbox, SUCCESS_POPUP_DELAY); return; } showSuccessbox(); }; /* Clear data cart */ window.tildaForm.clearTCart = function (formNode) { const form = t_forms__getElement(formNode); if (form.getAttribute('data-formcart') === 'y') { /* flag clear basket */ window.clearTCart = true; window.tcart = { amount: 0, currency: '', system: '', products: [], }; window.tcart.system = 'none'; if (typeof localStorage === 'object') { try { localStorage.removeItem('tcart'); } catch (error) { console.error('Your web browser does not support localStorage. Code status: ', error); } } try { delete window.tcart; window.tcart__loadLocalObj(); } catch (error) { /* */ } window.tcart_success = 'yes'; } }; /** * Handler for sending data and receiving the result(captcha, errors, successful result, launch of payment systems) * @param {Node} formNode - block form * @param {Node} btnSubmitNode - el btn submit * @param {number} formType - type form * @param {string} formKey - key form * @returns {undefined} - exit function */ window.tildaForm.send = function (formNode, btnSubmitNode, formType, formKey) { const form = t_forms__getElement(formNode); const btnSubmit = t_forms__getElement(btnSubmitNode); var allRecords = document.getElementById('allrecords'); var pageId = allRecords.getAttribute('data-tilda-page-id'); var projectId = allRecords.getAttribute('data-tilda-project-id'); var formId = form.getAttribute('id'); var dataFormCart = form.getAttribute('data-formcart'); var msgContainers; var errorBoxes; var allError; window.tildaForm.tildapayment = false; if (dataFormCart === 'y' || form.closest('.t706__orderform')) { window.tildaForm.addPaymentInfoToForm(form); } try { if (window.mauser) { window.tildaForm.addMembersInfoToForm(form); } } catch (error) { /* */ } var inputItsGood = form.querySelector('input[name="form-spec-comments"]'); if (!inputItsGood) { form.insertAdjacentHTML( 'beforeend', '
' ); } if (formType === 2 || (!formType && formKey)) { var tildaSpecs = { 'tildaspec-cookie': document.cookie, 'tildaspec-referer': window.location.href, 'tildaspec-formid': formId, 'tildaspec-formskey': formKey, 'tildaspec-version-lib': window.tildaForm.versionLib, 'tildaspec-pageid': pageId, 'tildaspec-projectid': projectId, 'tildaspec-lang': window.t_forms__lang, }; var hiddenInput; for (var spec in tildaSpecs) { hiddenInput = form.querySelector('input[name="' + spec + '"]'); if (!hiddenInput) { form.insertAdjacentHTML('beforeend', ''); hiddenInput = form.querySelector('input[name="' + spec + '"]'); hiddenInput.value = tildaSpecs[spec]; } } try { hiddenInput = form.querySelector('input[name=tildaspec-fp]'); if (!hiddenInput) { form.insertAdjacentHTML('beforeend', ''); hiddenInput = form.querySelector('input[name=tildaspec-fp]'); } if (window.tildastat) { hiddenInput.value = window.tildastat('fingerprint'); } else { hiddenInput.value = 'st' + window.pageYOffset + 'w' + window.innerWidth + 'h' + window.innerHeight + 'ft' + form.getBoundingClientRect().top + window.pageYOffset; } } catch (error) { /* */ } inputItsGood = form.querySelector('.js-form-spec-comments'); if (inputItsGood) inputItsGood.value = ''; const { status, data: formData, contentType } = t_forms__getFormData(form); if (status === 'invalid') { return false; } var startRequest = Date.now(); t_triggerEvent(form, 'tildaform:beforesend'); var formUrl = 'https://' + window.tildaForm.endpoint + '/procces/'; var secondFormTypeXhr = new XMLHttpRequest(); secondFormTypeXhr.open('POST', formUrl, true); secondFormTypeXhr.setRequestHeader('Content-Type', contentType); secondFormTypeXhr.setRequestHeader('Accept', 'application/json, text/javascript, */*; q=0.01'); secondFormTypeXhr.onreadystatechange = function () { if (secondFormTypeXhr.readyState === 4) { if (secondFormTypeXhr.status >= 200 && secondFormTypeXhr.status < 400) { var data = secondFormTypeXhr.responseText; if (data) { var objData = JSON.parse(data); if (typeof objData === 'object') { var dataSuccessUrl = form.getAttribute('data-success-url'); var dataSuccessCallback = form.getAttribute('data-success-callback'); var dataFormSendedCallback = form.getAttribute('data-formsended-callback'); t_removeClass(btnSubmit, 't-btn_sending'); btnSubmit.tildaSendingStatus = '0'; try { if ( objData && objData.redirectto && objData.redirectto.length == 3 && window.tildaForm.endpoint.substring(window.tildaForm.endpoint.length - 3) != objData.redirectto ) { window.tildaForm.endpoint = 'forms.tildaapi.' + objData.redirectto; window.tildaForm.send(form, btnSubmit, formType, formKey); return false; } } catch (e) { console.error('error in dc action.'); } if (objData && objData.error) { dataSuccessUrl; dataSuccessCallback; msgContainers = t_forms__getErrorContainers(form, ''); errorBoxes = msgContainers.errorBoxes; allError = msgContainers.allError; Array.prototype.forEach.call(allError, function (error) { error.style.display = 'block'; }); Array.prototype.forEach.call(errorBoxes, function (error) { var errorWrapperText = error.querySelector('.t-form__errorbox-text'); if (errorWrapperText) { errorWrapperText.innerHTML = objData.error; } else { error.innerHTML = objData.error; } error.style.display = 'block'; }); t_addClass(form, 'js-send-form-error'); t_triggerEvent(form, 'tildaform:aftererror'); if (window.t_cart__discounts) { window.localStorage.removeItem('tcart_discounts'); } } else { if (objData && objData.needcaptcha) { if (formKey) { window.tildaForm.addTildaCaptcha(form, formKey); return false; } else { alert('Server busy. Please try again later.'); return false; } } var formResult = {}; if (objData && objData.results && objData.results[0]) { var strValue = objData.results[0]; strValue = strValue.split(':'); formResult.tranId = strValue[0] + ':' + strValue[1]; formResult.orderId = strValue[2] ? strValue[2] : '0'; if (formResult.orderId && formResult.orderId !== '0') { window.tildaForm.orderIdForStat = formResult.orderId; } } else { formResult.tranId = '0'; formResult.orderId = '0'; } /** * This check on jQuery is necessary for old users, who can * use custom functions on their projects with jQuery-objects. * See example of custom function on: * https://help-ru.tilda.cc/tips/javascript#rec115335034 */ if (typeof jQuery !== 'undefined') { jQuery(form).data('tildaformresult', formResult); } form.tildaTranId = formResult.tranId; form.tildaOrderId = formResult.orderId; var dataEventName = form.getAttribute('data-tilda-event-name') || ''; if (!dataEventName) { if ( dataFormCart === 'y' && objData && ((objData.next && objData.next.type && (objData.next.type !== 'function' || (objData.next.value && (objData.next.value.sysname === 'stripev3' || objData.next.value.installation === 'outersite')))) || !objData.next) ) { dataEventName = '/tilda/' + formId + '/payment/'; } else { dataEventName = '/tilda/' + formId + '/submitted/'; } } var title = 'Send data from form ' + formId; var price = 0; var product = ''; var priceEl = form.querySelector('.js-tilda-price'); if (window.Tilda && typeof window.Tilda.sendEventToStatistics === 'function') { if (window.tildaForm.tildapayment && window.tildaForm.tildapayment.amount) { price = window.tildaForm.tildapayment.amount; if (parseFloat(price) > 0) { title = 'Order ' + formResult.orderId; } } else if (priceEl) { price = priceEl.value; if (parseFloat(price) > 0) { title = 'Order ' + formResult.orderId; } } try { window.Tilda.sendEventToStatistics(dataEventName, title, product, price); } catch (error) { console.error('Error while sending statistics. Code status: ', error); } if (window.dataLayer) { window.dataLayer.push({ event: 'submit_' + formId, }); } } else { try { /* eslint no-undef: */ if (typeof ga !== 'undefined' && window.mainTracker !== 'tilda') { ga('send', { hitType: 'pageview', page: dataEventName, title: title, }); } if (window.mainMetrika && window[window.mainMetrika]) { window[window.mainMetrika].hit(dataEventName, { title: title, referer: window.location.href, }); } } catch (error) { console.error('Error while sending main metrica. Code status: ', error); } if (window.dataLayer) { window.dataLayer.push({ event: 'submit_' + formId, }); } } // Если в настройках ЛКИМ выставлена настройка "Создавать аккаунт автоматически", то в ответе // придет объект members Нам нужно инициализировать userbar и отрисовать блок авторизации заново if (dataFormCart === 'y' && objData.member?.token) { // Имитируем сохранения профиля в LocalStorage, чтобы после перезагрузке виджет мемберсов // инициализировался const profileName = 'tilda_members_profile' + projectId; const memberInfo = { token: objData.member?.token, projectid: projectId, }; localStorage.setItem(profileName, JSON.stringify(memberInfo)); localStorage.setItem( profileName + '_timestamp', Math.floor(Date.now() / 1000).toString() ); t_onFuncLoad('t_bd__init', () => { // Инициализируем мемберс t_bd__init(); // Реинициализируем блок авторизации в корзине window.tcart__initAuthAndDelivery(true, false); }); } try { t_triggerEvent(form, 'tildaform:aftersuccess'); if (dataFormSendedCallback && typeof jQuery === 'function') { // eslint-disable-next-line no-eval eval(dataFormSendedCallback + '(jQuery(form));'); } else if (dataFormSendedCallback) { // eslint-disable-next-line no-eval eval(dataFormSendedCallback + '(form);'); } } catch (error) { console.error('Error while call success callback. Code status: ', error); } /* If you need to send the data further, to the payment system */ if (objData && objData.next && objData.next.type) { window.tildaForm.payment(form, objData.next); dataSuccessUrl; return false; } window.tildaForm.successEnd(form, dataSuccessUrl, dataSuccessCallback); } } } } else { var tsDelta = Date.now() - startRequest; t_removeClass(btnSubmit, 't-btn_sending'); btnSubmit.tildaSendingStatus = '0'; msgContainers = t_forms__getErrorContainers(form, ''); errorBoxes = msgContainers.errorBoxes; allError = msgContainers.allError; if (!secondFormTypeXhr || (secondFormTypeXhr.status == 0 && tsDelta < 100)) { Array.prototype.forEach.call(allError, function (error) { error.innerHTML = 'Request error (sending form data). Please check internet connection...'; }); } else if ( secondFormTypeXhr && (secondFormTypeXhr.status >= 500 || secondFormTypeXhr.status == 408 || secondFormTypeXhr.status == 410 || secondFormTypeXhr.status == 429 || secondFormTypeXhr.statusText == 'timeout') /* Похоже 'timeout' отсутствует https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/statusText */ && window.tildaForm.endpoint.indexOf('forms.tilda') !== -1 ) { window.tildaForm.endpoint = 'forms2.tildacdn.com'; window.tildaForm.send(form, btnSubmit, formType, formKey); return false; } else if (secondFormTypeXhr && secondFormTypeXhr.responseText) { Array.prototype.forEach.call(allError, function (error) { error.innerHTML = '[' + secondFormTypeXhr.status + '] ' + secondFormTypeXhr.responseText + '. Please, try again later.'; }); } else if (secondFormTypeXhr && secondFormTypeXhr.statusText) { Array.prototype.forEach.call(allError, function (error) { error.innerHTML = 'Error [' + secondFormTypeXhr.status + ', ' + secondFormTypeXhr.statusText + ']. Please, try again later.'; }); } else { Array.prototype.forEach.call(allError, function (error) { error.innerHTML = '[' + secondFormTypeXhr.status + '] Unknown error. Please, try again later.'; }); } Array.prototype.forEach.call(allError, function (error) { error.style.display = 'block'; }); Array.prototype.forEach.call(errorBoxes, function (error) { error.style.display = 'block'; }); t_addClass(form, 'js-send-form-error'); t_triggerEvent(form, 'tildaform:aftererror'); } } return true; }; secondFormTypeXhr.send(formData); return false; } else if (form.getAttribute('data-is-formajax') === 'y') { const { status, contentType, data: dataForm } = t_forms__getFormData(form); if (status === 'invalid') { return false; } var formAjaxXhr = new XMLHttpRequest(); formAjaxXhr.open('POST', form.getAttribute('action'), true); formAjaxXhr.setRequestHeader('Content-Type', contentType); formAjaxXhr.setRequestHeader('Accept', 'text/plain, */*; q=0.01'); formAjaxXhr.onreadystatechange = function () { if (formAjaxXhr.readyState === 4) { if (formAjaxXhr.status >= 200 && formAjaxXhr.status < 400) { var successBox = form.querySelector('.js-successbox'); var dataSuccessUrl = form.getAttribute('data-success-url'); var dataSuccessCallback = form.getAttribute('data-success-callback'); t_removeClass(btnSubmit, 't-btn_sending'); btnSubmit.tildaSendingStatus = '0'; var ajaxData = formAjaxXhr.responseText; if (ajaxData) { if (ajaxData.substring(0, 1) == '{') { var objData = JSON.parse(ajaxData); if (typeof objData === 'object') { if (objData && objData.message && objData.message !== 'OK') { successBox.innerHTML = objData.message; } else if (objData && objData.error) { msgContainers = t_forms__getErrorContainers( form, 'Unknown error. Please, try again later.' ); errorBoxes = msgContainers.errorBoxes; allError = msgContainers.allError; Array.prototype.forEach.call(allError, function (error) { error.style.display = 'block'; error.innerHTML = objData.error; }); Array.prototype.forEach.call(errorBoxes, function (error) { error.style.display = 'block'; }); t_addClass(form, 'js-send-form-error'); t_triggerEvent(form, 'tildaform:aftererror'); return false; } } } else { successBox.innerHTML = ajaxData; t_parseScripts(successBox, ''); } } var linkPage = '/tilda/' + formId + '/submitted/'; var title = 'Send data from form ' + formId; if (window.Tilda && typeof window.Tilda.sendEventToStatistics === 'function') { window.Tilda.sendEventToStatistics(linkPage, title, '', 0); } else if (typeof ga !== 'undefined' && window.mainTracker !== 'tilda') { ga('send', { hitType: 'pageview', page: linkPage, title: title, }); } else if (window.mainMetrika > '' && window[window.mainMetrika]) { window[window.mainMetrika].hit(linkPage, { title: title, referer: window.location.href, }); } t_triggerEvent(form, 'tildaform:aftersuccess'); window.tildaForm.successEnd(form, dataSuccessUrl, dataSuccessCallback); } else { t_removeClass(btnSubmit, 't-btn_sending'); btnSubmit.tildaSendingStatus = '0'; msgContainers = t_forms__getErrorContainers(form, ''); errorBoxes = msgContainers.errorBoxes; allError = msgContainers.allError; var data = formAjaxXhr.responseText; Array.prototype.forEach.call(allError, function (error) { if (data) { error.innerHTML = data + '. Please, try again later. [' + formAjaxXhr.status + ']'; } else if (formAjaxXhr.statusText) { error.innerHTML = 'Error [' + formAjaxXhr.statusText + ']. Please, try again later. [' + formAjaxXhr.status + ']'; } else { error.innerHTML = 'Unknown error. Please, try again later. [' + formAjaxXhr.status + ']'; } error.style.display = 'block'; }); Array.prototype.forEach.call(errorBoxes, function (error) { error.style.display = 'block'; }); t_addClass(form, 'js-send-form-error'); t_triggerEvent(form, 'tildaform:aftererror'); } } return true; }; formAjaxXhr.send(dataForm); return false; } else if (form.getAttribute('action').indexOf(window.tildaForm.endpoint) == -1) { t_removeClass(btnSubmit, 't-btn_sending'); btnSubmit.tildaSendingStatus = '3'; form.submit(); return true; } else { return false; } }; /* Left for compatibility with old blocks */ window.validateForm = function ($jform) { return window.tildaForm.validate($jform); }; /** * Заполнение кук UTM тегами при загрузке страницы * Куки позже будут использованы в форме для отправки * * Анонимная функция позволит изолировать переменные, например, date */ (function () { try { var TILDAPAGE_URL = window.location.href, TILDAPAGE_QUERY, TILDAPAGE_UTM = ''; if (TILDAPAGE_URL.toLowerCase().indexOf('utm_') !== -1) { TILDAPAGE_URL = TILDAPAGE_URL.toLowerCase(); TILDAPAGE_QUERY = TILDAPAGE_URL.split('?'); TILDAPAGE_QUERY = TILDAPAGE_QUERY[1]; if (typeof TILDAPAGE_QUERY == 'string') { var arPair, i, arParams = TILDAPAGE_QUERY.split('&'); for (i in arParams) { if (typeof arParams[i] != 'function') { arPair = arParams[i].split('='); if (arPair[0].substring(0, 4) == 'utm_') { TILDAPAGE_UTM = TILDAPAGE_UTM + arParams[i] + '|||'; } } } if (TILDAPAGE_UTM.length > 0 && (!window.tildastatcookie || window.tildastatcookie != 'no')) { var date = new Date(); date.setDate(date.getDate() + 30); document.cookie = 'TILDAUTM=' + encodeURIComponent(TILDAPAGE_UTM) + '; path=/; expires=' + date.toUTCString(); } } } } catch (error) { /* */ } })(); /** * MAIN SCRIPT WORK BEGINS HERE */ /* Iteration rec blocks and init functions */ function t_forms__initForms() { var recBlocks = document.querySelectorAll('.r:not([data-record-type="1093"], [data-parenttplid="1093"])'); /* This object is used in several functions, therefore it is declared global */ window.t_forms__inputData = {}; t_forms__addRecaptcha(); const canonicalUrl = t_forms__getCanonicalUrl(); const isCachedPage = t_forms__isCachedPage(); Array.prototype.forEach.call(recBlocks, function (rec) { var recid = rec.id; if (window.initForms[recid]) return; const form = t_forms__getRecForm(rec); if (isCachedPage && form) { // если форма открыта закешированной странице // показываем попап с предложением перейти на оригинальную страницу при нажатии на любой контрол на форме t_forms__onCachedPageAction(form, canonicalUrl); // отключаем автозаполнение инпутов формы // чтобы при клике интерфейс автозаполнения не перебивал открывшийся попап // и не отвлекал пользователя от выбора перехода на оригинальную страницу t_forms__offInputsAutocomplete(form); return; } t_forms__initVibeForms(rec); t_forms__initFormFields(rec); t_forms__initEventPlaceholder(rec); t_forms__addInputItsGood(rec); t_forms__addAttrAction(rec); t_forms__onSubmit(rec); t_forms__onClick(rec); t_forms__onRender(rec); if (form) t_forms__initFormMutationListeners(rec); t_forms__addFocusOnTab(rec); t_onFuncLoad('t_throttle', function () { window.addEventListener( 'resize', t_throttle(function () { t_forms__calculateInputsWidth(recid); }) ); }); window.initForms[recid] = true; // на время поэтапной раскатки новго дизайна сообщения об успехе // добавляем необходимые классы и атрибуты здесь, по условию if (form && t_forms__isNewSuccessBox(form)) { form.setAttribute('data-success-popup', 'y'); const successBox = form.querySelector('.t-form__successbox'); if (successBox) { successBox.classList.add('t-form-success-popup'); } } }); } /** * Инициализирует вайб-блок формы у которых нет никаких классов форм. * * Тем самым реализуется подключение любых форм которые попали в вайб-блок к нашей отправке. * * @param {HTMLElement} rec */ function t_forms__initVibeForms(rec) { Array.from(rec.querySelectorAll('form')).forEach((form, index) => { const isVibeBlock = Boolean(form.closest('.t1370')); const isFormProcess = form.classList.contains('js-form-proccess'); const isFormOff = form.classList.contains('t-form-off'); const hasAction = Boolean(form.getAttribute('action')); if (!isVibeBlock || isFormProcess || isFormOff || hasAction) { return; } form.classList.add('js-form-proccess'); form.setAttribute('data-formactiontype', '2'); form.setAttribute('data-vibeblock-auto-init', 'y'); form.setAttribute('data-success-popup', 'y'); if (!form.querySelector('.js-successbox')) { form.insertAdjacentHTML( 'beforeend', '' ); } if (!form.id) { const recordId = rec.id.replace(/^rec/, ''); form.id = 'form' + recordId + '_' + (index + 1); } if (!form.getAttribute('name')) { form.setAttribute('name', form.id); } }); } /** * В стандартных блоках (не зеро) поле с вводом своего варианта ответа исчезает по событию blur. * При клике на submit-кнопку формы, это событие активируется и поле своего варианта скрывается. * Нам важно его показать при пробросе ошибки, чтобы пользователь понимал какие именно данные он не ввёл. * Поэтому создаём таймер в 500мс для показа пустого поля ввода. * * @param {HTMLInputElement & {timerID: number}} inputTextField */ function t_forms__validateOwnVariant(inputTextField) { if (!inputTextField) return; if (inputTextField.value) inputTextField.value = ''; // если были только пробелы - очищаем поле const isZero = inputTextField.closest('.tn-atom__form'); if (isZero) return; if (inputTextField.timerID) clearTimeout(inputTextField.timerID); inputTextField.timerID = setTimeout(() => { inputTextField.classList.add('t-input-ownanswer_active'); inputTextField.style.display = 'flex'; clearTimeout(inputTextField.timerID); }, 500); } /* a11y: add a visual display of focus when interacting with the page from the keyboardt-submit */ function t_forms__addFocusOnTab(rec) { if (window.isMobile) return; var focusableElements = rec.querySelectorAll('.t-input, .t-select'); if (!focusableElements) return; /* check if event focus from mouse or from keyboard */ var handlerType = null; document.addEventListener('keydown', function () { handlerType = 'keyboard'; }); document.addEventListener('mousedown', function () { handlerType = 'mouse'; }); document.addEventListener('visibilitychange', function () { handlerType = 'mouse'; }); Array.prototype.forEach.call(focusableElements, function (focusableElement) { focusableElement.addEventListener('focus', function () { if (handlerType === 'keyboard') { var elementToFocus = focusableElement; if ( elementToFocus.classList.contains('t-input_pvis') || elementToFocus.classList.contains('t-input-phonemask') ) { elementToFocus = elementToFocus.parentElement; } elementToFocus.classList.add('t-focusable'); handlerType = null; } }); focusableElement.addEventListener('blur', function () { focusableElement.classList.remove('t-focusable'); }); }); } /* Resetting standard inputs handlers and hovering own event listeners */ function t_forms__initEventPlaceholder(rec) { var eventFocus = 'focus'; var eventBlur = 'blur'; if (!document.addEventListener) { eventFocus = 'focusin'; eventBlur = 'focusout'; } t_removeEventListener(rec, eventFocus, t_forms__removePlaceholder); t_addEventListener(rec, eventFocus, t_forms__removePlaceholder, true); t_removeEventListener(rec, eventBlur, t_forms__addPlaceholder); t_addEventListener(rec, eventBlur, t_forms__addPlaceholder, true); } /* Remove placeholder on focus event */ function t_forms__removePlaceholder(event) { var targetEvent = event || window.event; var input = targetEvent.target || targetEvent.srcElement; if (input.tagName !== 'INPUT') return; var inputGroup = input.closest('[data-input-lid]'); var strPlace = input.getAttribute('placeholder'); var inputId = ''; if (inputGroup) { inputId = inputGroup.getAttribute('data-input-lid'); } else { var form = input.closest('form'); if (form) inputId = form.getAttribute('data-input-lid'); } if (strPlace && inputId) { window.t_forms__inputData[inputId] = strPlace; input.setAttribute('placeholder', ''); } } /** * Move to input with error * @param {Element} elementToFocus * @param {Element} currentErrorItem */ function t_forms__addMoveToInputWithErrorClickHandler(elementToFocus, currentErrorItem) { if (!currentErrorItem || !elementToFocus) return; currentErrorItem.TElementToFocus = elementToFocus; currentErrorItem.removeEventListener('click', t_forms__handleClickOnError); currentErrorItem.addEventListener('click', t_forms__handleClickOnError); } function t_forms__handleClickOnError(event) { event.preventDefault(); const errorItem = event.target.closest('.t-form__errorbox-item'); if (!errorItem) return; const elementToFocus = errorItem.TElementToFocus; t_forms__focusInput(elementToFocus); } /* Add placeholder on blur event */ function t_forms__addPlaceholder(event) { var targetEvent = event || window.event; var input = targetEvent.target || targetEvent.srcElement; var inputGroup = input.closest('[data-input-lid]'); var inputId = ''; if (inputGroup) { inputId = inputGroup.getAttribute('data-input-lid'); } else { var form = input.closest('form'); if (form) inputId = form.getAttribute('data-input-lid'); } var strPlace = window.t_forms__inputData[inputId] || ''; if (strPlace && inputId) { input.setAttribute('placeholder', strPlace); window.t_forms__inputData[inputId] = ''; } } /* Add in form input with the value it's good */ function t_forms__addInputItsGood(rec) { var allForms = rec.querySelectorAll('.js-form-proccess[data-formactiontype]'); Array.prototype.forEach.call(allForms, function (form) { var formActionType = form.getAttribute('data-formactiontype'); var inputItsGood = form.querySelector('input[name="form-spec-comments"]'); if (formActionType !== '1' && !inputItsGood) { form.insertAdjacentHTML( 'beforeend', '
' ); } }); } /* Add attr action in form */ function t_forms__addAttrAction(rec) { var allForms = rec.querySelectorAll('.js-form-proccess'); Array.prototype.forEach.call(allForms, function (form) { var formType = form.getAttribute('data-formactiontype'); if (formType === '2') form.setAttribute('action', '#'); }); } /* Calculate width of inputs */ function t_forms__calculateInputsWidth(recordId) { var recId = recordId; if (recId) recId = recId.replace('rec', ''); var rec = document.querySelector('#rec' + recId); if ( !recId && (document.body.classList.contains('t706__body_cartwinshowed') || document.body.classList.contains('t706__body_cartpageshowed')) ) { rec = document.querySelector('.t706'); } if (!rec) return; var formWrapper = rec.querySelector('.t-form__inputsbox'); if (!formWrapper) return; // TODO: перенести добавление класса в tpl после тестирования if (formWrapper.closest('.t706')) { formWrapper.classList.add('t-form__inputsbox_inrow'); } var fields = rec.querySelectorAll('.t-input-group_widthdef, .t-input-group_inrow'); if (!formWrapper.classList.contains('t-form__inputsbox_inrow')) { fields = rec.querySelectorAll('.t-input-block_width'); } if (fields.length === 0) return; // TODO: перенести добавление класса в tpl после тестирования if (formWrapper.classList.contains('t-form__inputsbox_vertical-form') || formWrapper.closest('.t706')) { formWrapper.classList.add('t-form__inputsbox_flex'); } var formWrapperWidth = formWrapper.offsetWidth; var fieldsType = ['rd', 'ri', 'uc', 'ws', 'hd', 'fr', 'st']; Array.prototype.forEach.call(fields, function (currentField) { var field = currentField; if (!formWrapper.classList.contains('t-form__inputsbox_inrow')) { field = field.closest('.t-input-group'); } var nextField; if (field && field.classList.contains('t-input-group_inrow-withsibling')) { nextField = field.nextElementSibling; var incorrectType = fieldsType.filter(function (type) { return nextField.classList.contains('t-input-group_' + type); }); if ( nextField && incorrectType.length === 0 && ((nextField.classList.contains('t-input-group_inrow') && !field.classList.contains('t-input-group_widthdef')) || (field.classList.contains('t-input-group_widthdef') && nextField.classList.contains('t-input-group') && !nextField.classList.contains('t-input-group_inrow'))) ) { // Если у поля включено объединение в один ряд и // задана ширина у него и соседнего, либо // ширина по умолчанию у него и соседнего nextField.classList.add('t-input-group_inonerow'); } else { field.classList.remove('t-input-group_inrow-withsibling'); field.classList.add('t-input-group_inrow-last'); return; } } else { // Если нет следующего поля для объединения в ряд field.classList.add('t-input-group_inrow-last'); } if ( nextField && field.classList.contains('t-input-group_widthdef') && field.classList.contains('t-input-group_inrow-withsibling') && nextField.classList.contains('t-input-group_inonerow') && !nextField.classList.contains('t-input-group_inrow') ) { // Если у поля ширина по умолчанию, включено объединение в один ряд // и следующее поле так же с шириной по умолчанию nextField.classList.add('t-input-group_widthdef'); if (!nextField.classList.contains('t-input-group_inrow-withsibling')) { // Если нет следующего поля для объединения в ряд nextField.classList.add('t-input-group_inrow-last'); } if (nextField.classList.contains('t-input-group_inrow')) { field.classList.add('t-input-group_inrow-last'); } } // TODO: обратная совместимость для певого варианта расчёта ширины if (!formWrapper.classList.contains('t-form__inputsbox_inrow')) { t_forms__calculateFieldsWidthInJS(field, formWrapperWidth); } }); var allLastFieldsWithCertainWidth = rec.querySelectorAll( '.t-input-group_inrow.t-input-group_inonerow.t-input-group_inrow-last' ); if (allLastFieldsWithCertainWidth.length > 0) { t_forms__moveFieldToNextRow(allLastFieldsWithCertainWidth); } var allLastFieldsWithDefWidth = rec.querySelectorAll('.t-input-group_widthdef.t-input-group_inrow-last'); if (formWrapper.classList.contains('t-form__inputsbox_inrow') && allLastFieldsWithDefWidth.length > 0) { t_forms__combineFieldsWithDefWidth(allLastFieldsWithDefWidth, recId); } } /* Adds margin-right to the last field in row if common width of fields in row > 100% */ function t_forms__moveFieldToNextRow(allLastFields) { var rows = t_forms__createArrWithAllRows(allLastFields, 't-input-group_inrow'); rows.forEach(function (row) { var isLongNextField = false; row.forEach(function (field) { if ( field.classList.contains('t-input-group_inrow-last') && field.nextElementSibling && !field.nextElementSibling.classList.contains('t-input-group_inonerow') ) { isLongNextField = true; } }); if (isLongNextField) return; // Считаем общую ширину всех полей в ряду var commonWidth = row.reduce(function (sum, field) { var fieldClasses = field.classList.value.split(' '); var widthClass = fieldClasses.filter(function (fieldClass) { return fieldClass.indexOf('t-input-group_width') !== -1; }); widthClass = widthClass[0]; var characterQuantity = 2; if (widthClass.indexOf('100') !== -1) { characterQuantity = 3; } var fieldWidth = Number(widthClass.substr(widthClass.length - 2, characterQuantity)); return sum + fieldWidth; }, 0); if (commonWidth <= 100) return; // Если ширина > 100, добавляем отступ к последнему полю, // чтобы следующее за ним короткое поле переносилось в следующий ряд row.forEach(function (field) { if (field.classList.contains('t-input-group_inrow-last')) { field.style.marginRight = 'calc(100% - (' + (commonWidth - 100) + '%)'; field.style.flex = '0 0 auto'; } }); }); } /* Combine fields with default width into row */ function t_forms__combineFieldsWithDefWidth(allLastFields, recId) { var allRowsWithDefWidth = []; var rows = t_forms__createArrWithAllRows(allLastFields, 't-input-group_widthdef'); rows.forEach(function (row) { var maxRowLength = 4; if (row.length > maxRowLength) { for (var i = 0; i < row.length; i += maxRowLength) { var newRow = row.slice(i, i + maxRowLength); allRowsWithDefWidth.push(newRow); } } else { allRowsWithDefWidth.push(row); } }); allRowsWithDefWidth.forEach(function (row) { var rowWidth = { 4: '25', 3: '33', 2: '50', }; var widthClass = 't-input-group_width' + (rowWidth[row.length] || '100'); row.forEach(function (field) { field.classList.add(widthClass); if (field.classList.contains('t-input-group_rg')) { var lid = field.getAttribute('data-input-lid'); window.t_input_range_init(recId, lid); } }); }); } /* Creates array with every row in form */ function t_forms__createArrWithAllRows(allLastFields, certainClass) { var allSequences = []; var oneSequence = []; // Создаём массив с подмассивами из всех последовательностей // с полями в одном ряду Array.prototype.forEach.call(allLastFields, function (lastField) { var field = lastField; oneSequence.push(field); while ( field.previousElementSibling && field.previousElementSibling.classList.contains(certainClass) && !field.previousElementSibling.classList.contains('t-input-group_inrow-last') ) { field = field.previousElementSibling; oneSequence.push(field); } allSequences.push(oneSequence.reverse()); oneSequence = []; }); return allSequences; } /* First version of form columns width setting */ function t_forms__calculateFieldsWidthInJS(field, formWrapperWidth) { var marginLeft = 15; var columns = { 1: 't-input-block_width100', 2: 't-input-block_width50', 3: 't-input-block_width33', 4: 't-input-block_width25', }; for (var i in columns) { if (field.classList.contains(columns[i])) { field.style.width = (formWrapperWidth - marginLeft * (i - 1)) / i + 'px'; var label = field.previousElementSibling; if (label && label.classList.contains('t-input-title')) { label.style.width = (formWrapperWidth - marginLeft * (i - 1)) / i + 'px'; } if (window.innerWidth < 480) { if (field) field.style.width = '100%'; if (label) label.style.width = '100%'; } } } } /* Add submit for form */ function t_forms__onSubmit(rec) { var allForms = rec.querySelectorAll('.js-form-proccess'); Array.prototype.forEach.call(allForms, function (form) { t_removeEventListener(form, 'submit', t_forms__submitEvent); t_addEventListener(form, 'submit', t_forms__submitEvent); }); } /* Add event click for submit in form */ function t_forms__onClick(rec) { t_addEventListener(rec, 'dblclick', t_forms__initBtnDblClick); t_removeEventListener(rec, 'click', t_forms__initBtnClick); t_addEventListener(rec, 'click', t_forms__initBtnClick); } /** * Добавляет обработчик клика на форму с показом уведомления о том, что форма открыта не на оригинальной странице * @param {Node} rec * @param {string} canonicalUrl */ function t_forms__onCachedPageAction(rec, canonicalUrl) { t_addEventListener(rec, 'click', function () { t_forms__showWrongPageUrlMessage(canonicalUrl); }); t_addEventListener(rec, 'submit', function (event) { event.preventDefault(); event.stopPropagation(); t_forms__showWrongPageUrlMessage(canonicalUrl); }); } /** * Отключает автозаполнение для инпутов в форме * @param {Node} rec */ function t_forms__offInputsAutocomplete(rec) { const inputs = rec.querySelectorAll('.t-input'); Array.prototype.forEach.call(inputs, function (input) { input.setAttribute('autocomplete', 'off'); }); } /** * DblClick Event default * @param {MouseEvent} event - event * @returns {boolean || undefined} */ function t_forms__initBtnDblClick(event) { var dblClickEvent = event || window.event; var target = dblClickEvent.target || dblClickEvent.srcElement; if (!target.closest('[type="submit"]')) return; dblClickEvent.preventDefault ? dblClickEvent.preventDefault() : (dblClickEvent.returnValue = false); } /* Init click for button submit */ function t_forms__initBtnClick(event) { var btnClickEvent = event || window.event; var target = btnClickEvent.target || btnClickEvent.srcElement; var btnSubmit = target.closest('[type="submit"]') ? target : false; if (!btnSubmit) return; var form = btnSubmit.closest('.js-form-proccess'); if (!form) return; btnClickEvent.preventDefault ? btnClickEvent.preventDefault() : (btnClickEvent.returnValue = false); var formId = form.getAttribute('id'); var arrErrors; var btnStatus = ''; if (btnSubmit.tildaSendingStatus) { btnStatus = btnSubmit.tildaSendingStatus; } /* 0 - I can send, 1 - I send as soon as sent, set again to 0 */ if (btnStatus && btnStatus >= 1) return; if (t_hasClass(btnSubmit, 't706__submit_disable')) return; t_addClass(btnSubmit, 't-btn_sending'); btnSubmit.tildaSendingStatus = '1'; window.tildaForm.hideErrors(form); arrErrors = window.tildaForm.validate(form); if (window.tildaForm.showErrors(form, arrErrors)) { t_removeClass(btnSubmit, 't-btn_sending'); btnSubmit.tildaSendingStatus = '0'; } else { var allRecords = document.getElementById('allrecords'); var formKey = allRecords.getAttribute('data-tilda-formskey'); var formType = parseInt(form.getAttribute('data-formactiontype')); var inputsServices = form.querySelectorAll('.js-formaction-services'); if (!inputsServices.length && formType !== 1 && !formKey) { var msgContainers = t_forms__getErrorContainers(form, ''); var errorBoxes = msgContainers.errorBoxes; var allError = msgContainers.allError; Array.prototype.forEach.call(allError, function (error) { error.innerHTML = 'Please set receiver in block with forms'; error.style.display = 'block'; }); Array.prototype.forEach.call(errorBoxes, function (box) { box.style.display = 'block'; }); t_addClass(form, 'js-send-form-error'); t_removeClass(btnSubmit, 't-btn_sending'); btnSubmit.tildaSendingStatus = '0'; t_triggerEvent(form, 'tildaform:aftererror'); return; } /* Add custom google recaptcha from the user */ if (form.querySelector('.g-recaptcha') && window.grecaptcha) { window.tildaForm.currentFormProccessing = { form: form, btn: btnSubmit, formtype: formType, formskey: formKey, }; var captchaId = form.tildaCaptchaClientId; if (!captchaId) { var opts = { size: 'invisible', sitekey: form.getAttribute('data-tilda-captchakey'), callback: window.tildaForm.captchaCallback, }; captchaId = window.grecaptcha.render(formId + 'recaptcha', opts); form.tildaCaptchaClientId = captchaId; } else { window.grecaptcha.reset(captchaId); } window.grecaptcha.execute(captchaId); return; } window.tildaForm.send(form, btnSubmit, formType, formKey); } } /* Add event render for ZB */ function t_forms__onRender(rec) { var ist396 = !!rec.querySelector('.t396'); if (!ist396) return; t_removeEventListener(rec, 'render', t_forms__renderEvent); t_addEventListener(rec, 'render', t_forms__renderEvent); } /* Handled render trigger for ZB */ function t_forms__renderEvent() { t_forms__onSubmit(this); } function t_forms__initFormMutationListeners(rec) { if (!rec) return; t_removeEventListener(rec, 'tildaform:contentchanged', t_forms__onFormContentChanged); t_addEventListener(rec, 'tildaform:contentchanged', t_forms__onFormContentChanged); } function t_forms__onFormContentChanged(event) { var target = event && event.target ? event.target : this; t_forms__recalcCoverHeightByFormMutation(target); } function t_forms__recalcCoverHeightByFormMutation(target) { var form = target && target.closest ? target.closest('form') : null; if (!form && target && target.querySelector) { form = target.querySelector('form'); } if (!form) return; var cover = form.closest('.t-cover'); if (!cover) return; var rec = form.closest('.r'); if (!rec || !rec.id || rec.id.indexOf('rec') !== 0) return; var recId = rec.id.replace('rec', ''); if (!recId) return; t_onFuncLoad('t_cover__recalcContentHeight', function () { t_cover__recalcContentHeight(recId, false, 0); }); } /* Submit event for form */ function t_forms__submitEvent(event) { var form = event; if (event.target) form = event.target; if (!form) return; var btnSubmit = form.querySelector('[type="submit"]'); var btnStatus = ''; if (btnSubmit && btnSubmit.tildaSendingStatus) { btnStatus = btnSubmit.tildaSendingStatus; } if (btnStatus && btnStatus === '3') { btnSubmit.tildaSendingStatus = ''; } else { if (btnSubmit && !t_hasClass(btnSubmit, 't706__submit_disable')) { btnSubmit.click(); } event.preventDefault ? event.preventDefault() : (event.returnValue = false); } } /** * ALL ADDITIONAL FUNCTIONS */ function t_asyncLoad(input) { var dataMask = input.getAttribute('data-tilda-mask'); var dataPlaceholder = input.getAttribute('data-tilda-mask-holder'); var dataInit = input.getAttribute('data-tilda-mask-init'); if (dataMask && !dataInit) { if (dataPlaceholder) { t_onFuncLoad('t_customMask__mask', function () { t_customMask__mask(input, dataMask, { placeholder: dataPlaceholder, }); }); } else { t_onFuncLoad('t_customMask__mask', function () { t_customMask__mask(input, dataMask); }); } input.setAttribute('data-tilda-mask-init', '1'); } } /** * The function looks for containers for error messages. * Inserts them into the layout as needed and returns a collection * of containers and items for error messages * * @param {node} form * @param {string} innerText * @returns object with errors containers nodes */ function t_forms__getErrorContainers(form, innerText) { var errorBoxes = form.querySelectorAll('.js-errorbox-all'); var allError = form.querySelectorAll('.js-errorbox-all .js-rule-error-all'); if (!errorBoxes.length) { form.insertAdjacentHTML('afterbegin', '
'); errorBoxes = form.querySelectorAll('.js-errorbox-all'); } if (!allError.length) { Array.prototype.forEach.call(errorBoxes, function (error) { error.insertAdjacentHTML('beforeend', '

' + innerText + '

'); }); allError = form.querySelectorAll('.js-errorbox-all .js-rule-error-all'); } return { errorBoxes: errorBoxes, allError: allError, }; } /* Add custom recaptcha */ function t_forms__addRecaptcha() { var allRecaptchas = document.querySelectorAll('.js-tilda-captcha'); Array.prototype.forEach.call(allRecaptchas, function (recaptcha) { var captchaKey = recaptcha.getAttribute('data-tilda-captchakey'); if (captchaKey) { var formId = recaptcha.getAttribute('id'); if (!window.tildaForm.isRecaptchaScriptInit) { var head = document.head; var script = document.createElement('script'); window.tildaForm.isRecaptchaScriptInit = true; script.type = 'text/javascript'; script.src = 'https://www.google.com/recaptcha/api.js?render=explicit'; script.async = true; head.appendChild(script); head.insertAdjacentHTML( 'beforeend', '' ); } if (!document.getElementById(formId + 'recaptcha')) { recaptcha.insertAdjacentHTML( 'beforeend', '
' ); } } else { t_removeClass(recaptcha, 'js-tilda-captcha'); } }); } const t_forms__setFormErrorMsg = (errorContainer, errorMsg) => { if (errorContainer.getAttribute('data-rule-filled')) { errorContainer.style.display = 'block'; return; } if (!errorMsg) return; errorContainer.innerHTML = '' + errorMsg + ''; errorContainer.style.display = 'block'; }; /** * @param {Element} form */ function t_forms__showEmptyFormError(form) { const formErrorContainers = form.querySelectorAll('.js-rule-error-all'); const emptyFormMsg = t_forms__getMsg('emptyfill'); formErrorContainers.forEach(errorContainer => { t_forms__setFormErrorMsg(errorContainer, emptyFormMsg); }); const firstInputGroup = form.querySelector('.t-input-group'); t_forms__addMoveToInputWithErrorClickHandler(firstInputGroup, formErrorContainers[0]); } function t_forms__showInputErrors(form, inputGroup, errorItem) { if (!inputGroup) return; // obj === 'none' относится к ошибке пустой формы if (errorItem.obj === 'none') return; inputGroup.classList.add('js-error-control-box'); const errorInputs = inputGroup.querySelectorAll('.t-input-error'); errorItem.type.forEach(errorType => { const customErrorMsg = t_forms__getCustomMessage(form, errorType); const errorText = customErrorMsg || t_forms__getFieldErrorText(errorType); if (!errorText) return; errorInputs.forEach(input => { input.innerHTML = errorText; }); }); } /** * * @param {Element} form * @param {FormError} errorItem * @param {ReturnType} focusListeners */ function t_forms__showFormErrors(form, errorItem, focusListeners) { errorItem.type.forEach(errorType => { const errorMsgContainers = form.querySelectorAll('.js-rule-error-' + errorType); const customErrorMsg = t_forms__getCustomMessage(form, errorType); const errorMsg = customErrorMsg || t_forms__getMsg(errorType); const errorsToUpdate = errorMsgContainers.length ? errorMsgContainers : form.querySelectorAll('.js-rule-error-all'); errorsToUpdate.forEach(currentErrorMsgContainer => { t_forms__setFormErrorMsg(currentErrorMsgContainer, errorMsg, errorType); // Для каждого общего сообщения об ошибке добавляем обработчик click, который фокусируется на нужном поле. focusListeners.add(errorType, errorItem.obj, currentErrorMsgContainer); }); }); } function t_forms__getFieldErrorText(errorType) { const fieldErrorMsg = t_forms__getMsg(errorType + 'field'); if (fieldErrorMsg) return fieldErrorMsg; const generalErrorMsg = t_forms__getMsg(errorType); return generalErrorMsg; } /** * @param {Element} form * @param {ValidationError} errorType */ function t_forms__getCustomMessage(form, errorType) { // Находим первый контейнер с этой ошибкой const errorMsgContainer = form.querySelector('.js-rule-error-' + errorType); if (!errorMsgContainer) return ''; const originalMsg = errorMsgContainer.getAttribute('data-original-msg'); const escapedMsg = originalMsg ? originalMsg.replace(/\\\'/g, ''') : originalMsg; if (escapedMsg != null) { return escapedMsg; } // Сохраняем первоначальный текст ошибки. Если он есть, то это кастомное сообщение пользователя. // Нужно его сохранить, чтобы показать корректное сообщение для полей формы const msg = errorMsgContainer ? errorMsgContainer.textContent.replace(/\\\'/g, ''') : ''; errorMsgContainer.setAttribute('data-original-msg', msg); return msg; } function t_forms__createErrorFocusHash() { const inputErrors = {}; return { /** * Добавляет слушатель клика на ошибку, если он не был добавлен ранее. * @param {ValidationError} errorType * @param {Element | 'none' | null} inputToFocus * @param {Element} errorContainer */ add: (errorType, inputToFocus, errorContainer) => { const isInputElement = inputToFocus instanceof Element; if (inputErrors[errorType] || !inputToFocus || !isInputElement) return; t_forms__addMoveToInputWithErrorClickHandler(inputToFocus, errorContainer); inputErrors[errorType] = inputToFocus; }, }; } /** * @param {FormError} error */ function t_forms__scrollToInputWithError(error) { if (!error) return; const { obj: inputWithError } = error; const isElement = inputWithError instanceof Element; if (inputWithError === 'none' || !isElement) return; if (window.isMobile) { const scrollTarget = inputWithError.querySelector('input, textarea, select') || inputWithError; t_onFuncLoad('t_scrollTo', () => { t_scrollTo(scrollTarget); }); } t_forms__focusInput(inputWithError); } /** * * @param {Element | undefined} inputOrInputGroup */ async function t_forms__focusInput(inputOrInputGroup) { if (!inputOrInputGroup) return; const inputGroup = inputOrInputGroup.closest('.t-input-group'); if (!inputGroup) return; try { const fieldApi = await formsApi.t_formsApi__initTildaField(inputGroup); fieldApi.focus(); } catch (e) { inputOrInputGroup.focus(); } } /** * Shows t-errorbox-middle and t-errorbox-bottom containers * @param {Element} form */ function t_forms__showFormErrorsContainers(form) { const errorBoxes = form.querySelectorAll('.js-errorbox-all'); errorBoxes.forEach(error => { error.style.display = 'block'; }); } /** * Получение элемента для jquery. * @param {Element | { 0: Element }} elem */ function t_forms__getElement(elem) { if (!(elem instanceof Element)) { return elem[0]; } return elem; } /** * The function accepts a message code, e.g. "req" is the code for the "Required field" message in English. * The function determines the language and returns the required message in the language set on the page. */ function t_forms__getMsg(msg) { var dict = []; var lang = window.t_forms__lang; dict['EN'] = { success_title: 'Thank you!', success_text: 'Data submitted successfully', success_btn: 'Done', success_btn_redirect: 'Continue', success_info: "You'll be automatically redirected in:", success_info_redirect_error: 'Redirecting...', success: 'Thank you! Your data has been submitted.', successorder: 'Thank you! Order created. Please wait while you are redirected to the payment page...', email: 'Please enter a valid email address', url: 'Please put a correct URL', phone: 'Please put a correct phone number', number: 'Please put a correct number', date: 'Please put a correct date', time: 'Please put a correct time (HH:mm)', name: 'Please put a name', namerus: 'Please put a correct name (only cyrillic letters)', nameeng: 'Please put a correct name (only latin letters)', string: 'You put incorrect symbols. Only letters, numbers and punctuation symbols are allowed', req: 'Please fill out all required fields', reqfield: 'Required field', minlength: 'Value is too short', maxlength: 'Value too big', emptyfill: 'None of the fields are filled in', chosevalue: 'Please select an address from the options', deliveryreq: 'It is not possible to place an order without delivery. Please refresh the page and try again', unauthorized_order: 'Please log in to proceed with your order', promocode: 'Please activate promo code or clear input field', cached_page_popup_title: 'Form submission available on original page', cached_page_popup_text: 'To fill out and submit the form, go to the original page', cached_page_popup_btn: 'Proceed', }; dict['RU'] = { success_title: 'Спасибо!', success_text: 'Данные успешно отправлены.', success_btn: 'Хорошо', success_btn_redirect: 'Продолжить', success_info: 'Автоматический переход через:', success_info_redirect_error: 'Перенаправление...', success: 'Спасибо! Данные успешно отправлены.', successorder: 'Спасибо! Заказ оформлен. Пожалуйста, подождите. Идет переход к оплате...', email: 'Укажите, пожалуйста, корректный email', url: 'Укажите, пожалуйста, корректный URL', phone: 'Укажите, пожалуйста, корректный номер телефона', number: 'Укажите, пожалуйста, корректный номер', date: 'Укажите, пожалуйста, корректную дату', time: 'Укажите, пожалуйста, корректное время (ЧЧ:ММ)', name: 'Укажите, пожалуйста, имя', namerus: 'Укажите, пожалуйста, имя (только кириллица)', nameeng: 'Укажите, пожалуйста, имя (только латиница)', string: 'Вы написали некорректные символы. Разрешены только буквы, числа и знаки пунктуации', req: 'Пожалуйста, заполните все обязательные поля', reqfield: 'Обязательное поле', minlength: 'Слишком короткое значение', maxlength: 'Слишком длинное', emptyfill: 'Ни одно поле не заполнено', chosevalue: 'Пожалуйста, выберите адрес из предложенных вариантов', deliveryreq: 'Невозможно оформить заказ без доставки. Пожалуйста, перезагрузите страницу и попробуйте еще раз.', unauthorized_order: 'Пожалуйста, авторизуйтесь для оформления заказа', promocode: 'Активируйте, пожалуйста, промокод или очистите поле', cached_page_popup_title: 'Отправка формы доступна на оригинальной странице', cached_page_popup_text: 'Чтобы заполнить и отправить форму перейдите на оригинальную страницу', cached_page_popup_btn: 'Перейти', }; if (typeof t_forms__getDict === 'function' && lang !== 'RU' && lang !== 'EN') { dict = window.t_forms__getDict(); } return dict[lang] ? dict[lang][msg] : dict['EN'][msg]; } /** * Checke verification captcha * @param {MouseEvent} event - event */ function checkVerifyTildaCaptcha(event) { var verifyEvent = event || window.event; /* IMPORTANT: Check the origin of the data! */ if (verifyEvent.origin.indexOf(window.tildaForm.endpoint) !== -1) { var tildaCaptcha = document.getElementById('js-tildaspec-captcha'); var formCaptchaBox = document.getElementById('tildaformcaptchabox'); if (verifyEvent.data == 'closeiframe') { if (formCaptchaBox) t_removeEl(formCaptchaBox); if (tildaCaptcha) t_removeEl(tildaCaptcha); return; } var capthaKey = verifyEvent.data; // Browser iframe registration messages are not captcha tokens. if (typeof capthaKey !== 'string' || capthaKey.trim() === '') { console.warn('capthaKey is not a string', JSON.stringify(capthaKey)); capthaKey = JSON.stringify(capthaKey); if (!Array.isArray(window.t_jserrors)) window.t_jserrors = []; window.t_jserrors.push({ message: 'Recaptcha returned object, instead of string: ' + capthaKey, filename: 'tilda-form-1.0', lineno: 0, colno: 0, }); return; } if (tildaCaptcha) { tildaCaptcha.value = capthaKey; if (formCaptchaBox) t_removeEl(formCaptchaBox); var form = tildaCaptcha.closest('form'); if (form) t_forms__submitEvent(form); } } } /* Parsing a string with scripts */ function t_parseScripts(main, className) { var scripts = main.querySelectorAll(className + 'script'); Array.prototype.forEach.call(scripts, function (oldScript) { var newScript = document.createElement('script'); for (var j = 0; j < oldScript.attributes.length; j++) { var attr = oldScript.attributes[j]; newScript.setAttribute(attr.name, attr.value); } if (!oldScript.innerHTML.length) { var script = document.createElement('script'); script.src = oldScript.attributes.src.value; main.appendChild(script); t_removeEl(oldScript); } else { newScript.appendChild(document.createTextNode(oldScript.innerHTML)); oldScript.parentNode.replaceChild(newScript, oldScript); } }); } function t_forms__onSuccess(formNode) { window.isRedirectError = false; const form = t_forms__getElement(formNode); var rec = form.closest('.r'); var recType = rec.getAttribute('data-parenttplid') || rec.getAttribute('data-record-type'); var inputWrapper = form.querySelector('.t-form__inputsbox'); var inputWrapperStyle = getComputedStyle(inputWrapper, null); var inputWrapperPaddingTop = parseInt(inputWrapperStyle.paddingTop) || 0; var inputWrapperPaddingBottom = parseInt(inputWrapperStyle.paddingBottom) || 0; var inputWrapperHeight = inputWrapper.clientHeight - (inputWrapperPaddingTop + inputWrapperPaddingBottom); var inputOffset = inputWrapper.getBoundingClientRect().top + window.pageYOffset; var inputBottom = inputWrapperHeight + inputOffset; var successBox = form.querySelector('.t-form__successbox'); var successBoxOffset = successBox ? successBox.getBoundingClientRect().top + window.pageYOffset : 0; var target; var windowHeight = window.innerHeight; var body = document.body; var html = document.documentElement; var documentHeight = Math.max( body.scrollHeight, body.offsetHeight, html.clientHeight, html.scrollHeight, html.offsetHeight ); // Alias type if (recType == 121) { var successCallbackName = form.getAttribute('data-success-callback'); if (successCallbackName) { recType = successCallbackName.split('_onSuccess')[0].replace('t', ''); } } var inputsboxHiddenClassName = 't' + recType + '__inputsbox_hidden'; var arrNotScroll = [702, 708, 862, 945, 1014, 1114]; var isScroll = true; if (window.innerWidth > 960) { target = successBoxOffset - 200; } else { target = successBoxOffset - 100; } var tildaLabel = document.querySelector('.t-tildalabel'); const isNewSuccessBox = t_forms__isNewSuccessBox(form); if (successBoxOffset > window.scrollY || documentHeight - inputBottom < windowHeight - 100) { if (!isNewSuccessBox) { // для новой версии сообщения успеха не скрываем форму inputWrapper.classList.add(inputsboxHiddenClassName); } if (windowHeight > documentHeight && tildaLabel) { setTimeout(function () { t_fadeOut(tildaLabel); }, 300); } } else { for (var i = 0; i < arrNotScroll.length; i++) { if (arrNotScroll[i] == recType) { isScroll = false; break; } } if (isScroll) t_forms__scrollBeginForm(target); setTimeout(function () { if (!isNewSuccessBox) { inputWrapper.classList.add(inputsboxHiddenClassName); } }, 400); } const successUrl = form.getAttribute('data-success-url'); if (successUrl) { t_forms__handleRedirect(form, successUrl, successBox); } // Hide prev btn in step to step form if (recType == 835 || recType == 862) { var prevBtn = rec.querySelector('.t' + recType + '__btn_prev'); var quizWrapper = rec.querySelector('.t' + recType + '__wrapper'); var quizFormWrapper = rec.querySelector('.t' + recType + '__quiz-form-wrapper'); if (prevBtn) prevBtn.style.display = 'none'; if (quizWrapper) quizWrapper.style.minHeight = ''; if (quizFormWrapper) quizFormWrapper.style.minHeight = ''; } } function t_forms__handleRedirect(form, successUrl, successBox) { let timeout = 500; if (!t_forms__isNewSuccessBox(form)) { setTimeout(function () { window.location.href = successUrl; }, timeout); } else { const title = successBox?.getAttribute('data-success-title') || ''; const text = successBox?.getAttribute('data-success-message') || ''; const isPopupShowing = Boolean(title || text); const countdownElement = document.getElementById('tildaformsuccesspopupinfodigit-new'); if (isPopupShowing) { timeout = 5000; startRedirectCountdown(timeout); } // при нажатии на Continue подменяем обычный переход по ссылке // на перезагрузку страницы для одинаковой логики let linkButton = document.getElementById('tildaformsuccesspopuplink-new'); if (linkButton) { linkButton.removeEventListener('click', handleRedirectClick); linkButton.addEventListener('click', handleRedirectClick); } let mainTimeout = null; let redirectTimeout = null; mainTimeout = setTimeout(() => { try { const currentUrl = window.location.href; redirect(successUrl); // редирект без отображения попапа if (!isPopupShowing) { window.tildaForm.handleClosePopup(); // если через 2с не произошёл редирект, // показываем попап с кнопкой Continue redirectTimeout = setTimeout(() => { try { if (window.location.href === currentUrl) { handleRedirectError(); } } catch (error) { console.error(error); } }, 2000); } } catch (error) { console.error(error); } }, timeout); window.addEventListener('pageshow', () => { clearTimeout(mainTimeout); clearTimeout(redirectTimeout); }); function handleRedirectClick(event) { event.preventDefault(); clearTimeout(mainTimeout); const href = event.currentTarget.getAttribute('href'); redirect(href); } function redirect(href) { window.tildaForm.handleClosePopup(); window.location.href = href; } function handleRedirectError() { window.isRedirectError = true; countdownElement.textContent = ''; t_forms__showSuccessbox(form); // так как попапа нет изначально, то надо дождаться появления кнопки new MutationObserver((mutations, obs) => { linkButton = document.getElementById('tildaformsuccesspopuplink-new'); if (linkButton) { obs.disconnect(); linkButton.removeEventListener('click', handleRedirectClick); linkButton.addEventListener('click', handleRedirectClick); } }).observe(document.body, { childList: true }); } function startRedirectCountdown(timeout) { let count = timeout / 1000; countdownElement.textContent = count; const countInterval = setInterval(function () { count--; countdownElement.textContent = count; if (count <= 0) { clearInterval(countInterval); } }, 1000); } } } function t_forms__scrollBeginForm(target) { var duration = 400; var start = (window.pageYOffset || document.documentElement.scrollTop) - (document.documentElement.clientTop || 0); var change = target - start; var currentTime = 0; var increment = 16; /* same amount of milliseconds as requestAnimationFrame */ document.body.setAttribute('data-scrollable', 'true'); /* easeInOutCubic animation included in the library */ function t_forms__easeInOutCubic(time) { var currentTime = time; if ((currentTime /= duration / 2) < 1) { return (change / 2) * currentTime * currentTime * currentTime + start; } else { return (change / 2) * ((currentTime -= 2) * currentTime * currentTime + 2) + start; } } function t_forms__animateScroll() { currentTime += increment; window.scrollTo(0, t_forms__easeInOutCubic(currentTime)); if (currentTime < duration) { setTimeout(t_forms__animateScroll, increment); } else { document.body.removeAttribute('data-scrollable'); } } t_forms__animateScroll(); } /** @param {Element} form */ function t_forms__getConditionCheckHandler(form) { const allHiddenElements = Array.from(form.querySelectorAll('[data-hidden-by-condition="true"]')); /** @param {Element} input */ const isHiddenByCondition = input => allHiddenElements.some(el => el === input || el.contains(input)); return { isHiddenByCondition, }; } /** * Получает форму внутри записи * @param {Node} rec * @returns {Node} */ function t_forms__getRecForm(rec) { return rec.querySelector('.t-form'); } /** * Проверяет наличие форму внутри записи * @param {Node} rec * @returns {bool} true - есть форма, false - отсутствует */ function t_forms__hasFormInRec(rec) { return !!t_forms__getRecForm(rec); } /** * @param {Element} rec */ function t_forms__initFormFields(rec) { const form = t_forms__getRecForm(rec); if (!form) return; t_forms__parseVariables(rec); } /** * Вынесено в функцию для переиспользования. * Пример текста с переменной: `Hello {{form.name=Jack}}`. * `Номер заявки: {{tilda.lead_id}}` * * - Перед переменной указывается домен, к которой она относится. Домен и переменная разделяются . * - Значение по умолчанию указывается через =. * - В значении по умолчанию можно использовать любые символы, кроме {} */ function t_forms__getVariableRegexp() { return /{{(form|tilda).([A-zА-я0-9_-]+)(?:=([^{}]+))?}}/g; } /** * @param {Node} elemNode */ function t_forms__elementHasVariables(elemNode) { const regex = t_forms__getVariableRegexp(); return regex.test(elemNode.textContent); } /** * Заменяет текстовые переменные в элементе на необходимые html тэги. * @param {Element} target */ function t_forms__replaceVariablesWithPlaceholders(target) { const elemsWithVariables = t_forms__findMatchingTextNodes(target, t_forms__elementHasVariables); elemsWithVariables.forEach(elem => { elem.innerHTML = elem.innerHTML.replace( t_forms__getVariableRegexp(), (match, domainName, variableName, defaultValue) => t_forms__buildVariablePlaceholderHTML(match, domainName, variableName, defaultValue) ); }); return elemsWithVariables; } function t_forms__buildVariablePlaceholderHTML(match, domainName, variable, defaultValue) { const span = document.createElement('span'); span.classList.add('t-variable-placeholder'); span.setAttribute('data-variable', variable); span.setAttribute('data-variable-domain', domainName); span.setAttribute('data-original', match); if (defaultValue) { span.setAttribute('data-default-value', defaultValue); } span.textContent = defaultValue || variable; return span.outerHTML; } /** * Находит подходящие под условие текстовые ноды. * @param {Element} root * @param {(node: Node) => boolean} matchCb */ function t_forms__findMatchingTextNodes(root, matchCb) { var result = []; // Создаем итератор, который собирает текстовые ноды. var walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT, { acceptNode(node) { if (matchCb(node)) { return NodeFilter.FILTER_ACCEPT; } return NodeFilter.FILTER_REJECT; }, }); // Проходим итератором по текстовым нодам и собираем их обертки, если они подходят. while (walker.nextNode()) { var node = walker.currentNode; // Пропускаем также ноды внутри textarea, что используется для легаси передачи данных if ( !['SCRIPT', 'STYLE'].includes(node.parentElement.tagName) && !node.parentElement.classList.contains('tn-atom__inputs-textarea') ) { result.push(node.parentElement); } } // На всякий случай удаляем повторяющиеся элементы return t_forms__removeDuplicateElements(result); } /** * Связывает поля формы с плейсхолдерами и обновляет их при изменении значений. * @param {HTMLElement} rec - Элемент блока. * @param {HTMLElement[]} elems - Элементы с плейсхолдерами для переменных. * @returns {Promise} - Промис, который разрешается после настройки всех слушателей. */ function t_forms__bindFormVariablesToPlaceholders(rec, elems) { return new Promise(resolve => { // Собираем уникальные переменные, которые нашли const usedVariables = t_forms__getUsedVariables(elems, { unique: true }); const promises = usedVariables.map(variable => { // Если переменная системная, обрабатываем их отдельно if (t_forms__isSystemVariable(variable)) { elems.forEach(elem => t_forms__updateSystemVariable(rec, elem, variable)); return Promise.resolve(); } const inputGroup = t_forms__findFormField(rec, variable.name); if (!inputGroup) { return Promise.resolve(); } // Для каждой переменной ищем связанное поле формы и подписываемся на его изменение, если нужно. return formsApi.t_formsApi__initTildaField(inputGroup).then(fieldApi => { const update = elem => t_forms__updateInputVariable(elem, variable, fieldApi); // при изменении в поле обновляем переменные во всем блоке fieldApi.onChange(() => update(rec), { uniqueKey: variable.name }); // Первоначальное обновление – обновляем только переданные элементы, а не блок целиком elems.forEach(update); }); }); Promise.all(promises).then(resolve); }); } function t_forms__getSystemVariables() { return /** @type {const} */ ({ LEAD_ID: 'lead_id', }); } /** * @param {FormVariable} variable */ function t_forms__isSystemVariable(variable) { return variable.domain === 'tilda' && Object.values(t_forms__getSystemVariables()).includes(variable.name); } /** * Обновляет все переданные переменные внутри элемента на новое значение. * Если новое значение falsy, то используется значение по умолчанию, если оно есть. * @param {Element} elem * @param {FormVariable} variable * @param {string} newValue */ function t_forms__updateVariables(elem, variable, newValue) { const placeholders = elem.querySelectorAll( `.t-variable-placeholder[data-variable="${variable.name}"][data-variable-domain="${variable.domain}"]` ); if (!placeholders.length) return; placeholders.forEach(placeholder => { const { variable, defaultValue } = placeholder.dataset; placeholder.textContent = newValue || defaultValue || variable; }); } /** * Актуализирует значение переданной переменной, связанной с полем для ввода. * @param {Element} elem * @param {FormVariable} variable * @param {TildaField} fieldApi */ function t_forms__updateInputVariable(elem, variable, fieldApi) { const { getValue, data } = fieldApi; let { value } = getValue(); // Свой вариант ответа отображается в переменной без названия, только значение введенное пользователем. if (data.ownVariantTitle && value) { value = value.replace(`${data.ownVariantTitle}: `, ''); } // У способа связи особый формат value. Ключ - название поля, Значение - объект с value // Для типа способа связи выводится человекочитаемый текст if (data.isContactMethod) { const v = value[variable.name]; if (v.typeInputDisplayText) { value = v.typeInputDisplayText; } else { value = value[variable.name].value; } } t_forms__updateVariables(elem, variable, value); } /** * Актуализирует значение переданной системной переменной. * @param {Element} rec - элемент блока * @param {Element} elem - элемент, в котором нужно выполнить подстановку переменных * @param {FormVariable} variable */ function t_forms__updateSystemVariable(rec, elem, variable) { const SYS_VARS = t_forms__getSystemVariables(); const form = rec.querySelector('.t-form'); if (!form) return; let value = variable.name; if (variable.name === SYS_VARS.LEAD_ID) { const { tildaTranId } = form; // eg: 12098159:7157790111 const [, leadId] = (tildaTranId || '').split(':'); value = leadId || '0'; } t_forms__updateVariables(elem, variable, value); } /** * Обновляет все системные переменные в блоке. * @param {Element} elem */ function t_forms__updateAllSystemVariables(elem) { const rec = elem.closest('.t-rec'); const variables = t_forms__getUsedVariables([rec], { unique: true }); const systemVars = variables.filter(t_forms__isSystemVariable); systemVars.forEach(variable => { t_forms__updateSystemVariable(rec, rec, variable); }); } /** * Обновляет все переменные в блоке. * @param {Element} elem */ async function t_forms__updateAllVariables(elem) { try { const rec = elem.closest('.t-rec'); const variables = t_forms__getUsedVariables([rec], { unique: true }); const systemVars = variables.filter(t_forms__isSystemVariable); systemVars.forEach(variable => t_forms__updateSystemVariable(rec, rec, variable)); const inputVars = variables.filter(variable => !t_forms__isSystemVariable(variable)); const promises = inputVars.map(async variable => { const inputGroup = t_forms__findFormField(rec, variable.name); if (!inputGroup) return Promise.resolve(); const fieldApi = await formsApi.t_formsApi__initTildaField(inputGroup); if (!fieldApi) return Promise.resolve(); t_forms__updateInputVariable(rec, variable, fieldApi); return Promise.resolve(); }); await Promise.all(promises); } catch (e) { console.error('Failed to update variabls in rec:', e); } } /** * @typedef {Object} FormVariable * @prop {string} name * @prop {string} domain */ /** * @param {Element[]} elems * @param {{ unique?: boolean }} options * @returns {FormVariable[]} */ function t_forms__getUsedVariables(elems, options = {}) { const { unique } = options; // Собираем все переменные из элементов const variables = Array.from(elems).flatMap( elem => Array.from(elem.querySelectorAll('.t-variable-placeholder')) .map(placeholder => { return { name: placeholder.getAttribute('data-variable'), domain: placeholder.getAttribute('data-variable-domain'), }; }) .filter(variable => variable.name && variable.domain) // Отфильтровываем пустые ); // Если нужно вернуть уникальные значения if (unique) { const seen = {}; return variables.filter(variable => { const key = `${variable.name}|${variable.domain}`; if (seen[key]) return false; seen[key] = true; return true; }); } return variables; } /** * Превращает переменные в тексте в html элементы и подписывается на изменения в связанных полях. * Вызывается только на тех элементах, которые недавно появились и для них нужно инициализировать переменные. * @param {Element} elem * @returns {Promise} */ function t_forms__parseVariables(elem) { const elementsWithVariables = t_forms__replaceVariablesWithPlaceholders(elem); if (!elementsWithVariables.length) { // если в элементе нет переменных, то выходим. return Promise.resolve(); } const rec = elem.closest('.t-rec'); return t_forms__bindFormVariablesToPlaceholders(rec, elementsWithVariables); } /** * Хелпер для поиска inputGroup по имени переменной. * Нужен, чтобы выполнять поиск по сложным полям, которые состоят из нескольких имен (способ связи). * В сложносоставных полях имена указываются через ;. * Пример: messenger-id;messenger-type * @param {Element} rec * @param {string} name * @returns {Element} */ function t_forms__findFormField(rec, name) { const fieldWithExactName = rec.querySelector(`.t-input-group[data-field-name="${name}"]`); if (fieldWithExactName) return fieldWithExactName; const fieldsWithSimillarNames = Array.from(rec.querySelectorAll(`.t-input-group[data-field-name*="${name}"]`)); return fieldsWithSimillarNames.find(group => group.getAttribute('data-field-name').split(';').includes(name)); } /** * Очищает значения всех полей формы. * @param {Element} form */ function t_forms__clearFormInputs(form) { var upwidgetRemoveBtns = form.querySelectorAll('.t-upwidget-container__data_table_actions_remove svg'); var inputText = form.querySelectorAll('input[type="text"]'); var inputNumber = form.querySelectorAll('input[type="number"]'); var inputEmail = form.querySelectorAll('input[type="email"]'); var inputPhone = form.querySelectorAll('input[type="tel"], input[type="hidden"][data-tilda-rule="phone"]'); var inputTextarea = form.querySelectorAll('textarea'); /* replace to public fn */ upwidgetRemoveBtns.forEach(function (widget) { t_triggerEvent(widget, 'click'); }); inputText.forEach(function (input) { input.value = ''; }); inputNumber.forEach(function (input) { input.value = ''; }); inputEmail.forEach(function (input) { input.value = ''; }); inputPhone.forEach(function (input) { input.value = ''; }); inputTextarea.forEach(function (textarea) { textarea.innerHTML = ''; textarea.value = ''; }); } /** * Очищает данные формы: номер заказа и номер заявки * @param {Element} form */ function t_forms__clearFormData(form) { /** * This check on jQuery is necessary for old users, who can * use custom functions on their projects with jQuery-objects. * See example of custom function on: * https://help-ru.tilda.cc/tips/javascript#rec115335034 */ if (typeof jQuery !== 'undefined') { jQuery(form).data('tildaformresult', { tranId: '0', orderId: '0', }); } form.tildaTranId = '0'; form.tildaOrderId = '0'; } /** * Выводит сообщение об успешной отправке формы * @param {Element} form */ function t_forms__showSuccessbox(form) { const successBox = form.querySelector('.js-successbox'); if (!successBox) return Promise.resolve(); const isNewSuccessBox = t_forms__isNewSuccessBox(form); const successBoxContent = t_forms__getSuccessBoxContent(successBox, isNewSuccessBox); if (isNewSuccessBox) { successBox.innerHTML = `
${successBoxContent.title}
${successBoxContent.text}
${successBoxContent.button}
`; } else { successBox.innerHTML = successBoxContent.text; } // Обработка переменных асинхронная операция, поэтому ждем ее завершения. // Нам не важно, успешно или не успешно, главное, чтобы выполнение закончилось. return t_forms__parseVariables(successBox).finally(() => { if (form.getAttribute('data-success-popup') === 'y') { t_forms__showSuccessPopup(form, successBox); return; } successBox.style.display = 'block'; }); } function t_forms__getSuccessBoxContent(successBox, isNewSuccessBox) { const successStr = t_forms__getMsg('success'); const successMessage = successBox.getAttribute('data-success-message'); let content = { text: '', title: '', button: '', }; if (successMessage) { content.text = successMessage; } else if ((!successBox.textContent || !successBox.innerText) && !successMessage && successStr) { content.text = successStr; } else { content.text = successBox.innerHTML; } if (isNewSuccessBox) { if (!successMessage) { content.text = ''; } content.title = successBox.getAttribute('data-success-title') || ''; content.button = successBox.getAttribute('data-success-btn') || ''; } return content; } function t_forms__showSuccessPopup(form, successBox) { const isZero = !!form.closest('.t396'); if (isZero) { window.tildaForm.showSuccessPopup(successBox.innerHTML); return; } const elements = { title: successBox.querySelector('.t-form__successbox-title'), text: successBox.querySelector('.t-form__successbox-text'), btn: successBox.querySelector('.t-form__successbox-btn'), }; window.tildaForm.showSuccessPopupNew( form, elements.text?.innerHTML || '', elements.title?.innerHTML || '', elements.btn?.innerHTML || '' ); } /** * Вызывает successCallback если он передан или запускает процесс redirect'a. * @param {{ successUrl?: string, successCallback?: string }} options */ function t_forms__handleSuccess(form, options) { const { successUrl, successCallback = '' } = options || {}; /** * eval() is needed to execute a user function. The jQuery check is left * for compatibility with older users whose code can work with the jQuery object. * An example of a custom function: https://help-ru.tilda.cc/tips/javascript#rec115335034 */ let callback = (successCallback || '').replace('window.', ''); if (callback && typeof window[callback] === 'function') { if (typeof jQuery !== 'undefined') { // eslint-disable-next-line no-eval eval(callback + '(jQuery(form))'); } else { // eslint-disable-next-line no-eval eval(callback + '(form)'); } } else if (successUrl) { const successBox = form.querySelector('.t-form__successbox'); t_forms__handleRedirect(form, successUrl, successBox); } } function t_forms__getRootZone() { const allrecords = document.getElementById('allrecords'); const rootZone = allrecords && allrecords.getAttribute('data-tilda-root-zone'); return rootZone || 'com'; } function t_forms__isTesterPage() { const allRecords = document.getElementById('allrecords'); const isOwnerATester = allRecords && allRecords.getAttribute('data-tilda-ts') === 'y'; return isOwnerATester; } function t_forms__isTeam() { const allRecords = document.getElementById('allrecords'); return allRecords && allRecords.getAttribute('data-tilda-te') === 'y'; } function t_forms__isQuiz(form) { return form && form.closest('.t-quiz'); } function t_forms__isIOS() { return /iPhone|iPad|iPod/i.test(navigator.userAgent) && !window.MSStream; } function t_forms__isNewSuccessBox(form) { if (!form) return false; if (t_forms__isQuiz(form)) return false; const blocksWithOldSuccessBox = ['t396', 't447', 't651', 't653', 't706', 't708', 't945', 't1122']; const isOldVersion = blocksWithOldSuccessBox.some(block => form.closest(`.${block}`)); return !isOldVersion; } /** * Удаляет дубликаты из массива DOM-элементов с использованием Map * @param {Element[]} nodes * @return {Element[]} */ function t_forms__removeDuplicateElements(nodes) { const uniqueMap = new Map(); nodes.forEach(node => uniqueMap.set(node, true)); return Array.from(uniqueMap.keys()); } /** * * @param {Element} form * @returns {{ status: 'valid' | 'invalid', data: string, contentType: string }} */ function t_forms__getFormData(form) { const JSON_FORMAT = 'text/plain'; const URLENCODED_FORMAT = 'application/x-www-form-urlencoded; charset=UTF-8'; try { const USE_JSON = t_forms__shouldEnableFormAsJSON(); // TODO BL-1184: Оставить только формат JSON после проверки на работоспособность if (USE_JSON) { const formData = t_forms__getFormDataJSON(form); const hasPaymentAndProducts = window.tildaForm.tildapayment && window.tildaForm.tildapayment.products; const hasMemberInfo = window.tildaForm.tildamember && Object.keys(window.tildaForm.tildamember).length > 0; if (!hasPaymentAndProducts && form.closest('.t706__orderform')) { return { status: 'invalid', data: '', contentType: '', }; } // Удаляем поля доставок, потому что они передаются внутри tildapayment Object.keys(formData).forEach(key => { if (key.includes('tildadelivery-')) { delete formData[key]; } }); if (hasPaymentAndProducts) { formData['tildapayment'] = window.tildaForm.tildapayment; } if (hasMemberInfo) { formData['tildamember'] = window.tildaForm.tildamember; } return { status: 'valid', data: JSON.stringify(formData), contentType: JSON_FORMAT, }; } const rawData = t_serializeArray(form); const formData = rawData.filter(data => data.name.indexOf('tildadelivery-') === -1); if (window.tildaForm.tildapayment && window.tildaForm.tildapayment.products) { formData.push({ name: 'tildapayment', value: JSON.stringify(window.tildaForm.tildapayment), }); } else if (form.closest('.t706__orderform')) { return { status: 'invalid', data: '', contentType: '', }; } if (window.tildaForm.tildamember && Object.keys(window.tildaForm.tildamember).length > 0) { formData.push({ name: 'tildamember', value: JSON.stringify(window.tildaForm.tildamember), }); } return { status: 'valid', data: t_forms__formData(formData), contentType: URLENCODED_FORMAT, }; } catch (e) { console.error('Failed to prepare form data for process. Error:', e); return { status: 'invalid', data: '', contentType: '', }; } } function t_forms__shouldEnableFormAsJSON() { try { const params = new URLSearchParams(window.location.search); return params.get('sendjson') === 'true'; } catch (e) { return false; } } /** * ALL FUNCTIONS AND METHODS FOR IE8+ */ /* Function remove() for IE8+ */ function t_removeEl(el) { if (el && el.parentNode) { el.parentNode.removeChild(el); } } /* Checks whether there is an event or it is custom */ var t_forms__htmlEvents = { onblur: 1, onchange: 1, onfocus: 1, onsubmit: 1, onclick: 1, ondblclick: 1, onkeydown: 1, onkeypress: 1, onpaste: 1, oninput: 1, }; /* Function removeEventListener for IE8+ */ function t_removeEventListener(el, eventName, callback) { if (el.removeEventListener) { el.removeEventListener(eventName, callback, false); } else if (el.detachEvent && t_forms__htmlEvents['on' + eventName]) { el.detachEvent('on' + eventName, callback); } else { el['on' + eventName] = null; } } /* Function addEventListener for IE8+ */ function t_addEventListener(el, eventName, callback, options) { if (el.addEventListener) { el.addEventListener(eventName, callback, options); } else if (el.attachEvent && t_forms__htmlEvents['on' + eventName]) { el.attachEvent('on' + eventName, callback); } else { el['on' + eventName] = callback; } } /** * Function serializeArray equivalent on JS for IE8+ * @param {Element} form * @returns {{name: string, value: string}[]} */ function t_serializeArray(form) { var arr = []; var elements = form.querySelectorAll('input, textarea, button, select'); const { isHiddenByCondition } = t_forms__getConditionCheckHandler(form); for (var i = 0; i < elements.length; i++) { if ( !elements[i].name || elements[i].disabled || ['file', 'reset', 'submit', 'button'].indexOf(elements[i].type) > -1 || isHiddenByCondition(elements[i]) ) continue; if (elements[i].type === 'select-multiple') { var options = elements[i].options; for (var j = 0; j < options.length; j++) { if (!options[j].selected) continue; arr.push({ name: options[j].name, value: options[j].value, }); } continue; } if (['checkbox', 'radio'].indexOf(elements[i].type) > -1 && !elements[i].checked) continue; var name = elements[i].name; var value = elements[i].value; arr.push({ name, value, }); } return arr; } /** * Преобразует данные формы в JSON. * * TODO BL-1184: Оставить только формат JSON после проверки на работоспособность * @param {Element} form * @returns {Record} */ function t_forms__getFormDataJSON(form) { const result = {}; const elements = form.querySelectorAll('input, textarea, button, select'); const { isHiddenByCondition } = t_forms__getConditionCheckHandler(form); // Хелпер для добавления значений в формате массива const addToArray = (name, value) => { if (!Array.isArray(result[name])) { result[name] = []; } result[name].push(value); }; elements.forEach(elem => { const { name, type, disabled, value, checked, options } = elem; // Пропускаем неактивные или невалидные элементы if (!name || disabled || isHiddenByCondition(elem)) return; // Пропускаем лишние элементы, которые не нужны в форме if (['file', 'reset', 'submit', 'button'].includes(type)) return; // Пропускаем элементы, которые не были выбраны if (['checkbox', 'radio'].includes(type) && !checked) return; // Обработка поля select с атрибутом multiple if (type === 'select-multiple') { Array.from(options || []) .filter(option => option.selected) .forEach(option => addToArray(name, option.value)); return; } // Обработка полей, которые должны сохраняться как массивы if (name.includes('[]')) { const key = name.replace('[]', ''); addToArray(key, value); return; } // Обычные поля result[name] = value; }); return result; } /* Function classList.add for IE8+ */ function t_addClass(el, className) { /* HTML 5 compliant browsers */ if (document.body.classList) { el.classList.add(className); return; } /* legacy browsers (IE<10) support */ el.className += (el.className ? ' ' : '') + className; } /* Function classList.remove for IE8+ */ function t_removeClass(el, className) { /* HTML 5 compliant browsers */ if (document.body.classList) { el.classList.remove(className); return; } /* legacy browsers (IE<10) support */ el.className = el.className .replace(new RegExp('(^|\\s+)' + className + '(\\s+|$)'), ' ') .replace(/^\s+/, '') .replace(/\s+$/, ''); } /* Function classList.contains for IE8+ */ function t_hasClass(el, className) { if (document.body.classList) { return el.classList.contains(className); } return new RegExp('(\\s|^)' + className + '(\\s|$)').test(el.className); } /* Function formData for IE8+ */ function t_forms__formData(obj) { var data = ''; for (var i = 0; i < obj.length; i++) { if (data !== '') { data += '&'; } data += encodeURIComponent(obj[i].name) + '=' + encodeURIComponent(obj[i].value); } return data.replace(/%20/g, '+'); } /* Function fade out for IE8+ */ function t_fadeOut(el) { if (el.style.display === 'none') return; var opacity = 1; var timer = setInterval(function () { el.style.opacity = opacity; opacity -= 0.1; if (opacity <= 0.1) { clearInterval(timer); el.style.display = 'none'; el.style.opacity = null; } }, 30); } /* Function fade in for IE8+ */ function t_fadeIn(el) { if (el.style.display === 'block') return; var opacity = 0; el.style.opacity = opacity; el.style.display = 'block'; var timer = setInterval(function () { el.style.opacity = opacity; opacity += 0.1; if (opacity >= 1.0) { clearInterval(timer); } }, 30); } // Функция временно продублирована из tilda-scrits для избежания проблем с кэшем function t_triggerEvent(el, eventName) { var event; if (document.createEvent) { event = document.createEvent('HTMLEvents'); event.initEvent(eventName, true, false); } else if (document.createEventObject) { event = document.createEventObject(); event.eventType = eventName; } event.eventName = eventName; if (el.dispatchEvent) { el.dispatchEvent(event); } else if (el.fireEvent) { el.fireEvent('on' + event.eventType, event); } else if (el[eventName]) { el[eventName](); } else if (el['on' + eventName]) { el['on' + eventName](); } } function t_forms__processFormsInPopup(popup, form) { if (popup.style.backgroundColor) { const styleElement = document.createElement('style'); styleElement.className = 't-success-popup'; const cssRule = ` #tildaformsuccesspopup-new { background-color: ${popup.style.backgroundColor}; }`; styleElement.textContent = cssRule; document.head.appendChild(styleElement); } const rec = form.closest('.t-rec'); // если форма в попапе, скрываем его, после отправки формы let blockId = rec.getAttribute('data-parenttplid') || rec.getAttribute('data-record-type'); if (blockId === '121') { // если попап находится внутри alias-блока, выбираем атрибут с id внутри попапа const popupContainer = popup.querySelector('.t-popup__container'); blockId = popupContainer.getAttribute('data-popup-type') || '121'; } const closePopupFuncName = `t${blockId}_closePopup`; const recId = rec.id.replace('rec', ''); const closeFunction = window[closePopupFuncName]; if (typeof closeFunction === 'function') { closeFunction(recId); } } function t_forms__drawNewSuccessPopup() { return ` `; } function t_forms__trapFocus(popup) { const focusableElements = popup.querySelectorAll( 'a, button, input:not([type="hidden"]):not(.js-form-spec-comments), select, textarea, embed, video, iframe, [tabindex="0"]' ); const firstFocusableElement = focusableElements[0]; const lastFocusableElement = focusableElements[focusableElements.length - 1]; document.addEventListener('keydown', function (event) { if (!document.body.classList.contains('t-body_popupshowed')) return; const isTab = event.key === 'Tab' || event.keyCode === 9; const isTabPressed = isTab || (isTab && event.shiftKey); if (!isTabPressed) { return; } if (event.shiftKey && document.activeElement.classList.contains('t-popup_show')) { lastFocusableElement.focus(); } if (event.key === 'Tab' && !event.shiftKey && document.activeElement === lastFocusableElement) { event.preventDefault(); firstFocusableElement.focus(); } // if tab+shift and we moving back if (event.key === 'Tab' && event.shiftKey && document.activeElement === firstFocusableElement) { event.preventDefault(); lastFocusableElement.focus(); } }); } /** * Проверяет открыта ли страница на кеширующем сервисе * @returns {boolean} Возвращает true, если страница открыта на кеширующем сервисе, иначе false. */ function t_forms__isCachedPage() { try { const url = new URL(window.location.href); const hostname = url.hostname; const href = url.href; // Список кеширующих сервисов и их доменов/шаблонов URL const cacheServices = [ { domains: ['webcache.googleusercontent.com'], urlPattern: /(^|&|\?)q=cache:/, }, { domains: ['www.google.com'], urlPattern: /\/amp\/s\//, }, { domains: ['t.me'], urlPattern: /\/web\//, }, { domains: ['dzen.ru'], urlPattern: /\/away\?/, }, { domains: [ 'yandex.ru', 'yandexwebcache.net', 'archive.today', 'archive.ph', 'archive.is', 'web.archive.org', 'ghostarchive.org', 'cachedview.com', ], }, ]; for (const service of cacheServices) { const isDomainMatch = service.domains.some(domain => hostname === domain); const isUrlPatternMatch = service.urlPattern ? service.urlPattern.test(href) : true; if (isDomainMatch && isUrlPatternMatch) { return true; } } return false; } catch (error) { return false; } } /** * Получает каноническую ссылку страницы, если она задана. * @returns {string} Каноническая ссылка страницы, если она есть, иначе пустая строка. */ function t_forms__getCanonicalUrl() { const canonicalLink = document.querySelector('link[rel="canonical"]'); return canonicalLink ? canonicalLink.getAttribute('href') : ''; } /** * Рендерит сообщение о том, что форма открыта не на том url * @param {string} canonicalUrl */ function t_forms__showWrongPageUrlMessage(canonicalUrl) { if (!canonicalUrl) { return; } const popupId = 'tildaforms-origin-url-popup-notification'; const existingPopup = document.getElementById(popupId); if (existingPopup) { show(existingPopup); return; } const html = ` `; document.body.insertAdjacentHTML('beforeend', html); const popup = document.getElementById(popupId); const closeButton = popup.querySelector('.t-form-success-popup__close-icon'); t_addEventListener(popup, 'click', function (event) { const clickEvent = event || window.event; const target = clickEvent.target || clickEvent.srcElement; if (target === this) { hide(popup); } }); t_addEventListener(closeButton, 'click', function () { hide(popup); }); show(popup); function show(popup) { t_fadeIn(popup); t_addClass(document.body, 't-body_success-popup-showed'); if (t_forms__isIOS()) { setTimeout(function () { window.tildaForm.lockBodyScroll(); }, 500); } t_forms__trapFocus(popup); } function hide(popup) { t_removeClass(document.body, 't-body_success-popup-showed'); if (t_forms__isIOS()) { window.tildaForm.unlockBodyScroll(); } t_fadeOut(popup); } } /** * Обработчик урла и его query-параметров, который проставляет * значения на существующие поля форм на странице. * @param {event | {}} event */ function t_forms__processGetParameters(event = {}) { if (!window.URLSearchParams || t_forms__getTildaMode() !== 'published') return; const params = new URLSearchParams(window.location.search); if (!params?.size) return; const { currentTarget } = event; let inputSelectors = [ '.t-select', '.t-input', '.t-rate', '.t-radio', '.t-checkbox', '.t-img-select', '.t-range', '.t-checkboxes__hiddeninput', '.t-img-select__hiddeninput', '[type="hidden"]', ]; if (!currentTarget) inputSelectors = inputSelectors.map(field => `.js-form-proccess ${field}`); const parentNode = currentTarget || document; const inputList = Array.from(parentNode.querySelectorAll(inputSelectors)); if (!inputList.length) return; const fieldNames = new Set(inputList.map(field => field.getAttribute('name')).filter(name => name)); fieldNames.forEach(name => { const value = params.get(`form-setter-${name}`); if (!value) return; let inputListForCurrentField = inputList.filter(field => field.getAttribute('name') === name); inputListForCurrentField = t_forms__includeCheckboxesForInputList(inputListForCurrentField); inputListForCurrentField.forEach(input => t_forms__setGetParameterToField(input, value)); }); } /** * У чекбоксов нет параметра "name", который является определяющим в функции t_forms__processGetParameters, * поэтому мы ищем по имени , который хранит значения чекбоксов, * и от него уже определяем настоящие чекбоксы, которые понадобится обработать. * * @param {HTMLInputElement[]} inputListForCurrentField * @returns {HTMLInputElement[]} */ function t_forms__includeCheckboxesForInputList(inputListForCurrentField) { return inputListForCurrentField.reduce((acc, input) => { if ( input.classList.contains('t-checkboxes__hiddeninput') || input.classList.contains('t-img-select__hiddeninput') ) { const checkboxWrapper = input.closest('.t-input-block'); const checkboxList = Array.from(checkboxWrapper?.querySelectorAll('.t-checkbox, .t-img-select') || []); acc.push(...checkboxList); } else { acc.push(input); } return acc; }, []); } /** * Задаём значение из гет-параметра в соответствующее поле формы. * Если поле может содержать только числовые значения (номер телефона, число, диапазон), * то дополнительно проверяем, что строку можно корректно распарсить в число. * * @param {HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement} input * @param {string} value */ function t_forms__setGetParameterToField(input, value) { if (['tel', 'number', 'range'].includes(input.type) && isNaN(value)) return; const timeout = 500; if (['checkbox', 'radio'].includes(input.type)) { processFieldOnCalcReady(() => { const valueList = value.split(','); const inputValue = input?.value?.trim() || ''; if (!valueList.includes(inputValue)) return; input.checked = true; if (input.type === 'checkbox') processCheckbox(); if (input.classList.contains('t-rate')) processRate(); if (input.type === 'radio' && input.closest('.t-contact-method__types-container')) { triggerChangeEvent(timeout); } }); } else if (input.type === 'select-one') { processSelectbox(); } else { input.value = value; if (input.classList.contains('t-range')) triggerChangeEvent(); if (input.type === 'tel') processPhoneMask(); } processFieldOnCalcReady(triggerChangeEvent, false); /** * Необходимо стриггерить событие, в зависимости от того где чекбокс находится, * чтобы в проставились значения из выбранных чекбоксов. * Для чекбокса внутри зеро-формы (только для него, изображения в виде варианта ответа * работают в обычном режиме) дополнительно нужно дождаться активации обработчика * события 'input', поэтому используем setTimeout. * * Для Сафари нужно дополнительно сбросить `checked`-значение для чекбоксов в обычной форме, * так как программный клик только в этом браузере распознаётся как активация или деактивация чекбокса. */ function processCheckbox() { const isCheckboxFromZero = input.closest('.tn-elem .t-checkbox__control'); const isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent); if (isCheckboxFromZero) { setTimeout(() => { input.dispatchEvent(new Event('input')); }, timeout); } else { const label = input.closest('.t-checkbox__control, .t-img-select__control'); if (label && isSafari) input.checked = false; if (label) label.dispatchEvent(new Event('click')); } } function processSelectbox() { const optionList = Array.from(input.options); const currentOption = optionList.find(option => option.value.trim() === value); if (currentOption) currentOption.selected = true; } /** * Родителю поля необходимо задать активный класс, чтобы выделились все звезды * до выделенного поля, а не только это поле. */ function processRate() { input.closest('.t-rate__wrapper')?.classList.add('t-rate__wrapper_active'); } function triggerChangeEvent(timeout) { const callback = () => input.dispatchEvent(new Event('change')); if (timeout) { setTimeout(callback, timeout); } else { callback(); } } /** * Необходимо получить id поля, которое в дальнейшем будет удалено после обработки * скриптом маски телефона. Поэтому по таймеру необходимо найти обновленное поле * и к нему применить событие 'input', чтобы к вставленному значению из гет-параметру * применились настройки маски. */ function processPhoneMask() { let inputId = input.getAttribute('data-phonemask-lid'); if (inputId) inputId = `input_${inputId}`; if (!inputId) inputId = input.id; if (!inputId) return; setTimeout(() => { const updatedInput = document.getElementById(inputId); updatedInput?.dispatchEvent(new Event('input')); }, timeout); } function processFieldOnCalcReady(callback, processWithoutCalc = true) { const calcFieldWrapper = getConnectedCalcWrapper(); if (!processWithoutCalc && !calcFieldWrapper) return; if (!calcFieldWrapper || calcFieldWrapper.getAttribute('data-init-calc') === 'y') { callback(); } else { calcFieldWrapper.addEventListener('inputReady', callback); } } function getConnectedCalcWrapper() { const form = input.closest('.t-form'); if (!form) return null; const calcExpressions = Array.from(form.querySelectorAll('[data-calc-expr]')); if (!calcExpressions.length) return null; const connectedCalc = calcExpressions.find(expr => expr.getAttribute('data-calc-expr').includes(input.name)); return connectedCalc?.closest('.t-input-group') || null; } } /** * * @returns {'published' | 'edit' | 'preview' | 'notdefined'} */ function t_forms__getTildaMode() { if (typeof window.tildamode !== 'undefined') return window.tildamode; const allRec = document.getElementById('allrecords'); if (!allRec) return 'notdefined'; window.tildamode = allRec.getAttribute('data-tilda-mode') || 'published'; return window.tildamode; }