/* $Id$ */
function initTabContClick()
{
    $('#homeTab,#allforumsTab,#myareaTab,#moderationTab,#SettingsTab,#NewTopicTab,#Search,#reportsTab').click(function()
    {
        var $this = $(this);
        var hashPurpose = $this.attr('hashPurpose');
        processHash(hashPurpose);
        return false;
    });
    $('#searchComboDownArrow').parent().click(function()
    {
        displaySearchOption();
    });
}//function initTabContClick()

function processHash(hash)
{
    if(isTopicQuickView == "false")
    {
        if(hash.toLowerCase() == "home")
        {
            hash = "recent"; //No I18N
        }
        else if(hash.toLowerCase() == "search")
        {
            var searchFor = $('#searchInputBox').val();
            searchFor =$.trim(searchFor);
            if(searchFor == "")
            {
                showMessage(i18n['zohodiscussions.searchList.noSearchString'],'failure');
                return;
            }
            location.href = serverURL+'/'+hash.toLowerCase()+'/'+searchFor;
            return false;
        }
        location.href = serverURL+'/'+hash.toLowerCase();
        return false;
    }
    if(shouldReload == true && hash != "Search")
    {
        window.location.href = serverURL+'#'+hash;
        return false;
    }
    showLoadingImage();
    if(hash == '')
    {
        if(isTopicQuickView == "false")
        {
            window.location.href = serverURL+'/recent';
            return false;
        }
        discussionsFunctions['home']();
        return false;
    }
    var hashList = hash.split("/");
    var givenKey = hashList[0];
    var hashKey = givenKey.toLowerCase();
    selectTab(hashKey);
    switch(hashKey)
    {
        case 'home':
        case 'chome':
            var fetchPage = 1
            if(parseInt(hashList[1]) > 1)
            {
                fetchPage = hashList[1];
            }
            discussionsFunctions[hashKey](givenKey,fetchPage);
            break;
        case 'alltags':
            discussionsFunctions[hashKey](givenKey);
            break;
        case 'allforums':
            discussionsFunctions[hashKey](givenKey);
            break;
        case 'reports':
            discussionsFunctions[hashKey](givenKey);
            break;
        case 'search':
            var searchFor = hashList[1];
            discussionsFunctions[hashKey](givenKey,searchFor);
            break;
        case 'myarea':
            var myAreaKey = hashList[1];
            var subAction = "";
            if(myAreaKey)
            {
                myAreaKey = myAreaKey.toLowerCase();
            }
            if(myAreaKey == "watchlist")
            {
                subAction = hashList[2];
                if(subAction)
                {
                    subAction = subAction.toLowerCase();
                }    
            }
            discussionsFunctions[hashKey](givenKey,myAreaKey,subAction);
            break;
        case 'moderation':
        case 'settings':
            discussionsFunctions[hashKey](givenKey);
            break;
        case 'topic':
            var forumTopicId = hashList[1];
            var recentResponseId = hashList[2];
            discussionsFunctions[hashKey](givenKey,forumTopicId,recentResponseId);
            break;
        case 'forum':
            var forumURL = hashList[1];
            var fetchPage = 1;
            if(hashList[2])
            {
                var categoryURL = "";
                var count = parseInt(2);
                if(hashList[count] != "filter" && hashList[count].toLowerCase() != "all")
                {
                    var temp = parseInt(hashList[count]);
                    if(temp > 0)
                    {
                        fetchPage = temp;
                        count = count+1;
                    }
                    else
                    {
                        categoryURL = hashList[count];
                        count = count+1;
                    }
                }
                if(hashList[count])
                {
                    if(hashList[count] == "filter")
                    {
                        count = count+1;
                        var filterType = hashList[count];
                        var filterStatus = "";
                        filterType = filterType.toLowerCase();
                        if(filterType != "discussions" && filterType != "questions" && filterType != "ideas" && filterType != "problems" && filterType != "announcement" && filterType != "sticky" && filterType != "unrepliedposts" && filterType != "postssincelastvisit")
                        {
                            filterType = "all"; //No I18N
                            if(isOneTopicType != "true")
                            {
                                count = count+1;
                            }
                        }
                        else
                        {
                            count = count+1;    
                            if(hashList[count])
                            {
                                filterStatus = hashList[count];
                            }
                        }
                        if(isOneTopicType == "true" && filterType == "all")
                        {
                            filterStatus = hashList[count];
                        }
                        if(hashList[count])
                        {
                            if(parseInt(hashList[count]) > 0)
                            {
                                fetchPage = hashList[count];
                            }
                        }
                        getMoreTopics(forumURL,categoryURL,fetchPage,filterType,'',filterStatus,"reload"); //No I18N
                    }
                    else
                    {
                        if(hashList[count])
                        {
                            if(parseInt(hashList[count]) > 0)
                            {
                                fetchPage = hashList[count];
                            }
                        }
                        discussionsFunctions[hashKey](givenKey,forumURL,categoryURL,fetchPage);
                    }
                }
                else
                {
                    discussionsFunctions[hashKey](givenKey,forumURL,categoryURL,fetchPage);
                }
            }
            else
            {
                discussionsFunctions[hashKey](givenKey,forumURL,"",fetchPage);
            }
            break;
        case 'filter':
            var filterType = hashList[1];
            filterType = filterType.toLowerCase();
            var filterStatus = "";
            var fetchPage = 1;
            if(filterType != "discussions" && filterType != "questions" && filterType != "ideas" && filterType != "problems" && filterType != "announcement" && filterType != "sticky" && filterType != "unrepliedposts" && filterType != "postssincelastvisit")
            {
                filterType = "all"; //No I18N
                if(parseInt(hashList[2]) > 0)
                {
                    fetchPage = hashList[2];
                }
            }
            else
            {
                if(hashList[3])
                {
                    filterStatus = hashList[2];
                    if(parseInt(hashList[3]) > 0)
                    {
                        fetchPage = hashList[3];
                    }
                }
                else if(parseInt(hashList[2]) > 0)
                {
                    fetchPage = hashList[2];
                }
                else
                {
                    filterStatus = hashList[2];
                }
            }
            if(isOneTopicType == "true" && filterType == "all")
            {
                filterStatus = hashList[1];
            }
            getMoreTopics("","",fetchPage,filterType,"",filterStatus,"reload"); //No I18N
            break;
        case 'user':
            var authorName = hashList[1];
            discussionsFunctions[hashKey](givenKey,authorName);
            break;
       case 'tag':
            var tagName = hashList[1];
            discussionsFunctions[hashKey](givenKey,tagName);
            break;
       case 'newtopic':
            var forumId = hashList[1];
            var categoryId = hashList[2];
            discussionsFunctions[hashKey](givenKey,forumId,categoryId);
            break;
       case 'newdiscussion':
            var forumId = hashList[1];
            var categoryId = hashList[2];
            discussionsFunctions["newtopic"](givenKey,forumId,categoryId);
            break;     
       case 'newquestion':
            var forumId = hashList[1];
            var categoryId = hashList[2]
            discussionsFunctions["newtopic"](givenKey,forumId,categoryId);
            break;
       case 'newidea':
            var forumId = hashList[1];
            var categoryId = hashList[2]
            discussionsFunctions["newtopic"](givenKey,forumId,categoryId);
            break;
       case 'newproblem':
            var forumId = hashList[1];
            var categoryId = hashList[2]
            discussionsFunctions["newtopic"](givenKey,forumId,categoryId);
            break;
        case 'tpw' : //No I18N
            var forumId = hashList[1];
            var categoryId = hashList[2];
            var limit = hashList[3];
            var style = hashList[4];
            var ph = hashList[5];
            var tps = hashList[6];
            var widget = hashList[7];
            var aj = hashList[8];
            var stat = hashList[9];
            var qstr = hashList[10];
            var tgt = hashList[11];
            discussionsFunctions["tphome"](givenKey,forumId,categoryId,limit,style,ph,tps,widget,aj,stat,qstr,tgt);//No I18N
            break;
       default:
            hideLoadingImage();
    }//switch(tabPurpose)
    return false;
}//function processHash(hash)

var discussionsFunctions = {};

//to load topic list
discussionsFunctions['tphome'] = function(givenKey,forumId,categoryId,limit,style,ph,tps,widget,aj,stat,qstr,tgt) //No I18N
{
    var fetchPage =1;
    getForumTopics(forumId,categoryId,fetchPage,givenKey,limit,style,ph,tps,widget,aj,stat,qstr,tgt);
};
discussionsFunctions['home'] = function(givenKey,fetchPage)
{   
    var forumId = -1;
    var categoryId = -1;
    var fetchPage =fetchPage;
    if(typeof givenKey == "undefined")
    {
        givenKey = "home"; //No I18N
        fetchPage = 1;
    }
    getForumTopics(forumId,categoryId,fetchPage,givenKey);
};
discussionsFunctions['chome'] = function(givenKey,fetchPage)
{
    var forumId = -1;
    var categoryId = -1;
    var fetchPage =fetchPage;
    if(typeof givenKey == "undefined")
    {
        givenKey = "chome"; //No I18N
        fetchPage = 1;
    }
    getForumTopics(forumId,categoryId,fetchPage,givenKey);
};

discussionsFunctions['reports'] = function(givenKey)
{
    var forumId = -1;
    var categoryId = -1;
    var fetchPage =1;
    getTopicsReport(forumId,categoryId,fetchPage,givenKey);
};
//to load single forum topic list/ with widgets container
//params : forumURL, categoryURL
discussionsFunctions['forum'] = function(givenKey,forumURL,categoryURL,fetchPage)
{
    document.title = forumGroupName;
    var $topicListMainContainer = $('#topicListMainContainer');
    if($topicListMainContainer.length > 0 && $topicListMainContainer.is('[shouldReload="false"]'))
    {
        $topicListMainContainer.show().attr('shouldReload','true').siblings().remove();
        hideLoadingImage();
        if(isMac == "false")
        {
            setToHotkeys();
        }
    }
    else
    {
        var options = {};
        options.forumGroupId = forumGroupId;
        options.forumURL = forumURL;
        options.fetchPage = fetchPage;
        if(categoryURL)
        {
            options.categoryURL = categoryURL;
        }     
        doAjaxAction(
            '/getSingleForumTopics.do',
            options,            
            function (data)
            {
                hideLoadingImage();
                $('#mainContent').get(0).innerHTML = data;
                lightBox('#chartWidget');
                if(categoryURL)
                {
                    if(parseInt(fetchPage) > 1)
                    {
                        $.history.add(givenKey+'/'+forumURL+'/'+categoryURL+'/'+fetchPage);
                    }
                    else
                    {
                        $.history.add(givenKey+'/'+forumURL+'/'+categoryURL);
                    }
                }
                else
                {
                    if(parseInt(fetchPage) > 1)
                    {
                        $.history.add(givenKey+'/'+forumURL+'/'+fetchPage);
                    }
                    else
                    {   
                        $.history.add(givenKey+'/'+forumURL);
                    }
                }
                goToTop();
                bindTopicClicks($('#topicList'));
                bindTopicClicks($('#topicsList'));
                bindTopicListHeaderClicks($('#topicListHeader'));
                bindWidgetsContClick($('#topicListWidgetsCont'));
                var $topicListFilter = $('#forumComboCont');
                var forumId = $topicListFilter.attr('forumId');
                var categoryId = $topicListFilter.attr('categoryId');
                var hashPurpose = "NewTopic/"+forumId+"/"+categoryId;
                if($('#allForumWidget').length > 0)
                {
                   if($('#allForumWidget').find('li[purpose="forumList"]').length < 9)
                   {
                       $('#moreForumView').hide();
                   }
                }
                $('#NewTopicTab').attr('hashPurpose',hashPurpose);
                if(typeof WmsContacts != "undefined" && ch == true)
                {
                    var dataOb = WmsContacts.getZohoContacts();
                    setPresence(dataOb,"moderatorsChatList_"+forumId);
                    setPresenceInTopicList(dataOb);
                }
                if(isMac == "false")
                {
                    setToHotkeys();
                }
                return false;
            },
            function (errordata)
            {
                $('#mainContent').get(0).innerHTML = errordata.responseText;
                hideLoadingImage();
                
                
            }
        );
    } 
    
};
//to load new topic page
discussionsFunctions['newtopic'] = function(givenKey,forumId,categoryId)
{   
    if(typeof forumId == "undefined" && typeof categoryId == "undefined")
    {
        getWritePost("-1","-1",givenKey);
    }
    else
    {
        forumId = (typeof forumId == "undefined")?-1:forumId;
        categoryId = (typeof categoryId == "undefined")?-1:categoryId;       
        getWritePost(forumId,categoryId,givenKey);
    }
};
//to load new topic page
discussionsFunctions['search'] = function(givenKey,searchFor)
{   
    var options = {};
    options.forumGroupId = forumGroupId;
    if(!searchFor)
    {
        searchFor = $('#searchInputBox').val();
        searchFor =$.trim(searchFor);
    }
    if(searchFor == "")
    {
        showMessage(i18n['zohodiscussions.searchList.noSearchString'],'failure');
        hideLoadingImage();
        return;
    }
    options.searchFor = searchFor;
    var forumId = -1;
    options.forumId = forumId;
    options.normalSearchType = $('#searchSelectedImage').attr('purpose');
    $.history.add(givenKey+"/"+searchFor);
    if($('#currSearchSortBy').attr('currSortBy') == "date")
    {
        options.searchSortBy = "date"; //No I18N
    }
    doAjaxAction('/getSearchResult.do',options,function(data)//No internationalization
    {
        hideLoadingImage();
        var $data = $('<div></div>');
        $data.get(0).innerHTML = data;
        $('#mainContent').get(0).innerHTML = data;
        bindSearchContentClick($('#mainContent'));
        showAuthorPopout($data);
        $('#searchInputBox').val(searchFor);
    });
};
//to load single post
discussionsFunctions['topic'] = function(givenKey,forumTopicId,recentResponseId)
{   
    if(recentResponseId != undefined)
    {
        openSinglePost(forumTopicId,givenKey,recentResponseId);
    }
    else
    {
        openSinglePost(forumTopicId,givenKey);
    }
};

