var $=function(id) { return document.getElementById(id); };
function IsJsonString(str) { try { JSON.parse(str); } catch(e) { return false; } return true; }

//var t,d=false;
//function selectText(e,x) {
function selectText() {
    //clearTimeout(t);

    //if(e.which==1) {
    //    switch(x) {
    //        case 1:
    //            d=true;
    //            t=setTimeout(function() { selectText(e,0); },200);
    //            break;
    //        case 2:
    //            if(d) {
                    if(document.selection) {
                        var range=document.body.createTextRange();
                        range.moveToElementText($('code'));
                        range.select();
                    } else if(window.getSelection) {
                        var range=document.createRange();
                        range.selectNode($('code'));
                        window.getSelection().addRange(range);
                    }
    //            }
    //            break;
    //        default:
    //            d=false;
    //    }
    //}
}

var zT;
function zindex(id) {
    clearTimeout(zT);

    if(id=="chat") {
        if($('text')) $('text').style.zIndex=9;
        $(id).style.zIndex=10;
    } else {
        zT=setTimeout(function() {
            if($('chat')) $('chat').style.zIndex=9;
            $(id).style.zIndex=10;
        },500);
    }
}

var nShow;
function showNotification(nt,nc) {
    var nc1=nc.substring(nc.indexOf("<b>")+3,nc.indexOf("</b>"));
    var nc2=nc.substring(nc.indexOf("</b>")+12,nc.indexOf("<br>"));
    nc2=nc2.replace(/<(a\s+.*?|\/a)>/g,'');

    if(window.Notification && Notification.permission!=="denied") {
        Notification.requestPermission(function(status) {
            nShow=new Notification('Twily.info ('+nt+')', {
                body: nc1+' '+nc2,
                icon: '/favicon.ico'
            });
        });

        nShow.close();
    }
}

var n=0,fI,fT=false,fL=false;
window.addEventListener('message',function(event) {
	data=event.data;
	if(IsJsonString(data)) data=JSON.parse(data);

    var title=document.title;
    var link=document.createElement('link');
    link.id="favicon";
    link.type="image/x-icon";
    link.rel="shortcut icon";

    if(data[0]=="notify") {
        if(!fL) {
            fL=true;

            fI=setInterval(function() {
                fT=!fT;

                if(fT) link.href="/favicon_red.ico";
                else   link.href="/favicon.ico";

                document.getElementsByTagName('head')[0].removeChild($('favicon'));
                document.getElementsByTagName('head')[0].appendChild(link);
            },500);
        }

        if(title.substr(0,1)!="(") {
            n=1;
        } else {
            n+=parseInt(data[1]);
            title=title.substr(title.indexOf(" ")+1);
        }
        document.title="("+n+") "+title;

		showNotification(n,data[2]);
    } else {
        clearInterval(fI);
        fT=false;
        fL=false;

        link.href="/favicon.ico";

        document.getElementsByTagName('head')[0].removeChild($('favicon'));
        document.getElementsByTagName('head')[0].appendChild(link);

        n=0;
        if(title.substr(0,1)=="(") document.title=title.substr(title.indexOf(" ")+1);
    }
});

window.addEventListener('scroll',function() {
    if($('text')) {
        var eT,wY;
        eT=$('text').offsetTop;
        eB=$('text').offsetTop+$('text').offsetHeight;
        wY=window.pageYOffset;
        wH=window.innerHeight;

        if(wY>eT) {
            $('top_arrow').style.display="block";
        } else {
            $('top_arrow').style.display="none";
        }
        if((wY+wH)<eB) {
            $('bot_arrow').style.display="block";
        } else {
            $('bot_arrow').style.display="none";
        }
    }

    if(!$('code')) {
        if($('followView')) {
            //$('followView').style.top=window.scrollY+"px";
            if(!fVrunning) {
                fVrunning=true;
                scrollInFollowView();

                ifrmO=document.body.getElementsByClassName('dir')[0].offsetTop;
                //ifrmH=winHeight-ifrmO;
                if(ifrmH<50) ifrmH=50;
                if($('ifrm')) {
                    $('ifrm').style.maxHeight=ifrmH+"px";
                    $('ifrm').style.minHeight=ifrmH+"px";
                }
            }
        }
    } else {
        $('followView').style.top="0";
    }
});

