var SEARCH_ENCODING = 'utf8';
var HOT_WORDS = ['八十八佛','地藏經','阿彌陀經','大悲咒','心經','金剛經','普門品','阿彌陀佛','觀音菩薩','慧律法師','淨界法師','大安法師'];
var CUSTOM_LINKS = [
  
];
var SUGGEST_DATA = [
  
{word:'阿彌陀佛',abbr:'amtf',full:'amituofo'},{word:'阿彌陀經',abbr:'amtj',full:'amituojing'},
  {word:'大悲咒',abbr:'dbz',full:'dabeizhou'},
  {word:'大安法師',abbr:'dafs',full:'daanfashi'},
  {word:'華嚴經',abbr:'hyj',full:'huayanjing'},
  {word:'心經',abbr:'xj',full:'xinjing'},
  {word:'金剛經',abbr:'jgj',full:'jinggangjing'},{word:'楞嚴經',abbr:'lyj',full:'lengyanjing'},
  {word:'普賢行願品',abbr:'phxyp',full:'puxianxingyuanpin'},
  {word:'普門品',abbr:'pmp',full:'pumenpin'},
  {word:'淨土五經',abbr:'jtwj',full:'jingtuwujing'},{word:'念佛',abbr:'nf',full:'nianfo'},
  
  {word:'地藏經',abbr:'dzj',full:'dizangjing'},
  {word:'觀音菩薩',abbr:'gyps',full:'guanyinpusa'},
  {word:'藥師經',abbr:'ysj',full:'yaoshijing'},{word:'藥師佛',abbr:'ysf',full:'yaoshifo'},
  {word:'佛號',abbr:'fh',full:'fohao'},
  {word:'禪宗',abbr:'cz',full:'chanzong'},
  {word:'慧律法師',abbr:'hlfs',full:'huilüfashi'},
  
 {word:'印光大師',abbr:'ygds',full:'yinguangdashi'},
  {word:'虛雲老和尚',abbr:'xylhs',full:'xuyunlaoheshang'},
  
  {word:'文殊菩薩',abbr:'wsps',full:'wenshupusa'},
  {word:'普賢菩薩',abbr:'pxps',full:'puxianpusa'},
  {word:'大勢至菩薩',abbr:'dszps',full:'dashizhipusa'},
  {word:'彌勒菩薩',abbr:'mlps',full:'mileFopusa'},
  {word:'觀無量壽佛經',abbr:'gwlsfj',full:'guanwuliangShouFojing'},
  {word:'念佛圓通章',abbr:'nfytz',full:'nianFoYuantongzhang'},
  {word:'妙法蓮華經',abbr:'mflhj',full:'miaoFaLianhuajing'},
  {word:'八大人覺經',abbr:'bdrjj',full:'badaRenjuejing'},
  {word:'六祖壇經',abbr:'lztj',full:'liuzutanjing'},
  {word:'印光大師文鈔',abbr:'ygdswc',full:'yinguangDashiwenchao'},
  {word:'八十八佛',abbr:'bsbf',full:'八十八佛'},
  {word:'禮佛大懺悔文',abbr:'lfdchw',full:'lifodachanhuiwen'},
  
  
  {word:'會性法師',abbr:'hxfs',full:'huixingfashi'},{word:'因果',abbr:'yg',full:'yinguo'},
  {word:'佛教故事',abbr:'fjgs',full:'fojiaogushi'},
  {word:'往生',abbr:'ws',full:'wangsheng'},{word:'往生咒',abbr:'wsz',full:'wangshengzhou'},
  {word:'極樂世界',abbr:'jlsj',full:'jilesijie'},{word:'菩提心',abbr:'ptx',full:'putixin'},
  {word:'菩薩',abbr:'ps',full:'pusa'},{word:'菩薩戒',abbr:'psj',full:'pusajie'},
  {word:'戒律',abbr:'jl',full:'jielü'},{word:'五戒',abbr:'wj',full:'wujie'},
  {word:'八關齋戒',abbr:'bgzj',full:'baguanzhaijie'},{word:'佈施',abbr:'bs',full:'bushi'},
  {word:'功德',abbr:'gd',full:'gongde'},{word:'迴向',abbr:'hx',full:'huixiang'},
  {word:'輪迴',abbr:'lh',full:'lunhui'},{word:'六道',abbr:'ld',full:'liudao'},
  {word:'三皈依',abbr:'sgy',full:'sanguiyi'},
  {word:'三寶',abbr:'sb',full:'sanbao'},{word:'皈依',abbr:'gy',full:'guiyi'},
  {word:'四念處',abbr:'snc',full:'sinianchu'},{word:'八正道',abbr:'bzd',full:'bazhengdao'},
  {word:'十二因緣',abbr:'seyy',full:'shieryinyuan'},

  
  {word:'淨旻法師',abbr:'jmfs',full:'jingminfashi'},
  {word:'夢參老和尚',abbr:'mclhs',full:'mengcanlaoHeshang'},
  {word:'淨慧法師',abbr:'jhfs',full:'jinghuifashi'},
  {word:'淨界法師',abbr:'jjfs',full:'jingjìefashi'},
  {word:'道證法師',abbr:'dzfs2',full:'daozhengfashi'},
  {word:'惟賢法師',abbr:'wxfs',full:'weixianfashi'},
  {word:'覺光長老',abbr:'jgzl',full:'jueguangzhanglao'},
  {word:'靜波法師',abbr:'jbfs',full:'jingbofashi'},
  {word:'昌臻法師',abbr:'czfs',full:'changzhenfashi'},
  {word:'界詮法師',abbr:'jqfs',full:'jiequanfashi'},
  {word:'妙華法師',abbr:'mhfs',full:'miaohuafashi'},
  {word:'教育短片',abbr:'jydp',full:'jiaoyuduanpian'},
  {word:'宏海法師',abbr:'hhfs',full:'honghaifashi'},
  {word:'懺雲法師',abbr:'cyfs',full:'chanyunfashi'},
  {word:'佛教卡通',abbr:'fjkt',full:'fojiaokaTong'},
  {word:'咒語',abbr:'zy',full:'zhouyu'},
  {word:'佛經念誦',abbr:'fjns',full:'fojingniansong'},
  {word:'佛教紀錄片',abbr:'fjjlp',full:'fojiaojilupian'},
  {word:'六祖大師',abbr:'lzds',full:'liuzudashi'},
  {word:'智海長老',abbr:'zHzl',full:'zhihaizhanglao'},
  {word:'阿彌陀佛聖號',abbr:'amtfsh',full:'amituofoShenghao'},
  {word:'觀音菩薩聖號',abbr:'gypsSh',full:'guanyinpusaShenghao'},
  {word:'地藏菩薩',abbr:'dzps',full:'dizangpusa'},
  {word:'地藏菩薩聖號',abbr:'dzpsSh',full:'dizangpusaShenghao'},
  {word:'釋迦牟尼佛',abbr:'sjmnf',full:'shijiamoNifo'},
  {word:'釋迦牟尼佛聖號',abbr:'sjmnfSh',full:'shijiamoNifoShenghao'},
  {word:'藥師佛聖號',abbr:'ysfSh',full:'yaoshifoShenghao'},
  {word:'財神咒',abbr:'cSz',full:'caishEnzhou'},
  {word:'度母咒',abbr:'dmz',full:'dumUzhou'},
  {word:'金剛薩埵咒',abbr:'jgsdz',full:'jingangSaduozhou'},
  {word:'楞嚴咒',abbr:'lyz',full:'lengyAnzhou'},
  {word:'六字大明咒',abbr:'lzdmz',full:'liuziDamingzhou'},
  {word:'藥師咒',abbr:'ysz',full:'yaoshiZhou'},
  {word:'准提咒',abbr:'ztZ',full:'zhuntiZhou'},
  {word:'十小咒',abbr:'sxz',full:'shixiaoZhou'},
  {word:'無量壽經',abbr:'wlsj',full:'wuliangShoudejing'},
  {word:'法華經',abbr:'fhj',full:'fahuajing'},
  {word:'十善業道經',abbr:'ssydj',full:'shishanYedaojing'},
  {word:'晚課',abbr:'wk',full:'wanke'},
  {word:'早課',abbr:'zk',full:'zaoke'},
  {word:'耀一法師',abbr:'yyfs',full:'yaoyifashi'},
  {word:'慧普法師',abbr:'hpfs',full:'huipufashi'},
  {word:'佛教晚會',abbr:'fjwh',full:'fojiaowanHui'},
  {word:'齊豫',abbr:'qy',full:'qiyu'},
  {word:'黃慧音',abbr:'hhy',full:'huangHuiyin'},
  {word:'蔡可荔',abbr:'ckl',full:'caikeli'},
  {word:'偈贊',abbr:'jz',full:'jizan'},
  {word:'黃帥',abbr:'hs',full:'huangshuai'},
  {word:'喬安舞',abbr:'qaw',full:'qiaoanwu'},
  {word:'純音樂',abbr:'cyl',full:'chunyinyue'},
  {word:'奕晥居士',abbr:'ywjs',full:'yiwanJushi'},
  {word:'演甫居士',abbr:'yfjs',full:'yanfuJushi'},
  {word:'敬善媛',abbr:'jsy',full:'jingshanYuan'},
  {word:'善音居士',abbr:'syjs',full:'shanyinJushi'},
  {word:'聆志居士',abbr:'lzjs',full:'lingzhiJushi'},
  {word:'妙喜居士',abbr:'mxjs',full:'miaoXijushi'},
  {word:'慧平法師',abbr:'hpfs2',full:'huipingfashi'},

  {word:'佛法修行',abbr:'ffxx',full:'fofaxiuXing'},
  {word:'佛法入門',abbr:'ffrm',full:'fofaRumen'},
  {word:'佛法問答',abbr:'ffwd',full:'fofaWenda'},
  {word:'施食',abbr:'ss',full:'shishi'},
  {word:'放生',abbr:'fs',full:'fangSheng'},
  {word:'懺悔',abbr:'ch',full:'chanhui'},
  {word:'智慧',abbr:'zh',full:'zhihui'},
  {word:'孝順',abbr:'xs',full:'xiaoshun'},
  {word:'臨終',abbr:'lz',full:'linzhong'},
  {word:'命運',abbr:'my',full:'minyun'},
  {word:'出家',abbr:'cj',full:'chujia'},
  {word:'唯識',abbr:'ws2',full:'weishi'},
  {word:'佛七',abbr:'fq',full:'foqi'},
  {word:'口業',abbr:'ky',full:'kouye'},
  {word:'婚姻愛情',abbr:'hyaq',full:'hunyinAiqing'},
  {word:'人生',abbr:'rs',full:'rensheng'},
  {word:'治病',abbr:'zb',full:'zhibing'},
  {word:'寺院',abbr:'sy',full:'siyuan'},
  {word:'妙蓮法師',abbr:'mlfs',full:'miaoLianfashi'},
  {word:'成剛法師',abbr:'cgfs',full:'chenggangFashi'},
  {word:'本源法師',abbr:'byfs',full:'benyuanFashi'},
  {word:'如瑞法師',abbr:'rrfs',full:'ruruiFashi'},
  {word:'仁清法師',abbr:'rqfs',full:'renqingFashi'},
  {word:'則旭法師',abbr:'zxfs',full:'zexuFashi'},
  {word:'妙境法師',abbr:'mjfs',full:'miaojingFashi'},
  {word:'演肅法師',abbr:'ysfs',full:'yansuFashi'},
  {word:'昌義法師',abbr:'cyfs2',full:'changyiFashi'},
  {word:'楞伽經',abbr:'lgj',full:'lengjiejing'},
  {word:'阿含經',abbr:'ahj',full:'ahanjing'},
  {word:'助念',abbr:'zn',full:'zhunian'},
  {word:'四十八大願',abbr:'ssdbdy',full:'SishibaDayuan'},
  {word:'佛遺教經',abbr:'fyjj',full:'foyijiaojing'},
  {word:'高僧大德',abbr:'gsdd',full:'gaosengDade'},
  {word:'善導大師',abbr:'sdds',full:'shAndaodashi'},
  {word:'忍辱',abbr:'rr',full:'renru'},
  {word:'印能法師',abbr:'ynfs',full:'yinnengFashi'},
  {word:'印良法師',abbr:'ylfs',full:'yinliangFashi'},
  {word:'雲泉法師',abbr:'yqfs',full:'yunquanFashi'},
  {word:'桑吉平措',abbr:'sjpc',full:'sangjipingcuo'},
  {word:'懷靜法師',abbr:'hjfs',full:'huaijingFashi'},
  {word:'悟公上人',abbr:'wgsr',full:'wugongShangren'},
  {word:'柯佩磊',abbr:'kpl',full:'kepeilei'},
  {word:'李佳寧',abbr:'ljn',full:'lijianing'},
  {word:'孟庭葦',abbr:'mtw',full:'mengtingwei'},
  {word:'李文發',abbr:'lwf',full:'liwenfa'},
  {word:'浴佛',abbr:'yf',full:'yufo'},
  {word:'朝聖',abbr:'cs',full:'Chaosheng'},
  {word:'淨土論著',abbr:'jtlz',full:'jingtulunzhu'},
  {word:'慧律法師念誦',abbr:'hlfsns',full:'huilüFashinianSong'},
  {word:'惠空法師',abbr:'hkfs',full:'huikongFashi'},
  {word:'覺醒法師',abbr:'jxfs',full:'juexingFashi'},
  {word:'能傑法師',abbr:'njfs',full:'nengjieFashi'},
  {word:'天因法師',abbr:'tyfs',full:'tianyinFashi'},
  {word:'崇慈法師',abbr:'ccfs',full:'chongciFashi'},
  {word:'顯明法師',abbr:'xmfs',full:'xianmingFashi'},
  {word:'果良法師',abbr:'glfs',full:'guoliangFashi'},
  {word:'果清法師',abbr:'gqfs',full:'guoqingFashi'},
  {word:'慧天法師',abbr:'htfs',full:'huitianFashi'},
  {word:'智諭法師',abbr:'zyfs',full:'zhiyuFashi'},
  {word:'東林佛號',abbr:'dlfh',full:'donglinFohao'},
  {word:'大安法師問答',abbr:'dafswd',full:'daanFashiwenda'},
  {word:'慧律法師問答',abbr:'hlfswd',full:'huilüFashiwenda'},
  {word:'慧律法師楞嚴經',abbr:'hlfslyj',full:'huilüFashilengyanjing'},
  {word:'慧律法師楞伽經',abbr:'hlfslgj',full:'huilüFashilengjiejing'},
  {word:'安樂妙寶',abbr:'almb',full:'anlemiaobao'},
  {word:'大安法師阿彌陀經',abbr:'dafsamtj',full:'daanFashiAmituojing'},
  {word:'大安法師無量壽經',abbr:'daFswlsj',full:'daanFashiWuliangShoujing'},
  {word:'慧律法師華嚴經',abbr:'hlfshyj',full:'huilüFashiHuayanjing'}, 
  {word:'虛空藏菩薩',abbr:'xkzps',full:'xukongzangpusa'},
  {word:'蕅益大師',abbr:'oyds',full:'ouyidashi'},
  {word:'蓮池大師',abbr:'lcds',full:'lianchidashi'},  
  {word:'圓覺經',abbr:'yjj',full:'yuanjuejing'},
  {word:'維摩詰經',abbr:'wmjj',full:'weimojiejing'},
  {word:'四十二章經',abbr:'ssezj',full:'sishierZhangjing'},
  {word:'弘一法師',abbr:'hyfs',full:'hongyifashi'},
  {word:'永明延壽大師',abbr:'ymysds',full:'yongmingYanshoudashi'},
  {word:'智者大師',abbr:'zzds',full:'Zhizhedashi'},
  {word:'憨山大師',abbr:'hsds',full:'hanshandashi'},
  {word:'毗盧遮那佛',abbr:'plznf',full:'piluzhenafo'},
  {word:'韋陀菩薩',abbr:'wdps',full:'weitopusa'},
  {word:'達摩大師',abbr:'dmds',full:'damodashi'},
  {word:'佛教音樂',abbr:'fjyl',full:'fojiaoyinyue'}, {word:'聖嚴法師',abbr:'syfs',full:'shengyanfashi'},
  
];


