function fgInsertRow(schemaName,queryName,row,cb=null,containerPath=null){
   let fName='[fgInsertRow]';
   print(fName);
   //cb=function(data){....}
	let qconfig=new Object();
	if (containerPath)
      qconfig.containerPath=containerPath;
	qconfig.schemaName=schemaName;
	qconfig.queryName=queryName;
	qconfig.success=cb;
	qconfig.rows=[row];
   print(fName+' qconfig '+qconfig);
	LABKEY.Query.insertRows(qconfig);
}

function addInputRow(table,header,type){
   let fName='[addInputRow]';
   print(fName);
   let row=table.insertRow();
   let cell=config.document.createElement('th');
   let text=config.document.createTextNode(header);
   cell.appendChild(text);
   row.appendChild(cell);
   let input=null;
      
   if (type=="select")
      input=config.document.createElement(type);

   if (type=="button"){
      input=config.document.createElement("input");
      input.type="button";
   }
   if (type=="text"){
      input=config.document.createElement('textarea');
      input.cols="65";
      input.rows="5";
   }
   if (type=="label")
      input=config.document.createElement(type);

   let cell1=row.insertCell();
   cell1.appendChild(input);
   return input;
}
 
function getFormName(formId){
   let rows=config.formConfig.dataForms.rows;
   for (let i=0;i<rows.length;i++){
      if (rows[i]['Key']==formId){
         return rows[i]['formName'];
      }
   }
   return "NONE";
}

function getQueryName(queryId){
   let rows=config.formConfig.inputLists.rows;
   for (let i=0;i<rows.length;i++){
      if (rows[i]['Key']==queryId){
         return rows[i]['queryName'];
      }
   }
   return "NONE";
}

function getGCRow(formId){
   let formRows=config.formConfig.generateConfigData.rows;
   for (let i=0;i<formRows.length;i++){
      if (formRows[i]['formId']==formId){
         return formRows[i];
      }
   }
   return Object();
}

function getCrfSelectRow(crfRef){
   let rows=config.formConfig.crfSelectRows;
   for (let i=0;i<rows.length;i++){
      if (rows[i]['crfRef']==crfRef)
         return rows[i];

   }
   return Object();
}


function addOption(input,name,value){
   let opt=config.document.createElement("option");
   opt.text=name;
   opt.value=value;
   input.options[input.options.length]=opt;
}
 
function clearOptions(input){
   for(let i = input.options.length; i >= 0; i--) {
		input.remove(i);
   }
}
	

   
function addFormGenerator(){
      
   let fName='[addFormGenerator]';
   print(fName);
   //layout
   let table=config.document.createElement("table");
   table.className="t2";
   config.document.getElementById(config.div).appendChild(table);
   let formGenerator=new Object();
   formGenerator.formSelect=addInputRow(table,'Select form',"select");
   formGenerator.crfSelect=addInputRow(table,'Select CRF',"select");
   formGenerator.comment=addInputRow(table,'Enter comment','text');
   formGenerator.details=addInputRow(table,'Details','label');
   formGenerator.warnings=addInputRow(table,'Warnings','label');
   formGenerator.warnings.innerHTML='None';
   addOption(formGenerator.formSelect,'<Select>',-1);
   let formRows=config.formConfig.generateConfigData.rows;
   for (let i=0;i<formRows.length;i++){
      let formId=formRows[i]["formId"];
      let formName=getFormName(formId);
      print(fName+' '+formRows[i]["formId"]+'/'+formName);
      addOption(formGenerator.formSelect,formName,formId);
   }
   formGenerator.formSelect.onchange=function(){updateIdList(formGenerator);};
   formGenerator.crfSelect.onchange=function(){updateLabel(formGenerator);};
   formGenerator.generateButton=addInputRow(table,'Generate Form','button');
   formGenerator.generateButton.value="Generate Form";
   formGenerator.generateButton.onclick=function(){createFormWithId(formGenerator);};
      
}
      
