function TextDIManager(){
    // logDebug("TextDIManager");
    bindMethods(this);
    this.title = '';
    this.user_info = {};
    this.draft_headers = [];
    this.textdi_info = {};
    this.req = loadJSONDoc('getTextDIJsonData');
    this.req.addCallbacks(this.process,this.fetchError)
}

TextDIManager.prototype.createExpandShrinkNodes = function(){
    //logDebug("DecisionItemManager.prototype.createExpandShrinkNodes");
    if (document.getElementById('expand-top'))
       return
    this.expandShrinkManagerDisabled = false;
    var expand = A({'class':'expand-shrink-but'}, IMG({'src':'expand_icon.gif'}),"Expand All")
    addToCallStack(expand, 'onclick', this.expandAll);
    var shrink = A({'class':'expand-shrink-but'},IMG({'src':'collapse_icon.gif'}),"Shrink All")
    addToCallStack(shrink, 'onclick', this.shrinkAll)
    appendChildNodes($('expand-shrink-top'),
       SPAN({'id':'expand-top','class':'hideNode'},expand),
       SPAN({'id':'shrink-top','class':'hideNode'},shrink));

    var expand = A({'class':'expand-shrink-but'}, IMG({'src':'expand_icon.gif'}),"Expand All")
    addToCallStack(expand, 'onclick', this.expandAll);
    var shrink = A({'class':'expand-shrink-but'},IMG({'src':'collapse_icon.gif'}),"Shrink All")
    addToCallStack(shrink, 'onclick', this.shrinkAll)
     appendChildNodes($('expand-shrink-bottom'),
        SPAN({'id':'expand-bottom','class':'hideNode'}, expand),
        SPAN({'id':'shrink-bottom','class':'hideNode'}, shrink));
}

TextDIManager.prototype.process = function(dis){
   //logDebug("DecisionItemManager.prototype.process");

    this.req = false;
    this.title = dis.title
    this.user_info = dis.user_info
    this.draft_headers = dis.draft_headers
    this.textdi_info = dis.textdi_info
    this.can_add_draft = dis.can_add_draft
    this.draft_obj = []
    for ( var i = 0; i < this.draft_headers.length ; i++){
        if (this.draft_headers[i] && typeof this.draft_headers[i] == 'object'){
            this.draft_headers[i]['draft_no'] = i + 1
        }
        this.draft_obj[i] = new Draft(this, this.draft_headers[i])
    }
    this.render(); 
    this.createExpandShrinkNodes()
    this.expandShrinkManager();
    

}
TextDIManager.prototype.fetchError = function(err){
    //alert(err)
}

TextDIManager.prototype.getActiveDraft = function(obj,states){
    for (var i=0;i<this.draft_headers.length;i++){
        if(isIn(this.draft_headers[i].status,
                     states) && this.draft_obj[i] != obj)
        {
            result = {}
            result['title'] = this.draft_headers[i].title
            result['state'] = this.draft_headers[i].status
            return result

        }

    }
    return false;

}


TextDIManager.prototype.render = function(){
    // logDebug('TextDIManager.prototype.render');
    var title = H1({'id':'textdi-title'}, this.title)
    var textdi_info = SPAN({'class' : 'formHelp'}, ' Phase ' + this.textdi_info.phase + ' duration ' + this.textdi_info.duration + ' days end date: ' + this.textdi_info.end_date)
        var top_controller = TABLE({'id' : 'top-controler-table'},TBODY(null, TR(null, TD({'id' :
        'expand-shrink-top'}, ''), TD({'id' : 'add-draft-top'}, ''))))
    
    var drafts = DIV({'id' : 'drafts'}, '')
    var bottom_controller = TABLE({'id' : 'bottom-controler-table'}, TBODY(null,TR(null, TD({'id' :
        'expand-shrink-bottom'}, ''), TD({'id' : 'add-draft-bottom'}, ''))))
   
    appendChildNodes($('region-content'), title, textdi_info, top_controller,
                                                               drafts, bottom_controller)
                    
      this.expandShrinkManager();
    for (var i = 0; i < this.draft_obj.length; i++){
        var draft = this.draft_obj[i].render();
        appendChildNodes($('drafts'), draft);
        if (this.draft_obj[i].getStatus() == "public" ){
            this.draft_obj[i].expand()
        }
    }
    if (this.draft_obj.length > 0)    
    this.draft_obj[this.draft_obj.length - 1].expand()

}

TextDIManager.prototype.getPrevDraft = function(obj){
    //logDebug('TextDIManager.prototype.getPrevDraft ');
    if (!obj || !obj instanceof Draft){
        //logDebug("TextDIManager.prototype.getPrevDraft calling object Null");
        return null;
    }
    //logDebug("TextDIManager.prototype.getPrevDraft called by", obj);
    var i = 0; 
    for (i = 1;i < this.draft_obj.length; i++){
        if (this.draft_obj[i] === obj){
            return this.draft_obj[i-1];
        }
    }
    if (this.draft_obj.length > 0){
        this.draft_obj[this.draft_obj.length - 1 ].fetchFullDraft()
    }
    return null

}

TextDIManager.prototype.getNextDraft = function(obj){
    //logDebug('TextDIManager.prototype.getNextDraft')
    if (!obj || !obj instanceof Draft){
        //logDebug("TextDIManager.prototype.getNextDraft calling object Null");
        return null;
    }
    //logDebug("TextDIManager.prototype.getNextDraft called by", obj);
    var i = 0; 
    for (i = 0;i < (this.draft_obj.length - 1); i++){
        if (this.draft_obj[i] === obj){
            return this.draft_obj[i+1]
        }
    }
    return null
}

