/* Copyright IBM Corp. 2008  All Rights Reserved.                    */

//DEPRECATED use COM below...
var Tango = {
    editFormRefCount : 0,

    Util: {
        constructUrl: function(url, params) {
            var query = '';
            for (var p in params) {
                if (query.length > 0)
                    query += "&";
                query += encodeURIComponent(p);
                query += "=";
                query += encodeURIComponent(params[p]);
            }

            if (query.length > 0)
                url += "?" + query;

            return url;
        },

        getCookie: function(name) {
            key = name + "=";
            c = document.cookie;

            // set start of cookie
            start = c.indexOf("; " + key) + 2 + key.length;
            start = start > -1 + 2 + key.length ? start : c.indexOf(name + "=") + key.length;

            // set end of cookie if start is found
            if (start > -1 + key.length) {
               end = c.indexOf(";", start);
               end = end > -1 ? end : c.length;

               // return cookie value
               return unescape(c.substring(start , end));
            } else {
               // no cookie
               return null;
            }
        },

        setCookie: function(name, value) {
            document.cookie = name + "=" + escape(value) +  "; expires=" +
                new Date(new Date().getTime() + 365*24*60*60*1000).toGMTString() + "; path=/";
        }
    }
};

var COM = {
    editFormRefCount : 0,

    utils: {
    
        hide: function(elementName) {            
            var el = elementName;
            if (typeof elementName == "string") {
                el = dojo.byId(elementName);
            } 
            if (el != null) {
                el.style.display = 'none';
            }
        },        
        
        show: function(elementName) {                
            var el = elementName;
            if (typeof elementName == "string") {
                el = dojo.byId(elementName);
            } 
            if (el != null) {
                el.style.display = '';
            }
        },
        
        constructUrl: function(url, params) {
            var query = '';
            for (var p in params) {
                if (query.length > 0)
                    query += "&";
                query += encodeURIComponent(p);
                query += "=";
                query += encodeURIComponent(params[p]);
            }

            if (query.length > 0)
                url += "?" + query;

            return url;
        },

        getCookie: function(name) {
            key = name + "=";
            c = document.cookie;

            // set start of cookie
            start = c.indexOf("; " + key) + 2 + key.length;
            start = start > -1 + 2 + key.length ? start : c.indexOf(name + "=") + key.length;

            // set end of cookie if start is found
            if (start > -1 + key.length) {
               end = c.indexOf(";", start);
               end = end > -1 ? end : c.length;

               // return cookie value
               return unescape(c.substring(start , end));
            } else {
               // no cookie
               return null;
            }
        },

        setCookie: function(name, value) {
            document.cookie = name + "=" + escape(value) +  "; expires=" +
                new Date(new Date().getTime() + 365*24*60*60*1000).toGMTString() + "; path=/";
        }
    }
};
var addMembers_W = null;
function displayMemberCreateForm(ownerStr, memberStr, addStr, removeStr) {
    Element.toggle('memberAddForm');                 
    dojo.require('lconn.typeahead.AddMembers');   
    if (addMembers_W == null) {
        addMembers_W = new lconn.typeahead.AddMembers({"class":"content","rs_owner":ownerStr, "rs_member":memberStr, "rs_addMember_title":addStr, "rs_removeMember_title":removeStr},dojo.byId("addMembersWidget"));     
    }
    else {
        addMembers_W.reset();
    }    
    setFieldFocus('addMembersSelect'); 
    return false;
}

