/* procedures used to modify xml parameter files   */

/*  ======

 For all of these:
        the sessName global variable MUST contain the name of the current session!

 modifySession() -- modify the descriptor file for current session
 modifyGeneral(filename) -- modify the "GENERAL" section of an xml file.
 modifyReference(filename,'REFERENCE') -- modify the "REFERENCE" section of an xml file.
 modifyReference(filename,'USERS') -- modify the "USERS" section of an xml file.

 Filename is a session specific parameter file (for the current session).
                      
The following IDS are used to display stuff:              
   statusMessages :  various status messages
    displayArea   : parametters etc.
      paramsTable : should be under displayArea: tbody of the table used to display parameters
       saveButton : should be under displayArea: input used to save changes
 

======== */

/* ========== Modify a session's descriptor file ======= */
function modifySession(aval,ido) {
  var icurrent,glub,instname;

// <table  border="1" style="margin-left:2%"><tbody  id="paramsTable">
//     <tr><th width="15%"></th><th width="35%"></th><th width="50%"></th>  
//  </tbody ></table>

   showSessionDetails('paramsTable',sessionNode,'',1,'SESSIONNAME SESSIONDESCRIPTION INSTRUMENTNAME CREATED MODIFIED FILE') ;

  instname=lookupNodeVar(sessionNode,'instrumentName','');
  instname=instname.replace(/\n /g,'');instname=strip(instname); 
  icurrent=document.getElementById('saveButton');
  icurrent.value='Save changes to session-descriptor file ';
  glub=make_procString("saveModifiedSession",1,aval,instname) ;
  icurrent.setAttribute('onClick',glub);

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

return 1 ;
}

/* ========== Modify a session's parameter file: GENERAL section  ======= */
function modifyGeneral(aval,ido) {

if (arguments.length<2) ido=1 ;

var tmp,icurrent,toget,m;

if (typeof(sessName)=='undefined' || sessName=='') {
        alert('Error in modifyGeneral: sessName not defined ');
        return 1;
}

m=document.getElementById('statusMessages'); m.innerHTML='' ;
if (ido==1) {
  if (sessName=='') {
        alert('Error: you must first select a session ');
        return 1 ;
  }
  if (aval=='') {
        alert('No file specified for this session ');
        return 1 ;
   }
  aval=strip(aval);
  toget=getSessionDataURL+'name='+sessName+'&file='+aval;
   Get_xmlFile(toget,'paramFileNode','retrieving a sessions parameter file ','modifyGeneral',aval,2) ;
   return 1 ;

}

if (ido==2) {

 tmp=E2_getNodes(paramFileNode,'GENERAL');
 if (tmp.length<1) {
    icurrent=document.getElementById('statusMessages');
    icurrent.innerHTML='The '+aval+' parameters file does not have a GENERAL section ' ;
    icurrent.style.display="block";
    m=document.getElementById('displayArea');  m.style.display='none';
    return 1;
 }

   showSessionDetails('paramsTable',paramFileNode,'general',1) ;
  icurrent=document.getElementById('saveButton');
  icurrent.value='Save changes to GENERAL parameters ';
  var glub=make_procString("saveModifiedGeneral",1,aval) ;
  icurrent.setAttribute('onClick',glub);
  icurrent.style.display='block';
  var m=document.getElementById('displayArea');  m.style.display='block';
  var m=document.getElementById('paramsTable');  m.style.display='block';

}
return 1 ;

}


/* ========== Modify reference or user section of a xml data file. ======= */
// Step 1: read the aval file (an xml file)
// Step 2: display a table (in the paramsTable) containing each row of this file (1 table row per reference row, 1 cell per variable

