/* ============ The create-a-basic-descriptor-file functions ===== */
// GoCreateE --  similar to goCreate0, but used when modifying an existing descriptor file
// GoCreate --  create a form that contains values of changeable, and non-changeable, variables
// setMe      -- helper function used by onClick and onChange in the goCreate form
// createDesc  -- using values set in the goCreate form, generate an new descriptor.xml and save to server
// createDesc2  -- called after return from createDesc sends file to server.
//  showDesc  --  helper function: display description of a descriptor variable (in the goCreate form)
// ===================

// this is called to modify an existing instrument descriptor
function goCreateE(usenam) {
 var toget ;
 toggleDisplay('doModify',0);
  var toget=getDescriptorXML_1.replace(/\$NAME\$/g,usenam) ;

// now get basic descriptor xml file and modify it
    Get_xmlFile(toget,'descNode','retrieving a descriptor file ','goCreate',usenam,1) ;
    return 1 ;

}


// this is called after creation of a new instrument's directory
function goCreate0(usenam,useopen,useAllowed) {
//alert('fungus '+makeDirs);
  if (makeDirs.substr(0,1)=='-') {
        addActionHistory('<b>Error.</b> Creating directories',makeDirs);
        updateStatus('Error creating directories for '+usenam,1);
        return 1;
  }

   addActionHistory('For instrument '+usenam+', directories were created ',makeDirs);
   updateStatus('For instrument '+usenam+', directories were created');

// now get basic descriptor xml file and modify it
    if (useopen==1) {
       if (useAllowed==1) {
           Get_xmlFile(getDescriptorOeSpXML,'descNode','retrieving a descriptor template ','goCreate',usenam,0,useopen,useAllowed) ;
        }else {
           Get_xmlFile(getDescriptorOeXML,'descNode','retrieving a descriptor template ','goCreate',usenam,0,useopen,useAllowed) ;
       }
    } else {
       if (useAllowed==1) {
          Get_xmlFile(getDescriptorSpXML,'descNode','retrieving a descriptor template ','goCreate',usenam,0,useopen,useAllowed) ;
       }else {
          Get_xmlFile(getDescriptorXML,'descNode','retrieving a descriptor template ','goCreate',usenam,0,useopen,useAllowed) ;
       }
    }
    return 1 ;

}


// ===================
// this handles creation of a new instrument basic descriptor file, and its display
// Called after creation of directories,
// Or, to modify an existing descriptor file
// so check for errors

function goCreate(usenam,isexist,useopen,useAllowed) {
  var danodes,tmp,foo,m,tt,uname,tname,aname ;
  var atable,vv,vv2,arow,tusenam,nvalue,mvalue,tvalue;
  var nvalue2,ischecked,idct,thisID;
  var tmp,m2,isnochange,aname;
  var isoe=' ',isSpecific=' ';
  var uu,tuseproj ;

  usenam=strip(usenam);

  if (arguments.length<2) isexist=0;
  if (arguments.length<3 || useopen=='') useopen=0;
  if (arguments.length<4 || useAllowed=='') useAllowed=0;

  if (useopen==1) isoe=' open-ended ';
  if (useAllowed==1) isSpecific=' participant-specific ';

  uu=extractProjectName(usenam);

  tusenam=uu[0].toUpperCase() ;
  tuseproj=uu[1].toUpperCase() ;

//    alert(isexist+' inx gocreate '+usenam);

  if (isexist!=1) {
    atable='For new instrument: <b>'+tusenam+'</b> (in project '+tuseproj+') <p/> <form name="ugly"> \n';
    atable=atable+'<input type="button" value="Create the '+isoe+' '+isSpecific+' instrument descriptor file" onClick="createDesc(\''+usenam+'\',0,'+useopen+','+useAllowed+')" /> \n ';
  } else {
     atable='<p/> <form name="ugly"> \n';
     atable=atable+'<input type="button" value="Modify the '+isoe+' '+isSpecific+' instrument descriptor file" onClick="createDesc(\''+usenam+'\',1,'+useopen+','+useAllowed+')" /> \n ';
  }
  atable=atable+'<table border="1"> ';

 danodes=E2_getNodes(descNode);
 tmp='';

 nodeNames=[]; nodeValues=[]; nodeNoChanges=[]; nodeRequireds=[];
 nodeNamesNames=[];
 nodePermitteds=[]; nodeDescs=[]; nodeDescsInfo=[];
 nodePermitted_displays=[]; nodeAttributes=[];nodeNumbers=[];nodeOneWords=[];
 nodeID_ct=0 ;

 descVars={};
 for (var m=0;m<danodes.length;m++) {
    nodeNames[m]=danodes[m].nodeName;
    nodeNamesNames[m]=getAttributes(danodes[m],'name','');

    isnochange=getAttributes(danodes[m],'noChangeVar',0);
    tmp='';
    for (m2=0;m2<danodes[m].attributes.length;m2++) {
        tmp=tmp+danodes[m].attributes[m2].nodeName+'="'+danodes[m].attributes[m2].nodeValue+'" ';  
    }
    nodeAttributes[m]=tmp;                      // attributes on "variable" name. Always included in XML file

// if creating new ...
    if (isexist!=1) {

         vv=E2_getNodes(danodes[m],'value');   // ALL variables must have a VALUE node.
         if (vv.length<1)  {
                alert('Error in '+isoe+' '+isSpecific+' DESCRIPTOR.XML. '+nodeNames[m]+' does not have a VALUE node ');
                return 0;
         }
        nodeNumbers[m]=getAttributes(vv[0],'number',0);
        nodeOneWords[m]=getAttributes(vv[0],'oneWord',0);
        isuse=getAttributes(vv[0],'use','');
        if (isuse!=='') {
           isuse=strip(isuse).toUpperCase() ;
           nvalue=isuse.replace('$NAME$',usenam.toUpperCase()) ;
       } else {
           nvalue=E2_getNodeText(vv) ;
       }

    } else {                    // modify
        try {
          nvalue=danodes[m].firstChild.nodeValue ;
        }
        catch(ierr) {
            nvalue='';
        }

    }

    nodeValues[m]=nvalue;

    vv=E2_getNodes(danodes[m],'desc');
   if (vv.length>0) nodeDescs[m]=E2_xmlToString(vv[0],1,1) ;

    nodeDescsInfo[m]='';
    vv=E2_getNodes(danodes[m],'descInfo');
   if (vv.length>0) nodeDescsInfo[m]=E2_xmlToString(vv[0],1,1) ;

    vv=E2_getNodes(danodes[m],'permitted');
    tt=[];
    if (vv.length>0)  {
        tt=getWord(E2_getNodeText(vv[0]));
    } else {
        tt=getAttributes(danodes[m],'permitteds','');
        if (tt!=='') tt=getWord(tt);
    }

    nodePermitteds[m]=tt ;

    vv=E2_getNodes(danodes[m],'permitted_display');
    tt=[];
    if (vv.length>0)   tt=getWord(E2_getNodeText(vv),0,',');
    nodePermitted_displays[m]=tt ;

    vv=E2_getNodes(danodes[m],'nochange');              // overrides nochangevar attribute
    tt=isnochange;
    if (vv.length>0)  tt=getAttributes(vv[0],'value',0);
    nodeNoChanges[m]=tt
 
    vv=E2_getNodes(danodes[m],'required');
    tt=0;
    if (vv.length>0)  tt=getAttributes(vv[0],'value',0);
    nodeRequireds[m]=tt ;

  }

  for (m=0;m<danodes.length;m++) {
    if (isexist!=1) {
        uname='<a href="" onClick="showDesc('+m+');return false;">'+nodeNames[m]+'</a> \n ';
   } else {
        uname='<a href="" onClick="showDesc('+m+',2);return false;">'+nodeNames[m]+'</a> \n ';
   }
     if (nodePermitteds[m].length==0 || isexist==1) {
        nodeID_ct++ ;
        thisID=' id="ID_'+nodeID_ct+'" ' ;
        tvalue='<input '+thisID+'  type="text" name="'+nodeNames[m]+'" value="'+nodeValues[m]+'" '; 
        if (nodeNoChanges[m]>0) tvalue=tvalue+'  readonly="1"  style="background-color:#bccbbc"  ';
        setarg="setMe('"+nodeNames[m]+"',this.value)";
        tvalue=tvalue+' onChange="'+setarg+'" ';
        tvalue=tvalue+'/> ';
        descVars[nodeNames[m]]=nodeValues[m];

     } else {

        tvalue="<menu>";
         if (nodeNoChanges[m]>0)  tvalue='<menu style="background-color:#bccbbc" ';
        tname= ' name="'+nodeNames[m]+'"' ;
        nvalue=strip(nodeValues[m]).toUpperCase();
        for (var mm=0;mm<nodePermitteds[m].length;mm++) {
           nvalue2=strip(nodePermitteds[m][mm]).toUpperCase();
           ischecked='';
           if (nvalue==nvalue2) {
                 ischecked=' checked="1" ';
                descVars[nodeNames[m]]=nodeValues[m];
           }
         if (nodeNoChanges[m]>0) ischecked=ischecked +' onClick="return false"   ';

          nodeID_ct++ ;
          thisID=' id="ID_'+nodeID_ct+'" ' ;

          setarg="setMe('"+nodeNames[m]+"',this.value)";

           tvalue=tvalue+'<li><input '+thisID+' ';
           tvalue=tvalue+ischecked+' onClick="'+setarg+' "  ';  
           tvalue=tvalue+' '+tname+' type="radio" value="'+nodePermitteds[m][mm]+'" />'+nodePermitted_displays[m][mm] +' </li> \n '
        }
        tvalue=tvalue+'</menu> \n ';
     }
     if (strip(nodeNames[m]).toUpperCase()!=='DESC') {
       arow='<tr><td>'+uname+'</td><td>'+tvalue+'</td><td><div style="border:1px solid #effeef;display:none"  id="NODE_'+m+'"></div></td></tr> \n '
       atable=atable+arow;
    }
  }   
  atable=atable+'</table> </form><b>Note:</b> <span style="background-color:#bccbbc">values</span> are not changeable by this utility ' ;

// now display the form in the currentTask div

 currentTaskDisplay('<b>Specify the basic  descriptor file for the '+isoe+' '+isSpecific+' instrument:</b> '+tusenam +'  (in project '+ tuseproj+')',atable);
  currentTaskDisplay(1);

// update nodeDescs (if isexist)
   if (isexist==1) {
        tmp={};
        for (m=0;m<nodeNames.length;m++) {
          aname=nodeNames[m].toUpperCase();
          if (aname!=='DESC') continue;
          aname=nodeNamesNames[m];
          tmp[aname]=nodeValues[m];
       }
       for (m=0;m<nodeNames.length;m++) {
          aname=nodeNames[m].toUpperCase();
          if (aname=='DESC') continue;
          if (aname=='FILE') aname=nodeNamesNames[m];
          if (typeof(tmp[aname])!=='undefined') {
             nodeDescs[m]=tmp[aname];
          } else {
             nodeDecs[m]=' ... ';
         }
       }
   }                            // isexist=1, create desc


return 1;
}

