/* $Id$ */

/****Method to open single post*****/
function openSinglePost(forumTopicId,givenHashKey,recentResponseId)
{   
    givenHashKey = givenHashKey || 'Topic';
    if(recentResponseId != undefined)
    {
        loadSinglePost(forumTopicId,"true",undefined,recentResponseId);
    }
    else
    {
        loadSinglePost(forumTopicId);
    }
    $.history.add(givenHashKey+'/'+forumTopicId);
}//function openSinglePost()

function loadSinglePost(forumTopicId,shouldScrollToTop,goHere,recentResponseId)
{
    var options = {};
    options.forumTopicId = forumTopicId;
    options.forumGroupId = forumGroupId;
    
    if(typeof shouldScrollToTop == "undefined")
    {
        shouldScrollToTop = true;
    }
    doAjaxAction('/getSinglePost.do',options,function (data)//No internationalization
    {
        hideLoadingImage();
        if($('#topicListMainContainer').length > 0 || $('#userProfileMainContainer').length > 0 || $('#myAreaParentContainer').length > 0)
        {
        $('#topicListMainContainer').hide().attr('shouldReload','false');
        $('#userProfileMainContainer').hide().attr('shouldReload','false');
        $('#myAreaParentContainer').hide().attr('shouldReload','false');
            if($('#singlePostMainContainer').length > 0)
            {
                $('#mainContent').get(0).innerHTML = data;
                $(window).scrollTop(0);
            }
            else
            {
                var singlePostCont = document.createElement('div');
                singlePostCont.innerHTML = data;
                $('#mainContent').get(0).appendChild(singlePostCont);
            }
        }
        else
        {
            $('#mainContent').get(0).innerHTML = data;
        }
        if(shouldScrollToTop && shouldScrollToTop == true)
        {
            $(window).scrollTop(0);
        }
        if(typeof goHere != "undefined")
        {
            var topDiff = $(goHere).offset().top;
            $('html,body').scrollTop(topDiff-100);
        }
        initSinglePost(forumTopicId);
        var $singlePostCont = $('#topicContainer_'+forumTopicId);
        var forumId = $singlePostCont.attr('forumId');
        var categoryId = $singlePostCont.attr('categoryId');
        if(typeof forumId == "undefined")
        {
            forumId = -1;
        }
        if(typeof categoryId == "undefined")
        {
            categoryId = -1;
        }
        var hashPurpose = "NewTopic/"+forumId+"/"+categoryId;
        $('#NewTopicTab').attr('hashPurpose',hashPurpose);
        if(typeof WmsContacts != "undefined" && ch == true)
        {
            var dataOb = WmsContacts.getZohoContacts();
            setPresenceInTopicList(dataOb,forumTopicId)
        }
        if(recentResponseId != undefined)
        {
            setFocusToContainer($('#fullResponseContainer_'+recentResponseId),false,100,0);
            $('#SinglePostContainer').data('currentFocusResponse',$('#'+recentResponseId));
        }
        if(isMac == "false")
        {
            setHotkeysToSinglePost();
        }    
      },
      function(errordata)
      {
        hideLoadingImage();
        var responseData = (errordata.responseText);
        $('#mainContent').get(0).innerHTML = responseData;
  });//$.get('/getSinglePost.do?forumTopicId=' + forumTopicId, function (data)
}//function loadSinglePost(forumTopicId, $newMenuItem)

//method to initialize all actions in topic (single post view)
function initSinglePost(forumTopicId)
{
    showAuthorPopout($('#SinglePostContainer'));
    var $documentTitle = $('#DocumentTitle');
    document.title = ($documentTitle.length > 0)?$documentTitle.text()+" - "+forumGroupName:forumGroupName;
    bindSingleTopicClicks($('#SinglePostContainer'));

    var $topicContainer = $('#topicContainer_'+forumTopicId);
    //this is to perform single post widget actions
    $('#topicContainer_'+forumTopicId).unbind('click',singlePostWidgetActions).click(singlePostWidgetActions);
    //$('#singlePostActionsWidget_'+forumTopicId).unbind('click',singlePostWidgetActions).click(singlePostWidgetActions);
    singlePostTagActions(forumTopicId);
    //do a timeout to set the pre-tag
    $('#mainContent').attr('process-pre-tags', forumTopicId);
    setTimeout (function(){processCodeTags($('#SinglePostContainer'), forumTopicId)}, 5);
    return false;
}//function initSinglePost(forumTopicId)
function showCode(codeNode)
{
    	var toUnFormat = codeNode.parentNode.nextSibling.innerHTML;
	toUnFormat = toUnFormat.replace (/<\/li>/ig, "\n").replace (/<[^>]*>/ig, "").replace(/&nbsp;/ig, " ").replace(/&lt;/ig, "<").replace (/&gt;/ig, ">").replace (/&amp;/ig, "&");
	$('#CopyCodeCont').show().parent().show();
	$('#copycode_text').val(toUnFormat).select();
        
}//function showCode(codeNode)
var codeForPreview = '<div class="__zd_findAndReplaceParent" style="height:11px"></div><div class = "__zd_findAndReplace" style="text-align:right;float:right;background-color:#efefef;margin-right:30px;padding:0px 3px;"><span onclick = "javascript:showCode(this);return false;" style="font:normal 10px trebuchet ms,arial;text-decoration:underline;color:blue;cursor:pointer">Copy code</span></div>';
function processCodeTags($codeTagContainer, passKey)
{
	if (!passKey || !$codeTagContainer || $codeTagContainer.length < 1 ){return;}
	var $mainContainer = $('#mainContent');
	var setPassKey = $mainContainer.attr('process-pre-tags');
	if (setPassKey != passKey)
	{
		//probably someother page has been loaded - so ignore.
		return;
	}//if (setPassKey != passkey)
	var codeTags = $codeTagContainer.find('ol.code');
	codeTags.before(codeForPreview);
}//function processCodeTags(passKey)

function bindSingleTopicClicks($context)
{   
    $context.unbind('click', processSingleTopicClicks).click(processSingleTopicClicks);
}

