/* © Copyright RadioBS - Created by Lugsoft - lugsoft.com.br */
let ajaxify=new Ajaxify({elements:'#ajaxArea',scrolltop:!0,prefetchoff:!0,memoryoff:!0,inlineskip:''});(function($){'use strict';var playerAudio=document.querySelector('#player_audio');let playerYoutube;var timeMsg;var LoadApiTime;let autoPlayAttempt;document.addEventListener('pronto.beforeload',function(e){clearTimeout(LoadApiTime)});document.addEventListener('pronto.render',function(e){App();var bsOffcanvas=bootstrap.Offcanvas.getInstance($('#offcanvas'));if(bsOffcanvas){bsOffcanvas.hide()}});App();autoPlay();menuActive();function App(){$('.top-music-card .b-play, .top-music-card .b-stop').click(function(e){e.preventDefault();const videoId=$(this).data('video-id');if(videoId){playTopMusicYoutube(this)}else{audioPlay(this)}});$('.podcast .b-play, .podcast .b-stop').click(function(e){e.preventDefault();const videoId=$(this).data('video-id');if(videoId){playPodcastYoutube(this)}else{audioPodcast(this)}});ShareBS();lightboxCarousel();loadApi();cropImageModal();if($('#user_name_reg').length>0){document.getElementById('user_name_reg').onkeypress=function(e){var chr=String.fromCharCode(e.which);if('1234567890qwertyuioplkjhgfdsazxcvbnmQWERTYUIOPLKJHGFDSAZXCVBNM'.indexOf(chr)<0)
    return!1}}}
    $('#player .b-play, #player .b-stop').click(function(e){e.preventDefault();audioPlay(this)});function audioPodcast(data){const playing=data.classList.contains('b-play');stopAllPlayer();if(playing){const audioUrl=$(data).attr('data-audio');let collapseYT=document.createElement('div');collapseYT.className='collapse show card rounded-0 border-bottom';collapseYT.id='collapsePodcast';let playerContainer=document.createElement('div');playerContainer.className='audio-panel';let playerPodAudio=document.createElement('audio');playerPodAudio.controls='controls';let playerSource=document.createElement('source');playerSource.src=audioUrl;playerSource.type='audio/mp3';playerPodAudio.appendChild(playerSource);playerContainer.appendChild(playerPodAudio);collapseYT.appendChild(playerContainer);data.closest('li').insertAdjacentElement('afterend',collapseYT);new bootstrap.Collapse(collapseYT,{toggle:!1});playerPodAudio.load();$(data).removeClass('b-play').addClass('b-stop');$(data).closest('li').addClass('active');playerPodAudio.play().then(()=>{console.log('play success')}).catch((e)=>{console.log('play failed')})}}
    function playPodcastYoutube(data){const playing=data.classList.contains('b-play');stopAllPlayer();if(playing){const videoId=$(data).data('video-id');let playerYT=document.createElement('div');let collapseYT=document.createElement('div');collapseYT.className='collapse show border-bottom';collapseYT.id='collapsePodcast';let cardYT=document.createElement('div');cardYT.className='card rounded-0';let ratioYT=document.createElement('div');ratioYT.className='ratio ratio-16x9';ratioYT.appendChild(playerYT);cardYT.appendChild(ratioYT);collapseYT.appendChild(cardYT);data.closest('li').insertAdjacentElement('afterend',collapseYT);new bootstrap.Collapse(collapseYT,{toggle:!1});let playerOption={rel:0};createPIframeYoutube(playerYT,videoId,playerOption);$(data).removeClass('b-play').addClass('b-stop');$(data).closest('li').addClass('active')}}
    function playTopMusicYoutube(data){const playing=data.classList.contains('b-play');stopAllPlayer();if(playing){const videoId=$(data).data('video-id');$(data).parent().children('img').addClass('d-none');let playerYT=document.createElement('div');let containerYT=document.createElement('div');containerYT.className='yt-container';containerYT.appendChild(playerYT);data.parentNode.appendChild(containerYT);let playerOption={controls:0,fs:0,showinfo:0,modestbranding:1,rel:0};const callbackChangeYT=(e)=>{if(e.data==YT.PlayerState.ENDED)stopAllPlayer();};createPIframeYoutube(playerYT,videoId,playerOption,null,callbackChangeYT);$(data).removeClass('b-play').addClass('b-stop')}}
    function createPIframeYoutube(playerId,videoId,options={},readyCK,changeCk){if($('script[src="https://www.youtube.com/iframe_api"]').length===0){let scriptYTApi=$('<script></script>').attr('src','https://www.youtube.com/iframe_api');$('script').first().before(scriptYTApi)}
    const data={playerId:playerId,videoId:videoId,options:options,readyCK:readyCK,changeCk:changeCk};if(playerYoutube){return(playerYoutube=getYouTubeIframeAPI(data))}
    window.onYouTubeIframeAPIReady=function(){playerYoutube=getYouTubeIframeAPI(data)};return playerYoutube}
    function getYouTubeIframeAPI(data){return new YT.Player(data.playerId,{playerVars:data.options,videoId:data.videoId,events:{onReady:function(){playerYoutube.setVolume(100);playerYoutube.playVideo();if(data.readyCK)data.readyCK(e);},onStateChange:function(e){if(data.changeCk)data.changeCk(e);}}})}
    function stopAllPlayer(){const topMusicYT=document.querySelector('.yt-container');const podcastAudio=document.querySelector('.podcast audio');const podcastYT=document.querySelector('.podcast ul .collapse');if(topMusicYT){topMusicYT.remove();$('.top-music-card img').removeClass('d-none')}
    if(podcastYT){podcastYT.remove();$('.podcast ul li').removeClass('active')}
    if(podcastAudio){podcastAudio.pause();$('.podcast ul li').removeClass('active')}
    playerAudio.pause();$('.b-stop').removeClass('b-stop').addClass('b-play');if(autoPlayAttempt)clearInterval(autoPlayAttempt);}
    function audioPlay(data){const playing=data.classList.contains('b-play');stopAllPlayer();if(playing){const StreamUrl=$(data).attr('data-stream');$('#player_audio').html('<source id="radio_stream" src="'+StreamUrl+'" type="audio/mp3">');playerAudio.load();$(data).removeClass('b-play').addClass('b-stop');playerAudio.play().then(()=>{console.log('play success')}).catch((e)=>{console.log('play failed')})}}
    function autoPlay(){if(!$('.podcast audio').length){const StreamUrl=$('#player .b-play').attr('data-stream');$('#player_audio').html('<source id="radio_stream" src="'+StreamUrl+'" type="audio/mp3">');playerAudio.load();autoPlayAttempt=setInterval(()=>{if(playerAudio.paused){playerAudio.play().then(()=>{stopAllPlayer();playerAudio.play();$('#player .b-play').removeClass('b-play').addClass('b-stop');clearInterval(autoPlayAttempt);console.log('autoplay success')}).catch((e)=>{console.log('autoplay failed')})}else{$('#player .b-play').removeClass('b-play').addClass('b-stop');console.log('clean autoplay');clearInterval(autoPlayAttempt)}},3000)}}
    if($('.player-volume').length){const slider_volume=document.getElementById('slider-volume');playerAudio.volume=0.8;$('#volume-mute').click(function(){const muted=document.querySelector('#volume-mute').className;if(muted=='b-volume'){$('#volume-mute').removeClass('b-volume').addClass('b-mute');slider_volume.value='0';playerAudio.volume=0.0}else{$('#volume-mute').removeClass('b-mute').addClass('b-volume');slider_volume.value='80';playerAudio.volume=0.8}});slider_volume.oninput=()=>{playerAudio.volume=~~slider_volume.value*0.01;if(playerAudio.volume==0){$('#volume-mute').removeClass('b-volume').addClass('b-mute')}else{$('#volume-mute').removeClass('b-mute').addClass('b-volume')}}}
    function ShareBS(){if($('#shareBS').length){var share=$('#shareBS');var url=share.attr('data-url');var text=share.attr('data-title');var fb='<button class="btn-fb" id="fb" aria-label="Share Facebook"><span class="fab fa-facebook"></span></button>';var tw='<button class="btn-tw" id="tw" aria-label="Share Twitter"><span class="fab fa-x-twitter"></span></button>';var wa='<button class="btn-wa" id="wa" aria-label="Share WhatsApp"><span class="fab fa-whatsapp"></span></button>';var sr='<button class="btn-sr" id="sr" aria-label="More Share"><span class="fas fa-share"></span></button>';share.html('<div>'+fb+tw+wa+sr+'</div>');$('#shareBS button').click(function(e){var id=$(this).attr('id');if(id=='fb'){openurl('https://facebook.com/sharer/sharer.php?u='+encodeURIComponent(url))}
    if(id=='tw'){openurl('https://x.com/intent/tweet?url='+encodeURIComponent(url)+'&text='+encodeURIComponent(text))}
    if(id=='wa'){openurl('https://wa.me/?text='+encodeURIComponent(url))}
    if(id=='sr'){if(navigator.share){navigator.share({title:text,url:url})}else{alert('Seu navegador não suporta compartilhamento direto.')}}});function openurl(url){window.open(url)}}}
    const setThemeMode=function(theme){if(theme==='auto'&&window.matchMedia('(prefers-color-scheme: dark)').matches){document.documentElement.setAttribute('data-bs-theme','dark')}else{document.documentElement.setAttribute('data-bs-theme',theme)}};setThemeMode(CONFIG.themeMode);function lightboxCarousel(){if($('.image-grid').length){const imageGrid=document.querySelector('.image-grid');const links=imageGrid.querySelectorAll('a');const imgs=imageGrid.querySelectorAll('a');const lightboxModal=document.getElementById('lightbox-modal');const bsModal=new bootstrap.Modal(lightboxModal);const modalBody=document.querySelector('.modal-body .container-fluid');for(const link of links){link.addEventListener('click',function(e){e.preventDefault();const currentImg=link;const lightboxCarousel=document.getElementById('lightboxCarousel');if(lightboxCarousel){const parentCol=link.parentElement.parentElement;const index=[...parentCol.parentElement.children].indexOf(parentCol);const bsCarousel=new bootstrap.Carousel(lightboxCarousel);bsCarousel.to(index)}else{createCarousel(currentImg)}
    bsModal.show()})}
    function createCarousel(img){const markup=`
                    <div id="lightboxCarousel" class="carousel slide ">
                    <div class="carousel-inner">
                        ${createSlides(img)}
                    </div>
                    <button class="carousel-control-prev" type="button" data-bs-target="#lightboxCarousel" data-bs-slide="prev">
                    <span class="prev" aria-hidden="true"><i class="fas fa-angle-left"></i></span>
                    <span class="visually-hidden">Previous</span>
                    </button>
                    <button class="carousel-control-next" type="button" data-bs-target="#lightboxCarousel" data-bs-slide="next">
                        <span class="next" aria-hidden="true"><i class="fas fa-angle-right"></i></span>
                        <span class="visually-hidden">Next</span>
                    </button>
                    </div>`;modalBody.innerHTML=markup}
    function createSlides(img){let markup='';const currentImgSrc=img.getAttribute('href');for(const img of imgs){const imgSrc=img.getAttribute('href');const imgAlt=img.getAttribute('alt');const imgCaption=img.getAttribute('data-caption');markup+=`
                        <div class="carousel-item${currentImgSrc === imgSrc ? ' active' : ''}">
                        <img loading="lazy" src=${imgSrc} alt=${imgAlt}>
                        ${imgCaption ? createCaption(imgCaption) : ''}
                        </div>`}
    return markup}
    function createCaption(caption){return `<div class="carousel-caption">
                    <p class="m-0">${caption}</p>
                    </div>`}}}
    function menuActive(){var href=CONFIG.pathSystem+CONFIG.page1;if(href==CONFIG.pathSystem+'home'){$('#home-active').addClass('active');$('#home-active').attr('aria-current','page')}else{$('header ul li a[href="'+href+'"]').addClass('active');$('header ul li a[href="'+href+'"]').attr('aria-current','page');$('header ul li a[href="'+href+'"]').closest('.dropdown').children().addClass('active')}
    $('header ul li a').click(function(e){e.preventDefault();if($(this).attr('id')!='dropdown-toggle'){$('.dropdown-toggle').dropdown('hide');$('header ul li a').removeAttr('aria-current','page');$('header ul li a').removeClass('active')}else{$('header ul li a.nav-link').removeAttr('aria-current','page');$('header ul li a.nav-link').removeClass('active')}
    $(this).addClass('active');$(this).attr('aria-current','page');$(this).closest('.dropdown').children().addClass('active')})}
    function cropImageModal(){let instance='';let openNewModal='true';let imgw='';let imgh='';let imgCrop='';let imgPrev='';let modalView=$('#viewModal');let modalCrop=$('#modal-crop');$(document).on('change','.crop-image-modal',function(e){$('.btn-crop-submit').removeClass('d-none');$('#btn-crop-cancel').removeClass('d-none');$('#crop-load').removeClass('d-block');imgPrev=document.querySelector('#modal-crop #image');imgw=Number($(this).attr('data-imgw'));imgh=Number($(this).attr('data-imgh'));instance=$(this).attr('data-instance');openNewModal=$(this).attr('data-newmodal');imgCrop=document.getElementById('crop-instance-'+instance);let cropper=[];let input=this;if(input.files&&input.files[0]){let reader=new FileReader();reader.onload=function(e){imgPrev.src=e.target.result;if(openNewModal=='true'){modalView.modal('hide')}
    modalCrop.modal('show')};reader.readAsDataURL(input.files[0])}
    $('#crop').click(function(){$('.btn-crop-submit').addClass('d-none');$('#btn-crop-cancel').addClass('d-none');$('#crop-load').addClass('d-block');$('#cropclick').attr('value',1);if(cropper[instance]){let canvas=cropper[instance].getCroppedCanvas({width:imgw,height:imgh});imgCrop.src=canvas.toDataURL()}
    modalCrop.modal('hide')});modalCrop.on('shown.bs.modal',function(){cropper[instance]=new Cropper(imgPrev,{aspectRatio:imgw/imgh,viewMode:2,movable:!0,zoomable:!0,rotate:0,rotatable:!1,scalable:!1,autoCropArea:1,crop:function(e){$('#x').val(e.detail.x);$('#y').val(e.detail.y);$('#w').val(e.detail.width);$('#h').val(e.detail.height)},ready:function(){$('body').addClass('modal-open')}})}).on('hidden.bs.modal',function(){let cropclick=$('#cropclick').attr('value');cropclick==0?(input.value=''):'';cropper[instance].destroy();cropper[instance]=null;if(openNewModal=='true'){modalView.modal('show')}})})}
    var cookieAlert=document.querySelector('.cookiealert');if(!cookieAlert){return}
    cookieAlert.offsetHeight;if(!getCookie('acceptCookies')){cookieAlert.classList.add('show');$('.cookiealert').html(`
                <b>${CONFIG.lang.this_uses_cookies}</b> ${CONFIG.lang.using_agree_to_our} <a href="${CONFIG.pathSystem}privacy-policy">${CONFIG.lang.privacy_policy}</a>
                <button type="button" class="btn btn-primary btn-sm acceptcookies">${CONFIG.lang.to_accept}</button>
            `);var acceptCookies=document.querySelector('.acceptcookies');acceptCookies.addEventListener('click',function(){setCookie('acceptCookies',!0,365);cookieAlert.classList.remove('show');window.dispatchEvent(new Event('cookieAlertAccept'))})}
    function setCookie(cname,cvalue,exdays){var d=new Date();d.setTime(d.getTime()+exdays*24*60*60*1000);var expires='expires='+d.toUTCString();document.cookie=cname+'='+cvalue+';'+expires+';path=/'}
    function getCookie(cname){var name=cname+'=';var decodedCookie=decodeURIComponent(document.cookie);var ca=decodedCookie.split(';');for(var i=0;i<ca.length;i++){var c=ca[i];while(c.charAt(0)===' '){c=c.substring(1)}
    if(c.indexOf(name)===0){return c.substring(name.length,c.length)}}
    return''}
    function requestApi(ref,data,service,method,processData=!1,contentType=!1){return $.ajax({method:method,url:CONFIG.pathSystem+'api/'+service,data:data,dataType:'json',processData:processData,contentType:contentType==!0?'application/x-www-form-urlencoded; charset=UTF-8':!1,cache:!1,beforeSend:function(){$(ref+' .loading').removeClass('d-none');$(ref+' .submit').addClass('d-none')},success:function(res){$(ref+' .loading').addClass('d-none');$(ref+' .submit').removeClass('d-none');if(method=='POST'){if(res.status){$(ref+' #res-message').html('<span class="text-success">'+res.message+'</span>')}else{$(ref+' #res-message').html('<span class="text-danger">'+res.message+'</span>')}}
    clearTimeout(timeMsg);timeMsg=setTimeout(()=>{$(ref+' #res-message').html('')},7000)}})}
    function zeroLeftDate(num){return num>=10?num:`0${num}`}
    function getDatetime(datetime){const newDate=new Date(datetime);return{year:newDate.getFullYear(),month:zeroLeftDate(newDate.getMonth()+1),day:zeroLeftDate(newDate.getDate()),hours:zeroLeftDate(newDate.getHours()),min:zeroLeftDate(newDate.getMinutes()),sec:zeroLeftDate(newDate.getSeconds()),date:newDate}}
    async function loadApi(){await Promise.allSettled([chatBS(),loadAds(),announcerOnAir(),loadPolls(),generateCaptcha(),lastSeen()]);contactForm();commentForm();userLogout();userEditProfile();userEditPass();userEditPassReset()}
    userPassReset();userLogin();codeVerify();userRegister();requestMusic();setTimeout(()=>{playingNow();clickAds()},800);setInterval(()=>{lastSeen()},150000);setInterval(()=>{announcerOnAir()},120000);setInterval(()=>{playingNow()},90000);setInterval(()=>{loadAds()},300000);async function contactForm(){var ref='#contact-form';if($(ref).length){$(ref).submit(async function(e){e.preventDefault();var data=new FormData(this);await requestApi(ref,data,'contactForm','POST').done(function(res){if($('.captcha-input')){$('.captcha-input').val('');generateCaptcha()}
    if(res.status){$(ref+' #message_contact').val('')}})})}}
    async function requestMusic(){var ref='#musicRequest';if($(ref).length){$(ref).submit(async function(e){e.preventDefault();var data=new FormData(this);await requestApi(ref,data,'musicRequest','POST').done(function(res){if($('.captcha-input')){$('.captcha-input').val('');generateCaptcha()}
    if(res.status){$(ref+' #request_music').val('')}})})}}
    async function commentForm(){var ref='#comment-form';if($(ref).length){$(ref).submit(async function(e){e.preventDefault();var data=new FormData(this);await requestApi(ref,data,'commentForm','POST').done(function(res){if(res.status){$(ref+' #comment').val('');$('#append-comment').prepend(`
                                <div class="comment mb-3">
                                    <div class="me-3">
                                        <img class="avatar rounded-circle" loading="lazy" src="${CONFIG.pathSystem}public/avatar/${res.data.avatar}" alt="${res.data.full_name}">
                                    </div>
                                    <div class="card w-100">
                                        <div class="p-3">
                                            <span class="author">${res.data.full_name}</span>
                                            <p class="mb-1">${res.data.comment}</p>
                                            <small class="text-muted float-end">${res.data.elapsedTime}</small>
                                        </div>
                                    </div>
                                </div>
                            `)}})})}}
    async function userEditProfile(){var ref='#userEditProfile';if($(ref).length){$(ref).submit(async function(e){e.preventDefault();var data=new FormData(this);await requestApi(ref,data,'user','POST').done(function(res){if(res.status){$('.name-user').text(res.data.full_name);if(res.data.avatar){$('.avatar-user').attr('src',CONFIG.pathSystem+'public/avatar/'+res.data.avatar)}}})})}}
    async function userEditPass(){var ref='#userEditPass';if($(ref).length){$(ref).submit(async function(e){e.preventDefault();var data=new FormData(this);await requestApi(ref,data,'user','POST').done(function(res){if(res.status){$('#new_password').val('');$('#confirm_password').val('')}})})}}
    async function userEditPassReset(){var ref='#userEditPassReset';if($(ref).length){$(ref).submit(async function(e){e.preventDefault();var data=new FormData(this);await requestApi(ref,data,'user','POST').done(function(res){if(res.status){$('#new_password').val('');$('#confirm_password').val('');$(ref+' #changesuccess').html('');setTimeout(()=>{location.reload()},2000)}})})}}
    async function userRegister(){var ref='#userRegister';if($(ref).length){$(ref).submit(async function(e){e.preventDefault();var data=new FormData(this);await requestApi(ref,data,'register','POST').done(function(res){if($('.captcha-input')){$('.captcha-input').val('');generateCaptcha()}
    if(res.status){$('#action_verify').val('codeRegisterVerify');$('#modalRegister').modal('hide');if(res.data.code_verify){$('#modalVerify').modal('show')}else{location.reload()}}})})}}
    async function userLogin(){var ref='#userLogin';if($(ref).length){$(ref).submit(async function(e){e.preventDefault();var data=new FormData(this);await requestApi(ref,data,'login','POST').done(function(res){if(res.status){if(res.data.code_verify){$('#modalLogin').modal('hide');$('#modalVerify').modal('show');$('#action_verify').val('codeRegisterVerify')}else{$('#modalLogin').modal('hide');location.reload()}}})})}}
    function userLogout(){$('#logout, #logout-md').click(function(e){e.preventDefault();location.reload()})}
    async function codeVerify(){var ref='#codeVerify';if($(ref).length){$(ref).submit(async function(e){e.preventDefault();var data=new FormData(this);await requestApi(ref,data,'codeVerify','POST').done(function(res){if(res.status){$('#modalVerify').modal('hide');if(res.data.passReset){window.location.href=CONFIG.pathSystem+'passreset'}else{location.reload()}}else{if(res.data.codeAttempts){$('#modalVerify').modal('hide');$('#modalMsg').modal('show');$('#modalMsg #title').html(res.title);$('#modalMsg #content').html('<span class="text-danger">'+res.message+'</span>')}}
    $('#code_verify').val('')})})}}
    async function userPassReset(){const ref='#userPassReset';if($(ref).length){$(ref).submit(async function(e){e.preventDefault();let data=new FormData(this);await requestApi(ref,data,'passReset','POST').done(function(res){if(res.status){$('#action_verify').val('codePassReset');$('#modalPassReset').modal('hide');$('#modalVerify').modal('show')}})})}}
    async function announcerOnAir(){const ref='.announcer-air-card';if($(ref).length){await requestApi(ref,'','onAir','GET').done(function(res){if(res.status){$(ref+' .info').removeClass('d-none');$(ref+' .message').addClass('d-none');$(ref+' .info button').removeClass('disabled');$(ref+' .avatar img').attr('src',CONFIG.pathSystem+'public/avatar/'+res.data.avatar).attr('alt',res.data.announcer);$(ref+' .announcer').text(res.data.announcer);$(ref+' .program').text(res.data.program);$(ref+' .date').text(res.data.time);$(ref+' .message').text('')}else{$(ref+' .info').addClass('d-none');$(ref+' .message').removeClass('d-none');$(ref+' .message').html('<p class="mb-0">'+res.message+'</p>');$(ref+' .info button').addClass('disabled')}})}
    return Promise.resolve()}
    async function lastSeen(){if(CONFIG.clientId){let data=new FormData();if($('#rank_value').length||$('#points_value').length){data.append('rank',!0)}
    await requestApi('#notref',data,'lastSeen','POST').done(function(res){if(res.status){if($('#rank_value').length||$('#points_value').length){$('#rank_value').text(res.data.rank);$('#points_value').text(res.data.points)}}})}
    return Promise.resolve()}
    async function loadAds(){const ref='.adsPub';if($(ref).length){await requestApi(ref,'','loadAds','GET').done(function(res){if(res.data){res.data.map((item)=>{if(item.ads&&item.ref){let adsShow='';if(item.type=='slide'){adsShow=adsRotation(item);$(item.ref+' .carousel-inner').html(adsShow);window.addEventListener('resize',function(e){adsShow=adsRotation(item);$(item.ref+' .carousel-inner').html(adsShow)})}else{item.ads.map((item)=>{if(item.link){adsShow=`<a class="click-ads" href="${
                                                item.link
                                            }" target="${item.link_target}" id="${item.id}">
                                            <img class="img-fluid" src="${CONFIG.pathSystem + 'public/banner/' + item.image}" alt="${
                                                item.title
                                            }"></a>`}else{adsShow=`<img class="img-fluid" src="${
                                                CONFIG.pathSystem + 'public/banner/' + item.image
                                            }" alt="${item.title}">`}});$(item.ref).html(adsShow)}}})}});function adsRotation(item){let adsShow='';let adsContainer=document.querySelector(item.ref+'.ads-rotation').clientWidth;let adsItem;let adsCol;let adsCount=0;if(item.size=='400x400'){if(adsContainer>1000){adsItem=4;adsCol=3}else if(adsContainer>768){adsItem=3;adsCol=4}else if(adsContainer<768&&adsContainer>420){adsItem=2;adsCol=6}else{adsItem=1;adsCol=12}}else{if(adsContainer>1000){adsItem=2;adsCol=6}else if(adsContainer>768){adsItem=1;adsCol=12}}
    item.ads.map((v,k)=>{adsCount++;if(adsCount==1){adsShow+=`<div class="carousel-item ${
                                k == 0 ? 'active' : ''
                            }"><div class="row justify-content-center">`}
    if(adsCount<adsItem){adsShow+=`
                                <div class="col-${adsCol}" >
                                    <a class="click-ads" href="${v.link ? v.link : '#'}" target="${v.link_target}" id="${v.id}">
                                        <img class="img-fluid" src="${CONFIG.pathSystem + 'public/banner/' + v.image}" alt="${v.title}" />
                                        <div class="overlay"><div class="text"><i class="fas fa-link"></i></div></div>
                                    </a>
                                </div>
                            `;if(item.ads.length==k+1){adsShow+='</div></div>'}}else{adsShow+=`
                                    <div class="col-${adsCol}" >
                                        <a class="click-ads" href="${v.link ? v.link : '#'}" target="${v.link_target}" id="${v.id}">
                                            <img class="img-fluid" src="${CONFIG.pathSystem + 'public/banner/' + v.image}" alt="${v.title}" />
                                            <div class="overlay"><div class="text"><i class="fas fa-link"></i></div></div>
                                        </a>
                                    </div>
                                </div>
                            </div>
                            `;adsCount=0}});return adsShow}}
    return Promise.resolve()}
    async function clickAds(){const ref='.adsPub';if($(ref).length){$(document).on('click','.click-ads',async function(e){let data=new FormData();const id=$(this).attr('id');data.append('id',id);await requestApi('#notref',data,'clickAds','POST')})}}
    async function chatBS(){var ref='#chatBS';if($(ref).length){var refMsgs=$(ref+' #messages');var scrollstatus=!0;refMsgs.scroll(function(e){scrollstatus=!1});refMsgs.scrollTop(refMsgs.prop('scrollHeight'));await loadChat();var loadChatInterval=setInterval(async()=>{await loadChat()},5000);document.addEventListener('pronto.render',function(e){clearInterval(loadChatInterval)});$(ref+' #message-input button').click(async function(e){e.preventDefault();await sendMsg()});$(ref+' #message-input textarea').keypress(async function(e){if(e.which===13&&!e.shiftKey){e.preventDefault();await sendMsg()}});$(ref+' #usertoggle').click(function(e){e.preventDefault();var userToggle=$(ref+' #users').attr('class');if(!userToggle){$(ref+' #users').addClass('d-block');$(ref+' .btn-user-close').removeClass('d-none');$(ref+' .btn-user-open').addClass('d-none')}else{$(ref+' #users').removeClass('d-block');$(ref+' .btn-user-close').addClass('d-none');$(ref+' .btn-user-open').removeClass('d-none')}});async function sendMsg(){var message=$(ref+' #message-input textarea');var data=new FormData();data.append('message',message.val());await requestApi(ref,data,'chat','POST').done(async function(res){if(res.status){message.val('');await loadChat();refMsgs.scrollTop(refMsgs.prop('scrollHeight'))}})}
    function loadMessages(dataMsg){if(dataMsg){$(ref+' #messages ul').html('');let groupDate;let level;$.each(dataMsg,function(key,value){const datePost=getDatetime(value.date_post);const msgDate=`${datePost.year}-${datePost.month}-${datePost.day}`;const msgTime=`${datePost.hours}:${datePost.min}`;const localDate=datePost.date.toLocaleString(navigator.language,{dateStyle:'medium'});if(value.level==0){level='color_5'}else if(value.level==1){level='color_3'}else{level='color_4'}
    if(groupDate!==msgDate){$(ref+' #messages ul').append('<li class="date-group">'+localDate+'</li>')}
    groupDate=msgDate;$(ref+' #messages ul').append(`
                                <li class="d-flex ${
                                    CONFIG.clientId == value.client_id ? 'sent-msg' : ''
                                }">
                                    <img src="${
                                        CONFIG.pathSystem + 'public/avatar/' + value.avatar
                                    }" alt="${value.full_name}">
                                    <div class="message-body">
                                        <span class="message ${level}">${value.message} </span>
                                        <span class="time">${msgTime}</span>
                                        <span class="name">${value.full_name}</span>
                                    </div>
                                </li>
                            `)})}}
    async function loadChat(){if(CONFIG.clientId){await requestApi(ref,'','chat','GET').done(function(res){if(res.status){$(ref+' #login-view').addClass('d-none');$(ref+' .btn-user-open span').text(res.countOn);loadMessages(res.dataMsg);if(res.dataUser){$(ref+' #users ul').html('');$.each(res.dataUser,function(key,value){if(value.level==0){var level=''}else if(value.level==1){var level='color_1'}else{var level='color_2'}
    $(ref+' #users ul').append(`<li class="color ${level}">${value.full_name}</li>`)})}
    if(scrollstatus){refMsgs.scrollTop(refMsgs.prop('scrollHeight'))}}else{$(ref+' #messages ul').html('');$(ref+' #users ul').html('');$(ref+' #login-view').removeClass('d-none')}})}else{$('#chatBS .btn-user-open').css('display','none')}}
    if(!CONFIG.clientId){await requestApi(ref,'','chat','GET').done(function(res){if(res.status){$(ref+' .btn-user-open span').text(res.countOn);loadMessages(res.dataMsg);if(scrollstatus){refMsgs.scrollTop(refMsgs.prop('scrollHeight'))}}})}}
    return Promise.resolve()}
    async function loadPolls(){const ref='.polls';if($(ref).length){await requestApi(ref,'','loadPolls','GET').done(function(res){if(res.data){res.data.map((data)=>{if(data.poll.isEmpty){$(data.ref).html(`<span class="text-danger text-center d-block">${data.poll.isEmpty}</span>`);return}
    const question=data.poll.question;const pollId=data.poll.pollId;const alreadyVoted=data.poll.alreadyVoted;const optionIdVoted=data.poll.optionIdVoted;const pollMessage=data.poll.pollMessage;const pollStatus=data.poll.pollStatus;const pollFooter=data.poll.pollFooter;const totalVotes=data.poll.options.reduce((total,option)=>total+option.votes,0);let messageType='info';if(pollStatus==='schedule'){messageType='warning'}else if(pollStatus==='expired'){messageType='danger'}
    if(data.poll.options){let pollHtml=`
                                    <h4 class="question">${question}</h4>
                                    <form>
                                `;data.poll.options.map((option)=>{const percentage=totalVotes>0?(option.votes/totalVotes)*100:0;let inputVoted=optionIdVoted===option.id?'checked':'';let inputDisabled='';if(alreadyVoted&&optionIdVoted!==option.id){inputDisabled='disabled'}
    if(pollStatus!=='active'){inputVoted='';inputDisabled='disabled'}
    pollHtml+=`
                                        <div class="form-check">
                                            <input class="form-check-input" type="radio" name="poll-option"
                                                value="${option.id}" id="poll-option-${option.id}"
                                                data-pollid="${pollId}" ${inputVoted} ${inputDisabled}>
                                            <label class="form-check-label"
                                                for="poll-option-${option.id}">

                                                <div class="d-flex justify-content-between">
                                                    <span class="option">${option.label}</span>
                                                    <span class="votes">${option.votes}</span>
                                                </div>

                                                <div class="progress" role="progressbar"
                                                    aria-valuenow="${percentage.toFixed(2)}"
                                                    aria-valuemin="0"
                                                    aria-valuemax="100">
                                                    <div class="progress-bar bg-success"
                                                        style="width: ${percentage.toFixed(2)}%">
                                                    </div>
                                                </div>
                                            </label>
                                        </div>
                                    `});pollHtml+=`
                                    </form>
                                    <span class="text-${messageType} text-center d-block">${pollMessage}</span>
                                `;$(data.ref).html(pollHtml);if(pollStatus==='active'){$(data.ref).parent().find('.poll-footer').html(`
                                        <div class="card-footer">
                                            <small class="text-muted d-block text-center">${pollFooter}</small>
                                        </div>
                                    `)}}})}})}
    return Promise.resolve()}
    $(document).on('input','.polls input',async(e)=>{const pollId=e.target.dataset.pollid;const optionId=e.target.value;await requestApi('.polls',{pollId,optionId},'pollVote','POST',!0,!0).done(async(res)=>{if(res.status){await loadPolls()}
    toast({message:res.message,type:res.type})})});async function playingNow(){const ref='#player .player-radio';await requestApi(ref,'','playingNow','GET').done(function(res){if(res.status){if(res.data.playingNow){$(ref+' #playingNow').text(res.data.playingNow)}else{$(ref+' #playingNow').text('...')}
    if(res.data.albumCover){var albumCover=res.data.albumCover.replace('100x100','300x300');$(ref+' .player-info img').attr('src',albumCover)}
    if('mediaSession' in navigator){navigator.mediaSession.metadata=new MediaMetadata({title:res.data.trackName,artist:res.data.siteTitle,artwork:[{src:albumCover,sizes:'384x384',type:'image/png'}]});console.log('init mediaSession metadata')}else{console.log('mediaSession not available')}}})}
    async function generateCaptcha(){if(!CONFIG.clientId){const $ref=$('.captcha-code-modal, .captcha-code');if($ref){await requestApi('#noref','','captchaCode','GET').done(function(res){if(res.status){let data=res.data;$ref.html(`
                                <div class="text-center mb-3">
                                    <img style="margin-bottom:6px;width:120px" src="${
                                        CONFIG.pathSystem
                                    }api/captchaImage?v=${new Date().valueOf()}" alt="${data.alt}">
                                    <div class="form-floating">
                                        <input type="text" class="form-control captcha-input" placeholder="${
                                            data.label
                                        }" name="captcha-input" required="" maxlength="6">
                                        <label>${data.label}</label>
                                    </div>
                                </div>
                            `)}})}}
    return Promise.resolve()}
    function toast({message='',type='primary',delay=6000}){let toastContainer=document.getElementById('toastContainer');if(!toastContainer){toastContainer=document.createElement('div');toastContainer.id='toastContainer';toastContainer.className='toast-container position-fixed top-0 end-0 p-3';document.body.appendChild(toastContainer)}
    const toast=document.createElement('div');toast.setAttribute('data-bs-delay',delay);toast.innerHTML=`
                <div class="d-flex toast text-bg-${type} border-0" role="alert" aria-live="assertive" aria-atomic="true">
                    <div class="toast-body">${message}</div>
                    <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast" aria-label="Close"></button>
                </div>
            `;toastContainer.appendChild(toast);const innerToast=toast.querySelector('.toast');const bsToast=new bootstrap.Toast(innerToast);bsToast.show();innerToast.addEventListener('hidden.bs.toast',()=>{toast.remove()})}
    if($('.sticky-bottom#player').length){document.addEventListener('DOMContentLoaded',function(){const container=document.querySelector('.sticky-bottom#player');const footer=document.querySelector('footer');function updateFooterPadding(){const containerHeight=container.clientHeight;footer.style.paddingBottom=`${containerHeight}px`}
    window.addEventListener('resize',updateFooterPadding);updateFooterPadding()})}})(jQuery)