//===
// change vars (called via onClick or onChange)
function setMe(aname,a1) {
 descVars[aname]=a1;
  return 1;
}

//=====================================
// save the descriptor file to the server , using values modified by the user
function createDesc(uname,isexist,useopen,useAllowed) {

var m,afoo,a1,atype,aname,foo,ici,aval,perms,im ;
if (arguments.length<2) isexist=0;

afoo='<?xml version="1.0" encoding="UTF-8" ?> \n';
afoo=afoo+'<!-- Descriptor file for: '+uname+' \n Created: '+svy_currentTime(2,2)+' --> \n ';

afoo=afoo+'\n <descriptor> \n  \n ';
for (var m=0;m<nodeNames.length;m++) {
 aname=nodeNames[m];
 if (nodeRequireds[m]==1) {                                     // required fields must have a non '' value
         if (strip(descVars[aname])==='') {
                alert('Error. You must specify a value for '+aname);
                return 0;
          }
 }

 if (nodeNumbers[m]==1) {                                       // number fields must be numeric
     if (isNaN(strip(descVars[aname]))) {
                alert('Error.  "'+descVars[aname]+'" is not a numeric  value (for variable '+aname+')');
                return 0;
      }
 }

 if (nodeOneWords[m]==1) {                                       // number fields must be numeric
     tmp=getWord(strip(descVars[aname]));
     if (tmp.length>1) {
                alert('Error.  "'+descVars[aname]+'" is more than one-word long (for variable '+aname+')');
                return 0;
      }
 }
 if (nodePermitteds[m].length>0 && nodeNoChanges[m]!=1) {                                       // check permitted values
   aval=descVars[aname] ;
   iok=0 ;
   for (var im=0;im<nodePermitteds[m].length;im++) {
       if (strip(aval)==strip(nodePermitteds[m][im])) iok=1;
       if (iok==1)   break ;
   }
   if (iok==0) {
        alert('Error. '+aname+'='+aval+', but must be one of: '+nodePermitteds[m].join(' | '));
        return 0;
   }
 }
 foo0='';
 if (isexist!==1) {
   if (strip(aname).toUpperCase()=='FILE') {
       foo0='<desc name="'+nodeNamesNames[m]+'">'+nodeDescsInfo[m]+'</desc> \n ' ;
   } else {
     foo0='<desc name="'+aname+'">'+nodeDescsInfo[m]+'</desc> \n ' ;
    }
 }

 if (aname=='DESC' && isexist==1) {
        foo='<'+aname+' '+nodeAttributes[m]+'>'+nodeValues[m]+'</'+aname+'> \n ';
 } else {
   perms='';
   if (isexist!==1 && nodePermitteds[m].length>0) perms=' permitteds="'+nodePermitteds[m].join(' ')+'" ' ;
   if (nodeNoChanges[m]==0) {
     foo='<'+aname+' '+perms+' '+nodeAttributes[m]+'>'+descVars[aname]+'</'+aname+'> \n ';
   } else {
     if (nodeNoChanges[m]==1) {
         foo='<'+aname+' '+perms+' '+nodeAttributes[m]+'>'+nodeValues[m]+'</'+aname+'> \n ';
     } else {
        foo='<'+aname+' noChangeVar="1" '+nodeAttributes[m]+'>'+nodeValues[m]+'</'+aname+'> \n ';
     }
   }
 }
 afoo=afoo+foo0+foo;


}

afoo=afoo+' \n </descriptor> \n ';

descXML=afoo;

// and now write to server
if (isexist!=1) {
   toWrite=postNewDescriptor+'&file='+instFileName+'.XML&content='+escape(descXML);
//   alert('totoot '+toWrite);
} else {
   toWrite=postModifyDescriptor+'&file='+instFileName+'.XML&content='+escape(descXML);
}

Post_toServer(postFileURL,toWrite,'saveNewDescriptor','saving new XML descriptor file','createDesc2',instFileName,uname,isexist,useopen,useAllowed) ;
return 1;


}

//=====================================
// here after saving xml descriptor
function createDesc2(dafile,uname,isexist,useopen,useAllowed) {
 var afoo,istat,daword;

istat=saveNewDescriptor.substr(0,2);
daword=' modify ' ;
if (isexist==0) daword=' save ';

if (istat=='-1') {                      // an error
    afoo='<b>Error.</b> Unable to '+daword+' '+dafile ;
   addActionHistory(afoo,saveNewDescriptor);
   numErrs++ ;
   updateStatus('Unable to '+daword+' '+dafile+' :'+saveNewDescriptor);


} else { 
  afoo='<h4>Status of '+daword+' of '+dafile+' = '+saveNewDescriptor+'</h4> \n ';
  afoo=afoo+descXML.replace(/\</g,'&lt;');              // global descXML created in createDESC 
  afoo=afoo.replace(/\>/g,'&gt;')
  afoo=afoo.replace(/\n/g,'<br/>');

  addActionHistory(daword+'descriptor file '+dafile,afoo);

  updateStatus(daword+'  '+dafile+' = '+saveNewDescriptor);

// and hide the "create descriptor file" div
  currentTaskDisplay(0);

// Now, copy template files
  if (isexist!=1)   copyTemplateFiles(uname,1,useopen,useAllowed);  

  if (isexist==1)   toggleDisplay('doModify',1);

}
return 1;
}


//=====================================
// show description of a descriptor-file variable (when the variable name is clicked on)
function showDesc(m,i1) {
  if (arguments.length<2)i1=0;
  var a1,a2,a3 ;
  a1=document.getElementById('NODE_'+m);
  toggleDisplay('NODE_'+m) ;

  a1.innerHTML=nodeDescs[m]; 
  return 1;
}


/* ============ END OF The create-a-basic-descriptor-file functions ===== */


/* ============  The create-general-data functions (also used to create scenarios for a session) ===== */


function goModifyGeneral(usenam,theData) {
stuff='You can modify a dSurvey <tt>general</tt> data file.   \n ';
currentTaskDisplay('<b>Read a general data file for '+usenam,stuff);
currentTaskDisplay(1);
toggleDisplay('doModify',0);

genDescs={},genVals={},genVars=[]; genArray={};
genNewAdded=0;
 var toget=getGeneralXML_1.replace(/\$NAME\$/g,usenam) ;
 currentInstName=usenam;

// now get basic descriptor xml file and modify it
    Get_xmlFile(toget,'generalNode','retrieving a general data file ','goModifyGeneral2',usenam,0) ;
    return 1 ;

}


//==========================

