/* $Id$ */

/****  My Area Clicks start****/

function bindMyAreaClicks($context)
{   
    $context.unbind('click', processMyAreaClick).click(processMyAreaClick);
    $('#recentActivityContent, #profileDetailCont').unbind('click', processAllMyAreaMainClick).click(processAllMyAreaMainClick);
// purpose for binding two times so unbind it
    $('#mainContent').unbind('click', processAuthorProfileClick);
    $('#mainContent').unbind('click',processAllActionClick);
}//function bindMyAreaClicks($Content)

function processMyAreaClick(event)
{   
    var $target = $(event.target);
    var $targetParent = $target.parent();
    if($('#loadingImg').is(":visible"))
    {
        return;
    }
    if(($targetParent.is('[purpose="dashBoard"]') || $targetParent.is('[purpose="myJournals"]') || $targetParent.is('[purpose="watchList"]') ||$targetParent.is('[purpose="bookMark"]') || $targetParent.is('[purpose="privateMsg"]') || $targetParent.is('[purpose="preference"]')) && $targetParent.attr('isNiceUrl') != "Yes")
    {   
        getMyAreaAction($targetParent);
        return;
    }
    else if(($target.is('[purpose="dashBoard"]') || $target.is('[purpose="myJournals"]') || $target.is('[purpose="watchList"]') || $target.is('[purpose="bookMark"]') || $target.is('[purpose="privateMsg"]') || $target.is('[purpose="preference"]')) && $target.attr('isNiceUrl') != "Yes")
    {   
        getMyAreaAction($target);
        return;
    }
}//function processMyAreaClick(event)

function getMyAreaAction($target,subAction)
{   
    showLoadingImage();
    $target.parent('ul').find('li').removeClass('selected');
    $target.addClass('selected');
    var action = $target.attr("action");
    var options = {};
    options.forumGroupId = forumGroupId;
    options[csrfParamName] = csrfToken;
    options.ch = ch;
    var purpose = $target.attr("purpose");
    if(subAction != undefined && purpose=="watchList")
    {   
        action ="/myWatchListSubAction.do";
        options.subAction = subAction;
    }
    
    $('#myAreaLists').attr('currView',purpose);
    
    if(purpose == "myJournals")
    {   
        options.userId = $target.attr("userId");
        options.viewType = "myself";
    }
    doAjaxAction(
        action,
        options,
        function (data)
        {
            hideLoadingImage();
            $('#myAreaInnerMainContent').find('div.innerWrapper').get(0).innerHTML = data;
            if(purpose == "myJournals")
            {
                $.history.add('MyArea/myPosts');
            }
            else if(purpose == "watchList" && subAction != undefined)
            {
                $.history.add('MyArea/'+purpose+'/'+subAction);
            }
            else
            {
                $.history.add('MyArea/'+purpose);
            }
            bindMyareaTabsActions(purpose,subAction);
            return false;
        },
        function (err)
        {
            var responseData = eval(err.responseText);
            showMessage(responseData.reason,'failure');
            hideLoadingImage();
        }
    );
}//function getMyAreaAction($target)

function bindMyareaTabsActions(purpose,subAction)
{
    var $context = $('#myAreaInnerMainContent').find('div.innerWrapper');
    if(purpose == "preference")
    {
        $context.unbind('click', processPreferenceClick).click(processPreferenceClick);
        var $userAvatarImage = $('#user_AvatarImage');
        if($userAvatarImage.find('li.selected').length > 0)
        {
            avatarImageFocus($userAvatarImage);
        }
        var userPhotoPref = $('#preferenceInnerContent').find('form').attr('userPhotoPref');
        var userUploadPhotoUrl = $('#preferenceInnerContent').find('form').attr('userUploadPhotoUrl');
        var userIAMphoto = $('#preferenceInnerContent').find('form').attr('userIAMphoto');
        var userPhotoUrl ="";
        if(userPhotoPref == "IAM")
        {
            userPhotoUrl = userIAMphoto;
        }
        else if(userPhotoPref == "userUpload")
        {
            userPhotoUrl = userUploadPhotoUrl;
        }
        else if(userPhotoPref == "Avatar")
        {
            if($('#allAvatarList').find('li.selected').length == 0)
            {
                $('#allAvatarList').find('li[count="1"]').addClass("selected");
                var src='../images/avatars/avatarn1.gif';
                $('#userSelectedAvatarImage').attr('value',src);
                $('#userSelectedProfileImage').attr('value',src);
                $('#userPreferencePhotoCont').find('img').attr('src',src);
                $('#user_Photo').attr('value','Avatar');
            }
        }
        insertBrowserOptionToUpload(userPhotoPref,userPhotoUrl);
    }
    else
    {
        $context.unbind('click', processAllMyAreaMainClick).click(processAllMyAreaMainClick);
        $context.unbind('click', processAllActionClick).click(processAllActionClick);
        allFilterOption(purpose);
        showAuthorPopout($context);
        if(subAction=="following")
        {
            setFocusToContainer($context.find('#followingAuthors'),false,100,0);
        }
    }
    if(purpose == "dashBoard")
    {
        if(typeof WmsContacts != "undefined" && ch == true)
        {
            var dataOb = WmsContacts.getZohoContacts();
            setPresence(dataOb,"followingUserDetails");
            setPresence(dataOb,"followersUserDetails");
            setPresenceInMyArea(dataOb,"current_recentActivity_List");
        }
    }
    if(purpose == "watchList")
    {
        if(typeof WmsContacts != "undefined" && ch == true)
        {
            var dataOb = WmsContacts.getZohoContacts();
            setPresenceInMyArea(dataOb,"userChat_watchTopics");
        }
    }
    if(purpose =="privateMsg")
    {
        if(typeof WmsContacts != "undefined" && ch == true)
        {
            var dataOb = WmsContacts.getZohoContacts();
            setPresenceInMyArea(dataOb,"userChat_inbox");
        }
    }
}
function avatarImageFocus($userAvatarImage)
{
    var imgTop = $userAvatarImage.find('li.selected').attr('count');
    var height  = parseInt(imgTop/7);
    if(imgTop%7 == 0)
    {
        height = height-1;
    }
    $userAvatarImage.scrollTop(height*60)
}
function UserPhotoPreference(imageURL,upload)
{
    if(upload == "uploadUserPhoto")
    {
        $('#uploadPhotoCont').find('input[name="imageFileName"]').val("");
        $('#uploadPhotoCont').find('img[purpose="uploadPhotoLoadingCont"]').remove();
        $('#uploadPhotoPreference').attr('src',imageURL);
        $('#uploadPhotoCont').find('img[purpose="avat_Image"]').attr('src',imageURL);
        $('#userSelectedAvatarImage').attr('value',imageURL);
        $('#userSelectedProfileImage').attr('value',imageURL);
        $('#preferenceInnerContent').find('form').attr('userUploadPhotoUrl',imageURL);
        $('#userPreferencePhotoCont').find('img').attr('src',imageURL);
        $('#user_Photo').attr('value','userUpload');
        $('#uploadPhotoCont').find('div.profilePhoto').removeClass('profilePhoto').addClass('profilePhotoSelected');
        $('#allAvatarList').find('li.selected').removeClass("selected");
        showTipper(i18n['zohodiscussions.userpreference.uploadsuccessMess'],'success',1000);
    }
}
function processAllMyAreaMainClick(event)
{
    var $target = $(event.target);
    var $targetParent = $target.parent();
    if($('#loadingImg').is(":visible"))
    {
        return;
    }
    else if($target.is('a[purpose="postTitle"]'))
    {
        if($target.attr('postType') == "draft")
        {
            editDraftPost($target);
            return;
        }
        
        showLoadingImage();
        if(isTopicQuickView == "false")
        {
            //do nothing
        }
        else
        {
            var forumTopicId = $target.attr('forumTopicId');
            var recentResponseId = $target.attr('recentResponseId');
            if(recentResponseId != undefined)
            {
                processHash('Topic/'+forumTopicId+'/'+recentResponseId); //No I18N
            }
            else
            {
                processHash('Topic/'+forumTopicId); //No I18N
            }
            return false;
        }
    }
    else if(($target.is('a[purpose="forumAction"]') || $target.is('a[purpose="categoryAction"]')) && $target.attr('isNiceUrl') != "Yes")
    {   
        var hashPurpose = $target.attr("hashPurpose");
        processHash(hashPurpose);
    }
    else if(($target.is('a[purpose="authorProfile"],a[purpose="authorProfileMore"]')) && $target.attr('isNiceUrl') != "Yes")
    {   
        var authorName = $target.attr('authorName');
        var singleClickflag = $target.attr('singleClickflag');
        if(singleClickflag == "0")
        {
          if(authorName == ZU_Name)
          {   
              processHash('MyArea');
              $target.attr('singleClickflag','1');
          }
          else
          {   
              processHash('User/'+authorName);
              $target.attr('singleClickflag','1');
          }
        }
        return;
    }
    else if($target.is('div[purpose="unWatch"]'))
    {   
        unWatchItem($target);
        return;
    }
    else if($target.is('a[purpose="moreFollowing"]') && $target.attr('isNiceUrl') != "Yes")
    {
        processHash("myarea/watchList/following");
        return;
    }
    else if($target.is('a[purpose="moreFollowers"]') && $target.attr('isNiceUrl') != "Yes")
    {
        processHash("myarea/watchList/follower");
        return;
    }
    else if($targetParent.is('li[deletepurpose="deleteAttachment"]'))
    {
        deletePublishedAttachment($targetParent,event);
        return;
    }
    else if($target.is('li.navBtnEnabled')&& $target.is('li[action="false"]'))
    {
        var type = $target.attr('purpose');
        fnPaginationProcess($targetParent,type);
        return;
    }
    

}//function processAllMyAreaMainClick(event)
function processAllActionClick(event)
{   
    var $target = $(event.target);
    var $targetParent = $target.parent();
    var currView = $('#myAreaLists').attr('currView');
    if(!currView)
    {
        currView = "authorProfile";
    }
    if($('#loadingImg').is(":visible"))
    {
        return;
    }
    else if($target.is('.bigPlusIcon'))
    {   
        var $parent = $target.parents('li.headerContent');
        if(!$parent.find('div.expandTextContent').is(':visible') || currView=="privateMsg")
        {
            $parent.find('div.textContent').addClass('expandTextContent').show();
            $parent.parents('div.moderateSinglePost').find('div.lowerButton').show();
        }
        else
        {
            $parent.find('div.textContent').addClass('expandTextContent');
        }
        $target.removeClass('bigPlusIcon').addClass('bigMinusIcon');
        setFocusToContainer($target,true,200);
        return;
    }
    else if($target.is('.bigMinusIcon'))
    {   
        var $parent = $target.parents('li.headerContent');
        $parent.find('div.textContent').removeClass('expandTextContent').hide();
        $parent.parents('div.moderateSinglePost').find('div.lowerButton').hide();
        $target.removeClass('bigMinusIcon').addClass('bigPlusIcon');
        return;
    }
    else if($targetParent.is('li[purpose="expandedView"]')|| $targetParent.is('li[purpose="listView"]'))
    {
        manageExpandOrCollapseType($targetParent,currView);
        return;
    }
    else if($target.is('li.navBtnEnabled') && $target.is('li[action="true"]'))
    {
            var navType = $target.attr("purpose");
            if(currView == "authorProfile")
            {
                fnPagination($targetParent,navType,"true");
            }
            else
            {
                fnPagination($targetParent,navType);
            }    
            return;
    }
    else if($target.is('li[purpose="removeBookMark"]'))
    {   
        removeBookMarkAction($target) 
        return;
    }
    else if($targetParent.is('li[purpose="removeBookMark"]'))
    {   
        removeBookMarkAction($targetParent) 
        return;
    }
    else if($target.is('li[purpose="postTitle"]'))
    {   
        if($target.attr("postType")=="draft")
        {
            editDraftPost($target)
            return;
        }
        showLoadingImage();
        if(isTopicQuickView == "false")
        {
            //do nothing
        }
        else
        {
            var forumTopicId = $target.attr('forumTopicId');
            processHash('Topic/'+forumTopicId); //No I18N
            return false;
        }
    }
    else if($targetParent.is('li[purpose="postTitle"]'))
    {   
        if($targetParent.attr("postType")=="draft")
        {
            editDraftPost($targetParent)
            return;
        }
        showLoadingImage();
        if(isTopicQuickView == "false")
        {
            //do nothing
        }
        else
        {
            var forumTopicId = $targetParent.attr('forumTopicId');
            processHash('Topic/'+forumTopicId); //No I18N
            return false;
        }
    }
    else if($targetParent.is('li[purpose="delete"]'))
    {   
        myJournalsDeletePost($targetParent,currView+"Tab");
        return;
    }
    else if($target.is('li[purpose="delete"]'))
    {
        myJournalsDeletePost($target,currView+"Tab");
        return;
    }
    else if($target.is('li[purpose="topics"]') || $target.is('li[purpose="drafts"]') || $target.is('li[purpose="replies"]') || $target.is('li[purpose="authorTopics"]') || $target.is('li[purpose="authorReplies"]') || $target.is('li[purpose="privateMsg"]'))
    {   
        $('#'+currView+'Tab').find('li').removeClass('selected');
        myAreaAllTabClick($target,currView);
        return;
    }
    else if($targetParent.is('li[purpose="topics"]') || $targetParent.is('li[purpose="drafts"]') || $targetParent.is('li[purpose="replies"]') || $targetParent.is('li[purpose="authorTopics"]') || $targetParent.is('li[purpose="authorReplies"]')|| $targetParent.is('li[purpose="privateMsg"]'))
    {   
        $('#'+currView+'Tab').find('li').removeClass('selected');
        myAreaAllTabClick($targetParent,currView);
        return;
    }
    else if($target.attr("purpose") == "watchTopics" || $target.attr("purpose") == "watchUsers" || $target.attr("purpose") == "watchForums" || $target.attr("purpose") == "watchCategories" || $target.attr("purpose") == "simpleView" || $target.attr("purpose") == "followers")
    {
        $('#watchListTabs').find('li').removeClass('selected');
        myAreaAllTabClick($target,"watchList")
    }
    else if($targetParent.attr("purpose") == "watchTopics" || $targetParent.attr("purpose") == "watchUsers" || $targetParent.attr("purpose") == "watchForums" || $targetParent.attr("purpose") == "watchCategories" || $targetParent.attr("purpose") == "simpleView" || $targetParent.attr("purpose") == "followers")
    {
         $('#watchListTabs').find('li').removeClass('selected');
         myAreaAllTabClick($targetParent,"watchList")
    }
    else if($target.is('li[purpose="unWatch"]'))
    {   
        unWatchItem($target);
        return;
    }
    else if($targetParent.is('li[purpose="unWatch"]'))
    {   
        unWatchItem($targetParent);
        return;
    }
    else if($targetParent.is('li[purpose="unWatchItem"]'))
    {
        unWatchItem($targetParent,"authorProfile");
    }
    else if($target.attr("purpose") == "inbox" || $target.attr("purpose") == "sent")
    {   
        $('#privateMsgTab').find('li').removeClass('selected');
        var $newReplyEditor = $('#newReplyPrivateMsgCont');
        if($newReplyEditor.is(':visible'))
        {
            $newReplyEditor.parent().hide();   
            $newReplyEditor.remove();
        }
        myAreaAllTabClick($target,"privateMsg");
        return;
    }
    else if($targetParent.attr("purpose") == "inbox" || $targetParent.attr("purpose") == "sent")
    {
         $('#privateMsgTab').find('li').removeClass('selected');
         var $newReplyEditor = $('#newReplyPrivateMsgCont');
         if($newReplyEditor.is(':visible'))
         {
             $newReplyEditor.parent().hide();   
             $newReplyEditor.remove();
         }
         myAreaAllTabClick($targetParent,"privateMsg");
         return;
    }
    else if($target.is('li[purpose="deleteThisPM"]'))
    {
        deletePrivateMsg($target);
    }
    else if($targetParent.is('li[purpose="deleteThisPM"]'))
    {
        deletePrivateMsg($targetParent);
    }
    else if($target.is('li[purpose="replyToThisPM"]') || $target.is('li[purpose="editThisPM"]'))
    {   
        replyToPrivateMsg($target);
    }
    else if($targetParent.is('li[purpose="replyToThisPM"]') || $targetParent.is('li[purpose="editThisPM"]'))
    {
        replyToPrivateMsg($targetParent);
    }
    else if($targetParent.is('a[purpose="postConversation"]'))
    {
        privateConversation($targetParent);
    }
    else if($target.is('a[purpose="postConversation"]'))
    {
        privateConversation($target);
    }
    else if($target.is('a[purpose="postConversationTitle"]'))
    {
        var $parents = $target.parents('li.headerContent');
        var $textContent = $parents.find('div.textContent');
        if($textContent.is(':visible'))
        {
            $parents.find('div.bigMinusIcon').trigger('click');
        }
        else
        {
            $parents.find('div.bigPlusIcon').trigger('click');
        }
    }
}//function processAllActionClick(event)

