// == ******************************************************************
// message box functions (used by openControl.htm)
//===========================
//  rebuild a participant's mailbox (using the all mailbox, extract all messages to this participant
//  and add them to the participant's mailbox. This is useful if the particpant had to reload his
// browser, thereby losing the internally stored record of prior messages.
// 

function doRebuildMessage(ido) {
var m,alines,awords,ato,aline,a,ato,bto,cname1,mto,nmessages,cnameId ;

if (ido==1) {
  a=confirm('Rebuilding a participant\'s message-box is meant to be used if a participant had to reload his '+
            'browser (thereby losing internally stored messages). If the participant can view his messages, rebuilding his message-box  \n'+
            'could lead to duplication of messages when he next retrieves messages.\n'+
           ' Are you sure you want to rebuild a message box? ');
  if (!a) return 0;

// first, get the all mailbox
   toGet=messageRetrieve+'session='+sessName+'&erase=0&client=$ALL';
   amess='<b>Rebuilding a participant\'s message box </b>'+
       '<span style="background-color:#99aaee;float:right">'+
       '  <input type="button" style="font-size:90%;float:right;margin-right:10px" value="close" onClick="close_moveBox(7)" />'+
       '  <input type="button" style="font-size:90%;float:right;margin:1px 10px 1px 10px" value="Messages" '+
       '    onClick="doReadMessage(1)"  title="Return to main message screen" />'+
       '</span>';


   write_moveBox(7,amess,'Please wait while the message index is retreived ... ');
   Get_File(toGet,'readAllMessagesResult','read messages','doRebuildMessage',2) ;
   return 0;

}
alines=readAllMessagesResult.split('\n');

messageData.rebuilds={};
messageData.rebuilds['$list']=[];

nmessages=0;
for (m=0;m<alines.length;m++) {
  aline=alines[m];
  if (strip(aline)=='') continue ;
  awords=aline.split(',');

  ato=strip(awords[4]);
  bto=getWord(ato);
  for (var mto=0;mto<bto.length;mto++) {
      cnameId=bto[mto];
      cname1=cnameId ;
      if (typeof(currentParticipants[cnameId])!=='undefined' && typeof(currentParticipants[cnameId]['NAME'])!=='undefined') {
            cname1=currentParticipants[cnameId]['NAME'] ;
       }

      if (typeof(messageData.rebuilds[cnameId])=='undefined') {
           messageData.rebuilds[cnameId]={} ;
           messageData.rebuilds['$list']=messageData.rebuilds['$list'].concat(cnameId);
           messageData.rebuilds[cnameId].name=cname1;
           messageData.rebuilds[cnameId].ct=1;
           messageData.rebuilds[cnameId].messages=[aline];
      } else {
           messageData.rebuilds[cnameId].ct++ ;
           messageData.rebuilds[cnameId].messages=messageData.rebuilds[cnameId].messages.concat(aline) ;
      }

  }
  nmessages++ ;
}
 writeContent_moveBox(7,'Message index has been retrieved (with '+nmessages+' messages)');

showListOfNamesR(7,nmessages) ;            // uses .rebuilds
return 1;
}


//=====================
// select whose message box to rebuild

function showListOfNamesR(ibox,nmessages) {
var alist,z,alist2='',stuff='',amess ;
var aid,aname,act,aids,iz;
if (arguments.length<1) ibox=8;
if (arguments.length<2) nmessages='';
stuff='<div style="background-color:#dedddc">Select whose message box to rebuild (total messages send='+nmessages+') </div> ';


aids=messageData.rebuilds['$list'];
for (var iz=0;iz<aids.length;iz++)  {
     aid=aids[iz]; aname=messageData.rebuilds[aid].name ;
     act=messageData.rebuilds[aid].ct ;
     alist2=alist2+' '+
            '<span style="border:1px solid #abbaab;margin:6px"> '+
                 '<a href="#"  onClick="doRebuildNow('+iz+',1,'+act+');return false ">'+aname+'</a> '+
                 '<span style="font-size:80%">('+act+')</span>'+
             '</span> ' ;
}
stuff=stuff+alist2;
stuff=stuff+  '  <div style="margin-top:8px;font-size:80%">(number in parenthesis is number of messages recieved)</div> ' ;

amess=' Rebuild a participant\'s message box. <span style="float:right;margin-right:5px"><input type="button" value="close" onClick="close_moveBox(8)" /><span> ';

writeContent_moveBox(ibox,stuff);
top_moveBox(ibox);

return 0;
}


//=====================
// set value of Select Whose message to view
function doRebuildNow(ith,ido,act) {
  var aids,aid,aname,stuff,topost;
  if (arguments.length<2) ido=1 ;

  if (ido==1) {
     aids=messageData.rebuilds['$list'];
     aid=aids[ith];
     aname=messageData.rebuilds[aid].name;
     stuff=messageData.rebuilds[aid].messages.join('\n');
// adding stuff is NOT necessary in WAMP version (4/2011)
     topost=messageRebuild+'session='+sessName+'&client='+aid+'&message='+stuff;
//   alert('topost1='+topost);

     Post_toServer(postMessageURL,topost,'rebuildMessageResult','rebuild message box ','doRebuildNow',aname,2,act);
     return 1 ;
  }
  writeContent_moveBox(7,' Message box for '+ith+' has been rebuilt ('+act+' messages). <p/> Response from server<tt>: '+rebuildMessageResult+'</tt>');
  close_moveBox(8);
  top_moveBox(7); 
  return 0;

}


//===========================
//  modify message options
 
