//<!--################################################### 
//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 buildInstance = null;
var scatchInstance = null;
var templateInstance = null;

function initialize() {
    model = document.getElementById("model_Document");
    scratchInstance = model.getInstanceDocument("instance_scratch");
    templateInstance = model.getInstanceDocument("instance_template");
    buildInstance = model.getInstanceDocument("instance_build");
    sdInstance = model.getInstanceDocument("instance_sd");
    spInstance = model.getInstanceDocument("instance_sp");
 	encounterInstance = model.getInstanceDocument("instance_encounter");   
   	sdtmInstance = model.getInstanceDocument("codelist_SDTM_sd_version");
   	
         
    var scr = document.getElementById("javaScripts");
    
    scr.addEventListener("setDeaultSaveName", setDeaultSaveName, true);  
    scr.addEventListener("setSaveInstance", setSaveInstance, true);
    scr.addEventListener("setInstanceModel", setInstanceModel, true);
    scr.addEventListener("SaveSuccess", SaveSuccess, true);
    scr.addEventListener("SaveFail", SaveFail, true);
    scr.addEventListener("OpenSuccess", OpenSuccess, true);
    scr.addEventListener("OpenFail", OpenFail, true);
    
    scr.addEventListener("setLoadInstanceSD", setLoadInstanceSD, true);
	scr.addEventListener("setLoadInstanceSP", setLoadInstanceSP, true);
	scr.addEventListener("setInstanceModelSD", setInstanceModelSD, true);
    scr.addEventListener("setInstanceModelSP", setInstanceModelSP, true);
    scr.addEventListener("checkloadSP", checkloadSP, true); 	
    scr.addEventListener("checkloadSD", checkloadSD, true); 	
    scr.addEventListener("SBidExist", SBidExist, true); 	
    /*scr.addEventListener("SDidExist", SDidExist, true); */	
    
  scr.addEventListener("addNewSubject", addNewSubject, true);    
  scr.addEventListener("addNewRecord", addNewRecord, true); 
   //scr.addEventListener("deleteNewRecord", deleteNewRecord, true); 
  
  scr.addEventListener("addNewPerformer", addNewPerformer, true); 
  scr.addEventListener("deletePerformer",  deletePerformer, true); 
  scr.addEventListener("addNewPRorganization", addNewPRorganization, true); 
   scr.addEventListener("deletePRorganization", deletePRorganization, true); 
   scr.addEventListener("addNewpchoice", addNewpchoice, true); 
  scr.addEventListener("addNewpchoiced", addNewpchoiced, true); 
  scr.addEventListener("removeAuthorPChoice", removeAuthorPChoice, true); 
 /* scr.addEventListener("addNewPOrgpart", addNewPOrgpart, true);  */
  
    scr.addEventListener("addNewAuthor", addNewAuthor, true); 
     scr.addEventListener("deleteAuthor",  deleteAuthor, true); 
  scr.addEventListener("addNewRorganization", addNewRorganization, true); 
  scr.addEventListener("deleteRorganization", deleteRorganization, true); 
  scr.addEventListener("addNewachoice", addNewachoice, true); 
  scr.addEventListener("addNewachoiced", addNewachoiced, true); 
      scr.addEventListener("removeAuthorChoice", removeAuthorChoice, true); 
  
  scr.addEventListener("addNewAssignedPerson", addNewAssignedPerson, true);
   scr.addEventListener("deleteAssignedPerson", deleteAssignedPerson, true);
   scr.addEventListener("addNewReporg", addNewReporg, true);   
    scr.addEventListener("deleteReporg", deleteReporg, true);   
         scr.addEventListener("addNewLicence", addNewLicence, true);   
          scr.addEventListener("deleteLicence", deleteLicence, true);   
        scr.addEventListener("addNewMember", addNewMember, true);  
        scr.addEventListener("deleteMember", deleteMember, true);  
        scr.addEventListener("addNewRole", addNewRole, true);  
          scr.addEventListener("deleteRole", deleteRole, true);  
        scr.addEventListener("addNewOrgpartof", addNewOrgpartof, true);  
        scr.addEventListener("deleteOrgpartof", deleteOrgpartof, true);  
        scr.addEventListener("addNewContactp", addNewContactp, true);  
         scr.addEventListener("deleteContactp", deleteContactp, true);  
        scr.addEventListener("addNewOrgcont", addNewOrgcont, true);  
         scr.addEventListener("deleteOrgcont", deleteOrgcont, true);  
         scr.addEventListener("addNewLocated", addNewLocated, true);     
         
   scr.addEventListener("addNewvPerson", addNewvPerson, true);
     scr.addEventListener("deletePerson", deletePerson, true);
      scr.addEventListener("addNewvReporg", addNewvReporg, true);  
      scr.addEventListener("deletevReporg", deletevReporg, true);  
        scr.addEventListener("addNewvLicence", addNewvLicence, true); 
          scr.addEventListener("deletevLicence", deletevLicence, true); 
        scr.addEventListener("addNewvMember", addNewvMember, true);  
         scr.addEventListener("deletevMember", deletevMember, true);  
        scr.addEventListener("addNewvRole", addNewvRole, true);  
        scr.addEventListener("deletevRole", deletevRole, true);  
        scr.addEventListener("addNewvOrgpartof", addNewvOrgpartof, true);  
         scr.addEventListener("deletevOrgpartof", deletevOrgpartof, true);  
        scr.addEventListener("addNewvContactp", addNewvContactp, true);  
         scr.addEventListener("deletevContactp", deletevContactp, true);  
        scr.addEventListener("addNewvOrgcont", addNewvOrgcont, true);  
        scr.addEventListener("deletevOrgcont", deletevOrgcont, true);  
         scr.addEventListener("addNewvLocated", addNewvLocated, true);
  
    scr.addEventListener("addNewRelatedDocument", addNewRelatedDocument, true); 
     scr.addEventListener("deleteRelatedDocument", deleteRelatedDocument, true); 
  scr.addEventListener("addNewComponent", addNewComponent, true); 
    
    scr.addEventListener("myAlert", myAlert, true); 
    scr.addEventListener("setRoot", setRoot, true);   
    scr.addEventListener("setEffectiveTimeNullFlavor", setEffectiveTimeNullFlavor, true);   
    scr.addEventListener("removeEffectiveTimeNullFlavor", removeEffectiveTimeNullFlavor, true);   
 
    
       // ------------------- For Section / Clinical Statement   ------------------
    scr.addEventListener("getStuffFromSD", getStuffFromSD, true); 
    scr.addEventListener("addNewAllObservations", addNewAllObservations, true); 
     scr.addEventListener("addFieldsToStudyCS", addFieldsToStudyCS, true); 
        scr.addEventListener("addObservationTimeFromEncounter", addObservationTimeFromEncounter, true); 
        scr.addEventListener("addObservationTimeFromEncounterAllView", addObservationTimeFromEncounterAllView, true); 

 scr.addEventListener("checkSubjectChange", checkSubjectChange, true); 

               scr.addEventListener("checkSPSubjectType", checkSPSubjectType, true); 
               
    scr.addEventListener("encounterToScratch", encounterToScratch, true); 
    scr.addEventListener("updateEncounter", updateEncounter, true); 
   scr.addEventListener("deleteEncounter", deleteEncounter, true); 
   scr.addEventListener("deleteEncounterAllView", deleteEncounterAllView, true); 
     scr.addEventListener("encounterRemoveTrackingID", encounterRemoveTrackingID, true); 
    scr.addEventListener("addUnplannedObservation", addUnplannedObservation, true); 
        scr.addEventListener("removeObservation", removeObservation, true); 
        scr.addEventListener("addUnplannedEncounter", addUnplannedEncounter, true); 
         scr.addEventListener("addEncounterLocation", addEncounterLocation, true);  
        scr.addEventListener("setUnplannedObservationCode", setUnplannedObservationCode, true);  
            scr.addEventListener("countOfEncounters", countOfEncounters, true);   
    
        //Author Performer stuff
    scr.addEventListener("authorDetails", authorDetails, true);
    scr.addEventListener("performerDetails", performerDetails, true);
   scr.addEventListener("setTodaysDate", setTodaysDate, true);
    
 
		scr.addEventListener("encounterLocation", encounterLocation, true);
		scr.addEventListener("deleteEncounterLocation", deleteEncounterLocation, true);
		scr.addEventListener("setBirthdateAndAllocate", setBirthdateAndAllocate, true);
		scr.addEventListener("setBirthdateAndAllocateViewAll", setBirthdateAndAllocateViewAll, true);
		scr.addEventListener("emptyEncounterInstance", emptyEncounterInstance, true);
		scr.addEventListener("setUnplannedObservationCodeViewAll", setUnplannedObservationCodeViewAll, true);
		scr.addEventListener("deleteEncounterViewAll", deleteEncounterViewAll, true);
		scr.addEventListener("removeObservationViewAll", removeObservationViewAll, true);
		scr.addEventListener("addUnplannedObservationViewAll", addUnplannedObservationViewAll, true);
};


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 SDImportSuccess()  
 	{  
        alert("Study Design message successfully imported.");
    }; 
 
    
    function SBOpenFail()  
 	{  
        alert("Open Failed! Please open a Subject Data Message.");
    };
    
    
    function SDOpenFail()  
 	{  
        alert("Open Failed! Please open a Study Design Message.");
    };


  function SPOpenFail()  
 	{  
        alert("Open Failed! Please open a Study Participation Message.");
    };


function setDeaultSaveName()
{
var SDID = buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:id", buildInstance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.getAttributeNode("root").nodeValue;
//alert("DSID is:" +SDID);
var SubjectID= buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:subject/hl7-org_v3:researchSubject/hl7-org_v3:id", buildInstance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue

if (SubjectID.hasAttribute("extension"))
{
 SubjectID = SubjectID.getAttributeNode("extension").nodeValue;


//alert("SubjectID is:" +SubjectID);
if (SDID != "" )
{
var saveName = 'StudySubjectData_' +SDID+'_'+SubjectID;
scratchInstance.getElementsByTagName("defaultSaveName") [0].childNodes[0].nodeValue = saveName
return;
		 }
		 
}		

var openStudyRoot = buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:id", buildInstance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.getAttributeNode("root").nodeValue;

var openStudy = scratchInstance.evaluate("/data/studyOpenID", scratchInstance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue
openStudy.setAttribute("root", openStudyRoot) ;

};	
	

function setSaveInstance() {
    var saveFilename = scratchInstance.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));
}


function setInstanceModel() {
    buildInstance = model.getInstanceDocument("instance_build");    
};

function myAlert(){
alert("ALERT ALERT ALERT ALERT ALERT ALERT ALERT")
};
    
function nsResolver(prefix) {
    var ns = {
        'xhtml' : 'http://www.w3.org/1999/xhtml',
        'hl7-org_v3' : 'urn:hl7-org:v3'
    };
    return ns[prefix] || null;
};
 
 
 