//to load tag related post
discussionsFunctions['tag'] = function(givenKey,tagName)
{
      $.history.add(givenKey+'/'+tagName);
      $this = $(this);
      var options = {};
      options.forumGroupId = forumGroupId;
      options.tagName = tagName;
      options.fetchPage = 1;
      doAjaxAction('/getTagRelatedPosts.do',options,function (data)//No internationalization
      {
            hideLoadingImage();
            $('#mainContent').get(0).innerHTML = data;
            goToTop();
            bindTopicClicks($('#topicList'));
            bindTopicClicks($('#topicsList'));
            bindTopicListHeaderClicks($('#topicListHeader'));
            bindWidgetsContClick($('#topicListWidgetsCont'));
            return false;
          },
          function(errordata)
          {
            hideLoadingImage();
            var responseData = (errordata.responseText);
            $('#mainContent').get(0).innerHTML = responseData;
      });
}
//to load all tags
discussionsFunctions['alltags']=function(allTags)
{
    $.history.add(allTags);
    $this = $(this);
    var options = {};
    options.forumGroupId =  forumGroupId;
    doAjaxAction('/showAllTags.do',options,function (data)//No internationalization
    {
          hideLoadingImage();
          $('#mainContent').get(0).innerHTML = data;
          bindTagsContClick($('#allTagsContainer'));
          bindWidgetsContClick($('#topicListWidgetsCont'));
          return false;
        },
        function(errordata)
        {
            hideLoadingImage();
            var responseData = (errordata.responseText);
            $('#mainContent').get(0).innerHTML = responseData;
   });
}
//to load myarea
discussionsFunctions['allforums'] = function(givenKey)
{
    var options = {};
    options.purpose = "AllForums"
    options.forumGroupId = forumGroupId;
    options[csrfParamName] = csrfToken;
    doAjaxAction('/AllForums.do',options,function(data)//No internationalization
    {
        hideLoadingImage();
        document.title = i18n['zohodiscussions.general.allForums'];//No internationalization
        $.history.add('AllForums');
        $('#mainContent').get(0).innerHTML = data;
        allForumsBindActions();
        return false;
        },
        function(errordata)
        {
            hideLoadingImage();
            var responseData = (errordata.responseText);
            $('#mainContent').get(0).innerHTML = responseData;
   });
}
function allForumsBindActions()
{
    lightBox('#chartWidget');
    bindAllForumsClick($('#allForums_MainContentCont'));
    bindWidgetsContClick($('#topicListWidgetsCont'));
    goToTop();

    var $listof_FC_Counts = $('#listof_FC_Counts');
    $('#countOfForum').html($listof_FC_Counts.attr('forumCount'));
    $('#countOfCategory').html($listof_FC_Counts.attr('categoryCount'));
    $('#countOfPosts').html($listof_FC_Counts.attr('postCount'));
    $('#countOfResponses').html($listof_FC_Counts.attr('responseCount'));
    if(typeof WmsContacts != "undefined" && ch == true)
    {
        var dataOb = WmsContacts.getZohoContacts();
        setPresenceInTopicList(dataOb);
    }
}
discussionsFunctions['settings'] = function(givenKey)
{
    var options = {};
    options.forumGroupId = forumGroupId;
    doAjaxAction(
        '/settings.do',
        options,
        function(data)
        {   
            hideLoadingImage();
            $('#mainContent').get(0).innerHTML = data;
            $.history.add('Settings');
            initSettingTabClick();
            return false;
        },
        function(errordate)
        {
            //alert(errordata.responseText);
        }
    );
}
//to load myarea
discussionsFunctions['myarea'] = function(givenKey,myAreaAction,subAction)
{  
    document.title = i18n['zohodiscussions.general.myarea'];//No I18N
    var $myAreaParentContainer = $('#myAreaParentContainer');
    if($myAreaParentContainer.length > 0 && $myAreaParentContainer.is('[shouldReload="false"]'))
    {
        $myAreaParentContainer.show().attr('shouldReload','true').siblings().remove();
        hideLoadingImage();
    }
    else
    {
        var options = {};
        options.forumGroupId = forumGroupId;
        options[csrfParamName] = csrfToken;
        if(!myAreaAction)
        {   
            myAreaAction = "dashboard";
        }
        if(myAreaAction != "dashboard" && myAreaAction != "myposts" && myAreaAction != "watchlist" && myAreaAction != "bookmark" && myAreaAction != "privatemsg" && myAreaAction != "preference")
        {
            hideLoadingImage();
            return;
        }
        options.myAreaAction = myAreaAction
        options.ch = ch;
        doAjaxAction('/getMyArea.do',options,function(data)//No internationalization
        {
            $('#authorPopout:visible').hide();
            hideLoadingImage();
            $('#mainContent').get(0).innerHTML = data;
            getMyAreaBindActions(myAreaAction,givenKey,'',subAction);
            return false;
            },
            function(errordata)
            {
                hideLoadingImage();
                var responseData = (errordata.responseText);
                $('#mainContent').get(0).innerHTML = responseData;
           }
        );
    }//else
};
discussionsFunctions['user'] = function(givenKey,authorName)
{
    getAuthorProfile(authorName);
};
//to load moderation panel
discussionsFunctions['moderation'] = function(givenKey)
{
    document.title = i18n['zohodiscussions.moderationAction.moderation'];//No I18N
    var options = {};
    options.forumGroupId = forumGroupId;
    if(portalPlanIndex > 4)
    {
        options.postFor = 'AllWaitingApproval';//No internationalization
    }
    else
    {
        options[csrfParamName] = csrfToken;
        options.postFor = 'AllReportedSpam';//No internationalization 
    }
    ModerationLoadingPage(options);
};
function ModerationLoadingPage(options)
{
    var toLoad = "";
    if(portalPlanIndex > 4)
    {
        toLoad = "/getModerationPanel.do"; //No internationalization
    }
    else
    {
        toLoad = "/getReportedSpam.do"; //No internationalization
    }
    doAjaxAction(toLoad,options,function(data)
    { 
        hideLoadingImage();
        $('#mainContent').get(0).innerHTML = data;
        $.history.add('Moderation');
        getModerationPanelBindAction();
        return false;
        },
        function(errordata)
        {
            hideLoadingImage();
            var responseData = (errordata.responseText);
            $('#mainContent').get(0).innerHTML = responseData;
   });
}
function getModerationPanelBindAction()
{
    goToTop();
    bindModerationTabClick();
    if(portalPlanIndex > 4)
    {
        bindModerationActionClick("AllAwaiting");
    }
    else
    {
     bindModerationActionClick("AllReportedSpam");//No internationalization
     var $moderationLeftCont = $('#moderationLeftCont li[purpose="ReportedSpam"]');
     $moderationLeftCont.removeClass("default").addClass("selected").siblings('li.selected').removeClass("selected").addClass("default");
    }
    ModerationAction($('#moderationRightCont'));
    initModerationPanel($('#moderationPanel'));
}
function getMyAreaBindActions(myAreaAction,givenKey,niceUrl,subAction)
{
    bindMyAreaClicks($('#myAreaContent'));
    $('#authorPopout_'+ZUID).hide();
    showAuthorPopout($('#myAreaInnerMainContent'));
    if(myAreaAction != "dashboard")
    {
        if(myAreaAction == "myposts")
        {
            myAreaAction = "myjournals"; //No I18N
        }
        if(subAction != undefined)
        {
            if(subAction != "topic" && subAction != "user" && subAction != "forum" && subAction != "subforum" && subAction != "following" && subAction != "follower")
            {
                subAction = "topic"; //No I18N
            }
        }
        if(niceUrl != "niceurl")
        {
            if($('#'+myAreaAction+'View').length > 0)
            {
                getMyAreaAction($('#'+myAreaAction+'View'),subAction);
            }
            else
            {
                getMyAreaAction($('#dashboardView'));
            }
        }
        else
        {
            var purpose = $('#'+myAreaAction+'View').attr('purpose');
            bindMyareaTabsActions(purpose,subAction);
        }
    }
    else
    {
        if(niceUrl != "niceurl")
        {
            $.history.add(givenKey+"/"+myAreaAction);
        }
        if(typeof WmsContacts != "undefined" && ch == true)
        {
            var dataOb = WmsContacts.getZohoContacts();
            setPresence(dataOb,"followingUserDetails"); //No I18N
            setPresence(dataOb,"followersUserDetails"); //No I18N
            setPresenceInMyArea(dataOb,"current_recentActivity_List"); //No I18N
        }

    }

}
function ModerationAction($context)
{
    $context.unbind('click',bindModerationAction).click(bindModerationAction);
    showAuthorPopout($context);
}

function getTopicsReport(forumId,categoryId,fetchPage,givenkey)
{
    document.title = forumGroupName;
    var options = {};
    options.forumGroupId = forumGroupId;
    options.forumId = forumId;
    options.categoryId = categoryId;
    options.fetchPage = fetchPage;
    doAjaxAction('/Reports.do',options,function(data) //No internationalization
    {
        hideLoadingImage();

        if(givenkey)
        {
            $.history.add(givenkey);
        }
        $("#mainContent").get(0).innerHTML = data;
        lightBox('#chartWidget');
        bindReportsClicks($('#reportsContent'));
        //$('#reportsContent').unbind('click', processReportClick).click(processReportClick);
    });
 }//get Topics Report

function getForumTopics(forumId,categoryId,fetchPage,givenkey,limit,style,ph,tps,widget,aj,stat,qstr,tgt)
{
    document.title = forumGroupName;
    var $topicListMainContainer = $('#topicListMainContainer');
    var options = {};
    options.forumGroupId = forumGroupId;
    options.forumId = forumId;
    options.categoryId = categoryId;
    options.fetchPage = fetchPage;
    options.givenkey = givenkey;
    if(givenkey == "tpw")
    {
    options.limit = limit;
    options.style = style;
    options.ph = ph;
    options.tps = tps;
    options.widget = widget;
    options.aj = aj;
    options.stat = stat;
    options.querystring = qstr;
    options.tgt = tgt;
    }
    if($topicListMainContainer.length > 0 && $topicListMainContainer.is('[shouldReload="false"]'))
    {
        $topicListMainContainer.show().attr('shouldReload','true').siblings().remove();
        hideLoadingImage();
        if(isMac == "false")
        {
            setToHotkeys();
        }
    }
    else
    {
        doAjaxAction('/getSingleForumTopics.do',options,function(data)//No internationalization
        {
            hideLoadingImage();
            if(givenkey)
            {
                if(parseInt(fetchPage) > 1)
                {
                    $.history.add(givenkey+"/"+fetchPage);
                }
                else
                {
                    $.history.add(givenkey);
                }
            }
            $('#mainContent').get(0).innerHTML = data;
            lightBox('#chartWidget');
            bindTopicClicks($('#topicList'));
            bindTopicClicks($('#topicsList'));
            bindTopicListHeaderClicks($('#topicListHeader'));
            bindWidgetsContClick($('#topicListWidgetsCont'));
            var hashPurpose = "NewTopic/"+forumId+"/"+categoryId;
            $('#NewTopicTab').attr('hashPurpose',hashPurpose);
            if($('#allForumWidget').length > 0)
            {
               if($('#allForumWidget').find('li[purpose="forumList"]').length < 9)
               {
                   $('#moreForumView').hide();
               }
            }
            if(typeof WmsContacts != "undefined" && ch == true)
            {
                var dataOb = WmsContacts.getZohoContacts();
                setPresenceInTopicList(dataOb);
            }
            if(isMac == "false")
            {
                setToHotkeys();
            }
            return false;
            },
            function(errordata)
            {
                hideLoadingImage();
                var responseData = (errordata.responseText);
                $('#mainContent').get(0).innerHTML = responseData;
       });
    }
}

function getWritePost(forumId,categoryId,givenKey,isNewWritePost)
{   
    var options = {};
    options.forumGroupId = forumGroupId;
    options.forumId = forumId;
    options.categoryId = categoryId;
    if(isTopicQuickView != "false")
    {
        showLoadingImage();
    }
    doAjaxAction('/writePost.do',options,function (data)//No internationalization
        {
            hideLoadingImage();
            document.title = i18n['zohodiscussions.writePost.documentTitle']+" - "+forumGroupName;
            $('#mainContent').get(0).innerHTML = data;
            if(isNewWritePost != "true")
            {
                $.history.add(givenKey);
            }    
            $('#tabListCont li.selected').removeClass('selected');
            goToTop();
            var $selectForumContainer = $('#SelectForum > option');
            if(($selectForumContainer.length) == 1)
            {
                $selectForumContainer.attr('selected',true);
            }
            var $selectCategoryContainer = $('#SelectCategory > option');
            if(($selectCategoryContainer.length) == 1)
            {
                $selectCategoryContainer.attr('selected',true);
            }
            initWritePost();
            givenKey = givenKey.toLowerCase();
            if(givenKey != "newtopic")
            {
                if(givenKey == "newproblem")
                {
                    givenKey = "error";
                }
                else if(givenKey =="newquestion")
                {
                    givenKey ="question";
                }
                else if(givenKey == "newidea")
                {
                    givenKey = "idea";
                }
                else if(givenKey == "newdiscussion")
                {
                    givenKey = "discuss"; //No I18N
                }
                var $this = $('#writepostTabsCont').find('li[topiciconclass="'+givenKey+'"]');
                selectTopicType($this);
            }
            hideLoadingImage();
            return false;
        },
        function(errordata)
        {
             hideLoadingImage();
             var responseData = (errordata.responseText);
             $('#mainContent').get(0).innerHTML = responseData;
        });

}

//method to set the given tab as selected
function selectTab(tabId)
{
    if(tabId == "user")
    {
        $('#newtopicTab').siblings('li.selected').removeClass('selected');
        return;
    }
    else if(tabId == "newtopic" || tabId =="search")
    {
        searchFor = $('#searchInputBox').val();
        searchFor =$.trim(searchFor);
        if(tabId =="search" && searchFor == "")
        {
            return;
        }
        $('#'+tabId+"Tab").siblings('li.selected').removeClass('selected');
        return;
    }
    else if(tabId == "forum" || tabId == "topic" || tabId == "chome")
    {
        tabId = "home"; //No I18N
    }
    $('#'+tabId+"Tab").addClass('selected').siblings('li.selected').removeClass('selected');
    
}//function initTabContainerClicks()

/*** TOPIC LIST HEADER CLICKS ***/
function bindTopicListHeaderClicks($context)
{
    $context.unbind('click', processTopicListHeaderClick).click(processTopicListHeaderClick);
}
/**** TOPIC LIST CLICKS ****/
function bindTopicClicks($context) /* context is mandatory */
{
    $context.unbind('click', processTopicListClick).click(processTopicListClick);
    var $content = $context.find("script").html();
    try
    {   
        eval($content);
    }
    catch(e)
    {}
}//function bindTopicClicks()

//method show the author popout 
function showAuthorPopout($context)
{
    $context.find('a[purpose="authorProfile"],img[purpose="authorProfile"]').hover(
    function()
    {
        var $this = $(this);
        var authorId = $this.attr('authorId');
        if(authorId == -1)
        {
            return;
        }
        var authorName = $this.attr('authorName');
        var forumId = $this.attr('forumId');
        var handleAuthPopout = setTimeout(function()
        {
        var currPos = $this.position();
        if(currPos.left > 800)
        {
            currPos.left = currPos.left - 300;
        }
        $authorPopup = $('#authorPopout_'+authorId);
        if($authorPopup.length > 0)
        {
            $authorPopup.css(currPos).show();
            authorPopupHover($authorPopup)
        }  
        else
        {
            $authorPopup = $('#authorPopoutTemplate').clone();
            $authorPopup.attr('popoutPurpose','authorDetailsPopout');
            $authorPopup.attr('id','authorPopout_'+authorId);
            var options = {};
            options.forumGroupId = forumGroupId;
            options.authorId = authorId;
            options.forumId = forumId;
            options.ch = ch;
            doAjaxAction('/getAuthorPopup.do',options,function (data)//No internationalization
            {
                $thisAuthPopup = $("<div>"+data+"</div>");
                authorPopUpAction($thisAuthPopup,authorId,authorName,$authorPopup);
               
            });
            $authorPopup.css(currPos).show();
            $authorPopup.appendTo('body');  //No internationalization
            authorPopupHover($authorPopup)
        }
    },700);
        $this.data('destroyHandleAuthPopout', handleAuthPopout);
    },
    function()
    {
        var $this = $(this);
        var authorId = $this.attr('authorId');
        var handleAuthPopout = $this.data('destroyHandleAuthPopout');
        if(handleAuthPopout){clearTimeout(handleAuthPopout);}
        var $authCont = $('#authorPopout_'+authorId);
        $authCont.attr('hideAuhPopout','true');
        setTimeout(function()
        {
            var hideAuthPopout = $authCont.attr('hideAuhPopout');
            if(hideAuthPopout == "true")
            {
                $authCont.hide();
            }
        },500);
    }
  ); 
}//function showAuthorPopout($context)