function saveMemberFields(formObj)
{
    addMembers_W.setHiddenFields();    
    formObj.elements['members'].value = addMembers_W.getMembers();        
    formObj.elements['owners'].value  = addMembers_W.getOwners();
    addMembers_W.reset();
}
function cancelMemberCreateForm() {    
    COM.utils.hide('errorMessages');
    COM.utils.hide('memberAddForm');
    if (addMembers_W) {
        addMembers_W.reset();
    }
}   
function displayFeedEditForm(parentId, feedId) {
    if (COM.editFormRefCount > 0) {
        // alert ("Sorry, multiple edit forms are disallowed. \nCancel or Submit an existing form first.");
        return;
    }
    else {
                
        // Hide entry
        COM.editFormRefCount++;
        COM.utils.hide('b_summary_'+feedId);
        COM.utils.hide('b_details_'+feedId);
        COM.utils.hide('b_feedDisplay_'+feedId);
        COM.utils.show('b_editDisplay_'+feedId);

        // First clone the form and setup the actions, ids, etc..
        var template = document.getElementById('editForm');
        var newForm = template.cloneNode(true);
        var parentNode = document.getElementById(parentId);
        newForm.id = 'editForm'+'_'+feedId;
        var uuid_el = getElementById(newForm, 'feed_uuid');
        if (uuid_el) {
            uuid_el.id = uuid_el.id + '_' + feedId;
            uuid_el.value = feedId;
        }

        var type_el = getElementById(newForm, 'feed_type');
        if (type_el) {
            type_el.id = type_el.id + '_' + feedId;
        }

        var tag_input = getElementById(newForm, 'autocompletetags_edit');
        if (tag_input) {
            tag_input.id = tag_input.id + '_' + feedId;
        }

        var cancelBtn = getElementById(newForm, 'cancelBtn');
        var cancelCallBack = function onclick(event) {
            destroyFeedEditForm(parentNode,newForm,feedId);
            return false;
        };
        cancelBtn.onclick = cancelCallBack;

        // Now fill the form with data from DOM
        var name = getElementById(newForm, 'editFeedName');
        var editName = document.getElementById('b_name_'+feedId);
        if (name && editName) {
            if (editName.textContent) {
                name.value = editName.textContent;
            }
            else if (editName.innerText) {
                name.value = editName.innerText;
            }
        }
        var uri = getElementById(newForm, 'editFeedUrl');
        var editUri = document.getElementById('b_uri_'+feedId);
        if (uri && editUri)
            uri.value = editUri.getAttribute("href");
        var desc =  getElementById(newForm, 'editFeedDescription');
        var editDesc = document.getElementById('b_description_'+feedId);
        if (desc && editDesc) {
            if (editDesc.textContent) {
                desc.value = trim(editDesc.textContent);
            }
            else if (editDesc.innerText) {
                desc.value = trim(editDesc.innerText);
            }
        }

        var editTags = document.getElementById('b_tags_'+feedId);
        if (tag_input && editTags) {
            if (editTags.textContent) {
                tag_input.value = editTags.textContent;
            }
            else if (editTags.innerText) {
                tag_input.value = editTags.innerText;
            }
        }
        // Add the form to DOM
        parentNode.appendChild(newForm);

        var homepage =  getElementById(newForm, 'homepage');
        var editHomepage = document.getElementById('b_homepage_'+feedId);
        if (homepage && (editHomepage.innerHTML == 'true')) {
            homepage.checked = true;
        }        
        renderWidget(tag_input);
        setFieldFocus('editFeedUrl');        
    }
}

function destroyFeedEditForm(parentNode, formNode, feedId) {
    parentNode.removeChild(formNode);
    COM.utils.show('b_summary_'+feedId);
    COM.utils.show('b_details_'+feedId);
    COM.utils.show('b_feedDisplay_'+feedId);
    COM.utils.hide('b_editDisplay_'+feedId);
    COM.editFormRefCount--;
}
function setFieldFocus(fieldId) {
    var fieldElm = document.getElementById(fieldId);
    if (fieldElm) {                 
        setTimeout(function () {fieldElm.focus();}, 200);      
    }
}
function showTags(displayType, tagCloudId, tagListId) {
    if (displayType == 'cloud') {
        COM.utils.hide(tagListId);
        COM.utils.show(tagCloudId);
    }
    else {
        COM.utils.show(tagListId);
        COM.utils.hide(tagCloudId);
    }
}

function toggleBookmarkDisplay(bookmarkId, display) {
    if (display == 'show') {
        COM.utils.hide('b_show_'+bookmarkId);
        COM.utils.show('b_hide_'+bookmarkId);
        COM.utils.show('b_details_'+bookmarkId);        
    }
    else {
        COM.utils.show('b_show_'+bookmarkId);
        COM.utils.hide('b_hide_'+bookmarkId);
        COM.utils.hide('b_details_'+bookmarkId);       
    }
}

function toggleFeedDisplay(feedId, feedObj, display) {
    if (display == 'show') {
        COM.utils.hide('b_show_'+feedId);
        COM.utils.show('b_hide_'+feedId);
        COM.utils.show('b_details_'+feedId);
        feedObj.loadThread();
        COM.utils.show('b_feedDisplay_'+feedId);
    }
    else {
        COM.utils.show('b_show_'+feedId);
        COM.utils.hide('b_hide_'+feedId);
        COM.utils.hide('b_details_'+feedId);
        COM.utils.hide('b_feedDisplay_'+feedId);
    }
}