function allFilterOption(type)
{
    $('#'+type+'_Filter').change(function()
    {   
        var $this = $(this);
        var currOption = $this.val();
        var $currSelectOption = $(this).find('option[filterType="'+currOption+'"]');
        if($this.attr('action') == "true")
        {
            myJournalsFilterAction($currSelectOption,type);
        }
        else
        {   
            myJournalsFilter($currSelectOption,type);
        }
    });

}
/********************* BOOKMARK START **********************/
function removeBookMarkAction($target)
{   
    var forumTopicId = $target.attr("forumTopicId");
    var options = {};
    options.forumGroupId = forumGroupId;
    options.forumTopicId = forumTopicId;
    options[csrfParamName] = csrfToken;
    doAjaxAction(
        '/removeBookMark.do',
        options,
        function (data)
        {
            hideLoadingImage();
            showTipper(i18n['zohodiscussions.bookMark.successfullyRemoveBookMark'],"success")
            $('#bookMark_'+forumTopicId).remove();
        },
        function (err)
        {
            var responseData = eval(err.responseText);
            showMessage(responseData.reason,'failure');
            hideLoadingImage();
        }
    );
}//funtion removeBookMarkAction($target)
/********************* BOOKMARK END *************************/
/********************* PREFERENCE START *********************/
function processPreferenceClick(event)
{
    var $target = $(event.target);
    var $targetParent = $target.parent();
    var userUploadPhotoUrl = $('#preferenceInnerContent').find('form').attr('userUploadPhotoUrl');
    var userIAMphoto = $('#preferenceInnerContent').find('form').attr('userIAMphoto');
    if($('#loadingImg').is(":visible"))
    {
        return;
    }
    if($target.attr("purpose") == "profile" || $target.attr("purpose") == "notification" || $target.attr("purpose") == "privacy")
    {
        $targetParent.find('li.selected').removeClass('selected');
        $target.addClass('selected');
        myAreaAllTabClick($target,"preference")
    }
    else if($targetParent.attr("purpose") == "profile" || $targetParent.attr("purpose") == "notification" || $targetParent.attr("purpose") == "privacy")
    {
         $targetParent.parent('ul').find('li.selected').removeClass('selected'); 
         $targetParent.addClass('selected');
         myAreaAllTabClick($targetParent,"preference")
    }
    else if($target.is('input[purpose="save"]') || $targetParent.is('input[purpose="save"]'))
    {
        updateUserPreference();
    }
    else if($targetParent.is('li[purpose="avat_Image"]'))
    {
        $('#user_IamImage').find('div.profilePhotoSelected').removeClass('profilePhotoSelected').addClass('profilePhoto');
        $('#user_AvatarImage').find('li.selected').removeClass('selected');
        $targetParent.addClass('selected');
        var src=$target.attr('src');
        $('#userPreferencePhotoCont').find('img').attr('src',src);
        $('#user_Photo').attr('value','Avatar');
        $('#userSelectedAvatarImage').val(src);
        $('#userSelectedProfileImage').val("");
        $('#zohoAccounts').removeAttr('purpose');
        $('#myComputer').removeAttr('purpose');
    }
    else if($target.is('#myComputer'))
    {
        $('#zohoAccountMess').remove();
        $('#uploadPhotoCont').remove();
        $('#curr_UploadPhoto_Cont').remove();
        $('#fgid').remove();
        $('#allAvatarList').hide();
        $('#myComputer').addClass('selected').siblings('li.selected').removeClass("selected");
        insertBrowserOptionToUpload("userUpload",userUploadPhotoUrl);//No internationalization
    }
    else if($target.is('#zohoAccounts'))
    {
        $('#curr_UploadPhoto_Cont').remove();
        $('#fgid').remove();
        $('#uploadPhotoCont').remove();
        $('#curr_UploadPhoto_Cont').remove();
        $('#allAvatarList').hide();
        $('#zohoAccounts').addClass('selected').siblings('li.selected').removeClass("selected");
        insertBrowserOptionToUpload("IAM",userIAMphoto);//No internationalization
    }
    else if($target.is('#AvatarsList'))
    {
        $('#zohoAccountMess').remove();
        $('#uploadPhotoCont').remove();
        $('#curr_UploadPhoto_Cont').remove();
        $('#AvatarsList').addClass('selected').siblings('li.selected').removeClass("selected");
        if($('#fgid').length == 0)
        {
            var $forumgrouphiddenfield = $('<input type = "hidden" id="fgid" name="forumGroupId" value="'+forumGroupId+'"/>');
            $forumgrouphiddenfield.insertAfter($('#preferenceInnerContent > form > input[name="avatar"]')).show();
        }
        
        var selectedUrl = $('#allAvatarList').find('li.selected').find('img').attr('src');
        $('#userSelectedAvatarImage').attr('value',selectedUrl);
        $('#userSelectedProfileImage').attr('value',selectedUrl);

        $('#allAvatarList').show();
        avatarImageFocus($('#user_AvatarImage'));
    }
    else if($targetParent.is('div[purpose="avat_Image"]'))
    {
        $('#user_AvatarImage').find('li.selected').removeClass('selected');
        $targetParent.removeClass('profilePhoto').addClass('profilePhotoSelected');
        $('#userSelectedProfileImage').val("yes");
        var src=$target.attr('src');
        $('#userPreferencePhotoCont').find('img').attr('src',src);
        $('#userSelectedAvatarImage').val(src);
        $('#zohoAccounts').removeAttr('purpose');
        $('#myComputer').removeAttr('purpose');
    }
}//function processPreferenceClick(event)

