/* This library contains functions that support the admin tools cd lib
   It uses functions in svyInputs2.js and svylibE2.js

 displayInstrumentTable(i)  : display a clickable list of available instruments.
 getInstrumentDescription(ith,ido) : retreive instument descriptor file, and modify a "display this description" link that calls showInstrumentDetails
 showInstrumentDetails()  : display instrument details
 checkSessionName(a1,ido)   : check that a chosen session name is valid
 makeSession(todo)       : create a new session, given a selected instrument

 displaySessionsTable(i,domods,defSess) : display a clickable list of current sessions 
 getSessionDescription(ith,domods,ido,autodo) : retrieve session descriptor file. Modify display of a few elements, including a link to showSessionDetails
 addSessionModifierButtons()  : called by getSessionDescription -- will display buttons that allow one to edit parameter files
    Note: addSessionModifierButtons creates links that call the modifySessions, modifyGeneral, and modifyReference functions in svyModParamFiles.js
 showSessionDetails(useID,useNode,useNodeName,useInput,suppress) :  display session details, possibly display other stuff

 lookupNodeVar(pnode,daVar,adef,doall)  :  Lookup a variable in node containing an XML file, return its value.


* /

/* --- user changeable parameters --- */                        
/* Number of columns in display table (of available instruments) */
nColumns=6 ;

/* number of columns in table of input-file values */
refNodesCols=8 ;                      

inputRowColor=[];                               // colors used in input row table
inputRowColor[0]='#ebebeb' ;
inputRowColor[1]='#dadada' ;

/* write debug alerts (if 1) */
doDebug=1 ;

/* --- end of user changeable parameters --- */


var instList ;                          // global containing a list of XML files (that are "instrument descriptor files")
var currentInst=-1;                     // indicate the currently selected instrument 
var useName='';                             // session name to use 
var useProject='';                             // session project to use 
var useNameFull='';                             // full session name to use 
var instNode='';                            // dom node of the XML instrument desriptor file ('' means "none loaded")
var useDesc='';                             // description of the session.


var instName='';                            // name of the instrument (pulled from instrument descriptor file, and not necessarily same as the filename of the instrument descriptor file 
var instDesc=''        ;                    // description of the instrument (pulled from instrument descriptor file)
var instPfile='',instIfile='';          // param_file and input_file (for currently selected instrument)
var sessName='';

refNodes=[];                            // the nodes, and info about nodes, from the INPUT file
refNodesVarlist='' ;
refNodesIDS=[];
refNodesDESC=new Object() ;

var paramFileNode=0;                   // used to store node containing a session specific parameter file 

/* the following IDS must be available (in the page that calls these functions)
   instrumentTable  : table where clickable  list of current instruments are displayed
   instrumentDetails : table tbody where details on the variables defined in the instrument file are displayed
   instrumentDetails2 : table tbody where details on the files defined in the instrument file are displayed
   selectedInstrumentName : name of the selected instrument (changes when you click on an instrument name)
   selectedInstrumentDesc : description of the selected instrument (changes when you click on an instrument name)
   currentInst : used to display name of currently selected instrument
   currentInst2 : used to display name of currently selected instrument

   sessionName : input field for entering the name of the new session
   sessionDesc: input field for entering the description of the new session
   doit: Button to create the session (causes a submit)
   makeSessionStatus: used to display the results of the session creation (uses server response)
   currentSessionName: used to display name of current session
   selectedSessionName: name of the selected session (changes when you click on an session name)
   selectedSessionDesc:  description of the selected session (changes when you click on an session name)
   sessionDetails: details on a selected session
   workArea0 : xml file contents to be modified: the div containing workarea. display css attribute should be changed
   workArea : xml file contents to be modified: the table to write variables to
   modifyIt: input for submitting the modified parameters or input file
   dataCell : cell for "change parameter files" buttons are placed  

*/



/* =================================== */
/* call this when list of instruments returned
 Display in a table, with each cell containing clickable name.
 When clicked, get xml file and display name and description
 */

function displayInstrumentTable(i,adef) {
var id1,atr,m,atd,arf,aname,atr,ict,aa ;
var wasproj,aproject ;
var instPfile='',instIfile='';          // param_file and input_file (for currently selected instrument)
var uu;
var mdef=-1;

if (arguments.length<2) {
        adef='';
} else {
  adef=strip(adef).toUpperCase()+'.XML';
 adef=adef.substr(1);
}

instList=getWord(instList);
instList=instList.sort();               // sort it!

id1=document.getElementById('instrumentTable');
atr=document.createElement('tr');
id1.tBodies[0].appendChild(atr);
ict=0;
wasproj='';
for (var m=0; m<instList.length;m++) {

  ainst=instList[m];

  if (strip(ainst).toUpperCase()==adef) mdef=m;

  uu=extractProjectName(ainst);
  aname=uu[0];
  aname=aname.replace(/\..*/g,'');   // remove .xxx
  aproject=uu[1];
  if (m==0) {
      atd=document.createElement('td');
      atd.innerHTML='<span title="Project">'+aproject+'</span>';
      atd.style.backgroundColor='#efefef';
      aa=aproject; if (aa=='') aa='(none)';
      atd.innerHTML='<span title="Project">'+aa+'</span>';
      atr.appendChild(atd);
      wasproj=aproject;
  }
  ict++ ;
  if (ict>=nColumns || aproject!==wasproj) {                  // new row 
      atr=document.createElement('tr') ;
      id1.tBodies[0].appendChild(atr) ;
      ict=0 ;
      atd=document.createElement('td') ;
      atd.style.backgroundColor='#efefef' ; 
      aa=aproject; if (aa=='') aa='(none)';
      atd.innerHTML='<span title="Project">'+aa+'</span>';
      atr.appendChild(atd) ;
      wasproj=aproject ;
  }
  atd=document.createElement('td');
  atd.setAttribute('id','cell'+m);

  arf='<div title="select this instrument" onClick=" getInstrumentDescription('+m+')" > '
  arf=arf+  aname +'</div>'
  atd.innerHTML=arf;
  atd.style.textDecoration='underline' ;
  atd.style.color='blue' ; 

  atr.appendChild(atd);
}                       // for

if (mdef>-1) {
 getInstrumentDescription(mdef)
}

}