function processSingleTopicClicks(event)
{   
    var $target = $(event.target);
    var $targetParent = $target.parent();
    var $location = "singlePost";
    var forumTopicId = $('#SinglePostContainer').attr('forumTopicId');
    var $topicContainer = $('#topicContainer_'+forumTopicId);
    var $dropDownConts = $('#statusList');
    if($('#loadingImg').is(":visible"))
    {
        return;
    }
    if($target.is('a[purpose="authorProfile"]'))
    {
        //to show authoor profile page
        var authorName = $target.attr('authorName');
        var singleClickflag = $target.attr('singleClickflag');
        if(singleClickflag == "0")
        {
          var hashValue = (authorName == ZU_Name)?'MyArea':'User/'+authorName;
          processHash(hashValue);
        }
        return;
    }//if($target.is('a[purpose="authorProfile"]'))    
    else if($targetParent.is('#replyToTopicBtn_'+forumTopicId+',#replyToTopicBtnSec_'+forumTopicId+',#privateResponseThisTopic_'+forumTopicId))
    {
        $this = $targetParent;
        var location = $this.attr('location');
        var postauthor = $this.attr('postauthor');
        var topicTypeString = $this.attr('topicTypeString');
        var $topicUtilContainer = $('#paginationContainer');
        if($('#topicListMainContainer').length > 0 && $('#singlePostMainContainer').length > 0 && $topicUtilContainer.data('inEditMode'))
        {
            removeTopicListCache();
        }
        if($('#responsePreviewContainer').is(":visible"))
        {
            $('#responsePreviewContainer').find('button[purpose="backToEditorResponse"]').trigger('click');
            showMessage(i18n['zohodiscussions.singlepost.alertmessageforediting'],'info');
            var openedEditorLcation = $topicContainer.data('editorContLocation');
            setFocusToContainer($(openedEditorLcation),false);
            return;
        }
        var replyLink = "replyToTopicBtn";
        if($targetParent.is('[purpose="privateResponse"]'))
        {
            replyLink = "privateResponseThisTopic";
        }
        var newResponseLocation = '#newResponseCont_'+forumTopicId;
        //check whether a editor was already opened // if so set the focus to that location
        if($topicContainer.data('inEditMode'))
        {
            showMessage(i18n['zohodiscussions.singlepost.alertmessageforediting']);
            $('#responsePreviewButton').find('button[purpose="backToEditorResponse"]').trigger('click');
            var openedEditorLcation = $topicContainer.data('editorContLocation');
            setFocusToContainer($(openedEditorLcation),false);
            return false;
        }      
        $(newResponseLocation).show();
        openEditor($('#newResponse_'+forumTopicId),"responseContent","postContentTA",replyLink+'_'+forumTopicId,"Write",'topicContainer_'+forumTopicId);
        setFocusToContainer($(newResponseLocation),false);
        $topicContainer.data('inEditMode',true);
        $topicContainer.data('editorContLocation',newResponseLocation);
        $('#previewResponse').attr('forumTopicId',forumTopicId);
        if($(this).is('[purpose="privateResponse"]'))
        {
            $('#newResponseCont_'+forumTopicId).find('div.header').html(i18n['zohodiscussions.singlePost.editorHeaderPrivateResponseTo']+ " " +postauthor+'');
        }
        /*else
        {
            var messString = "";
            if(topicTypeString == "Announcement" || topicTypeString == "Discussion")
            {
                messString = i18n[topicTypeString];
            }
            else
            {
                messString = postauthor+"'s "+i18n[topicTypeString];
            }
            $('#newResponseCont_'+forumTopicId).find('div.header').html(i18n['zohodiscussions.singlePost.editorHeaderReplyTo']+" "+messString);
        }*/
        return false;
    }
    else if($target.is('#TopicListLink,#ForumTopicListLink,#CategoryTopicListLink'))
    {
        $this = $target;
        hashPurpose = $this.attr('hashPurpose');
        $('#topicListMainContainer').attr('shouldReload','true');
        processHash(hashPurpose);
        return false;
    }
    else if($targetParent.is('#topicVoteLink'))
    {
        var $this = $targetParent;
        var responseId = $this.attr('firstResponseId');
        showSmallLoadingImage(event);
        doAjaxAction('/voteTopic.do?forumGroupId='+forumGroupId+'&forumTopicId='+forumTopicId+'&responseId='+responseId,csrfOptions,function(data)//No internationalization
        {
            if(data == "SUCCESS")
            {
                removeTopicListCache();
                loadSinglePost(forumTopicId,false);
            }
            else
            {
                hideLoadingImage();
            }
        }); 
    }
    else if($targetParent.is('#topicPermalink'))
    {
        var thisTopicPermalink = $targetParent.attr('thisTopicPermalink');
        $('#PermalinkCont textarea').val(thisTopicPermalink);
        $('#permalink_Text').select();
        $('#PermalinkCont').show().parent().show();
        return;
    }
    else if($targetParent.is('#linkToTopic'))
    {
      linkToTopic();  
    }
    else if($targetParent.is('#deleteLinkedTopic'))
    {
      deletelinkedTopic($targetParent);  
    } 
    else if($target.is('a[purpose="linkedTopicTitle"]'))
    {   
        //to open a single post in full thread view
        if(isTopicQuickView == "false")
        {
            //do nothing
        }
        else
        {
            var forumTopicId = $target.attr('forumTopicId');
            processHash('Topic/'+forumTopicId);
            return false;
        }
    }
    else if($targetParent.is('#emailThisTopic'))
    {
        openEmailTopicDialog($targetParent);
        return false;
    }
    else if($targetParent.is('li[actionPurpose="reportSpam"],div[actionPurpose="reportSpam"]'))
    {
       singlePostSpamAction($targetParent,$location);   
       return;
    }
    else if($targetParent.is('div[buttonPurpose="approve"]') || $targetParent.is('li[buttonPurpose="approve"]'))
    {
       singlePostApproveAction($targetParent,"singlePostApprove");
       return;
    }
    else if($target.is('div[purpose="inappropriateReason"]') || $target.is('span[purpose="inappropriateReason"]'))
    {
        getReasonForInapppropriate($target);
    }
    else if($targetParent.is('li[deletepurpose="deleteAttachment"]'))
    {
        deletePublishedAttachment($targetParent,event);
        return;
    }
    else if($target.is('li[purpose="topicLabel"]'))
    {
        changeTopicLabel($target);
    }
    else
    {
        var topicAuthorId = $topicContainer.attr('topicAuthorId');
        var thisForumId = $topicContainer.attr('forumId');
        var thisCategoryId = $topicContainer.attr('categoryId');

        var $singlePostUtilCont = $('#singlePostUtilCont');
        var newThreadReplyLinks = $singlePostUtilCont.attr('newThreadReplyLinks');//this is collection of all newThreadReply links ids
        if($targetParent.is(newThreadReplyLinks))
        {
            var $this = $targetParent;
            var forumTopicId = $this.attr('forumTopicId');
            var thisResponseId = $this.attr('responseId');
            var newThreadResponseLocation = '#newThreadResponseCont_'+thisResponseId;
            var $topicUtilContainer = $('#paginationContainer');
            if($('#topicListMainContainer').length > 0 && $('#singlePostMainContainer').length > 0 && $topicUtilContainer.data('inEditMode'))
            {
                removeTopicListCache();
            }
            if($('#responsePreviewContainer').is(":visible"))
            {
                $('#responsePreviewContainer').find('button[purpose="backToEditorResponse"]').trigger('click');
                showMessage(i18n['zohodiscussions.singlepost.alertmessageforediting'],'info');
                var openedEditorLcation = $topicContainer.data('editorContLocation');
                setFocusToContainer($(openedEditorLcation),false);
                return;
            }
            //check whether a editor was already opened // if so set the focus to that location
            if($topicContainer.data('inEditMode'))
            {
                showMessage(i18n['zohodiscussions.singlepost.alertmessageforediting'],'info');
                $('#responsePreviewButton').find('button[purpose="backToEditorResponse"]').trigger('click');
                var openedEditorLcation = $topicContainer.data('editorContLocation');
                setFocusToContainer($(openedEditorLcation),false);
                return false;
            }
            $(newThreadResponseLocation).show();
            openEditor($('#newThreadResponse_'+thisResponseId),"responseContent","postContentTA",'newThreadReply_'+thisResponseId,"Write",'topicContainer_'+forumTopicId);
            setFocusToContainer($(newThreadResponseLocation),false);
            $topicContainer.data('inEditMode',true);
            $topicContainer.data('editorContLocation',newThreadResponseLocation);
            $('#previewResponse').attr('forumTopicId',forumTopicId);
            $('#previewResponse').attr('responseId',thisResponseId);
            return false;
        }
        var responseVoteLinks = $singlePostUtilCont.attr('responseVoteLinks');//this is collection of all response vote links ids
        if($targetParent.is(responseVoteLinks))
        {
            var $this = $targetParent;
            var thisResponseId = $this.attr('responseId');
            var purpose = $this.attr('votePurpose');
            var voteAction = (purpose == "removeVote")?"/removeResponseVote.do":"/voteResponse.do";
            showSmallLoadingImage(event);
            doAjaxAction(voteAction+'?forumGroupId='+forumGroupId+'&responseId='+thisResponseId+'&forumTopicId='+forumTopicId,csrfOptions,function(data)//No internationalization
            {
                if(data == "SUCCESS")
                {
                    removeTopicListCache();
                    loadSinglePost(forumTopicId,false);
                }
                else
                {
                    hideLoadingImage();
                }
            }); 
            return;
        }//if(responseVoteLinks)
        var chooseBestResponseLinks = $singlePostUtilCont.attr('chooseBestResponseLinks');//this is collection of all chooseBestResponse links ids
        if($targetParent.is(chooseBestResponseLinks))
        {
            var $this = $targetParent;
            var thisResponseId = $this.attr('responseId');
            var options = {};
            options.forumGroupId = forumGroupId;
            options.responseId = thisResponseId;
            options.forumTopicId = forumTopicId;
            if(topicAuthorId == ZUID)
            {
                options.topicowner = "true";
            }
            options[csrfParamName] = csrfToken;
            showSmallLoadingImage(event);
            doAjaxAction('/bestResponse.do',options,function(data)//No internationalization
            {
                if(data == "SUCCESS")
                {
                    removeTopicListCache();
                    showTipper(i18n['zohodiscussions.singlepost.bestResponseSuccessMsg'],'success');
                    loadSinglePost(forumTopicId,false,'#bestResponseContainer_'+thisResponseId);
                    options = {};
                    options.forumGroupId = forumGroupId;
                    options.forumTopicId = forumTopicId;
                    doAjaxAction('/notifyForBestResponse.do',options,function(){});//No internationalization
                }
                else
                {
                    hideLoadingImage();
                    showMessage(i18n['zohodiscussions.generalmessage.noPermission']);
                }
            }); 
            return;
        }//if(chooseBestResponseLinks)
        var responseEditLinks = $singlePostUtilCont.attr('responseEditLinks');//this is collection of all edit links ids
        if($targetParent.is(responseEditLinks))
        {
            var editLinkId = $targetParent.attr('id');
            var $this = $targetParent;
            var thisResponseId = $this.attr('responseId');
            var editResponseLocation = "#fullResponseContainer_"+thisResponseId; 
            var $topicUtilContainer = $('#paginationContainer');
            if($('#topicListMainContainer').length > 0 && $('#singlePostMainContainer').length > 0 && $topicUtilContainer.data('inEditMode'))
            {
                removeTopicListCache();
            }
            if($('#responsePreviewContainer').is(":visible"))
            {
                $('#responsePreviewContainer').find('button[purpose="backToEditorResponse"]').trigger('click');
                showMessage(i18n['zohodiscussions.singlepost.alertmessageforediting'],'info');
                var openedEditorLcation = $topicContainer.data('editorContLocation');
                setFocusToContainer($(openedEditorLcation),false);
                return;
            }           
            //check whether a editor was already opened // if so set the focus to that location
            if($topicContainer.data('inEditMode'))
            {
                showMessage(i18n['zohodiscussions.singlepost.alertmessageforediting'],'info');
                var openedEditorLcation = $topicContainer.data('editorContLocation');
                $('#responsePreviewButton').find('button[purpose="backToEditorResponse"]').trigger('click');
                setFocusToContainer($(openedEditorLcation),false);
                return false;
            }
            $(editResponseLocation).show();
            if(editLinkId == 'editTopic')
            {
                $('#linkTopicCont_'+forumTopicId).hide();
                $('#statusContainer').hide();
            }
            openEditor($('#responseContentContainer_'+thisResponseId),"responseContent","postContentTA",editLinkId,"Edit",'topicContainer_'+forumTopicId);
            setFocusToContainer($(editResponseLocation),false);
            $topicContainer.data('inEditMode',true);
            $topicContainer.data('editorContLocation',editResponseLocation);
            $('#previewResponse').attr('responseId',thisResponseId);
            if($(editResponseLocation).attr('class') == "postContent")
            {
                $('#previewResponse').attr('location','editTopic');
            }
            else
            {
                $('#previewResponse').attr('location','editResponse');
            }
            $('#previewResponse').attr('forumTopicId',forumTopicId);
            return false;
        }//if(responseEditLinks)
        //to remove the best response for topic
        if($targetParent.is('#removeBestResponse'))
        {
            var options = {};
            options.forumGroupId = forumGroupId;
            options.forumTopicId = forumTopicId;
            if(topicAuthorId == ZUID)
            {
                options.topicowner = "true";
            }
            options[csrfParamName] = csrfToken;
            showSmallLoadingImage(event);
            doAjaxAction('/removeBestResponse.do',options,function(data)//No internationalization
            {
                if(data == "SUCCESS")
                {
                    removeTopicListCache();
                    showTipper(i18n['zohodiscussions.singlePost.removeBestResponseMsg'],'info');
                    loadSinglePost(forumTopicId);
                }
                else
                {
                    hideLoadingImage();
                    showMessage(i18n['zohodiscussions.generalmessage.noPermission']);
                }
            }); 
            return;
        }
        if($targetParent.is('#deleteTopic'))
        {
            if(confirm(i18n['zohodiscussions.singlePost.messagefordeletingTopic']))
            {
                var deleteTopicOptions = {};
                if(topicAuthorId == ZUID)
                {
                    deleteTopicOptions.access = "author";
                }
                deleteTopicOptions.forumGroupId = forumGroupId;
                deleteTopicOptions.forumTopicId = forumTopicId;
                deleteTopicOptions.categoryId = thisCategoryId;
                deleteTopicOptions.forumId = thisForumId;
                deleteTopicOptions[csrfParamName] = csrfToken;
                doAjaxAction(
                    "/deleteTopic.do", //No I18N
                    deleteTopicOptions,
                    function (data)
                    {
                        if(jQuery.trim(data) == "SUCCESS")
                        {
                            removeTopicListCache();
                            showTipper(i18n['zohodiscussions.generalmessage.topicMovedToTrash'],'info');
                            processHash('Home');
                        }
                    },    
                    function (errordata)
                    {
                        //alert(errordata.responseText);
                    }
                    
                );
            }
            return;
        }
        var responseDeleteLinks = $singlePostUtilCont.attr('responseDeleteLinks');//this is collection of all delete response links ids
        if($targetParent.is(responseDeleteLinks))
        {
            var $this = $targetParent;
            var thisResponseId = $this.attr('responseId');
            var thisResponseAuthId = $this.attr('responseAuthorId');
            if(confirm(i18n['zohodiscussions.singlePost.messagefordeletingResponse']))
            {
                var deleteResponseOptions = {};
                if(thisResponseAuthId == ZUID)
                {
                    deleteResponseOptions.responseowner = "true";
                }
                deleteResponseOptions.forumGroupId = forumGroupId;
                deleteResponseOptions.forumTopicId = forumTopicId;
                deleteResponseOptions.categoryId = thisCategoryId;
                deleteResponseOptions.forumId = thisForumId;
                deleteResponseOptions.responseId = thisResponseId;
                deleteResponseOptions[csrfParamName] = csrfToken;
                doAjaxAction(
                    "/deleteForumResponse.do", //No I18N
                    deleteResponseOptions,
                    function (data)
                    {
                        if(data == "SUCCESS")
                        {
                            removeTopicListCache();
                            showTipper(i18n['zohodiscussions.generalmessage.responseMovedToTrash'],'info');
                            loadSinglePost(forumTopicId);
                        }
                    },
                    function (errordata)
                    {
                        //alert(errordata.responseText);
                    }
                );
            }//
            return false;
        }//if(responseEditLinks)   
    }
    
    $dropDownConts.hover
    (
        function()
        {
           var handle = $dropDownConts.data('destroyHandle');//No internationalization
           if(handle){clearTimeout(handle);}
        },
        function ()
        {
            var handle = setTimeout(function()
            {
                $dropDownConts.hide();
            }, 500);
            $dropDownConts.data('destroyHandle', handle);//No internationalization
        }
    );
   // hideTopicStatus()
}//function processSingleTopicClicks(event)