function doModifyMessage(ido) {
var arf,arf2,aform,a1,opts={};
var ug,acurrent,ww,m,aword ;

doCreateMoveBox(7) ;


arf=getVarInfo('message_options.c','value');

open_moveBox(7);
arf2=' Modify message box options, and then  '+
   '  <input type="button" value="Save message options" onClick="doModifyMessages2()" />  ' +
       '<span style="background-color:#99aaee;float:right">'+
       '  <input type="button" style="font-size:90%;float:right;margin-right:10px" value="close" onClick="close_moveBox(7)" />'+
       '  <input type="button" style="font-size:90%;float:right;margin:1px 10px 1px 10px" value="Messages" '+
       '    onClick="doReadMessage(1)"  title="Return to main message screen" />'+
       '</span>';

write_moveBox(7,arf2,arf);


aform='' +
 '<form name="messageOptionsForm">  '+
 ' <table border="1"> '+
 '  <tr> <td>Select from the following options ... </th> '+
 '       <td> <input title="If you uncheck this, the other options are ignored (message sending and reading will be disabled)" type="checkbox" %ENABLE% id="messageOption_enable" />Enable messages? '+
 '     <br/>   <input title="If checked, only enable note-taking (messages will not be sent or received) " '  +
 '            type="checkbox" %NOTESONLY% id="messageOption_notesOnly" />Notes Only? </td> '+
 '       <td> <input type="checkbox" %SHOW% id="messageOption_show" />Show message button? </td> '+
 '       <td> <input title="Check this to notify participants when they get a new message" type="checkbox" %NOTIFY% id="messageOption_notify" />Notify? </td> '+
 '       <td> <input type="text" title="Frequency (in seconds) messages retrieved from server '+
 '               (0=no polling, use manual requests)" size="6" id="messageOption_poll" value="%POLL%" /> '+
 '        Polling  (0=none) </td> '+
 '       <td> <input title="Check this to enable note-taking feature" type="checkbox" %NOTES% id="messageOption_notes" />Notes? </td> '+

 '   </tr> '+
 '   <tr bgcolor="#ababab"> '+
 '      <th> Enable sending messages to: </th> '+
 '       <td>    <input type="radio" %SENDALL% name="message_radio1" id="messageOption_sendall" value="1" /> All </td> '+
 '      <td>    <input type="radio" %ADMINSEND% name="message_radio1" id="messageOption_adminsend" value="2" />admin only </td> '+
 '       <td>    <input type="radio" %NOSEND% name="message_radio1" id="messageOption_nosend" value="3" />no one </td> '+
 '       <td colspan="2">    <input type="radio" %IFSEND%  name="message_radio1" id="messageOption_ifsend" value="4" />If condition ... '+
 '               <input type="text" size="40" id="messageOption_iftext" value="%IFTEXT%" /> '+
 '       </td> '+
 '    </tr> '+
 '</table> '+
 '</form> ';


// now modify the checkboxes in the form
opts={};
opts.show='SHOW';
opts.notify='NONOTIFY';
opts.enable='ENABLE';
opts.notes='NOTES';
opts.poll=0;
opts.send='SENDALL';
opts.send2='';

ww=getWord(arf,0,',');
for (var m=0;m<ww.length;m++) {
  aword=strip(ww[m]).toUpperCase();
  if (aword=='') continue ;

  if (aword=='SHOW') opts.show='SHOW';
  if (aword=='NOSHOW') opts.show='NOSHOW';

  if (aword=='NOTES') opts.notes='NOTES';
  if (aword=='NONOTES') opts.notes='NONOTES';

  if (aword=='NOTIFY') opts.notify='NOTIFY';
  if (aword=='NONOTIFY') opts.notify='NONOTIFY';

  if (aword=='ENABLE') opts.enable='ENABLE';
  if (aword=='DISABLE') opts.enable='DISABLE';
  if (aword=='NOTESONLY') opts.enable='NOTESONLY';

  if (aword=='NOPOLL') opts.poll=0;
  if (aword.substr(0,5)=='POLL=') {
        ug=strip(aword.substr(5));
        if (isNaN(ug)) ug=0;
        opts.poll=ug;
  }
  if (aword=='SENDALL' || aword=='*' || aword=='ALL') opts.send='SENDALL';
  if (aword=='NOSEND' || aword=='0' || aword=='NONE' ) opts.send='NOSEND';
  if (aword=='ADMINSEND' || aword=='ADMIN' ) opts.send='ADMINSEND';
  if (aword.substr(0,7)=='SENDIF=' || aword.substr(0,7)=='IFSEND=' ) {
         opts.send='IF' ;
         opts.send2=aword.substr(7);
   }
  
}
a1='';  if (opts.show=='SHOW') a1=' checked ' ;
aform=aform.replace(/%SHOW%/,a1);

a1='';  if (opts.enable=='ENABLE') a1=' checked ' ;
aform=aform.replace(/%ENABLE%/,a1);

a1='';  if (opts.enable=='NOTESONLY') a1=' checked ' ;
aform=aform.replace(/%NOTESONLY%/,a1);

a1='';  if (opts.notify=='NOTIFY') a1=' checked ' ;
aform=aform.replace(/%NOTIFY%/,a1);

a1='';  if (opts.notes=='NOTES') a1=' checked ' ;
aform=aform.replace(/%NOTES%/,a1);

aform=aform.replace(/%POLL%/,opts.poll);

a1='';  if (opts.send=='SENDALL') a1=' checked ' ;
aform=aform.replace(/%SENDALL%/,a1);
a1='';  if (opts.send=='NOSEND') a1=' checked ' ;
aform=aform.replace(/%NOSEND%/,a1);
a1='';  if (opts.send=='ADMINSEND') a1=' checked ' ;
aform=aform.replace(/%ADMINSEND%/,a1);
a1='';  if (opts.send=='IF') a1=' checked ' ;
aform=aform.replace(/%IFSEND%/,a1);
aform=aform.replace(/%IFTEXT%/,opts.send2);

writeContent_moveBox(7,aform);

return 0;
}