var ifrmO=0;
var ifrmH=0;

var fVy=0;
var fVfps=60;
var fVrunning=false;

var sIFVt;
function scrollInFollowView() {
    clearTimeout(sIFVt);

    var targ=window.scrollY-(ifrmO / 2);
    if(targ<0) targ=0;
    var diff=targ-fVy;
    //console.log("start sIFV , diff="+diff);

    if(diff<1 && diff>-1) {
        fVrunning=false;
    } else {
        if(diff<0) {
            var multi=Math.abs(diff)/10;
            //if(multi<1) multi=1;
            fVy-=1*multi;
        } else {
            var multi=diff/10;
            //if(multi<1) multi=1;
            fVy+=1*multi;
        }
        $('followView').style.top=fVy+"px";
    
        sIFVt=setTimeout(function() { scrollInFollowView(); }, 1000/fVfps);
    }
}

var rzC;
function loadCmt(x,f) {
    clearInterval(rzC);

    //$(x).contentWindow.postMessage(f,'*');

    rzC=setInterval(function() {
        //$(x).style.height=0;
        $(x).style.height=$(x).contentWindow.document.body.scrollHeight+"px";
    },100);
}

async function ajaxThumbs(name, idx, cb) {
    var xhr;
    if(window.XMLHttpRequest) xhr=new XMLHttpRequest();
    else                      xhr=new ActiveXObject("Microsoft.XMLHTTP");

    var data;
    xhr.onreadystatechange=function() {
        if(xhr.readyState==4 && xhr.status==200) {
            cb(xhr.responseText);
        }
    }

    xhr.open("GET","/ffthumber.php?p="+name+"&i="+idx,true);
    xhr.send(null);
}

var mfiles=[];
var mcount=0;
var mindex=[];
var mstring=[];
async function checkThumbs() {
    mfiles=document.getElementsByClassName('file');
    mcount=0;
    var host=location.hostname;
    for(var i=0;i<mfiles.length;i++) {
        //console.log(mfiles[i].className);
        if(mfiles[i].className.includes("mimg") || mfiles[i].className.includes("mvid")) {
            var src=mfiles[i].getElementsByTagName('img')[0].src;
            src=src.substring(src.indexOf('/') + host.length + 3);
            src=src.substring(0, src.lastIndexOf('/') + 1);
            //console.log(src);
            if(src=="img/") { // defalt icon loaded only
                mcount++; // ready generate thumb first time
                mindex.push(i);
                var href=mfiles[i].href.split("#")[0];
                href=href.substring(href.indexOf('/') + host.length + 3);
                mstring.push(href);
                //console.log(decodeURI(mstring[(mstring.length-1)]));
            }
        }
    }
    //console.log(mcount);
    for(var i=0;i<mindex.length;i++) {
        var name=mstring[i];
        var idx=mindex[i];
        // ajax name w callback ?
        //console.log("/ffthumber.php?p="+name+"&i="+idx);

        await ajaxThumbs(name,idx,function(data) {
            // callback
            if(data!="") {
                //console.log(data);
                if(IsJsonString(data)) {
                    var json=JSON.parse(data);
                    var targetidx=json['idx'];
                    var targetfile=mfiles[targetidx];
                    if(typeof targetfile!=='undefined') {
                        var targetthumb=json['thumb'];
                        targetfile.getElementsByTagName('img')[0].src="/"+targetthumb;
                    } else {
                        console.log("empty json");
                    }
                }
            }
        });
    }
}