function goModifyGeneral2(usenam,ith,scName) {

var ithrow=0,isScenario,uu;
var newVarName='',taname;

if (arguments.length<2) ith=0;
if (arguments.length<3) {
   isScenario=0;
   scName='';
} else {
  if (strip(scName)!=='') isScenario=1;
}

var tmp,newVarDesc,gDesc,descnode,v1,descNodes,i,i2,i3,itmp,aval0 ;

var gtaname,taname,aname,aval,isArray,arow,ivv,isArray0;

var trcolors=['#effeef','#feeffe'];          
var maxlength=4 ;

if (usenam===0) usenam=currentInstName;

if (ith==1 ) {

  var gDesc='General parameters for '+makeProjName(usenam) ;
  
  descnode=E2_getNodes(generalNode,'desc');
  if (descnode.length>0) gDesc=E2_getNodeText(descnode[0]);

  if (genNewAdded>0) {
       newVarName=prompt('Name of the new variable (Caution: values you may have entered for new or existing variables will be lost) ','');
  } else {
        newVarName=prompt('Name of the new variable ','');
  }
  if (newVarName==='') {
        alert('Error: you must enter a new variable name ');
        return 0 ;
  }
  tmp=getWord(newVarName);
  if (tmp.length>1) {
        alert('Error: the new variable name must be just one word ');
        return 0 ;
  }
  if (!isNaN(newVarName)) {
        alert('Error: you must enter a non-numeric new variable name ');
        return 0 ;
  }

  newVarName=strip(newVarName);
  tmp=getWord(newVarName);
  if (tmp.length>1) {
        alert('Error: new variable name must be just one word ');
        return 0;
   }
   isArray0=prompt('If this is an array, enter its length (enter 0 if it not an array)',0);
   if (isNaN(isArray0)) {
        alert('Error: you must enter a number (0 means "not an array", otherwise enter # of elements)');
        return 0;
    }
   newVarDesc=prompt('Enter a description for this variable ('+newVarName+') ','');
   genNewAdded++ ;

} else {                                // first read == parse general data file


  var gDesc='General parameters for '+usenam ;
  
  descnode=E2_getNodes(generalNode,'desc');
  if (descnode.length>0) gDesc=E2_getNodeText(descnode[0]);

  v1=E2_getNodes(generalNode,'general');
  if (v1.length==0) {
        alert('Error: No general data for '+usenam);
     return 0;
  }


// read all desc variables 
  descNodes=E2_getNodes(v1[0],'desc');
  for (var i=0;i<descNodes.length;i++) {
    aname=getAttributes(descNodes[i],'value','');
    if (aname!=='') {
          taname=strip(aname).toUpperCase();
          genDescs[taname]=E2_getNodeText(descNodes[i]);
    }
  }

// read all variables 
  descNodes=E2_getNodes(v1[0],'*');
  for (var i=0;i<descNodes.length;i++) {
   aname=descNodes[i].nodeName;
   taname=strip(aname).toUpperCase();
   if (taname=='DESC') continue ;

   genArray[taname]=0;
   isArray=getAttributes(descNodes[i],'array',0);
   if (isArray==1) {
        aval0=E2_getNodeText(descNodes[i]);   
        aval=getWord(aval0,0,',');
        genArray[taname]=aval.length;
        genVals[taname]=aval ;
   } else {
       aval=E2_getNodeText(descNodes[i]);   
       genVals[taname]=aval ;
   }
   genVars=genVars.concat(aname);
  }
}                               // first read

if (ith==1 ) {                          // the new variable
  gtaname=strip(newVarName).toUpperCase();
  for (var i=0;i<genVars.length;i++) {         // check if this name already exists
      aname=strip(genVars[i]).toUpperCase() ;
      if (aname==gtaname) {
         alert('Error: general variable with this name already exists');
         return  0;
       }
   }

   genArray[gtaname]=isArray0;
   genVars=genVars.concat(newVarName);
   genDescs[gtaname]=newVarDesc ;
   genVals[gtaname]='';
   if (isArray0>0) {
        genVals[gtaname]=[];
        for (var i3=0;i3<isArray0;i3++) genVals[gtaname][i3]='';
   }
}


if (isScenario!=1) {
   stuff='<b>The general data: </b><input type="value" name="newGenDesc" value="'+gDesc+'" size="80" title="Optional: a general description of the parameters">';  
   stuff=stuff+'<input style="margin-left:20px" type="button" value="Add a variable" title="Click here to add a variable. You can click several times to add several variables"  onClick="goModifyGeneral2(0,1)"> '; 
} else {
   stuff='<b>Scenario  data: </b><input type="value" name="newGenDesc" value="'+gDesc+'" size="40" title="Optional: a general description of the parameters">';  
} 

stuff=stuff+'<table border="1"> ';

// display table of values, existing, and new
for (var i=0;i<genVars.length;i++) {

  ithrow=1-ithrow;
  tmp='';
  if (isScenario!=1)  tmp='<input type="checkbox" title="check here to remove this variable ('+genVars[i]+')" name="removeVars" isVar="'+genVars[i]+'" / > ';
  arow='<tr style="background-color:#ababab"><th>'+tmp+genVars[i]+'</th>';
  taname=strip(genVars[i]).toUpperCase();
  aval=genVals[taname];
  if (genArray[taname]==0) {
    ivv='<input value="'+aval+'" type="value" name="newGenVals" varname="'+taname+'" size="40" > ';
  } else {
    ivv='<table><tr>';
    itmp=0;
    for (var i3=0;i3<genArray[taname];i3++) {
        if (itmp>4) {
                ivv=ivv+'</tr> \n <tr> ' ; 
                itmp=0;
        }
        itmp++;
        ivv=ivv+'<td><input value="'+aval[i3]+'" type="value" name="newGenVals" varname="'+taname+'" aElem="'+i3+'" size="8" > </td> ';
    }
    ivv=ivv+'</tr></table>';
  }
  arow=arow+'<td>'+ivv+'</td><td><span style="font-size:90%">'+genDescs[taname]+'</span></td> </tr> \n ';  
  stuff=stuff+arow;  
}
stuff=stuff+"</table> \n ";  

if (isScenario!=1) {
   stuff=stuff+'<input type="button" value="Save these modifications to the general data file " onClick="goModifyGeneral3(1)" title="click here after you have made changes that you wish to save" /> \n ';
} else {
   stuff=stuff+'<input type="button" value="Create the '+scName+' scenario file " onClick="goModifyGeneral3(1,\''+scName+'\')" title="click here after you have made changes that you wish to save to a scenario file" /> \n ';
}
if (isScenario!=1) {
   uu=extractProjectName(usenam);
   currentTaskDisplay('The general data for '+uu[0]+' (in project '+uu[1]+')',stuff);
   currentTaskDisplay(1);
   toggleDisplay('doModify',0);
} else {
   currentTaskDisplay('Create the <tt>'+scName+'</tt> scenario file for session <tt>'+makeProjName(usenam)+'</tt>',stuff);
   currentTaskDisplay(1);
  toggleDisplay('doModify',0);
}
return 0;
}


//===========
function goModifyGeneral3(ith,scName) {

var stuff,foo,i,i2,aname,aval,itmp,uu;
var rdata={};
var tvar,tval;
var isScenario=0;

if (arguments.length>1) isScenario=1 ;

foo=document.getElementsByName('newGenDesc');
rdata['newGenDesc']=foo[0].value ;


removeVars={};
foo=document.getElementsByName('removeVars');
for (var i=0;i<foo.length;i++) {
   if (foo[i].checked) {
     tmp=getAttributes(foo[i],'isVar',0); tmp=strip(tmp).toUpperCase();
     removeVars[tmp]=1; 
   }
}


foo=document.getElementsByName('newGenVals');
var usenam=currentInstName ;

if (isScenario==0) {
   stuff='<b>The general data: </b>'+rdata['newGenDesc']+' <br />';  
} else {
   stuff='<b>The <tt>'+scName+'</tt> scenario data: </b>'+rdata['newGenDesc']+' <br />';  
}

stuff=stuff+'<table border="1"> '; 
// get data from input fields
for (var i=0;i<foo.length;i++) {
  aname=getAttributes(foo[i],'varname','');
  taname=strip(aname).toUpperCase();
  if (typeof(removeVars[taname])!=='undefined') continue ;              // a removed variable
  aval=foo[i].value ;
  if (genArray[aname]==0) {
     rdata[aname]=aval;
  } else {
     ielem=getAttributes(foo[i],'aElem','0');
     if (typeof(rdata[aname])=='undefined') rdata[aname]=[] ;
     rdata[aname][ielem]=aval;
  }
}

newGenVals={};
newGenVals['newGenDesc']=rdata['newGenDesc'];

for (var i=0;i<genVars.length;i++) {
  arow='<tr><th>'+genVars[i]+'</th>';
  tvar=strip(genVars[i]).toUpperCase();
  if (typeof(removeVars[tvar])!=='undefined') continue ;              // a removed variable

  tval=rdata[tvar];
  newGenVals[tvar]=tval;
  if (genArray[tvar]>0) {  
        itmp=0;
       arow=arow+'<td><table border="1"> <tr>';
       for (var i2=0;i2<tval.length;i2++) {
            if (itmp>9) {
                arow=arow+'</tr> \n <tr> ';
                itmp=0;
            }
            itmp++ ;
            arow=arow+'<td>'+tval[i2]+'</td>';
        }
        arow=arow+'</tr></table></td>';
   } else {
       arow=arow+'<td>'+tval+'</td>';
   }
  arow=arow+'</tr> \n ' ;
  stuff=stuff+arow;
}
stuff=stuff+'</table> \n ';

if (isScenario==0) {
   arow='<input type="button" value="Save these values " title="If these values are correct, click here to modify the general parameters data file " onClick="goModifyGeneral4(1)" /> ';
   stuff=stuff+arow+' \n ';
   uu=extractProjectName(usenam);
   currentTaskDisplay('Modified general data for '+uu[0]+' (in project '+uu[1]+')',stuff);
} else {
   arow='<input type="button" value="Save these values " title="If these values are correct, click here to create the scenario file " onClick="goModifyGeneral4(1,\''+scName+'\')" /> ';
   stuff=stuff+arow+' \n ';
   currentTaskDisplay('Scenario data for '+makeProjName(usenam),stuff);
}
stuff=stuff+arow+' \n ';

currentTaskDisplay(1);

return 1 ;
}