function createFormWithId(formGenerator){
   //get form id and entry id from select and create form as above
   let fName='[createFormWithId]';

   print(fName);
   let formId=formGenerator.formSelect.options[formGenerator.formSelect.selectedIndex].value;
   let crfRef=formGenerator.crfSelect.options[formGenerator.crfSelect.selectedIndex].text;
   let configRow=getGCRow(formId);
   let crfSelectRow=getCrfSelectRow(crfRef);
	let formConfig=config.formConfig;

	print("Create form w/id "+formId);
	
	let crfEntry=new Object();
	crfEntry.entryId=Date.now();
	crfEntry["Date"]=new Date();
	crfEntry["View"]="[VIEW]";
   crfEntry['participantStudyId']=crfSelectRow['participantStudyId'];
   crfEntry['participantLocalId']=crfSelectRow['participantLocalId'];


	crfEntry.formStatus=configRow['formStatus'];//In progress
	//set other variables
	//requires studyData as part of formConfig
	let studyData=formConfig.studyData.rows[0];
   let varRows=formConfig['crfStaticVariables'].rows;
   for (let i=0;i<varRows.length;i++){
      let varName=varRows[i].staticVariable;
	   crfEntry[varName]=studyData[varName];
   }
	crfEntry.UserId=LABKEY.Security.currentUser.id;
	crfEntry.Site=config.formConfig.currentSites[0].siteNumber;
	print("Setting site to id="+crfEntry.Site);
	//from argument list
	crfEntry.Form=formId;
   crfEntry.parentCrf=crfRef;
  
   //
   //compose a reviewComments entry
   let reviewComment=new Object();
   reviewComment['submissionDate']=crfEntry['Date'];
   reviewComment['crfRef']=crfRef;
   //comment length
   let x=formGenerator.comment.value;
   print(fName+' comment length '+x.length);
   if (x.length==0){
      formGenerator.warnings.innerHTML='Supply a comment';
      return;
   }
   reviewComment['reviewComment']=formGenerator.comment.value;
   reviewComment['queryName']=configRow['queryId'];

   let rd=function(data){redirect();};
   let pass=function(data){fgInsertRow('lists','reviewComments',reviewComment,rd,getContainer('data'));}
   fgInsertRow('lists','crfEntry',crfEntry,pass,getContainer('data'));
}


function updateIdList(formGenerator){
   let fName='[updateIdList]';
   let formId=formGenerator.formSelect.options[formGenerator.formSelect.selectedIndex].value;
   print(fName+' id '+formId);
   //remove old options
   clearOptions(formGenerator.crfSelect);
   print(fName+' options cleared');
   //get query associated with form
   let configRow=getGCRow(formId);
   let queryId=configRow['queryId'];
   print(fName+' queryId '+queryId);
   if (!queryId || queryId<0)
      return;

   let qselect=new Object();
   qselect.containerPath=getContainer('data');
   qselect.schemaName='lists';
   qselect.queryName=getQueryName(queryId);
   qselect.success=function(data){updateIdListWithData(formGenerator,data);};
   LABKEY.Query.selectRows(qselect);
}

function updateIdListWithData(formGenerator,data){
   let rows=data.rows;
   config.formConfig.crfSelectRows=data.rows;
   for (let i=0;i<rows.length;i++){
      addOption(formGenerator.crfSelect,rows[i]['crfRef'],i);
   }
   let event=new Event('change');
   formGenerator.crfSelect.dispatchEvent(event);
}

function updateLabel(formGenerator){
   let crfRef=formGenerator.crfSelect.options[formGenerator.crfSelect.selectedIndex].text;
   let crfSelectRow=getCrfSelectRow(crfRef);
   formGenerator.details.innerHTML='Generating for Study:'+crfSelectRow['participantStudyId']+' / Local:'+crfSelectRow['participantLocalId'];
}

function redirect(){

	let debug=false;
	let formUrl="begin";
	let params=new Object();
	params.name=formUrl;
	params.pageId="CRF";

	//points to crf container
	let containerPath=getContainer('data');
        
	// This changes the page after building the URL. 
	//Note that the wiki page destination name is set in params.
        
	var homeURL = LABKEY.ActionURL.buildURL(
			"project", formUrl , containerPath, params);
        print("Redirecting to "+homeURL);
	if (debug) return;	 
	window.location = homeURL;

	

}