function modifyReference(aval,reftype,ido) {

if (arguments.length<3) ido=1 ;
if (arguments.length<2) reftype='reference';
reftype=strip(reftype.toUpperCase()) ;

if (typeof(sessName)=='undefined' || sessName=='') {
        alert('Error in modifyReference: sessName not defined ');
        return 1;
}

var  icurrent,ttr,tth,tstuff,ttd,cnode,aname,atype,vval,vvalslist,varlist,cnode2 ;
var cnode2,aname2,m2,theid,thevals,vallist,theval,adesc,tmp,m,aRefNode,rownodes,numRows,rdelim;
var refNodesDESC=new Object() ;
var linesPer,ict,vnodes;
var atable,atbody;

m=document.getElementById('statusMessages');  m.innerHTML='' ;

if (ido==1) {
  if (sessName=='') {
        alert('Error: you must first select a session ');
        return 1 ;
  }
  if (aval=='') {
        alert('No  file specified for this session ');
        return 1 ;
   } 

  toget=getSessionDataURL+'name='+sessName+'&file='+strip(aval) ;
   Get_xmlFile(toget,'paramFileNode','retrieving a sessions parameter file ','modifyReference',aval,reftype,2) ;
   return 1 ;

}

if (ido==2) {

 tmp=E2_getNodes(paramFileNode,reftype);
 if (tmp.length<1) {
    icurrent=document.getElementById('statusMessages');
    icurrent.innerHTML='The '+aval+' parameters  file does not have a  '+reftype+' section ' ;
    icurrent.style.display="block";
    m=document.getElementById('displayArea');  m.style.display='none'; 
    return 1;
 }

   aRefNode=tmp[0];
   var isexpanded=aRefNode.getAttribute('expanded');
   if (isexpanded=='1') {
    icurrent=document.getElementById('statusMessages');
    icurrent.innerHTML='The '+reftype+ ' node is expanded.  Currently, this utility can not edit this type of XML data.' ;
    icurrent.style.display="block";
    m=document.getElementById('displayArea');  m.style.display='none'; 
    return 1;
   }
// find VARS 
  cnode=E2_getNodes(aRefNode,'VARS');
  if (cnode.length==0) {
        alert('Error in '+reftype+' section of XML file: no VARS specified');
         return 1 ;
  }
  cnode=cnode[0]
  avarlist=E2_getNodeText(cnode,1,''); avarlist=avarlist.replace(/\,/g,' ')
  varlist=getWord(avarlist);
 

// find  DESCRIPTIONS node
  cnode=E2_getNodes(aRefNode,'DESCRIPTIONS');
  if (cnode.length>0) {
        cnode=cnode[0];
        vnodes=E2_getNodes(cnode,'VAR');
        for (var m2=0; m2<vnodes.length;m2++) {
              cnode2=vnodes[m2];
              aname2=getAttributes(cnode2,'name var desc','');
              aname2=strip(aname2.toUpperCase());
              if (aname2==='') continue;
              theval=E2_getNodeText(cnode2);
              refNodesDESC[aname2]=theval ;
       }                        // found DESC node
  }                             // search for DESC node



// find ROWS or USERS
  cnode=E2_getNodes(aRefNode,'VALS');
  if (cnode.length==0) {
        alert('Error in '+reftype+' section of XML file: no VALS specified');
         return 1 ;
  }
  rdelim=getAttributes(cnode[0],'delim',' ');

  if (reftype=='REFERENCE') {
     rownodes=E2_getNodes(cnode[0],'row');
 } else {
     rownodes=E2_getNodes(cnode[0],'user');
  }
  numRows=rownodes.length ;

// unhide and modify some divs
  icurrent=document.getElementById('displayArea');
  icurrent.style.display='block';

  icurrent=document.getElementById('saveButton');
  icurrent.value='Save changes to '+reftype ;
  var glub=make_procString("saveModifiedReference",1,reftype,aval,varlist.length) ;
  icurrent.setAttribute('onClick',glub);

  icurrent=document.getElementById('paramsTable');
  
  icurrent.innerHTML='';

  atable=document.createElement('table');
  atbody=document.createElement('tbody');

  linesPer=(varlist.length/refNodesCols)+0.999 ; linesPer=Math.floor(linesPer);

// Write the column headers 

  ttr=document.createElement('tr');             // first column (refereence id)
  tth=document.createElement('th');
  if (reftype=='REFERENCE') {
          tstuff=document.createTextNode('Ref ID');
  } else {
          tstuff=document.createTextNode('User ID');
  }        
  tth.appendChild(tstuff);
  tth.style.width='65px'; 
  ttr.style.backgroundColor='#aaff99'; 
  ttr.appendChild(tth);

  tth=document.createElement('td');                     // divider cell
  tstuff=document.createTextNode(' ');
  tth.appendChild(tstuff);
  tth.style.backgroundColor='cyan';
  tth.style.width='5px';
  ttr.appendChild(tth);

  ict=0;
  for (var m=0;m<varlist.length;m++) {                  // write the column headers, possibly several table rows per data row
    ict++ ;
    if (ict>refNodesCols) {                             // create 2nd, 3rd line within header row
        icurrent.appendChild(ttr);
        ttr=document.createElement('tr');
        ttr.style.backgroundColor='#aaff99'; 

        tth=document.createElement('td');
           tstuff=document.createTextNode(' ');
           tth.appendChild(tstuff);
           tth.style.width='65px'; 
        ttr.appendChild(tth);

        tth=document.createElement('td');                     // divider cell
           tstuff=document.createTextNode('   ');
           tth.appendChild(tstuff); 
           tth.style.backgroundColor='cyan';
           tth.style.width='5px';
        ttr.appendChild(tth);
        ict=1;
    }
    tth=document.createElement('th');
    tavar=strip(varlist[m].toUpperCase());
    tstuff=document.createTextNode(varlist[m]);
    tth.appendChild(tstuff);
    adesc='' ; 
    if (typeof(refNodesDESC[tavar])!='undefined') {
      tth.setAttribute('title',varlist[m]+' : ' + refNodesDESC[tavar]);
      tth.style.textDecoration='underline';
      tth.style.color='blue';
    }
    ttr.appendChild(tth);
  }

  atbody.appendChild(ttr);


// display data rows (possibly over several table lines

  iswitch=1;
  for  (var m=0;m<numRows;m++) {                                // 1 TR (table row) per data row

     rowID=getAttributes(rownodes[m],'id','');                  // this row's id
     if (rowID=='') {
        alert('Error: row ' +m+' in REFERENCE does NOT have an id');
        return 1;
      }
     rowVals=E2_getNodeText(rownodes[m],1,'');                          // data for this row
     rowVals=getWord(rowVals,0,rdelim);
     for (var m2=rowVals.length;m2<varlist.length;m2++) rowVals[m2]='';     // pad to proper length

     iswitch=1-iswitch ;
     ttr=document.createElement('tr');  
     ttr.style.backgroundColor=inputRowColor[iswitch] ;

     tth=document.createElement('th');                                  // id column
     tstuff=document.createTextNode(rowID);
     tth.appendChild(tstuff);
     tth.style.width='65px'; 
     tth.style.color='red';
     ttr.appendChild(tth);

     tth=document.createElement('td');                          // spacer
     tstuff=document.createTextNode(' ');
     tth.appendChild(tstuff);
     tth.style.backgroundColor='cyan';
     tth.style.width='5px';
     ttr.appendChild(tth);

     ict=0;
     for (var m2=0;m2<varlist.length;m2++) {                            // the variables (perhaps over several table lines
        ict++ ;
        if (ict>refNodesCols) {                                         // make 2nd, ... table line for this data row
            icurrent.appendChild(ttr);
            ttr=document.createElement('tr');
            ttr.style.backgroundColor=inputRowColor[iswitch] ;
            tth=document.createElement('td');
               tstuff=document.createTextNode(' ');
               tth.appendChild(tstuff);
               tth.style.width='65px'; 
               ttr.appendChild(tth);
            tth=document.createElement('td');
               tstuff=document.createTextNode(' ');
               tth.appendChild(tstuff);
               tth.style.width='5px'; 
               tth.style.backgroundColor='cyan'; 
               ttr.appendChild(tth);
            ict=1;
        }
        rval=rowVals[m2];
        tth=document.createElement('td');                               // a cell for this row/variable
        tti=document.createElement('input');
        tti.value=rval ;
        tti.setAttribute('size',rval.length+2);
        tti.setAttribute('class','rowval');
        tti.setAttribute('col',m2);
        tti.setAttribute('rowid',rowID);

        tth.appendChild(tti);
        ttr.appendChild(tth);
     }  
     atbody.appendChild(ttr);
        
  }                                     // all rows of vvalsIDS
}                       // ido=2

atable.appendChild(atbody);
icurrent.appendChild(atable);
icurrent.style.display='block';
 
return 1 ;

}                       