/* ================================================================== */
/* retrieve an XML "instrument" descriptor file. This is an XML file with a particular structure (see lookupNodeVar for details)
   Will read the "ith" array element from instList, where instList is created by displayInstrumentTable.
   Typically, this is called after a click on a link.
   After reading XML file (using ajax), extract the name and description nodes. 
*/
function getInstrumentDescription(ith,ido) {

  var uu0,uu,tm2;
  var aname,adesc,iname,idesc,icurrent,tmp,isessid ;
  if (arguments.length<2) ido=0 ;

 if (ido==0) {
    var toget=getInstrumentURL+instList[ith];
    Get_xmlFile(toget,'instNode','retrieving xml instrument file ','getInstrumentDescription',ith,2,instList[ith]) ;
    return 0;
  }
  if (ido==2) {
      currentInst=ith ;                             // set the current instrument global
      instName= strip(lookupNodeVar(instNode,'name'));
      instDesc= lookupNodeVar(instNode,'DESCRIPTION');
     idesc=document.getElementById('selectedInstrumentDesc');
     idesc.innerHTML=instDesc; 
     icurrent=document.getElementById('currentInst');
     tmp=instList[ith].replace(/\..*/,'');tmp=makeProjName(tmp);
//     icurrent.setAttribute('value',instList[ith].replace(/\..*/,''));
     icurrent.setAttribute('value',tmp);
    icurrent.style.color='darkred';
     icurrent=document.getElementById('currentInst2');

     isessid=document.getElementById('sessionName');
     if (isessid) isessid.style.backgroundColor='#fefefe';

     isessid=document.getElementById('sessionProject');
     if (isessid) isessid.style.backgroundColor='#fefefe';
 
     uu0=instList[ith].replace(/\..*/,'')
     uu=extractProjectName(uu0);
     tmp2=makeProjName(uu0);
     icurrent.innerHTML=' <u>'+makeProjName(tmp2)+'</u> ';
      iname=document.getElementById('selectedInstrumentName');
      iname.innerHTML='<span onClick="showInstrumentDetails()" style="color:blue;text-decoration:underline" id="dname2">'+makeProjName(instName)+'</span>' ;
 
// supress readonly on sessionName (if it exists)
     tmp=document.getElementById('sessionName');
     if (tmp) {
        tmp.setAttribute('readOnly',false);
        tmp.readOnly=false;
        if (tmp.title==''){
            tmp.title='Enter session name here ';
            tmp.setAttribute('title','Enter session name here ');
        }
     }
// supress readonly on sessionProject (if it exists)
     tmp=document.getElementById('sessionProject');
     if (tmp) {
        tmp.setAttribute('readOnly',false);
        tmp.readOnly=false;
        if (tmp.title==''){
          tmp.title="Enter the session's project here ";
          tmp.setAttribute('title',"Enter the session's project here ");
        }
        tmp.value=uu[1]; 
       }

     tmp=document.getElementById('doit');
     if (tmp) {
        tmp.setAttribute('readOnly',false);
        tmp.readOnly=false;
        tmp.title='Click here to create the new session ';
        tmp.setAttribute('title','Click here to create the new session ');
      }


     return 1 ;
  }
}
// uu
// ===============================  id( currentInst sessionName 
// Show the details of the instrument (use instNode)

function showInstrumentDetails() {
  var descs=new Object() ;
  var descsList=[];

  var ttr,ttd,tstuff,tth,thevar,thedesc,theval,m,ttnbody,ttn,m2,imm,tspan;

  var vvals=new Object();
  var vvalsList=[], fileVars=[] ;
 
  for (var m=0 ; m<instNode.childNodes.length;m++) {
      cnode=instNode.childNodes[m]
      atype=cnode.nodeType ;
      if (atype!=1 ) continue ;
      aname=cnode.nodeName ;
      taname=strip(aname.toUpperCase());
       aval='';
      if (taname=="DESC") {                              // a description node
         aval=getAttributes(cnode,'value','')  ;
         cval=E2_getNodeText(cnode,1,'');
         taval=strip(aval.toUpperCase());
         if (typeof(descs[taval])=='undefined') descsList=descsList.concat(taval);
         descs[taval]=cval;
         continue ;
      }

      if (taname=="FILE") {                              // a file node
         atype=getAttributes(cnode,'type','')  ;
         atype=strip(atype.toUpperCase()) ;
         aname=' DATA CONTROL ';
         if (aname.indexOf(' '+atype+' ')<0 ) { 
            alert(' Error: unknown file type = '+atype);
            return 0;
        }
         aname=getAttributes(cnode,'name','')  ;
         cval=E2_getNodeText(cnode,1,'');
         goo=new Object();
         
         goo.Type=atype ; goo.Name=aname; goo.Value=cval ;
         fileVars=fileVars.concat(goo);
      }

// else, a variable node
        cval=E2_getNodeText(cnode,1,'');
      if (typeof(vvals[taname])=='undefined') vvalsList=vvalsList.concat(taname);
      vvals[taname]=cval ;       
   }


// display table of variables
  ttnBody=document.getElementById('instrumentDetails');
  removeChildren(ttnBody,1);

  ttr=document.createElement('tr');

  tth=document.createElement('th');
  tstuff=document.createTextNode('Variable Name');
  tth.appendChild(tstuff);
  ttr.appendChild(tth);

  tth=document.createElement('th');
  tstuff=document.createTextNode('Description');
  tth.appendChild(tstuff);
  ttr.appendChild(tth);

  tth=document.createElement('th');
  tstuff=document.createTextNode('Value');
  tth.appendChild(tstuff);
  ttr.appendChild(tth);

  ttnBody.appendChild(ttr);


for (var m=0;m<vvalsList.length;m++){

  thevar=vvalsList[m];
  thedesc='';
  if (typeof(descs[thevar])!=='undefined') thedesc=descs[thevar];
  theval=vvals[thevar];

  ttr=document.createElement('tr');

  tth=document.createElement('th');
  tstuff=document.createTextNode(thevar);
  tth.appendChild(tstuff);
  ttr.appendChild(tth);

  ttd=document.createElement('td');
  tspan=document.createElement('span');
  thedesc=thedesc.replace(/\[p\]/ig,'<p/>');
  thedesc=thedesc.replace(/\[br\]/ig,'<br/>');

  tspan.innerHTML=thedesc ;
//  tspan=document.createTextNode(thedesc);
//  tstuff=document.createTextNode(thedesc);
//  ttd.appendChild(tstuff);
  ttd.appendChild(tspan);

  ttd.style.fontStyle='italic';

  ttr.appendChild(ttd);

  ttd=document.createElement('td');
  tstuff=document.createTextNode(theval);
  ttd.appendChild(tstuff);
  ttd.style.fontFamily='courier';
  ttr.appendChild(ttd);

  ttnBody.appendChild(ttr);
}



// display table of variables
  ttnBody=document.getElementById('instrumentDetails2');
  removeChildren(ttnBody,1);

  ttr=document.createElement('tr');

  tth=document.createElement('th');
  tstuff=document.createTextNode('Descriptive Name');
  tth.appendChild(tstuff);
  ttr.appendChild(tth);


  tth=document.createElement('th');
  tstuff=document.createTextNode('Type');
  tth.appendChild(tstuff);
  ttr.appendChild(tth);

  tth=document.createElement('th');
  tstuff=document.createTextNode('Description');
  tth.appendChild(tstuff);
  ttr.appendChild(tth);

  tth=document.createElement('th');
  tstuff=document.createTextNode('File Name');
  tth.appendChild(tstuff);
  ttr.appendChild(tth);

ttnBody.appendChild(ttr);

// display table of filenames
for (var m=0;m<fileVars.length;m++){

  ttr=document.createElement('tr');

  tth=document.createElement('th');
  tstuff=document.createTextNode(fileVars[m].Name);
  tth.appendChild(tstuff);
  ttr.appendChild(tth);

  tth=document.createElement('th');
  tstuff=document.createTextNode(fileVars[m].Type.toUpperCase());
  tth.appendChild(tstuff);
  ttr.appendChild(tth);

  thevar=strip(fileVars[m].Name.toUpperCase());
  thedesc='';
  if (typeof(descs[thevar])!=='undefined') thedesc=descs[thevar];
  ttd=document.createElement('td');
  tstuff=document.createTextNode(thedesc);
  ttd.appendChild(tstuff);
  ttd.style.fontStyle='italic';
  ttr.appendChild(ttd);

  ttd=document.createElement('td');
  tstuff=document.createTextNode(fileVars[m].Value);
  ttd.appendChild(tstuff);
  ttd.style.fontFamily='courier';
  ttr.appendChild(ttd);

  ttnBody.appendChild(ttr);
}


return 1;
}