//get reason for inappropriat response
function getReasonForInapppropriate($this)
{
    if(moderatorForSpam != "true")
    {
        return;
    }
    showLoadingImage();
    var responseId = $this.attr('responseId');
    var options = {};
    options.forumGroupId = forumGroupId;
    options.responseId = responseId;
    options[csrfParamName] = csrfToken;
    doAjaxAction('/getInappropriateReason.do',options,function(data)//No internationalization
    {
        hideLoadingImage();
        var $data = $('<div></div>').html(data);
        if($data.is('#noInappropriateReason'))
        {
            showMessage(i18n['zohodiscussions.inappropriate.NoReasonForInappropriate'],'failure'); //No I18N
        }
        var $inappropriateReason = $('#inappropriateReason');
        $inappropriateReason.html(data).show();
        $('#inappropriateReasonClose').click(function()
        {
            $inappropriateReason.html("").hide();
        });
    });

}//fucntion getReasonForInapppropriate($this)

//this is used to edit topic title
function editTopicTitle($this,forumTopicId,forumId,categoryId,$titleEditor)
{
    var newTopicTitle = $titleEditor.val();
    if(jQuery.trim(newTopicTitle) == "")
    {
        showMessage(i18n['zohodiscussions.writePost.TopicTitleCannotbeEmptymessage'],'failure');
        return;
    }
    if(newTopicTitle.length > 200)
    {
        showMessage(i18n['zohodiscussions.writePost.TopicTitleLengthMsg'],'failure');
        return;
    }
    var authorId = $this.attr('authorId');
    var editTopicTitle = {};
    if(ZUID == authorId)
    {
        editTopicTitle.access = "author";
    }
    editTopicTitle.forumGroupId = forumGroupId;
    editTopicTitle.forumTopicId = forumTopicId;
    editTopicTitle.forumId = forumId;
    editTopicTitle.categoryId = categoryId;
    editTopicTitle.topicTitle = newTopicTitle;
    editTopicTitle[csrfParamName] = csrfToken;
    doAjaxAction('/editTopicTitle.do',editTopicTitle,function(data)//No internationalization
    {
        var responseData = eval(data);
        if(responseData.result == "failure")
        {
            showTipper(i18n['zohodiscussions.singlepost.topicTitleUpdateErrordMsg'],'failure');
        }
        else
        {
            removeTopicListCache();
            showTipper(i18n['zohodiscussions.singlepost.topicTitleUpdatedMsg'],'success');
            loadSinglePost(forumTopicId);
        }
    });
}//function editTopicTitle($this,forumTopicId,$titleEditor)

//this method is used to link one topic to another topic 
function linkToTopic()
{
    $('#linkToTopicTemplate').html($('#dimDivLinkTO').html());
    $('#dimDivLinkTO').html('');
    $('#linkToTopicTemplate').show();
    $('#linkTopicUrl').focus();
    $('#cancelLinkTo').click(function()
    {
        $this = $(this);
        $('#dimDivLinkTO').html($('#linkToTopicTemplate').html());
        $('#linkToTopicTemplate').hide();
        $('#linkToTopicTemplate').html('');
    });
     
    $('#saveLinkToTopic').click(function()
    {
        $this = $(this);
        var currentTopicId = $this.attr('currentTopicId');
        var url_pattern = "^(ht|f)tp(s?)\:\/\/[0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*(:(0-9)*)*(\/?)([a-zA-Z0-9\-\.\?\,\:\'\/\\\+=&amp;%\$#_]*)?$";
        var topicPattern1 = "#Topic/";
        var topicPattern2 = "?ftid="
        var topicPattern3 = "/topic/"//No I18N
        var linkToTopicUrl = $('#linkTopicUrl').val();
        if(jQuery.trim(linkToTopicUrl) == "")
        {
            showMessage(i18n['zohodiscussions.createforumgroup.LinkEmpty'],'failure');
            return;
        }
        linkToTopicUrl = $.trim(linkToTopicUrl);
        if((linkToTopicUrl.match(url_pattern)))
        {
            if(linkToTopicUrl.indexOf(topicPattern1) > -1 || linkToTopicUrl.indexOf(topicPattern2) > -1 || linkToTopicUrl.indexOf(topicPattern3))
            {
                 var options = {};
                 options.forumGroupId = forumGroupId;
                 options.currentTopicId  = currentTopicId ;
                 options.linkToTopicUrl= linkToTopicUrl;
                 options[csrfParamName] = csrfToken;
                 doAjaxAction('/addLinkToTopic.do',options,function(data)//No internationalization
                 {
                    if(data == "SUCCESS")
                    {
                       removeTopicListCache();
                       loadSinglePost(currentTopicId);
                       showTipper(i18n['zohodiscussions.singlepost.topicLinkedSuccessMessage'],'success');
                       $('#linkToTopicTemplate').hide();
                    }
                    else if(data == "FAILURE")
                    {
                         showTipper(i18n['zohodiscussions.singlePost.requestedURLnotfoundMessage'],'failure');
                    }
                    else if(eval(data).result == 'failure')
                    {
                       var message = eval(data).reason;
                       showTipper(i18n[message],'failure');
                    }
                 });
            }
            else
            {
                showTipper(i18n['zohodiscussions.settings.PleaseEnteraValidurl'],'failure');
            }
        }
        else
        {
            showTipper(i18n['zohodiscussions.settings.PleaseEnteraValidurl'],'failure');
        }
    });
}//function linkToTopic()

