var httpHandle = (window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP"));
var ajaxQueue = [];
var ajaxBusy = false;

function ajaxPopQueue() {
    var nextRequest = ajaxQueue[0];
    ajaxQueue.splice(0, 1);
    ajaxRequest(nextRequest['method'], nextRequest['URL'], nextRequest['callback'], nextRequest['postData']);
}

function ajaxRequest(method, URL, callback, postData) {
    if(ajaxBusy) {
        ajaxQueue[ajaxQueue.length] =
            { 'method':method, 'URL':URL, 'callback':callback, 'postData':postData };
        return;
    }
    ajaxBusy = true;
    
    if(! postData) postData = null;
    httpHandle.open(method, URL, true);
    if(method == "POST")
        httpHandle.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    httpHandle.onreadystatechange = function() {
        callback();
        if(httpHandle.readyState == 4 && httpHandle.status == 200) {
            ajaxBusy = false;
            if(ajaxQueue.length < 1) return;
            setTimeout('ajaxPopQueue();', 0);
        }
    };
    httpHandle.send(postData);
}

function loadComments(postId) {
    ajaxRequest("GET", pathToRoot + "comments.php?action=show&post=" + encodeURIComponent(postId), function() {
        if(httpHandle.readyState == 4) {
            //log("HTTP status " + httpHandle.status);
            if(httpHandle.status == 200) {
                //log(httpHandle.responseText);
                showComments(postId);
            }
        }
    });
}

function showComments(postId) {
    var html = "";
    var count = 0;
    var commentNode = httpHandle.responseXML.firstChild.firstChild;
    while(commentNode) {
        if(commentNode.nodeType == 1) {
            var comment = {};
            var propNode = commentNode.firstChild;
            while(propNode) {
                if(propNode.nodeType == 1)
                    comment[propNode.nodeName] = propNode.firstChild.nodeValue;
                propNode = propNode.nextSibling;
            }
            html += renderComment(comment);
            count ++;
        }
        commentNode = commentNode.nextSibling;
    }
    var commentsText = (count > 0 ? count + " comentarii" : "Nici un comentariu");
    if(document.getElementById("comments")) {
        document.getElementById("comments").innerHTML = html;
        document.getElementById(postId + "_commentButton").style.display = "inline";
        document.getElementById(postId + "_commentCount").innerHTML = commentsText;
    }
    else {
        document.getElementById(postId + "_commentCount").innerHTML =
            "<a href='" + pathToRoot + postId + "#comentarii'>" + commentsText + "</a>";
    }
}

function renderComment(comment) {
    var author;
    if(comment.authorLink)
        author = "<a href='" + decodeAndEscape(comment['authorLink']) + "'>" + decodeAndEscape(comment['authorName']) + "</a>"
    else
        author = decodeAndEscape(comment['authorName']);
    
    var date = milisToHTML(comment['date']+"000");
    
    return "<div class='comment'>" +
            "<span class='commentMeta'>" +
                "<span class='commentAuthor'>" + author + "</span> " +
                "<span class='commentDate'>(" + date + ")</span>" +
            "</span>" +
            "<div class='commentContent'>" + decodeAndEscape(comment['content']) + "</div>" +
        "</div>";
}

function decodeAndEscape(data) {
    var str = decodeURIComponent(data);
    str = str.replace(/&/g, "&amp;");
    str = str.replace(/</g, "&lt;");
    str = str.replace(/>/g, "&gt;");
    str = str.replace(/\n/g, "<br>\n");
    return str;
}

function milisToHTML(raw) {
    var lunaRo = ['ianuarie', 'februarie', 'martie', 'aprilie', 'mai', 'iunie',
            'iulie', 'august', 'septembrie', 'octombrie', 'noiembrie', 'decembrie'];
    var date = new Date(raw-0);
    var year = date.getFullYear();
    var month = lunaRo[date.getMonth()];
    var day = date.getDate();
    var hour = ""+date.getHours(); while(hour.length < 2) hour = "0" + hour;
    var minute = ""+date.getMinutes(); while(minute.length < 2) minute = "0" + minute;
    return day + " " + month + " " + year + ", " + hour + ":" + minute;
}


function displayNewCommentInterface(postId) {
    document.getElementById(postId + "_commentButton").style.display = "none";
    document.getElementById("newComment").innerHTML =
        "<form onsubmit='try { sendComment(\"" + postId + "\"); } catch(e) {} return false;'>" +
            "<input class='newCommentField' id='newCommentAuthorName' size='20'> " +
            "<label for='newCommentAuthorName'>Nume</label> (trebuie)<br>" +
            
            "<input class='newCommentField' id='newCommentAuthorLink' size='20'> " +
            "<label for='newCommentAuthorLink'>URL</label><br>" +
            
            "<input class='newCommentField' id='newCommentAuthorMail' size='20'> " +
            "<label for='newCommentAuthorMail'>E-mail (nu apare pe site)</label><br>" +
            
            "<textarea class='newCommentField' id='newCommentContent' rows='8' cols='60'></textarea><br>" +
            "<input class='newCommentButton' type='submit' value='trimite'>" +
            "<input class='newCommentButton' type='button' value='răzgândire' onclick='abortNewCommentInterface(\"" + postId + "\");'>" +
            "<div id='newCommentError'></div>" +
        "</form>";
}

function abortNewCommentInterface(postId) {
    document.getElementById(postId + "_commentButton").style.display = "inline";
    document.getElementById("newComment").innerHTML = "";
}

function sendComment(postId) {
    document.getElementById("newCommentError").innerHTML = "";
    var authorName = document.getElementById('newCommentAuthorName').value;
    var authorLink = document.getElementById('newCommentAuthorLink').value;
    var authorMail = document.getElementById('newCommentAuthorMail').value;
    var content    = document.getElementById('newCommentContent'   ).value;
    var postData =
        "content="    + encodeURIComponent(encodeURIComponent(content   )) + "&" +
        "authorName=" + encodeURIComponent(encodeURIComponent(authorName)) + "&" +
        "authorLink=" + encodeURIComponent(encodeURIComponent(authorLink)) + "&" +
        "authorMail=" + encodeURIComponent(encodeURIComponent(authorMail));
    
    ajaxRequest("POST", pathToRoot + "comments.php?action=add&post="+encodeURIComponent(postId), function () {
        if(httpHandle.readyState == 4) {
            //log("HTTP status " + httpHandle.status);
            if(httpHandle.status == 500)
                document.getElementById("newCommentError").innerHTML = httpHandle.responseText;
            if(httpHandle.status == 400)
                document.getElementById("newCommentError").innerHTML = httpHandle.responseText;
            if(httpHandle.status == 200) {
                //log(httpHandle.responseText);
                document.getElementById("newComment").innerHTML =
                    "<div class='newCommentThankyou'>" +
//                        "Comentariul a fost dat la aprobare. Va apărea în curând pe site. Mulţumesc pentru contribuţie :)" +
                        "Comentariul a fost trimis. Mulţumesc pentru contribuţie :)" +
                    "</div>";
                setTimeout(function(){loadComments(postId);}, 0);
            }
        }
    }, postData);
}