/* ========== Save modified session descriptor file ======= */

function saveModifiedSession(ith,filename,instName) {
var ith,goo,toSubmit,alist,afile,m,aname,isarray,avalue,at1,arow,adesc,anode,alist2,bnode,gotmodified;

if (arguments.length<1) ith=1 ;

if (ith==2) {
  if (postResponse<0) {
     goo=document.getElementById('displayArea'); goo.style.display='none';
     goo=document.getElementById('statusMessages');  goo.style.display='block';
     goo.innerHTML= 'The session descriptor file, for the '+sessName+' session, was   <b>not modified</b> (error code='+postResponse+') ';
     return 1;
   }
   goo=document.getElementById('displayArea'); goo.style.display='none';
   goo=document.getElementById('statusMessages');  goo.style.display='block';
   goo.innerHTML= 'The  session descriptor  parameter file, for the '+sessName+' session, has been  <b>successfully modified</b> ';
  return 1 ;
}

 
/* save input and textarea elements  to storage array*/
alist=get_elements('input','aParameter');
alist2=get_elements('textarea','aParameter');
alist=Concat_Arrays(alist,alist2);
var valList=new Object() ;
for (var m=0;m<alist.length;m++) {
     avalue=alist[m].value ;
     if (alist[m].getAttribute('readonly')==1) continue ;
     aname=strip(alist[m].getAttribute('var').toUpperCase()) ;
     valList[aname]=avalue ;
}   
valList['MODIFIED']=svy_currentTime(1,2) ;
;
/*Always start with the xml header */
 afile='<?xml version="1.0" encoding="UTF-8" ?> \n' ;
gotmodified=0;
/* replace contents of nodes in sessionNode */
 for (var m=0;m<sessionNode.childNodes.length;m++) {
    anode=sessionNode.childNodes[m];
    if (anode.nodeType!=1) continue ;
    aname=strip(anode.nodeName.toUpperCase());
   if (aname=='MODIFIED') gotmodified=1;
    if (typeof(valList[aname])!='undefined') {
        anode.childNodes[0].nodeValue=valList[aname] ;
     }
 }
 if (gotmodified==0) {
    anode=document.createElement('modified');
    bnode=document.createTextNode(svy_currentTime(1,2));
    anode.appendChild(bnode);
    sessionNode.appendChild(anode);
  }
  afile=afile+'\n \n ' + E2_xmlToString(sessionNode) + ' \n ' ;

 afile=escape(afile);

   toSubmit=postSessionFilesHeader+'&name='+sessName+'&instName='+instName+'&overwrite=1&content='+afile;
   Post_toServer(postFileURL,toSubmit,'postResponse','posting modified session descriptor file ','saveModifiedSession',2);
   return 1;
}


