String.prototype.trim = function() {
return this.replace(/^\s*|\s*$/g, "");
}

function toolbarmove(id) {
    if (toolbar == id)
    {
        ajax_loadContent('panel','blank');
        toolbar = 0;
    }
    else
    {
        toolbar = id;
        ajax_loadContent('panel','blank');
        document.getElementById("panel").style.left = (id - 1) * 100 -1;
        switch (id) {
            case 0:
                ajax_loadContent('panel','blank');
                break;
            case 1:
                ajax_loadContent("panel","fileup.php", true);
                break;
            case 2:
                ajax_loadContent("panel","chan.php");
                break;
			case 3:
                ajax_loadContent("panel","pref.php", true);
                break;
        }
    }
}

function setCategory(id)
{
    cat = id;
    createCookie("cat",cat,365);
    reloadContent();
}

function reloadContent()
{
    removeAllChildren(document.getElementById("filelist"));
    loadStat = 0;
    noMoreFiles = false;
}

function submitPrefs()
{
    var reload = false;
    if (readCookie('minrating') != encodeURI(document.getElementById('prefs').minrating.value) ||
        readCookie('timezone') != encodeURI(document.getElementById('prefs').timezone.value))
        reload = true;
    createCookie('entries',encodeURI(document.getElementById('prefs').entries.value), 365);
    createCookie('refresh',encodeURI(document.getElementById('prefs').refresh.value * 1000), 365);
    createCookie('username',encodeURI(document.getElementById('prefs').username.value), 365);
    createCookie('minrating',encodeURI(document.getElementById('prefs').minrating.value), 365);
    createCookie('timezone',encodeURI(document.getElementById('prefs').timezone.value), 365);
    reloadCookie();
    toolbarmove(0);
    if (reload) reloadContent();
}

function processDisplayMore(){
    var myajax=ajaxpack.ajaxobj
    if (myajax.readyState == 4){
        var xml = myajax.responseXML.documentElement;
        var f = xml.getElementsByTagName("item");
        loadTotal = xml.getElementsByTagName("catCnt")[0].firstChild.nodeValue;
        catName = xml.getElementsByTagName("catName")[0].firstChild.nodeValue;
        var x = document.createElement('div');
        x.id = 'updateblock';

        for (var i=0; i < f.length; i++)
            x.appendChild(createHaxElement(f[i]));

        document.getElementById("filelist").appendChild(x);

        if (loadStat + numEntry < loadTotal)
            loadStat += numEntry;
        else
        {
            loadStat = loadTotal;
            x = document.createElement('div');
            x.className = 'endbar';
            document.getElementById("filelist").appendChild(x);
            noMoreFiles = true;
        }

        document.getElementById('status2').innerHTML = '@<b>' + catName + '</b> (' + loadStat + "/" + loadTotal + " posts)";
        processing = false;
    }
}

function processComment(){
    var myajax=ajaxpack.ajaxobj
    if (myajax.readyState == 4 && myajax.status==200){
        var id = myajax.responseText;
        var comment = document.getElementById('comment-' + id);
        if (!processing)
        {
            processing = true;
            ajaxpack.postAjaxRequest('get.php', 'req=-1&after=' + getLastId(), processUpdate, 'xml');
        }
    }
}

function processPost(){
    var myajax=ajaxpack.ajaxobj
    if (myajax.readyState == 4 && myajax.status==200){
        if (!processing)
    {
        processing = true;
            ajaxpack.postAjaxRequest('get.php', 'req=-1&after=' + getLastId(), processUpdate, 'xml');
    }
    }
}

function processUpdate(){
    var myajax=ajaxpack.ajaxobj
    if (myajax.readyState == 4 && myajax.status==200){
        var xml = myajax.responseXML.documentElement;
        var users = xml.getElementsByTagName("onlineUsers")[0].firstChild.nodeValue;
        var message = (xml.getElementsByTagName("message")[0].firstChild ? xml.getElementsByTagName("message")[0].firstChild.nodeValue : null);
        var f = xml.getElementsByTagName("item");

        for (var i=0;i<f.length;i++)
        {
            var replyid = getNodeValue(f[i],'replyid');
            var postid = getNodeValue(f[i],'postid');
            if(getNodeValue(f[i],'type') == 'topLevel')
            {
                if (document.getElementById('file-' + postid))
                {
                    //has already been displayed. wtf?
                }
                else
                {
                    var refDiv = document.getElementById("filelist").getElementsByTagName("div").item(0);
                    document.getElementById("filelist").insertBefore(createHaxElement(f[i]), refDiv);
                    loadStat += 1;
                    loadTotal += 1;
                }
            }
            else if (document.getElementById('file-' + replyid))
            {
                var comment = document.getElementById('comment-' + replyid);
                var last = comment.lastChild;
                if (last.className == "postform")
                {
                    comment.insertBefore(createHaxElement(f[i]), last);
                }
                else
                {
                    redrawComments(replyid);
                }
            }
            else
            {
                //not on screen.  do nothing for now.
            }
        }
        document.getElementById('status').innerHTML = users + " user" + (users > 1 ? "s" : "") +" online" + (message ? " ("+ message +")": "") +", ";
    processing = false;
    }
}