//===========================
// save changes from modify message options form
 
function doModifyMessages2(ido) {

var i1,i2,i3,i4,i5,ado;
var opts={};

opts.show='NOSHOW';
opts.notify='NONOTIFY';
opts.enable='DISABLE'; 
opts.poll=0;
opts.notes='NONOTES';
opts.send='SENDALL';
opts.send2='';


i1=document.getElementById('messageOption_enable');
if (i1.checked) opts.enable='ENABLE';

i1=document.getElementById('messageOption_notesOnly');
if (i1.checked) opts.enable='NOTESONLY';

i1=document.getElementById('messageOption_show');
if (i1.checked) opts.show='SHOW';

i1=document.getElementById('messageOption_notes');
if (i1.checked) opts.notes='NOTES' ;

i1=document.getElementById('messageOption_notify');
if (i1.checked) opts.notify='NOTIFY';

i1=document.getElementById('messageOption_poll');
vv=strip(i1.value) ;
if (isNaN(vv) || vv=='' ) vv=0;
opts.poll='POLL='+vv ;

i1=document.getElementById('messageOption_sendall');
i2=document.getElementById('messageOption_adminsend');
i3=document.getElementById('messageOption_nosend');
i4=document.getElementById('messageOption_ifsend');
i5=document.getElementById('messageOption_iftext');

if (i1.checked) opts.send='SENDALL';
if (i2.checked) opts.send='ADMINSEND';
if (i3.checked) opts.send='NOSEND';
if (i4.checked) opts.send='IFSEND='+strip(i5.value);

ado=opts.enable+', '+opts.show+', '+opts.notes+','+opts.notify+','+opts.poll+','+opts.send;

setControlVar('message_options',ado);

writeDataMessage('Message options changed to: '+ado,5);
close_moveBox(7);
return 1 ;



}

//===========================
//  open messages window -- display a menu of names to retrieve messages for, and a
// menu of other options (rebuild, options, send..)

function doReadMessage(ido) {
var stuff,cIds,messagesBox,amenu,m,aa,ii,cname,acurrent ;
if (typeof(currentParticipants)=='undefined' || typeof(currentParticipants['$IDS'])=='undefined') {
  alert('Error: the current participants have not been retrieved from the server ');
  return 0;
}
cIds=currentParticipants['$IDS'];

doCreateMoveBox(7) ;

close_moveBox(8);
open_moveBox(7);

amenu='<form name="readMessageRadios"><table border="1" width="90%" style="margin-left:30px"><tr><th colspan="'+Math.min(5,cIds.length)+'">Whose messages to read?' +
         '<span title="Check to read  messages to the administrator" style="margin-left:20px;padding-left:6px;border:1px solid gray"><input checked cname="admin" type="radio" id="adminLabel1" name="messageToCheckboxes" value="admin"><label for="adminLabel1"> admin</label></span>' +
         '<span title="Check to read ALL messages" style="margin-left:10px;padding-left:6px;border:1px solid gray"><input type="radio" cname="all" id="adminLabel2" name="messageToCheckboxes" value="$ALL"><label for="adminLabel2">all</label></span>' +
        '</th></tr>';
ii=0;
if (cIds.length==0) {
  tmp=confirm('No participants available -- would you like to try updating-participants?');
  if (tmp==1) {
        updateCurrentParticipants(1,'doReadMessage') ;
        return 0;
  }
}

for (var m=0;m<cIds.length;m++) {
  if (ii==0) amenu=amenu+'\n<tr>';
  cname=currentParticipants[cIds[m]]['NAME'];
  aline='<td><input  id="nameLabel_'+cIds[m]+'"  type="radio" cname="'+cname+'" name="messageToCheckboxes" value="'+cIds[m]+'">' +
             '<span style="margin:5px;border:1px dotted gray" title="to participant '+cIds[m]+'">'+
           '<label for="nameLabel_'+cIds[m]+'"> '+cname+'</label></span>' +
          '</td>';
  amenu=amenu+'\n'+aline;
  ii++;
  if (ii>4) {
        ii=0; amenu=amenu+'\n</tr>';
  }
}
if (ii>0) amenu=amenu+'</tr>';
amenu=amenu+'</table></form>';

// for now
stuff='Select whose messages to <span style="padding-left:20px"> <input type="button" value="read" onClick="doReadMessageRead(1)" /> </span> ...' + 
       '<span style="background-color:#99aaee;float:right">'+
       '<input type="button" style="font-size:90%;float:right;margin-right:10px" value="close" onClick="close_moveBox(7)" />'+
       '<input type="button" style="font-size:90%;float:right;margin:1px 10px 1px 10px" value="Send" '+
       '    onClick="doSendMessage(1)" title="Compose and send a message to one or more participants" />'+
       '<input type="button" style="font-size:90%;float:right;margin:1px 6px 1px 6px" value="Options" '+
       '    onClick="doModifyMessage(1)" title="Change the message display options" />'+ 
       '<input type="button" style="font-size:90%;float:right;margin:1px 6px 1px 6px" value="ReBuild" '+
       '    onClick="doRebuildMessage(1)" title="Rebuild a participant\'s mailbox" />'+
       '</span>'+
       '<span style="float:right;border-left:1px dotted black;margin-right:20px;padding-left:10px;color:#223399;font-style:oblique"> or ...</span>';

//     '(<input type="hidden" name="clearMessageBox" title="Check to empty message box after reading"/> empty message box?) '+


write_moveBox(7,stuff,amenu) ;
top_moveBox(7);

stuff='<br/><input type="button" title="read messages" value="read" onClick="doReadMessageRead(1)" />  ' ;
writeContent_moveBox(7,stuff,1);

return 0;
}

