function t835_init(recid) { var rec = document.querySelector('#rec' + recid); if (!rec) return; var container = rec.querySelector('.t835'); if (!container) return; var form = rec.querySelector('.t-form'); if (!form) return; var quizWrapper = rec.querySelector('.t835__quiz-wrapper'); var inputs = rec.querySelectorAll('.t-input-group'); var prevBtn = rec.querySelector('.t835__btn_prev'); var nextBtn = rec.querySelector('.t835__btn_next'); var resultBtn = rec.querySelector('.t835__btn_result'); var submitBtnWrapper = rec.querySelector('.t-form__submit'); var submitBtn = rec.querySelector('.t-submit'); var errorBoxMiddle = rec.querySelector('.t-form__errorbox-middle'); if (errorBoxMiddle) { var errorBoxMiddleWrapper = errorBoxMiddle.querySelector('.t-form__errorbox-wrapper'); } var captureFormHTML = '
'; errorBoxMiddle.insertAdjacentHTML('beforebegin', captureFormHTML); form.classList.remove('js-form-proccess'); var captureForm = rec.querySelector('.t835__capture-form'); var resultTitle = rec.querySelector('.t835__result-title'); var resultText = resultTitle ? resultTitle.textContent : ''; var autoStepChangeEnabled = Boolean(quizWrapper.getAttribute('data-auto-step-change')); var autoStepChangeInProgress = false; var autoStepChangeTimer; var autoStepChangeDuration = 300; // Анимация переключения шагов открыта вместе с автопереходом var stepChangeInProgress = false; t835_workWithAnswerCode(rec); Array.prototype.forEach.call(inputs, function (input, i) { input.setAttribute('data-step-number', i); }); t835_wrapCaptureForm(rec); var hasCaptureForm = Boolean(captureForm.innerHTML || resultText); var quizStepIndex = 0; var isConditionalForm = form.classList.contains('t-conditional-form'); var conditionalStepForm = null; t835_createSteps(inputs); var progressValue; /** @type {Array} Шаги без учета формы захвата */ var steps = t835_createStepsArray(rec); var visibleStepsCount = steps.length; var stepsWithCaptureForm = rec.querySelectorAll('.t835__screen-wrapper'); var currentStep = steps[quizStepIndex]; if (!currentStep) return; if (isConditionalForm) { // инициализируем условную пошаговую форму t_onFuncLoad('t_form__conditionals__initStepForm', function () { var config = { recId: recid, // В условную форму передаем шаги вместе с формой захвата. // Это нужно чтобы правильно работало переключение между шагами steps: stepsWithCaptureForm, activeStepIndex: quizStepIndex, ignoredSteps: ['.t835__capture-form'], ignoredInputGroups: ['.t835__t-input-group_capture'], onConditionalFieldChange: function (state) { // вычитаем 1 из количества шагов, чтобы не учитывать форму захвата visibleStepsCount = state.totalActiveStepsCount - 1; progressValue = updateProgressValue(); t835_showCounter(rec, progressValue.counterCurrentStep, progressValue.counterAllSteps); t835_setProgress(rec, progressValue.progressCurrentStep, progressValue.progressAllSteps); checkIfShouldSubmitForm(); showOrHideButtons(); }, }; conditionalStepForm = t_form__conditionals__initStepForm(config); // вычитаем 1 из количества шагов, чтобы не учитывать форму захвата visibleStepsCount = conditionalStepForm.getState().totalActiveStepsCount - 1; initForm(); }); } else { initForm(); } function initForm() { showStep(quizStepIndex); t835_disabledPrevBtn(rec, quizStepIndex); progressValue = updateProgressValue(); t835_showCounter(rec, progressValue.counterCurrentStep, progressValue.counterAllSteps); rec.setAttribute('data-animationappear', 'off'); rec.style.opacity = 1; if (autoStepChangeEnabled) { initAutoStepChange(); } prevBtn.addEventListener('click', function (event) { handleGoPrevStep(event); }); nextBtn.addEventListener('click', function (event) { handleGoNextStep(event); }); Array.prototype.forEach.call(inputs, function (input) { input.addEventListener('keypress', function (event) { var activeStep = form.querySelector('.t-step-form__step_active'); if ( (event.code === 'Enter' || event.keyCode === 13) && !form.classList.contains('js-form-proccess') && !activeStep.querySelector('.t-input-group_ta') ) { handleGoNextStep(event); } }); }); resultBtn.addEventListener('click', function (event) { handleGoNextStep(event); }); // В tilda-forms обработка клика на submit реализована через click на блок целиком. rec.addEventListener('click', function (event) { var target = event.target; var btnSubmit = target.closest('[type="submit"]') ? target : false; if (!btnSubmit) return; // Обновляем высоту при нажатии на submit, чтобы в случае появления ошибок установить актуальную высоту t835_adjustStepToHeight(rec); }); // пересчитывает высоту на изменения ширины экрана t835_adjustHeightOnResize(rec); } function handleGoPrevStep(event) { if (stepChangeInProgress) return; event.preventDefault(); resetAutoStepChangeProgress(); if (checkFirstStep()) return; quizStepIndex = conditionalStepForm ? conditionalStepForm.getState().prevStepIndex : getActiveStepIndex() - 1; if (conditionalStepForm) { conditionalStepForm.onStepChange(quizStepIndex); } progressValue = updateProgressValue(); t835_setProgress(rec, progressValue.progressCurrentStep, progressValue.progressAllSteps); t835_showCounter(rec, progressValue.counterCurrentStep, progressValue.counterAllSteps); t835_awayFromResultScreen(rec); t835_hideError(rec, quizStepIndex); t835_disabledPrevBtn(rec, quizStepIndex); showStep(quizStepIndex); t835_scrollToTop(quizWrapper); if (form.classList.contains('js-form-proccess')) { form.classList.remove('js-form-proccess'); } } function handleGoNextStep(event) { if (stepChangeInProgress) return; event.preventDefault(); resetAutoStepChangeProgress(); var showErrors = t835_showError(rec, quizWrapper, quizStepIndex); if (showErrors && errorBoxMiddleWrapper) { errorBoxMiddleWrapper.style.display = 'none'; } if (showErrors) return; var isCurrentStepLast = checkLastStep(); quizStepIndex = conditionalStepForm ? conditionalStepForm.getState().nextStepIndex : getActiveStepIndex() + 1; if (conditionalStepForm) { conditionalStepForm.onStepChange(quizStepIndex); } progressValue = updateProgressValue(); t835_setProgress(rec, progressValue.progressCurrentStep, progressValue.progressAllSteps); t835_showCounter(rec, progressValue.counterCurrentStep, progressValue.counterAllSteps); t835_disabledPrevBtn(rec, quizStepIndex); if (isCurrentStepLast && hasCaptureForm) { showCaptureForm(); } else { showStep(quizStepIndex); } t835_scrollToTop(quizWrapper); } function getActiveStepIndex() { if (conditionalStepForm) { return conditionalStepForm.getState().activePossibleStepIndex; } return quizStepIndex; } function updateProgressValue() { return { // + 1 т.к. шаги начинаются с 1 counterCurrentStep: getActiveStepIndex() + 1, counterAllSteps: visibleStepsCount, progressCurrentStep: getActiveStepIndex(), progressAllSteps: hasCaptureForm ? visibleStepsCount : visibleStepsCount - 1, }; } function checkLastStep() { return getActiveStepIndex() === visibleStepsCount - 1; } function checkFirstStep() { return getActiveStepIndex() === 0; } function checkNextToLast() { return getActiveStepIndex() === visibleStepsCount - 2; } function showOrHideButtons() { if (!hasCaptureForm) { // нет формы захвата и шаг предпоследний if (checkNextToLast()) { nextBtn.style.display = 'none'; resultBtn.style.display = 'block'; submitBtnWrapper.style.display = 'none'; return; } if (checkLastStep()) { // если шаг последний и отсутствует форма захвата - показываем кнопку отправки формы nextBtn.style.display = 'none'; resultBtn.style.display = 'none'; submitBtnWrapper.style.display = 'block'; return; } } if (checkLastStep()) { // шаг последний и есть форма захвата – показываем кнопку открытия формы захвата nextBtn.style.display = 'none'; resultBtn.style.display = 'block'; submitBtnWrapper.style.display = 'none'; return; } nextBtn.style.display = 'block'; resultBtn.style.display = 'none'; submitBtnWrapper.style.display = 'none'; } function showStep(newStepIndex) { var currentStep = form.querySelector('.t-step-form__step_active'); var newStep = steps[newStepIndex]; if (currentStep) { animateStepSwitch(currentStep, newStep, { onNewStepAnimationStart: function () { t835_runLazyLoad(); checkIfShouldSubmitForm(); showOrHideButtons(); enableButtons(rec); var range = rec.querySelector('.t-range'); if (range) t_triggerEvent(range, 'displayChanged'); stepChangeInProgress = false; t835_adjustStepToHeight(rec); }, onAnimationStart: function () { stepChangeInProgress = true; disableButtons(rec); }, }); return; } if (newStep) newStep.classList.add('t-step-form__step_active'); t835_runLazyLoad(); checkIfShouldSubmitForm(); showOrHideButtons(); var range = rec.querySelector('.t-range'); if (range) t_triggerEvent(range, 'displayChanged'); setTimeout(function () { t835_adjustStepToHeight(rec); }, 100); } function showCaptureForm() { form.classList.add('js-form-proccess'); var quizDescription = rec.querySelector('.t835__quiz-description'); var currentStep = form.querySelector('.t-step-form__step_active'); animateStepSwitch(currentStep, captureForm, { onAnimationStart: function () { stepChangeInProgress = true; if (quizDescription) quizDescription.style.display = 'none'; if (resultTitle) resultTitle.style.display = 'block'; if (resultBtn) resultBtn.style.display = 'none'; if (submitBtnWrapper) submitBtnWrapper.style.display = 'block'; disableButtons(rec); }, onNewStepAnimationStart: function () { t835_runLazyLoad(); enableButtons(rec); stepChangeInProgress = false; t835_adjustStepToHeight(rec); }, }); return; } /** * @typedef {Object} AnimationCallbacks * @property {Function=} onAnimationStart функция, выполняемая перед началом анимации. * @property {Function=} onAnimationComplete функция, выполняемая после завершения анимации. * @property {Function=} onNewStepAnimationStart функция, выполняемая после начала анимации появления нового шага. */ /** * * @param {HTMLElement} step шаг, который нужно скрыть * @param {HTMLElement} newStep шаг, который нужно показать * @param {AnimationCallbacks} callbacks */ function animateStepSwitch(step, newStep, callbacks) { function handleFadeInEnd() { newStep.classList.remove('t-step-form__step_fadeIn'); newStep.removeEventListener('animationend', handleFadeInEnd); newStep.removeEventListener('animationcancel', handleFadeInCancel); if (callbacks.onAnimationComplete) { callbacks.onAnimationComplete(); } } function handleFadeInCancel() { newStep.classList.remove('t-step-form__step_fadeIn'); newStep.removeEventListener('animationend', handleFadeInEnd); newStep.removeEventListener('animationcancel', handleFadeInCancel); } function animateStepIn() { newStep.addEventListener('animationend', handleFadeInEnd); // при быстром переключении шагов необходимо отменить анимацию newStep.addEventListener('animationcancel', handleFadeInCancel); newStep.classList.add('t-step-form__step_active'); newStep.classList.add('t-step-form__step_fadeIn'); if (callbacks.onNewStepAnimationStart) { callbacks.onNewStepAnimationStart(); } } function handleFadeOutEnd() { step.classList.remove('t-step-form__step_fadeOut'); step.classList.remove('t-step-form__step_active'); step.removeEventListener('animationend', handleFadeOutEnd); if (newStep) { animateStepIn(); } } function animateStepOut() { step.addEventListener('animationend', handleFadeOutEnd); step.classList.add('t-step-form__step_fadeOut'); } if (callbacks.onAnimationStart) { callbacks.onAnimationStart(); } if (step) { return animateStepOut(); } return animateStepIn(); } function disableButtons() { if (prevBtn) prevBtn.disabled = true; if (nextBtn) nextBtn.disabled = true; if (resultBtn) resultBtn.disabled = true; if (submitBtn) submitBtn.disabled = true; } function enableButtons() { if (!checkFirstStep()) { if (prevBtn) prevBtn.disabled = false; } if (nextBtn) nextBtn.disabled = false; if (resultBtn) resultBtn.disabled = false; if (submitBtn) submitBtn.disabled = false; } function initAutoStepChange() { var typesWithSkip = ['ri', 'rd', 'rs', 'sb', 'cb']; var stepsWithAutoSkip = steps.filter(function (step) { var inputGroup = step.querySelector('.t-input-group'); return typesWithSkip.indexOf(inputGroup.getAttribute('data-field-type')) !== -1; }); stepsWithAutoSkip.forEach(function (step) { var inputs = Array.prototype.slice.call(step.querySelectorAll('.js-tilda-rule')); inputs = inputs.filter(function (input) { // для своего варианта ответа не работает автопереключение return !input.classList.contains('t-radio-ownanswer'); }); inputs.forEach(function (input) { input.addEventListener('change', handleAutoStepChange); }); }); } function handleAutoStepChange(event) { if (checkLastStep() && !hasCaptureForm) return; if (autoStepChangeInProgress) return; autoStepChangeInProgress = true; autoStepChangeTimer = setTimeout(function () { handleGoNextStep(event); resetAutoStepChangeProgress(); }, autoStepChangeDuration); } function resetAutoStepChangeProgress() { clearTimeout(autoStepChangeTimer); autoStepChangeInProgress = false; } /** Добавляет флаг, который разрешает отправку формы */ function checkIfShouldSubmitForm() { if (!hasCaptureForm && checkLastStep()) { form.classList.add('js-form-proccess'); } else { form.classList.remove('js-form-proccess'); } } } function t835_workWithAnswerCode(rec) { var inputGroupRi = rec.querySelector('.t-input-group_ri'); if (inputGroupRi) { var inputsRi = inputGroupRi.querySelectorAll('input'); Array.prototype.forEach.call(inputsRi, function (input) { var value = input.value; if (value.indexOf('value::') !== -1) { t835_setAnswerCode(input); var inputParent = input.parentNode; var label = inputParent.querySelector('.t-img-select__text'); label.textContent = label.textContent.split('value::')[0].trim(); } }); } var inputGroupRd = rec.querySelector('.t-input-group_rd'); if (inputGroupRd) { var inputsRd = inputGroupRd.querySelectorAll('input'); Array.prototype.forEach.call(inputsRd, function (input) { var value = input.value; if (value.indexOf('value::') !== -1) { t835_setAnswerCode(input); var label = input.parentNode; label.innerHTML = function () { var html = input.innerHTML.split('value::')[0].trim(); return html; }; } }); } var inputGroupSb = rec.querySelector('.t-input-group_sb'); if (inputGroupSb) { var options = inputGroupSb.querySelectorAll('option'); Array.prototype.forEach.call(options, function (option) { var value = option.value; if (value.indexOf('value::') !== -1) { t835_setAnswerCode(option); option.textContent = option.textContent.split('value::')[0].trim(); } }); } } function t835_createSteps(inputs) { Array.prototype.forEach.call(inputs, function (input) { if (!input.classList.contains('t835__t-input-group_capture')) { var wrapper = document.createElement('div'); wrapper.classList.add('t835__screen-wrapper'); wrapper.classList.add('t-step-form__step'); input.parentNode.insertBefore(wrapper, input); wrapper.appendChild(input); } }); } function t835_runLazyLoad() { var records = document.querySelector('.t-records:not([data-tilda-mode])'); if (records) { var allRecs = document.querySelector('#allrecords'); if (window.lazy === 'y' || allRecs.getAttribute('data-tilda-lazy') === 'yes') { t_onFuncLoad('t_lazyload_update', function () { t_lazyload_update(); }); } } } function t835_setAnswerCode(option) { var parameter = option.value.split('value::')[1].trim(); option.value = parameter; } function t835_wrapCaptureForm(rec) { var captureForm = rec.querySelector('.t835__capture-form'); var inputs = rec.querySelectorAll('.t-input-group'); var quizFormWrapper = rec.querySelector('.t835__quiz-form-wrapper'); Array.prototype.forEach.call(inputs, function (input) { var currentStepInput = input; var emailInputExist = currentStepInput.classList.contains('t-input-group_em'); var nameInputExist = currentStepInput.classList.contains('t-input-group_nm'); var phoneInputExist = currentStepInput.classList.contains('t-input-group_ph'); var checkboxInputExist = currentStepInput.classList.contains('t-input-group_cb'); var quizStepIndex = currentStepInput.getAttribute('data-step-number'); var maxCountOfCaptureFields = quizFormWrapper.classList.contains('t835__quiz-form-wrapper_withcheckbox') ? 4 : 3; if (quizStepIndex >= inputs.length - maxCountOfCaptureFields) { var isCaptureGroup = true; if (quizFormWrapper.classList.contains('t835__quiz-form-wrapper_newcapturecondition')) { var inputsGroup = t835_getNextAll(currentStepInput); Array.prototype.forEach.call(inputsGroup, function (group) { isCaptureGroup = group.classList.contains('t-input-group_cb') || group.classList.contains('t-input-group_em') || group.classList.contains('t-input-group_nm') || group.classList.contains('t-input-group_ph'); }); } if (isCaptureGroup) { if (quizFormWrapper.classList.contains('t835__quiz-form-wrapper_withcheckbox')) { if (emailInputExist || nameInputExist || phoneInputExist || checkboxInputExist) { currentStepInput.classList.add('t835__t-input-group_capture'); captureForm.appendChild(currentStepInput); } } else if (emailInputExist || nameInputExist || phoneInputExist) { currentStepInput.classList.add('t835__t-input-group_capture'); captureForm.appendChild(currentStepInput); } } } }); } function t835_showCounter(rec, quizStepIndex, allStepsLength) { var counter = rec.querySelector('.t835__quiz-description-counter'); if (!counter) return; counter.innerHTML = quizStepIndex + '/' + allStepsLength; } function t835_setProgress(rec, index, allStepsLength) { var progressBar = rec.querySelector('.t835__progressbar'); var progressbarWidth = parseFloat(getComputedStyle(progressBar).width); var progress = rec.querySelector('.t835__progress'); var progressStep = progressbarWidth / allStepsLength; var percentProgressWidth = Math.abs((index * progressStep) / progressbarWidth) * 100 + '%'; if (progress) progress.style.width = percentProgressWidth; } function t835_scrollToTop(quizFormWrapper) { var topCoordinateForm = quizFormWrapper.getBoundingClientRect().top + window.pageYOffset; var blockContainer = quizFormWrapper.closest('.t835'); if (topCoordinateForm >= window.scrollY || blockContainer.classList.contains('t835_scroll-disabled')) return; // try to find fixed menu var isMenuFixed = !!document.querySelector('.t228__positionfixed'); if (isMenuFixed) { // if fixed menu is exist, find desctop version var menu = document.querySelector('.t228__positionfixed:not(.t228__mobile)'); var menuHeight = parseFloat(window.getComputedStyle(menu).height); // calculate current offset for scroll if (!window.isMobile && !isNaN(menuHeight)) { topCoordinateForm = topCoordinateForm - menuHeight - 5; } } window.scrollTo(0, topCoordinateForm); } /** * Возвращает массив шагов без формы захвата. * @param {*} rec * @returns {Array} */ function t835_createStepsArray(rec) { var steps = rec.querySelectorAll('.t835__screen-wrapper'); var allSteps = []; Array.prototype.forEach.call(steps, function (step) { if (!step.classList.contains('t835__capture-form')) { allSteps.push(step); } }); return allSteps; } function t835_disabledPrevBtn(rec, quizStepIndex) { var prevBtn = rec.querySelector('.t835__btn_prev'); if (quizStepIndex === 0) { prevBtn.setAttribute('disabled', true); } else { prevBtn.removeAttribute('disabled'); } } function t835_hideError(rec, quizStepIndex) { var stepsArray = t835_createStepsArray(rec); var currentStep = stepsArray[quizStepIndex]; if (!currentStep) return; currentStep.classList.remove('js-error-control-box'); currentStep.querySelector('.t-input-error').innerHTML = ''; } function t835_awayFromResultScreen(rec) { var quizDescription = rec.querySelector('.t835__quiz-description'); var resultTitle = rec.querySelector('.t835__result-title'); if (resultTitle) resultTitle.style.display = 'none'; if (quizDescription) quizDescription.style.display = 'block'; } function t835_showError(rec, quizWrapper, quizStepIndex) { if (quizWrapper.classList.contains('t835__quiz-published')) { return t835_setError(rec, quizStepIndex); } } function t835_setError(rec, quizStepIndex) { var arrQuestion = t835_createStepsArray(rec); var activeQuestion = arrQuestion[quizStepIndex]; var showErrors; if (typeof window.tildaForm !== 'object') return showErrors; var arrErrors = window.tildaForm.validate(activeQuestion); var errorsTypeObj = arrErrors[0]; if (errorsTypeObj) { var errorType = errorsTypeObj.type[0]; var error = rec.querySelector('.t-form .t-form__errorbox-middle .js-rule-error-' + errorType); var strError = ''; if (error) strError = error.textContent; if (!strError) { t_onFuncLoad('t_forms__getMsg', function () { strError = t_forms__getMsg(errorType); }); } if (errorType === 'emptyfill') { showErrors = false; } else { if (activeQuestion) activeQuestion.classList.add('js-error-control-box'); showErrors = window.tildaForm.showErrors(activeQuestion, arrErrors); } var inputError = activeQuestion.querySelector('.t-input-error'); if (inputError) inputError.innerHTML = strError; } return showErrors; } var t835_debounceAdjustheight = t835_debounce(t835_adjustStepToHeight, 200); function t835_adjustHeightOnResize(rec) { window.addEventListener('resize', function () { t835_debounceAdjustheight(rec); }); } function t835_debounce(callee, timeoutMs) { var timeoutId; return function () { var args = Array.prototype.slice.call(arguments); clearTimeout(timeoutId); timeoutId = setTimeout(function () { callee.apply(null, args); }, timeoutMs); }; } function t835_adjustStepToHeight(rec) { var MIN_VALID_DIFFERENCE = 30; var MIN_POSSIBLE_DIFFERENCE = 1; var stepWrapper = rec.querySelector('.t835__quiz-form-wrapper'); var stepContainer = rec.querySelector('.t835__quiz-nofixedheight'); var stepHeight = stepWrapper ? stepWrapper.offsetHeight : 0; if (stepHeight <= 0 || !stepContainer) return; var oldHeight = parseInt(getComputedStyle(stepContainer).height, 10); var heightDiff = Math.abs(oldHeight - stepHeight); // если изменение незанчительное, то ничего не делаем if (MIN_POSSIBLE_DIFFERENCE < heightDiff && heightDiff < MIN_VALID_DIFFERENCE) { return; } // если высота стала больше - скрывайем overflow ради анимации if (stepHeight > oldHeight) { stepContainer.style.overflow = 'hidden'; setTimeout(function () { stepContainer.style.overflow = ''; }, 300); } stepContainer.style.height = stepHeight + 'px'; } function t835_getNextAll(element) { var nextElements = []; var nextElement = element; while (nextElement.nextElementSibling) { if (nextElement.nextElementSibling.classList.contains('t-input-group')) { nextElements.push(nextElement.nextElementSibling); } nextElement = nextElement.nextElementSibling; } return nextElements; } function t835_onSuccess(form) { t_forms__onSuccess(form); } // Polyfill: Element.matches if (!Element.prototype.matches) { Element.prototype.matches = Element.prototype.matchesSelector || Element.prototype.msMatchesSelector || Element.prototype.mozMatchesSelector || Element.prototype.webkitMatchesSelector || Element.prototype.oMatchesSelector; } // Polyfill: Element.closest if (!Element.prototype.closest) { Element.prototype.closest = function (s) { var el = this; while (el && el.nodeType === 1) { if (Element.prototype.matches.call(el, s)) { return el; } el = el.parentElement || el.parentNode; } return null; }; }