//======
function goModifyGeneral4(ith,scName) {

var stuff,tmp,i,i2,avar,tavar,adesc,aline,arow,anelem,avar2;

var isScenario=0;

if (arguments.length>1) isScenario=1 ;

var uname=currentInstName;

stuff='<?xml version="1.0" encoding="UTF-8" ?> \n ';

if (isScenario==0) {
  stuff=stuff+'<!-- General data file for: '+ currentInstName + ' \n ' ;
  stuff=stuff+' Created: '+svy_currentTime(2,2)+' --> \n \n ';
} else {
  stuff=stuff+'<!-- Scenario data file '+scName+', for session: '+ currentInstName + ' \n ' ;
  stuff=stuff+' Created: '+svy_currentTime(2,2)+' --> \n \n ';
}
 
stuff=stuff+'<parameters>  \n  ';
stuff=stuff+'<desc>  \n' + strip(newGenVals['newGenDesc'])+'\n</desc> \n \n ';

stuff=stuff+'<general>  \n  ';


for (var i=0;i<genVars.length;i++) {
  avar=genVars[i];
  tvar=strip(avar).toUpperCase()
  if (typeof(removeVars[tvar])!=='undefined') continue ;              // a removed variable

  arow='<desc value="'+tvar+'">'+genDescs[tvar]+'</desc> \n ';
  if (genArray[tvar]==0) {
     arow=arow+'<'+tvar+'>'+newGenVals[tvar]+'</'+tvar+'> ';  
  } else {
    arow=arow+'<'+tvar+' array="1">';
    arow=arow+newGenVals[tvar][0];
    for (var i2=1;i2<newGenVals[tvar].length;i2++) arow=arow+','+newGenVals[tvar][i2];
    arow=arow+'</'+tvar+'> ' ;
  }
  stuff=stuff+arow+' \n \n ';
}

stuff=stuff+'</general> \n </parameters> \n ';  


// now save as PARAMS.XML in instruments/instName 
if (isScenario==0) {
  updateStatus('About to save modified general data file, for instrument (or session) '+uname);
  toWrite=postGeneralData+'&name='+uname+'&content='+escape(stuff);
  Post_toServer(postFileURL,toWrite,'saveModifiedGeneral','saving modified XML reference data file','goModifyGeneral5',uname,genNewAdded) ;
} else {
  updateStatus('About to save scenario file '+scName+' for session '+uname);
  toWrite=postGeneralData+'&scname=SC_'+scName+'&name='+uname+'&content='+escape(stuff);
  Post_toServer(postFileURL,toWrite,'saveModifiedGeneral','saving scenario  file','goModifyGeneral5',uname,scName,1) ;
}


return 1; 
  
}


//=====================
// here after posting modified reference data to serer
function goModifyGeneral5(uname,nvar,isScenario) {

  if (arguments.length<3) isScenario=0;
  var scName=nvar;
  var afoo,uu;

  if (isScenario==0) {
    if (saveModifiedGeneral.substr(0,1)=='-') {
       afoo='<b>Error.</b> Unable to update general data file';
       addActionHistory(afoo,saveModifiedGeneral);
       updateStatus('Unable to update modified general data file ');
       return 1;
     }
     afoo='Modified general data file, for instrument ' +uname+', has been updated; with '+nvar+' new variables.'
     addActionHistory(afoo,saveModifiedGeneral);
     updateStatus('Modified general data file has been updated');

     currentTaskDisplay('<b>Modify the general dataset for the instrument:</b> '+makeProjName(uname),saveModifiedGeneral);
     currentTaskDisplay(1);

     toggleDisplay('doModify',1);

   } else {
    if (saveModifiedGeneral.substr(0,1)=='-') {
       afoo='<b>Error.</b> Unable to create scenario  file';
       addActionHistory(afoo,saveModifiedGeneral);
       updateStatus('Unable to create scenario file ');
       return 1;
     }
     afoo='Scenario file '+scName+' for session ' +makeProjName(uname)+', has been created ';
     addActionHistory(afoo,saveModifiedGeneral);
     updateStatus('Scenario file has been created');

     currentTaskDisplay('<b>Saving </b> the '+scName+' scenario for session '+makeProjName(uname),saveModifiedGeneral);
     currentTaskDisplay(1);

   }

  return 1; 

}

/* ============  END OF  The modify-general-data functions ===== */


/* ============  The modify instrument description file ===== */

function goModifyDesc(usenam,theData) {

refDataVarnames=[]; getVars=[];

stuff='You can modify a dSurvey <tt>instrument documentation</tt> file.   \n ';
currentTaskDisplay('<b>Read an existing instrument documentation file for '+usenam,stuff);
currentTaskDisplay(1);
toggleDisplay('doModify',0);

var toget= getDescribeTXT_1.replace(/\$NAME\$/g,usenam) ;               // getReferenceXML_1 is set by caller (points to instruments or sessions directory

currentInstName=usenam;

// now get basic descriptor xml file and modify it
    Get_File(toget,'refText','retrieving a documentation text file ','goModifyDesc2',usenam,0) ;
    return 1 ;

}

// ===================
function goModifyDesc2(usenam,ith) {
var uu;
var aa=strip(refText);

if (aa=='Description of this instrument.') {
  refText='Description of instrument: '+usenam+'\n \n ';
}

stuff='Would you like to retrieve a list of all the current general and reference variables? <p/> \n ';
stuff=stuff+'<input type="button" value="Yes, get this list of variable " onClick="goModifyDesc2a(0)" /> &nbsp; &nbsp; ';
stuff=stuff +'<input type="button" value="No " onClick="goModifyDesc2b(1)" /> ';

uu=extractProjectName(usenam);
currentTaskDisplay('Current value of the '+uu[0]+ ' (in project '+uu[1]+') documentation file has been retrieved',stuff);

toggleDisplay('doModify',0);



}

// ===================
// get params.xml and reference.xml (pull out variable names)
function goModifyDesc2a(i0) {
var toget,vlist,ii;

var usenam=currentInstName ;
var L2,L1,ii,L1a,vname,tvname,uu;

// get all the desc in general parameters

if (i0==0) {
  uu=extractProjectName(usenam);
  currentTaskDisplay('<b>Read a general data file for '+uu[0]+' (in project '+uu[1]+') (extract descriptions)','');
  currentTaskDisplay(1);
  toggleDisplay('doModify',0);

  toget=getGeneralXML_1.replace(/\$NAME\$/g,usenam) ;

   updateStatus('About to read general parameters file for '+ usenam);

// now get basic descriptor xml file and modify it
    Get_xmlFile(toget,'generalNode','retrieving a general data file (for its descriptions) ','goModifyDesc2a',1) ;
    return 1 ;
}


if (i0==1) {                    // general parameters gotten, no get reference...

  addActionHistory('Retrieved general parameters for ',usenam);

  uu=extractProjectName(usenam);
  currentTaskDisplay('<b>Read a reference data file for '+uu[0] +' (in project '+uu[1]+' (extract descriptions)','');
  currentTaskDisplay(1);

  toget=getReferenceXML_1.replace(/\$NAME\$/g,usenam) ;               // getReferenceXML_1 is set by caller (points to instruments or sessions directory

  updateStatus('About to read reference parameters file for '+ usenam);

// now get basic descriptor xml file and modify it
    Get_xmlFile(toget,'refNode','retrieving a reference file (for its descriptions) ','goModifyDesc2a',2) ;
    return 1 ;
}


  addActionHistory('Retrieved reference parameters for ',usenam);

// if here, got two xml nodes. Pull out descriptions!

//
L1=E2_getNodes(generalNode,'general');
if (L1.length<1) {
        alert('Bad read of general parameters file for '+usenam);
        return 1;
}
L2=E2_getNodes(L1[0],'desc');
genVars=[]; genDescs={};

for (var ii=0;ii<L2.length;ii++) {
  vname=strip(getAttributes(L2[ii],'value',''));
  if (vname=='') continue ;                     // no varname, just skip it
  tvname=vname.toUpperCase();
  genVars=genVars.concat(vname);
  genDescs[tvname]=E2_getNodeText(L2[ii]);
}

addActionHistory('General parameters (with descriptions) for '+usenam,genVars.join(', '));


// now parse reference data

refDataVarnames=[];refDataDescs={};
L1=E2_getNodes(refNode,'reference');
if (L1.length<1) {
        alert('Bad read of reference parameters file for '+usenam);
        return 1;
}

L1a=E2_getNodes(L1[0],'descriptions');
if (L1a.length<1) {
        alert('No <descriptions> in reference parameters file for '+usenam);
        return 1;
}
L2=E2_getNodes(L1a[0],'var');
for (var ii=0;ii<L2.length;ii++) {
  vname=strip(getAttributes(L2[ii],'name',''));
  if (vname=='') continue ;                     // no varname, just skip it
  tvname=vname.toUpperCase();
  refDataVarnames=refDataVarnames.concat(vname);
  refDataDescs[tvname]=E2_getNodeText(L2[ii]);
}


addActionHistory('Reference variables for '+usenam,refDataVarnames.join(', '));


updateStatus('General and reference data has been read for '+ usenam);

goModifyDesc2b(2) ;      // now show the contents

return 1;

}


// ===================
// after retrieve of  general and reference var parameters (or var retrieval was skipped)
function goModifyDesc2b(gotVars) {
var stuff,uu ;
var usenam=currentInstName;
uu=extractProjectName(usenam);
stuff='<ul><li><input type="button" value="View current contents of '+uu[0]+' documentation file" onClick="displayDiv(\'showDesc0\')"> </li> ';
stuff=stuff+'<li><input type="button" value="Modify current contents of '+uu[0]+' documentation file"  onClick="goModifyDesc2b1(1)"> </li> ';
stuff=stuff+'<li><input type="button" value="Append to current contents of '+uu[0]+' documentation file" onClick="goModifyDesc2b1(2)" /> </li>';
if (gotVars==2) {
  stuff=stuff+'<li><input type="button" value="View variable descriptions" onClick="goModifyDesc2b3()" /> </li>';

}
stuff=stuff+'</ul> \n ';

// textarea where modifications (or appendoids) are entered
stuff=stuff+'<div id="changeDescDiv" style="display:none;margin-left:5px;margin-right:5px">';
stuff=stuff+'   <div id="changeDescDiv1" style="color:blue;background-color:#deedde"> </div> \n ';
stuff=stuff+'<textarea id="changeDesc" rows="20" cols="100"> </textArea> </div> \n ';

// area for displaying current contents of description file
stuff=stuff+'<div id="showDesc0" style="display:none;">';
stuff=stuff+'<table border="1"><tr><td style="font-size:80%">Current<br>description<br/>of<br/>'+usenam+'<br/></td> \n ';
stuff=stuff+'<td><div id="showDesc" style="margin-top:5px;margin-left:5px;margin-right:5px; white-space:pre;background-color:#efeffe;overflow:auto;height:60%;">'+refText+'</div> </td>\n ';
stuff=stuff+'</table> </div> \n ';

// area for displaying current contents variables
stuff=stuff+'<div id="showVarList" style="display:none;margin-top:15px;margin-left:5px;margin-right:5px;background-color:#fefeef;overflow:auto;height:60%;">General and reference parameters</div> </div>\n ';

uu=extractProjectName(usenam);
currentTaskDisplay('View/modify/append to the '+uu[0]+' (in project '+uu[1]+') documentation file.',stuff);

toggleDisplay('doModify',0);
return 1;
}