/* =================================== */
/* call this when list of sessions returned
 Display in a table, with each cell containing clickable name.
 When clicked, call getSessionDescription: which will get xml file and display name and description
 (what is displayed depends on domods)
 */

function displaySessionsTable(i,domods,defSess) {
var id1,atr,m,atd,arf,aname,atr,ict,isuspend,doDef=-1,wasproj,aproject,tanamefull ;
var taname,ss,m0,dosess,quickLink,arfQ ;
var vv,latestSession;
var projLists={}, projLists1=[];projListsLinks={};
var dosessp,ttable,thisproj,ttable,atr,tmp,ss,bigtable,dosess;
id1=document.getElementById('_sessionsTableDiv');

if (!id1 || 10==1) {                     // use old version
  displaySessionsTableOld(i,domods,defSess)
  return 1 ;
}

if (arguments.length<2) domods=0 ;                      // domods=1 : create buttons to modify an OBS or GENERAL file 
if (arguments.length<1) i=1 ;
if (arguments.length<3) defSess='';           defSess=strip(defSess.toUpperCase()) ;

isuspend=0;
if (i==11) {
  isuspend=10;
  i=1;
}

vv=parseAt(sessionList,' ; ');
sessionList=vv[0];
if (vv.length>1) {
   latestSession=strip(vv[1]);
   latestSession= latestSession.replace(/\..*/g,'');
}
        
quickLink='';
sessName='';          // param_file and input_file (for currently selected session)
sessionList=getWord(sessionList);
sessionList=sessionList.sort();

// seperate into projects
for (var m=0; m<sessionList.length;m++) {
  anamefull=sessionList[m];
   anamefull=anamefull.replace(/\..*/g,'');
  tanamefull=strip(anamefull).toUpperCase();

  uu=extractProjectName(anamefull);
  aname=uu[0];
  aproject=uu[1]; aproject=strip(aproject).toUpperCase();

  if (strip(aproject)=='') aproject='0' ;

  if (typeof(projLists[aproject])=='undefined')  {
        projLists[aproject]=[];
        projListsLinks[aproject]=[];
        projLists1=projLists1.concat(aproject);
   }
   projLists[aproject][projLists[aproject].length]=anamefull

  var varf='sessionTableValue_'+tanamefull;
  arf='<div title="click to chose this session" id="'+varf+'" onClick="getSessionDescription('+m+','+domods+','+isuspend+',1)" >  ';

  arfQ=arf+ '<span title="The most recently created session">Join:</span> <span style="text-decoration:underline;color:blue"> '+  makeProjName(anamefull)+' </span> '+
               '<em>... or choose a session from below</em> </div>';
  arf=arf+ '<span style="text-decoration:underline;color:blue">'+  aname +'</span></div>';
  if (anamefull==latestSession) { quickLink='<div style="margin:1px 5% 4px 5%;border:1px dotted #ababab">'+arfQ+'</div>' ; }

  projListsLinks[aproject][projListsLinks[aproject].length]=arf ;
}


// now display each project's sessions in a seperate table  
bigtable=quickLink+ '<table>';

for (var m0=0; m0<projLists1.length;m0++) {
  aproject=projLists1[m0];
  dosess=projLists[aproject];
  dosessp=projListsLinks[aproject];


  ttable=makeATable(dosessp,8,'',0,' frame="outer" cellpadding="5" ');
  thisproj='aproject_'+aproject ;
  ttable='<div id="'+thisproj+'" style="display:none">\n'+ttable+'\n</div>'
  atr='<tr><td> ' ;
     tmp="toggleDisplayProject('"+thisproj+"')";
     ss='<input id="toggleMe_'+m0+'" onClick="'+tmp+'" type="checkbox" name="toggleDisplayInput"  avalue="'+thisproj+'" '; 
            ss=ss+' style="font-size:60%" title="toggle display of this project\'s sessions">';
            if (aproject=='0') {
                ss=ss+'<label for="toggleMe_'+m0+'"><span id="toggleMe_'+m0+'"  title="Sessions not assigned to a project">(no project) <em>('+dosess.length+') </em></span></label> ';
            } else {
               ss=ss+'<label for="toggleMe_'+m0+'"><span title="Project">'+aproject+' <em>('+dosess.length+')</em> </span></label>';
            }
     atr=atr+ss+'</td><td>'+ttable+'</td></tr>\n';
  bigtable=bigtable+atr;
}
bigtable+'\n</table>';
id1.innerHTML=bigtable ;

return 1;

}