/* ========== Save modified  general parameters file ======= */

function saveModifiedGeneral(ith,filename) {
var ith,goo,toSubmit,alist,afile,m,aname,isarray,avalue,at1,arow,adesc,anode;


if (arguments.length<1) ith=1 ;

if (ith==2) {
  if (postResponse<0) {
     goo=document.getElementById('displayArea'); goo.style.display='none';
     goo=document.getElementById('statusMessages');  goo.style.display='block';
     goo.innerHTML= 'The '+filename+' parameter file, for the '+sessName+' session, was   <b>not modified</b> (error code='+postResponse+') ';
     return 1;
   }
     goo=document.getElementById('displayArea'); goo.style.display='none';
     goo=document.getElementById('statusMessages');  goo.style.display='block';
     goo.innerHTML= 'The '+filename+' parameter file, for the '+sessName+' session, has been  <b>successfully modified</b> ';
  return 1 ;
}

/* replace the GENERAL section with the results of the edit. Retain other sections */
/* write all the INPUT elements (using thevar as variable name */
alist=get_elements('input','aParameter');

/*Always start with the xml header */
   afile='<?xml version="1.0" encoding="UTF-8" ?> \n' ;
   afile=afile+'<parameters> \n \n';
   afile=afile+'<modified> '+ svy_currentTime(1,2) +'</modified> \n ';

/* now redo the general section --- */
   afile=afile+'<general> \n  \n';
 
   for (var m=0 ; m<alist.length;m++) {
        aname=alist[m].getAttribute('var');
        isarray=alist[m].getAttribute('array');
        avalue=alist[m].value ;
        adesc=alist[m].getAttribute('desc');
        at1='';
        if (isarray==1) at1=' array="1" '
        arow='<desc value="'+aname+'">'  + adesc +'</desc> \n';
        arow=arow+'<'+aname+' ' +at1+ '>'  + avalue +'</'+aname+'>';
        afile=afile+arow+'\n \n';
   }
   afile=afile+'</general> \n \n ';                     // END of redone general section

/* check for reference section. If it exists, add verbatim (no changes ) */
   anode=E2_getNodes(paramFileNode,'REFERENCE');
   if (anode.length>0) {
        tmp=E2_xmlToString(anode[0]);
        afile=afile+' \n \n' + tmp ;
    }

/* check for users section. If it exists, add verbatim (no changes ) */
   anode=E2_getNodes(paramFileNode,'USERS');
   if (anode.length>0) {
        tmp=E2_xmlToString(anode[0]);
        afile=afile+' \n \n '+tmp ;
    }

   afile=afile+'\n </parameters> \n ';                     // close out the XML file with proper end tag
   afile=escape(afile);

   toSubmit=postFileHeader+'&name='+sessName+'&File='+filename+'&content='+afile;
   Post_toServer(postFileURL,toSubmit,'postResponse','posting xml parameter file ','saveModifiedGeneral',2,filename);

   return 1;
} 