// ===== update the changeDest textarea
function goModifyDesc2b1(ado) {
var ii,i2;
if (ado==1) {                           // modify (so place all of current contents in text area
  ii=document.getElementById('changeDesc');
  ii.innerHTML=refText ;

  i2=document.getElementById('changeDescDiv1');
  i2.innerHTML='Modify current description ... <input type="button" value="Save the modified description" onClick="goModifyDesc3(1)"> \n ';
//  alert('i2 ' +i2.innerHTML);
  displayDiv('showDesc0','none');

} else {
  ii=document.getElementById('changeDesc');
  ii.innerHTML='';

  i2=document.getElementById('changeDescDiv1');

  i2.innerHTML='Append the contents of this text box to the current description <input type="button" value="Append to the description" onClick="goModifyDesc3(2)"> \n ';;

  displayDiv('showDesc0',1);
}
displayDiv("changeDescDiv",1);
return 1;
}


// ===== update the viewVars area
function goModifyDesc2b3() {
var ii,vname,tvname,arow;
var stuff,idiv,vvar ;

idiv=document.getElementById("showVarList");
stuff='';
if (genVars.length>0) {
  stuff=stuff+"<h4>General parameters </h4>";

  stuff=stuff+'<pre>\n';
  for (var ii=0;ii<genVars.length;ii++) {
        vvar=strip(genVars[ii]) ;
        tvarname=vvar.toUpperCase();
        for (ii2=vvar.length;ii2<20;ii2++) {
           vvar=vvar+' ';
        }
        stuff=stuff+vvar+' : '+genDescs[tvarname]+' \n';
  } 
  stuff=stuff+'</pre> \n ';

//  stuff=stuff+'<table border="1"> \n ';
//  for (var ii=0;ii<genVars.length;ii++) {
//    arow='<tr><th>'+genVars[ii]+'</td>';
//    tvarname=genVars[ii].toUpperCase();
//    arow=arow+'<td>'+genDescs[tvarname]+'</td></tr> \n ';
//    stuff=stuff+arow;
//   }
//   stuff=stuff+'</table> \n ';

}

if (refDataVarnames.length>0) {
  stuff=stuff+"<h4>Reference parameters </h4>";

  stuff=stuff+'<pre>\n';
  for (var ii=0;ii<refDataVarnames.length;ii++) {
        vvar=strip(refDataVarnames[ii]) ;
        tvarname=vvar.toUpperCase();
        for (ii2=vvar.length;ii2<20;ii2++) {
           vvar=vvar+' ';
        }
        stuff=stuff+vvar+' : '+refDataDescs[tvarname]+' \n';
  } 
  stuff=stuff+'</pre> \n ';

//  stuff=stuff+'<table border="1"> \n ';
//  for (var ii=0;ii<refDataVarnames.length;ii++) {
//    arow='<tr><th>'+refDataVarnames[ii]+'</td>';
//    tvarname=refDataVarnames[ii].toUpperCase();
//    arow=arow+'<td>'+refDataDescs[tvarname]+'</td></tr> \n ';
//    stuff=stuff+arow;
//  }
//  stuff=stuff+'</table> \n ';

}

idiv.innerHTML=stuff ;
idiv.style.display='block';
return 1;


}


// =====  save modified, or append to, description
function goModifyDesc3(ado) {
var ii,adesc,newDesc,vsay,uu;

var ii=document.getElementById('changeDesc');
adesc=ii.value ;

uu=extractProjectName(currentInstName);
if (ado==1) {           // contents of changeDesc is the new description
  vsay='After modification, the description file for '+uu[0]+' (in project '+uu[1]+') will be: ';
  newDescContents=adesc;
} else {
  vsay='After appending, the description file for '+uu[0]+' (in project '+uu[1]+') will be: ';
  newDescContents=refText+' \n '+adesc ;
}
vsay=vsay+'<input type="button" value="Would you like to save this (and overwrite the current contents of the description file)" onClick="goModifyDesc4()" />';

currentTaskDisplay(vsay,'<pre>'+newDescContents+'</pre>');

return 1;
}

// =====  save to describe.txt
function goModifyDesc4() {
var uname,toWrite,uu;

var uname=currentInstName ;

uu=extractProjectName(currentInstName);
updateStatus('About to save modified documentation file, for instrument or session '+uu[0]+' (in project '+uu[1]+')');


// postReferenceData set by caller (points either to instruments or session directory
toWrite=postDescText+'&name='+uname+'&content='+escape(newDescContents);

Post_toServer(postFileURL,toWrite,'saveModifiedDesc','saving modified documentation file','goModifyDesc5',uname); 

return 1; 

}


//=====================
// here after posting modified reference data to serer
function goModifyDesc5(uname) {
 var afoo,uu ;
  if (saveModifiedDesc.substr(0,1)=='-') {
   afoo='<b>Error.</b> Unable to update documentation text file';
   addActionHistory(afoo,saveModifiedDesc);
   updateStatus('Unable to update modified documentation text file ');
   return 1;
  }
   afoo='Modified  documentation text file, for instrument ' +uname+', has been updated.';
   addActionHistory(afoo,saveModifiedDesc);
   updateStatus('Modified  documentation text file has been updated');

  uu=extractProjectName(currentInstName);

  currentTaskDisplay('<b>Modify the  documentation text file for the instrument (or session):</b> '+uu[0]+' (in project '+uu[1]+')',saveModifiedDesc);
  currentTaskDisplay(1);

  toggleDisplay('doModify',1);

  return 1; 

}

/* ============  END of e modify instrument description file ===== */


/* ============  The modify-reference-data functions ===== */


function goModifyReference(usenam) {


stuff='You can modify a dSurvey <tt>reference</tt> data file.   \n ';
currentTaskDisplay('<b>Read an existing reference data file for '+usenam,stuff);
currentTaskDisplay(1);
toggleDisplay('doModify',0);

var toget=getReferenceXML_1.replace(/\$NAME\$/g,usenam) ;               // getReferenceXML_1 is set by caller (points to instruments or sessions directory

currentInstName=usenam;

// now get basic descriptor xml file and modify it
    Get_xmlFile(toget,['refNode','refNodeErr'],'retrieving a reference data file ','goModifyReference2',usenam,0) ;

    return 1 ;

}

//==========================