//this is used to delete the linked topic
function deletelinkedTopic($this)
{
    var forumTopicId = $this.attr('currentTopicId');
    var linkedTopicId = $this.attr('linkedTopicId');
    var location = $this.attr('location');
    var options = {};
    options.forumGroupId = forumGroupId;
    options.forumTopicId  = forumTopicId ;
    options.linkedTopicId= linkedTopicId;
    options[csrfParamName] = csrfToken;
    if(confirm(i18n['zohodiscussions.singlepost.removeLinkConfirmationMess']))
    {
        doAjaxAction('/deleteLinkedTopic.do',options,function(data)//No internationalization
        {
            if(data == "SUCCESS")
            {
                removeTopicListCache();
                showTipper(i18n['zohodiscussions.singlePost.deleteLinkedTopicMessage'],'success');
                if(location == "topicList")
                {
                    getForumTopics(-1,-1,1,"Home");
                }
                else if(location == "singlepost")
                {
                    loadSinglePost(forumTopicId);
                }
            }
            else if(data == "FAILURE")
            {
                showTipper(i18n['zohodiscussions.generalmessage.errorOccured'],'failure');
            }
        });
    }
}//function deletelinkedTopic($this)

function deletePublishedAttachment($target,event)
{
    if(confirm(i18n['zohodiscussions.generalmessage.deleteAttachmentConfirmMsg']))
    {
        showSmallLoadingImage(event);
        $this = $target
        var deletingAttachmentId = $this.attr('attachmentId');
        var forumTopicId = $this.attr('forumTopicId');
        var responseId = $this.attr('responseId');
        var attachmentDiv = (typeof responseId != "undefined") ? responseId : forumTopicId;
        var options = {};
        options.forumGroupId = forumGroupId;
        options.forumTopicId = $this.attr('forumTopicId');
        options.fileName = $this.attr('attachmentName');
        options.fileId = deletingAttachmentId;
        options[csrfParamName] = csrfToken;
        doAjaxAction('/deleteAttachment.do',options , function(data)//No internationalization
        {
            if(data == "SUCCESS")
            {
                showTipper(i18n['zohodiscussions.generalmessage.deleteAttachmentSuccessMsg'],'info');
                if($('#SinglePostContainer').length > 0)
                {
                    hideLoadingImage();
                    showLoadingImage();
                    removeTopicListCache();
                    loadSinglePost(forumTopicId,false);
                }
                else if($('#topicList').length > 0 || $('#topicsList').length > 0)
                {
                    $('#topicListMainContainer').attr('shouldReload',"true");
                    //user is adding response from topic list page
                    if($('#currentCategoryContext').length > 0)
                    {
                        $('#currentCategoryContext').trigger('click');
                    }
                    else
                    {
                        $('#currentForumContext').trigger('click');
                    }
                }
                else if(($('#topicContent_'+attachmentDiv).length > 0))
                { 
                    $('#topicContent_'+attachmentDiv).find('li[attachmentId ='+deletingAttachmentId+']').remove();
                    if(($('#topicContent_'+attachmentDiv).find('li.singleList').length == 0))
                    {
                        ($('#topicContent_'+attachmentDiv).find('div.Attachments')).remove();
                    }
        
                }
            }
        });
    }//
}
function openEmailTopicDialog($target)
{
    var $this = $target;
    var title = $this.attr('topicTitle');
    var forumTopicId = $this.attr('forumTopicId');
    forumTopicId = forumTopicId || $this.parents('div[parentCont="actualParent"]').attr('forumTopicId');
    var forumGroupId = forumGroupId;
    
    var $emailDialog = $('#emailTopicPrompt');

    $emailDialog.find(':input[name="Subject"]').val(title);
    $emailDialog.find(':input[name="forumTopicId"]').val(forumTopicId);
    $emailDialog.find(':input[name="topicTitle"]').val(title);
    $emailDialog.find(':input[name="emailIds"]');
    $emailDialog.show().parent().show();
    $emailDialog.find(':input[name="emailIds"]').focus();

    return false;
}//function emailPost()

function emailTopic(event)
{
    var $this = $(event.target);
    $this.html(i18n['zohodiscussions.singlePost.sending']);
    var $emailDialog = $('#emailTopicPrompt');
    if(validate($emailDialog.find('form')) == true)
    {
        doAjaxAction(
            "/eMailTopic.do", //No I18N
            $emailDialog.find('form').serialize(),
            function (data)
            {
                if(data == "SUCCESS")
                {
                    showTipper(i18n['zohodiscussions.singlepost.mailsentmessage'],'success');
                    $this.html(i18n['zohodiscussions.general.send']);
                    cancelEmailTopic();
                }//if(data == "SUCCESS")
            },
            function (err)
            {
                if(err.responseText.indexOf("'result':'failure'") > 0)
                {
                    var responseData = eval(err.responseText);
                    showMessage(responseData.reason,'failure');
                    $this.html(i18n['zohodiscussions.general.send']);
                }
                else
                {
                   showTipper(i18n['zohodiscussions.errorpage.requestedURLisnotfoundMess'],'failure',1000);
                }                  
            }
        );
        return false;
    }//if(validate($emailDialog.find('form')) == true)
    else
    {
        $this.html(i18n['zohodiscussions.general.send']);
    }
    return false;
}//function emailTopic()