/* ================================================================
   工具函数
================================================================ */
function escHtml(s) { return String(s).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;').replace(/'/g,'&#39;'); }
function getLS(k) { try { return localStorage.getItem(k); } catch(e) { return null; } }
function setLS(k,v) { try { localStorage.setItem(k,v); } catch(e) {} }
function rmLS(k) { try { localStorage.removeItem(k); } catch(e) {} }

/* ================================================================
   深浅模式
================================================================ */
var themeToggle = document.getElementById('themeToggle');
var themeLabel  = document.getElementById('themeLabel');
function notifyIframeDarkMode() {
  var iframe = document.getElementById('playerIframe');
  if (!iframe || !iframe.contentWindow) return;
  var dark = document.body.className.indexOf('dark-mode') !== -1;
  try { iframe.contentWindow.postMessage({type:'DARK_MODE', dark:dark}, '*'); } catch(e) {}
}
(function() {
  if (getLS('theme') === 'dark') { document.body.className += ' dark-mode'; if (themeLabel) themeLabel.textContent = '深色'; }
})();
if (themeToggle) {
  themeToggle.onclick = function() {
    var dark = document.body.className.indexOf('dark-mode') !== -1;
    if (dark) { document.body.className = document.body.className.replace(/\bdark-mode\b/g,'').replace(/^\s+|\s+$/g,''); setLS('theme','light'); if (themeLabel) themeLabel.textContent = '浅色'; }
    else { document.body.className += ' dark-mode'; setLS('theme','dark'); if (themeLabel) themeLabel.textContent = '深色'; }
    notifyIframeDarkMode();
  };
}