function displayBookmarkEditForm(parentId, bookmarkId) {
    if (COM.editFormRefCount > 0) {
        // alert ("Sorry, multiple edit forms are disallowed. \nCancel or Submit an existing form first.");
        return;
    }
    else {
        // Hide entry
        COM.editFormRefCount++;   
        COM.utils.hide('b_summary_'+bookmarkId);
        //COM.utils.hide('b_entry_'+bookmarkId);
        //COM.utils.hide('b_entry_date_'+bookmarkId);
        COM.utils.hide('b_details_'+bookmarkId);
        COM.utils.show('b_editDisplay_'+bookmarkId);
        
        // First clone the form and setup the actions, ids, etc..
        var template = document.getElementById('editForm');
        var newForm = template.cloneNode(true);
        var parentNode = document.getElementById(parentId);
        newForm.id = 'editForm'+'_'+bookmarkId;
        var uuid_el = getElementById(newForm, 'bookmark_uuid');
        if (uuid_el) {
            uuid_el.id = uuid_el.id + '_' + bookmarkId;
            uuid_el.value = bookmarkId;
        }

        var type_el = getElementById(newForm, 'bookmark_type');
        if (type_el) {
            type_el.id = type_el.id + '_' + bookmarkId;
        }
        
        var tag_input = getElementById(newForm, 'autocompletetags_edit');
        if (tag_input) {
            tag_input.id = tag_input.id + '_' + bookmarkId;
        }

        var cancelBtn = getElementById(newForm, 'cancelBtn');
        var cancelCallBack = function onclick(event) {
            destroyBookmarkEditForm(parentNode,newForm,bookmarkId);
            return false;
        };
        cancelBtn.onclick = cancelCallBack;

        // Now fill the form with data from DOM
        var name = getElementById(newForm, 'editBookmarkName');
        var editName = document.getElementById('b_name_'+bookmarkId);
        if (name && editName) {
            if (editName.textContent) {
                name.value = editName.textContent;
            }
            else if (editName.innerText){
                name.value = editName.innerText;
            }
        }
        var uri = getElementById(newForm, 'editBookmarkUrl');
        var editUri = document.getElementById('b_uri_'+bookmarkId);
        if (uri && editUri)
            uri.value = editUri.getAttribute("href");
        var desc =  getElementById(newForm, 'editBookmarkDescription');
        var editDesc = document.getElementById('b_description_'+bookmarkId);
        if (desc && editDesc) {
            if (editDesc.textContent) {
                desc.value = trim(editDesc.textContent);
            }
            else if (editDesc.innerText) {
                desc.value = trim(editDesc.innerText);
            }
        }
        var editTags = document.getElementById('b_tags_'+bookmarkId);
        if (tag_input && editTags) {
            if (editTags.textContent) {
                tag_input.value = editTags.textContent;
            }
            else if (editTags.innerText) {
                tag_input.value = editTags.innerText;
            }
        }
        
        //add the form to DOM
        parentNode.appendChild(newForm);

        //the checkbox is has to be updated AFTER the appendChild because of IE, which ignores checkbox changes before insertion!
        var homepage =  getElementById(newForm, 'homepage');
        var editHomepage = document.getElementById('b_homepage_'+bookmarkId);
        if (homepage && (editHomepage.innerHTML == 'true')) {
            homepage.checked = "true";
        }
        renderWidget(tag_input);             
        setFieldFocus('editBookmarkUrl');        
    }
}

function destroyBookmarkEditForm(parentNode, formNode, bookmarkId) {
    parentNode.removeChild(formNode);
    COM.utils.show('b_summary_'+bookmarkId);
    COM.utils.show('b_entry_'+bookmarkId);
    COM.utils.show('b_entry_date_'+bookmarkId);
    COM.utils.show('b_details_'+bookmarkId);
    COM.editFormRefCount--;
}