var cACt;
var cACstarted=false;
var cACcurrent=0;
var cACduration=0;
var trigNextNow=false;
var trigNextCount=0;
var nextAudio="";
var nlts;
function checkAudioCont() {
    cACt=clearTimeout(cACt);

    if(trigNextNow) {
        var nts=new Date().getTime();
        var ndiff=nts-nlts;
        trigNextCount-=ndiff; // 1000mcs
        nlts=nts;

        if(trigNextCount<=0) {
            var nuri=encodeURIComponent(path+nextAudio);
            nuri=nuri.replace(/%2F/g,'/');
            window.location.href="/"+nuri;
            trigNextNow=false;
        }
    }
    if(!cACstarted) {
        //
        cACstarted=true;
        cACduration=$('followView').getElementsByClassName('media')[0].duration;
        localStorage.setItem('playnext',"1");
    }
    cACcurrent=$('followView').getElementsByClassName('media')[0].currentTime;
    //
    if(cACduration-cACcurrent<1) { // 1sec
        trigNextNow=true;
        trigNextCount=1000;
    }

    if($('playnext').checked) {
        cACt=setTimeout(function() { checkAudioCont(); },1000/10); // 10 fps
    } else {
        cACstarted=false;
        localStorage.removeItem('playnext');
    }
}

var listTrack=0;
var lista=[];
var listb=[];
async function init() {
    win_resize();
    bgscroll_enable();

    if(typeof audiotrig==="number") {
        if(audiotrig==1) {
            //
    for(var i=firsts;i<(trs.length-lasts);i++) {
        if(trs[i].parentElement==tbl) {
            var listv=trs[i].getElementsByClassName('listv')[0];
            var name=listv.getElementsByClassName('td')[1].innerHTML;
            var ext=name.substr(name.lastIndexOf(".")+1).toLowerCase();

            if(trs[i].getElementsByClassName('selected').length>0) {
                listTrack=1; // found selected
            } else {
                if(ext=="mp3" || ext=="wma" || ext=="midi" || ext=="ogg") {
                if(listTrack==0) { // before selected
                    lista.push(name);
                } else if(listTrack==1) { // after selected
                    listb.push(name);
                }
            }
            } // audio files only
        }
    }
            //console.dir(lista);
            //console.dir(listb);
            // if playnext checked once audio ends play listb[0]
            // if listb.length>0 or play lista.length[0] if lista.
            // length is more than 0 or do nothing (loop same anyway)
            // predetermined on init
            if(listb.length>0) {
                //
                nextAudio=listb[0];
            } else if(lista.length>0) {
                //
                nextAudio=lista[0];
            } else {
                $('audiocont').style.display="none";
            }
        } // audiotrig
    }
    if(localStorage.getItem('playnext')) {
        if(localStorage.getItem('playnext')=="1") {
            if($('playnext')) {
                $('playnext').checked=true;
                checkAudioCont();
            } else {
                localStorage.removeItem('playnext');
            }
        }
    }

    checkThumbs();

    //if($('code')) {
    if($('code')) {
        setTimeout(function() { window.scrollTo(0,0); },100);
        $('followView').style.top="0";
        fVy=0;
    } else {
        setTimeout(function() {
            var itm=document.getElementsByClassName('selected')[1];
            if(typeof itm!=='undefined') {
                var bcr=itm.getBoundingClientRect();
                var wH2=window.innerHeight/2;
                //console.dir(bcr);
                window.scrollTo(0,bcr.top-wH2);
                fVy=bcr.top-wH2;
                if(fVy<0) fVy=0;
                $('followView').style.top=(fVy)+"px";
                //$('followView').style.top=(bcr.top-wH2)+"px";
            }
            //
        },100);
    }

    if(window.location.hash) {
        setTimeout(function() {
            var view=window.location.hash.substr(1);
            if($(view)) {
                $(view).scrollIntoView();
                //alert(window.location.hash);
            }
        },100);
    }
}

