(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();
}

function getvar(name) {
        var re=new RegExp("[?&]"+name+"=\([^&]*\)");
        var value=window.location.search.match(re);
        if(value===null || value.length<2)
                return(name+"=");
        return(name+"="+value[1]);
}

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

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

document.getElementById("account").href='/account.html?'+getvar("s");

var postsarray=[];
var functionsarray=[];
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=[];
        var comments=[];
        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>');
        comments.push('<div class="comments">');
        for(var i in p.comments) {
                var c=p.comments[i];
                comments.push('<div class="comment">');
                comments.push('<div class="commentheader">');
                var commentdate=new Date(0);
                commentdate.setUTCSeconds(parseInt(c.date));
                comments.push('<span class="commentauthor">');
                comments.push(decodeURIComponent(c.author));
                comments.push('</span>&nbsp;<span class="commentdate">');
                comments.push(commentdate.toString());
                comments.push('</span></div><div class="commenttext">');
                comments.push(decodeURIComponent(c.text));
                comments.push('</div>');
                comments.push('</div>');
        }
        comments.push('<div class="commentbox"><p class="commentbox">');
        comments.push('<input type="text" class="inputcomment" id="comment'+(toppost-postnum)+'" placeholder="Escribir comentario..."/>');
        comments.push('<input type="button" class="inputsendcomment" id="commentbutton'+(toppost-postnum)+'" value="Enviar"/>');
        comments.push('</p></div></div>');
        postsarray[toppost-postnum]='<div class="post">'+header.join("")+body.join("")+'</div>'+comments.join("") /*+JSON.stringify(p) */;
        functionsarray[toppost-postnum]=function() {
                var requri=[];
                requri.push("/newcomment?");
                requri.push(getvar("s"));
                requri.push("&n="+postnum);
                requri.push("&t=");
                requri.push(encodeURIComponent(document.getElementById("comment"+(toppost-postnum)).value));
                request(requri.join(""),function(r) {
                        refreshpost(postnum);
                },function() {});
        }
}

function clearpost(postnum) {
        postsarray[toppost-postnum]=undefined;
        functionsarray[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");
        for(var i=0;i<postsperpage;i++) {
                if(functionsarray[i]==undefined)
                        continue;
                document.getElementById("commentbutton"+i).onclick=functionsarray[i];
        }
}

function refreshpost(postnum) {
        request("/getpost?"+getvar("s")+"&n="+postnum, function(r1) {
                changepost(postnum,r1);
                displayposts();
        },function() {
                clearpost(postnum);
        });
}

function refreshprevnext() {
        var nav=[];
        var curpage;
        var totalpages;
        var inc;
        var maxinc=(Number(lastpost)/postsperpage)/2;
        nav.push('<span class="paginas">P&aacute;gina:');
        curpage=Math.floor(((Number(lastpost)-Number(toppost))/postsperpage))+1;
        totalpages=Math.floor((Number(lastpost)-1)/postsperpage)+1;
        for(var page=1;(Number(lastpost)-(page-1)*postsperpage)>0;page+=inc) {
                if(Number(toppost)<=(Number(lastpost)-(page-1)*postsperpage) &&
                   Number(toppost)>(Number(lastpost)-(page)*postsperpage)) {
                        nav.push(" "+page);
                } else {
                        nav.push(' <a href="');
                        nav.push('/posts.html?');
                        nav.push(getvar("s"));
                        if(page>1) {
                                nav.push('&p=');
                                nav.push(Number(toppost)-(page-1)*postsperpage);
                        }
                        nav.push('" class="pagenum">');
                        nav.push(page);
                        nav.push('</a>');
                }
                if(Math.abs(curpage-page)<5) {
                        inc=1;
                } else {
                        inc=Math.floor((Math.abs(curpage-page)/totalpages)*maxinc);
                        inc=(inc<=0)?1:inc;
                        if(page<totalpages && (page+inc)>totalpages)
                                inc=totalpages-page;
                }
        }
        nav.push('</span> ');
        nav.push('<span class="newerolder">');
        if(toppost<lastpost) {
                nav.push(' <a href="');
                nav.push('/posts.html?');
                nav.push(getvar("s"));
                if((Number(toppost)+Number(postsperpage))<lastpost) {
                        nav.push('&p=');
                        nav.push(Number(toppost)+Number(postsperpage));
                }
                nav.push('" class="pagenum">Posts m&aacute;s nuevos</a>');
        } else
                nav.push("Posts m&aacute;s nuevos");
        nav.push(" | ");
        if((Number(toppost)-Number(postsperpage))>0) {
                nav.push(' <a href="');
                nav.push('/posts.html?');
                nav.push(getvar("s"));
                nav.push('&p=');
                nav.push(Number(toppost)-Number(postsperpage));
                nav.push('" class="pagenum">Posts m&aacute;s antiguos</a>');
        } else
                nav.push('Posts m&aacute;s antiguos');
        nav.push('</span>');
        document.getElementById("prevnext").innerHTML=nav.join("");
}

request("/lastpost?"+getvar("s"),function(r) {
        var p;
        lastpost=r;
        toppost=r
        p=getvar("p");
        if(p.length>2)
                toppost=Number(p.slice(2));
        if(toppost<0 || toppost>lastpost)
                toppost=lastpost;
        refreshprevnext();
        for(var i=0;i<postsperpage;i++)
                refreshpost(toppost-i);
},function() {
        document.getElementById("posts").innerHTML='There are no posts';
});

}());