TextDIManager.prototype.showMessage = function(obj,message){
    return
    debugger
    if (!obj || !obj instanceof Draft){
        //logDebug("TextDIManager.prototype.getNextDraft calling object Null");
        return null;
    }
        if (this.message){
        swapDOM($('textdi-message'),null)
        this.message = null
    }
    this.message = DIV({'id':'textdi-message','style':'backround:red'},message)
    roundElement(this.message,{'corners':'all'})
    swapDOM(obj.render(),this.message,obj.render())

}
TextDIManager.prototype.expandAll = function(){
    //logDebug('TextDIManager.prototype.expandAll')
    this.expandShrinkManagerDisabled = true; 
    for (var i = 0; i < this.draft_obj.length; i++){
        this.draft_obj[i].expand()
    }
    this.expandShrinkManagerDisabled = false;
    this.expandShrinkManager()
}

TextDIManager.prototype.shrinkAll = function(){
    //logDebug('TextDIManager.prototype.shrinkAll ');
    this.expandShrinkManagerDisabled = true;
    for (var i = 0; i < this.draft_obj.length; i++){
        this.draft_obj[i].shrink()
    }
    this.expandShrinkManagerDisabled = false;
    this.expandShrinkManager()
}


TextDIManager.prototype.expandShrinkManager = function(){
    //logDebug("TextDIManager.prototype.expandShrinkManager");
    if (this.expandShrinkManagerDisabled)
        return;

    var expand = false;
    var shrink = false;
    for (var i = 0;i < (this.draft_obj.length - 1) ;i++){
        if (this.draft_obj[i].isVisible()){
           shrink = true;
        }
        else {
            expand = true;
        }

    }
    if (shrink){
          //logDebug("DecisionItemManager.prototype.expandShrinkManager:Showing shrink all Button");
          $('shrink-top')?$('shrink-top').style.display = "inline":false
          $('shrink-bottom')?$('shrink-bottom').style.display = "inline":false;
    }
    else{
             //logDebug("DecisionItemManager.prototype.expandShrinkManager:Hiding shrink all Button");
             $('shrink-top')?$('shrink-top').style.display = "none":false;
             $('shrink-bottom')?$('shrink-bottom').style.display = "none":false
    }
    if (expand){
             //logDebug("DecisionItemManager.prototype.expandShrinkManager:Showing Expand All Button");
             $('expand-top')?$('expand-top').style.display = "inline":false
             $('expand-bottom')?$('expand-bottom').style.display = "inline":false

    }
    else{
             //logDebug("DecisionItemManager.prototype.expandShrinkManager:Hiding Expand All Button");
             $('expand-top')?$('expand-top').style.display = "none":false;
             $('expand-bottom')?$('expand-bottom').style.display = "none":false;
    }

}



function Draft(parent,headers){
    //logDebug('Draft');
    bindMethods(this);
    this.parent = parent;
    this.headers = headers;
    this.clauses = [];
    this.replies = [];
    this.status = this.headers.status?this.headers.status:'private';
    this.__visible = false;
    this.__fetched = false;
    this.prefix = Math.round(Math.random() * 10000);
    this.summary =
             DIV({'id':this.prefix+'summary','class':'draft-summary'})
    if(this.headers.media_uri){
        media_slot = DIV({'id':this.prefix + 'media-slot', 'class' :
            'media-slot'},A({'href':this.headers.media_uri, 'target':'blank'},'Download'))
        appendChildNodes(this.summary,media_slot)
        

    }
    this.getAvgRating()
    this.getUserRating()
    this.registerUserRatingUpdateCallback()
    var summary = SPAN(null)
    summary.innerHTML = this.headers.summary.replace(/\n/g,'<br>')
    appendChildNodes(this.summary,summary)
    this.clauses_slot = DIV({'id':this.prefix + 'clauses', 'class':'hideNode'},'')
    
    this.replies_slot = DIV({'id':this.prefix + 'replies'})
    var reply_manager_headers = {}

    reply_manager_headers['get_reply_uri'] = this.headers.reply_uri
    reply_manager_headers['reply_count'] = this.headers.no_of_replies
    reply_manager_headers['post_reply_url'] = this.headers.post_reply_url
    reply_manager_headers['can_reply'] = this.headers.can_reply

    this.reply_manager = new ReplyManager(this,reply_manager_headers)
    appendChildNodes(this.replies_slot,this.reply_manager.render())
    this.menu_slot = DIV({'id': this.prefix+'menu','class':'draft-menu'},'')

    this.show_full_draft =  SPAN({'id':this.prefix+'full-draft-but','class':'full-draft-button'},
                            'Show Full Draft')
    addToCallStack(this.show_full_draft,'onclick',this.showFullDraft)
       
    this.show_summary =
                            SPAN({'id':this.prefix+'summary','class':'draft-show-summary hideNode'},
                            'Show Summary')
    addToCallStack(this.show_summary, 'onclick',this.showSummary)
        
    this.print_button = SPAN({'id':this.prefix+'print-button','class':'print-button'},
                            'Print')
    addToCallStack(this.print_button,'onclick',this.print)
        
    this.show_amendments = SPAN({'id':this.prefix+'show-ameendments','class':'show-ammedments'},
                            'Show Comments')
    addToCallStack(this.show_amendments,'onclick',this.showFullDraft )
        
     this.user_rating= SPAN({'id':this.prefix+'draft-user-rating','class':'draft-user-rating','style':'text-decoration:none;cursor:default'},
                               this.getUserRating())

     appendChildNodes(this.menu_slot, this.show_full_draft,
                      this.show_summary, this.print_button,
                      //this.show_amendments,
                      this.getEditStatusWidget(),
                      this.getNoReplies(),
                      this.user_rating)
  
        
        
}
Draft.prototype.print = function (){
    /* this.print_window =
    window.open('',
                'Print Draft',
                'status=yes, scrollbars=yes,copyhistory=no,resizable=yes')
    
    this.print_window.print()
    this.print_window.close()*/
    window.print()

}
Draft.prototype.fetchFullDraft = function (){
    if (this.fetched)
         return
    this.req = loadJSONDoc(this.headers.fulldraft_uri); 
    this.req.addCallbacks(this.process,alert); //logFatal
    this.reply_manager.fetch()
    this.fetched = true ;

}