/* ========== Save modified reference or user data ======= */

function saveModifiedReference(ith,reftype,filename,alength) {
var ith,changeFile,alist,goo,vlist,davar,m,tname,tnode,afile,cnode,atype,taname,aname,iatt,at1,m2,avalue,arow,tosubmit,tavar,rdelim;
if (arguments.length<1) ith=1 ;

if (ith==2) {
  if (postResponse.substr(0,1)=='-') {
     goo=document.getElementById('displayArea'); goo.style.display='none';
     goo=document.getElementById('statusMessages');  goo.style.display='block';
     goo.innerHTML= 'The  file, for the '+sessName+' session, was   <b>not modified</b> (error code='+postResponse+') ';
     return 1;
   }
     goo=document.getElementById('displayArea'); goo.style.display='none';
     goo=document.getElementById('statusMessages');  goo.style.display='block';
     goo.innerHTML= 'File '+filename+', for the '+sessName+' session, has been  <b>sucessfully modified</b> ';
  return 1 ;
}
 
// create a lookup table containing the values from the INPUTs

inodes=get_elements('input','rowval');                  // find all input elements with a rowval class

var newvals=new Object();
newvals['$ROWS']=[];

for (var m=0;m<inodes.length;m++) {                     // create a lookup table
    anode=inodes[m];
    aval=anode.value ;
    rowid=anode.getAttribute('rowid');
    if (typeof(newvals[rowid])=='undefined') {
         newvals[rowid]=[] ;
         newvals['$ROWS']=newvals['$ROWS'].concat(rowid);
    }
    acol=getAttributes(anode,'col','');
    newvals[rowid][acol]=aval;
}
for (m=0;m<newvals['$ROWS'].length;m++) {                // fill in missing values in newvals with ''
   tmp=newvals['$ROWS'][m];
   for (var m2=0;m2<alength;m2++) {
        if (typeof(newvals[tmp][m2])=='undefined') newvals[tmp][m2]=' ';
   }
   newvals[tmp]=newvals[tmp].slice(0,alength) ;                 // remove any extras
}    


/* modify the REFERENCE or USERS section of the paramFileNode node (depends on reftype) */
  tmp=E2_getNodes(paramFileNode,reftype);                    // assume it exists (if not, caught above)
  aRefNode=tmp[0];
  cnode=E2_getNodes(aRefNode,'VALS');
  rdelim=getAttributes(cnode[0],'delim',' ');

  if (reftype.toUpperCase()=='REFERENCE') {
      rownodes=E2_getNodes(cnode[0],'row');
   } else {
      rownodes=E2_getNodes(cnode[0],'user');
  }

  for (var m=0; m<rownodes.length;m++) {
     rnode=rownodes[m];
     anid=getAttributes(rnode,'ID','');                 // assume exists (so don't check for valid id
     if (typeof(newvals[anid])=='undefined') continue ;  // shouldn't happen: no inputs for this ROW
     vvals=newvals[anid].join(rdelim);
     rownodes[m].childNodes[0].nodeValue=vvals ;
   }

/*  Create the XML file. Start with generic header   */
   afile='<?xml version="1.0" encoding="UTF-8" ?> \n' ;
   afile=afile+'<parameters> \n \n ';
   afile=afile+'<modified> '+svy_currentTime(1,2)+' </modified>   \n ';

/* add general, reference, and users sections .. */
   anode=E2_getNodes(paramFileNode,'GENERAL');
   if (anode.length>0) {
        tmp=E2_xmlToString(anode[0]);
        afile=afile+' \n \n '+tmp ;
    }

   anode=E2_getNodes(paramFileNode,'REFERENCE');
   if (anode.length>0) {
        tmp=E2_xmlToString(anode[0]);
        afile=afile+' \n \n '+tmp ;
    }

   anode=E2_getNodes(paramFileNode,'USERS');
   if (anode.length>0) {
        tmp=E2_xmlToString(anode[0]);
        afile=afile+' \n \n '+tmp ;
    }

   afile=afile+' \n \n </parameters> \n ';

   afile=escape(afile);

   toSubmit=postFileHeader+'&name='+sessName+'&File='+strip(filename)+'&content='+afile ;
   Post_toServer(postFileURL,toSubmit,'postResponse','posting xml  file ','saveModifiedReference',2,reftype,filename,alength) ;

   return 1;
} 