function win_resize() {
    var winWidth=window.innerWidth;
    var winHeight=window.innerHeight;

    ifrmO=document.body.getElementsByClassName('dir')[0].offsetTop;
    ifrmH=winHeight-ifrmO;
    if(ifrmH<50) ifrmH=50;
    if($('ifrm')) {
        $('ifrm').style.minHeight=ifrmH+"px";
        $('ifrm').style.maxHeight=ifrmH+"px";
    }

    //alert(winWidth);
    if(typeof smallscreen!=='undefined') {
    if(winWidth<770) {
        if(!smallscreen) {
       		var style=document.createElement('style');
       		style.type="text/css";
       		var styhtm="/* smallscreen css */";
       		//styhtm+=".file, .dir { min-width: 64px; width: 64px; }";
       		styhtm+=".statsf { display: block; }";
       		styhtm+=".statsf2 { display: none; }";
       		styhtm+="#chat, #backdrop { width: 200px; }";
            //styhtm+="#container { padding: 64px 8px;  }";
            styhtm+=".embed { width: calc(100% - 200px) !important; margin-left: 200px; padding: 64px 8px !important; }";
            styhtm+="#dirbtn2 { display: none; }";
            styhtm+="#dirbtn { display: block; }";
       		style.innerHTML=styhtm;
       		document.getElementsByTagName('head')[0].appendChild(style);

            smallscreen=true;

            if($('comment')) {
                if($('comment').contentWindow) {
                    if(typeof $('comment').contentWindow.set_size==='function') {
                        $('comment').contentWindow.set_size('small');
                    }
                }
            }
        }
    } else {
        if(smallscreen) {
			var styles=document.getElementsByTagName('style');
       		for(var i=0;i<styles.length;i++) {
           		if(styles[i].innerHTML.indexOf('/* smallscreen css */')!=-1) {
               		styles[i].parentNode.removeChild(styles[i]);
               		break;
           		}
       		}
            
            smallscreen=false;

            if($('comment')) {
                if($('comment').contentWindow) {
                    if(typeof $('comment').contentWindow.set_size==='function') {
                        $('comment').contentWindow.set_size('big');
                    }
                }
            }
        }
    }
    }
}

var wrT;
window.onresize=function() {
    clearTimeout(wrT);
    wrT=setTimeout(function() { win_resize(); },100);
}

window.onscroll=function() {
    currentScroll=window.scrollY;
}

function bodytouch() {
    if(autoscrollOn) {
        if(scrollSpeed<0) {
            toggleScroll('Up');
        } else if(scrollSpeed>0) {
            toggleScroll('Down');
        }
    }
}

