//<!--################################################### 
//Copyright (c) 2010 U.S. Food and Drug Administration

//Permission is hereby granted, free of charge, to any person obtaining a copy of this software (Study Design XForm) and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, or sell copies of the Software or derivatives, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

//The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.  THIS SOFTWARE IS PROVIDED WITHOUT ANY OBLIGATION TO PROVIDE MAINTENANCE OR OTHER SUPPORT."
//####################################################################-->

var model = null;
var scratch_instance = null;
var template_instance = null;
var build_Instance = null;
var existing_template_instance=null;
var xInstance = null;
var typeofstudy_instance=null;
var tped_instance=null;
var sort_instance=null;
var glp_instance=null;
var celltemplate_instance =null;
var subject_instance=null;
var save_instance=null;
var matchfoundindex ='';
var library_instance=null;
var sorted_instance=null;
var sdtm_instance=null;
var duplicateexists=false;
var xmlfile;
var xslfile;
var xhttpRequest;





 var studyDesignProcessor = new XSLTProcessor();// var spl2htmlProcessor = new XSLTProcessor();

 var studyDesignSaveAsProcessor = new XSLTProcessor();

function initialize() {
 model = null;
 scratch_instance = null;
 template_instance = null;
 build_Instance = null;
 existing_template_instance=null;
 xInstance = null;
 typeofstudy_instance=null;
 tped_instance=null;
 sort_instance=null;
 glp_instance=null;
 celltemplate_instance =null;
 subject_instance=null;
 save_instance=null;
 matchfoundindex ='';
 library_instance=null;
 sorted_instance=null;
 sdtm_instance=null;


    // Initialize global variables for instance indexing
    model = document.getElementById("plannedStudyModel");
    scratch_instance = model.getInstanceDocument("instance_scratch");
    template_instance = model.getInstanceDocument("template_instance");
    build_Instance = model.getInstanceDocument("plannedStudyInstance");
    celltemplate_instance=model.getInstanceDocument("celltemplate");
    typeofstudy_instance=model.getInstanceDocument("TypeOfStudy");
    tped_instance=model.getInstanceDocument("Tped");
    glp_instance=model.getInstanceDocument("GLP");
    existing_template_instance=model.getInstanceDocument("buildTemplates");
    subject_instance=model.getInstanceDocument("subjectInstance");
    library_instance=model.getInstanceDocument("libraryInstance");
    sorted_instance=model.getInstanceDocument("sorted_instance");
    sdtm_instance=model.getInstanceDocument("SDTM");
    
    

        xhttpRequest = new XMLHttpRequest();
         xhttpRequest.open("GET", "xsl/externalGridStylesheet.xsl", false);
        xhttpRequest.send(null); 
        
        var xsl = xhttpRequest.responseXML;
       // alert(xsl);
        studyDesignProcessor.importStylesheet(xsl);





        var scr = document.getElementById("javaScripts");

    // Add event listeners for adding into nodesets
        scr.addEventListener("SaveSuccess", SaveSuccess, true);
        scr.addEventListener("SaveFail", SaveFail, true);
        scr.addEventListener("OpenSuccess", OpenSuccess, true);

     scr.addEventListener("setSaveInstance", setSaveInstance, false);
    scr.addEventListener("setInstanceModel", setInstanceModel, false);
    scr.addEventListener("setOpenFormat", setOpenFormat, false);
    scr.addEventListener("addNewEpoch",addFirstEpoch,false);
    scr.addEventListener("addNewStudyCharacteristics",add_StudyCharacteristics,false);
    scr.addEventListener("addNewArm",addFirstArm,false);
     scr.addEventListener("testEpoch",testEpoch,false);
     scr.addEventListener("addPositionalEpochs",addPositionalEpochs,false);
     scr.addEventListener("addPositionalCharacteristics",addPositionalCharacteristics,false);
     scr.addEventListener("addPositionalArms",addPositionalArms,false);
     scr.addEventListener("doesStudyTypeExist",doesStudyTypeExist,false);
     scr.addEventListener("alertTest",alertTest,false);
     scr.addEventListener("displayIndex",displayIndex,false);
     scr.addEventListener("appendSegments",appendSegments,false);
     scr.addEventListener("checkEpochDependencies",checkEpochDependencies,false);
     scr.addEventListener("checkArmDependencies",checkArmDependencies, false);

     scr.addEventListener("addTimePointEvent",addTimePointEvent,false);
     scr.addEventListener("characteristicsInsert",characteristicsInsert,false);
     scr.addEventListener("doesGLPCharacteristicExist",doesGLPCharacteristicExist,false);
     scr.addEventListener("reviewMode",reviewMode,false);
    scr.addEventListener("reviewModePreconditions",reviewModePreconditions,false);
    scr.addEventListener("reviewModeCharacteristics",reviewModeCharacteristics,false);

     scr.addEventListener("addSegmentPrecondition",addSegmentPrecondition,false);
     scr.addEventListener("deleteTimePoint",deleteTimePoint,false);
     scr.addEventListener("deletePrecondition",deletePrecondition,false);
     scr.addEventListener("addSegmentCharacteristics",addSegmentCharacteristics,false);
     scr.addEventListener("deleteTimePointCharacteristic",deleteTimePointCharacteristic,false);
     scr.addEventListener("insertComponent4",insertComponent4,false);
     scr.addEventListener("addTemplateElement",addTemplateElement,false);
     scr.addEventListener("addToStudy",addToStudy,false);
    scr.addEventListener("addTemplatePrecondition",addTemplatePrecondition,false);
    scr.addEventListener("addTemplateTimePointCharacteristic",addTemplateTimePointCharacteristic,false);
    scr.addEventListener("deleteCell",deleteCell,false);
    scr.addEventListener("addNewEligibilityCriterion",addNewEligibilityCriterion,false);
    scr.addEventListener("generateTemplates",generateTemplates,false);
    scr.addEventListener("addTemplateElementToExistingTemplate",addTemplateElementToExistingTemplate,false);
    scr.addEventListener("updateAllCells",updateAllCells,false);
    scr.addEventListener("deleteTemplateElementCells",deleteTemplateElementCells,false);
    scr.addEventListener("addTemplatePreconditionToExistingTemplate",addTemplatePreconditionToExistingTemplate,false);
    scr.addEventListener("deleteTemplatePreconditionCells",deleteTemplatePreconditionCells,false);
    scr.addEventListener("addTemplateTPCharacteristicToExistingTemplate",addTemplateTPCharacteristicToExistingTemplate,false);
    scr.addEventListener("deleteTemplateTPCharacteristicsCells",deleteTemplateTPCharacteristicsCells,false);
    scr.addEventListener("addTemplateLocation",addTemplateLocation,false);
        scr.addEventListener("addTemplateSubject",addTemplateSubject,false);

    scr.addEventListener("addTemplateLocationToExistingTemplate",addTemplateLocationToExistingTemplate,false);
        scr.addEventListener("deleteExistingTemplateLocation",deleteExistingTemplateLocation,false);

        scr.addEventListener("addTemplateSubjectToExistingTemplates",addTemplateSubjectToExistingTemplates,false);
       scr.addEventListener("deleteExistingTemplateSubject",deleteExistingTemplateSubject,false);
       scr.addEventListener("setStudyType",setStudyType,false);
       scr.addEventListener("addSubjectToArms",addSubjectToArms,false);
       scr.addEventListener("synchronizeSubjects",synchronizeSubjects,false);
       scr.addEventListener("generateSubjectTemplates",generateSubjectTemplates,false);
              scr.addEventListener("addTemplateElementTimePoint",addTemplateElementTimePoint,false);

      scr.addEventListener("deleteTemplateElementTimePoint",deleteTemplateElementTimePoint,false);
      scr.addEventListener("deleteTemplateSubElementCells",deleteTemplateSubElementCells,false);
      scr.addEventListener("addTemplateSubElementToExistingTemplate",addTemplateSubElementToExistingTemplate,false);
            scr.addEventListener("addSubElementTemplateLocation",addSubElementTemplateLocation,false);

      scr.addEventListener("deleteSubElementTemplateLocation",deleteSubElementTemplateLocation,false);

      scr.addEventListener("addTemplateLocationToExistingSubElement",addTemplateLocationToExistingSubElement,false);

      scr.addEventListener("deleteTemplateLocationFromExistingSubElement",deleteTemplateLocationFromExistingSubElement,false);
     scr.addEventListener("addSubElementTemplatePrecondition",addSubElementTemplatePrecondition,false);
     scr.addEventListener("deleteTemplateElementPrecondition",deleteTemplateElementPrecondition,false);
     scr.addEventListener("addExistingSubElementPrecondition",addExistingSubElementPrecondition,false);
     scr.addEventListener("deleteExistingSubElementPrecondition",deleteExistingSubElementPrecondition,false);
     scr.addEventListener("addSubElementTemplateCharacteristic",addSubElementTemplateCharacteristic,false);
     scr.addEventListener("deleteTemplateElementCharacteristic",deleteTemplateElementCharacteristic,false);
    scr.addEventListener("addExistingSubElementCharacteristic",addExistingSubElementCharacteristic,false);
         scr.addEventListener("deleteExistingSubElementCharacteristic",deleteExistingSubElementCharacteristic,false);
         scr.addEventListener("viewStylesheet", viewStylesheet,false);
         scr.addEventListener("refreshCellTemplate", refreshCellTemplate,false);
  scr.addEventListener("updateLibrary", updateLibrary,false);
  scr.addEventListener("addSubjectCondition",addSubjectCondition,false);
  scr.addEventListener("deleteSubjectCondition",deleteSubjectCondition,false);
  scr.addEventListener("characteristicDelete",characteristicDelete,false);
  scr.addEventListener("deleteSubjectFromArm",deleteSubjectFromArm,false);
  scr.addEventListener("checkCount",checkCount,false);
 scr.addEventListener("setTemplateEncounterName",setTemplateEncounterName,false);
 scr.addEventListener("setCDISCCodeValue",setCDISCCodeValue,false);
  scr.addEventListener("setCDISCCodeValueExistingTemplate",setCDISCCodeValueExistingTemplate,false);
  scr.addEventListener("testNumber",testNumber,false);
  scr.addEventListener("testString",testString,false);
  scr.addEventListener("checkFileType",checkFileType,false);
  scr.addEventListener("setBirthdateAndAllocate",setBirthdateAndAllocate,false);
  scr.addEventListener("setBirthdateAndAllocateExisting",setBirthdateAndAllocateExisting,false);
 scr.addEventListener("setRootOnOpen", setRootOnOpen, true); 	
 scr.addEventListener("setRoot", setRoot, true); 	
 scr.addEventListener("setGLPonOpen", setGLPonOpen, true); 	
 scr.addEventListener("checkTheGLP", checkTheGLP, true); 	
scratch_instance.getElementsByTagName("defaultSaveName") [0].childNodes[0].textContent=(scratch_instance.getElementsByTagName("defaultSaveName") [0].childNodes[0].textContent).concat(build_Instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:id",build_Instance, nsResolver,  XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.getAttributeNode("root").childNodes[0].nodeValue)+ '.xml';

}

function setTemplateEncounterName()
{
     var valuepassed = scratch_instance.getElementsByTagName("encounterName") [0].textContent;
     alert(" Value passed is:"+ valuepassed);
}


function checkFileType()
{

scratch_instance.getElementsByTagName("studyDesignMessage") [0].childNodes[0].nodeValue='No';
var studyDesignMessage = build_Instance.evaluate("/hl7-org_v3:plannedStudy", build_Instance, nsResolver, XPathResult.BOOLEAN_TYPE, null).booleanValue  ;
if (studyDesignMessage == true)
{
scratch_instance.getElementsByTagName("studyDesignMessage") [0].childNodes[0].nodeValue='Yes';
}
else
{
alert('Please open a valid Study Design message.');	
}
}


function testString()
{
  if(scratch_instance.getElementsByTagName("stringToCheck") [0].childNodes[0].nodeValue=='')
       {
         alert("Please enter a string in the mandatory field");
         scratch_instance.getElementsByTagName("stringToCheck") [0].childNodes[0].textContent="Fail";
       }
    else
    { 
             scratch_instance.getElementsByTagName("stringToCheck") [0].childNodes[0].textContent="Pass";

    }   
}




function testNumber()
{
  if(isNaN(scratch_instance.getElementsByTagName("numberToCheck") [0].childNodes[0].nodeValue) || scratch_instance.getElementsByTagName("numberToCheck") [0].childNodes[0].nodeValue=='')
       {
         alert("Please enter a numeric value in the mandatory 'Number' field");
         scratch_instance.getElementsByTagName("numberToCheck") [0].childNodes[0].textContent="Fail";
       }
    else
    { 
             scratch_instance.getElementsByTagName("numberToCheck") [0].childNodes[0].textContent="Pass";

    }   
}


//  A Working DOM Example
function testEpoch()
{
alert("xforms-ready invoked");

  // testing_instance = model.getInstanceDocument("plannedStudyInstance");
   //x=testing_instance.getElementsByTagName("epoch")[0];
   //y=x.getAttribute("classCode");
   //alert(y);
   
   //the below is a way to get the value of the text in a child node. since every text is stored in a child node you must first get the text node and then use the 'nodevalue' function to get the text.
    // alert("Javascript Insert "+ scratch_instance.getElementsByTagName("epochjavascript") [0].childNodes[0].nodeValue +" And the value of the index is " + scratch_instance.getElementsByTagName("epochindex") [0].textContent);
//      scratch_instance.getElementsByTagName("epochjavascript") [0].childNodes[0].nodeValue =100;
  //   alert("New value is : " + newvalue);

 }





function setCDISCCodeValueExistingTemplate()
{
   scratch_instance.getElementsByTagName("selectedCode") [0].textContent=""
   var theSelectedObservation = scratch_instance.getElementsByTagName("selectedObservation") [0].textContent
   var cellIndex = scratch_instance.getElementsByTagName("templateCellIndex") [0].textContent -1
   var encounterIndex = scratch_instance.getElementsByTagName("encounterNumber") [0].textContent -1
   var observationIndex = scratch_instance.getElementsByTagName("observationCodeIndex") [0].textContent -1
   
  var currentCell =  existing_template_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:component4/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1", existing_template_instance, nsResolver,XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,null).snapshotItem(cellIndex).cloneNode(true);
     
  var currentEncounter =  existing_template_instance.evaluate("hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1", currentCell, nsResolver,XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,null).snapshotItem(encounterIndex).cloneNode(true);
   
    var allObservations = existing_template_instance.evaluate("hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component2/hl7-org_v3:observation",currentEncounter, nsResolver,    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);

    var actualObservation=allObservations.snapshotItem(observationIndex);
        var thisOBS = existing_template_instance.evaluate("hl7-org_v3:code",actualObservation, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.getAttributeNode("displayName").nodeValue
       
    var preferredNames =    sdtm_instance.evaluate("dataroot/SDTMTerminology/PreferredTerm",sdtm_instance, nsResolver,    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
    var count=preferredNames.snapshotLength;
    var matchIndex="";
    for (var i=0;i<count ;i++)
	{ 
	    if (thisOBS == preferredNames.snapshotItem(i).textContent)	
	         { 	    
	        // alert(thisOBS +  ' =  ' +  preferredNames.snapshotItem(i).textContent)
	           matchIndex=i; 
	              var allCodes =  sdtm_instance.evaluate("dataroot/SDTMTerminology/Code",sdtm_instance, nsResolver,    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
   var relevantCode=allCodes.snapshotItem(matchIndex).textContent;
    scratch_instance.getElementsByTagName("selectedCode") [0].textContent=relevantCode;
	           break;
	          }
	          
	 	 
	} 
    

    selectedPreferredName=null;
    allPreferredNames=null;
    count=null;
    matchIndex=null;
    allCodes=null;
    relevantCode=null;
        
    
    
  
}


function setCDISCCodeValue()
{
 scratch_instance.getElementsByTagName("selectedCode") [0].textContent=""
    var encounterNumber = scratch_instance.getElementsByTagName("encounterNumber") [0].textContent-1;
    var index = scratch_instance.getElementsByTagName("observationCodeIndex") [0].textContent-1;
 //   alert("Encounter number is:" + encounterNumber + "Observation number is:" + index);
    var currentEncounter = celltemplate_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:component4/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1",celltemplate_instance, nsResolver,XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,null).snapshotItem(encounterNumber).cloneNode(true);
   // alert("current Encounter is:" + currentEncounter);
    var allObservations = celltemplate_instance.evaluate("hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component2/hl7-org_v3:observation",currentEncounter, nsResolver,    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);

   //alert("totalcount is is :" + allObservations.snapshotLength);
    var actualObservation=allObservations.snapshotItem(index);
    scratch_instance.getElementsByTagName("selectedObservation") [0].textContent=actualObservation.getElementsByTagName("code")[0].getAttributeNode("displayName").nodeValue;
//alert("selected observation is :" +  scratch_instance.getElementsByTagName("selectedObservation") [0].textContent);
    
    var preferredNames =    sdtm_instance.evaluate("dataroot/SDTMTerminology/PreferredTerm",sdtm_instance, nsResolver,    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
    var count=preferredNames.snapshotLength;
    var matchIndex=null;
    for (var i=0;i<count ;i++)
	{ 
	    if (scratch_instance.getElementsByTagName("selectedObservation") [0].textContent == preferredNames.snapshotItem(i).textContent)
	         { 
	           matchIndex=i; 
	              var allCodes =  sdtm_instance.evaluate("dataroot/SDTMTerminology/Code",sdtm_instance, nsResolver,    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
   var relevantCode=allCodes.snapshotItem(matchIndex).textContent;
    scratch_instance.getElementsByTagName("selectedCode") [0].textContent=relevantCode;
	           break;
	          }
	          
	 	 
	} 
	
	
   // alert("total preferred names are:"+ count + " And the match was found at :"+ matchIndex);
    

    
    index=null;
    allObservations=null;
    actualObservation=null;
    preferredNames=null;
    count=null;
    matchIndex=null;
    allCodes=null;
    relevantCode=null;
}

function loadXMLDoc(dname)

{
   xhttpRequest = new XMLHttpRequest();
   xhttpRequest.open("GET", dname, false);
  xhttpRequest.send(null);

  return xhttpRequest.responseXML;
}


function viewStylesheet()
{
//alert("View Stylesheet Called");
   /*sortForStylesheet();
   // sorted_instance=model.getInstanceDocument("sorted_instance");
   	 if (sorted_instance == null) {
    return null;
  }*/
  var mainDocument = document.implementation.createDocument("", "stylesheetdisplay", null);
  var fragment= studyDesignProcessor.transformToFragment(build_Instance, mainDocument);
  
  //alert("Fragment Is:"+ fragment);

var xsltnode= document.getElementById("xsltnode");

//alert("XSLT node is:" + xsltnode);
    if (xsltnode.childNodes.length == 0) {
        xsltnode.appendChild(html);
    } else {
    xsltnode.replaceChild(fragment, xsltnode.firstChild);
     
    }

fragment=null;
mainDocument=null;
xsltnode=null;

}


function sortAscending(a,b)
    {
       return (a-b);
       
    }


function   sortForStylesheet()
{
alert("sort called:");
   var sequenceArray=new Array();
   var epochNameArray= new Array();
   var armNameArray = new Array();

   var parentCell =   sorted_instance.evaluate("hl7-org_v3:plannedStudy/hl7-org_v3:root/hl7-org_v3:sort",sorted_instance, nsResolver,    XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
   var allCells = sorted_instance.evaluate("hl7-org_v3:cell",parentCell, nsResolver,    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
   var allEpochNameCells = sorted_instance.evaluate("hl7-org_v3:sortEpochName",parentCell, nsResolver,    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
   var allArmNameCells=sorted_instance.evaluate("hl7-org_v3:sortArmName",parentCell, nsResolver,    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
   
   var cellCountinSort=allCells.snapshotLength;
   var epochCellCount = allEpochNameCells.snapshotLength;
   var armCellCount=allArmNameCells.snapshotLength;
   
  //   alert("Total sort cells to delete :" + cellCountinSort + "  Epoch Cell NAme Cell:"+ epochCellCount);

	for (var i=0;i<cellCountinSort;i++)
	 {
	   var cellToDelete=allCells.snapshotItem(i);
	   cellToDelete.parentNode.removeChild(cellToDelete);  
	   cellToDelete=null;
	 }
    
  	for (var i=0;i<epochCellCount;i++)
	 {
	   var cellToDelete=allEpochNameCells.snapshotItem(i);
	 //  alert("Obtained Epoch Name Cell to delete:"+ cellToDelete);
	   cellToDelete.parentNode.removeChild(cellToDelete);  
	   cellToDelete=null;
	 }
   
   	for (var i=0;i<armCellCount;i++)
	 {
	   var cellToDelete=allArmNameCells.snapshotItem(i);
	 //  alert("Obtained Epoch Name Cell to delete:"+ cellToDelete);
	   cellToDelete.parentNode.removeChild(cellToDelete);  
	   cellToDelete=null;
	 }
  
  


var allEpochs=  build_Instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:component1",build_Instance, nsResolver,    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
var totalEpochs=allEpochs.snapshotLength;
var allArms=  build_Instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:component2",build_Instance, nsResolver,    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
var totalArms=allArms.snapshotLength;

for(var i=0;i<totalEpochs;i++)   //obtain all sequences that are present in the Study
      {
         sequenceArray[i]=parseInt(allEpochs.snapshotItem(i).getElementsByTagName("sequenceNumber")[0].getAttributeNode("value").nodeValue);
       //  alert("result is:"+ sequenceArray[i]);
         epochNameArray[i] = allEpochs.snapshotItem(i).getElementsByTagName("epoch")[0].getElementsByTagName("id")[0].getAttributeNode("extension").nodeValue;
      }
  sequenceArray.sort(sortAscending);     

//alert(sequenceArray);

for(var i=0;i<totalEpochs;i++)
	{
	   var seqTofind=sequenceArray[i];
		  
		   for(var j=0;j< totalEpochs;j++)
				  {
					  var epochElement= allEpochs.snapshotItem(j);
					 var epochName  = epochElement.getElementsByTagName("epoch")[0].getElementsByTagName("id")[0].getAttributeNode("extension").nodeValue;
					 var sequenceNumber  =epochElement.getElementsByTagName("sequenceNumber")[0].getAttributeNode("value").nodeValue;
					 if(sequenceNumber == seqTofind)
						  {
							 epochNameArray[i]=epochName;
						  }
	   
				  }
	
	}
      
      
      
      
      
 // alert("epoch name array-----"+     epochNameArray);
 //obtain sequences in order.
//epochNameArray.sort(); //sort Array of epochs 
//alert(epochNameArray);

for (var i=0;i<totalEpochs;i++) //create the elements in the sort_instance which stores the name of the epochs.
    {
           var sortEpochElement = template_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:addSortEpoch/hl7-org_v3:sortEpochName", template_instance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.cloneNode(true);
	 sortEpochElement.childNodes[0].nodeValue=epochNameArray[i];
      parentCell.appendChild(sortEpochElement);
      }
      


for (var i=0;i<totalArms;i++)
{
   armNameArray[i]=allArms.snapshotItem(i).getElementsByTagName("arm")[0].getElementsByTagName("id")[0].getAttributeNode("extension").nodeValue;
   var elementToInsert = template_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:addSortArm/hl7-org_v3:sortArmName", template_instance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.cloneNode(true);
   elementToInsert.childNodes[0].nodeValue= armNameArray[i];
   parentCell.appendChild(elementToInsert);
}

 var allExistingBuildCells  =   build_Instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:component4/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1",build_Instance, nsResolver,    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
  var totalCells=allExistingBuildCells.snapshotLength;
if(totalCells==0)
 {
  return;
  }


   for(var i=0;i<totalArms;i++)  //run through armname array to populate horizontal TD cells
        {
           for(var j=0;j<totalEpochs;j++)   //check if sequence number is the same as in the Sequence number array
             {
                var armName = armNameArray[i];
                var sequenceNumber = sequenceArray[j];
               // alert("Arm Name :"+ armName + "  sequence Number:"  + sequenceNumber);
                 var position=0;
                 var index=0;
                 var currentCellName=null;
                 var epochName=null;
                 var matchfound=false;
                      for(var k=0;k<totalCells;k++)
                         {
                            var currentCell =allExistingBuildCells.snapshotItem(k);
                            var currentCellSequenceNumber=build_Instance.evaluate("hl7-org_v3:sequenceNumber",currentCell,nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.getAttributeNode("value").childNodes[0].nodeValue; 
                            var currentCellArmName=build_Instance.evaluate("hl7-org_v3:timePointEventDefinition/hl7-org_v3:componentOf2/hl7-org_v3:armStub/hl7-org_v3:id",currentCell,nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.getAttributeNode("extension").childNodes[0].nodeValue; 
                             var currentCellEpochName=build_Instance.evaluate("hl7-org_v3:timePointEventDefinition/hl7-org_v3:componentOf1/hl7-org_v3:epochStub/hl7-org_v3:id",currentCell,nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.getAttributeNode("extension").childNodes[0].nodeValue; 
                         //   alert("SEQ number:"+ currentCellSequenceNumber + "  ARM Name :" + currentCellArmName);
                            if(currentCellSequenceNumber==sequenceNumber && currentCellArmName== armName)
                                   {
                                      matchfound=true;
                                      index=k;
                                      currentCellName=build_Instance.evaluate("hl7-org_v3:timePointEventDefinition/hl7-org_v3:id",currentCell,nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.getAttributeNode("extension").childNodes[0].nodeValue; 
                                      break;
                                   }
                              currentCell=null;
                              currentCellSequenceNumber=null;
                              currentCellArmName=null;
                              currentCellEpochName=null;
                                                       
                                   
                          }       
                          
                      if(matchfound==true)
                                   {
                                       //alert("match found at index:"+ index +" Cell name is:"+ currentCellName);
									 var elementToInsert=template_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:addSortedCell/hl7-org_v3:cell" , template_instance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.cloneNode(true);
									// alert("element to insert is:"+ elementToInsert + " Arm name is:" + armName);
									 elementToInsert.getElementsByTagName("arm")[0].childNodes[0].nodeValue=armName;
  									 elementToInsert.getElementsByTagName("epoch")[0].childNodes[0].nodeValue=epochNameArray[j];
                                       
	              								  elementToInsert.getElementsByTagName("sequence")[0].childNodes[0].nodeValue=sequenceNumber;
									  elementToInsert.getElementsByTagName("cellName")[0].childNodes[0].nodeValue=currentCellName;
                                     parentCell.appendChild(elementToInsert);
                              
                                 
                                   }               
                      else       
                            {
                                   // alert("match Not found for Sequence :" + sequenceNumber + "  Arm" + armName);
									 var elementToInsert=template_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:addSortedCell/hl7-org_v3:cell" , template_instance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.cloneNode(true);
							     //	 alert("element to insert is:"+ elementToInsert + " Arm name is:" + armName);
									 elementToInsert.getElementsByTagName("arm")[0].childNodes[0].nodeValue=armName;
  									 elementToInsert.getElementsByTagName("epoch")[0].childNodes[0].nodeValue=epochNameArray[j];
									  elementToInsert.getElementsByTagName("sequence")[0].childNodes[0].nodeValue=sequenceNumber;
									  elementToInsert.getElementsByTagName("cellName")[0].childNodes[0].nodeValue=currentCellName;
                                     parentCell.appendChild(elementToInsert);

                          
                            }                     
                     
               
             }
                    currentCellName=null;    
                    epochName=null;
                    matchfound=null;
        }



sequenceArray=null;
epochNameArray=null;
armNameArray=null;
parentCell=null;
allCells=null;
allEpochNameCells=null;
allArmNameCells=null;
cellCountinSort=null;
armCellCount=null;
epochCellCount=null;  

  
}





function checkCount()
{
alert("Value of variable to call sort is: "+ scratch_instance.getElementsByTagName("callSortFunction") [0].textContent);
}






function getSaveAsInstanceFragment(instance)
{
	 if (instance == null) {
    return null;
  }
  var mainDocument = document.implementation.createDocument("", "stylesheetdisplay", null);
 
  var documentFragment = studyDesignSaveAsProcessor.transformToFragment(instance, mainDocument);
// alert(documentFragment);
  return documentFragment;
	
}

function getInstanceFragment(instance)
{ if (instance == null) {
    return null;
  }
  
   var mainDocument = document.implementation.createDocument("", "stylesheetdisplay", null); //create document is at ------http://reference.sitepoint.com/javascript/DOMImplementation/createDocument
  var frag = studyDesignProcessor.transformToFragment(instance, mainDocument);
  //alert("html: frag="+frag);
  return frag;

  
}

function studyDesignToHTML(instance)
{
  if (instance == null) {
    return null;
  }
  var mainDocument = document.implementation.createDocument("", "stylesheetdisplay", null); //create document is at ------http://reference.sitepoint.com/javascript/DOMImplementation/createDocument
  var frag = studyDesignProcessor.transformToFragment(instance, mainDocument);
  return frag;
   
}


function updateAllCells()
{
   var index = scratch_instance.getElementsByTagName("templateCellIndex") [0].textContent-1;
 
   var allExistingTemplateCells  =   existing_template_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:component4/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1/hl7-org_v3:timePointEventDefinition/hl7-org_v3:id",existing_template_instance, nsResolver,    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
   
     var allExistingBuildCells  =   build_Instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:component4/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1/hl7-org_v3:timePointEventDefinition/hl7-org_v3:id",build_Instance, nsResolver,    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
     
     
  var elementIDToInsert = allExistingTemplateCells.snapshotItem(index);
  
  var cellname=elementIDToInsert.getAttributeNode("extension").childNodes[0].nodeValue; 
  
  var allBuildComponent1s = build_Instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:component4/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1",build_Instance,nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
  var totalBuildComponent1s = allBuildComponent1s.snapshotLength;
  
  var allComponent1 =  build_Instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:component4/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1",build_Instance, nsResolver,    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
  
  var parentElement=build_Instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:component4/hl7-org_v3:timePointEventDefinition",build_Instance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
  
   
  
  for(var i=0;i< totalBuildComponent1s; i++)
        {
            var cellNameInBuild = allExistingBuildCells.snapshotItem(i).getAttributeNode("extension").childNodes[0].nodeValue; 
            if( cellNameInBuild == cellname)  // when the match is found then delete the previous cell and replace it with the new template. Make sure to reset values of sequence number, epoch name and arm name at this point.
                 {
                       var nodeToDelete=allComponent1.snapshotItem(i);
                       var sequenceNumber=build_Instance.evaluate("hl7-org_v3:sequenceNumber",nodeToDelete,nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.getAttributeNode("value").childNodes[0].nodeValue; 
                       var epochName=build_Instance.evaluate("hl7-org_v3:timePointEventDefinition/hl7-org_v3:componentOf1/hl7-org_v3:epochStub/hl7-org_v3:id",nodeToDelete,nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.getAttributeNode("extension").childNodes[0].nodeValue; 
                       var armName=build_Instance.evaluate("hl7-org_v3:timePointEventDefinition/hl7-org_v3:componentOf2/hl7-org_v3:armStub/hl7-org_v3:id",nodeToDelete,nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.getAttributeNode("extension").childNodes[0].nodeValue; 
                  
                      var templateToInsert =  existing_template_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:component4/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1",existing_template_instance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null).snapshotItem(index); //obtain template node from the existing template instance that needs to go into the build instance.
                       
                addSubjectElementToNewNode(nodeToDelete,i,templateToInsert,armName);    //This function is called because subjects are not assigned in the 'templates' section. In this case if the node to delete had a subject assigned to it the subjuect details will be lost. Therefore it is required to save the subject details before deleting the node.      
                                             
                            nodeToDelete.parentNode.removeChild(nodeToDelete);  
                         
                
         var  templateToInsert =  existing_template_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:component4/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1",existing_template_instance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null).snapshotItem(index).cloneNode(true); //obtain final element before Inserting
         
           var sequenceNode = existing_template_instance.evaluate("hl7-org_v3:sequenceNumber",templateToInsert, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
           var epochNode =  existing_template_instance.evaluate("hl7-org_v3:timePointEventDefinition/hl7-org_v3:componentOf1/hl7-org_v3:epochStub/hl7-org_v3:id",templateToInsert, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
           var armNode =  existing_template_instance.evaluate("hl7-org_v3:timePointEventDefinition/hl7-org_v3:componentOf2/hl7-org_v3:armStub/hl7-org_v3:id",templateToInsert, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
       epochNode.setAttribute("extension",epochName);
       armNode.setAttribute("extension",armName);
       sequenceNode.setAttribute("value",sequenceNumber);
                  
                        parentElement.appendChild(templateToInsert);
                        nodeToDelete=null;
                        sequenceNumber=null;
                        epochName=null;
                        armName=null;
                        sequenceNode=null;
                        epochNode=null;
                        armNode=null;
                    
                 }
            cellNameInBuild=null;
                         
             
         }
  
 alert("All matching Cells Successfully Updated !!!");
index=null;
allExistingTemplateCells=null;
allExistingBuildCells=null;
elementIDToInsert=null;
allComponent1=null;
parentElement=null;



 
}



function addSubjectElementToNewNode(nodeToDelete, index,templateToInsert,armName)
     {
     
      // alert("Under Arm :" + armName +" index is :"+ index);
        var subjectCell=null;
        var length=0;
        try{  
             var subjectNode  =build_Instance.evaluate("hl7-org_v3:timePointEventDefinition/hl7-org_v3:subject",nodeToDelete,nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null).snapshotItem(0).cloneNode(true);
             var length=subjectNode.snapshotLength; 
            }catch(err)
                 {
                //  alert("Do nothing:");
                  length=0;
                 }
        
     
         
        if(length==0) //The build cell which is being deleted did not have any subjects assigned to it.
           {
           //alert("Subject not assigned under :"+ armName +" Therefore need to delete subject from Template:" ); // In this case you need to delete any 'subject' nodes in the template to Insert node.
						  var subjectNodeToDelete = existing_template_instance.evaluate("hl7-org_v3:timePointEventDefinition/hl7-org_v3:subject",templateToInsert, nsResolver,XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
						var subjectCountInTemplateNode = subjectNodeToDelete.snapshotLength;
						if( subjectCountInTemplateNode >0)  //delete subject node from template node because the node in the build did not have any subjects
						   {             
											 var nodeToDelete=subjectNodeToDelete.snapshotItem(0);  
										//	 alert("Deleting subject node since build did not have a subject node");
														  nodeToDelete.parentNode.removeChild(nodeToDelete);    
						   }                   
                           return;    //return if build cell did not have subjects
           }   
         else  //node which is being deleted HAD subjects. Therefore node which is being added must also include the already existing subject.
         {
        //   alert("node which is being deleted HAD subjects. Therefore node which is being added must also include the already existing subject.");
            var subjectNodeToDelete = existing_template_instance.evaluate("hl7-org_v3:timePointEventDefinition/hl7-org_v3:subject",templateToInsert, nsResolver,XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
            var subjectCountInTemplateNode = subjectNodeToDelete.snapshotLength;
            if( subjectCountInTemplateNode >0)  //delete OLDER subject node from template node
               {
              //       alert("Removing older node from the template to insert:");
                 			   	 var nodeToDelete1=subjectNodeToDelete.snapshotItem(0);  
								  nodeToDelete1.parentNode.removeChild(nodeToDelete1);    
               }                   
            
             
      
			            
			            // var subjectCell= subject_instance.evaluate("hl7-org_v3:subject",armAndSubjectCell, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null).snapshotItem(0);
			             var allComponent1Elements = existing_template_instance.evaluate("hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1",templateToInsert, nsResolver,    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
                         var componentOfElements = existing_template_instance.evaluate("hl7-org_v3:timePointEventDefinition/hl7-org_v3:timePointEventDefinition/hl7-org_v3:componentOf1", templateToInsert, nsResolver,    XPathResult.FIRST_ORDERED_NODE_TYPE, null);
                         var subjectOfElements = existing_template_instance.evaluate("hl7-org_v3:timePointEventDefinition/hl7-org_v3:subjectOf", templateToInsert, nsResolver,    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
                         var allPreConditionElements=existing_template_instance.evaluate("hl7-org_v3:timePointEventDefinition/hl7-org_v3:precondition", templateToInsert, nsResolver,    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
                         var allLocationElements = existing_template_instance.evaluate("hl7-org_v3:timePointEventDefinition/hl7-org_v3:location",templateToInsert, nsResolver,    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
                        var locationCount=allLocationElements.snapshotLength;
	                     var totalcomponent1 = allComponent1Elements.snapshotLength;
		                 var totalPreConditions=allPreConditionElements.snapshotLength;
		                 var totalSubjectOf = subjectOfElements.snapshotLength;		
		               
                         
		                   
		                 //alert("Under the template to Insert new - Total locations:"+ locationCount +" Total Component1:" + totalcomponent1+" Total Preconditions:" + totalPreConditions + " Total subject of:"+ totalSubjectOf ); 
		                                                 if(totalcomponent1==0 && totalSubjectOf==0 && totalPreConditions==0 && locationCount==0)  //condition to insert before componentOf section.
																			{
													       //    alert(" Inserting before componentOf1");
																			   var referenceElement=componentOfElements.singleNodeValue;
																			         var parentElement= existing_template_instance.evaluate("hl7-org_v3:timePointEventDefinition",templateToInsert, nsResolver,    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null).snapshotItem(0);	
                                                                      //  alert(" Parent element is :" + parentElement + " reference element obtained: "+ referenceElement);

																			   
																			 //  alert("reference element obtained: "+ referenceElement);
																			  parentElement.insertBefore(subjectNode,referenceElement);
																			}	
											 			else if(locationCount > 0)  //condition to insert before Locations
																			{
						                                             //      alert("Locations Exist Inserting before Locations");
						     
																			   var locationReferenceNode = allLocationElements.snapshotItem(0);
																			           var parentElement= existing_template_instance.evaluate("hl7-org_v3:timePointEventDefinition",templateToInsert, nsResolver,    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null).snapshotItem(0);	
                                                                                                                                                          																              //alert(" Parent element is :" + parentElement + " reference element obtained: "+ locationReferenceNode);

																		   parentElement.insertBefore(subjectNode,locationReferenceNode);
																			}		
													 else if(totalPreConditions>0)  //condition to insert before Preconditions
																			{
														                 //  alert("Preconditions Exist Inserting before PReconditions");
																		            var parentElement= existing_template_instance.evaluate("hl7-org_v3:timePointEventDefinition",templateToInsert, nsResolver,    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null).snapshotItem(0);	

																			   var preConditionReferenceNode = allPreConditionElements.snapshotItem(0);
											   				           //   alert(" Parent element is :" + parentElement + " reference element obtained: "+ preConditionReferenceNode);
				 
																			   //alert("Pre condition reference :"+ preConditionReferenceNode);
																				parentElement.insertBefore(subjectNode,preConditionReferenceNode);
																			}		
														else if(totalcomponent1>0)  //condition to insert before component1 
																			{
																		   // alert("Time Points exist Inserting before TimePoints");
																			     var component1referenceNode = allComponent1Elements.snapshotItem(0);
																			          var parentElement= existing_template_instance.evaluate("hl7-org_v3:timePointEventDefinition",templateToInsert, nsResolver,    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null).snapshotItem(0);	

																            //  alert(" Parent element is :" + parentElement + " reference element obtained: "+ component1referenceNode);
																	    		parentElement.insertBefore(subjectNode,component1referenceNode);
																			}		
													   else if(totalSubjectOf >0) //condition to Insert before subject Of
																			{
					                                                  //    alert("Subject of exist but no time points exist");
					                                                   	         var parentElement= existing_template_instance.evaluate("hl7-org_v3:timePointEventDefinition",templateToInsert, nsResolver,    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null).snapshotItem(0);	

				                                                            var subjectOfReferenceNode =  subjectOfElements.snapshotItem(0);
							                                                 parentElement.insertBefore(subjectNode,subjectOfReferenceNode);
						
																			} 		                 
						
                        
			     
                     			      
			      
			      
			 
            
         }        
         
     }







function deleteSubjectFromArm()
{
   var index = scratch_instance.getElementsByTagName("armForSubjectInsert") [0].textContent-1;
   var subjectInstanceCells=  subject_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:arm",subject_instance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
   var armname = subjectInstanceCells.snapshotItem(index).getElementsByTagName("armname")[0].childNodes[0].nodeValue;
//   alert("Arm name impacted is:"+ armname);
   var allCellElements=build_Instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:component4/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1/hl7-org_v3:timePointEventDefinition",build_Instance, nsResolver,    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
var totalCells=allCellElements.snapshotLength;

//alert("Arm to modify is :"+ templateCellArmName);

  for(var i=0;i<totalCells;i++)
        {
         // alert("In major loop for cell number:"+i);
          var parentElement=build_Instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:component4/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1/hl7-org_v3:timePointEventDefinition",build_Instance, nsResolver,    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null).snapshotItem(i);
         //  alert("Parent element obtained");
           var buildCellArmName=parentElement.getElementsByTagName("componentOf2")[0].getElementsByTagName("armStub")[0].getElementsByTagName("id")[0].getAttributeNode("extension").nodeValue;
          // alert("Build cell armname:"+ buildCellArmName);
           if(armname==buildCellArmName)
              {
               var nodeToDelete= build_Instance.evaluate("hl7-org_v3:subject",parentElement, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;      
            //   alert("Node to delete is :"+ nodeToDelete);        
                if(nodeToDelete!=null)
                                nodeToDelete.parentNode.removeChild(nodeToDelete);    

               }
               
         }      
    
   alert("All subjects removed from Arm :" + armname);

}

function doesStudyTypeExist()

{
 var allSubjects=  build_Instance.evaluate("//hl7-org_v3:component1/hl7-org_v3:timePointEventDefinition/hl7-org_v3:subject",build_Instance,nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
 var subjectCount=allSubjects.snapshotLength;
  
 

 var SubjectExists =scratch_instance.getElementsByTagName("SubjectExist")[0].childNodes[0].nodeValue;
   
  var count=countChildElements("subjectOf");
  var charkind = scratch_instance.getElementsByTagName("kindOfCharacteristic")[0].childNodes[0].nodeValue;
  var studykind = scratch_instance.getElementsByTagName("kindOfStudy")[0].childNodes[0].nodeValue;
   //alert ("   Study kind is :" + studykind);

     if(charkind!="TYPEOFSTUDY")
      {
         if (count==0)
               appendStudyType();
         else      
               insertFirstPositionStudyType();
      }
        
  scratch_instance.getElementsByTagName("kindOfStudy")[0].childNodes[0].nodeValue = typeofstudy_instance.getElementsByTagName("value")[0].childNodes[0].nodeValue;
  typeofstudy_instance.getElementsByTagName("value")[0].childNodes[0].nodeValue=scratch_instance.getElementsByTagName("kindOfStudy")[0].childNodes[0].nodeValue;
   
    if(subjectCount>0)  //This section does not allow change if subjects already exist in the study
         {  
              if( scratch_instance.getElementsByTagName("showAlert")[0].childNodes[0].nodeValue =="Yes")
                     {  
                      alert("You are not allowed to change the study characteristic because subjects already exist in the study. You will need to delete all subjects in order to change study type characteristic");
                     }
              scratch_instance.getElementsByTagName("showAlert")[0].childNodes[0].nodeValue ="Yes"
              scratch_instance.getElementsByTagName("kindOfStudy")[0].childNodes[0].nodeValue= studykind;

               //alert("Char kind:"+ charkind +  "   studykind is :"+ studykind);
                
         }    
	else
	{

		}
}


function checkTheGLP()
{

	 var allCodes=  build_Instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:subjectOf/hl7-org_v3:studyCharacteristic/hl7-org_v3:code",build_Instance,nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
	   
	   			for(var i=0;i< allCodes.snapshotLength;i++)
			{         
			         var thisCode = allCodes.snapshotItem(i);
			         
					if(thisCode.getAttributeNode("code").nodeValue == 'TYPEOFSTUDY')
					{
						 var thisStudyType=  build_Instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:subjectOf/hl7-org_v3:studyCharacteristic/hl7-org_v3:value",build_Instance,nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null).snapshotItem(i).textContent;
					if(thisStudyType =='Human Study')
					{
					for(var x=0;x< allCodes.snapshotLength;x++)
							{         
							if(allCodes.snapshotItem(x).getAttributeNode("code").nodeValue == 'GLP')
							{
					 var removeGLP =  build_Instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:subjectOf",build_Instance,nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null).snapshotItem(x);
					removeGLP.parentNode.removeChild(removeGLP); 
					 scratch_instance.getElementsByTagName("GLPValue")[0].childNodes[0].nodeValue='';
					 break;
					 }
					 
					 }
					 }
					}
			 }
	}




function setGLPonOpen()
{
	 var allCodes=  build_Instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:subjectOf/hl7-org_v3:studyCharacteristic/hl7-org_v3:code",build_Instance,nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
	   
	   			for(var i=0;i< allCodes.snapshotLength;i++)
			{         
			         var thisCode = allCodes.snapshotItem(i);
			         
					if(thisCode.getAttributeNode("code").nodeValue == 'GLP')
					{
					 var setGLP =  build_Instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:subjectOf/hl7-org_v3:studyCharacteristic/hl7-org_v3:value",build_Instance,nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null).snapshotItem(i).textContent;

					 scratch_instance.getElementsByTagName("GLPValue")  [0].childNodes[0].nodeValue = setGLP;
					}
}
}



function characteristicDelete()
{
 var allSubjects=  build_Instance.evaluate("//hl7-org_v3:component1/hl7-org_v3:timePointEventDefinition/hl7-org_v3:subject",build_Instance,nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
 var subjectCount=allSubjects.snapshotLength;
 var index =scratch_instance.getElementsByTagName("subjectIndex")[0].childNodes[0].nodeValue-1;
 //alert("Index:"+ index + "  Subject Count:" + subjectCount);
      
var elementToDelete= build_Instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:subjectOf",build_Instance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null).snapshotItem(index); 
var characteristicCode = elementToDelete.getElementsByTagName("studyCharacteristic")[0].getElementsByTagName("code")[0].getAttributeNode("code").nodeValue;
//alert("char code:"+ characteristicCode);
if(characteristicCode=="TYPEOFSTUDY" && subjectCount>0 && index==0) 
     {
            alert("You cannot delete this characteristic if subjects exist in the Study");
            return;
        }
        
  else
  {
               	 //  clearMemory(elementToDelete);
 
                  elementToDelete.parentNode.removeChild(elementToDelete);    

  }      
 
}

function generateSubjectTemplates()
{ 
//alert("inside subject template");
var allCells = build_Instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:component4/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1/hl7-org_v3:timePointEventDefinition",build_Instance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
var numberOfCells=allCells.snapshotLength;
var typeofStudy = setStudyType(); 		
if(typeofStudy=='' || numberOfCells==0)
       {
         if(scratch_instance.getElementsByTagName("SubjectExist")[0].childNodes[0].nodeValue!=0)
            alert("You have either not defined a Study Characteristic for 'type of study' or you have not created study cells. Please go back to the Study Characteristics tab and choose the 'type of study' or use the Cell Templates tab to assign cells to a Study. ");
          
         scratch_instance.getElementsByTagName("SubjectExist")[0].childNodes[0].nodeValue=1;   
            
          return;
       }
	
	 scratch_instance.getElementsByTagName("typeOfStudyRelevance") [0].childNodes[0].nodeValue  =typeofStudy;
 subjectInstanceCleanup(); 									   
//subjectInstanceCleanup(typeofStudy);     
var templateElementToInsert=null;
var actualElementToInsert=null;

 var parentElement=subject_instance.evaluate("/hl7-org_v3:plannedStudy",subject_instance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;




			for(var i=0;i<numberOfCells;i++)
			{         
			         var buildCell=allCells.snapshotItem(i);
                      var buildCellArmName=buildCell.getElementsByTagName("componentOf2")[0].getElementsByTagName("armStub")[0].getElementsByTagName("id")[0].getAttributeNode("extension").nodeValue;
                    // alert("Build cell name is :"+ buildCellArmName);
                     var subjectInstanceCells=  subject_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:arm",subject_instance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);

                      var subjectCount=subjectInstanceCells.snapshotLength;            
                   //   alert("total arms in template for subjects "+ subjectCount);
                      var found=false;   
                      var indexfound=0;
                     
                        for(var j=0;j<subjectCount;j++)
                         {
                            var subjectTemplate=subjectInstanceCells.snapshotItem(j);
                            try{
                                var subjectTemplateArmName = subjectTemplate.getElementsByTagName("armname")[0].childNodes[0].nodeValue;
                                }catch(err)
                                {
                                }
                          //  alert("subject template arm name " +  subjectTemplateArmName);
                            if (buildCellArmName==subjectTemplateArmName)
                                 { 
									  found=true;
									  
								//	  alert("Match Found");
                                  }
                         }
                         
					 if(found==false)
						{
					   //  alert("Match not found for "+ buildId  + " Updating template instance");
						 //alert("element to Insert obtained "+elementToInsert);
						 	 var elementToInsert=template_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:addSubjectToTemplate/hl7-org_v3:arm" , template_instance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.cloneNode(true);
						   elementToInsert.getElementsByTagName("armname")[0].childNodes[0].nodeValue=buildCellArmName;

				        var parentElement=subject_instance.evaluate("/hl7-org_v3:plannedStudy",subject_instance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
						 parentElement.appendChild(elementToInsert);
						}        
			 
			}
								   

addCorrectSubjectNodes(typeofStudy);

 
}

function addCorrectSubjectNodes(typeofStudy)
{
  //alert("Coming into add correct subjects function ");
   
		var allSubjectTemplateCells = subject_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:arm",subject_instance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
		var numberOfArmCells=allSubjectTemplateCells.snapshotLength;
		//alert("Total number of template cells =" + numberOfArmCells);
		var templateElementToInsert=null;
		for(var i=0;i<numberOfArmCells;i++)
			{         
			         var armCell=allSubjectTemplateCells.snapshotItem(i);
                      var templateCellArmName=armCell.getElementsByTagName("armname")[0].childNodes[0].nodeValue;
                    // alert("Template cell name is :"+ templateCellArmName);
                     var buildCells=   build_Instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:component4/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1/hl7-org_v3:timePointEventDefinition",build_Instance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
                     var numberOfCells=buildCells.snapshotLength;
                     var indexfound=0;
                     for(var j=0;j<numberOfCells;j++) //for loop to find out last occurance of the arm name in the actual study. The last occurence will then be used to see if a subject exists or not.
                          {
                            var currentBuildCell=buildCells.snapshotItem(j);
                             var buildCellArmName=currentBuildCell.getElementsByTagName("componentOf2")[0].getElementsByTagName("armStub")[0].getElementsByTagName("id")[0].getAttributeNode("extension").nodeValue;
                             if(buildCellArmName==templateCellArmName)
                                {
                                  
                                  indexfound=j;
                                }

                          }
                      //the below part finds out if a subject exists. If the subject count is 0 then the template needs to be added to the template_subject, otherwise the actual subject node is added.    
                       var buildCellToCheck= buildCells.snapshotItem(indexfound).cloneNode(true);
                       var subjectCell = build_Instance.evaluate("hl7-org_v3:subject",buildCellToCheck, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
                       var subjectCount=subjectCell.snapshotLength;
                    //   alert("Total subjects :"+ subjectCount);
                       if(subjectCount==0)
                                  {
                                     if (typeofStudy=="Animal Study")
												  {
												   					//    alert("Obtaining blank Template - Animal ");

												   templateElementToInsert=template_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:animalSubject/hl7-org_v3:subject" , template_instance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.cloneNode(true);
										

												  } 
																		  
											  else if (typeofStudy=="Human Study")
												  {
												            //      alert("Obtaining blank Template - Human ");

												   templateElementToInsert=template_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:humanSubject/hl7-org_v3:subject" , template_instance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.cloneNode(true);
										
       											  } 
											  else if (typeofStudy=="Product Study")
												  {
												   		//		alert("Obtaining blank Template - Product ");

												   templateElementToInsert=template_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:productSubject/hl7-org_v3:subject" , template_instance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.cloneNode(true);
												   
					              	              } 
					              	 }             
					              	  
                          else 
                                  {
                                  //  alert("Obtaining actual Template from build ");
                                     templateElementToInsert =build_Instance.evaluate("hl7-org_v3:subject",buildCellToCheck, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
                                  }
                                          
                           
                    //   alert("Template obtained "+ templateElementToInsert);
                        armCell.appendChild(templateElementToInsert);
                     
                     
            }

//alert("Type of study is set to :"+ scratch_instance.getElementsByTagName("typeOfStudyRelevance") [0].childNodes[0].nodeValue);

   
}



function subjectInstanceCleanup(typeofstudy)
{
     //  alert("Coming into cell cleanup function");
  		var allSubjectTemplateCells = subject_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:arm",subject_instance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
		var numberOfArmCells=allSubjectTemplateCells.snapshotLength;
		for (var i=0;i<numberOfArmCells;i++)
		{
		  var elementToRemove = allSubjectTemplateCells.snapshotItem(i);
		  elementToRemove.parentNode.removeChild(elementToRemove);    

		}
						  
}






function addTemplateSubjectToExistingTemplates()
{
 var index = scratch_instance.getElementsByTagName("templateSubjectIndex") [0].textContent-1;
//alert("Index of the position is :"+ index);


     
   var parentElement = existing_template_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:component4/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1/hl7-org_v3:timePointEventDefinition", existing_template_instance, nsResolver,    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null).snapshotItem(index);
   
// alert("PArent element is :"+ parentElement); 
 
 
  var allSubjectElements =existing_template_instance.evaluate("hl7-org_v3:subject",parentElement, nsResolver,    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
     var subjectCount=allSubjectElements.snapshotLength;

          if (subjectCount >0)
            {
               alert("You can only define one Experimental Unit for every cell.");
               return;
            }

   
  // var codeElements = existing_template_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:component4/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1/hl7-org_v3:timePointEventDefinition/hl7-org_v3:code", existing_template_instance, nsResolver,    XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;

 //alert("Code element is :"+ codeElements);
   
      var allComponent1Elements = existing_template_instance.evaluate("hl7-org_v3:component1",parentElement, nsResolver,    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);

      
    var componentOfElements = existing_template_instance.evaluate("hl7-org_v3:componentOf1", parentElement, nsResolver,    XPathResult.FIRST_ORDERED_NODE_TYPE, null);
    
    var subjectOfElements = existing_template_instance.evaluate("hl7-org_v3:subjectOf", parentElement, nsResolver,    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
    
  var allPreConditionElements=existing_template_instance.evaluate("hl7-org_v3:precondition", parentElement, nsResolver,    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
          var totalPreConditions=allPreConditionElements.snapshotLength;
          
    var allLocationElements = existing_template_instance.evaluate("hl7-org_v3:location",parentElement, nsResolver,    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
     var locationCount=allLocationElements.snapshotLength;
	
				             
				                     var totalcomponent1 = allComponent1Elements.snapshotLength;
				                     var totalSubjectOf = subjectOfElements.snapshotLength;
				                     var elementToInsert=null;
				                     
  var typeofStudy = getStudyType(); 		
 // alert ("Tyhpe of study is " + typeofStudy);		         
              
	
  if(typeofStudy=='')
       {   return;		}
  else if (typeofStudy=="Animal Study")
      {
       elementToInsert=template_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:animalSubject/hl7-org_v3:subject" , template_instance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.cloneNode(true);
      } 
          
  else if (typeofStudy=="Human Study")
      {
       elementToInsert=template_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:humanSubject/hl7-org_v3:subject" , template_instance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.cloneNode(true);
      } 
  else if (typeofStudy=="Product Study")
      {
       elementToInsert=template_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:productSubject/hl7-org_v3:subject" , template_instance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.cloneNode(true);
      } 
      
      
   scratch_instance.getElementsByTagName("typeOfStudyRelevance") [0].childNodes[0].nodeValue  =typeofStudy;
   // scratch_instance.getElementsByTagName("epochjavascript") [0].childNodes[0].nodeValue 
   		                     
	//	alert ("flag set to:"+  scratch_instance.getElementsByTagName("typeOfStudyRelevance") [0].childNodes[0].nodeValue);		               
				                     				                     
        //  alert("totalComponent 1 under the segment are : " + totalcomponent1 + " And total characteristics are: "+totalSubjectOf + " Total Preconditions "+ totalPreConditions );
                     if(totalcomponent1==0 && totalSubjectOf==0 && totalPreConditions==0 && locationCount==0)  //condition to insert before componentOf section.
                                                    {
                             //           alert(" Inserting before componentOf1");
                                                       var referenceElement=componentOfElements.singleNodeValue;
                                                     //  alert("reference element obtained: "+ referenceElement);
                                                      parentElement.insertBefore(elementToInsert,referenceElement);
                                                    }	
                                            else if(locationCount > 0)  //condition to insert before Locations
                                                    {
   //  alert("Locations Exist Inserting before Locations");
                                                       var locationReferenceNode = allLocationElements.snapshotItem(0);
                                                  //  alert("reference element obtained: "+ preConditionReferenceNode);
                                                   parentElement.insertBefore(elementToInsert,preConditionReferenceNode);
                                                    }		
                                     else if(totalPreConditions>0)  //condition to insert before Preconditions
                                                    {
                                   //    alert("Preconditions Exist Inserting before PReconditions");
                                                   
                                                       var preConditionReferenceNode = allPreConditionElements.snapshotItem(0);
                                                        parentElement.insertBefore(elementToInsert,preConditionReferenceNode);
                                                    }		
                                                else if(totalcomponent1>0)  //condition to insert before component1 
                                                    {
                                                // alert("Time Points exist Inserting before TimePoints");
                                                      var component1referenceNode = allComponent1Elements.snapshotItem(0);
                                           //  alert("reference element obtained: "+ component1referenceNode);
                                                    parentElement.insertBefore(elementToInsert,component1referenceNode);
                                                    }		
                                                   else if(totalSubjectOf >0) //condition to Insert before subject Of
                                                    {
  //  alert("Subject of exist but no time poitns exist");
                                                                                 
                                                       var subjectOfReferenceNode =  subjectOfElements.snapshotItem(0);
                                            
                                                  parentElement.insertBefore(elementToInsert,subjectOfReferenceNode);

                                                    } 		                     				                     

}






                       

				                     
  

function deleteSubjectCondition()
{
   var index= scratch_instance.getElementsByTagName("subjectConditionIndex") [0].childNodes[0].nodeValue-1;
   var subindex= scratch_instance.getElementsByTagName("subjectConditionToDelete") [0].childNodes[0].nodeValue-1;

   //alert("index to delete from" +index + "  sub index to delete:" + subindex);
            var allExperimentalUnitCells = subject_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:arm/hl7-org_v3:subject/hl7-org_v3:experimentalUnit",subject_instance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);

    var parentCell=allExperimentalUnitCells.snapshotItem(index);
    allSubjectConditionCells=subject_instance.evaluate("hl7-org_v3:subjectOf",parentCell, nsResolver,    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
   //     alert("Total deleteable cells are:"+ allComponent1SubElements.snapshotLength);
  var nodeToDelete=allSubjectConditionCells.snapshotItem(subindex);
//  alert("node to delete" + nodeToDelete);
  if(nodeToDelete==null)
  {
    alert("Nothing to delete");
    return;
  }
  
   nodeToDelete.parentNode.removeChild(nodeToDelete);
   
}


function addSubjectCondition()
{
    var index = scratch_instance.getElementsByTagName("subjectConditionIndex") [0].textContent-1;
    
    var elementToInsert = template_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:addSubjectOfToExperimentalUnit/hl7-org_v3:subjectOf" , template_instance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.cloneNode(true);
  //  alert("Index is :"+ index +" And the element to insert is :"+ elementToInsert);
    
          var allSubjectTemplateCells = subject_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:arm/hl7-org_v3:subject/hl7-org_v3:experimentalUnit",subject_instance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
          var parentCell=allSubjectTemplateCells.snapshotItem(index);
          parentCell.appendChild(elementToInsert);


}



function generateTemplates()
{ 

//alert("Inside Generate Templates: for study cells");
removeExtraNodes();

 var existingComponent1ID = build_Instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:component4/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1/hl7-org_v3:timePointEventDefinition/hl7-org_v3:id", build_Instance, nsResolver,    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);


 
//alert("total Build ids are:"+ existingComponent1ID.snapshotLength );
buildElementCount=existingComponent1ID.snapshotLength;


 var existingComponent1 = build_Instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:component4/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1", build_Instance, nsResolver,    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);



for (var i=0;i<buildElementCount;i++)
           {
               var buildId=existingComponent1ID.snapshotItem(i).getAttributeNode("extension").childNodes[0].nodeValue; 
         //      alert("Cell id in build "+ buildId);
               var found=false;
               var existingTemplateComponent1ID =existing_template_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:component4/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1/hl7-org_v3:timePointEventDefinition/hl7-org_v3:id", existing_template_instance, nsResolver,    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
             templateElementCount=existingTemplateComponent1ID.snapshotLength;
       //  alert( " total Template ids are:"+ existingTemplateComponent1ID.snapshotLength);

             
               for(var j=0;j<templateElementCount;j++)
                         {
                         
                         
                            var templateId=existingTemplateComponent1ID.snapshotItem(j).getAttributeNode("extension").childNodes[0].nodeValue; 
                            
                           // alert("i = " + i+ " Actual ID:" + buildId + "j=" + j+ " Template ID:"+ templateId);
                            if (buildId==templateId)
                                 { 
									  found=true;
								    // alert("Match Found");
								     break;
                                  }
                         }
                         
                 if(found==false)
                    {
                   //alert("Match not found for "+ buildId  + " Updating template instance");
                     var parentElement=existing_template_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:component4/hl7-org_v3:timePointEventDefinition",existing_template_instance, nsResolver,    XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
                     var elementToInsert=existingComponent1.snapshotItem(i).cloneNode(true);
                     parentElement.appendChild(elementToInsert);
                     parentElement=null;
                     elementToInsert=null;
                    }        
               
           }

existingComponent1ID=null;
 buildElementCount=null;
 existingComponent1=null;
}







function removeExtraNodes() 
{

// alert("inside remove extra nodes function:");
 var allExistingTemplates= existing_template_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:component4/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1", existing_template_instance, nsResolver,    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
 
  var totalTemplateElements= allExistingTemplates.snapshotLength;

   //alert("Total elements are:"+ totalTemplateElements);

   var existingBuildIds    =build_Instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:component4/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1/hl7-org_v3:timePointEventDefinition/hl7-org_v3:id", build_Instance, nsResolver,    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
   
             var totalBuildElements=existingBuildIds.snapshotLength;


 var indexfound=0;
 
 
 
 for( i=0;i<totalTemplateElements;i++)
        {
          var currentTemplate = allExistingTemplates.snapshotItem(i);
           currentTemplate.parentNode.removeChild(currentTemplate);   
           currentTemplate=null;
           
          /*  //I commented this line after noticing issues with only single cell updates replacing the older cell in the existing templates on July 13th. the line above should be deleted and the comments removed to revert back to the older state.
          var templateName=currentTemplate.getElementsByTagName("timePointEventDefinition") [0].getElementsByTagName("id") [0].getAttributeNode("extension").childNodes[0].nodeValue;
      //    alert("Checking if this node exists in the study:" + templateName);
          
            var found=false;
            //alert("checking for template:"+ templateName);
               for ( j=0;j<totalBuildElements;j++)
                    {
                        var buildName=existingBuildIds.snapshotItem(i).getAttributeNode("extension").childNodes[0].nodeValue;
                        if(templateName==buildName)
                        {
                          found=true;
                          break;                          
                        }
                    }
                    
              if(found==false)
               {
             //    alert("Match not found for template number:" + i + " Element not found is:"+ templateName);
 
            //      alert("elementToDelete is :" + currentTemplate);
                  currentTemplate.parentNode.removeChild(currentTemplate);   

               }                    
                    
                  */ 
        }
        
  
  
   
}



function updateLibrary()
{
    var chosenCellName = scratch_instance.getElementsByTagName("addedCellName") [0].childNodes[0].nodeValue;
    var updatedFrom = scratch_instance.getElementsByTagName("libraryUpdateFrom") [0].childNodes[0].nodeValue; 
    //alert("Chosen cell is :"+ chosenCellName + " Called from :"+ updatedFrom);
  
    var allLibraryComponents = library_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:component4/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1/hl7-org_v3:timePointEventDefinition", library_instance, nsResolver,                         XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
  var countLibrary= allLibraryComponents.snapshotLength;
    var matchfound=false;
  var indexfound = 0;
  
      for(var i=0;i<countLibrary;i++)
      {
         var  currentCellExtension = allLibraryComponents.snapshotItem(i).getElementsByTagName("id") [0].getAttributeNode("extension").childNodes[0].nodeValue;
           if(currentCellExtension == chosenCellName)
               {
                  matchfound=true;
                  indexfound=i;
                  break;
               }
      }
  
   // alert(" found  :"+ matchfound + " index :"+ indexfound);
    
   if(matchfound==false)
        {
        //   alert("need to add to library");
           var elementToInsert=celltemplate_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:component4/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1",celltemplate_instance, nsResolver,XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, 
                      null).snapshotItem(0).cloneNode(true);
                      
            var parentElement=library_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:component4/hl7-org_v3:timePointEventDefinition", library_instance, nsResolver,    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null).snapshotItem(0);          
            parentElement.appendChild(elementToInsert);
                      scratch_instance.getElementsByTagName("saveTemplateFile") [0].textContent="Yes";
           
           
        }    
    else
      {
           var  choice = confirm(" Would you like to update the template with your changes in the library? ");
           if (choice==true)
                  {
                  scratch_instance.getElementsByTagName("saveTemplateFile") [0].textContent="Yes";
                   var parentElement=library_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:component4/hl7-org_v3:timePointEventDefinition", library_instance, nsResolver,    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null).snapshotItem(0);  
                   var elementToInsert=celltemplate_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:component4/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1",celltemplate_instance, nsResolver,XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, 
                      null).snapshotItem(0).cloneNode(true);
                   var componentToDeleteInLibrary = library_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:component4/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1", library_instance, nsResolver,                         XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null).snapshotItem(indexfound);
                  componentToDeleteInLibrary.parentNode.removeChild(componentToDeleteInLibrary);   
                  parentElement.appendChild(elementToInsert);

                  }
                  
            else
            {
                              scratch_instance.getElementsByTagName("saveTemplateFile") [0].textContent="No";

            }      
      }
    

}



function refreshCellTemplate()   //function to maintain the library of nodes that have been pre-defined by the user
{
  var chosenCellName = scratch_instance.getElementsByTagName("cellTemplateId") [0].childNodes[0].nodeValue;
   var allLibraryComponents = library_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:component4/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1/hl7-org_v3:timePointEventDefinition", library_instance, nsResolver,    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
  var countLibrary= allLibraryComponents.snapshotLength;
   //alert("cell name is :"+ chosenCellName + " and number of elements in library :"+ countLibrary);
  var matchfound=false;
  var indexfound = 0;
  

  for(var i=0;i<countLibrary;i++)
      {
         var  currentCellExtension = allLibraryComponents.snapshotItem(i).getElementsByTagName("id") [0].getAttributeNode("extension").childNodes[0].nodeValue;
           if(currentCellExtension == chosenCellName)
               {
                  matchfound=true;
                  indexfound=i;
                  break;
               }
      }
  

   //  alert(" found  :"+ matchfound + " index :"+ indexfound);
     
     if(matchfound==true)
           {
               var elementToInsert = library_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:component4/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1", library_instance, nsResolver,XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null).snapshotItem(indexfound).cloneNode(true);
         //      alert("element to insert") 
               var parentElement=celltemplate_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:component4/hl7-org_v3:timePointEventDefinition",celltemplate_instance, nsResolver,XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null).snapshotItem(0);
             var elementToReplace= celltemplate_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:component4/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1",celltemplate_instance, nsResolver,XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null).snapshotItem(0);
                elementToReplace.parentNode.removeChild(elementToReplace);   
                elementToInsert.getElementsByTagName("timePointEventDefinition")[0].getElementsByTagName("componentOf1")[0].getElementsByTagName("epochStub")[0].getElementsByTagName("id")[0].getAttributeNode("extension").nodeValue='';
                elementToInsert.getElementsByTagName("timePointEventDefinition")[0].getElementsByTagName("componentOf2")[0].getElementsByTagName("armStub")[0].getElementsByTagName("id")[0].getAttributeNode("extension").nodeValue=''
                parentElement.appendChild(elementToInsert);
               return;
           }
    else
      { 
       
                       var templateToInsert =  template_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:component4/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1",template_instance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null).snapshotItem(0); //obtain template node to change values before actually inserting
                  //     alert("Template to insert is:"+ templateToInsert);
                            var parentElement=celltemplate_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:component4/hl7-org_v3:timePointEventDefinition",celltemplate_instance, nsResolver,XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null).snapshotItem(0);
                            
                      //    alert("parent element is :" +parentElement);
                          
                      var elementToReplace= celltemplate_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:component4/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1",celltemplate_instance, nsResolver,XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, 
                      null).snapshotItem(0);
                      
                  //      alert("Element to Replace"+ elementToReplace);
                                      elementToReplace.parentNode.removeChild(elementToReplace);   

                          
                           templateToInsert.getElementsByTagName("timePointEventDefinition")[0].getElementsByTagName("id")[0].getAttributeNode("extension").nodeValue=chosenCellName;//setting value of extension
  
               
               //  alert("Value set to :"+    templateToInsert.getElementsByTagName("timePointEventDefinition")[0].getElementsByTagName("id")[0].getAttributeNode("extension").nodeValue);
  
           templateToInsert =  template_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:component4/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1",template_instance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null).snapshotItem(0).cloneNode(true); 
           
        //   alert("Template to Insert :"+ templateToInsert);
           
             parentElement.appendChild(templateToInsert);
                       
       }
          

}










function deleteExistingSubElementCharacteristic()
{
      var CellIndex = scratch_instance.getElementsByTagName("templateCellIndex") [0].textContent-1;
    var ElementIndex=scratch_instance.getElementsByTagName("templateElementIndex") [0].textContent-1;
    var SubElementIndex=scratch_instance.getElementsByTagName("characteristicInExistingSubElement") [0].textContent-1;
  
   //alert("Cell index is :"+ CellIndex +" Element Index is :"+ElementIndex + " Sub element Index is:" + SubElementIndex);
    
     var allExistingCells  =  existing_template_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:component4/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1/hl7-org_v3:timePointEventDefinition",existing_template_instance, nsResolver,    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
    
    
    
  var parentComponent1Cell = allExistingCells.snapshotItem(CellIndex);  
 //alert("Parent Component1 Cell is :"+ parentComponent1Cell);
 
// alert("Parent Component1 Cell is :"+ parentComponent1Cell);
   
   var allSubElementCells= existing_template_instance.evaluate("hl7-org_v3:component1/hl7-org_v3:timePointEventDefinition",parentComponent1Cell, nsResolver,    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
   
  // alert("Total sub element cells:"+ allSubElementCells.snapshotLength);
    
   var parentElement=allSubElementCells.snapshotItem(ElementIndex);
   
   ///****************************************************************
   
var allCharacteristicCells=celltemplate_instance.evaluate("hl7-org_v3:subjectOf",parentElement, nsResolver,    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
  // alert("Total deleteable cells are:"+ allCharacteristicCells.snapshotLength);
  var nodeToDelete=allCharacteristicCells.snapshotItem(SubElementIndex);
//  alert("node to delete" + nodeToDelete);
  if(nodeToDelete==null)
  {
    alert("Nothing to delete");
    return;
  }
  
   nodeToDelete.parentNode.removeChild(nodeToDelete);   
   
}

function addExistingSubElementCharacteristic()
{
  var CellIndex = scratch_instance.getElementsByTagName("templateCellIndex") [0].textContent-1;
    var ElementIndex=scratch_instance.getElementsByTagName("templateElementIndex") [0].textContent-1;
    var SubElementIndex=scratch_instance.getElementsByTagName("templateSubElement") [0].textContent-1;
  
  // alert("Cell index is :"+ CellIndex +" Element Index is :"+ElementIndex + " Sub element Index is:" + SubElementIndex);
    
     var allExistingCells  =  existing_template_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:component4/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1/hl7-org_v3:timePointEventDefinition",existing_template_instance, nsResolver,    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
    
    
    
  var parentComponent1Cell = allExistingCells.snapshotItem(CellIndex);  
 //alert("Parent Component1 Cell is :"+ parentComponent1Cell);
   
   var allSubElementCells= existing_template_instance.evaluate("hl7-org_v3:component1/hl7-org_v3:timePointEventDefinition",parentComponent1Cell, nsResolver,    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
   
   //alert("Total sub element cells:"+ allSubElementCells.snapshotLength);
    
   var parentElement=allSubElementCells.snapshotItem(ElementIndex);

   
   ///****************************************************************
 
                                                   // alert("no components exist and no subject of elements exist Inserting before componentOf1");
                                                      var elementToInsert = template_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:addNewTPCharacteristic/hl7-org_v3:subjectOf" , template_instance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.cloneNode(true);

                                                        parentElement.appendChild(elementToInsert);
                                                   
                                          
          

   
  
  
}







function deleteTemplateElementCharacteristic()
{
     var index= scratch_instance.getElementsByTagName("TimePointIndexInTemplate") [0].childNodes[0].nodeValue-1;
   var subindex= scratch_instance.getElementsByTagName("characteristicInSubElement") [0].childNodes[0].nodeValue-1;

  //alert("index to delete from" +index + "  sub index to delete:" + subindex);
    var allComponent1Cells =  celltemplate_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:component4/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1/hl7-org_v3:timePointEventDefinition",celltemplate_instance, nsResolver,    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
    var parentCell=allComponent1Cells.snapshotItem(index);
    allCharacteristicCells=celltemplate_instance.evaluate("hl7-org_v3:subjectOf",parentCell, nsResolver,    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
   //alert("Total deleteable cells are:"+ allCharacteristicCells.snapshotLength);
  var nodeToDelete=allCharacteristicCells.snapshotItem(subindex);
  //alert("node to delete" + nodeToDelete);
  if(nodeToDelete==null)
  {
    alert("Nothing to delete");
    return;
  }
  
   nodeToDelete.parentNode.removeChild(nodeToDelete);
   
  
}

function addSubElementTemplateCharacteristic()
{
    var CellIndex = scratch_instance.getElementsByTagName("TimePointIndexInTemplate") [0].textContent-1;
  
  //alert("Cell index is :"+ CellIndex );
    
   
  
 
   var mainElement = celltemplate_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:component4/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1/hl7-org_v3:timePointEventDefinition", celltemplate_instance, nsResolver,    XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
   
 var allparentElements =   celltemplate_instance.evaluate("hl7-org_v3:component1/hl7-org_v3:timePointEventDefinition", mainElement, nsResolver,    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
   
 var parentElement=  allparentElements.snapshotItem(CellIndex);
   
  //alert("PArent element is :"+ parentElement);
 //************************************
   var elementToInsert = template_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:addNewTPCharacteristic/hl7-org_v3:subjectOf" , template_instance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.cloneNode(true);

   parentElement.appendChild(elementToInsert);
 
}

function deleteExistingSubElementPrecondition()
{
     var CellIndex = scratch_instance.getElementsByTagName("templateCellIndex") [0].textContent-1;
    var ElementIndex=scratch_instance.getElementsByTagName("templateElementIndex") [0].textContent-1;
    var SubElementIndex=scratch_instance.getElementsByTagName("preConditioninExistingSubElement") [0].textContent-1;
  
  // alert("Cell index is :"+ CellIndex +" Element Index is :"+ElementIndex + " Sub element Index is:" + SubElementIndex);
    
     var allExistingCells  =  existing_template_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:component4/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1/hl7-org_v3:timePointEventDefinition",existing_template_instance, nsResolver,    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
    
    
    
  var parentComponent1Cell = allExistingCells.snapshotItem(CellIndex);  
// alert("Parent Component1 Cell is :"+ parentComponent1Cell);
 
 //alert("Parent Component1 Cell is :"+ parentComponent1Cell);
   
   var allSubElementCells= existing_template_instance.evaluate("hl7-org_v3:component1/hl7-org_v3:timePointEventDefinition",parentComponent1Cell, nsResolver,    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
   
   //alert("Total sub element cells:"+ allSubElementCells.snapshotLength);
    
   var parentElement=allSubElementCells.snapshotItem(ElementIndex);
   
   ///****************************************************************
   
var allpreconditionCells=celltemplate_instance.evaluate("hl7-org_v3:precondition",parentElement, nsResolver,    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
  //  alert("Total deleteable cells are:"+ allpreconditionCells.snapshotLength);
  var nodeToDelete=allpreconditionCells.snapshotItem(SubElementIndex);
//  alert("node to delete" + nodeToDelete);
  if(nodeToDelete==null)
  {
    alert("Nothing to delete");
    return;
  }
  
   nodeToDelete.parentNode.removeChild(nodeToDelete);   
   
}



function addExistingSubElementPrecondition()
{
    var CellIndex = scratch_instance.getElementsByTagName("templateCellIndex") [0].textContent-1;
    var ElementIndex=scratch_instance.getElementsByTagName("templateElementIndex") [0].textContent-1;
    var SubElementIndex=scratch_instance.getElementsByTagName("templateSubElement") [0].textContent-1;
  
 //  alert("Cell index is :"+ CellIndex +" Element Index is :"+ElementIndex + " Sub element Index is:" + SubElementIndex);
    
     var allExistingCells  =  existing_template_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:component4/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1/hl7-org_v3:timePointEventDefinition",existing_template_instance, nsResolver,    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
    
    
    
  var parentComponent1Cell = allExistingCells.snapshotItem(CellIndex);  
 //alert("Parent Component1 Cell is :"+ parentComponent1Cell);
   
   var allSubElementCells= existing_template_instance.evaluate("hl7-org_v3:component1/hl7-org_v3:timePointEventDefinition",parentComponent1Cell, nsResolver,    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
   
   //alert("Total sub element cells:"+ allSubElementCells.snapshotLength);
    
   var parentElement=allSubElementCells.snapshotItem(ElementIndex);
   
   ///****************************************************************
   var allComponent1Elements = celltemplate_instance.evaluate("hl7-org_v3:component1",parentElement, nsResolver,    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
    var allComponent2Elements = celltemplate_instance.evaluate("hl7-org_v3:component2",parentElement, nsResolver,    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
 
      
    var componentOfElements = celltemplate_instance.evaluate("hl7-org_v3:componentOf1", parentElement, nsResolver,    XPathResult.FIRST_ORDERED_NODE_TYPE, null);
    
    var subjectOfElements = celltemplate_instance.evaluate("hl7-org_v3:subjectOf", parentElement, nsResolver,    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
    

	
				             
				                     var totalcomponent1 = allComponent1Elements.snapshotLength;
  				                     var totalcomponent2 = allComponent2Elements.snapshotLength;

				                     var totalSubjectOf = subjectOfElements.snapshotLength;
				                     				                     
				   //     alert("totalComponent 1 under the segment are : " + totalcomponent1 + " And total characteristics are: "+totalSubjectOf );
                                               if(totalcomponent1==0)  //condition to insert before component2section.
                                                    {
                                      //            alert("no components exist and no subject of elements exist Inserting before component2");
                                                      var elementToInsert = template_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:addNewPreCondition/hl7-org_v3:precondition" , template_instance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.cloneNode(true);

                                                       var referenceElement=allComponent2Elements.snapshotItem(0);
                                                      parentElement.insertBefore(elementToInsert,referenceElement);
                                                    }				                     
				                     
                                                 else if(totalcomponent1!=0)  //condition to insert before component1 
                                                    {
                                                   //alert("Time Points exist Inserting before TimePoints");
                                                   
                                                       var component1referenceNode = allComponent1Elements.snapshotItem(0);
                                                     // alert("reference element obtained: "+ component1referenceNode);
                                                      var elementToInsert = template_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:addNewPreCondition/hl7-org_v3:precondition" , template_instance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.cloneNode(true);
  // alert("element to insert obtained "+ elementToInsert);
                                                   
                                          
                                                        
                                                        parentElement.insertBefore(elementToInsert,component1referenceNode);
                                                    }		
                                         				                     
		    

   
  
}






function deleteTemplateElementPrecondition()
{
   var index= scratch_instance.getElementsByTagName("TimePointIndexInTemplate") [0].childNodes[0].nodeValue-1;
   var subindex= scratch_instance.getElementsByTagName("preConditioninSubElement") [0].childNodes[0].nodeValue-1;

   //alert("index to delete from" +index + "  sub index to delete:" + subindex);
    var allComponent1Cells =  celltemplate_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:component4/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1/hl7-org_v3:timePointEventDefinition",celltemplate_instance, nsResolver,    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
    var parentCell=allComponent1Cells.snapshotItem(index);
    allpreconditionCells=celltemplate_instance.evaluate("hl7-org_v3:precondition",parentCell, nsResolver,    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
   //  alert("Total deleteable cells are:"+ allpreconditionCells.snapshotLength);
  var nodeToDelete=allpreconditionCells.snapshotItem(subindex);
//  alert("node to delete" + nodeToDelete);
  if(nodeToDelete==null)
  {
    alert("Nothing to delete");
    return;
  }
  
   nodeToDelete.parentNode.removeChild(nodeToDelete);
   
}









function addSubElementTemplatePrecondition()
{
  var CellIndex = scratch_instance.getElementsByTagName("TimePointIndexInTemplate") [0].textContent-1;
  
//   alert("Cell index is :"+ CellIndex );
    
   
  
 
   var mainElement = celltemplate_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:component4/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1/hl7-org_v3:timePointEventDefinition", celltemplate_instance, nsResolver,    XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
   
 var allparentElements =   celltemplate_instance.evaluate("hl7-org_v3:component1/hl7-org_v3:timePointEventDefinition", mainElement, nsResolver,    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
   
 var parentElement=  allparentElements.snapshotItem(CellIndex);
   
  //alert("PArent element is :"+ parentElement);


//***************************************************************************************


   
      var allComponent1Elements = celltemplate_instance.evaluate("hl7-org_v3:component1",parentElement, nsResolver,    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);

      
    var componentOfElements = celltemplate_instance.evaluate("hl7-org_v3:componentOf1", parentElement, nsResolver,    XPathResult.FIRST_ORDERED_NODE_TYPE, null);
    
    var subjectOfElements = celltemplate_instance.evaluate("hl7-org_v3:subjectOf", parentElement, nsResolver,    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
    
    var component2Element =  celltemplate_instance.evaluate("hl7-org_v3:component2", parentElement, nsResolver,XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
	
				             
				                     var totalcomponent1 = allComponent1Elements.snapshotLength;
				                     var totalSubjectOf = subjectOfElements.snapshotLength;
				                     var totalComponent2=component2Element.snapshotLength;
				          //  alert("totalComponent 1 under the segment are : " + totalcomponent1 + " And total characteristics are: "+totalSubjectOf );
				               if(totalcomponent1==0 && totalComponent2 >0 && totalSubjectOf==0 )  //condition to insert before Component2
                                                    {
                                                 //     alert("Inserting before component2");
                                                      var elementToInsert = template_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:addNewPreCondition/hl7-org_v3:precondition" , template_instance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.cloneNode(true);
													 var referenceElement=component2Element.snapshotItem(0);
                                                parentElement.insertBefore(elementToInsert,referenceElement);

                                                    }				
                                             else if(totalcomponent1==0 && totalSubjectOf==0)  //condition to insert before componentOf section.
                                                    {
                                                 //     alert("no components exist and no subject of elements exist Inserting before componentOf1");
                                                      var elementToInsert = template_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:addNewPreCondition/hl7-org_v3:precondition" , template_instance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.cloneNode(true);

                                                        parentElement.appendChild(elementToInsert);
                                                    }				                     
				                     
                                                 else if(totalcomponent1!=0)  //condition to insert before component1 
                                                    {
                                                  //  alert("Time Points exist Inserting before TimePoints");
                                                   
                                                       var component1referenceNode = allComponent1Elements.snapshotItem(0);
                                                   //   alert("reference element obtained: "+ component1referenceNode);
                                                      var elementToInsert = template_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:addNewPreCondition/hl7-org_v3:precondition" , template_instance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.cloneNode(true);
  // alert("element to insert obtained "+ elementToInsert);
                                                   
                                          
                                                        
                                                        parentElement.insertBefore(elementToInsert,component1referenceNode);
                                                    }		
                                                   else if(totalSubjectOf !=0) //condition to Insert before subject Of
                                                    {
                                                    // alert("Subject of exist but no time poitns exist");
                                                                                 
                                                       var subjectOfReferenceNode =  subjectOfElements.snapshotItem(0);
                                                     var elementToInsert = template_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:addNewPreCondition/hl7-org_v3:precondition" , template_instance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.cloneNode(true);
                                                 
                                                  parentElement.insertBefore(elementToInsert,subjectOfReferenceNode);

                                                    } 		                     				                     
		    

}



function deleteTemplateLocationFromExistingSubElement()
{
  var CellIndex = scratch_instance.getElementsByTagName("templateCellIndex") [0].textContent-1;
    var ElementIndex=scratch_instance.getElementsByTagName("templateElementIndex") [0].textContent-1;
    var SubElementLocation=scratch_instance.getElementsByTagName("existingTemplateLocationSubElement") [0].textContent-1;
  
    //alert("Cell index is :"+ CellIndex +" Element Index is :"+ElementIndex + " Sub element Index is:" + SubElementLocation);
    
 
   var allMainElements = existing_template_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:component4/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1/hl7-org_v3:timePointEventDefinition", existing_template_instance, nsResolver,    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
   
var mainElement = allMainElements.snapshotItem(CellIndex);

   
 var allparentElements =   celltemplate_instance.evaluate("hl7-org_v3:component1/hl7-org_v3:timePointEventDefinition", mainElement, nsResolver,    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
   
 var parentElement=  allparentElements.snapshotItem(ElementIndex);
   
//  alert("PArent element is :"+ parentElement);
  
  var location=celltemplate_instance.evaluate("hl7-org_v3:location", parentElement, nsResolver,    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
          if (location.snapshotLength ==0)
            {
               alert("Nothing to Delete !");
               return;
            }
   var elementToDelete=location.snapshotItem(0);  
  elementToDelete.parentNode.removeChild(elementToDelete);    


   
}

function addTemplateLocationToExistingSubElement()
{
    var CellIndex = scratch_instance.getElementsByTagName("templateCellIndex") [0].textContent-1;
    var ElementIndex=scratch_instance.getElementsByTagName("templateElementIndex") [0].textContent-1;
    var SubElementLocation=scratch_instance.getElementsByTagName("existingTemplateLocationSubElement") [0].textContent-1;
  
    //alert("Cell index is :"+ CellIndex +" Element Index is :"+ElementIndex + " Sub element Index is:" + SubElementLocation);
    
 
   var allMainElements = existing_template_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:component4/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1/hl7-org_v3:timePointEventDefinition", existing_template_instance, nsResolver,    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
   
var mainElement = allMainElements.snapshotItem(CellIndex);

   
 var allparentElements =   celltemplate_instance.evaluate("hl7-org_v3:component1/hl7-org_v3:timePointEventDefinition", mainElement, nsResolver,    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
   
 var parentElement=  allparentElements.snapshotItem(ElementIndex);
   
  //alert("PArent element is :"+ parentElement);
  
  var locationCount=celltemplate_instance.evaluate("hl7-org_v3:location", parentElement, nsResolver,    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null).snapshotLength;
          if (locationCount >0)
            {
               alert("You can only define one location at a time !");
               return;
            }
     
   
      var allComponent1Elements = celltemplate_instance.evaluate("hl7-org_v3:component1",parentElement, nsResolver,    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
      var allComponent2Elements = celltemplate_instance.evaluate("hl7-org_v3:component2",parentElement, nsResolver,    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);

      
    var componentOfElements = celltemplate_instance.evaluate("hl7-org_v3:componentOf1", parentElement, nsResolver,    XPathResult.FIRST_ORDERED_NODE_TYPE, null);
    
    var subjectOfElements = celltemplate_instance.evaluate("hl7-org_v3:subjectOf", parentElement, nsResolver,    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
    
  var allPreConditionElements=celltemplate_instance.evaluate("hl7-org_v3:precondition", parentElement, nsResolver,    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
          var totalPreConditions=allPreConditionElements.snapshotLength;
          

	
				             
				                     var totalcomponent1 = allComponent1Elements.snapshotLength;
   				                     var totalcomponent2 = allComponent2Elements.snapshotLength;

				                     var totalSubjectOf = subjectOfElements.snapshotLength;
				               
				                     				                     
			         //alert("totalComponent 1 under the segment are : " + totalcomponent1 + " And total characteristics are: "+totalSubjectOf + " Total Preconditions "+ totalPreConditions );
                                            if(totalcomponent1==0 && totalPreConditions==0)  //condition to insert before component2 section.
                                                    {
                                             // alert("no components exist and no subject of elements exist Inserting before component2");
                                                  
                                                      var elementToInsert = template_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:addLocation/hl7-org_v3:location" , template_instance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.cloneNode(true);
													 var component2Reference=allComponent2Elements.snapshotItem(0);
													  parentElement.insertBefore(elementToInsert,component2Reference);                                                    }		
                                      		                     
				                            else if(totalPreConditions!=0)  //condition to insert before Preconditions
                                                    {
                                      //alert("Preconditions Exist Inserting before PReconditions");
                                                   
                                                       var preConditionReferenceNode = allPreConditionElements.snapshotItem(0);
                                      //              alert("reference element obtained: "+ preConditionReferenceNode);
                                                   var elementToInsert = template_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:addLocation/hl7-org_v3:location" , template_instance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.cloneNode(true);
                                                     //   alert("element to insert obtained "+ elementToInsert);
                                                   
                                          
                                                        
                                                        parentElement.insertBefore(elementToInsert,preConditionReferenceNode);
                                                    }		
                                                                  		                     
				                     
                                                 else if(totalcomponent1!=0)  //condition to insert before component1 
                                                    {
                                                 //   alert("Time Points exist Inserting before TimePoints");
                                                   
                                                       var component1referenceNode = allComponent1Elements.snapshotItem(0);
            //                                       alert("reference element obtained: "+ component1referenceNode);
                                                                        var elementToInsert = template_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:addLocation/hl7-org_v3:location" , template_instance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.cloneNode(true);

                                                     //   alert("element to insert obtained "+ elementToInsert);
                                                   
                                          
                                                        
                                                        parentElement.insertBefore(elementToInsert,component1referenceNode);
                                                    }		
                                                                  
   
}



function deleteSubElementTemplateLocation()
{
    var CellIndex = scratch_instance.getElementsByTagName("TimePointIndexInTemplate") [0].textContent-1;
  
 //  alert("Cell index is :"+ CellIndex );
   
    var mainElement = celltemplate_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:component4/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1/hl7-org_v3:timePointEventDefinition", celltemplate_instance, nsResolver,    XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
   
 var allparentElements =   celltemplate_instance.evaluate("hl7-org_v3:component1/hl7-org_v3:timePointEventDefinition", mainElement, nsResolver,    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
   
 var parentElement=  allparentElements.snapshotItem(CellIndex);
   
  //alert("PArent element is :"+ parentElement);
  
 var location = celltemplate_instance.evaluate("hl7-org_v3:location", parentElement, nsResolver,    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
 
 //alert("location cell obtained:" + location);
 var totalLocations = location.snapshotLength;
 
 
   if(totalLocations==0)
   {
       alert("Nothing to delete");
       return;
   }
   var elementToDelete = location.snapshotItem(0);
 
elementToDelete.parentNode.removeChild(elementToDelete);    
    


}




function addSubElementTemplateLocation()
 {
 
 
    var CellIndex = scratch_instance.getElementsByTagName("TimePointIndexInTemplate") [0].textContent-1;
  
   // alert("Cell index is :"+ CellIndex );
    
   
  
 
   var mainElement = celltemplate_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:component4/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1/hl7-org_v3:timePointEventDefinition", celltemplate_instance, nsResolver,    XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
   
 var allparentElements =   celltemplate_instance.evaluate("hl7-org_v3:component1/hl7-org_v3:timePointEventDefinition", mainElement, nsResolver,    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
   
 var parentElement=  allparentElements.snapshotItem(CellIndex);
   
  //alert("PArent element is :"+ parentElement);
  
  var locationCount=celltemplate_instance.evaluate("hl7-org_v3:location", parentElement, nsResolver,    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null).snapshotLength;
          if (locationCount >0)
            {
               alert("You can only define one location at a time !");
               return;
            }
     

   
      var allComponent1Elements = celltemplate_instance.evaluate("hl7-org_v3:component1",parentElement, nsResolver,    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);

      
    var componentOfElements = celltemplate_instance.evaluate("hl7-org_v3:componentOf1", parentElement, nsResolver,    XPathResult.FIRST_ORDERED_NODE_TYPE, null);
    
    var subjectOfElements = celltemplate_instance.evaluate("hl7-org_v3:subjectOf", parentElement, nsResolver,    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
    
  var allPreConditionElements=celltemplate_instance.evaluate("hl7-org_v3:precondition", parentElement, nsResolver,    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
          var totalPreConditions=allPreConditionElements.snapshotLength;
          
  var allComponent2=celltemplate_instance.evaluate("hl7-org_v3:component2", parentElement, nsResolver,    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
          var totalComponent2=allComponent2.snapshotLength;
	//    alert("Total Component2 :"+ totalComponent2);
				             
				                     var totalcomponent1 = allComponent1Elements.snapshotLength;
				                     var totalSubjectOf = subjectOfElements.snapshotLength;
				               
            				                     
			    if(totalcomponent1==0 && totalPreConditions==0)  //condition to insert before component2 section.
                                                    {
                                                      var elementToInsert = template_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:addLocation/hl7-org_v3:location" , template_instance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.cloneNode(true);
                                                      
													  var component2reference=allComponent2.snapshotItem(0);	 
                                                        parentElement.insertBefore(elementToInsert,component2reference);
                                                    }		
                                           else if(totalcomponent1==0 && totalSubjectOf==0 && totalPreConditions==0)  //condition to insert before componentOf section.
                                                    {
                                             //    alert("no components exist and no subject of elements exist Inserting before componentOf1");
                                                  
                                                      var elementToInsert = template_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:addLocation/hl7-org_v3:location" , template_instance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.cloneNode(true);

                                                        parentElement.appendChild(elementToInsert);
                                                    }		
                                      		                     
				                            else if(totalPreConditions!=0)  //condition to insert before Preconditions
                                                    {
                                      //alert("Preconditions Exist Inserting before PReconditions");
                                                   
                                                       var preConditionReferenceNode = allPreConditionElements.snapshotItem(0);
                                      //              alert("reference element obtained: "+ preConditionReferenceNode);
                                                   var elementToInsert = template_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:addLocation/hl7-org_v3:location" , template_instance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.cloneNode(true);
                                                     //   alert("element to insert obtained "+ elementToInsert);
                                                   
                                          
                                                        
                                                        parentElement.insertBefore(elementToInsert,preConditionReferenceNode);
                                                    }		
                                                                  		                     
				                     
                                                 else if(totalcomponent1!=0)  //condition to insert before component1 
                                                    {
                                                 //   alert("Time Points exist Inserting before TimePoints");
                                                   
                                                       var component1referenceNode = allComponent1Elements.snapshotItem(0);
            //                                       alert("reference element obtained: "+ component1referenceNode);
                                                                        var elementToInsert = template_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:addLocation/hl7-org_v3:location" , template_instance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.cloneNode(true);

                                                     //   alert("element to insert obtained "+ elementToInsert);
                                                   
                                          
                                                        
                                                        parentElement.insertBefore(elementToInsert,component1referenceNode);
                                                    }		
                                                   else if(totalSubjectOf !=0) //condition to Insert before subject Of
                                                    {
                                               // alert("Subject of exist but no time poitns exist");
                                                                                 
                                                       var subjectOfReferenceNode =  subjectOfElements.snapshotItem(0);
                                                           var elementToInsert = template_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:addLocation/hl7-org_v3:location" , template_instance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.cloneNode(true);
                                                 
                                                  parentElement.insertBefore(elementToInsert,subjectOfReferenceNode);

                                                    } 		                     				                     
		    
 }








function addTemplateSubElementToExistingTemplate()
 {
    var CellIndex = scratch_instance.getElementsByTagName("templateCellIndex") [0].textContent-1;
    var ElementIndex=scratch_instance.getElementsByTagName("templateElementIndex") [0].textContent-1;
    var SubElementIndex=scratch_instance.getElementsByTagName("templateSubElement") [0].textContent-1;
  
    //alert("Cell index is :"+ CellIndex +" Element Index is :"+ElementIndex + " Sub element Index is:" + SubElementIndex);
    
    
     var allExistingCells  =  existing_template_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:component4/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1/hl7-org_v3:timePointEventDefinition",existing_template_instance, nsResolver,    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
    
    
    
  var parentComponent1Cell = allExistingCells.snapshotItem(CellIndex);  
  //alert("Parent Component1 Cell is :"+ parentComponent1Cell);
   
   var allSubElementCells= existing_template_instance.evaluate("hl7-org_v3:component1/hl7-org_v3:timePointEventDefinition",parentComponent1Cell, nsResolver,    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
   
   //alert("Total sub element cells:"+ allSubElementCells.snapshotLength);
    
   var parentCell=allSubElementCells.snapshotItem(ElementIndex);
   
   //alert("PArent cell obtained:" +  parentCell);
  
    
       var allComponent2Elements = existing_template_instance.evaluate("hl7-org_v3:component2", parentCell, nsResolver,    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);   
       var totalComponent2 = allComponent2Elements.snapshotLength;
	 var elementToInsert = template_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:addNewSubElement/hl7-org_v3:component1" , template_instance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.cloneNode(true);
	 var referenceElement=  existing_template_instance.evaluate("hl7-org_v3:component2" ,parentCell, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
	
				
			 parentCell.insertBefore(elementToInsert,referenceElement);
CellIndex=null;
ElementIndex=null;
SubElementIndex=null;
allExistingCells=null;
parentComponent1Cell=null;
allSubElementCells=null;
parentCell=null;
allComponent2Elements=null;
totalComponent2=null;
elementToInsert=null;
referenceElement=null;
 

 }







function deleteTemplateSubElementCells()
{
    var CellIndex = scratch_instance.getElementsByTagName("templateCellIndex") [0].textContent-1;
    var ElementIndex=scratch_instance.getElementsByTagName("templateElementIndex") [0].textContent-1;
    var SubElementIndex=scratch_instance.getElementsByTagName("templateSubElement") [0].textContent-1;
  
 //   alert("Cell index is :"+ CellIndex +" Element Index is :"+ElementIndex + " Sub element Index is:" + SubElementIndex);
   var allExistingTemplateCells =   existing_template_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:component4/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1/hl7-org_v3:timePointEventDefinition",existing_template_instance, nsResolver,    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);    
   var relevantTemplateCell = allExistingTemplateCells.snapshotItem(CellIndex);
   
   //alert("Relevant cell obtained  " + relevantTemplateCell);
   
   var allExistingElementCells = existing_template_instance.evaluate("hl7-org_v3:component1",relevantTemplateCell, nsResolver,    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null); 
   var totalElements=allExistingElementCells.snapshotLength;
   
  
   
   var elementToDelete =  allExistingElementCells.snapshotItem(ElementIndex);
   var allExistingSubElementCells= existing_template_instance.evaluate("hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1",elementToDelete, nsResolver,    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null); 

var totalSubElements=allExistingSubElementCells.snapshotLength;

//alert("Total Sub Elements in the cell are : " + totalSubElements);

 if(totalSubElements==0)
   {
       alert("Nothing to delete");
       return;
   }
var subElementToDelete=allExistingSubElementCells.snapshotItem(SubElementIndex);

//alert("Sub element to delete:"+ subElementToDelete);
subElementToDelete.parentNode.removeChild(subElementToDelete);    
   CellIndex=null;
    ElementIndex=null;
SubElementIndex=null;
allExistingTemplateCells=null;
relevantTemplateCell=null;
allExistingElementCells=null;
totalElements=null;
elementToDelete=null;
allExistingSubElementCells=null;
totalSubElements=null;
subElementToDelete=null;


}





function deleteTemplateElementTimePoint()
{
   var index= scratch_instance.getElementsByTagName("TimePointIndexInTemplate") [0].childNodes[0].nodeValue-1;
   var subindex= scratch_instance.getElementsByTagName("TimePointElementIndexInTemplate") [0].childNodes[0].nodeValue-1;

   //alert("index to delete from" +index + "  sub index to delete:" + subindex);
    var allComponent1Cells =  celltemplate_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:component4/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1/hl7-org_v3:timePointEventDefinition",celltemplate_instance, nsResolver,    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
    var parentCell=allComponent1Cells.snapshotItem(index);
    allComponent1SubElements=celltemplate_instance.evaluate("hl7-org_v3:component1",parentCell, nsResolver,    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
   //     alert("Total deleteable cells are:"+ allComponent1SubElements.snapshotLength);
  var nodeToDelete=allComponent1SubElements.snapshotItem(subindex);
//  alert("node to delete" + nodeToDelete);
  if(nodeToDelete==null)
  {
    alert("Nothing to delete");
    return;
  }
  
   nodeToDelete.parentNode.removeChild(nodeToDelete);
   
}


function addTemplateElementTimePoint()
 {
   var index= scratch_instance.getElementsByTagName("TimePointIndexInTemplate") [0].childNodes[0].nodeValue-1;

   

    var allComponent1Cells = celltemplate_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:component4/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1/hl7-org_v3:timePointEventDefinition",celltemplate_instance, nsResolver,    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
    //alert("Total cells are:"+ allComponent1Cells.snapshotLength);
    var parentCell=allComponent1Cells.snapshotItem(index);
    
  //alert("parent cell created: " + parentCell);

   
    

    var allSubjectOfElements = celltemplate_instance.evaluate("hl7-org_v3:component2", parentCell, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);   
  var totalCharacteristics = allSubjectOfElements.snapshotLength;
  
  
//  alert( "  total characteristics are: " + totalCharacteristics);
 

    var component2Elements = celltemplate_instance.evaluate("hl7-org_v3:component2",parentCell , nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);   


						
										//  alert("subeject element exists ");
										  var referenceElement=  celltemplate_instance.evaluate("hl7-org_v3:component2" ,parentCell, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
							     		//  alert("Reference Element: " + referenceElement);
                	 var elementToInsert = template_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:addNewSubElement/hl7-org_v3:component1" , template_instance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.cloneNode(true);
								//			 alert("Element to insert :" + elementToInsert);
											
										   //  alert("match found :" + " reference segment: " + referenceSegment +" elementToInsert " + elementToInsert);
				    parentCell.insertBefore(elementToInsert,referenceElement);
			     
			

 }




function deleteCell()
{
 var choice=confirm(" Are you sure you want to delete the highlighted Cell? ");
 
 if(choice==false)
   {
    return;
   }

 var indextoDelete = scratch_instance.getElementsByTagName("cellToDelete") [0].textContent-1;
 var allComponent1Nodes = build_Instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:component4/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1",build_Instance,nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
 var totalNodes=allComponent1Nodes.snapshotLength;
 //alert("total nodes are :"+ totalNodes + " Index to delete "+ indextoDelete);
 var nodeToDelete= allComponent1Nodes.snapshotItem(indextoDelete);
 var totalSimilarNodes = 0;
 var nodeNameToDelete=nodeToDelete.getElementsByTagName("timePointEventDefinition") [0].getElementsByTagName("id")[0].getAttributeNode("extension").childNodes[0].nodeValue;
 var armNameInNode=nodeToDelete.getElementsByTagName("timePointEventDefinition")[0].getElementsByTagName("componentOf2")[0].getElementsByTagName("armStub")[0].getElementsByTagName("id")[0].getAttributeNode("extension").childNodes[0].nodeValue;
 for(i=0;i<totalNodes;i++)
     {
        var nodeToCheck =  allComponent1Nodes.snapshotItem(i);
        var nodeNameChecked=nodeToCheck.getElementsByTagName("timePointEventDefinition") [0].getElementsByTagName("id")[0].getAttributeNode("extension").childNodes[0].nodeValue;
        if(nodeNameChecked==nodeNameToDelete)
         {
           totalSimilarNodes++;
         }
     }
 
 //alert("Total Similar nodes =" +totalSimilarNodes);

        //   alert("Node NAme being deleted is :"+nodeNameToDelete);
 		      nodeToDelete.parentNode.removeChild(nodeToDelete);  

 
 if(totalSimilarNodes==1) //if the node being deleted was the only instance of the node then the template should be removed from the 'existing templates' section to keep these instances in sych.
      {
                 //  alert("Inside for loop Node NAme being deleted is :"+nodeNameToDelete);

   var allExistingTemplateCells  =   existing_template_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:component4/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1",existing_template_instance, nsResolver,    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
   
  var totalExistingTemplates=allExistingTemplateCells.snapshotLength;
		  for(var j=0;j<totalExistingTemplates;j++)
		  {
		    var templateNode=allExistingTemplateCells.snapshotItem(j);
		    var templateNodeName=templateNode.getElementsByTagName("timePointEventDefinition") [0].getElementsByTagName("id")[0].getAttributeNode("extension").childNodes[0].nodeValue;
		//    alert("Template node name :"+ templateNodeName);
		    if(templateNodeName==nodeNameToDelete)
		       {
		  //     alert("Match found and Template: " + templateNodeName + " node Name to Delete :"+ nodeNameToDelete);
		        templateNode.parentNode.removeChild(templateNode);
		       }
		  }   
		   
      }

synchronizeSubjectTemplateInstance(armNameInNode);
removeComponent4Node();
}


function removeComponent4Node()
{
  var allComponent1Nodes = build_Instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:component4/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1",build_Instance,nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
 var totalNodes=allComponent1Nodes.snapshotLength;
 if(totalNodes==0)
    {
   // alert("Deleting component4:");
      var component4Node=build_Instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:component4",build_Instance,nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
      var nodeToDelete=component4Node.snapshotItem(0);
       nodeToDelete.parentNode.removeChild(nodeToDelete); 

    }
}


function synchronizeSubjectTemplateInstance(armNameInNode) //function to delete subject nodes in the subject template if all ARM nodes belonging to a particular arm have been deleted.
 {
   var allArmStubNodes= build_Instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:component4/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1/hl7-org_v3:timePointEventDefinition/hl7-org_v3:componentOf2/hl7-org_v3:armStub/hl7-org_v3:id",build_Instance,nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
   var totalNodes=allArmStubNodes.snapshotLength;
   var similarNodes=0;
   for(var i=0;i<totalNodes;i++) //find how many cells in the build have the same arm name as the node that was just deleted
        {
          var currentArmName=allArmStubNodes.snapshotItem(i).getAttributeNode("extension").childNodes[0].nodeValue;
          if(currentArmName==armNameInNode)
          {
            similarNodes++;
          }
        }   
   
   if(similarNodes==0)
     {
            var allSubjectTemplateCells = subject_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:arm",subject_instance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
	        var totalSubjectTemplateCells= allSubjectTemplateCells.snapshotLength;
	        //alert("Total subject template cells" + totalSubjectTemplateCells);
            for(var i=0;i<totalSubjectTemplateCells;i++)
               {
			      var templateSubjectCell=allSubjectTemplateCells.snapshotItem(i).cloneNode(true);
			      var templateCellArmName=templateSubjectCell.getElementsByTagName("armname")[0].childNodes[0].nodeValue;
                  //alert("Subject Template Arm NAME:"+ templateCellArmName);
			      if(templateCellArmName==armNameInNode)
			          {
                      //  alert("match found: i=" + i);
                        var nodeToDelete=allSubjectTemplateCells.snapshotItem(i);
                       // alert("Node to delete obtained:"+ nodeToDelete);
		               nodeToDelete.parentNode.removeChild(nodeToDelete); 
                      			          return;

			          }
			          
			      }    
     }
 }




function synchSubjectToNewCell(elementToInsert, armName)
{
  // alert("Element to Insert :" + elementToInsert + " Arm name :"+ armName);
    var allCells = build_Instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:component4/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1/hl7-org_v3:timePointEventDefinition", build_Instance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
    var cellCount=allCells.snapshotLength;
    var totalCellsInSameArm =0;
    var indexfound=0;
    var subjectCell=null;
    
    for (var i=0;i<cellCount;i++) //loop to find out where the last cell in the ARM existed and how many cells existed in the ARM. (All these cells should have the same subjects);
     {
       var currentCell=allCells.snapshotItem(i).cloneNode(true);
      var armNameInCells= currentCell.getElementsByTagName("componentOf2")[0].getElementsByTagName("armStub")[0].getElementsByTagName("id")[0].getAttributeNode("extension").nodeValue;
      //alert(armNameInCells);
      if(armNameInCells==armName && i!=cellCount-1)
         {
           totalCellsInSameArm++;
           indexfound=i;
         }      
      
     }   
  // alert("Last cell found at :"+ indexfound+ "  total matching cells"+ totalCellsInSameArm);
   if(totalCellsInSameArm==0) //no cells existed in the same arm of the study. In this case no subjects could have been assigned. Therefore no further change to cell is needed.
   {
    //alert("No cell existed in same arm. Therefore going back");
    return;
   }   
   
    
   var lastCellInArm=allCells.snapshotItem(indexfound).cloneNode(true);
   var subjectCellInLastCellInArm = build_Instance.evaluate("hl7-org_v3:subject",lastCellInArm, nsResolver,XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
   var numberOfSubjects =   subjectCellInLastCellInArm.snapshotLength;
   
   if( numberOfSubjects==0)
       return;
   else 
   {
     //alert("Subjects exist for this arm - Add code to insert similar subject in the element to Insert");
        subjectCell=subjectCellInLastCellInArm.snapshotItem(0);
        //alert("Subject cell obtained:"+ subjectCell);
   }    
    
   var parentCell= build_Instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:component4/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1/hl7-org_v3:timePointEventDefinition", build_Instance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null).snapshotItem(cellCount-1);
   //alert("Parent Cell obtained:"+ parentCell);
   	 var allComponent1Elements = build_Instance.evaluate("hl7-org_v3:component1",parentCell, nsResolver,    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
		 var componentOfElements = build_Instance.evaluate("hl7-org_v3:componentOf1", parentCell, nsResolver,    XPathResult.FIRST_ORDERED_NODE_TYPE, null);
		 var subjectOfElements = build_Instance.evaluate("hl7-org_v3:subjectOf", parentCell, nsResolver,    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
		 var allPreConditionElements=build_Instance.evaluate("hl7-org_v3:precondition", parentCell, nsResolver,    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
		 var allLocationElements = build_Instance.evaluate("hl7-org_v3:location",parentCell, nsResolver,    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
		var locationCount=allLocationElements.snapshotLength;
		 var totalcomponent1 = allComponent1Elements.snapshotLength;
		 var totalPreConditions=allPreConditionElements.snapshotLength;
		 var totalSubjectOf = subjectOfElements.snapshotLength;			      
       // alert("total subject of elements "  + totalSubjectOf + " All locations:"+ locationCount+ " preconditions:" + totalPreConditions + " Total time points:"+ totalcomponent1);
           if(totalcomponent1==0 && totalSubjectOf==0 && totalPreConditions==0 && locationCount==0)  //condition to insert before componentOf section.
																			{
		//											           alert(" Inserting before componentOf1");
																			   var referenceElement=componentOfElements.singleNodeValue;
          //                                                              alert(" Parent element is :" + parentCell + " reference element obtained: "+ referenceElement);

																			   
																			 //  alert("reference element obtained: "+ referenceElement);
																			  parentCell.insertBefore(subjectCell,referenceElement);
																			}	
											 			else if(locationCount > 0)  //condition to insert before Locations
																			{
						                                                    //alert("Locations Exist Inserting before Locations");
																			   var locationReferenceNode = allLocationElements.snapshotItem(0);

																		   parentCell.insertBefore(subjectCell,locationReferenceNode);
																			}		
													 else if(totalPreConditions>0)  //condition to insert before Preconditions
																			{
														                   //alert("Preconditions Exist Inserting before PReconditions");

																			   var preConditionReferenceNode = allPreConditionElements.snapshotItem(0);
				 
																			   //alert("Pre condition reference :"+ preConditionReferenceNode);
																				parentCell.insertBefore(subjectCell,preConditionReferenceNode);
																			}		
														else if(totalcomponent1>0)  //condition to insert before component1 
																			{
																		    //alert("Time Points exist Inserting before TimePoints");
																			     var component1referenceNode = allComponent1Elements.snapshotItem(0);

																	    		parentCell.insertBefore(subjectCell,component1referenceNode);
																			}		
													   else if(totalSubjectOf >0) //condition to Insert before subject Of
																			{
					                                                      //alert("Subject of exist but no time points exist");

				                                                            var subjectOfReferenceNode =  subjectOfElements.snapshotItem(0);
							                                                 parentCell.insertBefore(subjectCell,subjectOfReferenceNode);
						
																			} 		                 
			
   
    }   
    
 




function addToStudy()
{

        insertComponent4();
         var parentCell = build_Instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:component4/hl7-org_v3:timePointEventDefinition", build_Instance, nsResolver,XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
     //    alert("Parent cell is: " + parentCell);
         var referenceElement=build_Instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:component4/hl7-org_v3:timePointEventDefinition", build_Instance, nsResolver,XPathResult.FIRST_ORDERED_NODE_TYPE, null);
          //  alert("Reference Element is  " + referenceElement);
         var elementToInsert = celltemplate_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:component4/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1", celltemplate_instance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.cloneNode(true);
         //  alert("Element to Insert is " + elementToInsert); 
 try{
         var cellName = celltemplate_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:component4/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1/hl7-org_v3:timePointEventDefinition/hl7-org_v3:id", celltemplate_instance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.getAttributeNode("extension").childNodes[0].nodeValue;    
         
           }catch(err)
                   {
                
                   cellName='';
                   }             
           
           try{
         var epochName = celltemplate_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:component4/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1/hl7-org_v3:timePointEventDefinition/hl7-org_v3:componentOf1/hl7-org_v3:epochStub/hl7-org_v3:id", celltemplate_instance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.getAttributeNode("extension").childNodes[0].nodeValue;    
         
           }catch(err)
                   {
                
                    epochName='';
                   }  
                   
               try{     
                  var armName = celltemplate_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:component4/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1/hl7-org_v3:timePointEventDefinition/hl7-org_v3:componentOf2/hl7-org_v3:armStub/hl7-org_v3:id", celltemplate_instance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.getAttributeNode("extension").childNodes[0].nodeValue; 	     
                  
                   }catch(err)
                     {
                       armName='';
                     }
         
                  
	     
		//alert("Epoch Node is : "+ epochName + " And the Arm Node is :" + armName);
		 if (cellName=="")
                 {
                  alert ("Cell Name cannot be left blank. Please choose a value from the list or type in a new cell name");
                  return;
                 }		
        if (epochName=="")
                 {
                  alert ("Epoch Stub and Arm Stub fields cannot be left blank. Please select where you'd like to insert the Cell and try adding to the study again.If you cannot see any values in the drop down list box you must create Epochs and Arms on the respective tabs before templates can be added to the actual study design");
                  return;
                 }		
		   if (armName=="")
                 {
                  alert ("Epoch Stub and Arm Stub fields cannot be left blank. Please select where you'd like to insert the Cell and try adding to the study again. If you cannot see any values in the drop down list box you must create Epochs and Arms on the respective tabs before templates can be added to the actual study design");
                  return;
                 }	
          
          var allEpochs= build_Instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:component1/hl7-org_v3:epoch/hl7-org_v3:id",build_Instance,nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);    
          //alert ("All Epochs "+ allEpochs);
          var epochCount = allEpochs.snapshotLength;      
          for(var i=0;i<epochCount;i++)
           {
                           var epoch = getAttributevalue("/hl7-org_v3:plannedStudy/hl7-org_v3:component1/hl7-org_v3:epoch/hl7-org_v3:id",i,"extension");
                           if (epoch==epochName)
                              {
                                     var sequenceNumber = getAttributevalue("/hl7-org_v3:plannedStudy/hl7-org_v3:component1/hl7-org_v3:sequenceNumber",i,"value");
                             //        alert ("match found at sequence number: "+ sequenceNumber);
                  		          setAttributevalue(elementToInsert,"sequenceNumber",0,"value",sequenceNumber);

                              }

           }          
              
          var choice= checkDuplicateExists(epochName,armName);
                 
           if( duplicateexists==true && choice==true)  //if user has chosen to overwrite the previous cell delete the older cell and add the new cell
            {    
              var nodeToDelete = build_Instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:component4/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1",build_Instance,nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null).snapshotItem(matchfoundindex);
              var index=matchfoundindex;
              addSubjectElementToNewNode(nodeToDelete, index,elementToInsert,armName)
     
          //    alert("Node to Delete is :"+nodeToDelete);
		      nodeToDelete.parentNode.removeChild(nodeToDelete); 
            //  alert("Removing node at index " + matchfoundindex);  
	          parentCell.appendChild(elementToInsert);   
	        }  
	       else if (duplicateexists==false)
	          {
	                     // alert("New element being added at a location which did not have a previous cell - Subjects need to be synched up");
	          	          parentCell.appendChild(elementToInsert);   
   	                      synchSubjectToNewCell(elementToInsert,armName);

	          	       
	          }
	        else
	         {
	         return;
	         }  
        
 //generateTemplates();
 updateLibrary();
alert("Cell successfully added into existing study!!");
}


function alertTest()
{ 


 alert("value of flag is:"+  scratch_instance.getElementsByTagName("cellTemplateId") [0].childNodes[0].nodeValue);
}

function addSubjectToArms()
{


var armIndex=scratch_instance.getElementsByTagName("armForSubjectInsert") [0].childNodes[0].nodeValue-1;
//alert("Index to insert : " +armIndex);

var allSubjectTemplateCells = subject_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:arm",subject_instance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
	//	alert("Total number of cells =" + numberOfArmCells);
     
			         var armCell=allSubjectTemplateCells.snapshotItem(armIndex);
                      var templateCellArmName=armCell.getElementsByTagName("armname")[0].childNodes[0].nodeValue;
                      
                      
var currentSubjectTemplateCell=allSubjectTemplateCells.snapshotItem(armIndex).cloneNode(true);
var elementToInsert = subject_instance.evaluate("hl7-org_v3:subject",currentSubjectTemplateCell, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null).snapshotItem(0).cloneNode(true);


	//	alert("Total number of cells =" + numberOfArmCells);
var allCellElements=build_Instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:component4/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1/hl7-org_v3:timePointEventDefinition",build_Instance, nsResolver,    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
var totalCells=allCellElements.snapshotLength;

//alert("Arm to modify is :"+ templateCellArmName);

  for(var i=0;i<totalCells;i++)
        {
         // alert("In major loop for cell number:"+i);
          var parentElement=build_Instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:component4/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1/hl7-org_v3:timePointEventDefinition",build_Instance, nsResolver,    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null).snapshotItem(i);
         //  alert("Parent element obtained");
           var buildCellArmName=parentElement.getElementsByTagName("componentOf2")[0].getElementsByTagName("armStub")[0].getElementsByTagName("id")[0].getAttributeNode("extension").nodeValue;
          // alert("Build cell armname:"+ buildCellArmName);
           if(templateCellArmName==buildCellArmName)
              {
               //alert("Match found at index :" + i);
               
					
						
                         var allComponent1Elements = build_Instance.evaluate("hl7-org_v3:component1",parentElement, nsResolver,    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
                         var componentOfElements = build_Instance.evaluate("hl7-org_v3:componentOf1", parentElement, nsResolver,    XPathResult.FIRST_ORDERED_NODE_TYPE, null);
                         var subjectOfElements = build_Instance.evaluate("hl7-org_v3:subjectOf", parentElement, nsResolver,    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
                         var allPreConditionElements=build_Instance.evaluate("hl7-org_v3:precondition", parentElement, nsResolver,    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
                         var allLocationElements = build_Instance.evaluate("hl7-org_v3:location",parentElement, nsResolver,    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
                         var subjectNode = build_Instance.evaluate("hl7-org_v3:subject",parentElement, nsResolver,XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
                         var subjectNodeCount=subjectNode.snapshotLength;

                         var locationCount=allLocationElements.snapshotLength;
	                     var totalcomponent1 = allComponent1Elements.snapshotLength;
		                 var totalPreConditions=allPreConditionElements.snapshotLength;
		                 var totalSubjectOf = subjectOfElements.snapshotLength;				
		                   
		               //     alert("Total locations:"+ locationCount +" Total Component1:" + totalcomponent1+" Total Preconditions:" + totalPreConditions + " Total subject of:"+ totalSubjectOf + "  Subject node count: " + subjectNodeCount); 
		                    
						if(subjectNodeCount==1)
									{
									
									 // alert("Node needs to be deleted");
									 var nodeToDelete=subjectNode.snapshotItem(0);  
											  nodeToDelete.parentNode.removeChild(nodeToDelete);    
									}//end if statement
						
		            			//insert subject node 
											   if(totalcomponent1==0 && totalSubjectOf==0 && totalPreConditions==0 && locationCount==0)  //condition to insert before componentOf section.
																			{
													        //    alert(" Inserting before componentOf1");
																			   var referenceElement=componentOfElements.singleNodeValue;
																			   var currentSubjectTemplateCell=allSubjectTemplateCells.snapshotItem(armIndex).cloneNode(true);
                                                                                var elementToInsert = subject_instance.evaluate("hl7-org_v3:subject",currentSubjectTemplateCell, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null).snapshotItem(0).cloneNode(true);
																			   
																			 //  alert("reference element obtained: "+ referenceElement);
																			  parentElement.insertBefore(elementToInsert,referenceElement);
																			}	
																	else if(locationCount > 0)  //condition to insert before Locations
																			{
						                                                    //alert("Locations Exist Inserting before Locations");
																			   var locationReferenceNode = allLocationElements.snapshotItem(0);
																			   var currentSubjectTemplateCell=allSubjectTemplateCells.snapshotItem(armIndex).cloneNode(true);
                                                                                var elementToInsert = subject_instance.evaluate("hl7-org_v3:subject",currentSubjectTemplateCell, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null).snapshotItem(0).cloneNode(true);
																		//   alert("reference element obtained: "+ preConditionReferenceNode);
																		   parentElement.insertBefore(elementToInsert,locationReferenceNode);
																			}		
															 else if(totalPreConditions>0)  //condition to insert before Preconditions
																			{
														                   //   alert("Preconditions Exist Inserting before PReconditions");
																		   
																			   var preConditionReferenceNode = allPreConditionElements.snapshotItem(0);
																			   var currentSubjectTemplateCell=allSubjectTemplateCells.snapshotItem(armIndex).cloneNode(true);
                                                                                var elementToInsert = subject_instance.evaluate("hl7-org_v3:subject",currentSubjectTemplateCell, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null).snapshotItem(0).cloneNode(true);
																			   //alert("Pre condition reference :"+ preConditionReferenceNode);
																				parentElement.insertBefore(elementToInsert,preConditionReferenceNode);
																			}		
																		else if(totalcomponent1>0)  //condition to insert before component1 
																			{
																		    //   alert("Time Points exist Inserting before TimePoints");
																			     var component1referenceNode = allComponent1Elements.snapshotItem(0);
																			     var currentSubjectTemplateCell=allSubjectTemplateCells.snapshotItem(armIndex).cloneNode(true);
                                                                                var elementToInsert = subject_instance.evaluate("hl7-org_v3:subject",currentSubjectTemplateCell, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null).snapshotItem(0).cloneNode(true);
																              //  alert("reference element obtained: "+ component1referenceNode);
																	    		parentElement.insertBefore(elementToInsert,component1referenceNode);
																			}		
																		   else if(totalSubjectOf >0) //condition to Insert before subject Of
																			{
					                                                   	 //   alert("Subject of exist but no time poitns exist");
					                                                   	    var currentSubjectTemplateCell=allSubjectTemplateCells.snapshotItem(armIndex).cloneNode(true);
                                                                                var elementToInsert = subject_instance.evaluate("hl7-org_v3:subject",currentSubjectTemplateCell, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null).snapshotItem(0).cloneNode(true);
				                                                            var subjectOfReferenceNode =  subjectOfElements.snapshotItem(0);
							                                                 parentElement.insertBefore(elementToInsert,subjectOfReferenceNode);
						
																			} 		                 
						
						//**************
              }   //end if statement
              
              
              

        }  //end for loop
      
       alert("Subject assigment is complete !!" );
    }










function setStudyType()
   {
  // alert("Coming into StudyType");
 var allSubjectOf =build_Instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:subjectOf" ,build_Instance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
  var characteristicCount=allSubjectOf.snapshotLength;
 // alert("Total characteristics "+ characteristicCount);
  if(characteristicCount==0)
       {   
            scratch_instance.getElementsByTagName("typeOfStudyRelevance") [0].childNodes[0].nodeValue ='';
           return '';
         }
    else if(characteristicCount >0)
    {
      var firstCharacteristicNode = allSubjectOf.snapshotItem(0);
      var studyTypeCode=firstCharacteristicNode.getElementsByTagName("studyCharacteristic")[0].getElementsByTagName("code")[0].getAttributeNode("code").nodeValue;
      if(studyTypeCode=="TYPEOFSTUDY")
            {
              var studyType = firstCharacteristicNode.getElementsByTagName("studyCharacteristic")[0].getElementsByTagName("value")[0].textContent;
              scratch_instance.getElementsByTagName("typeOfStudyRelevance") [0].childNodes[0].nodeValue =studyType;

              return studyType;
            }
        else 
        {
             scratch_instance.getElementsByTagName("typeOfStudyRelevance") [0].childNodes[0].nodeValue ='';

             return '';
        }  
     
   }


}

function deleteExistingTemplateSubject()
{
var CellIndex = scratch_instance.getElementsByTagName("templateCellIndex") [0].textContent-1;
    
  //  alert("Cell chosedn is :"+ CellIndex);
   var allExistingTemplateCells =   existing_template_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:component4/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1/hl7-org_v3:timePointEventDefinition",existing_template_instance, nsResolver,    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);    
   var relevantTemplateCell = allExistingTemplateCells.snapshotItem(CellIndex);
   
   //alert("Relevant cell obtained  " + relevantTemplateCell);
   
   var allExistingSubjectCells = existing_template_instance.evaluate("hl7-org_v3:subject",relevantTemplateCell, nsResolver,    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null); 
   
   var totalSubjects=allExistingSubjectCells.snapshotLength;
   //alert("Total subject cells:"+ totalLocations);
   if(totalSubjects==0)
   {
       alert("Nothing to delete");
       return;
   }
   
   
   var subjectToDelete = allExistingSubjectCells.snapshotItem(0);
   
   //  alert("Relevant element obtained  " + locationToDelete);

subjectToDelete.parentNode.removeChild(subjectToDelete);    
    
   
}



function addTemplateLocationToExistingTemplate()
{

 var index = scratch_instance.getElementsByTagName("templateLocationIndex") [0].textContent-1;
 // alert ("index to insert is :" + index);
  
  
   var allExistingCells  =   existing_template_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:component4/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1/hl7-org_v3:timePointEventDefinition",existing_template_instance, nsResolver,    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
    
  var parentCell = allExistingCells.snapshotItem(index);  
 // alert("Parent Cell is :"+ parentCell);

  var allLocationElements= existing_template_instance.evaluate("hl7-org_v3:location", parentCell, nsResolver,    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);    
   
  var totalLocationElements=   allLocationElements.snapshotLength;
  
  if(totalLocationElements>0)
  {
   alert("You cannot insert more than one location for a cell ");
   return;
  }
   
   var allElementCells=  existing_template_instance.evaluate("hl7-org_v3:component1", parentCell, nsResolver,    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);    
   var totalComponent1 =allElementCells.snapshotLength;
   
 //alert("total component 1 are:" + totalComponent1);
   
       var allSubjectOfElements = existing_template_instance.evaluate("hl7-org_v3:subjectOf", parentCell, nsResolver,    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);   
  var totalSubjectOfElements = allSubjectOfElements.snapshotLength;
  				
  
    var allPreconditionElements =existing_template_instance.evaluate("hl7-org_v3:precondition", parentCell, nsResolver,    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);   
  var totalPreconditionElements = allPreconditionElements.snapshotLength;        
  
//alert("Total perconditions under cell are " + totalPreconditionElements);
  
    var allComponentOf1Elements = existing_template_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:component4/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1/hl7-org_v3:timePointEventDefinition/hl7-org_v3:componentOf1", existing_template_instance, nsResolver,XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);   
                 	  if(totalPreconditionElements >0)  //insert before the Precondition element
										  {  
								//	 alert(" inserting before PRecondition");
										   var referenceElement=allPreconditionElements.snapshotItem(0);
									// alert("Reference segment is :"+referenceElement);
						                        var elementToInsert = template_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:addLocation/hl7-org_v3:location" , template_instance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.cloneNode(true);
										
								// alert("element to insert is :"+ elementToInsert);
											
											 parentCell.insertBefore(elementToInsert,referenceElement);
										   }  
    
               
            	else  if(totalComponent1 >0)  //insert before the component1 element
										  {  
									 //alert(" inserting before component1");
										   var referenceElement=allElementCells.snapshotItem(0);
								//	 alert("Reference segment is :"+referenceElement);
						                        var elementToInsert = template_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:addLocation/hl7-org_v3:location" , template_instance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.cloneNode(true);
										
								// alert("element to insert is :"+ elementToInsert);
											
											 parentCell.insertBefore(elementToInsert,referenceElement);
										   }  
						  else if(totalSubjectOfElements>0 ) //insert before subject of element
										 {
					//	alert("subject element exists ");
										  var referenceElement=  existing_template_instance.evaluate("hl7-org_v3:subjectOf" ,parentCell, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
							    // 	 alert("Reference Element: " + referenceElement);
                	           var elementToInsert = template_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:addLocation/hl7-org_v3:location" , template_instance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.cloneNode(true);
							//	alert("Element to insert :" + elementToInsert);
										 parentCell.insertBefore(elementToInsert,referenceElement);
										 }   						   
   
   	  else        {       //insert before the componentof1 element
										  
									 //alert(" inserting before component of 1");
										   var referenceElement=allComponentOf1Elements.snapshotItem(index);
									//  alert("Reference segment is :"+referenceElement);
						                       var elementToInsert = template_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:addLocation/hl7-org_v3:location" , template_instance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.cloneNode(true);

										
							//	 alert("element to insert is :"+ elementToInsert);
											
											 parentCell.insertBefore(elementToInsert,referenceElement);
										   }  
										   
								   
   
   
}





























function addTemplateSubject()
{

//alert("Coming into function");

          var allSubjectElements = celltemplate_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:component4/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1/hl7-org_v3:timePointEventDefinition/hl7-org_v3:subject",celltemplate_instance, nsResolver,    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
     var subjectCount=allSubjectElements.snapshotLength;

          if (subjectCount >0)
            {
               alert("You can only define one Experimental Unit for every cell.");
               return;
            }
     
   var parentElement = celltemplate_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:component4/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1/hl7-org_v3:timePointEventDefinition", celltemplate_instance, nsResolver,    XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
   
// alert("PArent element is :"+ parentElement); 

   
   var codeElements = celltemplate_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:component4/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1/hl7-org_v3:timePointEventDefinition/hl7-org_v3:code", celltemplate_instance, nsResolver,    XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;

 //alert("Code element is :"+ codeElements);
   
      var allComponent1Elements = celltemplate_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:component4/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1",celltemplate_instance, nsResolver,    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);

      
    var componentOfElements = celltemplate_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:component4/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1/hl7-org_v3:timePointEventDefinition/hl7-org_v3:componentOf1", celltemplate_instance, nsResolver,    XPathResult.FIRST_ORDERED_NODE_TYPE, null);
    
    var subjectOfElements = celltemplate_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:component4/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1/hl7-org_v3:timePointEventDefinition/hl7-org_v3:subjectOf", celltemplate_instance, nsResolver,    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
    
  var allPreConditionElements=celltemplate_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:component4/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1/hl7-org_v3:timePointEventDefinition/hl7-org_v3:precondition", celltemplate_instance, nsResolver,    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
          var totalPreConditions=allPreConditionElements.snapshotLength;
          
    var allLocationElements = celltemplate_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:component4/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1/hl7-org_v3:timePointEventDefinition/hl7-org_v3:location",celltemplate_instance, nsResolver,    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
     var locationCount=allLocationElements.snapshotLength;
	
				             
				                     var totalcomponent1 = allComponent1Elements.snapshotLength;
				                     var totalSubjectOf = subjectOfElements.snapshotLength;
				                     var elementToInsert=null;
				                     
  var typeofStudy = getStudyType(); 		
 // alert ("Tyhpe of study is " + typeofStudy);		         
              
	
  if(typeofStudy=='')
       {   return;		}
  else if (typeofStudy=="Animal Study")
      {
       elementToInsert=template_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:animalSubject/hl7-org_v3:subject" , template_instance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.cloneNode(true);
      } 
          
  else if (typeofStudy=="Human Study")
      {
       elementToInsert=template_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:humanSubject/hl7-org_v3:subject" , template_instance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.cloneNode(true);
      } 
  else if (typeofStudy=="Product Study")
      {
       elementToInsert=template_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:productSubject/hl7-org_v3:subject" , template_instance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.cloneNode(true);
      } 
      
      
   scratch_instance.getElementsByTagName("typeOfStudyRelevance") [0].childNodes[0].nodeValue  =typeofStudy;
   // scratch_instance.getElementsByTagName("epochjavascript") [0].childNodes[0].nodeValue 
   		                     
	//	alert ("flag set to:"+  scratch_instance.getElementsByTagName("typeOfStudyRelevance") [0].childNodes[0].nodeValue);		               
				                     				                     
        //  alert("totalComponent 1 under the segment are : " + totalcomponent1 + " And total characteristics are: "+totalSubjectOf + " Total Preconditions "+ totalPreConditions );
                                               if(totalcomponent1==0 && totalSubjectOf==0 && totalPreConditions==0 && locationCount==0)  //condition to insert before componentOf section.
                                                    {
                                   //     alert(" Inserting before componentOf1");
                                                       var referenceElement=componentOfElements.singleNodeValue;
                                                     //  alert("reference element obtained: "+ referenceElement);
                                                      parentElement.insertBefore(elementToInsert,referenceElement);
                                                    }	
                                            else if(locationCount > 0)  //condition to insert before Locations
                                                    {
 //    alert("Locations Exist Inserting before Locations");
                                                       var locationReferenceNode = allLocationElements.snapshotItem(0);
                                                  //  alert("reference element obtained: "+ preConditionReferenceNode);
                                                   parentElement.insertBefore(elementToInsert,preConditionReferenceNode);
                                                    }		
                                                    
                                                    	
                                      		                     
				                            else if(totalPreConditions>0)  //condition to insert before Preconditions
                                                    {
                                 //      alert("Preconditions Exist Inserting before PReconditions");
                                                   
                                                       var preConditionReferenceNode = allPreConditionElements.snapshotItem(0);
                                                        parentElement.insertBefore(elementToInsert,preConditionReferenceNode);
                                                    }		
                                                                  		                     
				                     
                                                 else if(totalcomponent1>0)  //condition to insert before component1 
                                                    {
                                                // alert("Time Points exist Inserting before TimePoints");
                                                      var component1referenceNode = allComponent1Elements.snapshotItem(0);
                                      //       alert("reference element obtained: "+ component1referenceNode);
                                                    parentElement.insertBefore(elementToInsert,component1referenceNode);
                                                    }		
                                                   else if(totalSubjectOf >0) //condition to Insert before subject Of
                                                    {
  //  alert("Subject of exist but no time poitns exist");
                                                                                 
                                                       var subjectOfReferenceNode =  subjectOfElements.snapshotItem(0);
                                            
                                                  parentElement.insertBefore(elementToInsert,subjectOfReferenceNode);

                                                    } 		                     				                     


}


function getStudyType()
{
  var allSubjectOf =build_Instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:subjectOf" ,build_Instance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
  var characteristicCount=allSubjectOf.snapshotLength;
  if(characteristicCount==0)
       {   
           alert("You have not defined any study characteristics. Please choose the 'type of study' for this message on the study characteristics tab");
           return '';
         }
    else if(characteristicCount >0)
    {
      var firstCharacteristicNode = allSubjectOf.snapshotItem(0);
      var studyTypeCode=firstCharacteristicNode.getElementsByTagName("studyCharacteristic")[0].getElementsByTagName("code")[0].getAttributeNode("code").nodeValue;
      if(studyTypeCode=="TYPEOFSTUDY")
            {
              var studyType = firstCharacteristicNode.getElementsByTagName("studyCharacteristic")[0].getElementsByTagName("value")[0].textContent;
              return studyType;
            }
        else 
        {
        alert("You have not defined a characteristic 'TYPEOFSTUDY'. Please go to the study characteristics tab and select a valid choice from the radio button group");
         return '';
        }  
     }       

  
}













function deleteExistingTemplateLocation()
{
    var CellIndex = scratch_instance.getElementsByTagName("templateCellIndex") [0].textContent-1;
    
  //  alert("Cell chosedn is :"+ CellIndex);
   var allExistingTemplateCells =   existing_template_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:component4/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1/hl7-org_v3:timePointEventDefinition",existing_template_instance, nsResolver,    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);    
   var relevantTemplateCell = allExistingTemplateCells.snapshotItem(CellIndex);
   
   //alert("Relevant cell obtained  " + relevantTemplateCell);
   
   var allExistingLocationCells = existing_template_instance.evaluate("hl7-org_v3:location",relevantTemplateCell, nsResolver,    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null); 
   
   var totalLocations=allExistingLocationCells.snapshotLength;
   //alert("Total location cells:"+ totalLocations);
   if(totalLocations==0)
   {
       alert("Nothing to delete");
       return;
   }
   var locationToDelete = allExistingLocationCells.snapshotItem(0);
   
   //  alert("Relevant element obtained  " + locationToDelete);

locationToDelete.parentNode.removeChild(locationToDelete);    
    

}


function addTemplateLocation()
 {
 
     var allLocationElements = celltemplate_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:component4/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1/hl7-org_v3:timePointEventDefinition/hl7-org_v3:location",celltemplate_instance, nsResolver,    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
     var locationCount=allLocationElements.snapshotLength;
          if (locationCount >0)
            {
               alert("You can only define one location at a time !");
               return;
            }
     
 
   var parentElement = celltemplate_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:component4/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1/hl7-org_v3:timePointEventDefinition", celltemplate_instance, nsResolver,    XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
   
   //alert("PArent element is :"+ parentElement);
   
   var codeElements = celltemplate_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:component4/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1/hl7-org_v3:timePointEventDefinition/hl7-org_v3:code", celltemplate_instance, nsResolver,    XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;

 // alert("Code element is :"+ codeElements);
   
      var allComponent1Elements = celltemplate_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:component4/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1",celltemplate_instance, nsResolver,    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);

      
    var componentOfElements = celltemplate_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:component4/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1/hl7-org_v3:timePointEventDefinition/hl7-org_v3:componentOf1", celltemplate_instance, nsResolver,    XPathResult.FIRST_ORDERED_NODE_TYPE, null);
    
    var subjectOfElements = celltemplate_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:component4/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1/hl7-org_v3:timePointEventDefinition/hl7-org_v3:subjectOf", celltemplate_instance, nsResolver,    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
    
  var allPreConditionElements=celltemplate_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:component4/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1/hl7-org_v3:timePointEventDefinition/hl7-org_v3:precondition", celltemplate_instance, nsResolver,    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
          var totalPreConditions=allPreConditionElements.snapshotLength;
          

	
				             
				                     var totalcomponent1 = allComponent1Elements.snapshotLength;
				                     var totalSubjectOf = subjectOfElements.snapshotLength;
				               
				                     				                     
	//			          alert("totalComponent 1 under the segment are : " + totalcomponent1 + " And total characteristics are: "+totalSubjectOf + " Total Preconditions "+ totalPreConditions );
                                               if(totalcomponent1==0 && totalSubjectOf==0 && totalPreConditions==0)  //condition to insert before componentOf section.
                                                    {
                                   //                    alert("no components exist and no subject of elements exist Inserting before componentOf1");
                                                       var referenceElement=componentOfElements.singleNodeValue;
                                                     //  alert("reference element obtained: "+ referenceElement);
                                                      var elementToInsert = template_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:addLocation/hl7-org_v3:location" , template_instance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.cloneNode(true);

                                                        parentElement.insertBefore(elementToInsert,referenceElement);
                                                    }		
                                      		                     
				                            else if(totalPreConditions!=0)  //condition to insert before Preconditions
                                                    {
      //                                     alert("Preconditions Exist Inserting before PReconditions");
                                                   
                                                       var preConditionReferenceNode = allPreConditionElements.snapshotItem(0);
        //                                              alert("reference element obtained: "+ preConditionReferenceNode);
                                                   var elementToInsert = template_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:addLocation/hl7-org_v3:location" , template_instance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.cloneNode(true);
                                                     //   alert("element to insert obtained "+ elementToInsert);
                                                   
                                          
                                                        
                                                        parentElement.insertBefore(elementToInsert,preConditionReferenceNode);
                                                    }		
                                                                  		                     
				                     
                                                 else if(totalcomponent1!=0)  //condition to insert before component1 
                                                    {
          //                                  alert("Time Points exist Inserting before TimePoints");
                                                   
                                                       var component1referenceNode = allComponent1Elements.snapshotItem(0);
            //                                       alert("reference element obtained: "+ component1referenceNode);
                                                                        var elementToInsert = template_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:addLocation/hl7-org_v3:location" , template_instance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.cloneNode(true);

                                                     //   alert("element to insert obtained "+ elementToInsert);
                                                   
                                          
                                                        
                                                        parentElement.insertBefore(elementToInsert,component1referenceNode);
                                                    }		
                                                   else if(totalSubjectOf !=0) //condition to Insert before subject Of
                                                    {
              //                                    alert("Subject of exist but no time poitns exist");
                                                                                 
                                                       var subjectOfReferenceNode =  subjectOfElements.snapshotItem(0);
                                                           var elementToInsert = template_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:addLocation/hl7-org_v3:location" , template_instance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.cloneNode(true);
                                                 
                                                  parentElement.insertBefore(elementToInsert,subjectOfReferenceNode);

                                                    } 		                     				                     
		    
 }











function deleteTemplateTPCharacteristicsCells()
	{
	   var CellIndex = scratch_instance.getElementsByTagName("templateCellIndex") [0].textContent-1;
    var tpCharacteristicsIndex=scratch_instance.getElementsByTagName("templateTPCharacteristicsIndex") [0].textContent-1;
    
 //   alert("Cell index is :"+ CellIndex +" Precondition Index is :"+PreconditionIndex);
    
   var allExistingTemplateCells =   existing_template_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:component4/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1/hl7-org_v3:timePointEventDefinition",existing_template_instance, nsResolver,    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);    
   var relevantTemplateCell = allExistingTemplateCells.snapshotItem(CellIndex);
   
   //alert("Relevant cell obtained  " + relevantTemplateCell);
   
   var allExistingTPCharacteristicsCells = existing_template_instance.evaluate("hl7-org_v3:subjectOf",relevantTemplateCell, nsResolver,    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null); 
   
   var totalTPCharacteristics=allExistingTPCharacteristicsCells.snapshotLength;
   
   if(totalTPCharacteristics==0)
   {
       alert("Nothing to delete");
       return;
   }
   var tpCharToDelete = allExistingTPCharacteristicsCells.snapshotItem(tpCharacteristicsIndex);
   
      //  alert("Relevant element obtained  " + elementToDelete);

 tpCharToDelete.parentNode.removeChild(tpCharToDelete);    
    

	
	}






function addTemplateTPCharacteristicToExistingTemplate()
	{
	  var index = scratch_instance.getElementsByTagName("templateCellIndex") [0].textContent-1;
  // alert ("index to insert is :" + index);
   var allExistingCells  =   existing_template_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:component4/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1/hl7-org_v3:timePointEventDefinition",existing_template_instance, nsResolver,    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
    
  var parentCell = allExistingCells.snapshotItem(index);  
  //alert("Parent Cell is :"+ parentCell);
   

  
    var allComponentOf1Elements = existing_template_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:component4/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1/hl7-org_v3:timePointEventDefinition/hl7-org_v3:componentOf1", existing_template_instance, nsResolver,XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);   
    var referenceElement=allComponentOf1Elements.snapshotItem(index);

                      var elementToInsert = template_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:addNewTPCharacteristic/hl7-org_v3:subjectOf" , template_instance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.cloneNode(true);
								//	 alert("element to insert is :"+ elementToInsert);
											
											 parentCell.insertBefore(elementToInsert,referenceElement);
								   
   
	}


function deleteTemplatePreconditionCells()
{
    var CellIndex = scratch_instance.getElementsByTagName("templateCellIndex") [0].textContent-1;
    var PreconditionIndex=scratch_instance.getElementsByTagName("templatePreconditionIndex") [0].textContent-1;
    
 //   alert("Cell index is :"+ CellIndex +" Precondition Index is :"+PreconditionIndex);
    
   var allExistingTemplateCells =   existing_template_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:component4/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1/hl7-org_v3:timePointEventDefinition",existing_template_instance, nsResolver,    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);    
   var relevantTemplateCell = allExistingTemplateCells.snapshotItem(CellIndex);
   
   //alert("Relevant cell obtained  " + relevantTemplateCell);
   
   var allExistingPreconditionCells = existing_template_instance.evaluate("hl7-org_v3:precondition",relevantTemplateCell, nsResolver,    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null); 
   
   var totalPrecondition=allExistingPreconditionCells.snapshotLength;
   
   if(totalPrecondition==0)
   {
       alert("Nothing to delete");
       return;
   }
   var preconditionToDelete = allExistingPreconditionCells.snapshotItem(PreconditionIndex);
   
      //  alert("Relevant element obtained  " + elementToDelete);

preconditionToDelete.parentNode.removeChild(preconditionToDelete);    
    


}


function addTemplatePreconditionToExistingTemplate()
{

 var index = scratch_instance.getElementsByTagName("templateCellIndex") [0].textContent-1;
  //alert ("index to insert is :" + index);
   var allExistingCells  =   existing_template_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:component4/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1/hl7-org_v3:timePointEventDefinition",existing_template_instance, nsResolver,    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
    
  var parentCell = allExistingCells.snapshotItem(index);  
 // alert("Parent Cell is :"+ parentCell);
   
   var allElementCells=  existing_template_instance.evaluate("hl7-org_v3:component1", parentCell, nsResolver,    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);    
   var totalComponent1 =allElementCells.snapshotLength;
   
 //  alert("total component 1 are:" + totalComponent1);
   
       var allSubjectOfElements = existing_template_instance.evaluate("hl7-org_v3:subjectOf", parentCell, nsResolver,    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);   
  var totalSubjectOfElements = allSubjectOfElements.snapshotLength;
  				
  
//alert("Total characteristics under cell are " + totalSubjectOfElements);
  
    var allComponentOf1Elements = existing_template_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:component4/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1/hl7-org_v3:timePointEventDefinition/hl7-org_v3:componentOf1", existing_template_instance, nsResolver,XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);   
    
            	  if(totalComponent1 >0)  //insert before the component1 element
										  {  
									 //alert(" inserting before component1");
										   var referenceElement=allElementCells.snapshotItem(0);
									// alert("Reference segment is :"+referenceElement);
						               var elementToInsert = template_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:addNewPreCondition/hl7-org_v3:precondition" , template_instance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.cloneNode(true);

										
								// alert("element to insert is :"+ elementToInsert);
											
											 parentCell.insertBefore(elementToInsert,referenceElement);
										   }  
   
   	  else if(totalSubjectOfElements==0 && totalComponent1==0)  //insert before the componentof1 element
										  {  
									 //alert(" inserting before component of 1");
										   var referenceElement=allComponentOf1Elements.snapshotItem(index);
									//  alert("Reference segment is :"+referenceElement);
						               var elementToInsert = template_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:addNewPreCondition/hl7-org_v3:precondition" , template_instance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.cloneNode(true);

										
							//	 alert("element to insert is :"+ elementToInsert);
											
											 parentCell.insertBefore(elementToInsert,referenceElement);
										   }  
										   
	  else if(totalSubjectOfElements>0 && totalComponent1==0) //insert before subject of element
										 {
							//		alert("subject element exists ");
										  var referenceElement=  existing_template_instance.evaluate("hl7-org_v3:subjectOf" ,parentCell, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
							    // 	 alert("Reference Element: " + referenceElement);
                	    var elementToInsert = template_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:addNewPreCondition/hl7-org_v3:precondition" , template_instance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.cloneNode(true);

							//	alert("Element to insert :" + elementToInsert);
										 parentCell.insertBefore(elementToInsert,referenceElement);
										 }   									   
   
 
   
   
   
   
   
   
}



function deleteTemplateElementCells()
{
    var CellIndex = scratch_instance.getElementsByTagName("templateCellIndex") [0].textContent-1;
    var ElementIndex=scratch_instance.getElementsByTagName("templateElementIndex") [0].textContent-1;
    
   // alert("Cell index is :"+ CellIndex +" Element Index is :"+ElementIndex);
    
   var allExistingTemplateCells =   existing_template_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:component4/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1/hl7-org_v3:timePointEventDefinition",existing_template_instance, nsResolver,    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);    
   var relevantTemplateCell = allExistingTemplateCells.snapshotItem(CellIndex);
   
   //alert("Relevant cell obtained  " + relevantTemplateCell);
   
   var allExistingElementCells = existing_template_instance.evaluate("hl7-org_v3:component1",relevantTemplateCell, nsResolver,    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null); 
   
   var totalElements=allExistingElementCells.snapshotLength;
   
   if(totalElements==0)
   {
       alert("Nothing to delete");
       return;
   }
   
   var elementToDelete =  allExistingElementCells.snapshotItem(ElementIndex);
   
      //  alert("Relevant element obtained  " + elementToDelete);

 elementToDelete.parentNode.removeChild(elementToDelete);    
    


}









function addTemplateElementToExistingTemplate()
 {
   var index = scratch_instance.getElementsByTagName("templateCellIndex") [0].textContent-1;
  // alert ("index to insert is :" + index);
   var allExistingCells  =   existing_template_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:component4/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1/hl7-org_v3:timePointEventDefinition",existing_template_instance, nsResolver,    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
    
  var parentCell = allExistingCells.snapshotItem(index);  
  //alert("Parent Cell is :"+ parentCell);
   
       var allSubjectOfElements = existing_template_instance.evaluate("hl7-org_v3:subjectOf", parentCell, nsResolver,    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);   
  var totalSubjectOfElements = allSubjectOfElements.snapshotLength;
  				
  
//alert("Total characteristics under cell are " + totalSubjectOfElements);
  
    var allComponentOf1Elements = existing_template_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:component4/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1/hl7-org_v3:timePointEventDefinition/hl7-org_v3:componentOf1", existing_template_instance, nsResolver,XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);   
    
   
   	  if(totalSubjectOfElements==0)  //insert before the componentof1 element
										  {  
									 //alert("no subject of exists  therefore inserting before component of 1");
										   var referenceElement=allComponentOf1Elements.snapshotItem(index);
									 //  alert("Reference segment is :"+referenceElement);
						
											 var elementToInsert = tped_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:addNewTimePointEventDefinition/hl7-org_v3:component1" , tped_instance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.cloneNode(true);
								//	 alert("element to insert is :"+ elementToInsert);
											
											 parentCell.insertBefore(elementToInsert,referenceElement);
										   }  
										   
	  else if(totalSubjectOfElements>0) //insert before subject of element
										 {
									//alert("subject element exists ");
										  var referenceElement=  existing_template_instance.evaluate("hl7-org_v3:subjectOf" ,parentCell, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
							     //	 alert("Reference Element: " + referenceElement);
                	 var elementToInsert = tped_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:addNewTimePointEventDefinition/hl7-org_v3:component1" , tped_instance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.cloneNode(true);
									 //alert("Element to insert :" + elementToInsert);
										 parentCell.insertBefore(elementToInsert,referenceElement);
										 }   									   
   
 

 }






function addNewEligibilityCriterion()
{
 //  alert("Coming into the Eligbility Criteria");
   
    var allCriterion = build_Instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:precondition", build_Instance, nsResolver,    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);   
        var allEpochs = build_Instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:component1", build_Instance, nsResolver,    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);   
        var allArms = build_Instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:component2", build_Instance, nsResolver,    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);   
         var allCharacteristics = build_Instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:subjectOf", build_Instance, nsResolver,    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);   
var countEpochs=allEpochs.snapshotLength;
var countArms=allArms.snapshotLength;
var countCharacteristics=allCharacteristics.snapshotLength;
   
   var criterionCount = allCriterion.snapshotLength;
 //  alert ("Criterion :" + criterionCount);

				   if(criterionCount==0)
					  {
						   if(countEpochs>0)
								 insertFirstCriterion("component1");
							else if(countArms>0)
							     insertFirstCriterion("component2");
							else if(countCharacteristics>0)
							      insertFirstCriterion("subjectOf");   
							 else    	 
								 insertFirstCriterion(null);   
					  }
					else
					 {
					   positionalCriterionInsert();
					   }
	
   
}


function insertFirstCriterion(objectName)
    {
         //  alert("inside first insert function and the object name passed is" + objectName);
             var elementToInsert = template_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:addNewEligibilityCriteria/hl7-org_v3:precondition" , template_instance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.cloneNode(true);
             
             var str="/hl7-org_v3:plannedStudy/hl7-org_v3:"+objectName;
         //    alert(str);
            var parentElement= build_Instance.evaluate("/hl7-org_v3:plannedStudy",build_Instance, nsResolver,    XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
                 var referenceElement=build_Instance.evaluate(str,build_Instance, nsResolver,    XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
                 
             if(objectName==null)
					 {
				//	 alert("No object passed so append should work");
					 parentElement.appendChild(elementToInsert);
					 }
			else
			  {
			//   alert("string passed");
                                parentElement.insertBefore(elementToInsert,referenceElement);			   
			  }		 
  
    }

function positionalCriterionInsert()
{
  //alert("positional criterion insert");
   var index = scratch_instance.getElementsByTagName("criterionIndex") [0].textContent-1;
  // alert("Index to insert is :"+ index);
             var elementToInsert = template_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:addNewEligibilityCriteria/hl7-org_v3:precondition" , template_instance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.cloneNode(true);
        //     alert("Element to insert is " + elementToInsert);
             
             
            var parentElement= build_Instance.evaluate("/hl7-org_v3:plannedStudy",build_Instance, nsResolver,    XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
        //    alert("parent element is :"+ parentElement);
            var referenceElement=     build_Instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:precondition", build_Instance, nsResolver,XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null).snapshotItem(index);   
          //  alert("reference Element is :"+ referenceElement);
            
            parentElement.insertBefore(elementToInsert,referenceElement.nextSibling);

   
  
}



function addTemplateTimePointCharacteristic()
{
//alert("entering Characteristic add function");
   var parentElement = celltemplate_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:component4/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1/hl7-org_v3:timePointEventDefinition", celltemplate_instance, nsResolver,    XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
   
   //alert("Parent element is :"+ parentElement);
   
  
    var componentOfElements = celltemplate_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:component4/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1/hl7-org_v3:timePointEventDefinition/hl7-org_v3:componentOf1", celltemplate_instance, nsResolver,    XPathResult.FIRST_ORDERED_NODE_TYPE, null);
    
	               
                      var referenceElement=componentOfElements.singleNodeValue;
                 //    alert("reference element obtained: "+ referenceElement);
                      var elementToInsert = template_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:addNewTPCharacteristic/hl7-org_v3:subjectOf" , template_instance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.cloneNode(true);
                    parentElement.insertBefore(elementToInsert,referenceElement);
                                            
                      parentElement.insertBefore(elementToInsert,referenceElement);


}


function addTemplatePrecondition()
 {
//alert("entering segment Precondition");
   var parentElement = celltemplate_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:component4/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1/hl7-org_v3:timePointEventDefinition", celltemplate_instance, nsResolver,    XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
   
//   alert("PArent element is :"+ parentElement);
   
   var codeElements = celltemplate_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:component4/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1/hl7-org_v3:timePointEventDefinition/hl7-org_v3:code", celltemplate_instance, nsResolver,    XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;

 // alert("Code element is :"+ codeElements);
   
      var allComponent1Elements = celltemplate_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:component4/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1",celltemplate_instance, nsResolver,    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);

      
    var componentOfElements = celltemplate_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:component4/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1/hl7-org_v3:timePointEventDefinition/hl7-org_v3:componentOf1", celltemplate_instance, nsResolver,    XPathResult.FIRST_ORDERED_NODE_TYPE, null);
    
    var subjectOfElements = celltemplate_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:component4/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1/hl7-org_v3:timePointEventDefinition/hl7-org_v3:subjectOf", celltemplate_instance, nsResolver,    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
    

	
				             
				                     var totalcomponent1 = allComponent1Elements.snapshotLength;
				                     var totalSubjectOf = subjectOfElements.snapshotLength;
				                     				                     
				              //  alert("totalComponent 1 under the segment are : " + totalcomponent1 + " And total characteristics are: "+totalSubjectOf );
                                               if(totalcomponent1==0 && totalSubjectOf==0)  //condition to insert before componentOf section.
                                                    {
                                   //                    alert("no components exist and no subject of elements exist Inserting before componentOf1");
                                                       var referenceElement=componentOfElements.singleNodeValue;
                                                     //  alert("reference element obtained: "+ referenceElement);
                                                      var elementToInsert = template_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:addNewPreCondition/hl7-org_v3:precondition" , template_instance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.cloneNode(true);

                                                        parentElement.insertBefore(elementToInsert,referenceElement);
                                                    }				                     
				                     
                                                 else if(totalcomponent1!=0)  //condition to insert before component1 
                                                    {
                                     //                  alert("Time Points exist Inserting before TimePoints");
                                                   
                                                       var component1referenceNode = allComponent1Elements.snapshotItem(0);
                                                    //   alert("reference element obtained: "+ component1referenceNode);
                                                      var elementToInsert = template_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:addNewPreCondition/hl7-org_v3:precondition" , template_instance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.cloneNode(true);
                                                     //   alert("element to insert obtained "+ elementToInsert);
                                                   
                                          
                                                        
                                                        parentElement.insertBefore(elementToInsert,component1referenceNode);
                                                    }		
                                                   else if(totalSubjectOf !=0) //condition to Insert before subject Of
                                                    {
                                       //              alert("Subject of exist but no time poitns exist");
                                                                                 
                                                       var subjectOfReferenceNode =  subjectOfElements.snapshotItem(0);
                                                     var elementToInsert = template_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:addNewPreCondition/hl7-org_v3:precondition" , template_instance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.cloneNode(true);
                                                 
                                                  parentElement.insertBefore(elementToInsert,subjectOfReferenceNode);

                                                    } 		                     				                     
		    
 }







function addTemplateElement()
 {
 //  alert("Coming into the function");
  
    var parentCell = celltemplate_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:component4/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1/hl7-org_v3:timePointEventDefinition",celltemplate_instance, nsResolver,    XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
    
   // alert("parent cell created: " + parentCell);
    var allElements = celltemplate_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:component4/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1", celltemplate_instance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
    var totalElements=allElements.snapshotLength;
    

    var allSubjectOfElements = celltemplate_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:component4/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1/hl7-org_v3:timePointEventDefinition/hl7-org_v3:subjectOf", celltemplate_instance, nsResolver,    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);   
  var totalCharacteristics = allSubjectOfElements.snapshotLength;
  
  
  
  
 //   alert(" total Elements are :"+ totalElements + "  total characteristics are: " + totalCharacteristics);
    var componentOf1Element = celltemplate_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:component4/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1/hl7-org_v3:timePointEventDefinition/hl7-org_v3:componentOf1", celltemplate_instance, nsResolver,    XPathResult.FIRST_ORDERED_NODE_TYPE, null);   

   var totalSubjectOfElements =allSubjectOfElements.snapshotLength;
				                
										  if(totalSubjectOfElements==0)  //insert before the componentof1 element
										  {  
								//		  alert("no subject of exists  therefore inserting before component of 1");
										   var referenceElement=componentOf1Element.singleNodeValue;
									//	   alert("Reference segment is :"+referenceElement);
									//		alert("reference Segment " + referenceSegment);
											 var elementToInsert = tped_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:addNewTimePointEventDefinition/hl7-org_v3:component1" , tped_instance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.cloneNode(true);
											  parentCell.insertBefore(elementToInsert,referenceElement);
									
										   }  
				             else if(totalSubjectOfElements>0) //insert before subject of element
										 {
										//  alert("subeject element exists ");
										  var referenceElement=  celltemplate_instance.evaluate("hl7-org_v3:subjectOf" ,parentCell, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
							     		//  alert("Reference Element: " + referenceElement);
                	 var elementToInsert = tped_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:addNewTimePointEventDefinition/hl7-org_v3:component1" , tped_instance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.cloneNode(true);
								//			 alert("Element to insert :" + elementToInsert);
											
										   //  alert("match found :" + " reference segment: " + referenceSegment +" elementToInsert " + elementToInsert);
												 parentCell.insertBefore(elementToInsert,referenceElement);
											
										 }   
			 
			

 }






function checkDuplicateExists(epochName,armName)
 {
 
       var allCells= build_Instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:component4/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1",build_Instance,nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);    
      //   alert("count of cells is " + allCells.snapshotLength);
        duplicateexists=false;
  
          var cellCount = allCells.snapshotLength;      
          for(var i=0;i<cellCount;i++)
           {
                           var epochStub = getAttributevalue("/hl7-org_v3:plannedStudy/hl7-org_v3:component4/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1/hl7-org_v3:timePointEventDefinition/hl7-org_v3:componentOf1/hl7-org_v3:epochStub/hl7-org_v3:id",i,"extension");
                           var armStub = getAttributevalue("/hl7-org_v3:plannedStudy/hl7-org_v3:component4/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1/hl7-org_v3:timePointEventDefinition/hl7-org_v3:componentOf2/hl7-org_v3:armStub/hl7-org_v3:id",i,"extension");
                           if (epochStub==epochName && armStub==armName)
                              {
                                duplicateexists=true;
                                 matchfoundindex=i;
                                 var  choice = confirm("A Cell already exists in the location that you are trying to insert into. Would you like to overwrite the previous cell? ");
                               
                                 return choice;
                              }
           }
        
 }
 





function insertComponent4()
{
 // alert("coming into function");
  var component4count =  countChildElements("component4");
           if (component4count==0)
				   {
				     	var newElement=  getNodesetTemplate("addComponent4", "component4");
						var parentElement = build_Instance.evaluate("/hl7-org_v3:plannedStudy", build_Instance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
					
						var allCharacteristicNodes =build_Instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:subjectOf", build_Instance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
						var referenceElement = allCharacteristicNodes.snapshotItem(0);
					//	var elementToInsert= referenceElement.singleNodeValue;
						parentElement.insertBefore(newElement,referenceElement);
				   }  
		var totalCellsSnapshot = build_Instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:component4/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1" , build_Instance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null); 
		var totalCells = totalCellsSnapshot.snapshotLength;
		if (totalCells==0)
		        scratch_instance.getElementsByTagName("ScheduleExists") [0].childNodes[0].nodeValue ="No";
		 else
		     scratch_instance.getElementsByTagName("ScheduleExists") [0].childNodes[0].nodeValue ="Yes";         
		         
		//alert ("At present " +  totalCells + " cells exist	And the value of Schedule exists has been set to " +scratch_instance.getElementsByTagName("ScheduleExists") [0].childNodes[0].nodeValue  );	   
  
}










function deleteTimePointCharacteristic()
{
// alert("Characteristic index  number is: "+ scratch_instance.getElementsByTagName("TimePointCharacteristicToDelete")[0].childNodes[0].nodeValue +" And the segment in focus is :"+ scratch_instance.getElementsByTagName("CharacteristicSegmentInFocus")[0].childNodes[0].nodeValue);

    var allTimePointSegments = build_Instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:component4/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1/hl7-org_v3:timePointEventDefinition", build_Instance, nsResolver,    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
    var allComponentOfElements = build_Instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:component4/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1/hl7-org_v3:timePointEventDefinition/hl7-org_v3:componentOf1", build_Instance, nsResolver,    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
    var totalSegments=allTimePointSegments.snapshotLength;
 // alert("Index in Focus is: "+ scratch_instance.getElementsByTagName("CharacteristicSegmentInFocus")[0].childNodes[0].nodeValue + " And total Elements are :"+ totalSegments);
     
     
     for(segmentNumber=0;segmentNumber<totalSegments;segmentNumber++)
				 {
				         
				        var epochStubValue = getAttributevalue("/hl7-org_v3:plannedStudy/hl7-org_v3:component4/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1/hl7-org_v3:timePointEventDefinition/hl7-org_v3:componentOf1/hl7-org_v3:epochStub/hl7-org_v3:id",segmentNumber,"extension");
				       if ( scratch_instance.getElementsByTagName("CharacteristicSegmentInFocus")[0].childNodes[0].nodeValue == epochStubValue )
				             { 
				                var SegmentNode= allTimePointSegments.snapshotItem(segmentNumber);
				                 var allSubjectOfElements = build_Instance.evaluate("hl7-org_v3:subjectOf" ,SegmentNode, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
				        //         alert("Total number of characteristic elements are : " + allSubjectOfElements.snapshotLength);
				                     if(allSubjectOfElements.snapshotLength ==  0 )
				                       {
				                        alert("There are no Characteristics to delete.");
				                          return;
				                       }
				                 if(allSubjectOfElements.snapshotLength >  0 && scratch_instance.getElementsByTagName("CharacteristicSegmentInFocus")[0].childNodes[0].nodeValue ==0)
				                       {
				                        alert("You have not selected any Characteristic to Delete. Please click on the row you'd like to delete and try again ");
				                          return;
				                       }
				                  else
				                  {
				                  
				                   var indexToDelete= scratch_instance.getElementsByTagName("TimePointCharacteristicToDelete")[0].childNodes[0].nodeValue-1;
				                    var nodeToDelete = allSubjectOfElements.snapshotItem(indexToDelete);
				                    nodeToDelete.parentNode.removeChild(nodeToDelete); 
				                  }    
				                 
				                 
				             }     
				  } 
 }


function deletePrecondition()
{
 //alert("Precondition index  number is: "+ scratch_instance.getElementsByTagName("preconditionToDelete")[0].childNodes[0].nodeValue +" And the segment in focus is :"+ scratch_instance.getElementsByTagName("SegmentInFocus")[0].childNodes[0].nodeValue);

    var allTimePointSegments = build_Instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:component4/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1/hl7-org_v3:timePointEventDefinition", build_Instance, nsResolver,    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
    var allComponentOfElements = build_Instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:component4/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1/hl7-org_v3:timePointEventDefinition/hl7-org_v3:componentOf1", build_Instance, nsResolver,    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
    var totalSegments=allTimePointSegments.snapshotLength;
  //alert("Index in Focus is: "+ scratch_instance.getElementsByTagName("SegmentInFocus")[0].childNodes[0].nodeValue + " And total Elements are :"+ totalSegments);
     
     
     for(segmentNumber=0;segmentNumber<totalSegments;segmentNumber++)
				 {
				         
				        var epochStubValue = getAttributevalue("/hl7-org_v3:plannedStudy/hl7-org_v3:component4/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1/hl7-org_v3:timePointEventDefinition/hl7-org_v3:componentOf1/hl7-org_v3:epochStub/hl7-org_v3:id",segmentNumber,"extension");
				       if ( scratch_instance.getElementsByTagName("SegmentInFocus")[0].childNodes[0].nodeValue == epochStubValue )
				             { 
				                var SegmentNode= allTimePointSegments.snapshotItem(segmentNumber);
				                 var allPreConditionElements = build_Instance.evaluate("hl7-org_v3:precondition" ,SegmentNode, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
				            //     alert("Total number of precondition elements are : " + allPreConditionElements.snapshotLength);
				                     if(allPreConditionElements.snapshotLength ==  0 )
				                       {
				                        alert("There are no PreConditions to delete.");
				                          return;
				                       }
				                 if(allPreConditionElements.snapshotLength >  0 && scratch_instance.getElementsByTagName("preconditionToDelete")[0].childNodes[0].nodeValue ==0)
				                       {
				                        alert("You have not selected any PreCondition to Delete. Please click on the row you'd like to delete and try again ");
				                          return;
				                       }
				                  else
				                  {
				                   var indexToDelete= scratch_instance.getElementsByTagName("preconditionToDelete")[0].childNodes[0].nodeValue-1;
				                    var nodeToDelete = allPreConditionElements.snapshotItem(indexToDelete);
				                    nodeToDelete.parentNode.removeChild(nodeToDelete); 
				                  }    
				                 
				                 
				             }     
				  } 
}

function addSegmentPrecondition()
 {
//alert("entering segment Precondition");
   var allCodeElements = build_Instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:component4/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1/hl7-org_v3:timePointEventDefinition/hl7-org_v3:code", build_Instance, nsResolver,    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
    var totalCodeElements= allCodeElements.snapshotLength;
 //  alert("Index number is: "+ scratch_instance.getElementsByTagName("preconditionIndex")[0].childNodes[0].nodeValue +"Index in Focus is: "+ scratch_instance.getElementsByTagName("PreconditionSegmentInFocus")[0].childNodes[0].nodeValue + "  Total Code elements are :" + totalCodeElements );
   
      var allSegments = build_Instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:component4/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1/hl7-org_v3:timePointEventDefinition", build_Instance, nsResolver,    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
      
    var allComponentOfElements = build_Instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:component4/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1/hl7-org_v3:timePointEventDefinition/hl7-org_v3:componentOf1", build_Instance, nsResolver,    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
    
    var allSubjectOfElements = build_Instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:component4/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1/hl7-org_v3:timePointEventDefinition/hl7-org_v3:subjectOf", build_Instance, nsResolver,    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
    
				   
				for(i=0;i<totalCodeElements;i++)
				  {
				              var epochStubValue = getAttributevalue("/hl7-org_v3:plannedStudy/hl7-org_v3:component4/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1/hl7-org_v3:timePointEventDefinition/hl7-org_v3:componentOf1/hl7-org_v3:epochStub/hl7-org_v3:id",i,"extension");
                                  if ( scratch_instance.getElementsByTagName("PreconditionSegmentInFocus")[0].childNodes[0].nodeValue == epochStubValue )
				                  {
				                    var segmentReference=allSegments.snapshotItem(i).cloneNode(true);
				                   // alert("segment reference is :" + segmentReference);
				                     var totalcomponent1 = segmentReference.getElementsByTagName("component1").length;
				                     var totalSubjectOf = segmentReference.getElementsByTagName("subjectOf").length;
				                 //     alert("totalComponent 1 under the segment are : " + totalcomponent1 + " And total characteristics are: "+totalSubjectOf );
                                               if(totalcomponent1==0 && totalSubjectOf==0)  //condition to insert before componentOf section.
                                                    {
                                   //                    alert("no components exist and no subject of elements exist Inserting before componentOf1");
                                                       var referenceElement=allComponentOfElements.snapshotItem(i);
                                                     //  alert("reference element obtained: "+ referenceElement);
                                                      var elementToInsert = template_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:addNewPreCondition/hl7-org_v3:precondition" , template_instance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.cloneNode(true);
                                                     //   alert("element to insert obtained "+ elementToInsert);
                                                        var parentElement=allSegments.snapshotItem(i);
                                                  //      alert("PArent element is : " + parentElement);
                                                        
                                                        parentElement.insertBefore(elementToInsert,referenceElement);
                                                    }				                     
				                     
                                                 else if(totalcomponent1!=0)  //condition to insert before component1 
                                                    {
                                     //                  alert("Time Points exist Inserting before TimePoints");
                                                       var SegmentNode=allSegments.snapshotItem(i);
                                                       var component1referenceNode = build_Instance.evaluate("hl7-org_v3:component1" ,SegmentNode, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
                                                    //   alert("reference element obtained: "+ component1referenceNode);
                                                      var elementToInsert = template_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:addNewPreCondition/hl7-org_v3:precondition" , template_instance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.cloneNode(true);
                                                     //   alert("element to insert obtained "+ elementToInsert);
                                                        var parentElement=allSegments.snapshotItem(i);
                                                       // alert("PArent element is : " + parentElement);
                                                        
                                                        parentElement.insertBefore(elementToInsert,component1referenceNode);
                                                    }		
                                                   else if(totalSubjectOf !=0) //condition to Insert before subject Of
                                                    {
                                       //              alert("Subject of exist but no time poitns exist");
                                                       var SegmentNode=allSegments.snapshotItem(i);                                         
                                                       var subjectOfReferenceNode =  build_Instance.evaluate("hl7-org_v3:subjectOf" ,SegmentNode, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
                                                     var elementToInsert = template_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:addNewPreCondition/hl7-org_v3:precondition" , template_instance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.cloneNode(true);
                                                   var parentElement=allSegments.snapshotItem(i);
                                                  parentElement.insertBefore(elementToInsert,subjectOfReferenceNode);

                                                    } 		                     				                     
		                     
				                  }				              
				  }
  
 }







function addTimePointEvent()
 {
   
  
    var allTimePointSegments = build_Instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:component4/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1/hl7-org_v3:timePointEventDefinition", build_Instance, nsResolver,    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
    var allComponentOfElements = build_Instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:component4/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1/hl7-org_v3:timePointEventDefinition/hl7-org_v3:componentOf1", build_Instance, nsResolver,    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
    var totalSegments=allTimePointSegments.snapshotLength;
  //alert("Index in Focus is: "+ scratch_instance.getElementsByTagName("SegmentInFocus")[0].childNodes[0].nodeValue + " And total Elements are :"+ totalSegments);
    var allSubjectOfElements = build_Instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:component4/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1/hl7-org_v3:timePointEventDefinition/hl7-org_v3:subjectOf", build_Instance, nsResolver,    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);   

     for(segmentNumber=0;segmentNumber<totalSegments;segmentNumber++)
				 {
				         
				        var epochStubValue = getAttributevalue("/hl7-org_v3:plannedStudy/hl7-org_v3:component4/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1/hl7-org_v3:timePointEventDefinition/hl7-org_v3:componentOf1/hl7-org_v3:epochStub/hl7-org_v3:id",segmentNumber,"extension");
				       if ( scratch_instance.getElementsByTagName("SegmentInFocus")[0].childNodes[0].nodeValue == epochStubValue )
				             {
				            
				                var parentSegment=allTimePointSegments.snapshotItem(segmentNumber);
				                     var totalSubjectOf =parentSegment.getElementsByTagName("subjectOf").length;
				                
										  if(totalSubjectOf==0)  //insert before the componentof1 element
										  {  
										 //  alert("no subject of exist");
											var referenceSegment=allComponentOfElements.snapshotItem(segmentNumber);
									//		alert("reference Segment " + referenceSegment);
											 var elementToInsert = tped_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:addNewTimePointEventDefinition/hl7-org_v3:component1" , tped_instance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.cloneNode(true);
											
										   //  alert("match found :" + " reference segment: " + referenceSegment +" elementToInsert " + elementToInsert);
											 parentSegment.insertBefore(elementToInsert,referenceSegment);
										   }  
				             else if(totalSubjectOf>0) //insert before subject of element
										 {
										  //alert("subeject element exists ");
										  var referenceElement=  build_Instance.evaluate("hl7-org_v3:subjectOf" ,parentSegment, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
							//			  alert("Reference Element: " + referenceElement);
											 var elementToInsert = tped_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:addNewTimePointEventDefinition/hl7-org_v3:component1" , tped_instance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.cloneNode(true);
								//			 alert("Element to insert :" + elementToInsert);
											
										   //  alert("match found :" + " reference segment: " + referenceSegment +" elementToInsert " + elementToInsert);
											 parentSegment.insertBefore(elementToInsert,referenceElement);
										 }   
				             }     
				  }

 }




function addSegmentCharacteristics()
		{
	//	    alert("entering segment Characteristics insert");
		//    alert("Index number is: "+ scratch_instance.getElementsByTagName("TPCharacteristicIndex")[0].childNodes[0].nodeValue +"  Index in Focus is: "+ scratch_instance.getElementsByTagName("CharacteristicSegmentInFocus")[0].childNodes[0].nodeValue );
             var allComponentOfElements = build_Instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:component4/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1/hl7-org_v3:timePointEventDefinition/hl7-org_v3:componentOf1", build_Instance, nsResolver,    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
                   var allSegments = build_Instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:component4/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1/hl7-org_v3:timePointEventDefinition", build_Instance, nsResolver,    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
            
                var totalSegments=allSegments.snapshotLength;
                for(i=0;i<totalSegments;i++)
                    {
                        var epochStubValue = getAttributevalue("/hl7-org_v3:plannedStudy/hl7-org_v3:component4/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1/hl7-org_v3:timePointEventDefinition/hl7-org_v3:componentOf1/hl7-org_v3:epochStub/hl7-org_v3:id",i,"extension");
                        
                       if ( scratch_instance.getElementsByTagName("CharacteristicSegmentInFocus")[0].childNodes[0].nodeValue == epochStubValue )
                          {
                          
                           var parentSegment=allSegments.snapshotItem(i);
                           //alert("Parent segment :" + parentSegment);
                           var referenceElement=allComponentOfElements.snapshotItem(i);
                           //alert("reference segment :" + referenceElement);
                           var nodeSetToInsert =  template_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:addNewTPCharacteristic/hl7-org_v3:subjectOf" , template_instance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.cloneNode(true);
                           //alert("Node Set to Insert :"+ nodeSetToInsert);
                           
                           parentSegment.insertBefore(nodeSetToInsert,referenceElement);
                          }                        
                        
                        
                    }

		}

function deletePrecondition()
{
 //alert("Precondition index  number is: "+ scratch_instance.getElementsByTagName("preconditionToDelete")[0].childNodes[0].nodeValue +" And the segment in focus is :"+ scratch_instance.getElementsByTagName("SegmentInFocus")[0].childNodes[0].nodeValue);

    var allTimePointSegments = build_Instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:component4/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1/hl7-org_v3:timePointEventDefinition", build_Instance, nsResolver,    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
    var allComponentOfElements = build_Instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:component4/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1/hl7-org_v3:timePointEventDefinition/hl7-org_v3:componentOf1", build_Instance, nsResolver,    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
    var totalSegments=allTimePointSegments.snapshotLength;
  //alert("Index in Focus is: "+ scratch_instance.getElementsByTagName("SegmentInFocus")[0].childNodes[0].nodeValue + " And total Elements are :"+ totalSegments);
     
     
     for(segmentNumber=0;segmentNumber<totalSegments;segmentNumber++)
				 {
				         
				        var epochStubValue = getAttributevalue("/hl7-org_v3:plannedStudy/hl7-org_v3:component4/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1/hl7-org_v3:timePointEventDefinition/hl7-org_v3:componentOf1/hl7-org_v3:epochStub/hl7-org_v3:id",segmentNumber,"extension");
				       if ( scratch_instance.getElementsByTagName("SegmentInFocus")[0].childNodes[0].nodeValue == epochStubValue )
				             { 
				                var SegmentNode= allTimePointSegments.snapshotItem(segmentNumber);
				                 var allPreConditionElements = build_Instance.evaluate("hl7-org_v3:precondition" ,SegmentNode, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
				            //     alert("Total number of precondition elements are : " + allPreConditionElements.snapshotLength);
				                     if(allPreConditionElements.snapshotLength ==  0 )
				                       {
				                        alert("There are no PreConditions to delete.");
				                          return;
				                       }
				                 if(allPreConditionElements.snapshotLength >  0 && scratch_instance.getElementsByTagName("preconditionToDelete")[0].childNodes[0].nodeValue ==0)
				                       {
				                        alert("You have not selected any PreCondition to Delete. Please click on the row you'd like to delete and try again ");
				                          return;
				                       }
				                  else
				                  {
				                   var indexToDelete= scratch_instance.getElementsByTagName("preconditionToDelete")[0].childNodes[0].nodeValue-1;
				                    var nodeToDelete = allPreConditionElements.snapshotItem(indexToDelete);
				                    nodeToDelete.parentNode.removeChild(nodeToDelete); 
				                  }    
				                 
				                 
				             }     
				  } 
}






function deleteTimePoint()
{
 //alert("Time Point Index number is: "+ scratch_instance.getElementsByTagName("timePointEventDefinitionToDelete")[0].childNodes[0].nodeValue +" And the segment in focus is :"+ scratch_instance.getElementsByTagName("SegmentInFocus")[0].childNodes[0].nodeValue);

    var allTimePointSegments = build_Instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:component4/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1/hl7-org_v3:timePointEventDefinition", build_Instance, nsResolver,    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
    var allComponentOfElements = build_Instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:component4/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1/hl7-org_v3:timePointEventDefinition/hl7-org_v3:componentOf1", build_Instance, nsResolver,    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
    var totalSegments=allTimePointSegments.snapshotLength;
  //alert("Index in Focus is: "+ scratch_instance.getElementsByTagName("SegmentInFocus")[0].childNodes[0].nodeValue + " And total Elements are :"+ totalSegments);
     
     
     for(segmentNumber=0;segmentNumber<totalSegments;segmentNumber++)
				 {
				         
				        var epochStubValue = getAttributevalue("/hl7-org_v3:plannedStudy/hl7-org_v3:component4/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1/hl7-org_v3:timePointEventDefinition/hl7-org_v3:componentOf1/hl7-org_v3:epochStub/hl7-org_v3:id",segmentNumber,"extension");
				       if ( scratch_instance.getElementsByTagName("SegmentInFocus")[0].childNodes[0].nodeValue == epochStubValue )
				             { 
				                var SegmentNode= allTimePointSegments.snapshotItem(segmentNumber);
				                 var allComponent1Elements = build_Instance.evaluate("hl7-org_v3:component1" ,SegmentNode, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
				            //     alert("Total number of component1 elements are : " + allComponent1Elements.snapshotLength);
				                     if(allComponent1Elements.snapshotLength ==  0 )
				                       {
				                        alert("There are no time points to delete.");
				                          return;
				                       }
				                 if(allComponent1Elements.snapshotLength >  0 && scratch_instance.getElementsByTagName("timePointEventDefinitionToDelete")[0].childNodes[0].nodeValue ==0)
				                       {
				                        alert("You have not selected any Time Point to Delete. Please click on the row you'd like to delete and try again ");
				                          return;
				                       }
				                  else
				                  {
				                   var indexToDelete= scratch_instance.getElementsByTagName("timePointEventDefinitionToDelete")[0].childNodes[0].nodeValue-1;
				                    var nodeToDelete = allComponent1Elements.snapshotItem(indexToDelete);
				                    nodeToDelete.parentNode.removeChild(nodeToDelete); 
				                  }    
				                 
				                 
				             }     
				  } 
 
 
 
 
 
}

function reviewModePreconditions()
 {
 alert("You are currently in 'Review Mode'. You cannot insert or delete segment preconditions if you have a filter selected in the 'Filter For Review' section. Please delete any text from the filter box and try inserting again.");
}

function reviewModeCharacteristics()
 {
 alert("You are currently in 'Review Mode'. You cannot insert or delete segment Characteristics if you have a filter selected in the 'Filter For Review' section. Please delete any text from the filter box and try inserting again.");
}




function reviewMode()
 {
 alert("You are currently in 'Review Mode'. You cannot  delete cells if you have a filter selected in the 'Filter For Review' section. Please delete any text from the filter box and try inserting again.");
}

function doesGLPCharacteristicExist()
{

				 var valuefound= scratch_instance.getElementsByTagName("GLPValue") [0].childNodes[0].nodeValue;
								//	 alert( "coming into the GLP function" + "  Value found = " +valuefound );
 
 var allCharacteristicsForGLP =  build_Instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:subjectOf",build_Instance,nsResolver,XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
 var countCharacteristicsForGLP = allCharacteristicsForGLP.snapshotLength;
//alert("number of characteristics : "+ countCharacteristicsForGLP);
			 if(countCharacteristicsForGLP==0) //if no characteristic records exist then GLP can be added to the first position
				 {
                   appendGLP();
				 }
			else  { // characteristic records exist so we first need to check if GLP has been previously added. If no match is found then add GLP characteristic. Otherwise do nothing except change value to radio button group value.
		 //alert ("More characteristics exist so need to check if GLP Characteristic has been added previously");
			    var glpfound="No";
								 for (var i=0; i<countCharacteristicsForGLP;i++)
									  {
										var characteristicCode = getAttributevalue("/hl7-org_v3:plannedStudy/hl7-org_v3:subjectOf/hl7-org_v3:studyCharacteristic/hl7-org_v3:code",i,"code");
										 if (characteristicCode=="GLP")
											  {
												 
												 glpfound="Yes";
			 		 allCharacteristicsForGLP.snapshotItem(i).getElementsByTagName("value") [0].childNodes[0].nodeValue = scratch_instance.getElementsByTagName("GLPValue") [0].childNodes[0].nodeValue;
									 
											  }            
									   }
                   if(glpfound=="No")
                    {
                  appendGLP()
                    }                       
                       
			}	
			
	  
 
}




function appendGLP()
{
                   
				   var glpparentNode=build_Instance.evaluate("/hl7-org_v3:plannedStudy", build_Instance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;

				   var glpnodeSetToInsert = glp_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:addNewStudyCharacteristic/hl7-org_v3:subjectOf", glp_instance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.cloneNode(true);
		       	   glpnodeSetToInsert.getElementsByTagName("value") [0].childNodes[0].nodeValue = scratch_instance.getElementsByTagName("GLPValue") [0].childNodes[0].nodeValue;

				   glpparentNode.appendChild(glpnodeSetToInsert);
}







/**************************************************************************************************/


function insertFirstPositionStudyType()
{
try {
				var nodeSets = typeofstudy_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:" + "addNewStudyCharacteristic" + "/hl7-org_v3:" +  "subjectOf", typeofstudy_instance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
				var newObject = nodeSets.singleNodeValue.cloneNode(true); 
				var parentElement = build_Instance.evaluate("/hl7-org_v3:plannedStudy", build_Instance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
				//var indextoInsert = scratch_instance.getElementsByTagName("studycharacteristicsindex") [0].textContent-1;
				var allCharacteristicsNodes =build_Instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:subjectOf", build_Instance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
				var referenceElement = allCharacteristicsNodes.snapshotItem(0);
				var elementToInsert= referenceElement.singleNodeValue;
				parentElement.insertBefore(newObject,referenceElement);
									scratch_instance.getElementsByTagName("totalstudycharacteristics") [0].childNodes[0].nodeValue +=1;
					    scratch_instance.getElementsByTagName("studycharacteristicsindex") [0].childNodes[0].nodeValue +=1;
				
				}catch(err) { }
    

}







function characteristicsInsert()
{
//alert( "Value of characteristics index is " + scratch_instance.getElementsByTagName("subjectOfindex") [0].childNodes[0].nodeValue) ;
var index=scratch_instance.getElementsByTagName("subjectOfindex") [0].childNodes[0].nodeValue;
var allCharacteristics = build_Instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:subjectOf",build_Instance,nsResolver,XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
var countCharacteristics = allCharacteristics.snapshotLength;
//alert ("Total Characteristics are : " + countCharacteristics);
if (countCharacteristics ==0)
           {
             add_StudyCharacteristics();
           }
  else
        {
           addPositionalCharacteristics(index);
        }         


}

function addPositionalCharacteristics(index) {
                       //alert("Coming into the function");
						
						
						var parentElement = build_Instance.evaluate("/hl7-org_v3:plannedStudy", build_Instance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
				//		alert("parent element is:"+ parentElement);
						var indextoInsert = scratch_instance.getElementsByTagName("subjectOfindex") [0].textContent-1;
					//	alert("index to insert is :"+indextoInsert);
						var allCharacteristicsNodes =build_Instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:subjectOf", build_Instance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
				//		alert("Total characteristics are:"+ allCharacteristicsNodes.snapshotLength);
						var referenceElement = allCharacteristicsNodes.snapshotItem(index-1);
					//	alert("Reference Element :"+ referenceElement);
						var elementToInsert=template_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:addNewStudyCharacteristic/hl7-org_v3:subjectOf" , template_instance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.cloneNode(true);
				//		alert("element to Insert::"+ elementToInsert);
						parentElement.insertBefore(elementToInsert,referenceElement.nextSibling);
	
			


}

function add_StudyCharacteristics() {
try{
 var Path = getXPath();

 var newObject = getNodesetTemplate("addNewStudyCharacteristic", "subjectOf");
 Path.appendChild(newObject);
  //alert("Javascript Insert ");
    }catch(err)
    {}
} 

  function insertPositionalSegments(epochname,armname,sequenceNumber,allcomponents,allEpochStubs)
      {
 	     var parentElement = build_Instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:component4/hl7-org_v3:timePointEventDefinition", build_Instance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
      //   var segmentToInsert = template_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:component4/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1" , template_instance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.cloneNode(true);
          var positiontoInsert = 0;    
          var referenceSegment =allcomponents.snapshotItem(positiontoInsert);       
          var segmentToInsert =null;
  //       alert("Total segments existing are:" + allcomponents.snapshotLength);

          for(var count=0;count<allcomponents.snapshotLength;count++)  //Loop to find position to which the element needs to be inserted.
								  {
                                        
                                   var epochinfocus =allEpochStubs.snapshotItem(count).getAttributeNode("extension").childNodes[0].nodeValue; 
									   									
                                     if(epochinfocus==epochname)
                                           {
                                         
                                             positiontoInsert=count;
                                            referenceSegment=allcomponents.snapshotItem(positiontoInsert);
                                             segmentToInsert = allcomponents.snapshotItem(positiontoInsert).cloneNode(true);
                                           // alert("Segment to Insert Created :" +  segmentToInsert);
                                           
                                           }									 
         						  }

           var numberOfIDElements = segmentToInsert.getElementsByTagName("id").length;
           
         //   alert (" Number of ID Elements under the segment are : " + numberOfIDElements);
            setAttributevalue(segmentToInsert,"id",numberOfIDElements-1,"extension",armname); 
            setAttributevalue(segmentToInsert,"id",numberOfIDElements-2,"extension",epochname); 
             setAttributevalue(segmentToInsert,"sequenceNumber",0,"value",sequenceNumber); 
             //alert("Insert shoudl happen after position :" + positiontoInsert);
             parentElement.insertBefore(segmentToInsert,referenceSegment.nextSibling);
             
            
         }    

/*
function countChildElements(child)
{
       testing_instance = model.getInstanceDocument("plannedStudyInstance");

       var childCount=testing_instance.getElementsByTagName(child);
       return childCount.length;
}
*/
         
 function countChildElements(child)
{
       var componentcount = build_Instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:"+child , build_Instance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
       return componentcount.snapshotLength;
}

function countChildElementsUnderParent(parent,child)
{
       var componentcount = build_Instance.evaluate(parent+child , build_Instance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
       return componentcount.snapshotLength;
}

 function setAttributevalue(object,subobject,index,attributeName,value)// Function to set value of an attribute element inside a subobject .Subobject is located under the object. Index is the index of the subobject inside the path
{
  
     object.getElementsByTagName(subobject) [index].getAttributeNode(attributeName).nodeValue=value;   
          
}       
         
           
 function getAttributevalue(path,index,attributeName) // Function to retrieve value of an attribute element inside a section. If there are several nodes the index is used to specify which nodes attribute needs to be retrieved.
{
   try{ var allreferenceElements = build_Instance.evaluate(path , build_Instance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
     var singlereferenceElement=allreferenceElements.snapshotItem(index);
     var attributeNode=singlereferenceElement.getAttributeNode(attributeName);
     var attributeName = attributeNode.childNodes[0].nodeValue;
     return attributeName;     
    } 
    catch(err)
    {
       alert("Please verifiy that you've populate all mandatory fields. Mandatory fields are marked with an '*' ");
       return " ";
    }
          
}
           
           
function appendSegments(epochname,armname)
      {
                                    var xPath = build_Instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:component4/hl7-org_v3:timePointEventDefinition", build_Instance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
                                    var Path = xPath.singleNodeValue;	
                                    var nodeSets = template_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:component4/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1" , template_instance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
                                     var newObject = nodeSets.singleNodeValue.cloneNode(true);
                                      newObject.getElementsByTagName("id") [1].getAttributeNode("extension").nodeValue=epochname;  /*This line sets the value of the second 'ID' element in the Object - which is from epoch stub to the value of the epoch name*/
                                       setAttributevalue(newObject,"id",2,"extension",armname);   /*This line sets the value of the third 'ID' element in the Object - which is from arm stub to the value of the arm name.However a function is used instead*/     
                                        Path.appendChild(newObject);
                                       return newObject;

              
     }








function setAttributevalue(object,subobject,index,attributeName,value)// Function to set value of an attribute element inside a subobject .Subobject is located under the object. Index is the index of the subobject inside the path
{
  try{
     object.getElementsByTagName(subobject) [index].getAttributeNode(attributeName).nodeValue=value;   
     } catch(err)
            {
                ;  
            }
          
}





function checkEpochDependencies()
    {
       var count=  countChildElements("component4/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1");
    //   alert("there are :"+count+ " timepoints in all");
       scratch_instance.getElementsByTagName("confirmEpochDelete")[0].childNodes[0].nodeValue="Yes";

       
       var epochToDelete = scratch_instance.getElementsByTagName("epochToDelete") [0].childNodes[0].nodeValue;
       if (count!=0)
            {
					   var Segments = build_Instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:component4/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1" , build_Instance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
					   for(i=0;i<count;i++)
								  {
									 var attributeValue= getAttributevalue("/hl7-org_v3:plannedStudy/hl7-org_v3:component4/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1/hl7-org_v3:timePointEventDefinition/hl7-org_v3:componentOf1/hl7-org_v3:epochStub/hl7-org_v3:id",i,"extension");
                                     if(epochToDelete==attributeValue)
                                           {
                                            var choice = confirm("There are Time Point Events that have been created for this epoch. If you delete this Epoch, all dependent time point events will be deleted. Do you still want to proceed with delete? ") ;
                                                   if (choice)
                                                       {
                                                           scratch_instance.getElementsByTagName("confirmEpochDelete")[0].childNodes[0].nodeValue="Yes";
                                                           deleteEpochDependentTimePoints(epochToDelete,count);
                                                           return;
                                                        }                                            
                                                        
                                                     else
                                                         {
                                                          scratch_instance.getElementsByTagName("confirmEpochDelete")[0].childNodes[0].nodeValue="No"             
                                                          return;                                          
                                                          }
                                           
                                           }									 
         						  }
	          }       
       }


function  deleteEpochDependentTimePoints(epochToDelete,count) 
          { 
      
          var allTimePointSegments = build_Instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:component4/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1", build_Instance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
          
         var allEpochStubs = build_Instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:component4/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1/hl7-org_v3:timePointEventDefinition/hl7-org_v3:componentOf1/hl7-org_v3:epochStub/hl7-org_v3:id",build_Instance,nsResolver,XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);

           for(i=0;i<allTimePointSegments.snapshotLength;i++)
								  {
									 var EpochStubValue =  allEpochStubs.snapshotItem(i).getAttributeNode("extension").childNodes[0].nodeValue;
									 
                                     if(EpochStubValue==epochToDelete)
                                           {
                                            var TimePointToRemove = allTimePointSegments.snapshotItem(i);
                                            TimePointToRemove.parentNode.removeChild(TimePointToRemove);
                                         
                                           }									 
         						  }
         						 
         var remainingSegments=countChildElements("component4/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1");
 //        alert("Remaining Segments are :" + remainingSegments);			
         if(remainingSegments==0)
               {
                 	     var deletecomponent4 = build_Instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:component4", build_Instance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
                 	     deletecomponent4.parentNode.removeChild(deletecomponent4);

               }			  
          }
 
 
function checkArmDependencies()
    {
       var count=  countChildElements("component4/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1");
      // alert("there are :"+count+ " timepoints in all");
       scratch_instance.getElementsByTagName("confirmArmDelete")[0].childNodes[0].nodeValue="Yes";

       
       var armToDelete = scratch_instance.getElementsByTagName("armToDelete") [0].childNodes[0].nodeValue;
       if (count!=0)
            {
					   var Segments = build_Instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:component4/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1" , build_Instance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
					   for(i=0;i<count;i++)
								  {
									 var attributeValue= getAttributevalue("/hl7-org_v3:plannedStudy/hl7-org_v3:component4/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1/hl7-org_v3:timePointEventDefinition/hl7-org_v3:componentOf2/hl7-org_v3:armStub/hl7-org_v3:id",i,"extension");
							//		 alert("Attribute value from arm function: " + attributeValue);
                                     if(armToDelete==attributeValue)
                                           {
                                            var choice = confirm("There are Time Point Events that have been created for this arm. If you delete this arm, all dependent time point events will be deleted. Press Yes to proceed with delete or No to stop deletion. ") ;
                                                   if (choice)
                                                       {
                                                           scratch_instance.getElementsByTagName("confirmArmDelete")[0].childNodes[0].nodeValue="Yes";
                                                  //        alert("Delete selected going to function: ");
                                                           deleteArmDependentTimePoints(armToDelete,count);
                                                           return;
                                                        }                                            
                                                        
                                                     else
                                                         {
                                                          scratch_instance.getElementsByTagName("confirmArmDelete")[0].childNodes[0].nodeValue="No"             
                                                      //    alert ("Cancelling delete ");
                                                          return;                                          
                                                          }
                                           
                                           }									 
         						  }
	          }       
       } 
 
 
 
 function  deleteArmDependentTimePoints(armToDelete,count) 
          { 
      
          var allTimePointSegments = build_Instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:component4/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1", build_Instance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
          
         var allArmStubs = build_Instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:component4/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1/hl7-org_v3:timePointEventDefinition/hl7-org_v3:componentOf2/hl7-org_v3:armStub/hl7-org_v3:id",build_Instance,nsResolver,XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);

           for(i=0;i<allTimePointSegments.snapshotLength;i++)
								  {
									 var ArmStubValue =  allArmStubs.snapshotItem(i).getAttributeNode("extension").childNodes[0].nodeValue;
									 
                                     if(ArmStubValue==armToDelete)
                                           {
                                      //     alert("match found at index: "+ i + " Arm Stub to delete is :"+ ArmStubValue);
                                            var TimePointToRemove = allTimePointSegments.snapshotItem(i);
                                            TimePointToRemove.parentNode.removeChild(TimePointToRemove);
                                         
                                           }									 
         						  }
          var remainingSegments=countChildElements("component4/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1");
       //  alert("Remaining Segments are :" + remainingSegments);			
         if(remainingSegments==0)
               {
                 	     var deletecomponent4 = build_Instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:component4", build_Instance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
                 	     deletecomponent4.parentNode.removeChild(deletecomponent4);

               }			  						  
         						  
          }
 












function appendStudyType() {
try{

  var xPath = build_Instance.evaluate("/hl7-org_v3:plannedStudy", build_Instance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
    var Path = xPath.singleNodeValue;		
var nodeSets = template_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:" + "addNewStudyCharacteristic" + "/hl7-org_v3:" +  "subjectOf", typeofstudy_instance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
var newObject = nodeSets.singleNodeValue.cloneNode(true); 
 
 Path.appendChild(newObject);
 				scratch_instance.getElementsByTagName("totalstudycharacteristics") [0].childNodes[0].nodeValue +=1;
			    scratch_instance.getElementsByTagName("studycharacteristicsindex") [0].childNodes[0].nodeValue +=1;
   }catch(err)
    {}
}





function displayIndex()
 {
   
    alert("Index in Focus is: "+ scratch_instance.getElementsByTagName("SegmentInFocus")[0].childNodes[0].nodeValue);
 }





/*************************************************************************************************/


function SaveSuccess()
    {
        alert("Save successful.");
    }

    function SaveFail()  
 	{  
        alert("Save Failed! Please use the 'Save As' feature to save the file for the first time.");
    }
    
    
function OpenSuccess()
    {
        alert("Open successful.");
    }

    function OpenFail()  
 	{  
        alert("Open Failed!");
    }




function setSaveInstance() {
  //alert("Inside the setsave instance");
    var saveFilename = scratch_instance.getElementsByTagName("loadFilename") [0];
    document.getElementById("submit_load_existing") .setAttribute("action", "file:///" + encodeURI(saveFilename.textContent));
    document.getElementById("saveas_model_Document") .setAttribute("action", "file:///" + encodeURI(saveFilename.textContent));
  //  alert('Script called: fn='+saveFilename.textContent);
}

function setInstanceModel() {
    build_Instance = model.getInstanceDocument("plannedStudyInstance");
}



function setOpenFormat()
{
  	build_Instance = model.getInstanceDocument("plannedStudyInstance");
 //   alert("inside the open");
  	//var html = openXMLInstance(build_Instance);
  // var agentIdx = build_Instance.getElementsByTagName("document")[0];    
   //agentIdx.parentNode.replaceChild(html.childNodes[0],agentIdx); 
	   
}



 function nsResolver(prefix) {
    var ns = {
        'xhtml' : 'http://www.w3.org/1999/xhtml',
        'hl7-org_v3' : 'urn:hl7-org:v3'
    };
    return ns[prefix] || null;
}

function getXPath() {
  //alert ("getXPath");
 try{
    var xPath = build_Instance.evaluate("/hl7-org_v3:plannedStudy", build_Instance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
    var path = xPath.singleNodeValue;		
    return path; }catch(err){alert (err);}
    }




function getNodesetTemplate(repeat, section) {
//  alert ("Inside Nodeset template");
   try{  var nodeSets = template_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:" + repeat + "/hl7-org_v3:" +  section, template_instance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
    return nodeSets.singleNodeValue.cloneNode(true);
    }catch(err)
         {alert (err);}
}


 
 
// The below function adds a new characteristic. 
 


// The below function adds an Epoch. The epoch is added through the component 1 node in the XML Template file.
function addFirstEpoch() {
try{
         var armcount =  countChildElements("component2");
         var characteristicscount = countChildElements("subjectOf");
           if (armcount!=0)  /// The first epoch must always be added before any existing arms.
				   {
				     //  alert("Arms exist so adding before arms");
				     	var newElement=  getNodesetTemplate("addNewEpoch", "component1");
						var parentElement = build_Instance.evaluate("/hl7-org_v3:plannedStudy", build_Instance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
						var allArmNodes =build_Instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:component2", build_Instance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
						var referenceElement = allArmNodes.snapshotItem(0);
						parentElement.insertBefore(newElement,referenceElement);
				   }

          else if (characteristicscount !=0)
            {
                         //  alert("No Arms Exist but characteristics exist");     
				     	var newElement=  getNodesetTemplate("addNewEpoch", "component1");
						var parentElement = build_Instance.evaluate("/hl7-org_v3:plannedStudy", build_Instance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
						var allCharacteristicNodes =build_Instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:subjectOf", build_Instance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
						var referenceElement = allCharacteristicNodes.snapshotItem(0);
						parentElement.insertBefore(newElement,referenceElement);
				   }

          
          
          else 
                      {   //This is the case which gets called when an Arm dows not exist. In this case the epoch can be appended to the study
                      //  alert("No Arms or characteristics exist");
					 var newEpochPath = getXPath();
					 
					 var newEpoch = getNodesetTemplate("addNewEpoch", "component1");
					 newEpochPath.appendChild(newEpoch);
                   }
  //alert("Javascript Insert ");
    }catch(err)
    {}
}




function addPositionalEpochs() {
						var newElement=  getNodesetTemplate("addNewEpoch", "component1");
						var parentElement = build_Instance.evaluate("/hl7-org_v3:plannedStudy", build_Instance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
						var indextoInsert = scratch_instance.getElementsByTagName("epochindex") [0].textContent-1;
						var allEpochNodes =build_Instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:component1", build_Instance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
						var referenceElement = allEpochNodes.snapshotItem(indextoInsert);
						var elementToInsert= referenceElement.singleNodeValue;
						parentElement.insertBefore(newElement,referenceElement.nextSibling);


}



// The below function adds an Epoch. The epoch is added through the component 1 node in the XML Template file.
function addFirstArm() {
try{
var characteristicscount=countChildElements("subjectOf");  
var component4count =countChildElements("component4");
  	if (component4count!=0)   //This section is needed to insert the Arms in the correct position (before characteristics if any exist so that no errors are obtained)
		{
		           
				     	var newElement=  getNodesetTemplate("addNewArm","component2");
						var parentElement = build_Instance.evaluate("/hl7-org_v3:plannedStudy", build_Instance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
						var component4node =build_Instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:component4", build_Instance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
					//	var referenceElement = allCharacteristicNodes.snapshotItem(0);
						parentElement.insertBefore(newElement,component4node);
		}

       
	else if (characteristicscount!=0)   //This section is needed to insert the Arms in the correct position (before characteristics if any exist so that no errors are obtained.
		{
		           
				     	var newElement=  getNodesetTemplate("addNewArm","component2");
						var parentElement = build_Instance.evaluate("/hl7-org_v3:plannedStudy", build_Instance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
						var allCharacteristicNodes =build_Instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:subjectOf", build_Instance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
						var referenceElement = allCharacteristicNodes.snapshotItem(0);
						parentElement.insertBefore(newElement,referenceElement);
		}

 else {
		 var newArmPath = getXPath();
		 var newArm = getNodesetTemplate("addNewArm", "component2");
		 newArmPath.appendChild(newArm);
		}    
    }catch(err)
    {}
}



function addPositionalArms() {
						var newElement=  getNodesetTemplate("addNewArm", "component2");
						var parentElement = build_Instance.evaluate("/hl7-org_v3:plannedStudy", build_Instance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
						var indextoInsert = scratch_instance.getElementsByTagName("armindex") [0].textContent-1;
						//alert("arm should be inserted at index :" + indextoInsert );
						var allArmNodes =build_Instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:component2", build_Instance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
						var referenceElement = allArmNodes.snapshotItem(indextoInsert);
						var elementToInsert= referenceElement.singleNodeValue;
						parentElement.insertBefore(newElement,referenceElement.nextSibling);


}


 
function synchronizeSubjects()
{

var allCells = build_Instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:component4/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1/hl7-org_v3:timePointEventDefinition",build_Instance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
var numberOfCells=allCells.snapshotLength;
var typeofStudy = setStudyType(); 		
if(typeofStudy=='' || numberOfCells==0)
       {
          alert("You have either not defined a Study Characteristic for 'type of study' or you have not created study cells. Please go back to the Study Characteristics tab and choose the 'type of study' or use the Cell Templates tab to assign cells to a Study. ");
          return;
       }
       
  									   scratch_instance.getElementsByTagName("typeOfStudyRelevance") [0].childNodes[0].nodeValue  =typeofStudy;
  									   
//subjectInstanceCleanup(typeofStudy);     
var templateElementToInsert=null;
var actualElementToInsert=null;
var parentCell=null;
                     if (typeofStudy=="Animal Study")
						  {
						   templateElementToInsert=template_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:animalSubject/hl7-org_v3:subject/hl7-org_v3:experimentalUnit" , template_instance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.cloneNode(true);
						   parentCell=subject_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:animalSubject/hl7-org_v3:subject",subject_instance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
						//   alert("animal parent cell" );
						  } 
												  
					  else if (typeofStudy=="Human Study")
						  {
						   templateElementToInsert=template_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:humanSubject/hl7-org_v3:subject/hl7-org_v3:experimentalUnit" , template_instance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.cloneNode(true);
						     parentCell=subject_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:humanSubject/hl7-org_v3:subject",subject_instance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
						     					//	   alert("Human parent cell" );

						  } 
					  else if (typeofStudy=="Product Study")
						  {
						   templateElementToInsert=template_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:productSubject/hl7-org_v3:subject/hl7-org_v3:experimentalUnit" , template_instance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.cloneNode(true);
						     parentCell=subject_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:productSubject/hl7-org_v3:subject",subject_instance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
						     						//   alert("product parent cell" );

						  } 

var allArms= build_Instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:component2",build_Instance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
var armCount=allArms.snapshotLength;


for (var i=0;i<armCount;i++) //section to check if the Arm already has a subject node . If not a temporary node is inserted into the 'subject_instance'
     {
      var currentArm=allArms.snapshotItem(i);
      var currentArmName=currentArm.getElementsByTagName("id")[0].getAttributeNode("extension").nodeValue;
      var armExists="No";
      var lastindexfound=0;
          for (j=0;j<numberOfCells;j++)
           {
               var Cell=allCells.snapshotItem(j);
                 var cellArmName=Cell.getElementsByTagName("componentOf2")[0].getElementsByTagName("armStub")[0].getElementsByTagName("id")[0].getAttributeNode("extension").nodeValue;
                if (currentArmName==cellArmName)
                              {
                                armExists="Yes";
                                lastindexfound=j;
                              }
                
           }
           
        //Arm was found. Now check if subject node exists already.
                     
         alert(" Arm Found: " + armExists  +" Index found="+lastindexfound);  
         
         var cellToFindSubject = allCells.snapshotItem(lastindexfound);
      	 var allSubjectElements = build_Instance.evaluate("hl7-org_v3:subject",cellToFindSubject, nsResolver,    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
      	 var subjectCount=allSubjectElements.snapshotLength;
      	 if(subjectCount!=0)
      	    {
      	       templateElementToInsert=build_Instance.evaluate("hl7-org_v3:subject" , cellToFindSubject, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.cloneNode(true);
      	       alert("actual element obtained "+ actualElementToInsert);
      	    }

         
         //After this section you should insert the obtained templates (Actual or Template) into the subject_instance 
            
            parentCell.appendChild(templateElementToInsert);
                       if (typeofStudy=="Animal Study")
						  {
						   templateElementToInsert=template_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:animalSubject/hl7-org_v3:subject" , template_instance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.cloneNode(true);
						   parentCell=subject_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:animalSubject/hl7-org_v3:subject",subject_instance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
						  } 
												  
					  else if (typeofStudy=="Human Study")
						  {
						   templateElementToInsert=template_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:humanSubject/hl7-org_v3:subject" , template_instance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.cloneNode(true);
						     parentCell=subject_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:humanSubject/hl7-org_v3:subject",subject_instance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
						  } 
					  else if (typeofStudy=="Product Study")
						  {
						   templateElementToInsert=template_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:productSubject/hl7-org_v3:subject" , template_instance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.cloneNode(true);
						     parentCell=subject_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:productSubject/hl7-org_v3:subject",subject_instance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
						  } 
                   
           
     } 
 
   
}




function setBirthdateAndAllocate() 
{
	var elementRepeat = scratch_instance.getElementsByTagName("TimePointIndexInTemplate") [0].childNodes[0].nodeValue -1
	
	var observationRepeat = scratch_instance.getElementsByTagName("TimePointElementIndexInTemplate") [0].childNodes[0].nodeValue -1
	
	 var allComponent1Cells = celltemplate_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:component4/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1/hl7-org_v3:timePointEventDefinition",celltemplate_instance, nsResolver,    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
	 
    var parentCell=allComponent1Cells.snapshotItem(elementRepeat);		
    
	var allComponent1SubElements = celltemplate_instance.evaluate("hl7-org_v3:component1",parentCell, nsResolver,    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);

  var thisObservation = allComponent1SubElements.snapshotItem(observationRepeat);

	var observationID = celltemplate_instance.evaluate("hl7-org_v3:timePointEventDefinition/hl7-org_v3:component2/hl7-org_v3:observation/hl7-org_v3:id",thisObservation, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.getAttributeNode("extension").nodeValue;
	var observationCode = celltemplate_instance.evaluate("hl7-org_v3:timePointEventDefinition/hl7-org_v3:component2/hl7-org_v3:observation/hl7-org_v3:code",thisObservation, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue

	if(observationID == 'Birthdate')
	{
		observationCode.setAttribute("displayName", "Subject Birth Date");
		observationCode.setAttribute("code", "dob");
	}
	else if(observationID == 'Allocation')
	{
		observationCode.setAttribute("displayName", "Subject Allocation");
		observationCode.setAttribute("code", "Allocate");
	}
	else
	{
	
	}
	
}

function setBirthdateAndAllocateExisting() 
{
	var cellRepeat = scratch_instance.getElementsByTagName("templateCellIndex") [0].childNodes[0].nodeValue -1
	var elementRepeat = scratch_instance.getElementsByTagName("templateElementIndex") [0].childNodes[0].nodeValue -1
	var observationRepeat = scratch_instance.getElementsByTagName("templateSubElement") [0].childNodes[0].nodeValue -1

var currentCell =  existing_template_instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:component4/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1", existing_template_instance, nsResolver,XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,null).snapshotItem(cellRepeat)

var currentEncounter =  existing_template_instance.evaluate("hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1", currentCell, nsResolver,XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,null).snapshotItem(elementRepeat)

var actualObservation = existing_template_instance.evaluate("hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component2/hl7-org_v3:observation",currentEncounter, nsResolver,    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null).snapshotItem(observationRepeat);

	
    var observationID = existing_template_instance.evaluate("hl7-org_v3:id", actualObservation, nsResolver,    XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.getAttributeNode("extension").nodeValue;    	
    var observationCode = existing_template_instance.evaluate("hl7-org_v3:code", actualObservation, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;

	if(observationID == 'Birthdate')
	{
		observationCode.setAttribute("displayName", "Subject Birth Date");
		observationCode.setAttribute("code", "dob");
	}
	
	else if(observationID == 'Allocation')
	{
		observationCode.setAttribute("displayName", "Subject Allocation");
		observationCode.setAttribute("code", "Allocate");
	}
	
	else
	{
	
	}
	
}

function setRootOnOpen ()
{
var openStudyRoot = build_Instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:id", build_Instance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.getAttributeNode("root").nodeValue;
var openStudy = scratch_instance.evaluate("/values/studyOpenID", scratch_instance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue
openStudy.setAttribute("root", openStudyRoot) ;
}


function setRoot() {
var openStudyRoot = scratch_instance.evaluate("/values/studyOpenID", scratch_instance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.getAttributeNode("root").nodeValue

var rootID = build_Instance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:id", build_Instance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.getAttributeNode("root").nodeValue;
	if( openStudyRoot != rootID)
		{
		// Root ID has changed from opening
			var nodesSnapshot = build_Instance.evaluate("//hl7-org_v3:id", build_Instance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE , null);
			var counter = nodesSnapshot.snapshotLength;
			for ( var i=0 ; i < counter; i++ )
			{
			var thisID = nodesSnapshot.snapshotItem(i)
			if(thisID.hasAttribute("root"))
				var myVar = nodesSnapshot.snapshotItem(i).getAttributeNode("root").nodeValue;
				if (myVar != '1.3.6.1.4.1.519.1')
					{
					nodesSnapshot.snapshotItem(i).setAttribute("root", rootID) ;
					}
				}
			}
	else
	{
			// Root ID has not changed Set all nulls to protocol identifier
			var nodesSnapshot = build_Instance.evaluate("//hl7-org_v3:id", build_Instance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE , null);
			var counter = nodesSnapshot.snapshotLength
			for ( var i=0 ; i < counter; i++ )
			{
			var thisID = nodesSnapshot.snapshotItem(i)
			if(thisID.hasAttribute("root"))
			{
			var myVar = nodesSnapshot.snapshotItem(i).getAttributeNode("root").nodeValue;
			if (myVar == "" && myVar != '1.3.6.1.4.1.519.1')
				{
			var myVar = nodesSnapshot.snapshotItem(i).getAttributeNode("root").nodeValue;
			nodesSnapshot.snapshotItem(i).setAttribute("root", rootID) ;
				}
				}
			else
				{

				}
			}
	}
}