function setRoot() {
		var encountersSnapshot = buildInstance.evaluate("//hl7-org_v3:encounter", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE , null);
			for ( var e=0 ; e < encountersSnapshot.snapshotLength; e++ )
			{
			var encounter = encountersSnapshot.snapshotItem(e)
			encounter.setAttribute("moodCode", "EVN") ;
			}
			
		var observationsSnapshot = buildInstance.evaluate("//hl7-org_v3:observation", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE , null);
			for ( var o=0 ; o < observationsSnapshot.snapshotLength; o++ )
			{
			var observation = observationsSnapshot.snapshotItem(o)
			observation.setAttribute("moodCode", "EVN") ;
			}


var openStudyRoot = scratchInstance.evaluate("/data/studyOpenID", scratchInstance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.getAttributeNode("root").nodeValue
try{
var rootID = buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:id", buildInstance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.getAttributeNode("root").nodeValue;
}
catch(err)	{ }	

var theStudyrootID = ""
try{
theStudyrootID = buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:definition1/hl7-org_v3:actDefinition/hl7-org_v3:id", buildInstance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.getAttributeNode("root").nodeValue;
	}
	catch(err)	{ }	
	
//alert( openStudyRoot + '  !=   '  +rootID)
	if( openStudyRoot != rootID)
		{
		// Root ID has changed from opening
		var nodesSnapshot = buildInstance.evaluate("//hl7-org_v3:id", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE , null);
			for ( var i=0 ; i < nodesSnapshot.snapshotLength; i++ )
			{
			var myVar = nodesSnapshot.snapshotItem(i).getAttributeNode("root").nodeValue;
						if (myVar != '1.3.6.1.4.1.519.1')
			{
			nodesSnapshot.snapshotItem(i).setAttribute("root", rootID) ;
			}
			}
			
		var resetStudyrootID = buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:definition1/hl7-org_v3:actDefinition/hl7-org_v3:id", buildInstance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
		resetStudyrootID.setAttribute("root", theStudyrootID) ;
		
		}
		
	else
	{
			// Root ID has not changed Set all nulls to protocol identifier
		var nodesSnapshot = buildInstance.evaluate("//hl7-org_v3:id", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE , null);
			for ( var i=0 ; i < nodesSnapshot.snapshotLength; i++ )
			{
			var myVar = nodesSnapshot.snapshotItem(i).getAttributeNode("root").nodeValue;
			if (myVar == "")
				{
			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
				{

				}
			}
					var resetStudyrootID = buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:definition1/hl7-org_v3:actDefinition/hl7-org_v3:id", buildInstance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
		resetStudyrootID.setAttribute("root", theStudyrootID) ;
	}
}
 
 
 
function getFirstPath() {
 var firstPath = buildInstance.evaluate("/hl7-org_v3:document", buildInstance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
   //alert("get First Path function");
  //alert("firstPath");
    var path = firstPath.singleNodeValue;
    return path; 
    };
    
    
function getNodesetTemplate(repeat, section) {
     var nodeSets = templateInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:" + repeat + "/hl7-org_v3:" +  section, templateInstance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
        //  alert("Get Nodeset Template function");
    // alert("nodeSets");
    return nodeSets.singleNodeValue.cloneNode(true);
};

 /*-------------------------------------------Position----------------------------------------------------------------------------------------------------*/
  function countChildElements(child)
{
var componentcount = buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:"+child , buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
return componentcount.snapshotLength;
} 
 
//F1
function addNewSubject()
{
var index=scratchInstance.getElementsByTagName("subjectIndex") [0].childNodes[0].nodeValue;
var allSubject = buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:subject", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
var countSubject = allSubject.snapshotLength;
	if (countSubject ==0)
	{
	appendFirstSubject();
	}
	else
	{
	insertPositionalSubject(index);
	} 
};

function insertPositionalSubject(index) {
var newElement= getNodesetTemplate("addsubject", "subject");
var parentElement = buildInstance.evaluate("/hl7-org_v3:document", buildInstance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
//alert("Parent Element is :"+ parentElement);
var allSubjectNodes =buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:subject", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
var referenceElement = allSubjectNodes.snapshotItem(index-1);
var elementToInsert= referenceElement.singleNodeValue;
parentElement.insertBefore(newElement,referenceElement.nextSibling);};


function appendFirstSubject() {
 var newObject = getNodesetTemplate("addsubject", "subject");
 var recordTargetCount = countChildElements("recordTarget");		   
		 var performerCount = countChildElements("performer");		   
		 var authorCount = countChildElements("author");		   
		 var dataEntererCount = countChildElements("dataEnterer");		   
		 var verifierCount = countChildElements("verifier");		   
		 var definition1Count = countChildElements("definition1");		   
  <!--       var definition2Count = countChildElements("definition2");		-->   
		 var relatedDocumentCount = countChildElements("relatedDocument");		   
		 var componentCount = countChildElements("component");		   
		
		var parentElement = buildInstance.evaluate("/hl7-org_v3:document", buildInstance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
		
	   	 if (recordTargetCount !=0)
		{
					var recordTarget =buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:recordTarget", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
			var referenceElement = recordTarget.snapshotItem(0);
			parentElement.insertBefore(newObject,referenceElement);
	   }
	   
	   	 else if (performerCount !=0)
		{
			
			var performer =buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:performer", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
			var referenceElement = performer.snapshotItem(0);
			parentElement.insertBefore(newObject,referenceElement);
	   }
	   
	   	   else if (authorCount !=0)
		{
		
			var author =buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:author", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
			var referenceElement = author.snapshotItem(0);
			parentElement.insertBefore(newObject,referenceElement);
	   }
	   
	   	 else if (dataEntererCount !=0)
		{
					var dataEnterer =buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:dataEnterer", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
			var referenceElement = dataEnterer.snapshotItem(0);
			parentElement.insertBefore(newObject,referenceElement);
	   }
	   
	 	   	 else if (verifierCount !=0)
		{
			
			var verifier =buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:verifier", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
			var referenceElement = verifier.snapshotItem(0);
			parentElement.insertBefore(newObject,referenceElement);
	   }  
	   
	 	   	 else if (definition1Count !=0)
		{
			
			var definition1 =buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:definition1", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
			var referenceElement = definition1.snapshotItem(0);
				parentElement.insertBefore(newObject,referenceElement);
	   }  	   
	   
	 	   
		 	else if (relatedDocumentCount !=0)
		{
			
			var relatedDocument =buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:relatedDocument", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
			var referenceElement = relatedDocumentsnapshotItem(0);
					parentElement.insertBefore(newObject,referenceElement);
	   }  	     
	
	  		else if (componentCount !=0)
		{
			
			var component =buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:component", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
			var referenceElement = component.snapshotItem(0);
					parentElement.insertBefore(newObject,referenceElement);
	   }  	    
	   	
	else
	{
	
	parentElement.appendChild(newObject);
	  }
};
 

//F2
function addNewRecord()
{
var index=scratchInstance.getElementsByTagName("recordIndex") [0].childNodes[0].nodeValue -1;
var allRecordTarget = buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:recordTarget/hl7-org_v3:researchSubject", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
var countRecordTarget = allRecordTarget.snapshotLength;
if (countRecordTarget >0)
{
alert( "Only one Record is allowed to be added in here!") ;
//alert( "Value of INDEX is " + scratchInstance.getElementsByTagName("recordIndex")[0].childNodes[0].nodeValue) ;
}
else
{
//alert("Total Subject are :" + countRecordTarget);
	appendFirstRecord();
}
};

function appendFirstRecord() {
 var newObject = getNodesetTemplate("addrecord", "recordTarget");
		 var performerCount = countChildElements("performer");		   
		 var authorCount = countChildElements("author");		   
		 var dataEntererCount = countChildElements("dataEnterer");		   
		 var verifierCount = countChildElements("verifier");		   
		 var definition1Count = countChildElements("definition1");		   
        <!-- var definition2Count = countChildElements("definition2");		-->   
		 var relatedDocumentCount = countChildElements("relatedDocument");		   
		 var componentCount = countChildElements("component");		   
		
		var parentElement = buildInstance.evaluate("/hl7-org_v3:document", buildInstance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
	 
	   	 if (performerCount !=0)
		{
			var performer =buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:performer", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
			var referenceElement = performer.snapshotItem(0);
			parentElement.insertBefore(newObject,referenceElement);
	   }
	   	   else if (authorCount !=0)
		{
			var author =buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:author", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
			var referenceElement = author.snapshotItem(0);
			parentElement.insertBefore(newObject,referenceElement);
	   }
	   	 else if (dataEntererCount !=0)
		{
			var dataEnterer =buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:dataEnterer", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
			var referenceElement = dataEnterer.snapshotItem(0);
			parentElement.insertBefore(newObject,referenceElement);
	   }
	 	   	 else if (verifierCount !=0)
		{
		var verifier =buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:verifier", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
			var referenceElement = verifier.snapshotItem(0);
			parentElement.insertBefore(newObject,referenceElement);
	   }  
	 	   	 else if (definition1Count !=0)
		{
			var definition1 =buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:definition1", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
			var referenceElement = definition1.snapshotItem(0);
				parentElement.insertBefore(newObject,referenceElement);
	   }  	   
			 	else if (relatedDocumentCount !=0)
		{
			var relatedDocument =buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:relatedDocument", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
			var referenceElement = relatedDocumentsnapshotItem(0);
					parentElement.insertBefore(newObject,referenceElement);
	   }  	     
	   		else if (componentCount !=0)
		{
			var component =buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:component", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
			var referenceElement = component.snapshotItem(0);
					parentElement.insertBefore(newObject,referenceElement);
	   }  	    
	
	else
	{
	parentElement.appendChild(newObject);
	  }
}; 


//F3
function addNewPerformer() 
{
var index=scratchInstance.getElementsByTagName("performerIndex") [0].childNodes[0].nodeValue;
var allPerformer = buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:performer", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
var countPerformer = allPerformer.snapshotLength;

	if (countPerformer==0)
	{
	appendFirstPerformer();
	}
	else
	{
	insertPositionalPerformer(index);
	} 
};


function deletePerformer()
{
//alert("delete function");
var index=scratchInstance.getElementsByTagName("performerIndex") [0].childNodes[0].nodeValue-1;
var allPerformer = buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:performer", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
	var subPerformer = allPerformer.snapshotItem(index);
		subPerformer.parentNode.removeChild(subPerformer);		
};


function insertPositionalPerformer() {

var newElement= getNodesetTemplate("addperformer", "performer");
var parentElement = buildInstance.evaluate("/hl7-org_v3:document", buildInstance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
var index =scratchInstance.getElementsByTagName("performerIndex") [0].textContent;
var allPerformerNodes =buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:performer", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
var referenceElement = allPerformerNodes.snapshotItem(index-1);
var elementToInsert= referenceElement.singleNodeValue;
parentElement.insertBefore(newElement,referenceElement.nextSibling);};

function appendFirstPerformer() {
 var newObject = getNodesetTemplate("addperformer", "performer");
 		 var authorCount = countChildElements("author");		   
		 var dataEntererCount = countChildElements("dataEnterer");		   
		 var verifierCount = countChildElements("verifier");		   
		 var definition1Count = countChildElements("definition1");		   
         <!--var definition2Count = countChildElements("definition2");	-->	   
		 var relatedDocumentCount = countChildElements("relatedDocument");		   
		 var componentCount = countChildElements("component");		   
		
		var parentElement = buildInstance.evaluate("/hl7-org_v3:document", buildInstance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
 	   	   if (authorCount !=0)
		{
			
			var author =buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:author", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
			var referenceElement = author.snapshotItem(0);
			parentElement.insertBefore(newObject,referenceElement);
	   }
	   
	   	 else if (dataEntererCount !=0)
		{
			
			var dataEnterer =buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:dataEnterer", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
			var referenceElement = dataEnterer.snapshotItem(0);
			parentElement.insertBefore(newObject,referenceElement);
	   }
	   
	 	   	 else if (verifierCount !=0)
		{
			
			var verifier =buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:verifier", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
			var referenceElement = verifier.snapshotItem(0);
			parentElement.insertBefore(newObject,referenceElement);
	   }  
	   
	 	   	 else if (definition1Count !=0)
		{
		
			var definition1 =buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:definition1", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
			var referenceElement = definition1.snapshotItem(0);
				parentElement.insertBefore(newObject,referenceElement);
	   }  	   
	   
	 		 	else if (relatedDocumentCount !=0)
		{
		  
			var relatedDocument =buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:relatedDocument", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
			var referenceElement = relatedDocumentsnapshotItem(0);
					parentElement.insertBefore(newObject,referenceElement);
	   }  	     
	   
	   	 	else if (componentCount !=0)
		{
			
			var component =buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:component", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
			var referenceElement = component.snapshotItem(0);
					parentElement.insertBefore(newObject,referenceElement);
	   }  	     

	else
	{
	
	parentElement.appendChild(newObject);
	  }
 }; 

//F3.1

function countChildPRO(child)
{
var PROcount = buildInstance.evaluate("/hl7-org_v3:document/v3:hl7-org_v3:performer/hl7-org_v3:assignedAuthor/hl7-org_v3:representedOrganization/hl7-org_v3:"+child , buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
return PROcount.snapshotLength;
};  

function addNewPRorganization()
{
var index=scratchInstance.getElementsByTagName("prorganizationIndex") [0].childNodes[0].nodeValue;
//alert ("index"  + index);
var performerIndex = scratchInstance.getElementsByTagName("performerIndex") [0].childNodes[0].nodeValue;
var parentPRO = buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:performer/hl7-org_v3:assignedAuthor", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
var PRO = parentPRO.snapshotItem(performerIndex - 1);
var allprorganization = buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:performer/hl7-org_v3:assignedAuthor/hl7-org_v3:representedOrganization", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
var countprorganization = allprorganization.snapshotLength;
	if (countprorganization ==0)
	{
	appendFirstPRorganization(performerIndex);
	}
	else
	{
	alert('Only one Represented Organization can be added in here!');
	} 
};

	   
function deletePRorganization()
{
//alert("delete function");
var allprorganization = buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:performer/hl7-org_v3:assignedAuthor/hl7-org_v3:representedOrganization", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
var index=scratchInstance.getElementsByTagName("prorganizationIndex") [0].childNodes[0].nodeValue -1;
var suborgpartof = allprorganization.snapshotItem(index);
suborgpartof.parentNode.removeChild(suborgpartof);		
};



function appendFirstPRorganization(performerIndex) {
 var newObject = getNodesetTemplate("addprepresentedOrganization", "representedOrganization");
 var performerIndex = performerIndex
 var parentPRO = buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:performer/hl7-org_v3:assignedAuthor", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
  //alert('parentPRO:' +parentPRO)
 var PRO= parentPRO.snapshotItem(performerIndex-1);
	//alert('Document is empty, append nodes document')
	PRO.appendChild(newObject);
}; 


//F3.2

function addNewpchoice()
{
//alert( "Value of pchoiceIndex is " + scratchInstance.getElementsByTagName("pchoiceIndex") [0].childNodes[0].nodeValue) ;
var index=scratchInstance.getElementsByTagName("pchoiceIndex") [0].childNodes[0].nodeValue;
var performerIndex=scratchInstance.getElementsByTagName("performerIndex") [0].childNodes[0].nodeValue;
var allperformers = buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:performer/hl7-org_v3:assignedAuthor", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
var performer = allperformers.snapshotItem(performerIndex-1);

try{
var device = buildInstance.evaluate("hl7-org_v3:assignedAuthoringDevice", performer, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
	}
	catch(err)	{ }	
if (device != null)
	{
	device.parentNode.removeChild(device);	
	}


var allpchoice = buildInstance.evaluate("hl7-org_v3:assignedPerson", performer, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
var countpchoice = allpchoice.snapshotLength;
//alert ("Total pchoice are : " + countpchoice);
	if (countpchoice ==0)
	{
	appendFirstpchoice(performerIndex);
	}
	

};

function removeAuthorPChoice()
{
//alert( "Value of pchoiceIndex is " + scratchInstance.getElementsByTagName("pchoiceIndex") [0].childNodes[0].nodeValue) ;
//var index=scratchInstance.getElementsByTagName("pchoiceIndex") [0].childNodes[0].nodeValue;
var performerIndex=scratchInstance.getElementsByTagName("performerIndex") [0].childNodes[0].nodeValue;
var allperformers = buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:performer/hl7-org_v3:assignedAuthor", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
var performer = allperformers.snapshotItem(performerIndex-1);

try{
var device = buildInstance.evaluate("hl7-org_v3:assignedAuthoringDevice", performer, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
	}
	catch(err)	{ }	
if (device != null)
	{
	device.parentNode.removeChild(device);	
	}
try{
var person = buildInstance.evaluate("../hl7-org_v3:assignedAuthor/hl7-org_v3:assignedPerson", performer, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
	}
	catch(err)	{ }	
if (person != null)
	{
	person.parentNode.removeChild(person);	
	}
}


function appendFirstpchoice(performerIndex) {
 var newObject = getNodesetTemplate("addPerformerChoicePerson", "assignedPerson");
 var performerIndex = performerIndex
 var allperformers = buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:performer/hl7-org_v3:assignedAuthor", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
 var performer = allperformers.snapshotItem(performerIndex-1);
	 //alert('allperformers:' +allperformers)
var allprorganization = buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:performer/hl7-org_v3:assignedAuthor/hl7-org_v3:representedOrganization", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
var countprorganization = allprorganization.snapshotLength;
	if (countprorganization !=0)
{
	//alert("organization are exist");     
	var referenceAP = allprorganization.snapshotItem(0);
    performer.insertBefore(newObject,referenceAP);
}
else
{	 
	performer.appendChild(newObject);
	}
}; 


//F3.3

function addNewpchoiced()
{
//alert( "Value of pchoicedIndex is " + scratchInstance.getElementsByTagName("pchoicedIndex") [0].childNodes[0].nodeValue) ;
// var index=scratchInstance.getElementsByTagName("pchoicedIndex") [0].childNodes[0].nodeValue;
var performerIndex=scratchInstance.getElementsByTagName("performerIndex") [0].childNodes[0].nodeValue;
var allperformers = buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:performer/hl7-org_v3:assignedAuthor", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
var performer = allperformers.snapshotItem(performerIndex-1);


try{
var person = buildInstance.evaluate("hl7-org_v3:assignedPerson", performer, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
	}
	catch(err)	{ }	
if (person != null)
	{
	person.parentNode.removeChild(person);	
	}

var allpchoiced = buildInstance.evaluate("hl7-org_v3:assignedAuthoringDevice", performer, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
var countpchoiced = allpchoiced.snapshotLength;
	if (countpchoiced ==0)
	{
	appendFirstpchoiced(performerIndex);
	}

};


function appendFirstpchoiced(performerIndex) {
 var newObject = getNodesetTemplate("addPerformerChoiceDevice", "assignedAuthoringDevice");
 var performerIndex = performerIndex
 var allperformers = buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:performer/hl7-org_v3:assignedAuthor", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
 var performer = allperformers.snapshotItem(performerIndex-1);
	 //alert('allperformers:' +allperformers)
var allprorganization = buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:performer/hl7-org_v3:assignedAuthor/hl7-org_v3:representedOrganization", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
var countprorganization = allprorganization.snapshotLength;
	if (countprorganization !=0)
{
	alert("organization are exist");     
	var referenceAP = allprorganization.snapshotItem(0);
    performer.insertBefore(newObject,referenceAP);
}
else
{	 	  
	performer.appendChild(newObject);
}	
}; 


//F4
function addNewAuthor()
{
//alert( "Value of authorIndex is " + scratchInstance.getElementsByTagName("authorIndex") [0].childNodes[0].nodeValue) ;
var index=scratchInstance.getElementsByTagName("authorIndex") [0].childNodes[0].nodeValue;
var allAuthor = buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:author", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
var countAuthor = allAuthor.snapshotLength;
//alert ("Total Author are : " + countAuthor);
	if (countAuthor ==0)
	{
	appendFirstAuthor();
	}
	else
	{
	insertPositionalAuthor(index);
	} 
};



function deleteAuthor()
{
//alert("delete function");
var index=scratchInstance.getElementsByTagName("authorIndex") [0].childNodes[0].nodeValue-1;
var allAuthor = buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:author", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
	var subAuthor  = allAuthor.snapshotItem(index);
		subAuthor.parentNode.removeChild(subAuthor);		
};



function insertPositionalAuthor() {
//alert("Coming into the positional Insert function");
var newElement= getNodesetTemplate("addauthor", "author");
//alert("new Element is :"+ newElement);
var parentElement = buildInstance.evaluate("/hl7-org_v3:document", buildInstance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
//alert("Parent Element is :"+ parentElement);
var index =scratchInstance.getElementsByTagName("authorIndex") [0].textContent;
var allAuthorNodes =buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:author", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
var referenceElement = allAuthorNodes.snapshotItem(index-1);
//alert("Reference Element is :"+ referenceElement);
var elementToInsert= referenceElement.singleNodeValue;
parentElement.insertBefore(newElement,referenceElement.nextSibling);};


function appendFirstAuthor() {
 var newObject = getNodesetTemplate("addauthor", "author");
 var dataEntererCount = countChildElements("dataEnterer");		   
		 var verifierCount = countChildElements("verifier");		   
		 var definition1Count = countChildElements("definition1");		   
    <!--     var definition2Count = countChildElements("definition2");		-->   
		 var relatedDocumentCount = countChildElements("relatedDocument");		   
		 var componentCount = countChildElements("component");		   
		var parentElement = buildInstance.evaluate("/hl7-org_v3:document", buildInstance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
	 if (dataEntererCount !=0)
		{
			//alert("dataEnterer exist");     
			var dataEnterer =buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:dataEnterer", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
			var referenceElement = dataEnterer.snapshotItem(0);
			parentElement.insertBefore(newObject,referenceElement);
	   }
	   
	 	   	 else if (verifierCount !=0)
		{
			//alert("verifier exist");     
			var verifier =buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:verifier", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
			var referenceElement = verifier.snapshotItem(0);
			parentElement.insertBefore(newObject,referenceElement);
	   }  
	   
	 	   	 else if (definition1Count !=0)
		{
			//alert("definition1 exist");     
			var definition1 =buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:definition1", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
			var referenceElement = definition1.snapshotItem(0);
				parentElement.insertBefore(newObject,referenceElement);
	   }  	   
	    
		 	else if (relatedDocumentCount !=0)
		{
			//alert("relatedDocument exist");     
			var relatedDocument =buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:relatedDocument", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
			var referenceElement = relatedDocumentsnapshotItem(0);
					parentElement.insertBefore(newObject,referenceElement);
	   }  	     
	   
	   	 else if (componentCount !=0)
		{
			//alert("component exist");     
			var component =buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:component", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
			var referenceElement = component.snapshotItem(0);
					parentElement.insertBefore(newObject,referenceElement);
	   }  	   
	
	else
	{
	//alert('Document is empty, append nodes document')
	parentElement.appendChild(newObject);
	  }
}; 

//F4.1
function countChildRO(child)
{
var ROcount = buildInstance.evaluate("/hl7-org_v3:document/v3:hl7-org_v3:author/hl7-org_v3:assignedAuthor/hl7-org_v3:representedOrganization/hl7-org_v3:"+child , buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
return ROcount.snapshotLength;
};  

function addNewRorganization()
{
//alert( "Value of rorganizationIndex is " + scratchInstance.getElementsByTagName("rorganizationIndex") [0].childNodes[0].nodeValue) ;
var index=scratchInstance.getElementsByTagName("rorganizationIndex") [0].childNodes[0].nodeValue;
var authorIndex=scratchInstance.getElementsByTagName("authorIndex") [0].childNodes[0].nodeValue;
var allAuthors = buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:author/hl7-org_v3:assignedAuthor", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
var author = allAuthors.snapshotItem(authorIndex-1);
var allrorganization = buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:author/hl7-org_v3:assignedAuthor/hl7-org_v3:representedOrganization", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
var countrorganization = allrorganization.snapshotLength;
//alert ("Total rorganization are : " + countrorganization);
	if (countrorganization ==0)
	{
	appendFirstRorganization(authorIndex);
	}
	else
	{
	alert('Only one Represented Organization can be added.');
	} 
};
	   
function deleteRorganization()
{
//alert("delete function");
var allrorganization = buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:author/hl7-org_v3:assignedAuthor/hl7-org_v3:representedOrganization", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
var index=scratchInstance.getElementsByTagName("rorganizationIndex") [0].childNodes[0].nodeValue -1;
var suborgpartof = allrorganization.snapshotItem(index);
suborgpartof.parentNode.removeChild(suborgpartof);		
};



function appendFirstRorganization(authorIndex) {
 var newObject = getNodesetTemplate("addrepresentedOrganization", "representedOrganization");
 var authorIndex = authorIndex
  var allAuthors = buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:author/hl7-org_v3:assignedAuthor", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
 var author = allAuthors.snapshotItem(authorIndex-1);
	 //alert('allAuthors:' +allAuthors)
	author.appendChild(newObject);
}; 


//F4.2

function addNewachoice()
{
var index=scratchInstance.getElementsByTagName("achoiceIndex") [0].childNodes[0].nodeValue;
var authorIndex=scratchInstance.getElementsByTagName("authorIndex") [0].childNodes[0].nodeValue;
var allAuthors = buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:author/hl7-org_v3:assignedAuthor", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
 var author = allAuthors.snapshotItem(authorIndex-1);

try{
var device = buildInstance.evaluate("hl7-org_v3:assignedAuthoringDevice", author, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
	}
	catch(err)	{ }	
if (device != null)
	{
	device.parentNode.removeChild(device);	
	}

	appendFirstachoice(authorIndex);

};


function appendFirstachoice(authorIndex) {
var newObject = getNodesetTemplate("addAuthorChoicePerson", "assignedPerson");
var authorIndex = authorIndex
var allAuthors = buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:author/hl7-org_v3:assignedAuthor", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
var author = allAuthors.snapshotItem(authorIndex-1);
//alert('allAuthors:' +allAuthors)
var allrorganization = buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:author/hl7-org_v3:assignedAuthor/hl7-org_v3:representedOrganization", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
var countrorganization = allrorganization.snapshotLength;
//alert ("Total organization are :" + countrorganization);	 
 if (countrorganization !=0)
{
	//alert("organization are exist");     
	var referenceAP = allrorganization.snapshotItem(0);
    author.insertBefore(newObject,referenceAP);
}
else
{	 
	author.appendChild(newObject);
}	
}; 


function removeAuthorChoice()
{
var index=scratchInstance.getElementsByTagName("achoiceIndex") [0].childNodes[0].nodeValue;
var authorIndex=scratchInstance.getElementsByTagName("authorIndex") [0].childNodes[0].nodeValue;
var allAuthors = buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:author/hl7-org_v3:assignedAuthor", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
 var author = allAuthors.snapshotItem(authorIndex-1);
var allachoice = buildInstance.evaluate("hl7-org_v3:assignedPerson", author, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
try{
var device = buildInstance.evaluate("../hl7-org_v3:assignedAuthor/hl7-org_v3:assignedAuthoringDevice", author, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
	}
	catch(err)	{ }	
if (device != null)
	{
	device.parentNode.removeChild(device);	
	}
try{
var person = buildInstance.evaluate("../hl7-org_v3:assignedAuthor/hl7-org_v3:assignedPerson", author, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
	}
	catch(err)	{ }	
if (person != null)
	{
	person.parentNode.removeChild(person);	
	}
}


//F4.3

function addNewachoiced()
{
//alert( "Value of achoicedIndex is " + scratchInstance.getElementsByTagName("achoicedIndex") [0].childNodes[0].nodeValue) ;
var index=scratchInstance.getElementsByTagName("achoicedIndex") [0].childNodes[0].nodeValue;
var authorIndex=scratchInstance.getElementsByTagName("authorIndex") [0].childNodes[0].nodeValue;
var allAuthors = buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:author/hl7-org_v3:assignedAuthor", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
var author = allAuthors.snapshotItem(authorIndex-1);
try{
var person = buildInstance.evaluate("hl7-org_v3:assignedPerson", author, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
	}

	catch(err)	{ }	
if (person != null)
	{
	person.parentNode.removeChild(person);	
	}

	appendFirstachoiced(authorIndex);

};


function appendFirstachoiced(authorIndex) {
 var newObject = getNodesetTemplate("addAuthorChoiceDevice", "assignedAuthoringDevice");
 var authorIndex = authorIndex
 var allAuthors = buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:author/hl7-org_v3:assignedAuthor", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
 var author = allAuthors.snapshotItem(authorIndex-1);
	 //alert('allAuthors:' +allAuthors)
var allrorganization = buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:author/hl7-org_v3:assignedAuthor/hl7-org_v3:representedOrganization", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
var countrorganization = allrorganization.snapshotLength;
//alert ("Total organization are :" + countrorganization);	 
 if (countrorganization !=0)
{
	//alert("organization are exist");     
	var referenceAP = allrorganization.snapshotItem(0);
    author.insertBefore(newObject,referenceAP);
}
else	 
{ 
	author.appendChild(newObject);
}	
}; 



//F5
function addNewAssignedPerson() {
//alert( "Value of assignedPersonIndex is " + scratchInstance.getElementsByTagName("assignedPersonIndex") [0].childNodes[0].nodeValue) ;
var index=scratchInstance.getElementsByTagName("assignedPersonIndex") [0].childNodes[0].nodeValue;
var allassignedPerson = buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:dataEnterer", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
var countassignedPerson = allassignedPerson.snapshotLength;
//alert ("Total Subject are : " + countassignedPerson);
if (countassignedPerson > 0)
{
alert( "Only one Record is allowed to add in here!") ;
}
else
{
	appendassignedPerson();
}
 };

	
function deleteAssignedPerson()
{
//alert("delete function");
var index=scratchInstance.getElementsByTagName("assignedPersonIndex") [0].childNodes[0].nodeValue-1;
var allassignedPerson = buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:dataEnterer", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
	var subassignedPerson  = allassignedPerson.snapshotItem(index);
		subassignedPerson.parentNode.removeChild(subassignedPerson);		
};


/*function insertassignedPerson() {
//alert("Coming into the positional Insert function");
var newElement= getNodesetTemplate("addassignedPerson", "dataEnterer");
//alert("new Element is :"+ newElement);
var parentElement = buildInstance.evaluate("/hl7-org_v3:document", buildInstance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
//alert("Parent Element is :"+ parentElement);
var index =scratchInstance.getElementsByTagName("assignedPersonIndex") [0].textContent;
var allassignedPersonNodes=buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:dataEnterer", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
var referenceElement = allassignedPersonNodes.snapshotItem(index-1);
//alert("Reference Element is :"+ referenceElement);
var elementToInsert= referenceElement.singleNodeValue;
parentElement.insertBefore(newElement,referenceElement.nextSibling);};*/

function appendassignedPerson() {
  var newObject = getNodesetTemplate("addassignedPerson", "dataEnterer");
 		 var verifierCount = countChildElements("verifier");		   
		 var definition1Count = countChildElements("definition1");		   
        <!-- var definition2Count = countChildElements("definition2");		   -->
		 var relatedDocumentCount = countChildElements("relatedDocument");		   
		 var componentCount = countChildElements("component");		 
		 var parentElement = buildInstance.evaluate("/hl7-org_v3:document", buildInstance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
		   
	 if (verifierCount !=0)
		{
			//alert("verifier exist");     
			var verifier =buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:verifier", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
			var referenceElement = verifier.snapshotItem(0);
			parentElement.insertBefore(newObject,referenceElement);
	   }  
	   
	 	   	 else if (definition1Count !=0)
		{
			//alert("definition1 exist");     
			var definition1 =buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:definition1", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
			var referenceElement = definition1.snapshotItem(0);
				parentElement.insertBefore(newObject,referenceElement);
	   }  	   
	   
	
		 	else if (relatedDocumentCount !=0)
		{
			//alert("relatedDocument exist");     
			var relatedDocument =buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:relatedDocument", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
			var referenceElement = relatedDocumentsnapshotItem(0);
					parentElement.insertBefore(newObject,referenceElement);
	   }  	     
	   
	   	 	else if (componentCount !=0)
		{
			//alert("component exist");     
			var component =buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:component", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
			var referenceElement = component.snapshotItem(0);
					parentElement.insertBefore(newObject,referenceElement);
	   }  	     

	else
	{
	//alert('Document is empty, append nodes document')
	parentElement.appendChild(newObject);
	  }
 }; 


//F5.0

function addNewReporg() {
//alert( "Value of reporgIndex is " + scratchInstance.getElementsByTagName("reporgIndex") [0].childNodes[0].nodeValue) ;
var index=scratchInstance.getElementsByTagName("reporgIndex") [0].childNodes[0].nodeValue;
var assignedPersonIndex = scratchInstance.getElementsByTagName("assignedPersonIndex") [0].childNodes[0].nodeValue;
var parentAP = buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:dataEnterer/hl7-org_v3:assignedPerson", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
var AP = parentAP.snapshotItem( assignedPersonIndex - 1 );
var allreporg = buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:dataEnterer/hl7-org_v3:assignedPerson/hl7-org_v3:representedOrganization", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
var countreporg = allreporg.snapshotLength;
//alert ("Total reporg are :" + countreporg);
	if (countreporg > 0)
	{
	alert( "Only one Represented Organization is allowed to add in here!") ;
		}
	else
	{
	appendreporg(assignedPersonIndex);
	} 
};


function deleteReporg()
{
//alert("delete function");
var allreporg = buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:dataEnterer/hl7-org_v3:assignedPerson/hl7-org_v3:representedOrganization", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
var index=scratchInstance.getElementsByTagName("reporgIndex") [0].childNodes[0].nodeValue -1;
var suborgpartof = allreporg.snapshotItem(index);
suborgpartof.parentNode.removeChild(suborgpartof);		
};


function appendreporg(assignedPersonIndex)
 {
 var newObject = getNodesetTemplate("addRepOrg", "representedOrganization");
 var assignedPersonIndex = assignedPersonIndex
 var allparent = buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:dataEnterer/hl7-org_v3:assignedPerson", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
 var parent = allparent.snapshotItem(assignedPersonIndex -1);
	 //alert('allAuthors:' +allAuthors)
	parent.appendChild(newObject);
}; 


//F5.1

 function countChildAp(child)
{
var apcount = buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:dataEnterer/hl7-org_v3:assignedPerson/hl7-org_v3:assignedPerson/hl7-org_v3:"+child , buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
return apcount.snapshotLength;
};


//F5.1

 function countChildAp(child)
{
var apcount = buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:dataEnterer/hl7-org_v3:assignedPerson/hl7-org_v3:assignedPerson/hl7-org_v3:"+child, buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
return apcount.snapshotLength;
};


function addNewLicence() {
//alert( "Value of licenceIndex is " + scratchInstance.getElementsByTagName("licenceIndex") [0].childNodes[0].nodeValue) ;
var index=scratchInstance.getElementsByTagName("licenceIndex") [0].childNodes[0].nodeValue;
 var newObject = getNodesetTemplate("addasLicensedEntity", "asLicensedEntity");
var assignedPersonIndex = scratchInstance.getElementsByTagName("assignedPersonIndex") [0].childNodes[0].nodeValue -1;
var parentAP = buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:dataEnterer/hl7-org_v3:assignedPerson/hl7-org_v3:assignedPerson", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
var AP = parentAP.snapshotItem(assignedPersonIndex);
var AP = parentAP.snapshotItem( assignedPersonIndex);
          var asMemberCount = countChildAp("asMember");					
          var asRoleOtherCount = countChildAp("asRoleOther");
                  	
	 if (asMemberCount !=0)
		{
			var asMember =buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:dataEnterer/hl7-org_v3:assignedPerson/hl7-org_v3:assignedPerson/hl7-org_v3:asMember", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
			var referenceAP = asMember.snapshotItem(0);
			AP.insertBefore(newObject,referenceAP);
	   }
	   
	   	else if (asRoleOtherCount !=0)
		{
	var asRoleOther =buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:dataEnterer/hl7-org_v3:assignedPerson/hl7-org_v3:assignedPerson/hl7-org_v3:asRoleOther", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
			var referenceAP = asRoleOther.snapshotItem(0);
			AP.insertBefore(newObject,referenceAP);
	   }
	
else
	{
	AP.appendChild(newObject);
	  }

};

	   
function deleteLicence()
{
var alllicence = buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:dataEnterer/hl7-org_v3:assignedPerson/hl7-org_v3:assignedPerson/hl7-org_v3:asLicensedEntity", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
var index=scratchInstance.getElementsByTagName("licenceIndex") [0].childNodes[0].nodeValue -1;
var suborgpartof = alllicence.snapshotItem(index);
suborgpartof.parentNode.removeChild(suborgpartof);		
};

function appendlicence(assignedPersonIndex) {
alert("append function");
 var newObject = getNodesetTemplate("addasLicensedEntity", "asLicensedEntity");
 var assignedPersonIndex = scratchInstance.getElementsByTagName("assignedPersonIndex") [0].childNodes[0].nodeValue;
var parentAP = buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:dataEnterer/hl7-org_v3:assignedPerson/hl7-org_v3:assignedPerson", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
var AP = parentAP.snapshotItem( assignedPersonIndex);
 alert("ApOrder")
          var asMemberCount = countChildAp("asMember");					
          var asRoleOtherCount = countChildAp("asRoleOther");
                  	
	 if (asMemberCount !=0)
		{
			alert("asMember exist");     
			var asMember =buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:dataEnterer/hl7-org_v3:assignedPerson/hl7-org_v3:assignedPerson/hl7-org_v3:asMember", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
			var referenceAP = asMember.snapshotItem(0);
			AP.insertBefore(newObject,referenceAP);
	   }
	   
	   	else if (asRoleOtherCount !=0)
		{
			alert("asRoleOther exist");     
			var asRoleOther =buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:dataEnterer/hl7-org_v3:assignedPerson/hl7-org_v3:assignedPerson/hl7-org_v3:asRoleOther", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
			var referenceAP = asRoleOther.snapshotItem(0);
			AP.insertBefore(newObject,referenceAP);
	   }
	
else
	{
	alert('Ap is empty, append nodes Ap')
	AP.appendChild(newObject);
	  }
}; 


//F5.2
function addNewMember() {
alert( "Value of memberIndex is " + scratchInstance.getElementsByTagName("memberIndex") [0].childNodes[0].nodeValue) ;
var index=scratchInstance.getElementsByTagName("memberIndex") [0].childNodes[0].nodeValue;
var assignedPersonIndex = scratchInstance.getElementsByTagName("assignedPersonIndex") [0].childNodes[0].nodeValue;
var parentAP = buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:dataEnterer/hl7-org_v3:assignedPerson/hl7-org_v3:assignedPerson", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
var AP = parentAP.snapshotItem( assignedPersonIndex - 1 );
var allmember = buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:dataEnterer/hl7-org_v3:assignedPerson/hl7-org_v3:assignedPerson/hl7-org_v3:asMember", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
var countmember = allmember.snapshotLength;
alert ("Total Member are :" + countmember);
	if (countmember==0)
	{
	appendmember(assignedPersonIndex);
	}
	else
	{
	insertmember(index);
	} 
};


function deleteMember()
{
//alert("delete function");
var allmember = buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:dataEnterer/hl7-org_v3:assignedPerson/hl7-org_v3:assignedPerson/hl7-org_v3:asMember", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
var index=scratchInstance.getElementsByTagName("memberIndex") [0].childNodes[0].nodeValue -1;
var suborgpartof = allmember.snapshotItem(index);
suborgpartof.parentNode.removeChild(suborgpartof);		
};


function insertmember(index) {
alert("Coming into the positional Insert function");
var newElement= getNodesetTemplate("addasMember", "asMember");
alert("new Element is :"+ newElement);
var assignedPersonIndex = scratchInstance.getElementsByTagName("assignedPersonIndex") [0].childNodes[0].nodeValue;
var parentAP = buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:dataEnterer/hl7-org_v3:assignedPerson/hl7-org_v3:assignedPerson", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
var AP = parentAP.snapshotItem( assignedPersonIndex - 1 );
//alert("Parent Element is :"+ parentElement);
var index =scratchInstance.getElementsByTagName("memberIndex") [0].textContent;
var allmemberNodes=buildInstance.evaluate("/hl7-org_v3:asMember", AP, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
var referenceElement = allmemberNodes.snapshotItem(index-1);
alert("Reference Element is :"+ referenceElement);
<!--var elementToInsert= referenceElement.singleNodeValue;-->
AP.insertBefore(newElement,referenceElement);};

function appendmember(assignedPersonIndex) {
 var newObject = getNodesetTemplate("addasMember", "asMember");
 var assignedPersonIndex = scratchInstance.getElementsByTagName("assignedPersonIndex") [0].childNodes[0].nodeValue;
var parentAP = buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:dataEnterer/hl7-org_v3:assignedPerson/hl7-org_v3:assignedPerson", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
var AP = parentAP.snapshotItem( assignedPersonIndex - 1 );
          var asRoleOtherCount = countChildAp("asRoleOther");
          var asLocatedEntityCount = countChildAp("asLocatedEntity");
       	   
	  if (asRoleOtherCount !=0)
		{
			alert("asRoleOther exist");     
			var asRoleOther =buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:dataEnterer/hl7-org_v3:assignedPerson/hl7-org_v3:assignedPerson/hl7-org_v3:asRoleOther", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
			var referenceAp = asRoleOther.snapshotItem(0);
			AP.insertBefore(newObject,referenceAp);
	   }  
	else
	{
	alert('Ap is empty, append nodes Ap')
	AP.appendChild(newObject);
	  }
}; 

//F5.3
function addNewRole() {
//alert( "Value of roleIndex is " + scratchInstance.getElementsByTagName("roleIndex") [0].childNodes[0].nodeValue) ;
var index=scratchInstance.getElementsByTagName("roleIndex") [0].childNodes[0].nodeValue;
 var assignedPersonIndex = scratchInstance.getElementsByTagName("assignedPersonIndex") [0].childNodes[0].nodeValue;
var parentAP = buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:dataEnterer/hl7-org_v3:assignedPerson/hl7-org_v3:assignedPerson", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
var AP = parentAP.snapshotItem( assignedPersonIndex - 1 );
var allrole = buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:dataEnterer/hl7-org_v3:assignedPerson/hl7-org_v3:assignedPerson/hl7-org_v3:asRoleOther", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
var countrole = allrole.snapshotLength;
//alert ("Total role are :" + countrole);
	if (countrole==0)
	{
	appendrole(assignedPersonIndex);
	}
	else
	{
	insertrole(index);
	} 
};

	   
function deleteRole()
{
//alert("delete function");
var allrole = buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:dataEnterer/hl7-org_v3:assignedPerson/hl7-org_v3:assignedPerson/hl7-org_v3:asRoleOther", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
var index=scratchInstance.getElementsByTagName("roleIndex") [0].childNodes[0].nodeValue -1;
var suborgpartof = allrole.snapshotItem(index);
suborgpartof.parentNode.removeChild(suborgpartof);		
};


function insertrole(index) {
//alert("Coming into the positional Insert function");
var newElement= getNodesetTemplate("addasRoleOther", "asRoleOther");
//alert("new Element is :"+ newElement);
var assignedPersonIndex = scratchInstance.getElementsByTagName("assignedPersonIndex") [0].childNodes[0].nodeValue;
var parentAP = buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:dataEnterer/hl7-org_v3:assignedPerson/hl7-org_v3:assignedPerson", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
var AP = parentAP.snapshotItem( assignedPersonIndex - 1 );
var index =scratchInstance.getElementsByTagName("roleIndex") [0].textContent;
var allroleNodes=buildInstance.evaluate("/hl7-org_v3:asRoleOther", AP, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
var referenceElement = allroleNodes.snapshotItem(index-1);
//alert("Reference Element is :"+ referenceElement);
//var elementToInsert= referenceElement.singleNodeValue;
AP.insertBefore(newElement,referenceElement);};

function appendrole(assignedPersonIndex) {
 var newObject = getNodesetTemplate("addasRoleOther", "asRoleOther");
 var assignedPersonIndex = scratchInstance.getElementsByTagName("assignedPersonIndex") [0].childNodes[0].nodeValue;
var parentAP = buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:dataEnterer/hl7-org_v3:assignedPerson/hl7-org_v3:assignedPerson", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
var AP = parentAP.snapshotItem( assignedPersonIndex - 1 );
	//alert('Ap is empty, append nodes Ap')
	AP.appendChild(newObject);
	}; 


//F5.3.1

function countChildRo(child)
{
var Rocount = buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:dataEnterer/hl7-org_v3:assignedPerson/hl7-org_v3:assignedPerson/hl7-org_v3:asRoleOther"+child , buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
return Rocount.snapshotLength;
};


function addNewOrgpartof() {
//alert( "Value of orgpartofIndex is " + scratchInstance.getElementsByTagName("orgpartofIndex") [0].childNodes[0].nodeValue) ;
var index=scratchInstance.getElementsByTagName("orgpartofIndex") [0].childNodes[0].nodeValue;
var roleIndex = scratchInstance.getElementsByTagName("roleIndex") [0].childNodes[0].nodeValue;
var parentAP = buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:dataEnterer/hl7-org_v3:assignedPerson/hl7-org_v3:assignedPerson/hl7-org_v3:asRoleOther/hl7-org_v3:scopingOrganization", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
var AP = parentAP.snapshotItem( roleIndex - 1 );
var allorgpartof = buildInstance.evaluate("/hl7-org_v3:asOrganizationPartOf", AP, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
var countorgpartof = allorgpartof.snapshotLength;
//alert ("Total orgpartof are :" + countorgpartof);
	if (countorgpartof==0)
	{
	appendorgpartof(roleIndex);
	}
	else
	{
	insertorgpartof(index);
	} 
};


function deleteOrgpartof()
{
//alert("delete function");
var allorgpartof = buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:dataEnterer/hl7-org_v3:assignedPerson/hl7-org_v3:assignedPerson/hl7-org_v3:asRoleOther/hl7-org_v3:scopingOrganization/hl7-org_v3:asOrganizationPartOf", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
var index=scratchInstance.getElementsByTagName("orgpartofIndex") [0].childNodes[0].nodeValue -1;
var suborgpartof = allorgpartof.snapshotItem(index);
suborgpartof.parentNode.removeChild(suborgpartof);		
};



function insertorgpartof(index) {
//alert("Coming into the positional Insert function");
var newElement= getNodesetTemplate("addasOrganizationPartOf ", "asOrganizationPartOf");
//alert("new Element is :"+ newElement);
var roleIndex = scratchInstance.getElementsByTagName("roleIndex") [0].childNodes[0].nodeValue;
var parentAP = buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:dataEnterer/hl7-org_v3:assignedPerson/hl7-org_v3:assignedPerson/hl7-org_v3:asRoleOther/hl7-org_v3:scopingOrganization", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
var AP = parentAP.snapshotItem( roleIndex - 1 );
//alert("Parent Element is :"+ parentElement);
var index =scratchInstance.getElementsByTagName("orgpartofIndex") [0].textContent;
var allorgpartofNodes=buildInstance.evaluate("/hl7-org_v3:asOrganizationPartOf", AP, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
var referenceElement = allorgpartofNodes.snapshotItem(index-1);
//alert("Reference Element is :"+ referenceElement);
//var elementToInsert= referenceElement.singleNodeValue;
AP.insertBefore(newElement,referenceElement);};

function appendorgpartof(roleindex) {
 var newObject = getNodesetTemplate("addasOrganizationPartOf ", "asOrganizationPartOf");
 var roleIndex = scratchInstance.getElementsByTagName("roleIndex") [0].childNodes[0].nodeValue;
var parentAP = buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:dataEnterer/hl7-org_v3:assignedPerson/hl7-org_v3:assignedPerson/hl7-org_v3:asRoleOther/hl7-org_v3:scopingOrganization", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
var AP = parentAP.snapshotItem( roleIndex - 1 );
   var contactPartyCount = countChildRo("contactParty");
   var organizationContainsCount = countChildRo("organizationContains");
 		
 if (contactPartyCount !=0)
		{
			//alert("contactParty exist");     
			var contactParty =buildInstance.evaluate("/hl7-org_v3:contactParty", AP, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
			var referenceRo = contactParty.snapshotItem(0);
			AP.insertBefore(newObject,referenceRo);
	   }
	   
	   	else if (organizationContainsCount !=0)
		{
			//alert("organizationContains exist");     
			var organizationContains =buildInstance.evaluate("/hl7-org_v3:organizationContains", AP, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
			var referenceRo = organizationContains.snapshotItem(0);
			AP.insertBefore(newObject,referenceRo);
	   }  
	   
else
	{
	//alert('Ro is empty, append nodes Ro')
	AP.appendChild(newObject);
	  }
}; 

//F5.3.2
function addNewContactp() {
//alert( "Value of contactpIndex is " + scratchInstance.getElementsByTagName("contactpIndex") [0].childNodes[0].nodeValue) ;
var index=scratchInstance.getElementsByTagName("contactpIndex") [0].childNodes[0].nodeValue;
var roleIndex = scratchInstance.getElementsByTagName("roleIndex") [0].childNodes[0].nodeValue;
var parentAP = buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:dataEnterer/hl7-org_v3:assignedPerson/hl7-org_v3:assignedPerson/hl7-org_v3:asRoleOther/hl7-org_v3:scopingOrganization", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
var AP = parentAP.snapshotItem( roleIndex - 1 );
var allcontactp = buildInstance.evaluate("/hl7-org_v3:contactParty", AP, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
var countcontactp = allcontactp.snapshotLength;
//alert ("Total contactp are :" + countcontactp);
	if (countcontactp==0)
	{
	appendcontactp(roleIndex);
	}
	else
	{
	insertcontactp(index);
	} 
};


function deleteContactp()
{
//alert("delete function");
var allcontactp = buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:dataEnterer/hl7-org_v3:assignedPerson/hl7-org_v3:assignedPerson/hl7-org_v3:asRoleOther/hl7-org_v3:scopingOrganization/hl7-org_v3:contactParty", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
var index=scratchInstance.getElementsByTagName("contactpIndex") [0].childNodes[0].nodeValue -1;
	var subcontactp = allcontactp.snapshotItem(index);
	subcontactp.parentNode.removeChild(subcontactp);		
};


function insertcontactp(index) {
//alert("Coming into the positional Insert function");
var newElement= getNodesetTemplate("addcontactParty", "contactParty");
var roleIndex = scratchInstance.getElementsByTagName("roleIndex") [0].childNodes[0].nodeValue;
var parentAP = buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:dataEnterer/hl7-org_v3:assignedPerson/hl7-org_v3:assignedPerson/hl7-org_v3:asRoleOther/hl7-org_v3:scopingOrganization", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
var AP = parentAP.snapshotItem( roleIndex - 1 );
var index =scratchInstance.getElementsByTagName("contactpIndex") [0].textContent;
var allcontactpNodes=buildInstance.evaluate("/hl7-org_v3:contactParty", AP, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
var referenceElement = allcontactpNodes.snapshotItem(index-1);
//alert("Reference Element is :"+ referenceElement);
//var elementToInsert= referenceElement.singleNodeValue;
AP.insertBefore(newElement,referenceElement);};

function appendcontactp(roleIndex) {
 var newObject = getNodesetTemplate("addcontactParty", "contactParty");
 var roleIndex = scratchInstance.getElementsByTagName("roleIndex") [0].childNodes[0].nodeValue;
var parentAP = buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:dataEnterer/hl7-org_v3:assignedPerson/hl7-org_v3:assignedPerson/hl7-org_v3:asRoleOther/hl7-org_v3:scopingOrganization", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
var AP = parentAP.snapshotItem( roleIndex - 1 );

 var organizationContainsCount = countChildRo("organizationContains");
 		
  if (organizationContainsCount !=0)
		{
			//alert("organizationContains exist");     
			var organizationContains =buildInstance.evaluate("/hl7-org_v3:organizationContains", AP, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
			var referenceRo = organizationContains.snapshotItem(0);
			AP.insertBefore(newObject,referenceRo);
	   }  
	   
else
	{
	//alert('Ro is empty, append nodes Ro')
	AP.appendChild(newObject);
	  }
}; 

//F5.3.3
function addNewOrgcont() {
//alert( "Value of orgcontIndex is " + scratchInstance.getElementsByTagName("orgcontIndex") [0].childNodes[0].nodeValue) ;
var index=scratchInstance.getElementsByTagName("orgcontIndex") [0].childNodes[0].nodeValue;
 var roleIndex = scratchInstance.getElementsByTagName("roleIndex") [0].childNodes[0].nodeValue;
var parentAP = buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:dataEnterer/hl7-org_v3:assignedPerson/hl7-org_v3:assignedPerson/hl7-org_v3:asRoleOther/hl7-org_v3:scopingOrganization", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
var AP = parentAP.snapshotItem( roleIndex - 1 );
var allorgcont = buildInstance.evaluate("/hl7-org_v3:organizationContains", AP, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
var countorgcont = allorgcont.snapshotLength;
//alert ("Total orgcont are :" + countorgcont);
	if (countorgcont==0)
	{
	appendorgcont(roleIndex);
	}
	else
	{
	insertorgcont(index);
	} 
};


function deleteOrgcont()
{
//alert("delete function");
var allorgcont = buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:dataEnterer/hl7-org_v3:assignedPerson/hl7-org_v3:assignedPerson/hl7-org_v3:asRoleOther/hl7-org_v3:scopingOrganization/hl7-org_v3:organizationContains", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
	var suborgcont = allorgcont.snapshotItem(index);
	var index=scratchInstance.getElementsByTagName("orgcontIndex") [0].childNodes[0].nodeValue-1;
	suborgcont.parentNode.removeChild(suborgcont);		
};


function insertorgcont(iindex) {
//alert("Coming into the positional Insert function");
var newElement= getNodesetTemplate("addorganizationContains", "organizationContains"); var roleIndex = scratchInstance.getElementsByTagName("roleIndex") [0].childNodes[0].nodeValue;
var parentAP = buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:dataEnterer/hl7-org_v3:assignedPerson/hl7-org_v3:assignedPerson/hl7-org_v3:asRoleOther/hl7-org_v3:scopingOrganization", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
var AP = parentAP.snapshotItem( roleIndex - 1 );
var index =scratchInstance.getElementsByTagName("orgcontIndex") [0].textContent;
var allorgcontNodes=buildInstance.evaluate("/hl7-org_v3:organizationContains", AP, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
var referenceElement = allorgcontNodes.snapshotItem(index-1);
//alert("Reference Element is :"+ referenceElement);
//var elementToInsert= referenceElement.singleNodeValue;
AP.insertBefore(newElement,referenceElement);};

function appendorgcont(roleIndex) {
 var newObject = getNodesetTemplate("addorganizationContains", "organizationContains"); 
 var roleIndex = scratchInstance.getElementsByTagName("roleIndex") [0].childNodes[0].nodeValue;
var parentAP = buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:dataEnterer/hl7-org_v3:assignedPerson/hl7-org_v3:assignedPerson/hl7-org_v3:asRoleOther/hl7-org_v3:scopingOrganization", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
var AP = parentAP.snapshotItem( roleIndex - 1 );
 	{
	//alert('Ro is empty, append nodes Ro')
	AP.appendChild(newObject);
	  }
}; 

//F5.4
function addNewLocated() {
//alert( "Value of locatedIndex is " + scratchInstance.getElementsByTagName("locatedIndex") [0].childNodes[0].nodeValue) ;
var index=scratchInstance.getElementsByTagName("locatedIndex") [0].childNodes[0].nodeValue;
var assignedPersonIndex = scratchInstance.getElementsByTagName("assignedPersonIndex") [0].childNodes[0].nodeValue;
var parentAP = buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:dataEnterer/hl7-org_v3:assignedPerson/hl7-org_v3:assignedPerson", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
var AP = parentAP.snapshotItem( assignedPersonIndex - 1 );
var alllocated = buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:dataEnterer/hl7-org_v3:assignedPerson/hl7-org_v3:assignedPerson/hl7-org_v3:asLocatedEntity", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
var countlocated = alllocated.snapshotLength;
//alert ("Total located are :" + countlocated);
if (countlocated> 0)
{
alert( "Only one location is allowed to add in here!") 
}
else
{
	appendlocated(assignedPersonIndex);
	}
};


function appendlocated(assignedPersonIndex) {
 var newObject = getNodesetTemplate("addasLocatedEntity", "asLocatedEntity");
 var assignedPersonIndex = scratchInstance.getElementsByTagName("assignedPersonIndex") [0].childNodes[0].nodeValue;
var parentAP = buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:dataEnterer/hl7-org_v3:assignedPerson/hl7-org_v3:assignedPerson", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
var AP = parentAP.snapshotItem( assignedPersonIndex - 1 );
{
	//alert('Ap is empty, append nodes Ap')
	AP.appendChild(newObject);
	  }
}; 


//F6
 function addNewvPerson() {
//alert( "Value of vpersonIndex is " + scratchInstance.getElementsByTagName("vpersonIndex") [0].childNodes[0].nodeValue) ;
var index=scratchInstance.getElementsByTagName("vpersonIndex") [0].childNodes[0].nodeValue;
var allvperson = buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:verifier", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
var countvperson = allvperson.snapshotLength;
//alert ("Total Subject are : " + countvperson);
	if (countvperson ==0)
	{
	appendvperson();
	}
	else
	{
	insertvperson(index);
	} };
	
	
function deletePerson()
{
//alert("delete function");
var index=scratchInstance.getElementsByTagName("vpersonIndex") [0].childNodes[0].nodeValue-1;
var allvperson = buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:verifier", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
	var subPerson  = allvperson.snapshotItem(index);
		subPerson.parentNode.removeChild(subPerson);		
};	
	

function insertvperson(index) {
//alert("Coming into the positional Insert function");
var newElement= getNodesetTemplate("addVassignedPerson", "verifier");
//alert("new Element is :"+ newElement);
var parentElement = buildInstance.evaluate("/hl7-org_v3:document", buildInstance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
//alert("Parent Element is :"+ parentElement);
var index =scratchInstance.getElementsByTagName("vpersonIndex") [0].textContent;
var allvpersonNodes=buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:verifier", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
var referenceElement = allvpersonNodes.snapshotItem(index-1);
//alert("Reference Element is :"+ referenceElement);
var elementToInsert= referenceElement.singleNodeValue;
parentElement.insertBefore(newElement,referenceElement.nextSibling);};

function appendvperson() {
 var newObject = getNodesetTemplate("addVassignedPerson", "verifier");
 	 var definition1Count = countChildElements("definition1");		   
         <!--var definition2Count = countChildElements("definition2");	-->	   
		 var relatedDocumentCount = countChildElements("relatedDocument");		   
		 var componentCount = countChildElements("component");		 
		var parentElement = buildInstance.evaluate("/hl7-org_v3:document", buildInstance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;   
	 if (definition1Count !=0)
		{
			//alert("definition1 exist");     
			var definition1 =buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:definition1", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
			var referenceElement = definition1.snapshotItem(0);
				parentElement.insertBefore(newObject,referenceElement);
	   }  	   
	    
		 	else if (relatedDocumentCount !=0)
		{
			//alert("relatedDocument exist");     
			var relatedDocument =buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:relatedDocument", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
			var referenceElement = relatedDocumentsnapshotItem(0);
					parentElement.insertBefore(newObject,referenceElement);
	   }  	     
	   
		 	else if (componentCount !=0)
		{
			//alert("component exist");     
			var component =buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:component", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
			var referenceElement = component.snapshotItem(0);
					parentElement.insertBefore(newObject,referenceElement);
	   }  	 
	
	else
	{
	//alert('Document is empty, append nodes document')
	parentElement.appendChild(newObject);
	  }
}; 
   
  
//F6.0

function addNewvReporg() {
 var newObject = getNodesetTemplate("addvRepOrg", "representedOrganization");
var index = scratchInstance.getElementsByTagName("vreporgIndex") [0].childNodes[0].nodeValue -1;
var vpersonIndex = scratchInstance.getElementsByTagName("vpersonIndex") [0].childNodes[0].nodeValue -1;
var parentAP = buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:verifier/hl7-org_v3:assignedPerson", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
var AP = parentAP.snapshotItem( vpersonIndex);

AP.appendChild(newObject);



};  
  
 	   
function deletevReporg()
{
//alert("delete function");
var index = scratchInstance.getElementsByTagName("vpersonIndex") [0].childNodes[0].nodeValue -1;
var allVerifiers = buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:verifier/hl7-org_v3:assignedPerson", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
var verfier = allVerifiers.snapshotItem(index);
		var repORG = buildInstance.evaluate("hl7-org_v3:representedOrganization", verfier, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;   

repORG.parentNode.removeChild(repORG);		
};
 
  


  
  
  
   
   //F6.1
   
function countChildVAp(child)
{
var VApcount = buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:verifier/hl7-org_v3:assignedPerson/hl7-org_v3:assignedPerson/hl7-org_v3:"+child , buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
return VApcount.snapshotLength;
};  
   
function addNewvLicence() {
var newObject= getNodesetTemplate("addVasLicensedEntity", "asLicensedEntity");
var index = scratchInstance.getElementsByTagName("vlicenceIndex") [0].childNodes[0].nodeValue -1;
var vpersonIndex = scratchInstance.getElementsByTagName("vpersonIndex") [0].childNodes[0].nodeValue -1;
var parentAP = buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:verifier/hl7-org_v3:assignedPerson/hl7-org_v3:assignedPerson", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
var AP = parentAP.snapshotItem( vpersonIndex);
//alert("VApOrder")
          var asMemberCount = countChildVAp("asMember");
          var asRoleOtherCount = countChildVAp("asRoleOther");
          
  	if (asMemberCount !=0)
		{
			//alert("asMember exist");     
			var asMember =buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:verifier/hl7-org_v3:assignedPerson/hl7-org_v3:assignedPerson/hl7-org_v3:asMember", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
			var referenceAP = asMember .snapshotItem(0);
			AP.insertBefore(newObject,referenceAP);
	   }
	   
	   	else if (asRoleOtherCount !=0)
		{
			//alert("asRoleOther exist");     
			var asRoleOther =buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:verifier/hl7-org_v3:assignedPerson/hl7-org_v3:assignedPerson/hl7-org_v3:asRoleOther", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
			var referenceAP = asRoleOther.snapshotItem(0);
			AP.insertBefore(newObject,referenceAP);
	   }
	   
else
	{
	//alert('AP is empty, append nodes VAp')
	AP.appendChild(newObject);
	  }
};

	   
function deletevLicence()
{
var index = scratchInstance.getElementsByTagName("vpersonIndex") [0].childNodes[0].nodeValue -1;
var licIndex = scratchInstance.getElementsByTagName("vlicenceIndex") [0].childNodes[0].nodeValue -1;
var allVerifiers = buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:verifier/hl7-org_v3:assignedPerson/hl7-org_v3:assignedPerson", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
var verifier = allVerifiers.snapshotItem(index);
var theLicenses = buildInstance.evaluate("hl7-org_v3:asLicensedEntity", verifier, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
var thisLicense = theLicenses.snapshotItem(licIndex);
thisLicense.parentNode.removeChild(thisLicense);		


};


function insertvlicence(index) {
alert("Coming into the positional Insert function");
var newObject= getNodesetTemplate("addVasLicensedEntity", "asLicensedEntity");
alert("new Object is :"+ newObject);
var vpersonIndex = scratchInstance.getElementsByTagName("vpersonIndex") [0].childNodes[0].nodeValue;
var parentAP = buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:verifier/hl7-org_v3:assignedPerson/hl7-org_v3:assignedPerson", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
var AP = parentAP.snapshotItem( vpersonIndex - 1 );
var index =scratchInstance.getElementsByTagName("vlicenceIndex") [0].textContent;
var allvlicenceNodes=buildInstance.evaluate("/hl7-org_v3:asLicensedEntity", AP, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
var referenceElement = allvlicenceNodes.snapshotItem(index-1);
alert("Reference Element is :"+ referenceElement);
<!--var elementToInsert= referenceElement.singleNodeValue;-->
AP.insertBefore(newObject,referenceElement);};

function appendvlicence(vpersonIndex) {
 var newObject = getNodesetTemplate("addVasLicensedEntity", "asLicensedEntity");
var vpersonIndex = scratchInstance.getElementsByTagName("vpersonIndex") [0].childNodes[0].nodeValue;
 var parentAP = buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:verifier/hl7-org_v3:assignedPerson/hl7-org_v3:assignedPerson", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
 var AP = parentAP.snapshotItem( vpersonIndex - 1 );
 //alert("VApOrder")
          var asMemberCount = countChildVAp("asMember");
          var asRoleOtherCount = countChildVAp("asRoleOther");
          
  	if (asMemberCount !=0)
		{
			//alert("asMember exist");     
			var asMember =buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:verifier/hl7-org_v3:assignedPerson/hl7-org_v3:assignedPerson/hl7-org_v3:asMember", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
			var referenceAP = asMember .snapshotItem(0);
			AP.insertBefore(newObject,referenceAP);
	   }
	   
	   	else if (asRoleOtherCount !=0)
		{
			//alert("asRoleOther exist");     
			var asRoleOther =buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:verifier/hl7-org_v3:assignedPerson/hl7-org_v3:assignedPerson/hl7-org_v3:asRoleOther", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
			var referenceAP = asRoleOther.snapshotItem(0);
			AP.insertBefore(newObject,referenceAP);
	   }
	   
else
	{
	//alert('AP is empty, append nodes VAp')
	AP.appendChild(newObject);
	  }
};


//F6.2
function addNewvMember() {
//alert( "Value of vmemberIndex is " + scratchInstance.getElementsByTagName("vmemberIndex") [0].childNodes[0].nodeValue) ;
var index=scratchInstance.getElementsByTagName("vmemberIndex") [0].childNodes[0].nodeValue;
var vpersonIndex = scratchInstance.getElementsByTagName("vpersonIndex") [0].childNodes[0].nodeValue;
var parentAP = buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:verifier/hl7-org_v3:assignedPerson/hl7-org_v3:assignedPerson", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
var AP = parentAP.snapshotItem( vpersonIndex - 1 );
var allvmember = buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:verifier/hl7-org_v3:assignedPerson/hl7-org_v3:assignedPerson/hl7-org_v3:asMember", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
var countvmember = allvmember.snapshotLength;
//alert ("Total vmember are :" + countvmember);
	if (countvmember==0)
	{
	appendvmember(vpersonIndex);
	}
	else
	{
	insertvmember(index);
	} 
};


	   
function deletevMember()
{
//alert("delete function");
var allvmember = buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:verifier/hl7-org_v3:assignedPerson/hl7-org_v3:assignedPerson/hl7-org_v3:asMember", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
var index=scratchInstance.getElementsByTagName("vmemberIndex") [0].childNodes[0].nodeValue -1;
var suborgpartof = allvmember.snapshotItem(index);
suborgpartof.parentNode.removeChild(suborgpartof);		
};

function insertvmember(index) {
//alert("Coming into the positional Insert function");
var newElement= getNodesetTemplate("addVasMember", "asMember");
//alert("new Element is :"+ newElement);
var vpersonIndex = scratchInstance.getElementsByTagName("vpersonIndex") [0].childNodes[0].nodeValue;
var parentAP = buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:verifier/hl7-org_v3:assignedPerson/hl7-org_v3:assignedPerson", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
var AP = parentAP.snapshotItem( vpersonIndex - 1 );
var index =scratchInstance.getElementsByTagName("vmemberIndex") [0].textContent;
var allvmemberNodes=buildInstance.evaluate("/hl7-org_v3:asMember", AP, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
var referenceElement = allvmemberNodes.snapshotItem(index-1);
//alert("Reference Element is :"+ referenceElement);
/*var elementToInsert= referenceElement.singleNodeValue;*/
AP.insertBefore(newElement,referenceElement);};

function appendvmember(vpersonIndex) {
 var newObject = getNodesetTemplate("addVasMember", "asMember");
 var vpersonIndex = scratchInstance.getElementsByTagName("vpersonIndex") [0].childNodes[0].nodeValue;
var parentAP = buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:verifier/hl7-org_v3:assignedPerson/hl7-org_v3:assignedPerson", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
var AP = parentAP.snapshotItem( vpersonIndex - 1 ); 
          var asRoleOtherCount = countChildVAp("asRoleOther");
           
 if (asRoleOtherCount !=0)
		{
			//alert("asRoleOther exist");     
			var asRoleOther =buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:verifier/hl7-org_v3:assignedPerson/hl7-org_v3:assignedPerson/hl7-org_v3:asRoleOther", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
			var referenceAP = asRoleOther.snapshotItem(0);
			AP.insertBefore(newObject,referenceAP);
	   }   
else
	{
	//alert('VAp is empty, append nodes VAp')
	AP.appendChild(newObject);
	  }
}; 


//F6.3
function addNewvRole() {
//alert( "Value of vroleIndex is " + scratchInstance.getElementsByTagName("vroleIndex") [0].childNodes[0].nodeValue) ;
var index=scratchInstance.getElementsByTagName("vroleIndex") [0].childNodes[0].nodeValue;
var vpersonIndex = scratchInstance.getElementsByTagName("vpersonIndex") [0].childNodes[0].nodeValue;
var parentAP = buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:verifier/hl7-org_v3:assignedPerson/hl7-org_v3:assignedPerson", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
var AP = parentAP.snapshotItem( vpersonIndex - 1 );
var allvrole = buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:verifier/hl7-org_v3:assignedPerson/hl7-org_v3:assignedPerson/hl7-org_v3:asRoleOther", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
var countvrole = allvrole.snapshotLength;
//alert ("Total vrole are :" + countvrole);
	if (countvrole==0)
	{
	appendvrole(vpersonIndex);
	}
	else
	{
	insertvrole(index);
	} 
};


function deletevRole()
{
//alert("delete function");
var allvrole = buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:verifier/hl7-org_v3:assignedPerson/hl7-org_v3:assignedPerson/hl7-org_v3:asRoleOther", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
var index=scratchInstance.getElementsByTagName("vroleIndex") [0].childNodes[0].nodeValue -1;
var suborgpartof = allvrole.snapshotItem(index);
suborgpartof.parentNode.removeChild(suborgpartof);		
};


function insertvrole(index) {
//alert("Coming into the positional Insert function");
var newElement= getNodesetTemplate("addVasRoleOther", "asRoleOther");
//alert("new Element is :"+ newElement);
var vpersonIndex = scratchInstance.getElementsByTagName("vpersonIndex") [0].childNodes[0].nodeValue;
var parentAP = buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:verifier/hl7-org_v3:assignedPerson/hl7-org_v3:assignedPerson", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
var AP = parentAP.snapshotItem( vpersonIndex - 1 );
var index =scratchInstance.getElementsByTagName("vroleIndex") [0].textContent;
var allvroleNodes=buildInstance.evaluate("/hl7-org_v3:asRoleOther", AP, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
var referenceElement = allvroleNodes.snapshotItem(index-1);
//alert("Reference Element is :"+ referenceElement);
/*var elementToInsert= referenceElement.singleNodeValue;*/
AP.insertBefore(newElement,referenceElement);};


function appendvrole(vpersonIndex) {
 var newObject = getNodesetTemplate("addVasRoleOther", "asRoleOther");
 var vpersonIndex = scratchInstance.getElementsByTagName("vpersonIndex") [0].childNodes[0].nodeValue;
 var parentAP = buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:verifier/hl7-org_v3:assignedPerson/hl7-org_v3:assignedPerson", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
var AP = parentAP.snapshotItem( vpersonIndex - 1 );
          var asLocatedEntityCount = countChildVAp("asLocatedEntity");
	//alert('VAp is empty, append nodes VAp')
	AP.appendChild(newObject);
	}; 


//F6.3.1

function countChildVRo(child)
{
var VRocount = buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:verifier/hl7-org_v3:assignedPerson/hl7-org_v3:assignedPerson/hl7-org_v3:asRoleOther/hl7-org_v3:"+child , buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
return VRocount.snapshotLength;
};

function countChildVRo(child)
{
var VRocount = buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:verifier/hl7-org_v3:assignedPerson/hl7-org_v3:assignedPerson/hl7-org_v3:asRoleOther/hl7-org_v3:scopingOrganization/hl7-org_v3:"+child , buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
return VRocount.snapshotLength;
};

function addNewvOrgpartof() {
//alert( "Value of vorgpartofIndex is " + scratchInstance.getElementsByTagName("vorgpartofIndex") [0].childNodes[0].nodeValue) ;
var index=scratchInstance.getElementsByTagName("vorgpartofIndex") [0].childNodes[0].nodeValue;
var vpersonIndex = scratchInstance.getElementsByTagName("vpersonIndex") [0].childNodes[0].nodeValue;
var parentAP = buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:verifier/hl7-org_v3:assignedPerson/hl7-org_v3:assignedPerson/hl7-org_v3:asRoleOther/hl7-org_v3:scopingOrganization", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
var AP = parentAP.snapshotItem( vpersonIndex - 1 );
var allvorgpartof = buildInstance.evaluate("/hl7-org_v3:asOrganizationPartOf", AP, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
var countvorgpartof = allvorgpartof.snapshotLength;
//alert ("Total vorgpartof are :" + countvorgpartof);
	if (countvorgpartof==0)
	{
	appendvorgpartof(vpersonIndex);
	}
	else
	{
	insertvorgpartof(index);
	} 
};



function deletevOrgpartof()
{
//alert("delete function");
var allvorgpartof = buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:verifier/hl7-org_v3:assignedPerson/hl7-org_v3:assignedPerson/hl7-org_v3:asRoleOther/hl7-org_v3:scopingOrganization/hl7-org_v3:asOrganizationPartOf", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
var index=scratchInstance.getElementsByTagName("vorgpartofIndex") [0].childNodes[0].nodeValue -1;
var subvorgpartof = allvorgpartof.snapshotItem(index);
subvorgpartof.parentNode.removeChild(subvorgpartof);		
};



function insertvorgpartof(index) {
//alert("Coming into the positional Insert function");
var newElement= getNodesetTemplate("addasOrganizationPartOf ", "asOrganizationPartOf");
//alert("new Element is :"+ newElement);
var vpersonIndex = scratchInstance.getElementsByTagName("vpersonIndex") [0].childNodes[0].nodeValue;
var parentAP = buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:verifier/hl7-org_v3:assignedPerson/hl7-org_v3:assignedPerson/hl7-org_v3:asRoleOther/hl7-org_v3:scopingOrganization", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
var AP = parentAP.snapshotItem( vpersonIndex - 1 );
var index =scratchInstance.getElementsByTagName("vorgpartofIndex") [0].textContent;
var allvorgpartofNodes=buildInstance.evaluate("/hl7-org_v3:asOrganizationPartOf", AP, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
var referenceElement = allvorgpartofNodes.snapshotItem(index-1);
//alert("Reference Element is :"+ referenceElement);
/*var elementToInsert= referenceElement.singleNodeValue;*/
AP.insertBefore(newElement,referenceElement);};


function appendvorgpartof(vpersonIndex) {
 var newObject = getNodesetTemplate("addasOrganizationPartOf ", "asOrganizationPartOf");
var vpersonIndex = scratchInstance.getElementsByTagName("vpersonIndex") [0].childNodes[0].nodeValue;
var parentAP = buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:verifier/hl7-org_v3:assignedPerson/hl7-org_v3:assignedPerson/hl7-org_v3:asRoleOther/hl7-org_v3:scopingOrganization", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
var AP = parentAP.snapshotItem( vpersonIndex - 1 );
   var contactPartyCount = countChildVRo("contactParty");
   var organizationContainsCount = countChildVRo("organizationContains");
 		
 if (contactPartyCount !=0)
		{
			//alert("contactParty exist");     
			var contactParty =buildInstance.evaluate("/hl7-org_v3:contactParty", AP, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
			var referenceAP = contactParty.snapshotItem(0);
			AP.insertBefore(newObject,referenceAP);
	   }
	   
	   	else if (organizationContainsCount !=0)
		{
			//alert("organizationContains exist");     
			var organizationContains =buildInstance.evaluate("/hl7-org_v3:organizationContains", AP, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
			var referenceAP = organizationContains.snapshotItem(0);
			AP.insertBefore(newObject,referenceAP);
	   }
   	   
else
	{
	//alert('AP is empty, append nodes VRo')
	AP.appendChild(newObject);
	  }
}; 


//F6.3.2

function addNewvContactp() {
//alert( "Value of vcontactpIndex is " + scratchInstance.getElementsByTagName("vcontactpIndex") [0].childNodes[0].nodeValue) ;
var index=scratchInstance.getElementsByTagName("vcontactpIndex") [0].childNodes[0].nodeValue;
var vpersonIndex = scratchInstance.getElementsByTagName("vpersonIndex") [0].childNodes[0].nodeValue;
var parentAP = buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:verifier/hl7-org_v3:assignedPerson/hl7-org_v3:assignedPerson/hl7-org_v3:asRoleOther/hl7-org_v3:scopingOrganization", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
var AP = parentAP.snapshotItem( vpersonIndex - 1 );
var allvcontactp = buildInstance.evaluate("/hl7-org_v3:contactParty", AP, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
var countvcontactp = allvcontactp.snapshotLength;
//alert ("Total vcontactp are :" + countvcontactp);
	if (countvcontactp==0)
	{
	appendvcontactp(vpersonIndex);
	}
	else
	{
	insertvcontactp(index);
	} 
};


function deletevContactp()
{
//alert("delete function");
var allvcontactp = buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:verifier/hl7-org_v3:assignedPerson/hl7-org_v3:assignedPerson/hl7-org_v3:asRoleOther/hl7-org_v3:scopingOrganization/hl7-org_v3:contactParty", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
var index=scratchInstance.getElementsByTagName("vcontactpIndex") [0].childNodes[0].nodeValue -1;
var subvcontactp = allvcontactp.snapshotItem(index);
subvcontactp.parentNode.removeChild(subvcontactp);		
};



function insertvcontactp() {
//alert("Coming into the positional Insert function");
var newElement= getNodesetTemplate("addVcontactParty", "contactParty");
//alert("new Element is :"+ newElement);
var vpersonIndex = scratchInstance.getElementsByTagName("vpersonIndex") [0].childNodes[0].nodeValue;
var parentAP = buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:verifier/hl7-org_v3:assignedPerson/hl7-org_v3:assignedPerson/hl7-org_v3:asRoleOther/hl7-org_v3:scopingOrganization", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
var AP = parentAP.snapshotItem( vpersonIndex - 1 );
var index =scratchInstance.getElementsByTagName("vcontactpIndex") [0].textContent;
var allvcontactpNodes=buildInstance.evaluate("/hl7-org_v3:contactParty", AP, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
var referenceElement = allvcontactpNodes.snapshotItem(index-1);
//alert("Reference Element is :"+ referenceElement);
AP.insertBefore(newElement,referenceElement);};

function appendvcontactp(vpersonIndex) {
   var newObject = getNodesetTemplate("addVcontactParty", "contactParty");
   var vpersonIndex = scratchInstance.getElementsByTagName("vpersonIndex") [0].childNodes[0].nodeValue;
var parentAP = buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:verifier/hl7-org_v3:assignedPerson/hl7-org_v3:assignedPerson/hl7-org_v3:asRoleOther/hl7-org_v3:scopingOrganization", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
var AP = parentAP.snapshotItem( vpersonIndex - 1 );
   var organizationContainsCount = countChildVRo("organizationContains");
  		
 if (organizationContainsCount !=0)
		{
			//alert("organizationContains exist");     
			var organizationContains =buildInstance.evaluate("/hl7-org_v3:organizationContains", AP, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
			var referenceAP = organizationContains.snapshotItem(0);
			AP.insertBefore(newObject,referenceAP);
	   }
else
	{
	AP.appendChild(newObject);
	  }
}; 

//F6.3.3

function addNewvOrgcont() {
//alert( "Value of vorgcontIndex is " + scratchInstance.getElementsByTagName("vorgcontIndex") [0].childNodes[0].nodeValue) ;
var index=scratchInstance.getElementsByTagName("vorgcontIndex") [0].childNodes[0].nodeValue;
var vpersonIndex = scratchInstance.getElementsByTagName("vpersonIndex") [0].childNodes[0].nodeValue;
var parentAP = buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:verifier/hl7-org_v3:assignedPerson/hl7-org_v3:assignedPerson/hl7-org_v3:asRoleOther/hl7-org_v3:scopingOrganization", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
var AP = parentAP.snapshotItem( vpersonIndex - 1 );
var allvorgcont = buildInstance.evaluate("/hl7-org_v3:organizationContains", AP, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
var countvorgcont = allvorgcont.snapshotLength;
//alert ("Total vorgcont are :" + countvorgcont);
	if (countvorgcont==0)
	{
	appendvorgcont(vpersonIndex);
	}
	else
	{
	insertvorgcont(index);
	} 
};


function deletevOrgcont()
{
//alert("delete function");
var allvorgcont = buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:verifier/hl7-org_v3:assignedPerson/hl7-org_v3:assignedPerson/hl7-org_v3:asRoleOther/hl7-org_v3:scopingOrganization/hl7-org_v3:organizationContains", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
var index=scratchInstance.getElementsByTagName("vorgcontIndex") [0].childNodes[0].nodeValue -1;
var subvorgcont = allvorgcont.snapshotItem(index);
subvorgcont.parentNode.removeChild(subvorgcont);		
};

function insertvorgcont() {
//alert("Coming into the positional Insert function");
var newElement= getNodesetTemplate("addorganizationContains", "organizationContains");
//alert("new Element is :"+ newElement);
var vpersonIndex = scratchInstance.getElementsByTagName("vpersonIndex") [0].childNodes[0].nodeValue;
var parentAP = buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:verifier/hl7-org_v3:assignedPerson/hl7-org_v3:assignedPerson/hl7-org_v3:asRoleOther/hl7-org_v3:hl7-org_v3:scopingOrganization", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
var AP = parentAP.snapshotItem( vpersonIndex - 1 );
var index =scratchInstance.getElementsByTagName("vorgcontIndex") [0].textContent;
var allvorgcontNodes=buildInstance.evaluate("/hl7-org_v3:organizationContains", AP, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
var referenceElement = allvorgcontNodes.snapshotItem(index-1);
//alert("Reference Element is :"+ referenceElement);
AP.insertBefore(newElement,referenceElement);};

function appendvorgcont(vpersonIndex) {
 var newObject = getNodesetTemplate("addorganizationContains", "organizationContains");
 var vpersonIndex = scratchInstance.getElementsByTagName("vpersonIndex") [0].childNodes[0].nodeValue;
var parentAP = buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:verifier/hl7-org_v3:assignedPerson/hl7-org_v3:assignedPerson/hl7-org_v3:asRoleOther/hl7-org_v3:scopingOrganization", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
var AP = parentAP.snapshotItem( vpersonIndex - 1 );
 	{
	//alert('VRo is empty, append nodes VRo')
	AP.appendChild(newObject);
	  }
}; 



//F6.4
function addNewvLocated() {
//alert( "Value of vlocatedIndex is " + scratchInstance.getElementsByTagName("vlocatedIndex") [0].childNodes[0].nodeValue) ;
var index=scratchInstance.getElementsByTagName("vlocatedIndex") [0].childNodes[0].nodeValue;
var vpersonIndex = scratchInstance.getElementsByTagName("vpersonIndex") [0].childNodes[0].nodeValue;
var parentAP = buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:verifier/hl7-org_v3:assignedPerson/hl7-org_v3:assignedPerson", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
var countparent = parentAP.snapshotLength;
//alert ("Total countparent are :" + countparent);
var AP = parentAP.snapshotItem( vpersonIndex - 1 );
var allvlocated = buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:verifier/hl7-org_v3:assignedPerson/hl7-org_v3:assignedPerson/hl7-org_v3:asLocatedEntity", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
var countvlocated = allvlocated.snapshotLength;
//alert ("Total vlocated are :" + countvlocated);
if (countvlocated  != countparent-1)
{
alert( "Only one location is allowed to be added in here!") 
}
else
{
		appendvlocated(vpersonIndex);
}	
};

function appendvlocated(vpersonIndex) {
 var newObject = getNodesetTemplate("addVasLocatedEntity", "asLocatedEntity");
 var vpersonIndex = scratchInstance.getElementsByTagName("vpersonIndex") [0].childNodes[0].nodeValue;
 var parentAP = buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:verifier/hl7-org_v3:assignedPerson/hl7-org_v3:assignedPerson", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
var AP = parentAP.snapshotItem( vpersonIndex - 1 );
<!--var parentVAp = buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:verifier/hl7-org_v3:assignedPerson/hl7-org_v3:assignedPerson", buildInstance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;-->
	{
	//alert('VAp is empty, append nodes VAp')
	AP.appendChild(newObject);
	  }
}; 

//F7

//F9
function addNewRelatedDocument()
{
//alert( "Value of relatedDocIndex is " + scratchInstance.getElementsByTagName("relatedDocIndex") [0].childNodes[0].nodeValue) ;
var index=scratchInstance.getElementsByTagName("relatedDocIndex") [0].childNodes[0].nodeValue;
var allrelatedDoc = buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:relatedDocument", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
var countrelatedDoc = allrelatedDoc.snapshotLength;
//alert ("Total Subject are : " + countrelatedDoc);
	if (countrelatedDoc ==0)
	{
	appendFirstRelatedDoc();
	}
	else
	{
	insertPositionalRelatedDoc(index);
	} 
};


function deleteRelatedDocument()
{
//alert("delete function");
	var index=scratchInstance.getElementsByTagName("relatedDocIndex") [0].childNodes[0].nodeValue-1;
var allrelatedDoc = buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:relatedDocument", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
	var subrelatedDoc = allrelatedDoc.snapshotItem(index);

	subrelatedDoc.parentNode.removeChild(subrelatedDoc);		
};



function insertPositionalRelatedDoc() {
//alert("Coming into the positional Insert function");
var newElement= getNodesetTemplate("addRelatedDocument", "relatedDocument");
//alert("new Element is :"+ newElement);
var parentElement = buildInstance.evaluate("/hl7-org_v3:document", buildInstance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
//alert("Parent Element is :"+ parentElement);
var index =scratchInstance.getElementsByTagName("relatedDocIndex") [0].textContent;
var allrelatedDocNodes =buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:relatedDocument", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
var referenceElement = allrelatedDocNodes.snapshotItem(index-1);
//alert("Reference Element is :"+ referenceElement);
var elementToInsert= referenceElement.singleNodeValue;
//alert("elementToInsert :"+ elementToInsert);
parentElement.insertBefore(newElement,referenceElement.nextSibling);
//alert("parentElement insertBefore");
};

function appendFirstRelatedDoc() {
 var newObject = getNodesetTemplate("addRelatedDocument", "relatedDocument");
		 var componentCount = countChildElements("component");		 
		var parentElement = buildInstance.evaluate("/hl7-org_v3:document", buildInstance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;   
 if (componentCount !=0)
		{
			//alert("component exist");     
			var component =buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:component", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
			var referenceElement = component.snapshotItem(0);
					parentElement.insertBefore(newObject,referenceElement);
	   }  	     
	
	else
	{
	//alert('Document is empty, append nodes document')
	parentElement.appendChild(newObject);
	  }
}; 




//F10 
function addNewComponent() {
alert( "Only one Component is allowed to add in here!")
//alert( "Value of componentIndex is " + scratchInstance.getElementsByTagName("componentIndex") [0].childNodes[0].nodeValue) ;
var index=scratchInstance.getElementsByTagName("componentIndex") [0].childNodes[0].nodeValue;
var allcomponent = buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:component/hl7-org_v3:structuredBody/hl7-org_v3:component/hl7-org_v3:section", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
var countcomponent = allcomponent.snapshotLength;
//alert ("Total Subject are :" + countcomponent);
	if (countcomponent==0)
	{
	appendcomponent();
	}
	else
	{
	insertcomponent(index);
	} 
};

function insertcomponent() {
//alert("Coming into the positional Insert function");
var newElement= getNodesetTemplate("addcomponent", "component");
//alert("new Element is :"+ newElement);
var parentElement = buildInstance.evaluate("/hl7-org_v3:document", buildInstance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
//alert("Parent Element is :"+ parentElement);
var index =scratchInstance.getElementsByTagName("componentIndex") [0].textContent;
var allcomponentNodes=buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:component/hl7-org_v3:structuredBody/hl7-org_v3:component/hl7-org_v3:section", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
var referenceElement = allcomponentNodes.snapshotItem(index-1);
//alert("Reference Element is :"+ referenceElement);
var elementToInsert= referenceElement.singleNodeValue;
parentElement.insertBefore(newElement,referenceElement.nextSibling);};

function appendcomponent() {
  var newObject = getNodesetTemplate("addcomponent", "component");
  var parentElement = buildInstance.evaluate("/hl7-org_v3:document", buildInstance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;   
 
	//alert('Document is empty, append nodes document')
	parentElement.appendChild(newObject);
	  };


 /*-------------------------------------------import--------------------------------------------------------------------------*/
 

function setLoadInstanceSD() {
    var loadFilename = scratchInstance.getElementsByTagName("studyDesignFilename")  [0];
    document.getElementById("load_study_design").setAttribute("action", "file:///" + encodeURI(loadFilename.textContent));
   }


function setLoadInstanceSP() {
    var loadFilename = scratchInstance.getElementsByTagName("studyParticipationFilename")  [0];
    document.getElementById("load_study_participation").setAttribute("action", "file:///" + encodeURI(loadFilename.textContent));
   }


function setInstanceModelSD() {
   sdInstance = model.getInstanceDocument("instance_sd");    
}


function setInstanceModelSP() {
   spInstance = model.getInstanceDocument("instance_sp");    
};


 function checkloadSD() 
 {
 	var SDidSnapshot = sdInstance.evaluate("/hl7-org_v3:plannedStudy", sdInstance, nsResolver, XPathResult.BOOLEAN_TYPE, null).booleanValue;
	if( SDidSnapshot == true)
	{
		scratchInstance.getElementsByTagName("SDInputMessage") [0].childNodes[0].nodeValue = 'Yes';	
		//OpenSuccess()
	}
	else
	{
		scratchInstance.getElementsByTagName("studyDesignFilename") [0].childNodes[0].nodeValue = '';	
		SDOpenFail()
		return;
	};
	 
 //check if DEF has been loaded
var DEFID = buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:definition1/hl7-org_v3:actDefinition/hl7-org_v3:id", buildInstance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;			
var DEFrootID = DEFID.getAttributeNode("root").nodeValue;
var DEFextensionID = DEFID.getAttributeNode("extension").nodeValue;


if (DEFrootID =="" && DEFextensionID =="")
{
//alert('This is the first time import!')
//alert('This is SD import file!')
var SDID = sdInstance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:id", sdInstance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
//alert('SDID   '   + SDID);
	var SDrootID = SDID.getAttributeNode("root").nodeValue;
//alert('SDrootID:  '   +SDrootID)
	var SDextensionID = SDID.getAttributeNode("extension").nodeValue;
	scratchInstance.getElementsByTagName("SDMessageCorrect") [0].childNodes[0].nodeValue='Yes' 
//alert('SDextensionID:  '  +SDextensionID)
}  
else  
{
//alert('This is NOT the first time import!')
// Get Study ID Root and Extension from Design
	var SDID = sdInstance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:id", sdInstance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
//alert('SDID   '   + SDID);
	var SDrootID = SDID.getAttributeNode("root").nodeValue;
//alert('SDrootID:  '   +SDrootID)
	var SDextensionID = SDID.getAttributeNode("extension").nodeValue;
//alert('SDextensionID:  '  +SDextensionID)
			
			// Check the study design root and extension ids against the DFID and DIFD_EXT
			if ( DEFrootID == SDrootID && DEFextensionID == SDextensionID)
		   {
			//alert('Definition all ID is the same as study design')		
			scratchInstance.getElementsByTagName("SDMessageCorrect") [0].childNodes[0].nodeValue='Yes'
			SDImportSuccess()
			setDeaultSaveName();
			}
			else
			{
			scratchInstance.getElementsByTagName("studyDesignFilename") [0].childNodes[0].nodeValue = '';	
			alert('The Study Design message does not match the Sudject Data message. Please Import the correct file.')	
			}
}  //DEF exist true 
};  //function checkSDload


function checkloadSP() 
{
	var SPidSnapshot = spInstance.evaluate("//hl7-org_v3:instantiation", spInstance, nsResolver, XPathResult.BOOLEAN_TYPE, null).booleanValue;	
	if ( SPidSnapshot == true)
	{
		scratchInstance.getElementsByTagName("SPInputMessage") [0].childNodes[0].nodeValue = 'Yes';	

	}
	else
	{
		scratchInstance.getElementsByTagName("studyParticipationFilename") [0].childNodes[0].nodeValue = '';	
		SPOpenFail();
		return;
	}


var SDID = sdInstance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:id", sdInstance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
var SDrootID = SDID.getAttributeNode("root").nodeValue;
var SDextensionID = SDID.getAttributeNode("extension").nodeValue;
			
if (SDID == null)
{
alert('Please import Study Design Message first!')
}
else
{
//alert('Check SPID exist!')
var SPID_EXISTS = spInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:instantiation/hl7-org_v3:plannedStudy/hl7-org_v3:id", spInstance, nsResolver, XPathResult.BOOLEAN_TYPE, null).booleanValue;
	if ( SPID_EXISTS == true)
	{
// Set SPID Root and Extension in Particpation
	var SPID = spInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:instantiation/hl7-org_v3:plannedStudy/hl7-org_v3:id", spInstance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;		
	var SProotID = SPID.getAttributeNode("root").nodeValue;
	var SPextensionID = SPID.getAttributeNode("extension").nodeValue;

	if (SDrootID == SProotID && SDextensionID == SPextensionID)
		{  
		alert('Correct Messages Loaded');

var DEFID = buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:definition1/hl7-org_v3:actDefinition/hl7-org_v3:id", buildInstance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;			
var DEFrootID = buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:definition1/hl7-org_v3:actDefinition/hl7-org_v3:id", buildInstance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.getAttributeNode("root").nodeValue;	
var DEFextensionID = buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:definition1/hl7-org_v3:actDefinition/hl7-org_v3:id", buildInstance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.getAttributeNode("extension").nodeValue;	
var studyDocumentrootID = buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:id", buildInstance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue
if (studyDocumentrootID.getAttributeNode("root").nodeValue == '')
{
studyDocumentrootID.setAttribute("root",SDrootID)
}
else
{

}


if (DEFrootID == "")
{
				// Set Definition ID in Subject Data
				DEFID.setAttribute("root", SDrootID); 
				//alert('setDEFrootID:' +SDrootID)
				DEFID.setAttribute("extension", SDextensionID); 
				//alert('setDEFextensionID:' +SDextensionID)
		scratchInstance.getElementsByTagName("SDMessageCorrect") [0].childNodes[0].nodeValue='Yes'
		scratchInstance.getElementsByTagName("SPMessageCorrect") [0].childNodes[0].nodeValue='Yes' 
		setDeaultSaveName();
		}
		else //DEFrootID !=null
		{
			if ( DEFrootID == SDrootID && DEFextensionID == SDextensionID)
		   {
			//alert('Definition all ID is the same as study design')		
			scratchInstance.getElementsByTagName("SDMessageCorrect") [0].childNodes[0].nodeValue='Yes'
			scratchInstance.getElementsByTagName("SPMessageCorrect") [0].childNodes[0].nodeValue='Yes' 
					setDeaultSaveName();
			}
		    else
		    {
		    alert('The Study Participation Message did not match the Study Design Message, please import the correct message.')
		    		scratchInstance.getElementsByTagName("studyParticipationFilename") [0].childNodes[0].nodeValue = '';	
		    }
		}
		
		}  //SDID matchSPID
			
		else
		{
		   alert('The Study Participation Message did not match the Study Design Message, please import the correct message.')
		   		scratchInstance.getElementsByTagName("studyParticipationFilename") [0].childNodes[0].nodeValue = '';	
		}		
	}
    else //SPID_EXISTS is false
    {
     //alert('SPID_EXISTS is false')
	  alert('You have not import correct SP file!')
    }
}  //SDID not 0

};   //function checkloadSP
	
/*###########################################################################*/	
function SBidExist() {

	var SBidSnapshot = buildInstance.evaluate("/hl7-org_v3:document", buildInstance, nsResolver, XPathResult.BOOLEAN_TYPE, null).booleanValue;
	if( SBidSnapshot == true)
	{
		scratchInstance.getElementsByTagName("SBMessage") [0].childNodes[0].nodeValue = 'Yes';	
		//OpenSuccess()
	}
	else
	{
		SBOpenFail();
	}
	var calledFromOpen = 'true';
subjectAllocationCheck(calledFromOpen) 
};


    // ------------------- For Section / Clinical Statement   ------------------
 function getStuffFromSD() 
 {

 var studyDesingOpened = scratchInstance.getElementsByTagName("SDFileOpened") [0].childNodes[0].nodeValue;
 		
 if (studyDesingOpened == 'No')
 {
return;
 }
var studyComponent1s = sdInstance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:component4/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1", sdInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);

 var firstSequence = "";
 var firstSequenceIndex = 0;
	for ( var c1=0 ;  c1 < studyComponent1s.snapshotLength ; c1++ )
	{
		var path = studyComponent1s.snapshotItem(c1)
		
		var  sequence = buildInstance.evaluate("hl7-org_v3:sequenceNumber", path, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.getAttributeNode("value").nodeValue;

			if ( firstSequence > sequence || firstSequence == "" )
			{
				firstSequence = sequence
				firstSequenceIndex = c1
			}
	}
	
	var firstPath = studyComponent1s.snapshotItem(firstSequenceIndex)
	var firstEpochName = buildInstance.evaluate("hl7-org_v3:timePointEventDefinition/hl7-org_v3:id", firstPath, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.getAttributeNode("extension").nodeValue;

	scratchInstance.getElementsByTagName("firstEpochName") [0].childNodes[0].nodeValue = firstEpochName;
	scratchInstance.getElementsByTagName("firstEpochSequence") [0].childNodes[0].nodeValue =	firstSequence;
};



 function subjectAllocationCheck(calledFromOpen) 
{
var calledFromOpen = calledFromOpen;
	if (calledFromOpen == 'true')
	{
				//Check to see if allocation has alread occured
						 var allObservations= buildInstance.evaluate("//hl7-org_v3:sourceOf2/hl7-org_v3:observation", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
								 for ( var s=0 ; s < allObservations.snapshotLength; s++ )
								{
										var observation = allObservations.snapshotItem(s);
									  var observationCode= buildInstance.evaluate("hl7-org_v3:code", observation, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.getAttributeNode("code").nodeValue;
									   if( observationCode == 'Allocate')
									   {		
								var arm = buildInstance.evaluate("hl7-org_v3:value", observation, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.textContent;
								scratchInstance.getElementsByTagName("assignedArm") [0].childNodes[0].nodeValue=arm;						   
								//alert('Subject has already been assigned to arm.' + arm)
							   break;
						   }
						}
	}
	else
	{
		//Check to see if allocation has alread occured
						 var allObservations= buildInstance.evaluate("//hl7-org_v3:sourceOf2/hl7-org_v3:observation", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
								 for ( var s=0 ; s < allObservations.snapshotLength; s++ )
								{
										var observation = allObservations.snapshotItem(s);
									  var observationCode= buildInstance.evaluate("hl7-org_v3:code", observation, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.getAttributeNode("code").nodeValue;
									   if( observationCode == 'Allocate')
									   {									   
										//alert('Subject has already been assigned to arm.')
										   thisValue = 'AlreadyAssigned'
										   return thisValue;
										   break;
									   }
								  }

			}
	}



 function addNewAllObservations() 
 {
 var firstEpochName = scratchInstance.getElementsByTagName("firstEpochName") [0].childNodes[0].nodeValue
 var firstEpochSequence = scratchInstance.getElementsByTagName("firstEpochSequence") [0].childNodes[0].nodeValue
 var firstEpochEncounter = scratchInstance.getElementsByTagName("firstEpochEncounter") [0].childNodes[0].nodeValue
var sectionForObservation = 'StudyObservations'
 var trackingID = getNodesetTemplate("updateThisEntry", "id");
 var generatedID = generateID()
scratchInstance.getElementsByTagName("updatingThisEncounter") [0].childNodes[0].nodeValue = generatedID

	if (sectionForObservation == "")
		{
			alert('Please select Document Section.')
			return;
		}
	else
		{

		 
	 // Empty Encounter Instance
	var currentSection =  encounterInstance.evaluate("/hl7-org_v3:data/hl7-org_v3:section", encounterInstance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
	try{
	var currentEntry =  encounterInstance.evaluate("hl7-org_v3:entry", currentSection, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
	currentSection.removeChild(currentEntry)
	}
	catch(err)	{ }	


		var studyComponent1s = sdInstance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:component4/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1", sdInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
	
		// Loop through all Elements
		 for ( var i=0 ; i < studyComponent1s.snapshotLength; i++ )
		{
		var j = 0;
		var e = 0;
		var se= 0;										
			var studyComponent1 = studyComponent1s.snapshotItem(i);
		
			var cellName = sdInstance.evaluate("hl7-org_v3:timePointEventDefinition/hl7-org_v3:id", studyComponent1, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.getAttributeNode("extension").nodeValue;

			if(cellName == firstEpochName)
			{
			
				var allComponent2s = sdInstance.evaluate("hl7-org_v3:timePointEventDefinition/hl7-org_v3:component1/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component2", studyComponent1, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);

					// Loop through all allComponent2s of Cell
					 for ( var e=0 ; e < allComponent2s.snapshotLength; e++ )
					{
						var se= 0;
						var component2 = allComponent2s.snapshotItem(e);

					var encounterID = sdInstance.evaluate("hl7-org_v3:encounter/hl7-org_v3:id", component2, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.getAttributeNode("extension").nodeValue;

						if(encounterID == firstEpochEncounter)
						{
						
						// Place in Encounter Scratch Instance
						var section =  encounterInstance.evaluate("/hl7-org_v3:data/hl7-org_v3:section", encounterInstance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
						//Add entry
						var newEntry = getNodesetTemplate("addEntry", "entry");
						 section.appendChild(newEntry);
						
						  var entryInScratch= encounterInstance.evaluate("hl7-org_v3:entry", section, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue
						 
						//Add From Study Design
						var sectionEntrys =  encounterInstance.evaluate("hl7-org_v3:entry", section, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
						var entryCounter = sectionEntrys.snapshotLength
						var sectionEntry = sectionEntrys.snapshotItem(entryCounter -1);

						//Encounter from study design
						var sdEncounter = sdInstance.evaluate("hl7-org_v3:encounter", component2, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.cloneNode(true);
						sectionEntry.appendChild(sdEncounter);
						var sdEncounterID = sdInstance.evaluate("hl7-org_v3:encounter/hl7-org_v3:id", component2, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.getAttributeNode("extension").nodeValue;
						
						var sdEncounterIDs = encounterInstance.evaluate("//hl7-org_v3:encounter/hl7-org_v3:id", encounterInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
						var idForGeneratedID = sdEncounterIDs.snapshotItem(1);
						idForGeneratedID.setAttribute("extension", generatedID);					
						
						//Find Location in Study Design - If not at element level, check cell level for location

						var SDelementLocationExist = sdInstance.evaluate("../hl7-org_v3:location/hl7-org_v3:serviceDeliveryLocation/hl7-org_v3:location/hl7-org_v3:id", component2, nsResolver, XPathResult.BOOLEAN_TYPE, null).booleanValue;
						
						if( SDelementLocationExist == true)
						{	
						var SDLocation = sdInstance.evaluate("../hl7-org_v3:location/hl7-org_v3:serviceDeliveryLocation/hl7-org_v3:location/hl7-org_v3:id", component2, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.getAttributeNode("extension").nodeValue;
						}
						
						else
						{
						var SDcellLocationExist = sdInstance.evaluate("../../../hl7-org_v3:location/hl7-org_v3:serviceDeliveryLocation/hl7-org_v3:location/hl7-org_v3:id", component2, nsResolver, XPathResult.BOOLEAN_TYPE, null).booleanValue;
							if( SDcellLocationExist == true)
							{	
							var SDLocation = sdInstance.evaluate("../../../hl7-org_v3:location/hl7-org_v3:serviceDeliveryLocation/hl7-org_v3:location/hl7-org_v3:id", component2, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.getAttributeNode("extension").nodeValue;
							}
						}
										
					//Location Exists in Study Design
					if(SDelementLocationExist == true || SDcellLocationExist  == true)
					{	
					var newLocation = getNodesetTemplate("addLocationCS", "location");
					
					var encounterForLocation = encounterInstance.evaluate("hl7-org_v3:encounter", sectionEntry, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue
					var referenceElement = encounterInstance.evaluate("hl7-org_v3:sourceOf2", encounterForLocation, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue	
				
				 encounterForLocation.appendChild(newLocation);	 

					
					//Find location in Study Participation
					var SPlocations = spInstance.evaluate("//hl7-org_v3:location/hl7-org_v3:serviceDeliveryLocation", spInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
					var countOfLocations = SPlocations.snapshotLength

						 for ( var l=0 ; l <SPlocations.snapshotLength; l++ )
						{
						var SPlocation = SPlocations.snapshotItem(l)

						var thisSPlocation = spInstance.evaluate("hl7-org_v3:location", SPlocation, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue
	
						var SPlocationID = spInstance.evaluate("hl7-org_v3:id", thisSPlocation, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.getAttributeNode("extension").nodeValue;
						var SPlocationIName = spInstance.evaluate("hl7-org_v3:name", thisSPlocation, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.textContent;
						var SPlocationIAddr = spInstance.evaluate("hl7-org_v3:addr", thisSPlocation, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.cloneNode(true);

							if(SDLocation == SPlocationID)
							{
							var encounterLocation = encounterInstance.evaluate("hl7-org_v3:encounter/hl7-org_v3:location/hl7-org_v3:healthCareFacility/hl7-org_v3:serviceProviderOrganization/hl7-org_v3:id", sectionEntry, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue
								encounterLocation.setAttribute("extension", SPlocationID);	
								
							var encounterLocationName = encounterInstance.evaluate("hl7-org_v3:encounter/hl7-org_v3:location/hl7-org_v3:healthCareFacility/hl7-org_v3:serviceProviderOrganization/hl7-org_v3:name", sectionEntry, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue
							encounterLocationName.textContent = SPlocationIName
							
							var encounterLocationAddr = encounterInstance.evaluate("hl7-org_v3:encounter/hl7-org_v3:location/hl7-org_v3:healthCareFacility/hl7-org_v3:serviceProviderOrganization", sectionEntry, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue	
							encounterLocationAddr.appendChild(SPlocationIAddr);	 
							
							// Remove original blank address
							var encounterLocationAddrOrig = encounterInstance.evaluate("//hl7-org_v3:location/hl7-org_v3:healthCareFacility/hl7-org_v3:serviceProviderOrganization/hl7-org_v3:addr", encounterInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
							encounterLocationAddrOrig.snapshotItem(0).parentNode.removeChild(encounterLocationAddrOrig.snapshotItem(0));
							break;
							}
						}
						
						}
						
						
						
						//Observation from study design
						var sdObservations = sdInstance.evaluate("../hl7-org_v3:component1/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component2/hl7-org_v3:observation", component2, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
						
						 for ( var o=0 ; o < sdObservations.snapshotLength; o++ )
						 {
							var sdObservation = sdObservations.snapshotItem(o);
					
						var newSourceOf2 = getNodesetTemplate("addSourceOf2", "sourceOf2");
						//Add sourceOf2 for the CS in subject Data
						var encounterForSource = encounterInstance.evaluate("hl7-org_v3:encounter", sectionEntry, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue
						encounterForSource.appendChild(newSourceOf2);					
							
							// Function to Add Observations
							addObservationForCS(encounterForSource, sdObservation, o) 
							
						}// For all Observations
						
						var allNewObservations = encounterInstance.evaluate("//hl7-org_v3:observation", encounterInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
								
						 for ( var newO=0 ; newO < allNewObservations.snapshotLength; newO++ )
						 {
							var newObservation = allNewObservations.snapshotItem(newO);
					
						var newObservationCode = encounterInstance.evaluate("hl7-org_v3:code", newObservation, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.getAttributeNode("code").nodeValue;
						
						if(newObservationCode == 'Allocate')
						{
						var subjectAssigned = subjectAllocationCheck()
						 if (subjectAssigned == 'AlreadyAssigned')
						 {
						  // Empty Encounter Instance
							var currentSection =  encounterInstance.evaluate("/hl7-org_v3:data/hl7-org_v3:section", encounterInstance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
							try{
							var currentEntry =  encounterInstance.evaluate("hl7-org_v3:entry", currentSection, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
							currentSection.removeChild(currentEntry)
							}
							catch(err)	{ }	
						
						 return;
						 }
						 }
						
						}// For all Observations
						

						 
						// Copy the Encounter From scratch to the Build Instance
							 var allSections= buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:component/hl7-org_v3:structuredBody/hl7-org_v3:component/hl7-org_v3:section", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
		var sectionCounter = 	allSections.snapshotLength-1
								// Loop through all Elements
								var sectionExists = 'No'
								 for ( var s=0 ; s < allSections.snapshotLength; s++ )
								 {
								 var section = allSections.snapshotItem(s);
								 var sectionCode= buildInstance.evaluate("hl7-org_v3:code", section, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.getAttributeNode("code").nodeValue;
									 if(sectionForObservation == sectionCode)
									 {
										 sectionExists = 'Yes'
										
										 //Move entry from Subject Data to Encounter Scratch
										 var entryInScratch =  encounterInstance.evaluate("/hl7-org_v3:data/hl7-org_v3:section/hl7-org_v3:entry", encounterInstance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.cloneNode(true);
										 
										 
										 section.appendChild(entryInScratch);	 
										 
										 scratchInstance.getElementsByTagName("viewSection") [0].childNodes[0].nodeValue = sectionForObservation
										 scratchInstance.getElementsByTagName("viewEncounter") [0].childNodes[0].nodeValue = sdEncounterID
										 scratchInstance.getElementsByTagName("viewEncounterTime") [0].childNodes[0].nodeValue = ""
										 
										e = allComponent2s.snapshotLength;
										i = studyComponent1s.snapshotLength;
										break;
										 }
										
										else if (sectionCounter == s && sectionExists=='No')
										{

										var newSectionForObservation = getNodesetTemplate("addObservationSection", "component");
										var  path = buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:component/hl7-org_v3:structuredBody", buildInstance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue
										 path.appendChild(newSectionForObservation);	
										var allSections= buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:component/hl7-org_v3:structuredBody/hl7-org_v3:component/hl7-org_v3:section", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
										sectionCounter = s+1
										s = 0
										};

										}
										

									
								 } //viewSection = sectionCode				


							}; // if cellName == firstEpochName
							
						}; // For sub Elements loop
		
						} //for Elements loop
	
		}; //for Component1 Cells loop
	
	}; //sectionForObservation not null




 function checkSDSubjectType() 
{
	var humanElement = sdInstance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:subjectOf/hl7-org_v3:studyCharacteristic[./hl7-org_v3:value='Human Study']", sdInstance, nsResolver, XPathResult.BOOLEAN_TYPE, null).booleanValue  ;	
						if ( humanElement == true)   
							{
								 //alert('HUMAN STUDY');
								 scratchInstance.getElementsByTagName("TypeOfStudy") [0].childNodes[0].nodeValue='Human_Study';
							}
						else
								{
								var animalElement = sdInstance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:subjectOf/hl7-org_v3:studyCharacteristic[./hl7-org_v3:value='Animal Study']", sdInstance, nsResolver, XPathResult.BOOLEAN_TYPE, null).booleanValue  ;
									if ( animalElement == true)   
										{
										//alert('ANIMAL STUDY');
											 scratchInstance.getElementsByTagName("TypeOfStudy") [0].childNodes[0].nodeValue='Animal_Study';
										}
										else
										{
										}
								}
}

function addFieldsToStudyCS()
{
 checkSDSubjectType() 
var studyComponent2s = sdInstance.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/hl7-org_v3:component2/hl7-org_v3:encounter", sdInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
	
	for ( var i=0 ; i < studyComponent2s.snapshotLength; i++ )
	{
		var sdEncounter = studyComponent2s.snapshotItem(i);
		
		addCSEncounterID(sdEncounter) 
		addCSEncounterDetails(sdEncounter) 
		
	}
	
	


 function addCSEncounterID(sdEncounter) 
 {
  var secondID = getNodesetTemplate("addNewID", "id");
 var sdEncounter = sdEncounter
 		var referenceElement = sdInstance.evaluate("hl7-org_v3:id", sdEncounter, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue
		sdEncounter.insertBefore(secondID,referenceElement.nextSibling);
 		
 }


 function addCSEncounterDetails(sdEncounter) 
 {
  var effectiveTimeCS = getNodesetTemplate("addEffectiveTimeCS", "effectiveTime");
 var sdEncounter = sdEncounter
 		var referenceElements = sdInstance.evaluate("hl7-org_v3:id", sdEncounter, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null)
 		var referenceElement = referenceElements.snapshotItem(1);
		sdEncounter.insertBefore(effectiveTimeCS,referenceElement.nextSibling);
 }

	
	
var studyObservations = sdInstance.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/hl7-org_v3:component1/hl7-org_v3:timePointEventDefinition/hl7-org_v3:component2/hl7-org_v3:observation", sdInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
	
	for ( var o=0 ; o < studyObservations.snapshotLength; o++ )
	{
		var studyObservation = studyObservations.snapshotItem(o);
		
		addCSObservationTime(studyObservation) 
		addCSObservationValue(studyObservation) 
	}	
}

 function addCSObservationTime(studyObservation) 
 {
  var effectiveTimeCS = getNodesetTemplate("addEffectiveTimeCS", "effectiveTime");
 var studyObservation = studyObservation
 		var referenceElement = sdInstance.evaluate("hl7-org_v3:code", studyObservation, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue
		studyObservation.insertBefore(effectiveTimeCS,referenceElement.nextSibling);
 }


 function addCSObservationValue(studyObservation) 
 {
  var valueCS = getNodesetTemplate("addValueCS", "value");
 var studyObservation = studyObservation
 		var referenceElement = sdInstance.evaluate("hl7-org_v3:effectiveTime", studyObservation, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue
		studyObservation.insertBefore(valueCS,referenceElement.nextSibling);
 }

function addObservationTimeFromEncounter()
{
	var section =  encounterInstance.evaluate("/hl7-org_v3:data/hl7-org_v3:section", encounterInstance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
	
	var encounter = encounterInstance.evaluate("hl7-org_v3:entry/hl7-org_v3:encounter", section, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;

	var encounterEffectiveTime =  encounterInstance.evaluate("hl7-org_v3:effectiveTime", encounter, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.getAttributeNode("value").nodeValue;
	
	var allObservations =  encounterInstance.evaluate("hl7-org_v3:sourceOf2/hl7-org_v3:observation", encounter, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
	
		for ( var i=0 ; i < allObservations.snapshotLength; i++ )
	{
		var observation = allObservations.snapshotItem(i);
		addObservationTimeFromEncounter2(observation, encounterEffectiveTime)
	}
	
}

function addObservationTimeFromEncounter2(observation, encounterEffectiveTime)
{
var observation = observation
var encounterEffectiveTime = encounterEffectiveTime
	var observationTime =  encounterInstance.evaluate("hl7-org_v3:effectiveTime", observation, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue
	var observationEffectiveTime = observationTime.getAttributeNode("value").nodeValue;

	if( observationEffectiveTime == "")
	{
		observationTime.setAttribute("value", encounterEffectiveTime) ;
	}
}


function addObservationTimeFromEncounterAllView()
{
var index =  scratchInstance.getElementsByTagName("repeatEncounterForViewAll") [0].childNodes[0].nodeValue-1;

	var section =  buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:component/hl7-org_v3:structuredBody/hl7-org_v3:component/hl7-org_v3:section/hl7-org_v3:entry/hl7-org_v3:encounter",  buildInstance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
	
	var allEncounters =  buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:component/hl7-org_v3:structuredBody/hl7-org_v3:component/hl7-org_v3:section/hl7-org_v3:entry/hl7-org_v3:encounter",  buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
	 var thisEncounter = allEncounters.snapshotItem(index);
	 
	 	var allObservations = buildInstance.evaluate("hl7-org_v3:sourceOf2/hl7-org_v3:observation", thisEncounter, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);

	var encounterEffectiveTime =  encounterInstance.evaluate("hl7-org_v3:effectiveTime", thisEncounter, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.getAttributeNode("value").nodeValue;
	 
	 
		for ( var i=0 ; i < allObservations.snapshotLength; i++ )
	{
		var observation = allObservations.snapshotItem(i);
		addObservationTimeFromEncounterAllView2(observation, encounterEffectiveTime)
	}
	
}
function addObservationTimeFromEncounterAllView2(observation, encounterEffectiveTime)
{
var observation = observation
var encounterEffectiveTime = encounterEffectiveTime
	var observationTime =  buildInstance.evaluate("hl7-org_v3:effectiveTime", observation, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue
	var observationEffectiveTime = observationTime.getAttributeNode("value").nodeValue;

	if( observationEffectiveTime == "")
	{
		observationTime.setAttribute("value", encounterEffectiveTime) ;
	}
}


  function checkSubjectChange() 
{

var currentSelectedSubject = scratchInstance.getElementsByTagName("currentSelectedSubject") [0].childNodes[0].nodeValue;
var selectedSubject = scratchInstance.getElementsByTagName("selectedSubject") [0].childNodes[0].nodeValue;

		if (confirm ('Do you wish to change the subject from ' + currentSelectedSubject + ' to ' + selectedSubject + '?'))
		{
		
		}
		else
		{
		scratchInstance.getElementsByTagName("selectedSubject") [0].childNodes[0].nodeValue = currentSelectedSubject
		 var resetSubjectID= buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:subject/hl7-org_v3:researchSubject/hl7-org_v3:id", buildInstance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
		resetSubjectID.setAttribute("extension", currentSelectedSubject)
					setDeaultSaveName()
		}

}


function checkSPSubjectType()
{

var humanElement = spInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:component1/hl7-org_v3:studyActivitiesAtSite/hl7-org_v3:subject1/hl7-org_v3:experimentalUnit/hl7-org_v3:subjectPerson", spInstance, nsResolver, XPathResult.BOOLEAN_TYPE, null).booleanValue  ;	
	if ( humanElement == true)   
	{
		//alert('HUMAN STUDY');
		 scratchInstance.getElementsByTagName("TypeOfStudy") [0].childNodes[0].nodeValue='Human_Study';

	}
	else
			{
			var animalElement = spInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:component1/hl7-org_v3:studyActivitiesAtSite/hl7-org_v3:subject1/hl7-org_v3:experimentalUnit/hl7-org_v3:subjectNonPersonLivingSubject", spInstance, nsResolver, XPathResult.BOOLEAN_TYPE, null).booleanValue  ;	
			if ( animalElement == true)   
			{
				//alert('ANIMAL STUDY');
				 scratchInstance.getElementsByTagName("TypeOfStudy") [0].childNodes[0].nodeValue='Animal_Study';
			}
			else
			{
			};
	}
}




 function encounterToScratch() 
{
 var viewSection = scratchInstance.getElementsByTagName("viewSection") [0].childNodes[0].nodeValue
 var viewEncounter = scratchInstance.getElementsByTagName("viewEncounter") [0].childNodes[0].nodeValue
 var viewEncounterTime = scratchInstance.getElementsByTagName("viewEncounterTime") [0].childNodes[0].nodeValue

	 // Empty Encounter Instance
	var currentSection =  encounterInstance.evaluate("/hl7-org_v3:data/hl7-org_v3:section", encounterInstance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
	try{
	var currentEntry =  encounterInstance.evaluate("hl7-org_v3:entry", currentSection, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
	currentSection.removeChild(currentEntry)
	}
	catch(err)	{ }			

																	
//Find encounter in subject data and add to encoutner scratch for editing																	
	 var allSections= buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:component/hl7-org_v3:structuredBody/hl7-org_v3:component/hl7-org_v3:section", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);

	
		// Loop through all Sections
		 for ( var i=0 ; i < allSections.snapshotLength; i++ )
		 {
		 var section = allSections.snapshotItem(i);
		 var sectionCode= buildInstance.evaluate("hl7-org_v3:code", section, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.getAttributeNode("code").nodeValue;

		 if(viewSection == sectionCode)
		 {
		  var allEntries= buildInstance.evaluate("hl7-org_v3:entry", section, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);

		 	for ( var e=0 ; e< allEntries.snapshotLength; e++ )
			 {
			 var entry = allEntries.snapshotItem(e); 
			 // Add tracking ID to Build Instance

			 var entryToUpdate =  entry.cloneNode(true);
			 var encounter= buildInstance.evaluate("hl7-org_v3:encounter/hl7-org_v3:id", entry, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue
			 var encounterForTime= buildInstance.evaluate("hl7-org_v3:encounter", entry, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue
			var encounterID	= encounter.getAttributeNode("extension").nodeValue;
			
		 		 if(viewEncounter == encounterID)
					 {
					 
					 var encounterEffectiveTime= buildInstance.evaluate("hl7-org_v3:effectiveTime", encounterForTime, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.getAttributeNode("value").nodeValue;
							 if(viewEncounterTime == encounterEffectiveTime)
								 {
									
									 //Move entry from Subject Data to Encounter Scratch
									 currentSection.appendChild(entryToUpdate);
									 
									  var newEncounterIDs = buildInstance.evaluate("hl7-org_v3:encounter/hl7-org_v3:id", entry, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
									   var newEncounterIDFull = newEncounterIDs.snapshotItem(1); 
									   var trackingID	=newEncounterIDFull.getAttributeNode("extension").nodeValue;
									 scratchInstance.getElementsByTagName("updatingThisEncounter") [0].childNodes[0].nodeValue = trackingID
									 return;
								 }
					 } //  if(viewEncounter == encounterID)
				} //viewSection = sectionCode
				
		 } 
	 
}

}



 function updateEncounter() 
	{
		var updatingThisEncounter =  scratchInstance.getElementsByTagName("updatingThisEncounter") [0].childNodes[0].nodeValue
		var encounterTime =  encounterInstance.evaluate("/hl7-org_v3:data/hl7-org_v3:section/hl7-org_v3:entry/hl7-org_v3:encounter/hl7-org_v3:effectiveTime", encounterInstance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.getAttributeNode("value").nodeValue;
	if(encounterTime == '' )
	{
	alert('Please enter encounter time before applying changes.')
	return;
	}
	else
	{
	var currentEntry =  encounterInstance.evaluate("/hl7-org_v3:data/hl7-org_v3:section/hl7-org_v3:entry", encounterInstance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.cloneNode(true);
	var trackingEncounterIDs =  encounterInstance.evaluate("/hl7-org_v3:data/hl7-org_v3:section/hl7-org_v3:entry/hl7-org_v3:encounter/hl7-org_v3:id", encounterInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
	var trackingEncounterIDFull =  trackingEncounterIDs.snapshotItem(1);
	var trackingEncounterID = trackingEncounterIDFull.getAttributeNode("extension").nodeValue
	
	var allEntries= buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:component/hl7-org_v3:structuredBody/hl7-org_v3:component/hl7-org_v3:section/hl7-org_v3:entry", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
	
		// Loop through all Elements
		 for ( var i=0 ; i < allEntries.snapshotLength; i++ )
		 {
		  var entry = allEntries.snapshotItem(i);


			  var encounterIDs= buildInstance.evaluate("hl7-org_v3:encounter/hl7-org_v3:id", entry, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
			  var encounterIDFull =  encounterIDs.snapshotItem(1);
			  var encounterID = encounterIDFull.getAttributeNode("extension").nodeValue

			  if(encounterID == updatingThisEncounter)		 
				{
					 entry.parentNode.appendChild(currentEntry);
					 entry.parentNode.removeChild(entry)
					 scratchInstance.getElementsByTagName("viewEncounterTime") [0].textContent = encounterTime
					 alert('Success')
					 return;
				}
			}
		 }
	}


 function deleteEncounterAllView() 
	{
	var index =  scratchInstance.getElementsByTagName("repeatEncounterForViewAll") [0].childNodes[0].nodeValue-1;
	
	var currentSection =  encounterInstance.evaluate("/hl7-org_v3:data/hl7-org_v3:section", encounterInstance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
	var currentEntry =  encounterInstance.evaluate("hl7-org_v3:entry", currentSection, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue

	var allEntries= buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:component/hl7-org_v3:structuredBody/hl7-org_v3:component/hl7-org_v3:section/hl7-org_v3:entry", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
	
	  var entry = allEntries.snapshotItem(index);
	  
		  var entryIDExist = buildInstance.evaluate("hl7-org_v3:id", entry, nsResolver, XPathResult.BOOLEAN_TYPE, null).booleanValue  ;

		    if(entryIDExist == true)		 
		    {
			 entry.parentNode.removeChild(entry)
			 currentSection.removeChild(currentEntry)
			return;
			}
	}
	
	

 function deleteEncounter() 
	{
	var currentSection =  encounterInstance.evaluate("/hl7-org_v3:data/hl7-org_v3:section", encounterInstance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
	var currentEntry =  encounterInstance.evaluate("hl7-org_v3:entry", currentSection, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue
var currentEncounterIDs =  encounterInstance.evaluate("hl7-org_v3:encounter/hl7-org_v3:id", currentEntry, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
 var currentEncounterIDFull = currentEncounterIDs.snapshotItem(1)
var currentEncounterID = currentEncounterIDFull.getAttributeNode("extension").nodeValue

	var allEntries= buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:component/hl7-org_v3:structuredBody/hl7-org_v3:component/hl7-org_v3:section/hl7-org_v3:entry", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
	
		// Loop through all Elements
		 for ( var i=0 ; i < allEntries.snapshotLength; i++ )
		 {
		  var entry = allEntries.snapshotItem(i);
		
		  var encounterIDs= buildInstance.evaluate("hl7-org_v3:encounter/hl7-org_v3:id", entry, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
		  var encounterIDFull =  encounterIDs.snapshotItem(1);
		  var encounterID = encounterIDFull.getAttributeNode("extension").nodeValue

		    if(encounterID == currentEncounterID)		 
		    {
			 entry.parentNode.removeChild(entry)
			 currentSection.removeChild(currentEntry)
			return;
			}
		 }
	
	}

 function encounterRemoveTrackingID() 
{
 var entries= buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:component/hl7-org_v3:structuredBody/hl7-org_v3:component/hl7-org_v3:section/hl7-org_v3:entry", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
	
		// Loop through all Elements
		 for ( var t=0 ; t< entries.snapshotLength; t++ )
		{
		 var entry = entries.snapshotItem(t);
		  var entryIDExist = buildInstance.evaluate("hl7-org_v3:id", entry, nsResolver, XPathResult.BOOLEAN_TYPE, null).booleanValue  ;
		  
		    if(entryIDExist == true)		 
		    {
			  var entryID= buildInstance.evaluate("hl7-org_v3:id", entry, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
			  var thisID =  entryID.getAttributeNode("extension").nodeValue;			   
			  
			  if(thisID == 'updatingThisEncounter')		 
				{
					 entry.removeChild(entryID);	
					 return;
				}
			 }
			 }
}




function addUnplannedEncounter() 
{
try{
 var unplannedEncounter = scratchInstance.getElementsByTagName("unplannedEncounter") [0].childNodes[0].nodeValue
 		}
		catch(err)	{ }	
 var unplannedObservations = scratchInstance.getElementsByTagName("unplannedObservations") [0].childNodes[0].nodeValue
var sectionForObservation = 'StudyObservations'
var newElement= getNodesetTemplate("addObservationEncounterInstance", "sourceOf2");	 
var generatedID = generateID()
scratchInstance.getElementsByTagName("updatingThisEncounter") [0].childNodes[0].nodeValue = generatedID

	if (unplannedEncounter == '' || unplannedEncounter == null)
		{
			alert('Please  add an encounter Name.')
				return;
		}

	else if(unplannedObservations == '')
		{
			alert('Please enter number of observations.')
				return;
		}
	else if (sectionForObservation == '')
		{
			alert('Please select Document Section.')
			return;
		}
	else
		{

		 // Empty Encounter Instance
		var currentSection =  encounterInstance.evaluate("/hl7-org_v3:data/hl7-org_v3:section", encounterInstance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
		try{
		var currentEntry =  encounterInstance.evaluate("hl7-org_v3:entry", currentSection, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
		currentSection.removeChild(currentEntry)
		}
		catch(err)	{ }	
		
		var section =  encounterInstance.evaluate("/hl7-org_v3:data/hl7-org_v3:section", encounterInstance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
		//Add entry
		var newEntry = getNodesetTemplate("addEntry", "entry");
		 section.appendChild(newEntry);
		
		var thisEntry =  encounterInstance.evaluate("hl7-org_v3:entry", section, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
		var newEncounter = getNodesetTemplate("addNewEncounter", "encounter");
		thisEntry.appendChild(newEncounter);
	
		
		var theNewEncounter =  encounterInstance.evaluate("hl7-org_v3:entry/hl7-org_v3:encounter/hl7-org_v3:id", section, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
		theNewEncounter.setAttribute("extension", unplannedEncounter);	
		
		var sdEncounterIDs = encounterInstance.evaluate("//hl7-org_v3:encounter/hl7-org_v3:id", encounterInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
		var idForGeneratedID = sdEncounterIDs.snapshotItem(1);
		idForGeneratedID.setAttribute("extension", generatedID);		
		
		var newObservation = getNodesetTemplate("addObservationEncounterInstance", "sourceOf2");	 
		
			for ( var j=0 ; j < unplannedObservations; j++ )   
			{
				addUnplannedObservation()
			}
		
		
		// Copy the Encounter From scratch to the Build Instance
					 var allSections= buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:component/hl7-org_v3:structuredBody/hl7-org_v3:component/hl7-org_v3:section", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
var sectionExists = 'No'
	var sectionCounter = 	allSections.snapshotLength-1
						// Loop through all Elements
						 for ( var s=0 ; s < allSections.snapshotLength; s++ )
						 {
						 var buildSection = allSections.snapshotItem(s);
						 var sectionCode= buildInstance.evaluate("hl7-org_v3:code", buildSection, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.getAttributeNode("code").nodeValue;

								 if(sectionForObservation == sectionCode)
									 {
										 sectionExists=='Yes'
										 //Move entry from Subject Data to Encounter Scratch
										 var entryInScratch =  encounterInstance.evaluate("/hl7-org_v3:data/hl7-org_v3:section/hl7-org_v3:entry", encounterInstance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.cloneNode(true);
										 
										 buildSection.appendChild(entryInScratch);	 
										 
										 scratchInstance.getElementsByTagName("viewSection") [0].childNodes[0].nodeValue = sectionForObservation
										 scratchInstance.getElementsByTagName("viewEncounter") [0].childNodes[0].nodeValue = unplannedEncounter
										 scratchInstance.getElementsByTagName("viewEncounterTime") [0].childNodes[0].nodeValue = ""
										 
										break;
									 }
								else if (sectionCounter == s && sectionExists=='No')
										{
										var newSectionForObservation = getNodesetTemplate("addObservationSection", "component");
										var  path = buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:component/hl7-org_v3:structuredBody", buildInstance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue
										 path.appendChild(newSectionForObservation);	
										var allSections= buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:component/hl7-org_v3:structuredBody/hl7-org_v3:component/hl7-org_v3:section", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
										sectionCounter = s+1
										s = 0
								}
								 }			
		
		}
}


function countOfEncounters()
{
 var viewSection = scratchInstance.getElementsByTagName("viewSection") [0].childNodes[0].nodeValue
 var viewEncounter = scratchInstance.getElementsByTagName("viewEncounter") [0].childNodes[0].nodeValue
 
 //Find encounter in subject data and add to encoutner scratch for editing																	
	 var allSections= buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:component/hl7-org_v3:structuredBody/hl7-org_v3:component/hl7-org_v3:section", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);

	var encountersCounter = 0
	
		// Loop through all Sections
		 for ( var i=0 ; i < allSections.snapshotLength; i++ )
		 {
		 var section = allSections.snapshotItem(i);
		 var sectionCode= buildInstance.evaluate("hl7-org_v3:code", section, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.getAttributeNode("code").nodeValue;

		 if(viewSection == sectionCode)
		 {
		  var allEntries= buildInstance.evaluate("hl7-org_v3:entry", section, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);

		 	for ( var e=0 ; e< allEntries.snapshotLength; e++ )
			 {
			 var entry = allEntries.snapshotItem(e); 
			 
			 var encounter= buildInstance.evaluate("hl7-org_v3:encounter/hl7-org_v3:id", entry, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue		 
			 var encounterForTime= buildInstance.evaluate("hl7-org_v3:encounter", entry, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue
			 var encounterID	= encounter.getAttributeNode("extension").nodeValue;
			
			 var allEntries= buildInstance.evaluate("hl7-org_v3:entry", section, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);

			  		 if(viewEncounter == encounterID)
					 {
					 encountersCounter = encountersCounter +1
					 var thisIndex = e
					 }
			 }

			 if(encountersCounter == 1)
			 {
			 var oneEncounter = allEntries.snapshotItem(thisIndex); 
			var encounterEffectiveTime= buildInstance.evaluate("hl7-org_v3:encounter/hl7-org_v3:effectiveTime", oneEncounter, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.getAttributeNode("value").nodeValue;
			var currentTime = scratchInstance.getElementsByTagName("viewEncounterTime") [0].childNodes[0].nodeValue
			scratchInstance.getElementsByTagName("viewEncounterTime") [0].childNodes[0].nodeValue = encounterEffectiveTime;
			encounterToScratch()
			break;
			
			 }
			 }
			 }
			 
}



function setUnplannedObservationCode() 
{
	var allObservationsIndex = scratchInstance.getElementsByTagName("repeatForAllSourceOf2") [0].childNodes[0].nodeValue -1
			
		
	var encounter =  encounterInstance.evaluate("/hl7-org_v3:data/hl7-org_v3:section/hl7-org_v3:entry/hl7-org_v3:encounter", encounterInstance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
	 var allObservations = encounterInstance.evaluate("hl7-org_v3:sourceOf2", encounter, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
  var thisObservation = allObservations.snapshotItem(allObservationsIndex);
  
  var observationID = buildInstance.evaluate("hl7-org_v3:observation/hl7-org_v3:id", thisObservation, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.getAttributeNode("extension").nodeValue;
  var display = buildInstance.evaluate("hl7-org_v3:observation/hl7-org_v3:code", thisObservation, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.getAttributeNode("displayName").nodeValue;
 
  var displayNames = sdtmInstance.evaluate("/dataroot/SDTMTerminology/PreferredTerm", sdtmInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
 		 for ( var i=0 ; i < displayNames.snapshotLength; i++ )
		 {           
		 var displayName = displayNames.snapshotItem(i);
			 if(display == displayName.textContent)
			 {
			   var CodelistCode = sdtmInstance.evaluate("../CodelistName", displayName, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.textContent;
				 if(observationID == CodelistCode)
				 {
					var thisCode = sdtmInstance.evaluate("../Code", displayName, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.textContent;
					var setThisObservation =  encounterInstance.evaluate("hl7-org_v3:observation/hl7-org_v3:code", thisObservation, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
					setThisObservation.setAttribute("code", thisCode);	
					break;
				}
				  
			 }
		 }
		 
}




function addEncounterLocation() 
{
	var newLocation = getNodesetTemplate("addLocationCSshort", "location");
		
	var encounterForLocation = encounterInstance.evaluate("/hl7-org_v3:data/hl7-org_v3:section/hl7-org_v3:entry/hl7-org_v3:encounter", encounterInstance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue
	var referenceElement = encounterInstance.evaluate("hl7-org_v3:sourceOf2", encounterForLocation, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue	
	// encounterForLocation.appendChild(newLocation);	 
	 encounterForLocation.insertBefore(newLocation,referenceElement.previousSibling);

}

function removeObservation() 
{
 var index = scratchInstance.getElementsByTagName("repeatForAllSourceOf2") [0].childNodes[0].nodeValue -1
 var allObservations = encounterInstance.evaluate("/hl7-org_v3:data/hl7-org_v3:section/hl7-org_v3:entry/hl7-org_v3:encounter/hl7-org_v3:sourceOf2", encounterInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
  var thisObservation = allObservations.snapshotItem(index);
	thisObservation.parentNode.removeChild(thisObservation)
}


function addUnplannedObservation() 
{
var counter = 0
var newElement= getNodesetTemplate("addObservationEncounterInstance", "sourceOf2");	 
var encounterNode =  encounterInstance.evaluate("/hl7-org_v3:data/hl7-org_v3:section/hl7-org_v3:entry/hl7-org_v3:encounter", encounterInstance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
var encounterEffectiveTime =  encounterInstance.evaluate("hl7-org_v3:effectiveTime", encounterNode, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.getAttributeNode("value").nodeValue;

encounterNode.appendChild(newElement);
var encounterNode2 =  encounterInstance.evaluate("/hl7-org_v3:data/hl7-org_v3:section/hl7-org_v3:entry/hl7-org_v3:encounter", encounterInstance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
var allObservations = encounterInstance.evaluate("hl7-org_v3:sourceOf2", encounterNode2, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);

	if (encounterEffectiveTime != '')
	{
		counter = allObservations.snapshotLength -1
	//	alert(' counter  '  + counter)
		var thisObservation = allObservations.snapshotItem(counter);
		var obervationEffectiveTime =  encounterInstance.evaluate("hl7-org_v3:observation/hl7-org_v3:effectiveTime", thisObservation, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue
		obervationEffectiveTime.setAttribute("value", encounterEffectiveTime); 
	}
}
   
function addUnplannedObservationTime(){
var encounterNode2 =  encounterInstance.evaluate("/hl7-org_v3:data/hl7-org_v3:section/hl7-org_v3:entry/hl7-org_v3:encounter", encounterInstance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
var allObservations = encounterInstance.evaluate("hl7-org_v3:sourceOf2", encounterNode2, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);

	if (encounterEffectiveTime != '')
	{
		counter = allObservations.snapshotLength
		alert(' counter  '  + counter)
		var thisObservation = allObservations.snapshotItem(counter);
		var obervationEffectiveTime =  encounterInstance.evaluate("hl7-org_v3:observation/hl7-org_v3:effectiveTime", thisObservation, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue
		obervationEffectiveTime.setAttribute("value", encounterEffectiveTime); 
	}

}




 function addObservationForCS(encounterForSource, sdObservation, o) 
{
var encounterForSource = encounterForSource;
var sdObservation = sdObservation.cloneNode(true);
var o = o;
	
			var sourceOfs =  buildInstance.evaluate("hl7-org_v3:sourceOf2", encounterForSource, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
			var sourceOf = sourceOfs.snapshotItem(o);
			sourceOf.appendChild(sdObservation);
};



function generateID() 
{ 
   var chars = '0123456789ABCDEF'.split(''); 
   var uuid = [], rnd = Math.random, r; 
	   for (var i = 0; i < 12; i++) 
	   { 
		  if (!uuid[i]) 
		  { 
			 r = 0 | rnd()*16; 
			 uuid[i] = chars[(i == 12) ? (r & 0x3) | 0x8 : r & 0xf]; 
		  } 
	   } 
   return uuid.join(''); 
} 





function authorDetails() 
{
	var authorIndex = scratchInstance.getElementsByTagName("authorIndex") [0].childNodes[0].nodeValue -1 ;
	var authorNameExist = 'false'
  	 var authorID = scratchInstance.getElementsByTagName("authorID") [0].childNodes[0].nodeValue ;
  
	  	var parElement = buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:author", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
		var parentElementNode = parElement.snapshotItem(authorIndex);
		
		 
		var allInvestigators = spInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:primaryPerformer", spInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
		 var foundMatch = 'No'
		 var matchIndex = ''
		for ( var i=0 ;i < allInvestigators.snapshotLength; i++ )   
		{   
			var investigators = allInvestigators.snapshotItem(i)
		
				var investigator = spInstance.evaluate("hl7-org_v3:investigator/hl7-org_v3:id", investigators, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.getAttributeNode("extension").nodeValue;
			if (investigator == authorID)
				{
					matchIndex = i;
					foundMatch = 'Yes'
				}
				
						if(foundMatch == 'Yes')
						{
										try {
		var authorNameExist = sdInstance.evaluate("hl7-org_v3:assignedAuthor/hl7-org_v3:assignedPerson/hl7-org_v3:name", parentElementNode, nsResolver, XPathResult.BOOLEAN_TYPE, null).booleanValue;
			}	catch(err)	{ }	
		if (authorNameExist == false)
		{
		var assignedAuthor = buildInstance.evaluate("hl7-org_v3:assignedAuthor", parentElementNode, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue
		 var newObject = getNodesetTemplate("addAuthorChoicePerson", "assignedPerson");
		assignedAuthor.appendChild(newObject);
		}
			
		var assignedAuthorElement = buildInstance.evaluate("hl7-org_v3:assignedAuthor/hl7-org_v3:assignedPerson", parentElementNode, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
		var assignedAuthorNode = assignedAuthorElement.snapshotItem(0);
		
		var assignedAuthorElementName = buildInstance.evaluate("hl7-org_v3:name", assignedAuthorNode, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
		var assignedAuthorNodeName = assignedAuthorElementName.snapshotItem(0);
		
		var assignedAuthorElementAddr = buildInstance.evaluate("hl7-org_v3:assignedAuthor/hl7-org_v3:addr", parentElementNode, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
		var assignedAuthorNodeAddr = assignedAuthorElementAddr.snapshotItem(0);
			
						
								var thisInvestigator = allInvestigators.snapshotItem(matchIndex)
								
								//Get Investigator Name
								 var investigator = buildInstance.evaluate("hl7-org_v3:investigator/hl7-org_v3:investigatorPerson/hl7-org_v3:name", thisInvestigator, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null)

									var selectedInvestigatorName = investigator.singleNodeValue.cloneNode(true);
								
								assignedAuthorNode.insert
								(selectedInvestigatorName,assignedAuthorNodeName);	
								
							var parElement = buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:author", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
							var parentElementNode = parElement.snapshotItem(authorIndex);
	
							var assignedAuthorElement = buildInstance.evaluate("hl7-org_v3:assignedAuthor/hl7-org_v3:assignedPerson", parentElementNode, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
							var assignedAuthorNode = assignedAuthorElement.snapshotItem(0);
	
							var assignedAuthorElementName = buildInstance.evaluate("hl7-org_v3:name", assignedAuthorNode, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
		var assignedAuthorNodeName = assignedAuthorElementName.snapshotItem(0);	
		
								assignedAuthorNodeName.parentNode.removeChild(assignedAuthorElementName.snapshotItem(1));		
								
								
									//Get Investigator Address
									 var investigatorAddr = buildInstance.evaluate("hl7-org_v3:investigator/hl7-org_v3:investigatorPerson/hl7-org_v3:addr", thisInvestigator, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null)
								 
									var selectedInvestigatorAddr = investigatorAddr.singleNodeValue.cloneNode(true);

				assignedAuthorNode.parentNode.insertBefore(selectedInvestigatorAddr,assignedAuthorNodeAddr);	
								
							var parElement = buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:author", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
							var parentElementNode = parElement.snapshotItem(authorIndex);
								
							var assignedAuthorElementAddr = buildInstance.evaluate("hl7-org_v3:assignedAuthor/hl7-org_v3:addr", parentElementNode, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
		var assignedAuthorNodeAddr = assignedAuthorElementAddr.snapshotItem(0);	

								assignedAuthorNodeAddr.parentNode.removeChild(assignedAuthorElementAddr.snapshotItem(1));		
								
								
								//Get Sponsoring/Represented  Organization  Address
								var investigatorSponsorOrgExist = 'false'
								try{
									var investigatorSponsorOrgExist = buildInstance.evaluate("hl7-org_v3:investigator/hl7-org_v3:sponsoringOrganization", thisInvestigator, nsResolver, XPathResult.BOOLEAN_TYPE, null).booleanValue;
									}	catch(err)	{ }	
								if(investigatorSponsorOrgExist == true)
								{
									 var investigatorSponsorOrg = buildInstance.evaluate("hl7-org_v3:investigator/hl7-org_v3:sponsoringOrganization", thisInvestigator, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue
									var investigatorSponsorOrgID = buildInstance.evaluate("hl7-org_v3:id", investigatorSponsorOrg, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.getAttributeNode("extension").nodeValue;

									var investigatorSponsorOrgName = buildInstance.evaluate("hl7-org_v3:name", investigatorSponsorOrg, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.textContent
									 var investigatorSponsorOrgAddr = buildInstance.evaluate("hl7-org_v3:addr", investigatorSponsorOrg, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null)
									var selectedinvestigatorSponsorOrgAddr = investigatorSponsorOrgAddr.singleNodeValue.cloneNode(true);
	
										var assignedAuthorRepOrgExist = 'false'
										try{
										var assignedAuthorRepOrgExist = buildInstance.evaluate("hl7-org_v3:representedOrganization", assignedAuthor, nsResolver, XPathResult.BOOLEAN_TYPE, null).booleanValue;
										}	catch(err)	{ }	

										
										if(assignedAuthorRepOrgExist == false)
										{
											addNewRorganization()
										}
										
										var assignedAuthorRepOrg = buildInstance.evaluate("hl7-org_v3:assignedAuthor/hl7-org_v3:representedOrganization", parentElementNode, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue
										var assignedAuthorRepOrgID = buildInstance.evaluate("hl7-org_v3:id", assignedAuthorRepOrg, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue
										var assignedAuthorRepOrgName = buildInstance.evaluate("hl7-org_v3:name", assignedAuthorRepOrg, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue
										assignedAuthorRepOrgID.setAttribute("extension", investigatorSponsorOrgID) 
										assignedAuthorRepOrgName.textContent = investigatorSponsorOrgName
										
										assignedAuthorRepOrg.appendChild(selectedinvestigatorSponsorOrgAddr);	 
												
												// Remove original blank address
												var assignedAuthorRepOrgAddrs = buildInstance.evaluate("hl7-org_v3:addr", assignedAuthorRepOrg, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
												assignedAuthorRepOrgAddrs.snapshotItem(0).parentNode.removeChild(assignedAuthorRepOrgAddrs.snapshotItem(0));										
										
									}
								break;
						}
				
				
				
		} // End For Loop
		
};
 
    
function performerDetails() 
{
	var authorIndex = scratchInstance.getElementsByTagName("performerIndex") [0].childNodes[0].nodeValue -1 ;
    var authorNameExist = 'false'
  	 var authorID = scratchInstance.getElementsByTagName("performerID") [0].childNodes[0].nodeValue ;
  
	  	var parElement = buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:performer", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
		var parentElementNode = parElement.snapshotItem(authorIndex);



		 
		var allInvestigators = spInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:primaryPerformer", spInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);

		 var foundMatch = 'No'
		 var matchIndex = ''
		for ( var i=0 ;i < allInvestigators.snapshotLength; i++ )   
		{   
			var investigators = allInvestigators.snapshotItem(i)
		
				var investigator = spInstance.evaluate("hl7-org_v3:investigator/hl7-org_v3:id", investigators, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.getAttributeNode("extension").nodeValue;

			if (investigator == authorID)
				{
					matchIndex = i;
					foundMatch = 'Yes'
				}
				
						if(foundMatch == 'Yes')
						{		try {
		var authorNameExist = sdInstance.evaluate("hl7-org_v3:assignedAuthor/hl7-org_v3:assignedPerson/hl7-org_v3:name", parentElementNode, nsResolver, XPathResult.BOOLEAN_TYPE, null).booleanValue;
			}	catch(err)	{ }	

		if (authorNameExist == false)
		{
		var assignedAuthor = buildInstance.evaluate("hl7-org_v3:assignedAuthor", parentElementNode, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue
		 var newObject = getNodesetTemplate("addAuthorChoicePerson", "assignedPerson");
		assignedAuthor.appendChild(newObject);
		}

		var assignedAuthorElement = buildInstance.evaluate("hl7-org_v3:assignedAuthor/hl7-org_v3:assignedPerson", parentElementNode, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
		var assignedAuthorNode = assignedAuthorElement.snapshotItem(0);

		var assignedAuthorElementName = buildInstance.evaluate("hl7-org_v3:name", assignedAuthorNode, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
		var assignedAuthorNodeName = assignedAuthorElementName.snapshotItem(0);
	
		var assignedAuthorElementAddr = buildInstance.evaluate("hl7-org_v3:assignedAuthor/hl7-org_v3:addr", parentElementNode, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
		var assignedAuthorNodeAddr = assignedAuthorElementAddr.snapshotItem(0);
								var thisInvestigator = allInvestigators.snapshotItem(matchIndex)
								
								//Get Investigator Name
								 var investigator = buildInstance.evaluate("hl7-org_v3:investigator/hl7-org_v3:investigatorPerson/hl7-org_v3:name", thisInvestigator, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null)
									 
									var selectedInvestigatorName = investigator.singleNodeValue.cloneNode(true);
														
								assignedAuthorNode.insertBefore(selectedInvestigatorName,assignedAuthorNodeName);	
								
							var parElement = buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:performer", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
							var parentElementNode = parElement.snapshotItem(authorIndex);
							
							var assignedAuthorElement = buildInstance.evaluate("hl7-org_v3:assignedAuthor/hl7-org_v3:assignedPerson", parentElementNode, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
							var assignedAuthorNode = assignedAuthorElement.snapshotItem(0);
								
							var assignedAuthorElementName = buildInstance.evaluate("hl7-org_v3:name", assignedAuthorNode, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
		var assignedAuthorNodeName = assignedAuthorElementName.snapshotItem(0);	

		
								assignedAuthorNodeName.parentNode.removeChild(assignedAuthorElementName.snapshotItem(1));		
								
								
									//Get Investigator Address
									 var investigatorAddr = buildInstance.evaluate("hl7-org_v3:investigator/hl7-org_v3:investigatorPerson/hl7-org_v3:addr", thisInvestigator, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null)
								 
									var selectedInvestigatorAddr = investigatorAddr.singleNodeValue.cloneNode(true);
														
								assignedAuthorNode.parentNode.insertBefore(selectedInvestigatorAddr,assignedAuthorNodeAddr);	
								
							var parElement = buildInstance.evaluate("/hl7-org_v3:document/hl7-org_v3:performer", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
							var parentElementNode = parElement.snapshotItem(authorIndex);
								
							var assignedAuthorElementAddr = buildInstance.evaluate("hl7-org_v3:assignedAuthor/hl7-org_v3:addr", parentElementNode, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
		var assignedAuthorNodeAddr = assignedAuthorElementAddr.snapshotItem(0);	

								assignedAuthorNodeAddr.parentNode.removeChild(assignedAuthorElementAddr.snapshotItem(1));	
								
											//Get Sponsoring/Represented  Organization  Address
								var investigatorSponsorOrgExist = 'false'
								try{
									var investigatorSponsorOrgExist = buildInstance.evaluate("hl7-org_v3:investigator/hl7-org_v3:sponsoringOrganization", thisInvestigator, nsResolver, XPathResult.BOOLEAN_TYPE, null).booleanValue;
									}	catch(err)	{ }	
								if(investigatorSponsorOrgExist == true)
								{
									 var investigatorSponsorOrg = buildInstance.evaluate("hl7-org_v3:investigator/hl7-org_v3:sponsoringOrganization", thisInvestigator, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue
									var investigatorSponsorOrgID = buildInstance.evaluate("hl7-org_v3:id", investigatorSponsorOrg, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.getAttributeNode("extension").nodeValue;
					
									var investigatorSponsorOrgName = buildInstance.evaluate("hl7-org_v3:name", investigatorSponsorOrg, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.textContent
									 var investigatorSponsorOrgAddr = buildInstance.evaluate("hl7-org_v3:addr", investigatorSponsorOrg, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null)
									var selectedinvestigatorSponsorOrgAddr = investigatorSponsorOrgAddr.singleNodeValue.cloneNode(true);
	
										var assignedAuthorRepOrgExist = 'false'
										try{
										var assignedAuthorRepOrgExist = buildInstance.evaluate("hl7-org_v3:representedOrganization", assignedAuthor, nsResolver, XPathResult.BOOLEAN_TYPE, null).booleanValue;
										}	catch(err)	{ }	

										
										if(assignedAuthorRepOrgExist == false)
										{
											addNewPRorganization()
										}
										
										var assignedAuthorRepOrg = buildInstance.evaluate("hl7-org_v3:assignedAuthor/hl7-org_v3:representedOrganization", parentElementNode, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue
										var assignedAuthorRepOrgID = buildInstance.evaluate("hl7-org_v3:id", assignedAuthorRepOrg, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue
										var assignedAuthorRepOrgName = buildInstance.evaluate("hl7-org_v3:name", assignedAuthorRepOrg, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue
										assignedAuthorRepOrgID.setAttribute("extension", investigatorSponsorOrgID) 
										assignedAuthorRepOrgName.textContent = investigatorSponsorOrgName
										
										assignedAuthorRepOrg.appendChild(selectedinvestigatorSponsorOrgAddr);	 
												
												// Remove original blank address
												var assignedAuthorRepOrgAddrs = buildInstance.evaluate("hl7-org_v3:addr", assignedAuthorRepOrg, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
												assignedAuthorRepOrgAddrs.snapshotItem(0).parentNode.removeChild(assignedAuthorRepOrgAddrs.snapshotItem(0));										
										
									}
								
									
								break;
						}
				
				
				
		} // End For Loop
		
};
    
    
   
function setTodaysDate(){
var thisDate = getTodaysDate()
var allEffectiveTimes =  encounterInstance.evaluate("//hl7-org_v3:effectiveTime", encounterInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
		for ( var j=0 ;j < allEffectiveTimes.snapshotLength; j++ )   
		{   
			var effectiveTime  = allEffectiveTimes.snapshotItem(j)		
			effectiveTime.setAttribute("value", thisDate); 
		}

}


function getTodaysDate(){
var todayDate = new Date();
var thisDate = todayDate.getDate();
	if (thisDate < 10)
	{
	thisDate = '0' + thisDate
	}
var thisMonth = todayDate.getMonth();
thisMonth++;
	if (thisMonth < 10)
	{
	thisMonth = '0' + thisMonth
	}
var thisYear = todayDate.getFullYear();
var completeDate =  thisYear + '' + thisMonth + '' + thisDate;
return completeDate;
};
    
    


function encounterLocation() 
{				
				var thisEncounterLocation = encounterInstance.evaluate("//hl7-org_v3:location/hl7-org_v3:healthCareFacility/hl7-org_v3:serviceProviderOrganization", encounterInstance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
				
				var thisLocation = encounterInstance.evaluate("hl7-org_v3:id", thisEncounterLocation, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.getAttributeNode("extension").nodeValue;
				
		// alert('thisLocation  ' + thisLocation)

		var allILocations = spInstance.evaluate("//hl7-org_v3:location/hl7-org_v3:serviceDeliveryLocation/hl7-org_v3:location", spInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
		 var foundMatch = 'No'
		 var matchIndex = ''
		for ( var i=0 ;i < allILocations.snapshotLength; i++ )   
		{   
			var location = allILocations.snapshotItem(i)
		
				var spLocation = spInstance.evaluate("hl7-org_v3:id", location, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.getAttributeNode("extension").nodeValue;
				//alert(spLocation + '  =  ' + thisLocation)
			if (spLocation == thisLocation)
				{
					matchIndex = i;
					foundMatch = 'Yes'
				}
				
						if(foundMatch == 'Yes')
						{
						//alert('Found match ' )
				var spLocationName = spInstance.evaluate("hl7-org_v3:name", location, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.textContent;								
						
						var thisLocationName = encounterInstance.evaluate("hl7-org_v3:name", thisEncounterLocation, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.textContent = spLocationName ;
						
				
						return;
						}
			
			}
		
};

function deleteEncounterLocation() 
{

		
	var encounterForLocation = encounterInstance.evaluate("/hl7-org_v3:data/hl7-org_v3:section/hl7-org_v3:entry/hl7-org_v3:encounter/hl7-org_v3:location", encounterInstance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue
 	encounterForLocation.parentNode.removeChild(encounterForLocation);		
}


function setBirthdateAndAllocate() 
{
	var allObservationsIndex = scratchInstance.getElementsByTagName("repeatForAllSourceOf2") [0].childNodes[0].nodeValue -1
			
		
	var encounter =  encounterInstance.evaluate("/hl7-org_v3:data/hl7-org_v3:section/hl7-org_v3:entry/hl7-org_v3:encounter", encounterInstance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
	 var allObservations = encounterInstance.evaluate("hl7-org_v3:sourceOf2", encounter, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
  var thisObservation = allObservations.snapshotItem(allObservationsIndex);
  
  var observationID = buildInstance.evaluate("hl7-org_v3:observation/hl7-org_v3:id", thisObservation, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.getAttributeNode("extension").nodeValue;
   var observationCode = buildInstance.evaluate("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 setBirthdateAndAllocateViewAll() 
{
	var allObservationsIndex = scratchInstance.getElementsByTagName("repeatForAllSourceOf2") [0].childNodes[0].nodeValue -1
	var indexRepeatViewAllEncounter = scratchInstance.getElementsByTagName("indexRepeatViewAllEncounter") [0].childNodes[0].nodeValue -1
	//alert(' allObservationsIndex   '  + allObservationsIndex  +  '        indexRepeatViewAllEncounter  ' + indexRepeatViewAllEncounter)
	var allEncounters =  buildInstance.evaluate("//hl7-org_v3:section[hl7-org_v3:code/@code='StudyObservations']/hl7-org_v3:entry/hl7-org_v3:encounter", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
	  var encounter = allEncounters.snapshotItem(indexRepeatViewAllEncounter);
	  //alert('encounter  ' + encounter)
	 var allObservations = buildInstance.evaluate("hl7-org_v3:sourceOf2", encounter, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
  var thisObservation = allObservations.snapshotItem(allObservationsIndex);
  //alert('thisObservation  ' + thisObservation)
  
  var observationID = buildInstance.evaluate("hl7-org_v3:observation/hl7-org_v3:id", thisObservation, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.getAttributeNode("extension").nodeValue;
   var observationCode = buildInstance.evaluate("hl7-org_v3:observation/hl7-org_v3:code", thisObservation, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
   
  
  var display = buildInstance.evaluate("hl7-org_v3:observation/hl7-org_v3:code", thisObservation, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.getAttributeNode("displayName").nodeValue;
 
	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 emptyEncounterInstance()
{
	 // Empty Encounter Instance
	 
	var currentSection =  encounterInstance.evaluate("/hl7-org_v3:data/hl7-org_v3:section", encounterInstance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
	 	var currentEntryExist = encounterInstance.evaluate("hl7-org_v3:entry", currentSection, nsResolver, XPathResult.BOOLEAN_TYPE, null).booleanValue;
	 //	alert('currentEntryExist  ' + currentEntryExist)
	if( currentEntryExist == true)
	{
	var currentEntry =  encounterInstance.evaluate("hl7-org_v3:entry", currentSection, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
	currentSection.removeChild(currentEntry)	
	scratchInstance.getElementsByTagName("viewEncounter") [0].childNodes[0].nodeValue = 0
	scratchInstance.getElementsByTagName("viewEncounterTime") [0].childNodes[0].nodeValue = 0
		scratchInstance.getElementsByTagName("viewObservationsBy")  [0].textContent = 'ByEncounter'
	}
	else
	{
	scratchInstance.getElementsByTagName("viewObservationsBy")  [0].textContent = 'ByEncounter'
	}

	
}


function setUnplannedObservationCodeViewAll() 
{
	var allObservationsIndex = scratchInstance.getElementsByTagName("repeatForAllSourceOf2") [0].childNodes[0].nodeValue -1
	var indexRepeatViewAllEncounter = scratchInstance.getElementsByTagName("indexRepeatViewAllEncounter") [0].childNodes[0].nodeValue -1
	//	alert(' allObservationsIndex   '  + allObservationsIndex  +  '        indexRepeatViewAllEncounter  ' + indexRepeatViewAllEncounter)
	var allEncounters =  buildInstance.evaluate("//hl7-org_v3:section[hl7-org_v3:code/@code='StudyObservations']/hl7-org_v3:entry/hl7-org_v3:encounter", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
	  var encounter = allEncounters.snapshotItem(indexRepeatViewAllEncounter);
	 //  alert('encounter  ' + encounter)
	 var allObservations = buildInstance.evaluate("hl7-org_v3:sourceOf2", encounter, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
  var thisObservation = allObservations.snapshotItem(allObservationsIndex);
  // alert('thisObservation  ' + thisObservation)
  var observationID = buildInstance.evaluate("hl7-org_v3:observation/hl7-org_v3:id", thisObservation, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.getAttributeNode("extension").nodeValue;
  var display = buildInstance.evaluate("hl7-org_v3:observation/hl7-org_v3:code", thisObservation, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.getAttributeNode("displayName").nodeValue;
 //alert('observationID  ' + observationID)
  var displayNames = sdtmInstance.evaluate("/dataroot/SDTMTerminology/PreferredTerm", sdtmInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
 		 for ( var i=0 ; i < displayNames.snapshotLength; i++ )
		 {           
		 var displayName = displayNames.snapshotItem(i);
			 if(display == displayName.textContent)
			 {
			   var CodelistCode = sdtmInstance.evaluate("../CodelistName", displayName, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.textContent;
				 if(observationID == CodelistCode)
				 {
					var thisCode = sdtmInstance.evaluate("../Code", displayName, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.textContent;
					var setThisObservation =  encounterInstance.evaluate("hl7-org_v3:observation/hl7-org_v3:code", thisObservation, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
					setThisObservation.setAttribute("code", thisCode);	
					break;
				}
				  
			 }
		 }
		 
}



 function deleteEncounterViewAll() 
	{
	var indexRepeatViewAllEncounter = scratchInstance.getElementsByTagName("indexRepeatViewAllEncounter") [0].childNodes[0].nodeValue -1
	var allEncounters =  buildInstance.evaluate("//hl7-org_v3:section[hl7-org_v3:code/@code='StudyObservations']/hl7-org_v3:entry", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
	  var encounter = allEncounters.snapshotItem(indexRepeatViewAllEncounter);
encounter.parentNode.removeChild(encounter)

	}
	
	function removeObservationViewAll() 
{
		var allObservationsIndex = scratchInstance.getElementsByTagName("repeatForAllSourceOf2") [0].childNodes[0].nodeValue -1
		var indexRepeatViewAllEncounter = scratchInstance.getElementsByTagName("indexRepeatViewAllEncounter") [0].childNodes[0].nodeValue -1
		//alert(' allObservationsIndex   '  + allObservationsIndex  +  '        indexRepeatViewAllEncounter  ' + indexRepeatViewAllEncounter)
		var allEncounters =  buildInstance.evaluate("//hl7-org_v3:section[hl7-org_v3:code/@code='StudyObservations']/hl7-org_v3:entry/hl7-org_v3:encounter", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
		var encounter = allEncounters.snapshotItem(indexRepeatViewAllEncounter);
		//alert('encounter  ' + encounter)
		var allObservations = buildInstance.evaluate("hl7-org_v3:sourceOf2", encounter, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
		var thisObservation = allObservations.snapshotItem(allObservationsIndex);
		//alert('thisObservation  ' + thisObservation)
		thisObservation.parentNode.removeChild(thisObservation)
}



function addUnplannedObservationViewAll() 
{
var counter = 0
var newElement= getNodesetTemplate("addObservationEncounterInstance", "sourceOf2");	 
	var indexRepeatViewAllEncounter = scratchInstance.getElementsByTagName("indexRepeatViewAllEncounter") [0].childNodes[0].nodeValue -1
		 // alert('indexRepeatViewAllEncounter  ' + indexRepeatViewAllEncounter)
var allEncounters =  buildInstance.evaluate("//hl7-org_v3:section[hl7-org_v3:code/@code='StudyObservations']/hl7-org_v3:entry/hl7-org_v3:encounter", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
	  var encounter = allEncounters.snapshotItem(indexRepeatViewAllEncounter);
	 // alert('encounter  ' + encounter)
var encounterEffectiveTime =  buildInstance.evaluate("hl7-org_v3:effectiveTime", encounter, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.getAttributeNode("value").nodeValue;
encounter.appendChild(newElement);
var allObservations = buildInstance.evaluate("hl7-org_v3:sourceOf2", encounter, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);

	if (encounterEffectiveTime != '')
	{
		counter = allObservations.snapshotLength -1
		var thisObservation = allObservations.snapshotItem(counter);
		var obervationEffectiveTime =  buildInstance.evaluate("hl7-org_v3:observation/hl7-org_v3:effectiveTime", thisObservation, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue
		obervationEffectiveTime.setAttribute("value", encounterEffectiveTime); 
	}
}
  
    
    
function setEffectiveTimeNullFlavor() {
var allEffectiveTimes = buildInstance.evaluate("//hl7-org_v3:effectiveTime[hl7-org_v3:low]", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE , null);

		for(var i=0 ; i < allEffectiveTimes.snapshotLength; i++ )   
			{
				
		var  effectiveTime =  allEffectiveTimes.snapshotItem(i)
		
				var effectiveTimeLow = buildInstance.evaluate("hl7-org_v3:low", effectiveTime, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
				     if (effectiveTimeLow.hasAttribute('value') && effectiveTimeLow.getAttribute('value') == '')
				     {
				         effectiveTimeLow.setAttribute('nullFlavor','NA')
						effectiveTimeLow.removeAttribute('value','')
						}
						else{
							}
				

				var effectiveTimeHigh = buildInstance.evaluate("hl7-org_v3:high", effectiveTime, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
				         if (effectiveTimeHigh.hasAttribute('value') && effectiveTimeHigh.getAttribute('value') == '')				    
				          {
				         effectiveTimeHigh.setAttribute('nullFlavor','NA')
						effectiveTimeHigh.removeAttribute('value','')
						}
						else{
							}
			}

	var allEffectiveTimes3 = buildInstance.evaluate("//hl7-org_v3:availabilityTime", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE , null);

		for(var a=0 ; a < allEffectiveTimes3.snapshotLength; a++ )   
			{
				
		var  effectiveTime3 =  allEffectiveTimes3.snapshotItem(a)
		
				     if (effectiveTime3.hasAttribute('value') && effectiveTime3.getAttribute('value') == '')
				     {
				         effectiveTime3.setAttribute('nullFlavor','NA')
						effectiveTime3.removeAttribute('value','')
						}
						else{
							}		
			}		
			
	var allEffectiveTimes4 = buildInstance.evaluate("//hl7-org_v3:time[hl7-org_v3:low]", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE , null);

		for(var jt=0 ; jt < allEffectiveTimes4.snapshotLength; jt++ )   
			{
				
		var  effectiveTime4 =  allEffectiveTimes4.snapshotItem(jt)
		
				var effectiveTimeLow4 = buildInstance.evaluate("hl7-org_v3:low", effectiveTime4, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
				     if (effectiveTimeLow4.hasAttribute('value') && effectiveTimeLow4.getAttribute('value') == '')
				     {
				         effectiveTimeLow4.setAttribute('nullFlavor','NA')
						effectiveTimeLow4.removeAttribute('value','')
						}
						else{
							}
				

				var effectiveTimeHigh4 = buildInstance.evaluate("hl7-org_v3:high", effectiveTime4, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
				         if (effectiveTimeHigh4.hasAttribute('value') && effectiveTimeHigh4.getAttribute('value') == '')				    
				          {
				         effectiveTimeHigh4.setAttribute('nullFlavor','NA')
						effectiveTimeHigh4.removeAttribute('value','')
						}
						else{
							}
			}		
			
			
//Set null for StatusCode
var allStatusCodes = buildInstance.evaluate("//hl7-org_v3:statusCode", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE , null);

		for(var s=0 ; s < allStatusCodes.snapshotLength; s++ )   
		{
			var  statusCode =  allStatusCodes.snapshotItem(s)
				     if (statusCode.hasAttribute('code') && statusCode.getAttribute('code') == '')
				     {
				         statusCode.setAttribute('nullFlavor','NA')
						statusCode.removeAttribute('code','')
						}
						else{
							}
		}
		
    		
var allSetIds = buildInstance.evaluate("//hl7-org_v3:setId", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE , null);

		for(var si =0 ; si < allSetIds.snapshotLength; si++ )   
		{
			var  setID =  allSetIds.snapshotItem(si)
				     if (setID.hasAttribute('extension') && setID.getAttribute('extension') == '')
				     {
				         setID.setAttribute('nullFlavor','NA')
						setID.removeAttribute('extension','')
						}
						else{
							}
		}


var allVersionNumbers = buildInstance.evaluate("//hl7-org_v3:versionNumber", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE , null);

		for(var vn =0 ; vn < allVersionNumbers.snapshotLength; vn++ )   
		{
			var  versionNumber =  allVersionNumbers.snapshotItem(vn)
				     if (versionNumber.hasAttribute('value') && versionNumber.getAttribute('value') == '')
				     {
				         versionNumber.setAttribute('nullFlavor','NA')
						versionNumber.removeAttribute('value','')
						}
						else{
							}
		}
		
		
var studyDesignID = buildInstance.evaluate("//hl7-org_v3:definition1/hl7-org_v3:actDefinition/hl7-org_v3:id", buildInstance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
				     if (studyDesignID.hasAttribute('root') && studyDesignID.getAttribute('root') == '' && studyDesignID.hasAttribute('extension')  && studyDesignID.getAttribute('extension') == '')
				     {
				         studyDesignID.setAttribute('nullFlavor','NA')
						studyDesignID.removeAttribute('root','')
						studyDesignID.removeAttribute('extension','')
						}
						else if (studyDesignID.hasAttribute('root') && studyDesignID.getAttribute('root') != '' && studyDesignID.hasAttribute('extension')  && studyDesignID.getAttribute('extension') == '')
						{
							studyDesignID.removeAttribute('extension','')
						}
						else if (studyDesignID.hasAttribute('root') && studyDesignID.getAttribute('root') == '' && studyDesignID.hasAttribute('extension')  && studyDesignID.getAttribute('extension') != '')
						{
						studyDesignID.removeAttribute('root','')
						}
						else
						{}

							
var subjectD = buildInstance.evaluate("//hl7-org_v3:subject/hl7-org_v3:researchSubject/hl7-org_v3:id", buildInstance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
				     if (subjectD.hasAttribute('root') && subjectD.getAttribute('root') == '' && subjectD.hasAttribute('extension')  && subjectD.getAttribute('extension') == '')
				     {
				         subjectD.setAttribute('nullFlavor','NA')
						subjectD.removeAttribute('root','')
						subjectD.removeAttribute('extension','')
						}
						else if (subjectD.hasAttribute('root') && subjectD.getAttribute('root') != '' && subjectD.hasAttribute('extension')  && subjectD.getAttribute('extension') == '')
						{
							subjectD.removeAttribute('extension','')
						}
						else if (subjectD.hasAttribute('root') && subjectD.getAttribute('root') == '' && subjectD.hasAttribute('extension')  && subjectD.getAttribute('extension') != '')
						{
						subjectD.removeAttribute('root','')
						}
						else
						{}				
							
}



function removeEffectiveTimeNullFlavor() {

var allEffectiveTimes = buildInstance.evaluate("//hl7-org_v3:effectiveTime[hl7-org_v3:low]", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE , null);
		for(var i=0 ; i < allEffectiveTimes.snapshotLength; i++ )   
			{
				var  effectiveTime =  allEffectiveTimes.snapshotItem(i)
				

				var effectiveTimeLow = buildInstance.evaluate("hl7-org_v3:low", effectiveTime, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
				     if (effectiveTimeLow.hasAttribute('nullFlavor'))
				     {
				         effectiveTimeLow.setAttribute('value','')
						effectiveTimeLow.removeAttribute('nullFlavor')
						}
						else{
							}
				

				var effectiveTimeHigh = buildInstance.evaluate("hl7-org_v3:high", effectiveTime, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
				     if (effectiveTimeHigh.hasAttribute('nullFlavor'))
				     {
				         effectiveTimeHigh.setAttribute('value','')
						effectiveTimeHigh.removeAttribute('nullFlavor')
						}
						else{
							}
			}
			
	var allEffectiveTimes2 = buildInstance.evaluate("//hl7-org_v3:effectiveTime", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE , null);

		for(var t=0 ; t < allEffectiveTimes2.snapshotLength; t++ )   
			{
				
		var  effectiveTime2 =  allEffectiveTimes2.snapshotItem(t)
		
				     if (effectiveTime2.hasAttribute('nullFlavor'))
				     {
				         effectiveTime2.setAttribute('value','')
						effectiveTime2.removeAttribute('nullFlavor','')
						}
						else{
							}		
			}
			
		var allEffectiveTimes3 = buildInstance.evaluate("//hl7-org_v3:availabilityTime", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE , null);

		for(var a=0 ; a < allEffectiveTimes3.snapshotLength; a++ )   
			{
				
		var  effectiveTime3 =  allEffectiveTimes3.snapshotItem(a)
		
				     if (effectiveTime3.hasAttribute('nullFlavor'))
				     {
				         effectiveTime3.setAttribute('value','')
						effectiveTime3.removeAttribute('nullFlavor','')
						}
						else{
							}		
			}
			
		var allEffectiveTimes4 = buildInstance.evaluate("//hl7-org_v3:time[hl7-org_v3:low]", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE , null);
		for(var jt=0 ; jt < allEffectiveTimes4.snapshotLength; jt++ )   
			{
				
		var  effectiveTime4 =  allEffectiveTimes4.snapshotItem(jt)
		
				var effectiveTimeLow4 = buildInstance.evaluate("hl7-org_v3:low", effectiveTime4, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
				     if (effectiveTimeLow4.hasAttribute('nullFlavor'))
				     {
				         effectiveTimeLow4.setAttribute('value','')
						effectiveTimeLow4.removeAttribute('nullFlavor','')
						}
						else{
							}
				

				var effectiveTimeHigh4 = buildInstance.evaluate("hl7-org_v3:high", effectiveTime4, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
				         if (effectiveTimeHigh4.hasAttribute('nullFlavor'))				    
				          {
					effectiveTimeHigh4.setAttribute('value','')
						effectiveTimeHigh4.removeAttribute('nullFlavor','')
						}
						else{
							}
			}		
							
	//Set null for StatusCode
var allStatusCodes = buildInstance.evaluate("//hl7-org_v3:statusCode", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE , null);

		for(var s=0 ; s < allStatusCodes.snapshotLength; s++ )   
		{
			var  statusCode =  allStatusCodes.snapshotItem(s)
				     if (statusCode.hasAttribute('nullFlavor'))
				     {
				         statusCode.setAttribute('code','')
						statusCode.removeAttribute('nullFlavor','')
						}
						else{
							}
		}		
		
	var allSetIds = buildInstance.evaluate("//hl7-org_v3:setId", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE , null);
	
			for(var si =0 ; si < allSetIds.snapshotLength; si++ )   
			{
				var  setID =  allSetIds.snapshotItem(si)
						 if (setID.hasAttribute('nullFlavor'))
						 {
							 setID.setAttribute('extension','')
							setID.removeAttribute('nullFlavor','')
							}
							else{
								}
			}
	
	
	var allVersionNumbers = buildInstance.evaluate("//hl7-org_v3:versionNumber", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE , null);
	
			for(var vn =0 ; vn < allVersionNumbers.snapshotLength; vn++ )   
			{
				var  versionNumber =  allVersionNumbers.snapshotItem(vn)
						 if (versionNumber.hasAttribute('nullFlavor'))
						 {
							 versionNumber.setAttribute('value','')
							versionNumber.removeAttribute('nullFlavor','')
							}
							else{
								}
			}		
		
			
var studyDesignID = buildInstance.evaluate("//hl7-org_v3:definition1/hl7-org_v3:actDefinition/hl7-org_v3:id", buildInstance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
				     if (studyDesignID.hasAttribute('nullFlavor'))
				     {
				         studyDesignID.setAttribute('root','')
				         studyDesignID.setAttribute('extension','')
						studyDesignID.removeAttribute('nullFlavor','')
						}
						else if (studyDesignID.hasAttribute('root') && studyDesignID.hasAttribute('extension'))
						{
						}
						else if (studyDesignID.hasAttribute('root'))
						{
						studyDesignID.setAttribute('extension','')
						}
						else if (studyDesignID.hasAttribute('extension'))
						{
						studyDesignID.setAttribute('root','')
						}
						else{}

							
var subjectID = buildInstance.evaluate("//hl7-org_v3:subject/hl7-org_v3:researchSubject/hl7-org_v3:id", buildInstance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
				     if (subjectID.hasAttribute('nullFlavor'))
				     {
				         subjectID.setAttribute('root','')
				         subjectID.setAttribute('extension','')
						subjectID.removeAttribute('nullFlavor','')
						}
						else if (subjectID.hasAttribute('root') && subjectID.hasAttribute('extension'))
						{
						}
						else if (subjectID.hasAttribute('root'))
						{
						subjectID.setAttribute('extension','')
						}
						else if (subjectID.hasAttribute('extension'))
						{
						subjectID.setAttribute('root','')
						}
						else{}
			
}


    
    
    