function mouseOutAuthor($target)
{
    var $this = $target;
    var authorId = $this.attr('authorId');
    var handleAuthPopout = $this.data('destroyHandleAuthPopout');//No internationalization
    if(handleAuthPopout){clearTimeout(handleAuthPopout);}
    var $authCont = $('#authorPopout_'+authorId);
    $authCont.attr('hideAuhPopout','true');
    setTimeout(function()
    {
        var hideAuthPopout = $authCont.attr('hideAuhPopout');
        if(hideAuthPopout == "true")
        {
            $authCont.hide();
        }
    },500);
}


/** SEARCH CONTENT CLICK **/

function mouseOverAuthor($target)
{
    var $this = $target;
    var $authorPopup;
    var authorId = $this.attr('authorId');
    if(authorId == -1)
    {
        return;
    }
    var authorName = $this.attr('authorName');
    var forumId = $this.parents('div[parentCont="actualParent"]').attr('forumId');
    if(typeof forumId == "undefined")
    {
        forumId = $this.attr('forumId');
    }
    var handleAuthPopout = setTimeout(function()
    {
        var currPos = $this.position();
        $authorPopup = $('#authorPopout_'+authorId);
        if($authorPopup.length > 0)
        {
            $authorPopup.css(currPos).show();
            authorPopupHover($authorPopup);
        }  
        else
        {
            $authorPopup = $('#authorPopoutTemplate').clone();
            $authorPopup.attr('popoutPurpose','authorDetailsPopout');
            $authorPopup.attr('id','authorPopout_'+authorId);
            var options = {};
            options.forumGroupId = forumGroupId;
            options.authorId = authorId;
            options.forumId = forumId;
            options.ch = ch;
            doAjaxAction('/getAuthorPopup.do',options,function (data)//No internationalization
            {
                $thisAuthPopup = $("<div>"+data+"</div>");
                authorPopUpAction($thisAuthPopup,authorId,authorName,$authorPopup);
               
            });
            $authorPopup.css(currPos).show();
            $authorPopup.appendTo('body');  //No internationalization
            authorPopupHover($authorPopup)
        }
    },700);
    $this.data('destroyHandleAuthPopout', handleAuthPopout);//No internationalization
}
function authorPopUpAction($thisAuthPopup,authorId,authorName,$authorPopup)
{
    $thisAuthPopup.find('li[purpose="watchUser"]').click(function()
    {
        $thisWatchCont = $(this);
        var watchOptions = {};
        watchOptions.forumGroupId = forumGroupId;
        watchOptions.itemId = authorId;
        watchOptions.itemType = 3;
        watchOptions[csrfParamName] = csrfToken;
        var watchAction = $thisWatchCont.attr('watchAction');
        var watchActionURL = (watchAction == "watch")?'/watchUser.do':'/unwatchUser.do';
        doAjaxAction(watchActionURL,watchOptions,function(data)
        {
            if(data == "SUCCESS")
            {
                $thisWatchCont.attr('watchAction',(watchAction == "watch")?'unwatch':'watch');
                var displayText = ((watchAction == "watch")?i18n['zohodiscussions.general.Unwatch']:i18n['zohodiscussions.general.watch'])+" "+authorName;
                $thisWatchCont.find('a[purpose="watchuserNameCont"]').html(displayText);
                if(watchAction == "watch")
                {
                    showTipper(i18n['zohodiscussions.generalmessage.userAddedToWatchlist'],'success');
                }
                else
                {
                    showTipper(i18n['zohodiscussions.generalmessage.userRemovedFromWatchlist']);
                }
            }
        }); 
    });
    $thisAuthPopup.find('li[purpose="authorProfile"]').click(function()
    {
        if(authorName == ZU_Name)
        {   
          processHash('MyArea');
        }
        else
        {   
          processHash('User/'+authorName);
        } 
    });
    $authorPopup.html('').append($thisAuthPopup);
    if(typeof WmsContacts != "undefined" && ch == true)
    {
        var authStatus = WmsContacts.status(authorId);
        if(authStatus === false)
        {
                authStatus = 9;
        }
        manageUserChatStatus("authorPopup_"+authorName,authStatus,authorName);
    }
}
function authorPopupHover($authorPopup)
{
    $authorPopup.hover
    (
        function()
        {
            $authorPopup.attr('hideAuhPopout','false');
            var handle = $authorPopup.data('destroyHandle');//No internationalization
            if(handle){clearTimeout(handle);}
        },
        function ()
        {
            var handle = setTimeout(function()
            {
                $authorPopup.hide();
                $authorPopup.unbind('mouseenter').unbind('mouseleave');
            }, 700);
            $authorPopup.data('destroyHandle', handle);//No internationalization
        }
    );
}
function displaySearchOption()
{
    var $listOfSearchOptions = $('#listOfSearchOptions');
    $listOfSearchOptions.show();
    $listOfSearchOptions.find('li').unbind('click').click(function()
    {
        var $this = $(this);
        var $currselectImg = $this.find('div');
        var selectImg = $currselectImg.attr('class');
        var currpurpose = $currselectImg.attr('purpose');
        if(!$currselectImg.is('.imgAdvanceSearch'))
        {
            $('#searchSelectedImage').attr('class',selectImg).attr('purpose',currpurpose);
        }
        else
        {
            if($('#advanceSearchContainerForm').is(':visible'))
            {
                $('#listOfSearchOptions').hide();
                return;
            }
            
            if($('#searchMainContainer').is(':visible'))
            {
                $('#normalSearchInSearchList').hide();
                $('#advanceSearchContainerForm').show();
                $('#advanceSearchInpurBox').focus();
                return;
            }
            showLoadingImage();
            var options ={};
            options.forumGroupId = forumGroupId;
            doAjaxAction('/AdvanceSearchContainer.do',options,function (data)//No internationalization
            {
                hideLoadingImage();
                var $firstMainContainer = $('#mainContent > div:first');
                var $data = $('<div></div>');
                $data.get(0).innerHTML = data;
                $data.insertBefore($firstMainContainer);
                $data.find('#advanceSearchContainerForm').show();
                $data.find('#advanceSearchInpurBox').focus();
                if($('#normalSearchInSearchList').is(':visible'))
                {
                    $('#normalSearchContainer').hide();
                }
                bindSearchContentClick($data);
            },
            function(errordata)
            {
                hideLoadingImage();
                var responseData = (errordata.responseText);
                $('#mainContent').get(0).innerHTML = responseData;
            });
        }
        $listOfSearchOptions.hide();
    });
    var $searchOptionParent = $listOfSearchOptions.parent('div.searchOpList');
    $searchOptionParent.hover
    (
        function()
        {
           var handle = $searchOptionParent.data('destroyHandle');
           if(handle){clearTimeout(handle);}
        },
        function ()
        {
            var handle = setTimeout(function()
            {
                $listOfSearchOptions.hide();
                $searchOptionParent.unbind('mouseenter').unbind('mouseleave');
            }, 500);
            $searchOptionParent.data('destroyHandle', handle);
        }
    );
}//function displaySearchOption()
function bindSearchContentClick($context)
{
    $context.unbind('click', processSearchContClick).click(processSearchContClick);
    $('#SearchforumCategoryVice').change(function()
    {
        searchForumCatSelect($(this));
    });
}

function searchForumCatSelect($target)
{
        var forumId = $target.val();
        var categoriesForForum = $('#searchCategoryList').val().split('$$');
        $.each(categoriesForForum, function(index, item)
        {
            if(item.indexOf(forumId+':') > -1)
            {   
                $('#SearchCategoryVice').html('<option selected value="-1">' + i18n['zohodiscussions.searchList.all'] + '</option>'+item.split(':')[1]).show();
                $('#SelectCategory option:first').attr('selected','true');
                return false;
            }//if(item.indexOf(forumId+':') > -1)
            else
            {
               if(forumId == -1)
               {
                   $('#SearchCategoryVice').html('<option selected value="-1">' + i18n['zohodiscussions.searchList.all'] + '</option>').show();//No I18N
               }
               else
               {
                   $('#SearchCategoryVice').html('<option selected value="-1">Uncategorised</option>').show();
               }    
            }
        });
        $('#SearchCategoryVice option:first').attr('selected','true');  
}
/*** WIDGETS CONTAINR CLICK ***/
function bindWidgetsContClick($context)
{   
    $context.unbind('click', processWidgetsContClick).click(processWidgetsContClick);
    showAuthorPopout($context);
}
function bindAllForumsClick($context)
{
    $context.unbind('click', processAllForumsClick).click(processAllForumsClick);
    showAuthorPopout($context);
}
function processTopicListHeaderClick(event)
{ 
    var $target = $(event.target);
    var $targetParent = $target.parent();
    if($target.is('#forumsFilter li,#categoriesFilter li,#currentCategoryContext,#currentForumContext'))
    {
        //this is forum filter
        hashPurpose = $target.attr('hashPurpose');
        processHash(hashPurpose);
        return false;
    }//if($target.is('#forumsFilter li'))
    else if($target.is('div[purpose="linkForDropDown"]'))
    {
        var $switchPortalLink = $target;
        var portalsDropDownLocation = $switchPortalLink.attr('dropDownContLocation');
        var $parentCont = $($switchPortalLink.attr('parentCont'));
        if($parentCont.is('.newCombo'))
        {
            $parentCont.addClass('newComboSelected').removeClass('newCombo');
        }
        else
        {
            $parentCont.addClass('newCombo').removeClass('newComboSelected');
        }
        var $portalsDropDown = $('#'+portalsDropDownLocation);
        $portalsDropDown.toggle();
    }
    if($target.is('#topicListFilter li[purpose="filterLink"]'))
    {
        //this is topic filter
        var topicFilter = $target.attr('topicFilter');
        $topicFilterParent = $('#topicListFilter');
        var forumURL = $topicFilterParent.attr('forumURL');
        var categoryURL = $topicFilterParent.attr('subForumURL');
        var postSinceLastVisitTime = $topicFilterParent.attr('postSinceLastVisitTime');
        var labelStatus = "";
        //getMoreTopics(forumId,categoryId,fetchPage,topicFilter,postSinceLastVisitTime);
        if($topicFilterParent.attr('isTypeURL') == "yes")
        {
            getMoreTopics(forumURL,categoryURL,fetchPage,topicFilter,'',labelStatus);
            $('#currentFilterContext').html($target.text());
        }
        else
        {
            manageFilterHash(forumURL,categoryURL,topicFilter,labelStatus);
        }
        return false;
    }//
    if($target.is('#showAllTags') && $target.attr('isNiceURL') != "Yes")
    {
       processHash("AllTags");
    }
    if($target.is('#innerTabFilter span') && $targetParent.attr('purpose')=="filterTab")
    {
        manageFilterTabList($target);

    }
    if($target.is('#innerTabFilter div[purpose="filterTabCombo"]'))
    {
        manageFilterMenuList($target.attr('filterParent'));

    }
    var $dropDownConts = $('#forumsListOptions,#categoriesListOptions,#typeFilterOptions');
    $dropDownConts.hover
    (
        function()
        {
           var handle = $dropDownConts.data('destroyHandle');
           if(handle){clearTimeout(handle);}
        },
        function ()
        {
            var handle = setTimeout(function()
            {
                $dropDownConts.parent('.newComboSelected').addClass('newCombo').removeClass('newComboSelected');
                $dropDownConts.hide();
            }, 500);
            $dropDownConts.data('destroyHandle', handle);
        }
    );
}//function processTopicListHeaderClick(event)

function manageFilterTabList($target)
{
    var $innerTabFilter = $('#innerTabFilter');
    $innerTabFilter.find('li.selectedTab').removeClass('selectedTab');
    $target.parents('li').addClass('selectedTab');
    var forumURL= $innerTabFilter.attr('forumURL');
    var categoryURL = $innerTabFilter.attr('subForumURL');
    var fetchPage = 1;
    var topicFilter = $target.attr('filterBy');
    var labelStatus = '';
    var topicFilterType = $innerTabFilter.attr('topicFilterType');
    var postsincelastvisit = $innerTabFilter.attr('postSinceLastVisitTime');
    if(topicFilterType != 'All')
    {
        labelStatus = $target.attr('filterLabelId');
        if(labelStatus)
        {
            labelStatus = topicFilter;
            topicFilter = topicFilterType;
        }
    }
    if($innerTabFilter.attr('isTypeURL') == "yes")
    {
        getMoreTopics(forumURL,categoryURL,fetchPage,topicFilter,postsincelastvisit,labelStatus);
    }
    else
    {
        manageFilterHash(forumURL,categoryURL,topicFilter,labelStatus);
    }
}//function manageFilterTabList()
function manageFilterHash(forumURL,categoryURL,topicFilter,labelStatus)
{
    if(forumURL == "" && categoryURL == "")
    {
        if(labelStatus)
        {
            processHash("filter/"+topicFilter+"/"+labelStatus+"/1"); //No I18N
        }
        else
        {
            processHash("filter/"+topicFilter+"/1"); //No I18N
        }
    }
    else if(categoryURL == "")
    {
        if(labelStatus)
        {
            processHash("forum/"+forumURL+"/filter/"+topicFilter+"/"+labelStatus+"/1"); //No I18N
        }
        else
        {
            processHash("forum/"+forumURL+"/filter/"+topicFilter+"/1"); //No I18N
        }
    }
    else
    {
        if(labelStatus)
        {
            processHash("forum/"+forumURL+"/"+categoryURL+"/filter/"+topicFilter+"/"+labelStatus); //No I18N
        }
        else
        {
            processHash("forum/"+forumURL+"/"+categoryURL+"/filter/"+topicFilter); //No I18N
        }
    }
}
function manageFilterMenuList(context)
{
    var $this = $('#'+context);
    if($('#innerTabFilter div.forumOptions').is(':visible'))
    {
        $(this).hide();
    }
    $this.removeClass('newCombo').addClass('newComboSelected');
    $this.hover
    (
        function()
        {
            var handle = $this.data('destroyHandle');
            if(handle){clearTimeout(handle);}
        },
        function ()
        {
            var handle = setTimeout(function()
            {
                $this.removeClass('newComboSelected').addClass('newCombo');
            }, 500);
            $this.data('destroyHandle', handle);
        }
    );
    
    $this.find('li[purpose="filterTabMenu"]').unbind('click').click(function() //No I18N
    {
        var $this = $(this);
        var $innerTabFilter = $('#innerTabFilter');
        var forumURL= $innerTabFilter.attr('forumURL');
        var categoryURL = $innerTabFilter.attr('subForumURL');
        var labelStatus = $this.attr('labelName');
        var topicFilter = $this.parent().attr('filterType');
        var fetchPage = 1;
        $innerTabFilter.find('li.selectedTab').removeClass('selectedTab');
        $('#'+topicFilter+'FilterMenuList').addClass('selectedTab');
        var filterBy = $this.attr('filterBy');
        var labelName = '';
        if(filterBy)
        {
            topicFilter = filterBy;
        }
        if($innerTabFilter.attr('isTypeURL') == "yes")
        {
            getMoreTopics(forumURL,categoryURL,fetchPage,topicFilter,'',labelStatus);
        }
        else
        {
            manageFilterHash(forumURL,categoryURL,topicFilter,labelStatus);
        }
        //getMoreTopics(forumURL,categoryURL,fetchPage,topicFilter,'',labelStatus);
    });
}//function manageFilterMenuList()