/* ================================================================
   播放器工具函数
================================================================ */
function updateQS(uri, key, val) {
  var re = new RegExp('([?&])'+key+'=.*?(&|$)','i');
  var sep = uri.indexOf('?') !== -1 ? '&' : '?';
  return uri.match(re) ? uri.replace(re,'$1'+key+'='+val+'$2') : uri+sep+key+'='+val;
}
function getQS(name) {
  name = name.replace(/[\[\]]/g,'\\$&');
  var r = new RegExp('[?&]'+name+'(=([^&#]*)|&|#|$)').exec(location.search);
  if (!r) return null; if (!r[2]) return ''; return decodeURIComponent(r[2].replace(/\+/g,' '));
}
function getWatchHist() { try { var h = getLS('watchHistory'); return h ? JSON.parse(h) : {}; } catch(e) { return {}; } }
function markWatched(el) { void(el); }
function loadWatchHistory() {
  var h = getWatchHist();
  var epgBtns = document.querySelectorAll('.epg-btn[data-id]');
  for (var j = 0; j < epgBtns.length; j++) {
    var eid = epgBtns[j].getAttribute('data-id');
    if (eid && h[eid] && !epgBtns[j].classList.contains('epg-watched')) {
      epgBtns[j].classList.add('epg-watched');
    }
  }
}

/* ================================================================
   搜索
================================================================ */
var searchCancel  = document.getElementById('searchCancel');
var searchOverlay = document.getElementById('searchOverlay');
var searchInput   = document.getElementById('searchInput');
var searchClear   = document.getElementById('searchClear');
var searchSuggest = document.getElementById('searchSuggest');
var searchOpen    = false;
var categoryBtn    = document.getElementById('categoryBtn');
var tagCategoryBtn = document.getElementById('tagCategoryBtn');
var tagShareBtn    = document.getElementById('tagShareBtn');

function doSearch(word) {
  var hist = []; try { hist = JSON.parse(getLS('searchHistory') || '[]'); } catch(e) {}
  var nh = [word];
  for (var i = 0; i < hist.length; i++) { if (hist[i] !== word) nh.push(hist[i]); }
  if (nh.length > 20) nh = nh.slice(0,20);
  setLS('searchHistory', JSON.stringify(nh));
  if (SEARCH_ENCODING === 'utf8') { window.location.href = '/so/mso.asp?keyword=' + encodeURIComponent(word); }
  else { var form = document.createElement('form'); form.method='GET'; form.action='/so/mso.asp'; form.acceptCharset='GB2312'; form.style.display='none'; var inp=document.createElement('input'); inp.type='hidden'; inp.name='keyword'; inp.value=word; form.appendChild(inp); document.body.appendChild(form); form.submit(); }
}
var isHijackBrowser = (function() { var ua=navigator.userAgent; if (/MicroMessenger/i.test(ua)) return false; return /UCBrowser|UCWEB|Quark|baidubrowser|baiduboxapp|bdbrowser/i.test(ua); })();
var _popupSavedSrc = '';
function unloadPlayer() { if (!isHijackBrowser) return; var pif=document.getElementById('playerIframe'); if (pif&&pif.src) { _popupSavedSrc=pif.src; pif.src=''; } }
function reloadPlayer() { if (!isHijackBrowser||!_popupSavedSrc) return; var pif=document.getElementById('playerIframe'); if (pif) { pif.src=_popupSavedSrc; } _popupSavedSrc=''; }
function openPopup(showFn, overlayClass) {
  unloadPlayer(); showFn();
  if (!isHijackBrowser) history.pushState({popupOpen:overlayClass},'',window.location.href);
  if (!window.MutationObserver) { setTimeout(reloadPlayer,2000); return; }
  var obs=new MutationObserver(function(mutations){ for(var i=0;i<mutations.length;i++){var removed=mutations[i].removedNodes; for(var j=0;j<removed.length;j++){var el=removed[j]; if(el.className&&el.className.indexOf(overlayClass)!==-1){reloadPlayer();obs.disconnect();return;}}}});
  obs.observe(document.body,{childList:true});
}
function openSearch() {
  if (searchOpen) return; searchOpen=true; unloadPlayer();
  searchOverlay.className+=' active';
  if (!isHijackBrowser) history.pushState({searchOpen:true},'',window.location.href);
  if (searchInput) searchInput.focus();
  renderHot(); renderCustomLinks(); renderHistory();
}
function closeSearch() {
  if (!searchOpen) return; searchOpen=false;
  searchOverlay.className=searchOverlay.className.replace(/\bactive\b/g,'');
  if (searchInput) searchInput.value='';
  if (searchClear) searchClear.className=searchClear.className.replace(/\bshow\b/g,'');
  hideSuggest(); reloadPlayer();
}
window.addEventListener('popstate',function(e){ if(searchOpen){closeSearch();return;} var catOverlay=document.querySelector('.category-overlay'); if(catOverlay){var closeBtn=catOverlay.querySelector('button');if(closeBtn)closeBtn.click();return;} });
var inlineSearchBar=document.getElementById('inlineSearchBar');
if (inlineSearchBar) {
  inlineSearchBar.onclick = function() {
    if (!isHijackBrowser && searchInput) searchInput.focus();
    openSearch();
  };
}
if (categoryBtn) categoryBtn.onclick=function(){if(typeof showCategoryPopup==='function')openPopup(showCategoryPopup,'category-overlay');};
if (tagCategoryBtn) tagCategoryBtn.onclick=function(e){e.preventDefault();if(typeof showCategoryPopup==='function')openPopup(showCategoryPopup,'category-overlay');};
if (tagShareBtn) tagShareBtn.onclick=function(e){e.preventDefault();var isWechat=/MicroMessenger/i.test(navigator.userAgent);if(isWechat&&typeof showWechatShareTip==='function')openPopup(showWechatShareTip,'share-overlay');else if(typeof showShareUrl==='function')openPopup(showShareUrl,'share-overlay');};
var headerShareBtn=document.getElementById('headerShareBtn');
if (headerShareBtn) headerShareBtn.onclick=function(){var isWechat=/MicroMessenger/i.test(navigator.userAgent);if(typeof showWechatShareTip==='function'&&isWechat)showWechatShareTip();else if(typeof showShareUrl==='function')showShareUrl();};

/* ================================================================
   大屏
================================================================ */
(function() {
  var btn     = document.getElementById('epgBigscreenBtn');
  var k2      = document.querySelector('.k2');
  var iconExp = document.getElementById('epgBigscreenIconExpand');
  var iconCol = document.getElementById('epgBigscreenIconCollapse');
  var label   = document.getElementById('epgBigscreenLabel');
  if (!btn || !k2) return;

  var ua = navigator.userAgent;
  if (/UCBrowser|UCWEB|Quark|baidubrowser|baiduboxapp|bdbrowser|BaiduHD/i.test(ua)) {
    btn.style.display = 'none';
    return;
  }

  var isBig = false;
  var bsIframe = document.getElementById('playerIframe');

  btn.onclick = function() {
    isBig = !isBig;
    var topbarEl = document.getElementById('topbar');
    var topbarH  = topbarEl ? topbarEl.offsetHeight : 48;
    if (isBig) {
      var bigH = window.innerHeight - topbarH - (EPG_CFG.bigscreenOffset || 0);
      if (bsIframe) bsIframe.style.height = bigH + 'px';
      k2.classList.add('epg-bigscreen');
      btn.classList.add('epg-bigscreen-on');
      if (iconExp) iconExp.style.display = 'none';
      if (iconCol) iconCol.style.display = 'inline';
      if (label)   label.textContent = '恢復';
      var rect = k2.getBoundingClientRect();
      var targetY = window.pageYOffset + rect.top - topbarH;
      window.scrollTo({ top: targetY, behavior: 'smooth' });
    } else {
      if (bsIframe) bsIframe.style.height = '';
      k2.classList.remove('epg-bigscreen');
      btn.classList.remove('epg-bigscreen-on');
      if (iconExp) iconExp.style.display = 'inline';
      if (iconCol) iconCol.style.display = 'none';
      if (label)   label.textContent = '大屏';
    }
  };
})();