// ================
// retreive, and then display, messages for a client, the admin, or ALL messages

function doReadMessageRead(ido,aclient,cname) {

 var alist,m,i,a1,jid,toGet,stuff,amess,aerase,asubject,atimeu;
var atable,amessage,aform,atime1,d,atime,awords,aline,alines,m;
var afromId,afromName,aheader,amessageUse,asubjectUse,afromUse,asubjectUse0,aurgent;
var ato,bto,atoUse,cIds,mto,cname,cname1,m00,tcname1,achecked,hd;
var iss,checkName,checkOk,idd,amessageUse0,nDid;


 messageData.atoList={};
 messageData.nameFilter='';

 if (ido==1 || ido==11) {

   if (ido==1) {
     iss=document.getElementById('selectWhoseMessages');  // reset Who to read (before fetching messages from server
     if (iss) {
       iss.value=''
     }

     stuff='';
     alist=document.getElementsByName('messageToCheckboxes');   // whose messages to retrieve?
     for (var m=0;m<alist.length;m++) {
        a1=alist[m];
        if (a1.checked) {
           stuff=a1.value ;
           cname=getAttributes(a1,'cname','');
           break ;
        }
     }
     if (stuff=='') {
        alert('You did not select whose messages to retrieve. ');
        return 0;
     }
     alist=document.getElementsByName('clearMessageBox');
     aerase='&erase=0';
     if (alist.length>0 && alist[0].checked) aerase='&erase=1';    // not currently supported (april 2011)
   } else {                                     // 11 (a reread)
        aerase='&erase=0';
        stuff=aclient;
   }
   arand=Math.random(); arand=''+arand; arand=arand.substr(3,8);
   toGet=messageRetrieve+'session='+sessName+aerase+'&junk='+arand+'&client='+stuff;
//alert ('xxxtoget='+toGet);
   Get_File(toGet,'readMessageResult','read messages','doReadMessageRead',2,stuff,cname) ;
   return 0;
 }


// If here, back from message retrieval (alist

//           ' onClick="doReadMessage(1)" />'+
if (readMessageResult=='') {
   atimeu=new Date(); atimeu=atimeu.toLocaleTimeString();
   aheader='<input type="button" style="font-size:90%;float:left;margin:1px 10px 1px 10px" value="Re-read messages...." '+
           ' onClick="doReadMessageRead(11,\''+aclient+'\',\''+cname+'\')" '+
           '  title="Re-read messages to '+cname+' " />'+
           'No messages available for: '+cname+' (updated: '+atimeu+') '+
       '<span style="background-color:#99aaee;float:right">'+
       '  <input type="button" style="font-size:90%;float:right;margin-right:10px" value="close" onClick="close_moveBox(7)" />'+
       '  <input type="button" style="font-size:90%;float:right;margin:1px 10px 1px 10px" value="Messages" '+
       '    onClick="doReadMessage(1)"  title="Return to main message screen" />'+
       '</span>';


//           '<input type="button" style="font-size:90%;float:right;margin-right:10px" value="close" '+
//           '       onClick="close_moveBox(7)" />' +
//           '<input type="button" style="font-size:90%;float:right;margin:1px 10px 1px 10px" value="Send" '+
//           '    onClick="doSendMessage(1)" title="Compose and send a message to one or more participants" />';
  write_moveBox(7,aheader,'...');
  return 0;
}


//alert("zxlllll00 "+readMessageResult);

  alines=readMessageResult.split('\n');
  messageData.alines=alines
  messageData.aclient=aclient ;
  messageData.cname=cname ;


if (messageData.compressDisplay) {
atable='<table  width="100%" cellpadding="2" rules="rows" ><tr>' +
        ' <th width="5%">Time</th> '+
         '<th width="10%"> <span style="background-color:#cddefe;font-variant:small-caps">From</span></th>'+
         '<td style="font-style:oblique"  width="40%" >Subject</td></tr>';
} else {
atable='<table  width="100%" cellpadding="2" rules="rows" ><tr>' +
        ' <th width="5%">Time</th> '+
         '<th width="10%"> <span style="background-color:#cddefe;font-variant:small-caps">From</span></th>'+
         '<td style="font-style:oblique"  width="40%" >Subject</td><td width="45%"><b>Message</b></td></tr>';
}

iss=document.getElementById('selectWhoseMessages');
checkName='';
if (iss) {
  checkName=strip(iss.value).toUpperCase();
}
if (ido==3 && checkName=='') { ido=2;cname='all'}             // if no checkName (after a change), show all messages

messageData.messageFull=[];
m00=-1;
nDid=0;
for (m=alines.length-1;m>-1;m--) {
  checkOk=0;                            // used if checkName!==''
  aline=alines[m];
//  alert(m+' xxxx=xxxx '+aline);
  if (strip(aline)=='') continue ;
  m00++ ;
  messageData.messageFull[m00]=aline;
  awords=aline.split(',');
  aurgent=awords[0];
  atime=awords[1];
  d =new Date();
  d.setTime(atime);
  atime1='<span title="'+d.toLocaleString()+'" style="font-size:80%">'+d.toLocaleTimeString().substr(0,5)+'</span>';
  afromId=awords[2];
  afromName=awords[3];

  ato=strip(awords[4]);
  bto=getWord(ato);

  atoUse='';
  cIds=currentParticipants['$IDS'];
  for (var mto=0;mto<bto.length;mto++) {
      cname1=bto[mto];
      if (typeof(currentParticipants[cname1])!=='undefined' && typeof(currentParticipants[cname1]['NAME'])!=='undefined')  cname1=currentParticipants[cname1]['NAME'];
      atoUse=atoUse+' '+cname1;

      tcname1=strip(cname1).toUpperCase();
      if (tcname1=='ADMIN' ) tcname1='ADMINISTRATOR';

      if (checkName!=='') {
        if (checkName==tcname1) checkOk=1;
      }

      if (typeof(messageData.atoList[tcname1])=='undefined') {
//alert('ssss '+tcname1);
         messageData.atoList[tcname1]=1;
      } else {
         messageData.atoList[tcname1]++ ;
      }

  }
  if (checkName!=='') {
       if (checkOk!==1) continue ;
   }
   nDid++ ;
  asubject=unescape(awords[5]);
  asubjectUse0=removeHTMLTags(asubject);
    asubjectUse='<span title="'+asubjectUse0+'" style="font-style:oblique">'+asubjectUse0.substr(0,50)+'</span>';
  amessage=unescape(awords[6]);
    amessageUse0=removeHTMLTags(amessage);
    amessageUse='<div style="overflow:auto;height:50px;width:95%;font-size:90%;padding-left:8px;background-color:#fdfefd">'+amessageUse0.substr(0,120)+'</div>';

  afromUse='<span onClick="sendAMessageA(\''+afromId+'\',\''+afromName+'\',0,\''+asubjectUse0+'\')"  '+
                 ' style="background-color:#cddefe;font-variant:small-caps" ' +
                  ' title="Message sent to: '+atoUse+' (click to send a reply)" >'+afromName+'</span>';

  avu='<span style="background-color:#eaea99;font-size:80%;padding-right:3px;" title="click to view this message" '+
       '     onClick="readAClientMessage('+m00+')">vu</span>';

  if (messageData.compressDisplay) {
     if (ato=='') {
       atable=atable+'<tr><td width="5%" >'+atime1+ '</td> '+
            '<td  width="10%"> <span style="background-color:#cddefe;font-variant:small-caps">'+afromUse+'</span></td>'+
           ' <td  width="40%" >'+asubjectUse+'</td><td>'+avu+'  '+amessageUse0.length+' characters: ' +
           '  <span style="font-size:90%;font-style:oblique">'+amessageUse0.substr(0,35)+' ... </span> </td></tr>';
     } else {
       ato=ato.replace(/\s/g,' | ');
       atable=atable+'<tr><td  width="5%" >'+atime1+ '</td>'+
                   '<td  width="10%"> <span title="Sent to: '+atoUse+'" style="background-color:#cddefe;font-variant:small-caps">'+afromUse+'</span></td> '+
           ' <td  width="40%" >'+asubjectUse+'</td><td>'+avu+'  '+amessageUse0.length+' characters: ' +
           '  <span style="font-size:90%;font-style:oblique">'+amessageUse0.substr(0,35)+' ... </span> </td></tr>';

     }
  } else {
    if (ato=='') {
       atable=atable+'<tr><td width="5%" >'+atime1+ '</td> '+
            '<td  width="10%"> <span style="background-color:#cddefe;font-variant:small-caps">'+afromUse+'</span></td>'+
           ' <td  width="40%" >'+avu+asubjectUse+'</td><td  width="45%" >'+amessageUse+'</td></tr>';
     } else {
       ato=ato.replace(/\s/g,' | ');
       atable=atable+'<tr><td  width="5%" >'+atime1+ '</td>'+
                   '<td  width="10%"> <span title="Sent to: '+atoUse+'" style="background-color:#cddefe;font-variant:small-caps">'+afromUse+'</span></td> '+
                   '<td width="40%" >'+avu+asubjectUse+'</td><td width="45%">'+amessageUse+'</td></tr>';
     }
  }
}

atable=atable+'</table>';

   aheader='<input type="button" style="font-size:90%;float:left;margin:1px 8px 1px 7px" value="Re-read messages... ..." '+
           ' onClick="doReadMessageRead(11,\''+aclient+'\',\''+cname+'\')" '+
           '  title="Re-read messages to '+cname+'" />';


//           ' onClick="doReadMessage(1)" />';
   if (cname=='all' || ido==3) { 
      atimeu=new Date(); atimeu=atimeu.toLocaleTimeString();
      if (ido==3) {
         aheader=aheader+' <span title="Displaying '+nDid+' messages. Last update at '+atimeu+' ">Messages sent to '+checkName+'</span> ' ;
      } else {
         aheader=aheader+' <span title="Displaying '+nDid+' messages . Last update at '+atimeu+'">All messages </span> ' ;
      }
      aheader=aheader+' ' +
            '<span style="background-color:#eeeeaa;margin:1px 5px 1px 30px"> '+
              '<a href="#"  title="Enter a name in textbox, and then click here" '+
              ' onClick="doReadMessageRead(3);return false"  />'+
              'Filter...</a> '+
              '<input type="text" size="15" id="selectWhoseMessages" '+
              '  title="Enter a NAME: only messages to this NAME will be displayed. Leave blank to view all messages." /> '+
              ' <a href="#"  title="Display participant NAMES" style="margin:1px 3px 1px 3px;background-color:#bfbfc2" onClick="showListOfNames();return false">?</a> '+
            '</span> ' ;  

  } else if (cname=='admin') {
        atimeu=new Date(); atimeu=atimeu.toLocaleTimeString();
        aheader=aheader+'<span title="Displaying '+nDid+' messages. Updated at '+atimeu+'">Messages sent to the Administrator.</span>';
  } else {
      atimeu=new Date(); atimeu=atimeu.toLocaleTimeString();
      aheader=aheader+'<span title="Displaying '+nDid+' messages. Updated at '+atimeu+'"> Pending messages for: '+cname+' ('+aclient+').</span>' ;
  }

//  aheader=aheader+' '+
//           '<input type="button" style="font-size:90%;float:right;margin-right:10px" value="close" '+
//          '        onClick="close_moveBox(7)" />' +
//           '<input type="button" style="font-size:90%;float:right;margin:1px 10px 1px 10px" value="Send" '+
//           '    onClick="doSendMessage(1)" title="Compose and send a message to one or more participants" />';

     achecked='';
     if (messageData.compressDisplay) achecked=' checked ';
     aheader=aheader+' '+
       '<span style="background-color:#99aaee;float:right">'+
       '  <input type="button" style="font-size:90%;float:right;margin-right:10px" value="close" onClick="close_moveBox(7)" />'+
       '  <input type="button" style="font-size:90%;float:right;margin:1px 10px 1px 10px" value="Messages" '+
       '    onClick="doReadMessage(1)"  title="Return to main message screen" />'+
       '</span>'+
       '<span style="background-color:#cdcdcd;font-size:90%;float:right;margin:1px 10px 1px 10px" "> '+
       '    <input id="compressMessages1" type="checkbox" value="1" ' +achecked+' ' +
               '    onClick="setCompressMessageDisplay(this.checked)" title="Check to compress display " />'+
              ' <label for="compressMessages1">Compress?</label> '+
      ' </span> ';


write_moveBox(7,aheader,atable);


return 0;
}