//this is used for click event while listing tags
function bindTagsContClick ($tagContext) 
{
    $tagContext.find('li[purpose ="getTagPosts"]').click(function()
    {
        $this = $(this);
        var hashPurpose = $this.attr('hashPurpose');
        processHash(hashPurpose);
    });
}
function processTopicListClick(event)
{
    var $target = $(event.target);
    var $targetParent = $target.parent();
    var $topicUtilContainer = $('#paginationContainer');
    var $location = "topicList"; //No I18N
    var forumTopicId = $target.parents('div[parentCont="actualParent"]').attr('forumTopicId');
    if($target.is('div.quickViewBtn') || $target.is('a[purpose="postTitleQuickView"]'))
    {
        forumTopicId = forumTopicId || $targetParent.parents('div[parentCont="actualParent"]').attr('forumTopicId');
        //to expand the response in topic list view
        handleTopicClick(event,forumTopicId,$location);     
    }
    else if($target.is('a[purpose="postTitle"]') || $target.is('div[purpose="postTitle"]'))
    {   
        //to open a single post in full thread view
        showLoadingImage();
        if(isTopicQuickView == "false")
        {
            //do nothing
        }
        else
        {
            var recentResponseId = $target.parents('div[parentCont="actualParent"]').attr('recentResponseId');
            var isResponse = $target.attr("isResponse");
            if(recentResponseId != undefined && isResponse=="true")
            {
                processHash('Topic/'+forumTopicId+'/'+recentResponseId);
            }
            else
            {   
                processHash('Topic/'+forumTopicId);
            }
            return false;
        }
        
    }
    else if($targetParent.is('li[purpose="moreAction"]'))
    {
        manageMoreAction($targetParent);
    }
    else if($target.is('a[purpose="moreAction"]'))
    {
        var parentLi = $target.parents('li');
        manageMoreAction(parentLi);
    }
     else if($target.is('a[purpose="linkedTopicTitle"]'))
    {   
        //to open a single post in full thread view
        showLoadingImage();
        if(isTopicQuickView == "false")
        {
            //do nothing
        }
        else
        {
            var linkToTopicId = $target.attr('linkToTopicId');
            processHash('Topic/'+linkToTopicId);
            return false;
        }
    }
    else if($target.is('li[linkPurpose="replyToTopic"]') || $targetParent.is('li[linkPurpose="replyToTopic"]'))
    {
        forumTopicId = forumTopicId || $targetParent.parents('div[parentCont="actualParent"]').attr('forumTopicId');
        //check whether a editor was already opened // if so set the focus to that location
        if($topicUtilContainer.data('inEditMode') == true)
        {
            showMessage(i18n['zohodiscussions.singlepost.alertmessageforediting'],'info');
            var openedEditorLcation = $topicUtilContainer.data('editorContLocation');
            var openedEditorTopicLocation = $topicUtilContainer.data('eachTopicContainerId');
            var openForumTopic = $topicUtilContainer.data('forumTopicId');
            if(openForumTopic != forumTopicId)
            {
                //to expand the response in topic list view
                handleTopicClick(event,openForumTopic,"editTopicList");  
            }
            setFocusToContainer($(openedEditorLcation));
            return false;
        }
        $('#eachTopicReplyCont_'+forumTopicId).show();
        openEditor($('#eachTopicReply_'+forumTopicId),"responseContent","postContentTA","replyToTopic_"+forumTopicId,"Write","paginationContainer");
        setFocusToContainer($('#eachTopicReplyCont_'+forumTopicId));
        $topicUtilContainer.data('inEditMode',true);
        $topicUtilContainer.data('editorContLocation',"#eachTopicReplyCont_"+forumTopicId);
        $topicUtilContainer.data('eachTopicContainerId','#eachTopic_'+forumTopicId);
        $topicUtilContainer.data('forumTopicId',forumTopicId);    
        return false;
    }
    else if(($target.is('#olderPostsLink') || $target.is('#newerPostsLink'))&& $target.is('.navBtnEnabled'))
    {
        var forumURL =  $target.attr('forumURL');
        var categoryURL = $target.attr('categoryURL');
        var fetchPage = $target.attr('fetchPage');
        var topicFilter = $target.attr('topicFilter');
        var getPostFor = $target.attr('getPostFor');
        var topicStatus = $target.attr('topicStatus');
        var postSinceLastVisitTime = $target.attr('postSinceLastVisitTime');
        if(typeof getPostFor == "undefined")
        {
            getMoreTopics(forumURL,categoryURL,fetchPage,topicFilter,postSinceLastVisitTime,topicStatus,"true");
        }
        else
        {
            var tagName = $target.attr('tag_Name');
            getMoreTagRelatedPost(fetchPage,tagName,getPostFor)     
        }
    }
    else if($target.is('a[purpose="forumPostsFilter"]'))
    {
        hashPurpose = $target.attr('hashPurpose');
        processHash(hashPurpose);
        return false;
    }
    else if(($target.is('a[purpose="authorProfile"]')) || $target.is('img[purpose="authorProfile"]'))
    {
        var authorName = $target.attr('authorName');
        if(authorName == ZU_Name)
        {
            processHash('MyArea');
        }
        else
        {
            processHash('User/'+authorName);
        }
        return;
    }
    else if($target.is('div.imgSmallWatchSel') || $target.is('div.imgSmallWatch'))
    {
       watchThisItem($target,"singleTopicWatch",event);
       return; 
    }
    else if(($target.is('li.imgNavPrevious') || $target.is('li.imgNavNext'))&& !$targetParent.is('.navLoading'))
    {   
        checkPrevNextResponse($target);
        return;
    }
    else if(($target.is('li.imgNavStart') || $target.is('li.imgNavEnd')) && !$targetParent.is('.navLoading'))
    {   
        firstOrLastResponse($target);
        return;
    }
    if($targetParent.is('li[purpose="watchAction"]'))
    {
        watchThisItem($targetParent,$location,event);
        return;
    }
    else if($targetParent.is('li[purpose="emailThisTopic"]'))
    {
        openEmailTopicDialog($targetParent);
        var parentLi = $targetParent.parents('li[purpose="moreAction"]');
        manageMoreAction(parentLi);
        return;
    }
    else if($targetParent.is('li[purpose="moderateThisTopic"]'))
    {   
        moderateAction($targetParent,$location,event);
        return; 
    }
    else if($targetParent.is('li[actionPurpose="reportSpam"],span[actionPurpose="reportSpam"]'))
    {   
        singlePostSpamAction($targetParent,$location);
        return;
    }
    else if($targetParent.is('div[actionPurpose="reportInappropriate"]') || $targetParent.is('li[actionPurpose="reportInappropriate"]') || $targetParent.is('span[actionPurpose="reportInappropriate"]'))
    {
        singlePostSpamAction($targetParent,$location);
        return;
    }
    else if($target.is('span[purpose="inappropriateReason"]'))
    {
        getReasonForInapppropriate($target);
    }
    else if($targetParent.is('li[actionPurpose="delete"]'))
    {
        singlePostDeleteAction($targetParent,$location);
        return;
    }
    else if($targetParent.is('#removeTopicLink') || $targetParent.is('li[purpose="removeTopicLink"]'))
    {
      deletelinkedTopic($targetParent);  
    }   
    else if($targetParent.is('li[actionPurpose="edit"]'))
    {
      var thisResponseId = $targetParent.attr('responseId');
      var editingForumTopic = $targetParent.parents('div[parentCont="actualParent"]').attr('forumTopicId');
      var editResponseLocation = "#eachTopic_"+editingForumTopic;
      if($topicUtilContainer.data('inEditMode'))
      {
          showMessage(i18n['zohodiscussions.singlepost.alertmessageforediting'],'info');
          openedEditorLcation = $topicUtilContainer.data('editorContLocation');
          var openForumTopic = $topicUtilContainer.data('forumTopicId');
          if(editingForumTopic!=openForumTopic)
          {
            //to expand the response in topic list view
            handleTopicClick(event,openForumTopic,$location);   
          }
          setFocusToContainer($(openedEditorLcation));
          return false;
      }
      openEditor($('#recentResponseContent_'+thisResponseId),"responseContent","postContentTA",('editPostContent_'+thisResponseId),"Edit",('eachTopic_'+thisResponseId));
      setFocusToContainer($(editResponseLocation));
      $topicUtilContainer.data('inEditMode',true);
      $topicUtilContainer.data('editorContLocation',editResponseLocation);
      $topicUtilContainer.data('forumTopicId',editingForumTopic);
      $('#postTextContent_'+thisResponseId).find('ul.singlePostActions').hide();
      $('#linkedTopic_'+thisResponseId).hide();
      $('#singlePostActions_'+thisResponseId).hide();
      $('#recent_ResPonse_'+thisResponseId).find('div.navigationCont').hide();
      $('#previewResponse').attr('location','topicListEditResponse');
      $('#previewResponse').attr('responseId',thisResponseId);
      $('#previewResponse').attr('forumTopicId',editingForumTopic);      
      return false;  
    }
    else if($targetParent.is('li[deletepurpose="deleteAttachment"]'))
    {
        deletePublishedAttachment($targetParent,event);
        return;
    }
    else if($targetParent.is('li[votePurpose]'))
    {
        var $this = $targetParent;
        var thisResponseId = $this.attr('responseId');
        forumTopicId = $this.parents('div[parentCont="actualParent"]').attr('forumTopicId');
        var purpose = $this.attr('votePurpose');
        var voteAction = (purpose == "removeVote")?"/removeResponseVote.do":"/voteResponse.do";
        showSmallLoadingImage(event);
        var options = {};
        options.forumGroupId = forumGroupId;
        options.responseId = thisResponseId;
        options.forumTopicId = forumTopicId;
        options[csrfParamName] = csrfToken;
        doAjaxAction(voteAction,options,function (data)
        {
            if(data == "SUCCESS")
            {
                refreshResponseVoteContainer(thisResponseId);
            }
            else
            {
                hideLoadingImage();
            }
        });
    }
    else if($targetParent.is('li[bestResponse]'))
    {
        var $this = $targetParent;
        var thisResponseId = $this.attr('responseId');
        var forumTopicId = $this.parents('div[parentCont="actualParent"]').attr('forumTopicId');

        var topicAuthorId = $this.attr('topicAuthorId');
        var bestResponseAction = $this.attr('bestResponse');
        var options = {};
        options.forumGroupId = forumGroupId;
        if(bestResponseAction == "choose")
        {
            options.responseId = thisResponseId;
        }
        options.forumTopicId = forumTopicId;
        if(topicAuthorId == ZUID)
        {
            options.topicowner = "true";
        }
        options[csrfParamName] = csrfToken;
        var bestResponseURL = (bestResponseAction == "choose")?'/bestResponse.do':'/removeBestResponse.do';
        showSmallLoadingImage(event);
        doAjaxAction(bestResponseURL,options,function (data)
        {
            if(data == "SUCCESS")
            {
                var bestResponseMsg = (bestResponseAction == "choose")?i18n['zohodiscussions.singlepost.bestResponseSuccessMsg']:i18n['zohodiscussions.singlePost.removeBestResponseMsg'];
                var msgStyle = (bestResponseAction == "choose")?'success':'info';
                showTipper(bestResponseMsg,msgStyle);
                refreshSingleTopic(forumTopicId);
            }
            else
            {
                hideLoadingImage();
                showMessage(i18n['zohodiscussions.generalmessage.noPermission']);
            }
        });
    }
    else if($targetParent.is('div[voteTopic]'))
    {
        var $this = $targetParent;
        var responseId = $this.attr('firstResponseId');
        var forumTopicId = $this.parents('div[parentCont="actualParent"]').attr('forumTopicId');
        showSmallLoadingImage(event);
        var voteActionoptions = {};
        voteActionoptions.forumGroupId = forumGroupId;
        voteActionoptions.responseId = responseId;
        voteActionoptions.forumTopicId = forumTopicId;
        voteActionoptions[csrfParamName] = csrfToken;
        doAjaxAction('/voteTopic.do',voteActionoptions,function (data)//No internationalization
        {
            if(data == "SUCCESS")
            {
                refreshResponseVoteContainer(responseId);
            }
            else
            {
                hideLoadingImage();
            }
        });
    }
}//function processTopicListClick(event)

