

/*
 * Creates a query string from a map of parameters.
 *
 * @param params a map of parameters to include in the query string
 */
function createQueryString(params) {
    var queryString = "", key;
    for (key in params) {
        queryString += key + "=" + params[key] + "&";
    }
    if (queryString.length > 0) {
        queryString = queryString.slice(0, queryString.length - 1);
    }
    return queryString;
}


/**
 * Returns the value if an input element with a given id
 * 
 * @param id Input element id
 */
function getInput(id) {
    var element, value;
    value = "";
    element = document.getElementById(id);
    if (element != null && element.type != null) {
        if (element.type === "text") {
            value = element.value;
        } else if (element.type === "checkbox") {
            value = element.checked;
        } else if (element.type === "textarea") {
            value = element.value;
        }
    }
    return value;
}

/**
 * Clears the value if an input element with a given id
 *
 * @param id Input element id
 */
function clearInput(id) {
    var element = document.getElementById(id);
    if (element != null && element.type != null) {
        if (element.type === "text") {
            element.value = "";
        } else if (element.type === "checkbox") {
            element.checked = false;
        } else if (element.type === "textarea") {
            element.value = "";
        }
    }
}

/**
 * Fetches the comments for a given content and displays these in the page's #comments element.
 *
 * @param contentId Content id
 * @param contextPath Site context path
 */
function getComments(contentId, contextPath) {
    debug("getComments(): contentId: " + contentId + ", contextPath: " + contextPath);
    var queryString = 'contentId=' + contentId;
    var xmlHttp = getXmlHttp();
    //Must use post to prevent ie from caching the comments.
    xmlHttp.open("POST", contextPath + '/oap/blog/listcomments.action');
    setXmlHttpPostHeaders(xmlHttp, queryString);
    xmlHttp.onreadystatechange=function() {
        if (xmlHttp.readyState == 4) {
            if(xmlHttp.status == 200) {
                debug("getComments(): Success! data: " + xmlHttp.responseText);
                document.getElementById("comments").innerHTML = xmlHttp.responseText;
            } else {
                debug("getComments(): Error! statusCode: " + xmlHttp.status);
                document.getElementById("comments").innerHTML = xmlHttp.status;
            }
        }
    };
    xmlHttp.send(queryString);
}

/**
 * Fetches the comments form for a given content and displays it in the page's #newcomment element.
 *
 * @param contentId Content id
 * @param contextPath Site context path
 */
function getCommentForm(contentId, contextPath) {
    debug("getCommentForm(): contentId: " + contentId + ", contextPath: " + contextPath);
    var queryString = 'contentId=' + contentId;
    var xmlHttp = getXmlHttp();
    xmlHttp.open("POST", contextPath + '/oap/blog/commentform');
    setXmlHttpPostHeaders(xmlHttp, queryString);
    xmlHttp.onreadystatechange=function() {
        if (xmlHttp.readyState == 4) {
            if(xmlHttp.status == 200) {
                debug("getCommentForm(): Success! data: " + xmlHttp.responseText);
                document.getElementById("newcomment").innerHTML = xmlHttp.responseText;
            } else {
                debug("getCommentForm(): Error! statusCode: " + xmlHttp.status);
                document.getElementById("newcomment").innerHTML = xmlHttp.status;
            }
        }
    };
    xmlHttp.send(queryString);
}

/**
 * Saves a user comment
 *
 * @param contentId
 * @param contextPath
 */
function addComment(contentId, contextPath) {
    debug("addComment(): contentId: " + contentId + ", contextPath: " + contextPath);
    document.getElementById("mod_status").style.display = 'none';
    var comment = { };
    comment.contentId = contentId;
    comment.username = getInput("comment_username");
    comment.email = getInput("comment_email");
    comment.title = getInput("comment_title");
    comment.text = getInput("comment_text");
    comment.moderator = getInput("comment_moderator");

    var xmlHttp = getXmlHttp();
    var queryString = createQueryString(comment);
    debug("addComment(): queryString: " + queryString);
    xmlHttp.open("POST", contextPath + "/oap/blog/addcomment.action", true);
    //Send the proper header information along with the request
    setXmlHttpPostHeaders(xmlHttp, queryString);
    xmlHttp.onreadystatechange=function() {
        if (xmlHttp.readyState == 4) {
            if(xmlHttp.status == 200) {
                debug("addComment(): Success! data: " + xmlHttp.responseText);
                var resp = eval('(' + xmlHttp.responseText + ')');
                debug("addComment(): response: " + resp + ", response.successMsg: " + resp.successMsg + ", response.errorMsg: " + resp.errorMsg);
                var statusContainer = document.getElementById("newcomment_status");
                if (resp.errorMsg) {
                    statusContainer.className += ' error';
                    statusContainer.innerHTML = resp.errorMsg;
                } else {
                    statusContainer.innerHTML = resp.successMsg;
                    clearInput("comment_username");
                    clearInput("comment_email");
                    clearInput("comment_title");
                    clearInput("comment_text");
                    clearInput("comment_moderator");
                }
                statusContainer.style.display = 'block';
                getComments(contentId, contextPath);
            } else {
                debug("addComment(): Error! statusCode: " + xmlHttp.status);
                document.getElementById("newcomment_status").innerHTML = "Kommentaren kunne ikke lagres. Prøv igjen senere.";
            }
        }
    };
    xmlHttp.send(queryString);
}