// Find child element by id.
function getElementById(parentNode, tagId) {
    var retval = null;
    var childTags = parentNode.getElementsByTagName("*");
    for (var ii=0; ii<childTags.length; ii++) {
        if (childTags[ii].id == tagId) {
            retval = childTags[ii];
            break;
        }
    }
    return (retval);
}
function toggleSection(sectionId, display) {
    var focusObj = null;
    if (display == 'show') {
        COM.utils.hide(sectionId+'Show');
        COM.utils.show(sectionId+'Hide');
        COM.utils.show(sectionId);
        focusObj = dojo.byId(sectionId+'Hide');
    }
    else {
        COM.utils.show(sectionId+'Show');
        COM.utils.hide(sectionId+'Hide');
        COM.utils.hide(sectionId);
        focusObj = dojo.byId(sectionId+'Show');
    }
    if (focusObj != null) {
        focusObj.focus();
    }
}
//Version 2.5 should fix this..
/*function selectTab(tabSelectedId) {    
    var tabSelected = dojo.byId(tabSelectedId);

    var tabsContainer = dojo.getFirstAncestorByTag(tabSelected, 'ul');
    var tab = dojo.getFirstChildElement(tabsContainer, 'li');

    do {        
        dojo.html.removeClass(tab, 'lotusSelected');
        var tabContentId = tab.id+'Content';
        COM.utils.hide(tabContentId);
        tab = dojo.dom.getNextSiblingElement(tab, 'li');
    } while (tab != undefined);

    dojo.html.setClass(tabSelected, 'lotusSelected');
    COM.utils.show(tabSelectedId+'Content');
}*/
function selectTab(tabSelectedId) {

    var threadedTab = dojo.byId('threadedTab');
    var recentTab = dojo.byId('recentTab');
    if (tabSelectedId == 'threadedTab') {        
        COM.utils.hide('recentTabContent');
        Element.removeClassName(recentTab, 'lotusSelected');
        Element.addClassName(threadedTab,  'lotusSelected');
        COM.utils.show('threadedTabContent');       
    }
    else {
        Element.addClassName(recentTab, 'lotusSelected');
        COM.utils.hide('threadedTabContent');
        Element.removeClassName(threadedTab, 'lotusSelected');
        Element.addClassName(recentTab, 'lotusSelected');        
        COM.utils.show('recentTabContent');               
    }
}
function toggleDisplay(showId, hideId) {
    COM.utils.show(showId);
    COM.utils.hide(hideId);
}

var communityCreateRTE = null;
var addComMembers_W = null;
function displayCommunityCreate(ownerStr, memberStr, addStr, removeStr) {
    Element.toggle('newCommunityForm');
    
    dojo.require('lconn.typeahead.AddMembers'); 
    if (addComMembers_W == null) {        
        addComMembers_W = new lconn.typeahead.AddMembers({"class":"content","rs_owner":ownerStr, "rs_member":memberStr, "rs_addMember_title":addStr, "rs_removeMember_title":removeStr, "cellContainer":"addMembersContainer"},dojo.byId("addComMembersWidget"));          
    }
    else {
        addComMembers_W.reset();
    }
    if (communityCreateRTE == null) {
        communityCreateRTE = initEditor('newCommunityForm','addCommunityDescription');
    }  
                
    // Force table cell to repaint (to get around IE display issues)               
    var cellElm = dojo.byId('editorContainer');   
    if (cellElm != null) {
        setTimeout(function () {cellElm.style.display = "none"; cellElm.style.display = "block";} , 200);                   
    }  
    dojo.parser.parse(dojo.byId("tagTypeAheadContainer"));
    
    setFieldFocus('addCommunityName'); 
}
function saveCommunityCreate(formObj)
{    
    var valueTmp = dijit.byId('addCommunityDescription').getValue(false);       
    formObj.elements['description'].value = valueTmp;    
    
    addComMembers_W.setHiddenFields();    
    formObj.elements['members'].value = addComMembers_W.getMembers();        
    formObj.elements['owners'].value  = addComMembers_W.getOwners();
    addComMembers_W.reset();
}
function cancelCommunityCreate() {    
    COM.utils.hide('errorMessages');
    COM.utils.hide('newCommunityForm');
    clearCommunityForm();
}
function clearCommunityForm(){
    var name =  document.getElementById('addCommunityName');
    if (name) {
        name.value ="";
    }
    var publicAccess =  document.getElementById('addPublicAccess');
    if (publicAccess) {
        publicAccess.checked = true;
    }
    var autoMembers = document.getElementById('autocompletemembers');
    if (autoMembers) {
        autoMembers.value ="";
    }
    var desc = document.getElementById('addCommunityDescription');
    if (desc) {
        desc.value = "";
    }
    if (communityCreateRTE) {
        communityCreateRTE.setValue("");        
    }
    if (addComMembers_W) {
        addComMembers_W.reset();
    }
    var photo = document.getElementById('photoId');
    if (photo) {
        photo.value ="";
    }
    var autoTags = document.getElementById('autocompletetags');
    if (autoTags) {
        autoTags.value ="";
    }
}