//============
// toggle off, or on, display of all sessions in each project
function checkAllBoxes(i) {
var vv,ii,aproj;

if (typeof(openAllBoxes)=='undefined') openAllBoxes='none';   // this should be initialized already

if (openAllBoxes=='none') {
     openAllBoxes='block'; 
} else {
   openAllBoxes='none';
}

vv=document.getElementsByName('toggleDisplayInput');

for (var ii=0;ii<vv.length;ii++) {
  if (openAllBoxes=='block') {
      vv[ii].checked=true ; 
  } else {
     vv[ii].checked=false ;
  }

  aproj=getAttributes(vv[ii],'avalue','');
  toggleDisplayProject(aproj,openAllBoxes);
}

}

//=============
// toggle display of a div
function toggleDisplayProject(thisproj,todo) {
var thisproj,id1,id2,tmp;
  id1=document.getElementById(thisproj);
  if (!id1) return 1 ;
  if (arguments.length<2) {
    if (id1.style.display=='none') {
        id1.style.display='block' ;
    } else {
          id1.style.display='none' ;
    }
  } else {
        id1.style.display=todo ;
  }
  return 1 ;
}
   

/* =================================== */
/* OLD version: call this when list of sessions returned
 Display in a table, with each cell containing clickable name.
 When clicked, call getSessionDescription: which will get xml file and display name and description
 (what is displayed depends on domods)
 */

function displaySessionsTableOld(i,domods,defSess) {

var id1,atr,m,atd,arf,aname,atr,ict,isuspend,doDef=-1,wasproj,aproject,tanamefull ;
var taname,ss ;

if (arguments.length<2) domods=0 ;     // domods=1 : create buttons to modify an OBS or GENERAL file 
if (arguments.length<1) i=1 ;
if (arguments.length<3) defSess='';           defSess=strip(defSess.toUpperCase()) ;

isuspend=0;
if (i==11) {
  isuspend=10;
  i=1;
}

sessName='';          // param_file and input_file (for currently selected session)


sessionList=getWord(sessionList);
sessionList=sessionList.sort();
id1=document.getElementById('sessionsTable');
if (!id1) id1=document.getElementById('_sessionsTable');
ict=0;
wasproj='';

for (var m=0; m<sessionList.length;m++) {
  
  anamefull=sessionList[m];
  anamefull=anamefull.replace(/\..*/g,'');
  tanamefull=strip(anamefull).toUpperCase();
  
  uu=extractProjectName(anamefull);
  aname=uu[0];
  taname=strip(aname).toUpperCase();

  aproject=uu[1]; aproject=strip(aproject).toUpperCase();

  if (m==0 || ict>=nColumns || wasproj!==aproject) {                  // new row 
      atr=document.createElement('tr');
      atd=document.createElement('td');
      atd.style.backgroundColor="#efefef";
      if (aproject!=='') {
         ss='<span title="Project">'+aproject+'</span>'
      } else {
         ss='<span title="not assigned to a project">(none)</span>'
      }
      atd.innerHTML=ss;
      atr.appendChild(atd);
      
      id1.tBodies[0].appendChild(atr);
      wasproj=aproject;
      ict=0;
  }

  var varf='sessionTableValue_'+tanamefull;
  if (typeof(_suppressSessionTableClick)=='undefined' || _suppressSessionTableClick!==1) {
     arf='<div title="click to chose this session" id="'+varf+'" onClick="getSessionDescription('+m+','+domods+','+isuspend+',1)" >  ';

    arf2='<span style="text-decoration:underline;color:blue">'+  aname +'</span>';
    arf=arf+  arf2 +'</div>'

  } else {
     arf='<div>'+ aname +'</div>'
     atd.style.color='#443322' ; 
  }
  atd=document.createElement('td');
  atd.setAttribute('id','cell'+m);
  atd.innerHTML=arf;

  atr.appendChild(atd);
  ict++ ;
  if (strip(aname.toUpperCase())==defSess) doDef=m ;
}
if (doDef!=-1)   getSessionDescription(doDef,domods,isuspend,1);

return 1;
}