function cancelEmailTopic()
{
    var $emailDialog = $('#emailTopicPrompt');
    $emailDialog.hide().parent().hide();
    $emailDialog.find(':input[name="emailIds"]').val('');
    $emailDialog.find(':input[name="Subject"]').val('');
    $('#emailContentArea').val('');
    return false;
}
function singlePostApproveAction($target)
{
    var action = $target.attr('action');
    var forumTopicId = $target.attr('forumTopicId');
    var forumId = $target.attr('forumId');
    var categoryId = $target.attr('categoryId');
    var itemType = $target.attr('itemType');

    var options = {};
    options.forumGroupId = forumGroupId;
    options.forumTopicId = forumTopicId;
    options.forumId = forumId;
    options.categoryId = categoryId;
    options.authorId = $target.attr('authorId');
    options[csrfParamName] = csrfToken;
    if(itemType == "response")
    {
        var responseId = $target.attr('responseId');
        options.responseId = responseId;
    }
    doAjaxAction(action,options,function(data)//No internationalization
    {
        if(data == "SUCCESS")
        {
            removeTopicListCache();
            var successMsg = i18n['zohodiscussions.moderationList.topicApprovedMess'];
            if(itemType == "response")
            {
                successMsg = i18n['zohodiscussions.moderationList.responseApprovedMess'];
            }
            showTipper(successMsg,'info',4000);
            loadSinglePost(forumTopicId);
        }
    });
}
//data send to spamaction
function singlePostSpamAction($this,$location)
{  
    var postType = $this.attr('postType');
    if(postType == "topic")
    {
        postType = i18n['zohodiscussions.moderationList.topic'];//No I18N
    }
    else if(postType == "response")
    {
        postType = i18n['zohodiscussions.moderationList.response'];//No I18N
    }
    var spamValue = $this.attr('spamValue');
    var confirmMess = "";
    if(moderatorForSpam == "true")
    {
        if(spamValue == 1)
        {
          confirmMess = i18n['zohodiscussions.singlepost.spamActionconfirmationmessage1']+" "+postType+" "+i18n['zohodiscussions.singlepost.inappropriateActionconfirmationmessage2']; //No I18N
        }
        else
        {
          confirmMess = i18n['zohodiscussions.singlepost.spamActionconfirmationmessage3']+" "+postType+" "+i18n['zohodiscussions.singlepost.appropriateActionconfirmationmessage2']; //No I18N
        }
        if(confirm(confirmMess))
        {   
            spamAction($this,postType,$location);
        }
    }
    else
    {
        if(spamValue == 1)
        {
            $('#spamStatusMsg').show();
            $('#spamDetails_Text').html(""); //No I18N
            $('#spamContentDetails').unbind('click').click(function()
            {   
                var spamDetails = $('#spamDetails_Text').val();
                spamDetails =$.trim(spamDetails);
                if(spamDetails == "")
                {
                    showMessage(i18n['zohodiscussions.singlePost.EmptyMsgError'],'failure'); //No I18N
                    return;
                }
                spamAction($this,postType,$location,"appropriate",spamDetails); //No I18N
            });
        }
        else
        {
            if(confirm(i18n['zohodiscussions.singlepost.spamActionconfirmationmessage3']+" "+postType+" "+i18n['zohodiscussions.singlepost.appropriateActionconfirmationmessage2'])) //No I18N
            {
                spamAction($this,postType,$location,"appropriate"); //No I18N
            }
        }
    }
    return;
}
function spamAction($this,postType,$location,appropriate,spamDetails)
{       
    var forumTopicId = $this.attr('forumTopicId');
    forumTopicId = forumTopicId || $this.parents('div[parentCont="actualParent"]').attr('forumTopicId');
    var forumId = $this.attr('forumId');
    forumId = forumId || $this.parents('div[parentCont="actualParent"]').attr('forumId');
    var categoryId = $this.attr('categoryId');
    categoryId = categoryId || $this.parents('div[parentCont="actualParent"]').attr('categoryId');
    
    var options = {};
    var spamValue = $this.attr('spamValue');
    options.forumTopicId = forumTopicId;
    options.forumGroupId = forumGroupId;
    options.action = spamValue;
    options.postType = postType;
    options.purpose = appropriate;
    options.forumId = forumId
    options.categoryId = categoryId
    options[csrfParamName]=csrfToken;
    if(typeof spamDetails != "undefined")
    {
        options.spamDetails = spamDetails
    }
    var responseId = $this.attr('responseId');
    if(typeof responseId != "undefined")
    {
        options.responseId = responseId;
    }
    doAjaxAction
    (
        "/spamAction.do", //No I18N
        options,
        function (data)
        {
            $('#spamStatusMsg').hide();
            if(data == "SUCCESS")
            {   
                removeTopicListCache();
                if(spamValue == "1")
                {   
                    if(appropriate == "appropriate")
                    {
                        showTipper(i18n['zohodiscussions.singlepost.Inappropriatemarkedmessage1']+" "+postType+" "+i18n['zohodiscussions.singlepost.Inappropriatemarkedmessage2'],'success',1000);
                    }
                    else
                    {
                        showTipper(i18n['zohodiscussions.singlepost.spammarkedmessage1']+" "+postType+" "+i18n['zohodiscussions.singlepost.spammarkedmessage2'],'success',1000);
                    }
                }
                else
                {   
                    if(appropriate == "appropriate")
                    {
                        showTipper(i18n['zohodiscussions.singlepost.Inappropriatemarkedmessage1']+" "+postType+" "+i18n['zohodiscussions.singlepost.InappropriateRemovedmessage'],'success',1000);
                    }
                    else
                    {
                        showTipper(i18n['zohodiscussions.singlepost.spammarkedmessage1']+" "+postType+" "+i18n['zohodiscussions.singlepost.spamRemovedmessage'],'success',1000);
                    }    
                }
                if($location =="singlePost")
                {
                    loadSinglePost(forumTopicId);
                }
                else
                {   
                    if(moderatorForSpam == "true")
                    {
                        if(spamValue == 1)
                        {
                            processHash("home"); //No I18N
                        }
                        else 
                        {
                            $this.parent().remove();
                            $('#reportInappropriate_'+responseId).remove();
                        }
                    }
                    else
                    {   
                        if(spamValue == 1)
                        {   
                            var $reportInappropriate = $('#reportInappropriate_'+responseId);
                            $reportInappropriate.attr('spamValue','2');
                            $reportInappropriate.find('div.imgAshSpam').removeClass('imgAshSpam').addClass('imgNotSpamIcon');
                            $reportInappropriate.find('a').html(i18n['zohodiscussions.singlePost.Appropriate']); //No I18N
                            if( $('#reasonInappropriate_'+responseId).length > 0)
                            {
                                 var $reasonInappropriate = $('#reasonInappropriate_'+responseId);
                                 var reportCount = parseInt($reasonInappropriate.attr('reportCount'));
                                 reportCount = reportCount+1;
                                 $reasonInappropriate.find('span[purpose="inappropriateReason"]').html(i18n['zohodiscussions.singlePost.Inappropriate']+" ("+reportCount+")");
                                 $reasonInappropriate.attr('reportCount',reportCount);
                            }
                        }       
                        else
                        {   
                            var $reportInappropriate = $('#reportInappropriate_'+responseId);
                            $reportInappropriate.attr('spamValue','1');
                            $reportInappropriate.find('div.imgNotSpamIcon').removeClass('imgNotSpamIcon').addClass('imgAshSpam');
                            $reportInappropriate.find('a').html(i18n['zohodiscussions.singlePost.Inappropriate']); //No I18N
                        
                            var $reasonInappropriate = $('#reasonInappropriate_'+responseId);
                            var reportCount = parseInt($reasonInappropriate.attr('reportCount'));
                            reportCount = reportCount-1;
                            if(reportCount > 0)
                            {
                                $reasonInappropriate.attr('reportCount',reportCount);
                                $reasonInappropriate.find('span[purpose="inappropriateReason"]').html(i18n['zohodiscussions.singlePost.Inappropriate']+" ("+reportCount+")");
                            }
                            else
                            {
                                $reasonInappropriate.remove();
                            }    
                        }
                    }
                }
            }//if(data == "SUCCESS")
        },
        function (errordata)
        {
            var responseData = eval(errordata.responseText);
            if(responseData.result == "failure") //No I18N
            {
                 showMessage(responseData.reason,'failure'); //No I18N
            }
            
        }
    );
}//function callToSpamAction($this,postType)
/*
function refreshSingleResponse(responseId)
{
    doAjaxAction('/refreshSingleResponse.do?forumGroupId='+forumGroupId+'&responseId='+responseId,'',function(data)
    {
        var $postCont = $(data).find('div#recent_ResPonse_'+responseId);
        $('#recent_ResPonse_'+responseId).html($postCont.html()); //No I18N
        hideLoadingImage();
    });
}//function refreshSingleResponse(responseId)
*/
//this is used for single post widget actions
function singlePostWidgetActions(event)
{
   var $target = $(event.target);
   var $targetParent = $target.parent();
   var $location = "singlePost";
   if($targetParent.is('div[purpose="bookmark"]'))
   {
       bookMark($targetParent,event);      
   }
   else if($targetParent.is('div[purpose="watchAction"]'))
   {
       watchThisItem($targetParent,$location,event);       
   }
   else if(($targetParent.is('div[purpose="lockTopic"]')) || ($targetParent.is('#unLockTopic')))
   {
      lockTopicLink($targetParent,event);
   }
   else if($targetParent.is('div[purpose="moveTopic"]'))
   {
      moveTopic($targetParent);
   }
   else if($targetParent.is('div[purpose="stickyPost"]'))
   {
      stickyLink($targetParent,event);
   }
   else if($targetParent.is('div[purpose="moderateThisTopic"]'))
   {
     moderateAction($targetParent,$location,event);
   }
   else if($targetParent.is('div[purpose="changeTopicType"]'))
   {
     var forumTopicId = $targetParent.attr('forumTopicId');
     changeTopicType(forumTopicId);
   }
   else if($target.is('input[purpose="notifyAuthor"]'))
   {
     var forumTopicId = $target.attr('forumTopicId');
     updateNotification($target,forumTopicId,event);
   }
   else if($target.is('a[purpose="forumPostsFilter"]'))
   {
        hashPurpose = $target.attr('hashPurpose');
        processHash(hashPurpose);
        return false;
    }
}//function singlePostWidgetActions(event)