/**
 *
 * @param id
 * @param contentId
 * @param contextPath
 */
function getModeratorOptions(id, contentId, contextPath) {
    debug("getModOptions(): id: " + id + ", contentId: " + contentId + ", contextPath: " + contextPath);
    var options = { };
    options.url = contextPath + '/oap/blog/moderator';
    options.data = {};
    options.data.id = id;
    options.data.contentId = contentId;
    return options;
}

/**
 *
 * @param id
 * @param contentId
 * @param contextPath
 */
function approveComment(id, contentId, contextPath) {
    debug("approveComment(): id: " + id + ", contentId: " + contentId + ", contextPath: " + contextPath);
    document.getElementById("newcomment_status").style.display = 'none';
    var options = getModeratorOptions(id, contentId, contextPath);
    options.data.action = 'approve';
    var xmlHttp = getXmlHttp();
    var queryString = createQueryString(options.data);
    debug("approveComment(): queryString: " + queryString);
    xmlHttp.open("POST", options.url, true);
    setXmlHttpPostHeaders(xmlHttp, queryString);
    xmlHttp.onreadystatechange=function() {
        if (xmlHttp.readyState == 4) {
            var statusContainer = document.getElementById("mod_status");
            if(xmlHttp.status == 200) {
                statusContainer.innerHTML = xmlHttp.responseText;
            } else {
                statusContainer.className += ' error';
                statusContainer.innerHTML = xmlHttp.status;
            }
            statusContainer.style.display = 'block';
            getComments(contentId, contextPath);
        }
    };
    xmlHttp.send(queryString);
}

function deleteComment(id, contentId, contextPath) {
    debug("deleteComment(): id: " + id + ", contentId: " + contentId + ", contextPath: " + contextPath);
    document.getElementById("newcomment_status").style.display = 'none';
    var options = getModeratorOptions(id, contentId, contextPath);
    options.data.action = 'delete';
    var xmlHttp = getXmlHttp();
    var queryString = createQueryString(options.data);
    debug("deleteComment(): queryString: " + queryString);
    xmlHttp.open("POST", options.url, true);
    setXmlHttpPostHeaders(xmlHttp, queryString);
    xmlHttp.onreadystatechange=function() {
        if (xmlHttp.readyState == 4) {
            var statusContainer = document.getElementById("mod_status");
            if(xmlHttp.status == 200) {
                statusContainer.innerHTML = xmlHttp.responseText;
            } else {
                statusContainer.className += ' error';
                statusContainer.innerHTML = xmlHttp.status;
            }
            statusContainer.style.display = 'block';
            getComments(contentId, contextPath);
        }
    };
    xmlHttp.send(queryString);
}

function refreshLoop(contentId, contextPath) {                  
    debug("refreshLoop(): contentId: " + contentId + ", contextPath: " + contextPath);
    getComments(contentId, contextPath);
    //setTimeout(eval("refreshLoop(contentId, contextPath)"), 300000); // refresh every 5 minutes
}

/**
 * Creates an XmlHttpRequest object.
 */
function getXmlHttp() {
    return window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("MSXML2.XMLHTTP.3.0");
}

/**
 * Prints debug to Firebug's console
 * @param msg
 */
function debug(msg) {
    if ( ("console" in window) && ("firebug" in console) ) {
        console.debug(msg);
    }
}

/**
 * 
 * @param xmlHttp
 */
function setXmlHttpPostHeaders(xmlHttp, queryString) {
    xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xmlHttp.setRequestHeader("Content-length", queryString.length);
}