function insertBrowserOptionToUpload(userPhotoPref,userphoto)
{
    var userUploadPhotoUrl = $('#preferenceInnerContent').find('form').attr('userUploadPhotoUrl');
    var userIAMphoto = $('#preferenceInnerContent').find('form').attr('userIAMphoto');
    if(userPhotoPref == "IAM")
    {
        var $uploadPhoto_Cont = $('#uploadPhoto_Cont');
        var $uploadPhoto = $uploadPhoto_Cont.clone();
        $uploadPhoto.insertAfter($('#user_AvatarImage').find('ul')).show();
        $uploadPhoto.attr('id','curr_UploadPhoto_Cont');
        $uploadPhoto.attr('purpose','userPhotoTemplate');
        $uploadPhoto.find('div[purpose="uploadPhotoContent"]').wrap('<form action = "/uploadUserPhoto.do" style="margin-left:230px;margin-top:-30px;margin-right:100px;" target = "fileUpdTgt_user" method="post" enctype="multipart/form-data"></form>');
        $uploadPhoto.find('div.iFrameContainer').html('<iframe name = "fileUpdTgt_user"> </iframe>');
        $uploadPhoto.find('form').attr('target', 'fileUpdTgt_user');
        var $forumgrouphiddenfield = $('<input type = "hidden"  name="forumGroupId" value="'+forumGroupId+'"/>');
        $forumgrouphiddenfield.insertAfter($('#curr_UploadPhoto_Cont').find('div[purpose="uploadPhotoContent"]'));
        $('#curr_UploadPhoto_Cont').find('div[purpose="uploadName"]').html('Zoho image');//No internationalization
        $uploadPhoto.find(':file').change(function()
        {
            $uploadPhoto.find('[purpose="uploadPhotoLoadingCont"]').show();
            $uploadPhoto.find(':input[name="attacher"]').val('');
            $uploadPhoto.find('form').get(0).submit();
       });
       var imagePurpose = $('#zohoAccounts').attr('purpose');
       var profileselected  = "profilePhoto";//No internationalization
       if(typeof imagePurpose != "undefined")
       {
           profileselected  = "profilePhotoSelected";//No internationalization
       }
       var $previewimage = $('<div class="'+profileselected+'"  imgpurpose="IAMPhotoSelected"><img height="48" width="48" purpose="avat_Image" src="'+userIAMphoto+'"/></div>');
       $previewimage.insertBefore($('#curr_UploadPhoto_Cont').find('form'));
       $('<div class="boldText" style="margin-left:120px;margin-top:-45px;margin-right:100px;">change photo:</div>').insertAfter($('#curr_UploadPhoto_Cont').find('div[imgpurpose="IAMPhotoSelected"]'));
       $('#curr_UploadPhoto_Cont').find('div[imgpurpose="IAMPhotoSelected"]').click(function()
       {
           var userIAMphoto = $('#preferenceInnerContent').find('form').attr('userIAMphoto');
           $('#userPreferencePhotoCont').find('img').attr('src',userIAMphoto);
           var currentPref = $('#userPreferencePhotoCont').attr('currentPref');
           if(currentPref = 'userUpload')
           {
              $('#myComputer').removeAttr('purpose');
              $('#zohoAccounts').attr('purpose','iamUploadselected');
           }
           $('#user_Photo').attr('value','IAM');
           $('#allAvatarList').find('li.selected').removeClass("selected");
           $('#curr_UploadPhoto_Cont').find('div.profilePhoto').removeClass('profilePhoto').addClass('profilePhotoSelected');
       });

       $('<div id="zohoAccountMess" style="padding:50px;margin-left:50px;"><p class="innerInfo tinyText"><span>'+i18n['zohodiscussions.userpreference.uploadzohoAccountMess']+'</span></p></div>').insertAfter($('#curr_UploadPhoto_Cont'));

    }
    else if(userPhotoPref == "userUpload")
    {
        var $uploadPhoto_Cont = $('#uploadPhoto_Cont');
        var $uploadPhotoPreference = $uploadPhoto_Cont.clone();
        $uploadPhotoPreference.insertAfter($('#user_AvatarImage').find('ul')).show();
        $uploadPhotoPreference.attr('id','uploadPhotoCont');
        $uploadPhotoPreference.attr('purpose','uploadUserPhotoTemplate');
        $uploadPhotoPreference.find('div[purpose="uploadPhotoContent"]').wrap('<form action = "/uploadCustomFile.do" style="margin-left:230px;margin-top:-30px;margin-right:100px;" target = "fileUpdTgt_user" method="post" enctype="multipart/form-data"></form>')
        $uploadPhotoPreference.find(':input[type="file"]').attr('name','imageFileName');
        $uploadPhotoPreference.find('div.iFrameContainer').html('<iframe name = "fileUpdTgt_user"> </iframe>');
        $uploadPhotoPreference.find('form').attr('target', 'fileUpdTgt_user');
        var $forumgrouphiddenfield = $('<input type = "hidden"  name="forumGroupId" value="'+forumGroupId+'"/>');
        var $purposehiddenfield = $(' <input type="hidden" value="uploadUserPhoto" name="purpose"/>');
        $forumgrouphiddenfield.insertAfter($('#uploadPhotoCont').find('div[purpose="uploadPhotoContent"]'));
        $purposehiddenfield.insertAfter($('#uploadPhotoCont').find('div[purpose="uploadPhotoContent"]'));
        $uploadPhotoPreference.find(':file').change(function()
        {
            $uploadPhotoPreference.find('[purpose="uploadPhotoLoadingCont"]').show();
            $uploadPhotoPreference.find('form').get(0).submit();
       });
       var imagePurpose = $('#myComputer').attr('purpose');
       var profileselected  = "profilePhoto";//No internationalization
       if(typeof imagePurpose != "undefined")
       {
           profileselected  = "profilePhotoSelected";//No internationalization
       }
       var $previewimage = $('<div class="'+profileselected+'" imgpurpose="userUploadedPhotoSelected"><img height="48" width="48" purpose="avat_Image" src="'+userUploadPhotoUrl+'"/></div>');
       $previewimage.insertBefore($('#uploadPhotoCont').find('form'));
       $('<div class="boldText" style="margin-left:120px;margin-top:-45px;margin-right:100px;">change photo:</div>').insertAfter($('#uploadPhotoCont').find('div[imgpurpose="userUploadedPhotoSelected"]'));
       $('#uploadPhotoCont').find('div[imgpurpose="userUploadedPhotoSelected"]').click(function()
       {
           var userUploadPhotoUrl = $('#preferenceInnerContent').find('form').attr('userUploadPhotoUrl');
           $('#uploadPhotoCont').find('div.profilePhoto').removeClass('profilePhoto').addClass('profilePhotoSelected');
           $('#userPreferencePhotoCont').find('img').attr('src',userUploadPhotoUrl);
           $('#user_Photo').attr('value','userUpload');
           $('#allAvatarList').find('li.selected').removeClass("selected");
            var currentPref = $('#userPreferencePhotoCont').attr('currentPref');
           if(currentPref = 'IAM')
           {
               $('#zohoAccounts').removeAttr('purpose');
               $('#myComputer').attr('purpose','userUploadselected');
           }
       });
    }
}

function uploadUserPhoto(result,reason)
{
    $('#curr_UploadPhoto_Cont').find('img[purpose="uploadPhotoLoadingCont"]').remove();
    if(result == "failure")
    {
        showMessage(reason+" ,Please try again.",'failure'); //No I18N
    }
    else
    {
        $('#curr_UploadPhoto_Cont').find('input[name="uploadPhotoFile"]').val("");
        var photoUrl = $('#preferenceInnerContent').find('form').attr('photoUrl');
        var src = photoUrl+"/file?t=user&width=48&height=48&ID="+ZUID+"&nocache=1"; //No I18N
        $('#curr_UploadPhoto_Cont').find('img[purpose="avat_Image"]').attr('src',src);
        $('#userSelectedAvatarImage').attr('value',src);
        $('#userSelectedProfileImage').attr('value',src);
        $('#preferenceInnerContent').find('form').attr('userIAMphoto',src);
        $('#userPreferencePhotoCont').find('img').attr('src',src);
        $('#curr_UploadPhoto_Cont').find('div.profilePhoto').removeClass('profilePhoto').addClass('profilePhotoSelected');
        $('#user_Photo').attr('value','IAM');
        $('#allAvatarList').find('li.selected').removeClass("selected");
        showTipper(i18n['zohodiscussions.userpreference.uploadsuccessMess'],'success',1000);
        processHash("myArea/preference");//No internationalization
    }
}
function updateUserPreference()
{
    if($('#userAvatarList').is(':focus'))
    {   
        var $listAvatarUl = $('#imgContUl');
        var $currSelectAvatar = $listAvatarUl.find('li.listAvatarSelected');
        var src = $currSelectAvatar.find('img').attr('src');
        $listAvatarUl.find('input[name="avatar"]').val(src);
    }
    var $wikiUrl = $('#wikiUrl');
    var $blogUrl = $('#blogUrl');
    var $webSite = $('#webSite');
    var wikiURL = sanitizeURL($.trim('' + $wikiUrl.val()));
    var blogURL = sanitizeURL($.trim('' + $blogUrl.val()));
    var website = sanitizeURL($.trim('' + $webSite.val()));
    $wikiUrl.val(wikiURL);
    $blogUrl.val(blogURL);
    $webSite.val(website);
    doAjaxAction(
        "/updateUserSetting.do", //No I18N
        $('#preferenceInnerContent').find('form').serialize(),
        function (data)
        {
            if(data == "SUCCESS")
            {
                showTipper(i18n['zohodiscussions.userpreference.userprofileupdated'],"success");
                var currSrc = $('#userSelectedAvatarImage').val();
                $('#topContainerPhoto').find('img').attr('src',currSrc);
                processHash("myArea/preference");
            }//if(data == "SUCCESS")
        },
        function (err)
        {
            var responseData = eval(err.responseText);
            showMessage(responseData.reason,'failure');
        }
    );
}
/******************* PREFERENCE END *******************/
/******************* MY JOURNALS START*****************/
function editDraftPost($target)
{   
    showLoadingImage();
    var authorId = $target.attr('authorId');
    var forumTopicId = $target.attr('forumTopicId');
    var options ={};
    options.forumGroupId = forumGroupId;    
    options.forumTopicId = forumTopicId;
    options[csrfParamName] = csrfToken;
    options.editMode = "true";
    var forumId = $target.attr('forumId');
    var categoryId = $target.attr('categoryId');
    if(authorId == ZUID)
    {
        options.access = "author";
    }
    doAjaxAction('/editDraft.do',options,function (data)//No internationalization
    {
        hideLoadingImage();
        document.title = i18n['zohodiscussions.writePost.documentTitle']+" - "+forumGroupName;
        $('#mainContent').get(0).innerHTML = data;
        $('#SelectForum').val(forumId);
        initWritePost();
        $('#SelectCategory').val(categoryId);
        },
        function(errordata)
        {
            var responseData = eval(errordata.responseText);
            showMessage(responseData.reason,'failure');
            hideLoadingImage();
        }
    );
}//editDraftPost($target)