/* ================================================================== */
/*    Retrieve, from the web-server, an XML "session" descriptor file. 
      Typically, this function is called via an onClick

      After retrieving the XML file (using ajax), extract the name and description nodes; and display them in elements (DIVs and SPANS)
      that have the following IDS.
        currentSessionName:  input, or other area, where the name of the currently selected session is displayed. 
        selectedSessionDesc:  area where a  short description of the currently selected session (as read from the session descriptor file)  is displayed. 
        selectedSessionName:  area where name of  currently selected session  is displayed.  
        sessionDetails: area where display session details are displayed (see  showSessionDetails() below)

        currentSessionName, selectedSessionName and selectedSessionDesc change when you click on a session button
        currentSessionName and , selectedSessionName show the same information
                currentSessionName is often used in, or near, a "select this session" box
                selectedSessionName is often in a decriptive area, near tsessionDetails and selectedSessionDeac       
        sessionDetails is used when you click on a clickable link stored in the selectedSessionName, that calls getSessionDescription()

  For some domodes, a saveButton element must exist (domod 3 and 1)

  ith  : the "ith" array element from sessionList

  domods controls details of presentation:
     0 :  Display  an "open control panel" button
     1 :  On click of session, call  addSessionModifierButtons (see below). Also suppress display of "open control panel" button
     2 : Suppress suppress display of both the session details header, and the link to dipslay details
     3 : Add  a button to call a custom function (i.e.; the "modify allowed users" button)

  ido :  if 10, look for suspended sessions. If 1 (or not specified), look for active sessions

  autodo: If 1, then double clicking session name mimics pushing the submit button


*/
function getSessionDescription(ith,domods,ido,autodo) {

 var sessionName,toget,sessCreated,sessDesc,ii,idesc,iname,icurrent,wasc,newc;

  if (arguments.length<3) ido=0 ;
  if (arguments.length<2) domods=0 ;
  if (arguments.length<4) autodo=0 ;
   isuspend=0;
   if (ido==10) {
        isuspend=1;
        ido=0;
     }

 if (ido==0) {
    sessionName=sessionList[ith].replace(/\..*/,'');
    sessName=sessionName ;
    if (isuspend!=1) { 
       var toget=getSessionDescriptorURL+sessionName ;
    } else {
       var toget=getSuspendedDescriptorURL+sessionName ;
     }
    Get_xmlFile(toget,'sessionNode','retrieving xml session file ','getSessionDescription',ith,domods,2,1) ;
    return 0;
  }

  if (ido==2) {                                 // here after response from server

   if (domods==1)       {                               // display buttons to modify a session descriptor file,  FILE
     addSessionModifierButtons() ;
  } 

// addCustomButton should be a function in the calling program
   if (domods==3)       {                               // display buttons to modify a session descriptor file,  FILE
     if (typeof(addCustomButton)!='function') {
          alert(' Error: no addCustomButton function has been defined ');
          return 0;
     }
     addCustomButton() ;
     icurrent=document.getElementById('currentSessionName');
     if (!icurrent)   icurrent=document.getElementById('_currentSessionName');
     if (icurrent) icurrent.value=makeProjName(sessName);

  } 

//currentSessionNa

   sessCreated= strip(lookupNodeVar(sessionNode,'created'));
   sessDesc= lookupNodeVar(sessionNode,'sessionDescription');
   sessionName= lookupNodeVar(sessionNode,'sessionName');

    idesc=document.getElementById('_selectedSessionDesc');
    if (!idesc)     idesc=document.getElementById('selectedSessionDesc');
    idesc.innerHTML=sessDesc;
    iname=document.getElementById('_selectedSessionName');
    if (!iname) iname=document.getElementById('selectedSessionName');
    if (domods!=2) {
       iname.innerHTML='<span onClick="showSessionDetails()" style="color:blue;text-decoration:underline" id="dname2">'+makeProjName(sessionName)+'</span>' ;
    } else {
       iname.innerHTML='<span   style="font-weight:500" >'+makeProjName(sessionName)+'</span>' ;
    }        
 
    try {
       icurrent=document.getElementById('currentSessionName');
       if (!icurrent)   icurrent=document.getElementById('_currentSessionName');
    }
    catch(err) {
        alert('Warning: problem reading "currentSessionName" element. You might have to reload this page ');
        return 0;
    }
    wasc=icurrent.getAttribute('value');                            // used to implement double click submit
    newc=sessionList[ith].replace(/\..*/,'') ;
    newc=makeProjName(newc);
    icurrent.setAttribute('value',newc);

    if (domods!=2) {
      icurrent=document.getElementById('_sessionDetails');
      if (!icurrent) icurrent=document.getElementById('sessionDetails');

      icurrent.innerHTML='';
    }

    ii=document.getElementById('saveButton');
    if (!ii)     ii=document.getElementById('_saveButton'); 
    
    if (ii) {

       if (domods==0 ) {
             if (ii)  {
                if (ii.value=='') {
                         ii.value=makeProjName(sessName) ;
                } else {
                       var foo=ii.value.split(':') ;
                       foo[1]=sessName;
                       ii.value=foo[0]+': ' + makeProjName(foo[1]);
                }
             }
       }
       if (autodo==1) {
             if (wasc==newc) ii.click();
       }
    }                      // saveButton exists ;


    return 1 ;

  }                             // ido=2 byid
}





//=======================================
/* add session modifier buttons for currently selected session (in global sessName, with XML node in sessionNode)
   Uses the following ids for display
        dataCell: area where file-modification buttons are added (domod=1)
        saveButton:   An "open control panel" button (button text can be changed)
        paramsTable : stub of a table used to display parameter values (domod=1)
        displayArea: div that contains paramsTable 
*/

function addSessionModifierButtons() {

var gnoodes,i1,atd,aspan,astuff,m,anode,dafile,aname,aspan,tinput,glub,icurrent,atr,ab;


   gnodes=E2_getNodes(sessionNode,'FILE');
   i1=document.getElementById('modifyButtons');
   try {
     i1.innerHTML='';
   }
   catch(err) {
   }
   
/* top line: modify descriptor file button */
  atr=document.createElement('tr');
    atd=document.createElement('td'); 
        astuff=document.createTextNode('For session: ') ; 
        ab=document.createElement('b'); 
           astuff2=document.createTextNode(sessName) ;  
           ab.appendChild(astuff2)
     atd.appendChild(astuff);
     atd.appendChild(ab);
   atr.appendChild(atd);
     atd=document.createElement('td'); 
     tinput=document.createElement('input');
           tinput.value=' Modify  session-descriptor file' ;
           tinput.type='button' ;
           tinput.setAttribute('onClick','modifySession()');
           atd.appendChild(tinput);
   atr.appendChild(atd);
   atr.style.color='blue';
   atr.style.height='50px';  
   i1.appendChild(atr);        

  atr=document.createElement('tr');
     atd=document.createElement('td');
        atd.style.textAlign='center'; atd.style.border='1px solid gray  ';
           astuff=document.createTextNode('Administrative parameter files files used in this session ...') ; 
     atd.appendChild(astuff);     
     atd.setAttribute('colspan',2);
   atr.appendChild(atd);
   i1.appendChild(atr);        
    
  atr=document.createElement('tr');
     atd=document.createElement('th');
        astuff=document.createTextNode('File Description') ;      
        atd.appendChild(astuff);
   atr.appendChild(atd);
     atd=document.createElement('th');
        astuff=document.createTextNode('Modify data sections:') ;      
        atd.appendChild(astuff);
   atr.appendChild(atd);
   i1.appendChild(atr);        

/* for each FILE, modify GENERAL REFRENCE, and USERS sections. Can be suppressed */
  for (var m=0;m<gnodes.length;m++){
        anode=gnodes[m];
        dafile=E2_getNodeText(anode,1,'');
        if (dafile=='') continue ;                      // missing file name, just skip it
        atype=getAttributes(anode,'type',''); atype=strip(atype.toUpperCase());
        if (atype!='DATA') continue ;                   // not DATA type, so can't modify it

        aname=getAttributes(anode,'name','');  if (aname=='') aname=dafile ;
        acontains=strip(getAttributes(anode,'contains','')); 
        if (acontains==0 || acontains=='' || acontains=='*') {
          acontains=' GENERAL REFERENCE USERS ';
        } else {
           acontains=' '+acontains.toUpperCase()+' ';
        }

        atr=document.createElement('tr');
           atd=document.createElement('th');
             aspan=document.createElement('span');  aspan.style.border="1px solid blue";
             astuff=document.createTextNode(aname) ; 
             aspan.appendChild(astuff);
           atd.appendChild(aspan);
        atr.appendChild(atd);

         atd=document.createElement('td');

        if (acontains.indexOf(' GENERAL ')>-1) {         
          tinput=document.createElement('input');
             tinput.value=' GENERAL ' ;
             tinput.type='button' ;
             tinput.setAttribute('onClick','modifyGeneral("'+dafile+'")');
          atd.appendChild(tinput)
        }

        if (acontains.indexOf(' REFERENCE ')>-1) {         
          tinput=document.createElement('input');
             tinput.value=' REFERENCE ' ;
             tinput.type='button' ;
             glub=make_procString('modifyReference',dafile,'REFERENCE');
             tinput.setAttribute('onClick',glub);
          atd.appendChild(tinput)
        }

        if (acontains.indexOf(' USERS ')>-1) {         
         tinput=document.createElement('input');
             tinput.value=' USERS ' ;
             tinput.type='button' ;
              glub=make_procString('modifyReference',dafile,'USERS');
              tinput.setAttribute('onClick',glub);
          atd.appendChild(tinput)
         }

         atr.appendChild(atd);                          // attach to this file's row 
         i1.appendChild(atr);                           // attach row to table 

      }

      icurrent=document.getElementById('paramsTable');
      icurrent.innerHTML='<tr><th width="15%"></th><th width="35%"></th><th width="50%"></th>  ';

      icurrent=document.getElementById('displayArea'); 
      icurrent.style.display='none';

   return 1 ;
}