if (searchCancel) searchCancel.onclick=function(){closeSearch();if(!isHijackBrowser&&history.state&&history.state.searchOpen)history.back();};
if (searchClear) searchClear.onclick=function(){searchInput.value='';searchClear.className=searchClear.className.replace(/\bshow\b/g,'');hideSuggest();searchInput.focus();};
if (searchInput) {
  searchInput.oninput=function(){var v=this.value;if(v)searchClear.className=searchClear.className.indexOf('show')===-1?searchClear.className+' show':searchClear.className;else searchClear.className=searchClear.className.replace(/\bshow\b/g,'');renderSuggest(v);};
  searchInput.onkeydown=function(e){var k=e.key||e.keyCode;if(k==='Enter'||k===13){var v=this.value.replace(/^\s+|\s+$/g,'');if(v)doSearch(v);}};
}
function renderSuggest(keyword){if(!keyword||!keyword.replace(/^\s+|\s+$/g,'')){hideSuggest();return;}var kw=keyword.toLowerCase().replace(/^\s+|\s+$/g,'');var isAlpha=/^[a-z]+$/.test(kw);var matched=[];for(var i=0;i<SUGGEST_DATA.length;i++){var d=SUGGEST_DATA[i];var byWord=d.word.indexOf(keyword)!==-1;var byAbbr=isAlpha&&d.abbr&&d.abbr.indexOf(kw)===0;var byFull=isAlpha&&d.full&&d.full.toLowerCase().indexOf(kw)===0;if(byWord||byAbbr||byFull){matched.push({word:d.word,byWord:byWord,keyword:keyword});if(matched.length>=8)break;}}if(!matched.length){hideSuggest();return;}var html='';for(var j=0;j<matched.length;j++){var w=matched[j].word;var hi=escHtml(w);if(matched[j].byWord){var idx=w.indexOf(matched[j].keyword);if(idx!==-1)hi=escHtml(w.substring(0,idx))+'<span class="suggest-match">'+escHtml(w.substring(idx,idx+matched[j].keyword.length))+'</span>'+escHtml(w.substring(idx+matched[j].keyword.length));}html+='<div class="suggest-item" onclick="doSearch(\''+escHtml(w)+'\')"><span class="suggest-icon">&#128269;</span>'+hi+'</div>';}if(searchSuggest){searchSuggest.innerHTML=html;searchSuggest.className=searchSuggest.className.indexOf('show')===-1?searchSuggest.className+' show':searchSuggest.className;}}
function hideSuggest(){if(searchSuggest){searchSuggest.className=searchSuggest.className.replace(/\bshow\b/g,'');searchSuggest.innerHTML='';}}
function renderHot(){var el=document.getElementById('hotList');if(!el)return;var h='';for(var i=0;i<HOT_WORDS.length;i++)h+='<span class="search-tag" onclick="doSearch(\''+escHtml(HOT_WORDS[i])+'\')">'+escHtml(HOT_WORDS[i])+'</span>';el.innerHTML=h;}
function renderCustomLinks(){var el=document.getElementById('customLinksList');if(!el)return;var h='';for(var i=0;i<CUSTOM_LINKS.length;i++){var cl=CUSTOM_LINKS[i];h+='<a class="custom-link-item" href="'+escHtml(cl.url)+'" target="_blank"><svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"/><polyline points="15 3 21 3 21 9"/><line x1="10" y1="14" x2="21" y2="3"/></svg>'+escHtml(cl.text)+'</a>';}el.innerHTML=h;}
function renderHistory(){var hist=[];try{hist=JSON.parse(getLS('searchHistory')||'[]');}catch(e){}var el=document.getElementById('historyList');var sec=document.getElementById('historySection');if(!hist.length){if(sec)sec.style.display='none';return;}if(sec)sec.style.display='block';var h='';var max=hist.length>12?12:hist.length;for(var i=0;i<max;i++)h+='<span class="search-tag" onclick="doSearch(\''+escHtml(hist[i])+'\')">'+escHtml(hist[i])+'</span>';if(el)el.innerHTML=h;}
var clearHistBtn=document.getElementById('clearHistory');
if(clearHistBtn)clearHistBtn.onclick=function(){rmLS('searchHistory');renderHistory();};

/* ================================================================
   继续加载推荐视频
================================================================ */
var PAGE_KEY='loadedContent_'+window.location.pathname;
var FP_KEY='contentFP_'+window.location.pathname;
function getPageFP(){var l=document.getElementsByClassName('video');return l.length>0?l[0].innerHTML.substring(0,200):null;}
function saveAllContent(){try{var l=document.getElementsByClassName('video');if(l.length<=1){sessionStorage.removeItem(PAGE_KEY);sessionStorage.removeItem(FP_KEY);return;}var s='';for(var i=1;i<l.length;i++)s+=l[i].outerHTML;sessionStorage.setItem(PAGE_KEY,s);sessionStorage.setItem(FP_KEY,getPageFP());}catch(e){}}
function restoreContent(){try{var s=sessionStorage.getItem(PAGE_KEY);var fp=sessionStorage.getItem(FP_KEY);if(!s||!fp||getPageFP()!==fp){sessionStorage.removeItem(PAGE_KEY);sessionStorage.removeItem(FP_KEY);return;}var l=document.getElementsByClassName('video');if(l.length>0){while(l.length>1)l[1].parentNode.removeChild(l[1]);l[0].insertAdjacentHTML('afterend',s);}}catch(e){}}
function loadMoreVid(){var xhr=new XMLHttpRequest();xhr.onreadystatechange=function(){if(xhr.readyState===4&&xhr.status===200){try{var l=document.getElementsByClassName('video');var last=l[l.length-1];var nc=new TextDecoder('gb2312').decode(xhr.response);if(last){last.insertAdjacentHTML('afterend',nc);saveAllContent();}}catch(e){}}};xhr.open('GET','/so/fclist.asp',true);xhr.responseType='arraybuffer';try{xhr.send();}catch(e){}}

/* ================================================================
   placeholder 控制
================================================================ */
(function(){
  function init(){var cd=document.getElementById('contentDisplay');if(!cd)return;function checkEmpty(){var hasImg=!!cd.querySelector('img');var txt=(cd.textContent||cd.innerText||'').replace(/[\s\u00a0]/g,'');var isEmpty=!hasImg&&txt.length===0;if(cd.innerHTML==='<br>'||cd.innerHTML==='<BR>'){cd.innerHTML='';isEmpty=true;}if(isEmpty){cd.setAttribute('data-empty','1');}else{cd.removeAttribute('data-empty');}}if(window.MutationObserver){var obs=new MutationObserver(checkEmpty);obs.observe(cd,{childList:true,subtree:true,characterData:true});}else{cd.addEventListener('input',checkEmpty);cd.addEventListener('DOMSubtreeModified',checkEmpty);}checkEmpty();}
  if(document.readyState==='loading')document.addEventListener('DOMContentLoaded',init);else init();
})();

/* ================================================================
   d 分享/栏目弹层
================================================================ */
document.addEventListener('DOMContentLoaded', function() {
  
  const shareButtons = document.querySelectorAll('.tags .tag');
  
  shareButtons.forEach(function(button) {
    if (button.textContent.trim() === '收藏/分享') {
      
      button.style.cursor = 'pointer';
      
      button.addEventListener('click', function(e) {
        
        if (!button.hasAttribute('href')) {
          e.preventDefault();
          
          const isWechat = /MicroMessenger/i.test(navigator.userAgent);
          
          if (isWechat) {
            showWechatShareTip();
          } else {
            showShareUrl();
          }
        }
      });
    }
  });

  const categoryButtons = document.querySelectorAll('.tags .tag');
  
  categoryButtons.forEach(function(button) {
    if (button.textContent.trim() === '所有分類') {
      
      button.style.cursor = 'pointer';
      
      button.addEventListener('click', function(e) {
        
        if (!button.hasAttribute('href')) {
          e.preventDefault();
          showCategoryPopup();
        }
      });
    }
  });
});