function myJournalsDeletePost($target,tabType)
{
    var authorId = $target.attr('authorId');
    var action = $target.attr('action');
    var options ={};
    options.forumGroupId = forumGroupId;    
    options.forumId = $target.attr('forumId');
    options.categoryId = $target.attr('categoryId');
    options.forumTopicId = $target.attr('forumTopicId');
    options[csrfParamName] = csrfToken;
    if(action == "/deleteForumResponse.do")
    {
        options.responseId = $target.attr('responseId');
    }
    if(authorId == ZUID)
    {
        options.access = "author";
    }
    doAjaxAction(
        action,
        options,
        function (data)
        {
            hideLoadingImage();
            if(action == "/deleteForumResponse.do")
            {
                showTipper(i18n['zohodiscussions.myJournals.successfullyTopicDeleted'],"success");
            }
            else
            {
                showTipper(i18n['zohodiscussions.myJournals.successfullyResponseDeleted'],"success");
            }
            $target.parents('div.moderateSinglePost').hide();
            //manageCountValue(tabType);
        },
        function (err)
        {
            var responseData = eval(err.responseText);
            showMessage(responseData.reason,'failure');
            hideLoadingImage();
        }
    );
}
/************ MY JOURNALS END *********************/
/************ FILTER ACTION START****************/
function myJournalsFilter($target,tabType)
{   
    var filterType = $target.attr('purpose');
   // get filter type and display this type only
    var $currShowList = $('#'+tabType+'InnerContent').find('div[status="show"]');
    $currShowList.attr("currFilterType",$target.text());
    $currShowList.attr("filterType",filterType);
    $currShowList.find('div.moderateSinglePost').hide();
    var totalPost = -1;
    if(filterType == "all")
    {
        $listOfTypes = $currShowList.find('div.moderateSinglePost');
        $listOfTypes.each (function(index, item)
        {
            if(index < postPerPage)
            {
                $(item).show();
            }
            totalPost = index;
        });
    }
    else
    {   
        $listOfTypes = $currShowList.find('div.'+filterType);
        $listOfTypes.each (function(index, item)
        {
            if(index < postPerPage)
            {
                $(item).show();
            }
            totalPost = index;
        });
    }
    if(tabType == "watchList")
    {
        tabType = "watchTopic";
    }
    if(postPerPage > totalPost ||  totalPost == -1)
    {
        $('#'+tabType+'Next').removeClass('navBtnEnabled').addClass('navBtnDisabled');
    }
    else
    {
        $('#'+tabType+'Next').removeClass('navBtnDisabled').addClass('navBtnEnabled');
    }
    var $prevButton = $('#'+tabType+'Prev');
    $prevButton.removeClass('navBtnEnabled').addClass('navBtnDisabled');
    $prevButton.parent('ul').attr("fetchPage",1);
    if(totalPost == -1)
    {
        $('#'+tabType+'FilterEmptyMsg').show();
        $('#'+tabType+'_Nav').hide();
    }
    else
    {
        $('#'+tabType+'FilterEmptyMsg').hide();
        $('#'+tabType+'_Nav').show();
    }
}

function myJournalsFilterAction($target,tabType)
{   
    var $targetParent = $target.parent();
    var filterType = $target.attr('purpose');
   // get filter type and display this type only
    var $currShowList = $('#'+tabType+'InnerContent').find('div[status="show"]');
    var filterText = $target.text();
    $currShowList.attr("currFilterType",filterText);
    var postType = $('#'+tabType+'Tab').find('li.selected').attr('purpose');
    showLoadingImage();
    var action = $targetParent.attr(postType+'Action');
    var options = {};
    options.forumGroupId = forumGroupId;
    options.userId = $targetParent.attr("userId");
    options.filterType = filterText;
    options[csrfParamName] = csrfToken;
    
    doAjaxAction(
        action,
        options,
        function (data)
        {
            hideLoadingImage();
            $currShowList.get(0).innerHTML = data;
            if(tabType == "myJournals")
            {
                var $currentSelectAction= $('#'+tabType+'SelectAction');
                $currentSelectAction.find('li[purpose="expandedView"]').html("<a class=underline href=javaScript:;>"+i18n['zohodiscussions.myArea.expandView']+"</a>");
                $currentSelectAction.find('li[purpose="listView"]').html("<span class=boldText>"+i18n['zohodiscussions.myArea.listView']+"</span>");
            }
        },
        function (err)
        {
            var responseData = eval(err.responseText);
            showMessage(responseData.reason,'failure');
            hideLoadingImage();
        }
    );
}
/************ FILTER ACTION END****************/

/******************** PRIVATE MSG START ****************/
function replyToPrivateMsg($this)
{   
    var $newReplyEditor = $('#newReplyPrivateMsgCont');
    if($newReplyEditor.is(':visible'))
    {
        showMessage(i18n['zohodiscussions.singlepost.alertmessageforediting'],'info');
        return;
    }
    var type= $this.attr("postType");
    var forumTopicId = $this.attr('forumTopicId');
    var $newPMLocation = $('#privateMsgCont_'+forumTopicId);
    var $PMContainer = $('#privateMsg'+type+'Container');
    var action = "reply";
    var actionType = "Write"
    var toMember = $this.attr('toMember');
    var purpose = $this.attr('purpose');
    var responseId = -1;
    var responseAuthor = "";
    if(type == "Sent")
    {
        $('#topicContent_'+forumTopicId).hide();
    }
    $newPMLocation.show();
    if(purpose == "editThisPM")
    {
         $('#PrivateMsgReply').hide();
         $('#PrivateMsgEdit').show();
    }
    else
    {
         $('#PrivateMsgReply').show();
         $('#PrivateMsgEdit').hide();
    }
    var $replyPMArea = $('#replyPrivateMsgContent');
    $newReplyEditor = $replyPMArea.clone();
    $newReplyEditor.attr('id','newReplyPrivateMsgCont');
    $newReplyEditor.find('#PrivateMsgReply').attr('id','newPrivateMsgReply');
    $newReplyEditor.find('#PrivateMsgEdit').attr('id','newPrivateMsgEdit');
    $newReplyEditor.find('#cancelPrivateReplyButton').attr('id','newcancelPrivateReplyButton');
    
    var action = "";
    var $pmReplyContent = $newReplyEditor.find('textarea[name="privateMsgContent"]');
    var $pmReplyToMember = $newReplyEditor.find('input[name="toMemberName"]');
    var $pmReplyTitle = $newReplyEditor.find('input[name="forumPostTitle"]');
    var postTitle = "";
    var editContent = $('#privateMsg_'+forumTopicId).html();

    if(purpose == "editThisPM")
    {
        responseId = $this.attr('responseId');
        $pmReplyToMember.parent().hide();
        postTitle = $this.attr('postTitle');
        $pmReplyTitle.val(postTitle);
        action = "/editPrivateMsg.do"; //No I18N
        $('#privateMsg_'+forumTopicId).hide();
    } 
    else
    {
        responseAuthor = $this.attr('toMemberName');
        $pmReplyToMember.val(responseAuthor);
        $pmReplyTitle.parent().hide();
        action = "/replyToPM.do"; //No I18N
    }
    $pmReplyContent.val(editContent);
        
    $newReplyEditor.find('input[name="toMember"]').val(toMember);
    $newReplyEditor.find('input[name="forumTopicId"]').val(forumTopicId);
    $newReplyEditor.find('input[name="responseId"]').val(responseId);

    $newPMLocation.append($newReplyEditor.show());
    
    $('#newPrivateMsgReply, #newPrivateMsgEdit').unbind('click').click(function()
    {
        if(purpose == "editThisPM")
        {
            if($pmReplyTitle.val().trim() == "")
            {
                showMessage(i18n['zohodiscussions.writePost.noTitleInPost'],"failure"); //No I18N
                return;
            }
        }
        if($pmReplyContent.val().trim() == "")
        {
            showMessage(i18n['zohodiscussions.writePost.noContentInPost'],"failure");
            return;
        }
        doAjaxAction(
        action,
        $newReplyEditor.find('form').serialize(),
        function (data)
        {
            showTipper(i18n['zohodiscussions.privateMsg.successfullyPMAdded'],"success");
            if(purpose == "editThisPM")
            {
                $('#privateMsg_'+forumTopicId).html($pmReplyContent.val());
                $('#topicContent_'+forumTopicId).html($pmReplyContent.val());
                $('#editPrivateMsg_'+forumTopicId).attr('postTitle',$pmReplyTitle.val());
                $('#privateMsgPostTitle_'+forumTopicId).html($pmReplyTitle.val());
                $('#newcancelPrivateReplyButton').trigger('click');
            }
            else
            {
                processHash("myArea/privateMsg"); //No I18N
            }
        },
        function (err, desc, exceptionobj)
        {
            $newReplyEditor.find('div#writePMCaptcha').attr('id','newWritePMCaptcha');
            var responseData = eval(err.responseText);
            if(responseData.errorcode == "HIP_REQUIRED")
            {
                var $writePMCaptcha = $('#newWritePMCaptcha');
                $writePMCaptcha.find('input#captchaCodePM').attr('id','newCaptchaCodePM');
                $writePMCaptcha.show();
                if($writePMCaptcha.attr('currCaptcha') == "new")
                {
                     showMessage(i18n['zohodiscussions.writePost.captchaMsg'],'failure');
                }
                else
                {
                    showMessage(i18n['zohodiscussions.writePost.captchaErrorMsg'],'failure');
                }

                $writePMCaptcha.find('img[purpose="captchaImage"]').replaceWith("<img purpose=captchaImage name=hipImg border=0 src=/showcaptcha?digest="+responseData.reason+" align=absmiddle alt=HIP image>");
                $('#newCaptchaCodePM').attr('name',responseData.reason);
                $writePMCaptcha.attr('currCaptcha',"old");
                $writePMCaptcha.show();
            }
            else
            {
                showMessage(responseData.reason,'failure');
            }
            hideLoadingImage();
        }
        );
    });

    $('#newcancelPrivateReplyButton').click(function()
    {
        $('#privateMsgCont_'+forumTopicId).hide();
        $newReplyEditor.remove();
        if(purpose == "editThisPM")
        {
            $('#privateMsg_'+forumTopicId).show();
        }
    });
    
    return false;
}//function replyToPrivateMsg($this)

function addPrivateMsg(forumTopicId,editorMode,responseId,type)
{   
    showLoadingImage();
    if(type=="UserPM")
    {
        var $currScreenView = $('#privateMsgTab').find('li.selected');
        $currScreenView.attr("isthere","false");
    }
    var $postContentTA =$('#postContentTA');
    var postTitle = "";
    if(editorMode && editorMode == "Edit")
    {
        postTitle = $postContentTA.parent().find('input[name="forumPostTitle"]').val();
        postTitle = postTitle.replace(/^\s+/g, '').replace(/\s+$/g, ''); //replace(/<[^>]*>/ig, '')
        if (postTitle == '' )
        {
            hideLoadingImage();
            showMessage(i18n['zohodiscussions.writePost.noTitleInPost'],"failure"); //No I18N
            return;
        }
    }
    var contentToPost = $postContentTA.data('editor').val(); //No I18N

    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")?"/editPrivateMsg.do":(type=="UserPM")?"/addPrivateMsg.do":"/replyToPM.do";
    doAjaxAction(
        newResponseAction,
        $('#editorHolder').serialize(),
        function (data)
        {
            hideLoadingImage();
            showTipper(i18n['zohodiscussions.privateMsg.successfullyPMAdded'],"success");
            if(editorMode == "Edit")
            {   
                var $parent = $('#privateMsgCont_'+forumTopicId).parent('li');
                $parent.find('a[purpose="postConversationTitle"]').html(postTitle);
                $('#cancelResponse').trigger('click');         
            }
            else
            {
                if(type == "UserPM")
                {
                    var currAuthorName = $('#UserPM').attr('authorName');
                    processHash("user/"+currAuthorName); //No I18N
                }
                else
                {
                    processHash("myArea/privateMsg"); //No I18N
                }
            }
        },
        function (err, desc, exceptionobj)
        {
            var responseData = eval(err.responseText);
            if(responseData.errorcode == "HIP_REQUIRED")
            {
                var $writePostCaptcha = $('#replyPMContActual').show().find('div[purpose="responseCaptcha"]');
                $writePostCaptcha.find(':input').val("");
                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');
            }
            hideLoadingImage();
        }
    );
    return false;
}

