var csrf_token = $('meta[name="csrf-token"]').attr('content')
$('#balance').html('')
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min)) + min;
}
function activeLinks(){
$('.sidebar__game').removeClass('sidebar__game--active');
var s = location.href;
var url = (s.substr(s.lastIndexOf("/")+1))
$('.btn_active').removeClass('active')
$('.btn_active.btn_'+url).addClass('active')
$('.game_'+url).addClass('sidebar__game--active');
}
function load(page, that, func = '', id = '') {
$('.preloader').removeClass("preloader-remove");
let _load = function() {
$.get("/" + page + (page.includes('?') ? '&' : '?') + 'json', function(data) {
$('#_ajax_content_').html(data);
window.history.pushState({"html":data,"pageTitle":$(document).find("title").text()}, $(document).find("title").text(), "/"+page);
$('#_ajax_content_').fadeIn('slow')
$('.preloader').addClass("preloader-remove");
$('.btn_open_close_prof').removeClass('active');
activeLinks();
chatGet()
getHistoryGames()
$(".popup--wallet .popup__content .wallet").not(":first").hide();
$(".popup--wallet .popup__content .wallet__history").not(":first").hide();
if(func == 1){
setTimeout(() => loadTournier(id), 1000);
}
socket.emit('getGamesOnline');
$('html, body').animate({scrollTop: 0},0);
}).fail(function(jqxhr, settings, exception) {
$('.preloader').addClass("preloader-remove");
notifaction("error", "Ошибка")
});
};
_load();
}
$(document).ready(function() {
$('.preloader').addClass("preloader-remove");
// $('#app').snowfall({image :"images/snow/snow/1.png", minSize: 5, maxSize:15, flakeCount: 20});
$.ripple('.is-ripples', {
debug: true,
multi: false,
color: "#fff",
opacity: 0.4,
duration: 0.3
});
toastr.options = {
"closeButton": false,
"debug": false,
"newestOnTop": true,
"progressBar": true,
"positionClass": "toast-top-right",
"preventDuplicates": false,
"onclick": null,
"showDuration": "500",
"hideDuration": "1000",
"timeOut": "5000",
"extendedTimeOut": "1000",
"showEasing": "swing",
"hideEasing": "linear",
"showMethod": "fadeIn",
"hideMethod": "fadeOut"
};
$('#chatBtn').click(function(e){
e.preventDefault();
$('#moreBtn').removeClass('active');
$(this).toggleClass('active')
$('body').toggleClass('chat--opened').removeClass('more--opened');
});
$('#moreBtn').click(function(e){
e.preventDefault();
$('#chatBtn').removeClass('active');
$(this).toggleClass('active')
$('body').toggleClass('more--opened').removeClass('chat--opened');
});
$('.close-chat').click(function(e){
e.preventDefault();
$('body').removeClass('chat--opened');
$('#chatBtn').removeClass('active');
})
});
const SOCKET_PORT = 2083;
const socketUrl = `${location.protocol}//${location.hostname}:${SOCKET_PORT}`;
const socket = io(socketUrl);
socket.emit('getUsersOnline');
socket.emit('getGamesOnline');
socket.on('usersOnline', function(data){
$('.online').html(Number(data));
})
socket.on('gamesOnline', function(data){
gamesOnline = JSON.parse(data)
let i = 0;
while (i < 9) {
onlineG = gamesOnline[i].length
$('.games .games__item:eq('+i+') .games__item-text p').html(Number(onlineG)+' человек');
i++;
}
})
socket.on('laravel_database_mess', function(data){
data = JSON.parse(data);
var type = data.type;
if(type == "uploadMessage"){
chatAdd(data);
}
if(type == "chat_clear"){
$('.chat__messages .ss-wrapper .ss-content').html('');
}
if(type == "deleteMess"){
var idd = data.id;
$('#msg_'+idd).remove();
}
})
socket.on('CHAT_TIME',e=>{
chatHour = String(e.chatHour)
chatMinute = String(e.chatMinute)
chatSecond = String(e.chatSecond)
$('.Chat .chat__promocode-timer--span:nth-child(1)').html(chatHour[0])
$('.Chat .chat__promocode-timer--span:nth-child(2)').html(chatHour[1])
$('.Chat .chat__promocode-timer--span:nth-child(4)').html(chatMinute[0])
$('.Chat .chat__promocode-timer--span:nth-child(5)').html(chatMinute[1])
$('.Chat .chat__promocode-timer--span:nth-child(7)').html(chatSecond[0])
$('.Chat .chat__promocode-timer--span:nth-child(8)').html(chatSecond[1])
})
socket.on('laravel_database_history', function(data){
e = JSON.parse(data);
$(".gameHistory").prepend(' \
\
| \
\
\
'+e.name_game+'\
\
| \
\
\
| \
\
\
'+e.bet+'\
\
\
| \
\
\
'+((e.win / e.bet).toFixed(2))+'x \
'+((e.win / e.bet).toFixed(2))+'x\
\
| \
\
\
'+e.win+'\
\
\
| \
');
$('.gameHistory').children().slice(10).remove();
})
function sleep(milliseconds) {
const date = Date.now();
let currentDate = null;
do {
currentDate = Date.now();
} while (currentDate - date < milliseconds);
}
function stretchArray(arr, limit) {
if (!arr.length || limit < arr.length) {
throw new Error('Не удалось растянуть массив.');
}
// Целое число, на которое будет размножен каждый элемент.
const integer = Math.floor(limit / arr.length);
// a % b - остаток от деления.
// По единичке будем накидывать на каждый элемент.
// Кому досталось, тому досталось, как `крошки` со стола.
let crumbs = limit % arr.length;
const newArr = Array.from(arr, function(item, index) {
// Сколько раз нужно размножить элемент массива.
const repeater = integer + (crumbs > 0 ? 1 : 0);
// Уменьшаем количество `крошек`.
crumbs--;
// Размножаем элемент массива и возвращаем.
return Array(repeater).fill(item);
});
// [[1, 1], [2, 2]] => [1, 1, 2, 2]
return [].concat(...newArr);
// Можно с помощью `flat`:
// return newArr.flat();
}
var numbersBlockBoom = [10, 11, 12, 13, 14, 15,
18, 19, 20, 21, 22, 23,
26, 27, 28, 29, 30, 31,
34, 35, 36, 37, 38, 39,
42, 43, 44, 45, 46, 47,
50, 51, 52, 53, 54, 55]
function startBoom(e) {
if(e.statusBoom == 0){
// WAIT
numbersBlockBoom.forEach(function(item, i, arr) {
if(e.blocksBoom[i] == 'wait'){
$('.boomcity__path div:eq('+(item - 1)+')').addClass('wait').html('')
}else{
$('.boomcity__path div:eq('+(item - 1)+')').addClass(e.blocksBoom[i])
}
});
}
}
const perFace = [
[-0.1, 0.3, -1],
[-0.1, 0.6, -0.4],
[-0.85, -0.42, 0.73],
[-0.8, 0.3, -0.75],
[0.3, 0.45, 0.9],
[-0.16, 0.6, 0.18]
];
function rollDice(first, second){
$('.diceBoom').removeClass('rolling throw')
$(".diceBlock:nth-child(1) .diceBoom").css("transform", `rotate3d(${perFace[first - 1]}, 180deg)`);
$(".diceBlock:nth-child(2) .diceBoom").css("transform", `rotate3d(${perFace[second - 1]}, 180deg)`);
setTimeout(() => {
$(".diceBoom").addClass("throw");
}, 50);
}
socket.on('BOOM_GET',e=>{
startBoom(e)
$('#boom_city__timer').html(e.timeBoom)
})
socket.on('BOOM_TIME',e=>{
$('#boom_city__timer').html(e.time)
})
var BetOffWheel = 'on';
socket.on('WHEEL_GET',e=>{
startWheel(e)
var arr = e.coefficients
$(".x30__bet-heading_x30").each(function() {
$(this).html('x'+arr[0]+'');
if(e.statusBonus == 2){
$(this).addClass('gold')
}
arr.shift();
});
if(e.statusBonus == 1){
startBonus(e)
}
})
socket.on('WHEEL_NEW_COEFF',e=>{
var arr = e.coefficients
console.log(arr)
$(".x30__bet-heading_x30").each(function() {
$(this).html('x'+arr[0]+'').removeClass('gold');
arr.shift();
});
})
socket.on('WHEEL_START',e=>{
startWheel(e)
})
socket.on('WHEEL_BONUS',e=>{
startBonus(e)
})
function startBonus(e){
$('.x30 .x30__bonus-scroll').css({'transition':'0s','transform':'translateX(0px)'})
$('.x30 .x30__bonus-scroll').html('')
$('.x30 .x30__bonus').show()
$('.x30 .x30__timer').hide()
x = 56 * 42 - rand(5, 40)
setTimeout(() => $('.x30 .x30__bonus-scroll').css({'transition':''+e.bonusWheelTime+'s','transform':'translateX(-'+x+'px)'}), 100);
e.bonusArr.forEach((e)=>{
$('.x30 .x30__bonus-scroll').append(''+e.multiplayer[0]+'
')
})
}
function startWheel(e){
if(e.wheelStatus == 1){
$('#x30__text').html('Прокрутка');
$('#x30__status').addClass('x30__rocket--started');
}
rotateW = e.wheelRotate + e.wheelPlus;
$('#x30__wheel').css('transition', 'all '+e.wheelTime+'s ease 0s').css('transform', 'rotate('+rotateW+'deg)')
console.log('startWheel')
}
socket.on('WHEEL_TIME',e=>{
window.BetOffWheel = e.bet
$('#x30__timer').html(e.time)
per = 100 * Number(e.time) / 30
$('.prog_wheel').css('width', per+'%')
$('.text_wheel').html(e.text)
})
socket.on('WHEEL_NOTIFY',e=>{
if(USER_ID == e.user_id){
notification('success', 'Вы выиграли '+e.win.toFixed(2)+' монет')
updateBalance()
}
})
socket.on('WHEEL_FINISH',e=>{
// $('.bets_block_col').addClass('opacity');
// $('.bets_block_col.x'+e.colorCoffResult).removeClass('opacity')
$('#x30__status').removeClass('x30__rocket--started');
// updateBalance()
updateHistory(e.history)
})
socket.on('WHEEL_CLEAR',e=>{
$('#x30__text').html('Начало через');
$('.bets_block_col').removeClass('opacity');
$('span[data-sumBets]').html(0)
$('span[data-players]').html(0)
$('.x30 .x30__bonus').hide()
$('.x30 .x30__timer').show()
$('.x30__bet-users').html('')
var arr = [2, 3, 5, 7, 14, 30]
$(".x30__bet-heading_x30").each(function() {
$(this).html('x'+arr[0]+'').removeClass('gold');
arr.shift();
});
})
socket.on('laravel_database_updateBalance',e => {
e = $.parseJSON(e)
if(USER_ID == e.user_id){
balanceUpdate(e.lastbalance, e.newbalance)
}
})
socket.on('laravel_database_wheelBet',e => {
e = $.parseJSON(e)
e = e.data
class_dop = ''
if(e.user_id == USER_ID){
class_dop = 'img_no_blur'
}
$('.x30__bet-users.x'+e.coff).prepend('\
\
\
'+(Number(e.bet).toFixed(2))+'\
\
\
')
$('span[data-sumBets='+e.coff+']').html((e.sumBets).toFixed(0))
$('span[data-players='+e.coff+']').html(e.players)
})
socket.on('laravel_database_updateWheelBet',e => {
e = $.parseJSON(e)
e = e.data
$('span[data-sumBets='+e.coff+']').html((e.sumBets).toFixed(0))
$('span[data-players='+e.coff+']').html(e.players)
$('.x30__bet-users.x'+e.coff+' .x30__bet-user[data-user-id='+e.user_id+'] .x30__bet-sum span').html((Number(e.bet).toFixed(2))+'')
})
function betWheel(coff){
if(window.BetOffWheel == 'off'){
notification('error','Ставки закрыты, ждите следующий раунд')
return undisable('.x30__bet-heading')
}
$.post('/wheel/bet',{_token: csrf_token, coff: coff, bet: $('#wheel_input').val()}).then(e=>{
undisable('.x30__bet-heading')
if(e.success){
balanceUpdate(e.lastbalance, e.newbalance)
notification('success',e.success)
}
if(e.error){
notification('error',e.error)
}
})
}
socket.on('X100_GET',e=>{
startX100(e)
})
socket.on('X100_START',e=>{
startX100(e)
})
socket.on('X100_START_BONUS',e=>{
$('.x100 .wheel__x100-bonus-scroll').css('transition', '0s').css('transform', 'translateX(0px)')
$('.x100 .bonusBlock').show();
$('.TimerBlock').hide();
$('.x100 .wheel__x100-bonus-scroll').html('')
e.x100BonusAvatars.forEach((e)=>{
$('.x100 .wheel__x100-bonus-scroll').append('')
})
pxScrollX100Bonus = (56*48) - (Number($('.wheel__x100-bonus-x').width())/2) + rand(10, 40)
setTimeout(() => $('.x100 .wheel__x100-bonus-scroll').css('transition', '10s').css('transform', 'translateX(-'+pxScrollX100Bonus+'px)'), 100);
})
socket.on('X100_CLEAR',e=>{
$('.wheel__x100-winner').hide();
$('#x100__text').html('Начало через');
$('span[data-sumBetsX100]').html(0)
$('span[data-playersX100]').html(0)
$('.x100__bet-users').html('')
})
socket.on('X100_FINISH',e=>{
// $('.bonusBlock').hide();
// $('.betBlock').show();
// $('.historyBlock').show();
// $('.wheel__x100-winner').show();
// $('.wheel__x100-winner b').html('x'+e.colorCoffResultX100)
$('.wheel__bet-item-users').html('')
$('.bonusBlock').hide();
$('.TimerBlock').show();
$('#x100__status').removeClass('x30__rocket--started');
// updateBalance()
updateHistoryX100(e.history)
$('.x100__bet-users').html('')
})
function startX100(e){
if(e.x100Status == 1){
$('#x100__text').html('Прокрутка');
$('#x100__status').addClass('x30__rocket--started');
}
rotateW = e.x100Rotate - e.x100Plus - 180;
$('#x100__wheel').css('transition', 'all '+e.x100Time+'s ease 0s').css('transform', 'rotate('+rotateW+'deg)')
if(e.statusBonusX100 > 0){
$('.x100 .wheel__x100-bonus-scroll').css('transition', '0s').css('transform', 'translateX(0px)')
$('.bonusBlock').show();
$('.bonusBlock').hide();
$('.x100 .wheel__x100-bonus-scroll').html('')
e.x100BonusAvatars.forEach((e)=>{
$('.x100 .wheel__x100-bonus-scroll').append('')
})
pxScrollX100Bonus = (56*48) - (Number($('.wheel__x100-bonus-x').width())/2) + rand(10, 40)
$('.x100 .wheel__x100-bonus-scroll').css('transition', ''+(e.x100Time - 20)+'s')
$('.x100 .wheel__x100-bonus-scroll').css('transform', 'translateX(-'+pxScrollX100Bonus+'px)');
}
}
socket.on('X100_TIME',e=>{
$('#x100__timer').html(e.time)
})
socket.on('laravel_database_updateX100Bet',e => {
e = $.parseJSON(e)
e = e.data
$('span[data-sumBetsX100='+e.coff+']').html((e.sumBets).toFixed(0))
$('span[data-playersX100='+e.coff+']').html(e.players)
$('.x100 .x100__bet-users.x'+e.coff+' .x30__bet-user[data-user-id='+e.user_id+'] .x30__bet-sum span').html((Number(e.bet).toFixed(2))+'')
})
function betX100(coff){
$.post('/x100/bet',{_token: csrf_token, coff: coff, bet: $('#sumBetX100').val()}).then(e=>{
undisable('.x30__bet-heading')
if(e.success){
balanceUpdate(e.lastbalance, e.newbalance)
notification('success',e.success)
}
if(e.error){
notification('error',e.error)
}
})
}
function getHistoryGames() {
$.post('/history/games',{_token: csrf_token}).then(e=>{
e.history.forEach((e)=>{
$(".gameHistory").prepend(' \
\
| \
\
\
'+e.name_game+'\
\
| \
\
\
| \
\
\
'+e.bet+'\
\
\
| \
\
\
'+((e.win / e.bet).toFixed(2))+'x \
'+((e.win / e.bet).toFixed(2))+'x\
\
| \
\
\
'+e.win+'\
\
\
| \
');
});
});
}
getHistoryGames()
var SHOW = 0;
function typeShow(that){
$("#all_systems").toggleClass('show')
if(SHOW == 0){
SHOW = 1;
$(that).html('Свернуть')
}else{
SHOW = 0;
$(that).html('Развернуть')
}
}
function getHistoryJackpot(){
$.post('/jackpot/all',{_token: csrf_token}).then(e=>{
$('#history_jackpot').html('')
e.jackpot.forEach((e)=>{
randomR = (e.random)
randomR = randomR.replace(/""/g,"''")
class_dop = ''
if(e.user_id == USER_ID){
class_dop = 'img_no_blur'
}
$('#history_jackpot').append("| "+e.id+" | \
 | \
"+e.bet+" | \
"+e.win+" | \
|
\
")
});
});
}
function updateHistory(e){
$('.x30__history-scroll').html('')
e.forEach((e)=>{
randomR = (e.random)
randomR = randomR.replace(/""/g,"''")
$('.x30__history-scroll').append("\
")
})
}
function updateHistoryX100(e){
$('.x100__history-scroll').html('')
e.forEach((e)=>{
randomR = (e.random)
randomR = randomR.replace(/""/g,"''")
$('.x100__history-scroll').append("\
")
})
}
function disable(that){
$(that).css('pointer-events', 'none')
$(that).attr('disabled', 'disabled')
}
function undisable(that){
$(that).removeAttr('disabled', 'disabled')
$(that).css('pointer-events', '')
}
function notification(type, mess){
toastr[type](mess)
}
function chatScroll(){
var div = $(".chat__messages .ss-wrapper .ss-content");
div.scrollTop(div.prop('scrollHeight'));
}
function rotateBonusWheel(select, deg, time){
$('.'+select).css('transition', time+'s').css('transform', 'rotate('+deg+'deg) ')
}
var options = {
useEasing : true,
useGrouping : true,
separator : ',',
decimal : 2,
prefix : '',
suffix : ''
};
function updateBalance(){
$.post('/balance/get',{_token: csrf_token}).then(e=>{
if(e.success){
balanceUpdate($('#balance').attr('balance'), e.balance)
}
});
}
function changeRepostBalance(){
$.post('/repost/change',{_token: csrf_token}).then(e=>{
if(e.success){
$('#bonusBalance').html(0)
notification('success', 'Вы успешно обменяли бонусный баланс на реальный')
balanceUpdate($('#balance').attr('balance'), e.balance)
}else{
notification('error', e.mess)
}
});
}
function changeRefBalance(){
$.post('/refs/change',{_token: csrf_token}).then(e=>{
if(e.success){
$('#refBalance').html(0)
notification('success', 'Вы успешно обменяли реферальный баланс на реальный')
balanceUpdate($('#balance').attr('balance'), e.balance)
}else{
notification('error', e.mess)
}
});
}
function animateNumber(first, second, time){
$({numberValue: first}).animate({numberValue: second}, {
duration: time,
easing: "linear",
step: function(val) {
$('#balance').text(parseFloat(val).toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, " "));
}
});
}
function balanceUpdate(lastbalance, balance, time = 250) {
$('#balance').attr('balance', balance);
animateNumber(lastbalance, balance, time)
}
function open_link(link){
window.open(link)
}
function getBonusVk(that){
$.post('/bonus/vk',{_token: csrf_token}).then(e=>{
undisable(that)
if(e.link){
setTimeout(() => open_link(e.link), 1000);
}
if(e.success){
notification('success', e.mess)
balanceUpdate(e.lastbalance, e.newbalance)
}else{
notification('error', e.mess)
}
});
}
function getBonusRef(that){
$.post('/bonus/ref',{_token: csrf_token}).then(e=>{
if(e.success){
$('#refs').html(e.refs)
rotateBonusWheel('bonus__rotate', 0, 0)
setTimeout(() => rotateBonusWheel('bonus__rotate', (e.rotate) - rand(10, 45), 10), 100);
setTimeout(() => notification('success', e.mess), 10000);
setTimeout(() => balanceUpdate(e.lastbalance, e.newbalance), 10000);
setTimeout(() => undisable(that), 10000);
}else{
undisable(that)
notification('error', e.mess)
}
});
}
// function copy(id) {
// var copyText = document.getElementById(id);
// copyText.select();
// document.execCommand("copy");
// }
function copyText(id) {
console.log('copyText called with id:', id);
var element = document.getElementById(id);
if (!element) {
console.error('Element with id "' + id + '" not found');
toastr['error']('Элемент не найден');
return false;
}
var textToCopy = element.textContent || element.innerText || '';
console.log('Text to copy:', textToCopy);
// Убираем лишние пробелы и переносы строк, но сохраняем структуру
textToCopy = textToCopy.trim().replace(/\s+/g, ' ');
if (!textToCopy) {
console.error('No text to copy from element with id "' + id + '"');
toastr['error']('Нет текста для копирования');
return false;
}
// Используем современный Clipboard API
if (navigator.clipboard && window.isSecureContext) {
navigator.clipboard.writeText(textToCopy).then(function() {
console.log('Successfully copied to clipboard');
if (typeof toastr !== 'undefined') {
toastr['success']('Скопировано!');
} else {
alert('Скопировано: ' + textToCopy);
}
}).catch(function(err) {
console.error('Failed to copy with Clipboard API: ', err);
// Fallback на старый метод
fallbackCopyText(textToCopy);
});
} else {
console.log('Using fallback copy method');
// Fallback для старых браузеров или небезопасного контекста
fallbackCopyText(textToCopy);
}
return false;
}
function fallbackCopyText(text) {
console.log('Using fallback copy for text:', text);
var $temp = $("");
$("body").append($temp);
$temp.val(text).select();
try {
var successful = document.execCommand("copy");
if (successful) {
console.log('Successfully copied with execCommand');
if (typeof toastr !== 'undefined') {
toastr['success']('Скопировано!');
} else {
alert('Скопировано: ' + text);
}
} else {
throw new Error('execCommand returned false');
}
} catch (err) {
console.error('Fallback copy failed: ', err);
// Последняя попытка - показать текст для ручного копирования
if (typeof toastr !== 'undefined') {
toastr['error']('Не удалось скопировать. Текст: ' + text.substring(0, 50) + '...');
} else {
alert('Не удалось скопировать. Пожалуйста, скопируйте вручную: ' + text);
}
}
$temp.remove();
}
function checkTgConnect(that) {
$.post('/bonus/checktg',{_token: csrf_token}).then(e=>{
undisable(that)
if(e.success){
notification('success', e.mess)
$('.close').click()
}else{
notification('error', e.mess)
}
});
}
function getBonusTg(that) {
$.post('/bonus/tg',{_token: csrf_token}).then(e=>{
undisable(that)
if(e.modal){
showPopup('popup--tg')
}
if(e.success){
notification('success', e.mess)
balanceUpdate(e.lastbalance, e.newbalance)
}else{
notification('error', e.mess)
}
});
}
function getBonus(that) {
$.post('/bonus/get',{_token: csrf_token}).then(e=>{
if(e.success){
rotateBonusWheel('bonus__rotate', 0, 0)
setTimeout(() => rotateBonusWheel('bonus__rotate', (e.rotate) - rand(10, 45), 10), 100);
setTimeout(() => notification('success', e.mess), 10000);
setTimeout(() => balanceUpdate(e.lastbalance, e.newbalance), 10000);
setTimeout(() => undisable(that), 10000);
}else{
undisable(that)
notification('error', e.mess)
}
});
}
function sendMess(that){
$.post('/chat/send',{_token: csrf_token, message: $('#messageChat').val()}).then(e=>{
undisable(that)
if(e.success){
$('#messageChat').val('')
notification('success', 'Сообщение отправлено')
}else{
notification('error', e.mess)
}
});
}
function sendSticker(sticker, that){
$.post('/chat/sendsticker',{_token: csrf_token, sticker}).then(e=>{
undisable(that)
if(e.success){
$('.panel_stickers').removeClass('open')
}else{
notification('error', e.mess)
}
});
}
function checkStatus(id, that){
$.post('/deposit/checkstatus',{_token: csrf_token, id}).then(e=>{
undisable(that)
if(e.success){
updateBalance()
notification('success', 'Вы успешно пополнили баланс')
$('.close').click()
}else{
notification('error', e.mess)
}
});
}
// Функция для восстановления окна пополнения из localStorage
function restoreDepositWindow(orderId) {
var depositDataStr = localStorage.getItem('last_deposit_' + orderId);
if(!depositDataStr) {
// Пробуем найти по другим ключам (для совместимости)
var keys = Object.keys(localStorage);
for(var i = 0; i < keys.length; i++) {
if(keys[i].startsWith('last_deposit_')) {
try {
var data = JSON.parse(localStorage.getItem(keys[i]));
if(data.order_id == orderId || keys[i] == 'last_deposit_' + orderId) {
depositDataStr = localStorage.getItem(keys[i]);
break;
}
} catch(e) {}
}
}
}
if(!depositDataStr) {
notification('error', 'Данные пополнения не найдены. Создайте новое пополнение.');
return;
}
try {
var depositData = JSON.parse(depositDataStr);
// Восстанавливаем данные
$('#wallet_pay').html(depositData.wallet_to);
$('#comment_pay').html(depositData.comment_to);
var sumText = depositData.amount_to.toString().replace(/\s+/g, ' ').trim();
$('#sum_pay').html(sumText);
// Проверка на криптоплатеж
if(depositData.qr_code) {
$('#crypto_qr_section').show();
$('#qr_code_img').attr('src', depositData.qr_code);
$('#comment_section').hide();
$('#payment_instruction').html('Отсканируйте QR-код или скопируйте адрес кошелька. После отправки средств нажмите "Проверить перевод".');
$('#check_pay').attr('onclick', 'disable(this);checkCryptoStatus("'+depositData.order_id+'", this)');
} else {
$('#crypto_qr_section').hide();
$('#comment_section').show();
$('#payment_instruction').html('При переводе вы должны в точности указать номер кошелька, сумму, комментарий. В случае ошибки деньги не возвращаем.');
$('#check_pay').attr('onclick', 'disable(this);checkStatus('+depositData.order_id+', this)');
}
// Открываем окно
showPopup('popup--refill');
notification('success', 'Окно пополнения восстановлено');
} catch(e) {
notification('error', 'Ошибка при восстановлении данных');
console.error(e);
}
}
function checkCryptoStatus(paymentId, that){
$.get('/crypto/deposit/status/' + paymentId, {_token: csrf_token}).then(e=>{
undisable(that)
if(e.status === 'confirmed' || e.status === 'success'){
updateBalance()
notification('success', 'Вы успешно пополнили баланс')
$('.close').click()
}else if(e.status === 'pending'){
notification('info', 'Платеж еще не подтвержден. Пожалуйста, подождите.')
// Автоматически проверяем статус каждые 5 секунд
if(!that.hasAttribute('data-checking')) {
that.setAttribute('data-checking', 'true');
var checkInterval = setInterval(function() {
$.get('/crypto/deposit/status/' + paymentId, {_token: csrf_token}).then(function(statusData) {
if(statusData.status === 'confirmed' || statusData.status === 'success'){
clearInterval(checkInterval);
that.removeAttribute('data-checking');
updateBalance()
notification('success', 'Платеж подтвержден! Баланс обновлен.')
$('.close').click()
} else if(statusData.status === 'failed' || statusData.status === 'error') {
clearInterval(checkInterval);
that.removeAttribute('data-checking');
notification('error', 'Платеж не подтвержден')
}
}).catch(function(err) {
console.error('Status check error:', err);
});
}, 5000); // Проверяем каждые 5 секунд
// Останавливаем проверку через 5 минут
setTimeout(function() {
clearInterval(checkInterval);
that.removeAttribute('data-checking');
}, 300000);
}
}else{
notification('error', e.error || 'Ошибка проверки статуса')
}
}).catch(function(err){
undisable(that)
notification('error', 'Ошибка проверки статуса')
});
}
function createPromoUser(that) {
$.post('/promo/create',{_token: csrf_token, name: $('#name_crpromo').val(), sum: $('#sum_crpromo').val(), act: $('#act_crpromo').val()}).then(e=>{
undisable(that)
if(e.success){
balanceUpdate(e.lastbalance, e.newbalance)
notification('success', 'Вы успешно создали промокод')
close_modal()
}else{
notification('error', e.mess)
}
});
}
function goTransfer(that) {
$.post('/transfer/go',{_token: csrf_token, id: $('#trans_id').val(), sum: $('#trans_sum').val()}).then(e=>{
undisable(that)
if(e.success){
balanceUpdate(e.lastbalance, e.newbalance)
notification('success', 'Вы успешно перевели средства')
close_modal()
}else{
notification('error', e.mess)
}
});
}
function getUserTransfer(that) {
$.post('/transfer/getuser',{_token: csrf_token, id: $('#id_transfer').val()}).then(e=>{
undisable(that)
if(e.success){
$('#avatar_transfer').attr('src', e.avatar)
$('#trans_id').val(e.id)
show_modal('transfer')
}else{
notification('error', e.mess)
}
});
}
function actPromo(that){
var cap = $('#captcha > iframe').attr('data-hcaptcha-response')
if (cap == ''){
notification('error','Пройдите капчу')
undisable(that)
return false;
}
$.post('/promo/act',{_token: csrf_token, name: $('#promo_name').val()}).then(e=>{
undisable(that)
if(e.success){
balanceUpdate(e.lastbalance, e.newbalance)
notification('success', 'Промокод успешно активирован')
$('#promo_name').val('')
captcha_r()
}else{
notification('error', e.mess)
captcha_r()
}
});
}
function canselWithdraw(id, that) {
$.post('/withdraw/cansel',{_token: csrf_token, id}).then(e=>{
undisable(that)
if(e.success){
balanceUpdate(e.lastbalance, e.newbalance)
notification('success', 'Вывод успешно отменен')
$('#statusW_'+id+' span').html('Отменен')
$('#statusW_'+id).removeClass('warning').addClass('error')
}else{
notification('error', e.mess)
}
});
}
function goWithdraw(that) {
$.post('/withdraw/go',{_token: csrf_token, sum: Number($('#sum_withdraw').val()), system: $('#systemW').val(), wallet: $('#wallet_withdraw').val()}).then(e=>{
undisable(that)
if(e.success){
balanceUpdate(e.lastbalance, e.newbalance)
notification('success', 'Средства успешно поставлены на вывод. Время ожидания от 5 минут до 24 часов')
$('.wallet__history--withdraw').prepend('\
\
\

\
'+e.withdraw.ps+'\
\
\
'+e.withdraw.sum+'\
\
\
\
\
Ожидание... (Отменить)\
\
')
}else{
notification('error', e.mess)
}
});
}
function goDeposit(that) {
$.post('/deposit/go',{_token: csrf_token, sum: Number($('#sumDep').val()), system: $('#systemDep').val(), promo: $('#promoDep').val()}).then(e=>{
undisable(that)
if(e.success){
if(e.modal == 0){
notification('success', 'Перенаправляем на оплату')
location.href = e.link
}else{
transfer = e.transfer
amount_to = transfer.amount_to
wallet_to = transfer.wallet_to
comment_to = transfer.comment_to
order_id = transfer.order_id
img = e.img
// Сохраняем данные пополнения в localStorage
var depositData = {
order_id: order_id,
amount_to: amount_to,
wallet_to: wallet_to,
comment_to: comment_to,
qr_code: transfer.qr_code || null,
img: img,
timestamp: new Date().getTime()
};
localStorage.setItem('last_deposit_' + order_id, JSON.stringify(depositData));
// Проверка на криптоплатеж
if(transfer.qr_code){
// Криптоплатеж - показываем QR-код
$('#crypto_qr_section').show()
$('#qr_code_img').attr('src', transfer.qr_code)
$('#comment_section').hide()
$('#payment_instruction').html('Отсканируйте QR-код или скопируйте адрес кошелька. После отправки средств нажмите "Проверить перевод".')
$('#check_pay').attr('onclick', 'disable(this);checkCryptoStatus("'+order_id+'", this)')
} else {
// Обычный платеж
$('#crypto_qr_section').hide()
$('#comment_section').show()
$('#payment_instruction').html('При переводе вы должны в точности указать номер кошелька, сумму, комментарий. В случае ошибки деньги не возвращаем.')
$('#check_pay').attr('onclick', 'disable(this);checkStatus('+order_id+', this)')
}
$('#wallet_pay').html(wallet_to)
$('#comment_pay').html(comment_to)
// Улучшенное отображение суммы - убираем переносы строк
var sumText = amount_to.toString().replace(/\s+/g, ' ').trim();
$('#sum_pay').html(sumText)
showPopup('popup--refill')
}
}else{
notification('error', e.mess)
}
});
}
function open_panel_smiles() {
$(".panel_smiles").toggleClass('open');
$(".panel_stickers").removeClass('open');
}
function open_panel_stickers(){
$(".panel_stickers").toggleClass('open');
$(".panel_smiles").removeClass('open');
}
function addSmileInChat(smile){
$("#messageChat").val($("#messageChat").val() +' '+smile)
}
$(document).ready(function(){
$('img').attr('draggable', "false")
$('.logo').css('pointer-events', "auto")
$(".click_pp").click(function(){ // задаем функцию при нажатиии на элемент