//=============
// set the value of the messageData.compressDisplay variable
function setCompressMessageDisplay(aval) {
 messageData.compressDisplay=aval;
 if (aval) {
    writeDataMessage('List of messages will be compressed',2);
 } else {
    writeDataMessage('List of messages will NOT be compressed',2);
 }
 return 0;
}

//=====================
// display list of names using dataMessages.atoList 

function showListOfNames() {
var alist,z,alist2='',stuff='',amess='<b>Choose a participant</b>' ;

stuff='<div style="background-color:#dedddc">Participants who have received messages</div> ';

open_moveBox(8);
alist=messageData.atoList ;  
for (var z in alist)  {
        alist2=alist2+'<span style="border:1px solid #abbaab;margin:6px"> '+
              '<a href="#"  onClick="makeSelectWhoValue(\''+z+'\',\'selectWhoseMessages\');return false ">'+z+'</a> '+
             '<span style="font-size:80%">('+alist[z]+')</span></span> ' ;
}
stuff=stuff+alist2;
stuff=stuff+  '  <div style="margin-top:8px;font-size:80%">To view only messages to a participant, click on a name and then click on <u>filter</u> <br/>(the number in parenthesis is number of messages recieved)</div> ' ;

write_moveBox(8,amess,stuff);
top_moveBox(8);

return 0;
}