Draft.prototype.registerUserRatingUpdateCallback = function(){
    if (this.user_rating && this.avg_rating){
        this.user_rating.registerCallback('process_submit',this.avg_rating.getRating)
        return true
    }
    return false
}

Draft.prototype.showFullDraft = function (){
    if (!this.fetched)
        this.fetchFullDraft()
    this.clauses_slot.style.display = 'block'
    this.summary.style.display = 'none'
    this.show_summary.style.display = 'inline'
    this.show_full_draft.style.display = 'none'

}

Draft.prototype.showSummary = function (){
    if (!this.fetched)
        this.fetchFullDraft()
    this.clauses_slot.style.display = 'none'
    this.summary.style.display = 'block'
    this.show_summary.style.display = 'none'
    this.show_full_draft.style.display = 'inline'

}

Draft.prototype.process = function(clauses){
    this.clauses = []
    //logDebug('Draft.prototype.process');
    for (var i =0 ; i <clauses.length; i++){
        this.clauses[i] = new Clause(this,clauses[i]);
        appendChildNodes(this.clauses_slot, this.clauses[i].render() );
    }
    
}

Draft.prototype.replyAdded = function (){
    //debugger
    this.headers.no_of_replies = Number(this.headers.no_of_replies) + 1
    swapDOM($(this.prefix+'draft-replies-count'),this.getNoReplies())
}

Draft.prototype.render = function() {
    //logDebug('Draft.render');
    if (this.nodes){
        return this.nodes;
    }
   
     if(this.parent.getPrevDraft(this)) {

         left_class = 'mid-top-left'
        right_class = 'mid-top-right'
    }else{
       left_class = 'first-top-left'
       right_class = 'first-top-right'
       }
     if(this.parent.getNextDraft(this)) {
        left_bottom_class = 'mid-bottom-left'
        right_bottom_class = 'mid-bottom-right'
    }else{
       left_bottom_class = 'last-bottom-left'
       right_bottom_class = 'last-bottom-right'
       }

    draft_headers =
    TABLE({'id':this.prefix+'draft-header','class':'draft-header', 'width':'100%'},
                       TBODY(null,
                         TR(null,
                           TD({'id':this.prefix+'draft-no',
                                'width':'1%'},'#' + this.getDraftNo()),
                            TD({'id':this.prefix+'draft-title',
                                'class':'draft-title','width':'25%'},this.getTitle()),
                            TD({'id':this.prefix+'draft-owner',
                               'class':'draft-owner link-user','width':'17%'},this.getOwner()),
                            TD({'id':this.prefix+'draft-status',
                                 'class':'draft-status'},this.getDraftStatus()),
                            TD({'id':this.prefix+'draft-avg-rating',
                                'class':'draft-avg-rating','width':'27%','align':'right'},this.getAvgRating())
                           )
                             )
                 )

     card_header_left =
    TD({'id':this.prefix+'card-header-left','class':left_class}, ' ');
    card_header_right = TD({'id':this.prefix+'card-header-right','class':right_class});
    card_header_content = TD({'id':this.prefix+'card-header-content','class':'top-center'},draft_headers);
    
    card_footer_left =
    TD({'id':this.prefix+'card-footer-left','class':left_bottom_class}, ' ');
    card_footer_right = TD({'id':this.prefix+'card-footer-right','class':right_bottom_class});
    card_footer_content = TD({'id':this.prefix+'card-footer-content','class':'bottom-center'});
    
    this.card_header = TR({'id':this.prefix+'card-header'},card_header_left,card_header_content,card_header_right);
    this.card_content =
    TD({'id':this.prefix+'card-content','class':'card-content'})
        
    appendChildNodes(this.card_content, this.menu_slot, this.summary, this.clauses_slot, this.replies_slot);
        
    this.card_footer =  TR({'id':this.prefix+'card-footer','class':'card-footer hideNode'},card_footer_left,card_footer_content,card_footer_right);
    this.card_footer.style.display = 'none'
    
    this.nodes = TABLE({'id':this.prefix+'card','class':'cards',
                            'width':'100%','cellpadding':'0','cellspacing':'0','border':'0'},
                       TBODY(null,
                             this.card_header,
                            TR({'class':'hideNode'},TD({'class':'center-left'},' '),this.card_content,TD({'class':'center-right'},'')),
                             this.card_footer));
    return this.nodes
}