function manageMoreAction($target)
{
    if($target.is('.newComboSelectedNm'))
    {   
        $target.removeClass('newComboSelectedNm').addClass('newCombo');
        $target.find('div.forumOptins').hide();
        return;
    }
    $target.removeClass('newCombo').addClass('newComboSelectedNm');
    var $moreOptions = $target.find('div.forumOptins');
    $moreOptions.show();

    $target.hover
    (
        function()
        {
            $target.attr('hideAuhPopout','false');
            var handle = $target.data('destroyHandle');
            if(handle){clearTimeout(handle);}
        },
        function ()
        {
            var handle = setTimeout(function()
            {
                $target.removeClass('newComboSelectedNm').addClass('newCombo');
                $moreOptions.hide();
                $target.unbind('mouseenter').unbind('mouseleave');
            }, 500);
            $target.data('destroyHandle', handle);
        }
    );

}//function manageMoreAction(parentLi)
function refreshResponseVoteContainer(responseId)
{

    var options = {};
    options.forumGroupId = forumGroupId;
    options.responseId = responseId;
    doAjaxAction('/refreshSingleResponse.do',options,function (data)//No internationalization
    {
        var $voteCont = $(data).find('div[contPurpose="voteContainer"]');
        $('#postTextContent_'+responseId+' div[contPurpose="voteContainer"]').html($voteCont.html());
        hideLoadingImage();
    });
}
function backtoEditor()
{
  $('#addForumPostForm').show();
  $('#writeNewTopic').show();
  $('#publishPreviewedTopic').hide();
  $('#backToEditor').hide(); 
  $('#preview_Posts').hide();
  $('#writePostButtons').show();
  $('#forumTagsPreview').html(' ');
  //$.history.add("NewTopic/Editor");
}
function publishPreviewedTopic()
{
  $('#publishTopic').trigger('click');
}
function writePostPreview(userName,location,flag,isDraft)
{ 
    var topicTitle = $('#topicTitle').val();
    var finalTopicTitle = topicTitle.replace(/^<+|<+$/g,'&lt;').replace(/<+/g,'&lt;').replace(/^>+|>+$/g,'&gt;').replace(/>+/g,'&gt;');

    finalTopicTitle = finalTopicTitle.replace(/^\s+|\s+$/g,'').replace(/\s+/g,' ');
    if (finalTopicTitle == '' )
    {
        hideLoadingImage();
        setFocusToContainer(($('#topicTitle')).focus());
        enablePostButtons();
        showMessage(i18n['zohodiscussions.writePost.TopicTitleCannotbeEmptymessage'],'failure');
        return;
    }
    if(finalTopicTitle.length > 200)
    {
        hideLoadingImage();
        showMessage(i18n['zohodiscussions.writePost.TopicTitleLengthMsg'],'failure');
        enablePostButtons();
        return;
    }
    var contentToPost = $('#postContentTA').data('editor').val();
    contentToPost = contentToPost.replace(/^\s+/g, '').replace(/\s+$/g, ''); //replace(/<[^>]*>/ig, '')

    var $tempCont = $('<div></div>').html(contentToPost);
    contentToPost = $tempCont.text();
    if (contentToPost == '' )
    {
        hideLoadingImage();
        showMessage(i18n['zohodiscussions.writePost.noContentInPost'],'failure');
        enablePostButtons();
        return;
    }

    var selectedForumOption = $('#SelectForum').val();
    if(selectedForumOption == null)
    {
       hideLoadingImage();
       $('#selectForumMessage').show();
       setFocusToContainer($('#SelectForum'));
       enablePostButtons();
       showMessage(i18n['zohodiscussions.writePost.selectAnyForum'],'failure');
       return;
    }
    else
    {
      $('#selectForumMessage').hide();
    }
    var writepostTags = $('#forumTags').val();
    if(writepostTags != "")
    {
      writepostTags = writepostTags.replace(/^\s+|\s+$/g,' ').replace(/\s+/g,' ');
      if(writepostTags.match(/[a-zA-Z0-9, ]+$/) == null)
      {
         hideLoadingImage();
         showMessage(i18n['zohodiscussions.singlepost.specialCharacterNotAllowedMsg'],'failure');
         enablePostButtons();
         return;  
      }
    }
    /*
    var topicPreviewFlag = $('#previewTopic').attr('topicPreviewFlag');
    if(topicPreviewFlag == "true" && flag == "true")
    {
      $.history.add('NewTopic/Editor');
      $.history.add('NewTopic/'+location);
      $('#previewTopic').attr('topicPreviewFlag','false');
    }
    */
    
    if(isDraft)
    {
        $('#previewAttachment >li').html('');
        var attachmentDetails = $('#attachmentsListCont').find('div[attachmentDetails]');
        var attachmentContLength = $('#attachmentsListCont').find('div[attachmentDetails]').length;
        if(attachmentContLength > 0)
        {
            var $appendingAttachmentCont = $('#previewAttachment'); //$editorLocation.find('div[purpose ="attachmentListContForPreview"] > ul');
            attachmentListPreview($appendingAttachmentCont,attachmentDetails);
            $('#AttachmentPreviewCont').show();
        }
        else
        {
             $('#AttachmentPreviewCont').hide();
        }
        
    }
  
    $('#addForumPostForm').hide();
    $('#writeNewTopic').hide();
    $('#publishPreviewedTopic').show();
    $('#backToEditor').show();
    
    //this function will sync the preview contents with the editor and fields - so that live preview can be given
    var $previewSection = $('#preview_Posts').show();
    $('#writePostButtons').hide();
    var topicClass = $('#TopicContentHolder').attr('class');
    var topicTypeClass = $('#topicTypePreview').attr('class');
    var topicType = topicTypeClass.split(" ");
    $('#topicTypePreview').removeClass(topicType[1]).addClass(topicClass);
    
    if($previewSection.is(':visible'))
    {
        $('#preview_postHeader').find('a[purpose="authorProfile"]').html(userName);
        //process only if the preview section is visible.
        $('#previewDocumentTitle').html(finalTopicTitle);
        //get forumName
        $('#preview_postHeader').find('a[purpose="forum_Topic"]').html($('#SelectForum option:selected').text());
        var categoryCont = $('#SelectCategory option:selected').text();
        if(categoryCont != "Uncategorised")
        {
          $('#preview_postHeader').find('a[purpose="category_Topic"]').html('&nbsp;&raquo; '+categoryCont+'');
        }
        
        writepostTags = writepostTags.replace(/^\s+|\s+$/g,' ').replace(/\s+/g,' ');
        if(writepostTags == "")
        {
          $('#forumTagsPreview').append('No tags available for this topic.');  
        }
        var tagList = writepostTags.split(",");
        
        //var flag = "false";
        for(var index = 0; index<tagList.length ;index++)
        {
          if(jQuery.trim(tagList[index]) != "")
          {
            $('#forumTagsPreview').append('<li><div class="imgTag flLeft"></div><div class="flLeft">&nbsp;<a class="blueLink" >'+tagList[index]+'</a>&nbsp;</div><div class="clearAll"></div> </li>');
          } 
        }
        var contentToPost = $('#postContentTA').data('editor').val();
        contentToPost = contentToPost.replace(/^\s+/g, '').replace(/\s+$/g, ''); //replace(/<[^>]*>/ig, '')
        if (contentToPost == '' )
        {
            hideLoadingImage();
            showMessage(i18n['zohodiscussions.writePost.noContentInPost'],'failure');
            return;
        }
         //get post content
        $previewSection.find('#responsePreviewContentContainer').html(contentToPost);
    }//if($previewSection.is(':visible'))
    
}
function forHidingSmallLoadingImg()
{
    var $browserCont = "";
    var cont ="";
    if($('#newPostRightCont').length > 0)
    {
        $browserCont = $('#newPostRightCont');
    }
    else if($('#attachBrowseCont').length > 0)
    {
        $browserCont = $('#attachBrowseCont');
    }
    $browserCont.find("[purpose='attachLoadingCont']").hide();
}

