/*
 * Copyright 1997-2009 Day Management AG
 * Barfuesserplatz 6, 4001 Basel, Switzerland
 * All Rights Reserved.
 *
 * This software is the confidential and proprietary information of
 * Day Management AG, ("Confidential Information"). You shall not
 * disclose such Confidential Information and shall use it only in
 * accordance with the terms of the license agreement you entered into
 * with Day.
 */

/**
 * Utility functions for comments components.
 */

var CQ_collab_comments_loadedForms = {};
var CQ_collab_comments_defaultMessage = ""; // overlay in page


function CQ_collab_comments_toggleForm(buttonId, formId, url) {
    var form = document.getElementById(formId);
    var button = document.getElementById(buttonId);
    if (!CQ_collab_comments_loadedForms[formId]) {
        var request = document.all ? new ActiveXObject("Microsoft.XMLHTTP") :
                      new XMLHttpRequest();
        try {
            request.open("GET", url, true);
            request.onreadystatechange = function() {
                form.innerHTML = request.responseText;
            };
            request.send(null);
        } catch (e) {
            alert("Error loading form: " + url);
        }
        CQ_collab_comments_loadedForms[formId] = true;
    }
    var hidden = form.style.display != "block";
    form.style.display = hidden ? "block" : "none";
    button.innerHTML = hidden ? "Cancel" : "Reply";
}

function CQ_collab_comments_handleOnFocus(el) {
    if(el.value == CQ_collab_comments_getDefaultMessage()) {
        el.value = "";
    }
    el.style.color = "#333";
}

function CQ_collab_comments_handleOnBlur(el) {
    if(el.value == "") {
        el.value = CQ_collab_comments_getDefaultMessage();
        el.style.color = "#888";
    }
    else {
        el.style.color = "#333";
    }
}

function CQ_collab_comments_validateFields(id) {
    // Validate text
    var message = document.getElementById(id + "-text");
    if (message.value == "" || message.value == CQ_collab_comments_getDefaultMessage()) {
        CQ_collab_comments_showError('Please enter a comment', id + "-text");
        return false;
    }
    var check = document.getElementById(id + "-id");
    if (!check) {
        var form = document.getElementById(id + "-form");
        check = document.createElement("input");
        check.type = "hidden";
        check.name = "id";
        check.value = new Date().valueOf();
        form.appendChild(check);
    }
    return true;
}

function CQ_collab_comments_validateSubmit(id) {
    return CQ_collab_comments_validateFields(id);
}

function CQ_collab_comments_showError(msg, id) {
    var errorElem = document.getElementById(id + "-error");
    if (!errorElem) {
        alert(msg);
    } else {
        errorElem.innerHTML = msg;
    }
}

function CQ_collab_comments_getDefaultMessage() {
    return CQ_collab_comments_defaultMessage;
}
