/*
 * 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
var CQ_collab_comments_requireLogin = false;


function CQ_collab_comments_toggleForm(buttonId, formId, url) {
    var form = document.getElementById(formId);
    var button = document.getElementById(buttonId);
    try {
        url = CQ.shared.HTTP.noCaching(url);
        CQ.shared.HTTP.get(url, function(o, ok, response) {
            var result = response.responseText;
            $CQ(form).html(result);
            //evaluate the first form element's id and remove the '-form' ending to use it as the idPrefix for updating the form
            var formElementId = $CQ(form).children("form").attr("id");
            if(formElementId){
                var tokens = formElementId.split("-");
                tokens.length=tokens.length-1;
                var idPrefix = tokens.join("-");
                if( CQ_Analytics && CQ_Analytics.CCM) {
                    var store = CQ_Analytics.CCM.getRegisteredStore(CQ_Analytics.ProfileDataMgr.STORENAME);
                    if(store){
                        CQ_collab_comments_formStateChanged(idPrefix, store)
                    }
                }
            }
        });
    } catch (e) {
        alert("Error loading form: " + url);
    }
    var hidden = form.style.display != "block";
    form.style.display = hidden ? "block" : "none";
    button.innerHTML = hidden ? "Cancel" : "Reply";
}

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

function CQ_collab_comments_handleOnBlur(el, id) {
    if (el.value == "") {
        el.value = CQ_collab_comments_getDefaultMessage(id);
        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(id)) {
        CQ_collab_comments_showError('Please enter a comment', id );
        return false;
    }
    return true;
}

function CQ_collab_comments_validateSubmit(id) {
    if (!CQ_collab_comments_validateFields(id)) {
        return false;
    }
    try {
        var check = document.getElementById(id + "-id");
        if (!check) {
            var form = document.getElementById(id + "-form");
            check = document.createElement("input");
            check.id = id + "-id";
            check.type = "hidden";
            check.name = "id";
            check.value = "nobot";
            form.appendChild(check);
        }
    } catch (e) {
        return false;
    }
    return true;
}

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(id) {
    if (id && document.getElementById(id + "-rating")) {
        return CQ_collab_ratings_defaultMessage;
    }
    return CQ_collab_comments_defaultMessage;
}

function CQ_collab_comments_openCollabAdmin() {
    CQ.shared.Util.open(CQ.HTTP.externalize('/socoadmin#/content/usergenerated' + CQ.WCM.getPagePath()));
}

function CQ_collab_comments_activate(cmd, callback) {
    if (!cmd) cmd = "Activate";
    CQ.HTTP.post(
        "/bin/replicate.json",
        function(options, success, response) {
            CQ.Notification.notify(null, success
                ? CQ.I18n.getMessage("Comment activated")
                : CQ.I18n.getMessage("Unable to activate comment"));
            if (callback) {
                callback.call(this, options, success, response);
            }
        },
        {
            "_charset_":"utf-8",
            "path":this.path,
            "cmd":cmd
        }
    );
}

function CQ_collab_comments_refresh() {
    if (this.refreshCommentSystem) {
        this.refreshCommentSystem();
    } else {
        CQ.wcm.EditBase.refreshPage();
    }
}

function CQ_collab_comments_afterEdit() {
    CQ_collab_comments_activate.call(this, "Activate", CQ_collab_comments_refresh);
}

function CQ_collab_comments_afterDelete() {
    CQ_collab_comments_activate.call(this, "Delete", CQ_collab_comments_refresh);
}

function CQ_collab_comments_initFormState(idPrefix){
    if( CQ_Analytics && CQ_Analytics.CCM) {
        $CQ(function() {
            if(CQ_Analytics.CCM.areStoresLoaded){
                var store = CQ_Analytics.CCM.getRegisteredStore(CQ_Analytics.ProfileDataMgr.STORENAME);
                CQ_collab_comments_formStateChanged(idPrefix, store); 
            }
            else{
                CQ_Analytics.CCM.addListener('storesloaded', function() {
                    var store = CQ_Analytics.CCM.getRegisteredStore(CQ_Analytics.ProfileDataMgr.STORENAME);
                    if(store){
                        CQ_collab_comments_formStateChanged(idPrefix, store);
                        if(store.addListener){
                            store.addListener('update', function(){
                                CQ_collab_comments_formStateChanged(idPrefix, store);
                            });
                        }
                    }
                });
            }
        })
    }
}

function CQ_collab_comments_formStateChanged(idPrefix, store){
    var p = store.getData();
    if(p){
        var formId = idPrefix + "-form";
        var textId = idPrefix + "-text";
        var nameId = idPrefix + "-userIdentifier";
        var mailId = idPrefix + "-email";
        var webId = idPrefix + "-url";
        var userId = p['authorizableId'];
        var formattedName = p['formattedName'];
        if(!formattedName){
            formattedName = userId;
        }
        
        if(userId && userId == 'anonymous'){
            if(CQ_collab_comments_requireLogin){
                $CQ("#" + formId).hide();
                $CQ("[id$=-reply-button]").hide();
                $CQ("[id$=-reply-arrow]").hide();
            }
            else{
                $CQ("#" + formId).show();
                $CQ("[id$=-reply-button]").show();
                $CQ("[id$=-reply-arrow]").show();
                $CQ("#" + nameId + "-comment-block").show();
                $CQ("#" + mailId + "-comment-block").show();
                $CQ("#" + webId + "-comment-block").show();
                
                $CQ("[id$=-signed-in-text]").hide();
                $CQ("[id$=-signed-in-user]").text("");
            }
        }
        else{
            $CQ("[id$=-reply-button]").show();
            $CQ("[id$=-reply-arrow]").show();
            
            $CQ("#" + nameId + "-comment-block").hide();
            $CQ("#" + nameId).attr('value', userId);
            $CQ("#" + mailId + "-comment-block").hide();
            $CQ("#" + webId + "-comment-block").hide();
            
            $CQ("[id$=-signed-in-user]").text(formattedName);
            $CQ("[id$=-signed-in-text]").show();
        }
    }
}