function deletePrivateMsg($target)
{
    var forumTopicId = $target.attr('forumTopicId');
    var options = {};
    options.forumGroupId = forumGroupId;
    options.forumTopicId = forumTopicId;
    options[csrfParamName] = csrfToken;
    doAjaxAction(
        '/deletePM.do',
        options,
        function (data)
        {
            hideLoadingImage();
            showTipper(i18n['zohodiscussions.privateMsg.successfullyPMDeleted'],"success");
            var $currScreenView = $('#privateMsgTab').find('li.selected');
            if($currScreenView.attr("purpose") == "inbox")
            {
                processHash("myArea/privateMsg");
            }
            else
            {
                $currScreenView.attr("isthere","false").trigger('click');
            }
        },
        function (err)
        {
            var responseData = eval(err.responseText);
            showMessage(responseData.reason,'failure');
            hideLoadingImage();
        }
    );
}//function deletePrivateMsg($target)

function privateConversation($target)
{
    var forumTopicId = $target.attr('forumTopicId');
    var $currPrivateCont = $('#privateConversation_'+forumTopicId).html();
    var $pirvateConversation = $('#privateConversation');
    $pirvateConversation.show();
    $('#privateConversationCont').get(0).innerHTML = $currPrivateCont;
    $('#privateConversationClose').unbind('click').click(function()
    {
        $pirvateConversation.hide();
        return;
    });
    $('#morePrivateConversation').unbind('click').click(function()
    {
        $pirvateConversation.hide();
        showLoadingImage();
        openSinglePost(forumTopicId);
        return;    
    });
}//function privateConversation($target)

/************************************************* PRIVATE MSG END *******************************************************/

function myAreaAllTabClick($this,parentName)
{   
    var $currentShowingInnerContent = $('#'+parentName+'InnerContent');
    var $currentList = $currentShowingInnerContent.find('div[status="show"]');
    $this.addClass('selected');
    var purpose = $this.attr('purpose');
    var isthere = $this.attr('isthere');
    
    var $requiredList = $currentShowingInnerContent.find('div[purpose="author_'+purpose+'"]');
    $currentList.attr("status","hide").hide();
    if(parentName == "authorProfile")
    {   
        if(purpose == "privateMsg")
        {
            $('#authorProfileContentAction').hide();
        }
        else
        {
            $('#authorProfileContentAction').show();
        }
    }
//hide filter in watchlist-user
    if(parentName == "watchList")
    {   
        if(purpose != "watchTopics")
        {   
            $('#'+parentName+'_Filter').parent().hide();
        }
        else
        {   
            $('#'+parentName+'_Filter').parent().show();
        }
    }
    if(parentName == "myJournals" || parentName == "privateMsg" || parentName == "authorProfile")
    {   
        var $currentShowingSelectAction = $('#'+parentName+'SelectAction');
        if(isthere == "true")
        {
            if(parentName == "myJournals" || parentName == "authorProfile")
            {   
                var $myJournalsFilter = $('#'+parentName+'_Filter');
                if(purpose == "replies" || purpose == "authorReplies")
                {
                    $myJournalsFilter.parent().hide();
                }
                else
                {   
                    $myJournalsFilter.parent().show();
                    var currFilterType = $requiredList.attr('currFilterType');
                    $myJournalsFilter.val(currFilterType);
                }

            }
            $requiredList.attr("status","show").show();
            if($requiredList.find('div.collapse').length > 0)
            {
                $currentShowingSelectAction.find('li[purpose="expandedView"]').html("<a class=underline href=javaScript:;>"+i18n['zohodiscussions.myArea.expandView']+"</a>");
                $currentShowingSelectAction.find('li[purpose="listView"]').html("<span class=boldText>"+i18n['zohodiscussions.myArea.listView']+"</span>");
            }
            else if($requiredList.find('div.expand').length > 0)
            {
                $currentShowingSelectAction.find('li[purpose="expandedView"]').html("<span class=boldText>"+i18n['zohodiscussions.myArea.expandView']+"</span>");
                $currentShowingSelectAction.find('li[purpose="listView"]').html("<a class=underline href=javaScript:;>"+i18n['zohodiscussions.myArea.listView']+"</a>");
            }
            if(parentName == "privateMsg")
            {
                if(typeof WmsContacts != "undefined" && ch == true)
                {
                    var dataOb = WmsContacts.getZohoContacts();
                    setPresenceInMyArea(dataOb,"userChat_"+purpose);
                }
            }
            return;
        }
    }
    else
    {   
        if(isthere == "true")
        {   
            $requiredList.attr("status","show").show();
            if(parentName == "watchList")
            {
                if(typeof WmsContacts != "undefined" && ch == true)
                {
                    var dataOb = WmsContacts.getZohoContacts();
                    setPresenceInMyArea(dataOb,"userChat_"+purpose);
                }
            }
            return;
        }

    }
    showLoadingImage();
    var purpose = $this.attr('purpose');
    var action = $this.attr('action');
    var options = {};
    
    if(purpose != "privateMsg")
    {
        options.forumGroupId = forumGroupId;
        options[csrfParamName] = csrfToken;
    
        if(parentName == "myJournals" || parentName == "authorProfile")
        {
            options.userId = $this.attr("userId");
        }
    }
    if(parentName =="myJournals")
    {
        options.viewType = "myself";
    }
    doAjaxAction(
        action,
        options,
        function (data)
        {
            hideLoadingImage();

            var $data;
            if(parentName == "myJournals" || parentName == "authorProfile")
            {
                $data = $("<div purpose=author_"+purpose+" status=show currFilterType=all></div>").html(data);
                var $currFilter = $('#'+parentName+'_Filter');
                if(purpose == "replies" || purpose == "authorReplies")
                {
                    $currFilter.parent().hide();
                }
                else
                {   

                    $currFilter.parent().show();
                    $currFilter.val("All");
                }
            }
            else
            {
                $data = $("<div purpose=author_"+purpose+" status=show id=userChat_"+purpose+"></div>").html(data);
            }
            hideLoadingImage();
            showAuthorPopout($data);
            $data.insertAfter($currentList);
            $this.attr("isthere","true");

            if(purpose == "drafts" || purpose == "inbox" || purpose == "sent" || purpose=="authorTopics")
            {
                $currentShowingSelectAction.find('li[purpose="expandedView"]').html("<a class=underline href=javaScript:;>"+i18n['zohodiscussions.myArea.expandView']+"</a>");
                $currentShowingSelectAction.find('li[purpose="listView"]').html("<span class=boldText>"+i18n['zohodiscussions.myArea.listView']+"</span>");
            }
            else if(purpose == "replies" || purpose=="authorReplies")
            {
                $currentShowingSelectAction.find('li[purpose="expandedView"]').html("<span class=boldText>"+i18n['zohodiscussions.myArea.expandView']+"</span>");
                $currentShowingSelectAction.find('li[purpose="listView"]').html("<a class=underline href=javaScript:;>"+i18n['zohodiscussions.myArea.listView']+"</a>");
            }
            if(parentName == "privateMsg" || parentName=="watchList")
            {
                if(typeof WmsContacts != "undefined" && ch == true)
                {
                    var dataOb = WmsContacts.getZohoContacts();
                    setPresenceInMyArea(dataOb,"userChat_"+purpose);
                }
            }
        },
        function (err)
        {
            var responseData = eval(err.responseText);
            showMessage(responseData.reason,'failure');
            hideLoadingImage();
        }
    );
    
}//function myAreaAllTabClick($target)

function manageExpandOrCollapseType($target,parentName)
{
      
    // get the view type and assign to my journal page
    var purpose = $target.attr("purpose");
    if($target.find('a').length < 1)
    {    
        return;
    }
    var $currentShowingInnerContent = $('#'+parentName+'InnerContent');
    var $currentShowingSelectAction = $('#'+parentName+'SelectAction');
    var currentShowList = $currentShowingInnerContent.find('div[status="show"]');
    if(purpose=="expandedView")
    {   
        currentShowList.find('div.collapse').attr("class","expand");
        currentShowList.find('div.expand div.bigPlusIcon').removeClass('bigPlusIcon').addClass('bigMinusIcon');
        currentShowList.find('div.textContent').addClass('expandTextContent').show();
        currentShowList.find('div.moderateSinglePost div.lowerButton').show();
        $currentShowingSelectAction.find('li[purpose="expandedView"]').html("<span class=boldText>"+i18n['zohodiscussions.myArea.expandView']+"</span>");
        $currentShowingSelectAction.find('li[purpose="listView"]').html("<a class=underline href=javaScript:;>"+i18n['zohodiscussions.myArea.listView']+"</a>");
    }
    else if(purpose=="listView")
    {   
        currentShowList.find('div.expand').attr("class","collapse");
        currentShowList.find('div.collapse div.bigMinusIcon').removeClass('bigMinusIcon').addClass('bigPlusIcon');
        currentShowList.find('div.textContent').addClass('expandTextContent').hide();
        currentShowList.find('div.moderateSinglePost div.lowerButton').hide();
        $currentShowingSelectAction.find('li[purpose="expandedView"]').html("<a class=underline href=javaScript:;>"+i18n['zohodiscussions.myArea.expandView']+"</a>");
        $currentShowingSelectAction.find('li[purpose="listView"]').html("<span class=boldText>"+i18n['zohodiscussions.myArea.listView']+"</span>");
    }
    return;
}//function manageExpandOrCollapseType()

function manageCountValue(selectTab)
{
   
    var currSelectedTab = $('#'+selectTab).find('li.selected');
    var count = currSelectedTab.attr('count');
    count = --count;
    var purpose = currSelectedTab.attr('purpose');
    
    if(purpose == "watchTopics")
    {   
        currSelectedTab.find('a').html(i18n['zohodiscussions.myJournals.topics']+"("+count+")"); 
    }
    else if(purpose=="authorReplies")
    {   
        currSelectedTab.find('a').html(i18n['zohodiscussions.general.replies']+"("+count+")");
    }
    else if(purpose == "watchUsers")
    {
        currSelectedTab.find('a').html(i18n['zohodiscussions.watchList.users']+"("+count+")");
    }
    else if(purpose == "inbox")
    {
        currSelectedTab.find('a').html(i18n['zohodiscussions.privateMsg.inbox']+"("+count+")");
    }
    else if(purpose == "sent")
    {
        currSelectedTab.find('a').html(i18n['zohodiscussions.privateMsg.sent']+"("+count+")");
    }
    currSelectedTab.attr('count',count);
    
}//function manageCountValue()    

/**** My Area Clicks End ****/

/*** PAGINATION START *****/

function fnPagination($target,navType,authorProfile)
{   
    showLoadingImage();
    var action = $target.attr('action');
    var currType = $target.attr('currType');
    var options={};
    
    if(authorProfile == "true")
    {
        currType = "authorProfile"
    }
    var currShowPage = $('#'+currType+'InnerContent').find('div[status="show"]');
    
    options.forumGroupId = forumGroupId;
    if(currType != "privateMsg")
    {
        options.userId = $target.attr('userId');
        var postType = $('#'+currType+'Tab').find('li.selected').attr('purpose');
        if(postType == "topics" || postType == "drafts" || postType == "authorTopics")
        {
            options.filterType = currShowPage.attr('currfiltertype');
        }
    }
    if(currType == "myJournals")
    {
        options.viewType = "myself";
    }
    var fetchPage = parseInt($target.attr('fetchPage'));
    if(navType == "next")
    {
        options.fetchPage = fetchPage+1
    }
    else
    {
        options.fetchPage = fetchPage-1
    }
    options.getPostFor = $target.attr('getPostFor');
            
    doAjaxAction(
        action,
        options,
        function (data)
        {   
            hideLoadingImage();
            currShowPage.get(0).innerHTML = data;

         // expand and list view type maintained   
            var currSelectTab  = $('#'+currType+'Tab').find('li.selected').attr('purpose');
            var $currentSelectAction = $('#'+currType+'SelectAction');
            if(currSelectTab == "replies")
            {
                $currentSelectAction.find('li[purpose="expandedView"]').html("<span class=boldText>"+i18n['zohodiscussions.myArea.expandView']+"</span>");
                $currentSelectAction.find('li[purpose="listView"]').html("<a class=underline href=javaScript:;>"+i18n['zohodiscussions.myArea.listView']+"</a>");
            }
            else
            {
                $currentSelectAction.find('li[purpose="expandedView"]').html("<a class=underline href=javaScript:;>"+i18n['zohodiscussions.myArea.expandView']+"</a>");
                $currentSelectAction.find('li[purpose="listView"]').html("<span class=boldText>"+i18n['zohodiscussions.myArea.listView']+"</span>");
            }

        },
        function (err)
        {
            var responseData = eval(err.responseText);
            showMessage(responseData.reason,'failure');
            hideLoadingImage();
        }
    );

}//function fnPagination($target,navType,authorProfile)