var origCommunityName = null;
var origCommunityDescription = null;
var origCommunityTagNameString = null;
var origManagedAppChecked = new Array();
var origCommunityType = null;

function saveCommunityEditOrigValues(numManagedApps, communityType) {
    origCommunityName = document.getElementById('editCommunityName').value;
    origCommunityDescription = document.getElementById('editcommunityDescription').value;
    origCommunityTagNameString = document.getElementById('autocompletetags_').value;
    for (i=0; i < numManagedApps; i++) {
    	origManagedAppChecked[i] = document.getElementById('managedApp' + (i+1)).checked;
    }
    origCommunityType = communityType;
}

function cancelCommunityEdit() {    

	populateCommunityEdit(origCommunityName, origCommunityType, origManagedAppChecked, origCommunityDescription, origCommunityTagNameString);

    COM.utils.show('photoUploadLink');
    COM.utils.hide('photoUploadHelp');
    COM.utils.hide('photoUpload');
    COM.utils.hide('photoUploadRemove');  

    var photo = document.getElementById('photoId');
    photo.value ="";

    var photoRemove = document.getElementById('photoRemove');
    photoRemove.checked = false;
    togglePhotoRemove(photoRemove);
        
    COM.utils.hide('editCommunityForm'); 
    COM.utils.show('lotusColRight'); 
    COM.utils.hide('headline-messages'); 
    COM.utils.show('headline-content'); 
    COM.utils.show('communityPage');
    
}

function populateCommunityEdit(communityName, communityType, managedAppChecked, communityDescription, tags) {    

    var name =  document.getElementById('editCommunityName');
    name.value = communityName;
    
    var publicAccess =  document.getElementById('addPublicAccess');
    publicAccess.checked = (communityType == 'public');
    
    var publicInviteOnlyAccess =  document.getElementById('addPublicInviteOnlyAccess');
    publicInviteOnlyAccess.checked = (communityType == 'publicInviteOnly');

    var privateAccess =  document.getElementById('addPrivateAccess');
    privateAccess.checked = (communityType == 'private');


    for (i=0;i<managedAppChecked.length;i++)
    {
        var managedApp = document.getElementById('managedApp' + (i+1));
        managedApp.checked = managedAppChecked[i];
    }

    communityEditRTE.setValue(communityDescription);

    var autoTags = document.getElementById('autocompletetags_');
    autoTags.value = tags;
}

var communityEditRTE = null;
function displayCommunityEdit() {
    COM.utils.show('editCommunityForm');
    COM.utils.hide('lotusColRight');
    COM.utils.hide('headline-content');
    COM.utils.hide('communityPage');
    if (communityEditRTE == null) {
        communityEditRTE = initEditor('editCommunityForm', 'editcommunityDescription');
    }
    dojo.parser.parse(dojo.byId("tagTypeAheadContainer"));
    setFieldFocus('editCommunityName'); 
}

function saveForm(formObj, formField, editorId)
{    
    var valueTmp = dijit.byId(editorId).getValue(false);       
    formObj.elements[formField].value = valueTmp;    
}

function initEditor(form, editor){
    // console.log("ronin.initEditor");
    var dojoEditWidget = null;
    var editForm = dojo.byId (form);
    if (editForm) {
        if (editForm.style.display != 'none') {
            console.log("ronin.initEditor: creating editor");
            var pluginsTemp = ["bold","italic","underline","strikethrough","|", "foreColor", "hiliteColor","|", "insertUnorderedList", "insertOrderedList", "|", "indent","outdent", "|" , "justifyLeft","justifyRight", "justifyCenter", "justifyFull", "|", "createLink", "insertImage", "insertHorizontalRule"];
            var params = { minHeight: "100px", plugins: pluginsTemp};
            dojoEditWidget = new dijit.Editor(params, dojo.byId (editor));                
        }
    }
    return dojoEditWidget;
}

