(function () {
"use strict";

function request(querytext, func, errorfunc) {
        var req = new XMLHttpRequest();
        req.onreadystatechange = function() {
                if (req.readyState !== 4) {
                        return;
                }
                if (req.status !== 200) {
                        errorfunc();
                        return;
                }
                func(req.responseText);
        };
        req.open("GET",querytext);
        req.send();
}

gotonewpost.onclick = function(e) {
        window.location="/newpost.html"+window.location.search
};

document.getElementById("posts").innerHTML='Loading posts...';

var postsarray=[];
var lastpost=-1;
var toppost=-1;
var postsperpage=5;

function changepost(postnum,data) {
        var p=JSON.parse(data);
        var postdate=new Date(0);
        postdate.setUTCSeconds(parseInt(p.date));
        var header="";
        var body="";
        header='<div class="postheader"><p class="authorpostnum">&nbsp;<span class="author">Autor: '+p.author+'</span><span class="postnum">#'+postnum+'</span></p><p class="date">Fecha: '+postdate.toString()+'</p></div>';
        body='<div class="postbody">'+decodeURIComponent(p.text)+'</div>';
        postsarray[toppost-postnum]='<div class="post">'+header+body+'</div>' /*+JSON.stringify(p) */;
}

function clearpost(postnum) {
        postsarray[toppost-postnum]=undefined;
}

function displayposts() {
        var contents=[]
        for(var i=0;i<postsperpage;i++) {
                if(postsarray[i]==undefined)
                        continue;
                contents.push(postsarray[i]);
        }
        if(contents.length==0)
                contents[0]='No posts loaded';
        document.getElementById("posts").innerHTML=contents.join("\n");
}

function refreshpost(postnum) {
        request("/getpost"+window.location.search+"&n="+postnum, function(r1) {
                changepost(postnum,r1);
                displayposts();
        },function() {
                clearpost(postnum);
        });
}


request("/lastpost"+window.location.search,function(r) {
        lastpost=r;
        toppost=r;
        for(var i=0;i<postsperpage;i++)
                refreshpost(r-i);
},function() {
        document.getElementById("posts").innerHTML='There are no posts';
});

}());