// JavaScript Document if (typeof window.gib !== 'undefined') { if (istmUserId()) { window.gib.setAuthStatus(window.gib.IS_AUTHORIZED); console.log(`set auth status authorized`) } } // Запускать при запуске всех форм function AllOnLoad() { let LANGUAGE = 'ru-RU'; let hintTimer = 0; //Таймер подсказок // Обработка языка $('.lang-switch').html(LANGUAGE == 'kz-KZ' ? 'ru' : 'kz'); // Изменение языка по клику на lang-switch $('.lang-switch').on('click', () => { changeLanguage(); }); // Обработка сообщений //Ошибка BIGERROR if ($('#fbigerror').length && $('#fbigerror').html()) { showError($('#fbigerror').html()); } //Сообщение BIGMSG if ($('#fbigmsg').length && $('#fbigmsg').html()) { showMsg($('#fbigmsg').html()); } // желтый круглешок в меню if ($('#menu-num').length && ($('#menu-num').html() == '0' || $('#menu-num').html() == '')) { $('#menu-num').prop('style', 'display: none'); } // Обработка отправки токена в WebView if (istmUserId() && typeof Android !== 'undefined' && Android.setToken) { // На страничке с пользователем открытым в WebView let A = document.cookie.split(';'); A.forEach(function (T) { if (T.includes('tmUserId')) Android.setToken(T.trim()); }); } } //Создаем независимые страницы function pageWorker() { let page = 1; return { get: () => { return page; }, set: () => { page++; return page; }, reset: () => { page = 1; }, }; } // Страница для анонсов let announcePage = pageWorker(); // Смена языка function changeLanguage() { let ru = 'ru-RU'; let kz = 'kz-KZ'; // Проверка на # if (location.href.includes('#') && !location.href.includes('?') && !location.href.includes('&SetLanguage')) { let str = location.href; str = str.split('#'); str[0] = str[0] + '?SetLanguage=' + LANGUAGE; str = str.join('#'); history.replaceState(null, null, str); window.location.href = str; window.location.reload(); return; } if ( location.href.includes('#') && location.href.includes('?') && !location.href.includes('?SetLanguage=') && !location.href.includes('&SetLanguage') ) { let str = location.href; str = str.split('#'); str[0] = str[0] + '&SetLanguage=' + LANGUAGE; str = str.join('#'); history.replaceState(null, null, str); location.href = str; window.location.reload(); return; } // Проверка на & if (!location.href.includes('?') && !location.href.includes('&SetLanguage')) { location.href = location.href + '?SetLanguage=' + LANGUAGE; } if (location.href.includes('?SetLanguage') || location.href.includes('&SetLanguage')) { if (location.href.includes(ru)) { location.href = location.href.replace(ru, kz); } if (location.href.includes(kz)) { location.href = location.href.replace(kz, ru); } return; } // Проверка на ? if (location.search && !location.href.includes('&SetLanguage')) { location.href = location.href + '&SetLanguage=' + LANGUAGE; return; } } // ------------------- Утилиты ---------------------------- function showError(b) { notify('Ошибка', b, 0, 150, 1, '', '', 'https://rpo.logycom.kz/tm/static/lib/gritter/images/warning.svg'); } function showMsg(b) { notify('Сообщение', b, 0, 150, 3, '', '', 'https://rpo.logycom.kz/tm/static/lib/gritter/images/success.svg'); } function showWarn(b) { notify('Предупреждение', b, 0, 150, 2, '', '', 'https://rpo.logycom.kz/tm/static/lib/gritter/images/info.svg'); } function showPopup(json) { if (!json || !json.type) { throw new Error('You should set popup type'); } if (json.type === 2) { if (json.msgType == 0) showError(json.msg); if (json.msgType == 1) showWarn(json.msg); if (json.msgType == 2) showMsg(json.msg); return; } if (json.type === 0) { return; } else if (json.type === 1) { const modal = plugins.popup(calcProgressBar); modal.setContent(popupsTemplates.achivmentTemplate(json)); modal.open(); } else if (json.type === 999) { const modal = plugins.popup(setThemeOldMobilePopup); modal.setContent(popupsTemplates.mobileWarningTemplate()); modal.open(); } else if (json.type == 3) { console.log('modal type 3') const modal = plugins.popup(); const decodedData = atob(json.html); const html = new TextDecoder("utf-8").decode(Uint8Array.from(decodedData, (c) => c.charCodeAt(0))); modal.setContent(html); modal.setID(json.type); document.querySelector('.popup__content').style.padding = 0; modal.open(); } else if (json.type === 'profile') { const modal = plugins.popup(); modal.setContent(popupsTemplates.profileTemplate(json)); modal.open(); } else if (json.type === 'custom') { // Для кастомных модалок. const modal = plugins.popup(); } else { showError('Что то пошло не так'); } } // function showPopupOldMobile() { // let current = +new Date(); // let day = 24 * 3600 * 1000; // if (!localStorage['timeForOldApp']) { // localStorage.setItem('timeForOldApp', current); // showPopup({ "type": 999 }); // } else if (current - +localStorage['timeForOldApp'] > day) { // localStorage.clear(); // localStorage.setItem('timeForOldApp', current); // showPopup({ "type": 999 }); // } // } // Сообщение об ошибке или что-то типа (Заголовок, Сообщение, 0-время 1-пока не закроют, Время в сек., Класс('1','2','3',''), Центрирование, Стили, Картинка) function notify(h, b, s, t, c, x, p, m) { $('#gritter-notice-wrapper').remove(); if (!h) { $.gritter.removeAll(); return; } $.gritter.add({ title: h, text: b, sticky: s ? s : false, time: t ? t * 1000 : 5000, class_name: c ? 'notify_' + c : '', after_open: function (e) { e.find('.gritter-close').html(''); if (x) { e.css({ position: 'fixed', left: 'calc(50% - ' + parseInt(e.outerWidth()) + 'px / 2)', top: 'calc(50% - ' + parseInt(e.outerHeight()) + 'px / 2)', width: e.outerWidth() + 'px', }); } if (p) { eval('e.css(' + p + ')'); } }, image: m ? m : null, }); } // Отправить сообщение к лиснеру srv. // Если вернут ошибку - показать ошибку, если OK и url - перейти на этот URL, если только OK то return true function SendToSrv(message) { var forRet = false; $.ajax({ url: 'https://rpo.logycom.kz/tm/threemen.dll/srv', async: false, type: 'POST', data: message, dataType: 'text', }).always(function (data, errStatus) { var msg = {}; if (errStatus == 'success') msg = uparams(data); if (msg['status'] !== 'OK') { if (msg.tmErrorCode) { setErrorToInput(msg.tmErrorCode, msg.msg); } else { showError(msg['msg'] ? msg['msg'] : 'Что-то пошло не так'); forRet = false; } } else { if (typeof msg['gibID'] !== 'undefined') { if (typeof window.gib !== 'undefined') { window.gib.setIdentity(msg['gibID']); } if (msg['top'] && msg['top'] == '1') { top.location.href = decodeURIComponent(msg['url']); } else { location.href = decodeURIComponent(msg['url']); } } if (typeof msg['url'] !== 'undefined') { if (msg['top'] && msg['top'] == '1') { top.location.href = decodeURIComponent(msg['url']); } else { location.href = decodeURIComponent(msg['url']); } // вот это во фрейме не работает //window.location.href = decodeURIComponent(msg['url']); // location.href = decodeURIComponent(msg['url']); } if (typeof msg['warning'] !== 'undefined') { showWarn(msg['warning']); } forRet = true; } }); return forRet; } async function asyncSendToSrv(message) { let forRet = false; await $.ajax({ url: 'https://rpo.logycom.kz/tm/threemen.dll/srv', type: 'POST', data: message, dataType: 'text', }).always(function (data, errStatus) { var msg = {}; if (errStatus == 'success') msg = uparams(data); if (msg['status'] !== 'OK') { if (msg.tmErrorCode && msg.tmErrorCode !== '3') { setErrorToInput(msg.tmErrorCode, msg.msg); } else { showError(msg['msg'] ? msg['msg'] : 'Что-то пошло не так'); } forRet = false; } else { if (typeof msg['url'] !== 'undefined') { if (msg['top'] && msg['top'] == '1') { top.location.href = decodeURIComponent(msg['url']); } else { location.href = decodeURIComponent(msg['url']); } } if (typeof msg['warning'] !== 'undefined') { showWarn(msg['warning']); } forRet = true; } }); return forRet; } function setErrorToInput(code, message) { let input; let input2; let input3; let input4; if (code == 1) { input = document.querySelector('.input_type_tel'); validate(input, message, code); } if (code == 2) { input = document.querySelector('.input_type_pass'); validate(input, message, code); } if (code == 3) { fillProfileFunc(); } if (code == 5) { input = document.querySelector('.input_type_str1'); input2 = document.querySelector('.input_type_str2'); input3 = document.querySelector('.input_type_str3'); input4 = document.querySelector('.input_type_str4'); input.classList.add('input-invalid'); input2.classList.add('input-invalid'); input3.classList.add('input-invalid'); input4.classList.add('input-invalid'); document.querySelector('.error-message-str1').style.color = 'red'; document.querySelector('.error-message-str2').style.color = 'red'; document.querySelector('.error-message-str3').style.color = 'red'; document.querySelector('.error-message-str4').style.color = 'red'; validate(input, message, code); validate(input2, message, code); validate(input3, message, code); validate(input4, message, code); } } // Синхронно получить данные function RecieveFromSrv(message) { var forRet; $.ajax({ url: 'https://rpo.logycom.kz/tm/threemen.dll/srv', async: true, type: 'POST', data: message, dataType: 'text', }).always(function (data, errStatus) { var msg = {}; if (errStatus == 'success') msg = uparams(data); if (msg['status'] !== 'OK') { showError(msg['msg'] ? msg['msg'] : 'Что-то пошло не так'); return; } if (typeof msg['url'] !== 'undefined') { window.location.href = decodeURIComponent(msg['url']); } forRet = msg; }); return forRet; } // Выполнит запрос асинхронно и результат вместе с AValue передаст в функцию fun function AsyncRecieveFromSrv(message, AValue, fun) { $.ajax({ url: 'https://rpo.logycom.kz/tm/threemen.dll/srv', type: 'POST', data: message, dataType: 'text', }).always(function (data, errStatus) { var msg = {}; if (errStatus == 'success') msg = uparams(data); fun(msg, message, AValue); }); } //предбразовать строку &имя=значение в объект function uparams(p) { var ret = {}; if (typeof p != 'undefined') { var seg = p.replace(/^\?/, '').split('&'), len = seg.length, i = 0, s; for (; i < len; i++) { if (!seg[i]) { continue; } s = seg[i].split('='); if (s.length > 2) { for (let j = 2; j < s.length; j++) { s[1] += '=' + s[j]; } } ret[s[0]] = s[1]; } } return ret; } // фокус на input по имени function SetFocusByName(AName) { var x = document.getElementsByName(AName); x[0].focus(); } // фокус на input по id function SetFocusById(AName) { document.getElementById(AName).focus(); } // проверить строчку на содержание в ней e-mail function validateEmail(email) { const re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; return re.test(String(email).toLowerCase()); } // получить корректро числа. Пока вроде не надо function getIntCorrector(intValue, cor1, cor2, cor5) { var S = intValue + ''; if (S.length > 1 && S[S.length - 2] == '1') return cor5; else if (S[S.length - 1] == '1') return cor1; else if (S[S.length - 1] == '2' || S[S.length - 1] == '3' || S[S.length - 1] == '4') return cor2; else return cor5; } // добавить 0 перед числом до digits_length function addZero(digits_length, source) { var text = source + ''; while (text.length < digits_length) text = '0' + text; return text; } // Обработка Push сообщений function subscribe(messaging) { // получаем ID устройства messaging .getToken() .then(function (currentToken) { if (currentToken) { sendTokenToServer(currentToken); // Привяжемся к сообщениям если уже запущены messaging.onMessage(function (payload) { var pl = payload.notification; notify(pl.title ? pl.title : ' ', pl.body, 1, 7, 3, '', '', pl.icon); }); } else { setTokenSentToServer(false); } }) .catch(function () { setTokenSentToServer(false); }); } // отправка ID на сервер function sendTokenToServer(currentToken) { if (!isTokenSentToServer(currentToken)) { if (SendToSrv({ srv: 'messagePushToken', userAgent: navigator.userAgent, token: currentToken })) { setTokenSentToServer(currentToken); } } } // используем localStorage для отметки того, // что пользователь уже подписался на уведомления function isTokenSentToServer(currentToken) { return window.localStorage.getItem('sentFbMesTokenToThreeMen') == currentToken; } // Записываем в хранилище function setTokenSentToServer(currentToken) { window.localStorage.setItem('sentFbMesTokenToThreeMen', currentToken ? currentToken : ''); } // Проверяет логинут ли пользователь в платформу function istmUserId() { if (getCookie('tmUserId') == '0') return false; else return true; } // Проверяет запущены ли мы в мобильном приложении function isMobileApp() { if (typeof Android !== 'undefined' && Android.setToken) return true; else return false; } function isOurMobileApp() { if (document.cookie.includes('tmMobApp=true')) return true; else return false; } // Получить значение cookie function getCookie(name) { let matches = document.cookie.match(new RegExp('(?:^|; )' + name.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g, '\\$1') + '=([^;]*)')); return matches ? decodeURIComponent(matches[1]) : '0'; } function sendDataToPage(params) { const { data, page } = params; $.ajax({ url: `https://rpo.logycom.kz/tm/threemen.dll/${page}`, type: 'POST', data: JSON.stringify(data), enctype: 'multipart/form-data', processData: false, contentType: false, cache: false, success: data => { }, error: err => { showError('Что то пошло не так'); }, }); } //Отправить форму с изображением async function sendMultiForm(form, page, isNotReload) { const data = new FormData(form); return $.ajax({ url: `https://rpo.logycom.kz/tm/threemen.dll/${page}`, type: 'POST', data: data, enctype: 'multipart/form-data', processData: false, async: true, contentType: false, cache: false, }).then(res => { if (isNotReload) { return true; } else { return location.reload(); } }).catch(err => { showError('Что то пошло не так'); return false; }); } function checkIOS() { const iosDevices = ['iPad Simulator', 'iPhone Simulator', 'iPod Simulator', 'iPad', 'iPhone', 'iPod']; if (iosDevices.includes(navigator.platform)) { //Если платформа IOS let v = navigator.appVersion.match(/OS (\d+)_(\d+)_?(\d+)?/); // Объясвим совпадение по версии. Например 12.5.4; return [parseInt(v[1], 10), parseInt(v[2], 10), parseInt(v[3] || 0, 10)]; //Вернем номер версии. Например 12; } return false; } //Заблокировать скролл страницы. function disableScroll() { if (!$('body').is('.modal__is-opened')) { let cWidth = $('body').width(); $('body').attr('data-scroll-position', window.pageYOffset); $('body').addClass('modal__is-opened'); // $('body').css({ // "top": "-" + $('body').attr('data-scroll-position') + "px" // }) let sWidth = $('body').width() - cWidth; if (!checkMobileDevice()) { $('body').css('padding-right', sWidth + 'px'); $('.header').css('padding-right', sWidth + 'px'); } $('body').on('touchmove', e => { return false; }); // const iosVer = checkIOS(); // if (iosVer && iosVer[0] < 15) { // $('body').prop('style', 'position: fixed!important;'); // } } else { return; } } //Разблокировать скролл страницы. function enableScroll() { if (!document.querySelector('body').dataset.modalOpen) { $('body').removeClass('modal__is-opened'); $('body, .header').prop('style', ''); $('body').off('touchmove'); window.scroll(0, document.body.getAttribute('data-scroll-position')); } } //Проверка на мобильные устройства. function checkMobileDevice() { if (screen.width <= 1024 || window.innerWidth <= 1024) { return true; } else { return false; } } function changeDisplay(keyboard, h) { //Передаем параметрами если клава открыта то 1 параметр true, вторым передаем высоту клавиатуры let page = document.querySelector('.page'); // Здесь задаем селектор который хотим изменить. Ну типа у меня это div.page весь контент тут лежит. if (keyboard) { page.style.height = `${document.documentElement.clientHeight - h}px`; page.style.overflowY = 'scroll'; } else { page.style.height = 'auto'; page.style.overflowY = 'auto'; } } function checkEnableCaptcha(element, sitekey) { if (element && element.getAttribute('data-sitekey') !== '') { return true; } else if (sitekey && sitekey !== '') { return true; } return false; } async function fontLoader(fontName, url) { const font = new FontFace(fontName, `url("${url}")`); await font.load(); document.fonts.add(font); } function checkWhatPage() { const links = checkMobileDevice() ? document.querySelectorAll('.fixed-footer-box a') : document.querySelectorAll('.header__linksCont a'); for (let link of links) { if ( link.getAttribute('href') === document.location.href.split('?')[0] || link.getAttribute('href') + '/' === document.location.href.split('?')[0] ) { link.classList.add('active'); } else if (link.getAttribute('href').includes('/results') && document.location.href.includes('/resultsGame')) { link.classList.add('active'); } else if (link.getAttribute('href').includes('/index') && document.location.href.includes('/index')) { link.classList.add('active'); } else if (link.getAttribute('href').includes('/cash') && document.location.href.includes('/cash')) { link.classList.add('active'); } else if (link.dataset.index && location.href.split('?')[0].includes('/index')) { link.classList.add('active'); } else { link.classList.remove('active'); } } } async function asyncSendToSRV(options) { let requestBody = []; for (let option in options) { let key = encodeURIComponent(option); let value = encodeURIComponent(options[option]); requestBody.push(key + '=' + value); } requestBody = requestBody.join('&'); return fetch('https://rpo.logycom.kz/tm/threemen.dll/srv', { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8', }, body: requestBody, }) .then(res => res.text()) .then(res => { let msg = uparams(res); if (msg['status'] !== 'OK') { if (msg['tmErrorCode'] === '3') { return msg; } showError(msg['msg'] ? msg['msg'] : 'Что-то пошло не так'); return false; } return msg; }); } async function asyncSendToSrvJSON(options) { let requestBody = []; for (let option in options.body) { let key = encodeURIComponent(option); let value = encodeURIComponent(options.body[option]); requestBody.push(key + '=' + value); } requestBody = requestBody.join('&'); return fetch(`https://rpo.logycom.kz/tm/threemen.dll/${options.url}`, { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8', }, body: requestBody, }) .then(res => res.text()) .then(res => { let msg = JSON.parse(res); if (msg['status'] !== 'OK') { showError(msg['msg'] ? msg['msg'] : 'Что-то пошло не так'); return false; } return msg; }); } function checkUserCategory(options) { let result = false; $.ajax({ url: 'https://rpo.logycom.kz/tm/threemen.dll/srv?srv=checkCategory', async: false, type: 'POST', data: options, dataType: 'text', }).always(function (data, errStatus) { var msg = {}; if (errStatus == 'success') msg = uparams(data); if (msg['status'] !== 'OK') { showError(msg['msg'] ? msg['msg'] : 'Что-то пошло не так'); result = false; return result; } result = msg['belongs']; }); return JSON.parse(result); } function blockButton(button) { button.setAttribute('disabled', true); $(button) .prepend(`
Loading...
`); } function unBlockButton(button) { button.removeAttribute('disabled'); $(button).find('.loaderButton').remove(); } function removeLoadFromButton(button) { $(button).find('.loaderButton').remove(); } function declOfNum(number, words_list) { // Получаем абсолютное число number = Math.abs(number) % 100; // Получаем число через деление без остатка. Пример 20 % 10 = 2; const _number = number % 10; // Если число больше одного и меньше 5 то подставляем из массива слов 1 значение if (_number > 1 && _number < 5) { return words_list[1]; } // Если 1 то подставляем из массиова слов 0 значение if (_number == 1) { return words_list[0]; } // Если число больше 10 и число меньше 20 то подставляем из массива слов 2 значение return words_list[2]; } function logout() { if (typeof window.gib !== 'undefined') { window.gib.setAuthStatus(window.gib.IS_GUEST); } localStorage.removeItem('tmUserId'); localStorage.removeItem("tmUserIdExpiration") return location.href = 'https://rpo.logycom.kz/tm/threemen.dll/home?exit=true'; }