// =============================== 
/* Show the details of the session (use sessionNode)
   sessionDetails is used as element id if useID not specified 
   sessionNode is used as node element if useNode not specified 
   if useNodeName specified, just show parameters in the subsection "useNode" that is th useNodeName element
   if useInput=1, then display using INPUT fields. These input fields will have the following attributes:
        value: the current value (changeable!)
        'class'='aParameter'   --  used by other procedures to find input nodes (so as to update xml parameters)
         'var' : the variable name
         'array': 1 if array="1" specified
         'desc' : description, if one exists, for this variable
   suppress :if specified, space delimited list of variables that SHOULD NOT be changeable (that is, suppresses useInput on a variable specific basis)
*/

function showSessionDetails(useID,useNode,useNodeName,useInput,suppress) {


   if (arguments.length<1) useID="_sessionDetails" ;
  if (!document.getElementById(useID)) useID="sessionDetails" ;
  if (arguments.length<2) useNode=sessionNode ;
  if (arguments.length<3) useNodeName='';
  if (arguments.length<4) useInput=0;  
  if (arguments.length<5) suppress='' ;  suppress=' '+suppress.toUpperCase()+' ';

  displayDiv(useID);

  useNodeName=strip(useNodeName);

  var ttr,ttd,tstuff,tth,thevar,thedesc,theval,m,ttnbody,ttn,m2,tinput,foo,foo2,isarray,tspan;
   var dodiv,ttable;
  var descs=new Object() ;
  var descsList=[];

  var vvals=new Object();
  var vvalsList=[],vvalsArray=[] ;

  if (useNodeName!='') {                        // use a section (i.e.; the "general" or "users" section)
      foo=E2_getNodes(useNode,useNodeName);
      if (foo.length==0) {
           m=document.getElementById('statusMessages'); m.style.display='block';
           m.innerHTML='The '+filename+' parameters file does not have a GENERAL section. ';
           m=document.getElementById('displayArea');  m.style.display='none'; 
           return 1;
       }
       useNode=foo[0];
  }

  for (var m=0 ; m<useNode.childNodes.length;m++) {
      cnode=useNode.childNodes[m]
      atype=cnode.nodeType ;
      if (atype!=1 ) continue ;
      aname=cnode.nodeName ;
      taname=strip(aname.toUpperCase());
       aval='';
      if (taname=="DESC") {                              // a description node
         aval=getAttributes(cnode,'value','')  ;
         cval=E2_getNodeText(cnode,1,'');
         taval=strip(aval.toUpperCase());
         if (typeof(descs[taval])=='undefined') descsList=descsList.concat(taval);
         descs[taval]=cval;
         continue ;
      }
// else, a variable node
      cval=E2_getNodeText(cnode,1,'');
      isarray=getAttributes(cnode,'array','');
      if (typeof(vvals[taname])=='undefined') {
                vvalsList=vvalsList.concat(taname);
                vvalsArray=vvalsArray.concat(isarray);
                vvals[taname]=cval ;       
        } else {
                vvals[taname]=vvals[taname]+ ' | ' + cval ;       
        }
   }


  dodiv=document.getElementById(useID);
  dodiv.innerHTML='';

ttable=document.createElement('table');
 ttable.setAttribute('border',1);

ttnBody=document.createElement('tbody');

  ttr=document.createElement('tr');
  tth=document.createElement('th');
  tstuff=document.createTextNode('Variable Name');
  tth.appendChild(tstuff);
  tth.setAttribute('width','15%');
  tth.style.width='15%';  
  ttr.appendChild(tth);

  tth=document.createElement('th');
  tstuff=document.createTextNode('Description');
  tth.appendChild(tstuff);  
  tth.setAttribute('width','35%');
  tth.setAttribute('bgcolor','yellow');
  tth.style.color='red';
  tth.style.width='35%';  
 
  ttr.appendChild(tth);

  tth=document.createElement('th');
  tth.setAttribute('width','50%');
  tstuff=document.createTextNode('Value');
  tth.appendChild(tstuff);
  tth.style.width='50%';  
  ttr.appendChild(tth);

ttnBody.appendChild(ttr);

for (var m=0;m<vvalsList.length;m++){

  thevar=vvalsList[m]; isarray=vvalsArray[m];
  thedesc='';
  if (typeof(descs[thevar])!=='undefined') thedesc=descs[thevar];
  theval=vvals[thevar];

  ttr=document.createElement('tr');

  tth=document.createElement('th');
  tth.setAttribute('width','15%');
  tth.style.width='15%';  
  tstuff=document.createTextNode(thevar);
  tth.appendChild(tstuff);
  ttr.appendChild(tth);

  ttd=document.createElement('td');
  ttd.setAttribute('width','35%');
  ttd.style.width='35%';  
  tspan =document.createElement('span');
  thedesc=thedesc.replace(/\[p\]/ig,'<p/>');
  thedesc=thedesc.replace(/\[br\]/ig,'<br/>');
  tspan.innerHTML=thedesc+' &nbsp; ';
  ttd.appendChild(tspan);
  ttd.style.fontStyle='italic';
  ttr.appendChild(ttd);

  ttd=document.createElement('td');
  ttd.setAttribute('width','50%');
  ttd.style.width='50%';  
  foo=' '+strip(thevar.toUpperCase())+' ' ;
  foo2=suppress.indexOf(foo);

  if (useInput==0) {
    tstuff=document.createTextNode(theval);
    ttd.appendChild(tstuff);
  } else {
    if (theval.length<60) {
       tinput=document.createElement('input');
    } else {
       tinput=document.createElement('textarea');
    }
    if (foo2>-1) {
         tinput.setAttribute('readonly',1);
         tinput.style.backgroundColor='#ecedee';
    }
    tinput.setAttribute('value',theval);
    tinput.setAttribute('class','aParameter');
    tinput.setAttribute('var',thevar);
    tinput.setAttribute('array',isarray);
    tinput.setAttribute('desc',thedesc);

    tinput.value=theval ;
    tinput.style.width='95%';
    tinput.style.marginLeft='3%';
    ttd.appendChild(tinput);
  }
  ttd.style.fontFamily='courier';
  ttr.appendChild(ttd);

  ttnBody.appendChild(ttr);
}
ttable.appendChild(ttnBody);
dodiv.appendChild(ttable);

return 1;
}