function initDropDownSearch(searchAllLabel, searchMyLabel){
    var dojoMenuWidget = null;
    var params = { id: "searchPopup", style:"display:none"};
    dojoMenuWidget = new dijit.Menu( params, dojo.byId('searchCentral') );

    var searchAll = new dijit.MenuItem({ label: searchAllLabel,  value: "all", iconClass:"dijitMenuItemIcon lotusCheckmark"});
    var searchMine = new dijit.MenuItem({ label: searchMyLabel,  value: "my"})

    dojoMenuWidget.addChild(searchAll);
    dojoMenuWidget.addChild(searchMine);

    dojo.connect(dojoMenuWidget, 'onItemClick', 'setSearchSelection');        
}

function setSearchSelection(selected){
    var searchScope  = document.getElementById("searchScope");
    
    var menu = dijit.byId("searchPopup");
    var items = menu.getChildren();
    for(var i=0; i < items.length; i++)
    {
        var item = items[i];

        if(dojo.string.trim(item.value) == dojo.string.trim(selected.value))
        {
            dojo.addClass(item.iconNode, "dijitMenuItemIcon lotusCheckmark");

        }else{
            //reset the classes of others
            dojo.removeClass(item.iconNode, "dijitMenuItemIcon lotusCheckmark");
        }
    }    
    searchScope.value = selected.value;
}

function displayPhoto(editFlag) {
    COM.utils.hide('photoUploadLink');
    COM.utils.show('photoUploadHelp');
    COM.utils.show('photoUpload');
    if (editFlag) {
        COM.utils.show('photoUploadRemove');        
    }
    setFieldFocus('photoId');
}
function togglePhotoRemove(removeCtl) {

    var uploadCtl = document.getElementById("photoId");
    if(removeCtl.checked) {
        uploadCtl.value="";
        uploadCtl.disabled = true;
    }
    else {
        uploadCtl.disabled = false;
    }
}
// Handle Community AJAX related errors
function handleComAjaxErrors(errorObj, status, feedId, forumFlag) {
    console.log("Entered handleComFeedErrors");
    
    var msgId=null;
    switch(status){
        case 302:
        case 401:
            msgId="feedErrorUnauth_"+feedId;
            break;
        case 404:
            if (forumFlag) {
                msgId="feedErrorDefaultForum_"+feedId;
            }
            else {
                msgId="feedErrorNotFound_"+feedId;
            }
            break;
        default:
            if (forumFlag) {
                msgId="feedErrorDefaultForum_"+feedId;
            }
            else {
                msgId="feedErrorDefault_"+feedId;
            }
            break;
    }
    var msgEl = dojo.byId("feedErrorDetailMessage_"+feedId);
    if (msgEl != null && errorObj != null) {
        msgEl.innerHTML=errorObj.message;        
    }       
    COM.utils.hide("feedContainer_"+feedId);  
    COM.utils.show(msgId);
    COM.utils.show("feedErrorContainer_"+feedId);
    return;    
}