Draft.prototype.getOwner = function(){
    //logDebug('Draft.getOwner');
    owner = this.headers.creator;
    return A({'href':owner.profile_url,'target':'_blank'},owner.fullname)

}

Draft.prototype.getDraftStatus = function(){
    if (this.headers.transitions.status){
        var newVal = ''
        newVal = capitalize(this.headers.transitions.status)
        this.draft_state = SPAN({'id':this.prefix + 'Draft_status'},
                                newVal)
        return this.draft_state
    }
}

Draft.prototype.changeState = function(event) {
    if (window.event)
        event = window.event
    var state_active = ['public_participate','public_view','visible', 'private_customized']
    if (this.show_state_change)
        return
    var ele
    if (this.state_change_req)
       this.state_change_req.abort()
    if(event.target){
            ele = event.target;
    }
    else if (event.srcElement){
        ele = event.srcElement;            
    }
    else{
            return;
    }
    this.state_change_req = loadJSONDoc(this.headers.id+'/activeDraftExist')
    
    this.state_change_req.addCallbacks(this.changeStateResponse,this.changeStateResponseError)
    this.state_change_url = ele.value
    this.state_to_change = ele[ele.selectedIndex].text
}

Draft.prototype.changeStateResponse = function (result){
    this.msg= TD(null)
    this.state_change_req = false
    if (result && result['draft_title']){
        state = capitalize(result['draft_state'])
        this.msg.innerHTML = " <div class=\"failure\"> \
                Draft with title <b> "+result['draft_title']+" </b> already  exist in " + state + " state. \
             </div> \
             <div style=\"margin: 2em 0em;\"> \
               Clicking on 'OK' will \
               <ul> \
                <li>Change the state of draft <b>"+result['draft_title']+ "</b> to submit state</li> \
                <li>Change the state of current Draft to <b>" + this.state_to_change +"</b> state</li> \
               </ul> \
             </div> "
    }
    else{
        this.msg.innerHTML = "  <div class=\"failure\"> \
                Change Draft State \
             </div> \
             <div style=\"margin: 2em 0em;\"> \
               Clicking on 'OK' will \
               <ul> \
                <li>Change the state of current Draft to <b>" + this.state_to_change +"</b> state</li> \
               </ul> \
             </div> "
        

    }
    var frm = FORM({'method':'get','style':'text-align:center;margin-bottom:10px;'})
    var but_ok = INPUT({'type':'button','value':'OK','class':'context'})
    addToCallStack(but_ok,'onclick',this.change_state)        
    var but_cancel = INPUT({'type':'button','value':'CANCEL','class':'standalone'})
    addToCallStack(but_cancel,'onclick',this.changeStateCancel)
    appendChildNodes(frm,but_ok,but_cancel)
    appendChildNodes(this.msg,frm)
    swapDOM(this.card_content,this.msg)
    
    this.show_state_change =true

}
Draft.prototype.changeStateResponseError = function (mes){
    //    alert(mes)
}

Draft.prototype.changeStateCancel = function() {
        this.state_change_url = false
    if (!this.show_state_change)
        return
    this.show_state_change = false
    swapDOM(this.msg,this.card_content)


    
}

Draft.prototype.change_state = function (){

    if (this.state_change_url)
        window.location = this.state_change_url
}

Draft.prototype.processStateChange= function (status){
    this.state_change_req= false;
    this.headers.transitions = status
    swapDOM($(this.prefix + 'state_editable'),this.getEditStatusWidget())
    swapDOM($(this.prefix + 'Draft_status'),this.getDraftStatus())
    this.parent.showMessage(this,status.message)
}

Draft.prototype.getEditStatusWidget = function(){
    this.draft_state_editable = null
    if (this.headers.transitions.transitions && this.headers.transitions.transitions.length){
        var tr = this.headers.transitions.transitions
        this.draft_state_editable = SELECT({'id':this.prefix + 'state_editable'})
        addToCallStack(this.draft_state_editable,'onchange',this.changeState)
        
        opts=OPTION({'disabled':'disabled','selected':'selected'},'Move to')
        appendChildNodes( this.draft_state_editable,opts)
        
        for (var i=0; i<tr.length;i++) {
            var opts = OPTION({'value':tr[i].url},tr[i].name)
            appendChildNodes( this.draft_state_editable,opts)
            }
        }
    return this.draft_state_editable

}



Draft.prototype.getNoReplies = function (){
    //logDebug('Draft.getNoReplies');
    reply_cnt = this.headers.no_of_replies? this.headers.no_of_replies: 0
    fullText = reply_cnt>1? (reply_cnt +' Comments'):(reply_cnt +' Comment')
    nodes = A({'title':fullText,'class':'draft-replies-count','id':this.prefix+'draft-replies-count'},fullText);
    addToCallStack(nodes,'onclick',this.showComments)
    return nodes
}