function changeTopicType(forumTopicId)
{
    
    $('#changeTopicTypeTemplate').html($('#changeTopicType_'+forumTopicId).html());
    $('#changeTopicType_'+forumTopicId).html('');
    $('#changeTopicTypeTemplate').show();
    
    $('#cancelTopicChange,#cancelChangingTopicType').click(function()
    {
        $('#changeTopicType_'+forumTopicId).html($('#changeTopicTypeTemplate').html());
        $('#changeTopicTypeTemplate').hide();
        $('#changeTopicTypeTemplate').html('');
    }); 
    
    $('#topicTypeListForChange').change(function()
    {
       var $this = $(this); 
       if($this.val () == 1)
       {
           $('#postExpiryDays_'+forumTopicId).show();
       }
       else
       {
           $('#postExpiryDays_'+forumTopicId).hide();
       }
    });
    
    $('#doChange_'+forumTopicId).click(function()
    { 
      var $this = $(this); 
      var value=$('#topicTypeListForChange').val();
      var forumId = $this.attr('forumId');
      var categoryId= $this.attr('categoryId');
      var isTopicOwner = $this.attr('isTopicOwner');
      var authorId = $this.attr('postAuthorId');
      var options = {}
      if(isTopicOwner == "true")
      {
        options.access = "author";
      }
      if(value == 1)
      {
        var expiryDay = $('#announcementExpiryDays_'+forumTopicId).val();
        options.expiryDay = expiryDay;
      }
      options.authorId = authorId; 
      options.forumGroupId = forumGroupId;
      options.forumTopicId = forumTopicId;
      options.forumId = forumId;
      options.categoryId = categoryId;
      options.postTopicType=value;
      options[csrfParamName]=csrfToken;
      doAjaxAction('/updateTopicType.do',options, function(data)//No internationalization
      {
          if(data == "failure")
          {
              showTipper(i18n['zohodiscussions.singlePost.updateTopicTypeErrorMessage'],'failure');
          }
          else
          {
              removeTopicListCache();
              loadSinglePost(forumTopicId);
              $('#changeTopicTypeTemplate').hide();
          }
      });
    });
}
function updateNotification($this,forumTopicId,event)
{
    var options = {};
    options.forumGroupId = forumGroupId;
    options.forumTopicId = forumTopicId;
    options.access = "author";
    options.currNotifyStatus = $this.attr('checked');
    options[csrfParamName]=csrfToken;
    showSmallLoadingImage(event);
    doAjaxAction('/updateNotify.do', options, function(data)//No internationalization
    {
        removeTopicListCache();
        showTipper(i18n['zohodiscussions.singlepost.Notificationsavedmessage'],'success',1000);
        loadSinglePost(forumTopicId);
    });//$.get('/updateNotify.do?',options,function()
}
//this is used to moderate and unmoderate the topic
function moderateAction($this,$location,event)
{   
    var forumTopicId = $this.attr('forumTopicId');
    forumTopicId = forumTopicId || $this.parents('div[parentCont="actualParent"]').attr('forumTopicId');
    var forumId = $this.attr('forumId');
    forumId = forumId || $this.parents('div[parentCont="actualParent"]').attr('forumId');
    if($this.attr('moderationStatus') == "moderate")
    {
       var moderateTopic = {};
       moderateTopic.forumTopicId = forumTopicId;
       moderateTopic.forumGroupId = forumGroupId;
       moderateTopic.forumId = forumId;
       moderateTopic[csrfParamName] = csrfToken;
       showSmallLoadingImage(event);
       doAjaxAction('/moderateTopic.do',moderateTopic,function(data)//No internationalization
       {
	   if(data == "SUCCESS")
	    {
                removeTopicListCache();
		$this.attr('moderationStatus',"moderated");
		showTipper(i18n['zohodiscussions.singlepost.Now']+i18n['zohodiscussions.singlepost.topicundermoderationmessage'],'success',2000);
                if($location == "singlePost")
                {   
                  $('#moderateTopicText').html(i18n['zohodiscussions.singlepost.unmoderatethistopicmessage']);
                }
                else
                {
                  $this.find('a[purpose = "moderateTopicText"]').html(i18n['zohodiscussions.singlepost.unmoderatethistopicmessage']);
                }
	    }
	    else
	    {
		showTipper(i18n['zohodiscussions.singlepost.Moderationfailed'],'success',2000);
	    }
           hideLoadingImage();
       });
    }//if($this.is('.block') == true)
    else if($this.attr('moderationStatus') == "moderated")
    {
        var unModerateTopic = {};
        unModerateTopic.forumTopicId = forumTopicId;
        unModerateTopic.forumGroupId = forumGroupId;
        unModerateTopic[csrfParamName] = csrfToken;
    doAjaxAction('/unModerateTopic.do',unModerateTopic,function(data)//No internationalization
	{
	    if(data == "SUCCESS")
	    {
                removeTopicListCache();
                $this.attr('moderationStatus',"moderate");
                showTipper(i18n['zohodiscussions.singlepost.moderationtopicremoved'],'success',2000);
                if($location == "singlePost")
                { 
                  $('#moderateTopicText').html(i18n['zohodiscussions.singlepost.moderatethistopicmessage']);
                }
                else
                {
                  $this.find('a[purpose = "moderateTopicText"]').html(i18n['zohodiscussions.singlepost.moderatethistopicmessage']);
                }
                
	    }//if(data == "SUCCESS")
	    else
	    {
		showTipper(i18n['zohodiscussions.singlepost.Moderationfailed'],'success',2000);
	    }
	});
    }//else if($this.is('.blocked') == true)
}//function moderateTopic(forumTopicId)

 //this method is used to  move topic from one forum to another  forum
function moveTopic($moveTopicLink)
{
    var forumTopicId = $moveTopicLink.attr('forumTopicId'); 
    $('#moveTopicTemplate').html($('#moveTopic_'+forumTopicId).html());
    $('#moveTopic_'+forumTopicId).html('');
    loadCategoriesToMove($('#forumListForMove').val());
    $('#moveTopicTemplate').show();
    var $forumListForMove = $('#forumListForMove');
    var $forumListForModerator = $('#forumListForModerator');
    if($moveTopicLink.attr('moderatorUser') == 'yes')
    {
        $forumListForModerator.hide();
        $forumListForMove.show();
        $forumListForMove.val($moveTopicLink.attr('forumId'));
        loadCategoriesToMove($moveTopicLink.attr('forumId'));
        $('#moveToCategory').val($moveTopicLink.attr('categoryId'));
    }
    else
    {
        $forumListForMove.hide();   
        $forumListForModerator.show();
        loadCategoriesToMove($forumListForModerator.val());
    }
     
    $('#cancelMove,#cancelMoveTopic').click(function()
    {
        $('#moveTopic_'+forumTopicId).html($('#moveTopicTemplate').html());
        $('#moveTopicTemplate').hide();
        $('#moveTopicTemplate').html('');
        $('#doMove').html(i18n['zohodiscussions.singlePost.Movetopic']);
    }); 
    
    $('#forumListForMove,#forumListForModerator').change(function()
    {
        var currentForumId = $moveTopicLink.attr('forumId'); 
        var destinationForumId = $(this).val();
        if(currentForumId == destinationForumId )
        {
          $('#doMove').attr('disabled', true );
        }
        else
        {
          $('#doMove').attr('disabled',false);
        }
        loadCategoriesToMove($(this).val());
    });
    
    $('#doMove').unbind('click').click(function()
    {
        var $moveButton = $(this);
        $moveButton.html(i18n['zohodiscussions.singlePost.Moving']);
        var modratorUser = 0;
        if($moveTopicLink.attr('moderatorUser') == 'yes')
        {
           modratorUser = 1;
        }
        var isTopicOwner = $(this).attr('isTopicOwner');
      
        
        var args = {};
        args.forumTopicId = forumTopicId;
        args.forumId = $('#forumListForMove').val();
        if(modratorUser == 0)
        {
            args.forumId = $('#forumListForModerator').val();
        }
        if(isTopicOwner)
        {
          args.topicowner = "true";
        }
        var $categoryListCont = $('#moveToCategory');
        var doescategoryExists = $categoryListCont.is(":visible");
        args.categoryId = (doescategoryExists == true)?$categoryListCont.val():-1;    
        args.forumGroupId = forumGroupId;
        args[csrfParamName]= csrfToken;
        if(!args.categoryId) args.categoryId = '';
        doAjaxAction('/moveTopic.do', args, function(data)//No internationalization
        {
            var responseData = eval(data);
            if(responseData.result == "success")
            {
                removeTopicListCache();
                $('#moveTopicTemplate').hide();
                $('#moveTopicTemplate').html('');
                //showTipper(responseData.reason,'success');//dont delete this commented code// it will display the details of forum/category
                showTipper(i18n['zohodiscussions.generalmessage.moveTopicSuccessMsg'],'success',3000);
                loadSinglePost(forumTopicId);
            }
            else
            {
                $moveButton.html(i18n['zohodiscussions.singlePost.Movetopic'])
                showMessage(responseData.reason,'failure');
            }
        });
    });
 }//function moveTopic($this,forumTopicId)
 //this is used for load categories for each forum