// ===============================
/* Lookup a variable in node containing an XML file, return its value.
   If no such variable, return adef.
   If adef not defined, error message and return ''
   If doall is specified, then look for all instances of davar, and concatenate using the doall character.
==== */
function  lookupNodeVar(pnode,daVar,adef,doall) {
var gnodes,thisVal ;

gnodes=E2_getNodes(pnode,daVar);
if (gnodes.length==0) {
  if (arguments.length<3) {
     alert('Error: no '+daVar+' node/variable found');
     return 1;
  }
  return adef;
}
if (arguments.length<4 || gnodes.length==1) {
   thisVal=E2_getNodeText(gnodes[0]);
   return thisVal ;
}
thisVal='';
thisVal=E2_getNodeText(gnodes[0]);
for (var m=1; m<gnodes.length;m++)  {
   thisVal=thisVal+doall+E2_getNodeText(gnodes[m]);
}
return thisVal;

}

//==============
// legal name (session name or project name
function checkNameOk(aname,isproj) {
 if (arguments.length<2) isproj=0;
 var a1,iu;
 aname=strip(aname);
 if (isproj==1 && aname=='') return 1 ;
 
 a1=aname.substr(0,1);

 if (a1=='_' || a1=='$') {
      alert('Error: session (or project) name can NOT start with a _ or a $');
      return 0;
 }
 vv=getWord(aname);
 if (vv.length>1) {
      alert('Error: session (or project) name can only be 1 word: '+aname);
      return 0;
 }

  iu=document.getElementById('currentSessionName'); 
    if (!iu)   iu=document.getElementById('_currentSessionName'); 
   if (iu) {
      if (isproj==0) {
         iu.innerHTML='<u>'+aname+'</u>';
     } else {
        if (aname!=='') {
           iu.innerHTML=iu.innerHTML+' (<tt>in session-project '+aname+'</tt>)';
        }
     }
   }
 return 1;

}

/*================================================ 
 check the session name 
  a) is it legal (1 word)
  b) does it exist
        If yes, display error message
===========================*/

function checkSessionName(a1,ido) {

var awords,toget,iu ;
if (arguments.length<2) ido=1 ;

a1=strip(a1) ;

if (a1=='' || typeof(a1)=='undefined' ) {
    useName='';
    iu=document.getElementById('sessionName'); 
    if (iu) {
         iu.value='';
         iu.setAttribute('value','');
    }
    iu=document.getElementById('makeSessionStatus'); 
    if (iu) iu.innerHTML='';

    iu=document.getElementById('currentSessionName'); 
    if (!iu)     iu=document.getElementById('_currentSessionName'); 
    if (iu) iu.innerHTML='not yet specified';

      icurrent=document.getElementById('_sessionDetails');
      if (!icurrent) icurrent=document.getElementById('sessionDetails');

      icurrent.innerHTML='';

      icurrent=document.getElementById('paramsTable');
      icurrent.innerHTML='<tr><th width="15%"></th><th width="35%"></th><th width="50%"></th>  ';

      icurrent=document.getElementById('displayArea');
      icurrent.style.display='none';

    return 1;
}

if (ido==1) {                                   // check syntax, and check if this session already exists
  awords=getWord(a1);
  if (awords.length!=1) {
    alert('You must enter a 1 word session name (no spaces allowed) ')
    useName='';
    iu=document.getElementById('sessionName'); 
    if (iu) {
         iu.value='';
         iu.setAttribute('value','');
    }
    iu=document.getElementById('makeSessionStatus'); 
    if (iu) iu.innerHTML='';

    return 1;
  }
  useName=getWord(a1,1);
  var toget=getSessionExistsURL+useName ;
  Get_File(toget,'sessionExists','checking existence of xml session file ','checkSessionName',useName,2) ;
  return 1;
}

if (ido==2)  {                  // session file existence was checked .. does it exist?
  usename=a1;
  if (sessionExists==1) {                                              // exists! can't use
      var toget=getSessionDescriptorURL+useName ;
      Get_xmlFile(toget,'sessionNode','retrieving xml session file ','checkSessionName',useName,3) ;
      return 1; 
   }
  iu=document.getElementById('currentSessionName'); 
  if (!iu) iu=document.getElementById('_currentSessionName'); 
  iu.innerHTML='<u>'+makeProjName(useName)+'</u>';
  iu=document.getElementById('makeSessionStatus'); 
  if (iu) iu.innerHTML='';

  return 1;                     // else, okay!
}

if (ido==3)  {                  // session file existence was checked .. and it exists
  usename=a1;
  aname= strip(lookupNodeVar(sessionNode,'sessionName'));
  aInst= lookupNodeVar(sessionNode,'instrumentName');
  aDesc= lookupNodeVar(sessionNode,'sessionDescription','ax');
  aCreated= lookupNodeVar(sessionNode,'created');
  alert('Sorry, a session with the name '+usename+' already exists.\n  Created:'+aCreated+'.\n  Description:'+aDesc);
  useName='';
  iu=document.getElementById('sessionName'); 
   if (iu) {
        iu.value='';
        iu.setAttribute('value','');
   }
  iu=document.getElementById('currentSessionName'); 
  if (!iu)     iu=document.getElementById('_currentSessionName'); 
  if (iu)  iu.innerHTML='not yet specified';

 icurrent=document.getElementById('_sessionDetails');
 if (!icurrent) icurrent=document.getElementById('sessionDetails');

  if (icurrent) { 
      icurrent.innerHTML='';
      icurrent=document.getElementById('paramsTable');
      icurrent.innerHTML='<tr><th width="15%"></th><th width="35%"></th><th width="50%"></th>  ';
      icurrent=document.getElementById('displayArea');
      icurrent.style.display='none';
  }
  iu=document.getElementById('makeSessionStatus'); 
  if (iu) iu.innerHTML='';

  return 1;       
}

return 0;       

}