function goModifyReference2(usenam,ith) {

var ithrow=0,stuff;
var newRecordId='' ,newVarName='',taname;

var oof=E2_getNodes(refNode,'reference');
if (oof.length==0) {
  daval=E2_getNodeText(refNode);
        daval=daval.replace(/\</g,'&lt;');
        daval=daval.replace(/\>/g,'&gt;');
  currentTaskDisplay('Error reading XML file for '+makeProjName(usenam),daval);
  return 0;
}
var trcolors=['#effeef','#feeffe'];
var v1,i,i2,isexpand,isVars,isDesc0,isDesc,descs={},isRecords,stuff,stuff0,tmp,adesc,rdata,rids=[],myvals,varnames=[],tvarnames=[];
var avarval,aelem,avarname,arow,anid,tmp,isdel;
var maxlength=4 ;

if (usenam===0) usenam=currentInstName;

if (ith==1 || ith==11) {
  newVarName=prompt('Name of the new variable ','');
  if (newVarName==='') {
        alert('Error: you must enter a new variable name ');
        return 0 ;
  }
  newVarName=strip(newVarName);
  tmp=getWord(newVarName);
  if (tmp.length>1) {
        alert('Error: new variable name must be just one word ');
        return 0;
   }
   newVarDesc=prompt('Enter a description for this variable ('+newVarName+') ','');
}

if (ith==2 || ith==11) {
  newRecordId=prompt('The record ID (note: 0 can be used to define default values) ','');
  if (newRecordId==null) return 0 ;
  if (newRecordId==='' || newRecordId.length==0 ) {
        alert('Error: you must enter a new record ID ');
        return 0 ;
  }
  if (isNaN(newRecordId)) {
        alert('Error: record ID must be a number ');
        return 0;
   }
 }

v1=E2_getNodes(refNode,'reference');

// parse reference data file for variables and descriptions?
if (ith==0) {
  if (v1.length==0) {
        alert('Error: No <reference>, in file for '+usenam);
     return 0;
  }
  isexpand=getAttributes(v1[0],'expanded','0');
  if (isexpand!=1) {
     alert('Error: this utility can only modify "expanded" reference-data files. Try using the \n Modify an instruments control, parameter, SPEC, and module files\n option (on the main administrative page)');
    return 0;
  }
  isVars=E2_getNodes(v1[0],'vars');
  if (isVars.length<1) {
      alert('Error: no VARS section in reference data file ');
      return 0;
  } else {
     varnames=getWord(E2_getNodeText(isVars[0]));
  }

  isDesc0=E2_getNodes(v1[0],'descriptions');
  if (isDesc0.length<1) {
      alert('Error: no DESCRIPTIONS section in reference data file ');
      return 0;
  } else {
     isDesc=E2_getNodes(isDesc0[0],'var');
     descs={};
     for (var i=0;i<isDesc.length;i++) {
        aname=getAttributes(isDesc[i],'value name','0');
        if (aname=='0') {
           alert('Error: no name attribute in a variable description ');
           return 0;
        }
        aname=strip(aname).toUpperCase();
        descs[aname]=E2_getNodeText(isDesc[i]);
     }
     refDataDescs=descs ;
   }

   for (var i=0;i<varnames.length;i++) tvarnames[i]=strip(varnames[i]).toUpperCase() ;      // capitalize varnames

   refDataVarnames=varnames ;
} else {
   for (var i=0;i<refDataVarnames.length;i++) {
        varnames[i]=strip(refDataVarnames[i]) ;
        tvarnames[i]=varnames[i].toUpperCase() ;      // capitalize varnames
    }
    for (var i in refDataDescs) descs[i]=refDataDescs[i];
}

// check if newvarname already exists

// add a variable?
if (newVarName!=='') {

  taname=strip(newVarName).toUpperCase();
  for (var i=0;i<varnames.length;i++) {         // check if this name already exists
     if (taname==tvarnames[i]) {
          alert('Error: variable with this name ('+newVarName+') exists.');
          return 0;
      }
   }

   varnames=varnames.concat(newVarName);
   tvarnames=tvarnames.concat(taname);
   descs[taname]=newVarDesc;
   refDataVarnames=varnames ;
   refDataDescs=descs ;
}



isRecords=E2_getNodes(v1[0],'record');
stuff0='<input style="margin-left:20px" type="button" onClick="toggleDisplay(\'refVarDescs\');" title="toggle view of the variables and their descriptions " value="descriptions..."> <br/> \n ';

stuff=stuff0+'<div id="refVarDescs" style="display:none;margin-left:10%;background-color:#efe1ef"><table border="1"><tr>';

for (var i=0;i<varnames.length;i++) {
  stuff=stuff+'<tr><th>'+varnames[i]+'</th> ';
  adesc=descs[tvarnames[i]];
  stuff=stuff+'<td>'+adesc+'</td></tr> \n ';
}
stuff=stuff+'</table></div> \n ';


// read records
rdata={};
rids=[];
for (var i=0;i<isRecords.length;i++) {
  anid=getAttributes(isRecords[i],'id','');
  if (anid==='') {
        alert("Warning: no ID attribute for an existing record. It will be removed ");
        continue ;
  }
  rids=rids.concat(anid);
  rdata[anid]={};
  for (var i2=0;i2<varnames.length;i2++) {      // initialize
    avarname=tvarnames[i2];
    rdata[anid][avarname]='';
  }
  myvals=E2_getNodes(isRecords[i],'*');
  for (var i2=0;i2<myvals.length;i2++) {
       avarname=myvals[i2].nodeName; avarname=strip(avarname).toUpperCase();
       aelem=getAttributes(myvals[i2],'element','-');
       if (aelem!=='-') avarname=avarname+'['+aelem+']';
       avarname=cvtToArrayName(avarname) ;

       avarval=E2_getNodeText(myvals[i2]);
       maxlength=Math.max(maxlength,avarval.length);

//foo=confirm(' saveing '+anid+','+avarname+'='+avarval);
//if (!foo) return 0;

       rdata[anid][avarname]=avarval;
  }
}

// add a blank record
if (ith==2 || ith==11) {

   for (var i=0;i<rids.length;i++) {                       // does this recordid already exists?
     if (newRecordId==rids[i]) {
          alert('Error: a record with this id ('+newRecordId+') already exists.');
          return 0;
     }
   }

   anid=newRecordId;
   rids=rids.concat(anid);
   rdata[anid]={};
   for (var i2=0;i2<varnames.length;i2++) {             // might include new variable
      avarname=tvarnames[i2];
      rdata[anid][avarname]='';
    }
}


refDataIds=rids ;


stuff=stuff+'<b>The reference data </b>';

stuff=stuff+'<div style="margin-left:20px"><input type="button" value="Add a record" onClick="goModifyReference2(0,2)"> ';
stuff=stuff+'<input type="button" value="Add a variable" onClick="goModifyReference2(0,1)"> ';
stuff=stuff+'<input type="button" value="Add a record and a variable" onClick="goModifyReference2(0,11)"> </div> \n ';

stuff=stuff+'<table border="1"> ';
ithrow=1-ithrow;
 arow='<tr style="background-color:#ababab"><th>ID</th>';
 for (var i2=0;i2<varnames.length;i2++) {
   avar=varnames[i2];

   isdel=' <input type="checkbox" title="check here to remove this variable ('+avar+')" name="removeVars" isVar="'+avar+'"> ';
   arow=arow+'<th>'+isdel+'<br/>'+avar+'</th> ';
  }

  arow=arow+'</tr> \n ';
  stuff=stuff+arow;

 refDataInputs=[];
 for (var i=0;i<rids.length;i++) {
   anid=rids[i];
   ithrow=1-ithrow;
   arow='<tr style="background-color:'+trcolors[ithrow]+'">';

   isdel=' <input type="checkbox" title="check here to remove this record ('+anid+')" name="removeRecs" isid="'+anid+'"> ';
   arow=arow+'<th>'+ isdel + anid+'</th>';
   for (var i2=0;i2<varnames.length;i2++) {
     avar=tvarnames[i2];
     aval=rdata[anid][avar];
//foo=confirm(' showng '+anid+','+avar+'='+aval);
//if (!foo) return 0;

     tmp='<input size="'+(maxlength+2)+'" value="'+aval+'" type="value" name="newRefVals" varname="'+avar+'" recid="'+anid+'" /> \n ';
     arow=arow+'<td>'+tmp+'</td> ';
     tmp={};
     irr=refDataInputs.length;
     refDataInputs[irr]={};
     refDataInputs[irr]['varname']=avar;
     refDataInputs[irr]['recid']=anid;

    }
    arow=arow+'</tr> \n ';
    stuff=stuff+arow;
  }

stuff=stuff+'</table> \n ';

stuff=stuff+'<input type="button" value="Save the modifications " onClick="goModifyReference3(1)" title="click here after you have made changes that you wish to save" /> \n ';
stuff=stuff+'<p/>Notes: <ul><li>checkboxs are used to remove records, or variables </li><li>you can only add 1 record, and/or variable, at a time. That is: after adding a record/variable, you must save the modifications and click again on the <u>modify current reference data</u> task. </li></ul> ';
currentTaskDisplay('The reference data for '+makeProjName(usenam),stuff);

toggleDisplay('doModify',0);
return 0;
}

//============= stuff0
function goModifyReference3(ith) {

var stuff,i,i2,rdata={},anid,a1,a2,a3,uname;

foo=document.getElementsByName('newRefVals');

// initialize 
for (var i=0;i<refDataIds.length;i++) {
  anid=refDataIds[i];
  rdata[anid]={};
  for (var i2=0;i2<refDataVarnames.length;i2++) {
    avar=strip(refDataVarnames[i2]).toUpperCase();
    rdata[anid][avar]='' ;
  }
}

// get data from input fields
for (var i=0;i<foo.length;i++) {
  a1=getAttributes(foo[i],'recid','noid');
  if (typeof(rdata[a1])=='undefined') {
        alert('Error: goofy misssing ref id:'+a1);
        return 0;
  }
  a2=getAttributes(foo[i],'varname','novar');
  if (typeof(rdata[a1][a2])=='undefined'  ) {
          alert('Error: goofy misssing ref var '+a1+','+a2);
          return 0;
  }
  rdata[a1][a2]=foo[i].value ;
}


// get list of removeRecs and removeVars 
foo=document.getElementsByName('removeRecs');
removeRecs={};
for (var i=0;i<foo.length;i++) {
   if (foo[i].checked) {
     tmp=getAttributes(foo[i],'isId',0);tmp=strip(tmp).toUpperCase();
     removeRecs[tmp]=1; 
    }
}

removeVars={};
foo=document.getElementsByName('removeVars');
for (var i=0;i<foo.length;i++) {
   if (foo[i].checked) {
     tmp=getAttributes(foo[i],'isVar',0); tmp=strip(tmp).toUpperCase();
     removeVars[tmp]=1; 
   }
}


// display table
stuff='<table style="margin-left:5%;background-color:#efefef" border="1"><tr><td><tt>ID</tt>';
for (var i=0;i<refDataVarnames.length;i++) {
   tmp=strip(refDataVarnames[i]).toUpperCase();
   if (typeof(removeVars[tmp])=='undefined') stuff=stuff+"<th>"+refDataVarnames[i]+'</th>';
}
stuff=stuff+'</tr> \n ';
for (var i=0;i<refDataIds.length;i++) {  
  anid=refDataIds[i];
  if (typeof(removeRecs[anid])!=='undefined') continue ;
  arow='<tr><td><tt>'+anid+'</tt></td>' ;
  for (var i2=0;i2<refDataVarnames.length;i2++) {
        avar=strip(refDataVarnames[i2]).toUpperCase();
       if (typeof(removeVars[avar])=='undefined')  arow=arow+'<td>'+rdata[anid][avar]+'</td>';
  }
  arow=arow+'</tr> \n ';
  stuff=stuff+arow;
}
stuff=stuff+'</table> \n ';

refDataNewVals=rdata;

tmp='<input style="margin-left:20px;" type="button" value="If you want to save these values, click here" onClick="goModifyReference4(1)" /> ';
currentTaskDisplay('The modified reference data: '+tmp ,stuff);
currentTaskDisplay(1);
 
}
//======
function goModifyReference4(ith) {

var stuff,tmp,i,i2,avar,tavar,adesc,aline,arow,anelem,avar2;
var nrecs,nvars;
var uname=currentInstName;

stuff='<?xml version="1.0" encoding="UTF-8" ?> \n ';
stuff=stuff+'<!-- Reference data file for: '+ currentInstName + ' \n ' ;
stuff=stuff+' Created: '+svy_currentTime(2,2)+' --> \n \n ';
 
stuff=stuff+'<parameters>  \n  ';
stuff=stuff+'<reference expanded="1" >  \n  ';

aline='<vars>' ;
for (var i=0;i<refDataVarnames.length;i++) {
  tavar=strip(refDataVarnames[i]).toUpperCase();
  if (typeof(removeVars[tavar])!=='undefined') continue ;
  aline=aline+' '+refDataVarnames[i] ;
}
aline=aline+' </vars> ';
stuff=stuff+aline+' \n \n ';

stuff=stuff+'<descriptions> \n ';
nvars=0;
for (var i=0;i<refDataVarnames.length;i++)  {
  avar=refDataVarnames[i];
  tavar=avar.toUpperCase();
  if (typeof(removeVars[tavar])!=='undefined') continue ;
  nvars++;
  adesc=refDataDescs[tavar]; 
  aline= '  <var name="'+avar+'">'+adesc+'</var> \n '; 
  stuff=stuff+aline;
}
stuff=stuff+'</descriptions> \n \n ';

nrecs=0; 
for (var i=0;i<refDataIds.length;i++) {
  anid=refDataIds[i];
  if (typeof(removeRecs[anid])!=='undefined') continue ;
  nrecs++ ;
  arow='<record id="'+anid+'" > \n';
  for (var i2=0;i2<refDataVarnames.length;i2++) {
        avar=strip(refDataVarnames[i2]).toUpperCase();
        if (typeof(removeVars[avar])!=='undefined') continue ;
        anelem=' ';avar2=avar;
        if (avar.indexOf('[')>-1) {                             // a[n] style
            tmp=parseUsing(avar,'[',']',1);
            avar =tmp[0];
            anelem=' element="'+tmp[1]+'" '    
         }
        arow=arow+'  <'+avar+anelem+' >'+refDataNewVals[anid][avar2]+'</'+avar+'> \n';
  }  
  arow=arow+'</record> \n \n ';
  stuff=stuff+arow;
}

stuff=stuff+'</reference> \n </parameters> \n ';  


// now save as REFERENCE.XML in instruments/instName 

updateStatus('About to save modified reference data file, for instrument or session '+uname);


// postReferenceData set by caller (points either to instruments or session directory
toWrite=postReferenceData+'&name='+uname+'&content='+escape(stuff);

Post_toServer(postFileURL,toWrite,'saveModifiedReference','saving modified XML reference data file','goModifyReference5',uname,nrecs,nvars) ;

return 1; 

}



