var _mj_domain='https://test.api2.ma.ru',cnt=0,token,dataUID;try{var params=new URLSearchParams(location.search),referer=_getUTMValue(params,'utm_referrer');if(referer&&window.gtag){window.gtag('set','page_referrer',referer)}}catch(e){console.error(e)} function _getUTMValue(params,name){var value=params.get(name);if(value){return value} value=_getCookie(name);if(value){return value} return null} function _getCookie(name){var match=document.cookie.match(new RegExp('(^| )'+name+'=([^;]+)'));if(match){return decodeURIComponent(match[2])} return null} function isDesktop(){return!/Android|webOS|iPhone|iPad|iPod|BlackBerry|BB|PlayBook|IEMobile|Windows Phone|Kindle|Silk|Opera Mini/i.test(window.navigator.userAgent)} function _mj(ac,dm){var data={data:dm,action:ac,data_id:dataUID,yandex_client_id:mgyci(),google_client_id:mggci(),mj_token:mgtci(),};var c="onload" in new XMLHttpRequest?XMLHttpRequest:XDomainRequest,d=new c;d.open("POST",_mj_domain+"/api/analytics/set/action/",!0),d.withCredentials=!0,d.setRequestHeader("Content-Type","application/json; charset=utf-8"),d.send(JSON.stringify(data)),d.onload=function(){var a=JSON.parse(this.responseText);console.log(a)},d.onerror=function(){return console.log("\u041E\u0448\u0438\u0431\u043A\u0430 "+this.status),!1}} function mgc(a){const b=`; ${document.cookie}`,c=b.split(`; ${a}=`);if(2===c.length)return c.pop().split(";").shift()} function mggci(){return mgc("_ga")} function ctSessId(){try{if(typeof window.ct!=='function')return;const params=window.ct('calltracking_params');if(!params||!params.length)return;return params[0].sessionId}catch(e){console.error('ctSessId Err: ',e.message)}} function setCtToken(){try{if(typeof window.ct!=='function')return null;let attrs=`{"_mj_token":"${token}", "data_uid":"${dataUID}"}`;window.ct('set_attrs',attrs)}catch(e){console.error('setCtToken Err: ',e.message)}} function mgtci(){return mgc("_mj_token")} function mgyci(){return mgc("_ym_uid")} function __mgr(){var a=document.referrer,b=mgc("_mj_referrer"),c=a.search(window.location.hostname);return-1===c&&""!==a?document.cookie="_mj_referrer="+a+";path=/;max-age=2592000":("undefined"==typeof b||""===a)&&(document.cookie="_mj_referrer=direct;path=/;max-age=2592000"),mgc("_mj_referrer")} function sD(){cnt++;if(window.ct&&!ctSessId()&&cnt<=5){return} const qS=window.location.search,uP=new URLSearchParams(qS);var p={site:window.location.hostname,site_url:window.location.pathname,referrer_site:__mgr(),utm_medium:_getUTMValue(uP,"utm_medium"),utm_source:_getUTMValue(uP,"utm_source"),utm_campaign:_getUTMValue(uP,"utm_campaign"),utm_term:_getUTMValue(uP,"utm_term"),utm_content:_getUTMValue(uP,"utm_content"),yandex_client_id:mgyci(),google_client_id:mggci(),mj_token:mgtci(),ctSessId:ctSessId(),is_desktop:isDesktop(),};mxc(_mj_domain+"/api/analytics/set/",p);return!0;function mxc(a,b){var c="onload" in new XMLHttpRequest?XMLHttpRequest:XDomainRequest,d=new c;d.open("POST",a,!0),d.withCredentials=!0,d.setRequestHeader("Content-Type","application/json; charset=utf-8"),d.send(JSON.stringify(b)),d.onload=function(){var res=JSON.parse(this.responseText);dataUID=res&&res.id;token=res&&res.token;document.cookie=`data_uid=${dataUID};path=/`;if(mgtci()){token=mgtci();setCtToken();return} document.cookie=`_mj_token=${token};path=/`;setCtToken()},d.onerror=function(){return console.log("\u041E\u0448\u0438\u0431\u043A\u0430 "+this.status),!1}}} if(!sD()){setTimeout(sD,2000)}(function(){const excludedSites=['est.ma.ru',];if(excludedSites.some(site=>location.host.includes(site)))return;const DEBUG=!1;function log(...args){if(DEBUG){console.log('[CaptchaInterceptor]',...args)}} const CAPTCHA_INDICATORS=['need_captcha','captcha_required','captcha_flag','captcha','needCaptcha','isCaptcha','captcha_needed'];const CAPTCHA_COOKIE='show_captcha=1; path=/; max-age=3600';const RELOAD_PROTECTION_COOKIE='captcha_reload_protection=1; path=/; max-age=5';const CAPTCHA_RESPONSE_STATUSES=[200,429];function shouldCheckCaptchaStatus(status){return CAPTCHA_RESPONSE_STATUSES.includes(status)} function checkCaptchaResponse(responseText,url){log('🔍 Проверка ответа:',{url,responseLength:responseText?.length});if(!responseText){log('❌ Шаг 1: Пустой ответ');return!1} let data;try{data=JSON.parse(responseText);log('✅ Шаг 2: JSON распарсен успешно')}catch(e){log('❌ Шаг 2: Не JSON ответ',e.message);return!1} log('🔎 Шаг 3: Поиск индикаторов капчи...');const foundIndicators=[];const hasCaptchaFlag=CAPTCHA_INDICATORS.some(indicator=>{const rootValue=data?.[indicator];const jsonValue=data?.json?.[indicator];const nestedDataValue=data?.data?.[indicator];const hasFlag=rootValue===!0||(typeof rootValue==='number'&&rootValue===1)||jsonValue===!0||(typeof jsonValue==='number'&&jsonValue===1)||nestedDataValue===!0||(typeof nestedDataValue==='number'&&nestedDataValue===1);if(hasFlag){if(rootValue!==undefined){foundIndicators.push(`${indicator}: ${rootValue}`)} if(jsonValue!==undefined){foundIndicators.push(`json.${indicator}: ${jsonValue}`)} if(nestedDataValue!==undefined){foundIndicators.push(`data.${indicator}: ${nestedDataValue}`)}} return hasFlag});if(hasCaptchaFlag){log('🚨 Шаг 3: КАПЧА ОБНАРУЖЕНА!',{indicators:foundIndicators,fullData:data})}else{log('✅ Шаг 3: Индикаторы капчи не найдены');return!1} log('🛡️ Шаг 4: Проверка защиты от циклической перезагрузки');if(document.cookie.includes('captcha_reload_protection')){log('⏭️ Шаг 4: Защита активна, перезагрузка отменена');return!0} log('✅ Шаг 4: Защита не активна, можно перезагружать');log('🍪 Шаг 5: Установка кук капчи');document.cookie=CAPTCHA_COOKIE;document.cookie=RELOAD_PROTECTION_COOKIE;log('🔄 Шаг 5: Перезагрузка страницы через 100мс');setTimeout(()=>{log('💫 Выполняется перезагрузка...');window.location.reload()},100);return!0}(function initFetchInterceptor(){const originalFetch=window.fetch;if(!originalFetch){log('⚠️ Fetch не поддерживается');return} window.fetch=function(...args){const url=typeof args[0]==='string'?args[0]:args[0]?.url;log('📡 Fetch запрос:',{url,method:args[1]?.method||'GET'});return originalFetch.apply(this,args).then(response=>{log('📨 Fetch ответ получен:',{url,status:response.status,ok:response.ok});const clonedResponse=response.clone();clonedResponse.text().then(text=>{log('📄 Fetch тело ответа получено, длина:',text.length);checkCaptchaResponse(text,url)}).catch(err=>{log('❌ Ошибка чтения fetch ответа:',err.message)});return response})};log('✅ Fetch перехватчик активирован')})();if(window.fw_MOJAX){log('🔄 Обнаружен fw_MOJAX, активируем сложный XHR перехватчик');(function setupComplexXHRInterceptor(){const originalXHR=window.XMLHttpRequest;function PatchedXHR(){const xhr=new originalXHR();let requestUrl='';const originalOpen=xhr.open;xhr.open=function(method,url,...args){requestUrl=url;log('📡 XHR (сложный) запрос:',{method,url});return originalOpen.apply(this,[method,url,...args])};xhr.addEventListener('readystatechange',function(){if(xhr.readyState!==4)return;if(shouldCheckCaptchaStatus(xhr.status)&&requestUrl){checkCaptchaResponse(xhr.responseText,requestUrl)}});const originalAddEventListener=xhr.addEventListener;xhr.addEventListener=function(type,listener,options){if(type==='load'){const wrappedListener=function(event){log('📨 XHR (сложный) load event:',{url:requestUrl,status:xhr.status});if(shouldCheckCaptchaStatus(xhr.status)&&requestUrl){checkCaptchaResponse(xhr.responseText,requestUrl)} listener.apply(this,[event])};return originalAddEventListener.call(this,type,wrappedListener,options)} return originalAddEventListener.call(this,type,listener,options)};return xhr} PatchedXHR.prototype=originalXHR.prototype;PatchedXHR.UNSENT=originalXHR.UNSENT;PatchedXHR.OPENED=originalXHR.OPENED;PatchedXHR.HEADERS_RECEIVED=originalXHR.HEADERS_RECEIVED;PatchedXHR.LOADING=originalXHR.LOADING;PatchedXHR.DONE=originalXHR.DONE;window.XMLHttpRequest=PatchedXHR;log('✅ Сложный XHR перехватчик активирован')})();(function setupJQueryInterceptor(){if(!window.jQuery||!window.jQuery(document)){log('⚠️ jQuery не найден, хотя fw_MOJAX присутствует');return} log('🔄 Настройка jQuery обработчика');window.jQuery.ajaxPrefilter(function(options,originalOptions,jqXHR){jqXHR._mj_url=options.url;log('📡 jQuery запрос:',{url:options.url,type:options.type})});window.jQuery(document).ajaxComplete(function(event,jqXHR,ajaxOptions){const url=jqXHR._mj_url||ajaxOptions.url;log('📨 jQuery ответ получен:',{url,status:jqXHR.status,alreadyChecked:!!jqXHR._mj_captcha_checked});if(shouldCheckCaptchaStatus(jqXHR.status)&&!jqXHR._mj_captcha_checked){jqXHR._mj_captcha_checked=!0;try{checkCaptchaResponse(jqXHR.responseText,url)}catch(e){log('❌ Ошибка в jQuery обработчике:',e.message)}}});log('✅ jQuery обработчик настроен')})()}else{log('🔄 fw_MOJAX не обнаружен, активируем простой XHR перехватчик');(function setupSimpleXHRInterceptor(){const originalXHR=window.XMLHttpRequest;window.XMLHttpRequest=function(){const xhr=new originalXHR();let requestUrl='';let captchaChecked=!1;function checkCaptchaOnce(eventType){if(captchaChecked){return} if(xhr.readyState!==4){return} captchaChecked=!0;log('📨 XHR (простой) ответ:',{url:requestUrl,status:xhr.status,readyState:xhr.readyState,eventType:eventType});if(shouldCheckCaptchaStatus(xhr.status)&&requestUrl){checkCaptchaResponse(xhr.responseText,requestUrl)}} const originalOpen=xhr.open;xhr.open=function(method,url,...args){requestUrl=url;log('📡 XHR (простой) запрос:',{method,url});return originalOpen.apply(this,[method,url,...args])};const originalAddEventListener=xhr.addEventListener;xhr.addEventListener=function(type,listener,options){if(type==='load'||type==='readystatechange'){const wrappedListener=function(event){if(type==='readystatechange'&&xhr.readyState!==4){if(listener)listener.apply(this,[event]);return} checkCaptchaOnce(type);if(listener)listener.apply(this,[event]);};return originalAddEventListener.call(this,type,wrappedListener,options)} return originalAddEventListener.call(this,type,listener,options)};const originalSend=xhr.send;xhr.send=function(...args){if(!xhr._mjCaptchaLoadendBound){xhr._mjCaptchaLoadendBound=!0;originalAddEventListener.call(xhr,'loadend',function(){checkCaptchaOnce('loadend')})} return originalSend.apply(this,args)};return xhr};log('✅ Простой XHR перехватчик активирован')})()} if(DEBUG){console.log('🎯 [CaptchaInterceptor] Инициализация завершена, режим:',window.fw_MOJAX?'fw_MOJAX':'обычный')}})();(function(){const DEBUG=!1;function log(...args){if(DEBUG){console.log('[ContactCapture]',...args)}} const PHONE_KEYS=/^(phone|tel|telephone|mobile|phone_number|user_phone|client_phone)$/i;const EMAIL_KEYS=/^(email|e[-_]?mail|user_email|client_email)$/i;const NAME_KEYS=/^(name|fio|full_name|first_name|user_name|client_name)$/i;const EMAIL_RE=/^[^\s@]+@[^\s@]+\.[^\s@]+$/;function isOwnRequest(url){return typeof url==='string'&&url.indexOf('/api/analytics/')!==-1} function isSuccessStatus(status){return status>=200&&status<300} function extractRoute(url){try{const parsed=new URL(url,window.location.origin);return parsed.pathname.replace(/^\/+|\/+$/g,'')||null}catch(e){return null}} function normalizePhone(raw){if(!raw)return null;const digits=String(raw).replace(/\D/g,'');if(digits.length===11&&(digits[0]==='7'||digits[0]==='8')){return'7'+digits.slice(1)} if(digits.length===10){return'7'+digits} return null} function normalizeEmail(raw){const value=String(raw||'').trim();return EMAIL_RE.test(value)?value:null} function parseBody(body){const result={};function collect(obj,depth){if(!obj||typeof obj!=='object'||depth>2)return;for(const key in obj){if(!Object.prototype.hasOwnProperty.call(obj,key))continue;const value=obj[key];if(value&&typeof value==='object'){collect(value,depth+1)}else if((typeof value==='string'||typeof value==='number')&&!(key in result)){result[key]=value}}} try{if(typeof body==='string'){try{collect(JSON.parse(body),0)}catch(e){const params=new URLSearchParams(body);params.forEach((value,key)=>{if(!(key in result))result[key]=value})}}else if(typeof FormData!=='undefined'&&body instanceof FormData){body.forEach((value,key)=>{if(typeof value==='string'&&!(key in result))result[key]=value})}else if(body&&typeof body==='object'){collect(body,0)}}catch(e){log('Ошибка парсинга тела запроса',e.message)} return result} function extractContact(body){const fields=parseBody(body);let phone=null,email=null,name=null;for(const key in fields){if(!phone&&PHONE_KEYS.test(key)){phone=normalizePhone(fields[key])} if(!email&&EMAIL_KEYS.test(key)){email=normalizeEmail(fields[key])} if(!name&&NAME_KEYS.test(key)){name=String(fields[key]).trim()||null}} if(!phone&&!email)return null;return{phone,email,name}} function alreadySent(contact,route){const key='mj_contact_sent_'+(contact.phone||'')+'_'+(contact.email||'')+'_'+(route||'');try{if(sessionStorage.getItem(key))return!0;sessionStorage.setItem(key,'1')}catch(e){} return!1} function sendContactEvent(contact,url){if(!contact||(!contact.phone&&!contact.email))return;const route=extractRoute(url);if(alreadySent(contact,route)){log('Контакт уже отправлялся в этой сессии, пропуск',contact,route);return} if(typeof window._mj!=='function')return;log('📤 Отправка контакта в send_contact',{contact,route,url});window._mj('send_contact',{phone:contact.phone,email:contact.email,name:contact.name,route:route,})}(function initFetchContactCapture(){const originalFetch=window.fetch;if(!originalFetch)return;window.fetch=function(...args){const url=typeof args[0]==='string'?args[0]:args[0]?.url;const body=args[1]?.body;const contact=!isOwnRequest(url)?extractContact(body):null;return originalFetch.apply(this,args).then(response=>{if(contact&&isSuccessStatus(response.status)){sendContactEvent(contact,url)} return response})}})();(function initXHRContactCapture(){const OriginalXHR=window.XMLHttpRequest;if(!OriginalXHR)return;window.XMLHttpRequest=function(){const xhr=new OriginalXHR();let requestUrl='';const originalOpen=xhr.open;xhr.open=function(method,url,...rest){requestUrl=url;return originalOpen.apply(this,[method,url,...rest])};const originalSend=xhr.send;xhr.send=function(body){const contact=!isOwnRequest(requestUrl)?extractContact(body):null;if(contact){xhr.addEventListener('loadend',function(){if(isSuccessStatus(xhr.status)){sendContactEvent(contact,requestUrl)}})} return originalSend.apply(this,[body])};return xhr}})();(function initJQueryContactCapture(){if(!window.jQuery)return;window.jQuery(document).ajaxComplete(function(event,jqXHR,ajaxOptions){if(isOwnRequest(ajaxOptions.url)||!isSuccessStatus(jqXHR.status))return;const contact=extractContact(ajaxOptions.data);if(contact){sendContactEvent(contact,ajaxOptions.url)}})})()})()