function processSearchContClick(event)
{
    var $target = $(event.target);
    var $targetParent = $target.parent();
    if($('#loadingImg').is(":visible"))
    {
        return;
    }
    if($targetParent.is('div[purpose="advanceSearch"]'))
    {   
        
     /*   $(function()
        {
            $('#selectFromDate').datePicker(
                    {
                            startDate: '01/01/2006',
                            endDate: (new Date()).asString()
                    }
            );
            $('#selectToDate').datePicker(
                    {
                            startDate: '01/01/2006',
                            endDate: (new Date()).asString()
                    }
            );
        });
      */  
        $('#advanceSearchContainerForm').show();
        $('#normalSearchInSearchList').hide();
    }
    else if($target.is('button[purpose="advanceSearchCancel"]') || $target.is('div[purpose="advanceSearchCancel"]'))
    {
        if($('#advancedSearchForm').is(':visible'))
        {
            $('#advancedSearchForm').remove();
        }
        else
        {
            $('#advanceSearchContainerForm').hide();
            $('#normalSearchContainer').show();
            $('#normalSearchInSearchList').show()
        }
    }
    else if($target.is('button[purpose="normalSearch"]'))
    {
        var searchFor = $('#normalSearchInputBox').val();
        processHash("search/"+searchFor);
    }
    else if($target.is('button[purpose="getAdvanceSearch"]'))
    {   
        getAdvanceSearchResult();
    }
    else if($target.is('a[purpose="postTitle"]'))
    {
        var forumTopicId = $target.attr('forumTopicId');
        var searchFor = $target.attr('searchFor');
        openSinglePost(forumTopicId,"topic",searchFor);
        return;
    }
    else if($targetParent.is('a[purpose="postTitle"]'))
    {
        var forumTopicId = $targetParent.attr('forumTopicId');
        var searchFor = $targetParent.attr('searchFor');
        openSinglePost(forumTopicId,"topic",searchFor);
        return;
    }
    else if($target.is('a[purpose="forumAction"]') || $target.is('a[purpose="categoryAction"]') )
    {   
        var hashPurpose = $target.attr("hashPurpose");
        processHash(hashPurpose);
    }
    else if($target.is('a[purpose="authorProfile"]') || $targetParent.is('a[purpose="authorProfile"]'))
    {   
        var authorName = $target.attr('authorName');
        if(!authorName)
        {
            authorName = $targetParent.attr('authorName');
        }
        var singleClickflag = $target.attr('singleClickflag');
        if(!singleClickflag)
        {
            singleClickflag = $targetParent.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('li.navBtnEnabled') && $target.is('[navType="searchNav"]'))
    {
        var navTab = $target.attr('purpose');
        searchNavigation($targetParent,navTab);
        return;
    }
    else if($target.is('a[purpose="relativeLinkSearch"]'))
    {
        //categoryId = $target.attr('categId');
        searchNavigation($target,"relativeLinkSearch")
        
    }
    else if($target.is('a[purpose="sortbyrelevance"]') && !$target.is('.boldText'))
    {
        searchNavigation($('#breadCrumbForSearch a[fieldType="All"]'),"breadCrumbForSearch","relevance"); //No I18N
    }
    else if($target.is('a[purpose="sortbydate"]') && !$target.is('.boldText'))
    {
        searchNavigation($('#breadCrumbForSearch a[fieldType="All"]'),"breadCrumbForSearch","date"); //No I18N
    }
    else if($target.is('a[purpose="breadCrumbForSearch"]'))
    {
        searchNavigation($target,"breadCrumbForSearch");
    }
    else if($target.is('a[purpose="expandForumList"]'))
    {
        var currStatus = $target.attr('status');
        if(currStatus == "off") 
        {
            $target.attr('status','on').html("&laquo; less");
            $target.parents('ul').find('li').show();
        }
        else
        {
            $target.attr('status','off').html("more &raquo;");
            var count = 0;
            $target.parents('ul').children('li').each(function()
            {
                if(count > 4)
                {
                    $(this).hide();
                }
                count++;
            });
        }
        
    }
}
function searchNavigation($target,navTab,sortby)
{   
    showLoadingImage();
    var currFetchPage = parseInt($target.attr('fetchPage'));
    var fieldType = $target.attr('fieldType');
    var categ_Id = $target.attr('categId');
    var path_Traverse = $target.attr('pathTraverse');
    var $breadCrumbForSearch = $('#breadCrumbForSearch');
    
    if(navTab == "next")
    {
        currFetchPage = currFetchPage+1;
    }
    else if(navTab == "prev")
    {
        currFetchPage = currFetchPage-1;
    }
    else
    {
        currFetchPage = 1;
    }
    var searchSortBy = sortby;
    if(searchSortBy != "relevance" && searchSortBy != "date")
    {
        searchSortBy = $('#currSearchSortBy').attr('currSortBy');
    }
    if($('#searchListContainer').is('.selected'))
    {
        doAjaxAction('/getMoreSearchResult.do?fetchPage='+currFetchPage+'&searchSortBy='+searchSortBy+'&category_id='+categ_Id+'&category_pathTraverse='+path_Traverse+'',$('#advanceSearchForm').serialize(),function(data)//No internationalization
        {
            hideLoadingImage();
            reloadeSearchContainer(data,navTab,fieldType,forumId,categ_Id,path_Traverse,searchSortBy);
        });

    }
    else
    {
        var options = {};
        options.fetchPage = currFetchPage;
        options.category_id = categ_Id;
        options.category_pathTraverse = path_Traverse;
        options.searchSortBy = searchSortBy;
        var forumId = $target.attr('forumId');
        if(!forumId)
        {
            forumId = -1;
        }
        if(navTab == "breadCrumbForSearch")
        {   
            options.searchFor = $breadCrumbForSearch.attr('searchFor');
        }
        else
        {
            options.searchFor = $target.attr('searchFor');
        }
        options.forumGroupId = forumGroupId;
        options.forumId = forumId;
        options.normalSearchType = $('#searchSelectedImage').attr('purpose');
        doAjaxAction('/getMoreSearchResult.do',options,function(data)//No internationalization
        {   
            hideLoadingImage();
            reloadeSearchContainer(data,navTab,fieldType,forumId,categ_Id,path_Traverse,searchSortBy);
        });
    }
}

function reloadeSearchContainer(data,navTab,fieldType,forumId,categ_Id,path_Traverse,sortby)
{
    var $breadCrumbForSearch = $('#breadCrumbForSearch');
    var $data = $('<div></div>');
    $data.get(0).innerHTML = data;
    var $container = $data.find('#searchListContainer').html();
    $('#searchListContainer').html($container);
    var $searchResultViewRange = $data.find('#searchResultViewRange').html();
    $('#searchResultViewRange').html($searchResultViewRange);
    var $filterContainer = $data.find('#searchFilterArea').html();
    $('#searchFilterArea').html($filterContainer);
    var $currSearchSortBy =  $data.find('#currSearchSortBy').html();
    $('#currSearchSortBy').html($currSearchSortBy).attr('currSortBy',sortby);
    
    if(navTab == "relativeLinkSearch")
    {   
        var $newbreadCrumb = $("<span> &raquo; <a class=underline href=javaScript:; purpose=breadCrumbForSearch fieldType="+fieldType+" forumId="+forumId+" categId="+categ_Id+" pathTraverse="+path_Traverse+ ">"+fieldType+"</a></span>"); 
        $newbreadCrumb.insertAfter($('#breadCrumbForSearch').find('span:last'));
        
    }
    else if(navTab == "breadCrumbForSearch")
    {   
        var afterRemove = 0;
        $breadCrumbForSearch.children().each(function()
        {
            var $this = $(this);
            var currType = $this.find('a').attr('fieldType');
            if(afterRemove == 1)
            {
                $this.remove();
            }
            if(currType == fieldType)
            {
                afterRemove = 1;
            }
        });
    }

}//function reloadeSearchContainer(data,navTab)
function getAdvanceSearchResult()
{
    showLoadingImage();
    var searchString = $('#advanceSearchInpurBox').val()
    searchString =$.trim(searchString);
    if(searchString == "")
    {
        showMessage(i18n['zohodiscussions.searchList.noSearchString'],'failure');
        hideLoadingImage();
        return;
    }
/*
    var fromDate = $('#selectFromDate').val();
    var toDate = $('#selectToDate').val();
    if((fromDate !="" && toDate == "") || (fromDate =="" && toDate != ""))
    {
        hideLoadingImage();
        return;
    }
    if(fromDate !="" && toDate != "")
    {   
        var splitFromDate = fromDate.split("/");
        var fromDay = splitFromDate[0];
        var fromMonth = splitFromDate[1];
        var fromYear = splitFromDate[2];
        var splitToDate = toDate.split("/");
        var toDay = splitToDate[0];
        var toMonth = splitToDate[1];
        var toYear = splitToDate[2];
        if(!fromDay ||  !fromMonth || !fromYear || !toDay || !toMonth || !toYear)
        {
            hideLoadingImage();
            return;
        }
        var correctDate = 0;
        if(toDay < fromDay)
        {
            if(toMonth > fromMonth)
            {
                if(toYear >= fromYear)
                {
                    correctDate = 1;
                }
            }
            else
            {
                if(toYear > fromYear)
                {
                    correctDate = 1;
                }
            }
        }
        else
        {
            if(toMonth >= fromMonth)
            {
                if(toYear >= fromYear)
                {
                    correctDate = 1;
                }
            }
            else
            {
                if(toYear > fromYear)
                {
                    correctDate = 1;
                }
            }
        }
        if(correctDate == 0)
        {
            hideLoadingImage();
            return;
        }
        $('#startDateinMils').val(fromYear+fromMonth+fromDay);
        $('#endDateinMils').val(toYear+toMonth+toDay);
    }
*/
    var $searchForumCategoryVice  = $('#SearchforumCategoryVice');
    var searchType = "forumId";
    var options = {};
    
    doAjaxAction(
        "/getAdvanceSearchResult.do", //No I18N
        $("#advanceSearchForm").serialize(),
        function (data)
        {
            hideLoadingImage();
            var $data = $('<div></div>');
            $data.get(0).innerHTML = data;
            var $searchContainer = $('#searchContainer');
            //$.history.add("Search/"+searchFor);
            if($('#searchListContainer').is(':visible'))
            {
                 var $container = $data.find('#searchResultFullContainer').html();
                 $('#searchResultFullContainer').html($container);
                 $('#searchListContainer').addClass('selected');
            }
            else
            {
                $('#mainContent').get(0).innerHTML = data;
                bindSearchContentClick($('#mainContent'));
                $('#advanceSearchContainerForm').show();
                $('#normalSearchInSearchList').hide();
            }
        },
        function (errordata)
        {
            hideLoadingImage();
            $('#mainContent').html(errordata.responseText);
        }
    );
}//function getAdvanceSearchResult()

function processWidgetsContClick(event)
{   
    var $target = $(event.target);
    var $targetParent = $target.parent();
    if($target.is('a[hashPurpose]') && $target.is('a[currpurpose="usingHash"]'))
    {   
        var hash = $target.attr('hashPurpose');
        if(isTopicQuickView == "false" && hash.indexOf("Topic/") == 0)
        {
            //do nothing
        }
        else
        {
            processHash(hash);
            return false;
        }
    }
    else if($target.is('div.teeplus'))
    {
        var forumId = $target.attr('forumId');//No internationalization
        var $teecont = $('#allForumControl').find('div[purpose="subForumView_'+forumId+'"]');
        $teecont.removeClass('teeplus').addClass('teeminus');//No internationalization
        $('ul.eachCategoryContainer_'+forumId).show();
    }
    else if($target.is('div.teeminus'))
    {
        var forumId = $target.attr('forumId');//No internationalization
        var $teecont = $('#allForumControl').find('div[purpose="subForumView_'+forumId+'"]');
        $teecont.removeClass('teeminus').addClass('teeplus');//No internationalization
        $('ul.eachCategoryContainer_'+forumId).hide(); 
    }
    else if($targetParent.is('#forumPermalink'))
    {   
        var thisForumPermalink = $targetParent.attr('thisForumPermalink');
        $('#PermalinkCont textarea').val(thisForumPermalink);
        $('#permalink_Text').select();
        $('#PermalinkCont').show().parent().show();
        return;
    }
    else if($targetParent.is('li.watchingForum'))
    {
        watchThisItem($targetParent,"singleForumActions",event);
    }
    else if($targetParent.is('li.watchingCategory'))
    {
        watchThisItem($targetParent,"singleCategoryActions",event);  
    }
    else if($target.is('a[purpose="newWatchedUser"]'))
    {
        processHash("myarea/dashboard");
        return;
    }
    else if($target.is('a[purpose="newPrivateMsg"]'))
    {
        processHash("myarea/privateMsg");
        return;
    }
    else if($target.is('a[purpose="newRecentActivity"]'))
    {
        var currStatus = $target.attr("currStatus");
        if(currStatus == "dashboard")
        {
            processHash("myarea/"+currStatus);
            return;
        }
        processHash("myarea/watchList/"+currStatus);
        return;
    }
    else if($target.is('a[purpose="authorProfile"]'))
    {
        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($targetParent.is("#loginToParticipate"))
    {
        $('#signinwidgetBox').hide();
        $('#iamLoginBox').show();
    }
    else if($targetParent.is("#chartMenu"))
    {
        //
        if($target.is('li'))
        {
            $target.siblings().removeClass('selected');
            $target.addClass('selected');
            var assocImage=$target.attr('assocImage');
            $(assocImage).show().siblings().hide();
        }
        
    }
    else if($targetParent.is("#topContributorsMenu"))
    {
        if($target.is('li'))
        {
            $target.siblings().removeClass('selected');
            $target.addClass('selected');
            var assocImage=$target.attr('assocDiv');
            $(assocImage).show().siblings('ul').hide();
        }
        
    }
}//function processWidgetsContClick(event)

function processAllForumsClick(event)
{
    var $target = $(event.target);
    var $targetParent = $target.parent();
    if($target.is('a[hashPurpose]'))
    {   
        var hashPurpose = $target.attr('hashPurpose');
        if((isTopicQuickView == "false" && hashPurpose.indexOf("Topic/") == 0) || $target.attr('isNiceUrl') == "Yes")
        {
            //do nothing
        }
        else
        {
            processHash(hashPurpose);
            return false;
        }
    }
    else if($targetParent.is('li[purpose="eachForumPermalink"]'))
    {
        var thisForumPermalink = $targetParent.attr('thisForumPermalink');
        $('#PermalinkCont textarea').val(thisForumPermalink);
        $('#permalink_Text').select();
        $('#PermalinkCont').show().parent().show();
        return;
    }
    else if($targetParent.is('li.watchingForum'))
    {
        watchThisItem($targetParent,"singleForumActions",event);
    }
}

function handleTopicClick(event,forumTopicId,$location)
{
    var $topicContainer = $('#eachTopic_'+forumTopicId);
    var $recentResponseContainer = $('#lastResponse_'+forumTopicId);
    var responseId = $recentResponseContainer.parents('div[parentCont="actualParent"]').attr('recentResponseId');
    var $topicList = $('#topicList');
    $topicList.data('currentSelectedPost',$topicContainer);
    var $currFocusPost = $topicList.data('currentFocusPost');
    if($currFocusPost != undefined)
    {
        $currFocusPost.removeClass('hotKeyTopicCont');
    }    
    $topicList.data('currentFocusPost',$topicContainer);
    if($recentResponseContainer.is(':visible') == true)
    {
        $topicContainer.removeClass('singleTopicContSel').addClass('singleTopicCont');
    }
    else
    {
        $topicContainer.siblings('div.singleTopicContSel').removeClass('singleTopicContSel').addClass('singleTopicCont');
        $topicContainer.removeClass('singleTopicCont').addClass('singleTopicContSel')
        if(topicContent[forumTopicId])
        {
            $('#recentResponseContent_'+responseId).html(topicContent[forumTopicId]);
            topicContent[forumTopicId] = undefined;
        }
        setFocusToContainer($('#eachTopic_'+forumTopicId),false,0);
    }

    if($recentResponseContainer.attr('navStatus') == "No" && $location == "topicList")
    { 
        $recentResponseContainer.attr('navStatus',"Yes");
        getprevAndFirstPost($recentResponseContainer);
    }
}//function handleTopicClick(event,forumTopicId)

//method to fetch more topics in topic list
function getMoreTopics(forumId,categoryId,fetchPage,topicFilter,postSinceLastVisitTime,statusURL,isPagination)
{
    showLoadingImage();
    var options = {};
    var filterHash = "";
    var $currviewFilter = $('#innerTabFilter');
    if($('#topicListFilter').is(':visible'))
    {
        $currviewFilter = $('#topicListFilter');
    }
    if(forumId != "")
    {
        options.forumURL =  forumId;
        filterHash = "forum/"+forumId; //No I18N
    }
    if(categoryId != "")
    {
        options.categoryURL = categoryId;
        filterHash = filterHash+"/"+categoryId; //No I18N
    }
    options.forumGroupId = forumGroupId;
    options.fetchPage = fetchPage;
    var isFilterThere = 0;
    if(topicFilter && topicFilter.toLowerCase() != "all" && (isOneTopicType != "true" || topicFilter.toLowerCase() != "questions" && topicFilter.toLowerCase() != "ideas" && topicFilter.toLowerCase() != "problems"))
    {   
        if(filterHash == "")
        {
            filterHash = "filter"; //No I18N
        }
        else
        {
            filterHash = filterHash+"/filter"; //No I18N
        }
        isFilterThere = 1;
        filterHash = filterHash+"/"+topicFilter;     
    }
    if(topicFilter)
    {
        if($currviewFilter.attr('isTypeURL') == 'yes')
        {
            var currTopicFilter = $currviewFilter.attr('topicfiltertype');
            if(topicFilter.toLowerCase() == "all")
            {
                topicFilter = currTopicFilter;
            }
            else if(topicFilter.toLowerCase() == "unrepliedposts")
            {
                options.unReplyWithType = currTopicFilter;
            }
        }    
        options.topicFilter = topicFilter;
    }
    if(topicFilter == "postssincelastvisit") 
    {
        var lastVisit = $currviewFilter.attr('postSinceLastVisitTime');
        if(lastVisit != null && lastVisit != "undefined")
        {
            options.postSinceLastVisitTime = lastVisit;
        }
    }
    var action = "";
    var $loadLocation = "";
    if($('#topicList').length > 0 && isPagination != "reload")
    {
        action = "/getMoreTopics.do"; //No I18N
        $locadLocation = $('#topicList');
    }
    else if($('#topicsList').length > 0 && isPagination != "reload")
    {
        action = "/getMoreTopicsTP.do"; //No I18N
        $locadLocation = $('#topicsList');
    }
    else
    {
        action = "/getSingleForumTopics.do"; //No I18N
        $locadLocation = $('#mainContent');
    }
    if(statusURL)
    {
        if(isPagination == "true")
        {
            options.topicStatus = statusURL;
        }
        else
        {
            statusURL = statusURL.toLowerCase();
            statusURL = statusURL.replace(/\s/ig,"").replace("-","");
            var currStatusURL = statusURL;
            if(topicFilter == "problems" && statusURL == "needmoreinfo")
            {   
                statusURL = "moreinfo" //No I18N
                currStatusURL = "needmoreinfo"; //No I18N
            }
            if(topicFilter == "questions" && statusURL == "workingonit")
            {   
                statusURL = "working" //No I18N
                currStatusURL = "workingonit"; //No I18N
            }
            if(statusURL == "we")
            {
                statusURL = "wewillthinkaboutit" //No I18N
                currStatusURL = statusURL //No I18N
            }
            if(i18n_Status_[statusURL])
            {   
                var i18n_statusURL = i18n_Status_[statusURL];
                if(i18n_statusURL)
                {
                    if(isFilterThere == 0 && filterHash == "")
                    {
                        filterHash = "filter"; //No I18N
                    }
                    else if(isFilterThere == 0)
                    {
                        filterHash = filterHash+"/filter"; //No I18N
                    }
                    filterHash = filterHash+"/"+currStatusURL;
                    options.statusURL = i18n_statusURL;
                } 
            }  
        }
    }
   
    doAjaxAction(
        action,
        options,
        function (data)
        {
            $locadLocation.get(0).innerHTML = data;
            bindTopicClicks($('#topicList'));
            bindTopicClicks($('#topicsList'));
            if(action = "/getSingleForumTopics.do")
            {
                 lightBox('#chartWidget');
                bindTopicListHeaderClicks($('#topicListHeader'));
                bindWidgetsContClick($('#topicListWidgetsCont'));
            }
            goToTop();
            hideLoadingImage();
            if(typeof WmsContacts != "undefined" && ch == true)
            {
                var dataOb = WmsContacts.getZohoContacts();
                setPresenceInTopicList(dataOb);
            }
            if(topicFilter == "PostsSinceLastVisit") 
            {
                var $postSinceLastVisit = $('#topicList').find('a.mediumUnderlineLink');
                $postSinceLastVisit.removeClass('mediumUnderlineLink').addClass('mediumUnderlineLinkNew');
            }
            if($currviewFilter.attr('isTypeURL') == "no")
            {
                if(filterHash != "")
                {
                    if(parseInt(fetchPage) > 1)
                    {
                        $.history.add(filterHash+"/"+fetchPage);
                    }
                    else
                    {
                        $.history.add(filterHash);
                    }
                }
                else
                {
                    if(parseInt(fetchPage) > 1)
                    {
                        $.history.add("home/"+fetchPage); //No I18N
                    }
                    else
                    {
                        $.history.add("home"); //No I18N
                    }    
                }
            }    
        },
        function (errordata)
        {
            //alert(errordata.responseText);
        }
    );
    return false;
}//function getMoreTopics(forumId,categoryId,fetchPage)

//method to fetch more topics in topic list
function getMoreTagRelatedPost(fetchPage,tagName,getPostFor)
{
    showLoadingImage();
    var options = {};
    options.fetchPage =  fetchPage;
    options.tagName = tagName;
    options.forumGroupId = forumGroupId;
    options.getPostFor = getPostFor;
    doAjaxAction(
        "/getMoreTagRelatedPosts.do", //No I18N
        options,
        function (data)
        {
            if($('#topicList').length > 0)
            {
                $('#topicList').get(0).innerHTML = data; 
                bindTopicClicks($('#topicList'));
            }
            else
            {
                $('#topicsList').get(0).innerHTML = data; 
                bindTopicClicks($('#topicsList'));
            }
            goToTop();
            hideLoadingImage();
        },
        function (errordata)
        {
            //alert(errordata.responseText);
        }
     );
    return false;
}//function getMoreTopics(forumId,categoryId,fetchPage)

//method to fetch single forum topics
function getSingleForumTopics($target)
{  
    showLoadingImage();
    var $this = $target
    var options = {};
    options.forumId =  $this.attr('forumId');
    options.categoryId = $this.attr('categoryId');
    options.forumGroupId = forumGroupId;
    options.fetchPage = $this.attr('fetchPage');
    options.ch = ch;
    doAjaxAction(
        "/getSingleForumTopics.do", //No I18N
        options,
        function (data)
        {
             
            $('#mainContent').get(0).innerHTML = data;
            lightBox('#chartWidget');
            bindTopicClicks($('#topicList'));
            bindTopicClicks($('#topicsList'));
            bindTopicListHeaderClicks($('#topicListHeader'));
            bindWidgetsContClick($('#topicListWidgetsCont'));
            goToTop();
            hideLoadingImage();  
            if($('#allForumWidget').length > 0)
            {
               if($('#allForumWidget').find('li[purpose="forumList"]').length < 9)
               {
                   $('#moreForumView').hide();
               }
            }
        },
        function (errordata)
        { 
            $('#mainContent').get(0).innerHTML = errordata.responseText;
            hideLoadingImage();
        }        
    );
    return false;
}//

function bindTopContainerClick()
{
    var $switchPortalLink = $('#switchPortalLink');
    var $portalsDropDown = $('#portalsDropDown,#borderPortal');
    var $portalComboCont = $('#portalComboCont');
    $switchPortalLink.click(function()
    {
        if($portalsDropDown.is(':visible'))
        {
            $portalsDropDown.hide();
            $portalComboCont.removeClass('newComboSelected').addClass('newCombo');
        }
        else
        {
            $portalsDropDown.show();
            $portalComboCont.removeClass('newCombo').addClass('newComboSelected');
        }
    });
    $portalsDropDown.hover
    (
        function()

        {
           var handle = $portalsDropDown.data('destroyHandle');
           if(handle){clearTimeout(handle);}
        },
        function ()
        {
            var handle = setTimeout(function()

            {
                $portalsDropDown.hide();
                $portalComboCont.removeClass('newComboSelected').addClass('newCombo');
            }, 500);
            $portalsDropDown.data('destroyHandle', handle);
        }
    );
    $('#portalsDropDown li').click(function()
    {
        $('#portalsDropDown').hide();
        var $this = $(this);
        var thisPortalURL = $this.attr('thisPoratlUrl');
        if(thisPortalURL != currentForumGroupURL)
        {
            $('#dimDivContainer').show();
            location.href= defaultDomain+"/"+thisPortalURL;
            return false;
        }
    });
}//function bindTopContainerClick()
/**** END OF TOPIC LIST CLICKS ****/
function selectTopicType($this)
{
        $this.addClass('selected').siblings('li[purpose="topicTypeTab"]').removeClass('selected');
        var topicType = $this.attr('topicType');
        if(topicType == 1)
        {
            $('#announcementExpiryCont').show();
        }
        else
        {
            $('#announcementExpiryCont').hide();    
        }
        $('#currentTopicType').val(topicType);
        var topicTypeIcon = $this.attr('topicIconClass');
        if(topicTypeIcon == 'discuss')
        {
            $('#writeNewTopic').html(i18n['zohodiscussions.writePost.discussionTypeMessage']);
        }
        else if(topicTypeIcon == 'question')
        {
            $('#writeNewTopic').html(i18n['zohodiscussions.writePost.questionTypeMessage']);
        }
        else if(topicTypeIcon == 'idea')
        {
            $('#writeNewTopic').html(i18n['zohodiscussions.writePost.ideaTypeMessage']);
        }
        else if(topicTypeIcon == 'error')
        {
            $('#writeNewTopic').html(i18n['zohodiscussions.writePost.problemTypeMessage']);
        }
        else
        {
            $('#writeNewTopic').html(i18n['zohodiscussions.writePost.announcementTypeMessage']);
        }
        $('#TopicContentHolder').attr('class',topicTypeIcon);
        var selectedForumOption = $('#SelectForum').val();
        if(selectedForumOption == null)
        {
           $('#selectForumMessage').show();
        }
        else
        {
           $('#selectForumMessage').hide();  
        }
}//function selectTopicType($this)
/****WRITE POST****/
function initWritePost()
{
    
    openEditor($('#editorLocation'),"responseContent","postContentTA");
    loadCategories();
    $('#writepostTabsCont li[purpose="topicTypeTab"]').click(function()
    {
        selectTopicType($(this));
    });
    $('#SelectForum').change(function()
    {
        loadCategories();
    });
    $('#publishTopic').click(function()
    {
        addForumPost(false);
    });
    $('#previewTopic').click(function()
    {
      var $this = $(this);
      var isDraft = $this.attr('isDraft');
      var userName = $this.attr('userName');
      writePostPreview(userName,"Preview","true",isDraft)
    });

    $('#attachmentsListCont').find('div.imgAshDelete').click(function(event)
    {
        $this = $(this);
        var attachmentName = $this.attr('attachmentName');
        var attachmentId = $this.attr('attachmentId');
        deleteUnpublishedAttachment(attachmentName,attachmentId,event);
        return;
    });
    
    $('#listOfMyDraftCont').click(function()
    {   

        var draftSize = $(this).attr('draftsize');
        if(draftSize < 1)
        {
            return;
        }
        var $this = $(this);
        if($this.is('.moreOptionsTop'))
        {
            $this.removeClass('moreOptionsTop').addClass('moreOptionsTopSelected');
        }
        else
        {
            $this.removeClass('moreOptionsTopSelected').addClass('moreOptionsTop');
        }
        $this.hover
        (
            function()
            {
               var handle = $this.data('destroyHandle');
               if (handle) {clearTimeout(handle);}
            },
            function ()
            {
                var handle = setTimeout(function()
                {
                    $this.removeClass('moreOptionsTopSelected').addClass('moreOptionsTop');
                }, 500);
                $this.data('destroyHandle', handle);
            }
        );//$myDraftContainer.hover()
    });
    $('#saveDraft').click(function()
    {   
        addForumPost(true);
    });
    $('#cancelAddTopic').click(function()
    {
        $('#mainContent div.mainFullWrite').html('');
        processHash('Home');
    });
    
    loadUploadAttachmentsCont();
}//function initWritePost()


function loadUploadAttachmentsCont()
{
    //before loading a attachment cont delete the existing attachements cont
    var forNewPost = ($('#attachTemplate').length == 1)?true:false;
    var contName = (forNewPost == true)?"attachTemplate":"responseAttachTemplate"
    var $attachmentsListCont = $('#attachmentsListCont');
    var attachementsUploaded = $attachmentsListCont.find('div.singleElementBox,li.tinyText').length;
    if(forNewPost == true)
    {
        $('#newPostRightCont  div[purpose="attachmentTemplate"]').remove();
    }
    else
    {
        $('#attachBrowseCont').html('');
    }
    //make (sure that uploaded attachments count is less than maxAttachmentsPerPost
    if(attachementsUploaded < maxAttachmentsPerPost)
    {
        var currentAttachementNo = attachementsUploaded+1;
        //we have attachement container template 
        var $attachTemplate = $('#'+contName);
        //take a clone of attachTemplate container and process the file uploading
        var $attacher = $attachTemplate.clone();
        if(forNewPost == true)
        {
            $attacher.insertBefore($attachmentsListCont).show();
        }
        else
        {
            $('#attachBrowseCont').append($attacher.show()).show();
        }
        $attacher.attr('id',contName+'_'+currentAttachementNo);
        $attacher.attr('purpose','attachmentTemplate');
        $attacher.find('div.dataEncloser').wrap('<form action = "/uploadFile.do" target = "fileUpdTgt" method="post" enctype="multipart/form-data"></form>')
        $attacher.find('div.iFrameContainer').html('<iframe name = "fileUpdTgt_'+currentAttachementNo+ '"> </iframe>')
        $attacher.find('form').attr('target', 'fileUpdTgt_'+currentAttachementNo)
        
        //write the file upload action

        $attacher.find(':file').change(function()
        {
            $attacher.find('[purpose="attachLoadingCont"]').show();
            $attacher.find(':input[name="attacher"]').val('');
            $attacher.find('form').get(0).submit();
        });
    }//if(attachementsUploaded < maxAttachmentsPerPost)
}//function loadUploadAttachmentsCont()

function uploadFileSuccess(attachmentId,attachmentName,forumGroupId,actualAttachmentId,formattedFileSize)
{
    //hideLoadingImage();
    var $attachmentsListCont = $('#attachmentsListCont');
    var forNewPost = ($('#attachTemplate').length == 1)?true:false;
    var $currentAttachment;
    var attachmentDetails = attachmentId+','+attachmentName+','+formattedFileSize;
    if(forNewPost == true)
    {
        $currentAttachment = $('<div id="newAttachment_' + attachmentId + '" class="singleElementBox" attachmentDetails="'+ attachmentDetails +'"><div class="flLeft">'+attachmentName+'</div><div class="flRight imgAshDelete bgBox"></div></div>');
        var $attachmentContForPreview = $('#previewAttachment');
        var $eachAttachment = $('<li class="singleList" id="eachAttachmentForPreview_'+ attachmentId +'"  attachmentDetails="'+ attachmentDetails +'"><div class="flLeft iconCont"><div class="attachIcon imgAttachmentTh"></div></div>  <ul class="ulNoStyle detailsListNew"> <li class="header"> <a>'+attachmentName+'</a> </li> <li class="forumDetailsList"> <span>Size:'+formattedFileSize+'</span></li></ul></li>')
        $attachmentContForPreview.append($eachAttachment);
        $('#newAttachment_' + attachmentId).attr('attachmentDetails', attachmentDetails);
        $('#AttachmentPreviewCont').show();
    }
    else
    {
        $currentAttachment = $('#responseEachAttachmentTemplate').clone();
        $currentAttachment.attr('id','newAttachment_' + attachmentId).attr('attachmentDetails',attachmentDetails).show();
        $currentAttachment.find('[attachmentPurpose="attachmentName"]').html(attachmentName);
        $currentAttachment.find('[attachmentPurpose="attachmentSize"]').html(formattedFileSize);
    }
    $('#previewResponse').append('<input type = "hidden" name="attachmentId" value = "' + attachmentId + '"  attachmentDetails= "' + attachmentDetails + '">')
    $currentAttachment.append('<input type = "hidden" name="attachmentId" value = "' + attachmentId + '">');
    if(actualAttachmentId != '-1')
    {
        $currentAttachment.append('<input type = "hidden" name="attachmentId" value = "' + actualAttachmentId + '">');
    }
    $currentAttachment.find('div.imgAshDelete').click(function(event)
    {
        deleteUnpublishedAttachment(attachmentName,attachmentId,event);
    });
    $attachmentsListCont.append($currentAttachment);
    
    //generate the new file upload container
    loadUploadAttachmentsCont();
}

function deleteUnpublishedAttachment(attachmentName,attachmentId,event)
{
    if(confirm(i18n['zohodiscussions.generalmessage.deleteAttachmentConfirmMsg']))
    {
        showSmallLoadingImage(event);
        var options = {};
        options.forumGroupId = forumGroupId;
        options.fileName = attachmentName;
        options.fileId = attachmentId;
        options[csrfParamName] = csrfToken;
        doAjaxAction('/deleteUnpublishedAttachment.do',options,function (data)//No internationalization
        {
            hideLoadingImage();
                if(data == "SUCCESS")
                {
                    $('#newAttachment_'+attachmentId).remove();
                    if($('#previewAttachment').find('li.singleList').length == 1)
                    {
                      $('#AttachmentPreviewCont').hide();
                    }                     
                    $('#previewResponse').find('input[value= "' + attachmentId + '"]').remove();
                    showTipper(i18n['zohodiscussions.generalmessage.deleteAttachmentSuccessMsg'],'info');
                    loadUploadAttachmentsCont();
                }//if(data == "SUCCESS")
            });
        }// 
}
function loadCategories()
{
    loadAdminActionsLinks();
    var $selectForumContainer = $('#SelectForum');
    var forumId = $selectForumContainer.val();
    var selectedCategoryName = $selectForumContainer.attr('selectedCategoryName');
    var selectedCategoryId = $selectForumContainer.attr('selectedCategoryId');
    //load categories for this forum
    var categoriesForForum = $('#categoryList').val().split('$$');
    $('#SelectCategory').hide();
    $('#selectCategory').html('');
    $.each(categoriesForForum, function(index, item)
    {
        if(item.indexOf(forumId+':') > -1)
        {
            $('#SelectCategory').html(item.split(':')[1]).show();
            //$('#SelectCategory option:first').attr('selected','true');
            return false;
        }//if(item.indexOf(forumId+':') > -1)
        else
        {
           $('#SelectCategory').html('<option selected value="-1">Uncategorised</option>').show();
        }
    });
    var $selectedCategoryCont = $('#SelectCategory').find('option[value="'+selectedCategoryId+'"]');
    if($selectedCategoryCont.length == 1)
    {
        $selectedCategoryCont.attr('selected','true');
    }
    else
    {
        $('#SelectCategory option:first').attr('selected','true');
    }
    
}//function loadCategories(postId)

function loadAdminActionsLinks()
{
    var isForumModerator = $('#SelectForum option:selected').attr('isForumModerator');
    if(isForumModerator == "true")
    {
        $('#isStickyLinkCont,#announcementLinkCont').fadeIn();
    }
    else
    {
        //the author is not admin or moderator
        $('#isStickyLinkCont,#announcementLinkCont').fadeOut();
        //if the currently selected topictype is announcement then select the discussions tab
        if($('#writepostTabsCont li.selected').attr('topicIconClass') == 'announcement')
        {
            $('#writepostTabsCont li:first').trigger('click');
        }
    }
}//function loadAdminActionsLinks()

function addForumPost(isDraft)
{
    if($('#fileUploadStatus').val() != 'uploading')
    {
        var loadingMessage = (isDraft == true)?i18n['zohodiscussions.general.saving']:i18n['zohodiscussions.general.publishing'];
        disablePostButtons();
        var $writePostForm = $('#addForumPostForm');
        $topicTitle = $('#topicTitle');
        var postTitle = $topicTitle.val();
        postTitle = postTitle.replace(/^\s+|\s+$/g,' ').replace(/\s+/g,' ');
        postTitle = $.trim(postTitle);
        if (postTitle == '')
        {
            hideLoadingImage();
            setFocusToContainer($('#topicTitle'));
            enablePostButtons();
            showMessage(i18n['zohodiscussions.writePost.TopicTitleCannotbeEmptymessage'],'failure');
            $('#topicTitle').focus();
            return;
        }
        $('#topicTitle').val(postTitle);
        if(postTitle.length > 200)
        {
            hideLoadingImage();
            showMessage(i18n['zohodiscussions.writePost.TopicTitleLengthMsg'],'failure');
            enablePostButtons();
            return;
        }
        var postTags = $('#forumTags').val();
        postTags = postTags.replace(/^\s+|\s+$/g,' ').replace(/\s+/g,' ');
        if(postTags != "")
        {
          if(postTags.match(/^[^()~`!@#$%&:;\/?|<>{}[\]*-+=]+$/)== null)
          {
             hideLoadingImage();
             showMessage(i18n['zohodiscussions.singlepost.specialCharacterNotAllowedMsg'],'failure');
             enablePostButtons();
             return;  
          }
        }//if(postTags != "")
        var tag =postTags.split(",");
        for(var i=0;i<tag.length;i++)
        {
            if(tag[i].length > 50)
            {
                showTipper(i18n['zohodiscussions.singlepost.TagexceedMessage'],'failure');
                enablePostButtons();
                return;   
            } 
        }// for(var i=0;i<tag.length;i++)
         
        var contentToPost = $('#postContentTA').data('editor').val();
        contentToPost = contentToPost.replace(/^\s+|\s+$/g,' ').replace(/\s+/g,' ');
        $('#postContentTA').val(contentToPost);
        var $tempCont = $('<div></div>').html(contentToPost);
        contentToPost = $tempCont.text();
        contentToPost = $.trim(contentToPost);
        if (contentToPost == '')
        {
            setFocusToContainer(($('#editorHolder')).focus());
            hideLoadingImage();
            enablePostButtons();
            showMessage(i18n['zohodiscussions.writePost.noContentInPost'],'failure');
            return;
        }

        if(isDraft == true)
        {
            //this is draft so topic status will be 1
            $('#topicStatus').val(1);
        }
        else
        {
            //this is a normal post so status will be 0
            $('#topicStatus').val(0);
        }
        var selectedForum = $('#SelectForum').val();
        if(selectedForum == null)
        {
           hideLoadingImage();
           showMessage(i18n['zohodiscussions.writePost.selectAnyForum'],'failure');
           enablePostButtons();
           return;
        }
        var action = '/addForumPost.do';
        if(ZUID == -1)
        {
            action = '/addGuestForumPost.do';
        }
        showLoadingImage(loadingMessage);   
            doAjaxAction(
            action, 
            $('#addForumPostForm').serialize(),
            function (data)
            {
                hideLoadingImage();
                var responseData = eval(data);
                if(responseData.result=="success")
                {   
                    var forumTopicId = responseData.value;
                    if(isDraft == true)
                    {
                        showTipper(i18n['zohodiscussions.writePost.saveDraftMsg'],'success',3000);
                        enablePostButtons();
                        $('#forumTopicId').val(forumTopicId);
                    }
                    else
                    {
                        if(responseData.isApproved == 0)
                        {
                            //this topic is waiing for moderation
                            $('#mainContent div.mainFullWrite').html('');
                            showMessage(i18n['zohodiscussions.writePost.topicAwaitingModeration'],'info');
                            if(isTopicQuickView == "false")
                            {
                                window.location.href = serverURL+'/topic/'+responseData.topicPermaLink;
                            }
                            else
                            {
                                showLoadingImage();
                                openSinglePost(forumTopicId);
                            }   
                            return;
                        }
                        else
                        {
                            $('#mainContent div.mainFullWrite').html('');
                            showTipper(i18n['zohodiscussions.writePost.publishMsg'],'success',4000);
                            if(isTopicQuickView == "false")
                            {
                                window.location.href = serverURL+'/topic/'+responseData.topicPermaLink;
                            }
                            else
                            {
                                showLoadingImage();
                                openSinglePost(responseData.value);
                            }
                        }
                    }
                }//
                else
                {   
                    showMessage(responseData.reason,'failure');
                    if(responseData.errorcode == "IMAGE_CODE_MANDATORY" || responseData.errorcode == "INVALID_IMAGE_CODE")
                    {
                        //this error occured due to invalid image code
                        //so replace the captcha with new one
                        var newTime = new Date();
                        //var forumTopicId = $('#frmAddForumPost_' + postId).find('input[purpose="forumTopicId"]').val();
                        //$('#frmAddForumPost_' + postId).find('img[purpose="captchaImage"]').replaceWith('<img purpose="captchaImage" name="hipImg" border="0" src="/generateCaptcha.do?forumTopicId=NewPost_'+postId+'&timeStamp='+newTime+'" alt="HIP image" align="absmiddle">');
                    }
                    enablePostButtons();
                }
            },
            function(errordata)
            {
                hideLoadingImage();
                if(errordata.responseText.indexOf("'result':'failure'") > 0)
                {
                    var responseData = eval(errordata.responseText);
                    if(responseData.result == "failure")
                    {
                        if(responseData.errorcode == "HIP_REQUIRED")
                        {
                            var $writePostCaptcha = $('#writePostCaptcha');
                            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>");
                            $('#captchaCode').attr('name',responseData.reason);
                            $writePostCaptcha.attr('currCaptcha',"old");
                            $writePostCaptcha.show();
                        }
                        else
                        {
                            showMessage(responseData.reason,'failure'); //No I18N
                        }
                    }
                }
                else
                {
                    $('#writepostCont').get(0).innerHTML = errordata.responseText;
                }
                enablePostButtons();
            });            
        }
        else
        {
            $('#submitStat').show();
        }
}//function addForumPost(isDraft)

function singlePostDeleteAction($this,$location)
{
  var forumTopicId = $this.attr('forumTopicId');
  forumTopicId = forumTopicId || $this.parents('div[parentCont="actualParent"]').attr('forumTopicId');
  var responseId = $this.attr('responseId');
  var categoryId = $this.attr('categoryId');
  categoryId = categoryId || $this.parents('div[parentCont="actualParent"]').attr('categoryId');
  var responseAuthorId = $this.parents('div[parentCont="actualParent"]').attr('responseAuthorId');//No internationalization
  var forumId = $this.attr('forumId');
  forumId = forumId || $this.parents('div[parentCont="actualParent"]').attr('forumId');
  var itemType = $this.attr('itemType');
  if(itemType != "post") //handle responses and threads
  {
    if(confirm(i18n['zohodiscussions.singlePost.messagefordeletingResponse']))
    {
      var deleteResponse = {};
      if(responseAuthorId == ZUID)
      {
        deleteResponse.responseowner = "true";
      }
      deleteResponse.forumGroupId = forumGroupId;
      deleteResponse.forumTopicId = forumTopicId;
      deleteResponse.categoryId = categoryId;
      deleteResponse.forumId = forumId;
      deleteResponse.responseId = responseId;
      deleteResponse[csrfParamName] = csrfToken;
      doAjaxAction('/deleteForumResponse.do',deleteResponse,function (data)//No internationalization
      {
        if((data) == "SUCCESS")
        { 
          showTipper(i18n['zohodiscussions.generalmessage.responseMovedToTrash'],'info',2000);
          if($location =="moderation")
          {
            var tabPurpose = $('#moderationTabCont').find('li.selected').attr('tabPurpose');
            refreshingPage(tabPurpose);
          }
          else
          {
            refreshSingleTopic(forumTopicId);
          }
        }
      });
    }//if(confirm("Are you sure, you want to delete this response?"))
  }//if(itemType != "post")
  else
  {
  //TODO: post delete. Prompt that all response will be deleted.
    if (confirm(i18n['zohodiscussions.singlePost.messagefordeletingTopic']))
    {
      var deleteOptions = {};
      if(responseAuthorId == ZUID)
      {
        deleteOptions.access = "author";//No internationalization
      }
      deleteOptions.forumGroupId = forumGroupId;
      deleteOptions.forumTopicId = forumTopicId;
      deleteOptions.categoryId = categoryId;
      deleteOptions.forumId = forumId;
      deleteOptions[csrfParamName] = csrfToken;
      doAjaxAction('/deleteTopic.do',deleteOptions,function (data)//No internationalization
      {
        if((data) == "SUCCESS")
        {
          showTipper(i18n['zohodiscussions.generalmessage.topicMovedToTrash'],'info',2000);
          if($location =="moderation")
          {
            var tabPurpose = $('#moderationTabCont').find('li.selected').attr('tabPurpose');
            refreshingPage(tabPurpose);
          }
          else
          {
            refreshSingleTopic(forumTopicId);
          }
        }
      });
     }
   }
}//function deletePost()

function refreshSingleTopic(forumTopicId)
{
	//refresh the content of a single topic in the forum list page.
	//this will be called whenever a forum topic is changed - by adding/deleting a response / thread
	//as well as topic level events like sticky and locking/unlocking.
        var $topicList = $('#topicList');
        if($topicList.length < 1)
        {
            $topicList = $('#topicsList');
        }
        var options = {};
        options.forumTopicId = forumTopicId;
        options.forumGroupId = forumGroupId;
        options.singleTopicRefresh='singleTopicRefresh'; //No internationalization
        var $divToRefresh = $('#eachTopic_'+forumTopicId);//$topicList.find('div[forumTopicId="' + forumTopicId + '"]');
        doAjaxAction('/refreshSingleTopic.do',options, function(data)//No internationalization
        {
            hideLoadingImage();
            $data = $("<div></div>").html(data);
            if($data.find('div.singleTopicCont').length < 1)
            {
                $divToRefresh.remove();
                return false;
            }

            var thisModifiedTime = $data.find('div.singleTopicCont').attr('modifiedtime');
            var endPostModifiedTime =$topicList.find('div.singleTopicCont:last').attr('modifiedtime');
            var $firstSinglePost = $topicList.find('div.singleTopicCont:first');
            var startPostModifiedTime = $firstSinglePost.attr('modifiedtime');
            var shouldScrollTop= false;

            if(thisModifiedTime < endPostModifiedTime)
            {
                $divToRefresh.remove();
            }
            else if(thisModifiedTime > startPostModifiedTime)
            {  
               $data.insertBefore($firstSinglePost);
               $divToRefresh.remove();
               eval($data.find("script").html());
               shouldScrollTop = true;
            }
            else
            {   
                $data.insertBefore($divToRefresh);
                $divToRefresh.remove();
                eval($data.find("script").html());
                shouldScrollTop = true;
            }
            if(shouldScrollTop == true)
            goToTop();

	});//$divToRefresh.load('/getForumTopicList.do?forumTopicId='+forumTopicId, function()
}//function refreshSingleTopic(forumTopicId)


function disablePostButtons()
{
    $('#publishTopic').attr('disabled',true);
    $('#saveDraft').attr('disabled',true);
}
function enablePostButtons()
{
    $('#publishTopic').attr('disabled',false);
    $('#saveDraft').attr('disabled',false);
}

//response pagination

function getprevAndFirstPost($content)
{
    var forumTopicId = $content.parents('div[parentCont="actualParent"]').attr('forumTopicId');
    var options = {};
    options.forumGroupId = forumGroupId
    options.forumTopicId = forumTopicId;
    
    var responseId = $content.attr('recentResponseId');
    if(typeof responseId != "undefined")
    {
        options.responseId = responseId;
        options.modifiedTime = $content.attr('modifiedTime');
        options.currResponseCount = $content.attr('currResponseCount');
    }
    else
    {
        var targetParent = $content.parents('div.listOfResponseLink');
        options.responseId = targetParent.attr('responseId');
        options.modifiedTime = targetParent.attr('modifiedTime');
        options.currResponseCount = targetParent.attr('currResponseCount');
    }
    
    options.toProvide = "First";
    options.currStage = "1";
    doAjaxAction('/getResponse.do',options,function(data)
    {
        var $data = $(data);
        var $currResponseContent = $('#recent_ResPonse_'+responseId);
        if($('#lastResponse_'+forumTopicId).find('div.listOfResponseLink[prev="-1"]').length < 1)
        {
            $data.insertAfter($currResponseContent);
            $currResponseContent.next('div.listOfResponseLink').attr("Prev","-1");
        }
        var $navLoading = $('#navigationLoading_'+responseId);
        if($navLoading.attr('currRequest') == "first")
        {   
            $navLoading.remove();
            $currResponseContent.hide();
            $('#navCont_'+responseId+',#navCont_1_'+responseId).removeClass('navLoading');
            firstOrLastResponse($('#navCont_'+responseId).find('li.imgNavStart'));
        }
        else
        {
            provideResponse($content);
        }
        return;
    });    
}//function getprevAndFirstPost($content)

function provideResponse($content)
{  
    var forumTopicId = $content.parents('div[parentCont="actualParent"]').attr('forumTopicId');
    var responseId = $content.attr('recentResponseId');
    var toProvide = $content.attr('toProvide');
    var options = {};
    options.forumGroupId = forumGroupId;
    options.forumTopicId = forumTopicId;
    options.toProvide = toProvide;
    if(typeof responseId != "undefined")
    {
        options.modifiedTime = $content.attr('modifiedTime');
        options.currResponseCount = $content.attr('currResponseCount');
        options.currStage = $content.attr('currResponsestage');
    }
    else
    {   
        var targetParent = $content.parents('div.listOfResponseLink');
        responseId = targetParent.attr('responseId'); 
        options.modifiedTime = targetParent.attr('modifiedTime');
        options.currResponseCount = targetParent.attr('currResponseCount');
        options.currStage = targetParent.attr('currResponsestage');
    }
    options.responseId = responseId;
    doAjaxAction('/getResponse.do',options,function(data)
    {    
          var $currResponseContent = $('#recent_ResPonse_'+responseId);  
          // now check it new input response data was already loaded or not..
          var $this = $("<div>"+data+"</div>");
          var inputResponseId = $this.find('div.listOfResponseLink').attr('responseId');
          var inputResponseContent = $('#lastResponse_'+forumTopicId).find('div.listOfResponseLink[responseId = "'+inputResponseId+'"]');          
          if(inputResponseContent.length > 0)
          {     
                if(toProvide == "Prev")
                {
                    $currResponseContent.attr("Prev",inputResponseId);
                    inputResponseContent.attr("Next",responseId);
                }
                else if(toProvide == "Next")
                {
                    $currResponseContent.attr("Next",inputResponseId);
                    inputResponseContent.attr("Prev",responseId);
                }
                
          }
          else
          {
              var $data = $($this.html());  
              if(toProvide == "Prev")
              {
                  $data.insertAfter($currResponseContent);
                  var $newResponseContent = $currResponseContent.next('div.listOfResponseLink');
                  $newResponseContent.attr("Next",responseId);
                  $currResponseContent.attr("Prev",inputResponseId);
              }
              else if(toProvide == "Next")
              {
                  $data.insertBefore($currResponseContent);
                  var $newResponseContent = $currResponseContent.prev('div.listOfResponseLink');
                  $newResponseContent.attr("Prev",responseId);
                  $currResponseContent.attr("Next",inputResponseId);  
              }
          }    
         var $navLoading = $('#navigationLoading_'+responseId);
         if($navLoading.attr('currRequest') == "Prev")
         {   
             $navLoading.remove();
             $currResponseContent.hide();
             checkPrevNextResponse($('#navCont_'+responseId).find('li.imgNavPrevious'));
             $('#navCont_'+responseId+',#navCont_1_'+responseId).removeClass('navLoading');
         }
         else if($navLoading.attr('currRequest') == "Next")
         {
             $navLoading.remove();
             $currResponseContent.hide();
             checkPrevNextResponse($('#navCont_'+responseId).find('li.imgNavNext'));
             $('#navCont_'+responseId+',#navCont_1_'+responseId).removeClass('navLoading');
         }
      });  
}//function provideRespones($conent)

function checkPrevNextResponse($content)
{   
    var $contentParent = $content.parents('div.listOfResponseLink');
    var responseId = $contentParent.attr('responseId');
    var toProvide = $content.attr('toProvide');
    
    var currResponse = $contentParent.attr(toProvide);
    
    if(currResponse == "0")
    {   
        var $loading = $('#navigationLoading').clone();
        $loading.attr('id','navigationLoading_'+responseId).attr('currRequest',toProvide);
        var $navCont = $('#navCont_'+responseId);
        $loading.insertAfter($navCont).show();
        $('#navCont_'+responseId+',#navCont_1_'+responseId).addClass('navLoading');
        provideResponse($content);
        return;
    }
    else
    {
        var $newResponseCont = $('#recent_ResPonse_'+currResponse);
        $contentParent.hide();
        $newResponseCont.show();
        setFocusToContainer($newResponseCont.parents('.singleTopicContSel'),false,0);
        if($('#navCont_'+currResponse).is('.navLoading'))
        {   
            $('#navCont_'+responseId+',#navCont_1_'+responseId).removeClass('navLoading');
        }
        if($newResponseCont.attr(toProvide) == "0")
        {  
           var $shouldProvideLink =  $('#navCont_'+currResponse).find('li[toProvide="'+toProvide+'"]');
           provideResponse($shouldProvideLink);
        }
        else
        {
            return;
        }
     }   
}//fucntion checkPrevNextResponse($content)

//if click first or last img
// if click first img which one prev is -1 then that's will be display,
// click last img whick one next is -1 then that's will be display..
function firstOrLastResponse($content)
{   
    var $targetParent = $content.parents('div.listOfResponseLink');
    var toProvide = $content.attr('toProvide');
    var responseId = $targetParent.attr('responseId');
    var forumTopicId = $content.parents('div[parentCont="actualParent"]').attr('forumTopicId');

    var $responaseContainer = $('#lastResponse_'+forumTopicId);
    var $currentOpenedResponse = $('#recent_ResPonse_'+responseId);
    if(toProvide == "First")
    {
        var $firstResponse = $responaseContainer.find('div.listOfResponseLink[Prev="-1"]');
        if($firstResponse.length == 0)
        {  
           var $loading = $('#navigationLoading').clone();
           $loading.attr('id','navigationLoading_'+responseId).attr('currRequest','first');
           var $navCont = $('#navCont_'+responseId);
           $loading.insertAfter($navCont).show();
           $('#navCont_'+responseId+', #navCont_1_'+responseId).addClass('navLoading');
           getprevAndFirstPost($content);
           return;
        }
        $currentOpenedResponse.hide();
        $firstResponse.show();
        setFocusToContainer($('#eachTopic_'+forumTopicId),false,0);
        if($('#navCont_'+responseId).is('.navLoading'))
        {   
            $('#navCont_'+responseId+',#navCont_1_'+responseId).removeClass('navLoading');
        }
        var currResponse = $firstResponse.attr('responseId');
        if($firstResponse.attr('Next') == "0")
        {  
           var $shouldProvideLink =  $('#navCont_'+currResponse).find('li[toProvide="Next"]')
           provideResponse($shouldProvideLink);
        }
    }
    else if(toProvide == "Last")
    {   
        $currentOpenedResponse.hide();
        $responaseContainer.find('div.listOfResponseLink[Next="-1"]').show();
        setFocusToContainer($('#eachTopic_'+forumTopicId),false,0);
    }
}//function firstOrLastResponse($content)


function lightBox(containerId)
{
     $(containerId+" a.lightbox").lightbox(
        {
           'navbarOnTop': true,
           'resizeSpeed' : 150,
           'overlayOpacity': 0.1
        });
    $(window.document).keydown(function (e)
    {
        if(e.keyCode == 27)
        {
            if($('#lightbox').is(':visible'))
            {
                $("#lightbox").hide();
                $("#overlay").hide();
            }
            return false;
        }
     });
}