// Bring up the Topic form.
var topicCreateRTE = null;
function displayForumForm(form, rte) {
    Element.toggle(form);      
    if (topicCreateRTE == null) {
        topicCreateRTE = initEditor(form,rte);
    }
    setFieldFocus('addForumTitle');
}
// Cancel the Topic / Reply form.
function cancelForumForm(form) {
    clearForumForm();
    Element.toggle(form);
}
// Clear the Topic / Reply form.
function clearForumForm(){
    console.log("ronin.clearForumForm");
    var topicNode = document.getElementById('addForumTitle');
    if (topicNode) {
        topicNode.value = "";
    }

    if (topicCreateRTE) {
        topicCreateRTE.setValue("");        
    }

    var autoTags = document.getElementById('autocompletetags2');
    if (autoTags) {
        autoTags.value ="";
    }
}
// Create a Topic 
function createForumItem(formType,communityOwnersRoleId,communityMembersRoleId,privateCommunity) {
         
    // Retrieve title
    var title = "";
    var titleNode = document.getElementById('addForumTitle');
    if (titleNode) {
        title = (titleNode.value).escapeHTML();        
    }

    // Retrieve topic body
    var content = "";
    if (topicCreateRTE) {
        content = topicCreateRTE.getValue();
    }
    
    // Set ownership
    var contrib =
        '<contributor>' +
        '<snx:communityUuid xmlns:snx="http://www.ibm.com/xmlns/prod/sn" component=' +
        '"http://www.ibm.com/xmlns/prod/sn/activities">' + communityOwnersRoleId + '</snx:communityUuid>' +
        '<category scheme="http://www.ibm.com/xmlns/prod/sn/type" term="community" />' +
        '<snx:role xmlns:snx="http://www.ibm.com/xmlns/prod/sn" component=' +
        '"http://www.ibm.com/xmlns/prod/sn/activities">owner</snx:role>' +
        '</contributor>' +
        '<contributor>' +
        '<snx:communityUuid xmlns:snx="http://www.ibm.com/xmlns/prod/sn" component=' +
        '"http://www.ibm.com/xmlns/prod/sn/activities">' + communityMembersRoleId + '</snx:communityUuid>' +
        '<category scheme="http://www.ibm.com/xmlns/prod/sn/type" term="community" />' +
        '<snx:role xmlns:snx="http://www.ibm.com/xmlns/prod/sn" component=' +
        '"http://www.ibm.com/xmlns/prod/sn/activities">member</snx:role>' +
        '</contributor>';
        
    if (!privateCommunity) {       
        contrib = contrib +        
            '<contributor>' +
            '<snx:userid xmlns:snx="http://www.ibm.com/xmlns/prod/sn" component="http://www.ibm.com/xmlns/prod/sn/activities">*</snx:userid>' +
            '<snx:role xmlns:snx="http://www.ibm.com/xmlns/prod/sn" component=' +
            '"http://www.ibm.com/xmlns/prod/sn/activities">reader</snx:role>' +
            '</contributor>';
    }
    
    // Construct the XML to be sent in the request as a string
    var postXML = '<entry xmlns="http://www.w3.org/2005/Atom"><title type="text"><![CDATA['+title+']]></title><content type="html"><![CDATA['+content+']]></content>'+contrib+'</entry>'
    // alert("Post XML: "+postXML);

    // Get target URL
    var postURL = feed_thread.getFullURL();
    // alert("Post URL: "+postURL);

    //NEEDSWORK feed_thread hardcoded. and this is old
    /*dojo.io.bind({url: postURL,
                  method: "POST",
                  postContent: postXML,
                  load: itemCreated,
                  error: handleError,
     */

    dojo.rawXhrPost({ url: postURL,
                      load: function (response, ioArgs) { 
                          itemCreated();
                          return response;
                      },
                      postData: postXML,
                      error: function(response, ioArgs){ return handleError(response, ioArgs); },
                      contentType: "application/atom+xml",
                      handleAs: "xml"});

    // Clear and hide form
    clearForumForm();
    COM.utils.hide('add'+formType+'Form');
}
// Refresh the thread when new item created.
function itemCreated(type, data, evt) {
   
    //NEEDSWORK shouldn't hardcode feed_thread variable    

    // Refresh the thread.
    if (feed_thread) {
        feed_thread.refreshThread();
    }
}
// Handle dojo errors
/*
function handleError(type, errObj) {
    alert(dojo.errorToString(errObj));
}
*/
function handleError(response, ioArgs) {
    alert("Error: " + response.dojoType + " - " + response);
    console.error(response);
    return response;
}
// Add a thumbnail photo to the entries.
function addThumbnail(postObj, postDiv) {    
    if (profileService != null) {
        var photoURL = profileService + "/photo.do?userid=";           
        var photoElm = getElementById(postDiv, 'post_photo_'+postObj.postId);        
        if (photoElm && postObj.author_userid) {                  
            photoElm.src = photoURL+postObj.author_userid;                
        }
    }
}

function renderWidget(inputElement)
{
    dijit.registry.remove(inputElement.id);
    dijit.registry.remove("tagTypeAheadStoreId");
    var storeParams = { queryParam: "tag", url: "autoCompleteTags.do?format=v2"};
    var mystore = new lconn.core.TypeAheadDataStore(storeParams, document.getElementById("tagTypeAheadStoreId"));
    var widgetParams = { store: mystore, name: "tags", value: inputElement.value, 
        searchDelay: 400, minChars: 2, multipleValues: true, token: ",", style: "width: 98%"};
    new lconn.core.TypeAhead(widgetParams, inputElement);
}