Draft.prototype.showComments = function(){
    debugger
    if(this.reply_manager){
        this.reply_manager.show()
    }
}
Draft.prototype.getTitle = function (){
    //logDebug('Draft.getTitle');
    title = this.headers.title? this.headers.title:"Untitled";
    if (title.length > 20 ){
        stripped_title =  title.substr(0,20) + '...'
    }
    else{
         stripped_title =  title
    }
    nodes = A({'title':title},stripped_title);
    addToCallStack(nodes,'onclick',this.showHide)
    nodes = SPAN(null,nodes,this.getEditIcon())
    return nodes
}
Draft.prototype.getEditIcon = function (){
    //logDebug('Draft.getTitle');
    if(this.headers.draft_edit_url){
        var nodes =
           A({'href':this.headers.draft_edit_url,'style':'margin-left:5px;'},
                    IMG({'src':'edit_icon.gif','alt':'Edit this draft','title':'edit'}))
         return nodes
    }
  else
    return null
}
Draft.prototype.getTitleText = function (){
    return this.headers.title? this.headers.title:" "
}

Draft.prototype.getAvgRating = function (){
    //logDebug('Draft.getAvgRating');
    if (!this.avg_rating)
         this.avg_rating = new createAvgRating ('',this.headers.id)
    return SPAN(null,"Avg Rating",this.avg_rating.render())
    
}

Draft.prototype.getUserRating = function (){
    
    //logDebug('Draft.getUserRating');
    if ( !this.headers.can_rate || this.headers.can_rate !='true' )  
            return ' '
     
    if (! this.user_rating)
        this.user_rating = new createRating ('',this.headers.id,true)
    return SPAN(null, "Rate this:",this.user_rating.render())
}

Draft.prototype.canReply = function(){
    if (this.headers.can_reply && this.headers.can_reply == 'true')
        return true;
    else
        return false;
}

Draft.prototype.canAmmend = function (){
    if (this.headers.can_add_amendment && this.headers.can_add_amendment == 'true')
        return true;
    else
        return false;
}

Draft.prototype.showHide = function (){
    //logDebug('Draft.showHide');
    if (this.__visible)
        this.shrink()
    else 
        this.expand()
}

Draft.prototype.expand = function() {
    //logDebug('Draft.show');
    if (!this.nodes)
        this.render();
    if (!this.__visible){
        if (document.all){
                 this.card_content.parentNode.style.display = 'inline';
                 this.card_footer.style.display = 'inline';
        }else{
                 this.card_content.parentNode.style.display = 'table-row';
                 this.card_footer.style.display = 'table-row';

        }
    }
    this.__visible = true;
    this.parent.expandShrinkManager();
}

Draft.prototype.shrink = function(){
    //logDebug('Draft.hide');
    if (!this.nodes)
    this.render();
    if (!this.parent.getNextDraft(this))
       return;
    if (this.__visible){
        this.card_content.parentNode.style.display = 'none';
        this.card_footer.style.display = 'none';
    }
    this.__visible = false;
    this.parent.expandShrinkManager();
}

Draft.prototype.isVisible = function(){
    return this.__visible;
}


Draft.prototype.getStatus= function(){
    return this.headers.status;
}

Draft.prototype.getDraftNo = function(){
    if (this.headers.draft_no)
        return this.headers.draft_no
}


function Clause(parent,clause_info){
    bindMethods(this);
    this.parent = parent
    this.clause_info = clause_info;
    this.prefix = Math.round(Math.random()*23434);
    this.amendments = []
    this.contents = DIV({'id':this.prefix,'class':'clause-slot'})
    this.description = DIV({'id':this.prefix +
    'description','class':'clause-description'})
    this.description.innerHTML = this.clause_info.description.replace(/\n/g,'<br>')
     this.amendments_slot =
        DIV({'id':this.prefix+'amendments','class':'clause-amendments'},
             ' ');
     for (var i = 0; i < this.clause_info.amendments.length; i++){
        this.amendments[i] = new
             Amendment(this,this.clause_info.amendments[i])
             appendChildNodes(this.amendments_slot,this.amendments[i].render())
             this.amendments[i].hide()
        }
      if(this.amendments.length > 0){
         this.amendments[this.amendments.length-1].show()
         this.ammendment_shown = 'last'
         }
     this.clause_footer = DIV({'id':this.prefix+'clause-footer','class':'clause-footer'})
     this.amendment_count = SPAN({'id':this.prefix +'amendment_count',
                                   'class':'amendment-count'},
                                 "Show All Comments (" + this.amendments.length +
                                  ")")
    if (this.clause_info.amendments.length<2){
        this.amendment_count.style.display = 'none'
    }
        
    addToCallStack(this.amendment_count,'onclick',this.showAmendments)
    appendChildNodes(this.clause_footer,this.amendment_count);
    
    if (this.parent.canAmmend()){
         var add_amendments_but =  SPAN({'class':'add-amendment'},
                                        'Add Comments')
       addToCallStack(add_amendments_but,'onclick',this.addAmendment)
        appendChildNodes(this.clause_footer,add_amendments_but)
    }
    appendChildNodes( this.contents,this.description,this.clause_footer,this.amendments_slot)
    this.contents.style.dispaly = 'none'

}

Clause.prototype.render = function(){
    this.contents.style.display = 'block'
    return this.contents

}

Clause.prototype.addAmendment = function(){
    if (this.new_amendment){
        this.new_amendment.setFocus();
        return;
    }
    this.new_amendment = new Amendment(this,{},true)
    appendChildNodes(this.amendments_slot,this.new_amendment.render())
    this.new_amendment.setFocus();


}