function showWechatShareTip() {
  
  if (document.querySelector('.share-overlay')) {
    return;
  }
  
  const overlay = document.createElement('div');
  overlay.className = 'share-overlay';
  overlay.style.cssText = `
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.7);
    z-index: 9999;
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;
  `;
  
  const tipContainer = document.createElement('div');
  tipContainer.className = 'share-tip-container';
  tipContainer.style.cssText = `
    color: white;
    text-align: center;
    padding: 20px;
    max-width: 80%;
  `;
  
  const arrow = document.createElement('div');
  arrow.innerHTML = '↗&#65039;';
  arrow.style.cssText = `
    position: absolute;
    top: 20px;
    right: 40px;
    font-size: 40px;
    color: white;
  `;
  
  const tipText = document.createElement('p');
  tipText.textContent = '请点击微信右上角的···按钮，然后选择"收藏"或"转发给朋友"';
  tipText.style.cssText = `
    font-size: 16px;
    margin-bottom: 20px;
  `;
  
  const closeButton = document.createElement('button');
  closeButton.textContent = '我知道了';
  closeButton.style.cssText = `
    padding: 8px 16px;
    background-color: #07C160;
    color: white;
    border: none;
    border-radius: 4px;
    font-size: 14px;
    cursor: pointer;
  `;
  
  closeButton.addEventListener('click', function() {
    document.body.removeChild(overlay);
  });
  
  overlay.addEventListener('click', function(e) {
    if (e.target === overlay) {
      document.body.removeChild(overlay);
    }
  });
  
  tipContainer.appendChild(tipText);
  tipContainer.appendChild(closeButton);
  overlay.appendChild(arrow);
  overlay.appendChild(tipContainer);
  
  document.body.appendChild(overlay);
}


function showShareUrl() {
  
  if (document.querySelector('.share-overlay')) {
    return;
  }

  
  var WECHAT_DOMAIN = 'http://m.fzps.org';
  
  var currentUrl = window.location.href;
  var wechatUrl  = WECHAT_DOMAIN + window.location.pathname + window.location.search + window.location.hash;

  const overlay = document.createElement('div');
  overlay.className = 'share-overlay';
  overlay.style.cssText = `
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.7);
    z-index: 9999;
    display: flex;
    justify-content: center;
    align-items: center;
  `;
  
  const container = document.createElement('div');
  container.className = 'share-url-container';
  container.style.cssText = `
    background-color: white;
    padding: 20px;
    border-radius: 8px;
    max-width: 90%;
    width: 300px;
  `;
  
  const title = document.createElement('h3');
  title.textContent = '分享網址';
  title.style.cssText = `
    margin-top: 0;
    margin-bottom: 16px;
    font-size: 18px;
    text-align: center;
  `;
  
  const urlInput = document.createElement('input');
  urlInput.type = 'text';
  urlInput.value = currentUrl;
  urlInput.readOnly = true;
  urlInput.style.cssText = `
    width: 100%;
    padding: 8px;
    box-sizing: border-box;
    border: 1px solid #ccc;
    border-radius: 4px;
    margin-bottom: 16px;
  `;
  
  /* 复制按钮 */
  const copyButton = document.createElement('button');
  copyButton.textContent = '點此複製網址保存';
  copyButton.style.cssText = `
    width: 100%;
    padding: 10px;
    background-color: #1677ff;
    color: white;
    border: none;
    border-radius: 4px;
    font-size: 14px;
    cursor: pointer;
    margin-bottom: 10px;
  `;

  /* 专用复制 */
  const wechatCopyButton = document.createElement('button');
  wechatCopyButton.textContent = '複製微信可用網址(简体站)';
  wechatCopyButton.style.cssText = `
    width: 100%;
    padding: 10px;
    background-color: #e53935;
    color: white;
    border: none;
    border-radius: 4px;
    font-size: 14px;
    cursor: pointer;
    margin-bottom: 10px;
  `;

  const closeButton = document.createElement('button');
  closeButton.textContent = '关闭';
  closeButton.style.cssText = `
    width: 100%;
    padding: 10px;
    background-color: #f5f5f5;
    color: #333;
    border: none;
    border-radius: 4px;
    font-size: 14px;
    cursor: pointer;
  `;

  /* 通用复制函数 */
  function copyText(text, btn, successMsg, resetMsg, resetDelay) {
    /* 优先用现代 Clipboard API，降级用 execCommand */
    if (navigator.clipboard && navigator.clipboard.writeText) {
      navigator.clipboard.writeText(text).then(function() {
        btn.textContent = successMsg;
        setTimeout(function() { btn.textContent = resetMsg; }, resetDelay);
      }).catch(function() { fallbackCopy(text, btn, successMsg, resetMsg, resetDelay); });
    } else {
      fallbackCopy(text, btn, successMsg, resetMsg, resetDelay);
    }
  }
  function fallbackCopy(text, btn, successMsg, resetMsg, resetDelay) {
    var tmp = document.createElement('input');
    tmp.value = text;
    tmp.style.cssText = 'position:fixed;top:-9999px;left:-9999px;opacity:0';
    document.body.appendChild(tmp);
    tmp.focus(); tmp.select();
    try { document.execCommand('copy'); } catch(e) {}
    document.body.removeChild(tmp);
    btn.textContent = successMsg;
    setTimeout(function() { btn.textContent = resetMsg; }, resetDelay);
  }

  copyButton.addEventListener('click', function() {
    copyText(currentUrl, copyButton,
      '複製成功，請貼到備忘錄儲存或傳給朋友',
      '點此複製網址保存', 8000);
  });

  wechatCopyButton.addEventListener('click', function() {
    copyText(wechatUrl, wechatCopyButton,
      '複製成功，請貼到微信聊天對話框',
      '複製微信可用網址(简体)', 8000);
  });
  
  closeButton.addEventListener('click', function() {
    document.body.removeChild(overlay);
  });
  
  overlay.addEventListener('click', function(e) {
    if (e.target === overlay) {
      document.body.removeChild(overlay);
    }
  });
  
  container.appendChild(title);
  container.appendChild(urlInput);
  container.appendChild(copyButton);
  container.appendChild(wechatCopyButton);
  container.appendChild(closeButton);
  overlay.appendChild(container);
  
  document.body.appendChild(overlay);
}