//=====================
// here after posting modified reference data to serer
function goModifyReference5(uname,nrec,nvar) {
 var afoo ;

  if (saveModifiedReference.substr(0,1)=='-') {
   afoo='<b>Error.</b> Unable to update reference data file';
   addActionHistory(afoo,saveModifiedReference);
   updateStatus('Unable to update modified reference data file ');
   return 1;
  }
   afoo='Modified reference data file, for instrument ' +uname+', has been updated; with '+nrec+' records and '+nvar+' variables.'
   addActionHistory(afoo,saveModifiedReference);
   updateStatus('Modified reference data file has been updated');

  var uu=extractProjectName(uname);
  var tfoo=uu[0]+' (in project '+uu[1]+')';
  currentTaskDisplay('<b>Modify the reference dataset for the instrument (or session):</b> '+tfoo,saveModifiedReference);
  currentTaskDisplay(1);

  toggleDisplay('doModify',1);

  return 1; 

}



/* ============  END OF The modify-reference-data  functions ===== */



/* ============  The create-reference-data-from-csv functions ===== */


function goMakeReference(usenam,theData) {

 if (arguments.length<2) theData='';
 var stuff,uu;

 stuff='You can create a dSurvey <tt>reference</tt> data set from CSV (comma seperated) file.   \n ';
 stuff=stuff+'<a href="#top" title="click here to view some hints and rules about using CSV files " ';
  stuff=stuff+' onClick="toggleDisplay(\'csvHints\');return false">More details</a> \n ';
                  
 stuff=stuff+' <div id="csvHints" style="display:none;padding-left:10px"> \n ';

stuff=stuff+'<h4>Rules for the CSV file</h4> ';

stuff=stuff+'<ul> \n ' ;
stuff=stuff+'<li>The first row must contain variable names. <br> \n ' ;
stuff=stuff+'  Note: the first column (of the first row) is ignored, since .... \n ' ;
stuff=stuff+'<li> The first column must contain the <tt>reference id</tt>.  \n ' ;
stuff=stuff+'<li> You can specify <em>array names</em> for your variable names by using a syntax of <tt>vname[ith]</tt>, \n ' ;
stuff=stuff+'where <tt>vname</tt> is the array name, and <tt>ith</tt> is the numeric index. For example: <tt>COSTU[1]</tt>. \n ' ;
stuff=stuff+'<li> Until we update this utility, you must <b>not</b> include  commas or double-quote characters in your values. \n ' ;
stuff=stuff+'<li> If the last row has no value in the first column (or a value of <tt>D</tt>), then its values are used as "descriptions" of the variable \n ' ;
stuff=stuff+'(corresponding to this column). \n ' ;
stuff=stuff+'</ul> \n ' ;  
  
stuff=stuff+'<br/> \n ' ;
stuff=stuff+'<a href="/dsurvey/docs/sampleCSVFile.htm" target="help1">Would you like to view an example of a suitable CSV file?</a> \n ' ;
stuff=stuff+'<br> </div> \n ' ;

stuff=stuff+'<p/><em>for now, use this hacky entry method ...</em>  Enter your CSV file in this text box. Better yet, cut &amp; paste! <br/> \n ';
stuff=stuff+'<textarea wrap="off" style="white-space: nowrap; overflow: auto"  cols="110" rows="18" name="myCSVfile" ">';
stuff=stuff+theData+'\n </textarea>';
stuff=stuff+' <input onClick="goMakeReference2()" type="button" value="Create the Reference data using the above CSV info" \n ';
uu=extractProjectName(usenam);
currentTaskDisplay('<b>Read a CSV data file, and create a reference dataset for the instrument:</b> '+uu[0]+' (in project '+uu[1]+')',stuff);
currentTaskDisplay(1);

toggleDisplay('doModify',0);

}

//=====================
// here after entry of  csv file
function goMakeReference2() {
var arf,arf2,avars,i,alines,goo,vnames,j,zoo,anid;
var theRefNameVar=0;

var rowColors=[];
var iRowColors=0;  
rowColors[0]='#efeeed';
rowColors[1]='#dddedf';  

var idsList={};


refDescVars={}; refVars=[];

  arf=document.getElementsByName('myCSVfile');
  arf2=arf[0];
  csvRefDataSavedOrig=arf2.value ;                // global used in next step

 numErrs=0;

// first, divide into lines (at CRLFS or ;)

csvRefDataSaved=csvRefDataSavedOrig.replace(/\n/g,';');  
alines=csvRefDataSaved.split(';'); 

goo='<div id="refVarsDescShow" style="border:1px solid gray;background-color:#feeffe; display:none"> </div> \n ';
goo=goo+'<table border="1"> <tr style="background-color:yellow"><th style="background-color:cyan">ID</th> \n ';
vnames=alines[0];
refVars=vnames.split(',');
for (var i=1;i<refVars.length;i++) {
   if (strip(refVars[i]).toUpperCase()=='REFNAME') theRefNameVar=i ;
    goo=goo+'<th><span style="text-decoration:underline" onClick="showRefDescVars('+i+')" title="Click to see variable description (if available)">'+refVars[i]+'</span></th> '
}
goo=goo+"</tr> \n " ;

for (var i=1;i<alines.length;i++) {
   if (strip(alines[i])=='') continue ;
   avars=alines[i].split(',');

   if (avars.length>refVars.length) {
                alert(' Record '+i+' has too many variables. It will be dropped ');
                continue;
   }

   iRowColors=1-iRowColors;
   goo=goo+'<tr style="background-color:'+rowColors[iRowColors]+'"> \n ' ;
   aid=avars[0];
   if (isNaN(aid)) {                            //maybe a D or DESC?
       if (strip(aid).substr(0,1).toUpperCase()=='D') {                        // description line
           for (var j=1;j<avars.length;j++) refDescVars[j]=avars[j];    
          continue ;
       } else {
          alert('Error in CSV file: non-numeric value ('+aid+') for ID (first column inr row '+i);
         numErrs++ ;
       }
    }
   
     anid=strip(avars[0]);
     if (typeof(idsList[anid])!='undefined') {
                alert('Error: multiple rows with the same ID ('+anid+'). Skipping row '+i);
                continue ;
     }
    idsList[anid]=i;
     goo=goo+'<td  style="background-color:cyan">'+anid+'</td> ' ;
     for (var j=1;j<avars.length;j++) {   
         if (j==theRefNameVar) {
             goo=goo+'<td style="background-color:lime">'+avars[j]+'</td> ' ;     

         } else {
             goo=goo+'<td>'+avars[j]+'</td> ' ;     
         }
     }
   
   goo=goo+"<tr> \n " ;
}
goo=goo+'</table>';   

goo=goo+'<p/> If this looks correct, ';
goo=goo+'<input title="click here to save the CSV file as the reference data file" ';
goo=goo+'         type="button" value="create the REFERENCE datafile" onClick="goMakeReference3()"> \n ';
goo=goo+'<br>Otherwise, you can  ';
goo=goo+'<input title="modify the CSV data" ';
goo=goo+'         type="button" value="modify the CSV data" onClick="goMakeReference(currentInstName,csvRefDataSavedOrig)"> \n ';


currentTaskDisplay('<b>Your CSV data as a table ...',goo);

return 1; 
}