function fnPaginationProcess($target,type)
{
    var fetchPage = parseInt($target.attr('fetchPage'));
    var currType = $target.attr('currType');
    var postCount = $target.attr('postCount');
    if(type == "next")
    {
        fetchPage = fetchPage+1;
    }
    else
    {
        fetchPage = fetchPage-1;
    }
    $target.attr('fetchPage',fetchPage);
    var $currShowList = $('#current_'+currType+'_List');
    var endPost = (fetchPage * postPerPage);
    var startPost = (endPost - postPerPage)+1;
    var count = startPost;
    if(postCount <= endPost)
    {
        endPost = postCount;
        $target.find('li[purpose="next"]').removeClass('navBtnEnabled').addClass('navBtnDisabled');
    }
    else
    {
        $target.find('li[purpose="next"]').removeClass('navBtnDisabled').addClass('navBtnEnabled');
    }
    if(startPost == 1)
    {
        $target.find('li[purpose="prev"]').removeClass('navBtnEnabled').addClass('navBtnDisabled');
    }
    else
    {
        $target.find('li[purpose="prev"]').removeClass('navBtnDisabled').addClass('navBtnEnabled');
    }
    if(currType == "recentActivity")
    {
        $currShowList.find('li').hide();
        for(count;count <= endPost ; count++)
        {
            $('#recentActivity_'+count).show();
        }
    }
    else
    {   
        $currShowList.find('div.moderateSinglePost').hide();
        var currViewType =  currType
        if(currType == "watchTopic")
        {
            currType = "watchList";
        };
        var filterType  = $('#'+currType+'InnerContent').find('div[status="show"]').attr('filterType');
        if((currType == "watchList" || currType == "bookMark") && filterType != "all")
        {
            var totalPost;
            $listOfTypes = $currShowList.find('.'+filterType);
            count--;
            $listOfTypes.each (function(index, item)
            {   
                if(index < endPost && count <= index)
                {
                    $(item).show();
                }
                totalPost = index;
            });
        }
        else
        {
            for(count;count <= endPost ; count++)
            {   
                $currShowList.find('div.moderateSinglePost[listStage="'+currViewType+'_'+count+'"]').show();
            }
        }    
    }
}//function fnPaginationProcess($target,type)

/*** PAGINATION END *****/

/**** AUTHOR PROFILE START ***/

function getAuthorProfile(authorName)
{   
    showLoadingImage();
    var $userProfileMainContainer = $('#userProfileMainContainer');
    if($userProfileMainContainer.length > 0 && $userProfileMainContainer.is('[shouldReload="false"]'))
    {
        $userProfileMainContainer.show().attr('shouldReload','true').siblings().remove();
        hideLoadingImage();
    }
    else
    {
        var options={}
        options.forumGroupId = forumGroupId;
        options.authorName = authorName;
        options[csrfParamName] = csrfToken;
        options.ch = ch;
        doAjaxAction(
            '/getAuthorProfile.do',
            options,
            function (data)
            {
                hideLoadingImage();
                $('#authorPopout:visible').hide();
                $('#mainContent').get(0).innerHTML = data;
                $.history.add('User/'+authorName)
                bindAuthorProfileActions(authorName);
            },
            function (err)
            {
                var responseData = eval(err.responseText);
                showMessage(responseData.reason,'failure');
                hideLoadingImage();
            }
        );    
    }
}
function bindAuthorProfileActions(authorName)
{
    $('#mainContent').unbind('click', processAuthorProfileClick).click(processAuthorProfileClick);
    $('#mainContent').unbind('click', processAllMyAreaMainClick).click(processAllMyAreaMainClick);
    $('#mainContent').unbind('click', processAllActionClick).click(processAllActionClick);
    allFilterOption("authorProfile");
    var authorId = $('#mainContent > #userProfileMainContainer').attr("authorId");
     $('#authorPopout_'+authorId).hide();
    if(typeof WmsContacts != "undefined" && ch == true)
    {
        var authStatus = WmsContacts.status(authorId);
        if(authStatus === false)
        {
                authStatus = 9;
        }
        manageUserChatStatus("userOnlineStatus_"+authorName,authStatus,authorName);
    }
}
function processAuthorProfileClick(event)
{
    var $target = $(event.target);
    var $targetParent = $target.parent();
    if($('#loadingImg').is(":visible"))
    {
        return;
    }
    else if($targetParent.is('li[purpose="sendPM"]'))
    {   
        //$('#userPrivateMsgTab').trigger('click');
        //writePrivateMsg();
        addPrivateMessage($targetParent);
    }
    else if($targetParent.is('li[purpose="watchItem"]'))
    {
        watchItem($targetParent);
    }
    else if($targetParent.is('li[purpose="blockUser"]'))
    {
        blockUser($targetParent)
    }
    else if($targetParent.is('li[purpose="unBlockUser"]'))
    {
        unBlockUser($targetParent)
    }
    else if($targetParent.is('li[purpose="moderateUser"]'))
    {
       moderateUser();
    }
    else if($targetParent.is('li[purpose="assignLabel"]'))
    {
       bindUserLabelsAction();
    }
}
function writePrivateMsg()
{   
    var $editTopicCont = $('#sentPrivateMsg');
    var $topicContainer=$('#editorContainer_PM');
    if($topicContainer.data('inEditMode'))
    {
        showMessage(i18n['zohodiscussions.singlepost.alertmessageforediting'],"failure");
        return false;
    }
    $editTopicCont.show();
    openEditor($('#editPM'),"privateMsgContent","postContentTA","UserPM","Write","editorContainer_PM");
    $topicContainer.data('inEditMode',true);
   // bindEditorPMAction($topicContainer,$editTopicCont);

}//function writePrivateMsg()

/***** AUTHOR PROFILE END *****/

function watchItem($target)
{
    showLoadingImage();
    var itemType = $target.attr('itemType');
    var options = {};
    options.forumGroupId = forumGroupId;
    options.itemType = itemType;
    options.itemId = $target.attr('itemId');
    options[csrfParamName] = csrfToken;
    doAjaxAction(
        '/watchItem.do',
        options,
        function (data)
        {
            hideLoadingImage();
            showTipper(i18n['zohodiscussions.watchList.successfullyWatchUser'],"success");
            $target.attr('purpose',"unWatchItem");
            $target.find('a').html(i18n['zohodiscussions.userProfile.unwatchUser']);
        },
        function (err)
        {
            var responseData = eval(err.responseText);
            showMessage(responseData.reason,'failure');
            hideLoadingImage();
        }
    );
}//function watchItem($target)

function unWatchItem($target,type)
{
    showLoadingImage();
    var type = $target.attr('unWatchType');
    var itemId = $target.attr('itemId');
    var options = {};
    
    options.forumGroupId = forumGroupId;
    options.itemId = itemId;
    options[csrfParamName] = csrfToken;
    doAjaxAction(
        '/unWatch.do',
        options,
        function (data)
        {
            hideLoadingImage();
            if(type == "authorProfile")
            {
                showTipper(i18n['zohodiscussions.watchList.successfullyUnwatchUser'],"success");
                $target.attr('purpose',"watchItem");
                $target.find('a').html(i18n['zohodiscussions.userProfile.watchUser']);
            }
            else
            {
                if(type == "following")
                {
                    showTipper(i18n['zohodiscussions.watchList.successfullyUnwatchUser'],"success");
                    $('#watch_'+itemId).parents('li').remove();
                }
                else
                {
                    showTipper(i18n['zohodiscussions.watchList.successfullyUnwatchTopic'],"success");
                    $('#watch_'+itemId).remove();
                    manageCountValue("watchListTabs");
                }
            }
        },
        function (err)
        {
            var responseData = eval(err.responseText);
            showMessage(responseData.reason,'failure');
            hideLoadingImage();
        }
    );
}//function watchItem($target)

function blockUser($target)
{
    showLoadingImage();
    var options = {};
    options.forumGroupId = forumGroupId;
    options.authorId = $target.attr("authorId");
    options[csrfParamName] = csrfToken;
    doAjaxAction(
        '/blockUser.do',
        options,
        function (data)
        {
            hideLoadingImage();
            showTipper(i18n['zohodiscussions.userProfile.successfullyBlockUser'],"success");
            $target.attr('purpose',"unBlockUser");
            $target.find('a').html(i18n['zohodiscussions.userProfile.unblockUser']);
        },
        function (err)
        {
            var responseData = eval(err.responseText);
            showMessage(responseData.reason,'failure');
            hideLoadingImage();
        }
    );
}//function blockUser($target)

function unBlockUser($target)
{   
    showLoadingImage();
    var options = {};
    options.forumGroupId = forumGroupId;
    options.authorId = $target.attr("authorId");
    options[csrfParamName] = csrfToken;
    doAjaxAction(
        '/unBlockUser.do',
        options,
        function (data)
        {
            hideLoadingImage();
            showTipper(i18n['zohodiscussions.userProfile.successfullyUnBlockUser'],"success");
            $target.attr('purpose',"blockUser");
            $target.find('a').html(i18n['zohodiscussions.userProfile.blockUser']);
        },
        function (err)
        {
            var responseData = eval(err.responseText);
            showMessage(responseData.reason,'failure');
            hideLoadingImage();
        }
    );
}//function unBlockUser($target)