function showCategoryPopup() {
  
  if (document.querySelector('.category-overlay')) {
    return;
  }
  
  const overlay = document.createElement('div');
  overlay.className = 'category-overlay';
  overlay.style.cssText = `
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.7);
    z-index: 9999;
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 20px;
    box-sizing: border-box;
  `;
  
  const container = document.createElement('div');
  container.className = 'category-container';
  container.style.cssText = `
    background-color: white;
    border-radius: 12px;
    max-width: 90%;
    width: 360px;
    max-height: 70vh;
    box-shadow: 0 10px 25px rgba(0, 0, 0, 0.2);
    overflow: hidden;
    display: flex;
    flex-direction: column;
  `;
  
  const header = document.createElement('div');
  header.className = 'category-header';
  header.style.cssText = `
    padding: 16px 20px;
    border-bottom: 1px solid #eaeaea;
    display: flex;
    justify-content: space-between;
    align-items: center;
    background-color: #f9f9f9;
  `;
  
  const title = document.createElement('h3');
  title.textContent = '分類導覽';
  title.style.cssText = `
    margin: 0;
    font-size: 16px;
    color: #333;
    font-weight: 600;
  `;
  
  const closeBtn = document.createElement('button');
  closeBtn.textContent = '關閉';
  closeBtn.style.cssText = `
    background: none;
    border: 1px solid #ddd;
    font-size: 13px;
    color: #666;
    cursor: pointer;
    padding: 4px 12px;
    border-radius: 12px;
    line-height: 1.6;
    font-family: inherit;
  `;
  
  closeBtn.addEventListener('click', function() {
    document.body.removeChild(overlay);
  });
  
  const content = document.createElement('div');
  content.className = 'category-content';
  content.style.cssText = `
    padding: 20px;
    overflow-y: auto;
    flex: 1;
  `;
  
  const categoryData = [{
    title: '法師講座',
    links: [
      {name: '慧律法師', url: 'm1_2.htm'},
      {name: '淨界法師', url: 'm1_19.htm'},
      {name: '大安法師', url: 'm1_4.htm'},
      {name: '界詮法師', url: 'm1_32.htm'},
      {name: '宏海法師', url: 'm1_35.htm'},
      {name: '妙境法師', url: 'm1_47.htm'},
      {name: '惠空法師', url: 'm1_60.htm'},
      {name: '印光大師', url: 'm1_55.htm'},
      {name: '六祖大師', url: 'm1_56.htm'},
      {name: '妙蓮法師', url: 'm1_40.htm'},
      {name: '善導大師', url: 'm1_58.htm'},
      {name: '天因法師', url: 'm1_63.htm'},
      {name: '夢參老和尚', url: 'm1_11.htm'},
      {name: '顯明法師', url: 'm1_65.htm'},
      {name: '會性法師', url: 'm1_66.htm'},
      {name: '果良法師', url: 'm1_67.htm'},
      {name: '果清法師', url: 'm1_68.htm'},
      {name: '慧天法師', url: 'm1_69.htm'},
      {name: '智諭法師', url: 'm1_70.htm'},
      {name: '達照法師', url: 'm1_6.htm'},
      {name: '星雲法師', url: 'm1_8.htm'},
      {name: '淨旻法師', url: 'm1_9.htm'},
      {name: '本煥老和尚', url: 'm1_12.htm'},
      {name: '淨慧法師', url: 'm1_13.htm'},
      {name: '聖嚴法師', url: 'm1_14.htm'},
      {name: '道證法師', url: 'm1_20.htm'},
      {name: '惟賢法師', url: 'm1_23.htm'},
      {name: '覺光長老', url: 'm1_24.htm'},
      {name: '靜波法師', url: 'm1_25.htm'},
      {name: '昌臻法師', url: 'm1_28.htm'},
      {name: '宏明法師', url: 'm1_30.htm'},
      {name: '其他法師', url: 'm1_31.htm'},
      {name: '妙華法師', url: 'm1_33.htm'},
      {name: '懺雲法師', url: 'm1_37.htm'},
      {name: '智海長老', url: 'm1_57.htm'},
      {name: '成剛法師', url: 'm1_41.htm'},
      {name: '本源法師', url: 'm1_42.htm'},
      {name: '如瑞法師', url: 'm1_43.htm'},
      {name: '仁清法師', url: 'm1_45.htm'},
      {name: '演肅法師', url: 'm1_48.htm'},
      {name: '昌義法師', url: 'm1_49.htm'},
      {name: '悟公上人', url: 'm1_59.htm'},
      {name: '覺醒法師', url: 'm1_61.htm'},
      {name: '能傑法師', url: 'm1_62.htm'},
      {name: '崇慈法師', url: 'm1_64.htm'}
    ]
  },{
    title: '佛經念誦',
    links: [
      {name: '阿彌陀經', url: 'm5.htm'},
      {name: '無量壽經', url: 'm5_13.htm'},
      {name: '地藏經', url: 'm5_2.htm'},
      {name: '法華經普門品', url: 'm5_10.htm'},
      {name: '金剛經', url: 'm5_3.htm'},
      {name: '早課', url: 'm5_5.htm'},
      {name: '晚課', url: 'm5_6.htm'},
      {name: '佛經念誦最新', url: 'm5_15.htm'},
      {name: '楞嚴經', url: 'm5_4.htm'},
      {name: '普賢行願品', url: 'm5_8.htm'},
      {name: '其他淨土經', url: 'm5_1.htm'},
      {name: '其他佛經', url: 'm5_12.htm'},
      {name: '十善業道經', url: 'm5_11.htm'},
      {name: '心經', url: 'm5_9.htm'},
      {name: '藥師經', url: 'm5_7.htm'},
      {name: '善音居士', url: 'b119.htm'},
      {name: '聆志居士', url: 'b120.htm'},
      {name: '妙喜居士', url: 'b121.htm'},
      {name: '慧平法師', url: 'b122.htm'},
      {name: '慧律法師念誦', url: 'c230.htm'}
    ]
  },{
    title: '佛號',
    links: [
      {name: '阿彌陀佛聖號', url: 'm3.htm'},
      {name: '觀音菩薩聖號', url: 'm3_1.htm'},
      {name: '地藏菩薩聖號', url: 'm3_2.htm'},
      {name: '釋迦牟尼佛聖號', url: 'm3_4.htm'},
      {name: '藥師佛聖號', url: 'm3_3.htm'},
      {name: '其他聖號', url: 'm3_5.htm'},
      {name: '佛號最新', url: 'm3_6.htm'}
    ]
  },{
    title: '咒語',
    links: [
      {name: '大悲咒', url: 'm4.htm'},
      {name: '六字大明咒', url: 'm4_1.htm'},
      {name: '楞嚴咒', url: 'm4_4.htm'},
      {name: '藥師咒', url: 'm4_6.htm'},
      {name: '准提咒', url: 'm4_2.htm'},
      {name: '十小咒', url: 'm4_3.htm'},
      {name: '其他咒語', url: 'm4_7.htm'},
      {name: '咒語最新', url: 'm4_10.htm'},
      {name: '財神咒', url: 'm4_5.htm'},
      {name: '度母咒', url: 'm4_8.htm'},
      {name: '金剛薩埵咒', url: 'm4_9.htm'}
    ]
  },{
    title: '佛菩薩',
    links: [
      {name: '阿彌陀佛', url: 'c123.htm'},
      {name: '觀音菩薩', url: 'c124.htm'},
      {name: '地藏菩薩', url: 'c125.htm'},
      {name: '藥師佛', url: 'c126.htm'},
      {name: '釋迦牟尼佛', url: 'c127.htm'},
      {name: '文殊菩薩', url: 'c128.htm'},
      {name: '普賢菩薩', url: 'c129.htm'},
      {name: '大勢至菩薩', url: 'c130.htm'},
      {name: '彌勒菩薩', url: 'c131.htm'},
      {name: '八十八佛', url: 'c171.htm'}
    ]
  },{
    title: '佛經咒語論著',
    links: [
      {name: '阿彌陀經', url: 'c132.htm'},
      {name: '無量壽經', url: 'c133.htm'},
      {name: '觀無量壽佛經', url: 'c134.htm'},
      {name: '普門品', url: 'c135.htm'},
      {name: '地藏經', url: 'c136.htm'},
      {name: '藥師經', url: 'c137.htm'},
      {name: '普賢行願品', url: 'c138.htm'},
      {name: '念佛圓通章', url: 'c139.htm'},
      {name: '金剛經', url: 'c140.htm'},
      {name: '楞嚴經', url: 'c141.htm'},
      {name: '妙法蓮華經', url: 'c142.htm'},
      {name: '心經', url: 'c143.htm'},
      {name: '八大人覺經', url: 'c144.htm'},
      {name: '十善業道經', url: 'c145.htm'},
      {name: '華嚴經', url: 'c146.htm'},
      {name: '六祖壇經', url: 'c147.htm'},
      {name: '印光大師文鈔', url: 'c148.htm'},
      {name: '大悲咒', url: 'c177.htm'},
      {name: '六字大明咒', url: 'c178.htm'},
      {name: '楞嚴咒', url: 'c180.htm'},
      {name: '楞伽經', url: 'c204.htm'},
      {name: '准提咒', url: 'c205.htm'},
      {name: '阿含經', url: 'c206.htm'},
      {name: '佛遺教經', url: 'c210.htm'},
      {name: '淨土論著', url: 'c229.htm'}
    ]
  },{
    title: '佛教音樂',
    links: [
      {name: '佛教音樂', url: 'm7.htm'},
      {name: '耀一法師', url: 'b90.htm'},
      {name: '慧普法師', url: 'b91.htm'},
      {name: '佛光山人間音緣', url: 'b93.htm'},
      {name: '齊豫歌曲', url: 'b101.htm'},
      {name: '黃慧音歌曲', url: 'b102.htm'},
      {name: '佛曲專輯', url: 'b108.htm'},
      {name: '偈讚偈頌', url: 'b109.htm'},
      {name: '黃帥佛曲', url: 'b113.htm'},
      {name: '喬安舞歌曲', url: 'b114.htm'},
      {name: '純音樂', url: 'b115.htm'},
      {name: '則旭法師', url: 'b194.htm'},
      {name: '印能法師', url: 'b217.htm'},
      {name: '印良法師', url: 'b218.htm'},
      {name: '極樂音樂工作室', url: 'b89.htm'},
      {name: '廣東佛曲', url: 'b99.htm'},
      {name: '佛教晚會', url: 'b100.htm'},
      {name: '蔡可荔歌曲', url: 'b105.htm'},
      {name: '其他佛曲', url: 'b112.htm'},
      {name: '奕晥居士歌曲', url: 'b116.htm'},
      {name: '演甫居士歌曲', url: 'b117.htm'},
      {name: '敬善媛歌曲', url: 'b118.htm'},
      {name: '雲泉法師', url: 'b219.htm'},
      {name: '桑吉平措', url: 'b220.htm'},
      {name: '懷靜法師', url: 'b221.htm'},
      {name: '柯佩磊', url: 'c223.htm'},
      {name: '李佳寧', url: 'c224.htm'},
      {name: '孟庭葦', url: 'c225.htm'},
      {name: '李文發', url: 'c226.htm'}
    ]
  },{
    title: '其他',
    links: [
      {name: '佛教教育短片', url: 'm1_34.htm'},
      {name: '佛教卡通', url: 'm2.htm'},
      {name: '佛教紀錄片', url: 'm6.htm'},
      {name: '佛教寺院', url: 'c176.htm'},
      {name: '佛教高僧大德系列', url: 'c211.htm'},
      {name: '佛教故事', url: 'c212.htm'},
      {name: '聖地朝聖', url: 'c228.htm'}
    ]
  },{
    title: '修行',
    links: [
      {name: '佛法修行', url: 'c149.htm'},
      {name: '佛法入門', url: 'c150.htm'},
      {name: '佛法問答', url: 'c151.htm'},
      {name: '功德', url: 'c152.htm'},
      {name: '慈悲施食', url: 'c153.htm'},
      {name: '放生', url: 'c154.htm'},
      {name: '佛教戒律', url: 'c155.htm'},
      {name: '懺悔', url: 'c156.htm'},
      {name: '智慧', url: 'c157.htm'},
      {name: '孝順', url: 'c158.htm'},
      {name: '臨終', url: 'c159.htm'},
      {name: '八關齋戒', url: 'c160.htm'},
      {name: '禪宗', url: 'c161.htm'},
      {name: '命運', url: 'c162.htm'},
      {name: '皈依', url: 'c163.htm'},
      {name: '出家', url: 'c164.htm'},
      {name: '唯識', url: 'c165.htm'},
      {name: '佛七', url: 'c166.htm'},
      {name: '斷除口業', url: 'c168.htm'},
      {name: '念佛開示', url: 'c169.htm'},
      {name: '婚姻愛情', url: 'c170.htm'},
      {name: '因果', url: 'c172.htm'},
      {name: '人生', url: 'c173.htm'},
      {name: '治病', url: 'c174.htm'},
      {name: '輪迴', url: 'c175.htm'},
      {name: '臨終助念', url: 'c207.htm'},
      {name: '菩薩戒', url: 'c208.htm'},
      {name: '阿彌陀佛四十八大願', url: 'c209.htm'},
      {name: '忍辱', url: 'c216.htm'},
      {name: '浴佛', url: 'c227.htm'}
    ]
  }];

  categoryData.forEach(function(category, index) {
    const categoryTitle = document.createElement('div');
    categoryTitle.className = 'category-title';
    categoryTitle.style.cssText = `
      font-weight: bold;
      font-size: 15px;
      color: #333;
      margin-bottom: 10px;
      margin-top: ${index > 0 ? '20px' : '0'};
    `;
    categoryTitle.textContent = category.title;
    content.appendChild(categoryTitle);
    
    const linkContainer = document.createElement('div');
    linkContainer.className = 'category-links';
    linkContainer.style.cssText = `
      display: flex;
      flex-wrap: wrap;
      gap: 15px;
      margin-bottom: 5px;
      padding-bottom: 15px;
      border-bottom: ${index < categoryData.length - 1 ? '1px dashed #eaeaea' : 'none'};
    `;
    
    category.links.forEach(function(link) {
      const linkElem = document.createElement('a');
      linkElem.href = link.url;
      linkElem.textContent = link.name;
      linkElem.style.cssText = `
        text-decoration: none;
        color: #555;
        padding: 6px 12px;
        background-color: #f5f5f5;
        border-radius: 15px;
        font-size: 12px;
        transition: all 0.2s ease;
        display: inline-block;
      `;
      
      linkElem.addEventListener('mouseover', function() {
        this.style.backgroundColor = '#e9e9e9';
        this.style.color = '#222';
      });
      
      linkElem.addEventListener('mouseout', function() {
        this.style.backgroundColor = '#f5f5f5';
        this.style.color = '#555';
      });
      
      linkContainer.appendChild(linkElem);
    });
    
    content.appendChild(linkContainer);
  });
  
  header.appendChild(title);
  header.appendChild(closeBtn);
  container.appendChild(header);
  container.appendChild(content);
  overlay.appendChild(container);
  
  overlay.addEventListener('click', function(e) {
    if (e.target === overlay) {
      document.body.removeChild(overlay);
    }
  });
  
  document.body.appendChild(overlay);
}