var aST;
var autoscrollOn=false;
var scrollSpeed=1.0;
var currentScroll=0;
function autoscroll() {
    clearTimeout(aST);

    if(autoscrollOn) {
        currentScroll+=scrollSpeed;

        window.scrollTo(0,currentScroll);

        if(scrollSpeed<0) {
            if(currentScroll+window.innerHeight<=0) {
                toggleScroll('Up');
                scrollSpeed=-1.0;
            }
         } else if(scrollSpeed>0) {
             if(currentScroll+window.innerHeight>=$('container').scrollHeight) {
                toggleScroll('Down');
                scrollSpeed=1.0;
             }
         }

        aST=setTimeout(function() { autoscroll(); },1000/60);
    }
}
function toggleScroll(x="") {
	var btnsel="";
	var btnoth="";
	var directionRunning=false;
	
	currentScroll=window.scrollY;
	
	if(x=="Up") {
	    //
	    btnsel="btnScrollU";
	    btnoth="btnScrollD";
	
	    $(btnoth).value="Down";
	
	    if(autoscrollOn && scrollSpeed<0) directionRunning=true;
	
	    if(scrollSpeed>0) scrollSpeed=0-scrollSpeed;
	    //scrollSpeed=-1.0;
	} else if(x=="Down") {
	    //
	    btnsel="btnScrollD";
	    btnoth="btnScrollU";
	
	    $(btnoth).value="Up";
	
	    if(autoscrollOn && scrollSpeed>0) directionRunning=true;
	
	    if(scrollSpeed<0) scrollSpeed=Math.abs(scrollSpeed);
	    //scrollSpeed=1.0;
	}
    if(directionRunning) {
        $(btnsel).value=x;
        $('scrollSpeed').style.display="none";
        autoscrollOn=false;
    } else {
        $(btnsel).value="Stop";
        $('scrollSpeed').innerHTML=scrollSpeed;
        $('scrollSpeed').style.display="inline-block";
        autoscrollOn=true;
        autoscroll();
    }
}
var scrollSpeedInc=[0.2,0.4,0.8,1.6,2.4];
var scrollSpeedIdx=0;
var lastchangeSpeedX=0;
var sSIT;
function changeSpeed(x) {
    var step=0.5;

    if(autoscrollOn) {
        //step=scrollSpeedInc[scrollSpeedIdx];
        //console.log('x: '+x+' , step: '+step);

        //if(lastchangeSpeedX==x) {
        //    if(scrollSpeedIdx<scrollSpeedInc.length-1) scrollSpeedIdx++;

        //    clearTimeout(sSIT);
        //    sSIT=setTimeout(function() {
        //        scrollSpeedIdx=0;
        //    },250);
        //}
        //
        //lastchangeSpeedX=x;
        step=1.0;

        if(x==1) { // increaseA (+)
            if(scrollSpeed>0) { // down active
                if(scrollSpeed<1.0) step=0.1;

                scrollSpeed=Math.round((scrollSpeed+step)*100)/100;
            } else if(scrollSpeed<0) { // up active
                if(scrollSpeed>-1.0) step=0.1;

                scrollSpeed=Math.round((scrollSpeed-step)*100)/100;
            }
        } else if(x==-1) { // decrease (-)
            if(scrollSpeed>0) { // down active
                if(scrollSpeed<=1.0) step=0.1;

                if((Math.round((scrollSpeed-step)*100)/100)>0) {
                    scrollSpeed=Math.round((scrollSpeed-step)*100)/100;
                }
            } else if(scrollSpeed<0) { // up active
                if(scrollSpeed>=-1.0) step=0.1;

                if((Math.round((scrollSpeed+step)*100)/100)<0) {
                    scrollSpeed=Math.round((scrollSpeed+step)*100)/100;
                }
            }
        }
        $('scrollSpeed').innerHTML=scrollSpeed;
    }
}
function showBar() {
    if($('control')) {
        $('control').style.opacity="1";
    }
}
function hideBar() {
    if($('control')) {
        $('control').style.opacity="0";
    }
}

function scrollbgto(y) {
    if(!bgscrollOn) {
        bgscroll_enable();
    }
    var ny=100-y;
    $('bg').style.top="-"+(y/10)+"%";
    //$('bg').style.top="-"+(ny/10)+"%";
}

var bgscrollOn=false;
function bgscroll_enable() {
    var styles=document.getElementsByTagName('style');
    for(var i=0;i<styles.length;i++) {
        if(styles[i].innerHTML.indexOf('/* scroll bg css */')!=-1) {
            styles[i].parentNode.removeChild(styles[i]);
            break;
        }
    }

    var style = document.createElement('style');
    style.type = 'text/css';

    var styhtm="/* scroll bg css  */";
    styhtm+="#bg { height: 110%; top: -0%; }";
    //styhtm+="#bg { height: 110%; top: -10%; transition: top 1s ease; }";
    style.innerHTML=styhtm;

    document.getElementsByTagName('head')[0].appendChild(style);
    bgscrollOn=true;
}

var myAjax;
var connectionout=0;
var ddDel=0;
var ddLatency=0;
async function ajaxThis(x,y,z,cb,l="//analiestar.com") {
    var xhr;
    if(window.XMLHttpRequest) xhr=new XMLHttpRequest();
    else                      xhr=new ActiveXObject("Microsoft.XMLHTTP");

    xhr.onreadystatechange=function() {
        if(xhr.readyState==4 && xhr.status==200) {
            if(typeof cb==='function') {
                cb(xhr.responseText);
            }
        }
    }
    //conlog('ajax out --> '+x);

    xhr.open("POST",l+"/ajax.php",true);
    //xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
    xhr.setRequestHeader("Content-Type","application/json");
    //xhr.send("setting="+x+"&value="+y+"&key="+z);
    xhr.send(JSON.stringify({setting: x, value: y, key: z}));
}
function pinghome() {
    ajaxThis('pinghome','filebrowser.anatwi.xyz\v/'+path+"/"+file,ip,function(data) {
        //
    });
}
pinghome();