function processShowComments(){
    var myajax=ajaxpack.ajaxobj
    if (myajax.readyState == 4 && myajax.status==200){
        var xml = myajax.responseXML.documentElement;
        var f = xml.getElementsByTagName("item");
        var replyid = getNodeValue(f[0],'replyid');

        var x = document.getElementById("comment-" + replyid)
        removeAllChildren(x);

        if (f.length > 0)
        {
            var a = document.createElement('a');
            a.setAttribute('href','');
            a.setAttribute('onClick','hideComments('+replyid+');return false;');
            a.appendChild(document.createTextNode('Hide replies'));
            x.appendChild(a);
        }

        for (var i=0;i<f.length;i++)
            x.appendChild(createHaxElement(f[i]));

        x.appendChild(createCommentForm(replyid));
    processing = false;
    }
}

function processShowCommentsForm(id){
    var x = document.getElementById("comment-" + id)
    removeAllChildren(x);
    x.appendChild(createCommentForm(id));
}

function processHideComments(){
    var myajax=ajaxpack.ajaxobj
    if (myajax.readyState == 4 && myajax.status==200){
        var xml = myajax.responseXML.documentElement;
        var f = xml.getElementsByTagName("item")[0];
        var postid = getNodeValue(f,'postid');
        var x = document.getElementById("comment-" + postid)
        removeAllChildren(x);

        x.appendChild(createCommentElement(f));
    processing = false;
    }
}

function createCommentForm(id){
    var hax = document.createElement('div');
    hax.className = 'postform';
    var form = document.createElement('div');
    form.innerHTML = "<object classid=\"clsid:d27cdb6e-ae6d-11cf-96b8-444553540000\" codebase=\"http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0\" width=\"520\" height=\"140\" id=\"fileupcomment\" align=\"middle\"><param name=\"allowScriptAccess\" value=\"sameDomain\" /><param name=\"movie\" value=\"fileupcomment.swf\" /><param name=\"quality\" value=\"high\" /><param name=\"bgcolor\" value=\"#f8f8f8\" /><embed src=\"fileupcomment.swf?username=" + username + "&commentid=" + id + "\" quality=\"high\" bgcolor=\"#f8f8f8\" width=\"520\" height=\"140\" name=\"fileupcomment\" align=\"middle\" allowScriptAccess=\"sameDomain\" type=\"application/x-shockwave-flash\" pluginspage=\"http://www.macromedia.com/go/getflashplayer\" /></object>";
    hax.appendChild(form);
    var a = document.createElement('a');
    a.setAttribute('href','');
    a.setAttribute('onClick','hideComments('+id+');if (_getWindowHeight() < document.getElementById("file-' + id + '").offsetHeight) scroll(0,document.getElementById("file-' + id + '").offsetTop - 30);return false;');
    a.appendChild(document.createTextNode('Hide replies'));
    hax.appendChild(a);
    return hax;
}