//to moderate user
function moderateUser()
{
    $('#moderateUserTemplate').html($('#dimDivModerateUser').html());
    $('#dimDivModerateUser').html('');
    $('#moderateUserTemplate').show();
    var $forumCont = $('#eachForumListForModeration').find(":input[name='forumLevelModeration']");
    var $portalCont = $('#moderateUserPopOutForm').find(":input[name='portalLevelModeration']");
    if($forumCont.length == 0)
    {
        $('#forumLabel').hide();
    }
    if($portalCont.attr('checked'))
    {
        $forumCont.attr('disabled',true);
    }
    //for cancelling moderate action
    $('#imgCancel').click(function()
    {
        $this = $(this);
        $('#dimDivModerateUser').html($('#moderateUserTemplate').html());
        $('#moderateUserTemplate').hide();
        $('#moderateUserTemplate').html('');
        var $status = $('#moderateUserCont');
        if($status.attr('status') == 'changed')
        {
            var $userProfileMainContainer = $('#userProfileMainContainer');
            $userProfileMainContainer.show().attr('shouldReload','true');
            getAuthorProfile($this.attr('authorName'));
        }
    }); 
          
    //for portal
    $portalCont.click(function()
    {
        $this = $(this);
        if($this.attr('checked'))
        {
            $forumCont.attr('disabled',true);
        }
        else
        {
            $forumCont.attr('disabled',false);
        } 
       moderateUserAction($this);
    });
    
    //for forum
    $forumCont.click(function()
    {
        $this = $(this);
        moderateUserAction($this);
    });
}
//moderateUser action
function moderateUserAction($this)
{ 
    var $status = $('#moderateUserCont');
    $status.attr('status','changed');
    var authorId =$this.attr('authorId');
    var author =$this.attr('userName');
    var moderteStatus = $this.attr('moderationStatus');
    var adminUser = $this.attr('isAdmin');
    var isPortal = $this.attr('isPortal');
    var moderateType = 0;
    var isModerted = false;
    var confirmMess = "";
    var successMess = "";
    var options = {};
    options.authorId = authorId;
    options.forumGroupId = forumGroupId;
    options[csrfParamName] = csrfToken;
    options.adminUser = adminUser
    if(isPortal)
    {
        options.moderateType = 1;
        if(moderteStatus == 'unmoderated')
        {
            confirmMess = i18n['zohodiscussions.userProfile.moderateUserConfirmMess']+" "+author+" "+i18n['zohodiscussions.userProfile.moderateUserPortalLevel'];
            successMess = i18n['zohodiscussions.userProfile.usermoderatedSuccessMess'];
        }
        else
        {
             confirmMess = i18n['zohodiscussions.userProfile.unmoderateUserConfirmMess']+" "+author+" "+i18n['zohodiscussions.userProfile.moderateUserPortalLevel'];
             successMess = i18n['zohodiscussions.userProfile.userUnmoderatedSuccessMess'];
        } 
    }
    else
    {
        options.moderateType = 0;
        var forumId = $this.attr('forumId');
        options.forumId = forumId;
        var forumName = $this.attr('forumName');
        if(moderteStatus == 'unmoderated')
        {
            confirmMess = i18n['zohodiscussions.userProfile.moderateUserConfirmMess']+" "+author+" "+i18n['zohodiscussions.general.in']+" "+forumName+" "+i18n['zohodiscussions.userProfile.moderateUserForumLevel'];
            successMess = " "+i18n['zohodiscussions.userProfile.usermoderatedSuccessMess'];
        }
        else
        {
            confirmMess = i18n['zohodiscussions.userProfile.unmoderateUserConfirmMess']+" "+author+" "+i18n['zohodiscussions.general.in']+" "+forumName+" "+i18n['zohodiscussions.userProfile.moderateUserForumLevel'];
            successMess = i18n['zohodiscussions.userProfile.userUnmoderatedSuccessMess'];
        }     
    }
    if(moderteStatus == 'unmoderated')
    {
        if(confirm(confirmMess))
        {
            doAjaxAction('/moderateUser.do',options,function(data)//No internationalization
            {
                if(data == "SUCCESS")
                { 
                   showTipper(author+" "+successMess,'success',1000);
                   $this.attr('moderationStatus','moderated');
                   if(!isPortal)
                   {
                       $('#itemListCont_'+forumId).find('span.italicText').html(i18n['zohodiscussions.moderationLeftContainer.moderated']);
                   }
                }
                else
                {
                    showMessage(i18n['zohodiscussions.moderationAction.errormessage'],"failure");
                }
            });//doAjaxAction('/moderateUser.do',options,function(data)
        }//if($this.is('.block') == true)
        else
        {
            var $status = $('#moderateUserCont');
            $status.attr('status','');
            if(isPortal)
            {
                $('#moderateUserPopOutForm').find(":input[isPortal='true']").attr('checked',false);
                $('#eachForumListForModeration').find(":input[name='forumLevelModeration']").attr('disabled',false);
                
            }
            else
            {
                $('#moderateUserPopOutForm').find(":input[forumId='"+forumId+"']").attr('checked',false);
            }  
        }
    }
    else
    {
        if(confirm(confirmMess))
        {
            doAjaxAction('/unModerateUser.do',options,function(data)//No internationalization
            {
                if(data == "SUCCESS")
                {
                  showTipper(author+" "+successMess,'success',1000);
                  $this.attr('moderationStatus','unmoderated');
                   if(!isPortal)
                   {
                       $('#itemListCont_'+forumId).find('span.italicText').html(i18n['zohodiscussions.ModerateUsers.ModerateUsers']);
                   }
                   
                }//if(data == "SUCCESS")
                else
                {
                    showMessage(i18n['zohodiscussions.moderationAction.errormessage'],"failure");
                }
            });
        }
        else
        {
            var $status = $('#moderateUserCont');
            $status.attr('status','');
            if(isPortal)
            {
                
                $('#moderateUserPopOutForm').find(":input[isPortal='true']").attr('checked',true);
                $('#eachForumListForModeration').find(":input[name='forumLevelModeration']").attr('disabled',true);
            }
            else
            {
                $('#moderateUserPopOutForm').find(":input[forumId='"+forumId+"']").attr('checked',true);
            }  
        }
    }
}//function moderateUserAction()

function bindUserLabelsAction()
{
    $('#userLabelsTemplate').html($('#dimDivUserLabels').html());
    $('#dimDivUserLabels').html('');
    $('#userLabelsTemplate').show();
    $('#closeUserLabelsDialog').click(function()
    {
        $('#dimDivUserLabels').html($('#userLabelsTemplate').html());
        $('#userLabelsTemplate').hide();
        $('#userLabelsTemplate').html('');
    });
    
    $('#userLabelsCont select[purpose="userLabelBox"]').change(function()
    {
        var $this = $(this);
        var forumId = $this.attr('forumId');
        var userId = $this.attr('userId');
        var labelId = $this.val();
        var options = {};
        options.forumGroupId = forumGroupId;
        options.forumId = $this.attr('forumId');
        options.userId = $this.attr('userId');
        options.labelId = $this.val();
        options[csrfParamName] = csrfToken;
        doAjaxAction('/mapLabelToUser.do',options,function(data)
        {
            if(data == "SUCCESS")
            {
                $this.find("option[selected]").removeAttr('selected');
                var $selectedLabel = $this.find("option[value='"+labelId+"']");
                var labelText = $selectedLabel.text();
                $selectedLabel.replaceWith("<option value='"+labelId+"' selected>"+labelText+"</option>");
                if(labelId == "-1")
                {
                    showTipper(i18n['zohodiscussions.UserDetails.labelRemovedMsg'],'info');
                }
                else
                {
                    showTipper(i18n['zohodiscussions.UserDetails.labelAddedMsg'],'success');
                }
            }
        });
    });
}

// chat setpresence
function setPresenceInTopicList(dObj,forumTopicId)
{
    if(!dObj) {return;}
    var $authorContainer = "";
    if(!forumTopicId)
    {
        if($('#topicList').length > 0)
        {
            $authorContainer = $('#topicList > div.singleTopicCont > div.chatTopicCont > div.topicMDetails > div.lightGreyText > img.authorChatPresence');
        }
        else
        {
            $authorContainer = $('#topicsList > div.singleTopicCont > div.chatTopicCont > div.topicMDetails > div.lightGreyText > img.authorChatPresence');
        }
        $stickyPostAuthors = $('#recentStickyPosts >li  >div.ashColorText >div.authorChatPresence');
        $announcementPostAuthors = $('#recentAnnouncementPosts >li  >div.ashColorText >div.authorChatPresence');
        $authorContainer.each (function(index, item)
        {
            var $item = $(item);
            var userId = $item.attr('authorId');
            if(userId == ZUID) {return;}
            var responseId = $item.attr('responseId');
            var $authorContainers = "";
            $authorContainers = $('#uc_'+responseId+'_'+userId);
            try
            {   
                var status = dObj[userId]["STATUS"];
                manageUserChatStatusInTopicList($authorContainers,status,"topicList");
            }//try
            catch(ex)
            {
            }
        });
        $stickyPostAuthors.each(function(index,item)
        {
            var $item = $(item);
            var userId = $item.attr('authorId');
            if(userId == ZUID) {return;}
            try
            {   
                var status = dObj[userId]["STATUS"];
                manageUserChatStatusInTopicList($item,status);
            }//try
            catch(ex)
            {
            }
        });
        $announcementPostAuthors.each(function(index,item)
        {
            var $item = $(item);
            var userId = $item.attr('authorId');
            if(userId == ZUID) {return;}
            try
            {   
                var status = dObj[userId]["STATUS"];
                manageUserChatStatusInTopicList($item,status);
            }//try
            catch(ex)
            {
            }
        });
     }
     else
     {
        $authorContainer = $('#SinglePostContainer_'+forumTopicId+' div.postTitle div.authorChatPresence');
        $authorContainer.each (function(index, item)
        {
            var $item = $(item);
            var userId = $item.attr('authorId');
            if(userId == ZUID) {return;}
            var responseId = $item.attr('responseId');
            var $authorContainers = "";
            $authorContainers = $('#uc_'+forumTopicId+'_'+responseId+'_'+userId);
            try
            {   
                var status = dObj[userId]["STATUS"];
                manageUserChatStatusInTopicList($authorContainers,status);
            }//try
            catch(ex)
            {
            }
        });
     }
    
}//function setPresence(dobj)

function setPresenceInMyArea(dObj,$currLocation)
{
    if(!dObj) {return;}
    var $authorContainer = "";
    if($currLocation == "current_recentActivity_List")
    {
        $authorContainer = $('#'+$currLocation+' >li >div.authorChatPresence');
    }
    else if($currLocation == "userChat_inbox" || $currLocation == "userChat_sent")
    {
        $authorContainer = $('#'+$currLocation+' div.moderateSinglePost ul li img.authorChatPresence');
    }
    else
    {
        $authorContainer = $('#'+$currLocation+' div.moderateSinglePost ul li div.authorChatPresence');
    }    
    $authorContainer.each (function(index, item)
    {
        var $item = $(item);
        var userId = $item.attr('authorId');
        if(userId == ZUID) {return;}
        try
        {   
            var status = dObj[userId]["STATUS"];
            manageUserChatStatusInTopicList($item,status);
        }//try
        catch(ex)
        {
        }
    });
}//function setPresence(dobj)
function setPresence(dObj,userLocation)
{
    if(!dObj) {return;}
    var $userDetails = $('#'+userLocation+' > li > div.userChatPresence');
    $userDetails.each (function(index, item)
    {
        var $item = $(item);
        var authorId = $item.attr('authorId');
        if(authorId == ZUID) {return;}
        var authorLocation = $item.attr('id');
        var authorName = $item.attr('authorName');
        try
        {   
            var status = dObj[authorId]["STATUS"];
            manageUserChatStatus(authorLocation,status,authorName);
        }
        catch(ex)
        {

        }
    });   
}//setPresence(dObj)
function manageUserChatStatus(authorLocation,status,userName)
{
    var $currAuthorProfile =  $('#'+authorLocation);
    
    if(status == "4")
    {
        $currAuthorProfile.find('div').attr('class', 'wms-4 chatOverride flLeft').unbind('click', chatInvoker).click(chatInvoker);
        $currAuthorProfile.find('a').html(i18n['zohodiscussions.chat.idleForChat']);
        $currAuthorProfile.attr('title', userName +" "+i18n['zohodiscussions.chat.isNowIdle']).unbind('click',chatInvoker).click(chatInvoker);
    }
    else if(status == "3")
    {
        $currAuthorProfile.find('div').attr('class', 'wms-3 chatOverride flLeft').unbind('click', chatInvoker).click(chatInvoker);
        $currAuthorProfile.find('a').html(i18n['zohodiscussions.chat.busyforchat']);
        $currAuthorProfile.attr('title', userName +" "+i18n['zohodiscussions.chat.isBusyToChat']).unbind('click',chatInvoker).click(chatInvoker);
    }
    else if(status == "1")
    {
        //user is online, mark as present
        $currAuthorProfile.find('div').attr('class', 'wms-1 chatOverride flLeft');
        $currAuthorProfile.find('a').html(i18n['zohodiscussions.chat.availableforchatmessage']);
        $currAuthorProfile.attr('title', userName +" "+i18n['zohodiscussions.chat.isAvailableToChat']).unbind('click',chatInvoker).click(chatInvoker);

    }
    else if(status == "0")
    {
        $currAuthorProfile.find('div').attr('class', 'wms-0 chatOverride flLeft');
        $currAuthorProfile.find('a').html(i18n['zohodiscussions.chat.offlineforchat']).unbind('click',chatInvoker).click(chatInvoker);
        $currAuthorProfile.attr('title', i18n['zohodiscussions.chat.offlineforchat']).unbind('click',chatInvoker).click(chatInvoker);

    }
    else if(status== "-1")
    {
        $currAuthorProfile.find('div').attr('class','imgAddContact flLeft');
        $currAuthorProfile.find('a').html(i18n['zohodiscussions.chat.invitedforchat']);
        $currAuthorProfile.attr('title', i18n['zohodiscussions.chat.youHaveInvited'] +" "+ userName +" "+ i18n['zohodiscussions.chat.toChat']).unbind('click',chatInvoker);
    }
    else if(status== "-3")
    {
        $currAuthorProfile.find('div').attr('class','imgAddContact flLeft');
        $currAuthorProfile.find('a').html(i18n['zohodiscussions.chat.acceptinvitationforchat']);
        $currAuthorProfile.attr('title', userName +" "+ i18n['zohodiscussions.chat.youHaveInvited']).unbind('click',chatInvoker);
    }
    $currAuthorProfile.find('div').unbind('click',chatInvoker).click(chatInvoker);
    $currAuthorProfile.find('a').unbind('click',chatInvoker).click(chatInvoker);
}