//=====================
// set value of Select Whose message to view
function makeSelectWhoValue(aval,aaid) {
  var ii,i2;
 i2=document.getElementById(aaid);
 i2.value=aval;
 close_moveBox(8);
 top_moveBox(7); 
 return 0;
}



//=====================
// display full message
function readAClientMessage(ido) {

var aline,awords,atime,d,tt1,tt2,atime2,afrom,ato,aheader,asubject,acontent,afromId,afromName,aurgent;
 aline=messageData.messageFull[ido];

 awords=aline.split(',');
  aurgent=awords[0];
  atime=awords[1];
  d =new Date();
  d.setTime(atime);
  tt1=d.toLocaleTimeString()
  tt2=d.getHours()+':'+d.getMinutes();
  atime1='<span title="'+tt1+'" style="font-size:80%">'+tt2+'</span>';
  afromId=awords[2];
  afromName=awords[3];

  ato=_mbStrip(awords[4]);              // not used on participants side (admin uses it)
  asubject=unescape(awords[5]);
  amessage=unescape(awords[6]);

aheader='<input type="button" value="close" onClick="close_moveBox(8)" /> '+
      '<span style="margin:1px 5px 1px 5px;background-color:#deddde">'+tt1+'</span>'+
      '<span style="margin:1px 1px 1px 1px;background-color:#cddefe;font-variant:small-caps">From: '+afromName+'</span>'+
      '<span style="margin:1px 3px 1px 3px;background-color:#eeddee">Subject: '+asubject+'</span>';

open_moveBox(8);
write_moveBox(8,aheader,amessage);
top_moveBox(8);
return 1 ;
 
}


//===========================
// send a message