/* ================================================================
   e - 评论 点赞
================================================================ */
window.addEventListener("load", function () {

    /* -------------------------  ------------------------- */
    var commentInputBox = document.getElementById("commentInputBox");
	var commentForm = document.getElementById("commentForm");
	var textarea = document.getElementById("content");          
	var contentDisplay = document.getElementById("contentDisplay"); 
    var usernameInput = document.getElementById("username");
    var parentInput = document.getElementById("parent_id");
    var replyInfo = document.getElementById("replyInfo");
    var replyUserSpan = document.getElementById("replyUser");
    var cancelReplyLink = document.getElementById("cancelReplyLink");
    var sendBtn = document.getElementById("sendBtn");
    var cancelFormBtn = document.getElementById("cancelFormBtn");
    var sendSuccessBox = document.getElementById("sendSuccess");
    var commentsBox = document.getElementById("comments");
    var loadMoreBtn = document.getElementById("loadMore");
    var likeArea = document.getElementById("likeArea");

    /* -------------------------  ------------------------- */
    function ajax(url, method, callback) {
        var xhr = new XMLHttpRequest();
        xhr.open(method, url, true);
        xhr.onreadystatechange = function () {
            if (xhr.readyState === 4 && xhr.status === 200) {
                callback(JSON.parse(xhr.responseText));
            }
        };
        xhr.send();
    }

    /* ------------------------- 保存 ------------------------- */
    if (usernameInput) {
        var saved = localStorage.getItem("comment_username");
        if (saved) usernameInput.value = saved;
    }

    /* -------------------------  ------------------------- */
    fetch(API + "/tj?id=" + PAGE_ID, {
        method: "POST",
        headers: {"Content-Type": "application/x-www-form-urlencoded"},
        body:
            "screen=" + encodeURIComponent(window.screen.width + "x" + window.screen.height) +
            "&ref=" + encodeURIComponent(document.referrer) +
            "&url=" + encodeURIComponent(location.href) +
            "&title=" + encodeURIComponent(document.title)
    });
	
	/* ------------------------- uv ------------------------- */
	
var uvEl = document.getElementById('uvc');
if (uvEl) {
    fetch(API + '/wat?id=' + PAGE_ID)
        .then(function(r){ return r.json(); })
        .then(function(d){ uvEl.innerText = d.uv; });
}

    /* ------------------------- 输入框展开 ------------------------- */
    if (commentInputBox && commentForm && contentDisplay) {
    commentInputBox.onclick = function () {
        commentInputBox.style.display = "none";
        commentForm.style.display = "block";
        contentDisplay.focus();   
    };
}


    /* ------------------------- 自动高度 ------------------------- */
    if (contentDisplay) {
    contentDisplay.addEventListener("input", function () {
        this.style.height = "auto";
        this.style.height = this.scrollHeight + "px";
    });
}


    
    /* ------------------------- 表情 ------------------------- */
if (contentDisplay && textarea) {
    var emojis = document.querySelectorAll("#emojiBox img");
    for (var i = 0; i < emojis.length; i++) {
        emojis[i].onclick = function () {
            var code = this.getAttribute("data-code"); 
            var num = code.replace("emoji_", "");

            
            contentDisplay.innerHTML += '<img src="/em/' + num + '.png" class="emoji">';

            
            textarea.value += "[" + code + "]";
        };
    }
}

/* ------------------------- 粘贴文本 ------------------------- */
if (contentDisplay) {
    contentDisplay.addEventListener("paste", function (e) {
        e.preventDefault();

        var text = (e.clipboardData || window.clipboardData).getData("text");

        
        document.execCommand("insertText", false, text);
    });
}



/* -------------------------  ------------------------- */
if (contentDisplay && textarea) {
    contentDisplay.addEventListener("input", function () {
        var clone = contentDisplay.cloneNode(true);

        
        var imgs = clone.querySelectorAll("img.emoji");
        for (var i = 0; i < imgs.length; i++) {
            var src = imgs[i].getAttribute("src");
            var num = src.match(/\/(\d+)\.png$/)[1];
            var text = document.createTextNode("[emoji_" + num + "]");
            imgs[i].parentNode.replaceChild(text, imgs[i]);
        }

        
        var pureText = clone.textContent || clone.innerText;

        
        textarea.value = pureText;
    });
}




    /* ------------------------- 点赞 ------------------------- */
var likeOriginalHTML = likeArea ? likeArea.innerHTML : '';
var likeProcessing = false; /* 防重复点击 */

function restoreLikeBtn(count) {
    var area = document.getElementById('likeArea');
    if (!area) return;
    area.innerHTML = likeOriginalHTML;
    var span = document.getElementById('likeCount');
    if (span) span.innerText = count;
    area.classList.add('liked'); /* 点击当次变红，刷新后自然消失 */
}

function loadLikeCount() {
    ajax(API + '/getlike?id=' + PAGE_ID, 'GET', function (d) {
        var span = document.getElementById('likeCount');
        if (span) span.innerText = d.count;
    });
}
loadLikeCount();

if (likeArea) {
    likeArea.onclick = function () {
        if (likeProcessing) return; /* 防连续点击 */
        likeProcessing = true;

        ajax(API + '/like?id=' + PAGE_ID, 'POST', function (d) {
            likeProcessing = false;
            var area = document.getElementById('likeArea');
            var count = d.count;

            if (d.status === 'liked') {
                /* 后台判断已按讚：只弹提示，不变红，不动数字 */
                var tip = document.createElement('span');
                tip.className = 'like-plus';
                tip.innerText = '已按讚';
                tip.style.cssText = 'left:50%;top:0;transform:translateX(-50%);white-space:nowrap;';
                area.appendChild(tip);
                setTimeout(function () {
                    if (tip.parentNode) tip.parentNode.removeChild(tip);
                }, 1200);
                return;
            }

            /* 正常点赞：+1 动画，1秒后恢复大拇指样式并变红 */
            var plus = document.createElement('span');
            plus.className = 'like-plus';
            plus.innerText = '+1';
            plus.style.cssText = 'left:50%;top:0;transform:translateX(-50%);';
            area.appendChild(plus);
            setTimeout(function () {
                if (plus.parentNode) plus.parentNode.removeChild(plus);
            }, 800);
            setTimeout(function () {
                restoreLikeBtn(count);
            }, 1000);
        });
    };
}

    /* ------------------------- 加载 ------------------------- */
    var allComments = [];
    var showCount = 5;

    function loadComments() {
        if (!commentsBox) return;

        fetch(API + "/comments?id=" + PAGE_ID)
            .then(function (r) { return r.json(); })
            .then(function (list) {
                allComments = list || [];  // 防止接口返回 null 导致报错
                renderComments();
            })
            .catch(function () {
                allComments = [];  // 请求异常时也兜底为空数组
                renderComments();
            });
    }

    /* ------------------------- 渲染 ------------------------- */
    function renderComments() {
        if (!commentsBox) return;
        if (!Array.isArray(allComments)) allComments = [];  // 兜底，确保是数组

        var map = {};
        for (var i = 0; i < allComments.length; i++) {
            allComments[i].children = [];
            map[allComments[i].id] = allComments[i];
        }

        var roots = [];
        for (var j = 0; j < allComments.length; j++) {
            var c = allComments[j];
            if (c.parent_id && map[c.parent_id]) {
                map[c.parent_id].children.push(c);
            } else {
                roots.push(c);
            }
        }

        var displayRoots = roots.slice(0, showCount);

        function renderTree(nodes) {
            var html = "";

            for (var k = 0; k < nodes.length; k++) {
                var c = nodes[k];

                
               var content = c.content;

for (var i = 1; i <= 20; i++) {
    var key = "[emoji_" + i + "]";
    var img = '<img src="/em/' + i + '.png" class="emoji">';
    content = content.split(key).join(img);
}



              html +=
    '<div class="comment-box">' +
        '<b>' + c.username + '</b>' +
(c.pinned ? '<span class="pinned">置頂</span>' : '') +
'<div style="margin:8px 0">' + content + '</div>' +
        '<div style="display:-webkit-flex;display:flex;-webkit-align-items:center;align-items:center;-webkit-justify-content:space-between;justify-content:space-between;margin-top:8px">' +
            '<div style="display:-webkit-flex;display:flex;-webkit-align-items:center;align-items:center;gap:12px">' +
                '<span style="font-size:12px;color:#888">' + c.time + '</span>' +
                '<span class="reply-btn" data-id="' + c.id + '" data-user="' + c.username.replace(/"/g, '&quot;') + '">回覆</span>' +
            '</div>' +
            '<div class="like-btn" data-id="' + c.id + '">' +
                '<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z"/></svg>' +
                c.likes +
            '</div>' +
        '</div>' +
        (c.children.length ? '<div class="comment-children">' + renderTree(c.children) + '</div>' : '') +
    '</div>';
					
					
					
            }

            return html;
        }

        commentsBox.innerHTML = renderTree(displayRoots);
var plSection = document.querySelector('.pl-section');
if (plSection) {
    if (roots.length > 0) {
        plSection.style.borderTop = 'none';
        plSection.style.borderBottom = 'none';
    } else {
        plSection.style.borderTop = '';
        plSection.style.borderBottom = '';
    }
}

        
        if (loadMoreBtn) {
            loadMoreBtn.style.display = roots.length > showCount ? "block" : "none";
        }

        /* 点赞 */
        var likeBtns = commentsBox.querySelectorAll(".like-btn");
        for (var a = 0; a < likeBtns.length; a++) {
            likeBtns[a].onclick = function () {
                var id = this.getAttribute("data-id");
                var self = this;

                fetch(API + "/comment_like?id=" + id, { method: "POST" })
                    .then(function (r) { return r.json(); })
                    .then(function (d) {
                        self.innerHTML = '<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" ><path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z"/></svg>' + d.count;
                    });
            };
        }

        /* 回覆 */
        var replyBtns = commentsBox.querySelectorAll(".reply-btn");
        for (var b = 0; b < replyBtns.length; b++) {
            replyBtns[b].onclick = function () {
                var id = this.getAttribute("data-id");
                var user = this.getAttribute("data-user");
                setReply(id, user);
            };
        }
    }

    /* ------------------------- 展开 ------------------------- */
    if (loadMoreBtn) {
        loadMoreBtn.onclick = function () {
            showCount += 8; 
            renderComments();
        };
    }

    /* ------------------------- 回覆 ------------------------- */
    function setReply(id, username) {
        parentInput.value = id;
        replyUserSpan.innerText = username;
        replyInfo.style.display = "block";

        if (commentInputBox) commentInputBox.style.display = "none";
        commentForm.style.display = "block";

        commentForm.scrollIntoView({ behavior: "smooth" });
        textarea.focus();
    }

    if (cancelReplyLink) {
        cancelReplyLink.onclick = function () {
            parentInput.value = 0;
            replyInfo.style.display = "none";
        };
    }

    /* ------------------------- 取消 ------------------------- */
    if (cancelFormBtn) {
        cancelFormBtn.onclick = function () {
            textarea.value = "";
            textarea.style.height = "80px";
            parentInput.value = 0;
            replyInfo.style.display = "none";
            commentForm.style.display = "none";

            if (commentInputBox) commentInputBox.style.display = "block";
        };
    }

    /* ------------------------- 发送 ------------------------- */
    if (sendBtn) {
        sendBtn.onclick = function () {
            var username = usernameInput.value.trim();
            var content = textarea.value.trim();
            var parent = parentInput.value;

            if (!content) return alert("評論內容不能為空");
            if (content.length > 200) return alert("內容不能超過 200 字");
            if (username.length > 15) return alert("用戶名不能超過 15 字");

            if (!username) {
                username = "佛弟子" + Math.floor(10000 + Math.random() * 90000);
                usernameInput.value = username;
            }

            localStorage.setItem("comment_username", username);

            fetch(API + "/pl?id=" + PAGE_ID, {
                method: "POST",
                headers: {"Content-Type": "application/x-www-form-urlencoded"},
                body:
                    "username=" + encodeURIComponent(username) +
                    "&content=" + encodeURIComponent(content) +
                    "&parent_id=" + parent
            })
                .then(function (r) { return r.text(); })
                .then(function (t) {
    if (t === "too_fast") return alert("您評論太快了，請稍後再試");
    if (t === "too_long") return alert("不能超過 200 字");

    // 清空
    contentDisplay.innerHTML = "";
    textarea.value = "";
    contentDisplay.style.height = "80px";

    parentInput.value = 0;
    replyInfo.style.display = "none";
    commentForm.style.display = "none";
    if (commentInputBox) commentInputBox.style.display = "block";

    if (sendSuccessBox) {
        sendSuccessBox.innerText = "發送成功，評論將在審核後顯示";
        sendSuccessBox.style.opacity = 1;
        setTimeout(function () {
            sendSuccessBox.style.opacity = 0;
        }, 5000);
    }

    var successBox = document.getElementById('sendSuccess');
if (successBox) {
    successBox.innerText = '發送成功，評論將在審核後顯示';
    successBox.style.opacity = 1;
    setTimeout(function() {
        successBox.style.opacity = 0;
    }, 5000);
}
loadComments();
});

        };
    }

    /* ------------------------- 初始化 ------------------------- */
    loadComments();
});