function createHaxElement(f)
{
    var postid = getNodeValue(f,'postid');
    var date = getNodeValue(f,'date');
    var description = getNodeValue(f,'description');
    var ratingcontent = getNodeValue(f,'rating');
    var type = getNodeValue(f,'type');
    var link = getNodeValue(f,'link');
    var image = getNodeValue(f,'image');
    var thumbnail = getNodeValue(f,'thumbnail');
    var filesize = Math.round(getNodeValue(f,'filebytes')/1024);
    var commentcount = getNodeValue(f,'commentcount');
    var replyid = getNodeValue(f,'replyid');
    var category = getNodeValue(f,'category');

    //<div id="file-434" class="hax">
    var hax = document.createElement('div');
    hax.className = (type == 'topLevel' ? 'hax' : 'replylayer2');
    if (postid > last)
        hax.className += "-new";
    hax.id = 'file-' + postid;

    var tablerow = document.createElement('div');
    tablerow.className = 'tablerow';
    hax.appendChild(tablerow);

    if (image || type == 'topLevel')
    {
        //thumbnail
        var a = document.createElement('a');
        a.setAttribute('href',link);
        a.setAttribute('target','_blank');
        if (type == 'topLevel')
            a.setAttribute('onClick','getElementById("file-' + postid + '").setAttribute("class","hax");');
        tablerow.appendChild(a);

        var jax = document.createElement('div');
        jax.className = 'jax';
        a.appendChild(jax);

        var jaximg = document.createElement('img');
        jaximg.setAttribute('src',(thumbnail?thumbnail:'img/noimg.png'));
        jaximg.setAttribute('width','140');
        jax.appendChild(jaximg);
    }
    //main contents
    var max = document.createElement('div');
    max.className = (type == 'topLevel' ? 'max' : 'max-comment');
    tablerow.appendChild(max);

    //heading
    var h3 = document.createElement('h3');
    max.appendChild(h3);

    if (filesize > 0 || type == 'topLevel')
    {
        var a = document.createElement('a');
        a.setAttribute('href',link);
        a.setAttribute('target','_blank');
        if (type == 'topLevel')
            a.setAttribute('onClick','getElementById("file-' + postid + '").setAttribute("class","hax");');
        a.appendChild(document.createTextNode(getNodeValue(f,'title')));
        h3.appendChild(a);

        h3.appendChild(document.createTextNode(' '));
        var small = document.createElement('small');
        small.appendChild(document.createTextNode(filesize + "kb"));
        h3.appendChild(small);
        h3.appendChild(document.createTextNode(' - '));
    }

    var b = document.createElement('b');
    b.appendChild(document.createTextNode(getNodeValue(f,'author')));
    h3.appendChild(b);

    h3.appendChild(document.createTextNode(' ' + date));

    var rating = document.createElement('span');
    rating.className = 'rating';
    rating.id = 'rating-' + postid;
    h3.appendChild(rating);

    var ratingtext = document.createElement('span');
    ratingtext.innerHTML = ratingcontent;
    rating.appendChild(ratingtext);

    var ratingbuttons = document.createElement('span');

    rating.appendChild(ratingbuttons);

    var a = document.createElement('a');
    a.setAttribute('href',"");
    a.setAttribute('onClick','ajax_loadContent("rating-'+postid+'","rate.php?pid='+postid+'&rate=1"); return false;');
    var img = document.createElement('img');
    img.setAttribute('src','img/pos.png');
    a.appendChild(img);
    ratingbuttons.appendChild(a);

    ratingbuttons.appendChild(document.createTextNode(' '));
    
    var a = document.createElement('a');
    a.setAttribute('href',"");
    a.setAttribute('onClick','ajax_loadContent("rating-'+postid+'","rate.php?pid='+postid+'&rate=-1"); return false;');
    var img = document.createElement('img');
    img.setAttribute('src','img/neg.png');
    a.appendChild(img);
    ratingbuttons.appendChild(a);

    var cat = document.createElement('span');
    cat.className = 'category';
    cat.innerHTML = category;
    max.appendChild(cat);

    var desc = document.createElement('div');
    desc.className = 'comment';
    desc.innerHTML = description;
    max.appendChild(desc);


    tablerow.appendChild(max);
    if (type == 'topLevel')
    {
        max.appendChild(createCommentElement(f));
    }
    return hax;
}

function createCommentElement(f)
{
    var postid = getNodeValue(f,'postid');
    var commentcount = getNodeValue(f,'commentcount');

    var comments = document.createElement('div');
    comments.className = 'comments';
    comments.id = 'comment-' + postid;

    if (commentcount > 0)
    {
        var thumbs = f.getElementsByTagName('commentthumbs')[0].getElementsByTagName('c');
        if (thumbs.length > 0)
        {
            var replylayer = document.createElement('div');
            replylayer.className = 'replylayer';
            comments.appendChild(replylayer);

            for (var j=0;j<thumbs.length;j++)
            {
                var sthumb = getNodeValue(thumbs[j],'thumbnail');
                var simage = getNodeValue(thumbs[j],'image');

                var a = document.createElement('a');
                a.setAttribute('href',simage);
                a.setAttribute('target','_blank');
                a.setAttribute('onClick','getElementById("file-' + postid + '").setAttribute("class","hax");');

                var img = document.createElement('img');
                img.setAttribute('src',sthumb);
                img.setAttribute('width','60');
                a.appendChild(img);

                replylayer.appendChild(a);

                if ((j+1) % 8 == 0)
                    replylayer.appendChild(document.createElement('br'));
            }
        }

        var a = document.createElement('a');
        a.setAttribute('href','');
        a.setAttribute('onClick','showComments('+postid+'); return false;');
        a.appendChild(document.createTextNode('View all replies (' + commentcount + ')'));
        comments.appendChild(a);
    }
    else
    {
        var a = document.createElement('a');
        a.setAttribute('href','');
        a.setAttribute('onClick','processShowCommentsForm('+postid+'); return false;');
        a.appendChild(document.createTextNode('Post a reply'));
        comments.appendChild(a);
    }

    return comments;
}