Clause.prototype.showAmendments = function(){
 
    if (this.ammendment_shown == 'last'){
        this.ammendment_shown = 'all'
        for (i = 0; i <this.amendments.length; i++){
            this.amendments[i].show()
        }
        this.amendment_count.innerHTML = "Show Last Comment ("
                                 +this.amendments.length + ")"
        
    }
    else
    {
        this.ammendment_shown = 'last'
        for (i = 0; i <this.amendments.length -1; i++){
            this.amendments[i].hide()
        }
        this.amendment_count.innerHTML = "Show All Comments ("
                                 +this.amendments.length + ")"        
       
    }
        
}


Clause.prototype.changeMode = function(child){
    if (child && this.new_amendment && child === this.new_amendment){
        this.amendments[this.amendments.length] =  child;
        this.new_amendment = false;
        if(this.ammendment_shown){
            var msg = "Show All Comments"
        }
        else{
            var msg = "Show Last Comments"
        }
        this.amendment_count.innerHTML = msg + "(" + this.amendments.length + ")"
        if (this.amendments.length<2)
            this.amendment_count.style.display = 'none'
        else
            this.amendment_count.style.display = 'block'            
    
   

    }
}
Clause.prototype.del = function(child){
    this.new_amendment = false;
}

function Amendment (parent,info,mode){
    bindMethods(this)
    this.parent = parent
    this.info = info
    if (mode)
        this.editable = true
    else
       this.editable = false
    this.prefix = Math.round(Math.random() * 1045056)
}

Amendment.prototype.show = function (){
    this.content_slot.style.display = 'block'
}

Amendment.prototype.hide = function (){
    this.content_slot.style.display = 'none'
}

Amendment.prototype.render = function (){
    if (this.content_slot )
       return this.content_slot
   if (this.editable){
        this.content_slot = DIV({'id':this.prefix +
               'amendment-slot','class':'amendment-slot'})
        this.textArea = TEXTAREA(null,'')
        this.controlers = DIV(null)
        this.but_submit = INPUT({'type':'button','value':'Submit'})
        addToCallStack(this.but_submit,'onclick',this.submit)
        this.but_cancel = INPUT({'type':'button','value':'Cancel'})
        addToCallStack(this.but_cancel,'onclick',this.cancel)
        appendChildNodes(this.controlers,this.but_submit,this.but_cancel)
        appendChildNodes(this.content_slot,this.textArea,this.controlers)
                

    }
    else{
      this.nonEditMode();
 
    }
    return this.content_slot    
}

Amendment.prototype.change_mode = function (){
    if (!this.editable)
        return;
    this.info.fullname = this.parent.parent.parent.user_info.fullname
    this.info.profile_url = this.parent.parent.parent.user_info.profile_url
    this.info.description = this.textArea.value;
    if (!this.info.description)
    return;    
    if (this.info.description){
        this.sendData()
    }
    else{
    }
    this.info.datetime = ''
    this.nonEditMode();
    
}

Amendment.prototype.nonEditMode = function (){
    //;
    if ( this.content_slot){
        var old_amendment_content  = this.content_slot
    }
     this.content_slot =
    DIV({'id':this.prefix+'amendment-content','class':'amendment-content'})
    this.content_slot.innerHTML = this.info.description.replace(/\n/g,'<br>')

    author_info = DIV({'id':this.prefix +
                     'amedment-author-info','class':'amedment-author-info'},'')
    appendChildNodes(this.content_slot,this.amendment_content,author_info)
    author_info_content = SPAN(null,SPAN({'id':this.prefix +
    'amendment-author','class':'newsAbout'},"Author",
                       A({'id':this.prefix +
                              'author-link','class':'link-user','href':this.info.profile_url},this.info.fullname),
                                         SPAN({'class':'amendment-datetime','id':this.prefix + 'amendment-datetime'},this.info.datetime)))
    appendChildNodes(author_info,author_info_content)
    if (old_amendment_content) {
        swapDOM(old_amendment_content, this.content_slot);
    }
          
}

Amendment.prototype.submit = function (){
    if (!this.editable)
        return;
    this.change_mode()
    this.parent.changeMode(this);

}

Amendment.prototype.sendData = function (){
    //;
    var xmlHttpReq = getXMLHttpRequest()
    xmlHttpReq.open( "POST", this.parent.clause_info.amendment_uri, true);
    xmlHttpReq.setRequestHeader('Content-Type',
                 'application/x-www-form-urlencoded');
    this.req = sendXMLHttpRequest(
    xmlHttpReq,"clause_no="+escape(this.parent.clause_info.id) + '&description='
    + escape(this.info.description) ) ;
    this.req.addCallbacks(this.addAmendmentResponse,alert);
    //    this.req.addErrback(alert);    

}

Amendment.prototype.addAmendmentResponse = function (response){
    this.req = false
    response = evalJSONRequest(response)
    this.info.datetime = response.datetime
    this.updateAmendmentDateTime()
}

Amendment.prototype.updateAmendmentDateTime = function (){
    swapDOM($(this.prefix + 'amendment-datetime'),SPAN({'class':'amendment-datetime','id':this.prefix + 'amendment-datetime'},this.info.datetime))
}

Amendment.prototype.cancel = function (){
    if (!this.editable)
        return;
    can_remove = true
    if (this.textArea.value){
        can_remove = confirm("Do you want to cancel the Comment?",null,"Comments")
    }
    if(can_remove ){
        swapDOM(this.content_slot, null);
        this.parent.del();
    }
}
    



Amendment.prototype.setFocus = function (){
    if (this.editable && this.textArea){
            this.textArea.focus()
            scrollToDOMNode(this.textArea)

    }

}