function loadCategoriesToMove(forumId)
{
	//load categories for this forum
	categoriesForForum = $('#categoryListFormove').val().split('$$');
	$('#moveToCategory').hide().parent().hide();
	$.each(categoriesForForum, function(index, item)
	{
            if(item.indexOf(forumId+':') > -1)
            {
                $('#moveToCategory').html(item.split(':')[1]).show().parent().show();
                return;
            }
	});
}//function loadCategoriesToMove(forumTopicId, forumId)
function singlePostTagActions(forumTopicId,givenHashKey)
{
    $('#forumTopicTags').find('div[purpose = "deleteTag"]').click(function()
    {
        if(confirm(i18n['zohodiscussions.singlepost.tagDeleteConfirmMsg']))
        {
            $this = $(this);
            var deletePostTags = {};
            var postTagId = $this.attr('postTagId');
            var tagName = $this.attr('eachTagName');
            var zuid = $this.attr('zuid');
            var forumId = $this.attr('forumId');
            var postAuthorId = $this.attr('postAuthorId');
            if(postAuthorId == zuid)
            {
                deletePostTags.access = "author";
            }
            deletePostTags.forumGroupId = forumGroupId;
            deletePostTags.forumTopicId = forumTopicId;
            deletePostTags.forumId = forumId;
            deletePostTags.postTagId = postTagId;
            deletePostTags[csrfParamName] = csrfToken;
            doAjaxAction('/deleteForumPostTags.do',deletePostTags,function(data)//No internationalization
            {
                if(data == "SUCCESS")
                {
                    removeTopicListCache();
                    showTipper("<i>"+tagName+" </i> "+i18n['zohodiscussions.singlepost.tagDeletedMsg'],'info',3000);
                    loadSinglePost(forumTopicId); 
                }//if(data == "SUCCESS")
            });
        }//if(confirm(i18n['zohodiscussions.singlepost.tagDeleteConfirmMsg']))
    });//$('#forumTopicTags').find('div[purpose = "deleteTag"]').click(function()
    $('#addTagsForPost,#addNewTag').click(function()
    {
        $('#addPostTags').show();
        $('#addPostTags').find(':input[name="postTags"]').focus();
    });
    $('#cancelTags').click(function()
    {
        $('#addPostTags').hide();
        $('#addPostTags').find(':input[name="postTags"]').attr('value'," ");
    });
    
    $('#savePostTags').click(function()
    {
      $this = $(this);
      var $cont =  $('#addPostTags');
      var postTags = $cont.find(':input[name="postTags"]').val();
      postTags = postTags.replace(/^\s+|\s+$/g,' ').replace(/\s+/g,' ');
      var flag = "false";
      if(postTags != "")
      {
        if(postTags.match(/^[^\^()~`!@#$%&:;\/?|<>{}[\]*-+=]+$/) == null)
        {
            hideLoadingImage();
            showMessage(i18n['zohodiscussions.singlepost.specialCharacterNotAllowedMsg'],'failure');
            enablePostButtons();
            return;  
        }
      }//if(postTags != "")
      var checkEmpty =postTags.split(",");
      for(var i=0;i<checkEmpty.length;i++)
      {
        if(checkEmpty[i].length > 50)
        {
            showTipper(i18n['zohodiscussions.singlepost.TagexceedMessage'],'failure');
            return;   
        }
        if(!((checkEmpty[i]) == "") && !(jQuery.trim(checkEmpty[i])) == "")
        {
          flag = "true";
        }
      }
      if(flag == "false")
      {
         showMessage(i18n['zohodiscussions.singlepost.tagNameEmptyMsg'],'failure');
         return;
      }
      if(postTags.indexOf("-") < 0)
      {
        var forumId = $this.attr('forumId');
        var postAuthorId = $this.attr('postAuthorId');
        var addPostTagsOption ={};
        if(postAuthorId == ZUID)
        {
          addPostTagsOption.access = "author";
        }
        addPostTagsOption.forumId = forumId;
        addPostTagsOption.postTags = postTags;
        addPostTagsOption.forumGroupId = forumGroupId;
        addPostTagsOption.forumTopicId = forumTopicId;
        addPostTagsOption[csrfParamName] = csrfToken;
        if(jQuery.trim(postTags) == "")
        {
            showMessage(i18n['zohodiscussions.singlepost.tagNameEmptyMsg'],'failure');
            return;
        }
        doAjaxAction('/addNewTagsForPost.do',addPostTagsOption,function (data)//No internationalization
        {
            var responseData = eval(data);
            if(responseData.result == "SUCCESS")
            {
                removeTopicListCache();
                showTipper(i18n['zohodiscussions.singlepost.tagAddedMsg'],'success',2000);
                loadSinglePost(forumTopicId,false);
            }
        });
      }
    });
    
    $('#forumTopicTags').find('[purpose="getTagRelatedPosts"]').unbind('click').click(function()
    {
        $this = $(this);
        givenHashKey = givenHashKey || 'Tag';
        var hashPurpose = $this.attr('hashPurpose');
        processHash(hashPurpose);
    });
}//function singlePostTags(forumTopicId)

function changeTopicLabel($this)
{
    var $topicStatusList = $('#statusList');
    var topicLabelId = $this.attr('topicLabelId');//No internationalization
    var forumTopicId = $topicStatusList.attr('forumTopicId');//No internationalization
    var forumId = $topicStatusList.attr('forumId');//No internationalization
    showSmallLoadingImageForCont($('#statusContainer'),0,130);
    var params = {};
    params.forumGroupId = forumGroupId;
    params.forumTopicId = forumTopicId;
    params.forumId = forumId;
    params.topicLabelId = topicLabelId;
    params[csrfParamName] = csrfToken;

    doAjaxAction(
        "/updateTopicLabel.do",
        params,
        function(data)
        {
            if(data == "success")
            {
                removeTopicListCache();
                showTipper(i18n['zohodiscussions.singlePost.updateTopicLabelSuccessMsg'],'success');
                loadSinglePost(forumTopicId);
            }
            else
            {
                showMessage(i18n['zohodiscussions.singlePost.updateTopicLabelErrorMessage'],'failure');
            }
        },
        function(errorData)
        {
            
        }
    );
} 
function watchThisItem($this,$location,event)
{
    var hashPurpose = $this.attr('hashPurpose');
    var itemType = $this.attr('itemType');
    var itemId = $this.attr('itemId');
    itemId = itemId || $this.parents('div[parentCont="actualParent"]').attr('forumTopicId');
    var status = $this.attr('status');
    var itemName =$this.attr('itemName') 
    var watchOptions={};
    watchOptions.itemType =itemType;
    watchOptions.itemId = itemId;
    watchOptions.forumGroupId = forumGroupId;
    watchOptions[csrfParamName]=csrfToken;
    if(status == "watch")
    {
        showSmallLoadingImage(event);
        doAjaxAction('/watchItem.do',watchOptions,function(data)//No internationalization
        {
            if(data == "SUCCESS")
            {
                removeTopicListCache();
                if(itemType == 0)
                {
                    showTipper(i18n['zohodiscussions.singlepost.watchTopicSuccessMsg'],'success',3000);

                    if($location == "singlePost")
                    {
                        loadSinglePost(itemId,false);
                    }
                    else if($location == "singleTopicWatch")
                    {
                        $this.attr('status','unwatch');
                        var $thisParent = $this.parent();
                        $thisParent.removeClass('smallAshBox').addClass('smallAshBoxShow');
                        $this.removeClass('imgSmallWatch').addClass('imgSmallWatchSel');
                        hideLoadingImage();
                    }
                    else
                    {
                        $this.attr('status','unwatch');
                        $this.find('a[purpose = "watchItemText"]').html(i18n['zohodiscussions.singlePost.unwatchTopic']);
                        hideLoadingImage();
                    }
                }
                else if(itemType == 2)
                {
                    showTipper( i18n['zohodiscussions.widgetscontainer.watchForumSuccessMsg'],'success',3000);
                    $this.attr('status','unwatch');
                    //this is forum filter
                    if(hashPurpose != "type")
                    {
                        processHash(hashPurpose);
                    }
                    else
                      {
                          $this.find('a').html(i18n['zohodiscussions.general.Unwatch']+" "+itemName);
                          $('#ajaxLoaderSmall').hide();
                      }
                    return false;
                }
                else if(itemType == 1)
                {
                    showTipper( i18n['zohodiscussions.widgetscontainer.watchCategorySuccessMsg'],'success',3000);
                    $this.attr('status','unwatch');
                    //this is forum filter
                    if(hashPurpose != "type")
                    {
                        processHash(hashPurpose);
                    }
                    else
                      {
                          $this.find('a').html(i18n['zohodiscussions.general.Unwatch']+" "+itemName);
                          $('#ajaxLoaderSmall').hide();
                      }
                    return false;
                }
            }
        });
    }//if(status == "watch")
    else
    {
        var confirmMess = "";
        if(itemType == 0)
        {
            confirmMess = i18n['zohodiscussions.singlepost.unwatchTopicConfirmMsg1'];
        }
        else if(itemType == 1)
        {
            confirmMess = i18n['zohodiscussions.singlepost.unwatchCategoryConfirmMsg3'];
        }
        else if(itemType == 2)
        {
            confirmMess = i18n['zohodiscussions.singlepost.unwatchForumConfirmMsg2'];
        }
        if(confirm(confirmMess))
        {
            var unWatchOptions={};
            unWatchOptions.itemId = itemId;
            unWatchOptions.forumGroupId = forumGroupId;
            unWatchOptions[csrfParamName]=csrfToken;
            showSmallLoadingImage(event);
            doAjaxAction('/unWatch.do',unWatchOptions, function(data)//No internationalization
            {
                if(data == "SUCCESS")
                {
                    removeTopicListCache();
                    if(itemType == 0)
                    {
                        showTipper(i18n['zohodiscussions.singlepost.unwatchTopicSuccessMsg'],'info',3000); 
                        if($location == "singlePost")
                        {
                            loadSinglePost(itemId,false);
                        }
                        else if($location == "singleTopicWatch")
                        {
                            $this.attr('status','watch');
                            var $thisParent = $this.parent();
                            $thisParent.removeClass('smallAshBoxShow').addClass('smallAshBox');
                            $this.removeClass('imgSmallWatchSel').addClass('imgSmallWatch');
                            hideLoadingImage();
                        }
                        else
                        {
                            $this.attr('status','watch');
                            hideLoadingImage();
                        }
                    }
                    else if(itemType == 2)
                    {
                        showTipper( i18n['zohodiscussions.widgetscontainer.unwatchForumSuccessMsg'],'success',3000);
                        $this.attr('status','watch');
                        if(hashPurpose != "type")
                        {
                            processHash(hashPurpose);
                        }
                        else
                        {
                            $this.find('a').html(i18n['zohodiscussions.general.watch']+" "+itemName);
                            $('#ajaxLoaderSmall').hide();
                        }
                        return false;
                    }
                    else if(itemType == 1)
                    {
                      showTipper( i18n['zohodiscussions.widgetscontainer.unwatchCategorySuccessMsg'],'success',3000);
                      $this.attr('status','watch');
                      //this is forum filter
                      if(hashPurpose != "type")
                      {
                          processHash(hashPurpose);
                      }
                      else
                      {
                          $this.find('a').html(i18n['zohodiscussions.general.watch']+" "+itemName);
                          $('#ajaxLoaderSmall').hide();
                      }
                      return false;
                    }
                }//if(data == "SUCCESS")
            });
        }//if(confirm("Are you suer to Unwatch this topic"))
    }//else
}//function watchItem()
function bookMark($this,event)
{
        var status = $this.attr('status');
        var bookmarkOptions = {};
        bookmarkOptions.forumGroupId = forumGroupId;
        bookmarkOptions.forumTopicId = $this.attr('forumTopicId');
        bookmarkOptions[csrfParamName]=csrfToken;
        showSmallLoadingImage(event);
        if(status == "bookmark")
        {
          doAjaxAction('/addBookMark.do', bookmarkOptions, function(data)//No internationalization
          {
              hideLoadingImage();
              if(data == "failure")
              {
                  showTipper(i18n['zohodiscussions.singlePost.bookMarkErrorMessage'],'failure');
              }
              else
              {
                  removeTopicListCache();
                  showTipper(i18n['zohodiscussions.singlepost.bookmarkTopicSuccessMsg'],'success',3000);
                  $this.attr('status','removeBookmark');
                  $this.find('a').html(i18n['zohodiscussions.singlePost.removeBookmark']);
              }
          });
        }
        else
        {
          doAjaxAction('/removeBookMark.do',bookmarkOptions,function(data)//No internationalization
          {
              hideLoadingImage();
              if(data == "failure")
              {
                  showTipper(i18n['zohodiscussions.singlePost.removeBookMarkErrorMessage'],'failure');
              }
              else
              {
                  removeTopicListCache();
                  showTipper(i18n['zohodiscussions.singlePost.removeBookmarkMsg'],'info',3000);
                  $this.attr('status','bookmark');
                  $this.find('a').html(i18n['zohodiscussions.singlePost.bookmarkTopic']);
              }
          });
        }
   }//function bookmark()
// this is used for changing normal post to sticky post 
function stickyLink($this,event)
{
    var action = 0;
    var status = $this.attr('status');
    var isSticky = $this.attr('isSticky');
    if(isSticky == "true")
    {
        action = 1;  
    }
    //var actionToDo = (status == "stickyPost")?"":"";
    var stickyActionOptions ={};
    stickyActionOptions.forumGroupId = forumGroupId ;
    stickyActionOptions.forumTopicId =  $this.attr('forumTopicId');
    stickyActionOptions.action = action;
    stickyActionOptions[csrfParamName]= csrfToken;
    showSmallLoadingImage(event);
    doAjaxAction('/stickyAction.do',stickyActionOptions,function(data)//No internationalization
    {
        if(data == "SUCCESS")
        {
            removeTopicListCache();
            if(status == "stickyPost")
            {
                showTipper(i18n['zohodiscussions.singlepost.stickyPostSuccessMsg'],'success',3000);
                $this.attr('status','normal');
                $this.attr('isSticky','true');
                $('#stickyPostText').html(i18n['zohodiscussions.singlePost.notStickyPost']);
            }
            else
            {
                showTipper(i18n['zohodiscussions.singlePost.removeStickyPostMsg'],'info',3000);
                $this.attr('status','stickyPost');
                $this.attr('isSticky','false');
                $('#stickyPostText').html(i18n['zohodiscussions.singlePost.makeStickyPost']); 
            }
            hideLoadingImage();
        }//if(data == "SUCCESS")
    });
}//function stickyLink($this,forumTopicId)
function lockTopicLink($this,event)
{
    var action = 0;
    var status = $this.attr('status');
    var isLocked = $this.attr('isLocked');
    var forumTopicId = $this.attr('forumTopicId');
    if(isLocked == "true")
    {
        action = 1;  
    }
    var actionToDo = (status == "lockTopic")?i18n['zohodiscussions.singlepost.lockConfirmationMsg']:i18n['zohodiscussions.singlepost.unlockConfirmationMsg'];
    if(confirm(actionToDo))
    {
        var lockActionOptions ={};
        lockActionOptions.forumGroupId = forumGroupId ;
        lockActionOptions.forumTopicId = forumTopicId;
        lockActionOptions.action = action;
        lockActionOptions[csrfParamName]= csrfToken;
        showSmallLoadingImage(event);
        doAjaxAction('/lockAction.do',lockActionOptions,function(data)//No internationalization
        {
            if(data == "SUCCESS")
            {
                removeTopicListCache();
                if(status == "lockTopic")
                {
                    showTipper(i18n['zohodiscussions.singlepost.lockTopicSuccessMsg'],'info',3000);
                }
                else
                {
                    showTipper(i18n['zohodiscussions.singlepost.unlockTopicSuccessMsg'],'info',3000);
                }
                loadSinglePost(forumTopicId,false);
            }//if(data == "SUCCESS")
        });
    }//if(confirm("Are you sure do you want to lock this topic?"))
}//function lockTopicLink($this,$lockTopic)

//method to add a response/thread
function addForumResponse(forumTopicId,editorMode,responseId)
{
    showLoadingImage(i18n['zohodiscussions.general.publishing']);
    var contentToPost = $('#postContentTA').data('editor').val();
    contentToPost = contentToPost.replace(/^\s+/g, '').replace(/\s+$/g, ''); //replace(/<[^>]*>/ig, '')
    if (contentToPost == '' )
    {
        hideLoadingImage();
        showMessage(i18n['zohodiscussions.writePost.noContentInPost'],'failure');
        return;
    }
    $('#postContentTA').val(contentToPost);
    var newResponseAction = (editorMode && editorMode == "Edit")?"/updateResponse.do":(ZUID == -1)?"/addGuestForumResponse.do":"/addForumResponse.do";
    doAjaxAction(
    newResponseAction, 
    $('#editorHolder').serialize(),
    function (data)
    {
        hideLoadingImage();
        if(data.indexOf("'result':'failure'") > 0)
        {
            //error occured
            var responseData = eval(data);
            if(responseData.errorcode == "SPAM_DETECTED")
            {
                //throw msg to user that spam has been detected from the responseContent
                if(confirm(responseData.reason))
                {
                    //user prefered to update the response with spam content
                    //hence submit the form again and set the detectSpamPresence=0 (ie) no need to detect and throw the spam presene while updating the content, instead update it with IS_SPAM = true
                    $('#editorHolder').find('input[name="detectSpamPresence"]').val(0);
                    $('#publishResponse').trigger('click');
                }//if(confirm(responseData.reason))
            }
            else
            {
                showMessage(responseData.reason,'failure');
            }
        }
        else if(data.indexOf("'result':'success'") > 0)
        {
            //in this case the response has been posted but not yet approved
            var responseData = eval(data);
            if($('#SinglePostContainer').length > 0)
            {
                removeTopicListCache();
                loadSinglePost(forumTopicId,false);
            }
            else if($('#topicList').length > 0 || $('#topicsList').length > 0) 
            {
                $('#topicListMainContainer').attr('shouldReload',"true");
                //user is adding response from topic list page
                if($('#currentCategoryContext').length > 0)
                {
                    $('#currentCategoryContext').trigger('click');
                }
                else
                {
                    $('#currentForumContext').trigger('click');
                }
            }
            showTipper(i18n[responseData.reason],'info',5000);
            return;
        }
        else
        {
            var successMsg = (editorMode && editorMode == "Edit")?i18n['zohodiscussions.singlepost.ResponseUpdated']:i18n['zohodiscussions.singlepost.ResponseAdded'];
            showTipper(successMsg,'success',3000);
            if($('#SinglePostContainer').length > 0)
            {
                removeTopicListCache();
                //this is the case where user is adding the response in full thread view
                showLoadingImage();
                loadSinglePost(forumTopicId,false);
            }//if($('#SinglePostContainer').length > 0)
            else if($('#topicList').length > 0 || $('#topicsList').length > 0)
            {
                $('#topicListMainContainer').attr('shouldReload',"true");
                //user is adding response from topic list page
                if($('#currentCategoryContext').length > 0)
                {
                    $('#currentCategoryContext').trigger('click');
                }
                else
                {
                    $('#currentForumContext').trigger('click');
                }
            }
            else if($('#myJournalsInnerContent').length > 0)
            {   
                var topicId = forumTopicId;
                if(responseId && $('#topicContent_'+topicId).length < 1)
                {   
                    topicId = responseId;
                }
                $('#topicContent_'+topicId).html(contentToPost);
                $('#editTopic_'+topicId).html(contentToPost);
                $('#cancelResponse').trigger('click');
            }
            else if($('#authorProfileInnerContent').length > 0)
            {   
                var topicId = forumTopicId;
                if(responseId && $('#topicContent_'+topicId).length < 1)
                {   
                    topicId = responseId;
                }
                $('#topicContent_'+topicId).html(contentToPost);
                $('#editTopic_'+topicId).html(contentToPost);
                $('#cancelResponse').trigger('click');
            }            
        }
    },
    function(errordata)
    {
       hideLoadingImage();
       if(errordata.responseText.indexOf("'result':'failure'") > 0)
       {
            var responseData = eval(errordata.responseText);
            if(responseData.result == "failure")
            {
                if(responseData.errorcode == "HIP_REQUIRED")
                {
                    var $writePostCaptcha = $('#responseAttachmentContActual').find('div[purpose="responseCaptcha"]');
                    if($writePostCaptcha.attr('currCaptcha') == "new")
                    {
                         showMessage(i18n['zohodiscussions.writePost.captchaMsg'],'failure');
                    }
                    else
                    {
                        showMessage(i18n['zohodiscussions.writePost.captchaErrorMsg'],'failure');
                    }
                    $writePostCaptcha.find('img[purpose="captchaImage"]').replaceWith("<img purpose=captchaImage name=hipImg border=0 src=/showcaptcha?digest="+responseData.reason+" align=absmiddle alt=HIP image>");
                    $writePostCaptcha.find(':input').attr('name',responseData.reason);
                    $writePostCaptcha.attr('currCaptcha',"old");
                    $writePostCaptcha.show();
                }
                else
                {
                    showMessage(responseData.reason,'failure'); //No I18N
                }
            }
       }
       else
       {
           $('#SinglePostContainer').get(0).innerHTML = errordata.responseText;
       }
    });
    return false;
}//function addForumResponse(forumTopicId,isEditMode)

//method to delete the cached topiclist page
function removeTopicListCache()
{
    $('#topicListMainContainer:hidden').remove();
    $('#userProfileMainContainer:hidden').remove();
    $('#myAreaParentContainer:hidden').remove();
}
