window.thConfig = window.thConfig || {} window.thSavedCallback = null function sendDataToApiMultiProduct(form, formDataConfig, numberAttemptsToSend = 5) { const DEFAULT_LOCALE = 'ru' const ALLOWED_LOCALES = ['ru', 'en'] toggleErrorBlock(false); if (numberAttemptsToSend < 1) { toggleErrorBlock(true); return; } const API_MULTI_SKYENG_PRODUCT_URL = 'https://teachers-hiring-multiproduct.skyeng.ru/api/client/v1/registration/register-lead'; const config = Object.assign( {}, { beforeSendCallback: null, beforeRedirectCallback: null, joinedName: null, firstName: 'name', lastName: 'surname', email: 'email', phone: 'phone', locale: 'locale', type: '', birthday: 'birthday' }, isObject(formDataConfig) ? formDataConfig : window.thConfig ); const formData = form.serializeArray().reduce(function(acc, el) { return Object.assign({}, acc, { [el.name]: el.value }); }, {}); const requestData = buildRequestData(formData, config, form); try { if (config.beforeSendCallback && false === config.beforeSendCallback(form, requestData)) { return; } } catch (e) { console.log(e) } let apiUrl = API_MULTI_SKYENG_PRODUCT_URL; fetch(apiUrl, { method: 'POST', headers: { 'Content-Type': 'application/json;charset=utf-8' }, referrerPolicy: 'no-referrer-when-downgrade', body: JSON.stringify(requestData), credentials: "include" }).then( response => response.json() ).then(jsonData => { if (jsonData.code === 400) { toggleErrorBlock(true); return; } try { if (config.beforeRedirectCallback && false === config.beforeRedirectCallback(form, requestData, jsonData)) { return; } } catch (e) { console.log(e) } const urlParams = new URLSearchParams(window.location.search); const utmSource = urlParams.get('utm_source'); if (utmSource && utmSource === 'cpaexchange') { const leadUuid = jsonData.redirectUrl.match(/lead-id=(.*)/i)?.[1]; const clickId = urlParams.get('click_id'); if (leadUuid) { fetch(`https://go.cpaex.ru/track/goal-by-click-id?goal_id=3955&click_id=${clickId}&track_id=${leadUuid}`); } } if ('redirectUrl' in jsonData && jsonData.redirectUrl) { setTimeout(() => { window.location.assign(jsonData.redirectUrl); }, 100); } }).catch((e) => { console.log('api error', e) window.sendDataToApiMultiProduct(form, formDataConfig, numberAttemptsToSend - 1); }); function getFormDataForField(formData, fieldName, form) { const elements = $("[name='" + fieldName + "']", form); if (elements.is(':checkbox') && elements.length > 1) { const values = []; elements.filter(function () { return $(this).is(":checked"); }).each(function () { values.push($(this).val()); }); return values; } return formData[fieldName]; } function getFormDataForConfig(formData, config, form) { const requestData = {}; Object.keys(config).map((configKey) => { let formKey = config[configKey]; if (!formKey || typeof formKey === 'function') { return; } if (!Array.isArray(formKey)) { requestData[configKey] = getFormDataForField(formData, formKey, form); return; } formKey.map((formKeyItem) => { if (!formData[formKeyItem]) { return; } requestData[configKey] = getFormDataForField(formData, formKeyItem, form); }) }) return requestData } function buildRequestData(formData, config, form) { const requestData = getFormDataForConfig(formData, config, form); if (requestData['joinedName']) { const nameParts = requestData['joinedName'].split(' ').filter((item) => !!item); requestData['firstName'] = nameParts[0] || ''; requestData['lastName'] = nameParts[1] || ''; delete(requestData['joinedName']); } requestData['firstName'] = requestData['firstName'] || ''; requestData['lastName'] = requestData['lastName'] || ''; requestData['email'] = (requestData['email'] || '').replaceAll(' ', ''); requestData['phone'] = requestData['phone'] || ''; requestData['locale'] = config.locale || DEFAULT_LOCALE; requestData['locale'] = ALLOWED_LOCALES.includes(requestData['locale']) ? requestData['locale'] : DEFAULT_LOCALE; requestData['type'] = requestData['type'] || config.type || ''; requestData['skyeng_mData'] = formData['skyeng_mdata'] || getCookie('skyeng_mData') || ''; requestData['skyeng_hit_id'] = window.hasOwnProperty('skyengTrackHits') && isObject(window.skyengTrackHits) ? window.skyengTrackHits.get_current_hit_id() : ''; requestData['skyeng_seid'] = getCookie('_seid') || ''; requestData['skyeng_referrer'] = getCookie('skyeng_referrer') || ''; requestData['birthday'] = (requestData['birthday'] || '').replaceAll(' ', ''); const birthdayRegExp = /^\d{1,2}.\d{1,2}.\d{4}$|^\d{1,2}-\d{1,2}-\d{4}$|^\d{4}-\d{1,2}-\d{1,2}$|^\d{4}\/\d{1,2}\/\d{1,2}$/; if (!(requestData['birthday'].match(birthdayRegExp) || []).length) { delete(requestData['birthday']); } const params = new URLSearchParams(window.location.search); params.forEach((value, key) => { if (key.indexOf('utm_') !== -1) { requestData[key] = value; } }); return requestData; } function isObject(variable) { return typeof variable === 'object' && variable !== null } } function getCookie(name) { let matches = document.cookie.match(new RegExp( "(?:^|; )" + name.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g, '\\$1') + "=([^;]*)" )); return matches ? decodeURIComponent(matches[1]) : undefined; } function setCookie(name, value, options = {}) { options = { path: '/', ...options }; if (options.expires instanceof Date) { options.expires = options.expires.toUTCString(); } if (options.expiresDays) { let date = new Date(); date.setTime(date.getTime() + (options.expiresDays * 24 * 60 * 60 * 1000)); options.expires = date.toUTCString(); delete(options['expiresDays']); } let updatedCookie = encodeURIComponent(name) + "=" + encodeURIComponent(value); for (let optionKey in options) { updatedCookie += "; " + optionKey; let optionValue = options[optionKey]; if (optionValue !== true) { updatedCookie += "=" + optionValue; } } document.cookie = updatedCookie; } function checkReferrer() { if (!document.referrer || document.referrer.indexOf('skyeng') !== -1) { return; } setCookie('skyeng_referrer', document.referrer, {domain: '.skyeng.ru', expiresDays: 30}); } function setHiddenUid(numberAttempts = 10) { if (numberAttempts < 1) { return; } let cookieData = getCookie('skyeng_mData'); if (typeof cookieData !== 'undefined') { $("form").each(function () { $(this).append('').addClass('stuid'); }); } checkHiddenUid(--numberAttempts); } function checkHiddenUid(numberAttempts) { let mData = $('input[name="skyeng_mData"]'); let forms = $("form"); if (mData.length !== forms.length) { mData.remove(); setHiddenUid(--numberAttempts); } } $(document).ready(function() { setTimeout(function () { window.thSavedCallback = typeof window.t396_onSuccess === 'function' ? window.t396_onSuccess : null; window.t396_onSuccess = window.sendDataToApiMultiProduct; }, 3000); $('.js-form-proccess').each(function () { $(this).data('success-callback', 'window.sendDataToApiMultiProduct'); }); if ( window.thConfig.hasOwnProperty('classForm') && window.thConfig.classForm && (typeof window.thConfig.classForm === 'string' || window.thConfig.classForm instanceof String) ) { $('.' + window.thConfig.classForm).submit(function(event) { event.preventDefault(); sendDataToApiMultiProduct($(this), window.thConfig); }); } checkReferrer(); setHiddenUid(); $(".save-query a").click(function(event) { const link = $(this).attr('href'); const queryParams = document.location.search; event.preventDefault(); window.open(link + queryParams, '_blank'); }); }); function toggleErrorBlock(show) { $(".form-error").each(function () { if (show) { $(this).show(); } else { $(this).hide(); } }); }