function doSendMessage(ido) {
var cIds,cvarlist=[],aa,ii,m,amenu,alist,tmp,acurrent;

if (typeof(currentParticipants)=='undefined' || typeof(currentParticipants['$IDS'])=='undefined') {
  alert('Error: the current participants have not been retrieved from the server ');
  return 0;
}
cIds=currentParticipants['$IDS'];

doCreateMoveBox(7) ;
open_moveBox(7);

amenu='<b>Select recipients: </b> '+
        '<span style="margin-left:10px;text-decoration:underline;color:blue" title="click here to select, or deselect, all recipients" onClick="doSendMessageClick();return false">(select all)</a></span>'+
        '<span style="margin-left:10px;padding-left:6px;border:1px solid gray"><input type="checkbox" name="messageToCheckboxes" value="admin">admin</span>' +
        '<span style="margin-left:10px;"> '+
        '    <input type="button" value="all '+cIds.length+' participants ..."  title="click to toggle display of the clickable-list of participants" '+
        '             onClick="displayDiv(\'listOfParticipants\')" /> '+
        '</span>';

amenu=amenu+'<div id="listOfParticipants" style="display:none"> '+
       '<table border="1" width="90%" style="margin-left:10px"> ';

//<tr><th colspan="'+Math.min(5,cIds.length)+'">Select recipient(s)' +
//       '<span style="margin-left:16px;text-decoration:underline;color:blue" title="click here to select, or deselect, all recipients" onClick="doSendMessageClick();return false">(select all)</a></span>'+
//        '<span style="margin-left:20px;padding-left:6px;border:1px solid gray"><input type="checkbox" name="messageToCheckboxes" value="admin">admin</span>' +
//        '</th></tr>';

ii=0;
if (cIds.length==0) {
  tmp=confirm('No participants available -- would you like to try updating-participants?');
  if (tmp==1) {
        updateCurrentParticipants(1,'doSendMessage') ;
        return 0;
  }
}
for (var m=0;m<cIds.length;m++) {
  if (ii==0) amenu=amenu+'\n<tr>';
  aline='<td><input type="checkbox" name="messageToCheckboxes" value="'+cIds[m]+'"><span style="margin:5px;border:1px dotted gray" title="to participant '+cIds[m]+'">'+currentParticipants[cIds[m]]['NAME']+'</span></td>';
  amenu=amenu+'\n'+aline;
  ii++;
  if (ii>4) {
        ii=0; amenu=amenu+'\n</tr>';
  }
}
if (ii>0) amenu=amenu+'</tr>';
amenu=amenu+'</table></div>';

var aheader='Select who to send the message to, compose your message, and <span style="padding-left:60px"> <input type="button" value="send it" onClick="doSendMessageSend(1)" /> </span>'+
       '<span style="background-color:#99aaee;float:right">'+
       '  <input type="button" style="font-size:90%;float:right;margin-right:10px" value="close" onClick="close_moveBox(7)" />'+
       '  <input type="button" style="font-size:90%;float:right;margin:1px 10px 1px 10px" value="Messages" '+
       '    onClick="doReadMessage(1)"  title="Return to main message screen" />'+
       '</span>';

//      '<input type="button" title="Close this box (do NOT send message)" onClick="close_moveBox(7)" value="close" style="float:right;margin-right:10px" /> ';  

write_moveBox(7,aheader,amenu);  

aa='<div style="margin:6px 3% 3px 4%;background-color:#bebdbe">'+
   '<form name="message1"><table cellspacing="2">'+
   '<tr><td><b>Subject:</b>'+
        '<span style="background-color:#ababab">'+
            '<input type="checkbox" name="messageUrgent" value="1" '+
                    ' title="Check if this is an urgent message" /> '+
          '  <span style="font-size:80%">urgent?</span>'+
       '</span> '+
       '</td> '+
       '<td><input type="text" name="messageSubjectArea" size="80" value="" /></td> '+
   '<tr><th>Message:</th> '+
    '   <td><textarea  name="messageTextArea" rows="3" cols="80"> </textarea> </td>'+
   '</tr></table></form></div>';
writeContent_moveBox(7,aa,1);


aa='<br/><input type="button" value="Send your message" onClick="doSendMessageSend(1)" />';
writeContent_moveBox(7,aa,1);
return 0;
}

//===========================
// click stuff

function doSendMessageClick(ido) {
 var alist,m,i,a1;
            
 alist=document.getElementsByName('messageToCheckboxes');
 for (var m=0;m<alist.length;m++) {
    a1=alist[m];
    a1.checked=!a1.checked
 }
return 0;
}

//===========================
// reallly send a message


function doSendMessageSend(ido) {
 var alist,m,i,a1,jid,toGet,stuff,amess,asubject,topost,aurgent ;

 if (ido==1) {
   stuff='';
   alist=document.getElementsByName('messageToCheckboxes');
   for (var m=0;m<alist.length;m++) {
      a1=alist[m];
      if (a1.checked) stuff=stuff+a1.value+',';
   }
   adate=new Date();

   aurgent=0;
   if (document.message1.messageUrgent.checked) aurgent=1;

   asubject=document.message1.messageSubjectArea.value;
   asubject=escape(asubject);
   amess=document.message1.messageTextArea.value;
//alert('amess '+amess.length);
   amess=escape(amess);

   topost=messageSendPost+'session='+sessName+'&clientList='+stuff+'&fromId=admin&fromName=Administrator&time='+adate.getTime();
   topost=topost+'&urgent='+aurgent+'&subject='+asubject+'&message='+amess;
//   alert('topost1='+topost);

   Post_toServer(postMessageURL,topost,'sendMessageResult','post a message of length '+amess.length,'doSendMessageSend',2);

//   toGet=messageSend+'session='+sessName+'&clientList='+stuff+'&fromId=admin&fromName=Administrator&time='+adate.getTime();
//   toGet=toGet+'&subject='+asubject+'&message='+amess;
//  Get_File(toGet,'sendMessageResult','sending a message','doSendMessageSend',2) ;

   for (var m=0;m<alist.length;m++) {
      a1=alist[m];
      a1.checked=false;
   }

   return 1 ;
  }

  
  writeDoStatus('Message sent to: '+sendMessageResult);
  writeDataMessage('Message sent to: '+sendMessageResult,3);
  doReadMessage(1);
//  close_moveBox(7);

return 1;
}


