/*
 * @title  BlogDiscuss;  client view of the discussion board.
 * @author SB<subrata@thermo.sdsu.edu>, PS
 *
 */
var BlogDiscuss=Class.create({

    CLASSDEF : {
        name:  'BlogDiscuss',
        parent: SuperForm
    },

    initialize: function(oDiv){
        //alert("in constructor");
        this.oDiv = oDiv;

        this.id= 'blogBody';
        this.parentClass().constructor().call(this);

        //alert("after super in constructor");
        this.bMax = true;
        var i=0;
        //this.asNonFieldID[i++] = 'bAnon';
        //this.axNonFieldData['bAnon'] = true; // use it to control anonymous comments
        //
        var j = 0;
        this.asTopic = ['All', 'About TEST', 'Bug Report', 'Daemons', 'Animations', 'Problem Sets', 'Properties', 'First Law','Second Law', 'Steady Systems', 'Unsteady Systems', 'Exergy', 'IC Engines','Gas Turbines', 'Steam Turbines', 'Refrigeration','Air Conditioning', 'Combustion','Equilibrium','Gas Dynamics', 'Other'];


        this.axMsg = [];
        this.axMsg['All'] = 'Display conversations from all topics in chronological order.';
        this.axMsg['About TEST'] = "Blog on TEST - suggestions, criticisms, bug report, what you like, what you don't, etc. Also read comments from the past.";
        this.axMsg['Bug Report'] = 'Report any problem with the daemons, animations, problem and example sets, suggest improvements or new features.';
        this.axMsg['Daemons'] = 'Comment, question, suggestion, about the daemons.';
        this.axMsg['Animations'] = 'Comment, question, suggestion, about the animations.';
        this.axMsg['Problem Sets'] = 'Discussion on fifteen chapters of problems and examples.';
        this.axMsg['Properties'] = "Questions and answers (Q & A) on property evaluation using various material models, different types of properties, different kinds of states. Use of state daemons.";
        this.axMsg['First Law'] = "Energy transfer by different types of work and heat, and energy tranport by mass, the energy balance equation.";
        this.axMsg['Second Law'] = "Meaning of entropy, entropy transfer by heat and transport by mass, entropy generation, and the entropy balance equation.";
        this.axMsg['Steady Systems'] = "Mass, energy, and entropy analysis of closed (light bulb, overall heat engine) and open steady systems (nozzle, turbine, pump, compressor, HX, etc).";
        this.axMsg['Unsteady Systems'] = "Compression or expansion in a piston-cylinder device, heating or cooling of a substance, charging or discharging of  a cylinder are unsteady processes.";
        this.axMsg['Exergy'] = "Meaning of exergy or availability, exergy balance equation, exergetic efficiency, reversible work, rate of irreversibilty, optimization using exergy concepts.";
        this.axMsg['IC Engines'] = "Reciprocating cycles, Otto and Diesel cycle, Stirling and Miller cycles, cold-air standard analysis, different types of fuel. Use of reciprocating daemons.";
        this.axMsg['Gas Turbines'] = "Gas turbines and Brayton cycle, reheat regeneration and other improvements, compressor and turbine efficiency, application to turboject engines, thrust, etc.";
        this.axMsg['Steam Turbines'] = "Steam Turbines and Rankine cycle, reheat, regeneration using closed and open heaters, co-generation, binary cycle, etc.";
        this.axMsg['Refrigeration'] = "Refrigerator, heat pump, and vapor compression refigeration cycle. Cascade refrigeration, chillers, and gas refrigeration.";
        this.axMsg['Air Conditioning'] = "HVAC. Psychrometry, moist air properties, psychrometric processes, cooling, humidification, cooling towers, etc.;";
        this.axMsg['Combustion'] = "Balancing chemical reactions, air fuel ratio, formation enthalpy. Energy and entropy analysis of open and closed combustion chambers, adb. flame temperature, fuel exergy.";
        this.axMsg['Equilibrium'] = "Phase and chemical equilibrium, Gibbs phase rule, chemical potential, minimization of Gibbs function, equilibrium constant, emission calculations using daemons";
        this.axMsg['Gas Dynamics'] = "High speed flow of gas, static, total, and stagnation properties, Mach number, isentropic flow through variable area ducts, nozzles, diffusers, normal shock";
        this.axMsg['Other'] = "If you select this, then please suggest a topic name in the subject box. If there are sufficient requests for a particular topic, we will include it in this column.";

        this.bAnon = true;
        this.render();

    },

    render: function(){

        //writeHeader("Discussion Blog: ", "Expert Answers to Well-Posed Questions");
        //var oThisElement = document.getElementsByTagName("body")[0];
        //var oThisElement = $('blogBody');
        //alert("rending started");
        var oThisElement = this.oDiv;


        // creat title
        var tiltelDivision = document.createElement("div");
        tiltelDivision.innerHTML = this._sGetTitle();
        oThisElement.appendChild(tiltelDivision);


        // create chapter table
        var oBFilter = document.createElement("div");
        oBFilter.setAttribute("id", "topicsDiv");
        oBFilter.innerHTML = this._sGetChapterTable();
        oThisElement.appendChild(oBFilter);
        xAddClass(oBFilter,'left');


        // create blog2 table - discussion HTML
        var oBlog2 = document.createElement("div");
        oBlog2.setAttribute("id", "blogDiv");
        oBlog2.innerHTML = this._sGetDisViewPanel();
        oThisElement.appendChild(oBlog2);
        xAddClass(oBlog2,'right');
        //$('About TEST').checked = true;
        this.bindEvents();
        this.updateBlog(this);
    },




    // chapter row  has been clicked, fetch comments and highlight
    handleCommentBoxClick: function(){
        var args = $A(arguments);
        var e = args[0];
        var oThis = args[1];
        var iComment = args[2];
        if(oThis.bMODERATOR) {
            oThis.bINPUT = true;
            oThis.kCHECKED = iComment;
        }

        //oThis.handleCommentPostClick(oThis, oThis, 0);
        //alert("comment clicked: "+iComment);
    },
    // chapter row  has been clicked, fetch comments and highlight


    handleChapterTRClick: function(){
        var args = $A(arguments);
        var e = args[0];
        var oThis = args[1];
        var sTopic = args[2];
        var sTargetID = oThis.sGetTargetID(e); // only works for the checkbox
        if(oThis.bINPUT) { // user is entering a comment so return;
            oThis.displayMessage("newCourseMsg0"," To select a topic for a comment, click on the checkbox.");
            return;
        }

        //any topic other than All should unselect All
        if(sTopic != 'All'){
            $('All').checked = false;
        }

        // sTopic= sTargetID means checkbox has been clicked, make it cumulative
        if (sTopic != sTargetID){ // click is outside checkbox
            if($(sTopic).checked){ // box is checked, turn it off and reset title
                $(sTopic).checked = false; // turn checkboxes off it is on
                //$('title').innerHTML = 'Instructions for Browsing and Posting on the Thermodynamic Forum';
            }
            else{ // turn checkbox on if is off and turn everything else off
                var n = this.asTopic.length;
                for (var i = 0; i < n; i++){
                    if($(this.asTopic[i]).checked) {
                        $(this.asTopic[i]).checked = false;
                    }
                }
                $(sTopic).checked = true;
                $('title').innerHTML = 'Discussion on '+sTopic;
                //if(sTopic == 'About TEST') $('title').innerHTML = 'General Comments on TEST';
            }
        }
        $('title').innerHTML = this.sGetTitle();
        oThis.highLightChapters();

        //initialize batch etc.
        oThis.iBatch = 1;
        oThis.iSTART = 0;
        oThis.updateBlog(oThis);
    },

    // Create page title based on what is clicked
    sGetTitle: function(){
        var n = this.asTopic.length; var iChecked = 0; var sTitle = 'Discussion '; var sTopic = '';
        for (var i = 0; i < n; i++){
            if($(this.asTopic[i]).checked) {
                iChecked++;
                if(this.asTopic[i] == 'About TEST') sTopic = ' (General Comments) on TEST';
                else if(this.asTopic[i] == 'All') sTopic = ' (Cumulative) on All Topics';
                else if(iChecked == 1)sTopic = 'on '+  this.asTopic[i];
                else if(iChecked > 1 && iChecked <4)sTopic = ', ' + this.asTopic[i];
                //if(iChecked == 1) sTitle += sTopic;
                //else if(iChecked <4 ) sTitle += ', '+ sTopic;
                if(iChecked <4 ) sTitle += sTopic;
            }
        }
        //sTitle += sTopic;
        if(iChecked>3 ) sTitle += ',...';
        return sTitle;

    },

    // instruction button has been clicked, show instructions
    handleInstructionClick: function(){
        /*var args = $A(arguments);
        var e = args[0];
        var oThis = args[1];
        var sTopic = args[2];*/

            this.bINPUT = false;
            $('title').innerHTML = 'Instructions for Browsing and Posting on the Thermodynamic Forum';
            var n = this.asTopic.length;
            for (var i = 0; i < n; i++){
                if($(this.asTopic[i]).checked) {
                    $(this.asTopic[i]).checked = false;

                    xRemoveClass($(this.asTopic[i]+'TR'), 'highLight');
                    xAddClass($(this.asTopic[i] + "TR"),'chapterStyle');
                }
            }

        xRemoveClass($('spinner'),'download');
        var s = "(If this forum page does not look properly formatted, use your browser's reload button. Also, you may try clearing the cache.)";
        s += "<blockquote><b>Browsing the Forum: </b><ol>";
        s += "<li class = 'inst' />Use the <img width = '18' height = '18' style = 'margin-bottom: -5px;' src = 'img/maximize.png' /> toggle button to expand/shrink this page vertically. Try it now on this instruction page.";
        s += "<li class = 'inst' />Click on a topic on the left margin. To switch between topics, click on the topic name, not the checkbox. Comments on selected topic(s) are displayed in a reverse chronological order. An old thread bubbles to the top as soon as anyone responds to that thread. ";
        s += "<li class = 'inst' />You can select multiple topics by clicking the checkboxes or 'All' to display a batch of 100 threads at a time.";
        s += "<li class = 'inst' />To display the next (older) batch, select Older Batch or Newer Batch from the action menu or click on their links at the bottom of a page.  ";
        s += "<li class = 'inst' />Use the <img width = '18' height = '18' style = 'margin-bottom: -5px;' src = 'img/up.png' /> button to toggle through different views - expanded , headers only, thread headers only, and threads only views. ";
        s += "<li class = 'inst' />From the headers only view, you can expand a specific comment by clicking anywhere on the header. Click on the header again to shrink the comment body.";
        s += "</ol>";
        s += "</blockquote>";

        s += "<blockquote><b>Posting a Comment:</b> ";
        s += "<ol><li class = 'inst' />A comment can be a question on a specific topic, a reply to a question, a bug report, or just a comment. ";
        s += "<li class = 'inst' />You must be logged in to post a comment. Even if you post a comment anonymously, the system makes sure only registered TEST users are allowed to post.";
        s += "<li class = 'inst' />To post a new comment on a specific topic, select the topic on the left. ";
        s += "Sometime a comment may belong to more than one topic - for example, to look for a question on a tubine exergy analysis, select open steady and exergy (by clicking the checkboxes) and then search for turbine. ";
        s += "<li class = 'inst' />If you are posting a question, first search the displayed comments to see if a similar question has been already answered. ";
        s += "Click on the thread icon, <img  width = '81' height = '18'  style = 'margin-bottom: -5px;' src = 'img/thread.png' />, which will bring up a simple form with instructions.  ";
        s += "<li class = 'inst' />If you post a question, the moderators will be immediately notified. When an answer to your question is posted, you will be notified through a short email. ";
        s += "<li class = 'inst' />To reply to a post, simply click the Reply link and post your comment. Your comment will be inserted immediately below, allowing back-and-forth discussions on a topic. ";
        s += "</ol>";
        s += "</blockquote>";

        s += "<blockquote><b>Searching the Forum: </b>";
        s += "<ol><li class = 'inst' />Click on one or more relevant topics on the left margin. Cumulative comments on the selected topics are displayed. If you are not sure about the topic, select All.";
        s += "<li class = 'inst' />Type in a search string (turbine for example) and press the Enter key. Only comments containing the search string are displayed.";
        s += "<li class = 'inst' />You can narrow the search by entering additional strings (steam for example).";
        s += "<li class = 'inst' />Search works on the downloaded comments only. To search older comments, you may have to first load an older batch (using the action menu or link at the bottom) and then search again.  ";
        s += "<li class = 'inst' />To clear a search use the <img style = 'margin-bottom: -5px;' src = 'img/clear.png' /> button next to the search box. ";
        s += "</ol>";
        s += "</blockquote>";


        s += "<blockquote><b>Moderating the Forum: </b>";
        s += "<ol><li class = 'inst' />If you would like to be a moderator on one or more specific areas, please send an email to Prof. Bhattacharjee, prof.bhattacharee@gmail.com. Whenever someone posts a comment in your area of expertise, you will receive an email request to respond if the comment is a technical question. ";

        s += "</ol>";
        s += "</blockquote>";



        $('divBlgDis').innerHTML = s;
    },

    // construct the comment array for the selected chapters, called by render and handleInstructoinClick
    updateBlog: function(oThis){

        var asChapter = [];
        var n = oThis.asTopic.length;

        // If 'All' is selected, deselect other, otherwise deselect All
        if($(oThis.asTopic[0]).checked) {
            for (var i = 1; i < n; i++){
                if($(oThis.asTopic[i]).checked) $(oThis.asTopic[i]).checked = false;
            }
        }


        // collect chapter names
        for (var i = 0; i < n; i++){
            if($(oThis.asTopic[i]).checked) {
                asChapter.push(oThis.asTopic[i]);
            }
        }
        if (asChapter.length == 0) {
            oThis.handleInstructionClick();
            oThis.displayMessage("newCourseMsg0", 'Select one or more  topics on the left margin to display their contents.  ');

            asChapter.push('Instructions');
            //return;
        }

        //temporary class to bundle number of comments to be fetched from which chapters
        TempClass = Class.create();

            TempClass.prototype = {
            initialize: function(iOffset, nThread, asChapter) {
                this.iOffset = iOffset;
                this.nThread = nThread;
                this.asChapter = asChapter;
            }
        }
        var sOutJson = (new TempClass(oThis.iSTART, oThis.nTHREADS, asChapter)).toJSONString();

        // make webservice call through SynchronizerT class
        //alert('servet path = '+SERVLETPATH);
        oThis.highLightChapters();
        var oBlogSynch = new SynchronizerT(SERVLETPATH, 'http://resource/', 'Blog', 'BlogTService');
        xAddClass($('spinner'),'download');
        //alert("going to call synch. before to paint the blog now");
        oBlogSynch.commitGeneric(getEmail(), sOutJson, oThis.updateCommentsCallback, 'updateComments', oThis);

    },


    // callback after all the comments arrive, call string construction
    updateCommentsCallback: function() {

        var args = $A(arguments);
        var oSynchronizer = args.shift(); // no use here
        var sJSON = args.shift();  // contains sTimeStamp and status
        var oThis = args.shift();   // want this
        xRemoveClass($('spinner'),'download');
        this.aoComment = [];

        try{
            var oInData = eval("(" + sJSON + ")"); // object containing form data
            oThis.aoComment = oInData.ajoComment; //note how the comment object array is stored in a key called ajoComment
            oThis.sDisBlogContent = oThis.sGetBlogConstructed(oThis.aoComment);
            oThis.bMODERATOR = oInData.bModerator;
            oThis.nUsers = oInData.nUsers;
            oThis.nSites = oInData.nSites;
            oThis.nOnline = oInData.nOnline;
            oThis.ojStats = oInData.ojStats; // number of comments in each category
            //alert("getting stats: "+oThis.ojStats['All']);
        }
        catch(err){
            oSynchronizer = null;
            alert("The operation could not be completed; please check your network connection and try again.");
            return;
        }

        oThis.paintBlog(oThis);
        oSynchronizer = null;
        return;
    },



    // updateBlog brings comments and other permissions, time to draw the canvas, comment string, this.sDisBlogContent, has been already created
    paintBlog: function(oThis){

        oThis.bINPUT = false; // reset so that chapter links work.
        $('statDiv').innerHTML = "No. of Registered Users: "+this.nUsers+"  |  No. of Site Licenses: "+this.nSites+"  |  No. of Users Currently Online: "+this.nOnline;

        if(oThis.bMODERATOR){
            var n = $('actMenu').options.length;
            $('actMenu').options[5] = new Option("Reassign Topics", "Reassign Topics", false, false);

        }
        var bChecked = false;
        for (var i = 0; i < this.asTopic.length; i++){
            $(this.asTopic[i]).disabled = false;
            $(this.asTopic[i]+'TR').disabled = false; //topics enabled
            if($(this.asTopic[i]).checked) bChecked = true;
            $(this.asTopic[i]+'Stats').innerHTML =' ('+ oThis.ojStats[oThis.asTopic[i]]+')';
        }
        if(bChecked){
            this.paintPageNo(this.sDisBlogContent,this.iCOMMENTSPERPAGE,1); // this is the main routine.
            if($('fSearch').value != '') this.searchBlog();
        }
    },

    //--Filter Table-----------
    _sGetChapterTable:function(){
        var s="<table id='chapterTable' class='filterBlog' align='left' >";
        s += "<tr class='filterHeader' align='center'><td><input id='chapterB' type='button' value='Instructions' /><div id='spinner' >&nbsp;</div></td></tr>";
        for(var i = 0; i< this.asTopic.length; i++){
            s += "<tr class = 'chapterStyle' id='" + this.asTopic[i] + "TR" + "'><td><input id='" + this.asTopic[i] + "' type='checkbox' />" + this.asTopic[i] + "<span id = '"+ this.asTopic[i] + "Stats' class = 'stats'> ()</span>" +"</td></tr>";
        }
        s += "</table>";
        return s;
    },


    // slightly modified by taking out the course name...
    _sGetTitle: function(){
        var s = "<div id = 'statDiv' class='statDiv'>Access Statistics:</div> ";
        s += "<table class = 'headerBlog' cellpadding='0' cellspacing='0' border='0'>";
        s += "<tr><td colspan='2' align='left' width='100%'><div id='title' class='title'>Community Forum: <i>Questions, Answers, and Pedagogic Discussions</i></div></td></tr>";
        s += "<tr><td colspan='2' align='left' width='100%'><div id='newCourseMsg0'>&nbsp;</div></td></tr>";
        s += "</table>";
        return s;
    },




    //post a new thread, or just a reply (identified by k), also send a notification, previously handleReplyPostClick
    handleCommentPostClick: function(){
        var args = $A(arguments);
        var e = args[0]; // first arg is the event, second is this
        var oThis = args[1];
        var k = args[2]; // k is the comment index (0-200)to which we are replying
        var bReassign = args[3]; //when called by handleShowBlogChange()
        // test validity of the writer
        var sSign = '';
        sSign = $('fromText'+k).value.trim();
        if(sSign == 'Guest') $('fromText'+k).value = '';
        if($('anonBox'+k).checked == false && $('fromText'+k).value == ''){
        //if(getName().trim() == 'Guest' || getName().trim() == ''){
            alert("You must enter your name in the From field or check the Anonymous checkbox.")
            return;
        }
        var iAccessLevel = getAccessLevel(); // 0 (no account or expired), 5 (guest), 10, 15
        if (oThis.bMODERATOR)  iAccessLevel = 20;

        // get the raw comment body, signature, type, etc.
        var sBody = '';
        var sType = 'q';
        if($('fReply'+k)) {
            sBody = $('fReply'+k).value.trim();
            if(oThis.bCommentFlagged (sBody)) return;
            sBody = sBody.replace(/&/g,"&#38;"); // & creates xhr problems.
            sSign = $('fromText'+k).value.trim();
            if(oThis.bCommentFlagged (sSign)) return;

            if ($('aRad'+k).checked) sType = 'a';
            if ($('cRad'+k).checked) sType = 'c';
        }

        var iPID = 0;

        // collect chapter names, All is not a valid topic, used for thread and reassigning topics
        var asChapter = [];

        if($(oThis.asTopic[0]).checked) $(oThis.asTopic[0]).checked = false;

        var n = this.asTopic.length;
        for (var i = 0; i < n; i++){
            if($(oThis.asTopic[i]).checked) {
                asChapter.push(oThis.asTopic[i]);
            }
        }

        if(k == oThis.iTHREAD){// treat thread differently

            var sSubject = $('fSubject'+k).value.trim();
            if(oThis.bSubjectFlagged (sSubject)) return;

            if (asChapter.length == 0) {
                oThis.displayMessage("newCourseMsg0", 'Error: Select one or more appropriate topics that your comment belongs to and try again.  ');
                return;
            }
            if (asChapter.length > 3) {
                oThis.displayMessage("newCourseMsg0", 'Error: A comment cannot belong to more than 3 chapters. Please select one or two topics that best classify your comment.  ');
                return;
            }

            // now construct the comment object
            var oComment = new Comment(0, 0, iPID, 0, iAccessLevel, asChapter,  oThis.encodeBlogString(sSubject), oThis.encodeBlogString(sBody),  oThis.encodeBlogString(sSign), sType);
            var sCommentJson = oComment.toJSONString();

            // note the web service is changed here although the webaplicaiton is the same.
            var oBlogSynch = new SynchronizerT(SERVLETPATH, 'http://resource/', 'Blog', 'BlogTService');
            xAddClass($('spinner'),'download');//start spinner
            $('post'+k).disabled = true; // no more active button
            oThis.k = k;
            oBlogSynch.commitGeneric(getEmail(), sCommentJson, oThis.appendCommentCallback, 'appendThread', oThis);

        }

        else{ //post a reply, or the superModerator is reassigning topics
            var sHead = $('h' + k).innerHTML;

            //extract iPID = comment id of the post to which reply is being posted and construct subject
            var d = []; var iCID = -1;
            d = sHead.match(/#\d+\]/); // find #345] and then extract 345.
            if(d != null){
                var sCID = d[0];
                iCID = sCID.substring(1,sCID.length-1);
            }
            if(iCID>-1) sSubject = 'Response to #'+iCID+'.';
            iPID = iCID;


            // now create the comment object
            //var oComment = new Comment(0, 0, iPID, 0, iAccessLevel, asChapter, sSubject, sBody, sSign, sType);
            var oComment = new Comment(0, 0, iPID, 0, iAccessLevel, asChapter,  oThis.encodeBlogString(sSubject), oThis.encodeBlogString(sBody),  oThis.encodeBlogString(sSign), sType);
            var sCommentJson = oComment.toJSONString();

            var oBlogSynch = new SynchronizerT(SERVLETPATH, 'http://resource/', 'Blog', 'BlogTService');
            if(bReassign){
                if(asChapter.length == 0){ alert("No topic selected."); return;}
                oComment = new Comment(iCID, 0, iPID, 0, iAccessLevel, asChapter,  oThis.encodeBlogString(sSubject), oThis.encodeBlogString(sBody),  oThis.encodeBlogString(sSign), sType);
                sCommentJson = oComment.toJSONString();

                oBlogSynch.commitGeneric(getEmail(), sCommentJson, oThis.reassignChaptersCallback, 'reassignChapters', oThis);
                //alert('call web service with k = '+ oThis.kCHECKED+'chpater= '+asChapter.toString()+" json = "+sCommentJson);
                return;
            }
            xAddClass($('spinner'),'download');//start spinner
            $('post'+k).disabled = true; // no more active button
            oThis.k = k; // save k for callback.
            oBlogSynch.commitGeneric(getEmail(), sCommentJson, oThis.appendCommentCallback, 'appendReply', oThis);
        }

   },

    // callback after a thread is created or a reply is posted
    appendCommentCallback: function() {
        var args = $A(arguments);
        var oSynchronizer = args.shift(); // no use here
        var sJSON = args.shift();  // contains sTimeStamp and status
        var oThis = args.shift();   // want this
        oThis.bCommitFlag = false;
        xRemoveClass($('spinner'),'download');//stop spinner
        for (var i = 0; i < oThis.asTopic.length; i++) {
            $(oThis.asTopic[i]).disabled = false; //topics enabled
            $(oThis.asTopic[i]+'TR').disabled = false; //topics enabled
        }
        if($('post'+oThis.k)) $('post'+oThis.k).disabled = false; // no more active button

        try{
            var oInData = eval("(" + sJSON + ")"); // object containing form data
            //alert("the error after posting is: "+oInData.iError);
            if(oInData.iError == 0) {
                oThis.updateBlog(oThis);
                xAddClass($('divThread'),'hide');

            }
            else alert("A problem has been encountered in posting/editing/deleting the comment. Please make sure that you are logged into TEST and are authorized to perform this action. Only registered TEST users are allowed to post comments. To sign up, go to the TEST home page and use the Create An Account link.")

        }
        catch(err){
            oSynchronizer = null;
            alert("The operation could not be completed; please check your network connection and try again.");
            return;
        }

        oSynchronizer = null;
        return;
    },

    // callback after a thread is created or a reply is posted
    reassignChaptersCallback: function() {
        var args = $A(arguments);
        var oSynchronizer = args.shift(); // no use here
        var sJSON = args.shift();  // contains sTimeStamp and status
        var oThis = args.shift();   // want this
        oThis.bCommitFlag = false;
        for (var i = 0; i < oThis.asTopic.length; i++) {
            $(oThis.asTopic[i]).disabled = false; //topics enabled
            $(oThis.asTopic[i]+'TR').disabled = false; //topics enabled
        }
        //if($('post'+oThis.k)) $('post'+oThis.k).disabled = false; // no more active button

        oThis.bINPUT = false;
        oThis.kCHECKED = 0;
        //alert("back after reassign "+sJSON);
        try{
            var oInData = eval("(" + sJSON + ")"); // object containing form data
            if(oInData.iError == 0) {
                oThis.updateBlog(oThis);
                //xAddClass($('divThread'),'hide');
                oThis.displayMessage("newCourseMsg0", ' Selected thread has been regrouped successfully.');


            }
            else alert("A problem has been encountered in posting/editing/deleting the comment. Please make sure that you are logged into TEST and are authorized to perform this action. Only registered TEST users are allowed to post comments. To sign up, go to the TEST home page and use the Create An Account link.")

        }
        catch(err){
            oSynchronizer = null;
            alert("The operation could not be completed; please check your network connection and try again.");
            return;
        }

        oSynchronizer = null;
        return;
    },

    // called by handleChapterTRClick
    highLightChapters: function(){
        // collect chapter names
        var asChapter = [];
        var n = this.asTopic.length;
        //alert('in hightlight after a click?')
        for (var i = 0; i < n; i++){
            if($(this.asTopic[i]).checked) {
                xRemoveClass($(this.asTopic[i] + "TR"),'chapterStyle');
                xRemoveClass($(this.asTopic[i] + "TR"),'mildHighLight');
                xAddClass($(this.asTopic[i] + "TR"),'highLight');
            }
            else {
                xRemoveClass($(this.asTopic[i] + "TR"),'highLight');
                xAddClass($(this.asTopic[i] + "TR"),'chapterStyle');
            }
        }
    },

    // mouse over chapter name, highlight and tooltip
    highLightTR: function(){
        var args = $A(arguments);
        var e = args[0];
        var oThis = args[1];
        var sTopic = args[2];
        xRemoveClass($(sTopic+'TR'), 'chapterStyle');
        xAddClass($(sTopic+'TR'), 'mildHighLight');
        oThis.displayMessage("newCourseMsg0",this.axMsg[sTopic]);
    },
    // opposite of highLightTR
    deHighLightTR: function(){
        var args = $A(arguments);
        var e = args[0];
        var oThis = args[1];
        var sTopic = args[2];
        //alert('leaving: '+$(sTopic+'TR').checked  );
        xRemoveClass($(sTopic+'TR'), 'mildHighLight');
        if(!$(sTopic).checked) xAddClass($(sTopic+'TR'), 'chapterStyle');
        oThis.removeMessage("newCourseMsg0");
    },

//-------------------------identical methods below from BlogDiscussS.js-------------------------------------
// small differences: no reload button
    bindEvents: function(){

        this.superBindEvents();
        $('maxImageDis').onclick = this.handleMaxDisClick.bindAsEventListener(this, this);
        var oFE;
        for (var i = 0; i< this.asTopic.length; i++) {
            oChapterTR = $(this.asTopic[i]+'TR');
            oChapterTR.onmouseover = this.highLightTR.bindAsEventListener(this, this, this.asTopic[i]);
            oChapterTR.onmouseout = this.deHighLightTR.bindAsEventListener(this, this, this.asTopic[i]);
            oChapterTR.onclick = this.handleChapterTRClick.bindAsEventListener(this, this, this.asTopic[i]);
        }

        this.handleMessage('toggleImage3', 'newCourseMsg0',oMSG.msg['blog-imgRow']);
        this.handleMessage('toggleImage2', 'newCourseMsg0',oMSG.msg['blog-imgRow']);
        //this.handleMessage('reload', 'newCourseMsg0',oMSG.msg['resource-reload']);
        this.handleMessage('tdBlgSubject','newCourseMsg0', oMSG.msg['blog-subject']);
        this.handleMessage('clearImage','newCourseMsg0','Click to initialize after a search is complete.');
        this.handleMessage('maxImageDis','newCourseMsg0','Click to maximize/reduce the size of the discussion blog panel. ');


        this.handleMessage('threadImage','newCourseMsg0','Show/Hide the thread creation panel. Use this button to start a new thread/comment on any topic from the left.');
        this.handleMessage('upImage','newCourseMsg0','Toggle between thread and comment views (you may also directly click on a thread).');
        this.handleMessage('tdBlgSearch','newCourseMsg0', oMSG.msg['blog-search']);
        this.handleMessage('actMenu','newCourseMsg0', 'Select an action item (some requires selection of a comment first).');
        this.handleMessage('showRange','newCourseMsg0', "The numbers in red are the new comment id's, posted since you last visited the blog. ");
        this.handleMessage('chapterB','newCourseMsg0', "To display messages on a particular topic, select one or more topics listed below.");

        //$('reload').onclick = this.handleReload.bind(this);
        $('fSearch').onkeypress = this.handleSearchEnter.bindAsEventListener(this,this,'statusButt');
        $('fSearch').onclick = this.handleSearchClick.bindAsEventListener(this, this);
        $('actMenu').onchange = this.handleShowBlogChange.bindAsEventListener(this, this);
        $('actMenu').onclick = this.handleShowBlogClick.bindAsEventListener(this, this);
        $('clearImage').onclick = this.handleClearSearch.bindAsEventListener(this,this);
        $('upImage').onclick = this.handleSwitchView.bindAsEventListener(this,this);
        $('threadImage').onclick = this.handleThreadPanelView.bindAsEventListener(this,this);
        $('chapterB').onclick = this.handleInstructionClick.bindAsEventListener(this,this);
        $('newLink').onclick = this.handleNewerBatch.bindAsEventListener(this,this);
        $('oldLink').onclick = this.handleOlderBatch.bindAsEventListener(this,this);
    },


    // toggles through thread view panel, almost like handleReply with a high comment index number..
    paintThreadPanelView: function(oThis){

        var oThread = $('divThread');
        if (!xHasClass(oThread,'hide')) {
            xAddClass(oThread,'hide');
            return;
        }
        // create the content and listeners
        xRemoveClass(oThread,'hide');
        var k = oThis.iTHREAD; // designated thread target.
        oThread.innerHTML = oThis.sGetReplyHTML(oThis, k);
        if(oThis.bAnon) {
            xRemoveClass($('anonTD'+k), 'hide');
            $('anonBox'+k).onclick = oThis.handleAnonClick.bindAsEventListener(oThis, oThis, k);
        }

        $('discard'+k).onclick = oThis.handleDiscardClick.bindAsEventListener(oThis, oThis, oThread);
        $('post'+k).onclick = oThis.handleCommentPostClick.bindAsEventListener(oThis, oThis, k);
        $('post'+k).value = 'Post New Thread';
        $('aRad'+k).disabled = true;
        $('fReply'+k).onfocus = this.handleClearText.bindAsEventListener(oThis,'fReply'+ k,oThis.sInitThreadContent);
        $('fromText'+k).value = getName();

        this.bINPUT = true;
        //for (var i = 0; i < oThis.asTopic.length; i++) $(oThis.asTopic[i]+'TR').disabled = true;

    },

    // toggles through thread view panel, almost like handleReply with a high comment index number..
    handleThreadPanelView: function(){
        var args = $A(arguments);
        var e = args[0];
        var oThis = args[1];
        e.cancelBubble = true;
        if (e.stopPropagation) e.stopPropagation();

        oThis.paintThreadPanelView(oThis);
    },

    handleReload:   function (){
        this.displayMessage("newCourseMsg0", " Accessing ClassTA server: Loading in progress...");
        this.disRenderS();
    },

    handleAnon: function (){
        var args = $A(arguments);
        switch(args.length) {
            case 2:
                var e = args.shift();     // Event object
                var oThis = args.shift(); // Not used
                break;
            default:
                alert("error: call to BlogDiscussFormS::handleCommentPost with improper number of arguments");
                return;
        }
	if (e.stopPropagation) e.stopPropagation();
        e.cancelBubble = true;
    },


    //storeData from superform calls this to pack the blog objects and then convert those into jsons
    preProcess: function(){
        //this.axNonFieldData['inpBlog'] = this.inpBlog.toJSONString();
    },



    // stop propagation for click so that onchange can work
    handleShowBlogClick: function(){
        var args = $A(arguments);
        var e = args.shift();     // Event object
        var oThis = args.shift();
        e.cancelBubble = true;
        if (e.stopPropagation) e.stopPropagation();
    },

    // stop propagation if search box is clicked for focus
    handleSearchClick: function(){
        var args = $A(arguments);
        var e = args.shift();     // Event object

        var oThis = args.shift();
        e.cancelBubble = true;
        if (e.stopPropagation) e.stopPropagation();
    },



    //return comment id from a header string only if names match
    iGetCID: function(sHead){
        var iCID = -1;
        var asDigits = sHead.match(/#\d+\]/); // find #345] and then extract 345.
        //var asDigits = sHead.match(/#\d+/); // find #345] and then extract 345.
        if(asDigits != null){
            var sID = asDigits[0];
            iCID = sID.substring(1,sID.length-1);
            //iCID = sID.substring(1,sID.length);
        }
        //alert("icd = "+iCID);
        return iCID;
    },





    //do nothing when tab is closed
    handleTabclose: function(){
    },
    // store locally only
    handleKeyup: function(oThis){
        oThis.storeData();
    },
    // onfocus calls this to set label back to normal
    resetLabelStyle: function (sLabel) {
        $(sLabel).className = 'label3';
    },

    // maximize block and terminate event bubble
    handleMaxDisClick: function(){
        //alert("handle 445");
        var args = $A(arguments);
        var e = args[0];
        var oThis = args[1];
        e.cancelBubble = true;
        if (e.stopPropagation) e.stopPropagation();
        //oThis.disBlog.bMax = oThis.bMaxRow('divBlgDis', !oThis.disBlog.bMax);
        oThis.bMax = oThis.bMaxRow('divBlgDis', !oThis.bMax);
        this.storeData();
    },


    //Removing 'show' since it messes up firefox.
    bMaxRow: function (sMaxDivID, bMax) {
        var eDiv = $(sMaxDivID);
        //alert('max min: '+bMax);
        if (bMax) {
            xRemoveClass(eDiv,'blog');
            xAddClass(eDiv,'blogs');
        }
        else {
            xRemoveClass(eDiv,'blogs');
            xRemoveClass(eDiv,'show');
            xAddClass(eDiv,'blog');
        }

        return bMax;
    },

    //-- discussion blog html-----------
    _sGetDisViewPanel: function(){


        //var sStyled = this.sGetBlogStyled(sRaw);
        var sToggleImage = this.sExpandedImageName;
        //this.disBlog.bMax = true;
        this.dbMax = true;
        var sToogleClass = 'show';
        var sBlogClass = 'blog';
        if(this.bMax) sBlogClass = 'blogs';
        //if(!this.bDisBlk){sToggleImage = this.sCollapsedImageName; sToogleClass = 'hide';}

        var s = "<table class = 'header settings' id='DisViewPanel' cellpadding='3' cellspacing='0' border = '0'>";
        s += "<tr id='rowLinkBlog2' class='settingslink'>"; //not clickable..
        s += "<td width=30  ><img src = "+this.sUpImageName+" border='0' valign='bottom' style='margine-left:5px;' id = 'upImage' /></td>";
        s += "<td width='20%' ><label style='color:black;' id= 'showRange'> </label></td>";


        s += "<td width=81><img src = "+this.sThreadImageName+" border='0' valign='bottom' style='margine-left:5px;' id = 'threadImage' /></td>";
        s += "<td align='lef' valign='center'  width='28%' id='tdBlgShow'>";
        s += "<select id='actMenu' name='actMenu' class='actMenu' ><option>Action Menu</option><option>Newest Comments (Batch-1)</option><option>Older Comments (Batch+)</option><option>Newer Comments (Batch-)</option><option>Post a New Comment(Thread)</option></select></td>";

        s += "<td align='right' valign='center'  width='27%' id='tdBlgSearch'>";
        s += "<label id='searchLabel' > Search: </label><input id='fSearch' name='fSearch' type='text' size='15' style = 'height:12px; font: .9em;' /></td><td align='left' valign='center'  width='15' id='tdClearImage'><img src = "+this.sClearImageName+" border='0' valign='center' id = 'clearImage' class='show'  /></td>";

        s += "<td width='20' align='right' ><img src = "+this.sMaxImageName+" border='0' class = '"+sToogleClass+"' id='maxImageDis' /></td>";
        s += "</tr>";

        s += "<tr><td width='100%' id='vRowBlog2' class= "+sToogleClass+ " colspan = '7'>";

        //-----collpasible Blog2 table ----------------------------------------------------------------



        "<table  id='noid'  width='100%' cellpadding='0' cellspacing='0' border='0'  align='left'>";
        s += "<tr><td  colspan='7' width='100%'><div id = 'divThread' class='replyDiv thread hide'></div><div id='divBlgDis' class='"+sBlogClass+" '>";
        s += "</div></td></tr>";
        s += "<tr><td align = 'left' id='newLink' class= 'link' colspan = '4'>Newer Batch..</td><td colspan = '3' align = 'right'  id='oldLink' class= 'link' >Older Batch..</td></tr>";
        s += "</table></td></tr>";
        s += "</table>";
        return s;
    }
});