function manageUserChatStatusInTopicList($authorContainers,status,isTopic)
{
    var flag=0;
    if(status == "4")
    {   
        flag=1;
        $authorContainers.attr('class', 'wms-4 flLeft').unbind('click',chatInvoker).click(chatInvoker);
    }
    else if(status == "3")
    {   
        flag=1;
        $authorContainers.attr('class', 'wms-3 flLeft').unbind('click',chatInvoker).click(chatInvoker);
    }
    else if(status == "1")
    {   
        flag=1;
        $authorContainers.attr('class', 'wms-1 flLeft').unbind('click',chatInvoker).click(chatInvoker);
    }
    else if(status == "0")
    {   
        flag=1;
        $authorContainers.attr('class', 'wms-0 flLeft').unbind('click',chatInvoker).click(chatInvoker);
    }
    else if(status == "-4")
    {   
        $authorContainers.attr('class', 'flLeft').unbind('click',chatInvoker);
    }
    else if(status == "-5")
    {   
        $authorContainers.attr('class', 'flLeft').unbind('click',chatInvoker);
    }
    if(isTopic == "topicList")
    {   
        if(flag == 1)
        {
            $authorContainers.addClass('authorChatPresence chatStyleOverride');
        }
        else
        {
            $authorContainers.remove();
        }
    }
    else
    {
        $authorContainers.addClass('authorChatPresence chatOverride');
    }
}

function chatInvoker()
{   
        var $this = $(this);
        var name = $this.attr('authorName');
        var authorId = $this.attr('authorId');
        if(authorId==undefined){
                authorId = $this.parent().attr("authorId");
                name = $this.parent().attr("authorName");
        }
        var authStatus = WmsContacts.status(authorId);
        if(authStatus > -1 && authStatus !== false)
        {
                WebMessanger.chat(authorId);
                return;
        }
        if(authStatus==-1)
        {
          if(confirm(name+ " " + i18n['zohodiscussions.chat.reminder']))
          {
                WmsContacts.add("zoho",name,ZUID);
          }
        }
        else if(authStatus==-3)
        {
          WmsContacts.accept("zoho",name, ZUID);
        }
        else
        {
                WmsContacts.add("zoho",name,ZUID);
        }
}

function updatePresence(usid,uname,status)
{
    if(ch != true)
    {
        return;
    }
    if($('#recentStickyPosts').is(':visible'))
    {
        var $stickyPostAuthors = $('#recentStickyPosts >li >div.ashColorText >div.authorChatPresence');
        $stickyPostAuthors.each(function(index,item)
         {
                 var $item = $(item);
                 var userId = $item.attr('authorId');
                 if(userId == usid)
                 {
                          manageUserChatStatusInTopicList($item,status);
                 }//try

         });
    }
    if($('#recentAnnouncementPosts').is(':visible'))
    {
        var $stickyPostAuthors = $('#recentAnnouncementPosts >li >div.ashColorText >div.authorChatPresence');
        $stickyPostAuthors.each(function(index,item)
         {
                 var $item = $(item);
                 var userId = $item.attr('authorId');
                 if(userId == usid)
                 {
                          manageUserChatStatusInTopicList($item,status);
                 }//try

         });
    }
    if($('#topicListMainContainer').is(':visible'))
    {
        var uCont = eval('('+$('#uListForStatusUpdate').html()+')');
        var zuid = "z"+usid;
        if(typeof uCont[zuid] != "undefined")
        {
          for(i=0;i<uCont[zuid].length;i++)
          {
                var $authorContainers = $('#uc_'+uCont[zuid][i]+'_'+usid);
                manageUserChatStatusInTopicList($authorContainers, status,"topicList");
          }
        }
        if($('#singleForumHeaderView').is(':visible'))
        {
            var currForumId = $('#singleForumHeaderView').attr('forumId');
            manageUserChatStatus("moderatorOnlineStatus_"+currForumId+"_"+uname,status,uname);

        }
        
     }
     else if($('#SinglePostContainer').is(':visible'))
     {
        var topicId = $('#SinglePostContainer').attr('forumTopicId');
        var uCont = eval('('+$('#uListForStatusUpdateInSP').html()+')');
        var zuid = "z"+usid;
        if(typeof uCont[zuid] != "undefined")
        {
          for(i=0;i<uCont[zuid].length;i++)
          {
                var $authorContainers = $('#uc_'+topicId+'_'+uCont[zuid][i]+'_'+usid);
                manageUserChatStatusInTopicList($authorContainers, status);
          }
        }
     }
     else if($('#userProfileMainContainer').is(':visible'))
     {
        manageUserChatStatus("userOnlineStatus_"+uname,status,uname);
     }
     else if($('#myAreaInnerMainContent').is(':visible'))
     {
        if($('#profileDetailCont').is(':visible'))
        {
            manageUserChatStatus("followersOnlineStatus_"+uname,status,uname);
            manageUserChatStatus("followingOnlineStatus_"+uname,status,uname);
            var $authorContainer = $('#current_recentActivity_List >li >div.authorChatPresence');
            $authorContainer.each (function(index, item)
            {
                var $item = $(item);
                var userId = $item.attr('authorId');
                if(userId == usid)
                {
                    manageUserChatStatusInTopicList($item, status);
                }
            });
        }  
        else
        {
            var currView = "";
            if($('#watchListInnerContent').is(':visible'))
            {
                var $currShowing = $('#watchListInnerContent').find('div[status="show"]');
                currView = $currShowing.attr('id');
            }
            else if($('#privateMsgInnerContentent').is(':visible'))
            {
                 var $currShowing = $('#privateMsgInnerContent').find('div[status="show"]');
                 currView = $currShowing.attr('id');
            }
            if(currView != "")
            {
                var $authorContainer = "";
                if(currView == "privateMsgInnerContent")
                {
                    $authorContainer = $('#'+currView+' div.moderateSinglePost ul li img.authorChatPresence');
                }
                else
                {
                    $authorContainer = $('#'+currView+' div.moderateSinglePost ul li div.authorChatPresence');
                }
                $authorContainer.each (function(index, item)
                {
                    var $item = $(item);
                    var userId = $item.attr('authorId');
                    if(userId == usid)
                    {
                        manageUserChatStatusInTopicList($item, status);
                    }
                });
            }
        }
        manageUserChatStatus("authorPopup_"+uname,status,uname);
    }
}//function updatePresence(uid)

function addPrivateMessage($this)
{   
     var toMember = $this.attr('toMember');
     var toMemberName = $this.attr('authorname');
     var $privateMsgPrompt = $('#privateMsgPrompt');
     var $privateMsgToMemberArea = $('#privateMsgToMemberArea');
     var $privateMsgTitleArea = $('#privateMsgTitleArea');
     var $privateMsgContentArea = $('#privateMsgContentArea');
     var $privateMsgToMemberId = $('#privateMsgToMemberId');
     $privateMsgToMemberId.val("");
     $privateMsgToMemberArea.val("");
     $privateMsgTitleArea.val("");
     $privateMsgContentArea.val("");
     $privateMsgToMemberId.val(toMember);
     $privateMsgToMemberArea.val(toMemberName);
     $privateMsgPrompt.show().parent().show();
     $('#cancelPrivateMsgButton, #cancelPrivateMsg').unbind('click').click(function()
     {
        $privateMsgToMemberArea.val("");$privateMsgTitleArea.val("");$privateMsgContentArea.val("");
        var $writePMCaptcha = $('#writePMCaptcha');
        $writePMCaptcha.find('img').attr("src","/images/spacer.gif");
        $writePMCaptcha.find(':input').val("");
        $writePMCaptcha.hide();
        $privateMsgPrompt.hide().parent().hide();
     });
     $('#addNewPrivateMsg').unbind('click').click(function()
     {
        showLoadingImage();
    
        var contentToPost = $privateMsgContentArea.val();

        contentToPost = contentToPost.replace(/^\s+/g, '').replace(/\s+$/g, ''); //replace(/<[^>]*>/ig, '')

        if (contentToPost == '' )
        {
            hideLoadingImage();
            showMessage(i18n['zohodiscussions.writePost.noContentInPost'],"failure");
            return;
        }
        var titleToPost = $privateMsgTitleArea.val();
        titleToPost = titleToPost.replace(/^\s+/g, '').replace(/\s+$/g, ''); //replace(/<[^>]*>/ig, '')

        if (titleToPost == '' )
        {
            hideLoadingImage();
            showMessage(i18n['zohodiscussions.writePost.noTitleInPost'],"failure");
            return;
        }
        doAjaxAction(
            "/addPrivateMsg.do", //No I18N
            $privateMsgPrompt.find('form').serialize(),
            function (data)
            {
                var $writePMCaptcha = $('#writePMCaptcha');
                $writePMCaptcha.find('img').attr("src","/images/spacer.gif");
                $writePMCaptcha.find(':input').val("");
                $writePMCaptcha.hide();
                hideLoadingImage();
                showTipper(i18n['zohodiscussions.privateMsg.successfullyPMAdded'],"success");
                $privateMsgPrompt.hide().parent().hide();
            },
            function (err)
            {
                var responseData = eval(err.responseText);
                if(responseData.errorcode == "HIP_REQUIRED")
                {
                    var $writePMCaptcha = $('#writePMCaptcha');
                    if($writePMCaptcha.attr('currCaptcha') == "new")
                    {
                         showMessage(i18n['zohodiscussions.writePost.captchaMsg'],'failure');
                    }
                    else
                    {
                        showMessage(i18n['zohodiscussions.writePost.captchaErrorMsg'],'failure');
                    }

                    $writePMCaptcha.find('img[purpose="captchaImage"]').replaceWith("<img purpose=captchaImage name=hipImg border=0 src=/showcaptcha?digest="+responseData.reason+" align=absmiddle alt=HIP image>");
                    $('#captchaCodePM').attr('name',responseData.reason);
                    $writePMCaptcha.attr('currCaptcha',"old");
                    $writePMCaptcha.show();
                }
                else
                {
                    showMessage(responseData.reason,'failure');
                }
                hideLoadingImage();
            }
        );
     });
     $privateMsgTitleArea.focus();
}