function ReplyManager (parent,headers){
    bindMethods(this)
    if (parent)
        this.parent = parent;
    if (headers)
        this.headers = headers
    else
        this.headers = {}
    this.prefix = Math.round(Math.random()*34234345)
    this.main_container = DIV({'id':this.prefix+'reply','class':'reply-manager'})
 
    this.controller = DIV({'id':this.prefix + 'contoller',
                           'class':'reply-controller'})
            
    if (this.headers.can_reply && this.headers.can_reply == "true" ){
        this.reply_but = A({'id':this.prefix + 'reply-button', 'class':
                             'reply-button'},'Comment')
        addToCallStack(this.reply_but,'onclick',this.post_reply)
        appendChildNodes(this.controller,this.reply_but)

    }
    this.reply_toggle = A({'id':this.prefix + 'reply-toggle-but', 'class':'reply-toggel-button hideNode'},'Show Comments')
    addToCallStack(this.reply_toggle,'onclick',this.replyToggle)
    appendChildNodes(this.controller,this.reply_toggle)
    if (this.headers.reply_count && this.headers.reply_count > 0){
        this.reply_toggle.style.display = 'inline'

    }
    this.container =
           DIV({'id':this.prefix+'reply','class':'reply-manager-replies hideNode'})
    appendChildNodes (this.main_container,this.controller,this.container)    


}
ReplyManager.prototype.fetch = function () {
    if (this.fetched)
        return
    if (this.headers.get_reply_uri){
        this.request = loadJSONDoc(this.headers.get_reply_uri)
        this.request.addCallbacks(this.processReplies,alert)
        this.fetched = true
    }

}

ReplyManager.prototype.processReplies = function (replies) {
    this.replies_data = replies
    this.replies = []
    for (var i = 0; i< this.replies_data.length; i++){
        this.replies[i] = new Reply(this,this.replies_data[i] )
        appendChildNodes(this.container,this.replies[i].render())

    }
    this.request = false
}

ReplyManager.prototype.replyToggle = function () {
    
    if (this.container.style.display == 'none' || this.container.style.display =='' ){
        this.fetch()
        this.show()
        this.reply_toggle.innerHTML = 'Hide Comments'
    }
    else {
        this.hide()
        this.reply_toggle.innerHTML = 'Show Comments'
    }
}

ReplyManager.prototype.show = function () {
     this.container.style.display = 'block'
     this.reply_toggle.innerHTML = 'Hide Comments'
}

ReplyManager.prototype.hide = function () {
     this.container.style.display = 'none'
}

ReplyManager.prototype.render = function () {
    return this.main_container
}

ReplyManager.prototype.post_reply = function (){
    if (this.container.style.display == '' || this.container.style.display == 'none' ){
        this.fetch()
        this.show()
        this.reply_toggle.innerHTML = 'Hide Comments'
    } 
    this.reply()

}


ReplyManager.prototype.reply = function (){
    if (this.reply_slot){
        this.setFocus()
        return
    } 
    this.reply_slot = DIV({'id':this.prefix +
            'reply-slot','class':'reply-slot'})
    this.title = INPUT({'type':'text','class':'reply-subject'})
    this.title.value ="Re:" + this.parent.getTitleText()
    this.textArea = TEXTAREA({'class':'reply-content'},'')
    this.controlers = DIV(null)
    this.reply_subject_title = DIV({'class':'reply-subject-title'},'Title(Required)')
    this.reply_content_title =
        DIV({'class':'reply-content-title'},'Comment Body (Required)')
    this.but_submit = INPUT({'type':'button','value':'Submit'})
    addToCallStack(this.but_submit,'onclick',this.submit)
    this.but_cancel =
        INPUT({'type':'button','value':'Cancel','name':this.prefix + 'reply-cancel'})
    addToCallStack(this.but_cancel,'onclick',this.cancel_reply)
    appendChildNodes(this.controlers,this.but_submit,this.but_cancel)
    appendChildNodes(this.reply_slot,
                         this.reply_subject_title,
                         this.title, 
                         this.reply_content_title,                        
                         this.textArea,
                         this.controlers)
    appendChildNodes(this.container,this.reply_slot)
    this.setFocus()
        
}

ReplyManager.prototype.cancel_reply = function (){
    if (confirm("Do you want to cancel the Comment?",null,"Comment")) {
         swapDOM(this.reply_slot,null)
         this.reply_slot = null
    }
}

ReplyManager.prototype.submit = function (){
   var focusOn = false
   if (!this.title.value ){
       this.reply_subject_title.style.color='#f00'
       if(!focusOn)
            focusOn = this.title

    }
   else{
       this.reply_subject_title.style.color='#000'
   }
   if (!this.textArea.value ){
        this.reply_content_title.style.color='#f00'
    }
   else{
        this.reply_content_title.style.color='#000'
   }

   if (!this.textArea.value || !this.title.value ){
       this.setFocus()
       return
   }
    this.sendData()
    this.reply_slot = false
   

}


