(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.push('<div class="postheader">');
        header.push('<p class="title"><span class="title">');
        header.push(decodeURIComponent(p.title));
        header.push('</span><span class="postnum">#');
        header.push(postnum);
        header.push('</span></p>');
        header.push('<p class="authorpostnum">Por <span class="author">');
        header.push(p.author);
        header.push('</span> el <span class="date">');
        header.push(postdate.toString());
        header.push('</span></p>');
        header.push('</div>')
        body.push('<div class="postbody">');
        body.push(decodeURIComponent(p.text));
        body.push('</div>');
        postsarray[toppost-postnum]='<div class="post">'+header.join("")+body.join("")+'</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';
});

}());