//=====================
// send a message (reply)
function sendAMessageA(aid,aname,inew,oldSubject) { 
var aa,aname,amess,ato,areply;

if (arguments.length<1) aid='';
if (arguments.length<2) aname='';
if (arguments.length<3) inew=0 ;
if (arguments.length<3) oldSubject='';
oldSubject=strip(oldSubject);
if (oldSubject!=='') oldSubject='Reply to: '+oldSubject ;
areply=' reply ';
if (inew==1) areply=' message ';
aname=strip(aname);

open_moveBox(8);
top_moveBox(8); 

amess='';
if (aname=='') {
   amess=amess+   '<span style="margin:1px 30px 1px 30px;background-color:#ffeedd">Compose a message</span> ';
} else {
   amess=amess+   '<span style="margin:1px 30px 1px 30px;background-color:#ffeedd">Send a '+areply+' to '+aname+'</span> ';
}
amess=amess+' ' +
       '<input type="button" value="Send" title="Send your message" onClick="sendAMessageA2(1,\''+aid+'\',\''+aname+'\')" /> ';

amess=amess+'<span style="float:right;margin-right:5px"><input type="button" value="close" onClick="close_moveBox(8)" /><s/an> ';

aa='<form name="message1"><table cellspacing="2">'; 

aa=aa+' ' +
   '<tr><td><b>Subject:<b> '+
        '<span style="background-color:#ababab">'+
            '<input type="checkbox" name="messageUrgent" value="1" '+
                    ' title="Check if this is an urgent message" /> '+
           ' <span style="font-size:80%">urgent?</span>'+
       '</span> '+
     '</td> '+
       '<td><input type="text" name="messageSubjectArea" size="80" value="'+oldSubject+'" /></td> '+
   '<tr><th>Message:</th> '+
    '   <td><textarea  name="messageTextArea" rows="3" cols="80"> </textarea> </td>'+
   '</tr></table></form>';

write_moveBox(8,amess,aa);
return 0;
}

//==== do the work
function sendAMessageA2(ido,aid,aname) {

 var alist,m,i,a1,jid,toGet,stuff,amess,asubject,topost,aurgent ;
 var myname,myid;

 if (ido==1) { 
   stuff=''; 
   adate=new Date();

   aurgent=0;
   if (document.message1.messageUrgent.checked) aurgent=1;

   asubject=document.message1.messageSubjectArea.value;
   asubject=escape(asubject);
   amess=document.message1.messageTextArea.value;

   amess=escape(amess);

   myname='Administrator';
   myid='admin';

   topost=messageSendPost+'session='+sessName+'&clientList='+aid+'&fromId='+myid+'&fromName='+myname+'&time='+adate.getTime();
   topost=topost+'&urgent='+aurgent+'&subject='+asubject+'&message='+amess;
//   alert('topost2='+topost);

   Post_toServer(postMessageURL,topost,'sendMessageResult','post a message of length '+amess.length,'sendAMessageA2',2);

   return 1 ;

  }

  writeStatus('Message sent to: '+sendMessageResult);
  writeDataMessage('Message sent to: '+sendMessageResult,2);

  close_moveBox(8);

return 1;

}

//=====================
// display a table of the message data specified in a <message> section of most recently
// process CAP file. Display occurs inbox 8
// expects messageData['$capVars']['$list'] to contain a list of variables
// and messageData['$capVars']['$list'][varname] an array of values (for variable varname)
// messageData['$capVars']['$ct] is the size of the largest array (they should all have the
// same length

//function viewMessageData
//   View a table containing the values save in <message> section of most recently created
//   CAP file.

function viewMessageData() {

 var alist,gotid,nct,stuff,m,a1,ii,iv,aline,avar,amess ;

  if (typeof(messageData)=='undefined' || typeof(messageData['$capVars'])=='undefined') {
     alert('Error in viewMessageData: messageData.$capVars variable does not exist ');
     return 0;
  }
  alist=messageData['$capVars']['$list'] ;
  gotid=0;
  if (typeof(messageData['$capVars']['ID'])!=='undefined') gotid=1;

  nct=messageData['$capVars']['$ct'] ;

//alert(gotid+','+nct+' alist ='+alist);     

  stuff='<table border="1" cellpadding="3"> ';
  aline='<tr>';
  if (gotid==1) aline=aline+'<th bgcolor="cyan">ID</th> ';
  for (var m=0;m<alist.length;m++) {
     a1=alist[m];
     if (a1=='ID') continue ;
     aline=aline+'<th>'+a1+'</th>';
  }
  stuff=stuff+aline+'</tr>';
 
  for (ii=0;ii<nct;ii++) {
     aline='<tr>';
     if (gotid==1) {
           aline=aline+'<td bgcolor="cyan">'+messageData['$capVars']['ID'][ii]+'</td>';
    }
     for (var iv=0;iv<alist.length;iv++) {
        avar=alist[iv];
        if (gotid==1 && avar=='ID') continue;
//alert(avar+','+ii);
        aline=aline+'<td>'+messageData['$capVars'][avar][ii]+'</td>';
      }
      aline=aline+'</tr>';
      stuff=stuff+aline;
  }
  stuff=stuff+'</table>';


  doCreateMoveBox(7)  ;
  open_moveBox(7);

  amess='<b>messageData (specified in CAP file) </b>'+
            '<span style="float:right;margin-right:6px"><input type="button" value="close" '+
            '        onClick="close_moveBox(7)" /> </span> ';
  write_moveBox(7,amess,stuff);
  window.scroll(1,1);
  return 0;

}


//=========
// create box 7 and 8 
function doCreateMoveBox(ibox) {
  var acurrent ;

  acurrent=exists_moveBox(7);
  if (acurrent==0) {                     // else, use existing box
     create_moveBox(7,['5%','20%'],['85%','33%'],'Read/send messages ','border=lime boxstyle=border:2px_solid_blue menuadd=moreMenuOptions7 ' ); 
     create_moveBox(8,['1%','55%'],['75%','30%'],'Read/send a message ','border=lime boxstyle=border:2px_solid_blue  menuadd=moreMenuOptions8 ' ); 
  }
  if (arguments.length>0) top_moveBox(ibox);
  return 0 ;
}