ReplyManager.prototype.sendData = function (){
    var xmlHttpReq = getXMLHttpRequest()
    
    if (typeof this.headers.id  == 'undefined')
        this.headers.id = ''
    xmlHttpReq.open( "POST", this.headers.post_reply_url, true);
    xmlHttpReq.setRequestHeader('Content-Type',
                 'application/x-www-form-urlencoded');
    
    this.req = sendXMLHttpRequest(
    xmlHttpReq,"parent_id="+escape(this.headers.id) + '&text='
    + escape(this.textArea.value) + '&title=' + escape(this.title.value) ) ;
    new_reply_header = {}
    new_reply_header.id = ''
    new_reply_header.can_reply = true
    new_reply_header.creator = ''
    new_reply_header.get_reply_uri = ''
    new_reply_header.text = this.textArea.value
    new_reply_header.post_repy_url = ''
    new_reply_header.datetime = ''
    new_reply_header.reply_count = 0
    new_reply_header.title = this.title.value
    new_reply_header.profile_url = ''
    new_reply = new Reply(this,new_reply_header)
    this.replies[this.replies.length] = new_reply
    swapDOM(this.reply_slot,new_reply.render())
    
    this.req.addCallbacks(new_reply.update,logFatal);

}
ReplyManager.prototype.replyAdded = function (){
    debugger
    this.reply_toggle.style.display = 'block'
    this.parent.replyAdded()
}

ReplyManager.prototype.replyResponse = function (response){
    this.req = false
    
    response = evalJSONRequest(response)
    this.info.datetime = response.datetime
    this.updateAmendmentDateTime()
}

ReplyManager.prototype.cancel = function (){
    if (!this.editable && !this.textArea.value)
        return;
    if(confirm("Do you want to cancel the Comment?",null,"Comment")){
        swapDOM(this.reply_slot, null);
    }
    

}

ReplyManager.prototype.setFocus = function (){
    if(this.reply_slot){
        if(this.title && this.title.focus && !this.title.value){
            this.title.focus()
            scrollToDOMNode(this.reply_slot)
            return
        }
        if(this.textArea && this.textArea.focus ){
            this.textArea.focus()
            scrollToDOMNode(this.reply_slot)
            return
        }        

    }
}


function Reply(parent,headers){
    bindMethods(this)
    if (parent)
        this.parent = parent;
    if (headers)
        this.headers = headers
    this.prefix = Math.round(Math.random()*34234345)
    this.__render()

}

Reply.prototype.__render = function(){
   this.container = DIV({'id':this.prefix+'reply','class':'reply'})

    this.replies = DIV({'id':this.prefix +
                      'reply-reply','class':'reply-reply'})
   var reply_manager_headers = {}

   reply_manager_headers['get_reply_uri'] = this.headers.get_reply_uri
   reply_manager_headers['reply_count'] = this.headers.reply_count
   reply_manager_headers['post_reply_url'] = this.headers.post_reply_url
   
   reply_manager_headers['id'] = this.headers.id
   reply_manager_headers['can_reply'] = this.headers.can_reply

    this.reply_manager = new ReplyManager(this,reply_manager_headers)

    appendChildNodes(this.replies,this.reply_manager.render()) 

    this.title = H3({'id':this.prefix +
                      'reply-title','class':'reply-title'},this.headers.title)
    this.author = A({'id':this.prefix +
                         'reply-author','class':'reply-author','href':this.headers.profile_url},
                         this.headers.creator)
    this.datetime = SPAN({'id':this.prefix +
                         'reply-datetime','class':'reply-datetime'},
                         this.headers.datetime)
        
    this.post_details = SPAN({'id':this.prefix +
                             'reply-post-details','class':'reply-post-deatils'},
                             'Posted by ',this.author,' at ',this.datetime)
    this.body = DIV({'id':this.prefix +
                         'reply-content','class':'reply-content,commentBody'})
   this.body.innerHTML= this.headers.text.replace(/\n/g,'<br>')
    appendChildNodes(this.container,DIV({'class':'comment'},this.title,this.post_details,this.body),this.replies)


}


Reply.prototype.update = function (response){
    
    response = evalJSONRequest(response)
    this.headers = response
    container = this.container
    this.__render()
    swapDOM(container,this.container)
    this.parent.replyAdded()
}


Reply.prototype.render = function(){
    return this.container
}

Reply.prototype.getTitleText = function () {
     return this.headers.title?this.headers.title: ''
}


function init(){
    /*  loading_info =
        DIV({'id':'loading','style':''},'Loading...')
    bodyRef = document.getElementsByTagName('body').item(0)
    appendChildNodes(bodyRef,loading_info)*/
    textDIManager = new TextDIManager();
}

function scrollToDOMNode(node){
    if (document.layers) {
        if (node.x && node.y){
            cords =  { x: node.x, y: node.y };
            if (cords.y-200 > 0){
                cords.y -= 200 
            }
            window.scroll(cords.x,cords.y);
        }
        else
            return
    }
    else if (document.getElementById) {
        var cords = {x: 0, y: 0 };
        if(node.offsetLeft && node.offsetTop){
            while (node) {
                cords.x += node.offsetLeft;
                cords.y += node.offsetTop;
                node = node.offsetParent;
            }
            if (cords.y-200 > 0){
                cords.y -= 200 
            }

            window.scroll(cords.x,cords.y);            
        }
        else
            return 
        
    }

}
function capitalize(str) {
    if (typeof str == 'string'){
        var newVal = ''
        var val = str.split('_');
        for(var c=0; c < val.length; c++) {
            newVal += val[c].substring(0,1).toUpperCase()+  val[c].substring(1,val[c].length) + ' ';
        }
        return newVal

    }
    return null

}
function isIn (what,where){
    for (var i=0;i< where.length;i++){
        if (what == where[i])
            return true
    }
    return false;
} 
addLoadEvent(init);