/* =========== Save instrument to a new session ==========================*/ 
/* create a session descriptor file from nodes in the instrument descriptor file.
   And, copy all files (noted in <FILE> nodes) from the instrument to the session directory.
*/

function makeSession(todo,usedName) {
if (arguments.length<1) todo=1 ;

var afile,m,aname,taname,aval,toSubmit;
var arow,avalue,t1,noCopy,iu;
var iatt,cnode,filelist,tmp;
var sessionDesc ;

if (todo==1)  {                         //  create an XML file and post it to server
  
  if (instName==='') {
     alert("You must select one of the available instruments! ");
     return 1;
  }

  if (useName==='') {
     iu=document.getElementById('sessionName');
     if (iu) useName=iu.value ;
  }
  useName=strip(useName);
  if (useName==='') {
     alert("You must specify a name for the new session! ");
    return 1;
  }
  
  if (useProject==='') {
     iu=document.getElementById('sessionProject');
     if (iu) useProject=iu.value ;
  }
  useProject=strip(useProject);

  iu=document.getElementById('sessionDesc');
  if (iu && iu.value!=='') {
    try {
       sessionDesc=iu.value;
    } 
    catch(err) {
        alert(' iu '+iu+','+iu.value+':'+err)
    }
  } else {
    sessionDesc=instDesc ;
  }

  useNameFull=useName;  
  if (useProject!=='')useNameFull='$'+useProject+'_'+useName;


   afile='<?xml version="1.0" encoding="UTF-8" ?> \n' ;
   afile=afile+'<session> \n ';
   afile=afile+'<sessionName> '+useNameFull+'</sessionName> \n ';
   afile=afile+'<sessionDescription> '+sessionDesc+'</sessionDescription> \n ';
   afile=afile+'<instrumentName> '+instName+'</instrumentName> \n ';
   afile=afile+'<created> '+svy_currentTime(1,2)+' </created>   \n ';

   filelist=[];
   filelist[0]='allowedUsers.xml';              // always copy allowedUsers.xml (might be stub file)
   filelist[1]='describe.txt';              // always copy describe.txt (might be stub file)

/* drop  NAME, and DESCRIPTION nodes (and drop comments) */
   for (var m=0 ; m<instNode.childNodes.length;m++) {
      cnode=instNode.childNodes[m]
      atype=cnode.nodeType ;
      if (atype!=1) continue ;
      aname=cnode.nodeName ;
      taname=strip(aname.toUpperCase());
      if (taname=='NAME' || taname=='DESCRIPTION' ) continue ;
      iatt=cnode.attributes.length;
      at1=''; 
      for (var m2=0;m2<iatt;m2++) {
            at1=at1+cnode.attributes[m2].nodeName+'="'+cnode.attributes[m2].nodeValue+'" ' ;
      }
      avalue=E2_getNodeText(cnode,1,''); 
      avalue=avalue.replace(/\n/g,' ');
      arow='<'+aname+' ' +at1+ '>'  + avalue +'</'+aname+'>';

     if (taname=='FILE') {
         noCopy=getAttributes(cnode,'noCopy','0');
         if (noCopy!='1')  filelist=filelist.concat(strip(avalue));
     }


      afile=afile+arow+'\n';
   }

   afile=afile+'</session> \n ';
   afile=escape(afile);
   tmp=escape(filelist.join(' '));

   toSubmit=postSessionFilesHeader+'&doScenario=1&name='+useNameFull+'&fileList='+tmp+'&instName='+instName+'&buster='+Math.random()+'&content='+afile;
//alert('tosubmit '+toSubmit);
   Post_toServer(postFileURL,toSubmit,'postResponse','posting xml session file ','makeSession',2,useNameFull);
   return 1;                                                                          
}                               //todo=1 

/* response from server */

 if (todo==2) {
    if (postResponse.substr(0,1)=='-') {                       // An error
        useName='';
        t1=document.getElementById("makeSessionStatus");
        if (t1) {
            t1.innerHTML='Error creating '+usedName+': '+ postResponse +'<p /><a href="newSession.htm">Try a different session name</a>.';
            t1.style.fontStyle='italic';
       }
       return 1;                       // will get caught by onchange 
    }

    if (postResponse==0) {
       alert('Error: unable to post a session descriptor file ('+useNameFull+')');
       t1=document.getElementById("makeSessionStatus");
       t1.innerHTML='Error creating '+usedName+': unable to post a session descriptor file ('+useNameFull+')';
       t1.style.fontStyle='italic';
       return 1 ;
   }

// what to do next? If afterMakeSession function available, use it. Otherwise, if makeSessionStatus div available
   if (typeof(afterMakeSession)=='function') {
         afterMakeSession(useNameFull,postResponse) ;
    }


   t1=document.getElementById("makeSessionStatus");
   t1.innerHTML='Session created: '+usedName;
   t1.style.fontStyle='italic';

   iu=document.getElementById('doit')
   iu.style.display='none';
   return 1;
 }

 return 1;
}