function showComments(id)
{
    processing = true;
    ajaxpack.postAjaxRequest("get.php", "req=" + id, processShowComments, "xml");
}

function redrawComments(id)
{
    processing = true;
    ajaxpack.postAjaxRequest("get.php", "count=1&req=-1&after=" + (id - 1), processHideComments, "xml");
}

function hideComments(id)
{
    redrawComments(id);
}

function removeAllChildren(obj)
{
    while(obj.firstChild)
        obj.removeChild(obj.firstChild);
}

function getNodeValue(obj,tag)
{
    if(obj.getElementsByTagName(tag)[0].firstChild)
        return obj.getElementsByTagName(tag)[0].firstChild.nodeValue;
    else
        return "";
}

function createCookie(name,value,days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = "; expires="+date.toGMTString();
    }
    else var expires = "";
    document.cookie = name+"="+value+expires+"; path=/";
    return value;
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;

}
function eraseCookie(name) {
    createCookie(name,"",-1);
}

function reloadCookie(){
    numEntry = (readCookie("entries") ? parseInt(readCookie("entries")) : createCookie("entries",numEntry,365));
    checkNewInterval = (readCookie("refresh") ? parseInt(readCookie("refresh")) : createCookie("refresh",checkNewInterval,365));
    minRating = (readCookie("minrating") ? parseInt(readCookie("minrating")) : createCookie("minrating",minRating,365));
    username = (readCookie("username") ? readCookie("username") : createCookie("username","",1));
    timezone = (readCookie("timezone") ? readCookie("timezone") : createCookie("timezone","+9",365));
    cat = (readCookie("cat") ? readCookie("cat") : createCookie("cat","-1",365));
}

function updatePage(){
    if (!noMoreFiles && !processing && mouseState == "up" && getPageHeight() - getScrollHeight() < preloadDistance) {
        processing = true;
        ajaxpack.postAjaxRequest("get.php", "req=-3&start=" + loadStat + "&count=" + numEntry + "&lastsession=" + last, processDisplayMore, "xml");
    }
    setTimeout("updatePage()", checkScrollInterval);
}

function checkForNew(){
    if (!processing)
    {
        processing = true;
		ajaxpack.postAjaxRequest('get.php', 'req=-1&after=' + getLastId(), processUpdate, 'xml');
    }
    setTimeout("checkForNew()", checkNewInterval);
}

function getLastId(){
    if (readCookie("last"))
        return readCookie("last");
    return null;
}

function onMouseDown(e ){
    mouseState = "down";
}

function onMouseUp(){
    mouseState = "up";
}



function init(){
    document.onmousedown = onMouseDown;
    document.onmouseup = onMouseUp;

    reloadCookie();
    last = (readCookie("last") ? parseInt(readCookie("last")) : createCookie("last",0,365));

    setTimeout("updatePage()", 50);
    setTimeout("checkForNew()",checkNewInterval);

    useStyleAgain('style');
}


function getPageHeight(){
  var y;
  var test1 = document.body.scrollHeight;
  var test2 = document.body.offsetHeight;
  if (test1 > test2) {
    y = document.body.scrollHeight;
  } else {
      y = document.body.offsetHeight;
  }
  return parseInt(y);
}


function _getWindowHeight(){
  if (self.innerWidth) {
        frameWidth = self.innerWidth;
        frameHeight = self.innerHeight;
  } else if (document.documentElement && document.documentElement.clientWidth) {
    frameWidth = document.documentElement.clientWidth;
    frameHeight = document.documentElement.clientHeight;
  } else if (document.body) {
    frameWidth = document.body.clientWidth;
    frameHeight = document.body.clientHeight;
  }
  return parseInt(frameHeight);
}

function getScrollHeight(){
  var y;
  // all except Explorer
  if (self.pageYOffset) {
      y = self.pageYOffset;
  } else if (document.documentElement && document.documentElement.scrollTop) {
      y = document.documentElement.scrollTop;
  } else if (document.body) {
      y = document.body.scrollTop;
  }
  return parseInt(y)+_getWindowHeight();
}

function addNewEntry(){
  alert(document.getElementById("comment-419"));
}