//=====================
// here after accepting the entered csv file
function goMakeReference3() {

var arf,arf2,avars,i,alines,goo,vnames,j,uname;
var vline,dline,rlines,anid ;
var nrecords=0,nvars=0 ;
var idsList={};

uname=currentInstName ;

refDescVars={}; refVars=[];

arf2=csvRefDataSaved ;

numErrs=0;

goo='<?xml version="1.0" encoding="UTF-8" ?> \n';
goo=goo+'<!-- Reference data file for: '+uname+' \n Created: '+svy_currentTime(2,2)+' --> \n \n ';

goo=goo+'<parameters> \n \n <reference expanded="1" > \n \n  ' ;

// first, divide into lines
alines=arf2.split(';');  

// first line is variable names
vnames=alines[0];
refVars=vnames.split(',');
vline='<vars>';
nvars=refVars.length;
for (var i=1;i<nvars;i++) {
    vline=vline+refVars[i]+' ' ;
}
vline=vline+'</vars> \n ';  

dline='<descriptions> \n  </descriptions> ';            // default is no descriptions

rlines='\n ';
for (var i=1;i<alines.length;i++) {
   if (strip(alines[i])=='') continue ;
   nrecords++ ; 
   avars=alines[i].split(',');

   if (avars.length>nvars) {
                alert(' Record '+i+' has too many variables. It will be dropped ');
                continue;
   }

   aid=avars[0];
   if (isNaN(aid)) {                            //maybe a D or DESC?
       if (strip(aid).substr(0,1).toUpperCase()=='D') {                        // description line
            dline='<descriptions> \n ';            // default is no descriptions
            for (var j=1;j<avars.length;j++) {
                dline=dline+'<var name="'+strip(refVars[j])+'">'+avars[j]+'</var> \n ' ;    
            }
           dline=dline+'</descriptions> \n ';
           continue ;
       } else {
             alert('Error in CSV file: non-numeric value ('+aid+') for ID (first column inr row '+i);
             numErrs++ ;
       }
    }

     anid=strip(avars[0]);
     if (typeof(idsList[anid])!='undefined') {
                alert('Error: multiple rows with the same ID ('+anid+'). Skipping row '+i);
                continue ;
     }
   idsList[anid]=i ;
  arecord='<record id="'+anid+'"> \n ' ;
  for (var j=1;j<avars.length;j++) {   
         vv1=refVars[j];
         velement='' ;
         if (vv1.indexOf('[')>-1) {
                vv1a=parseUsing(vv1,'[',']',1);
                vv1=strip(vv1a[0]);
                velement=' element="'+vv1a[1]+'" ' ;
          }
          arecord=arecord+'   <'+vv1+' '+strip(velement)+'>'+strip(avars[j])+'</'+vv1+'> \n ' ;    
     }
     arecord=arecord+'</record> \n  \n ';
     rlines=rlines+arecord;
}

goo=goo + vline + dline + rlines + ' </reference> \n </parameters> \n ';

// now save as REFERENCE.XML in instruments/instName 

updateStatus('About to save reference data file, for instrument (or session) '+uname);

toWrite=postReferenceData+'&name='+uname+'&content='+escape(goo);

Post_toServer(postFileURL,toWrite,'saveNewReference','saving new XML reference data file','goMakeReference4',uname,nrecords,nvars) ;

return 1; 

}

//=====================
// here after posting reference data to serer
function goMakeReference4(uname,nrec,nvar) {
 var uu,afoo,u2;
  if (saveNewReference.substr(0,1)=='-1') {
   afoo='<b>Error.</b> Unable to update reference data file';
   addActionHistory(afoo,saveNewReference);
   updateStatus('Unable to update reference data file ');
   return 1;
  }
  uu=extractProjectName(uname);

   afoo='Reference data file, for instrument ' +uname+', has been updated; with '+nrec+' records and '+nvar+' variables.'
   addActionHistory(afoo,saveNewReference);
   updateStatus('Reference data file has been updated');

  currentTaskDisplay('<b>Read a CSV data file, and created a reference dataset for the instrument:</b> '+uu[0]+' (in project '+uu[1]+')',saveNewReference);
  currentTaskDisplay(1);

  toggleDisplay('doModify',1);

   return 1; 

}



//===========================
// show a variable description
function showRefDescVars(ith) {
   if (typeof(refDescVars[ith])=='undefined') {
        mydesc='<em>n.a.</em>';
   } else {
        mydesc=refDescVars[ith] ;
   }
vv=document.getElementById('refVarsDescShow');
vv.innerHTML='Description of variable <u> '+refVars[ith]+'</u><tt>: '+mydesc+'</tt>' ;
toggleDisplay('refVarsDescShow',1);
return 1;
}

/* ========= update DIVS (status, etc) functions ============= */

//==================
// update the status area 
function updateStatus(amessage,ialert) {
if (arguments.length<2) ialert=0;
 var ici;

   ici=document.getElementById('statusRecent');  
   if (ici) ici.innerHTML=amessage ;

   ici=document.getElementById('statusCount');  
   if (ici)   ici.innerHTML=parseInt(ici.innerHTML)+1 ;
   return 1;
}

//=====================================
// add something to create results
function addActionHistory(header,content,includeTime) {
var ia,afoo;
  if (arguments.length<2) content='';
  if (arguments.length<3) includeTime=0;

  ia=document.getElementById('actionHistory');

  if (!ia) return 1 ;           // no actionHistory, so don't bother writing info there

  afoo='';
  if (includeTime==1)  afoo='<div class="resultsT">'+ svy_currentTime(2,2)+'</div> /n ';
  afoo=afoo+'\n <div class="results0">'+header+'</div> \n ';
  if (content!=='')   afoo=afoo+' <div class="results1">'+content+'</div> \n ';

  ia.innerHTML=ia.innerHTML+'\n '+afoo ;
  return 1 ;
}


//=====================================
// toggle display of a div. If no argument, div is 'actionHistory'
function toggleDisplay(a,todo,dohow) {
  if (arguments.length<1) a='actionHistory';
  if (arguments.length<2) todo=-1 ;
  if (arguments.length<3) dohow='block' ;
  var ia=document.getElementById(a);
  if (!ia) alert('no such id: '+a);
  if (typeof(toggleDisplayStatus[a])=='undefined') toggleDisplayStatus[a]=0;  // assume start undisplayed

  if (todo==-1) {                               // not explicit. Lookup in global array
      if (toggleDisplayStatus[a]==0) {                  // toggle!
           todo=1 ;     
      } else {
          todo=0;
      }
  }
  toggleDisplayStatus[a]=todo ;
  if (todo==0) {                               // not explicit. Lookup in global array
         ia.style.display='none' ;
   } else {
         ia.style.display=dohow ;
   }
  return false ;
}


//=================
// update the currentTask div (where forms and current task info is displayed
// header: header (in a 1 line colored div
// content : content 
// includeTime. If specified, include a time stamp at the top
// header special codes: 0= hide currentTask, 1=display currentTask
// note that currentTask by default is HIDDEN

function currentTaskDisplay(header,content,includeTime) {
  if (arguments.length<2) content='';
  if (arguments.length<3) includeTime=0;

// two special codes
  if (strip(header)=='0') {
    toggleDisplay('currentTask',0);  
     return 1;
  }
  if (strip(header)=='1') {
     toggleDisplay('currentTask',1);  
     return 1;
  }
  ia=document.getElementById('currentTask');
  afoo='';
  if (includeTime==1)  afoo='<div class="createT">'+ svy_currentTime(2,2)+'</div> /n ';
  afoo=afoo+'\n <div class="create0">'+header+'</div> \n ';
  if (content!=='')   afoo=afoo+' <div class="create1">'+content+'</div> \n ';

  ia.innerHTML=afoo ;

  return 1 ;

}


// =======================
// shows a list of currently defined instruments (in a div)
function showInstList() {
var atable,m,mm,tt,aname,wasproj,aproj,aproj0;
var instList2=[];
var projList={};

atable='<b>List of currently available instruments...</b>';
atable=atable+'<table border="1">';

// parse out projects and names from list of instrument files
for (m=0 ;m<instList.length;m++) {
  instList2[m]=[];
  ainst=strip(instList[m]);
  instList2[m]=extractProjectName(ainst)
  if (instList2[m][1]!=='') projList[instList2[m][1]]=1;
}
wasproj='';
mct=0;
//for (m=0 ;m<instList.length;m=m+6) {
for (m=0 ;m<instList.length;m++) {
  mct++;
  ainst=strip(instList[m]);
  aname=instList2[m][0];
  aproj=instList2[m][1];

  if (mct==7 || aproj!==wasproj) {
        atable=atable+'</tr> ';
        mct=1;
        wasproj=aproj;
  }
  aproj0=aproj;
  if (aproj0=='') aproj0='(none)';
  if (mct==1) atable=atable+'<tr><td style="background-color:#dedede"><tt>'+'<a title="Click to use this project" href="#" onClick="writeTo1wordB(\''+aproj+'\'); return false">'+aproj0+'</a></tt> ';

  tt='<a href="#" title="click to chose this instrument" onClick="writeTo1word(\''+ainst+'\'); return false">'+aname+'</a> ';
  atable=atable+'<td>'+tt+'</td>';
}
atable=atable+'</tr> \n ';
atable=atable+'</table> ';


dd=document.getElementById('instListShow') ;  
dd.innerHTML=atable;
toggleDisplay('instListShow',1);
return 1 ;


}

//==========
function writeTo1word(aword) { 
 var ii,uu ;
 ii=document.getElementById('existName');
 if (ii) {
     uu=extractProjectName(aword);
     ii.value=uu[0] ;
     writeTo1wordB(uu[1]) ;
  }
 return 1;
}

//==========
function writeTo1wordB(awordb) { 
 var ii ;
 ii=document.getElementById('existProject');
 if (ii) ii.value=awordb ;
return 1;
}


